Skip to content
Snippets Groups Projects
say_info.py 1.58 KiB
import re
from collections import defaultdict
"""Extract SAY titles and numbers from SAY trace nodes."""

_pattern = re.compile(r"\s+[0-9.]+\s+")

# Return {say text, [numbers]} where:
#   * say_text is say text with index prepended and numbers removed
#   * and numbers is a list of zero or more numbers.
# Say nodes are type="T"."""
def say_info(gry_graph):
    if not "trace" in gry_graph:
        raise RuntimeError("bad")

    says = defaultdict(list)
    for gry_node in gry_graph["trace"]["nodes"]:
        if gry_node["type"] == "T":
            label = gry_node["label"]
            key = _pattern.sub(" ", label)
            numbers = _pattern.findall(label)
            for i, number in enumerate(numbers, 1):
                try:
                    says["%i: %s"%(i, key)] = float(number)
                except Exception as e:
                    # multiple decimal places can thwart _pattern so manage
                    # invalid sortable numbers as text
                    print("say_info.say_info: invalid number: %s"%number)
                    says["%i: %s"%(i, key)] = number
    return says

# Return a list of "say text" column names.
def say_column_names(graphs):
    if len(graphs) >= 2:
        says = say_info(graphs[1].gry_graph)
        return sorted(says.keys())
    else:
        return list()

# Return a dict of {key="say text", value=column index}
def say_column_map(graphs, start_index):
    column_names = say_column_names(graphs)
    column_map = dict()
    for i, column_name in enumerate(column_names, start_index):
         column_map[column_name] = i
    return column_map