Skip to content

base

base

DATA_PRODUCTS_FNAME_DEFAULT module-attribute

DATA_PRODUCTS_FNAME_DEFAULT = 'data_products.json'

Hard-coded file name for storing data products in batch-processed input directories.

ProductGenerator module-attribute

ProductGenerator = Callable[[Path], ProductList]

Callable method type. Users must provide a ProductGenerator to map over raw data.

Parameters:

Name Type Description Default
path Path

Workdir holding raw data (Should be one per run from a batch)

required

Returns:

Type Description
ProductList

List of data products to be sorted and used to produce assets

ProductList module-attribute

ProductList = List[SerializeAsAny[InstanceOf[DataProduct]]]

List of serializable DataProduct or child classes thereof

Tag module-attribute

Tag = Union[Tuple[Hashable, ...], Hashable]

Determines what types can be used to define a tag

Tags module-attribute

Tags = List[Tag]

List of tags

DataProduct pydantic-model

Bases: BaseModel

Base class for data products to be generated and handled.

Attributes:

Name Type Description
product_type str

Product type should be the same as the class name. The product type is used to search for products from a DataProductCollection.

tags Tags

Tags to be used for sorting data.

metadata dict[str, str]

A dictionary of metadata to be used as a tool tip for mousover in grafana

Show JSON schema:
{
  "additionalProperties": true,
  "description": "Base class for data products to be generated and handled.\n\nAttributes:\n    product_type (str): Product type should be the same as the class name.\n        The product type is used to search for products from a [DataProductCollection][trendify.api.DataProductCollection].\n    tags (Tags): Tags to be used for sorting data.\n    metadata (dict[str, str]): A dictionary of metadata to be used as a tool tip for mousover in grafana",
  "properties": {
    "tags": {
      "items": {
        "anyOf": []
      },
      "title": "Tags",
      "type": "array"
    },
    "metadata": {
      "additionalProperties": {
        "type": "string"
      },
      "default": {},
      "title": "Metadata",
      "type": "object"
    }
  },
  "required": [
    "tags"
  ],
  "title": "DataProduct",
  "type": "object"
}

Config:

  • extra: 'allow'

Fields:

Validators:

  • _remove_computed_fields

product_type pydantic-field

product_type: str

Returns:

Type Description
str

Product type should be the same as the class name. The product type is used to search for products from a DataProductCollection.

__init_subclass__

__init_subclass__(**kwargs: Any) -> None

Registers child subclasses to be able to parse them from JSON file using the deserialize_child_classes method

Source code in src/trendify/api/base/data_product.py
def __init_subclass__(cls, **kwargs: Any) -> None:
    """
    Registers child subclasses to be able to parse them from JSON file using the
    [deserialize_child_classes][trendify.api.DataProduct.deserialize_child_classes] method
    """
    super().__init_subclass__(**kwargs)
    _data_product_subclass_registry[cls.__name__] = cls

append_to_list

append_to_list(l: List)

Appends self to list.

Parameters:

Name Type Description Default
l List

list to which self will be appended

required

Returns:

Type Description
Self

returns instance of self

Source code in src/trendify/api/base/data_product.py
def append_to_list(self, l: List):
    """
    Appends self to list.

    Args:
        l (List): list to which `self` will be appended

    Returns:
        (Self): returns instance of `self`
    """
    l.append(self)
    return self

deserialize_child_classes classmethod

deserialize_child_classes(key: str, **kwargs)

Loads json data to pydandic dataclass of whatever DataProduct child time is appropriate

Parameters:

Name Type Description Default
key str

json key

required
kwargs dict

json entries stored under given key

{}
Source code in src/trendify/api/base/data_product.py
@classmethod
def deserialize_child_classes(cls, key: str, **kwargs):
    """
    Loads json data to pydandic dataclass of whatever DataProduct child time is appropriate

    Args:
        key (str): json key
        kwargs (dict): json entries stored under given key
    """
    type_key = "product_type"
    elements = kwargs.get(key, None)
    if elements:
        for index in range(len(kwargs[key])):
            duck_info = kwargs[key][index]
            if isinstance(duck_info, dict):
                product_type = duck_info.pop(type_key)
                duck_type = _data_product_subclass_registry[product_type]
                kwargs[key][index] = duck_type(**duck_info)

HashableBase pydantic-model

Bases: BaseModel

Defines a base for hashable pydantic data classes so that they can be reduced to a minimal set through type-casting.

Show JSON schema:
{
  "description": "Defines a base for hashable pydantic data classes so that they can be reduced to a minimal set through type-casting.",
  "properties": {},
  "title": "HashableBase",
  "type": "object"
}

__hash__

__hash__()

Defines hash function

Source code in src/trendify/api/base/helpers.py
def __hash__(self):
    """
    Defines hash function
    """
    return hash((type(self),) + tuple(self.__dict__.values()))

Pen pydantic-model

Bases: HashableBase

Defines the pen drawing to matplotlib.

Attributes:

Name Type Description
color str

Color of line

size float

Line width

alpha float

Opacity from 0 to 1 (inclusive)

linestyle Union[str, Tuple[int, Tuple[int, ...]]]

Linestyle to plot. Supports str or tuple definition (matplotlib documentation).

zorder float

Prioritization

label Union[str, None]

Legend label

Show JSON schema:
{
  "additionalProperties": false,
  "description": "Defines the pen drawing to matplotlib.\n\nAttributes:\n    color (str): Color of line\n    size (float): Line width\n    alpha (float): Opacity from 0 to 1 (inclusive)\n    linestyle (Union[str, Tuple[int, Tuple[int, ...]]]): Linestyle to plot. Supports `str` or `tuple` definition ([matplotlib documentation](https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html)).\n    zorder (float): Prioritization\n    label (Union[str, None]): Legend label",
  "properties": {
    "color": {
      "anyOf": [
        {
          "maxItems": 3,
          "minItems": 3,
          "prefixItems": [
            {
              "type": "number"
            },
            {
              "type": "number"
            },
            {
              "type": "number"
            }
          ],
          "type": "array"
        },
        {
          "maxItems": 4,
          "minItems": 4,
          "prefixItems": [
            {
              "type": "number"
            },
            {
              "type": "number"
            },
            {
              "type": "number"
            },
            {
              "type": "number"
            }
          ],
          "type": "array"
        },
        {
          "type": "string"
        }
      ],
      "default": "k",
      "title": "Color"
    },
    "size": {
      "default": 1,
      "title": "Size",
      "type": "number"
    },
    "alpha": {
      "default": 1,
      "title": "Alpha",
      "type": "number"
    },
    "zorder": {
      "default": 0,
      "title": "Zorder",
      "type": "number"
    },
    "linestyle": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "maxItems": 2,
          "minItems": 2,
          "prefixItems": [
            {
              "type": "integer"
            },
            {
              "items": {
                "type": "integer"
              },
              "type": "array"
            }
          ],
          "type": "array"
        }
      ],
      "default": "-",
      "title": "Linestyle"
    },
    "label": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Label"
    }
  },
  "title": "Pen",
  "type": "object"
}

Config:

  • extra: 'forbid'

Fields:

rgba pydantic-field

rgba: str

Convert the pen's color to rgba string format.

Returns:

Name Type Description
str str

Color in 'rgba(r,g,b,a)' format where r,g,b are 0-255 and a is 0-1

as_scatter_plot_kwargs

as_scatter_plot_kwargs()

Returns kwargs dictionary for passing to matplotlib plot method

Source code in src/trendify/api/base/pen.py
def as_scatter_plot_kwargs(self):
    """
    Returns kwargs dictionary for passing to [matplotlib plot][matplotlib.axes.Axes.plot] method
    """
    return {
        "color": self.color,
        "linewidth": self.size,
        "linestyle": self.linestyle,
        "alpha": self.alpha,
        "zorder": self.zorder,
        "label": self.label,
    }

get_contrast_color

get_contrast_color(background_luminance: float = 1.0) -> str

Returns 'white' or 'black' to provide the best contrast against the pen's color, taking into account the alpha (transparency) value of the line.

Parameters:

Name Type Description Default
background_luminance float

The luminance of the background (default is 1.0 for white).

1.0

Returns:

Name Type Description
str str

'white' or 'black'

Source code in src/trendify/api/base/pen.py
def get_contrast_color(self, background_luminance: float = 1.0) -> str:
    """
    Returns 'white' or 'black' to provide the best contrast against the pen's color,
    taking into account the alpha (transparency) value of the line.

    Args:
        background_luminance (float): The luminance of the background (default is 1.0 for white).

    Returns:
        str: 'white' or 'black'
    """
    # Convert the pen's color to RGB (0-255 range) and get alpha
    if isinstance(self.color, tuple):
        if len(self.color) == 3:  # RGB tuple
            r, g, b = self.color
            a = self.alpha
        else:  # RGBA tuple
            r, g, b, a = self.color
        r, g, b = int(r * 255), int(g * 255), int(b * 255)
    else:  # String color (name or hex)
        rgba_vals = to_rgba(self.color, self.alpha)
        r, g, b = [int(x * 255) for x in rgba_vals[:3]]
        a = rgba_vals[3]

    # Calculate relative luminance of the pen's color
    def luminance(channel):
        channel /= 255.0
        return (
            channel / 12.92
            if channel <= 0.03928
            else ((channel + 0.055) / 1.055) ** 2.4
        )

    color_luminance = (
        0.2126 * luminance(r) + 0.7152 * luminance(g) + 0.0722 * luminance(b)
    )

    # Blend the color luminance with the background luminance based on alpha
    blended_luminance = (1 - a) * background_luminance + a * color_luminance

    # Return white for dark blended colors, black for light blended colors
    return "white" if blended_luminance < 0.5 else "black"

ProductType

Bases: StrEnum

Defines all product types. Used to type-cast URL info in server to validate.

Attributes:

Name Type Description
DataProduct str

class name

XYData str

class name

Trace2D str

class name

Point2D str

class name

TableEntry str

class name

HistogramEntry str

class name