def save_phrase_table(phrase_table:defaultdict, filename):
    with open("phrase_table/"+filename, 'w') as file:
        file.write("Default = " + str(phrase_table.default_factory().default_factory())+"\n")
        for f,e_prob in phrase_table.items():
            file.write("********** f = "+f+"\n")
            for e,prob in e_prob.items():
                file.write(e +": "+str(prob)+"\n")
def compare_default_dicts(a: defaultdict, b: defaultdict) -> bool:
    """Compare two defaultdicts, return True if equal, else False.
    Does a benign or soft compare. If the defaultdicts COULD become
    equal, they are considered equal.

    * Does NOT change the memory imprint of any of the dictionaries.
    * Any overlapping keys, must have same value.
    * Keys unique to one, must have the default value of the other.
    * Order of input does NOT matter.

    Example:
    a = defaultdict(lambda: "", a=42, b=42, c="")
    b = defaultdict(lambda: 42, c="", d="")
    compare_defaultdicts(a, b) -> True

    Parameters
    ----------
    a : defaultdict
        Default dictionary from collections
    b : defaultdict:
        Default dictionary from collections

    Returns
    -------
    bool : True if equal, else False

    """
    a_keys = set(a)
    b_keys = set(b)
    a_unique_keys = (a_keys | b_keys) - b_keys
    b_unique_keys = (a_keys | b_keys) - a_keys

    # The intersecting keys must have the same value
    if not all(a[key] == b[key] for key in (a_keys & b_keys)):
        return False

    # Keys unique to one, must have default value of other.
    if not all(b.default_factory() == a[key] for key in a_unique_keys):
        return False
    if not all(a.default_factory() == b[key] for key in b_unique_keys):
        return False

    return True
Beispiel #3
0
def apply_filter(image: defaultdict, filter) -> defaultdict:
    yrange = [_[1] for _ in image]
    xrange = [_[0] for _ in image]
    x_scan_range = range(min(xrange) - 1, max(xrange) + 2)
    y_scan_range = range(min(yrange) - 1, max(yrange) + 2)

    ix = 511 if image.default_factory() else 0
    res = defaultdict(constant_factory(filter[ix]))

    for y in y_scan_range:
        ypixrange = range(y - 1, y + 2)
        for x in x_scan_range:
            xpixrange = range(x - 1, x + 2)
            index = []
            for yi in ypixrange:
                for xi in xpixrange:
                    index.append(map_to_binary_digit[image[(xi, yi)]])
            res[(x, y)] = filter[int("".join(index), 2)]
    return res
def save_t(t: defaultdict, filename):
    with open(get_path("/t_models/" + filename), "w") as file:
        file.write(str(t.default_factory()) + "\n")
        for k, v in t.items():
            file.write(str(k[0]) + "qq" + str(k[1]) + " q:q " + str(v) + "\n")