API Reference¶
- class pollywog.core.CalcSet(items)¶
Bases:
objectRepresents a Leapfrog-style calculation set, containing variables, calculations, categories, filters, and conditional logic.
CalcSet is the main container for building, manipulating, and exporting calculation workflows. It is designed to help automate large, complex, or repetitive calculation sets, and supports querying, dependency analysis, and rich display in Jupyter notebooks.
- Args:
items (list of Item): List of calculation items (Number, Category, Filter, If, etc.)
- Example:
>>> from pollywog.core import CalcSet, Number >>> calcset = CalcSet([ ... Number("Au_est", "block[Au] * 0.95"), ... Number("Ag_est", "block[Ag] * 0.85") ... ])
- copy()¶
Return a deep copy of the CalcSet and its items.
- Return type:
- Returns:
CalcSet: A new CalcSet instance with all items copied.
- query(expr, **external_vars)¶
Filter items in the CalcSet using a query expression.
The expression can use attributes of Item (e.g., ‘item_type == “variable” and name.startswith(“Au”)’), and external variables using @var syntax (like pandas).
- Return type:
- Args:
expr (str): Query expression to filter items. **external_vars: External variables to use in the query (referenced as @var).
- Returns:
CalcSet: New CalcSet with filtered items.
- Example:
>>> calcset.query('name.startswith("Au")')
- topological_sort()¶
Return a new CalcSet with items sorted topologically by dependencies.
This method analyzes variable dependencies and reorders items so that each calculation appears after all the calculations it depends on. This ensures calculations can be evaluated in the correct order.
- Return type:
- Returns:
CalcSet: New CalcSet with topologically sorted items.
- Raises:
ValueError: If cyclic dependencies are detected (e.g., A depends on B and B depends on A).
- Example:
>>> cs = CalcSet([ ... Number("result", "[intermediate] * 2"), ... Number("intermediate", "[input] + 1") ... ]) >>> sorted_cs = cs.topological_sort() # Now 'intermediate' will come before 'result'
- to_dict(sort_items=True)¶
Convert the CalcSet to a dictionary representation.
- Return type:
dict[str,Any]
- Args:
sort_items (bool): Whether to sort items by type.
- Returns:
dict: Dictionary representation of the calculation set.
- classmethod from_dict(data)¶
Create a CalcSet from a dictionary.
- Return type:
- Args:
data (dict): Dictionary containing calculation set data.
- Returns:
CalcSet: Instance of CalcSet.
- to_json(sort_items=True, indent=0)¶
Convert the CalcSet to a JSON string.
- Return type:
str
- Args:
sort_items (bool): Whether to sort items by type. indent (int): Indentation level for JSON output.
- Returns:
str: JSON string representation.
- to_lfcalc(filepath_or_buffer, sort_items=True)¶
Write the CalcSet to a Leapfrog .lfcalc file.
- Return type:
None
- Args:
filepath_or_buffer (str, Path, or file-like): Output file path or buffer. sort_items (bool): Whether to sort items by type.
- static read_lfcalc(filepath_or_buffer)¶
Read a Leapfrog .lfcalc file and return a CalcSet.
- Return type:
- Args:
filepath_or_buffer (str, Path, or file-like): Input file path or buffer.
- Returns:
CalcSet: Instance of CalcSet.
- rename(items=None, variables=None, regex=False)¶
Return a copy of the CalcSet with specified items renamed and/or variables in expression renamed.
- Return type:
- Args:
items (dict-like or function): Mapping of old item names to new names. variables (dict-like or function): Mapping of old variable names to new names. regex (bool): Whether to treat keys in items and variables as regex patterns.
- Returns:
CalcSet: New instance with updated item names and/or expression.
- class pollywog.core.Item(name='', expression=None, comment_item='', comment_equation='')¶
Bases:
objectBase class for all items in a CalcSet.
Subclasses represent specific calculation types (Number, Category, Variable, Filter, If, etc.). Each item has a name, expressions, and optional comments.
The expression parameter can be either a string or a list: - Use a string for simple expressions:
Number("result", "[x] * 2")- Use a list when including If objects for conditional logic:Number("result", [If(...)])Strings are automatically converted to single-element lists internally, but If objects are separate structures that cannot be embedded in expression strings, which is why the parameter accepts lists.
- Attributes:
name (str): Name of the item. expression (list): List of expressions/statements (internally stored as a list). comment_item (str): Comment for the item. comment_equation (str): Comment for the equation.
- item_type = None¶
- calculation_type = None¶
- to_dict()¶
Convert the Item to a dictionary representation.
- Return type:
dict[str,Any]
- Returns:
dict: Dictionary representation of the item.
- classmethod from_dict(data)¶
Create an Item from a dictionary.
- Return type:
- Args:
data (dict): Dictionary containing item data.
- Returns:
Item: Instance of Item or subclass.
- property dependencies: set[str]¶
Get the set of variable dependencies for this item.
- Returns:
set: Set of variable names that are dependencies.
- copy()¶
Return a deep copy of the Item.
- Return type:
- Returns:
Item: A new Item instance with all attributes copied.
- replace(**changes)¶
Return a copy of the Item with specified attributes replaced.
- Return type:
- Args:
**changes: Attributes to replace.
- Returns:
Item: New instance with updated attributes.
- rename(name=None, variables=None, regex=False)¶
Return a copy of the Item with a new name and/or renamed variables in expression.
- Return type:
- Args:
name (str): New name for the item. variables (dict-like or function): Mapping of old variable names to new names. regex (bool): Whether to treat keys in variables as regex patterns.
- Returns:
Item: New instance with updated name and/or expression.
- class pollywog.core.IfRow(condition, value)¶
Bases:
objectRepresents a single row in an If block, containing a condition and corresponding value(s).
- Args:
condition (list): Condition expressions. value (list): Value expressions if condition is met.
- to_dict()¶
Convert the IfRow to a dictionary representation.
- Return type:
dict[str,Any]
- Returns:
dict: Dictionary representation of the IfRow.
- classmethod from_dict(data)¶
Create an IfRow from a dictionary.
- Return type:
- Args:
data (dict): Dictionary containing IfRow data.
- Returns:
IfRow: Instance of IfRow.
- class pollywog.core.If(*args, **kwargs)¶
Bases:
objectRepresents a conditional logic block (if/else) in a calculation set.
- Args:
rows (list): List of IfRow objects, dicts, or (condition, value) tuples. otherwise (list): Expressions for the ‘otherwise’ case.
Alternatively, in case of a single condition and value, these may be provided directly as three parameters:
- Args:
condition: condition expression. then: value expression if condition is met. otherwise: value expression if no conditions are met.
- Example:
>>> from pollywog.core import If, Number >>> if_block = If([ ... ("[Au] > 1", "[Au] * 1.1"), ... ("[Au] <= 1", "[Au] * 0.9") ... ], otherwise=["[Au]"])
- Example of the second case:
>>> from pollywog.core import If, Number >>> if_block = If("[Au] > 1", "[Au] * 1.1", "[Au]")
- to_dict()¶
Convert the If expression to a dictionary representation.
- Return type:
dict[str,Any]
- Returns:
dict: Dictionary representation of the If expression.
- classmethod from_dict(data)¶
Create an If expression from a dictionary.
- Return type:
- Args:
data (dict): Dictionary containing If expression data.
- Returns:
If: Instance of If.
- class pollywog.core.Number(name='', expression=None, comment_item='', comment_equation='')¶
Bases:
ItemRepresents a numeric calculation item in a CalcSet.
Used for calculations whose values are numbers, either integers or floats. This is the most common type of calculation in Leapfrog calculation sets.
- Example:
>>> from pollywog.core import Number >>> # Simple expression using positional arguments >>> au_calc = Number("Au_adjusted", "[Au] * 0.95") >>> # With comment >>> au_calc = Number("Au_adjusted", "[Au] * 0.95", comment_equation="Apply dilution")
- item_type = 'calculation'¶
- calculation_type = 'number'¶
- class pollywog.core.Category(name='', expression=None, comment_item='', comment_equation='')¶
Bases:
ItemRepresents a categorical (string) calculation item in a CalcSet.
Used for calculations whose values are categories or text labels. Commonly used for classification, domain assignment, or text manipulation.
- Example:
>>> from pollywog.core import Category, If >>> # Simple string category >>> domain = Category("rock_type", "'granite'") >>> # Conditional category using If (requires list) >>> grade_class = Category("grade_class", [If("[Au] > 1", "High", "Low")])
- item_type = 'calculation'¶
- calculation_type = 'string'¶
- class pollywog.core.Variable(name='', expression=None, comment_item='', comment_equation='')¶
Bases:
ItemRepresents a variable item in a calculation set.
Variables can perform calculations but are not available outside the scope of the calculation set. They are typically used as parameters or intermediate values that are referenced by other calculations.
- Example:
>>> from pollywog.core import Variable >>> au_var = Variable(name="Au", comment_item="Gold grade from drillhole database")
- item_type = 'variable'¶
- class pollywog.core.Filter(name='', expression=None, comment_item='', comment_equation='')¶
Bases:
ItemRepresents a filter item in a calculation set.
Filters define conditions that restrict or modify which data is included in calculations. They evaluate to boolean values.
- Example:
>>> from pollywog.core import Filter >>> ore_filter = Filter("is_ore", "[Au] > 0.5")
- item_type = 'filter'¶
- pollywog.core.dispatch_expression(data)¶
Dispatch an expression dictionary to the appropriate class constructor.
- Return type:
Any
- Args:
data (dict or any): Expression data.
- Returns:
object: Instantiated expression object or the original data if not a dict.
- pollywog.core.get_dependencies(item)¶
Recursively extract variable dependencies from an Item or expression.
- Return type:
set[str]
- Args:
item (Item or expression): The item or expression to analyze.
- Returns:
set: Set of variable names that are dependencies.
- pollywog.core.rename(item, mapper, regex=False)¶
Recursively rename variables in an Item or expression based on a mapping dictionary.
- Return type:
Any
- Args:
item (Item or expression): The item or expression to rename. mapper (dict-like or function): Mapping of old variable names to new names. regex (bool): If True, treat keys and values of the mapper as regular expressions.
- Returns:
Item or expression: The renamed item or expression.
- pollywog.display.set_theme(theme)¶
Set the global theme for display_calcset.
- Args:
theme (str): Theme name, either “light” or “dark”.
- Raises:
ValueError: If theme is not “light” or “dark”.
- pollywog.display.get_color_palette(theme=None, colors=None)¶
Get the color palette for a given theme.
- Args:
- theme (str, optional): Visual theme, either “light” or “dark”.
If None, uses the global theme. Defaults to None.
- colors (dict, optional): Custom color palette to override theme defaults.
Defaults to None.
- Returns:
dict: Color palette with keys for ‘background’, ‘text’, ‘variable’, etc.
- pollywog.display.render_expression(expr, palette, indent=0)¶
Render an expression as HTML with syntax highlighting.
- Args:
expr: Expression to render (string, list, dict, or other). palette (dict): Color palette for styling. indent (int): Indentation level. Defaults to 0.
- Returns:
str: HTML representation of the expression.
- pollywog.display.render_equation(eq, palette)¶
Render an equation as HTML.
- Args:
eq: Equation to render (dict or other). palette (dict): Color palette for styling.
- Returns:
str: HTML representation of the equation.
- pollywog.display.render_item(item, palette)¶
Render a single Item (Number, Category, Variable, Filter, etc.) as HTML.
- Args:
item: The item to render (must have to_dict() method). palette (dict): Color palette for styling.
- Returns:
str: HTML representation of the item.
- pollywog.display.display_item(item, theme=None, colors=None, display_output=True)¶
Display a single Item (Number, Category, Variable, Filter, etc.) in a Jupyter notebook.
This function renders individual calculation items with Leapfrog-style visual formatting.
- Args:
item: The item to display (Number, Category, Variable, Filter, etc.). theme (str, optional): Visual theme, either “light” or “dark”.
If None, uses the global theme set by set_theme(). Defaults to None.
- colors (dict, optional): Custom color palette to override theme defaults.
Keys can include: ‘background’, ‘text’, ‘variable’, ‘label’, ‘if’, ‘arrow’, ‘comment’, ‘var_ref’. Defaults to None.
- display_output (bool): Whether to display output in Jupyter.
If False, returns HTML string. Defaults to True.
- Returns:
- str or None: If display_output is False, returns HTML string.
Otherwise displays in Jupyter and returns None.
- Example:
>>> from pollywog.core import Number >>> from pollywog.display import display_item >>> n = Number(name="x2", children=["[x] * 2"]) >>> display_item(n, theme="dark")
- pollywog.display.display_calcset(calcset, theme=None, colors=None, display_output=True)¶
Display a CalcSet in a Jupyter notebook with Leapfrog-style visual formatting.
This function renders calculation sets with visual styling similar to Leapfrog, making equations and logic blocks easy to read and understand.
- Args:
calcset (CalcSet): The calculation set to display. theme (str, optional): Visual theme, either “light” or “dark”.
If None, uses the global theme set by set_theme(). Defaults to None.
- colors (dict, optional): Custom color palette to override theme defaults.
Keys can include: ‘background’, ‘text’, ‘variable’, ‘label’, ‘if’, ‘arrow’, ‘comment’, ‘var_ref’. Defaults to None.
- display_output (bool): Whether to display output in Jupyter.
If False, returns HTML string. Defaults to True.
- Returns:
- str or None: If display_output is False, returns HTML string.
Otherwise displays in Jupyter and returns None.
- Example:
>>> from pollywog.core import CalcSet, Number >>> from pollywog.display import display_calcset >>> cs = CalcSet([Number(name="x2", children=["[x] * 2"])]) >>> display_calcset(cs, theme="dark")
- pollywog.helpers.Sum(variables, name=None, comment=None, ignore_functions=True)¶
Create a sum expression or a Number representing the sum of the given variables.
- Args:
variables (list of str): Variable names (as strings) to sum, e.g. [“Au”, “Ag”]. name (str, optional): Name for the output variable. If provided, returns a Number; if None, returns the sum expression as a string. comment (str, optional): Optional comment for the calculation. Used only if name is provided. ignore_functions (bool): If True, strings that appear to be function
calls (e.g., “max([Au], [Ag])”) are not wrapped in brackets. Defaults to True.
- Returns:
Number or str: If name is provided, returns a pollywog Number representing the sum calculation. If name is None, returns the sum expression as a string.
- Raises:
ValueError: If variables is empty.
- Example:
>>> from pollywog.helpers import Sum >>> Sum(["Au", "Ag"], name="total_precious") >>> Sum(["Au", "Ag", "Cu"])
- pollywog.helpers.WeightedSum(variables, weights, name=None, comment=None, ignore_functions=True)¶
Create a weighted sum expression or a Number representing the weighted sum of the given variables.
- Args:
variables (list of str): Variable names (as strings) to sum, e.g. [“Au”, “Ag”]. weights (list of float or str): Corresponding weights for each variable. Can be constants or variable names. name (str, optional): Name for the output variable. If provided, returns a Number; if None, returns the weighted sum expression as a string. comment (str, optional): Optional comment for the calculation. Used only if name is provided. ignore_functions (bool): If True, strings that appear to be function
calls (e.g., “max([Au], [Ag])”) are not wrapped in brackets. Defaults to True.
- Returns:
Number or str: If name is provided, returns a pollywog Number representing the weighted sum calculation. If name is None, returns the weighted sum expression as a string.
- Raises:
ValueError: If variables and weights are empty or have different lengths.
- pollywog.helpers.Product(variables, name=None, comment=None, ignore_functions=True)¶
Create a product expression or a Number representing the product of the given variables.
- Args:
variables (list of str): Variable names (as strings) to multiply, e.g. [“Au”, “Ag”]. name (str, optional): Name for the output variable. If provided, returns a Number; if None, returns the product expression as a string. comment (str, optional): Optional comment for the calculation. Used only if name is provided. ignore_functions (bool): If True, strings that appear to be function
calls (e.g., “max([Au], [Ag])”) are not wrapped in brackets. Defaults to True.
- Returns:
Number or str: If name is provided, returns a pollywog Number representing the product calculation. If name is None, returns the product expression as a string.
- Raises:
ValueError: If variables is empty.
- Example:
>>> from pollywog.helpers import Product >>> Product(["grade", "tonnage"], name="metal_content") >>> Product(["Au", "recovery", "price"])
- pollywog.helpers.Normalize(variable, min_value, max_value, name=None, comment=None, ignore_functions=True)¶
Create a normalization expression or a Number that normalizes a variable to the range [0, 1].
- Args:
variable (str): Variable name to normalize. min_value (float): Minimum value for normalization (maps to 0). max_value (float): Maximum value for normalization (maps to 1). name (str, optional): Name for the output variable. If provided, returns a Number; if None, returns the normalization expression as a string. comment (str, optional): Optional comment for the calculation. Used only if name is provided. ignore_functions (bool): If True, strings that appear to be function
calls (e.g., “max([Au], [Ag])”) are not wrapped in brackets. Defaults to True.
- Returns:
Number or str: If name is provided, returns a pollywog Number representing the normalization calculation. If name is None, returns the normalization expression as a string.
- Example:
>>> from pollywog.helpers import Normalize >>> Normalize("Au", 0, 10, name="Au_normalized") >>> Normalize("porosity", 0.1, 0.3)
- pollywog.helpers.Average(variables, name=None, comment=None, ignore_functions=True)¶
Create an average expression or a Number representing the arithmetic mean of the given variables.
- Args:
variables (list of str): Variable names (as strings) to average, e.g. [“Au”, “Ag”]. name (str, optional): Name for the output variable. If provided, returns a Number; if None, returns the average expression as a string. comment (str, optional): Optional comment for the calculation. Used only if name is provided. ignore_functions (bool): If True, strings that appear to be function
calls (e.g., “max([Au], [Ag])”) are not wrapped in brackets. Defaults to True.
- Returns:
Number or str: If name is provided, returns a pollywog Number representing the average calculation. If name is None, returns the average expression as a string.
- Raises:
ValueError: If variables is empty.
- Example:
>>> from pollywog.helpers import Average >>> Average(["Au_est1", "Au_est2", "Au_est3"], name="Au_avg") >>> Average(["density_dry", "density_wet"])
- pollywog.helpers.WeightedAverage(variables, weights, name=None, comment=None, ignore_functions=True)¶
Create a weighted average expression or a Number representing the weighted average of variables.
- Args:
variables (list of str): Variable names to average, e.g. [“Au”, “Ag”, “Cu”]. weights (list of float or str): Corresponding weights for each variable. Can be constants or variable names. name (str, optional): Name for the output variable. If provided, returns a Number; if None, returns the weighted average expression as a string. comment (str, optional): Optional comment for the calculation. Used only if name is provided. ignore_functions (bool): If True, strings that appear to be function
calls (e.g., “max([Au], [Ag])”) are not wrapped in brackets. Defaults to True.
- Returns:
Number or str: If name is provided, returns a pollywog Number representing the weighted average calculation. If name is None, returns the weighted average expression as a string.
- Raises:
ValueError: If variables and weights are empty or have different lengths.
- Example:
>>> from pollywog.helpers import WeightedAverage >>> WeightedAverage(["Au_oxide", "Au_sulfide"], [0.7, 0.3], name="Au_composite") >>> WeightedAverage(["est1", "est2"], ["weight1", "weight2"])
- pollywog.helpers.Scale(variable, factor, name=None, comment=None)¶
Create a scaling expression or a Number that multiplies a variable by a scaling factor.
- Args:
variable (str): Variable name to scale. factor (float or str): Scaling factor. Can be a numeric constant or another variable name. name (str, optional): Name for the output variable. If provided, returns a Number; if None, returns the scaling expression as a string. comment (str, optional): Optional comment for the calculation. Used only if name is provided.
- Returns:
Number or str: If name is provided, returns a pollywog Number representing the scaled variable. If name is None, returns the scaling expression as a string.
- Example:
>>> from pollywog.helpers import Scale >>> Scale("Au_ppm", 0.001, name="Au_percent") >>> Scale("tonnes", 2204.62)
- pollywog.helpers.NumberFromThresholds(variable, thresholds, values, name=None, comment=None, ignore_functions=True)¶
Create a conditional block or a Number that assigns numeric values based on thresholds.
- Args:
variable (str): Variable to evaluate, with or without brackets. thresholds (list of float): Threshold values in ascending order. values (list of float or str): Numeric values for each range. Must have exactly one more element than thresholds. name (str, optional): Name for the output variable. If provided, returns a Number; if None, returns the If block. comment (str, optional): Optional comment for the calculation. Used only if name is provided. ignore_functions (bool): If True, strings that appear to be function
calls (e.g., “max([Au], [Ag])”) are not wrapped in brackets. Defaults to True.
- Returns:
Number or If: If name is provided, returns a pollywog Number. If name is None, returns the If block.
- Raises:
ValueError: If len(values) != len(thresholds) + 1.
- Example:
>>> from pollywog.helpers import NumberFromThresholds >>> NumberFromThresholds("Au", [0.5, 1.0], [0, 0.5, 1.0], name="Au_score")
- pollywog.helpers.CategoryFromThresholds(variable, thresholds, categories, name=None, comment=None, ignore_functions=True)¶
Create a conditional block or a Category that assigns labels based on value thresholds.
- Args:
variable (str): Variable to classify, with or without brackets. thresholds (list of float): Threshold values in ascending order. These define the boundaries between categories. categories (list of str): Category labels. Must have exactly one more element than thresholds. name (str, optional): Name for the output category. If provided, returns a Category; if None, returns the If block (conditional logic) for further encapsulation. comment (str, optional): Optional comment for the calculation. Used only if name is provided. ignore_functions (bool): If True, strings that appear to be function
calls (e.g., “max([Au], [Ag])”) are not wrapped in brackets. Defaults to True.
- Returns:
Category or If: If name is provided, returns a pollywog Category with conditional logic for threshold-based classification. If name is None, returns the If block (conditional logic) for further use.
- Raises:
ValueError: If len(categories) != len(thresholds) + 1.
- Example:
>>> from pollywog.helpers import CategoryFromThresholds >>> CategoryFromThresholds("Au", [0.5, 1.0, 2.0], ["Waste", "Low Grade", "Medium Grade", "High Grade"], name="ore_class") >>> CategoryFromThresholds("Au", [0.5, 1.0, 2.0], ["Waste", "Low Grade", "Medium Grade", "High Grade"])