Best Python code snippet using hypothesis
manage_output.py
Source:manage_output.py  
1""" Functions to plot the graphs and handle the html """2import os3import glob4import zlib5import matplotlib6matplotlib.use("Agg")7import matplotlib.pyplot as plt8import seaborn as sns9from constants import IMAGES10import sort_regions11sort_functions = {12    "pca": sort_regions.sort_by_pca,13    "pop_density": sort_regions.sort_by_pop_density,14    "distance": sort_regions.sort_by_distance,15    "distance_initials": sort_regions.sort_by_distance_initials,16    "correlation": sort_regions.sort_by_correlation,17    "random": sort_regions.sort_by_random,18    "kmeans": sort_regions.sort_by_kmeans,19    "alphabetical": sort_regions.sort_by_alphabetical,20}21########################################################################################################################22# Functions used to handle the plots23########################################################################################################################24def plot_graphs(pivot_regs, log_pivot_regs, suptitle, regions):25    """Plots two graphs: raw values and transformed values.26    Saves graphs to a file27    Args:28        pivot_regs (pandas.DataFrame): raw data29        log_pivot_regs (pandas.DataFrame): transformed values30        suptitle (str): title of the graph31        regions (list of str): regions to plot32    Returns:33        None34    """35    filename = get_filename_from_regions(36        regions37    )  # Filenames are a function of the selected region38    fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 12))39    fig.suptitle(suptitle)40    ax1.plot(pivot_regs)41    ax1.legend(pivot_regs.columns.values, loc="upper left")42    ax1.set_title("VALORI ASSOLUTI NUOVI CONTAGI")43    ax1.grid(True)44    ax2.plot(log_pivot_regs)45    ax2.legend(log_pivot_regs.columns.values, loc="upper left")46    ax2.set_title("VALORI TRASFORMATI (proporzionali agli abitanti, scala log)")47    ax2.grid(True)48    fig.autofmt_xdate(rotation=-45, ha="left")49    fig.savefig(os.path.join(IMAGES, filename))  # TODO path50def delete_images():51    """Deletes all image files of the day.52    Used by the scheduler.53    """54    files = glob.glob(IMAGES + "/*")55    for f in files:56        print(f)57        os.remove(f)58def build_heatmap(log_pivot_regs, how):59    """Builds a heatmap. Regions are sorted.60    Args:61        log_pivot_regs (pandas.DataFrame): Rransformed values.62        how: A sorting algorithm among those listed in sort_functions dictionary63    """64    log_pivot_regs = log_pivot_regs.copy()65    # Sort region names according to a selected function66    ordered_list = sort_functions[how](log_pivot_regs.dropna())67    log_pivot_regs.index = log_pivot_regs.index.strftime("%Y-%m-%d")68    select_log_pivot_regs = log_pivot_regs69    trans_log_pivot_regs = select_log_pivot_regs.T70    logs_ordered_by_dens = trans_log_pivot_regs.reindex(ordered_list)71    sns.heatmap(logs_ordered_by_dens, cmap="RdYlGn_r")72    plt.xlabel("Nuovi contagi giornalieri (log)")73    plt.ylabel(f"Regioni ordinate: {how}")74    plt.title("Heatmap", size=14)75    plt.tight_layout()76    filename = os.path.join(IMAGES, f"heatmap_{how}.jpg")77    plt.savefig(filename)78    plt.close()79########################################################################################################################80# Functions used to handle the html81########################################################################################################################82# Load the main web page83def get_template():84    """Returns the template for the web page.85    Returns:86        (str, str): template html, page css87    """88    with open("form_img_template.html", "r") as f:89        html_template = f.read()90    with open("form_img_template.css", "r") as f:91        css_template = f.read()92    return html_template, css_template93def get_full_page(94    html_template,95    css_template,96    plot_html="",97    error_message="",98    reg_options="",99    heatmap_html=''100):101    """Returns a web page, complete with plot area and region names.102    Args:103        html_template (str): html code for the webpage104        css_template (str): css for the webpage105        plot_html (str): html for the plot image106        error_message (str): html to show in case the input were wrong107        reg_options (str): html for the options of the multi choice box108        heatmap_html (str): html for the heatmap image109    Returns:110        str: the complete web page111    """112    web_page = html_template.format(113        css=css_template,114        plot_html=plot_html,115        error_message=error_message,116        reg_options=reg_options,117        heatmap_html=heatmap_html,118    )119    return web_page120def get_plot_html(filename, regions):121    """Returns the html img tag for the chosen regions.122    Args:123        filename (str): Name of the plot image.124        regions (list of str): Regions to plot.125    Returns:126        str: Html for the plot image.127    """128    html_code = f'<img src="/static/{filename}" alt="{regions}" id="plot-img">'129    return html_code.format(filename=filename, regions=regions)130def get_heatmap_html(filename):131    """Returns the html img tag for the chosen regions.132    Args:133        filename (str): Name of the plot image.134    Returns:135        str: Html for the plot image.136    """137    html_code = f'<img src="/static/{filename}" alt="heatmap" id="heatmap-img">'138    return html_code.format(filename=filename)139def incorrect_input_message():140    """Adds an error message to the page.141    Returns:142        str: html to show in case the input were wrong143    """144    html_code = "<br><p>The value is incorrect. Please enter a valid sequence of region codes</p><br>"145    return html_code146def get_reg_options(regions, pop):147    """Builds the options of a multi choice box148    Args:149        pop: regions-population150        regions: the (possibly default) regions to pre-select151    Returns:152        str: html for the options of the multi choice box153    """154    option_template = '<option value="{name}"{selected}>{name}</option>'155    option_list = []156    selected = " selected"157    for name in pop.index:158        activate_selected = name in regions159        new_option = option_template.format(160            name=name, selected=selected * activate_selected161        )162        option_list.append(new_option)163    html_code = "\n".join(option_list)164    return html_code165def get_filename_from_regions(regions):166    """Returns a filename for the plot.167    The file name is a hash of the input strings.168    Args:169        regions (list of str): the selected regions170    Returns:171        str: the file name for the chosen inputs172    """173    filename_checksum = zlib.adler32("".join(regions).encode("utf-8"))174    filename = str(filename_checksum) + ".png"...drawViolin.py
Source:drawViolin.py  
...45    writer.writeheader()46    for row in content:47        writer.writerow(row)48    f.close()49    def sort_regions(regions, ADD_new_regions, nADD_new_regions):50        rank = []51        for r in regions:52            value = np.var(np.concatenate((ADD_new_regions[r], nADD_new_regions[r])))53            rank.append((r, value))54        rank.sort(key=lambda x:x[1])55        return [a[0] for a in rank][::-1]56    TL = ['TL hippocampus', 'TL posterior temporal lobe', 'TL amygdala', 'TL anterior temporal lobe medial part', 'TL anterior temporal lobe lateral part',57          'TL parahippocampal and ambient gyrus', 'TL superior temporal gyrus middle part', 'TL middle and inferior temporal gyrus',58          'TL fusiform gyrus', 'TL superior temporal gyrus anterior part']59    TL = sort_regions(TL, ADD_new_regions, nADD_new_regions)60    FL = ['FL straight gyrus', 'FL anterior orbital gyrus', 'FL inferior frontal gyrus', 'FL precentral gyrus',61          'FL superior frontal gyrus', 'FL lateral orbital gyrus', 'FL posterior orbital gyrus','FL subcallosal area',62          'FL pre-subgenual frontal cortex', 'FL middle frontal gyrus', 'FL medial orbital gyrus','FL subgenual frontal cortex']63    FL = sort_regions(FL, ADD_new_regions, nADD_new_regions)64    PL = ['PL angular gyrus','PL postcentral gyrus','PL superior parietal gyrus','PL supramarginal gyrus']65    PL = sort_regions(PL, ADD_new_regions, nADD_new_regions)66    OL = ['OL lingual gyrus', 'OL cuneus','OL lateral remainder occipital lobe']67    OL = sort_regions(OL, ADD_new_regions, nADD_new_regions)68    insula = ['insula anterior short gyrus', 'insula middle short gyrus', 'insula posterior short gyrus', 'insula anterior inferior cortex',69              'insula anterior long gyrus', 'insula posterior long gyrus']70    insula = sort_regions(insula, ADD_new_regions, nADD_new_regions)71    ventricle = ['Lateral ventricle excluding temporal horn', 'Lateral ventricle temporal horn', 'Third ventricle']72    ventricle = sort_regions(ventricle, ADD_new_regions, nADD_new_regions)73    other = ['cerebellum', 'brainstem excluding substantia nigra', 'substantia nigra', 'CG anterior cingulate gyrus', 'CG posterior cingulate gyrus',74              'caudate nucleus', 'nucleus accumbens', 'putamen', 'thalamus', 'pallidum', 'corpus callosum']75    other = sort_regions(other, ADD_new_regions, nADD_new_regions)76    orders = TL + FL + PL + OL + ventricle + other + insula77    assert(len(orders) == len(list(ADD_new_regions.keys())))78    orders = [abbre(a) for a in orders]79    print(orders)80    from matplotlib import rc, rcParams81    rc('axes', linewidth=1)82    rc('font', weight='bold', size=10)83    sns.set_style("darkgrid", rc={"axes.facecolor": "#f7f7f7"})84    df = pd.read_csv('violin_shap.csv')85    fig, ax = plt.subplots(dpi=300, figsize=(20, 5))86    for i in range(49):87        plt.plot((i, i), (-0.1, 0.1), color='#e4d1ff', linestyle='dashed', linewidth=1, zorder=0)88    ax1 = sns.violinplot(data=df, x="region", y="shap", hue="Group", cut=0, order=orders, legend=False,89                   split=True, inner="quart", linewidth=1, palette={'nADD': "#42c5f5", 'AD': "#f54242"})...plot_lda_block_vs_stim.py
Source:plot_lda_block_vs_stim.py  
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3"""4Created on Thu Sep 30 15:19:11 20215By: Guido Meijer6"""7import pandas as pd8import numpy as np9import matplotlib.pyplot as plt10import seaborn as sns11from os.path import join12import matplotlib13from mpl_toolkits.axes_grid1 import make_axes_locatable14from serotonin_functions import paths, get_full_region_name, figure_style15# Settings16COLORMAP = 'seagreen'17_, fig_path, save_path = paths()18PRE_TIME = 019POST_TIME = 0.320MIN_IMPROVEMENT = 521# Load in results22decoding_block = pd.read_csv(join(save_path, f'lda_decoding_block_{PRE_TIME}_{POST_TIME}.csv'))23decoding_stim = pd.read_csv(join(save_path, f'lda_decoding_stim_{PRE_TIME}_{POST_TIME}.csv'))24# Calculate delta25decoding_block['delta_block'] = (decoding_block['acc_block_on'] - decoding_block['acc_block_off']) * 10026decoding_stim['delta_block'] = (decoding_stim['acc_block_on'] - decoding_stim['acc_block_off']) * 10027# Get full region names28decoding_result['full_region'] = get_full_region_name(decoding_result['region'])29# Exclude root30decoding_result = decoding_result.reset_index(drop=True)31incl_regions = [i for i, j in enumerate(decoding_result['region']) if not j.islower()]32decoding_result = decoding_result.loc[incl_regions]33# Calculate average decoding performance per region34for i, region in enumerate(decoding_result['region'].unique()):35    decoding_result.loc[decoding_result['region'] == region, 'mean'] = decoding_result.loc[decoding_result['region'] == region, 'delta_block'].mean()36    decoding_result.loc[decoding_result['region'] == region, 'n_rec'] = np.sum(decoding_result['region'] == region)37# Apply selection38decoding_result = decoding_result[decoding_result['mean'].abs() >= MIN_IMPROVEMENT]39#Create a matplotlib colormap40cmap = sns.light_palette(COLORMAP, reverse=True, as_cmap=True)41norm = matplotlib.colors.Normalize(vmin=decoding_result['p_value'].min(), vmax=decoding_result['p_value'].max())42colors = {}43for cval in decoding_result['p_value']:44    colors.update({cval : cmap(norm(cval))})45# Plot46_, dpi = figure_style()47f, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), dpi=dpi)48decoding_sert = decoding_result[decoding_result['sert-cre'] == 1]49sort_regions = decoding_sert.groupby('full_region').max().sort_values('mean', ascending=False).reset_index()['full_region']50sns.barplot(x='mean', y='full_region', data=decoding_sert, order=sort_regions,51            ci=68, facecolor=(1, 1, 1, 0), errcolor=".2", edgecolor=".2", ax=ax1)52sns.swarmplot(x='delta_block', y='full_region', data=decoding_sert, hue='p_value', palette=colors,53              order=sort_regions, ax=ax1)54ax1.legend_.remove()55divider = make_axes_locatable(plt.gca())56ax_cb = divider.new_horizontal(size="5%", pad=0.05)57f.add_axes(ax_cb)58cb1 = matplotlib.colorbar.ColorbarBase(ax_cb, cmap=cmap, norm=norm, orientation='vertical')59cb1.set_label('p-value', rotation=90)60ax1.set(xlabel='Stimulation induced decoding improvement of prior (% correct)', ylabel='', xlim=[-30, 30])61"""62decoding_wt = decoding_result[decoding_result['sert-cre'] == 0]63sort_regions = decoding_wt.groupby('full_region').max().sort_values('mean', ascending=False).reset_index()['full_region']64sns.barplot(x='mean', y='full_region', data=decoding_wt, order=sort_regions,65            ci=68, facecolor=(1, 1, 1, 0), errcolor=".2", edgecolor=".2", ax=ax2)66sns.swarmplot(x='delta_block', y='full_region', data=decoding_wt, order=sort_regions, ax=ax1)67ax2.set(xlabel='Stimulation induced decoding improvement of prior (% correct)', ylabel='', xlim=[-25, 25])68"""69plt.tight_layout(pad=2)70sns.despine(trim=True)71plt.savefig(join(fig_path, 'Ephys', 'LDA', f'lda_opto_improvement_{TARGET}_{PRE_TIME}_{POST_TIME}.png'))...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
