Source code for pyXLMS.parser.util
#!/usr/bin/env python3
# 2025 (c) Micha Johannes Birklbauer
# https://github.com/michabirklbauer/
# micha.birklbauer@gmail.com
from __future__ import annotations
import warnings
import pandas as pd
from ..constants import AMINO_ACIDS
from typing import List
from typing import Dict
from typing import Any
def __serialize_pandas_series(
pds: pd.Series, nan_values: List[str] = ["", "nan", "null", "none"]
) -> Dict[str, Any]:
r"""Serialize a pandas Series to a python native dictionary with native types.
Parameters
----------
pds : pd.Series
The pandas Series to serialize.
nan_values : list of str, default = ["", "nan", "null", "none"]
List of strings that should be considered as missing values.
Returns
-------
dict of str, any
The serialized pandas Series.
Notes
-----
This function should not be called directly, it is called from all parsers to serialize input.
"""
serialized_pds = dict()
for key in pds.index.tolist():
val = None
raw_val = pds[key]
if isinstance(raw_val, int):
val = int(raw_val)
elif isinstance(raw_val, float):
if not pd.isna(raw_val): # pyright: ignore[reportGeneralTypeIssues]
val = float(raw_val)
else:
if not pd.isna(raw_val): # pyright: ignore[reportGeneralTypeIssues]
str_val = str(raw_val)
if str_val.lower().strip() not in nan_values:
val = str_val
serialized_pds[key] = val
return serialized_pds
[docs]
def get_bool_from_value(value: Any) -> bool:
r"""Parse a bool value from the given input.
Tries to parse a boolean value from the given input object. If the object is of instance ``bool`` it will return the object, if it is of
instance ``int`` it will return ``True`` if the object is ``1`` or ``False`` if the object is ``0``, any other number will raise a
``ValueError``. If the object is of instance ``str`` it will return ``True`` if the lower case version contains the letter ``t`` and
otherwise ``False``. If the object is none of these types a ``ValueError`` will be raised.
Parameters
----------
value : any
The value to parse from.
Returns
-------
bool
The parsed boolean value.
Raises
------
ValueError
If the object could not be parsed to bool.
Examples
--------
>>> from pyXLMS.parser_util import get_bool_from_value
>>> get_bool_from_value(0)
False
>>> from pyXLMS.parser_util import get_bool_from_value
>>> get_bool_from_value("T")
True
"""
if isinstance(value, bool):
return value
elif isinstance(value, int):
if value in [0, 1]:
return bool(value)
else:
raise ValueError(f"Cannot parse bool value from the given input {value}.")
elif isinstance(value, str):
return "t" in value.lower()
else:
raise ValueError(f"Cannot parse bool value from the given input {value}.")
return False