Returns a DataFrame with the required format for 
	a surface (sine wave) plot

	Parameters:
	-----------
		n : int
			Ranges for X and Y axis (-n,n)
		n_y : int
			Size of increment along the axis
18002
def sinwave(n=4,inc=.25):
		
	x=np.arange(-n,n,inc)
	y=np.arange(-n,n,inc)
	X,Y=np.meshgrid(x,y)
	R = np.sqrt(X**2 + Y**2)
	Z = np.sin(R)/(.5*R)
	return pd.DataFrame(Z,index=x,columns=y)
119501
def surface(n_x=20,n_y=20):
		
	x=[float(np.random.randint(0,100))]
	for i in range(n_x):
		x.append(x[:1][0]+np.random.randn()*np.random.randint(1,10))
	df=pd.DataFrame(x)
	for i in range(n_y):
		df[i+1]=df[i].map(lambda x:x+np.random.randn()*np.random.randint(1,10))
	return df
533536
def sigma_fltr(dem, n=3):
    
    std = dem.std()
    u = dem.mean()
    print('Excluding values outside of range: {1:0.2f} +/- {0}*{2:0.2f}'.format(n, u, std))
    rangelim = (u - n*std, u + n*std)
    out = range_fltr(dem, rangelim)
    return out
292202
def compute_plot_size(plot):
    
    if isinstance(plot, GridBox):
        ndmapping = NdMapping({(x, y): fig for fig, y, x in plot.children}, kdims=['x', 'y'])
        cols = ndmapping.groupby('x')
        rows = ndmapping.groupby('y')
        width = sum([max([compute_plot_size(f)[0] for f in col]) for col in cols])
        height = sum([max([compute_plot_size(f)[1] for f in row]) for row in rows])
        return width, height
    elif isinstance(plot, (Div, ToolbarBox)):
        # Cannot compute size for Div or ToolbarBox
        return 0, 0
    elif isinstance(plot, (Row, Column, WidgetBox, Tabs)):
        if not plot.children: return 0, 0
        if isinstance(plot, Row) or (isinstance(plot, ToolbarBox) and plot.toolbar_location not in ['right', 'left']):
            w_agg, h_agg = (np.sum, np.max)
        elif isinstance(plot, Tabs):
            w_agg, h_agg = (np.max, np.max)
        else:
            w_agg, h_agg = (np.max, np.sum)
        widths, heights = zip(*[compute_plot_size(child) for child in plot.children])
        return w_agg(widths), h_agg(heights)
    elif isinstance(plot, (Figure, Chart)):
        if plot.plot_width:
            width = plot.plot_width
        else:
            width = plot.frame_width + plot.min_border_right + plot.min_border_left
        if plot.plot_height:
            height = plot.plot_height
        else:
            height = plot.frame_height + plot.min_border_bottom + plot.min_border_top
        return width, height
    elif isinstance(plot, (Plot, DataTable, Spacer)):
        return plot.width, plot.height
    else:
        return 0, 0
643215
def nDims(self):
        
        result = self._index.ndim
        assert result == 1, "Expected index to be 1D, got: {}D".format(result)
        return result
1033379
def nn_dims(self, x, y, dims_x, dims_y, k=1, radius=np.inf, eps=0.0, p=2):
        
        assert len(x) == len(dims_x)
        assert len(y) == len(dims_y)
        if len(dims_x) == 0:
            kdtree = scipy.spatial.cKDTree([np.array(data_y)[np.array(dims_y) - self.dim_x] for data_y in self.data[DATA_Y]])
        elif len(dims_y) == 0:
            kdtree = scipy.spatial.cKDTree([np.array(data_x)[dims_x] for data_x in self.data[DATA_X]])
        else:
            kdtree = scipy.spatial.cKDTree([np.hstack((np.array(data_x)[dims_x], np.array(data_y)[np.array(dims_y) - self.dim_x])) for data_x,data_y in zip(self.data[DATA_X], self.data[DATA_Y])])
        dists, idxes =  kdtree.query(np.hstack((x, y)), 
                               k = k, 
                               distance_upper_bound = radius,
                               eps = eps, 
                               p = p)
        if k == 1:
            dists, idxes = np.array([dists]), [idxes]
        return dists, idxes
1289470
def get_data_point(self, n):
        
        # loop over the columns and pop the data
        point = []
        for k in self.ckeys: point.append(self[k][n])
        return point
1011010
def setup_xrange(self, xrange):
        ''''''
        if self.xaxis:
            return
        xrange *= 24 * 60 * 60
        interval = 1
        intervals = [ 1, 2, 5, 10, 15, 30, 60, 120, 240, 300, 600,
                      900, 1800, 3600, 7200, 5*3600, 10*3600, 24*3600 ]
        for interval in intervals:
            if xrange / interval < 12:
                break
        self.locator = matplotlib.dates.SecondLocator(interval=interval)
        self.ax1.xaxis.set_major_locator(self.locator)
456402
def get_xy_simple_dipole_dipole(dataframe, spacing=1, indices=None):
    
    if indices is None:
        indices = slice(None)
    abmn = dataframe.ix[indices, ['a', 'b', 'm', 'n']].values
    posx = np.mean(abmn[:, 0:4], axis=1)
    posz = np.abs(
        np.min(abmn[:, 0:2], axis=1) - np.max(abmn[:, 2:4], axis=1)
    ) * -0.192

    # scale the positions with the electrode spacing
    posx *= spacing
    posz *= spacing
    print(abmn.shape, posx.shape)
    print('posxz', np.vstack((abmn.T, posx, posz)).T)
    return posx, posz
715113
def geometry_range(crd_range, elev, crd_type):
    

    d = OrderedDict()
    coordinates = [[] for i in range(len(crd_range))]

    # latitude
    if crd_type == "lat":
        for idx, i in enumerate(crd_range):
            coordinates[idx] = [crd_range[idx], "nan"]
            if elev:
                coordinates[idx].append(elev)

    # longitude
    elif crd_type == "lon":
        for idx, i in enumerate(crd_range):
            coordinates[idx] = ["nan", crd_range[idx]]
            if elev:
                coordinates[idx].append(elev)

    d["type"] = "Range"
    d["coordinates"] = coordinates

    return d
785903
def get_plot(self, width=8, height=8):
        
        plt = pretty_plot(width, height)
        for label, electrode in self._electrodes.items():
            (x, y) = self.get_plot_data(electrode)
            plt.plot(x, y, '-', linewidth=2, label=label)

        plt.legend()
        if self.xaxis == "capacity":
            plt.xlabel('Capacity (mAh/g)')
        else:
            plt.xlabel('Fraction')
        plt.ylabel('Voltage (V)')
        plt.tight_layout()
        return plt
1290242
def _get_df(self):
        
        grids = {}
        df = pd.DataFrame()
        for bnd in self.bands:
            s,b = self.get_band(bnd, **self.kwargs)
            logging.debug('loading {} band from {}'.format(b,s))
            if s not in grids:
                grids[s] = self.get_hdf(s)
            if self.common_columns[0] not in df:
                df[list(self.common_columns)] = grids[s][list(self.common_columns)]
            col = grids[s][b]
            n_nan = np.isnan(col).sum()
            if n_nan > 0:
                logging.debug('{} NANs in {} column'.format(n_nan, b))
            df.loc[:, bnd] = col.values #dunno why it has to be this way; something
                                        # funny with indexing.

        return df
1110039
def get_axis_grid(self, ind):
        
        ng = self.dim
        num_pts = ng[ind]
        lengths = self.structure.lattice.abc
        return [i / num_pts * lengths[ind] for i in range(num_pts)]
854983
def interpolation_points(self, N):
        
        if N == 1:
            return np.array([0.])
        return np.cos(np.arange(N)*np.pi/(N-1))
763211
def true_range(arg, high_col='high', low_col='low', close_col='close', skipna=0):
    
    _ensure_col(arg, high_col=high_col, low_col=low_col, close_col=close_col)
    yclose = arg[close_col].shift(1)
    low, high = arg[low_col], arg[high_col]
    mx = pd.DataFrame({'a': high, 'b': yclose}).max(axis=1, skipna=skipna)
    mn = pd.DataFrame({'a': low, 'b': yclose}).min(axis=1, skipna=skipna)
    result = mx - mn
    return pd.Series(result, index=arg.index, name='true_range')
310702
def create_scatterplot(df):
    
    fig = Figure("/mg/scatter/", "mg_scatter")
    fig.layout.set_size(width=450, height=200)
    fig.layout.set_margin(left=40, right=40)
    fig.graphics.animate_on_load()

    init_params = {"Data": "Steps"}

    def get_data():
        y = request.args.get("Data", "Steps")
        return jsonify(ScatterPlot.to_json(df, "Steps", y))

    # Make a histogram with 20 bins
    return ScatterPlot(df, fig, "Steps", "Distance",
        init_params={}, route_func=get_data)
344110
def _format_axes(self):
        
        if not self.obj.index.is_unique and self.orient in (
                'index', 'columns'):
            raise ValueError("DataFrame index must be unique for orient="
                             "'{orient}'.".format(orient=self.orient))
        if not self.obj.columns.is_unique and self.orient in (
                'index', 'columns', 'records'):
            raise ValueError("DataFrame columns must be unique for orient="
                             "'{orient}'.".format(orient=self.orient))