Example #1
0
def plot_time_param(
    time_list, param_list, x_label=None, y_label=None, x_rotation=False
):
    """
    Plots a parameter against time.

    `Quantity` type is supported.

    Parameters
    ----------
    time_list: Time
        list of times
    param_list : ndarray or list
        list of parameter values on the y axis
    x_label : str
        X axis label
    y_label : str
        Y axis label
    x_rotation : bool
        True rotates the X axis labels by 90 deg (useful for ISOT dates)

    """

    quantity_support()
    time_support(format="isot")

    fig1, ax1 = plt.subplots(figsize=(12, 8), dpi=100)

    # default with grid
    format_axis_with_grid(ax1, x_label, y_label, x_rotation)

    # plot the data and show the plot
    ax1.plot(time_list, param_list)

    plt.show()
Example #2
0
    def plot_time_trajectories(self, plot="xyz"):  # coveralls: ignore
        r"""
        Draws position history versus time.

        Parameters
        ----------
        plot : str (optional)
            Enable plotting of position component x, y, z for each of these
            letters included in `plot`.
        """
        from astropy.visualization import quantity_support
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D

        quantity_support()
        fig, ax = plt.subplots()
        for p_index in range(self.N):
            r = self.position_history[:, p_index]
            x, y, z = r.T
            if "x" in plot:
                ax.plot(self.t, x, label=f"x_{p_index}")
            if "y" in plot:
                ax.plot(self.t, y, label=f"y_{p_index}")
            if "z" in plot:
                ax.plot(self.t, z, label=f"z_{p_index}")
        ax.set_title(self.name)
        ax.legend(loc='best')
        ax.grid()
        plt.show()
Example #3
0
    def plot_time_trajectories(self, plot="xyz"):  # coveralls: ignore
        r"""
        Draws position history versus time.

        Parameters
        ----------
        plot : str (optional)
            Enable plotting of position component x, y, z for each of these
            letters included in `plot`.
        """
        from astropy.visualization import quantity_support
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D

        quantity_support()
        fig, ax = plt.subplots()
        for p_index in range(self.N):
            r = self.position_history[:, p_index]
            x, y, z = r.T
            if "x" in plot:
                ax.plot(self.t, x, label=f"x_{p_index}")
            if "y" in plot:
                ax.plot(self.t, y, label=f"y_{p_index}")
            if "z" in plot:
                ax.plot(self.t, z, label=f"z_{p_index}")
        ax.set_title(self.name)
        ax.legend(loc='best')
        ax.grid()
        plt.show()
Example #4
0
 def __init__(self):
     os.chdir(os.path.dirname(__file__))
     quantity_support()
     app = QApplication([])
     gallery = Frame()
     gallery.show()
     app.exec_()
Example #5
0
def plot_orbit(orbiter: spice.Trajectory, spacecraft: Union[int, str] = 2, planets: Optional[List[str]] = None):
    """
    :param orbiter: generated by kernel_loader
    :param spacecraft: 1 or 2 for Helios 1 or 2
    :param planets: list of planets orbits to be plotted
    :return:
    """
    quantity_support()
    times_float = [(t - orbiter.times[0]).total_seconds() for t in orbiter.times]
    fig = plt.figure()
    circle = plt.Circle((0, 0), 0.004, color='r')
    ax = fig.add_subplot(111)
    ax.scatter(orbiter.x, orbiter.y, s=3, c=times_float)
    radius = np.sqrt(orbiter.x ** 2 + orbiter.y ** 2 + orbiter.z ** 2)
    for n in range(len(radius)):
        if 0.1 * u.au < radius[n] < 0.2 * u.au:
            ax.scatter(orbiter.x[n], orbiter.y[n], s=3, c='k')
    ax.scatter(orbiter.x[0], orbiter.y[0], s=5, c='b')
    ax.scatter(orbiter.x[10], orbiter.y[10], s=5, c='r')
    if planets is not None:
        for planet in planets:
            orbiter_planet = get_planet_orbit(planet)
            ax.scatter(orbiter_planet.x, orbiter_planet.y, s=3, c='k')
    ax.set_xlim(-1, 1)
    ax.set_ylim(-1, 1)
    ax.set_title(str(spacecraft) + ' orbit between ' + str(orbiter.times[0]) + ' and ' + str(orbiter.times[-1]))
    fig = plt.gcf()
    ax = fig.gca()
    ax.add_artist(circle)
    plt.show()
Example #6
0
def init():
    matplotlib.rcParams.update({
        'image.origin': 'lower',
        'image.interpolation': 'nearest',
        'image.cmap': 'Greys_r'
    })
    from astropy.visualization import quantity_support
    quantity_support()
Example #7
0
def plot_period(orbiter, spacecraft: Union[int, str] = 2):
    """
    :param orbiter: generated by kernel_loader
    :param spacecraft: 1 or 2 for Helios 1 or 2
    :return:
    """
    quantity_support()
    fig = plt.figure()
    sun_distance = np.sqrt(orbiter.x ** 2 + orbiter.y ** 2 + orbiter.z ** 2)
    plt.plot(orbiter.times, sun_distance, label='Helios' + str(spacecraft) + ' orbit')
    plt.title(
        'Orbit of Helios ' + str(spacecraft) + '  between ' + str(orbiter.times[0]) + ' and ' + str(orbiter.times[-1]))
    plt.legend()
    plt.show()
Example #8
0
    def plot_photometry(self, ax=None, **kwargs):
        """
        Plots available photometry (mag v lambda_eff).
        :param ax: matplotlib ax object to plot with. A new object is generated if none is provided.
        :param kwargs:
        :return: matplotlib ax object containing plot info
        """
        if ax is None:
            fig, ax = plt.subplots()
        if "ls" not in kwargs:
            kwargs["ls"] = ""
        if "marker" not in kwargs:
            kwargs["marker"] = "x"
        if "ecolor" not in kwargs:
            kwargs["ecolor"] = "black"

        self.estimate_galactic_extinction()
        self.photometry_to_table(fmts=["ascii.ecsv", "ascii.csv"], best=False)
        self.photometry_to_table(
            output=self.build_photometry_table_path().replace(".ecsv", "_best.ecsv"),
            fmts=["ascii.ecsv", "ascii.csv"], best=True)

        with quantity_support():

            plot_limit = (-999 * units.mag == self.photometry_tbl["mag_sep_err"])
            plot_mag = np.invert(plot_limit)

            print(plot_limit)
            print(plot_mag)
            print(self.photometry_tbl["mag_sep"][plot_mag])

            ax.errorbar(
                self.photometry_tbl["lambda_eff"][plot_mag],
                self.photometry_tbl["mag_sep"][plot_mag],
                yerr=self.photometry_tbl["mag_sep_err"][plot_mag],
                label="Magnitude",
                **kwargs,
            )
            ax.scatter(
                self.photometry_tbl["lambda_eff"][plot_limit],
                self.photometry_tbl["mag_sep"][plot_limit],
                label="Magnitude upper limit",
                marker="v",
            )
            ax.scatter(
                self.photometry_tbl["lambda_eff"][plot_mag],
                self.photometry_tbl["mag_sep_ext_corrected"][plot_mag],
                color="orange",
                label="Corrected for Galactic extinction"
            )
            ax.scatter(
                self.photometry_tbl["lambda_eff"][plot_limit],
                self.photometry_tbl["mag_sep_ext_corrected"][plot_limit],
                label="Magnitude upper limit",
                marker="v",
            )
            ax.set_ylabel("Apparent magnitude")
            ax.set_xlabel("$\lambda_\mathrm{eff}$ (\AA)")
            ax.invert_yaxis()
        return ax
Example #9
0
    def plot_energy(self, ax=None, **kwargs):
        """Plot counts as a function of energy.

        Parameters
        ----------
        ax : `~matplotlib.axes.Axes` or None
            Axes
        **kwargs : dict
            Keyword arguments passed to `~matplotlib.pyplot.hist`

        Returns
        -------
        ax : `~matplotlib.axes.Axes` or None
            Axes
        """
        import matplotlib.pyplot as plt

        ax = plt.gca() if ax is None else ax

        energy_axis = self._default_plot_energy_axis

        kwargs.setdefault("log", True)
        kwargs.setdefault("histtype", "step")
        kwargs.setdefault("bins", energy_axis.edges)

        with quantity_support():
            ax.hist(self.energy, **kwargs)

        energy_axis.format_plot_xaxis(ax=ax)
        ax.set_ylabel("Counts")
        ax.set_yscale("log")
        return ax
Example #10
0
    def plot(self, ax=None, add_cbar=True, **kwargs):
        """Plot effective area image."""
        import matplotlib.pyplot as plt

        ax = plt.gca() if ax is None else ax

        energy = self.axes["energy_true"]
        offset = self.axes["offset"]
        aeff = self.evaluate(offset=offset.center,
                             energy_true=energy.center[:, np.newaxis])

        vmin, vmax = np.nanmin(aeff.value), np.nanmax(aeff.value)

        kwargs.setdefault("cmap", "GnBu")
        kwargs.setdefault("edgecolors", "face")
        kwargs.setdefault("vmin", vmin)
        kwargs.setdefault("vmax", vmax)

        with quantity_support():
            caxes = ax.pcolormesh(energy.edges, offset.edges, aeff.value.T,
                                  **kwargs)

        energy.format_plot_xaxis(ax=ax)
        offset.format_plot_yaxis(ax=ax)

        if add_cbar:
            label = f"Effective Area [{aeff.unit}]"
            ax.figure.colorbar(caxes, ax=ax, label=label)

        return ax
Example #11
0
    def plot_spectrum(self, ax=None, **kwargs):
        """Plot angle integrated background rate versus energy.

        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`, optional
            Axis
        **kwargs : dict
            Keyword arguments forwarded to `~matplotib.pyplot.plot`

        Returns
        -------
        ax : `~matplotlib.axes.Axes`
            Axis
        """
        import matplotlib.pyplot as plt

        ax = plt.gca() if ax is None else ax

        offset_axis = self.axes["offset"]
        energy_axis = self.axes["energy"]

        bkg = self.integral(offset=offset_axis.bounds[1], axis_name="offset")

        with quantity_support():
            ax.plot(energy_axis.center, bkg, label="integrated spectrum", **kwargs)

        energy_axis.format_plot_xaxis(ax=ax)
        ax.set_yscale("log")
        ax.set_ylabel(f"Background rate ({ax.yaxis.units})")
        ax.legend(loc="best")
        return ax
Example #12
0
    def plot(self, ax=None, add_cbar=True, **kwargs):
        """Plot energy offset dependence of the background model."""
        import matplotlib.pyplot as plt
        from matplotlib.colors import LogNorm

        ax = plt.gca() if ax is None else ax

        energy_axis, offset_axis = self.axes["energy"], self.axes["offset"]
        data = self.quantity.value

        kwargs.setdefault("cmap", "GnBu")
        kwargs.setdefault("edgecolors", "face")
        kwargs.setdefault("norm", LogNorm())

        with quantity_support():
            caxes = ax.pcolormesh(
                energy_axis.edges, offset_axis.edges, data.T, **kwargs
            )

        energy_axis.format_plot_xaxis(ax=ax)
        offset_axis.format_plot_yaxis(ax=ax)

        if add_cbar:
            label = f"Background rate ({self.unit})"
            ax.figure.colorbar(caxes, ax=ax, label=label)
Example #13
0
    def peek(self):
        """
        Draw a quick matplotlib plot of the array
        """
        from matplotlib import pyplot as plt
        from astropy.visualization import quantity_support

        types = {str(tel) for tel in self.tels.values()}
        tab = self.to_table()

        plt.figure(figsize=(8, 8))

        with quantity_support():
            for teltype in types:
                tels = tab[tab['tel_description'] == teltype]['tel_id']
                sub = self.select_subarray(teltype, tels)
                tel_coords = sub.tel_coords
                radius = np.array([np.sqrt(tel.optics.mirror_area / np.pi).value
                                   for tel in sub.tels.values()])

                plt.scatter(tel_coords.x, tel_coords.y, s=radius * 8, alpha=0.5,
                            label=teltype)

            plt.legend(loc='best')
            plt.title(self.name)
            plt.tight_layout()
Example #14
0
    def plot_bias(self, ax=None, **kwargs):
        """Plot reconstruction bias.

        See `~gammapy.irf.EnergyDispersion.get_bias` method.

        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`, optional
            Plot axis
        **kwargs : dict
            Kwyrow

        Returns
        -------
        ax : `~matplotlib.axes.Axes`, optional
            Plot axis
        """
        import matplotlib.pyplot as plt

        ax = plt.gca() if ax is None else ax

        energy = self.axes["energy_true"].center
        bias = self.get_bias(energy)

        with quantity_support():
            ax.plot(energy, bias, **kwargs)

        ax.set_xlabel(f"$E_\\mathrm{{True}}$ [{ax.yaxis.units}]")
        ax.set_ylabel(
            "($E_\\mathrm{{Reco}} - E_\\mathrm{{True}}) / E_\\mathrm{{True}}$"
        )
        ax.set_xscale("log")
        return ax
Example #15
0
    def plot(self, ax=None, **kwargs):
        """
        Plot the stellar spectrum.

        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`
            Matplotlib axis object
        kwargs : dict
            Dictionary passed to the `~matplotlib.pyplot.plot` command

        Returns
        -------
        ax : `~matplotlib.axes.Axes`
            Updated axis object
        """
        import matplotlib.pyplot as plt
        from astropy.visualization import quantity_support

        if ax is None:
            ax = plt.gca()

        with quantity_support():
            ax.plot(self.wavelength, self.spectral_flux_density, **kwargs)

        return ax
Example #16
0
def extrapolate_electron_current(probe_characteristic, fit,
                                 bimaxwellian=False, visualize=False):
    r"""Extrapolate the electron current from the Maxwellian electron
    temperature obtained in the exponential growth region.

    Parameters
    ----------
    probe_characteristic : ~plasmapy.diagnostics.langmuir.Characteristic
        The probe characteristic that is being analyzed.

    fit : ndarray
        Polynomial fit coefficients returned by the electron temperature fit.

    bimaxwellian : bool, optional
        If True the electron current is extrapolated assuming bi-Maxwellian
        electron populations, as opposed to Maxwellian. Default is False.

    visualize : bool, optional
        If True a plot of the extracted electron current is shown. Default is
        False.

    Returns
    -------
    electron_current : ~plasmapy.diagnostics.langmuir.Characteristic
        The extrapolated electron current characteristic.

    Notes
    -----
    Assuming the electron population is fully Maxwellian the pure electron
    current is extrapolated from the fit of the exponential region for the
    entire bias range.

    """

    probe_characteristic.check_validity()

    if bimaxwellian:
        fit_func = _fit_func_double_lin_inverse
    else:
        fit_func = _fit_func_lin_inverse

    electron_current = np.exp(fit_func(probe_characteristic.bias.to(u.V).value,
                                       *fit))*u.A

    electron_current[electron_current >
                     np.max(probe_characteristic.current)] = np.NaN

    electron_characteristic = Characteristic(probe_characteristic.bias,
                                             electron_current)

    if visualize:  # coverage: ignore
        with quantity_support():
            plt.figure()
            plt.scatter(probe_characteristic.bias,
                        probe_characteristic.current.to(u.mA), marker='.',
                        c='k')
            plt.plot(electron_characteristic.bias,
                     electron_characteristic.current.to(u.mA))

    return electron_characteristic
Example #17
0
    def peek(self):
        """
        Draw a quick matplotlib plot of the array
        """
        from matplotlib import pyplot as plt
        from astropy.visualization import quantity_support

        types = {str(tel) for tel in self.tels.values()}
        tab = self.to_table()

        plt.figure(figsize=(8, 8))

        with quantity_support():
            for teltype in types:
                tels = tab[tab['tel_description'] == teltype]['tel_id']
                sub = self.select_subarray(teltype, tels)
                radius = np.array([
                    np.sqrt(tel.optics.mirror_area / np.pi).value
                    for tel in sub.tels.values()
                ])

                plt.scatter(sub.pos_x,
                            sub.pos_y,
                            s=radius * 8,
                            alpha=0.5,
                            label=teltype)

            plt.legend(loc='best')
            plt.title(self.name)
            plt.tight_layout()
Example #18
0
    def peek(self):
        """
        Draw a quick matplotlib plot of the array
        """
        from matplotlib import pyplot as plt
        from astropy.visualization import quantity_support

        types = set(self.tels.values())
        tab = self.to_table()

        plt.figure(figsize=(8, 8))

        with quantity_support():
            for tel_type in types:
                tels = tab[tab["tel_description"] == str(tel_type)]["tel_id"]
                sub = self.select_subarray(tel_type, tels)
                tel_coords = sub.tel_coords
                radius = np.array(
                    [
                        np.sqrt(tel.optics.mirror_area / np.pi).value
                        for tel in sub.tels.values()
                    ]
                )

                plt.scatter(
                    tel_coords.x, tel_coords.y, s=radius * 8, alpha=0.5, label=tel_type
                )

            plt.legend(loc="best")
            plt.title(self.name)
            plt.tight_layout()
Example #19
0
def moon_dist_plot(vis,
                   grb,
                   times,
                   radec,
                   site="None",
                   ax=None,
                   alpha=1,
                   color="purple"):

    if (ax == None): fig, ax = plt.subplots(figsize=(21, 5))

    dist = radec.separation(grb.radec)

    with quantity_support():
        ax.plot(times.datetime,
                dist,
                color=color,
                alpha=alpha,
                label="Moon distance")
        ax.axhline(y=vis.moon_mindist,
                   color=color,
                   ls=":",
                   alpha=alpha,
                   label="Min. distance")
    ax.set_ylabel("Dist.")
    ax.legend()

    return ax
Example #20
0
 def dotheplot(openloop, closedloop, **kwargs):
     date = kwargs.pop('date', closedloop.date)
     ext = kwargs.pop('extension', extension)
     kind = kwargs.setdefault('kind', default_kind)
     index = kwargs.get('index', None)
     subdir = kwargs.pop('subdir', False)
     path = kwargs.pop('path', None)
     with quantity_support():
         figure = f(openloop, closedloop, **kwargs)
         parts = ["{date:%Y-%m-%d}","C{closedloop.n:04d}","O{openloop.n:04d}","{kind:s}", "{key:s}", "{index:s}"]
         if keyarg:
             if keyargtransform:
                 kpart = keyargtransform(kwargs.get(keyarg, ""))
             else:
                 kpart = str(kwargs.get(keyarg, ""))
             parts.append(kpart)
         basename = "{0}.{{ext:s}}".format("-".join(parts))
         
         if path is None:
             path = pjoin("{date:%Y-%m-%d}", "C{closedloop.n:04d}-O{openloop.n:04d}", "{kind:s}")
             if subdir:
                 path = pjoin(path, subdir)
         path = pjoin(path, basename)
         
         name = path.format(date=date, closedloop=closedloop, openloop=openloop, 
                            kind=kind, key=key, index=index_label(index), ext=ext)
         name = name.replace(":", "-")
         
         if not os.path.isdir(os.path.dirname(name)):
             os.makedirs(os.path.dirname(name))
         click.echo("--> Saving {0} for {1} to '{2}'".format(key, kind, name))
         figure.savefig(name)
         plt.close(figure)
Example #21
0
    def plot_at_energy(
        self, energy=None, add_cbar=True, ncols=3, figsize=None, **kwargs
    ):
        """Plot the background rate in Field of view coordinates at a given energy.

        Parameters
        ----------
        energy : `~astropy.units.Quantity`
            list of Energy
        ax: `~matplotlib.axes.Axes`, optional
            Axis
        add_cbar : bool
            Add color bar?
        ncols : int
            Number of columns to plot
        **kwargs : dict
            Keyword arguments passed to `~matplotlib.pyplot.pcolormesh`.
        """
        import matplotlib.pyplot as plt

        n = len(energy)
        cols = min(ncols, n)
        rows = 1 + (n - 1) // cols
        width = 12
        if figsize is None:
            figsize = (width, width * rows / cols)

        fig, axes = plt.subplots(
            ncols=cols,
            nrows=rows,
            figsize=figsize,
            gridspec_kw={"hspace": 0.2, "wspace": 0.3},
        )

        x = self.axes["fov_lat"].edges
        y = self.axes["fov_lon"].edges
        X, Y = np.meshgrid(x, y)

        for i, ee in enumerate(energy):
            if len(energy) == 1:
                ax = axes
            else:
                ax = axes.flat[i]
            bkg = self.evaluate(energy=ee)
            with quantity_support():
                caxes = ax.pcolormesh(X, Y, bkg.squeeze(), **kwargs)

            self.axes["fov_lat"].format_plot_xaxis(ax)
            self.axes["fov_lon"].format_plot_yaxis(ax)
            ax.set_title(str(ee))
            if add_cbar:
                label = f"Background [{bkg.unit}]"
                ax.figure.colorbar(caxes, ax=ax, label=label)

            row, col = np.unravel_index(i, shape=(rows, cols))
            if col > 0:
                ax.set_ylabel("")
            if row < rows - 1:
                ax.set_xlabel("")
Example #22
0
def extrapolate_ion_current_OML(probe_characteristic, fit,
                                visualize=False):
    r"""Extrapolate the ion current from the ion density obtained with the
    OML method.

    Parameters
    ----------
    probe_characteristic : ~plasmapy.diagnostics.langmuir.Characteristic
        The probe characteristic that is being analyzed.

    fit : ndarray
        Fit coefficients returned by the OML method.

    visualize : bool, optional
        If True a plot of the extracted electron current is shown. Default is
        False.

    Returns
    -------
    ion_section : ~plasmapy.diagnostics.langmuir.Characteristic
        The exponential electron current growth section.

    Notes
    -----
    The exponential section of the probe characteristic should be a straight
    line if the plasma electrons are fully Maxwellian. The slope is then
    inversely proportional to the electron temperature.

    """

    if not isinstance(probe_characteristic, Characteristic):
        raise TypeError(f"For 'probe_characteristic' expected type "
                        f"{Characteristic.__module__ + '.' + Characteristic.__qualname__} "
                        f"and got {type(probe_characteristic)}")

    slope = fit[0] * u.mA**2 / u.V
    offset = fit[1] * u.mA**2

    ion_current = -np.sqrt(np.clip(slope * probe_characteristic.bias + offset,
                                   0.0, None))

    ion_characteristic = Characteristic(probe_characteristic.bias, ion_current)

    if visualize:  # coverage: ignore
        try:
            import matplotlib.pyplot as plt
        except (ImportError, ModuleNotFoundError) as e:
            from plasmapy.optional_deps import mpl_import_error
            raise mpl_import_error from e

        with quantity_support():
            plt.figure()
            plt.scatter(probe_characteristic.bias,
                        probe_characteristic.current.to(u.mA), marker='.',
                        c='k')
            plt.plot(probe_characteristic.bias,
                     ion_characteristic.current.to(u.mA), c='y')

    return ion_characteristic
Example #23
0
    def plot(self):  # coverage: ignore
        r"""Plot the characteristic in matplotlib."""

        with quantity_support():
            plt.figure()
            plt.scatter(self.bias.to(u.V), self.current.to(u.mA),
                        marker='.', color='k')
            plt.title("Probe characteristic")
Example #24
0
    def plot_residuals(self, ax=None, method="diff", **kwargs):
        """Plot flux point residuals.

        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`
            Axes to plot on.
        method : {"diff", "diff/model"}
            Normalization used to compute the residuals, see `FluxPointsDataset.residuals`.
        **kwargs : dict
            Keyword arguments passed to `~matplotlib.axes.Axes.errorbar`.

        Returns
        -------
        ax : `~matplotlib.axes.Axes`
            Axes object.

        """
        import matplotlib.pyplot as plt

        ax = ax or plt.gca()

        fp = self.data
        residuals = self.residuals(method)

        xerr = self.data.energy_axis.as_plot_xerr

        yerr = fp._plot_get_flux_err(sed_type="dnde")

        if method == "diff/model":
            model = self.flux_pred()
            yerr = (yerr[0].quantity[:, 0, 0] / model), (
                yerr[1].quantity[:, 0, 0] / model
            )
        elif method == "diff":
            yerr = yerr[0].quantity[:, 0, 0], yerr[1].quantity[:, 0, 0]
        else:
            raise ValueError('Invalid method, choose between "diff" and "diff/model"')

        kwargs.setdefault("color", kwargs.pop("c", "black"))
        kwargs.setdefault("marker", "+")
        kwargs.setdefault("linestyle", kwargs.pop("ls", "none"))

        with quantity_support():
            ax.errorbar(fp.energy_ref, residuals, xerr=xerr, yerr=yerr, **kwargs)

        ax.axhline(0, color=kwargs["color"], lw=0.5)

        # format axes
        ax.set_xlabel(f"Energy [{self._energy_unit}]")
        ax.set_xscale("log")
        label = self._residuals_labels[method]
        ax.set_ylabel(f"Residuals\n {label}")
        ymin = np.nanmin(residuals - yerr[0])
        ymax = np.nanmax(residuals + yerr[1])
        ymax = max(abs(ymin), ymax)
        ax.set_ylim(-1.05 * ymax, 1.05 * ymax)
        return ax
Example #25
0
    def plot_trajectories(self):  # coveralls: ignore
        r"""Draws trajectory history."""
        from astropy.visualization import quantity_support
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D

        quantity_support()
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        for p_index in range(self.N):
            r = self.position_history[:, p_index]
            x, y, z = r.T
            ax.plot(x, y, z)
        ax.set_title(self.name)
        ax.set_xlabel("$x$ position")
        ax.set_ylabel("$y$ position")
        ax.set_zlabel("$z$ position")
        plt.show()
Example #26
0
    def plot_trajectories(self):  # coveralls: ignore
        r"""Draws trajectory history."""
        from astropy.visualization import quantity_support
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D

        quantity_support()
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        for p_index in range(self.N):
            r = self.position_history[:, p_index]
            x, y, z = r.T
            ax.plot(x, y, z)
        ax.set_title(self.name)
        ax.set_xlabel("$x$ position")
        ax.set_ylabel("$y$ position")
        ax.set_zlabel("$z$ position")
        plt.show()
Example #27
0
def preview_spectrum(HDU):
    """Preview a 1D spectrum"""
    from astropy.visualization import quantity_support
    with quantity_support():
        fig, ax = plt.subplots(1,1)
        wave = wavelength(HDU)
        ax.plot(wave, HDU.data)
        ax.set_xlabel("Wavelength ({0:latex})".format(wave.unit))
        ax.set_ylabel("Flux")
    return fig
Example #28
0
    def plot_containment_radius(self,
                                ax=None,
                                fraction=0.68,
                                add_cbar=True,
                                **kwargs):
        """Plot containment image with energy and theta axes.

        Parameters
        ----------
        ax : `~matplotlib.pyplot.Axes`
            Axes to plot on.
        fraction : float
            Containment fraction between 0 and 1.
        add_cbar : bool
            Add a colorbar
        **kwargs : dict
            Keyword arguments passed to `~matplotlib.pyplot.pcolormesh`

        Returns
        -------
        ax : `~matplotlib.pyplot.Axes`
             Axes to plot on.
        """
        import matplotlib.pyplot as plt

        ax = plt.gca() if ax is None else ax

        energy = self.axes["energy_true"]
        offset = self.axes["offset"]

        # Set up and compute data
        containment = self.containment_radius(
            energy_true=energy.center[:, np.newaxis],
            offset=offset.center,
            fraction=fraction,
        )

        # plotting defaults
        kwargs.setdefault("cmap", "GnBu")
        kwargs.setdefault("vmin", np.nanmin(containment.value))
        kwargs.setdefault("vmax", np.nanmax(containment.value))

        # Plotting
        with quantity_support():
            caxes = ax.pcolormesh(energy.edges, offset.edges,
                                  containment.value.T, **kwargs)

        energy.format_plot_xaxis(ax=ax)
        offset.format_plot_yaxis(ax=ax)

        if add_cbar:
            label = f"Containment radius R{100 * fraction:.0f} ({containment.unit})"
            ax.figure.colorbar(caxes, ax=ax, label=label)

        return ax
Example #29
0
def plot_runtimes(cases, title, logscale_plot=True):
    """Plots the runtimes."""
    quantity_support()
    time_support()

    fig, ax = plt.subplots()

    # ax.grid()
    # ax.xaxis.set_major_formatter(FormatStrFormatter("% 3.3f"))
    # ax.yaxis.set_major_formatter(FormatStrFormatter("% 3.3f"))
    plt.title(f"Runtime Analysis\n({title})")
    ax.set_ylabel("Runtime (s)")

    if logscale_plot:
        ax.set_yscale("log")

    fig.set_size_inches(8, 6)

    # generate data lists
    names = [case for case in cases]
Example #30
0
    def plot(self):  # coverage: ignore
        r"""Plot the characteristic in matplotlib."""
        try:
            import matplotlib.pyplot as plt
        except (ImportError, ModuleNotFoundError) as e:
            from plasmapy.optional_deps import mpl_import_error

            raise mpl_import_error from e

        with quantity_support():
            plt.figure()
            plt.scatter(self.bias.to(u.V), self.current.to(u.mA), marker=".", color="k")
            plt.title("Probe characteristic")
Example #31
0
    def plot_sun_moon(self):
        plt.style.use(astropy_mpl_style)
        quantity_support()

        # Create Sun Moon Plot
        sunaltazs_viewing_date = get_sun(self.midnight).transform_to(
            self.sun_moon_viewing_frame)
        moon_data = get_moon(self.sun_moon_viewing_times)
        moonaltazs = moon_data.transform_to(self.sun_moon_viewing_frame)
        plt.plot(self.sun_moon_delta_midnight,
                 moonaltazs.alt,
                 color=[0.75] * 3,
                 ls='--',
                 label='Moon')
        plt.plot(self.sun_moon_delta_midnight,
                 sunaltazs_viewing_date.alt,
                 color='r',
                 label='Sun')
        plt.fill_between(self.sun_moon_delta_midnight,
                         0 * u.deg,
                         90 * u.deg,
                         sunaltazs_viewing_date.alt < -0 * u.deg,
                         color='0.5',
                         zorder=0)
        plt.fill_between(self.sun_moon_delta_midnight,
                         0 * u.deg,
                         90 * u.deg,
                         sunaltazs_viewing_date.alt < -18 * u.deg,
                         color='k',
                         zorder=0)
        plt.legend(loc='upper left')
        plt.xlim(-12 * u.hour, 12 * u.hour)
        plt.xticks((np.arange(13) * 2 - 12) * u.hour)
        plt.ylim(0 * u.deg, 90 * u.deg)
        plt.xlabel('Hours from EDT Midnight on {0}'.format(self.date))
        plt.ylabel('Altitude [deg]')
        plt.title('Sun and Moon plot for {0}'.format(self.site_name))
        plt.savefig(self.plot_file_name)
        self.get_sunset(sunaltazs_viewing_date)
def test_terminal_velocity():
    data = pandas.read_csv("vel_vs_r.dat", names = ["radius", "velocity"], sep=r"\s+")
    data_radius = data['radius'].values * u.um
    data_velocity = data['velocity'].values * u.m / u.s
    my_velocity = spherical_terminal_velocity(data_radius)
    if True:
        with visualization.quantity_support():
            plt.plot(data_radius, data_velocity, label="Dane źródłowe")
            plt.plot(data_radius, my_velocity, label="Obliczone")
            plt.legend()
            plt.savefig("terminal_velocity.png")
            plt.show()
    assert u.allclose(data_velocity, my_velocity, rtol=4e-3)
Example #33
0
    def plot_bias(self, ax=None, offset=None, add_cbar=False, **kwargs):
        """Plot migration as a function of true energy for a given offset.

        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`, optional
            Axis
        offset : `~astropy.coordinates.Angle`, optional
            Offset
        add_cbar : bool
            Add a colorbar to the plot.
        kwargs : dict
            Keyword arguments passed to `~matplotlib.pyplot.pcolormesh`.

        Returns
        -------
        ax : `~matplotlib.axes.Axes`
            Axis
        """
        import matplotlib.pyplot as plt
        from matplotlib.colors import PowerNorm

        kwargs.setdefault("cmap", "GnBu")
        kwargs.setdefault("norm", PowerNorm(gamma=0.5))

        ax = plt.gca() if ax is None else ax

        if offset is None:
            offset = Angle(1, "deg")

        energy_true = self.axes["energy_true"]
        migra = self.axes["migra"]

        z = self.evaluate(
            offset=offset,
            energy_true=energy_true.center.reshape(1, -1, 1),
            migra=migra.center.reshape(1, 1, -1),
        ).value[0]

        with quantity_support():
            caxes = ax.pcolormesh(energy_true.edges, migra.edges, z.T,
                                  **kwargs)

        energy_true.format_plot_xaxis(ax=ax)
        migra.format_plot_yaxis(ax=ax)

        if add_cbar:
            label = "Probability density (A.U.)"
            ax.figure.colorbar(caxes, ax=ax, label=label)

        return ax
Example #34
0
    def plot(self, ax=None, **kwargs):
        """Plot region map.

        Parameters
        ----------
        ax : `~matplotlib.pyplot.Axis`
            Axis used for plotting
        **kwargs : dict
            Keyword arguments passed to `~matplotlib.pyplot.errorbar`

        Returns
        -------
        ax : `~matplotlib.pyplot.Axis`
            Axis used for plotting
        """
        import matplotlib.pyplot as plt

        ax = ax or plt.gca()

        if self.data.squeeze().ndim > 1:
            raise TypeError(
                "Use `.plot_interactive()` if more the one extra axis is present."
            )

        try:
            axis = self.geom.axes["energy"]
        except KeyError:
            axis = self.geom.axes["energy_true"]

        kwargs.setdefault("fmt", ".")
        kwargs.setdefault("capsize", 2)
        kwargs.setdefault("lw", 1)

        with quantity_support():
            xerr = (axis.center - axis.edges[:-1],
                    axis.edges[1:] - axis.center)
            ax.errorbar(axis.center,
                        self.quantity.squeeze(),
                        xerr=xerr,
                        **kwargs)

        if axis.interp == "log":
            ax.set_xscale("log")

        ax.set_xlabel(axis.name.capitalize() + f" [{axis.unit}]")

        if not self.unit.is_unity():
            ax.set_ylabel(f"Data [{self.unit}]")

        ax.set_yscale("log")
        return ax
Example #35
0
import pandas as pd

from astropy.visualization import quantity_support
from matplotlib import pyplot as plt

from scipy.optimize import curve_fit

from pocs.utils import error

from .conversions import cr2_to_fits
from .conversions import make_pretty_image
from .io import crop_data
from .io import read_exif
from .metadata import get_wcsinfo

quantity_support()


def process_cr2(cr2_fname, fits_headers={}, solve=True, make_pretty=False, verbose=False, **kwargs):
    assert os.path.exists(cr2_fname), warnings.warn("File must exist: {}".format(cr2_fname))

    processed_info = {}

    try:
        if verbose:
            print("Processing image")

        if make_pretty:
            # If we have the object name, pass it to pretty image
            if 'title' in fits_headers:
                kwargs['title'] = "{}".format(fits_headers.get('title'))
Example #36
0
    def imshow(
        self,
        data=None,
        save=False,
        ax=None,
        interpolation="none",
        extra_title=None,
        show_resonances="some",
        set_extent=True,
        equalized=False,
        rmin=None,
        rmax=None,
        savepath=".",
        **kwargs,
    ):
        """Powerful default display.

        show_resonances can be True, a list, 'all', or 'some'
        """
        if data is None:
            data = self.img
        if self.resonance_axis is not None:
            logger.debug("removing resonance_axis")
            self.resonance_axis.remove()
        if equalized:
            data = np.nan_to_num(data)
            data[data < 0] = 0
            data = exposure.equalize_hist(data)
        self.plotted_data = data

        extent_val = self.extent if set_extent else None
        min_, max_ = self.plot_limits
        self.min_ = min_
        self.max_ = max_
        if ax is None:
            if not _SEABORN_INSTALLED:
                fig, ax = plt.subplots(figsize=calc_4_3(8))
            else:
                fig, ax = plt.subplots()
        else:
            fig = ax.get_figure()

        with quantity_support():
            im = ax.imshow(
                data,
                extent=extent_val,
                cmap="gray",
                vmin=min_,
                vmax=max_,
                interpolation=interpolation,
                origin="lower",
                aspect="auto",
                **kwargs,
            )
        if any([rmin is not None, rmax is not None]):
            ax.set_ylim(rmin, rmax)
        self.mpl_im = im
        ax.set_xlabel("Longitude [deg]")
        ax.set_ylabel("Radius [Mm]")
        ax.ticklabel_format(useOffset=False)
        # ax.grid('on')
        title = self.plot_title
        if extra_title:
            title += ", " + extra_title
        ax.set_title(title, fontsize=12)
        if show_resonances:
            self.set_resonance_axis(ax, show_resonances, rmin, rmax)
        if save:
            savename = self.plotfname
            if extra_title:
                savename = savename[:-4] + "_" + extra_title + ".png"
            p = Path(savename)
            fullpath = Path(savepath) / p.name
            fig.savefig(fullpath, dpi=150)
            logging.info("Created %s", fullpath)
        self.im = im
        return im
Example #37
0
def ellipse(major, minor, n):
    """Return ellipse edge"""
    a = major/2
    b = minor/2
    t = np.linspace(0, 2*np.pi, n)
    return a*np.cos(t), b*np.sin(t)


data = DataFile('touchdown_data.h5')
xunits = imp.ft
yunits = imp.ft
npoints = 1000

fig, ax = plt.subplots()
with quantity_support():
    ax.plot(data['miss_x'], data['miss_y'], '.', 
            xunits=xunits, yunits=yunits, label='simulation data')

    x, y = ellipse(8*imp.mile, 6*imp.mile, npoints)
    ax.plot(x, y, label='accuracy requirement')

    x, y = ellipse(20*imp.mile, 7*imp.mile, npoints)
    ax.plot(x, y, label='keepout zone')

    ax.set_xlabel('X Miss Distance ({})'.format(ax.xaxis.units))
    ax.set_ylabel('Y Miss Distance ({})'.format(ax.yaxis.units))
    ax.grid(True)
    ax.axis('equal')
    ax.legend()