scitex_core.str

exception scitex_core.str.LaTeXFallbackError[source]

Bases: Exception

Raised when LaTeX fallback mechanisms fail.

scitex_core.str.add_hat_in_latex_style(str_or_num)[source]

Add LaTeX hat notation to string with fallback.

Parameters:

str_or_num (str or numeric) – Input to format with hat notation

Returns:

LaTeX-formatted string with hat notation and automatic fallback

Return type:

str

Examples

>>> add_hat_in_latex_style('aaa')
'$\hat{aaa}$'
>>> add_hat_in_latex_style('x')  # Falls back to unicode if LaTeX fails
'x̂'

Notes

If LaTeX rendering fails, this function falls back to unicode hat notation or plain text alternatives.

scitex_core.str.auto_factor_axis(ax, axis='both', precision=2, min_factor_power=3, return_latex=True, return_unicode=False, label_offset=(0.02, 0.98))[source]

Automatically factor out common powers of 10 from axis tick labels.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes object to modify

  • axis (str, optional) – Which axis to factor (‘x’, ‘y’, or ‘both’), by default ‘both’

  • precision (int, optional) – Number of decimal places in factored values, by default 2

  • min_factor_power (int, optional) – Minimum power of 10 to factor out, by default 3

  • return_latex (bool, optional) – Use LaTeX format for factor string, by default True

  • return_unicode (bool, optional) – Use Unicode superscripts for factor string, by default False

  • label_offset (Tuple[float, float], optional) – Position for factor label as (x, y) in axes coordinates, by default (0.02, 0.98)

Return type:

None

Examples

>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> ax.plot([1000, 2000, 3000], [0.001, 0.002, 0.003])
>>> auto_factor_axis(ax, axis='both')
scitex_core.str.axis_label(label, unit=None, **kwargs)[source]

Convenient alias for format_axis_label.

Return type:

str

scitex_core.str.check_latex_capability()[source]

Check if LaTeX rendering is available and working.

Returns:

True if LaTeX is available, False otherwise

Return type:

bool

scitex_core.str.check_unit_consistency(x_unit=None, y_unit=None, operation='none')[source]

Check unit consistency for mathematical operations.

Parameters:
  • x_unit (Optional[str], optional) – X-axis unit, by default None

  • y_unit (Optional[str], optional) – Y-axis unit, by default None

  • operation (str, optional) – Mathematical operation: “add”, “subtract”, “multiply”, “divide”, “none”, by default “none”

Returns:

(is_consistent, expected_result_unit)

Return type:

Tuple[bool, str]

Examples

>>> check_unit_consistency("m", "s", "divide")
(True, 'm/s')
>>> check_unit_consistency("m", "m", "add")
(True, 'm')
>>> check_unit_consistency("m", "kg", "add")
(False, 'Units incompatible for addition')
scitex_core.str.clean_path(path_string)[source]

Cleans and normalizes a file system path string.

Example

>>> clean('/home/user/./folder/../file.txt')
'/home/user/file.txt'
>>> clean('path/./to//file.txt')
'path/to/file.txt'
Parameters:

path_string (str) – File path to clean

Returns:

Normalized path string

Return type:

str

scitex_core.str.color_text(text, c='green')[source]

Apply ANSI color codes to text.

Parameters:
  • text (str) – The text to be colored.

  • c (str, optional) – The color to apply. Available colors are ‘red’, ‘green’, ‘yellow’, ‘blue’, ‘magenta’, ‘cyan’, ‘white’, and ‘grey’ (default is “green”).

Returns:

The input text with ANSI color codes applied.

Return type:

str

Example

>>> print(color_text("Hello, World!", "blue"))
# This will print "Hello, World!" in blue text
scitex_core.str.ct(text, c='green')

Apply ANSI color codes to text.

Parameters:
  • text (str) – The text to be colored.

  • c (str, optional) – The color to apply. Available colors are ‘red’, ‘green’, ‘yellow’, ‘blue’, ‘magenta’, ‘cyan’, ‘white’, and ‘grey’ (default is “green”).

Returns:

The input text with ANSI color codes applied.

Return type:

str

Example

>>> print(color_text("Hello, World!", "blue"))
# This will print "Hello, World!" in blue text
scitex_core.str.decapitalize(input_string)[source]

Converts first character of string to lowercase.

Example

>>> decapitalize("Hello")
'hello'
>>> decapitalize("WORLD")
'wORLD'
>>> decapitalize("")
''
Parameters:

input_string (str) – String to be processed

Returns:

Modified string with first character in lowercase

Return type:

str

Raises:

TypeError – If input is not a string

scitex_core.str.disable_latex_fallback()[source]

Disable LaTeX fallback (force LaTeX usage).

Return type:

None

scitex_core.str.enable_latex_fallback(mode='auto')[source]

Enable LaTeX fallback with specified mode.

Return type:

None

scitex_core.str.factor_out_digits(values, precision=2, min_factor_power=3, return_latex=True, return_unicode=False)[source]

Factor out common powers of 10 from numerical values for cleaner scientific notation.

Parameters:
  • values (Union[List, np.ndarray, float, int]) – Numerical values to factor

  • precision (int, optional) – Number of decimal places in factored values, by default 2

  • min_factor_power (int, optional) – Minimum power of 10 to factor out, by default 3

  • return_latex (bool, optional) – Return factor string in LaTeX format, by default True

  • return_unicode (bool, optional) – Return factor string with Unicode superscripts, by default False

Returns:

Tuple of (factored_values, factor_string)

Return type:

Tuple[Union[List, np.ndarray, float], str]

Examples

>>> factor_out_digits([1000, 2000, 3000])
([1.0, 2.0, 3.0], '$\times 10^{3}$')
>>> factor_out_digits([0.001, 0.002, 0.003])
([1.0, 2.0, 3.0], '$\times 10^{-3}$')
>>> factor_out_digits([1.5e6, 2.3e6, 4.1e6])
([1.5, 2.3, 4.1], '$\times 10^{6}$')
scitex_core.str.format_axis_label(label, unit=None, unit_style='parentheses', capitalize=True, latex_math=True, enable_fallback=True, replace_underscores=True)[source]

Format axis labels with proper unit handling.

Parameters:
  • label (str) – The variable name or description

  • unit (Optional[str], optional) – The unit string, by default None

  • unit_style (str, optional) – Unit bracket style, by default “parentheses”

  • capitalize (bool, optional) – Whether to capitalize, by default True

  • latex_math (bool, optional) – Whether to enable LaTeX math, by default True

  • enable_fallback (bool, optional) – Whether to enable LaTeX fallback mechanisms, by default True

  • replace_underscores (bool, optional) – Whether to replace underscores with spaces, by default True

Returns:

Formatted axis label with automatic LaTeX fallback

Return type:

str

Examples

>>> format_axis_label("time", "s")
'Time (s)'
>>> format_axis_label("voltage", "V", unit_style="brackets")
'Voltage [V]'
>>> format_axis_label("temperature", "°C")
'Temperature (°C)'
>>> format_axis_label("signal_power", "dB")
'Signal Power (dB)'
scitex_core.str.format_plot_text(text, capitalize=True, unit_style='parentheses', latex_math=True, scientific_notation=True, enable_fallback=True, replace_underscores=True)[source]

Format text for scientific plots with proper conventions and LaTeX fallback.

Parameters:
  • text (str) – Input text to format

  • capitalize (bool, optional) – Whether to capitalize the first letter, by default True

  • unit_style (str, optional) – Unit bracket style: “parentheses” (), “brackets” [], or “auto”, by default “parentheses”

  • latex_math (bool, optional) – Whether to enable LaTeX math formatting, by default True

  • scientific_notation (bool, optional) – Whether to format scientific notation properly, by default True

  • enable_fallback (bool, optional) – Whether to enable LaTeX fallback mechanisms, by default True

  • replace_underscores (bool, optional) – Whether to replace underscores with spaces, by default True

Returns:

Formatted text ready for matplotlib with automatic LaTeX fallback

Return type:

str

Examples

>>> format_plot_text("time (s)")
'Time (s)'
>>> format_plot_text("voltage [V]", unit_style="brackets")
'Voltage [V]'
>>> format_plot_text("frequency in Hz", unit_style="auto")
'Frequency (Hz)'
>>> format_plot_text("signal_power_db")
'Signal Power Db'
>>> format_plot_text(r"$lpha$ decay")  # Falls back if LaTeX fails
'α decay'

Notes

If LaTeX rendering fails, this function automatically falls back to mathtext or unicode alternatives while preserving scientific formatting.

scitex_core.str.format_title(title, subtitle=None, capitalize=True, latex_math=True, enable_fallback=True, replace_underscores=True)[source]

Format plot titles with proper conventions.

Parameters:
  • title (str) – Main title text

  • subtitle (Optional[str], optional) – Subtitle text, by default None

  • capitalize (bool, optional) – Whether to capitalize, by default True

  • latex_math (bool, optional) – Whether to enable LaTeX math, by default True

  • enable_fallback (bool, optional) – Whether to enable LaTeX fallback mechanisms, by default True

  • replace_underscores (bool, optional) – Whether to replace underscores with spaces, by default True

Returns:

Formatted title with automatic LaTeX fallback

Return type:

str

Examples

>>> format_title("neural spike analysis")
'Neural Spike Analysis'
>>> format_title("data analysis", "preliminary results")
'Data Analysis\nPreliminary Results'
>>> format_title("signal_processing_results")
'Signal Processing Results'
scitex_core.str.get_fallback_mode()[source]

Get the current fallback mode.

Return type:

str

scitex_core.str.get_latex_status()[source]

Get comprehensive LaTeX status information.

Returns:

Status information including capability, mode, and configuration

Return type:

Dict[str, Any]

scitex_core.str.grep(str_list, search_key)[source]

Search for a key in a list of strings and return matching items.

Parameters:
  • str_list (list of str) – The list of strings to search through.

  • search_key (str) – The key to search for in the strings.

Returns:

A list of strings from str_list that contain the search_key.

Return type:

list

Example

>>> grep(['apple', 'banana', 'cherry'], 'a')
['apple', 'banana']
>>> grep(['cat', 'dog', 'elephant'], 'e')
['elephant']
scitex_core.str.hat_latex_style(str_or_num)

Add LaTeX hat notation to string with fallback.

Parameters:

str_or_num (str or numeric) – Input to format with hat notation

Returns:

LaTeX-formatted string with hat notation and automatic fallback

Return type:

str

Examples

>>> add_hat_in_latex_style('aaa')
'$\hat{aaa}$'
>>> add_hat_in_latex_style('x')  # Falls back to unicode if LaTeX fails
'x̂'

Notes

If LaTeX rendering fails, this function falls back to unicode hat notation or plain text alternatives.

scitex_core.str.latex_fallback_decorator(fallback_strategy='auto', preserve_math=True)[source]

Decorator to add LaTeX fallback capability to functions.

Parameters:
  • fallback_strategy (str, optional) – Fallback strategy to use

  • preserve_math (bool, optional) – Whether to preserve mathematical notation

Returns:

Decorated function with LaTeX fallback

Return type:

callable

scitex_core.str.latex_style(str_or_num)

Convert string or number to LaTeX math mode format with fallback.

Parameters:

str_or_num (str or numeric) – Input to format in LaTeX style

Returns:

LaTeX-formatted string with automatic fallback

Return type:

str

Examples

>>> to_latex_style('aaa')
'$aaa$'
>>> to_latex_style('alpha')  # Falls back to unicode if LaTeX fails
'α'

Notes

If LaTeX rendering fails (e.g., due to missing fonts or Node.js conflicts), this function automatically falls back to mathtext or unicode alternatives.

scitex_core.str.latex_to_mathtext(latex_str)[source]

Convert LaTeX syntax to matplotlib mathtext equivalent.

Parameters:

latex_str (str) – LaTeX string to convert

Returns:

Mathtext equivalent string

Return type:

str

scitex_core.str.latex_to_unicode(latex_str)[source]

Convert LaTeX to Unicode plain text equivalent.

Parameters:

latex_str (str) – LaTeX string to convert

Returns:

Unicode plain text equivalent

Return type:

str

scitex_core.str.mask_api(api_key)[source]
scitex_core.str.parse(string_or_fstring, fstring_or_string)[source]

Bidirectional parser that attempts parsing in both directions.

Parameters:
  • string_or_fstring (str) – Either the input string to parse or the pattern

  • fstring_or_string (str) – Either the pattern to match against or the input string

Returns:

Parsed dictionary or formatted string

Return type:

Union[Dict[str, Union[str, int]], str]

Raises:

ValueError – If parsing fails in both directions

Examples

>>> # Forward parsing
>>> parse("./data/Patient_23_002", "./data/Patient_{id}")
{'id': '23_002'}
>>> # Reverse parsing
>>> parse("./data/Patient_{id}", "./data/Patient_23_002")
{'id': '23_002'}
scitex_core.str.print_debug()[source]

Print a prominent debug mode banner.

Displays a highly visible yellow banner to indicate that the program is running in debug mode. Useful for making debug runs immediately distinguishable from production runs.

The banner consists of multiple lines of exclamation marks with “DEBUG MODE” prominently displayed in the center.

Examples

>>> # At the start of debug runs
>>> if DEBUG:
...     print_debug()
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!! DEBUG MODE !!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
>>> # In configuration validation
>>> if config.debug_mode:
...     print_debug()
...     print("Debug logging enabled")

See also

printc

Colored printing function used internally

Notes

The banner is printed in yellow color to ensure high visibility in terminal output.

scitex_core.str.printc(message, c='blue', char='-', n=40)[source]

Print a message surrounded by a character border.

This function prints a given message surrounded by a border made of a specified character. The border can be colored if desired.

Parameters:
  • message (str) – The message to be printed inside the border.

  • char (str, optional) – The character used to create the border (default is “-“).

  • n (int, optional) – The width of the border (default is 40).

  • c (str, optional) – The color of the border. Can be ‘red’, ‘green’, ‘yellow’, ‘blue’, ‘magenta’, ‘cyan’, ‘white’, or ‘grey’ (default is None, which means no color).

Return type:

None

Example

>>> print_block("Hello, World!", char="*", n=20, c="blue")
********************
* Hello, World!    *
********************

Note: The actual output will be in green color.

scitex_core.str.readable_bytes(num, suffix='B')[source]

Convert a number of bytes to a human-readable format.

Parameters:
  • num (int) – The number of bytes to convert.

  • suffix (str, optional) – The suffix to append to the unit (default is “B” for bytes).

Returns:

A human-readable string representation of the byte size.

Return type:

str

Example

>>> readable_bytes(1024)
'1.0 KiB'
>>> readable_bytes(1048576)
'1.0 MiB'
>>> readable_bytes(1073741824)
'1.0 GiB'
scitex_core.str.remove_ansi(string)[source]

Removes ANSI escape sequences from a given text chunk.

Parameters: - chunk (str): The text chunk to be cleaned.

Returns: - str: The cleaned text chunk.

scitex_core.str.replace(string, replacements=None)[source]

Replace placeholders in the string with corresponding values from replacements.

This function replaces placeholders in the format {key} within the input string with corresponding values from the replacements dictionary. If replacements is a string, it replaces the entire input string.

Parameters:
  • string (str) – The string containing placeholders in the format {key}

  • replacements (Optional[Union[str, Dict[str, str]]], optional) – A dictionary containing key-value pairs for replacing placeholders in the string, or a single string to replace the entire string

Returns:

The input string with placeholders replaced by their corresponding values

Return type:

str

Examples

>>> replace("Hello, {name}!", {"name": "World"})
'Hello, World!'
>>> replace("Original string", "New string")
'New string'
>>> replace("Value: {x}", {"x": "42"})
'Value: 42'
>>> template = "Hello, {name}! You are {age} years old."
>>> replacements = {"name": "Alice", "age": "30"}
>>> replace(template, replacements)
'Hello, Alice! You are 30 years old.'
scitex_core.str.reset_latex_cache()[source]

Reset the LaTeX capability cache.

Return type:

None

scitex_core.str.safe_add_hat_in_latex_style(str_or_num, fallback_strategy='auto')[source]

Safe version of add_hat_in_latex_style with explicit fallback control.

Parameters:
  • str_or_num (str or numeric) – Input to format with hat notation

  • fallback_strategy (str, optional) – Explicit fallback strategy: “auto”, “mathtext”, “unicode”, “plain”

Returns:

Formatted string with hat notation and specified fallback behavior

Return type:

str

scitex_core.str.safe_latex_render(text, fallback_strategy='auto', preserve_math=True)[source]

Safely render LaTeX text with automatic fallback.

Parameters:
  • text (str) – Text that may contain LaTeX

  • fallback_strategy (str, optional) – Strategy when LaTeX fails: “auto”, “mathtext”, “unicode”, “plain”

  • preserve_math (bool, optional) – Whether to preserve mathematical notation in fallbacks

Returns:

Safely rendered text

Return type:

str

scitex_core.str.safe_to_latex_style(str_or_num, fallback_strategy='auto')[source]

Safe version of to_latex_style with explicit fallback control.

Parameters:
  • str_or_num (str or numeric) – Input to format in LaTeX style

  • fallback_strategy (str, optional) – Explicit fallback strategy: “auto”, “mathtext”, “unicode”, “plain”

Returns:

Formatted string with specified fallback behavior

Return type:

str

scitex_core.str.scientific_text(text, **kwargs)[source]

Convenient alias for format_plot_text with scientific defaults.

Return type:

str

scitex_core.str.search(patterns, strings, only_perfect_match=False, as_bool=False, ensure_one=False)[source]

Search for patterns in strings using regular expressions.

Parameters:
  • patterns (str or list of str) – The pattern(s) to search for. Can be a single string or a list of strings.

  • strings (str or list of str) – The string(s) to search in. Can be a single string or a list of strings.

  • only_perfect_match (bool, optional) – If True, only exact matches are considered (default is False).

  • as_bool (bool, optional) – If True, return a boolean array instead of indices (default is False).

  • ensure_one (bool, optional) – If True, ensures only one match is found (default is False).

Returns:

A tuple containing two elements: - If as_bool is False: (list of int, list of str)

The first element is a list of indices where matches were found. The second element is a list of matched strings.

  • If as_bool is True: (numpy.ndarray of bool, list of str) The first element is a boolean array indicating matches. The second element is a list of matched strings.

Return type:

tuple

Example

>>> patterns = ['orange', 'banana']
>>> strings = ['apple', 'orange', 'apple', 'apple_juice', 'banana', 'orange_juice']
>>> search(patterns, strings)
([1, 4, 5], ['orange', 'banana', 'orange_juice'])
>>> patterns = 'orange'
>>> strings = ['apple', 'orange', 'apple', 'apple_juice', 'banana', 'orange_juice']
>>> search(patterns, strings)
([1, 5], ['orange', 'orange_juice'])
scitex_core.str.set_fallback_mode(mode)[source]

Set the global fallback mode for LaTeX rendering.

Parameters:

mode (str) – Fallback mode: “auto” (detect capability), “force_mathtext”, or “force_plain”

Return type:

None

scitex_core.str.smart_tick_formatter(values, max_ticks=6, factor_out=True, precision=2, min_factor_power=3, return_latex=True)[source]

Smart tick formatter that combines nice tick selection with factor-out-digits.

Parameters:
  • values (Union[List, np.ndarray]) – Data values to create ticks for

  • max_ticks (int, optional) – Maximum number of ticks, by default 6

  • factor_out (bool, optional) – Whether to factor out common powers of 10, by default True

  • precision (int, optional) – Number of decimal places, by default 2

  • min_factor_power (int, optional) – Minimum power to factor out, by default 3

  • return_latex (bool, optional) – Use LaTeX format, by default True

Returns:

(tick_positions, tick_labels, factor_string)

Return type:

Tuple[Union[List, np.ndarray], List[str], str]

Examples

>>> smart_tick_formatter([1000, 1500, 2000, 2500, 3000])
([1000, 1500, 2000, 2500, 3000], ['1.0', '1.5', '2.0', '2.5', '3.0'], '$\times 10^{3}$')
scitex_core.str.squeeze_spaces(string, pattern=' +', repl=' ')[source]

Replace multiple occurrences of a pattern in a string with a single replacement.

Parameters:
  • string (str) – The input string to be processed.

  • pattern (str, optional) – The regular expression pattern to match (default is “ +”, which matches one or more spaces).

  • repl (str or callable, optional) – The replacement string or function (default is “ “, a single space).

Returns:

The processed string with pattern occurrences replaced.

Return type:

str

Example

>>> squeeze_spaces("Hello   world")
'Hello world'
>>> squeeze_spaces("a---b--c-d", pattern="-+", repl="-")
'a-b-c-d'
scitex_core.str.title(text, **kwargs)[source]

Convenient alias for format_title.

Return type:

str

scitex_core.str.to_latex_style(str_or_num)[source]

Convert string or number to LaTeX math mode format with fallback.

Parameters:

str_or_num (str or numeric) – Input to format in LaTeX style

Returns:

LaTeX-formatted string with automatic fallback

Return type:

str

Examples

>>> to_latex_style('aaa')
'$aaa$'
>>> to_latex_style('alpha')  # Falls back to unicode if LaTeX fails
'α'

Notes

If LaTeX rendering fails (e.g., due to missing fonts or Node.js conflicts), this function automatically falls back to mathtext or unicode alternatives.

scitex_core.str.__DIR__ = '/home/ywatanabe/proj/scitex-core/src/scitex_core/str'

Scitex str module.