Find the path for plot bands along the radial axis
334605
function (from, to, options) {
		var center = this.center,
			startAngleRad = this.startAngleRad,
			fullRadius = center[2] / 2,
			radii = [
				pick(options.outerRadius, '100%'),
				options.innerRadius,
				pick(options.thickness, 10)
			],
			percentRegex = /%$/,
			start,
			end,
			open,
			isCircular = this.isCircular, // X axis in a polar chart
			ret;
			
		// Polygonal plot bands
		if (this.options.gridLineInterpolation === 'polygon') {
			ret = this.getPlotLinePath(from).concat(this.getPlotLinePath(to, true));
		
		// Circular grid bands
		} else {

			// Keep within bounds
			from = Math.max(from, this.min);
			to = Math.min(to, this.max);
			
			// Plot bands on Y axis (radial axis) - inner and outer radius depend on to and from
			if (!isCircular) {
				radii[0] = this.translate(from);
				radii[1] = this.translate(to);
			}
			
			// Convert percentages to pixel values
			radii = map(radii, function (radius) {
				if (percentRegex.test(radius)) {
					radius = (pInt(radius, 10) * fullRadius) / 100;
				}
				return radius;
			});
			
			// Handle full circle
			if (options.shape === 'circle' || !isCircular) {
				start = -Math.PI / 2;
				end = Math.PI * 1.5;
				open = true;
			} else {
				start = startAngleRad + this.translate(from);
				end = startAngleRad + this.translate(to);
			}
		
		
			ret = this.chart.renderer.symbols.arc(
				this.left + center[0],
				this.top + center[1],
				radii[0],
				radii[0],
				{
					start: Math.min(start, end), // Math is for reversed yAxis (#3606)
					end: Math.max(start, end),
					innerR: pick(radii[1], radii[0] - radii[2]),
					open: open
				}
			);
		}

		return ret;
	}
459986
def _fit_position_tsmap(self, name, **kwargs):
        """"""

        prefix = kwargs.get('prefix', '')
        dtheta_max = kwargs.get('dtheta_max', 0.5)
        zmin = kwargs.get('zmin', -3.0)

        kw = {
            'map_size': 2.0 * dtheta_max,
            'write_fits':  kwargs.get('write_fits', False),
            'write_npy':  kwargs.get('write_npy', False),
            'use_pylike': kwargs.get('use_pylike', True),
            'max_kernel_radius': self.config['tsmap']['max_kernel_radius'],
            'loglevel': logging.DEBUG
        }

        src = self.roi.copy_source(name)

        if src['SpatialModel'] in ['RadialDisk', 'RadialGaussian']:
            kw['max_kernel_radius'] = max(kw['max_kernel_radius'],
                                          2.0 * src['SpatialWidth'])

        skydir = kwargs.get('skydir', src.skydir)
        tsmap = self.tsmap(utils.join_strings([prefix, name.lower().
                                               replace(' ', '_')]),
                           model=src.data,
                           map_skydir=skydir,
                           exclude=[name],
                           make_plots=False, **kw)

        # Find peaks with TS > 4
        peaks = find_peaks(tsmap['ts'], 4.0, 0.2)
        peak_best = None
        o = {}
        for p in sorted(peaks, key=lambda t: t['amp'], reverse=True):
            xy = p['ix'], p['iy']
            ts_value = tsmap['ts'].data[xy[1], xy[0]]
            posfit = fit_error_ellipse(tsmap['ts'], xy=xy, dpix=2,
                                       zmin=max(zmin, -ts_value * 0.5))
            offset = posfit['skydir'].separation(self.roi[name].skydir).deg
            if posfit['fit_success'] and posfit['fit_inbounds']:
                peak_best = p
                break

        if peak_best is None:
            ts_value = np.max(tsmap['ts'].data)
            posfit = fit_error_ellipse(tsmap['ts'], dpix=2,
                                       zmin=max(zmin, -ts_value * 0.5))

        o.update(posfit)
        pix = posfit['skydir'].to_pixel(self.geom.wcs)
        o['xpix'] = float(pix[0])
        o['ypix'] = float(pix[1])
        o['skydir'] = posfit['skydir'].transform_to('icrs')
        o['pos_offset'] = posfit['skydir'].separation(
            self.roi[name].skydir).deg
        o['loglike'] = 0.5 * posfit['zoffset']
        o['tsmap'] = tsmap['ts']

        return o
1310259
def points_in_each_seg(path, tvals):
    """"""
    A = np.array([[-1,  3, -3,  1], # transforms cubic bez to standard poly
                  [ 3, -6,  3,  0],
                  [-3,  3,  0,  0],
                  [ 1,  0,  0,  0]])
    B = [seg.bpoints() for seg in path]
    return np.dot(B, np.dot(A, np.power(tvals, [[3],[2],[1],[0]])))
666667
def get_band_structure(self):
        """"""

        kpath = HighSymmKpath(self.data.structure)
        kpt_line = [Kpoint(k, self.data.structure.lattice) for k
                    in
                    kpath.get_kpoints(coords_are_cartesian=False)[
                        0]]
        kpoints = np.array(
            [kp.frac_coords for kp in kpt_line])

        labels_dict = {l: k for k, l in zip(
            *kpath.get_kpoints(coords_are_cartesian=False)) if l}

        lattvec = self.data.get_lattvec()
        egrid, vgrid = fite.getBands(kpoints, self.equivalences, lattvec, self.coeffs)

        bands_dict = {Spin.up: (egrid / units.eV)}

        sbs = BandStructureSymmLine(kpoints, bands_dict,
                                    self.data.structure.lattice.reciprocal_lattice,
                                    self.efermi / units.eV,
                                    labels_dict=labels_dict)
        return sbs
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
502904
def ggplot2_style(ax):
    
    #set the style of the major and minor grid lines, filled blocks
    ax.grid(True, 'major', color='w', linestyle='-', linewidth=1.4)
    ax.grid(True, 'minor', color='0.92', linestyle='-', linewidth=0.7)
    ax.patch.set_facecolor('0.85')
    ax.set_axisbelow(True)

    #set minor tick spacing to 1/2 of the major ticks
    ax.xaxis.set_minor_locator(MultipleLocator( (plt.xticks()[0][1]-plt.xticks()[0][0]) / 2.0 ))
    ax.yaxis.set_minor_locator(MultipleLocator( (plt.yticks()[0][1]-plt.yticks()[0][0]) / 2.0 ))

    #remove axis border
    for child in ax.get_children():
        if isinstance(child, mpl.spines.Spine):
            child.set_alpha(0)

    #restyle the tick lines
    for line in ax.get_xticklines() + ax.get_yticklines():
        line.set_markersize(5)
        line.set_color("gray")
        line.set_markeredgewidth(1.4)

    #remove the minor tick lines
    for line in ax.xaxis.get_ticklines(minor=True) + ax.yaxis.get_ticklines(minor=True):
        line.set_markersize(0)

    #only show bottom left ticks, pointing out of axis
    mpl.rcParams['xtick.direction'] = 'out'
    mpl.rcParams['ytick.direction'] = 'out'
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')


    if ax.legend_ <> None:
        lg = ax.legend_
        lg.get_frame().set_linewidth(0)
        lg.get_frame().set_alpha(0.5)
110921
def calc_slopes_directions(self, plotflag=False):
        
        
        # TODO minimum filter behavior with nans?
        
        # fill/interpolate flats first
        if self.fill_flats:
            data = np.ma.filled(self.data.astype('float64'), np.nan)
            filled = data.copy()
            
            edge = np.ones_like(data, bool)
            edge[1:-1, 1:-1] = False

            if self.fill_flats_below_sea: sea_mask = data != 0
            else: sea_mask = data > 0
            flat = (spndi.minimum_filter(data, (3, 3)) >= data) & sea_mask

            flats, n = spndi.label(flat, structure=FLATS_KERNEL3)
            objs = spndi.find_objects(flats)

            for i, _obj in enumerate(objs):
                obj = grow_obj(_obj, data.shape)
                self._fill_flat(data[obj], filled[obj], flats[obj]==i+1, edge[obj])

            self.data = np.ma.masked_array(filled, mask=np.isnan(filled)).astype(self.data.dtype)

        # %% Calculate the slopes and directions based on the 8 sections from
        # Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf
        if self.data.shape[0] <= self.chunk_size_slp_dir and \
                self.data.shape[1] <= self.chunk_size_slp_dir:
            print "starting slope/direction calculation"
            self.mag, self.direction = self._slopes_directions(
                self.data, self.dX, self.dY, 'tarboton')
            # Find the flat regions. This is mostly simple (look for mag < 0),
            # but the downstream pixel at the edge of a flat will have a
            # calcuable angle which will not be accurate. We have to also find
            # these edges and set their magnitude to -1 (that is, the flat_id)

            self.find_flats()
        else:
            self.direction = np.full(self.data.shape, FLAT_ID_INT, 'float64')
            self.mag = np.full(self.data.shape, FLAT_ID_INT, 'float64')
            self.flats = np.zeros(self.data.shape, bool)
            top_edge, bottom_edge = \
                self._get_chunk_edges(self.data.shape[0],
                                      self.chunk_size_slp_dir,
                                      self.chunk_overlap_slp_dir)
            left_edge, right_edge = \
                self._get_chunk_edges(self.data.shape[1],
                                      self.chunk_size_slp_dir,
                                      self.chunk_overlap_slp_dir)
            ovr = self.chunk_overlap_slp_dir
            count = 1
            for te, be in zip(top_edge, bottom_edge):
                for le, re in zip(left_edge, right_edge):
                    print "starting slope/direction calculation for chunk", \
                        count, "[%d:%d, %d:%d]" % (te, be, le, re)
                    count += 1
                    mag, direction = \
                        self._slopes_directions(self.data[te:be, le:re],
                                                self.dX[te:be-1],
                                                self.dY[te:be-1])

                    flats = self._find_flats_edges(self.data[te:be, le:re],
                                                   mag, direction)

                    direction[flats] = FLAT_ID_INT
                    mag[flats] = FLAT_ID_INT
                    self._assign_chunk(self.data, self.mag, mag,
                                       te, be, le, re, ovr)
                    self._assign_chunk(self.data, self.direction, direction,
                                       te, be, le, re, ovr)
                    self._assign_chunk(self.data, self.flats, flats,
                                       te, be, le, re, ovr)

        if plotflag:
            self._plot_debug_slopes_directions()

        gc.collect()  # Just in case
        return self.mag, self.direction
854645
def axes(self):
        """"""
        return tuple(i for i in range(self.domain.ndim)
                     if self.domain.shape[i] != self.range.shape[i])
859592
def dot(self, rhs):
    

    return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
681690
def select_paths(cls, dataset, selection):
        
        return [s[0] for s in np.array([{0: p} for p in dataset.data])[selection]]
463650
def finder(self, figsize=(7,7), **kwargs):
        '''
        
        '''

        try:
            center = self.meta['center']
            radius = self.meta['radius']
        except KeyError:
            return self.allskyfinder(**kwargs)

        plt.figure(figsize=figsize)
        scatter = self.plot(**kwargs)
        plt.xlabel(r'Right Ascension ($^\circ$)'); plt.ylabel(r'Declination ($^\circ$)')
        #plt.title('{} in {:.1f}'.format(self.name, epoch))
        r = radius.to('deg').value
        plt.xlim(center.ra.deg + r/np.cos(center.dec), center.ra.deg - r/np.cos(center.dec))
        plt.ylim(center.dec.deg - r, center.dec.deg + r)
        ax = plt.gca()
        ax.set_aspect(1.0/np.cos(center.dec))

        return scatter
291649
def radialrange(self, origin, return_all_global_extrema=False):
        """"""
        if return_all_global_extrema:
            raise NotImplementedError
        else:
            global_min = (np.inf, None, None)
            global_max = (0, None, None)
            for seg_idx, seg in enumerate(self):
                seg_global_min, seg_global_max = seg.radialrange(origin)
                if seg_global_min[0] < global_min[0]:
                    global_min = seg_global_min + (seg_idx,)
                if seg_global_max[0] > global_max[0]:
                    global_max = seg_global_max + (seg_idx,)
            return global_min, global_max
1135809
function getSplinePath(points, isInCircle, constaint) {
    var data = [];
    var first = points[0];
    var prePoint = null;
    if (points.length <= 2) {
      return PathUtil.getLinePath(points, isInCircle);
    }
    Util.each(points, function (point) {
      if (!prePoint || !(prePoint.x === point.x && prePoint.y === point.y)) {
        data.push(point.x);
        data.push(point.y);
        prePoint = point;
      }
    });
    constaint = constaint || [// 范围
    [0, 0], [1, 1]];
    var splinePath = Spline.catmullRom2bezier(data, isInCircle, constaint);
    splinePath.unshift(['M', first.x, first.y]);
    return splinePath;
  }
501697
private Path[] getPaths(final Series<X, Y> SERIES) {
            if (!getData().contains(SERIES)) { return null; }

            Node seriesNode = SERIES.getNode();
            if (null == seriesNode) { return null; }

            Group seriesGroup = (Group) seriesNode;
            if (seriesGroup.getChildren().isEmpty() || seriesGroup.getChildren().size() < 2) { return null; }

        return new Path[] { /* FillPath   */ (Path) (seriesGroup).getChildren().get(0),
                            /* StrokePath */ (Path) (seriesGroup).getChildren().get(1) };
    }
910977
def plot_groups_unplaced(self, fout_dir=".", **kws_pltargs):
        """"""
        hdrgos = self.grprobj.get_hdrgos_unplaced()
        pltargs = PltGroupedGosArgs(self.grprobj, fout_dir=fout_dir, **kws_pltargs)
        return self._plot_groups_hdrgos(hdrgos, pltargs)
715563
function pathToLines(path) {
    var lines = [];
    var curr = null;

    path.forEach(function(cmd) {
        if(cmd[0] == PATH_COMMAND.MOVE) {
            curr = cmd[1];
        }
        if(cmd[0] == PATH_COMMAND.LINE) {
            var pt = cmd[1];
            lines.push(new Line(curr, pt));
            curr = pt;
        }
        if(cmd[0] == PATH_COMMAND.QUADRATIC_CURVE) {
            var pts = [curr, cmd[1], cmd[2]];
            for(var t=0; t<1; t+=0.1) {
                var pt = calcQuadraticAtT(pts,t);
                lines.push(new Line(curr, pt));
                curr = pt;
            }
        }
        if(cmd[0] === PATH_COMMAND.BEZIER_CURVE) {
            var pts = [curr, cmd[1], cmd[2], cmd[3]];
            bezierToLines(pts,10).forEach(pt => {
                lines.push(new Line(curr,pt))
                curr = pt
            })
        }
    });
    return lines;
}
1241640
def _x_axis(self):
        """"""
        if not self._x_labels or not self.show_x_labels:
            return
        axis = self.svg.node(
            self.nodes['plot'],
            class_="axis x%s" % (' always_show' if self.show_x_guides else '')
        )
        truncation = self.truncate_label
        if not truncation:
            if self.x_label_rotation or len(self._x_labels) <= 1:
                truncation = 25
            else:
                first_label_position = self.view.x(self._x_labels[0][1]) or 0
                last_label_position = self.view.x(self._x_labels[-1][1]) or 0
                available_space = (last_label_position - first_label_position
                                   ) / len(self._x_labels) - 1

                truncation = reverse_text_len(
                    available_space, self.style.label_font_size
                )
                truncation = max(truncation, 1)

        lastlabel = self._x_labels[-1][0]
        if 0 not in [label[1] for label in self._x_labels]:
            self.svg.node(
                axis,
                'path',
                d='M%f %f v%f' % (0, 0, self.view.height),
                class_='line'
            )
            lastlabel = None

        for label, position in self._x_labels:
            if self.horizontal:
                major = position in self._x_labels_major
            else:
                major = label in self._x_labels_major
            if not (self.show_minor_x_labels or major):
                continue
            guides = self.svg.node(axis, class_='guides')
            x = self.view.x(position)
            if x is None:
                continue
            y = self.view.height + 5
            last_guide = (self._y_2nd_labels and label == lastlabel)
            self.svg.node(
                guides,
                'path',
                d='M%f %f v%f' % (x or 0, 0, self.view.height),
                class_='%s%s%sline' % (
                    'axis ' if label == "0" else '', 'major '
                    if major else '', 'guide '
                    if position != 0 and not last_guide else ''
                )
            )
            y += .5 * self.style.label_font_size + 5
            text = self.svg.node(
                guides, 'text', x=x, y=y, class_='major' if major else ''
            )

            text.text = truncate(label, truncation)
            if text.text != label:
                self.svg.node(guides, 'title').text = label
            elif self._dual:
                self.svg.node(
                    guides,
                    'title',
                ).text = self._x_format(position)

            if self.x_label_rotation:
                text.attrib['transform'] = "rotate(%d %f %f)" % (
                    self.x_label_rotation, x, y
                )
                if self.x_label_rotation >= 180:
                    text.attrib['class'] = ' '.join((
                        text.attrib['class']
                        and text.attrib['class'].split(' ') or []
                    ) + ['backwards'])

        if self._y_2nd_labels and 0 not in [label[1]
                                            for label in self._x_labels]:
            self.svg.node(
                axis,
                'path',
                d='M%f %f v%f' % (self.view.width, 0, self.view.height),
                class_='line'
            )

        if self._x_2nd_labels:
            secondary_ax = self.svg.node(
                self.nodes['plot'],
                class_="axis x x2%s" %
                (' always_show' if self.show_x_guides else '')
            )
            for label, position in self._x_2nd_labels:
                major = label in self._x_labels_major
                if not (self.show_minor_x_labels or major):
                    continue
                # it is needed, to have the same structure as primary axis
                guides = self.svg.node(secondary_ax, class_='guides')
                x = self.view.x(position)
                y = -5
                text = self.svg.node(
                    guides, 'text', x=x, y=y, class_='major' if major else ''
                )
                text.text = label
                if self.x_label_rotation:
                    text.attrib['transform'] = "rotate(%d %f %f)" % (
                        -self.x_label_rotation, x, y
                    )
                    if self.x_label_rotation >= 180:
                        text.attrib['class'] = ' '.join((
                            text.attrib['class']
                            and text.attrib['class'].split(' ') or []
                        ) + ['backwards'])