Return an appropriate key code for the axes coordinate system by
    examining the FITS header.
969628
def get_coord_system_name(header):
    
    try:
        ctype = header['CTYPE1'].strip().upper()
    except KeyError:
        try:
            # see if we have an "RA" header
            ra = header['RA']  # noqa
            try:
                equinox = float(header['EQUINOX'])
                if equinox < 1984.0:
                    radecsys = 'FK4'
                else:
                    radecsys = 'FK5'
            except KeyError:
                radecsys = 'ICRS'
            return radecsys.lower()

        except KeyError:
            return 'raw'

    match = re.match(r'^GLON\-.*$', ctype)
    if match:
        return 'galactic'

    match = re.match(r'^ELON\-.*$', ctype)
    if match:
        return 'ecliptic'

    match = re.match(r'^RA\-\-\-.*$', ctype)
    if match:
        hdkey = 'RADECSYS'
        try:
            radecsys = header[hdkey]

        except KeyError:
            try:
                hdkey = 'RADESYS'
                radecsys = header[hdkey]
            except KeyError:
                # missing keyword
                # RADESYS defaults to IRCS unless EQUINOX is given
                # alone, in which case it defaults to FK4 prior to 1984
                # and FK5 after 1984.
                try:
                    equinox = float(header['EQUINOX'])
                    if equinox < 1984.0:
                        radecsys = 'FK4'
                    else:
                        radecsys = 'FK5'
                except KeyError:
                    radecsys = 'ICRS'

        radecsys = radecsys.strip()

        return radecsys.lower()

    match = re.match(r'^HPLN\-.*$', ctype)
    if match:
        return 'helioprojective'

    match = re.match(r'^HGLT\-.*$', ctype)
    if match:
        return 'heliographicstonyhurst'

    match = re.match(r'^PIXEL$', ctype)
    if match:
        return 'pixel'

    match = re.match(r'^LINEAR$', ctype)
    if match:
        return 'pixel'

    #raise WCSError("Cannot determine appropriate coordinate system from FITS header")  # noqa
    return 'icrs'
1080837
def cget(self, key):
        
        if key == 'showvalue':
            return self._showvalue
        elif key == 'tickinterval':
            return self._tickinterval
        elif key == 'tickpos':
            return self._tickpos
        elif key == 'labelpos':
            return self._labelpos
        elif key == 'digits':
            return self._digits
        elif key == 'resolution':
            return self._resolution
        else:
            return self.scale.cget(key)
171276
def _h(self, X, tau):

        

        def cos_func(y):
            if isinstance(y, float) or isinstance(y, int):
                if y > 1:
                    return np.arccosh(y)
                else:
                    return np.arccos(y)
            else:
                values = np.ones_like(y)
                inds1 = np.where(y < 1)
                inds2 = np.where(y > 1)
                values[inds1] = np.arccos(y[inds1])
                # values[inds2] = np.arccosh(y[inds2])
                values[inds2] = np.arccos((1 - y[inds2]) ** .5)
                return values

        def nfw_func(x):
            if isinstance(x,float) or isinstance(x,int):
                if x<1:
                    return np.log(x / 2.) ** 2 - np.arccosh(1. / x) ** 2
                else:
                    return np.log(x / 2.)**2 - np.arccos(1. /x)**2
            else:
                inds1 = np.where(x < 1)
                inds2 = np.where(x >= 1)
                y = np.zeros_like(x)
                y[inds1] = np.log(x[inds1] / 2.) ** 2 - np.arccosh(1. / x[inds1]) ** 2
                y[inds2] = np.log(x[inds2] / 2.) ** 2 - np.arccosh(1. / x[inds2]) ** 2

                return y

        def tnfw_func(x,tau):

            u = x**2
            t2 = tau**2
            Lx = self.L(u**.5, tau)

            return (t2 + 1) ** -2 * (
                2 * t2 * np.pi * (tau - (t2 + u) ** .5 + tau * np.log(tau + (t2 + u) ** .5))
                +
                2 * (t2 - 1) * tau * (t2 + u) ** .5 * Lx
                +
                t2 * (t2 - 1) * Lx ** 2
                +
                4 * t2 * (u - 1) * self.F(u**.5)
                +
                t2 * (t2 - 1) * (cos_func(u ** -0.5)) ** 2
                +
                t2 * ((t2 - 1) * np.log(tau) - t2 - 1) * np.log(u)
                -
                t2 * (
                (t2 - 1) * np.log(tau) * np.log(4 * tau) + 2 * np.log(0.5 * tau) - 2 * tau * (tau - np.pi) * np.log(
                    tau * 2)))

        c = 1e-9
        rescale = 1

        if np.any(X-c<1):

            warnings.warn('Truncated NFW potential not yet implemented for x<1. Using the expression for the NFW '
                          'potential in this regime isntead.')
            rescale = tnfw_func(1.00001,tau)*nfw_func(1)**-1

        if isinstance(X,float) or isinstance(X,int):
            if X<1:
                X = min(X,0.001)
                return nfw_func(X)*rescale
            else:
                return tnfw_func(X,tau)
        else:

            X[np.where(X<0.001)] = 0.001

            values = np.zeros_like(X)
            inds1,inds2 = np.where(X<1),np.where(X>=1)
            values[inds1] = nfw_func(X[inds1])*rescale
            values[inds2] = tnfw_func(X[inds2],tau)

            return values
1339874
def inspect_axes(ax):
        """"""
        ret = {'fig': ax.get_figure().number}
        if mpl.__version__ < '2.0':
            ret['axisbg'] = ax.get_axis_bgcolor()
        else:  # axisbg is depreceated
            ret['facecolor'] = ax.get_facecolor()
        proj = getattr(ax, 'projection', None)
        if proj is not None and not isinstance(proj, six.string_types):
            proj = (proj.__class__.__module__, proj.__class__.__name__)
        ret['projection'] = proj
        ret['visible'] = ax.get_visible()
        ret['spines'] = {}
        ret['zorder'] = ax.get_zorder()
        ret['yaxis_inverted'] = ax.yaxis_inverted()
        ret['xaxis_inverted'] = ax.xaxis_inverted()
        for key, val in ax.spines.items():
            ret['spines'][key] = {}
            for prop in ['linestyle', 'edgecolor', 'linewidth',
                         'facecolor', 'visible']:
                ret['spines'][key][prop] = getattr(val, 'get_' + prop)()
        if isinstance(ax, mfig.SubplotBase):
            sp = ax.get_subplotspec().get_topmost_subplotspec()
            ret['grid_spec'] = sp.get_geometry()[:2]
            ret['subplotspec'] = [sp.num1, sp.num2]
            ret['is_subplot'] = True
        else:
            ret['args'] = [ax.get_position(True).bounds]
            ret['is_subplot'] = False
        return ret
1262314
def get_right_axes(self):
        ""
        if len(self.fig.get_axes()) < 2:
            ax = self.axes.twinx()

        return self.fig.get_axes()[1]
773369
def hpx_to_axes(h, npix):
    
    x = h.ebins
    z = np.arange(npix[-1] + 1)

    return x, z
775347
def get_coord_box(centre_x, centre_y, distance):
    """Todo: return coordinates inside a circle, rather than a square"""
    return {
        'top_left': (centre_x - distance, centre_y + distance),
        'top_right': (centre_x + distance, centre_y + distance),
        'bottom_left': (centre_x - distance, centre_y - distance),
        'bottom_right': (centre_x + distance, centre_y - distance),
    }
1058919
def _get_plane_axes_index(self, axis):
        
        axis_name = self._get_axis_name(axis)

        if axis_name == 'major_axis':
            index = 'minor_axis'
            columns = 'items'
        if axis_name == 'minor_axis':
            index = 'major_axis'
            columns = 'items'
        elif axis_name == 'items':
            index = 'major_axis'
            columns = 'minor_axis'

        return index, columns
125841
def getLabel(self, key):
        
        axisItem = self.getPlotItem().axes[key]['item']
        return axisItem.label.toPlainText()
368284
def axis(self):
        """"""
        return getattr(
            self.colorbar.ax, self.axis_locations[self.position] + 'axis')
377343
def set_axis_centres(self, *args):
        
        for axis in self.axes_by_code.values():
            if isinstance(axis, CentredAxis):
                axis.centre = axis.value
7355
def squeeze_axes(shape, axes, skip=None):
    
    if len(shape) != len(axes):
        raise ValueError('dimensions of axes and shape do not match')
    if skip is None:
        skip = 'XY'
    shape, axes = zip(*(i for i in zip(shape, axes)
                        if i[0] > 1 or i[1] in skip))
    return tuple(shape), ''.join(axes)
945218
def match(header):
        '''
        
        '''
        mo = Library.header_re.match(header)
        if mo is None:
            raise ValueError(f'Not a SAS Version 5 or 6 XPORT file')
        return {
            'created': strptime(mo['created']),
            'modified': strptime(mo['modified']),
            'sas_version': float(mo['version']),
            'os_version': mo['os'].decode().strip(),
        }
96564
def _get_coarse_dataset(self, key, info):
        """"""
        angles = self.root.find('.//Tile_Angles')
        if key in ['solar_zenith_angle', 'solar_azimuth_angle']:
            elts = angles.findall(info['xml_tag'] + '/Values_List/VALUES')
            return np.array([[val for val in elt.text.split()] for elt in elts],
                            dtype=np.float)

        elif key in ['satellite_zenith_angle', 'satellite_azimuth_angle']:
            arrays = []
            elts = angles.findall(info['xml_tag'] + '[@bandId="1"]')
            for elt in elts:
                items = elt.findall(info['xml_item'] + '/Values_List/VALUES')
                arrays.append(np.array([[val for val in item.text.split()] for item in items],
                                       dtype=np.float))
            return np.nanmean(np.dstack(arrays), -1)
        else:
            return
868209
def _axis_properties(self, axis, key, plot, dimension=None,
                         ax_mapping={'x': 0, 'y': 1}):
        
        # need to copy dictionary by calling dict() on it
        axis_props = dict(theme_attr_json(self.renderer.theme, 'Axis'))

        if ((axis == 'x' and self.xaxis in ['bottom-bare', 'top-bare', 'bare']) or
            (axis == 'y' and self.yaxis in ['left-bare', 'right-bare', 'bare'])):
            axis_props['axis_label_text_font_size'] = value('0pt')
            axis_props['major_label_text_font_size'] = value('0pt')
            axis_props['major_tick_line_color'] = None
            axis_props['minor_tick_line_color'] = None
        else:
            labelsize = self._fontsize('%slabel' % axis).get('fontsize')
            if labelsize:
                axis_props['axis_label_text_font_size'] = labelsize
            ticksize = self._fontsize('%sticks' % axis, common=False).get('fontsize')
            if ticksize:
                axis_props['major_label_text_font_size'] = value(ticksize)
            rotation = self.xrotation if axis == 'x' else self.yrotation
            if rotation:
                axis_props['major_label_orientation'] = np.radians(rotation)
            ticker = self.xticks if axis == 'x' else self.yticks
            if isinstance(ticker, Ticker):
                axis_props['ticker'] = ticker
            elif isinstance(ticker, int):
                axis_props['ticker'] = BasicTicker(desired_num_ticks=ticker)
            elif isinstance(ticker, (tuple, list)):
                if all(isinstance(t, tuple) for t in ticker):
                    ticks, labels = zip(*ticker)
                    # Ensure floats which are integers are serialized as ints
                    # because in JS the lookup fails otherwise
                    ticks = [int(t) if isinstance(t, float) and t.is_integer() else t
                             for t in ticks]
                    labels = [l if isinstance(l, util.basestring) else str(l)
                              for l in labels]
                    axis_props['ticker'] = FixedTicker(ticks=ticks)
                    axis_props['major_label_overrides'] = dict(zip(ticks, labels))
                else:
                    axis_props['ticker'] = FixedTicker(ticks=ticker)

        formatter = self.xformatter if axis == 'x' else self.yformatter
        if formatter:
            if isinstance(formatter, TickFormatter):
                pass
            elif isinstance(formatter, FunctionType):
                msg = ('%sformatter could not be '
                       'converted to tick formatter. ' % axis)
                jsfunc = py2js_tickformatter(formatter, msg)
                if jsfunc:
                    formatter = FuncTickFormatter(code=jsfunc)
                else:
                    formatter = None
            else:
                formatter = PrintfTickFormatter(format=formatter)
            if formatter is not None:
                axis_props['formatter'] = formatter
        elif FuncTickFormatter is not None and ax_mapping and isinstance(dimension, Dimension):
            formatter = None
            if dimension.value_format:
                formatter = dimension.value_format
            elif dimension.type in dimension.type_formatters:
                formatter = dimension.type_formatters[dimension.type]
            if formatter:
                msg = ('%s dimension formatter could not be '
                       'converted to tick formatter. ' % dimension.name)
                jsfunc = py2js_tickformatter(formatter, msg)
                if jsfunc:
                    formatter = FuncTickFormatter(code=jsfunc)
                    axis_props['formatter'] = formatter

        if axis == 'x':
            axis_obj = plot.xaxis[0]
        elif axis == 'y':
            axis_obj = plot.yaxis[0]

        if self.geographic and self.projection == 'mercator':
            dimension = 'lon' if axis == 'x' else 'lat'
            axis_props['ticker'] = MercatorTicker(dimension=dimension)
            axis_props['formatter'] = MercatorTickFormatter(dimension=dimension)
            box_zoom = self.state.select(type=tools.BoxZoomTool)
            if box_zoom:
                box_zoom[0].match_aspect = True
        elif isinstance(axis_obj, CategoricalAxis):
            for key in list(axis_props):
                if key.startswith('major_label'):
                    # set the group labels equal to major (actually minor)
                    new_key = key.replace('major_label', 'group')
                    axis_props[new_key] = axis_props[key]

            # major ticks are actually minor ticks in a categorical
            # so if user inputs minor ticks sizes, then use that;
            # else keep major (group) == minor (subgroup)
            msize = self._fontsize('minor_{0}ticks'.format(axis),
                common=False).get('fontsize')
            if msize is not None:
                axis_props['major_label_text_font_size'] = msize

        return axis_props
680181
def get_coordinate_systems(
        self, token: dict = None, srs_code: str = None, prot: str = "https"
    ) -> dict:
        
        # if specific format
        if isinstance(srs_code, str):
            specific_srs = "/{}".format(srs_code)
        else:
            specific_srs = ""

        # search request
        req_url = "{}://v1.{}.isogeo.com/coordinate-systems{}".format(
            prot, self.api_url, specific_srs
        )

        req = self.get(
            req_url, headers=self.header, proxies=self.proxies, verify=self.ssl
        )

        # checking response
        checker.check_api_response(req)

        # end of method
        return req.json()
150881
def _get_list_axis(self, key, axis=None):
        
        if axis is None:
            axis = self.axis or 0
        try:
            return self.obj._take(key, axis=axis)
        except IndexError:
            # re-raise with different error message
            raise IndexError("positional indexers are out-of-bounds")