Utils Subpackage
This subpackage contains the utility modules used by the YugiQuery package.
Api Module
- yugiquery.utils.api.URLS: SimpleNamespace
A mapping of yugipedia API URLs with HTTP headers dinamically loaded from the headers.json file in the assets directory.
- yugiquery.utils.api.arrows_dict: Dict[str, str]
A dictionary mapping link arrow positions to their corresponding Unicode characters.
- yugiquery.utils.api.check_status() bool
Checks if the API is running and reachable by making a query to retrieve site information. If the API is up and running, returns True. If the API is down or unreachable, returns False and prints an error message with details.
- Returns:
True if the API is up and running, False otherwise.
- Return type:
bool
- async yugiquery.utils.api.download_images(file_names: DataFrame, save_folder: str = 'images', max_tasks: int = 10) None
Downloads a set of images given their names and saves them to a specified folder.
- Parameters:
file_names (pandas.DataFrame) – A DataFrame containing the names of the image files to be downloaded.
save_folder (str, optional) – The path to the folder where the downloaded images will be saved. Defaults to “images”.
max_tasks (int, optional) – The maximum number of images to download at once. Defaults to 10.
- Returns:
None
- yugiquery.utils.api.extract_artwork(row: Series) float | Tuple[str]
Formats a row of a dataframe that contains “alternate artworks” and “edited artworks” columns. If the “alternate artworks” column(s) in the row contain at least one “True” value, adds “Alternate” to the result tuple. If the “edited artworks” column(s) in the row contain at least one “True” value, adds “Edited” to the result tuple. Returns the result tuple.
- Parameters:
row (pd.Series) – A row of a dataframe that contains “alternate artworks” and “edited artworks” columns.
- Returns:
The formatted row as a tuple.
- Return type:
Tuple[str]
- yugiquery.utils.api.extract_category_bool(x: List[str]) float | bool
Extracts a boolean value from a list of strings that represent a boolean value. If the first string in the list is “t”, returns True. If the first string in the list is “f”, returns False. Otherwise, returns np.nan.
- Parameters:
x (List[str]) – The input list of strings to extract a boolean value from.
- Returns:
The extracted boolean value.
- Return type:
bool | np.nan
- yugiquery.utils.api.extract_fulltext(x: List[Dict[str, Any] | str], multiple: bool = False) str | Tuple[str] | float
Extracts fulltext from a list of dictionaries or strings. If multiple is True, returns a sorted tuple of all fulltexts. Otherwise, returns the first fulltext found, with leading/trailing whitespaces removed. If the input list is empty, returns np.nan.
- Parameters:
x (List[Dict[str, Any] | str]) – A list of dictionaries or strings to extract fulltext from.
multiple (bool, optional) – If True, return a tuple of all fulltexts. Otherwise, return the first fulltext. Default is False.
- Returns:
The extracted fulltext(s).
- Return type:
str or Tuple[str] or np.nan
- yugiquery.utils.api.extract_misc(x: str | List[str] | Tuple[str]) Series
Extracts the misc properties of a card. Checks whether the input contains the values “Legend Card” or “Requires Maximum Mode” and creates a boolean table.
- Parameters:
x (str | List[str] | Tuple[str]) – The Misc values to generate the boolean table from.
- Returns:
A pandas Series of boolean values indicating whether “Legend Card” and “Requires Maximum Mode” are present in the input.
- Return type:
pd.Series
- yugiquery.utils.api.extract_primary_type(row: str | List[str] | Tuple[str]) str | List[str]
Extracts the primary type of a card. If the input is a list or tuple, removes “Pendulum Monster” and “Maximum Monster” from the list. If the input is a list or tuple with only one element, returns that element. If the input is a list or tuple with multiple elements, returns the first element that is not “Effect Monster”. Otherwise, returns the input.
- Parameters:
row (str | List[str] | Tuple[str]) – The input type(s) to extract the primary type from.
- Returns:
The extracted primary type(s).
- Return type:
str | List[str]
- yugiquery.utils.api.extract_results(response: Response) DataFrame
Extracts the relevant data from the response object and returns it as a Pandas DataFrame.
- Parameters:
response (requests.Response) – The response object obtained from making a GET request to the Yu-Gi-Oh! Wiki API.
- Returns:
A DataFrame containing the relevant data extracted from the response object.
- Return type:
pd.DataFrame
- yugiquery.utils.api.fetch_backlinks(titles: List[str]) Dict[str, str]
Fetches backlinks for a list of page titles.
- Parameters:
titles (List[str]) – A list of titles.
- Returns:
A dictionary mapping backlink titles to their corresponding target titles.
- Return type:
Dict[str, str]
- yugiquery.utils.api.fetch_categorymembers(category: str, namespace: int = 0, step: int = 500, iterator: tqdm_asyncio | None = None, debug: bool = False) DataFrame
Fetches members of a category from the API by making iterative requests with a specified step size until all members are retrieved.
- Parameters:
category (str) – The category to retrieve members for.
namespace (int, optional) – The namespace ID to filter the members by. Defaults to 0 (main namespace).
step (int, optional) – The number of members to retrieve in each request. Defaults to 500.
iterator (tqdm.std.tqdm | None, optional) – A tqdm iterator to display progress updates. Defaults to None.
debug (bool, optional) – If True, prints the URL of each request for debugging purposes. Defaults to False.
- Returns:
A DataFrame containing the members of the category.
- Return type:
pandas.DataFrame
- yugiquery.utils.api.fetch_properties(condition: str, query: str, step: int = 500, limit: int = 5000, iterator: tqdm_asyncio | None = None, include_all: bool = False, debug: bool = False) DataFrame
Fetches properties from the API by making iterative requests with a specified step size until a specified limit is reached.
- Parameters:
condition (str) – The query condition to filter the properties by.
query (str) – The query to retrieve the properties.
step (int, optional) – The number of properties to retrieve in each request. Defaults to 500.
limit (int, optional) – The maximum number of properties to retrieve. Defaults to 5000.
iterator (tqdm.std.tqdm | None, optional) – A tqdm iterator to display progress updates. Defaults to None.
include_all (bool, optional) – If True, includes all properties in the DataFrame. If False, includes only properties that have values. Defaults to False.
debug (bool, optional) – If True, prints the URL of each request for debugging purposes. Defaults to False.
- Returns:
A DataFrame containing the properties matching the query and condition.
- Return type:
pandas.DataFrame
- yugiquery.utils.api.fetch_redirect_dict(codes: List[str] = [], names: List[str] = [], category: str = '', **kwargs) Dict[str, str]
Fetches a dictionary mapping rarity codes to their corresponding names by searching for backlinks and redirects.
- Parameters:
names (List[str], optional) – A list of names, i.e. “Super Rare” to search for a backling.
codes (List[str], optional) – A list of codes, i.e. “SR” to search for a redirect.
category (str, optional) – A category to search for backlinks. Defaults to empty.
**kwargs – Additional keyword arguments to pass to the fetch_categorymembers
- Returns:
A dictionary mapping codes to their corresponding names.
- Return type:
Dict[str, str]
- yugiquery.utils.api.fetch_redirects(titles: List[str]) Dict[str, str]
Fetches redirects for a list of page titles.
- Parameters:
titles (List[str]) – A list of titles.
- Returns:
A dictionary mapping source titles to their corresponding redirect targets.
- Return type:
Dict[str, str]
- yugiquery.utils.api.fetch_set_info(sets: List[str], extra_info: List[str] = [], step: int = 15, debug: bool = False) DataFrame
Fetches information for a list of sets.
- Parameters:
sets (List[str]) – A list of set names to fetch information for.
extra_info (List[str], optional) – A list of additional information to fetch for each set. Defaults to an empty list.
step (int, optional) – The number of sets to fetch information for at once. Defaults to 15.
debug (bool, optional) – If True, prints debug information. Defaults to False.
- Returns:
A DataFrame containing information for all sets in the list.
- Return type:
pd.DataFrame
- Raises:
Any exceptions raised by requests.get(). –
- yugiquery.utils.api.fetch_set_lists(titles: List[str], debug: bool = False) None | Tuple[DataFrame, int, int]
Fetches card set lists from a list of page titles.
- Parameters:
titles (List[str]) – A list of page titles from which to fetch set lists.
debug (bool, optional) – If True, prints debug information. Defaults to False.
- Returns:
A DataFrame containing the parsed card set lists, the number of successful requests, and the number of failed requests.
- Return type:
Tuple[pd.DataFrame, int, int]
- yugiquery.utils.api.format_df(input_df: DataFrame, include_all: bool = False) DataFrame
Formats a dataframe containing card information. Returns a new dataframe with specific columns extracted and processed.
- Parameters:
input_df (pd.DataFrame) – The input dataframe to format.
include_all (bool, optional) – If True, include all unspecified columns in the output dataframe. Default is False.
- Returns:
The formatted dataframe.
- Return type:
pd.DataFrame
Dirs Module
- class yugiquery.utils.dirs.Dirs
Bases:
objectSingleton class to manage directory paths for the application.
- Variables:
APP (Path) – The path to the application (YugiQuery) directory.
ASSETS (Path) – The path to the assets directory.
DATA (Path) – The path to the data directory.
NOTEBOOKS (Path) – The path to the notebooks directory.
REPORTS (Path) – The path to the reports directory.
SHARE (Path) – The path to the share directory.
UTILS (Path:) – The path to the utils subpackage directory.
WORK (Path) – The path to the working directory.
- property ASSETS: SimpleNamespace
Returns a SimpleNamespace object containing the paths to the package and user assets directories.
- Returns:
A SimpleNamespace object containing the paths to the package and user assets directories.
- Return type:
SimpleNamespace
- property DATA: Path
Return the path to the data directory.
- Returns:
The path to the data directory.
- Return type:
Path
- property NOTEBOOKS: SimpleNamespace
Return the path to the notebooks directory.
- Returns:
The path to the notebooks directory.
- Return type:
Path
- property REPORTS: Path
Return the path to the reports directory.
- Returns:
The path to the reports directory.
- Return type:
Path
- static __new__(cls, *args, **kwargs)
Create a new instance of the Dirs class if one does not already exist.
- find_notebooks(notebooks: str | List[str] = 'all') List[Path]
Finds the paths of the specified notebooks.
- Parameters:
notebooks (str | List[str], optional) – A list of notebook names or paths. If “all”, finds all notebooks in the NOTEBOOKS directory. If “user”, finds all notebooks in the user directory. Defaults to “all”.
- get_asset(*parts: str) Path
Return the path to an asset file.
- Parameters:
*parts (str) – The path parts to the asset file or directory.
- Returns:
The path to the asset file or directory.
- Return type:
Path
- Raises:
FileNotFoundError – If the asset file is not found
- get_notebook(*parts: str) Path
Return the path to a notebook file. Names are case insensitive. If more than one occurrence is found, the first path will be returned. Notebooks in the user directory will take precedence over the pkg director.
- Parameters:
*parts (str) – The path parts to the notebook file.
- Returns:
The path to the notebook file.
- Return type:
Path
- Raises:
FileNotFoundError – If the notebook file is not found.
- property is_notebook: bool
Check if the current environment is a Jupyter notebook.
- Returns:
True if the current environment is a Jupyter notebook, False otherwise.
- Return type:
bool
- make() None
Ensure that the DATA and REPORTS directories exist.
- print() None
Prints the directory paths managed by this class.
- property secrets_file: Path
first ASSETS, then WORK. Returns none if the file is not found.
- Returns:
The path to the secrets file.
- Return type:
Path
- Type:
Return the path to the secrets file following the hierarchy
Git Module
- yugiquery.utils.git.commit(files: str | List[str], message: str = '', repo: Repo | None = None) str
Commits the specified files to the git repository after staging them.
- Parameters:
files (str | List[str]) – A list of file paths to be committed.
message (str, optional) – The commit message. If not provided, a default message will be used.
repo (git.Repo | None, optional) – The git repository object. If none provided, the current repository will be used.
- Raises:
git.GitCommandError – If an error occurs while committing the changes.
Exception – For any other unexpected errors.
- Returns:
The commit result.
- Return type:
str
- yugiquery.utils.git.ensure_repo() Repo
Ensures the execution happens inside a git repository. Initializes a repository if one is not found.
- Raises:
git.InvalidGitRepositoryError – If the dirs.SCRIPT is not in a git repository.
Exception – For any other unexpected errors.
RuntimeError – If a Git repository cannot be initialized.
- Returns:
The git repository object.
- Return type:
git.Repo
- yugiquery.utils.git.get_repo() Repo
Gets the current git repository if there is one.
- Raises:
git.InvalidGitRepositoryError – If the dirs.SCRIPT is not in a git repository.
git.GitCommandError – If an error occurs while committing the changes.
Exception – For any other unexpected errors.
- Returns:
The git repository object.
- Return type:
git.Repo
- yugiquery.utils.git.pull(passphrase: str = '', repo: Repo | None = None) str
Pulls changes from the remote git repository.
- Parameters:
passphrase (str, optional) – The passphrase to unlock your Git credential store. Defaults to empty.
repo (git.Repo | None, optional) – The git repository object. If none provided, the current repository will be used.
- Raises:
git.GitCommandError – If an error occurs while committing the changes.
Exception – For any other unexpected errors.
- Returns:
None
- yugiquery.utils.git.push(passphrase: str = '', repo: Repo | None = None) str
Pushes commits to the remote git repository.
- Parameters:
passphrase (str, optional) – The passphrase to unlock your Git credential store. Defaults to empty.
repo (git.Repo | None, optional) – The git repository object. If none provided, the current repository will be used.
- Raises:
git.GitCommandError – If an error occurs while committing the changes.
Exception – For any other unexpected errors.
- Returns:
None
- yugiquery.utils.git.restore(files: str | List[str], repo: Repo | None = None) str
Restores the specified files on the git repository.
- Parameters:
files (str | List[str]) – A list of file paths to be restored.
repo (git.Repo | None, optional) – The git repository object. If none provided, the current repository will be used.
- Raises:
git.GitCommandError – If an error occurs while committing the changes.
Exception – For any other unexpected errors.
- Returns:
The restore result.
- Return type:
str
- yugiquery.utils.git.squash_commits(start_commit: Commit, repo: Repo | None = None, message: str = '') str
Squashes all commits from the start_commit to HEAD into a single commit.
- Parameters:
start_commit (git.Commit) – The commit object to start squashing from.
repo (git.Repo | None, optional) – The git repository object. If none provided, the current repository will be used.
message (str, optional) – The commit message. If not provided, a default message will generated from commits.
- yugiquery.utils.git.unlock(passphrase: str = '') str
Unlock the git credential store.
- Parameters:
passphrase (str, optional) – The passphrase to unlock your Git credential store. Defaults to empty.
- Returns:
The result of the unlock operation.
- Return type:
str
Helpers Module
- class yugiquery.utils.helpers.CredAction
Bases:
Action
- yugiquery.utils.helpers.auto_or_bool(value: str) bool | Literal['auto']
Convert a string to a boolean (True or False) or “auto”.
- yugiquery.utils.helpers.check_debug(local_debug: bool = False) bool
Check if the debug mode is enabled.
- Parameters:
local_debug (bool, optional) – A boolean indicating whether the debug mode is enabled locally. Defaults to False.
- Returns:
A boolean indicating whether the debug mode is enabled.
- Return type:
bool
- yugiquery.utils.helpers.ensure_tqdm()
Ensure the required tqdm fork for the Discord API is installed. Exits the program if the installation fails.
- yugiquery.utils.helpers.escape_chars(string: str, chars: List[str] = ['_', '.', '-', '+', '#', '@', '=']) str
Escapes specified characters in a given string by adding a backslash before each occurrence.
- Parameters:
string (str) – The input string to be processed.
chars (list, optional) – A list of characters to be escaped. Default is [“_”, “.”, “-”, “+”, “#”, “@”, “=”].
- Returns:
The input string with the specified characters escaped.
- Return type:
str
- yugiquery.utils.helpers.get_granularity(seconds: int) list[str]
Humanizes a time interval given in seconds.
- Parameters:
seconds (int) – The time interval in seconds.
- Returns:
A list of human-readable granularities for the time interval.
- Return type:
list
- yugiquery.utils.helpers.load_json(json_file: str) dict
Load data from a JSON file.
- Parameters:
json_file (str) – The file path to the JSON file.
- Returns:
A dictionary containing the data from the JSON file. If the file does not exist, an empty dictionary is returned.
- Return type:
dict
- yugiquery.utils.helpers.load_secrets(requested_secrets: List[str] = [], secrets_file: str | None = None, required: bool = False) Dict[str, str]
Load secrets from environment variables and/or a .env file.
The secrets can be specified by name using the requested_secrets argument, which should be a list of strings. If requested_secrets is not specified, all available secrets will be returned.
The secrets_file argument is the path to a .env file containing additional secrets to load. If secrets_file is specified and the file exists, the function will load the secrets from the file and merge them with the secrets loaded from the environment variables giving priority to secrets obtained from the environment.
The required argument is a boolean or list of booleans indicating whether each requested secret is required to be present. If required is True, a KeyError will be raised if the secret is not found. If required is False or not specified, missing secrets will be skipped.
- Parameters:
requested_secrets (List[str], optional) – A list of names of the secrets to retrieve. If empty or not specified, all available secrets will be returned. Defaults to [].
secrets_file (str | None, optional) – The path to a .env file containing additional secrets to load. Defaults to None.
required (bool or List[bool], optional) – A boolean or list of booleans indicating whether each requested secret is required to be present. If True, a KeyError will be raised if the secret is not found. If False or not specified, missing secrets will be skipped. Defaults to False.
- Returns:
A dictionary containing the requested secrets as key-value pairs.
- Return type:
Dict[str, str]
- Raises:
KeyError – If a required secret is not found in the environment variables or .env file.
- yugiquery.utils.helpers.lock(file_name: str) None
Acquire a file lock and handle stale locks using the same lock file.
- Parameters:
file_name (str) – The name of the lock file to create
- Raises:
RuntimeError – If another instance is already running.
- yugiquery.utils.helpers.make_filename(report: str, timestamp: Arrow, previous_timestamp: Arrow | None = None) str
Generates a standardized filename based on the provided parameters.
- Parameters:
report (str) – The name or identifier of the report.
timestamp (arrow.Arrow) – The timestamp to be included in the filename.
previous_timestamp (arrow.Arrow | None) – The previous timestamp, if applicable. Defaults to None.
- Returns:
The generated filename.
- Return type:
str
- yugiquery.utils.helpers.md5(name: str) str
Generate the MD5 hash of a string.
- Parameters:
name (str) – The string to hash.
- Returns:
The MD5 hash of the string.
- Return type:
str
- yugiquery.utils.helpers.unlock(file_name: str) None
Release a file lock and remove the lock file.
- Parameters:
file_name (str) – The name of the lock file to remove
Plot Module
- yugiquery.utils.plot.adjust_lightness(color: str, amount: float = 0.5) tuple[float, float, float]
Adjust the lightness of a given color by a specified amount.
- Parameters:
color (str) – The color to be adjusted, in string format.
amount (float, optional) – The amount by which to adjust the lightness of the color. Default value is 0.5.
- Returns:
The adjusted color in RGB format.
- Return type:
tuple
- yugiquery.utils.plot.adjust_yaxis(ax: Axes, ydif: float, v: float) None
Shift the y-axis of a subplot by a specified amount, while maintaining the location of a specified point.
- Parameters:
ax (AxesSubplot) – The subplot whose y-axis is to be adjusted.
ydif (float) – The amount by which to adjust the y-axis.
v (float) – The location of the point whose position should remain unchanged.
- Returns:
None
- yugiquery.utils.plot.align_yaxis(ax1: Axes, v1: float, ax2: Axes, v2: float) None
Adjust the y-axis of two subplots so that the specified values in each subplot are aligned.
- Parameters:
ax1 (AxesSubplot) – The first subplot.
v1 (float) – The value in ax1 that should be aligned with v2 in ax2.
ax2 (AxesSubplot) – The second subplot.
v2 (float) – The value in ax2 that should be aligned with v1 in ax1.
- Returns:
None
- yugiquery.utils.plot.arrows(arrows: Series, figsize: Tuple[int, int] = (6, 6), **kwargs) None
Create a polar plot to visualize the frequency of each arrow direction in a pandas Series.
- Parameters:
arrows (pandas.Series) – A pandas Series containing arrow symbols as string data type.
figsize (Tuple[int, int], optional) – The width and height of the figure. Defaults to (6, 6).
**kwargs – Additional keyword arguments to be passed to the bar() method.
- Returns:
Displays the generated plot.
- Return type:
None
- yugiquery.utils.plot.box(df, mean: bool = True, **kwargs) None
Plots a box plot of a given DataFrame using seaborn, with the year of the Release column on the x-axis and the remaining column on the y-axis.
- Parameters:
df (pandas.DataFrame) – The input DataFrame containing the Release dates and another numeric column.
mean (bool, optional) – If True, plots a line representing the mean of each box. Defaults to True.
**kwargs – Additional keyword arguments to pass to seaborn.boxplot().
- Returns:
None
- Raises:
ValueError – If the DataFrame has no Release column.
- yugiquery.utils.plot.colors_dict = {"5D's": '#CCCCCC', '?': 'y', '???': '#ff7f0e', 'ARC-V': '#1D9E74', 'Character Card': '#FDE68A', 'Counter': '#C0C0C0', 'DARK': '#745ea5', 'DIVINE': '#7e6537', 'Duel Monsters': '#FF8B53', 'EARTH': '#060d0a', 'Effect Monster': '#FF8B53', 'Equip Card': '#1D9E74', 'FIRE': '#fd1b1b', 'First Series': '#FDE68A', 'Fusion Monster': '#A086B7', 'GO RUSH!!': '#BC5A84', 'GX': '#A086B7', 'LIGHT': '#9d8047', 'Level': '#f1a41f', 'Link Monster': '#00008B', 'Maximum Monsters': '#FF8B53', 'Monster Card': '#FF8B53', 'Monster Token': '#C0C0C0', 'Normal Monster': '#FDE68A', 'Pendulum Monster': '#1D9E74', 'Ritual Monster': '#9DB5CC', 'SEVENS': '#FF8B53', 'Skill Card': '#3571B4', 'Spell Card': '#1D9E74', 'Synchro Monster': '#CCCCCC', 'Trap Card': '#BC5A84', 'VRAINS': '#00008B', 'WATER': '#03a9e6', 'WIND': '#77bb58', 'Xyz Monster': '#000000', 'ZEXAL': '#000000'}
Dictionary containing the colors used in the plots.
- yugiquery.utils.plot.generate_rate_grid(dy: DataFrame, ax: Axes, xlabel: str = 'Date', size: str = '150%', pad: int = 0, colors: List[str] | None = None, cumsum: bool = True, fill: bool = False, limit_year: bool = False) axes
Generate a grid of subplots displaying yearly and monthly rates from a Pandas DataFrame.
- Parameters:
dy (pd.DataFrame) – A Pandas DataFrame containing the data to be plotted.
ax (AxesSubplot) – The subplot onto which to plot the grid.
xlabel (str, optional) – The label to be used for the x-axis. Default value is ‘Date’.
size (str, optional) – The size of the bottom subplot as a percentage of the top subplot. Default value is ‘150%’.
pad (int, optional) – The amount of padding between the two subplots in pixels. Default value is 0.
colors (List[str] | None, optional) – A list of colors to be used in the plot. If not provided, the default Matplotlib color cycle is used. Default value is None.
cumsum (bool, optional) – If True, plot the cumulative sum of the data. If False, plot only the yearly and monthly rates. Default value is True.
fill (bool, optional) – If True, fill the area under the cumulative sum curve. Default value is False.
limit_year (bool, optional) – If True, limit the x-axis to the next full year. Default value is False.
- Returns:
The generated subplot axes.
- Return type:
matplotlib.axes.Axes
- yugiquery.utils.plot.rate(dy: DataFrame, figsize: Tuple[int, int] = (12, 6), title: str | None = None, colors: List[str] | None = None, cumsum: bool = True, bg: DataFrame | None = None, vlines: DataFrame | None = None, fill: bool = False, limit_year: bool = False) None
Creates a single plot to visualize the rate of change over time of a single variable in a pandas DataFrame.
- Parameters:
dy (pd.DataFrame) – The pandas DataFrame containing the data to plot.
figsize (Tuple[int, int], optional) – The size of the figure to create. Default is (16, 6).
title (str | None, optional) – The title of the figure. Default is None.
colors (List[str] | None, optional) – The list of colors to use for the lines. If None, default colors are used.
cumsum (bool, optional) – Whether to plot the cumulative sum of the data. Default is True.
bg (pd.DataFrame | None, optional) – A DataFrame containing the background shading data. Default is None.
vlines (pd.DataFrame | None, optional) – A DataFrame containing the vertical line data. Default is None.
fill (bool, optional) – If True, fill the area under the cumulative sum curve. Default is False.
limit_year (bool, optional) – If True, limit the x-axis to the next full year. Default is False.
- Returns:
Displays the generated plot.
- Return type:
None
- yugiquery.utils.plot.rate_subplots(df: DataFrame, figsize: Tuple[int, int] | None = None, title: str = '', colors: List[str] | None = None, cumsum: bool = True, bg: DataFrame | None = None, vlines: DataFrame | None = None, fill: bool = False, limit_year: bool = False) None
Creates a grid of subplots to visualize rates of change over time of multiple variables in a pandas DataFrame.
- Parameters:
df (pd.DataFrame) – The pandas DataFrame containing the data to plot.
figsize (Tuple[int, int] | None, optional) – The size of the figure to create. If None, default size is (16, len(df.columns)*2*(1+cumsum)).
title (str, optional) – The title of the figure. Default is an empty string.
colors (List[str] | None, optional) – The list of colors to use for the lines. If None, default colors are used.
cumsum (bool, optional) – Whether to plot the cumulative sum of the data. Default is True.
bg (pd.DataFrame | None, optional) – A DataFrame containing the background shading data. Default is None.
vlines (pd.DataFrame | None, optional) – A DataFrame containing the vertical line data. Default is None.
fill (bool, optional) – If True, fill the area under the cumulative sum curve. Default is False.
limit_year (bool, optional) – If True, limit the x-axis to the next full year. Default is False.
- Returns:
Displays the generated plot.
- Return type:
None
Progress Handler Module
- class yugiquery.utils.progress_handler.ProgressHandler
Bases:
objectA progress handler class to comunicate progress of a process execution.
- Parameters:
queue (multiprocessing.Queue | None, optional) – The multiprocessing queue to communicate progress status. If None, a new queue is created. Defaults to None.
progress_bar (tqdm | None, optional) – The tqdm progress bar implementation. Defaults to None.
pbar_kwargs (Dict[str, Any], optional) – Keyword arguments to customize the progress bar. Defaults to None.
- queue
The multiprocessing queue to communicate progress status. If None, a new queue is created. Defaults to None.
- Type:
multiprocessing.Queue | None, optional
- progress_bar
The tqdm progress bar implementation. Defaults to None.
- Type:
tqdm | None, optional
- pbar_kwargs
Keyword arguments to customize the progress bar. Defaults to None.
- Type:
Dict[str, Any], optional
- __init__(queue: Queue | None = None, progress_bar: tqdm_asyncio | None = None, pbar_kwargs: Dict[str, Any] = {})
Initializes the ProgressHandler class.
- Parameters:
queue (multiprocessing.Queue | None, optional) – The multiprocessing queue to communicate progress status. If None, a new queue is created. Defaults to None.
progress_bar (tqdm | None, optional) – The tqdm progress bar implementation. Defaults to None.
pbar_kwargs (Dict[str, Any], optional) – Keyword arguments to customize the progress bar. Defaults to None.
- pbar(iterable, **kwargs) None | tqdm_asyncio
Initializes and returns a progress bar instance if progress_bar is not None.
- Parameters:
iterable (iterable) – The iterable to track progress.
**kwargs – Additional keyword arguments for the progress bar.
- Returns:
The initialized progress bar instance or None if progress_bar is None.
- Return type:
Progress bar instance or None
- send(**kwargs) None
Puts the keyword arguments into the queue
- Parameters:
**kwargs – Keyword arguments to put into the queue.
- Returns:
None