<commit_before>'''
Currently empty should contain the plotting tools portion of the
analysis toolbox
'''
import matplotlib.pyplot as plt
import matplotlib
from matplotlib import cm
import numpy as np


def set_xlabel(axis, label, unit=None, **kw):
    """
    Takes in an axis object and add a unit aware label to it.

    Args:
        axis: matplotlib axis object to set label on
        label: the desired label
        unit:  the unit
        **kw : keyword argument to be passed to matplotlib.set_xlabel

    """
    if unit is not None and unit != '':
        xticks = axis.get_xticks()
        scale_factor, unit = SI_prefix_and_scale_factor(
            val=max(abs(xticks)), unit=unit)
        formatter = matplotlib.ticker.FuncFormatter(
            lambda x, pos: round(x*scale_factor, ndigits=3))

        axis.xaxis.set_major_formatter(formatter)

        axis.set_xlabel(label+' ({})'.format(unit), **kw)
    else:
        axis.set_xlabel(label, **kw)
    return axis


def set_ylabel(axis, label, unit=None, **kw):
    """
    Takes in an axis object and add a unit aware label to it.

    Args:
        axis: matplotlib axis object to set label on
        label: the desired label
        unit:  the unit
        **kw : keyword argument to be passed to matplotlib.set_ylabel

    """
    if unit is not None and unit != '':
        yticks = axis.get_yticks()
        scale_factor, unit = SI_prefix_and_scale_factor(
            val=max(abs(yticks)), unit=unit)
        formatter = matplotlib.ticker.FuncFormatter(
            lambda x, pos: round(x*scale_factor, ndigits=3))

        axis.yaxis.set_major_formatter(formatter)

        axis.set_ylabel(label+' ({})'.format(unit), **kw)
    else:
        axis.set_ylabel(label, **kw)
    return axis



SI_PREFIXES_2 = dict(zip(range(-24, 25, 3), 'yzafpnμm kMGTPEZY'))
SI_PREFIXES_2[0] = ""
#SI_PREFIXES = 'yzafpnμm kMGTPEZY'

SI_UNITS = 'm,s,g,W,J,V,A,F,T,Hz,Ohm,S,N,C,px,b,B,K,Bar,Vpeak,Vpp,Vp,Vrms'.split(',')

def SI_prefix_and_scale_factor(val, unit=None):
    """
    Takes in a value and unit and if applicable returns the proper
    scale factor and SI prefix.
    Args:
        val (float) : the value
        unit (str)  : the unit of the value
    returns:
        scale_factor (float) : scale_factor needed to convert value
        unit (str)           : unit including the prefix
    """

    if unit in SI_UNITS:
        try:
            with np.errstate(all="ignore"):
                prefix_power = np.log10(abs(val))//3 * 3
            return 10 ** -prefix_power, SI_PREFIXES_2[prefix_power] + unit 
        except (KeyError, TypeError):
            pass

    return 1, unit if unit is not None else ""

    validtypes = (float, int, np.integer, np.floating)
    if unit in SI_UNITS and isinstance(val, validtypes):
        if val == 0:
            prefix_power = 0
        else:
            # The defined prefixes go down to -24 but this is below
            # the numerical precision of python
            prefix_power = np.clip(-15, (np.log10(abs(val))//3 * 3), 24)
        # Determine SI prefix, number 8 corresponds to no prefix
        SI_prefix_idx = int(prefix_power/3 + 8)
        prefix = SI_PREFIXES[SI_prefix_idx]
        # Convert the unit
        scale_factor = 10**-prefix_power
        unit = prefix+unit
    else:
        scale_factor = 1

    if unit is None:
        unit = ''  # to ensure proper return value
    return scale_factor, unit


def SI_val_to_msg_str(val: float, unit: str=None, return_type=str):
    """
    Takes in a value  with optional unit and returns a string tuple consisting
    of (value_str, unit) where the value and unit are rescaled according to
    SI prefixes, IF the unit is an SI unit (according to the comprehensive list 
    of SI units in this file ;).

    the value_str is of the type specified in return_type (str) by default.
    """
    
    sc, new_unit = SI_prefix_and_scale_factor(val, unit)
    try:
        new_val = sc*val
    except TypeError:
        return return_type(val), unit

    return return_type(new_val), new_unit 


def data_to_table_png(data: list, filename: str, title: str='',
                      close_fig: bool=True):
    """
    Takes in a list of list containing the data to be
    put in a table and saves this as a png.<commit_msg>Fixed build error and removed previous code that is replaced what is the currently implemented<commit_after>'''
Currently empty should contain the plotting tools portion of the
analysis toolbox
'''
import matplotlib.pyplot as plt
import matplotlib
from matplotlib import cm
import numpy as np


def set_xlabel(axis, label, unit=None, **kw):
    """
    Takes in an axis object and add a unit aware label to it.

    Args:
        axis: matplotlib axis object to set label on
        label: the desired label
        unit:  the unit
        **kw : keyword argument to be passed to matplotlib.set_xlabel

    """
    if unit is not None and unit != '':
        xticks = axis.get_xticks()
        scale_factor, unit = SI_prefix_and_scale_factor(
            val=max(abs(xticks)), unit=unit)
        formatter = matplotlib.ticker.FuncFormatter(
            lambda x, pos: round(x*scale_factor, ndigits=3))

        axis.xaxis.set_major_formatter(formatter)

        axis.set_xlabel(label+' ({})'.format(unit), **kw)
    else:
        axis.set_xlabel(label, **kw)
    return axis


def set_ylabel(axis, label, unit=None, **kw):
    """
    Takes in an axis object and add a unit aware label to it.

    Args:
        axis: matplotlib axis object to set label on
        label: the desired label
        unit:  the unit
        **kw : keyword argument to be passed to matplotlib.set_ylabel

    """
    if unit is not None and unit != '':
        yticks = axis.get_yticks()
        scale_factor, unit = SI_prefix_and_scale_factor(
            val=max(abs(yticks)), unit=unit)
        formatter = matplotlib.ticker.FuncFormatter(
            lambda x, pos: round(x*scale_factor, ndigits=3))

        axis.yaxis.set_major_formatter(formatter)

        axis.set_ylabel(label+' ({})'.format(unit), **kw)
    else:
        axis.set_ylabel(label, **kw)
    return axis



SI_PREFIXES_2 = dict(zip(range(-24, 25, 3), 'yzafpnμm kMGTPEZY'))
# SI_PREFIXES_2[0] = ""
#SI_PREFIXES = 'yzafpnμm kMGTPEZY'

SI_UNITS = 'm,s,g,W,J,V,A,F,T,Hz,Ohm,S,N,C,px,b,B,K,Bar,Vpeak,Vpp,Vp,Vrms'.split(',')

def SI_prefix_and_scale_factor(val, unit=None):
    """
    Takes in a value and unit and if applicable returns the proper
    scale factor and SI prefix.
    Args:
        val (float) : the value
        unit (str)  : the unit of the value
    returns:
        scale_factor (float) : scale_factor needed to convert value
        unit (str)           : unit including the prefix
    """

    if unit in SI_UNITS:
        try:
            with np.errstate(all="ignore"):
                prefix_power = np.log10(abs(val))//3 * 3
            return 10 ** -prefix_power, SI_PREFIXES_2[prefix_power] + unit 
        except (KeyError, TypeError):
            pass

    return 1, unit if unit is not None else ""


def SI_val_to_msg_str(val: float, unit: str=None, return_type=str):
    """
    Takes in a value  with optional unit and returns a string tuple consisting
    of (value_str, unit) where the value and unit are rescaled according to
    SI prefixes, IF the unit is an SI unit (according to the comprehensive list 
    of SI units in this file ;).

    the value_str is of the type specified in return_type (str) by default.
    """
    
    sc, new_unit = SI_prefix_and_scale_factor(val, unit)
    try:
        new_val = sc*val
    except TypeError:
        return return_type(val), unit

    return return_type(new_val), new_unit 


def data_to_table_png(data: list, filename: str, title: str='',
                      close_fig: bool=True):
    """
    Takes in a list of list containing the data to be
    put in a table and saves this as a png.
{'fraction_non_alphanumeric': 0.09524410243471679, 'fraction_numerical': 0.006812160968840671, 'mean_word_length': 2.5792325056433407, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '344163', 'n_tokens_mistral': 2582, 'n_tokens_neox': 2474, 'n_words': 819}