Peak generation of each technology and the 
        corresponding weather cell in the grid 

        Returns
        -------
        :pandas:`pandas.Series<series>`
            Peak generation index by technology
188972
def peak_generation_per_technology_and_weather_cell(self):
        
        peak_generation = defaultdict(float)
        for gen in self.generators:
            if hasattr(gen, 'weather_cell_id'):
                if (gen.type, gen.weather_cell_id) in peak_generation.keys():
                    peak_generation[gen.type, gen.weather_cell_id] += gen.nominal_capacity
                else:
                    peak_generation[gen.type, gen.weather_cell_id] = gen.nominal_capacity
            else:
                message = 'No weather cell ID found for ' \
                          'generator {}.'.format(repr(gen))
                raise KeyError(message)

        series_index = pd.MultiIndex.from_tuples(list(peak_generation.keys()),
                                                 names=['type', 'weather_cell_id'])

        return pd.Series(peak_generation, index=series_index)
61604
def energy_data():
    
    cur = db.cursor().execute("""SELECT timestamp, current FROM Readings""")
    original = TimeSeries()
    original.initialize_from_sql_cursor(cur)
    original.normalize("day", fusionMethod = "sum")
    return itty.Response(json.dumps(original, cls=PycastEncoder), content_type='application/json')
1299279
def get_best_frequencies(self):
        
        return self.freq[self.best_local_optima], self.per[self.best_local_optima]
789950
def humidity_series(self):
        
        return [(tstamp, \
                self._station_history.get_measurements()[tstamp]['humidity']) \
                for tstamp in self._station_history.get_measurements()]
992727
def gen_WS_DF(df_WS_data):
    
    df_fs = gen_FS_DF(df_WS_data)

    list_index = [('mean', 'T2'), ('max', 'T2'), ('min', 'T2'),
                  ('mean', 'U10'), ('max', 'U10'), ('min', 'U10'),
                  ('mean', 'RH2'), ('max', 'RH2'), ('min', 'RH2'),
                  ('mean', 'Kdown')]

    list_const = [getattr(const, attr)
                  for attr in ['T_MEAN', 'T_MAX', 'T_MIN',
                               'WIND_MEAN', 'WIND_MAX', 'WIND_MIN',
                               'RH_MEAN', 'RH_MAX', 'RH_MIN',
                               'SOLAR_RADIATION_GLOBAL']]
    list_ws = [df_fs.loc[idx] * cst
               for idx, cst
               in zip(list_index, list_const)]
    df_ws = pd.concat(list_ws, axis=1).sum(axis=1).unstack().dropna()

    return df_ws
988791
def to_dict(self):
        
        return {'station_id': self.station_id,
                'timestamp': self.timestamp,
                'aggregated_on': self.aggregated_on,
                'temp': self.temp,
                'humidity': self.humidity,
                'wind': self.wind,
                'pressure': self.pressure,
                'precipitation': self.precipitation}
683111
def peak_templates(self):
        
        peak_templates = []
        for peak_descr in self:
            expanded_dims = [dim_group.dimensions for dim_group in peak_descr]
            templates = product(*expanded_dims)
            for template in templates:
                peak_templates.append(PeakTemplate(template))
        return peak_templates
1108525
def summarize(self, **kwargs):
        
        import pandas as pd
        colnames = ["fname", "wall_time", "cpu_time", "mpi_nprocs", "omp_nthreads", "mpi_rank"]

        frame = pd.DataFrame(columns=colnames)
        for i, timer in enumerate(self.timers()):
            frame = frame.append({k: getattr(timer, k) for k in colnames}, ignore_index=True)
        frame["tot_ncpus"] = frame["mpi_nprocs"] * frame["omp_nthreads"]

        # Compute parallel efficiency (use the run with min number of cpus to normalize).
        i = frame["tot_ncpus"].values.argmin()
        ref_wtime = frame.ix[i]["wall_time"]
        ref_ncpus = frame.ix[i]["tot_ncpus"]
        frame["peff"] = (ref_ncpus * ref_wtime) / (frame["wall_time"] * frame["tot_ncpus"])

        return frame
79099
def gen_FS_DF(df_output):
    
    df_day = pd.pivot_table(
        df_output,
        values=['T2', 'U10', 'Kdown', 'RH2'],
        index=['Year', 'Month', 'Day'],
        aggfunc=[min, max, np.mean, ])
    df_day_all_year = pd.pivot_table(
        df_output,
        values=['T2', 'U10', 'Kdown', 'RH2'],
        index=['Month', 'Day'],
        aggfunc=[min, max, np.mean, ])

    array_yr_mon = df_day.index.droplevel(
        'Day').to_frame().drop_duplicates().values

    df_fs = pd.DataFrame(
        {(yr, mon):
         (df_day.loc[(yr, mon)].apply(gen_score_ser) -
          df_day_all_year.loc[mon].apply(gen_score_ser)).abs().mean()
         for yr, mon in array_yr_mon})

    return df_fs
481926
def peak_load(self):
        
        peak_load = pd.Series(self.consumption).mul(pd.Series(
            self.grid.network.config['peakload_consumption_ratio']).astype(
            float), fill_value=0)

        return peak_load
1038399
def max_curtailment(network, snapshots, curtail_max=0.03):
    
    
    renewables = ['wind_onshore', 'wind_offshore',
                  'solar']
    
    res = list(network.generators.index[
        (network.generators.carrier.isin(renewables))
        & (network.generators.bus.astype(str).isin(network.buses.index[network.buses.country_code == 'DE']))])
      
#    network.import_series_from_dataframe(pd.DataFrame(
#                index=network.generators_t.p_set.index,
#                columns=network.generators.index[
#                        network.generators.carrier=='biomass'],
#                data=1), "Generator", "p_max_pu")
    
    res_potential = (network.generators.p_nom[res]*network.generators_t.p_max_pu[res]).sum()
    
    snapshots = network.snapshots

    for gen in res:

        def _rule(m, gen):
            
            #import pdb; pdb.set_trace()
            re_n = sum(m.generator_p[gen, sn]
                                      for sn in snapshots)
            potential_n = res_potential[gen]

            return (re_n >= (1-curtail_max) * potential_n)
        setattr(network.model, "max_curtailment"+gen, Constraint(res, rule=_rule))
527754
def summary(self):
        
        ci = 1 - self.alpha
        lower_upper_bounds = self._compute_confidence_bounds_of_parameters()
        df = pd.DataFrame(index=self._fitted_parameter_names)
        df["coef"] = self._fitted_parameters_
        df["se(coef)"] = self._compute_standard_errors().loc["se"]
        df["lower %g" % ci] = lower_upper_bounds["lower-bound"]
        df["upper %g" % ci] = lower_upper_bounds["upper-bound"]
        df["p"] = self._compute_p_values()
        with np.errstate(invalid="ignore", divide="ignore"):
            df["-log2(p)"] = -np.log2(df["p"])
        return df
1119940
def info(self):
        
        names = []
        types = []
        sizes = []
        names.append('WIDGET')
        types.append('-')
        s = 0
        sizes.append(s)
        names.append('METADATA')
        types.append('-')
        s = 0
        for obj in self._rel().values():
            s += getsizeof(obj)
        sizes.append(s)
        for name, obj in self._data().items():
            names.append(name[1:] if name.startswith('_') else name)
            types.append('.'.join((obj.__module__, obj.__class__.__name__)))
            if isinstance(obj, pd.Series):
                sizes.append(obj.memory_usage())
            else:
                sizes.append(obj.memory_usage().sum())
        inf = pd.DataFrame.from_dict({'object': names, 'type': types, 'size': sizes})
        inf.set_index('object', inplace=True)
        return inf.sort_index()
917552
def tc_at_grid_col(self, idx):
        
        grid_col = 0
        for tc in self.tc_lst:
            if grid_col == idx:
                return tc
            grid_col += tc.grid_span
            if grid_col > idx:
                raise ValueError('no cell on grid column %d' % idx)
        raise ValueError('index out of bounds')
222760
def generate_values(self, *args, **kwargs):
        
        values = super().generate_values(*args, **kwargs, size=(len(self.times) * self.size,))
        alpha = self.cagr

        # @todo - fill to cover the entire time: define rules for filling first
        ref_date = self.ref_date if self.ref_date else self.times[0].to_pydatetime()
        # assert ref_date >= self.times[0].to_pydatetime(), 'Ref date must be within variable time span.'
        # assert ref_date <= self.times[-1].to_pydatetime(), 'Ref date must be within variable time span.'

        start_date = self.times[0].to_pydatetime()
        end_date = self.times[-1].to_pydatetime()

        a = growth_coefficients(start_date, end_date, ref_date, alpha, self.size)

        values *= a.ravel()

        df = pd.DataFrame(values)
        df.columns = [kwargs['name']]
        df.set_index(self._multi_index, inplace=True)
        # @todo this is a hack to return a series with index as I don't know how to set an index and rename a series
        data_series = df.iloc[:, 0]
        data_series._metadata = kwargs
        data_series.index.rename(['time', 'samples'], inplace=True)

        return data_series
34630
def generate(self, **kwargs):
        
        self.current_params.update(kwargs)
        rfparams = {param: self.current_params[param]
            for param in kwargs if param not in self.location_args}
        hp, hc = self.rframe_generator.generate(**rfparams)
        if isinstance(hp, TimeSeries):
            df = self.current_params['delta_f']
            hp = hp.to_frequencyseries(delta_f=df)
            hc = hc.to_frequencyseries(delta_f=df)
            # time-domain waveforms will not be shifted so that the peak amp
            # happens at the end of the time series (as they are for f-domain),
            # so we add an additional shift to account for it
            tshift = 1./df - abs(hp._epoch)
        else:
            tshift = 0.
        hp._epoch = hc._epoch = self._epoch
        h = {}
        if self.detector_names != ['RF']:
            for detname, det in self.detectors.items():
                # apply detector response function
                fp, fc = det.antenna_pattern(self.current_params['ra'],
                            self.current_params['dec'],
                            self.current_params['polarization'],
                            self.current_params['tc'])
                thish = fp*hp + fc*hc
                # apply the time shift
                tc = self.current_params['tc'] + \
                    det.time_delay_from_earth_center(self.current_params['ra'],
                         self.current_params['dec'], self.current_params['tc'])
                h[detname] = apply_fd_time_shift(thish, tc+tshift, copy=False)
                if self.recalib:
                    # recalibrate with given calibration model
                    h[detname] = \
                        self.recalib[detname].map_to_adjust(h[detname],
                            **self.current_params)
        else:
            # no detector response, just use the + polarization
            if 'tc' in self.current_params:
                hp = apply_fd_time_shift(hp, self.current_params['tc']+tshift,
                                         copy=False)
            h['RF'] = hp
        if self.gates is not None:
            # resize all to nearest power of 2
            for d in h.values():
                d.resize(ceilpow2(len(d)-1) + 1)
            h = strain.apply_gates_to_fd(h, self.gates)
        return h
1090094
def plot_generation_over_load(stats, plotpath):
    

    # Generation capacity vs. peak load
    sns.set_context("paper", font_scale=1.1)
    sns.set_style("ticks")

    # reformat to MW

    gen_cap_indexes = ["Gen. Cap. of MV at v_level 4",
                       "Gen. Cap. of MV at v_level 5",
                       "Gen. Cap. of LV at v_level 6",
                       "Gen. Cap. of LV at v_level 7"]
    peak_load_index = ["LA Total LV Peak Load total"]
    stats['generation_capacity'] = stats[gen_cap_indexes].sum(axis=1) / 1e3
    stats['peak_load'] = stats[peak_load_index] / 1e3

    sns.lmplot('generation_capacity', 'peak_load',
               data=stats,
               fit_reg=False,
               # hue='v_nom',
               # hue='Voltage level',
               scatter_kws={"marker": "D",
                            "s": 100},
               aspect=2)
    plt.title('Peak load vs. generation capacity')
    plt.xlabel('Generation capacity in MW')
    plt.ylabel('Peak load in MW')

    plt.savefig(os.path.join(plotpath,
                             'Scatter_generation_load.pdf'))