Example #1
0
def test_polar_box():
    # Remove this line when this test image is regenerated.
    plt.rcParams['text.kerning_factor'] = 6

    fig = plt.figure(figsize=(5, 5))

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).
    extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
                                                     lon_cycle=360,
                                                     lat_cycle=None,
                                                     lon_minmax=None,
                                                     lat_minmax=(0, np.inf))

    grid_locator1 = angle_helper.LocatorDMS(12)
    tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)

    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)

    # let right axis shows ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0
    # let bottom axis shows ticklabels for 2nd coordinate (radius)
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    fig.add_subplot(ax1)

    ax1.axis["lat"] = axis = grid_helper.new_floating_axis(0, 45, axes=ax1)
    axis.label.set_text("Test")
    axis.label.set_visible(True)
    axis.get_helper().set_extremes(2, 12)

    ax1.axis["lon"] = axis = grid_helper.new_floating_axis(1, 6, axes=ax1)
    axis.label.set_text("Test 2")
    axis.get_helper().set_extremes(-180, 90)

    # A parasite axes with given transform
    ax2 = ParasiteAxes(ax1, tr, viewlim_mode="equal")
    assert ax2.transData == tr + ax1.transData
    # Anything you draw in ax2 will match the ticks and grids of ax1.
    ax1.parasites.append(ax2)
    ax2.plot(np.linspace(0, 30, 50), np.linspace(10, 10, 50))

    ax1.set_aspect(1.)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    ax1.grid(True)
def test_ParasiteAxesAuxTrans():

    data = np.ones((6, 6))
    data[2, 2] = 2
    data[0, :] = 0
    data[-2, :] = 0
    data[:, 0] = 0
    data[:, -2] = 0
    x = np.arange(6)
    y = np.arange(6)
    xx, yy = np.meshgrid(x, y)

    funcnames = ['pcolor', 'pcolormesh', 'contourf']

    fig = plt.figure()
    for i, name in enumerate(funcnames):

        ax1 = SubplotHost(fig, 1, 3, i+1)
        fig.add_subplot(ax1)

        ax2 = ParasiteAxesAuxTrans(ax1, IdentityTransform())
        ax1.parasites.append(ax2)
        getattr(ax2, name)(xx, yy, data)
        ax1.set_xlim((0, 5))
        ax1.set_ylim((0, 5))

    ax2.contour(xx, yy, data, colors='k')
Example #3
0
def test_custom_transform():
    class MyTransform(Transform):
        input_dims = output_dims = 2

        def __init__(self, resolution):
            """
            Resolution is the number of steps to interpolate between each input
            line segment to approximate its path in transformed space.
            """
            Transform.__init__(self)
            self._resolution = resolution

        def transform(self, ll):
            x, y = ll.T
            return np.column_stack([x, y - x])

        transform_non_affine = transform

        def transform_path(self, path):
            ipath = path.interpolated(self._resolution)
            return Path(self.transform(ipath.vertices), ipath.codes)

        transform_path_non_affine = transform_path

        def inverted(self):
            return MyTransformInv(self._resolution)

    class MyTransformInv(Transform):
        input_dims = output_dims = 2

        def __init__(self, resolution):
            Transform.__init__(self)
            self._resolution = resolution

        def transform(self, ll):
            x, y = ll.T
            return np.column_stack([x, y + x])

        def inverted(self):
            return MyTransform(self._resolution)

    fig = plt.figure()

    SubplotHost = host_subplot_class_factory(Axes)

    tr = MyTransform(1)
    grid_helper = GridHelperCurveLinear(tr)
    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
    fig.add_subplot(ax1)

    ax2 = ParasiteAxes(ax1, tr, viewlim_mode="equal")
    ax1.parasites.append(ax2)
    ax2.plot([3, 6], [5.0, 10.])

    ax1.set_aspect(1.)
    ax1.set_xlim(0, 10)
    ax1.set_ylim(0, 10)

    ax1.grid(True)
Example #4
0
def curvelinear_test2(fig):
    """
    polar projection, but in a rectangular box.
    """
    tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()
    extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
                                                     lon_cycle = 360,
                                                     lat_cycle = None,
                                                     lon_minmax = None,
                                                     lat_minmax = (0, np.inf),
                                                     )
    grid_locator1 = angle_helper.LocatorDMS(12)
    tick_formatter1 = angle_helper.FormatterDMS()
    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1
                                        )
    ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper)
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)
    ax1.axis["right"].get_helper().nth_coord_ticks=0
    ax1.axis["bottom"].get_helper().nth_coord_ticks=1
    fig.add_subplot(ax1)
    ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")
    ax1.parasites.append(ax2)
    intp = cbook.simple_linear_interpolation
    ax2.plot(intp(np.array([0, 30]), 50),
             intp(np.array([10., 10.]), 50))
    ax1.set_aspect(1.)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)
    ax1.grid(True)
Example #5
0
    def __spacetime_diagram_o_prime_frame(self):
        # from (x,t) to (x',t')
        def tr(x_prime, t_prime):
            x_prime, t_prime = np.asarray(x_prime), np.asarray(t_prime)
            return self.lorentz_transformations.transform(
                x_prime, t_prime, self.velocity)

        # form (x',t') to (x,t)
        def inv_tr(x, t):
            x, t = np.asarray(x), np.asarray(t)
            return self.lorentz_transformations.transform(x, t, -self.velocity)

        grid_helper = GridHelperCurveLinear((tr, inv_tr))
        ax = SubplotHost(self.fig, 1, 2, 2, grid_helper=grid_helper)
        self.fig.add_subplot(ax)

        ax.set_xlabel("x'", loc="center")
        ax.set_ylabel("t'", loc="center")

        # O x axis
        ax.axis["x1"] = x1 = ax.new_floating_axis(0, 0)
        x1.label.set_text("x")

        # O t axis
        ax.axis["t1"] = t1 = ax.new_floating_axis(1, 0)
        t1.label.set_text("t")

        self.__add_x_and_y_axis(ax)
        ax.format_coord = self.__format_coord_o_prime_frame

        self.__remove_ticks(ax, x1, t1)

        self.world_lines_plotter.transform_and_plot(plt, ax, self.velocity)
def test_polar_box():
    fig = plt.figure(figsize=(5, 5))

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).
    extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
                                                     lon_cycle=360,
                                                     lat_cycle=None,
                                                     lon_minmax=None,
                                                     lat_minmax=(0, np.inf))

    grid_locator1 = angle_helper.LocatorDMS(12)
    tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)

    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)

    # let right axis shows ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0
    # let bottom axis shows ticklabels for 2nd coordinate (radius)
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    fig.add_subplot(ax1)

    ax1.axis["lat"] = axis = grid_helper.new_floating_axis(0, 45, axes=ax1)
    axis.label.set_text("Test")
    axis.label.set_visible(True)
    axis.get_helper()._extremes = 2, 12

    ax1.axis["lon"] = axis = grid_helper.new_floating_axis(1, 6, axes=ax1)
    axis.label.set_text("Test 2")
    axis.get_helper()._extremes = -180, 90

    # A parasite axes with given transform
    ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")
    assert ax2.transData == tr + ax1.transData
    # Anything you draw in ax2 will match the ticks and grids of ax1.
    ax1.parasites.append(ax2)
    ax2.plot(np.linspace(0, 30, 50), np.linspace(10, 10, 50))

    ax1.set_aspect(1.)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    ax1.grid(True)
def curvelinear_test2(fig):
    """
    Polar projection, but in a rectangular box.
    """

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi/180, 1) + PolarAxes.PolarTransform()
    # Polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).
    extreme_finder = angle_helper.ExtremeFinderCycle(
        nx=20, ny=20,  # Number of sampling points in each direction.
        lon_cycle=360, lat_cycle=None,
        lon_minmax=None, lat_minmax=(0, np.inf),
    )
    # Find grid values appropriate for the coordinate (degree, minute, second).
    grid_locator1 = angle_helper.LocatorDMS(12)
    # Use an appropriate formatter.  Note that the acceptable Locator and
    # Formatter classes are a bit different than that of Matplotlib, which
    # cannot directly be used here (this may be possible in the future).
    tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(
        tr, extreme_finder=extreme_finder,
        grid_locator1=grid_locator1, tick_formatter1=tick_formatter1)
    ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper)

    # make ticklabels of right and top axis visible.
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)
    # let right axis shows ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0
    # let bottom axis shows ticklabels for 2nd coordinate (radius)
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    fig.add_subplot(ax1)

    ax1.set_aspect(1)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    ax1.grid(True, zorder=0)

    # A parasite axes with given transform
    ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")
    # note that ax2.transData == tr + ax1.transData
    # Anything you draw in ax2 will match the ticks and grids of ax1.
    ax1.parasites.append(ax2)
    ax2.plot(np.linspace(0, 30, 51), np.linspace(10, 10, 51), linewidth=2)
Example #8
0
def test_ParasiteAxesAuxTrans():
    # Remove this line when this test image is regenerated.
    plt.rcParams['pcolormesh.snap'] = False

    data = np.ones((6, 6))
    data[2, 2] = 2
    data[0, :] = 0
    data[-2, :] = 0
    data[:, 0] = 0
    data[:, -2] = 0
    x = np.arange(6)
    y = np.arange(6)
    xx, yy = np.meshgrid(x, y)

    funcnames = ['pcolor', 'pcolormesh', 'contourf']

    fig = plt.figure()
    for i, name in enumerate(funcnames):

        ax1 = SubplotHost(fig, 1, 3, i + 1)
        fig.add_subplot(ax1)

        ax2 = ParasiteAxes(ax1, IdentityTransform())
        ax1.parasites.append(ax2)
        if name.startswith('pcolor'):
            getattr(ax2, name)(xx, yy, data[:-1, :-1])
        else:
            getattr(ax2, name)(xx, yy, data)
        ax1.set_xlim((0, 5))
        ax1.set_ylim((0, 5))

    ax2.contour(xx, yy, data, colors='k')
Example #9
0
def test_ParasiteAxesAuxTrans():

    data = np.ones((6, 6))
    data[2, 2] = 2
    data[0, :] = 0
    data[-2, :] = 0
    data[:, 0] = 0
    data[:, -2] = 0
    x = np.arange(6)
    y = np.arange(6)
    xx, yy = np.meshgrid(x, y)

    funcnames = ['pcolor', 'pcolormesh', 'contourf']

    fig = plt.figure()
    for i, name in enumerate(funcnames):

        ax1 = SubplotHost(fig, 1, 3, i + 1)
        fig.add_subplot(ax1)

        ax2 = ParasiteAxesAuxTrans(ax1, IdentityTransform())
        ax1.parasites.append(ax2)
        getattr(ax2, name)(xx, yy, data)
        ax1.set_xlim((0, 5))
        ax1.set_ylim((0, 5))

    ax2.contour(xx, yy, data, colors='k')
Example #10
0
def sgrid():
    # From matplotlib demos:
    # https://matplotlib.org/gallery/axisartist/demo_curvelinear_grid.html
    # https://matplotlib.org/gallery/axisartist/demo_floating_axis.html

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()
    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # 20, 20 : number of sampling points along x, y direction
    sampling_points = 20
    extreme_finder = ModifiedExtremeFinderCycle(sampling_points, sampling_points,
                                                     lon_cycle=360,
                                                     lat_cycle=None,
                                                     lon_minmax=(90,270),
                                                     lat_minmax=(0, np.inf),)

    grid_locator1 = angle_helper.LocatorDMS(15)
    tick_formatter1 = FormatterDMS()
    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1
                                        )

    fig = plt.figure()
    ax = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    # make ticklabels of right invisible, and top axis visible.
    visible = True
    ax.axis[:].major_ticklabels.set_visible(visible)
    ax.axis[:].major_ticks.set_visible(False)
    ax.axis[:].invert_ticklabel_direction()

    ax.axis["wnxneg"] = axis = ax.new_floating_axis(0, 180)
    axis.set_ticklabel_direction("-")
    axis.label.set_visible(False)
    ax.axis["wnxpos"] = axis = ax.new_floating_axis(0, 0)
    axis.label.set_visible(False)
    ax.axis["wnypos"] = axis = ax.new_floating_axis(0, 90)
    axis.label.set_visible(False)
    axis.set_axis_direction("left")
    ax.axis["wnyneg"] = axis = ax.new_floating_axis(0, 270)
    axis.label.set_visible(False)
    axis.set_axis_direction("left")
    axis.invert_ticklabel_direction()
    axis.set_ticklabel_direction("-")

    # let left axis shows ticklabels for 1st coordinate (angle)
    ax.axis["left"].get_helper().nth_coord_ticks = 0
    ax.axis["right"].get_helper().nth_coord_ticks = 0
    ax.axis["left"].get_helper().nth_coord_ticks = 0
    ax.axis["bottom"].get_helper().nth_coord_ticks = 0

    fig.add_subplot(ax)

    ### RECTANGULAR X Y AXES WITH SCALE
    #par2 = ax.twiny()
    #par2.axis["top"].toggle(all=False)
    #par2.axis["right"].toggle(all=False)
    #new_fixed_axis = par2.get_grid_helper().new_fixed_axis
    #par2.axis["left"] = new_fixed_axis(loc="left",
    #                                   axes=par2,
    #                                   offset=(0, 0))
    #par2.axis["bottom"] = new_fixed_axis(loc="bottom",
    #                                     axes=par2,
    #                                     offset=(0, 0))
    ### FINISH RECTANGULAR

    ax.grid(True, zorder=0,linestyle='dotted')

    _final_setup(ax)
    return ax, fig
Example #11
0
def create_cg(st, fig=None, subplot=111):
    """ Helper function to create curvelinear grid

    The function makes use of the Matplotlib AXISARTIST namespace
    `mpl_toolkits.axisartist \
    <https://matplotlib.org/mpl_toolkits/axes_grid/users/axisartist.html>`_.

    Here are some limitations to normal Matplotlib Axes. While using the
    Matplotlib `AxesGrid Toolkit \
    <https://matplotlib.org/mpl_toolkits/axes_grid/index.html>`_
    most of the limitations can be overcome.
    See `Matplotlib AxesGrid Toolkit User’s Guide \
    <https://matplotlib.org/mpl_toolkits/axes_grid/users/index.html>`_.

    Parameters
    ----------
    st : string
        scan type, 'PPI' or 'RHI'
    fig : matplotlib Figure object
        If given, the PPI will be plotted into this figure object. Axes are
        created as needed. If None a new figure object will be created or
        current figure will be used, depending on "subplot".
    subplot : :class:`matplotlib:matplotlib.gridspec.GridSpec`, \
        matplotlib grid definition
        nrows/ncols/plotnumber, see examples section
        defaults to '111', only one subplot

    Returns
    -------
    cgax : matplotlib toolkit axisartist Axes object
        curvelinear Axes (r-theta-grid)
    caax : matplotlib Axes object (twin to cgax)
        Cartesian Axes (x-y-grid) for plotting cartesian data
    paax : matplotlib Axes object (parasite to cgax)
        The parasite axes object for plotting polar data
    """

    if st == 'RHI':
        # create transformation
        tr = Affine2D().scale(np.pi / 180, 1) + PolarAxes.PolarTransform()

        # build up curvelinear grid
        extreme_finder = ah.ExtremeFinderCycle(20, 20,
                                               lon_cycle=100,
                                               lat_cycle=None,
                                               lon_minmax=(0, np.inf),
                                               lat_minmax=(0, np.inf),
                                               )

        # locator and formatter for angular annotation
        grid_locator1 = ah.LocatorDMS(10.)
        tick_formatter1 = ah.FormatterDMS()

        # grid_helper for curvelinear grid
        grid_helper = GridHelperCurveLinear(tr,
                                            extreme_finder=extreme_finder,
                                            grid_locator1=grid_locator1,
                                            grid_locator2=None,
                                            tick_formatter1=tick_formatter1,
                                            tick_formatter2=None,
                                            )

        # try to set nice locations for range gridlines
        grid_helper.grid_finder.grid_locator2._nbins = 30.0
        grid_helper.grid_finder.grid_locator2._steps = [0, 1, 1.5,
                                                        2, 2.5, 5, 10]

    if st == 'PPI':
        # Set theta start to north
        tr_rotate = Affine2D().translate(-90, 0)
        # set theta running clockwise
        tr_scale = Affine2D().scale(-np.pi / 180, 1)
        # create transformation
        tr = tr_rotate + tr_scale + PolarAxes.PolarTransform()

        # build up curvelinear grid
        extreme_finder = ah.ExtremeFinderCycle(20, 20,
                                               lon_cycle=360,
                                               lat_cycle=None,
                                               lon_minmax=(360, 0),
                                               lat_minmax=(0, np.inf),
                                               )

        # locator and formatter for angle annotation
        locs = [i for i in np.arange(0., 359., 10.)]
        grid_locator1 = FixedLocator(locs)
        tick_formatter1 = DictFormatter(dict([(i, r"${0:.0f}^\circ$".format(i))
                                              for i in locs]))

        # grid_helper for curvelinear grid
        grid_helper = GridHelperCurveLinear(tr,
                                            extreme_finder=extreme_finder,
                                            grid_locator1=grid_locator1,
                                            grid_locator2=None,
                                            tick_formatter1=tick_formatter1,
                                            tick_formatter2=None,
                                            )
        # try to set nice locations for range gridlines
        grid_helper.grid_finder.grid_locator2._nbins = 15.0
        grid_helper.grid_finder.grid_locator2._steps = [0, 1, 1.5, 2,
                                                        2.5,
                                                        5,
                                                        10]

    # if there is no figure object given
    if fig is None:
        # create new figure if there is only one subplot
        if subplot is 111:
            fig = pl.figure()
        # otherwise get current figure or create new figure
        else:
            fig = pl.gcf()

    # generate Axis
    cgax = SubplotHost(fig, subplot, grid_helper=grid_helper)

    fig.add_axes(cgax)

    # PPIs always plottetd with equal aspect
    if st == 'PPI':
        cgax.set_aspect('equal', adjustable='box')

    # get twin axis for cartesian grid
    caax = cgax.twin()
    # move axis annotation from right to left and top to bottom
    caax.toggle_axisline()

    # make ticklabels of right and top axis visible,
    cgax.axis["right"].major_ticklabels.set_visible(True)
    cgax.axis["top"].major_ticklabels.set_visible(True)
    cgax.axis["right"].get_helper().nth_coord_ticks = 0
    cgax.axis["top"].get_helper().nth_coord_ticks = 0

    # and also set tickmarklength to zero for better presentation
    cgax.axis["right"].major_ticks.set_ticksize(0)
    cgax.axis["top"].major_ticks.set_ticksize(0)

    # make ticklabels of left and bottom axis invisible,
    # because we are drawing them
    cgax.axis["left"].major_ticklabels.set_visible(False)
    cgax.axis["bottom"].major_ticklabels.set_visible(False)

    # and also set tickmarklength to zero for better presentation
    cgax.axis["left"].major_ticks.set_ticksize(0)
    cgax.axis["bottom"].major_ticks.set_ticksize(0)

    # generate and add parasite axes with given transform
    paax = ParasiteAxesAuxTrans(cgax, tr, "equal")
    # note that paax.transData == tr + cgax.transData
    # Anything you draw in paax will match the ticks and grids of cgax.
    cgax.parasites.append(paax)

    return cgax, caax, paax
Example #12
0
def polar_stuff(fig, telescope):
    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi / 180., 1.).translate(
        +np.pi / 2., 0) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # 20, 20 : number of sampling points along x, y direction
    n = 1
    extreme_finder = angle_helper.ExtremeFinderCycle(
        n,
        n,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(-90, 90),
    )

    grid_locator1 = angle_helper.LocatorDMS(12)
    # Find a grid values appropriate for the coordinate (degree,
    # minute, second).

    tick_formatter1 = angle_helper.FormatterDMS()
    # And also uses an appropriate formatter.  Note that,the
    # acceptable Locator and Formatter class is a bit different than
    # that of mpl's, and you cannot directly use mpl's Locator and
    # Formatter here (but may be possible in the future).

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)

    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    # make ticklabels of right and top axis visible.
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)

    # let right axis shows ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0
    # let bottom axis shows ticklabels for 2nd coordinate (radius)
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    fig.add_subplot(ax1)

    # A parasite axes with given transform
    ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")
    # note that ax2.transData == tr + ax1.transData
    # Anything you draw in ax2 will match the ticks and grids of ax1.
    ax1.parasites.append(ax2)
    # intp = cbook.simple_linear_interpolation
    #ax2.plot(intp(np.array([0, 30]), 50),
    #         intp(np.array([10., 10.]), 50),
    #         linewidth=2.0)

    x = np.rad2deg(telescope.az.value) * np.cos(telescope.alt.value)
    y = np.rad2deg(telescope.alt.value)

    circle = plt.Circle(
        (np.rad2deg(telescope.az.value - np.pi) * np.sin(telescope.alt.value),
         np.rad2deg(-telescope.alt.value * np.cos(
             (telescope.az.value - np.pi)))),
        radius=7.7 / 2,
        color="red",
        alpha=0.2,
    )

    circle = plt.Circle(
        (x, y),
        radius=7.7 / 2,
        color="red",
        alpha=0.2,
    )
    ax1.add_artist(circle)
    # point = ax1.scatter(x, y, c="b", s=20, zorder=10, transform=ax2.transData)
    ax2.annotate(1, (x, y),
                 fontsize=15,
                 xytext=(4, 4),
                 textcoords='offset pixels')

    ax1.set_xlim(-180, 180)
    ax1.set_ylim(0, 90)
    ax1.set_aspect(1.)
    ax1.grid(True, zorder=0)
    ax1.set_xlabel("Azimuth in degrees", fontsize=20)
    ax1.set_ylabel("Zenith in degrees", fontsize=20)

    plt.show()
    return fig
Example #13
0
    def curvelinear_test2(fig, gs=None, xcenter=0.0, ycenter=17.3, xwidth=1.5, ywidth=1.5,
            rot_angle=0.0, xlabel=xlabel, ylabel=ylabel, xgrid_density=8, ygrid_density=5):
        """
        polar projection, but in a rectangular box.
        """

        tr = Affine2D().translate(0,90)
        tr += Affine2D().scale(np.pi/180., 1.)
        tr += PolarAxes.PolarTransform()

        tr += Affine2D().rotate(rot_angle)  # This rotates the grid

        extreme_finder = angle_helper.ExtremeFinderCycle(10, 60,
                                                        lon_cycle = 360,
                                                        lat_cycle = None,
                                                        lon_minmax = None,
                                                        lat_minmax = (-90, np.inf),
                                                        )

        grid_locator1 = angle_helper.LocatorHMS(xgrid_density) #changes theta gridline count
        tick_formatter1 = angle_helper.FormatterHMS()
        grid_locator2 = angle_helper.LocatorDMS(ygrid_density) #changes theta gridline count
        tick_formatter2 = angle_helper.FormatterDMS()


        grid_helper = GridHelperCurveLinear(tr,
                                            extreme_finder=extreme_finder,
                                            grid_locator1=grid_locator1,
                                            grid_locator2=grid_locator2,
                                            tick_formatter1=tick_formatter1,
                                            tick_formatter2=tick_formatter2
                                            )

        # ax1 = SubplotHost(fig, rect, grid_helper=grid_helper)
        if gs is None:
            ax1 = SubplotHost(fig, 111, grid_helper=grid_helper)
        else:
            ax1 = SubplotHost(fig, gs, grid_helper=grid_helper)



        # make ticklabels of right and top axis visible.
        ax1.axis["right"].major_ticklabels.set_visible(False)
        ax1.axis["top"].major_ticklabels.set_visible(False)
        ax1.axis["bottom"].major_ticklabels.set_visible(True) #Turn off?

        # let right and bottom axis show ticklabels for 1st coordinate (angle)
        ax1.axis["right"].get_helper().nth_coord_ticks=0
        ax1.axis["bottom"].get_helper().nth_coord_ticks=0


        fig.add_subplot(ax1)

        grid_helper = ax1.get_grid_helper()

        # These move the grid
        ax1.set_xlim(xcenter-xwidth, xcenter+xwidth) # moves the origin left-right in ax1
        ax1.set_ylim(ycenter-ywidth, ycenter+ywidth) # moves the origin up-down


        if xlabel is not None: ax1.set_xlabel(xlabel)
        if ylabel is not None: ax1.set_ylabel(ylabel)
        ax1.grid(True, linestyle='-')


        return ax1,tr
class PolarPlot:
	''' plots heading angle and signal strength in polar coor in 2d'''
	def __init__(self):
		plt.ion()
		self.fig = plt.figure(num=2, figsize=(10,7))
		tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()
		# 20, 20 : number of sampling points along x, y direction
		extreme_finder = angle_helper.ExtremeFinderCycle(50, 50,
		                                                 lon_cycle = 360,
		                                                 lat_cycle = None,
		                                                 lon_minmax = None,
		                                                 lat_minmax = (0, np.inf),
		                                                 )
		grid_locator1 = angle_helper.LocatorDMS(15)
		tick_formatter1 = angle_helper.FormatterDMS()
		# And also uses an appropriate formatter.  Note that,the
		# acceptable Locator and Formatter class is a bit different than
		# that of mpl's, and you cannot directly use mpl's Locator and
		# Formatter here (but may be possible in the future).
		grid_helper = GridHelperCurveLinear(tr,
		                                    extreme_finder=extreme_finder,
		                                    grid_locator1=grid_locator1,
		                                    tick_formatter1=tick_formatter1
		                                    )

		self.ax1 = SubplotHost(self.fig, 1, 1, 1, grid_helper=grid_helper)
		
		# make ticklabels of right and top axis visible.
		self.ax1.axis["right"].major_ticklabels.set_visible(True)
		self.ax1.axis["top"].major_ticklabels.set_visible(True)
		self.ax1.axis["left"].major_ticklabels.set_visible(True)

		# let right axis shows ticklabels for 1st coordinate (angle)
		self.ax1.axis["right"].get_helper().nth_coord_ticks=0
		# let bottom axis shows ticklabels for 1st coordinate (angle)
		self.ax1.axis["bottom"].get_helper().nth_coord_ticks=0
		self.ax1.axis["left"].get_helper().nth_coord_ticks=0
		temp =  self.ax1.set_title('Signal strength & heading polar plots')
		temp.set_y(1.05) 

		self.ax1.grid(True)

		# insert x and y axises
		self.ax = self.fig.add_subplot(self.ax1)
		self.ax1.spines['left'].set_position('center')
		self.ax1.spines['right'].set_color('red')
		self.ax1.spines['bottom'].set_position('center')
		self.ax1.spines['top'].set_color('none')
		self.ax1.spines['left'].set_smart_bounds(True)
		self.ax1.spines['bottom'].set_smart_bounds(True)
		self.ax1.xaxis.set_ticks_position('bottom')
		self.ax1.yaxis.set_ticks_position('left')
		self.ax1.axhline(linewidth=2, color='blue')
		self.ax1.axvline(linewidth=2, color='blue')

		# label x and y axises manually 
		ticks = np.linspace(0, 255, 6)
		offset = np.zeros([1,255])
		for i in range(1,5):
			self.ax1.annotate(str(ticks[i]),size=10, xy=(ticks[i], -15))
			blah = self.ax1.plot(ticks[i],0, 'bo')

			self.ax1.annotate(str(ticks[i]),size=10, xy=(5, ticks[i]))
			blah = self.ax1.plot(0,ticks[i], 'bo')

		# annotate figure 
		bbox_props = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9)
		# self.annotation = self.ax1.annotate('init',size=20, xy=(100, 100), bbox = bbox_props)
		self.annotation = plt.figtext(0.02, 0.9, 'rssi = ', size=20, alpha = 0.9, bbox = bbox_props)
		self.Freq = plt.figtext(0.85, 0.85, 'freq = ???', size=10, alpha = 0.9, bbox = bbox_props)
		self.Freq = plt.figtext(0.85, 0.9, 'Horizontal Plane', size=10, alpha = 0.9, bbox = bbox_props)

		# initialize arrow 
		self.quiverLine = self.ax1.quiver(0,0,50,50,angles='xy',scale_units='xy',scale=1)		
		self.ax1.set_aspect(1.)
		self.ax1.set_xlim(-255, 255)
		self.ax1.set_ylim(-255, 255)
		
		# initialize mesh plot
		self.xdata = []
		self.ydata = []
		self.polarline, = self.ax1.plot(self.xdata,self.ydata)

	def update(self, signalStrength, yaw):
		U = signalStrength*cos(yaw*pi/180)
		V = signalStrength*sin(yaw*pi/180)
		self.xdata.append(U)
		self.ydata.append(V)
		self.polarline.set_data(self.xdata,self.ydata)
		self.quiverLine.set_UVC(U,V)
		self.annotation.set_text('rssi = ' + str(signalStrength))
		plt.draw()
def test_axis_direction():
    fig = plt.figure(figsize=(5, 5))

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # 20, 20 : number of sampling points along x, y direction
    extreme_finder = angle_helper.ExtremeFinderCycle(
        20,
        20,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(0, np.inf),
    )

    grid_locator1 = angle_helper.LocatorDMS(12)
    tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)

    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    for axis in ax1.axis.values():
        axis.set_visible(False)

    fig.add_subplot(ax1)

    ax1.axis["lat1"] = axis = grid_helper.new_floating_axis(
        0, 130, axes=ax1, axis_direction="left")
    axis.label.set_text("Test")
    axis.label.set_visible(True)
    axis.get_helper()._extremes = 0.001, 10

    ax1.axis["lat2"] = axis = grid_helper.new_floating_axis(
        0, 50, axes=ax1, axis_direction="right")
    axis.label.set_text("Test")
    axis.label.set_visible(True)
    axis.get_helper()._extremes = 0.001, 10

    ax1.axis["lon"] = axis = grid_helper.new_floating_axis(
        1, 10, axes=ax1, axis_direction="bottom")
    axis.label.set_text("Test 2")
    axis.get_helper()._extremes = 50, 130
    axis.major_ticklabels.set_axis_direction("top")
    axis.label.set_axis_direction("top")

    grid_helper.grid_finder.grid_locator1.den = 5
    grid_helper.grid_finder.grid_locator2._nbins = 5

    ax1.set_aspect(1.)
    ax1.set_xlim(-8, 8)
    ax1.set_ylim(-4, 12)

    ax1.grid(True)
def curvelinear_test2(fig):
    """
    polar projection, but in a rectangular box.
    """

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # 20, 20 : number of sampling points along x, y direction
    extreme_finder = angle_helper.ExtremeFinderCycle(50, 50,
                                                     lon_cycle = 360,
                                                     lat_cycle = None,
                                                     lon_minmax = None,
                                                     lat_minmax = (0, np.inf),
                                                     )

    grid_locator1 = angle_helper.LocatorDMS(12)
    # Find a grid values appropriate for the coordinate (degree,
    # minute, second).

    tick_formatter1 = angle_helper.FormatterDMS()
    # And also uses an appropriate formatter.  Note that,the
    # acceptable Locator and Formatter class is a bit different than
    # that of mpl's, and you cannot directly use mpl's Locator and
    # Formatter here (but may be possible in the future).

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1
                                        )

    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    # make ticklabels of right and top axis visible.
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)
    ax1.axis["left"].major_ticklabels.set_visible(True)

    # let right axis shows ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks=0
    # let bottom axis shows ticklabels for 2nd coordinate (radius)
    ax1.axis["bottom"].get_helper().nth_coord_ticks=0
    ax1.axis["left"].get_helper().nth_coord_ticks=0

    fig.add_subplot(ax1)


    ax1.quiver(0,0,50,50,angles='xy',scale_units='xy',scale=1)

    ax1.set_aspect(1.)
    ax1.set_xlim(-100, 100)
    ax1.set_ylim(-100, 100)

    ax1.grid(True)
	def __init__(self):
		plt.ion()
		self.fig = plt.figure(num=2, figsize=(10,7))
		# plt.grid(b=True)
		# self.ax = plt.gca()
		# self.quiverLine = self.ax.quiver(0,0,100,100,angles='xy',scale_units='xy',scale=1)
		# self.ax.set_xlim([-150,150])
		# self.ax.set_ylim([-150,150])
		# self.annotation = self.ax.annotate('init', xy=(100+5, 100+5))
		    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
		# system in degree
		tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()

		# polar projection, which involves cycle, and also has limits in
		# its coordinates, needs a special method to find the extremes
		# (min, max of the coordinate within the view).

		# 20, 20 : number of sampling points along x, y direction
		extreme_finder = angle_helper.ExtremeFinderCycle(50, 50,
		                                                 lon_cycle = 360,
		                                                 lat_cycle = None,
		                                                 lon_minmax = None,
		                                                 lat_minmax = (0, np.inf),
		                                                 )

		grid_locator1 = angle_helper.LocatorDMS(24)
		# Find a grid values appropriate for the coordinate (degree,
		# minute, second).

		tick_formatter1 = angle_helper.FormatterDMS()
		# And also uses an appropriate formatter.  Note that,the
		# acceptable Locator and Formatter class is a bit different than
		# that of mpl's, and you cannot directly use mpl's Locator and
		# Formatter here (but may be possible in the future).

		grid_helper = GridHelperCurveLinear(tr,
		                                    extreme_finder=extreme_finder,
		                                    grid_locator1=grid_locator1,
		                                    tick_formatter1=tick_formatter1
		                                    )

		self.ax1 = SubplotHost(self.fig, 1, 1, 1, grid_helper=grid_helper)

		# make ticklabels of right and top axis visible.
		self.ax1.axis["right"].major_ticklabels.set_visible(True)
		self.ax1.axis["top"].major_ticklabels.set_visible(True)
		self.ax1.axis["left"].major_ticklabels.set_visible(True)

		# let right axis shows ticklabels for 1st coordinate (angle)
		self.ax1.axis["right"].get_helper().nth_coord_ticks=0
		# let bottom axis shows ticklabels for 2nd coordinate (radius)
		self.ax1.axis["bottom"].get_helper().nth_coord_ticks=0
		self.ax1.axis["left"].get_helper().nth_coord_ticks=0
		temp =  self.ax1.set_title('Signal strength & heading polar plots')
		temp.set_y(1.05) 


		self.ax1.grid(True)

		self.ax = self.fig.add_subplot(self.ax1)
		self.ax1.spines['left'].set_position('center')
		self.ax1.spines['right'].set_color('red')
		self.ax1.spines['bottom'].set_position('center')
		self.ax1.spines['top'].set_color('none')
		self.ax1.spines['left'].set_smart_bounds(True)
		self.ax1.spines['bottom'].set_smart_bounds(True)
		self.ax1.xaxis.set_ticks_position('bottom')
		self.ax1.yaxis.set_ticks_position('left')
		self.ax1.axhline(linewidth=2, color='blue')
		self.ax1.axvline(linewidth=2, color='blue')

		ticks = np.linspace(0, 255, 6)
		offset = np.zeros([1,255])
		for i in range(1,5):
			self.ax1.annotate(str(ticks[i]),size=10, xy=(ticks[i], -15))
			blah = self.ax1.plot(ticks[i],0, 'bo')

			self.ax1.annotate(str(ticks[i]),size=10, xy=(5, ticks[i]))
			blah = self.ax1.plot(0,ticks[i], 'bo')

		bbox_props = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9)
		# self.annotation = self.ax1.annotate('init',size=20, xy=(100, 100), bbox = bbox_props)
		self.annotation = plt.figtext(0.02, 0.9, 'rssi = ', size=20, alpha = 0.9, bbox = bbox_props)
		self.Freq = plt.figtext(0.85, 0.85, 'freq = ???', size=10, alpha = 0.9, bbox = bbox_props)
		self.Freq = plt.figtext(0.85, 0.9, 'Horizontal Plane', size=10, alpha = 0.9, bbox = bbox_props)

		self.quiverLine = self.ax1.quiver(0,0,50,50,angles='xy',scale_units='xy',scale=1)
		

		self.ax1.set_aspect(1.)
		self.ax1.set_xlim(-255, 255)
		self.ax1.set_ylim(-255, 255)
		

		self.xdata = []
		self.ydata = []
		self.polarline, = self.ax1.plot(self.xdata,self.ydata)
Example #18
0
def SemiPolarPlot(fig):
    # see demo_curvelinear_grid.py for details
    tr = Affine2D().scale(pi/180., 1.) + PolarAxes.PolarTransform()
    extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
                                                     lon_cycle = 360,
                                                     lat_cycle = None,
                                                     lon_minmax = None,
                                                     lat_minmax = (0, 1),
                                                     )

    grid_locator1 = angle_helper.LocatorDMS(11)
    grid_locator2 = FixedLocator([0.25, 0.5, 1., 0.75])
    tick_formatter1 = angle_helper.FormatterDMS()
    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        grid_locator2=grid_locator2,
                                        tick_formatter1=tick_formatter1,
                                        tick_formatter2=None
                                        )


    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
    fig.add_subplot(ax1)
    ax1.axis["top"].set_visible(False)
    ax1.axis["right"].set_visible(False)
    ax1.axis["bottom"].set_visible(False)
    ax1.axis["lon"] = ax1.new_floating_axis(1, 1)
    ax1.set_aspect(1)
    ax1.set_xlim(0, 2)
    ax1.set_ylim(-1., 1.)
    ax1.grid(True)
    
    curved_ax = ax1.get_aux_axes(tr)

    curved_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax
    ax1.patch.zorder=0.9
    
    return ax1, curved_ax
def test_custom_transform():
    class MyTransform(Transform):
        input_dims = 2
        output_dims = 2
        is_separable = False

        def __init__(self, resolution):
            """
            Resolution is the number of steps to interpolate between each input
            line segment to approximate its path in transformed space.
            """
            Transform.__init__(self)
            self._resolution = resolution

        def transform(self, ll):
            x, y = ll.T
            return np.column_stack([x, y - x])

        transform_non_affine = transform

        def transform_path(self, path):
            ipath = path.interpolated(self._resolution)
            return Path(self.transform(ipath.vertices), ipath.codes)

        transform_path_non_affine = transform_path

        def inverted(self):
            return MyTransformInv(self._resolution)

    class MyTransformInv(Transform):
        input_dims = 2
        output_dims = 2
        is_separable = False

        def __init__(self, resolution):
            Transform.__init__(self)
            self._resolution = resolution

        def transform(self, ll):
            x, y = ll.T
            return np.column_stack([x, y + x])

        def inverted(self):
            return MyTransform(self._resolution)

    fig = plt.figure()

    SubplotHost = host_subplot_class_factory(Axes)

    tr = MyTransform(1)
    grid_helper = GridHelperCurveLinear(tr)
    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
    fig.add_subplot(ax1)

    ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")
    ax1.parasites.append(ax2)
    ax2.plot([3, 6], [5.0, 10.])

    ax1.set_aspect(1.)
    ax1.set_xlim(0, 10)
    ax1.set_ylim(0, 10)

    ax1.grid(True)
def test_axis_direction():
    fig = plt.figure(figsize=(5, 5))

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # 20, 20 : number of sampling points along x, y direction
    extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
                                                     lon_cycle=360,
                                                     lat_cycle=None,
                                                     lon_minmax=None,
                                                     lat_minmax=(0, np.inf),
                                                     )

    grid_locator1 = angle_helper.LocatorDMS(12)
    tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)

    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    for axis in ax1.axis.values():
        axis.set_visible(False)

    fig.add_subplot(ax1)

    ax1.axis["lat1"] = axis = grid_helper.new_floating_axis(
        0, 130,
        axes=ax1, axis_direction="left")
    axis.label.set_text("Test")
    axis.label.set_visible(True)
    axis.get_helper()._extremes = 0.001, 10

    ax1.axis["lat2"] = axis = grid_helper.new_floating_axis(
        0, 50,
        axes=ax1, axis_direction="right")
    axis.label.set_text("Test")
    axis.label.set_visible(True)
    axis.get_helper()._extremes = 0.001, 10

    ax1.axis["lon"] = axis = grid_helper.new_floating_axis(
        1, 10,
        axes=ax1, axis_direction="bottom")
    axis.label.set_text("Test 2")
    axis.get_helper()._extremes = 50, 130
    axis.major_ticklabels.set_axis_direction("top")
    axis.label.set_axis_direction("top")

    grid_helper.grid_finder.grid_locator1.den = 5
    grid_helper.grid_finder.grid_locator2._nbins = 5

    ax1.set_aspect(1.)
    ax1.set_xlim(-8, 8)
    ax1.set_ylim(-4, 12)

    ax1.grid(True)
Example #21
0
def make_mw_plot(fig=None, mw_img_name = "Milky_Way_2005.jpg",
        solar_rad=8.5, fignum=5):
    """
    Generate a "Milky Way" plot with Robert Hurt's Milky Way illustration as
    the background.

    .. TODO:
        Figure out how to fix the axis labels.  They don't work now!

    Parameters
    ----------
    fig : matplotlib.figure instance
        If you want to start with a figure instance, can specify it
    mw_img_name: str
        The name of the image on disk
    solar_rad : float
        The assumed Galactocentric orbital radius of the sun
    fignum : int
        If Figure not specified, use this figure number
    """

    # load image
    mw = np.array(PIL.Image.open(mw_img_name))[:,::-1]

    # set some constants
    npix = mw.shape[0] # must be symmetric
    # Galactic Center in middle of image
    gc_loc = [x/2 for x in mw.shape]

    # Sun is at 0.691 (maybe really 0.7?) length of image
    sun_loc = mw.shape[0]/2,int(mw.shape[1]*0.691)
    # determine scaling
    kpc_per_pix = solar_rad / (sun_loc[1]-gc_loc[1])
    boxsize = npix*kpc_per_pix

    # most of the code below is taken from:
    # http://matplotlib.sourceforge.net/examples/axes_grid/demo_curvelinear_grid.html
    # and http://matplotlib.sourceforge.net/examples/axes_grid/demo_floating_axis.html

    if fig is None:
        fig = plt.figure(fignum)
    plt.clf()

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    # this defines the polar coordinate system @ Galactic center
    tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # grid helper stuff, I think (grid is off by default)
    # This may not apply to the image *at all*, but would if you
    # used the grid
    # 40, 40 : number of sampling points along x, y direction
    extreme_finder = angle_helper.ExtremeFinderCycle(40, 40,
                                                     lon_cycle = 360,
                                                     lat_cycle = None,
                                                     lon_minmax = None,
                                                     lat_minmax = (0, np.inf),
                                                     )

    grid_locator1 = angle_helper.LocatorDMS(12)
    # Find a grid values appropriate for the coordinate (degree,
    # minute, second).

    tick_formatter1 = angle_helper.FormatterDMS()
    # And also uses an appropriate formatter.  Note that,the
    # acceptable Locator and Formatter class is a bit different than
    # that of mpl's, and you cannot directly use mpl's Locator and
    # Formatter here (but may be possible in the future).

    grid_helper = GridHelperCurveLinear(tr,
                extreme_finder=extreme_finder,
                grid_locator1=grid_locator1,
                tick_formatter1=tick_formatter1,
                #tick_formatter2=matplotlib.ticker.FuncFormatter(lambda x: x * kpc_per_pix)
                )


    ax = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper, axisbg='#333333')
    fig.add_subplot(ax)
    # ax.transData is still a (rectlinear) pixel coordinate. Only the
    # grids are done in galactocentric coordinate.

    # show the image
    ax.imshow(mw,extent=[-boxsize/2,boxsize/2,-boxsize/2,boxsize/2])

    ax_pixgrid = ax.twin() # simple twin will give you a twin axes,
                           # but with normal grids.

    # to draw heliocentric grids, it is best to update the grid_helper
    # with new transform.

    # need to rotate by -90 deg to get into the standard convention
    tr_helio = Affine2D().scale(np.pi/180., 1.).translate(-np.pi/2.,0) + \
               PolarAxes.PolarTransform() + \
               Affine2D().translate(0,solar_rad)
    # Note that the transform is from the heliocentric coordinate to
    # the pixel coordinate of ax (i.e., ax.transData).

    ax.get_grid_helper().update_grid_finder(aux_trans=tr_helio)

    # Now we defina parasite axes with galactocentric & heliocentric
    # coordinates.

    # A parasite axes with given transform
    gc_polar = ParasiteAxesAuxTrans(ax, tr, "equal")
    ax.parasites.append(gc_polar)
    # note that ax2.transData == tr + galactocentric_axis.transData
    # Anthing you draw in ax2 will match the ticks and grids of galactocentric_axis.

    hc_polar = ParasiteAxesAuxTrans(ax, tr_helio, "equal")
    ax.parasites.append(hc_polar)


    return ax, ax_pixgrid, gc_polar, hc_polar
Example #22
0
def sgrid():
    # From matplotlib demos:
    # https://matplotlib.org/gallery/axisartist/demo_curvelinear_grid.html
    # https://matplotlib.org/gallery/axisartist/demo_floating_axis.html

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()
    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # 20, 20 : number of sampling points along x, y direction
    sampling_points = 20
    extreme_finder = ModifiedExtremeFinderCycle(sampling_points, sampling_points,
                                                     lon_cycle=360,
                                                     lat_cycle=None,
                                                     lon_minmax=(90,270),
                                                     lat_minmax=(0, np.inf),)

    grid_locator1 = angle_helper.LocatorDMS(15)
    tick_formatter1 = FormatterDMS()
    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1
                                        )

    fig = plt.figure()
    ax = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    # make ticklabels of right invisible, and top axis visible.
    visible = True
    ax.axis[:].major_ticklabels.set_visible(visible)
    ax.axis[:].major_ticks.set_visible(False)
    ax.axis[:].invert_ticklabel_direction()

    ax.axis["wnxneg"] = axis = ax.new_floating_axis(0, 180)
    axis.set_ticklabel_direction("-")
    axis.label.set_visible(False)
    ax.axis["wnxpos"] = axis = ax.new_floating_axis(0, 0)
    axis.label.set_visible(False)
    ax.axis["wnypos"] = axis = ax.new_floating_axis(0, 90)
    axis.label.set_visible(False)
    axis.set_axis_direction("left")
    ax.axis["wnyneg"] = axis = ax.new_floating_axis(0, 270)
    axis.label.set_visible(False)
    axis.set_axis_direction("left")
    axis.invert_ticklabel_direction()
    axis.set_ticklabel_direction("-")

    # let left axis shows ticklabels for 1st coordinate (angle)
    ax.axis["left"].get_helper().nth_coord_ticks = 0
    ax.axis["right"].get_helper().nth_coord_ticks = 0
    ax.axis["left"].get_helper().nth_coord_ticks = 0
    ax.axis["bottom"].get_helper().nth_coord_ticks = 0

    fig.add_subplot(ax)

    ### RECTANGULAR X Y AXES WITH SCALE
    #par2 = ax.twiny()
    #par2.axis["top"].toggle(all=False)
    #par2.axis["right"].toggle(all=False)
    #new_fixed_axis = par2.get_grid_helper().new_fixed_axis
    #par2.axis["left"] = new_fixed_axis(loc="left",
    #                                   axes=par2,
    #                                   offset=(0, 0))
    #par2.axis["bottom"] = new_fixed_axis(loc="bottom",
    #                                     axes=par2,
    #                                     offset=(0, 0))
    ### FINISH RECTANGULAR

    ax.grid(True, zorder=0,linestyle='dotted')

    _final_setup(ax)
    return ax, fig
Example #23
0
    def curvelinear_test2(fig, gs=None, xcenter=0.0, ycenter=17.3, xwidth=1.5, ywidth=1.5,
            xlabel=xlabel, ylabel=ylabel, xgrid_density=8, ygrid_density=5):
        """
        polar projection, but in a rectangular box.
        """

        tr = Affine2D().translate(0,90)
        tr += Affine2D().scale(np.pi/180., 1.)
        tr += PolarAxes.PolarTransform()
        tr += Affine2D().rotate(1.34)  # This rotates the grid

        extreme_finder = angle_helper.ExtremeFinderCycle(10, 60,
                                                        lon_cycle = 360,
                                                        lat_cycle = None,
                                                        lon_minmax = None,
                                                        lat_minmax = (-90, np.inf),
                                                        )

        grid_locator1 = angle_helper.LocatorHMS(xgrid_density) #changes theta gridline count
        tick_formatter1 = angle_helper.FormatterHMS()
        grid_locator2 = angle_helper.LocatorDMS(ygrid_density) #changes theta gridline count
        tick_formatter2 = angle_helper.FormatterDMS()


        grid_helper = GridHelperCurveLinear(tr,
                                            extreme_finder=extreme_finder,
                                            grid_locator1=grid_locator1,
                                            grid_locator2=grid_locator2,
                                            tick_formatter1=tick_formatter1,
                                            tick_formatter2=tick_formatter2
                                            )

        # ax1 = SubplotHost(fig, rect, grid_helper=grid_helper)
        if gs is None:
            ax1 = SubplotHost(fig, 111, grid_helper=grid_helper)
        else:
            ax1 = SubplotHost(fig, gs, grid_helper=grid_helper)



        # make ticklabels of right and top axis visible.
        ax1.axis["right"].major_ticklabels.set_visible(False)
        ax1.axis["top"].major_ticklabels.set_visible(False)
        ax1.axis["bottom"].major_ticklabels.set_visible(True) #Turn off?

        # let right and bottom axis show ticklabels for 1st coordinate (angle)
        ax1.axis["right"].get_helper().nth_coord_ticks=0
        ax1.axis["bottom"].get_helper().nth_coord_ticks=0


        fig.add_subplot(ax1)

        grid_helper = ax1.get_grid_helper()

        # These move the grid
        ax1.set_xlim(xcenter-xwidth, xcenter+xwidth) # moves the origin left-right in ax1
        ax1.set_ylim(ycenter-ywidth, ycenter+ywidth) # moves the origin up-down
        # ax1.set_xlim(-1.5, 1.4)
        # ax1.set_ylim(15.8, 18.8)

        if xlabel is not None:
            ax1.set_xlabel(xlabel)
        if ylabel is not None:
            ax1.set_ylabel(ylabel)
        # ax1.set_ylabel('Declination')
        # ax1.set_xlabel('Right Ascension')
        ax1.grid(True, linestyle='-')
        #ax1.grid(linestyle='--', which='x') # either keyword applies to both
        #ax1.grid(linestyle=':', which='y')  # sets of gridlines


        return ax1,tr
Example #24
0
def create_cg(st=None, fig=None, subplot=111, rot=-450, scale=-1,
              angular_spacing=10, radial_spacing=10,
              latmin=0, lon_cycle=360):
    """ Helper function to create curvelinear grid

    The function makes use of the Matplotlib AXISARTIST namespace
    `mpl_toolkits.axisartist \
    <https://matplotlib.org/mpl_toolkits/axes_grid/users/axisartist.html>`_.

    Here are some limitations to normal Matplotlib Axes. While using the
    Matplotlib `AxesGrid Toolkit \
    <https://matplotlib.org/mpl_toolkits/axes_grid/index.html>`_
    most of the limitations can be overcome.
    See `Matplotlib AxesGrid Toolkit User’s Guide \
    <https://matplotlib.org/mpl_toolkits/axes_grid/users/index.html>`_.

    Parameters
    ----------
    fig : matplotlib Figure object
        If given, the PPI/RHI will be plotted into this figure object.
        Axes are created as needed. If None a new figure object will
        be created or current figure will be used, depending on "subplot".
    subplot : :class:`matplotlib:matplotlib.gridspec.GridSpec`, \
        matplotlib grid definition
        nrows/ncols/plotnumber, see examples section
        defaults to '111', only one subplot
    rot : float
        Rotation of the source data in degrees, defaults to -450 for PPI,
        use 0 for RHI
    scale : float
        Scale of source data, defaults to -1. for PPI, use 1 for RHI
    angular_spacing : float
        Spacing of the angular grid, defaults to 10.
    radial_spacing : float
        Spacing of the radial grid, defaults to 10.
    latmin : float
        Startvalue for radial grid, defaults to 0.
    lon_cycle : float
        Angular cycle, defaults to 360.

    Returns
    -------
    cgax : matplotlib toolkit axisartist Axes object
        curvelinear Axes (r-theta-grid)
    caax : matplotlib Axes object (twin to cgax)
        Cartesian Axes (x-y-grid) for plotting cartesian data
    paax : matplotlib Axes object (parasite to cgax)
        The parasite axes object for plotting polar data
    """

    if st is not None:
        warnings.warn("ScanType string is deprecated and will be removed in "
                      "future release. Please use `rot` and `scale` keyword "
                      "arguments to specify PPI/RHI. ",
                      DeprecationWarning)
        if st == 'RHI':
            rot = 0
            scale = 1

    # create transformation
    # rotate
    tr_rotate = Affine2D().translate(rot, 0)
    # scale
    tr_scale = Affine2D().scale(scale * np.pi / 180, 1)
    # polar
    tr_polar = PolarAxes.PolarTransform()

    tr = tr_rotate + tr_scale + tr_polar

    # build up curvelinear grid
    extreme_finder = ah.ExtremeFinderCycle(360, 360,
                                           lon_cycle=lon_cycle,
                                           lat_cycle=None,
                                           lon_minmax=None,
                                           lat_minmax=(latmin, np.inf),
                                           )
    # locator and formatter for angular annotation
    grid_locator1 = ah.LocatorDMS(lon_cycle // angular_spacing)
    tick_formatter1 = ah.FormatterDMS()

    # grid_helper for curvelinear grid
    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        grid_locator2=None,
                                        tick_formatter1=tick_formatter1,
                                        tick_formatter2=None,
                                        )

    # try to set nice locations for radial gridlines
    grid_locator2 = grid_helper.grid_finder.grid_locator2
    grid_locator2._nbins = (radial_spacing * 2 + 1) // np.sqrt(2)

    # if there is no figure object given
    if fig is None:
        # create new figure if there is only one subplot
        if subplot == 111:
            fig = pl.figure()
        # otherwise get current figure or create new figure
        else:
            fig = pl.gcf()

    # generate Axis
    cgax = SubplotHost(fig, subplot, grid_helper=grid_helper)
    fig.add_axes(cgax)

    # get twin axis for cartesian grid
    caax = cgax.twin()
    # move axis annotation from right to left and top to bottom for
    # cartesian axis
    caax.toggle_axisline()

    # make right and top axis visible and show ticklabels (curvelinear axis)
    cgax.axis["top", "right"].set_visible(True)
    cgax.axis["top", "right"].major_ticklabels.set_visible(True)

    # make ticklabels of left and bottom axis invisible (curvelinear axis)
    cgax.axis["left", "bottom"].major_ticklabels.set_visible(False)

    # and also set tickmarklength to zero for better presentation
    # (curvelinear axis)
    cgax.axis["top", "right", "left", "bottom"].major_ticks.set_ticksize(0)

    # show theta (angles) on top and right axis
    cgax.axis["top"].get_helper().nth_coord_ticks = 0
    cgax.axis["right"].get_helper().nth_coord_ticks = 0

    # generate and add parasite axes with given transform
    paax = ParasiteAxesAuxTrans(cgax, tr, "equal")
    # note that paax.transData == tr + cgax.transData
    # Anything you draw in paax will match the ticks and grids of cgax.
    cgax.parasites.append(paax)

    return cgax, caax, paax
Example #25
0
def plotGsrResidue(theta,
                   phi,
                   residue,
                   optTheta,
                   optPhi,
                   mvabTheta=None,
                   mvabPhi=None,
                   mvubTheta=None,
                   mvubPhi=None):
    fig = figure()
    fig.clf()

    # some matplotlib setup stuff which I don't fully understand but it works
    tr = Affine2D().scale(pi / 180., 1.) + PolarAxes.PolarTransform()
    extreme_finder = angle_helper.ExtremeFinderCycle(
        20,
        20,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(0, inf),
    )
    grid_locator1 = angle_helper.LocatorDMS(12)
    tick_formatter1 = angle_helper.FormatterDMS()
    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)
    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
    fig.add_subplot(ax1)
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    # draw the filled contoured map in polar coordinates
    ax1.contour(transpose(mat(theta)) * mat(cos(phi * pi / 180)),
                transpose(mat(theta)) * mat(sin(phi * pi / 180)),
                1 / transpose(reshape(residue, (phi.size, -1))),
                100,
                lw=0.1)
    cc = ax1.contourf(
        transpose(mat(theta)) * mat(cos(phi * pi / 180)),
        transpose(mat(theta)) * mat(sin(phi * pi / 180)),
        1 / transpose(reshape(residue, (phi.size, -1))), 100)
    # remove gaps between the contour lines
    for c in cc.collections:
        c.set_antialiased(False)

    # show the MVAB direction
    if mvabTheta is not None and mvabPhi is not None:
        ax1.plot(mvabTheta * cos(mvabPhi * pi / 180),
                 mvabTheta * sin(mvabPhi * pi / 180),
                 'sk',
                 markersize=8)

    # show the MVUB direction
    if mvubTheta is not None and mvubPhi is not None:
        ax1.plot(mvubTheta * cos(mvubPhi * pi / 180),
                 mvubTheta * sin(mvubPhi * pi / 180),
                 'dk',
                 markersize=8)

    # show the optimal direction
    ax1.plot(optTheta * cos(optPhi * pi / 180),
             optTheta * sin(optPhi * pi / 180),
             '.k',
             markersize=15)

    # aspect and initial axes limits
    ax1.set_aspect(1.)
    ax1.set_xlim(-90, 90)
    ax1.set_ylim(-90, 90)

    # add grid
    ax1.grid(True)

    # add colobar
    cb = colorbar(cc, pad=0.07)
    cb.locator = MaxNLocator(14)
    cb.update_ticks()
    cb.set_label(r"$1/\tilde{\mathcal{R}}$")

    # save
    if toSave:
        savefig(resultsDir + '/eps/gsr_ResidualMap.eps', format='eps')
        savefig(resultsDir + '/png/gsr_ResidualMap.png', format='png')
Example #26
0
def createRLUAxes(self,figure=None,ids=[1, 1, 1],basex=None,basey=None):
    """Create a reciprocal lattice plot for a given DataSet object.
    
    Args:
        
        - Dataset (DataSet): DataSet object for which the RLU plot is to be made.

    Kwargs:

        - figure: Matplotlib figure in which the axis is to be put (default None)

        - ids (array): List of integer numbers provided to the SubplotHost ids attribute (default [1,1,1])

        - basex (float): Ticks are positioned at multiples of this value along x (default None)

        - basey (float): Ticks are positioned at multiples of this value along y (default None)

    Returns:
        
        - ax (Matplotlib axes): Axes containing the RLU plot.

    .. note::
        When rlu axis is created, the orientation of Qx and Qy is assumed to be rotated as well. 
        This is to be done in the self.View3D method call!

    .. note::
        When using python 2 the changing of tick marks is not supported due to limitations in matplotlib. However, if python 3 is used, the number 
        of ticks and their location can be change after the initialization using the set_xticks_number, set_yticks_number chaning the wanted number 
        of tick marks, or the set_xticks_base or set_yticks_base to change the base number, see RLU tutorial under Tools. As default a sufficient base
        number is found and will update when zooming.
        
    """

    sample = copy.deepcopy(self.sample)
    for samp in sample:
        samp.convert = np.einsum('ij,j...->i...',samp.RotMat,samp.convert)
        #sample.convert = np.einsum('ij,j...->i...',sample.RotMat,sample.convert)
        samp.convertinv = np.linalg.inv(samp.convert) # Convert from Qx, Qy to projX, projY

        samp.orientationMatrix = np.dot(samp.RotMat3D,samp.orientationMatrix)
        samp.orientationMatrixINV = np.linalg.inv(samp.orientationMatrix)
        samp.theta = 0.0

    if figure is None:
        fig = plt.figure(figsize=(7, 4))
    else:
        fig = figure
    def calculateTicks(ticks,angle,round=True):
        val = ticks/np.tan(angle/2.0)
        if round:
            return np.array(np.round(val),dtype=int)
        else:
            return val

    if pythonVersion==3: # Only for python 3
        if  not basex is None or not basey is None: # Either basex or basey is provided (or both)
            if basex is None:
                basex = calculateTicks(basey,sample[0].projectionAngle,round=False)
            elif basey is None:
                basey = basex/calculateTicks(1.0,sample[0].projectionAngle,round=False)

            grid_locator1 = MultipleLocator(base=basex)
            grid_locator2 = MultipleLocator(base=basey)
        else:
            basex = 0.5
            basey = 0.5

            grid_locator1 = MultipleLocator(base=basex)
            grid_locator2 = MultipleLocator(base=basey)
            
        grid_helper = GridHelperCurveLinear((sample[0].inv_tr, sample[0].tr),grid_locator1=grid_locator1,grid_locator2=grid_locator2)
    else: # Python 2
        grid_helper = GridHelperCurveLinear((sample[0].inv_tr, sample[0].tr))
    ax = SubplotHost(fig, *ids, grid_helper=grid_helper)
    ax.sample = sample[0]
    
    if pythonVersion==3: # Only for python 3

        ax.basex = basex
        ax.basey = basey

    def set_axis(ax,v1,v2,*args):
        if not args is ():
            points = np.concatenate([[v1,v2],[x for x in args]],axis=0)
        else:
            points = np.array([v1,v2])
            
        if points.shape[1] == 3:
            points = ax.sample.calculateHKLtoProjection(points[:,0],points[:,1],points[:,2]).T
        boundaries = np.array([ax.sample.inv_tr(x[0],x[1]) for x in points])
        ax.set_xlim(boundaries[:,0].min(),boundaries[:,0].max())
        ax.set_ylim(boundaries[:,1].min(),boundaries[:,1].max())
        if pythonVersion == 3: # Only possible in python 3
            ax.forceGridUpdate()


    fig.add_subplot(ax)
    ax.set_aspect(1.)
    ax.grid(True, zorder=0)
    
    if not np.isclose(ax.sample.projectionAngle,np.pi/2.0,atol=0.001):
        ax.axis["top"].major_ticklabels.set_visible(True)
        ax.axis["right"].major_ticklabels.set_visible(True)

    ax.format_coord = ax.sample.format_coord
    ax.set_axis = lambda v1,v2,*args: set_axis(ax,v1,v2,*args)

    def beautifyLabel(vec):
        Vec = [x.astype(int) if np.isclose(x.astype(float)-x.astype(int),0.0) else x.astype(float) for x in vec]
        return '{} [RLU]'.format(', '.join([str(x) for x in Vec]))

    ax.set_xlabel(beautifyLabel(ax.sample.projectionVector1))
    ax.set_ylabel(beautifyLabel(ax.sample.projectionVector2))

    if pythonVersion==3: # Only for python 3
        ax.calculateTicks = lambda value:calculateTicks(value,ax.sample.projectionAngle)
        ax.forceGridUpdate = lambda:forceGridUpdate(ax)
        ax._oldXlimDiff = np.diff(ax.get_xlim())
        ax._oldYlimDiff = np.diff(ax.get_ylim())

        ax.get_aspect_ratio = lambda: get_aspect(ax)

        ax.callbacks.connect('xlim_changed', axisChanged)
        ax.callbacks.connect('ylim_changed', axisChanged)
        ax.callbacks.connect('draw_event',lambda ax: axisChanged(ax,forceUpdate=True))
        ax.axisChanged = lambda direction='both': axisChanged(ax,forceUpdate=True,direction=direction)
    
        @updateAxisDecorator(ax=ax,direction='x')
        def set_xticks_base(xBase,ax=ax):
            """Setter of the base x ticks to be used for plotting

            Args:

                - xBase (float): Base of the tick marks

            """
            if not isinstance(ax._grid_helper.grid_finder.grid_locator1,MultipleLocator):
                l1 = MultipleLocator(base=xBase)
                ax._grid_helper.update_grid_finder(grid_locator1=l1)

            ax.xbase = xBase

        @updateAxisDecorator(ax=ax,direction='y')
        def set_yticks_base(yBase,ax=ax):
            """Setter of the base y ticks to be used for plotting

            Args:

                - yBase (float): Base of the tick marks

            """
            if not isinstance(ax._grid_helper.grid_finder.grid_locator2,MultipleLocator):
                l2 = MultipleLocator(base=yBase)
                ax._grid_helper.update_grid_finder(grid_locator2=l2)
            ax.ybase = yBase

        @updateAxisDecorator(ax=ax,direction='x')
        def set_xticks_number(xNumber,ax=ax):
            """Setter of the number of x ticks to be used for plotting

            Args:

                - xNumber (int): Number of x tick marks

            """
            if not isinstance(ax._grid_helper.grid_finder.grid_locator1,MaxNLocator):
                l1 = MaxNLocator(nbins=xNumber)
                ax._grid_helper.update_grid_finder(grid_locator1=l1)
            ax.xticks = xNumber

        @updateAxisDecorator(ax=ax,direction='y')
        def set_yticks_number(yNumber,ax=ax):
            """Setter of the number of y ticks to be used for plotting

            Args:

                - yNumber (int): Number of y tick marks

            """
            if not isinstance(ax._grid_helper.grid_finder.grid_locator2,MaxNLocator):
                l2 = MaxNLocator(nbins=yNumber)
                ax._grid_helper.update_grid_finder(grid_locator2=l2)
            ax.yticks = yNumber

        ax.set_xticks_base = set_xticks_base
        ax.set_yticks_base = set_yticks_base
        ax.set_xticks_number = set_xticks_number
        ax.set_yticks_number = set_yticks_number

    return ax
Example #27
0
def curvelinear_test2(fig, rect=111):
    """
    Polar projection, but in a rectangular box.
    """

    # see demo_curvelinear_grid.py for details
    tr = Affine2D().translate(0, 90) + Affine2D().scale(np.pi / 180., 1.) + \
        PolarAxes.PolarTransform()

    extreme_finder = angle_helper.ExtremeFinderCycle(
        10,
        60,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(-90, np.inf),
    )
    # Changes theta gridline count
    grid_locator1 = angle_helper.LocatorHMS(12)
    grid_locator2 = angle_helper.LocatorDMS(6)
    tick_formatter1 = angle_helper.FormatterHMS()
    tick_formatter2 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        grid_locator2=grid_locator2,
                                        tick_formatter1=tick_formatter1,
                                        tick_formatter2=tick_formatter2)

    ax1 = SubplotHost(fig, rect, grid_helper=grid_helper)

    # make ticklabels of right and top axis visible.
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)
    ax1.axis["bottom"].major_ticklabels.set_visible(True)
    # let right and bottom axis show ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 0

    #
    fig.add_subplot(ax1)

    grid_helper = ax1.get_grid_helper()

    # You may or may not need these - they set the view window explicitly
    # rather than using the default as determined by matplotlib with extreme
    # finder.
    ax1.set_aspect(1.)
    ax1.set_xlim(-4, 25)  # moves the origin left-right in ax1
    ax1.set_ylim(-2.5, 30)  # moves the origin up-down

    ax1.set_ylabel('$DEC\,(^{\circ})$')
    ax1.set_xlabel('$RA\,(h)$')
    ax1.grid(True)
    # ax1.grid(linestyle='--', which='x') # either keyword applies to both
    # ax1.grid(linestyle=':', which='y')  # sets of gridlines

    return ax1, tr
Example #28
0
def plotGsrResidue(theta, phi, residue, optTheta, optPhi, mvabTheta=None, mvabPhi=None, mvubTheta=None, mvubPhi=None):
    fig = figure()
    fig.clf()

    # some matplotlib setup stuff which I don't fully understand but it works
    tr = Affine2D().scale(pi/180., 1.) + PolarAxes.PolarTransform()
    extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
                                                     lon_cycle = 360,
                                                     lat_cycle = None,
                                                     lon_minmax = None,
                                                     lat_minmax = (0, inf),
                                                     )
    grid_locator1 = angle_helper.LocatorDMS(12)
    tick_formatter1 = angle_helper.FormatterDMS()
    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1
                                        )
    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
    fig.add_subplot(ax1)
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)
    ax1.axis["right"].get_helper().nth_coord_ticks=0
    ax1.axis["bottom"].get_helper().nth_coord_ticks=1

    # draw the filled contoured map in polar coordinates
    ax1.contour(transpose(mat(theta))*mat(cos(phi*pi/180)), transpose(mat(theta))*mat(sin(phi*pi/180)), 1/transpose(reshape(residue, (phi.size,-1))), 100, lw=0.1)
    cc = ax1.contourf(transpose(mat(theta))*mat(cos(phi*pi/180)), transpose(mat(theta))*mat(sin(phi*pi/180)), 1/transpose(reshape(residue, (phi.size,-1))), 100)
    # remove gaps between the contour lines
    for c in cc.collections:
        c.set_antialiased(False)

    # show the MVAB direction
    if mvabTheta is not None and mvabPhi is not None:
        ax1.plot(mvabTheta*cos(mvabPhi*pi/180), mvabTheta*sin(mvabPhi*pi/180), 'sk', markersize=8)

    # show the MVUB direction
    if mvubTheta is not None and mvubPhi is not None:
        ax1.plot(mvubTheta*cos(mvubPhi*pi/180), mvubTheta*sin(mvubPhi*pi/180), 'dk', markersize=8)

    # show the optimal direction
    ax1.plot(optTheta*cos(optPhi*pi/180), optTheta*sin(optPhi*pi/180), '.k', markersize=15)

    # aspect and initial axes limits
    ax1.set_aspect(1.)
    ax1.set_xlim(-90, 90)
    ax1.set_ylim(-90, 90)

    # add grid
    ax1.grid(True)

    # add colobar
    cb = colorbar(cc, pad=0.07)
    cb.locator = MaxNLocator(14)
    cb.update_ticks()
    cb.set_label(r"$1/\tilde{\mathcal{R}}$")

    # save
    if toSave:
        savefig(resultsDir+'/eps/gsr_ResidualMap.eps', format='eps')
        savefig(resultsDir+'/png/gsr_ResidualMap.png', format='png')
Example #29
0
def curvelinear_test2(fig):
    """
    polar projection, but in a rectangular box.
    """
    global ax1
    import numpy as np
    import  mpl_toolkits.axisartist.angle_helper as angle_helper
    from matplotlib.projections import PolarAxes
    from matplotlib.transforms import Affine2D

    from mpl_toolkits.axisartist import SubplotHost

    from mpl_toolkits.axisartist import GridHelperCurveLinear

    # see demo_curvelinear_grid.py for details
    tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()

    extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
                                                     lon_cycle = 360,
                                                     lat_cycle = None,
                                                     lon_minmax = None,
                                                     lat_minmax = (0, np.inf),
                                                     )

    grid_locator1 = angle_helper.LocatorDMS(12)

    tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1
                                        )


    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    fig.add_subplot(ax1)

    # Now creates floating axis

    #grid_helper = ax1.get_grid_helper()
    # floating axis whose first coordinate (theta) is fixed at 60
    ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 60)
    axis.label.set_text(r"$\theta = 60^{\circ}$")
    axis.label.set_visible(True)

    # floating axis whose second coordinate (r) is fixed at 6
    ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 6)
    axis.label.set_text(r"$r = 6$")

    ax1.set_aspect(1.)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    ax1.grid(True)
Example #30
0
def get_smith(fig,
              rect=111,
              plot_impedance=True,
              plot_ticks=False,
              plot_admittance=False,
              plot_labels=False):
    '''Function which returns an axis with a blank smith chart, provide a figure and optional rect coords'''

    #Example use:

    # fig3 = plt.figure(3)
    # ax31 = pySmith.get_smith(fig3, 221)
    # ax31.plot(np.real(filtsmatrix[0,:,0,0]),np.imag(filtsmatrix[0,:,0,0]))
    # ax32= pySmith.get_smith(fig3, 222)
    # ax32.plot(np.real(filtsmatrix[0,:,0,1]),np.imag(filtsmatrix[0,:,0,1]))
    # ax33 = pySmith.get_smith(fig3, 223)
    # ax33.plot(np.real(filtsmatrix[0,:,1,0]),np.imag(filtsmatrix[0,:,1,0]))
    # ax34 = pySmith.get_smith(fig3, 224)
    # ax34.plot(np.real(filtsmatrix[0,:,1,1]),np.imag(filtsmatrix[0,:,1,1]))
    try:
        #font definition
        font = {
            'family': 'sans-serif',
            'color': 'black',
            'weight': 'normal',
            'size': 16,
        }

        #plot radial tick marks
        tr = PolarAxes.PolarTransform()
        num_thetas = 8  #*3 #12 gives in 30 deg intervals, 8 in 45 deg, 24 in 15deg
        thetas = np.linspace(0.0, math.pi * (1 - 2.0 / num_thetas),
                             num_thetas // 2)
        angle_ticks = []  #(0, r"$0$"),
        for theta in thetas:
            angle_info = []
            angle_info.append(theta)
            deg = int(round(180.0 * theta / math.pi))
            angle_info.append(r'%d$^{\circ}$' % deg)
            angle_ticks.append(angle_info)
        grid_locator1 = FixedLocator([v for v, s in angle_ticks])
        tick_formatter1 = DictFormatter(dict(angle_ticks))
        thetas2 = np.linspace(math.pi, 2 * math.pi * (1 - 1.0 / num_thetas),
                              num_thetas // 2)
        angle_ticks2 = []  #(0, r"$0$"),
        for theta in thetas2:
            angle_info = []
            angle_info.append(theta)
            deg = int(round(180.0 * theta / math.pi))
            angle_info.append(r'%d$^{\circ}$' % deg)
            angle_ticks2.append(angle_info)
        grid_locator2 = FixedLocator([v for v, s in angle_ticks2])
        tick_formatter2 = DictFormatter(dict(angle_ticks2))

        grid_helper1 = floating_axes.GridHelperCurveLinear(
            tr,
            extremes=(math.pi, 0, 1, 0),
            grid_locator1=grid_locator1,
            #grid_locator2=grid_locator2,
            tick_formatter1=tick_formatter1  #,
            #tick_formatter2=None,
        )

        grid_helper2 = floating_axes.GridHelperCurveLinear(
            tr,
            extremes=(2 * math.pi, math.pi, 1, 0),
            grid_locator1=grid_locator2,
            #grid_locator2=grid_locator2,
            tick_formatter1=tick_formatter2  #,
            #tick_formatter2=None,
        )

        r1 = int(math.floor(rect / 100))
        r2 = int(math.floor((rect - 100 * r1) / 10))
        r3 = int(math.floor((rect - 100 * r1 - 10 * r2)))
        ax = SubplotHost(fig, r1, r2, r3, grid_helper=grid_helper1)
        ax2 = SubplotHost(fig, r1, r2, r3, grid_helper=grid_helper2)
        #ax.set_aspect(math.pi/180.0,'datalim')
        fig.add_subplot(ax)
        fig.add_subplot(ax2)

        ax.axis["bottom"].major_ticklabels.set_axis_direction("top")
        ax.axis["bottom"].major_ticklabels.set_fontsize(13)
        ax.axis["left"].set_visible(False)
        ax.axis["left"].toggle(all=False)
        ax.axis["right"].set_visible(False)
        ax.axis["right"].toggle(all=False)
        ax.axis["top"].set_visible(False)
        ax.axis["top"].toggle(all=False)
        ax.patch.set_visible(False)

        ax2.axis["bottom"].major_ticklabels.set_fontsize(13)
        ax2.axis["left"].set_visible(False)
        ax2.axis["left"].toggle(all=False)
        ax2.axis["right"].set_visible(False)
        ax2.axis["right"].toggle(all=False)
        ax2.axis["top"].set_visible(False)
        ax2.axis["top"].toggle(all=False)

        #ax = fig.add_subplot(rect)

        #remove axis labels
        ax.axis('off')
        #set aspect ratio to 1
        ax.set_aspect(1)  #, 'datalim')
        #set limits
        ax.set_xlim([-1.02, 1.02])
        ax.set_ylim([-1.02, 1.02])
        #remove axis labels
        ax2.axis('off')
        #set aspect ratio to 1
        ax2.set_aspect(1)  #,'datalim')
        #set limits
        ax2.set_xlim([-1.02, 1.02])
        ax2.set_ylim([-1.02, 1.02])
        ax2.patch.set_visible(False)
        if plot_impedance:
            #make lines of constant resistance
            res_log = np.linspace(-4, 4, 9)
            react_log = np.linspace(-5, 5, 2001)
            res = 2**res_log
            react = 10**react_log
            react2 = np.append(-1.0 * react[::-1], np.array([0]))
            react = np.append(react2, react)
            for r in res:
                z = 1j * react + r
                gam = (z - 1) / (z + 1)
                x = np.real(gam)
                y = np.imag(gam)
                if abs(r - 1) > 1e-6:
                    ax.plot(x, y, c='k', linewidth=0.75, alpha=0.25)
                else:
                    ax.plot(x, y, c='k', linewidth=1.0, alpha=0.4)
            #make lines of constant reactance
            react_log = np.linspace(-3, 3, 7)
            res_log = np.linspace(-5, 5, 2001)
            res = 10**res_log
            react = 2**react_log
            react2 = np.append(-1.0 * react[::-1], np.array([0]))
            react = np.append(react2, react)
            for chi in react:
                z = 1j * chi + res
                gam = (z - 1) / (z + 1)
                x = np.real(gam)
                y = np.imag(gam)
                if abs(chi - 1) > 1e-6 and abs(chi +
                                               1) > 1e-6 and abs(chi) > 1e-6:
                    ax.plot(x, y, c='k', linewidth=0.75, alpha=0.25)
                else:
                    ax.plot(x, y, c='k', linewidth=1.0, alpha=0.4)
        if plot_admittance:
            #make lines of constant conductance
            res_log = np.linspace(-4, 4, 9)
            react_log = np.linspace(-5, 5, 2001)
            res = 2**res_log
            react = 10**react_log
            react = np.append(-1.0 * react[::-1], react)
            for r in res:
                y = 1.0 / r + 1.0 / (1j * react)
                gam = (1.0 / y - 1) / (1.0 / y + 1)
                x = np.real(gam)
                y = np.imag(gam)
                if abs(r - 1) > 1e-6:
                    ax.plot(x, y, c='k', linewidth=0.75, alpha=0.25)
                else:
                    ax.plot(x, y, c='k', linewidth=1.0, alpha=0.4)
            #make lines of constant susceptance
            react_log = np.linspace(-3, 3, 7)
            res_log = np.linspace(-5, 5, 2001)
            res = 10**res_log
            react = 2**react_log
            react = np.append(-1.0 * react[::-1], react)
            for chi in react:
                y = 1.0 / (1j * chi) + 1.0 / res
                gam = (1.0 / y - 1) / (1.0 / y + 1)
                x = np.real(gam)
                y = np.imag(gam)
                if abs(chi - 1) > 1e-6 and abs(chi + 1) > 1e-6:
                    ax.plot(x, y, c='k', linewidth=0.75, alpha=0.25)
                else:
                    ax.plot(x, y, c='k', linewidth=1.0, alpha=0.4)
            y = 1.0 / res
            gam = (1.0 / y - 1) / (1.0 / y + 1)
            x = np.real(gam)
            y = np.imag(gam)
            ax.plot(x, y, c='k', linewidth=1.0, alpha=0.75)
        if plot_labels:
            #naive text placement only works for default python figure size with 1 subplot
            ax.text(-0.15, 1.04, r'$\Gamma$ = 1j', fontdict=font)
            ax.text(-1.4, -0.035, r'$\Gamma$ = -1', fontdict=font)
            ax.text(-0.17, -1.11, r'$\Gamma$ = -1j', fontdict=font)
            ax.text(1.04, -0.035, r'$\Gamma$ = 1', fontdict=font)
        if plot_ticks:
            num_minorticks = 3
            num_thetas = num_thetas * (num_minorticks + 1)
            thetas = np.linspace(0, 2.0 * math.pi * (1.0 - 1.0 / num_thetas),
                                 num_thetas)
            r_inner = 0.985
            r_outer = 1.0
            rads = np.linspace(r_inner, r_outer, 2)
            ticknum = 0
            for theta in thetas:
                x = rads * np.cos(theta)
                y = rads * np.sin(theta)
                if ticknum % (num_minorticks + 1) != 0:
                    ax.plot(x, y, c='k', linewidth=1.0, alpha=1.0)
                ticknum = ticknum + 1

        return ax
    except Exception as e:
        print('\nError in %s' % inspect.stack()[0][3])
        print(e)
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)
Example #31
0
def curvelinear_test2(fig):
    """
    polar projection, but in a rectangular box.
    """

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # 20, 20 : number of sampling points along x, y direction
    extreme_finder = angle_helper.ExtremeFinderCycle(
        20,
        20,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(0, np.inf),
    )

    grid_locator1 = angle_helper.LocatorDMS(12)
    # Find a grid values appropriate for the coordinate (degree,
    # minute, second).

    tick_formatter1 = angle_helper.FormatterDMS()
    # And also uses an appropriate formatter.  Note that,the
    # acceptable Locator and Formatter class is a bit different than
    # that of mpl's, and you cannot directly use mpl's Locator and
    # Formatter here (but may be possible in the future).

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)

    ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper)

    # make ticklabels of right and top axis visible.
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)

    # let right axis shows ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0
    # let bottom axis shows ticklabels for 2nd coordinate (radius)
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    fig.add_subplot(ax1)

    # A parasite axes with given transform
    ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")
    # note that ax2.transData == tr + ax1.transData
    # Anthing you draw in ax2 will match the ticks and grids of ax1.
    ax1.parasites.append(ax2)
    intp = cbook.simple_linear_interpolation
    ax2.plot(intp(np.array([0, 30]), 50),
             intp(np.array([10., 10.]), 50),
             linewidth=2.0)

    ax1.set_aspect(1.)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    ax1.grid(True, zorder=0)
Example #32
0
def make_polar_axis(figure):
    """
    Generate a polar axis.

    Examples
    --------
    >>> from pylab import *
    >>> f = figure()
    >>> ax1,ax2 = make_polar_axis(f)
    >>> f.add_subplot(ax1)
    """
    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # 20, 20 : number of sampling points along x, y direction
    extreme_finder = angle_helper.ExtremeFinderCycle(
        40,
        40,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(0, np.inf),
    )

    grid_locator1 = angle_helper.LocatorDMS(12)
    # Find a grid values appropriate for the coordinate (degree,
    # minute, second).

    tick_formatter1 = angle_helper.FormatterDMS()
    # And also uses an appropriate formatter.  Note that,the
    # acceptable Locator and Formatter class is a bit different than
    # that of mpl's, and you cannot directly use mpl's Locator and
    # Formatter here (but may be possible in the future).

    grid_helper = GridHelperCurveLinear(
        tr,
        extreme_finder=extreme_finder,
        grid_locator1=grid_locator1,
        tick_formatter1=tick_formatter1,
        #tick_formatter2=matplotlib.ticker.FuncFormatter(lambda x: x * kpc_per_pix)
    )

    ax1 = SubplotHost(figure,
                      1,
                      1,
                      1,
                      grid_helper=grid_helper,
                      axisbg='#333333')

    # make ticklabels of right and top axis visible.
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)

    # let right axis shows ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0
    # let bottom axis shows ticklabels for 2nd coordinate (radius)
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")

    ax1.parasites.append(ax2)

    return ax1, ax2
Example #33
0
def createQEAxes(DataSet=None,axis=0,figure = None, projectionVector1 = None, projectionVector2 = None):
    """Function to create Q E plot

    Kwargs:

        - DataSet (DataSet): If provided and no projections vectors creates QE axis for main direction (default None)

        - axis (int): Whether to create axis 0 or 1 (projection vector 0 or orthogonal to this, default 0)

        - figure (figure): If provided, this is used to create the axis within (default None)

        - projectionVector1 (vec): Projection vector along which data is plotted. If not provided sample vector is used (default None)

        - projectionVector2 (vec): Projection vector orthogonal to data. If not provided sample vector is used (default None)


    """
    
    if projectionVector1 is None or projectionVector2 is None:
        v1 = DataSet.sample[0].projectionVector1
        v2 = DataSet.sample[0].projectionVector2
        angle = DataSet.sample[0].projectionAngle
        orientationMatrix = DataSet.sample[0].orientationMatrix
    else:
        v1 = np.array(projectionVector1)
        v2 = np.array(projectionVector2)
        
        if not np.all([x.shape==(3,) for x in [v1,v2]]) or not np.all([len(x.shape)==1 for x in [v1,v2]]):
            raise AttributeError('Provided vector(s) is not 3D: projectionVector1.shape={} or projectionVector2.shape={}'.format(v1.shape,v2.shape))
        angle = np.arccos(np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2)))
        orientationMatrix = np.ones(3)

    sample = copy.deepcopy(DataSet.sample)
    
    v1,v2 = sample[0].projectionVector1,sample[0].projectionVector2
    angle = np.sign(np.dot(np.cross(v1,v2),sample[0].planeNormal))*sample[0].projectionAngle
    
    v2Length = np.linalg.norm(v2)/np.linalg.norm(v1)
    projectionMatrix = np.linalg.inv(np.array([[1,0],[np.cos(angle)*v2Length,np.sin(angle)*v2Length]]).T)
    
    projectionVectorQX = np.dot(np.dot(projectionMatrix,[1,0]),np.array([v1,v2]))
    projectionVectorQY = np.dot(np.dot(projectionMatrix,[0,1]),np.array([v1,v2]))
    projectionVectorQX = _tools.LengthOrder(projectionVectorQX)
    projectionVectorQY = _tools.LengthOrder(projectionVectorQY)
    projectionVectorQXLength = np.linalg.norm(np.dot(orientationMatrix,projectionVectorQY))
    projectionVectorQYLength = np.linalg.norm(np.dot(orientationMatrix,projectionVectorQX))
    projectionVectorQXFormated = ', '.join(['{:.3f}'.format(x) for x in projectionVectorQX])
    projectionVectorQYFormated = ', '.join(['{:.3f}'.format(x) for x in projectionVectorQY])
    
    if axis == 0:
        projectionVectorLength = projectionVectorQYLength
        projectionVectorLengthORthogonal = projectionVectorQXLength
        projectionVectorFormated = projectionVectorQXFormated
        projectionVector = projectionVectorQX
        projectionVectorOrthogonal = projectionVectorQY
    elif axis == 1:
        projectionVectorLength = projectionVectorQXLength
        projectionVectorFormated = projectionVectorQYFormated
        projectionVectorLengthORthogonal = projectionVectorQYLength
        projectionVector = projectionVectorQY
        projectionVectorOrthogonal = projectionVectorQX
    else:
        raise AttributeError('Provided axis of {} is not allowed. Should be either 0 or 1.'.format(axis))

    if figure is None:
        
        figure = plt.figure(figsize=(7, 4))
    else:
        figure.clf()
    def inv_tr(l,x,y):
        return x*l,y
    
    def tr(l,x,y):
        return x/l,y
    
    if pythonVersion == 3:
        grid_locator1 = MultipleLocator(base=1.0) # Standard X ticks is multiple locator
        grid_helper = GridHelperCurveLinear((lambda x,y:inv_tr(projectionVectorLength,x,y), 
                                        lambda x,y:tr(projectionVectorLength,x,y)),grid_locator1=grid_locator1)
    
    else:
        grid_helper = GridHelperCurveLinear((lambda x,y:inv_tr(projectionVectorLength,x,y), 
                                        lambda x,y:tr(projectionVectorLength,x,y)))
    
    ax = SubplotHost(figure, 1, 1, 1, grid_helper=grid_helper)
    ax.sample = sample[0]

    figure.add_subplot(ax)
    #ax.set_aspect(1.)
    ax.grid(True, zorder=0)
    
    def calculateRLU(l,v1,x,y,v,step):
        return np.asarray(x)/l*v1+v*step, np.asarray(y)

    def format_coord(x,y): # pragma: no cover # x is H,K,L and y is  energy
        xformated = ', '.join(['{} = {}'.format(Y[0],Y[1]) for Y in zip(['h','k','l'],['{:.4f}'.format(X) for X in x])])
        return '{}, E={:.4f}'.format(xformated,y)
    
    
    ax.set_xlabel('{} [RLU]'.format(projectionVectorFormated))
    
    ax.set_ylabel('E [meV]')
    ax._length = projectionVectorLengthORthogonal
    ax._projectionVector = projectionVector 
    ax._projectionVectorOrthogonal = projectionVectorOrthogonal
    ax._step = 0.0
    ax.calculateRLU = lambda x,y: calculateRLU(projectionVectorLength,ax._projectionVector,x,y,ax._projectionVectorOrthogonal,ax._step)
    ax.format_coord = lambda x,y: format_coord(*ax.calculateRLU(x,y))


    if pythonVersion == 3:
        ax.forceGridUpdate = lambda:forceGridUpdate(ax)
        ax.xticks = 7

        def xAxisChanged(axis, forceUpdate=False):
            locator = axis._grid_helper.grid_finder.grid_locator1
            xlim = axis.get_xlim()
            xlimDiff = np.diff(xlim)
            if isinstance(locator,MultipleLocator):
                if hasattr(axis,'xBase'):
                    base = axis.xBase
                else:
                    base = calculateBase(locator,xlimDiff,axis.xticks)
                locator.set_params(base=base)
                
            elif isinstance(locator,MaxNLocator):
                if hasattr(axis,'xTicks'):
                    ticks = getattr(axis,'xTicks')
                else:
                    ticks = 7
                locator.set_params(nbins = ticks)
            else:
                return
            axis.forceGridUpdate()

        ax.callbacks.connect('xlim_changed', xAxisChanged)

        ax.callbacks.connect('draw_event',lambda ax: xAxisChanged(ax,forceUpdate=True))
        ax.xAxisChanged = lambda: xAxisChanged(ax,forceUpdate=True)


        @updateXAxisDecorator(ax=ax)
        def set_xticks_base(xBase=None,ax=ax):
            """Setter of the base x ticks to be used for plotting

            Kwargs:

                - xBase (float): Base of the tick marks (default automatic)

            """
            
                
            if not isinstance(ax._grid_helper.grid_finder.grid_locator1,MultipleLocator):
                l1 = MultipleLocator(base=xBase)
                ax._grid_helper.update_grid_finder(grid_locator1=l1)

            if xBase is None:
                if hasattr(ax,'xBase'):
                    delattr(ax,'xBase')
            else:
                ax.xBase = xBase

        @updateXAxisDecorator(ax=ax)
        def set_xticks_number(xNumber = None,ax=ax):
            """Setter of the number of x ticks to be used for plotting

            Kwargs:

                - xNumber (int): Number of x tick marks (default 7)

            """
            if xNumber is None:
                xNumber = 7

            if not isinstance(ax._grid_helper.grid_finder.grid_locator1,MaxNLocator):
                l1 = MaxNLocator(nbins=xNumber)
                ax._grid_helper.update_grid_finder(grid_locator1=l1)
            ax.xTicks = xNumber


        ax.set_xticks_base = set_xticks_base
        ax.set_xticks_number = set_xticks_number


    return ax
Example #34
0
def create_cg(st, fig=None, subplot=111):
    """ Helper function to create curvelinear grid

    The function makes use of the Matplotlib AXISARTIST namespace
    `mpl_toolkits.axisartist \
    <https://matplotlib.org/mpl_toolkits/axes_grid/users/axisartist.html>`_.

    Here are some limitations to normal Matplotlib Axes. While using the
    Matplotlib `AxesGrid Toolkit \
    <https://matplotlib.org/mpl_toolkits/axes_grid/index.html>`_
    most of the limitations can be overcome.
    See `Matplotlib AxesGrid Toolkit User’s Guide \
    <https://matplotlib.org/mpl_toolkits/axes_grid/users/index.html>`_.

    Parameters
    ----------
    st : string
        scan type, 'PPI' or 'RHI'
    fig : matplotlib Figure object
        If given, the PPI will be plotted into this figure object. Axes are
        created as needed. If None a new figure object will be created or
        current figure will be used, depending on "subplot".
    subplot : :class:`matplotlib:matplotlib.gridspec.GridSpec`, \
        matplotlib grid definition
        nrows/ncols/plotnumber, see examples section
        defaults to '111', only one subplot

    Returns
    -------
    cgax : matplotlib toolkit axisartist Axes object
        curvelinear Axes (r-theta-grid)
    caax : matplotlib Axes object (twin to cgax)
        Cartesian Axes (x-y-grid) for plotting cartesian data
    paax : matplotlib Axes object (parasite to cgax)
        The parasite axes object for plotting polar data
    """

    if st == 'RHI':
        # create transformation
        tr = Affine2D().scale(np.pi / 180, 1) + PolarAxes.PolarTransform()

        # build up curvelinear grid
        extreme_finder = ah.ExtremeFinderCycle(20, 20,
                                               lon_cycle=100,
                                               lat_cycle=None,
                                               lon_minmax=(0, np.inf),
                                               lat_minmax=(0, np.inf),
                                               )

        # locator and formatter for angular annotation
        grid_locator1 = ah.LocatorDMS(10.)
        tick_formatter1 = ah.FormatterDMS()

        # grid_helper for curvelinear grid
        grid_helper = GridHelperCurveLinear(tr,
                                            extreme_finder=extreme_finder,
                                            grid_locator1=grid_locator1,
                                            grid_locator2=None,
                                            tick_formatter1=tick_formatter1,
                                            tick_formatter2=None,
                                            )

        # try to set nice locations for range gridlines
        grid_helper.grid_finder.grid_locator2._nbins = 30.0
        grid_helper.grid_finder.grid_locator2._steps = [0, 1, 1.5,
                                                        2, 2.5, 5, 10]

    if st == 'PPI':
        # Set theta start to north
        tr_rotate = Affine2D().translate(-90, 0)
        # set theta running clockwise
        tr_scale = Affine2D().scale(-np.pi / 180, 1)
        # create transformation
        tr = tr_rotate + tr_scale + PolarAxes.PolarTransform()

        # build up curvelinear grid
        extreme_finder = ah.ExtremeFinderCycle(20, 20,
                                               lon_cycle=360,
                                               lat_cycle=None,
                                               lon_minmax=(360, 0),
                                               lat_minmax=(0, np.inf),
                                               )

        # locator and formatter for angle annotation
        locs = [i for i in np.arange(0., 359., 10.)]
        grid_locator1 = FixedLocator(locs)
        tick_formatter1 = DictFormatter(dict([(i, r"${0:.0f}^\circ$".format(i))
                                              for i in locs]))

        # grid_helper for curvelinear grid
        grid_helper = GridHelperCurveLinear(tr,
                                            extreme_finder=extreme_finder,
                                            grid_locator1=grid_locator1,
                                            grid_locator2=None,
                                            tick_formatter1=tick_formatter1,
                                            tick_formatter2=None,
                                            )
        # try to set nice locations for range gridlines
        grid_helper.grid_finder.grid_locator2._nbins = 15.0
        grid_helper.grid_finder.grid_locator2._steps = [0, 1, 1.5, 2,
                                                        2.5,
                                                        5,
                                                        10]

    # if there is no figure object given
    if fig is None:
        # create new figure if there is only one subplot
        if subplot is 111:
            fig = pl.figure()
        # otherwise get current figure or create new figure
        else:
            fig = pl.gcf()

    # generate Axis
    cgax = SubplotHost(fig, subplot, grid_helper=grid_helper)

    fig.add_axes(cgax)

    # PPIs always plottetd with equal aspect
    if st == 'PPI':
        cgax.set_aspect('equal', adjustable='box')

    # get twin axis for cartesian grid
    caax = cgax.twin()
    # move axis annotation from right to left and top to bottom for
    # cartesian axis
    caax.toggle_axisline()

    # make right and top axis visible and show ticklabels (curvelinear axis)
    cgax.axis["top", "right"].set_visible(True)
    cgax.axis["top", "right"].major_ticklabels.set_visible(True)

    # make ticklabels of left and bottom axis invisible (curvelinear axis)
    cgax.axis["left", "bottom"].major_ticklabels.set_visible(False)

    # and also set tickmarklength to zero for better presentation
    # (curvelinear axis)
    cgax.axis["top", "right", "left", "bottom"].major_ticks.set_ticksize(0)

    # show theta (angles) on top and right axis
    cgax.axis["top"].get_helper().nth_coord_ticks = 0
    cgax.axis["right"].get_helper().nth_coord_ticks = 0

    # generate and add parasite axes with given transform
    paax = ParasiteAxesAuxTrans(cgax, tr, "equal")
    # note that paax.transData == tr + cgax.transData
    # Anything you draw in paax will match the ticks and grids of cgax.
    cgax.parasites.append(paax)

    return cgax, caax, paax
Example #35
0
def create_cg(fig=None,
              subplot=111,
              rot=-450,
              scale=-1,
              angular_spacing=10,
              radial_spacing=10,
              latmin=0,
              lon_cycle=360):
    """ Helper function to create curvelinear grid

    The function makes use of the Matplotlib AXISARTIST namespace
    `mpl_toolkits.axisartist \
    <https://matplotlib.org/mpl_toolkits/axes_grid/users/axisartist.html>`_.

    Here are some limitations to normal Matplotlib Axes. While using the
    Matplotlib `AxesGrid Toolkit \
    <https://matplotlib.org/mpl_toolkits/axes_grid/index.html>`_
    most of the limitations can be overcome.
    See `Matplotlib AxesGrid Toolkit User’s Guide \
    <https://matplotlib.org/mpl_toolkits/axes_grid/users/index.html>`_.

    Parameters
    ----------
    fig : matplotlib Figure object
        If given, the PPI/RHI will be plotted into this figure object.
        Axes are created as needed. If None a new figure object will
        be created or current figure will be used, depending on "subplot".
    subplot : :class:`matplotlib:matplotlib.gridspec.GridSpec`, \
        matplotlib grid definition
        nrows/ncols/plotnumber, see examples section
        defaults to '111', only one subplot
    rot : float
        Rotation of the source data in degrees, defaults to -450 for PPI,
        use 0 for RHI
    scale : float
        Scale of source data, defaults to -1. for PPI, use 1 for RHI
    angular_spacing : float
        Spacing of the angular grid, defaults to 10.
    radial_spacing : float
        Spacing of the radial grid, defaults to 10.
    latmin : float
        Startvalue for radial grid, defaults to 0.
    lon_cycle : float
        Angular cycle, defaults to 360.

    Returns
    -------
    cgax : matplotlib toolkit axisartist Axes object
        curvelinear Axes (r-theta-grid)
    caax : matplotlib Axes object (twin to cgax)
        Cartesian Axes (x-y-grid) for plotting cartesian data
    paax : matplotlib Axes object (parasite to cgax)
        The parasite axes object for plotting polar data
    """
    # create transformation
    # rotate
    tr_rotate = Affine2D().translate(rot, 0)
    # scale
    tr_scale = Affine2D().scale(scale * np.pi / 180, 1)
    # polar
    tr_polar = PolarAxes.PolarTransform()

    tr = tr_rotate + tr_scale + tr_polar

    # build up curvelinear grid
    extreme_finder = ah.ExtremeFinderCycle(
        360,
        360,
        lon_cycle=lon_cycle,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(latmin, np.inf),
    )
    # locator and formatter for angular annotation
    grid_locator1 = ah.LocatorDMS(lon_cycle // angular_spacing)
    tick_formatter1 = ah.FormatterDMS()

    # grid_helper for curvelinear grid
    grid_helper = GridHelperCurveLinear(
        tr,
        extreme_finder=extreme_finder,
        grid_locator1=grid_locator1,
        grid_locator2=None,
        tick_formatter1=tick_formatter1,
        tick_formatter2=None,
    )

    # try to set nice locations for radial gridlines
    grid_locator2 = grid_helper.grid_finder.grid_locator2
    grid_locator2._nbins = (radial_spacing * 2 + 1) // np.sqrt(2)

    # if there is no figure object given
    if fig is None:
        # create new figure if there is only one subplot
        if subplot == 111:
            fig = pl.figure()
        # otherwise get current figure or create new figure
        else:
            fig = pl.gcf()

    # generate Axis
    cgax = SubplotHost(fig, subplot, grid_helper=grid_helper)
    fig.add_axes(cgax)

    # get twin axis for cartesian grid
    caax = cgax.twin()
    # move axis annotation from right to left and top to bottom for
    # cartesian axis
    caax.toggle_axisline()

    # make right and top axis visible and show ticklabels (curvelinear axis)
    cgax.axis["top", "right"].set_visible(True)
    cgax.axis["top", "right"].major_ticklabels.set_visible(True)

    # make ticklabels of left and bottom axis invisible (curvelinear axis)
    cgax.axis["left", "bottom"].major_ticklabels.set_visible(False)

    # and also set tickmarklength to zero for better presentation
    # (curvelinear axis)
    cgax.axis["top", "right", "left", "bottom"].major_ticks.set_ticksize(0)

    # show theta (angles) on top and right axis
    cgax.axis["top"].get_helper().nth_coord_ticks = 0
    cgax.axis["right"].get_helper().nth_coord_ticks = 0

    # generate and add parasite axes with given transform
    paax = ParasiteAxesAuxTrans(cgax, tr, "equal")
    # note that paax.transData == tr + cgax.transData
    # Anything you draw in paax will match the ticks and grids of cgax.
    cgax.parasites.append(paax)

    return cgax, caax, paax
Example #36
0
    def __init__(self, fig=None, max_normed_std=2.5, std_ratios=[1], \
            bias_vmin=None, bias_vmax=None, \
            normalized=True,
            cmap=plt.cm.jet, s=80, title_expected=r'expected'):
        """
    Set up Taylor diagram axes. 
    """
        self.title_polar = r'Correlation'
        self.title_xy = r'Normalized Standard Deviation'
        self.max_normed_std = max_normed_std
        self.s_min = 0
        self.std_ratios = std_ratios
        self.bias_vmin = bias_vmin
        self.bias_vmax = bias_vmax
        self.normalized = normalized
        self.cmap = cmap
        self.s = s  # marker size
        self.title_expected = title_expected

        # Define polar coordinate
        tr = PolarAxes.PolarTransform()
        extreme_finder = angle_helper.ExtremeFinderCycle(
            20,
            20,
            lon_cycle=360,
            lat_cycle=None,
            lon_minmax=None,
            lat_minmax=(0, np.inf),
        )

        grid_locator1 = angle_helper.LocatorDMS(12)

        tick_formatter1 = angle_helper.FormatterDMS()

        grid_helper = GridHelperCurveLinear(tr,
                                            extreme_finder=extreme_finder,
                                            grid_locator1=grid_locator1,
                                            tick_formatter1=tick_formatter1)

        # figure
        self.fig = fig
        if self.fig is None:
            self.fig = plt.figure()

        # setup axes
        ax = SubplotHost(self.fig, 111, grid_helper=grid_helper)
        self.ax = self.fig.add_subplot(ax)

        # set x and y axis
        self._setup_axes()

        # attach the polar axes and plot the correlation lines
        self.polar_ax = self.ax.get_aux_axes(tr)
        self.polar_ax.plot([np.pi / 2.135, np.pi / 2.135],
                           [self.s_min, self.max_normed_std * 2],
                           color='grey')
        self.polar_ax.plot([np.pi / 2.484, np.pi / 2.484],
                           [self.s_min, self.max_normed_std * 2],
                           color='grey')
        self.polar_ax.plot([np.pi / 3, np.pi / 3],
                           [self.s_min, self.max_normed_std * 2],
                           color='grey')
        self.polar_ax.plot([np.pi / 3.95, np.pi / 3.95],
                           [self.s_min, self.max_normed_std * 2],
                           color='grey')
        self.polar_ax.plot([np.pi / 6.95, np.pi / 6.95],
                           [self.s_min, self.max_normed_std * 2],
                           color='grey')

        # Add norm stddev ratio contours
        self._plot_req_cont(self.std_ratios)

        self.points = []
def curvelinear_test2(fig):
    """
    polar projection, but in a rectangular box.
    """

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # 20, 20 : number of sampling points along x, y direction
    extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
                                                     lon_cycle=360,
                                                     lat_cycle=None,
                                                     lon_minmax=None,
                                                     lat_minmax=(0, np.inf),
                                                     )

    grid_locator1 = angle_helper.LocatorDMS(12)
    # Find a grid values appropriate for the coordinate (degree,
    # minute, second).

    tick_formatter1 = angle_helper.FormatterDMS()
    # And also uses an appropriate formatter.  Note that,the
    # acceptable Locator and Formatter class is a bit different than
    # that of mpl's, and you cannot directly use mpl's Locator and
    # Formatter here (but may be possible in the future).

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1
                                        )

    ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper)

    # make ticklabels of right and top axis visible.
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)

    # let right axis shows ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0
    # let bottom axis shows ticklabels for 2nd coordinate (radius)
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    fig.add_subplot(ax1)

    # A parasite axes with given transform
    ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")
    # note that ax2.transData == tr + ax1.transData
    # Anything you draw in ax2 will match the ticks and grids of ax1.
    ax1.parasites.append(ax2)
    intp = cbook.simple_linear_interpolation
    ax2.plot(intp(np.array([0, 30]), 50),
             intp(np.array([10., 10.]), 50),
             linewidth=2.0)

    ax1.set_aspect(1.)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    ax1.grid(True, zorder=0)
def curvelinear_test(fig):
    """Polar projection, but in a rectangular box.
    """
    # 创建一个极坐标变换。PolarAxes.PolarTransform使用弧度,但本例
    # 要设置的坐标系中角度的单位为度
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    # 极坐标投影涉及到周期,在坐标上也有限制,需要一种特殊的方法来找到
    # 坐标的最小值和最大值
    extreme_finder = angle_helper.ExtremeFinderCycle(
        20,
        20,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(0, np.inf),
    )
    # 找到适合坐标的网格值(度、分、秒)
    grid_locator1 = angle_helper.LocatorDMS(12)

    # 使用适当的Formatter。请注意,可接受的Locator和Formatter类
    # 与Matplotlib中的相应类稍有不同,后者目前还不能直接在这里使用
    tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)

    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    fig.add_subplot(ax1)

    # 创建浮动坐标轴

    # 浮动坐标轴的第一个坐标(theta)指定为60度
    ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 60)
    axis.label.set_text(r"$\theta = 60^{\circ}$")
    axis.label.set_visible(True)

    # 浮动坐标轴的第二个坐标(r)指定为6
    ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 6)
    axis.label.set_text(r"$r = 6$")

    ax1.set_aspect(1.)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    ax1.grid(True)