Get a mean line chart
167716
def _altair_hline_(self, xfield, yfield, opts, style, encode):
        
        try:
            rawy = yfield
            if ":" in yfield:
                rawy = yfield.split(":")[0]
            mean = self.df[rawy].mean()
            l = []
            i = 0
            while i < len(self.df[rawy]):
                l.append(mean)
                i += 1
            self.df["Mean"] = l
            chart = Chart(self.df).mark_line(**style).encode(x=xfield, \
                                            y="Mean", **encode).properties(**opts)
            self.drop("Mean")
            return chart
        except Exception as e:
            self.err(e, "Can not draw mean line chart")
476169
def eval_mean(self, func, args=()):
        """"""
        self.fmean = func(self.mean, *args)
        return self.fmean
547005
function drawTrendline(linearData) {
            if (trendLinePath) {
                trendLinePath.remove();
            }

            const params = [
                {x: linearData.x1, y: linearData.y1},
                {x: linearData.x2, y: linearData.y2}
            ];

            let line = d3Shape.line()
              .curve(trendLineCurve)
              .x(({x}) => xScale(x))
              .y(({y}) => yScale(y));

            trendLinePath = svg.selectAll('.chart-group')
              .append('path')
                .attr('class', 'scatter-trendline')
                .attr('d', line(params))
                .attr('stroke', colorSchema[0])
                .attr('stroke-width', trendLineStrokWidth)
                .attr('fill', 'none');

            const totalLength = trendLinePath.node().getTotalLength();

            trendLinePath
              .attr('stroke-dasharray', `${totalLength} ${totalLength}`)
              .attr('stroke-dashoffset', totalLength)
              .transition()
                .delay(trendLineDelay)
                .duration(trendLineDuration)
                .ease(ease)
                .attr('stroke-dashoffset', 0);
        }
762433
def stdev(x):
    
    """
    from math import sqrt
    n = len(x)
    mean = sum(x) / float(n)
    std = sqrt(sum((a - mean)**2 for a in x) / float(n - 1))
    return std
725568
def get_b_star(x_star, y_err, y_mean, y_segment):
    
    #print "x_star, should be same as Xcorr / NRM"
    #print x_star
    x_star_mean = numpy.mean(x_star)
    x_err = x_star - x_star_mean
    b_star = -1* numpy.sqrt( old_div(sum(numpy.array(y_err)**2), sum(numpy.array(x_err)**2)) )  # averaged slope
    #print "y_segment", y_segment
    b_star = numpy.sign(sum(x_err * y_err)) * numpy.std(y_segment, ddof=1) / numpy.std(x_star, ddof=1)
    #print "b_star (should be same as corr_slope)"
    #print b_star
    return b_star
215923
def mean(self):
    """"""
    if len(self) == 0:
      return float('NaN')
    arr = self.samples()
    return sum(arr) / float(len(arr))
372682
def _get_mean(self, sites, rup, dists, imt, stddev_types):
        
        # Zhao et al. 2006 - Vs30 + Rrup
        mean_zh06, stds1 = super().get_mean_and_stddevs(sites, rup, dists, imt,
                                                        stddev_types)
        #
        # Atkinson and Macias (2009) - Rrup
        gmpe = AtkinsonMacias2009()
        mean_am09, stds2 = gmpe.get_mean_and_stddevs(sites, rup, dists, imt,
                                                     stddev_types)
        #
        # Abrahamson et al. (2015) - Rrup + vs30 + backarc
        gmpe = AbrahamsonEtAl2015SInter()
        mean_ab15, stds3 = gmpe.get_mean_and_stddevs(sites, rup, dists, imt,
                                                     stddev_types)
        #
        # Ghofrani and Atkinson (2014) - Rrup + vs30
        gmpe = GhofraniAtkinson2014()
        mean_ga14, stds4 = gmpe.get_mean_and_stddevs(sites, rup, dists, imt,
                                                     stddev_types)
        # Computing adjusted mean and stds
        cff = self.SITE_COEFFS[imt]
        mean_adj = (np.log(np.exp(mean_zh06)*cff['mf'])*0.1 +
                    mean_am09*0.5 + mean_ab15*0.2 +
                    np.log(np.exp(mean_ga14)*cff['mf'])*0.2)
        return mean_adj
178958
def vector_mean(data):
    
    Xbar = np.zeros((3))
    X = dir2cart(data).transpose()
    for i in range(3):
        Xbar[i] = X[i].sum()
    R = np.sqrt(Xbar[0]**2+Xbar[1]**2+Xbar[2]**2)
    Xbar = Xbar/R
    dir = cart2dir(Xbar)
    return dir, R
170369
def create_line_plot(df):
    
    fig = Figure("/mg/line_plot/", "mg_line_plot")
    fig.graphics.transition_on_update(True)
    fig.graphics.animate_on_load()
    fig.layout.set_size(width=450, height=200)
    fig.layout.set_margin(left=40, right=40)
    return LineChart(df, fig, "Date", ["value"],
        init_params={"Data": "Steps"}, timeseries=True)
1000503
def plot_normal(x=None, mean_x=None,std_x=None,color='red',linewidth=2,alpha=1,bins=20,xlim=False,plot_mean=True,plot_std=False,plot_2std=True,figure=None,annotate=True,histogram=True):
    
    import pylab
    if figure is None:
        figure=pylab.figure()
    if mean_x is None:
        #fit maximum likelihood Normal distribution mean to samples X
        mean_x = x.mean() #sample mean
    if std_x is None:
        #fit maximum likelihood Normal distribution standard deviation to samples X
        std_x = x.std()   #sample standard deviation

    xvals=np.arange(mean_x-5*std_x,mean_x+5*std_x,.001)
    yvals=st.norm.pdf(xvals,mean_x,std_x)
    #plot normal distribution:
    ax = pylab.plot(xvals,yvals,color=color,linewidth=linewidth,alpha=alpha)
    if x is not None and histogram:
        #plot histogram of x-values
        pylab.hist(x,bins,normed=True)

    if plot_mean:
        #evaluate distribution at the mean:
        max_cdf=st.norm.pdf(mean_x,mean_x,std_x)
        pylab.plot([mean_x,mean_x],[0,max_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        if annotate:
            pylab.annotate('$\mu$', xy=(mean_x+0.6*std_x, 1.0*max_cdf),
                horizontalalignment='center', verticalalignment='center',fontsize=15,color=color)
    if plot_std:#plot mean +- 1*standard deviation (64% interval)
        std_cdf=st.norm.pdf(mean_x+std_x,mean_x,std_x)
        pylab.plot([mean_x+std_x,mean_x+std_x],[0,std_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        pylab.plot([mean_x-std_x,mean_x-std_x],[0,std_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        if annotate:
            pylab.annotate('$\mu+\sigma$', xy=(mean_x+1.6*std_x, 1.5*std_cdf),
                horizontalalignment='center', verticalalignment='center',fontsize=15,color=color)
    if plot_2std:#plot mean +- 2*standard deviations (95% interval)
        std2_cdf=st.norm.pdf(mean_x+2*std_x,mean_x,std_x)
        pylab.plot([mean_x+2*std_x,mean_x+2*std_x],[0,std2_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        pylab.plot([mean_x-2*std_x,mean_x-2*std_x],[0,std2_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        if annotate:
            pylab.annotate('$\mu+2\sigma$', xy=(mean_x+2.6*std_x, 1.5*std2_cdf),
                horizontalalignment='center', verticalalignment='center',fontsize=15,color=color)
    if xlim: #cut of unused space on y-axis
        pylab.xlim([mean_x-4*std_x,mean_x+4*std_x])
    return figure
852556
def mean(self, axis=0, *args, **kwargs):
        
        nv.validate_mean(args, kwargs)
        valid_vals = self._valid_sp_values
        sp_sum = valid_vals.sum()
        ct = len(valid_vals)

        if self._null_fill_value:
            return sp_sum / ct
        else:
            nsparse = self.sp_index.ngaps
            return (sp_sum + self.fill_value * nsparse) / (ct + nsparse)
531069
def mean(data):
    
    if iter(data) is data:
        data = list(data)
    n = len(data)
    if n < 1:
        raise StatisticsError('mean requires at least one data point')
    return sum(data) / n
378070
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        
        C = self.COEFFS[imt]
        # Get the mean
        mean = self.get_mean(C, rup, sites, dists)
        if imt.name == "PGV":
            # Convert from log10 m/s to ln cm/s
            mean = np.log((10.0 ** mean) * 100.)
        else:
            # convert from log10 m/s/s to ln g
            mean = np.log((10.0 ** mean) / g)

        # Get the standard deviations
        stddevs = self.get_stddevs(C, mean.shape, stddev_types)
        return mean, stddevs
1340800
def show_plot(t_array, th_array):
    
    th_mean = gv.mean(th_array)
    th_sdev = gv.sdev(th_array)
    thp = th_mean + th_sdev
    thm = th_mean - th_sdev
    plt.fill_between(t_array, thp, thm, color='0.8')
    plt.plot(t_array, th_mean, linewidth=0.5)
    plt.xlabel('$t$')
    plt.ylabel(r'$\theta(t)$')
    plt.savefig('pendulum.pdf', bbox_inches='tight')
    plt.show()
26367
def _get_chart_info(df, vtype, cat, prep, callers):
    
    maxval_raw = max(list(df["value.floor"]))
    curdf = df[(df["variant.type"] == vtype) & (df["category"] == cat)
               & (df["bamprep"] == prep)]
    vals = []
    labels = []
    for c in callers:
        row = curdf[df["caller"] == c]
        if len(row) > 0:
            vals.append(list(row["value.floor"])[0])
            labels.append(list(row["value"])[0])
        else:
            vals.append(1)
            labels.append("")
    return vals, labels, maxval_raw
256818
def _get_mean(self, sites, C, ln_y_ref, exp1, exp2):
        
        # we do not support estimating of basin depth and instead
        # rely on it being available (since we require it).
        # centered_z1pt0
        centered_z1pt0 = self._get_centered_z1pt0(sites)
        # we consider random variables being zero since we want
        # to find the exact mean value.
        eta = epsilon = 0.

        ln_y = (
            # first line of eq. 12
            ln_y_ref + eta
            # second line
            + C['phi1'] * np.log(sites.vs30 / 1130).clip(-np.inf, 0)
            # third line
            + C['phi2'] * (exp1 - exp2)
            * np.log((np.exp(ln_y_ref) * np.exp(eta) + C['phi4']) / C['phi4'])
            # fourth line
            + C['phi5']
            * (1.0 - np.exp(-1. * centered_z1pt0 / C['phi6']))
            # fifth line
            + epsilon
        )

        return ln_y
551997
def mean_field(self):
        """"""
        mean_field = []
        for sp_oper in [self.oper['O'], self.oper['O_d']]:
            avgO = np.array([self.expected(op) for op in sp_oper])
            avgO[abs(avgO) < 1e-10] = 0.
            mean_field.append(avgO*self.param['ekin'])

        return np.array(mean_field)