r"""
    Plots or prints power output and power (coefficient) curves.

    Parameters
    ----------
    example_farm : WindFarm
        WindFarm object.
    example_farm_2 : WindFarm
        WindFarm object constant wind farm efficiency and coordinates.
15326
def plot_or_print(example_farm, example_cluster):
    

    """

    # plot or print power output
    if plt:
        example_cluster.power_output.plot(legend=True, label='example cluster')
        example_farm.power_output.plot(legend=True, label='example farm')
        plt.show()
    else:
        print(example_cluster.power_output)
        print(example_farm.power_output)
1315862
def make_plotters(self):
        """"""
        plotters, y = {}, 0
        for var_name in self.var_names:
            plotters[var_name] = VarHandler(
                var_name,
                self.data,
                y,
                model_names=self.model_names,
                combined=self.combined,
                colors=self.colors,
            )
            y = plotters[var_name].y_max()
        return plotters
791264
def f_cell_temp(poa_global, wind_speed, air_temp):
    
    temps = pvlib.pvsystem.sapm_celltemp(poa_global, wind_speed, air_temp)
    return temps['temp_cell'].values, temps['temp_module'].values
1054900
def plot_diagrams(results, configs, compiler, out_dir):
    """"""
    compiler_fn = make_filename(compiler)
    total = psutil.virtual_memory().total  # pylint:disable=I0011,E1101
    memory = int(math.ceil(byte_to_gb(total)))

    images_dir = os.path.join(out_dir, 'images')

    for config in configs:
        out_prefix = '{0}_{1}'.format(config['name'], compiler_fn)

        plot_diagram(
            config,
            results,
            images_dir,
            os.path.join(images_dir, '{0}.png'.format(out_prefix))
        )

        with open(
            os.path.join(out_dir, '{0}.qbk'.format(out_prefix)),
            'wb'
        ) as out_f:
            qbk_content = """{0}
Measured on a {2} host with {3} GB memory. Compiler used: {4}.

[$images/metaparse/{1}.png [width 100%]]
""".format(config['desc'], out_prefix, platform.platform(), memory, compiler)
            out_f.write(qbk_content)
411878
def plot_data(self, proj, ax):
        
        x, y = proj
        ax.scatter(self.ig.independent_data[x],
                   self.ig.dependent_data[y], c='b')
1272647
def infer(args):
    

    expected_output_files = ["inferred.pkl"]
    if args.plotting:
        expected_output_files.extend([each.format(args.plot_format) \
            for each in "chain.{}", "corner.{}", "acceptance-fractions.{}",
            "autocorrelation.{}"])

    # Optimise them first.
    model, data, metadata, optimised_theta = optimise(args,
        expected_output_files=expected_output_files, __return_result=True)

    # Get the inference parameters from the model configuration.
    kwargs = model._configuration.get("infer", {})
    [kwargs.pop(k, None) \
        for k in ("debug", "full_output", "initial_proposal", "data")]

    try:
        theta, chains, lnprobability, acceptance_fractions, sampler, info_dict \
            = model.infer(data, initial_proposal=optimised_theta, 
                full_output=True, debug=args.debug, 
                __keep_convolution_functions=True,
                __show_progress_bar=True, **kwargs)

    except:
        logger.exception("Failed to infer model parameters")
        raise

    metadata["inferred"] = {
        "theta": theta,
        "chi_sq": info_dict["chi_sq"],
        "dof": info_dict["dof"],
        "r_chi_sq": info_dict["chi_sq"]/info_dict["dof"]
    }

    logger.info("Inferred parameters are:")
    _announce_theta(theta)
    
    # Write the results to file.
    _write_output(_prefix(args, "inferred.pkl"), metadata)

    # Write the chains, etc to disk.
    if args.save_chain_files:
        filename = _prefix(args, "chains.pkl")
        with open(filename, "wb") as f:
            pickle.dump(
                (chains, lnprobability, acceptance_fractions, info_dict), f, -1)
        logger.info("Saved chains to {}".format(filename))

    # Make plots.
    if args.plotting:
        burn = info_dict["burn"]

        # Any truth values to plot?
        truths = model._configuration.get("truths", None)
        if truths:
            truths = [truths.get(p, np.nan) for p in model.parameters]

        # Labels?
        labels = model._configuration.get("labels", {})
        labels = [labels.get(p, p) for p in info_dict["parameters"]]
        
        # Acceptance fractions.
        fig = sick.plot.acceptance_fractions(acceptance_fractions,
            burn=burn)
        _ = _prefix(args, "acceptance-fractions.{}".format(args.plot_format))
        fig.savefig(_)
        logger.info("Saved acceptance fractions figure to {}".format(_))

        # Autocorrelation.
        fig = sick.plot.normalised_autocorrelation_function(chains, burn=burn)
        _ = _prefix(args, "auto-correlation.{}".format(args.plot_format))
        fig.savefig(_)
        logger.info("Saved auto-correlation figure to {}".format(_))

        # Chains.
        fig = sick.plot.chains(chains, labels=labels, burn=burn,
            truths=truths)
        _ = _prefix(args, "chains.{}".format(args.plot_format))
        fig.savefig(_)
        logger.info("Saved chains figure to {}".format(_))

        # Corner plots (astrophysical + all).
        N = len(model.grid_points.dtype.names)
        fig = sick.plot.corner(chains[:, burn:, :N].reshape(-1, N),
            labels=labels, truths=truths[:N] if truths else None)
        _ = _prefix(args, "corner.{}".format(args.plot_format))
        fig.savefig(_)
        logger.info("Saved corner plot (astrophysical parameters) to {}"\
            .format(_))

        if len(model.parameters) > N:
            fig = sick.plot.corner(chains[:, burn:, :].reshape(-1, len(theta)),
                labels=labels, truths=truths)
            _ = _prefix(args, "corner-all.{}".format(args.plot_format))
            fig.savefig(_)
            logger.info("Saved corner plot (all parameters) to {}".format(_))

        # Projections.
        # Note here we need to scale the chains back to redshift so the data
        # are generated properly.
        fig = sick.plot.projection(data, model, 
            chains=chains[:, burn:, :]/info_dict["scales"],
            parameters=theta.keys())
        _ = _prefix(args, "projection.{}".format(args.plot_format))
        fig.savefig(_)
        logger.info("Saved projection plot to {}".format(_))

    model._destroy_convolution_functions()

    return None
1267497
def main():
    
    fmt,plot='svg',0
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    elif '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        input=f.readlines()
    Data=[]
    for line in input:
        line.replace('\n','')
        if '\t' in line:   # read in the data from standard input
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        Data.append(float(rec[0]))
    
#
    if len(Data) >=10: 
        QQ={'unf1':1}
        pmagplotlib.plot_init(QQ['unf1'],5,5)
        pmagplotlib.plot_qq_unf(QQ['unf1'],Data,'QQ-Uniform') # make plot
    else:
        print('you need N> 10')
        sys.exit()
    pmagplotlib.draw_figs(QQ) 
    files={}
    for key in list(QQ.keys()):
        files[key]=key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(QQ,files)
    elif plot==1:
        files['qq']=file+'.'+fmt 
        pmagplotlib.save_plots(QQ,files)
    else:
        ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": pmagplotlib.save_plots(QQ,files)
371164
def plot_winds(self, ws, wd, wsmax, plot_range=None):
        
        # PLOT WIND SPEED AND WIND DIRECTION
        self.ax1 = fig.add_subplot(4, 1, 1)
        ln1 = self.ax1.plot(self.dates, ws, label='Wind Speed')
        self.ax1.fill_between(self.dates, ws, 0)
        self.ax1.set_xlim(self.start, self.end)
        if not plot_range:
            plot_range = [0, 20, 1]
        self.ax1.set_ylabel('Wind Speed (knots)', multialignment='center')
        self.ax1.set_ylim(plot_range[0], plot_range[1], plot_range[2])
        self.ax1.grid(b=True, which='major', axis='y', color='k', linestyle='--',
                      linewidth=0.5)
        ln2 = self.ax1.plot(self.dates, wsmax, '.r', label='3-sec Wind Speed Max')

        ax7 = self.ax1.twinx()
        ln3 = ax7.plot(self.dates, wd, '.k', linewidth=0.5, label='Wind Direction')
        ax7.set_ylabel('Wind\nDirection\n(degrees)', multialignment='center')
        ax7.set_ylim(0, 360)
        ax7.set_yticks(np.arange(45, 405, 90), ['NE', 'SE', 'SW', 'NW'])
        lns = ln1 + ln2 + ln3
        labs = [l.get_label() for l in lns]
        ax7.xaxis.set_major_formatter(mpl.dates.DateFormatter('%d/%H UTC'))
        ax7.legend(lns, labs, loc='upper center',
                   bbox_to_anchor=(0.5, 1.2), ncol=3, prop={'size': 12})
252374
def _plot(x, mph, mpd, threshold, edge, valley, ax, ind):
    """"""
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        print('matplotlib is not available.')
    else:
        if ax is None:
            _, ax = plt.subplots(1, 1, figsize=(8, 4))

        ax.plot(x, 'b', lw=1)
        if ind.size:
            label = 'valley' if valley else 'peak'
            label = label + 's' if ind.size > 1 else label
            ax.plot(ind, x[ind], '+', mfc=None, mec='r', mew=2, ms=8,
                    label='%d %s' % (ind.size, label))
            ax.legend(loc='best', framealpha=.5, numpoints=1)
        ax.set_xlim(-.02*x.size, x.size*1.02-1)
        ymin, ymax = x[np.isfinite(x)].min(), x[np.isfinite(x)].max()
        yrange = ymax - ymin if ymax > ymin else 1
        ax.set_ylim(ymin - 0.1*yrange, ymax + 0.1*yrange)
        ax.set_xlabel('Data #', fontsize=14)
        ax.set_ylabel('Amplitude', fontsize=14)
        mode = 'Valley detection' if valley else 'Peak detection'
        ax.set_title("%s (mph=%s, mpd=%d, threshold=%s, edge='%s')"
                     % (mode, str(mph), mpd, str(threshold), edge))
356250
def plot_summary(self, cycles=None):
        """"""
        if cycles is None:
            cycles = [0]
        fig1 = plt.figure()
        ax1 = fig1.add_subplot(221)
        ax1.set_title('Fit')
        ax2 = fig1.add_subplot(222)
        ax2.set_title('OCV')
        ax3 = fig1.add_subplot(223)
        ax3.set_title('Tau')
        ax3.set_yscale("log")
        ax4 = fig1.add_subplot(224)
        ax4.set_title('Voltage Impact')

        plot_data = self.get_best_fit_data()
        for cycle in cycles:
            ax1.plot(plot_data[cycle][0], plot_data[cycle][1])
            ax1.plot(plot_data[cycle][0], plot_data[cycle][2])

        plot_data = self.get_best_fit_parameters_grouped()

        for i in range(self.circuits):
            ax3.plot(self.get_fit_cycles(), plot_data['t' + str(i)])
            ax4.plot(self.get_fit_cycles(), plot_data['w' + str(i)])

        ax2.plot(self.get_fit_cycles(), plot_data['ocv'])
662314
def raw_data_engine(**kwargs):
    """"""
    logger.debug("cycles_engine")
    raise NotImplementedError

    experiments = kwargs["experiments"]
    farms = []
    barn = "raw_dir"

    for experiment in experiments:
        farms.append([])

    return farms, barn
1061004
def summary_plotting_engine(**kwargs):
    """"""

    logging.debug(f"Using {prms.Batch.backend} for plotting")
    experiments = kwargs["experiments"]
    farms = kwargs["farms"]
    barn = None

    logging.debug("    - summary_plot_engine")
    farms = _preparing_data_and_plotting(
        experiments=experiments,
        farms=farms
    )

    return farms, barn
1030525
def plot_mv_voltages(self, **kwargs):
        
        if self.network.pypsa is not None:
            try:
                v_res = self.network.results.v_res()
            except:
                logging.warning("Voltages `pfa_v_mag_pu` from power flow "
                                "analysis must be available to plot them.")
                return
            plots.mv_grid_topology(
                self.network.pypsa, self.network.config,
                timestep=kwargs.get('timestep', None),
                node_color='voltage',
                filename=kwargs.get('filename', None),
                grid_district_geom=kwargs.get('grid_district_geom', True),
                background_map=kwargs.get('background_map', True),
                voltage=v_res,
                limits_cb_nodes=kwargs.get('limits_cb_nodes', None),
                xlim=kwargs.get('xlim', None), ylim=kwargs.get('ylim', None),
                title=kwargs.get('title', ''))
        else:
            logging.warning("pypsa representation of MV grid needed to "
                            "plot voltages.")
495353
def plot_residual_load(network):
    

    renewables = network.generators[
        network.generators.carrier.isin(['wind_onshore', 'wind_offshore', 
                                         'solar', 'run_of_river',
                                         'wind'])]
    renewables_t = network.generators.p_nom[renewables.index] * \
        network.generators_t.p_max_pu[renewables.index].mul(
                network.snapshot_weightings, axis=0)
    load = network.loads_t.p_set.mul(network.snapshot_weightings, axis=0).\
    sum(axis=1)
    all_renew = renewables_t.sum(axis=1)
    residual_load = load - all_renew
    plot = residual_load.plot(
        title = 'Residual load',
        drawstyle='steps',
        lw=2,
        color='red',
        legend=False)
    plot.set_ylabel("MW")
    # sorted curve
    sorted_residual_load = residual_load.sort_values(
        ascending=False).reset_index()
    plot1 = sorted_residual_load.plot(
            title='Sorted residual load',
            drawstyle='steps',
            lw=2,
            color='red',
            legend=False)
    plot1.set_ylabel("MW")
263579
def _add_plots_to_output(out, data):
    
    out["plot"] = {}
    diagram_plot = _add_diagram_plot(out, data)
    if diagram_plot:
        out["plot"]["diagram"] = diagram_plot
    scatter = _add_scatter_plot(out, data)
    if scatter:
        out["plot"]["scatter"] = scatter
    scatter_global = _add_global_scatter_plot(out, data)
    if scatter_global:
        out["plot"]["scatter_global"] = scatter_global
    return out
973673
def render(self, **kwargs):
        
        # Calling parent function
        super(VisCurve2D, self).render(**kwargs)

        # Initialize variables
        legend_proxy = []
        legend_names = []

        # Draw control points polygon and the curve
        fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi)
        ax = fig.gca()

        # Start plotting
        for plot in self._plots:
            pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)
            # Plot control points
            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:
                cpplot, = plt.plot(pts[:, 0], pts[:, 1], color=plot['color'], linestyle='-.', marker='o')
                legend_proxy.append(cpplot)
                legend_names.append(plot['name'])

            # Plot evaluated points
            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:
                curveplt, = plt.plot(pts[:, 0], pts[:, 1], color=plot['color'], linestyle='-', alpha=self.vconf.alpha)
                legend_proxy.append(curveplt)
                legend_names.append(plot['name'])
                # Debugging for curve directions
                if self.vconf.debug_mode:
                    plt.quiver(pts[0, 0], pts[0, 1], pts[-1, 0] - pts[0, 0], pts[-1, 1] - pts[0, 1],
                               color='k', angles='xy', scale_units='xy', scale=1, width=0.003)

            # Plot bounding box
            if plot['type'] == 'bbox' and self.vconf.display_bbox:
                bboxplt, = plt.plot(pts[:, 0], pts[:, 1], color=plot['color'], linestyle='--')
                legend_proxy.append(bboxplt)
                legend_names.append(plot['name'])

            # Plot extras
            if plot['type'] == 'extras':
                extrasplt, = plt.plot(pts[:, 0], pts[:, 1],
                                      color=plot['color'][0], linestyle='-', linewidth=plot['color'][1])
                legend_proxy.append(extrasplt)
                legend_names.append(plot['name'])

        # Add legend
        if self.vconf.display_legend:
            plt.legend(legend_proxy, legend_names)

        # Remove axes
        if not self.vconf.display_axes:
            plt.axis('off')

        # Set aspect ratio
        if self.vconf.axes_equal:
            ax.set_aspect('equal')

        # Axis labels
        if self.vconf.display_labels:
            ax.set_xlabel('x')
            ax.set_ylabel('y')

        # Process keyword arguments
        fig_filename = kwargs.get('fig_save_as', None)
        fig_display = kwargs.get('display_plot', True)

        # Display the plot
        if fig_display:
            plt.show()
        else:
            fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename

        # Save the figure
        self.vconf.save_figure_as(fig, fig_filename)
741187
def _generate_examples(self, file_path):
    

    fieldnames = [
        'class_label', 'lepton_pT', 'lepton_eta', 'lepton_phi',
        'missing_energy_magnitude', 'missing_energy_phi', 'jet_1_pt',
        'jet_1_eta', 'jet_1_phi', 'jet_1_b-tag', 'jet_2_pt', 'jet_2_eta',
        'jet_2_phi', 'jet_2_b-tag', 'jet_3_pt', 'jet_3_eta', 'jet_3_phi',
        'jet_3_b-tag', 'jet_4_pt', 'jet_4_eta', 'jet_4_phi', 'jet_4_b-tag',
        'm_jj', 'm_jjj', 'm_lv', 'm_jlv', 'm_bb', 'm_wbb', 'm_wwbb'
    ]

    with tf.io.gfile.GFile(file_path) as csvfile:
      reader = csv.DictReader(csvfile, fieldnames=fieldnames)
      for row in reader:
        yield row