Exemplo n.º 1
0
    def to_svg(self):
        '''
        Renders the graph to a file.

        :return:    the rendered graph
        '''
        g = self.to_dot()
        return render_gv(g)
Exemplo n.º 2
0
 def finalgraph(self, filename=None):
     finaldb = Database(self.prac.mln)
     for step in self.inference_steps:
         for db in step.output_dbs:
             for atom, truth in list(db.evidence.items()):
                 if truth == 0: continue
                 _, predname, args = self.prac.mln.logic.parseLiteral(atom)
                 if predname in self.prac.roles.union(
                     ['has_sense', 'action_core', 'achieved_by']):
                     finaldb << atom
                 #         finaldb.write(sys.stdout, color=True)
     g = Digraph(format='svg', engine='dot')
     g.attr('node', shape='box', style='filled')
     for res in finaldb.query('action_core(?w, ?a) ^ has_sense(?w, ?s)'):
         actioncore = res['?a']
         sense = res['?s']
         predname = 'action_core'
         g.node(actioncore, fillcolor='#bee280')
         g.node(sense)
         g.edge(actioncore, sense, label='is_a')
         roles = self.prac.actioncores[actioncore].roles
         for role in roles:
             for res in db.query('{}(?w, {}) ^ has_sense(?w, ?s)'.format(
                     role, actioncore)):
                 sense = res['?s']
                 g.node(sense)
                 g.edge(actioncore, sense, label=role)
     for res in finaldb.query('achieved_by(?a1, ?a2)'):
         a1 = res['?a1']
         a2 = res['?a2']
         g.node(a1, fillcolor='#bee280')
         g.node(a2, fillcolor='#bee280')
         g.edge(a1, a2, label='achieved_by')
         actioncore = a2
         roles = self.prac.actionroles[actioncore].roles
         for role in roles:
             for res in db.query('{}(?w, {}) ^ has_sense(?w, ?s)'.format(
                     role, actioncore)):
                 sense = res['?s']
                 g.node(sense)
                 g.edge(actioncore, sense, label=role)
     return render_gv(g, filename)
Exemplo n.º 3
0
    def role_distributions(self, step):
        '''
        TODO

        :param step:
        :return:
        '''
        distrs = {}
        for db_ in step.output_dbs:
            for word in db_.domains['word']:
                for q in db_.query('action_core(?w,?ac)'):

                    # ==========================================================
                    # Initializaton
                    # ==========================================================

                    actioncore = q['?ac']
                    projectpath = os.path.join(self.module_path,
                                               '{}.pracmln'.format(actioncore))
                    project = MLNProject.open(projectpath)
                    mlntext = project.mlns.get(project.queryconf['mln'], None)
                    mln = parse_mln(
                        mlntext,
                        searchpaths=[self.module_path],
                        projectpath=projectpath,
                        logic=project.queryconf.get('logic',
                                                    'FirstOrderLogic'),
                        grammar=project.queryconf.get('grammar',
                                                      'PRACGrammar'))

                    # ==========================================================
                    # Preprocessing
                    # ==========================================================

                    # add inferred concepts to known_concepts to display
                    # them in the graph. Ignore verbs and adjectives,
                    # as they do not have hypernym relations to nouns
                    concepts = self.prac.config.getlist('wordnet', 'concepts')
                    for con in db_.query('has_sense(?w,?s)'):
                        if con['?s'].split('.')[1] in ['a', 's', 'v']:
                            continue
                        concepts.append(con['?s'])
                    wn = WordNet(concepts=concepts)

                    db = db_.copy(mln=mln)
                    for qs in db_.query('!(EXIST ?w (has_sense(?w,?s)))'):
                        db.rmval('sense', qs['?s'])
                    for concept in db_.domains['concept']:
                        if concept not in mln.domains['concept']:
                            db.rmval('concept', concept)
                    for res in db_.query('has_sense({}, ?s)'.format(word)):
                        sense = res['?s']
                        if sense == 'null': continue
                        roles = self.prac.actioncores[actioncore].roles
                        role = None
                        for r in roles:
                            vars = [
                                '?v{}'.format(i) for i in range(
                                    len(db_.mln.predicate(r).argdoms) - 1)
                            ]
                            br = False
                            for qr in db_.query('{}({},{})'.format(
                                    r, ','.join(vars), actioncore)):
                                for v in vars:
                                    if qr[v] == word:
                                        role = r
                                        br = True
                                        break
                                if br: break
                            if br: break
                        if role is None: continue
                        db.retract('has_sense({},{})'.format(word, sense))
                        add_all_wordnet_similarities(db, wn)

                        # ======================================================
                        # Inference
                        # ======================================================

                        infer = self.mlnquery(method='EnumerationAsk',
                                              mln=mln,
                                              db=db,
                                              queries='has_sense',
                                              cw=True,
                                              multicore=True,
                                              verbose=self.prac.verbose > 2)

                        result = infer.resultdb

                        if self.prac.verbose == 2:
                            print
                            print prac_heading('INFERENCE RESULTS')
                            print
                            infer.write()

                        # ======================================================
                        # Graph generation
                        # ======================================================

                        g = wn.to_dot()
                        maxprob = 0.
                        for atom, truth in result.gndatoms():
                            _, predname, args = db.mln.logic.parse_literal(
                                atom)
                            concept = args[1]
                            if predname == 'has_sense' and args[
                                    0] == word and concept != 'null':
                                maxprob = max(maxprob, truth)

                        for atom, truth in result.gndatoms():
                            _, predname, args = db.mln.logic.parse_literal(
                                atom)
                            concept = args[1]
                            if predname == 'has_sense' and args[
                                    0] == word and concept != 'null':
                                if concept in concepts:
                                    g.node(concept,
                                           fillcolor=get_prob_color(truth /
                                                                    maxprob))
                        distrs[role] = render_gv(g)
        return distrs