A utility class to get the size of the terminal window. This class provides
methods to obtain the terminal size across different platforms, ensuring
compatibility and providing a fallback size when necessary.
Variables:
DEFAULT_SIZE (tuple) – A default terminal size to fallback to when the actual terminal size
cannot be determined. The default is (80, 20).
Get the terminal size for Unix-like platforms using ioctl syscall.
Notes
The get_terminal_size method first tries to use shutil.get_terminal_size
with a fallback to DEFAULT_SIZE. If that fails, it checks the operating
system and attempts to use platform-specific methods. On Windows, it uses
the ctypes library to query the terminal size. On Unix-like systems, it
uses the ioctl syscall.
ValueError – If the precision is not a non-negative number or cannot be
converted to a non-negative integer.
Examples
>>> validate_precision(3)3>>> validate_precision(3.0)3>>> validate_precision(np.int32(2))2>>> validate_precision(np.float64(2.0))2>>> validate_precision(-1)Traceback (most recent call last):...ValueError: Precision must be a non-negative integer.>>> validate_precision('three')Traceback (most recent call last):...ValueError: Precision must be a non-negative integer.
A list where each tuple contains (‘pc{i}’, feature_names,
sorted_component_values),
corresponding to each principal component. ‘pc{i}’ is a string label
like ‘pc1’, ‘feature_names’ is an array of feature names sorted by
their importance, and ‘sorted_component_values’ are the corresponding
sorted values of component loadings.
kind (str) – A string that identifies the principal component number to extract,
e.g., ‘pc1’. The string should contain a numeric part that corresponds
to the component index in pc_list.
Returns:
A tuple containing two elements:
- An array of feature names for the specified principal component.
- An array of sorted component values for the specified principal
ValueError – If the kind parameter does not contain a valid component number or if the
specified component number is out of the range of available components
in pc_list.
The function requires that the kind parameter include a numeric value
that accurately represents a valid index in pc_list. The index is derived
from the numeric part of the kind string and is expected to be 1-based.
If no valid index is found or if the index is out of range, the function
raises a ValueError.
Calculates the maximum width of tables in a summary string based on header lines.
This function parses a multi-table summary string, identifying lines that represent
the top or bottom borders of tables (header lines). It determines the maximum width
of these tables by measuring the length of these header lines. The function assumes
that the header lines consist of repeated instances of a specific marker character.
Parameters:
summary_contents (str) – A string containing the summarized representation of one or more tables.
This string should include header lines made up of repeated header markers
that denote the start and end of each table’s border.
header_marker (str, optional) – The character used to construct the header lines in the summary_contents.
Defaults to ‘=’, the common character for denoting table borders in ASCII
table representations.
Returns:
The maximum width of the tables found in summary_contents, measured as the
length of the longest header line. If no header lines are found, returns 0.
This example shows how the function can be used to find the maximum table width
in a string containing summaries of model performances, where ‘=’ is used as
the header marker.
Formats a block of text to fit within a specified maximum character width,
optionally prefixing it with a key. If the text exceeds the maximum width,
it wraps to a new line, aligning with the key or the specified indentation.
key (str, optional) – An optional key to prefix the text. Defaults to None.
key_length (int, optional) – The length reserved for the key, including following spaces.
If key is provided but key_length is None, the length of the
key plus one space is used. Defaults to 15.
max_char_text (int, optional) – The maximum number of characters for the text width, including the key
if present. Defaults to 50.
add_frame_lines (bool, False) – If True, frame the text with ‘=’ line (top and bottom)
border_line (str, optional) – The border line to frame the text. Default is ‘=’
buffer_space (int, default=4) – The extra space to force breaken the text. Using a large value will
provide nice reading and force terminating the line sentence with no
preprosition like a, ‘of’ or the etc.
Returns:
The formatted text with line breaks added to ensure that no line exceeds
max_char_text characters. If a key is provided, it is included only
on the first line, with subsequent lines aligned accordingly.
>>> fromfusionlab.api.utilimportformat_text>>> text_example=("This is an example text that is supposed to wrap" "around after a certain number of characters.")>>> print(format_text(text_example,key="Note"))Note : This is an example text that is supposed to wrap around after a certain number of characters.
Notes
The function dynamically adjusts the text to fit within max_char_text,
taking into account the length of key if provided.
Text that exceeds the max_char_text limit is wrapped to new lines, with
proper alignment to match the initial line’s formatting.
Truncates a string to the maximum specified length and appends ‘…’
if needed, and right-aligns it.
Parameters:
x (str): The string to format.
max_width (int): The width to which the string should be aligned.
max_text_length (int): The maximum allowed length of the string before truncation.
Calculate the maximum table width from the given formatted string based on
the border style.
formatted_strstr
The string containing the formatted table.
border_charstr, optional
The character used for the table border. Default is ‘=’.
check_firstbool, optional
If True, check the width of the first border line found and return it.
If False, check for additional border lines if the first one is found.
Default is True.
deep_checkbool, optional
If True, evaluate all lines containing the border character to determine
the table width. If False, follow the check_first strategy. Default is
True.
width_strategy{‘max’, ‘min’, ‘average’}, optional
Strategy to determine the table width if deep_check is True. ‘max’
returns the longest border line. ‘min’ returns the shortest border line.
‘average’ returns the average width of all border lines. Default is ‘max’.
error{‘warn’, ‘raise’, ‘ignore’}, optional
How to handle cases where no border line is found. ‘warn’ logs a warning
message. ‘raise’ raises an exception. ‘ignore’ does nothing and returns
None. Default is ‘warn’.
int or None
The calculated table width, or None if no border line is found and error
handling is set to ‘ignore’.
This function identifies lines in the formatted_str containing the
border_char and calculates the width of the table based on the specified
strategies and checks.
The calculation follows these steps:
Identify lines in formatted_str containing border_char.
If no such lines are found, handle the error based on error parameter.
If deep_check is False:
If check_first is True, return the length of the first border line.
Otherwise, return the length of the last border line.
If deep_check is True:
Compute the lengths of all border lines.
If width_strategy is ‘average’, return the average length of border
lines:
\[ext{average\_width} =\]
rac{sum_{i=1}^{n} ext{length}_i}{n}
If width_strategy is ‘min’, return the minimum length of border lines.
If width_strategy is ‘max’, return the maximum length of border lines.
Generates a legend for a table (dataframe) matrix visualization, formatted
according to specified parameters.
This function supports both numeric and symbolic representations of table
values. Symbolic representations, which are used primarily for visual clarity,
include the following symbols:
'++': Represents a strong positive relationship.
'--': Represents a strong negative relationship.
'-+': Represents a moderate relationship.
'o': Used exclusively for diagonal elements, typically representing
a perfect relationship in correlation matrices (value of 1.0).
Parameters:
custom_markers (dict, optional) – A dictionary mapping table symbols to their descriptions. If provided,
it overrides the default markers. Default is None.
no_corr_placeholder (str, optional) – Placeholder text for table values that do not meet the minimum threshold.
Default is ‘…’.
hide_diag (bool, optional) – If True, omits the diagonal entries from the legend. These are typically
frame of a variable with itself (1.0). Default is True.
max_width (int, optional) – The maximum width of the formatted legend text, influences the centering
of the title. Default is 50.
add_frame_lines (bool, optional) – If True, adds a frame around the legend using the specified border_line.
Default is True.
border_line (str, optional) – The character used to create the border of the frame if add_frame_lines
is True. Default is ‘.’.
Returns:
The formatted legend text, potentially framed, centered according to the
specified width, and including custom or default descriptions of correlation
values.
Transforms a pandas Series into a DataFrame where the columns are the index
of the Series. If the Series’ index is numeric, the index values are converted
to strings and used as column names.
Parameters:
series (pandas.Series) – The Series to be transformed into a DataFrame.
Returns:
A DataFrame where each column represents a value from the Series,
with column names corresponding to the Series’ index values.
Determines the appropriate width (and optionally height) for table display
based on terminal size, with options for manual width adjustment.
Parameters:
width (int or str, optional) – The desired width for the table. If set to ‘auto’, the terminal width
is used. If an integer is provided, it will be used as the width,
default is ‘auto’.
error (str, optional) – Error handling strategy when specified width exceeds terminal
width: ‘warn’ or ‘ignore’.
Default is ‘warn’.
return_height (bool, optional) – If True, the function also returns the height of the table.
Default is False.
Returns:
The width of the table as an integer, or a tuple of (width, height)
if return_height is True.
Converts a given string to CamelCase. The function handles strings with or
without delimiters, and can optionally use regex for splitting based on
non-alphanumeric characters.
delimiter (str, optional) – A character or string used as a delimiter to split the input string.
Common delimiters include underscores (‘_’) or spaces (’ ‘). If None
and use_regex is False, the function tries to automatically detect
common delimiters like spaces or underscores.
If use_regex is True, it splits the string at any non-alphabetic
character.
use_regex (bool, optional) – Specifies whether to use regex for splitting the string on non-alphabetic
characters.
Defaults to False.
>>> fromfusionlab.api.utilimportremove_extra_spaces>>> text="this is text that have extra space.">>> remove_extra_spaces(text)'this is text that have extra space.'
>>> example_dict={... 'key1':'short value',... 'key2':'a much longer value that should be truncated for readability purposes',... 'key3':'another short value',... 'key4':'value'... }>>> print(format_dict_result(example_dict,dict_name='ExampleDict',max_char=30))ExampleDict({ key1: short value, key2: a much longer value that s..., key3: another short value, key4: value,})
Notes
The function calculates the required indentation based on the length of the
dictionary name and the maximum key length. If a value exceeds the specified
maximum length, it truncates the value and appends an ellipsis (”…”).
Count and list the number of functions and classes in a specified module.
Parameters:
module_name (str) – The name of the module to inspect, in the format package.module.
include_class (bool, optional) – Whether to include classes in the count and listing. Default is
False.
return_counts (bool, optional) – Whether to return only the count of functions and classes (if
include_class is True). If False, returns a list of functions
and classes in alphabetical order. Default is True.
include_private (bool, optional) – Whether to include private functions and classes (those starting with
_). Default is False.
include_local (bool, optional) – Whether to include local (nested) functions in the count and listing.
Default is False.
Returns:
If return_counts is True, returns the count of functions and
classes (if include_class is True). If return_counts is
False, returns a list of function and class names (if
include_class is True) in alphabetical order.
This function dynamically imports the specified module and analyzes its
Abstract Syntax Tree (AST) to count and list functions and classes. It
provides flexibility to include or exclude private and local functions
based on the parameters provided.
Rounds numeric floating values in a DataFrame to the specified
precision. Integers and non-numeric values are not modified.
Parameters:
df (pandas.DataFrame) – The DataFrame whose numeric floating values are to be rounded.
The DataFrame can contain mixed data types, including integers,
floating-point numbers, and non-numeric values.
This function applies rounding only to floating-point numbers.
Integers and non-numeric values remain unchanged. The function
uses pandas’ applymap to apply the rounding operation element-wise
across the DataFrame.
The mathematical formulation for the rounding operation is given by:
\[y =
egin{cases}
ext{round}(x, ext{precision}) & ext{if } x \in \mathbb{R} \
x & ext{otherwise} \
\end{cases}\]
Where:
- \(x\) is the input value
- \(y\) is the output value after rounding
- :math:` ext{precision}` is the specified number of decimal places
Examples
>>> fromfusionlab.api.utilimportround_numeric_values>>> importpandasaspd>>> df=pd.DataFrame({... 'A':[1.12345,2.6789,3],... 'B':[4,5.98765,'text'],... 'C':[7.123456,8.654321,9.0]... })>>> round_numeric_values(df,precision=2) A B C0 1.12 4 7.121 2.68 5.99 8.652 3 text 9