Exemple #1
0
    def __init__(self, graph_name='G', obj_dict=None, template_file=None):
        pydot.Dot.__init__(self, graph_name=graph_name, obj_dict=obj_dict)

        # If create empty new graph...
        if (obj_dict is None):

            ### Some default setting.
            try:
                if template_file is None:
                    g = ExtParser.parse_file(TEMPLATE_DOT)
                else:
                    g = ExtParser.parse_file(template_file)
            except:
                g = ExtParser.parse_string(INIT_SCRIPT)

            self.obj_dict = g.obj_dict

        # If create graph from parsing program...
        else:
            # Now check if wildcard nodes existed in every graph and subgraph.
            self.__check_wildcard_existed()

        ### Important!!! To make "pydot.Graph.toString()" working correct.
        self.set_parent_graph(self)
        ### -------------------------------------------------------------

        self.refresh_bitmap()

        return
Exemple #2
0
    def __init__(self, graph_name="G", obj_dict=None, template_file=None):
        pydot.Dot.__init__(self, graph_name=graph_name, obj_dict=obj_dict)

        # If create empty new graph...
        if obj_dict is None:

            ### Some default setting.
            try:
                if template_file is None:
                    g = ExtParser.parse_file(TEMPLATE_DOT)
                else:
                    g = ExtParser.parse_file(template_file)
            except:
                g = ExtParser.parse_string(INIT_SCRIPT)

            self.obj_dict = g.obj_dict

        # If create graph from parsing program...
        else:
            # Now check if wildcard nodes existed in every graph and subgraph.
            self.__check_wildcard_existed()

        ### Important!!! To make "pydot.Graph.toString()" working correct.
        self.set_parent_graph(self)
        ### -------------------------------------------------------------

        self.refresh_bitmap()

        return
    def onOK(self, event):
        '''
        If script is ok, store script in graph objcet and return to main window.
        Else highlight the error line in editor. 
        '''
        script = self.m_text_script.GetValue().strip()
        ### Get strict status here.
        strict_status = False
        if script[:6].lower() == 'strict':
            strict_status = True
            
        try:
            g = ExtParser.parse_string(script.encode('utf8'))
            ### Hack the strcit status cause bug of pydot.
            g.set_strict(strict_status)
            
            self.graph = ExtGraph.ExtGraph(obj_dict=g.obj_dict)
            self.EndModal(wx.ID_OK)

        except ExtParser.ParseException, err:
            
            pos = self.m_text_script.XYToPosition(0, err.lineno-1)
            w = self.m_text_script.GetLineLength(err.lineno-1)
            
            self.m_text_script.SetFocus()
            self.m_text_script.SetSelection(pos, pos+w)
            
            wx.MessageBox("Parse Script Error.\n"+20*"-"+"\n%s"%err, 'Parse script error')
    def onCheck(self, event):
        '''Do check on script, format script if correct.'''
        script = self.m_text_script.GetValue().strip()
        ### Get strict status here.
        strict_status = False
        if script[:6].lower() == 'strict':
            strict_status = True
            
        try:
            g = ExtParser.parse_string(script.encode('utf8'))
            ### Hack the strcit status cause bug of pydot.
            g.set_strict(strict_status)
            g = ExtGraph.ExtGraph(obj_dict=g.obj_dict)

        except ExtParser.ParseException, err:
            
            pos = self.m_text_script.XYToPosition(0, err.lineno-1)
            w = self.m_text_script.GetLineLength(err.lineno-1)
            
            self.m_text_script.SetFocus()
            self.m_text_script.SetSelection(pos, pos+w)
            
            wx.MessageBox("Parse Script Error.\n"+20*"-"+"\n%s"%err, 'Parse script error')
            
            return
Exemple #5
0
    def onOpenGraph(self, event):
        
        if self.is_data_changed:
            md = wx.MessageDialog(self, 
                                  "Current Graph not save yet, open another graph "+\
                                   "should lead to DATA LOST, continue anyway?",
                                   caption="Confirm to create new",
                                   style=wx.YES_NO|wx.NO_DEFAULT|wx.ICON_EXCLAMATION
                                   )
            if md.ShowModal() != wx.ID_YES:
                return
            
        fd = wx.FileDialog(self, "Open Dot File", "", "", 
                           "Graphviz Dot Script (*.*)|*.*", 
                           wx.OPEN|wx.FD_FILE_MUST_EXIST)
        if fd.ShowModal() == wx.ID_OK:
            fp = fd.GetPath()
        else:
            return ### User canceled

        fd.Destroy()
                
        ### Load graph from fp.
        try:
            g = ExtParser.parse_file(fp)

            self.file_path = fp
            self.is_data_changed = False
            self.update_graph(g)

        except ExtParser.ParseException, _:
            pass
Exemple #6
0
    def onOK(self, event):
        '''
        If script is ok, store script in graph objcet and return to main window.
        Else highlight the error line in editor. 
        '''
        script = self.m_text_script.GetValue().strip()
        ### Get strict status here.
        strict_status = False
        if script[:6].lower() == 'strict':
            strict_status = True

        try:
            g = ExtParser.parse_string(script)
            ### Hack the strcit status cause bug of pydot.
            g.set_strict(strict_status)

            self.graph = ExtGraph.ExtGraph(obj_dict=g.obj_dict)
            self.EndModal(wx.ID_OK)

        except ExtParser.ParseException as err:

            pos = self.m_text_script.XYToPosition(0, err.lineno - 1)
            w = self.m_text_script.GetLineLength(err.lineno - 1)

            self.m_text_script.SetFocus()
            self.m_text_script.SetSelection(pos, pos + w)

            wx.MessageBox("Parse Script Error.\n" + 20 * "-" + "\n%s" % err,
                          'Parse script error')

        return
Exemple #7
0
    def onCheck(self, event):
        '''Do check on script, format script if correct.'''
        script = self.m_text_script.GetValue().strip()
        ### Get strict status here.
        strict_status = False
        if script[:6].lower() == 'strict':
            strict_status = True

        try:
            g = ExtParser.parse_string(script)
            ### Hack the strcit status cause bug of pydot.
            g.set_strict(strict_status)
            g = ExtGraph.ExtGraph(obj_dict=g.obj_dict)

        except ExtParser.ParseException as err:

            pos = self.m_text_script.XYToPosition(0, err.lineno - 1)
            w = self.m_text_script.GetLineLength(err.lineno - 1)

            self.m_text_script.SetFocus()
            self.m_text_script.SetSelection(pos, pos + w)

            wx.MessageBox("Parse Script Error.\n" + 20 * "-" + "\n%s" % err,
                          'Parse script error')

            return

        self.SetScript(g.EG_to_string())

        return
Exemple #8
0
    def create_empty_subgraph(self, name):
        sg = pydot.Subgraph()
        sg.set_name(name)

        g = ExtParser.parse_string(INIT_SCRIPT_SUBGRAPH)
        sg.obj_dict['nodes'] = g.obj_dict['nodes']

        return sg
Exemple #9
0
    def create_empty_subgraph(self, name):
        sg = pydot.Subgraph()
        sg.set_name(name)

        g = ExtParser.parse_string(INIT_SCRIPT_SUBGRAPH)
        sg.obj_dict["nodes"] = g.obj_dict["nodes"]

        return sg
Exemple #10
0
    def __init__(self):
        # set up logging
        self.logger = logging.getLogger('Vampire')
        logging.basicConfig(
            filename='vampire.log',
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            level=logging.DEBUG,
            filemode='w')

        # load default values from .ini file
        self.config = ExtParser.ExtParser()
        cur_dir = os.path.join(os.getcwd(), 'vampire.ini')
        ini_files = [
            'vampire.ini',
            os.path.join(os.getcwd(), 'vampire.ini'), cur_dir
        ]
        dataset = self.config.read(ini_files)
        if len(dataset) == 0:
            msg = "Failed to open/find vampire.ini in {0}, {1} and {2}".format(
                ini_files[0], ini_files[1], ini_files[2])
            raise ValueError, msg
        self.countries = dict(self.config.items('country'))
        self.countries = dict(
            (k.title(), v) for k, v in self.countries.iteritems())
        self.country_codes_l = []
        self.country_codes = {}

        for c in self.countries:
            cc = ast.literal_eval(self.countries[c].replace("\n", ""))
            if 'chirps_boundary_file' in ast.literal_eval(
                    self.countries[c].replace("\n", "")):
                _chirps_boundary_file = ast.literal_eval(
                    self.countries[c].replace("\n",
                                              ""))['chirps_boundary_file']
                p = re.match(r'.*\$\{(?P<param>.*)\}.*', _chirps_boundary_file)
                if p:
                    # has a reference
                    _chirps_boundary_file = _chirps_boundary_file.replace(
                        '${' + p.group('param') + '}',
                        self.config.get('CHIRPS', p.group('param')))
                    cc['chirps_boundary_file'] = _chirps_boundary_file
            if 'modis_boundary_file' in ast.literal_eval(
                    self.countries[c].replace("\n", "")):
                _modis_boundary_file = ast.literal_eval(
                    self.countries[c].replace("\n", ""))['modis_boundary_file']
                p = re.match(r'.*\$\{(?P<param>.*)\}.*', _modis_boundary_file)
                if p:
                    # has a reference
                    _modis_boundary_file = _modis_boundary_file.replace(
                        '${' + p.group('param') + '}',
                        self.config.get('MODIS', p.group('param')))
                    cc['modis_boundary_file'] = _modis_boundary_file
            self.countries[c] = cc
            self.country_codes[cc['abbreviation']] = c
            self.country_codes_l.append(cc['abbreviation'])
        return
Exemple #11
0
def generate_node_shape_images():

    g = ExtParser.parse_file(ExtGraph.TEMPLATE_DOT)

    n1 = g.get_node('"n1"')[0]
    n1.set_label('" "')
    n1.get_attributes()['colorscheme'] = add_double_quote('blues3')
    n1.get_attributes()['color'] = add_double_quote('3')
    n1.get_attributes()['fillcolor'] = add_double_quote('1')
    n1.get_attributes()['style'] = add_double_quote('filled')

    for shape in AttrsDef.E_SHAPE:
        n1.get_attributes()['shape'] = add_double_quote(shape)
        g.write('resource/node_shape/%s.png' % shape, 'dot', 'png')

    return
Exemple #12
0
def generate_node_shape_images():
    
    g = ExtParser.parse_file(ExtGraph.TEMPLATE_DOT)
    
    n1 = g.get_node('"n1"')[0]
    n1.set_label('" "')
    n1.get_attributes()['colorscheme'] = add_double_quote('blues3')
    n1.get_attributes()['color'] = add_double_quote('3')
    n1.get_attributes()['fillcolor'] = add_double_quote('1')
    n1.get_attributes()['style'] = add_double_quote('filled')
    
    for shape in AttrsDef.E_SHAPE:
        n1.get_attributes()['shape'] = add_double_quote(shape)
        g.write('resource/node_shape/%s.png'%shape, 'dot', 'png')
        
    return
Exemple #13
0
def gen_arrow_image(arrowtype, out_filepath):
    script = '''
digraph G {
    rankdir=LR;
    edge [colorscheme="blues3", color=3];
//    node [style="invis"];
    node [fontname="sans-serif", colorscheme="x11", fontsize=12, color="lightgray", fontcolor="lightgray", style=" ", penwidth=0.5];
    "n1" [label="A"];
    "n2" [label="B"];
    "n1" -> "n2"  [arrowhead="dot"];
}
    '''

    g = ExtParser.parse_string(script)    
    e1 = g.get_edge('"n1"', '"n2"')
    e1.get_attributes()['arrowhead'] = add_double_quote('%s'%arrowtype)
    g.write(out_filepath, 'dot', 'png')
        
    return
Exemple #14
0
    def onOpenGraph(self, event):
        
        if self.is_data_changed:
            md = wx.MessageDialog(self, 
                                  "Current Graph not save yet, open another graph "+\
                                   "should lead to DATA LOST, continue anyway?",
                                   caption="Confirm to create new",
                                   style=wx.YES_NO|wx.NO_DEFAULT|wx.ICON_EXCLAMATION
                                   )
            if md.ShowModal() != wx.ID_YES:
                return
        
        fd = wx.FileDialog(self, "Open Dot File", "", "", 
                           "Graphviz Dot Script (*.*)|*.*", 
                           wx.OPEN|wx.FD_FILE_MUST_EXIST)
        if fd.ShowModal() == wx.ID_OK:
            fp = fd.GetPath()
        else:
            return ### User canceled

        fd.Destroy()
                
        ### Load graph from fp.
        try:
            g = ExtParser.parse_file(fp)

            self.file_path = fp
            self.is_data_changed = False
            self.update_graph(g)

        except ExtParser.ParseException as _:
            wx.MessageBox('Can\'t load specified file. Maybe file format error. \n'+\
                          'Be sure the file is in graphviz dot language, or check \n'+\
                          'if some syntax error existed in specified file. ',
                          "Can't load file", wx.ICON_ERROR)
        return
Exemple #15
0
    def __init__(self):

        self.diagram = None  # The diagram we're walking.
        self.verbose = False  # -v, --verbose
        self.nowalk = False  # -n, --nowalk
        self.walk = True  # -w, --walk
        self.shortest = False  # -s, --shortest
        self.exhaustive = False  # -e, --exhaustive
        self.random = False  # -r, --random
        self.randomwalk = False  # -rw, --randomwalk
        self.Nfeatures = None  # -n, --number
        self.dot = False  # -d, --dot

        # Start by creating an argument parser to help with user input.
        parser = argparse.ArgumentParser(description="Walk-ER: a system for walking the paths in an entity-relational diagram."\
                                         " Written by Alexander L. Hayes ([email protected]))"\
                                         " and Mayukh Das. University of Texas at Dallas. STARAI Lab (dir. Professor Natarajan).",
                                         epilog="Copyright 2017 Free Software Foundation, Inc."\
                                         " License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>."\
                                         " This is free software: you are free to change and redistribute it."\
                                         " There is NO WARRANTY, to the extent permitted by law.")
        # Add the arguments.
        walk = parser.add_mutually_exclusive_group()
        parser.add_argument("diagram_file")
        parser.add_argument("-v",
                            "--verbose",
                            help="Increase verbosity to help with debugging.",
                            action="store_true")
        parser.add_argument(
            "--number",
            type=int,
            help=
            "Select number of features to walk to (assumes that Important features are ordered from most important to least important). Defaults to number_attributes + number_relations if chosen number is greater than both."
        )
        #parser.add_argument('Nfeatures')
        walk.add_argument("-w",
                          "--walk",
                          help="[Default] Walk graph from target to features.",
                          action="store_true")
        walk.add_argument(
            "-s",
            "--shortest",
            help=
            "Walk the graph from target to features. If there are multiple paths, take the shortest. If the shortest are equal lengths, walk both.",
            action="store_true")
        walk.add_argument(
            "-n",
            "--nowalk",
            help="[Not implemented] Instantiate variables without walking.",
            action="store_true")
        walk.add_argument(
            "-e",
            "--exhaustive",
            help="Walk graph from every feature to every feature.",
            action="store_true")
        walk.add_argument(
            "-r",
            "--random",
            help=
            "Ignore features the user selected and walk (-w) from the target to random features.",
            action="store_true")
        walk.add_argument(
            "-rw",
            "--randomwalk",
            help=
            "Walk a random path from the target until reaching a depth limit (specified with --number).",
            action="store_true")
        parser.add_argument("-d",
                            "--dot",
                            help="Graph provided in dot format.",
                            action="store_true")
        # Get the args.
        args = parser.parse_args()

        # Make sure the diagram_file is valid.
        if not os.path.isfile(args.diagram_file):
            raise ExceptionCase('Error [1]: Could not find file: "' +
                                args.diagram_file + '"')

        # Import the diagram:
        self.dot = args.dot
        if self.dot:
            self.diagram = ExtParser.parse_file(args.diagram_file)
        else:
            '''Reads the contents of 'file_to_read', raises an exception if it cannot be read.'''
            try:
                diagram = open(args.diagram_file).read()
            except:
                raise ExceptionCase('Error [1]: Could not read the file: "' +
                                    args.diagram_file + '"')
            if len(diagram.splitlines()) == 6:
                self.diagram = diagram
            else:
                raise ExceptionCase(
                    'Error [1]: File opened successfully, but has the wrong number of lines.'
                )

        # Since the files exist, we can go ahead and set the rest of the parameters, starting with verbose
        self.verbose = args.verbose

        if (args.number != None):
            if (args.number >= 0):
                self.Nfeatures = args.number
            else:
                raise (
                    ExceptionCase('Error [1]: Cannot have negative features.'))

        # Check the rest of the parameters, update if necessary.
        if not (args.walk or args.nowalk or args.exhaustive or args.random
                or args.shortest or args.randomwalk):
            # If this occurs, no flags were specified, so keep defaults (default: self.walk=True).
            print('[Default] "Walk Mode": Walk graph from target to features.')
            pass
        else:
            self.nowalk = args.nowalk
            self.walk = args.walk
            self.shortest = args.shortest
            self.exhaustive = args.exhaustive
            self.random = args.random
            self.randomwalk = args.randomwalk

        if self.verbose:
            print('Imported Diagram File:\n')
            print(diagram)