Plots the tropical solar length
    by year.
482503
def plot(hdiff, title):
    
    import matplotlib.pyplot as plt
    years = [elem[0] for elem in hdiff]
    diffs = [elem[1] for elem in hdiff]
    plt.plot(years, diffs)
    plt.ylabel('Distance in minutes')
    plt.xlabel('Year')
    plt.title(title)
    plt.axhline(y=0, c='red')
    plt.show()
1104019
def plot(x, y, z, color=default_color, **kwargs):
    
    fig = gcf()
    _grow_limits(x, y, z)
    defaults = dict(
        visible_lines=True, color_selected=None, size_selected=1, size=1, connected=True, visible_markers=False
    )
    kwargs = dict(defaults, **kwargs)
    s = ipv.Scatter(x=x, y=y, z=z, color=color, **kwargs)
    s.material.visible = False
    fig.scatters = fig.scatters + [s]
    return s
462653
def inband_solarirradiance(self, rsr, scale=1.0, **options):
        """"""

        return self._band_calculations(rsr, False, scale, **options)
170276
def plot(self, phi, r, **kwargs):
        
        if self.use_radians:
            phi = np.degrees(phi)
        super(PolarPlot, self).plot(phi, r, **kwargs)
642032
def earth_sun_d(dtime):
        
        doy = int(dtime.strftime('%j'))
        rad_term = 0.9856 * (doy - 4) * pi / 180
        distance_au = 1 - 0.01672 * cos(rad_term)
        return distance_au
1266916
def plot(self, **kwds):
        """
        plo = self.lx.plot(dist_to_center=3, **kwds)
        plo += self.ly.plot(dist_to_center=3, **kwds)
        plo += self.lz.plot(dist_to_center=3, **kwds)
        plo += self.lx_r.plot(dist_to_center=3, **kwds)
        plo += self.ly_r.plot(dist_to_center=3, **kwds)
        plo += self.lz_r.plot(dist_to_center=3, **kwds)
        return plo
677902
def _calculate_solar_time(self, hour, eq_of_time, is_solar_time):
        """"""
        if is_solar_time:
            return hour

        return (
            (hour * 60 + eq_of_time + 4 * math.degrees(self._longitude) -
             60 * self.time_zone) % 1440) / 60
1061378
def yearly_plots(
    df,
    variable,
    renormalize                   = True,
    horizontal_axis_labels_days   = False,
    horizontal_axis_labels_months = True,
    plot                          = True,
    scatter                       = False,
    linestyle                     = "-",
    linewidth                     = 1,
    s                             = 1
    ):
    
    if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]:
        log.error("index is not datetime")
        return False
    years = []
    for group in df.groupby(df.index.year):
        years.append(group[1])
    scaler = MinMaxScaler()
    plt.xlabel("days")
    plt.ylabel(variable);
    for year in years:
        if renormalize:
            values = scaler.fit_transform(year[[variable]])
        else:
            values = year[variable]
        if plot:
            plt.plot(year["days_through_year"], values, linestyle = linestyle, linewidth = linewidth, label = year.index.year.values[0])
        if scatter:
            plt.scatter(year["days_through_year"], values, s = s)
    if horizontal_axis_labels_months:
        plt.xticks(
            [     15.5,         45,    74.5,     105, 135.5,    166,  196.5,    227.5,         258,     288.5,        319,      349.5],
            ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
        )
    plt.legend()
262365
def _gti_dirint_lt_90(poa_global, aoi, aoi_lt_90, solar_zenith, solar_azimuth,
                      times, surface_tilt, surface_azimuth, pressure=101325.,
                      use_delta_kt_prime=True, temp_dew=None, albedo=.25,
                      model='perez', model_perez='allsitescomposite1990',
                      max_iterations=30):
    
    I0 = get_extra_radiation(times, 1370, 'spencer')
    cos_zenith = tools.cosd(solar_zenith)
    # I0h as in Marion 2015 eqns 1, 3
    I0h = I0 * np.maximum(0.065, cos_zenith)

    airmass = atmosphere.get_relative_airmass(solar_zenith, model='kasten1966')
    airmass = atmosphere.get_absolute_airmass(airmass, pressure)

    # these coeffs and diff variables and the loop below
    # implement figure 1 of Marion 2015

    # make coeffs that is at least 30 elements long so that all
    # coeffs can be assigned as specified in Marion 2015.
    # slice below will limit iterations if necessary
    coeffs = np.empty(max(30, max_iterations))
    coeffs[0:3] = 1
    coeffs[3:10] = 0.5
    coeffs[10:20] = 0.25
    coeffs[20:] = 0.125
    coeffs = coeffs[:max_iterations]  # covers case where max_iterations < 30

    # initialize diff
    diff = pd.Series(9999, index=times)
    best_diff = diff

    # initialize poa_global_i
    poa_global_i = poa_global

    for iteration, coeff in enumerate(coeffs):

        # test if difference between modeled GTI and
        # measured GTI (poa_global) is less than 1 W/m^2
        # only test for aoi less than 90 deg
        best_diff_lte_1 = best_diff <= 1
        best_diff_lte_1_lt_90 = best_diff_lte_1[aoi_lt_90]
        if best_diff_lte_1_lt_90.all():
            # all aoi < 90 points have a difference <= 1, so break loop
            break

        # calculate kt and DNI from GTI
        kt = clearness_index(poa_global_i, aoi, I0)  # kt from Marion eqn 2
        disc_dni = np.maximum(_disc_kn(kt, airmass)[0] * I0, 0)
        kt_prime = clearness_index_zenith_independent(kt, airmass)
        # dirint DNI in Marion eqn 3
        dni = _dirint_from_dni_ktprime(disc_dni, kt_prime, solar_zenith,
                                       use_delta_kt_prime, temp_dew)

        # calculate DHI using Marion eqn 3 (identify 1st term on RHS as GHI)
        # I0h has a minimum zenith projection, but multiplier of DNI does not
        ghi = kt * I0h                  # Kt * I0 * max(0.065, cos(zen))
        dhi = ghi - dni * cos_zenith    # no cos(zen) restriction here

        # following SSC code
        dni = np.maximum(dni, 0)
        ghi = np.maximum(ghi, 0)
        dhi = np.maximum(dhi, 0)

        # use DNI and DHI to model GTI
        # GTI-DIRINT uses perez transposition model, but we allow for
        # any model here
        all_irrad = get_total_irradiance(
            surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,
            dni, ghi, dhi, dni_extra=I0, airmass=airmass,
            albedo=albedo, model=model, model_perez=model_perez)

        gti_model = all_irrad['poa_global']

        # calculate new diff
        diff = gti_model - poa_global

        # determine if the new diff is smaller in magnitude
        # than the old diff
        diff_abs = diff.abs()
        smallest_diff = diff_abs < best_diff

        # save the best differences
        best_diff = diff_abs.where(smallest_diff, best_diff)

        # on first iteration, the best values are the only values
        if iteration == 0:
            best_ghi = ghi
            best_dni = dni
            best_dhi = dhi
            best_kt_prime = kt_prime
        else:
            # save new DNI, DHI, DHI if they provide the best consistency
            # otherwise use the older values.
            best_ghi = ghi.where(smallest_diff, best_ghi)
            best_dni = dni.where(smallest_diff, best_dni)
            best_dhi = dhi.where(smallest_diff, best_dhi)
            best_kt_prime = kt_prime.where(smallest_diff, best_kt_prime)

        # calculate adjusted inputs for next iteration. Marion eqn 4
        poa_global_i = np.maximum(1.0, poa_global_i - coeff * diff)
    else:
        # we are here because we ran out of coeffs to loop over and
        # therefore we have exceeded max_iterations
        import warnings
        failed_points = best_diff[aoi_lt_90][~best_diff_lte_1_lt_90]
        warnings.warn(
            ('%s points failed to converge after %s iterations. best_diff:\n%s'
             % (len(failed_points), max_iterations, failed_points)),
            RuntimeWarning)

    # return the best data, whether or not the solution converged
    return best_ghi, best_dni, best_dhi, best_kt_prime
1162580
def mangle(data_point):
    """"""
    temp_dict = {}
    temp_dict.update(data_point)
    temp_dict['utc_datetime'] = \
        datetime.datetime.utcfromtimestamp(temp_dict['time'])
    if 'solar' in data_point:
        temp_dict['GHI (W/m^2)'] = data_point['solar']['ghi']
        temp_dict['DNI (W/m^2)'] = data_point['solar']['dni']
        temp_dict['DHI (W/m^2)'] = data_point['solar']['dhi']
        temp_dict['ETR (W/m^2)'] = data_point['solar']['etr']
        del temp_dict['solar']
    else:
        temp_dict['GHI (W/m^2)'] = 0.0
        temp_dict['DNI (W/m^2)'] = 0.0
        temp_dict['DHI (W/m^2)'] = 0.0
        temp_dict['ETR (W/m^2)'] = 0.0
    return temp_dict
283818
def plot_rh(self, rh, plot_range=None):
        
        # PLOT RELATIVE HUMIDITY
        if not plot_range:
            plot_range = [0, 100, 4]
        self.ax3 = fig.add_subplot(4, 1, 3, sharex=self.ax1)
        self.ax3.plot(self.dates, rh, 'g-', label='Relative Humidity')
        self.ax3.legend(loc='upper center', bbox_to_anchor=(0.5, 1.22), prop={'size': 12})
        self.ax3.grid(b=True, which='major', axis='y', color='k', linestyle='--',
                      linewidth=0.5)
        self.ax3.set_ylim(plot_range[0], plot_range[1], plot_range[2])

        self.ax3.fill_between(self.dates, rh, self.ax3.get_ylim()[0], color='g')
        self.ax3.set_ylabel('Relative Humidity\n(%)', multialignment='center')
        self.ax3.xaxis.set_major_formatter(mpl.dates.DateFormatter('%d/%H UTC'))
        axtwin = self.ax3.twinx()
        axtwin.set_ylim(plot_range[0], plot_range[1], plot_range[2])
844037
private int majorSolarTerm(int days) {
        
        astro.setTime(daysToMillis(days));

        // Compute (floor(solarLongitude / (pi/6)) + 2) % 12
        int term = ((int) Math.floor(6 * astro.getSunLongitude() / Math.PI) + 2) % 12;
        if (term < 1) {
            term += 12;
        }
        return term;
    }
286379
def plot_prior_dates(self, dwidth=30, ax=None):
        """"""
        if ax is None:
            ax = plt.gca()
        depth, probs = self.prior_dates()
        pat = []
        for i, d in enumerate(depth):
            p = probs[i]
            z = np.array([p[:, 0], dwidth * p[:, 1] / np.sum(p[:, 1])])  # Normalize
            z = z[:, z[0].argsort(kind='mergesort')]  # np.interp requires `xp` arg to be sorted
            zy = np.linspace(np.min(z[0]), np.max(z[0]), num=200)
            zp = np.interp(x=zy, xp=z[0], fp=z[1])
            pol = np.vstack([np.concatenate([d + zp, d - zp[::-1]]),
                             np.concatenate([zy, zy[::-1]])])
            pat.append(Polygon(pol.T))
        p = PatchCollection(pat)
        p.set_label('Prior dates')
        ax.add_collection(p)
        ax.autoscale_view()
        ax.set_ylabel('Age (cal yr BP)')
        ax.set_xlabel('Depth (cm)')
        ax.grid(True)
        return ax
909847
private int newYear(int gyear) {

        long cacheValue = newYearCache.get(gyear);

        if (cacheValue == CalendarCache.EMPTY) {

            int solsticeBefore= winterSolstice(gyear - 1);
            int solsticeAfter = winterSolstice(gyear);
            int newMoon1 = newMoonNear(solsticeBefore + 1, true);
            int newMoon2 = newMoonNear(newMoon1 + SYNODIC_GAP, true);
            int newMoon11 = newMoonNear(solsticeAfter + 1, false);
            
            if (synodicMonthsBetween(newMoon1, newMoon11) == 12 &&
                (hasNoMajorSolarTerm(newMoon1) || hasNoMajorSolarTerm(newMoon2))) {
                cacheValue = newMoonNear(newMoon2 + SYNODIC_GAP, true);
            } else {
                cacheValue = newMoon2;
            }

            newYearCache.put(gyear, cacheValue);
        }
        return (int) cacheValue;
    }
367348
def guinierplot(*args, **kwargs):
    """"""
    ret=plotsascurve(*args, **kwargs)
    plt.xscale('power',exponent=2)
    plt.yscale('log')
    return ret
423525
def _plot(self):
        """"""
        map = etree.fromstring(self.svg_map)
        map.set('width', str(self.view.width))
        map.set('height', str(self.view.height))

        for i, serie in enumerate(self.series):
            safe_vals = list(
                filter(lambda x: x is not None, cut(serie.values, 1))
            )
            if not safe_vals:
                continue
            min_ = min(safe_vals)
            max_ = max(safe_vals)
            for j, (area_code, value) in self.enumerate_values(serie):
                area_code = self.adapt_code(area_code)
                if value is None:
                    continue
                if max_ == min_:
                    ratio = 1
                else:
                    ratio = .3 + .7 * (value - min_) / (max_ - min_)

                areae = map.findall(
                    ".//*[@class='%s%s %s map-element']" %
                    (self.area_prefix, area_code, self.kind)
                )

                if not areae:
                    continue

                for area in areae:
                    cls = area.get('class', '').split(' ')
                    cls.append('color-%d' % i)
                    cls.append('serie-%d' % i)
                    cls.append('series')
                    area.set('class', ' '.join(cls))
                    area.set('style', 'fill-opacity: %f' % ratio)

                    metadata = serie.metadata.get(j)

                    if metadata:
                        node = decorate(self.svg, area, metadata)
                        if node != area:
                            area.remove(node)
                            for g in map:
                                if area not in g:
                                    continue
                                index = list(g).index(area)
                                g.remove(area)
                                node.append(area)
                                g.insert(index, node)

                    for node in area:
                        cls = node.get('class', '').split(' ')
                        cls.append('reactive')
                        cls.append('tooltip-trigger')
                        cls.append('map-area')
                        node.set('class', ' '.join(cls))
                        alter(node, metadata)

                    val = self._format(serie, j)
                    self._tooltip_data(area, val, 0, 0, 'auto')

        self.nodes['plot'].append(map)
1183627
def _earth_orientation(date):
    

    ttt = date.change_scale('TT').julian_century
    # a_a = 0.12
    # a_c = 0.26
    # s_prime = -0.0015 * (a_c ** 2 / 1.2 + a_a ** 2) * ttt
    s_prime = - 0.000047 * ttt

    return date.eop.x / 3600., date.eop.y / 3600., s_prime / 3600