Ejemplo n.º 1
0
def parse_confident_atoms(graph_parse):
    core_parse = graph_parse.core_parse
    line_graph = graph_parse.line_graph
    circle_dict = graph_parse.circle_dict
    confident_variable_nodes = []

    for from_key, to_key, data in line_graph.edges(data=True):
        line_variable = FunctionNode(function_signatures['Line'],
                                     [core_parse.point_variables[from_key], core_parse.point_variables[to_key]])
        points = data['points']
        for point_key, point in points.iteritems():
            point_variable = core_parse.point_variables[point_key]
            variable_node = FunctionNode(function_signatures['PointLiesOnLine'], [point_variable, line_variable])
            confident_variable_nodes.append(variable_node)

    for center_key, d in circle_dict.iteritems():
        for radius_key, dd in d.iteritems():
            circle_variable = FunctionNode(function_signatures['Circle'],
                                           [core_parse.point_variables[center_key],
                                            core_parse.radius_variables[center_key][radius_key]])
            points = dd['points']
            for point_key, point in points.iteritems():
                point_variable = core_parse.point_variables[point_key]
                variable_node = FunctionNode(function_signatures['PointLiesOnCircle'], [point_variable, circle_variable])
                confident_variable_nodes.append(variable_node)

    return confident_variable_nodes
Ejemplo n.º 2
0
def _ground_leaf(match_parse, leaf, return_type):
    assert isinstance(leaf, FunctionNode)
    assert isinstance(match_parse, MatchParse)
    variable_signature = leaf.signature
    if return_type == 'number':
        return FunctionNode(variable_signature, [])
    elif return_type == 'point':
        return match_parse.match_dict[variable_signature.id][0]
    elif return_type == 'line':
        assert len(variable_signature.id) == 2
        label_a, label_b = variable_signature.id
        point_a = match_parse.match_dict[label_a][0]
        point_b = match_parse.match_dict[label_b][0]
        return FunctionNode(function_signatures['Line'], [point_a, point_b])
    elif return_type == 'circle':
        assert len(variable_signature.id) == 1
        center_label = variable_signature.id
        center = match_parse.match_dict[center_label][0]
        center_idx = int(center.signature.id.split("_")[1])
        radius = match_parse.graph_parse.core_parse.radius_variables[
            center_idx][0]
        return FunctionNode(function_signatures['Circle'], [center, radius])
    elif return_type == 'triangle':
        pass
    elif return_type == 'quad':
        pass
Ejemplo n.º 3
0
def prefix_to_formula(prefix):
    """

    :param list prefix:
    :return FunctionNode:
    """
    if isinstance(prefix, str):
        try:
            return float(prefix)
        except:
            return FunctionNode(VariableSignature(prefix, 'root'), [])
    else:
        return FunctionNode(function_signatures[abbreviations[prefix[0]]],
                            [prefix_to_formula(child) for child in prefix[1:]])
Ejemplo n.º 4
0
 def number(self, name, init=None):
     assert name not in self.variables
     if init is None:
         init = np.random.rand()
     self.variables[name] = init
     vn = FunctionNode(VariableSignature(name, 'number'), [])
     self.named_entities[name] = vn
     return vn
Ejemplo n.º 5
0
def _ground_atom(match_parse, atom):
    if not isinstance(atom, FunctionNode):
        return atom
    elif atom.is_leaf():
        return _ground_leaf(match_parse, atom, atom.return_type)
    else:
        children = [
            _ground_atom(match_parse, child) for child in atom.children
        ]
        return FunctionNode(atom.signature, children)
Ejemplo n.º 6
0
def parse_match_atoms(match_parse):
    assert isinstance(match_parse, MatchParse)
    match_atoms = []
    for label, terms in match_parse.match_dict.iteritems():
        for term in terms:
            assert isinstance(term, FunctionNode)
            if issubtype(term.return_type, 'entity'):
                continue

            # FIXME : to be obtained by tag model
            try:
                left_term = float(label)
            except:
                vs = VariableSignature(label, 'number')
                left_term = FunctionNode(vs, [])

            atom = FunctionNode(function_signatures['Equals'],
                                [left_term, term])
            match_atoms.append(atom)

    return match_atoms
Ejemplo n.º 7
0
def parse_core(primitive_parse):
    all_intersections = _get_all_intersections(primitive_parse, params.INTERSECTION_EPS)
    clustered_intersections = _cluster_intersections(all_intersections, params.KMEANS_RADIUS_THRESHOLD)
    intersections = dict(enumerate(clustered_intersections))
    assignment = {}
    point_variables = {}
    for idx in intersections.keys():
        id_ = "point_%d" % idx
        vs = VariableSignature(id_, 'point')
        point_variables[idx] = FunctionNode(vs, [])
        assignment[id_] = intersections[idx]
    circles = _get_circles(primitive_parse, intersections)
    radius_variables = {}
    for point_idx, d in circles.iteritems():
        radius_variables[point_idx] = {}
        for radius_idx in d.keys():
            id_ = "radius_%d_%d" % (point_idx, radius_idx)
            vs = VariableSignature(id_, 'number')
            radius_variables[point_idx][radius_idx] = FunctionNode(vs, [])
            assignment[id_] = circles[point_idx][radius_idx].radius
    core_parse = CoreParse(primitive_parse, intersections, point_variables, circles, radius_variables, assignment)
    return core_parse
Ejemplo n.º 8
0
    def add(self, function_node):
        if not isinstance(function_node, FunctionNode):
            return function_node

        if function_node.is_leaf():
            if function_node.signature.id in self.named_entities:
                return self.named_entities[function_node.signature.id]
            elif function_node.return_type == "point":
                return self.point(function_node.signature.id)
            elif function_node.return_type == "number":
                return self.number(function_node.signature.id)
            else:
                raise Exception()
        else:
            children = [self.add(child) for child in function_node.children]
            return FunctionNode(function_node.signature, children)
Ejemplo n.º 9
0
 def apply(self, name, *args):
     vn = FunctionNode(function_signatures[name], args)
     if name in ['Point', 'Line', 'Circle']:
         self.entities.append(vn)
     return vn
Ejemplo n.º 10
0
def v(name, return_type):
    vs = VariableSignature(name, return_type)
    return FunctionNode(vs, [])
Ejemplo n.º 11
0
def f(name, *args):
    return FunctionNode(function_signatures[name], args)
Ejemplo n.º 12
0
def parse_match_from_known_labels(graph_parse, known_labels):
    assert isinstance(graph_parse, GraphParse)
    match_dict = {}
    offset = graph_parse.image_segment_parse.diagram_image_segment.offset
    for idx, d in enumerate(known_labels):
        label = d['label']
        x = d['x'] - offset[0]
        y = d['y'] - offset[1]
        label_point = instantiators['point'](x, y)
        type_ = d['type']
        arr = type_.split(' ')
        if len(arr) > 1:
            type_ = arr[-1]

        # Find closest type_ instance's key in graph_parse
        instances = get_all_instances(graph_parse, type_)
        if len(arr) > 1 and type_ == 'line' and arr[0] == 'length':
            distances = [(key,
                          label_distance_to_line(label_point, instance, True))
                         for key, instance in instances.iteritems()]
        elif type_ == 'line':
            distances = [(key,
                          label_distance_to_line(label_point, instance, False))
                         for key, instance in instances.iteritems()]
        elif type_ == 'point':
            distances = [(key, label_distance_to_point(label_point, instance))
                         for key, instance in instances.iteritems()]
        elif type_ == 'arc':
            distances = [(key, label_distance_to_arc(label_point, instance))
                         for key, instance in instances.iteritems()]
        elif type_ == 'angle':
            distances = [(key, label_distance_to_angle(label_point, instance))
                         for key, instance in instances.iteritems()]

        # Then use the key to get corresponding variable in general graph
        # Wrap the general instance in function nod3. If there are extra prefixes, add these as well the formula
        argmin_key = min(distances, key=lambda pair: pair[1])[0]
        if type_ == 'line':
            a_key, b_key = argmin_key
            a_point = graph_parse.point_variables[a_key]
            b_point = graph_parse.point_variables[b_key]
            formula = FunctionNode(function_signatures['Line'],
                                   [a_point, b_point])
            if len(arr) > 1 and arr[0] == 'length':
                formula = FunctionNode(function_signatures['LengthOf'],
                                       [formula])
        elif type_ == 'point':
            formula = graph_parse.point_variables[argmin_key]
        elif type_ == 'angle':
            assert len(arr) > 1 and arr[0] == 'angle'
            a_key, b_key, c_key = argmin_key
            a_point = graph_parse.point_variables[a_key]
            b_point = graph_parse.point_variables[b_key]
            c_point = graph_parse.point_variables[c_key]
            formula = FunctionNode(function_signatures['Angle'],
                                   [a_point, b_point, c_point])
            formula = FunctionNode(function_signatures['MeasureOf'], [formula])
        elif type_ == 'arc':
            (center_key, radius_key), a_key, b_key = argmin_key
            center_point = graph_parse.point_variables[center_key]
            radius = graph_parse.radius_variables[center_key][radius_key]
            circle = FunctionNode(function_signatures['Circle'],
                                  [center_point, radius])
            a_point = graph_parse.point_variables[a_key]
            b_point = graph_parse.point_variables[b_key]
            formula = FunctionNode(function_signatures['Arc'],
                                   [circle, a_point, b_point])
        if label not in match_dict:
            match_dict[label] = []
        elif issubtype(formula.return_type, 'entity'):
            raise Exception()
        match_dict[label].append(formula)

    match_parse = MatchParse(graph_parse, match_dict)
    return match_parse