示例#1
0
def bin_significance(out_dir, input_path, ndof):
    input_path = utils.full_path(input_path)
    out_dir = utils.full_path(out_dir)

    input_name = os.path.splitext(os.path.basename(input_path))[0]

    with utils.ROOTFile(input_path, "read") as f:
        w = f.Get("w")
        fit_b = f.Get("fit_b")
        fit_s = f.Get("fit_s")
        bins = [[b, 0., 0., 0.] for b in get_bin_names(w)]
        procs = get_process_names(w)
        constraints = get_constraint_names(w)
        r_sign = 0
        r = fit_s.floatParsFinal().find("r")
        if r.getVal() < 0.:
            r_sign = -1
        elif r.getVal() > 0.:
            r_sign = 1

        find_sat_nlls(bins, procs, w)
        find_bkg_nlls(bins, procs, constraints, w, fit_b)
        find_sig_nlls(bins, procs, constraints, w, fit_s)

        print("{:>48s}: {:>12s} {:>12s} {:>12s}".format(
            "Bin Name", "Bkg NLL", "Sig NLL", "Sat NLL"))
        for b in bins:
            print("{:>48s}: {:>12.3f} {:>12.3f} {:>12.3f}".format(
                b[0], b[1], b[2], b[3]))

        make_plot(out_dir, input_name, bins, ndof, r_sign, 1, 2)
        make_plot(out_dir, input_name, bins, ndof, 0, 1, 3)
示例#2
0
def copy_folder(src, dst, recursive, link):
    logger = logging.getLogger(__name__)

    svc = utils.get_gdrive_service(SCOPES=SCOPES)
    print("Source: ", utils.full_path(svc, src, tpath=[]))
    print("Destn:  ", utils.full_path(svc, dst, tpath=[]))

    for fileinfo in utils.iterfiles(svc, parent=src):
        if dst not in fileinfo['parents']:
            if link:
                update_result = svc.files().update(
                    fileId=fileinfo['id'],
                    addParents=dst,
                    fields='id, parents'
                    ).execute()
                print("update result ", update_result)
            else:
                raise NotImplementedError("TODO")
    utils.list_files(utils.iterfiles(svc, parent=src))
示例#3
0
文件: info.py 项目: amm042/GFileCmd
def listdrive(svc, recursive=None, **kwargs):
    for fileinfo in utils.iterfiles(svc, **kwargs):

        if 'parents' in fileinfo:
            fileinfo['parent_name'] = list(map(
                lambda p: utils.full_path(svc, p),
                fileinfo['parents']))
        if 'parent' in kwargs:
            pathname = "{}\\{}".format(utils.full_path(svc, kwargs['parent']), fileinfo['name'])
        else:
            pathname = "\\{}".format(fileinfo['name'])
        print(pathname, "-"*(max(1,term_columns-len(pathname)-1)))
        pprint(fileinfo, width=term_columns)

    if recursive:
        for pathinfo in utils.iterfiles(svc, parent=kwargs['parent'], is_folder=True):
            #print("-"*term_columns)
            #pprint(pathinfo, width=term_columns)
            listdrive(svc, recursive=True,
                    trashed=kwargs["trashed"],
                    parent=pathinfo["id"],
                    name=kwargs["name"])
示例#4
0
def run_combine(workspace_path, output_path, do_full_fit, overwrite, log_path, ndof):
    workspace_path = utils.full_path(workspace_path)
    log_path = utils.full_path(log_path)

    with open(log_path, "w") as log_file:
        print("Workspace file: {}".format(workspace_path),file=log_file)

    if output_path is None:
        output_path = workspace_path
    else:
        output_path = utils.full_path(output_path)
        shutil.copy2(workspace_path, output_path)

    utils.cmsenv("~/cmssw/CMSSW_7_4_14/src")
    if do_full_fit:
        run_fit(output_path, overwrite, log_path)
        if overwrite:
            fix_vars(output_path)
    goodness_of_fit(output_path, overwrite, ndof)
    run_obs_signif(output_path, overwrite, log_path)
    run_exp_signif(output_path, overwrite, log_path)
    run_limit(output_path, overwrite, log_path)
示例#5
0
def run_combine(workspace_path, output_path, do_full_fit, overwrite, log_path,
                ndof):
    workspace_path = utils.full_path(workspace_path)
    log_path = utils.full_path(log_path)

    with open(log_path, "w") as log_file:
        print("Workspace file: {}".format(workspace_path), file=log_file)

    if output_path is None:
        output_path = workspace_path
    else:
        output_path = utils.full_path(output_path)
        shutil.copy2(workspace_path, output_path)

    utils.cmsenv("~/cmssw/CMSSW_7_4_14/src")
    if do_full_fit:
        run_fit(output_path, overwrite, log_path)
        if overwrite:
            fix_vars(output_path)
    goodness_of_fit(output_path, overwrite, ndof)
    run_obs_signif(output_path, overwrite, log_path)
    run_exp_signif(output_path, overwrite, log_path)
    run_limit(output_path, overwrite, log_path)
示例#6
0
def dataset_from_pickle(file):
    '''Return the contents of the compressed pickle file in 'file'.  The
    pickle is assumed to contain only one data structure.
    '''
    log = Logger().get_log()
    file = full_path(file)
    try:
        log.debug('reading data set from pickle file {}'.format(file))
        with gzip.open(file, 'rb') as pickle_file:
            return pickle.load(pickle_file)
    except pickle.PickleError as err:
        log.error('unpickle failed for {}'.format(file))
        log.error(err)
        return ({}, None)
示例#7
0
def listdrive(svc, recursive=None, **kwargs):
    for fileinfo in utils.iterfiles(svc, **kwargs):

        if 'parents' in fileinfo:
            fileinfo['parent_name'] = list(
                map(lambda p: utils.full_path(svc, p), fileinfo['parents']))
        if 'parent' in kwargs:
            pathname = "{}\\{}".format(utils.full_path(svc, kwargs['parent']),
                                       fileinfo['name'])
        else:
            pathname = "\\{}".format(fileinfo['name'])
        print(pathname, "-" * (max(1, term_columns - len(pathname) - 1)))
        #pprint(fileinfo, width=term_columns)
        if fileinfo['modifiedTime'].startswith('2020-09-02'):
            print("UNTRASH")
            pprint(svc.files().update(fileId=fileinfo['id'],
                                      body={
                                          'trashed': False
                                      },
                                      fields='id, name, trashed').execute(),
                   width=term_columns)
        else:
            print("SKIP")
            pprint(fileinfo, width=term_columns)

    if recursive:
        for pathinfo in utils.iterfiles(svc,
                                        parent=kwargs['parent'],
                                        is_folder=True):
            pathname = utils.full_path(svc, pathinfo['id'])
            print(pathname, "-" * (max(1, term_columns - len(pathname) - 1)))
            #pprint(pathinfo, width=term_columns)
            listdrive(svc,
                      recursive=True,
                      trashed=kwargs["trashed"],
                      parent=pathinfo["id"],
                      name=kwargs["name"])
示例#8
0
def dataset_to_pickle(file, data_set):
    '''Save the contents of 'data_set' to the compressed pickle file 'file'.
    The pickle is assumed to contain only one data structure.
    '''
    log = Logger().get_log()
    file = full_path(file)
    try:
        log.debug('saving data set to pickle file {}'.format(file))
        with gzip.open(file, 'wb') as pickle_file:
            pickle.dump(data_set, pickle_file)
    except IOError as err:
        log.error('encountered error trying to dump pickle {}'.format(file))
        log.error(err)
    except pickle.PickleError as err:
        log.error('pickling error for {}'.format(file))
        log.error(err)
示例#9
0
def main(db_dir):
    db_dir = utils.full_path(db_dir)
    db.init_db(db_dir)

    def run_exp(exp_fun, save_dir):
        exp_fun(os.path.join(db_dir, save_dir))

    # Execute experiments

    #run_exp(exp_step, "exp_step")
    #run_exp(exp_samplesize, "exp_samplesize")
    #run_exp(exp_straggle_perc, "exp_straggle_perc")
    #run_exp(exp_straggleness, "exp_straggleness")
    #run_exp(exp_straggle_accuracy, "exp_straggle_accuracy")
    #run_exp(exp_frontier, "exp_frontier")
    #run_exp(exp_ratio, "exp_ratio")
    run_exp(exp_regression, "exp_regression")
示例#10
0
def PortSupPlot(fld, clr, ttl):
    """builodw charts
    fld = field
    clr = colour
    ttl = title
    """
    UpCase = fld.title()
    df = u.run_sql_query(
        u.full_path('Ann_report_sql', '{} frequented.sql'.format(fld)),
        i.shared)

    def title(tr):
        return tr.title()

    df[fld] = df[fld].apply(title)
    df['combined'] = pd.concat([
        df['{} with count GT 10'.format(fld)].dropna(),
        df['{} with count LT 10'.format(fld)].dropna()
    ]).reindex_like(df)
    df = df.sort_values(['combined'], ascending=1)
    df = df.drop(
        ['{} with count GT 10'.format(fld), '{} with count LT 10'.format(fld)],
        axis=1)
    df = df.sort_values(by='combined', ascending=False)
    df = df.set_index(fld, drop=True)
    fig, ax = plt.subplots(figsize=(10, 3))
    df[:20].plot(kind='bar', color=clr, ax=ax, legend=False, alpha=0.75)
    ax.spines['bottom'].set_color(clr)
    ax.spines['left'].set_color(clr)
    ax.spines['top'].set_color('#ffffff')
    ax.spines['right'].set_color('#ffffff')
    ax.spines['left'].set_lw(0.5)
    ax.spines['bottom'].set_lw(0.5)
    ax.tick_params(axis='y', colors='#282f65', labelsize=10)
    ax.tick_params(axis='x', colors='#282f65', labelsize=10)
    ax.set_ylabel(ttl, color='#282f65')
    ax.set_xlabel('')
    plt.savefig('plots/{} Visited.png'.format(UpCase),
                bbox_inches='tight',
                transparent=True)
示例#11
0
@author: TAQDJO
"""

from pptx import Presentation
from pptx.util import Inches
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN
from pptx.util import Pt
import json
import utils as u
import input as i

c = i.shared['cl']
n = f'PPTPeriodicalTemplate {c}.pptx'
df = u.run_sql_query(
    u.full_path('Ann_report_sql', 'den_incidences_offspec.sql'), i.shared)

###########################

prs = Presentation(n)
slide = prs.slides[27]
shapes = slide.shapes
rows = len(df) + 1
cols = 10
left = Inches(0.7)
top = Inches(1.2)
width = Inches(2.0)
height = Inches(0.6)
table = shapes.add_table(rows, cols, left, top, width, height).table

#margin_top
示例#12
0
import utils as u
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import input as i

shared = i.shared

df = u.run_sql_query(u.full_path("Ann_report_sql", "KPI.sql"), shared)

df = df.dropna()


def ttl(a):
    return a.title()


df.port = df.port.apply(ttl)
df.client = df.client.apply(ttl)
df.collected_sampled = df.collected_sampled.astype('int')
df.received_collected = df.received_collected.astype('int')
df["sampled_to_lab"] = df.collected_sampled + df.received_collected
df_cl_filt = df[df.client.str.contains(shared['cl'], case=False)]
cl_name = df_cl_filt.client.unique()
df_cl = df_cl_filt.groupby('port')['collected_sampled',
                                   'received_collected'].mean().astype('int')
ax = df_cl.plot.bar(figsize=(20, 7),
                    color=['#00AB91', '#3B8EDE'],
                    edgecolor='white',
                    lw=2,
                    width=0.8)
示例#13
0
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import utils as u
import input as ii

mpl.rcParams.update(mpl.rcParamsDefault)
sns.set_style("white")
pd.options.mode.chained_assignment = None
pd.set_option("display.max_rows", 999)
pd.set_option("display.max_columns", 20)

# Grab and clean DF for Sample distribution
df = u.run_sql_query(u.full_path('Ann_report_sql', 'Fleet_general_info.sql'),
                     ii.shared)
df['Names'] = [
    'Total ships registered on FOBAS program: ', 'Total Samples\nSubmitted: ',
    'Bunker Drip\nSamples: ', 'Fuel Audit\nProgramme: ', '\nOthers: ',
    'Sample Bottle Kits Ordered: ', 'Average analysis turnaround time (lab): ',
    'Investigations: '
]
df = df.fillna(0)
df['count'] = df['count'].astype(int)
df = df.dropna()

df_plot = df.iloc[1:5]
df_plot = df_plot.sort_values(by='count', ascending=False)
new_labels = df_plot['Names'].tolist()
new_counts = df_plot['count'].tolist()
示例#14
0
from pptx.dml.color import RGBColor
from pptx.util import Pt
from pptx import Presentation
import utils as u
import json
import input as i

c = i.shared['cl']
n = f'PPTPeriodicalTemplate {c}.pptx'
df = u.run_sql_query(u.full_path('Ann_report_sql', 's_incidences_offspec.sql'),
                     i.shared)
prs = Presentation(n)
slide = prs.slides[24]
for shape in slide.shapes:
    if not shape.has_text_frame:
        continue
    text_frame = shape.text_frame

sl = df["Sulphur level"].str.contains("LOW")
sh = df["Sulphur level"].str.contains("HIGH")
if len(df) == 0:
    a = b = c = 'No samples have'
if len(sh) == 1:
    a = str(sh.sum()) + ' sample has'
if len(sh) > 1:
    a = str(sh.sum()) + ' samples have'
if len(sl) == 1:
    b = c = str(sl.sum()) + ' samples have'
if len(sl) > 1:
    b = c = str(sl.sum()) + ' samples have'
示例#15
0
from pptx.dml.color import RGBColor
from pptx.util import Pt
from pptx import Presentation
import utils as u
import json
import input as i

c = i.shared['cl']
n = f'PPTPeriodicalTemplate {c}.pptx'
df = u.run_sql_query(u.full_path('Ann_report_sql', 'iso_revision.sql'),
                     i.shared)


def slide_num(n, txt, pres):
    prs = Presentation(pres)
    slide = prs.slides[n]
    for shape in slide.shapes:
        if not shape.has_text_frame:
            continue
        text_frame = shape.text_frame
    a = df.iloc[0]['revision']
    p = text_frame.paragraphs[0]
    run = p.add_run()
    run.text = txt.format(str(a))
    font = run.font
    font.name = 'Source Sans Pro'
    font.size = Pt(16)
    font.bold = False
    font.italic = None  # cause value to be inherited from theme
    font.color.rgb = RGBColor(0xff, 0xff, 0xff)
    prs.save(pres)
示例#16
0
import utils as u
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.font_manager as font_manager
import pandas as pd
from math import pi
pd.options.mode.chained_assignment = None
pd.set_option("display.max_rows", 999)
pd.set_option("display.max_columns", 20)
date_from = '2018-01-01'
date_to = '2018-12-31'
user = '******'
client = "TSAKOS SHIPPING"
shared = {"df": date_from, "dt": date_to, "cl": client, "u": user}
df = u.run_sql_query(u.full_path("Ann_report_sql", "spider_plot.sql"), shared)
df = df.drop_duplicates(subset='id', keep='last').reset_index(drop=True)

df['TSP_Result'] = df['TSP_Result'].replace('> 25 mins', '0.3')


def clients_global_summary():
    vc = []
    dc = []
    df2 = df[~((df.id.duplicated(keep=False)) &
               (df.BDN == 'no'))].reset_index(drop=True)
    perc_red = 100 - (len(df2[df2['overall_lr_outcome'] == 'RED']) / len(df2)) * 100
    df_bdn = df2.groupby('BDN').count().reset_index(drop=False)
    df_bdn = df_bdn[['BDN', 'id']].T
    perc_bdn = (df_bdn.iloc[1, 1] / (df_bdn.iloc[1, 0] + df_bdn.iloc[1, 1])) * 100
    sample_count_hfo = len(df2[df2['material_type'] == 'HFO'])
示例#17
0
def check_for_boost(path):
    path = utils.full_path(path)
    for root, dirs, files in os.walk(path):
        if "program_options.hpp" in files:
            return os.path.dirname(os.path.dirname(root))
示例#18
0
文件: info.py 项目: amm042/GFileCmd
    parser.add_argument('fileId',
                        help='Name of file/folder id to list.')
    levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
    parser.add_argument('--log-level', default='DEBUG', choices=levels)

    args = parser.parse_args()

    logging.basicConfig(level=args.log_level,
                        format='%(asctime)s - %(name)s - [%(levelname)s] %(message)s')

    logging.debug("Got args: {}".format(args))
    logging.getLogger("googleapiclient").setLevel(logging.WARNING)
    logging.getLogger("googleapiclient.discovery_cache").setLevel(logging.ERROR)

    logger = logging.getLogger(__name__)

    svc = utils.get_gdrive_service(SCOPES=SCOPES)

    try:
        fileinfo = svc.files().get(
            fileId=args.fileId,
            fields="id, name, mimeType, size, parents, modifiedTime, trashed").execute()

        fileinfo['paths'] = utils.full_path(svc, fileinfo['id'])

        pprint(fileinfo, width=term_columns)
    except KeyboardInterrupt:
        logging.info("ctrl-c ABORT.")
    logging.info("End of main, exit.")
    exit(0)
示例#19
0
 def load_icon(self, icon_filename: str):
     self.q_icon = QtGui.QIcon(utils.full_path(_ICON_PATH + icon_filename))
示例#20
0
import matplotlib.pyplot as plt
import pandas as pd
import utils as u
import seaborn as sns
import input as i

df_global_status = u.run_sql_query(
    u.full_path('Ann_report_sql', 'gar_count_global.sql'), i.shared)
df_client_status = u.run_sql_query(
    u.full_path('Ann_report_sql', 'gar_count_client.sql'), i.shared)
print(df_global_status)
print(df_client_status)


def title(a_):
    return a_.title()


df_global_status.outcome = df_global_status.outcome.apply(title)
df_client_status.outcome = df_client_status.outcome.apply(title)
df_global_status['outcome'] = pd.Categorical(df_global_status['outcome'],
                                             ["Green", "Amber", "Red"])
df_global_status = df_global_status.sort_values(by=['outcome'])
df_client_status['outcome'] = pd.Categorical(df_client_status['outcome'],
                                             ["Green", "Amber", "Red"])
df_client_status = df_client_status.sort_values(by=['outcome'])
if len(df_client_status) < 3:
    df_client_status.loc[len(df_client_status)] = ['Red', 0]
try:
    df_global_status['Global'] = (df_global_status['count'] /
                                  df_global_status['count'].sum()) * 100
示例#21
0
文件: process.py 项目: jbradmil/CARP
def process(base_dir, signal_file, analysis_dir):
    signal_file = utils.full_path(signal_file)
    analysis_dir = utils.full_path(analysis_dir)

    models.initialize(analysis_dir)
示例#22
0
@author: dahan
"""

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import utils as u
import seaborn as sns
import sankey
import input as i

mpl.rcParams.update(mpl.rcParamsDefault)
sns.despine(left=True, bottom=True)
sns.set_style("dark")
df = u.run_sql_query(u.full_path('Ann_report_sql', 'port_suppliers_ frequented.sql'), i.shared)

def title(tr):
    return tr.title()


df['ship'] = df['ship'].apply(title)
df['supplier'] = df['supplier'].apply(title)
df = df.sort_values('ship')
port_unique = df.port.unique().tolist()
port_count = df.port.nunique()
supplier_unique = df.supplier.unique().tolist()
supplier_count = df.supplier.nunique()
ship_unique = df.ship.unique().tolist()
ship_count = df.ship.nunique()
示例#23
0
import matplotlib.pyplot as plt
import matplotlib as mpl
from itertools import groupby
import pandas as pd
import utils as u
import input as i

mpl.rcParams.update(mpl.rcParamsDefault)
pd.options.mode.chained_assignment = None
criteria = i.shared.values()

df_supplier_reasons = u.run_sql_query(
    u.full_path('Ann_report_sql', 'offSpecsPS.sql'), i.shared)
df_supplier_reasons = df_supplier_reasons.drop('port_name', axis=1)
df_supplier_reason = pd.melt(df_supplier_reasons,
                             id_vars=["supplier_name"],
                             var_name="test_name",
                             value_name="t_value")
df_supplier_reason['t_value'] = df_supplier_reason['t_value'].astype(int)
df_supplier_reason = df_supplier_reason[df_supplier_reason.t_value > 0]
df_supplier_reason_a = df_supplier_reason[
    df_supplier_reason.test_name.str.contains('_a')]
df_supplier_reason_a = df_supplier_reason_a.sort_values(by=['supplier_name'])
df_supplier_reason_r = df_supplier_reason[
    df_supplier_reason.test_name.str.contains('_r')]
df_supplier_reason_r = df_supplier_reason_r.sort_values(by=['supplier_name'])


def plot_status(status, col, trm, name):
    df = status
    df['test_name'] = df['test_name'].str.replace('_a', '')
示例#24
0
@author: TAQDJO
"""
import json
import pandas as pd
import seaborn as sns
import utils as u
import matplotlib.pyplot as plt
import matplotlib as mpl
import input as i

mpl.rcParams.update(mpl.rcParamsDefault)
sns.despine(left=True, bottom=True)
sns.set_style("dark")
df_Ps = u.run_sql_query(
    u.full_path('Ann_report_sql', 'port_suppliers_ frequented.sql'), i.shared)


def PortSupPlot(fld, clr, ttl):
    """builodw charts
    fld = field
    clr = colour
    ttl = title
    """
    UpCase = fld.title()
    df = u.run_sql_query(
        u.full_path('Ann_report_sql', '{} frequented.sql'.format(fld)),
        i.shared)

    def title(tr):
        return tr.title()
示例#25
0
 def __init__(self, icon_filename: str):
     self.q_pixmap: QtGui.QPixmap = QtGui.QPixmap(utils.full_path(_ICON_PATH + icon_filename))
     self.q_label: widgets.XLabel = widgets.XLabel()
     self.q_label.setPixmap(self.q_pixmap)
示例#26
0
                    default="")
parser.add_argument("--scale-icons",
                    dest="scale_icons",
                    action="store_true",
                    help="scale icons if the notifier doesn't do it for us",
                    default=False)


if __name__ == '__main__':
    args = parser.parse_args()

    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)

    if args.album_art:
        args.album_art = full_path(args.album_art)

    icon_path = full_path(args.icon_path)

    try:
        logging.info("Loading icon from %s...", icon_path)
        growl_icon = load_image(icon_path, args.scale_icons)
        logging.debug("Icon loaded.")
    except:
        logging.exception("Failed to load icon, falling back to default.")
        growl_icon = None

    client = mpd.MPDClient()

    while True:
        try:
示例#27
0
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
import utils as u
import input as i

mpl.rcParams.update(mpl.rcParamsDefault)
pd.options.mode.chained_assignment = None
pd.set_option("display.max_rows", 999)
pd.set_option("display.max_columns", 20)

# get input for queries

criteria = list(i.shared.values())

df = u.run_sql_query(u.full_path('Ann_report_sql', 'loaded_quan_diff.sql'),
                     i.shared)
df2 = df[[
    'ship', 'adv_density', 'TESTED_DEN', 'bunker_quantity', 'material_type'
]]
df2 = df2.dropna()
df2['adv_density'] = pd.to_numeric(df2['adv_density'], errors='coerce')
df2['TESTED_DEN'] = pd.to_numeric(df2['TESTED_DEN'], errors='coerce')
df2['bunker_quantity'] = pd.to_numeric(df2['bunker_quantity'], errors='coerce')
df2['quan_diff'] = (df2['TESTED_DEN'] - df2['adv_density']) \
 * df2['bunker_quantity']
df3 = df2[['ship', 'bunker_quantity', 'quan_diff', 'material_type']]
df3['sample'] = 1

# Tidy up supplier text)
示例#28
0
def fuel_type(fl, color_):
    """doc"""
    i.shared.update({'fuel': fl})
    criteria = list(i.shared.values())

    df = u.run_sql_query(u.full_path('Ann_report_sql', 'offSpecsPeriodic.sql'), i.shared)

    for col in df.columns:
        if df[col].dtype == 'int64' and col[-1] == 'a':
            df = df.drop(col, axis=1)

    df2 = df.sum()
    df3 = df2[df2 != 0]
    df4 = pd.DataFrame(df3)
    df4 = df4.reset_index()
    df4.columns = ['test', 'count']
    df4['count'] = df4['count'].astype(float)

    def truncy(s):
        """doc"""
        if s is not None:
            return s[:len(s)-9]

    df4.test = df4.test.apply(truncy)
    df4['perc'] = ((df4['count'] / df4['count'].sum()) * 100).round(2)
    df4['labels'] = df4.test.str.cat(df4['perc'].astype(str), sep='\n')
    df4 = df4.sort_values(by='count').reset_index(drop=True)
    df4['counts'] = np.arange(1, max(df4.index)+2)

    plt.figure(figsize=(5, 5))
    ax = plt.axes([0.025, 0.025, 1, 1], polar=True)
    theta = df4.test
    theta = np.linspace(0.0, 2*np.pi, len(df4.test), endpoint=False)
    theta3 = np.linspace(0, np.pi)
    radii = df4['count']
    width = np.pi/(len(df4)/2)
    bars = plt.bar(theta, radii, width=width, bottom=0)
    radii2 = 10 * np.arange(0, len(df4), 1)
    for r, bars in zip(radii2, bars):
        bars.set_facecolor(cm.binary(r / (len(df4)*10.)))
        bars.set_alpha(0.8)

    ax.set_ylim(0, max(df4['count']))
    ax.set_yticklabels([])
    ax.set_xlim(0, len(theta3)+0.262)
    ax.spines['polar'].set_visible(False)
    print(criteria)
    if criteria[4] == 1:
        ax.set_title('Global off specification characteristics\nHFO percentage'
                     , color='#282f65', size=12)
    else:
        ax.set_title('Global off specification characteristics\nMGO percentage'
                     , color='#282f65', size=12)
    t = ax.title
    t.set_position([.5, 1.15])

    ax.set_xticklabels(df4['labels'], color=color_, fontsize=8)
    ax.patch.set_facecolor(color_)
    ax.patch.set_alpha(0.25)
    ax.set_xticks(np.pi/180 * np.linspace(-360, -360/len(df4.index), 
                                          len(df4.index)))
    ax.set_theta_offset(360 + len(df4) / 100)
    ax.yaxis.grid(False)
    plt.savefig('plots/PPTOffSpecPerc{}.png'.format(fl)
                , bbox_inches='tight', dpi=200)
    plt.show()
示例#29
0
                    " when available",
                    default="")
parser.add_argument("--scale-icons",
                    dest="scale_icons",
                    action="store_true",
                    help="scale icons if the notifier doesn't do it for us",
                    default=False)

if __name__ == '__main__':
    args = parser.parse_args()

    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)

    if args.album_art:
        args.album_art = full_path(args.album_art)

    icon_path = full_path(args.icon_path)

    try:
        logging.info("Loading icon from %s...", icon_path)
        growl_icon = load_image(icon_path, args.scale_icons)
        logging.debug("Icon loaded.")
    except:
        logging.exception("Failed to load icon, falling back to default.")
        growl_icon = None

    client = mpd.MPDClient()

    while True:
        try:
示例#30
0
import os
os.system("pip install numpy pandas matplotlib==2.2.3 seaborn python-pptx")

# https://stackoverflow.com/questions/43697460/import-matplotlib-failing-on-heroku
# force matplotlib to NOT use TK, since that has dependency issues
import matplotlib
matplotlib.use('Agg')

import json
import utils as u
import dsl
import os
import input as i

# do this here?
df = u.run_sql_query(u.full_path("Ann_report_sql", "Fleet_general_info.sql"),
                     i.shared)
df.to_csv('plots/genInf.csv')

import PPTALSIBox
import PPTPortSupVisited
import PPTstar_burst_charts
import PPTsummAnalysisQuan
import PPTtwincat
import glbl_clnt_side_by_side
import PPTGenDet
try:
    import PPTPortSupplier
except:
    pass
import alsi_gt_40_plot