Exemple #1
0
 def _setAttributes(self):  ### Sets Attributes of Object
     '''Sets Attributes of Object.'''
     ### ~ Basics ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
     self.strlist = ['BackBase', 'PrevBase']
     self.boollist = []
     self.intlist = []
     self.numlist = []
     self.filelist = []
     self.listlist = ['Output']
     self.dictlist = []
     self.objlist = []
     ### ~ Defaults ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
     self._setDefaults(str='None',
                       bool=False,
                       int=0,
                       num=0.0,
                       obj=None,
                       setlist=True,
                       setdict=True,
                       setfile=True)
     self.baseFile('slimsuite')
     self.setStr({
         'BackBase': 'slimsuite.%s' % rje.dateTime(dateonly=True),
         'PrevBase': 'slimsuite'
     })
     self.setBool({})
     self.setInt({})
     self.setNum({})
     self.list['Output'] = string.split(
         'release,history,updates,readme,dependencies', ',')
     ### ~ Other Attributes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
     self._setForkAttributes()  # Delete if no forking
Exemple #2
0
    def rmdHead(self,title=None,author=None,date=None,extra=[],setup=True,toc=True):    ### Generate Rmd output file
        '''
        Generate Rmd output file. Call self.rmdKnit(rmdfile) to convert to another format.
        >> rmdfile:str [self.str['RmdFile']] = Full/relative path to Rmd output file.
        >> header:dict {} = Dictionary of Rmd header elements. Will default to self.log.obj['Info'] and HTML.
        >> elements:list [] = List of tuples (type,content) to output into file. For R code, content will be a dictionary

        This method puts together the basic elements of an R markdown file into a text document that can be knitted into
        HTML or PDF using self.rmdKnit().
        '''
        try:### ~ [1] Setup ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            rcode = '---\n'
            if not title: title = '%s - %s' % (self.prog(),self.basefile())
            rcode += 'title: "%s"\n' % title
            if not author: author = self.log.obj['Info'].author
            rcode += 'author: "%s"\n' % author
            if not date: date = rje.dateTime(dateonly=True)
            rcode += 'date: "%s"\n' % date   #07/02/2019
            for (key,value) in extra:
                rcode += '%s: "%s"\n' % (key,value)
            rcode += 'output:\n  html_document:\n    css: http://www.slimsuite.unsw.edu.au/stylesheets/slimhtml.css\n'
            if toc: rcode += string.join(['    toc: true','    toc_float: true','    toc_collapsed: false','    toc_depth: 3','    number_sections: true',''],'\n')
            rcode += '---\n\n'

            if setup:
                rcode += '%s\n\n<a name="Top" />\n\n' % setupTest

            self.debug(rcode)
            return rcode
        except: self.errorLog('%s.rmdOutput error' % self.prog())
Exemple #3
0
 def _setAttributes(self):   ### Sets Attributes of Object
     '''Sets Attributes of Object.'''
     ### ~ Basics ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
     self.strlist = ['BackBase','PrevBase']
     self.boollist = []
     self.intlist = []
     self.numlist = []
     self.filelist = []
     self.listlist = ['Output']
     self.dictlist = []
     self.objlist = []
     ### ~ Defaults ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
     self._setDefaults(str='None',bool=False,int=0,num=0.0,obj=None,setlist=True,setdict=True,setfile=True)
     self.baseFile('slimsuite')
     self.setStr({'BackBase':'slimsuite.%s' % rje.dateTime(dateonly=True),'PrevBase':'slimsuite'})
     self.setBool({})
     self.setInt({})
     self.setNum({})
     self.list['Output'] = string.split('release,history,updates,readme,dependencies',',')
     ### ~ Other Attributes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
     self._setForkAttributes()   # Delete if no forking
Exemple #4
0
    def saveXGMML(
            self,
            filename=None,
            format='Cytoscape'):  ### Saves object data to file in XGMML format
        '''
        Saves object data to file in XGMML format.
        >> filename:str [None] = Output file. Will use name.xgmml if None.
        >> format:str [Cytoscape] = Target for output file
        '''
        try:  ### ~ [1] Setup ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            if not filename or filename.lower() == 'none':
                filename = '%s.xgmml' % self.info['Name']
            self.log.printLog('#XGMML',
                              'Output of XGMML file %s for %s...' %
                              (filename, format),
                              log=False,
                              newline=False)
            rje.backup(self, filename)
            date = rje.dateTime()
            OUT = open(filename, 'w')

            ### ~ [2] Output headers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            OUT.write(
                '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n')
            OUT.write(
                '<graph label="%s" id="%s" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns="http://www.cs.rpi.edu/XGMML" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n'
                % (self.info['Name'], self.info['Name']))
            OUT.write('    <att name="documentVersion" value="1.0"/>\n')
            ## ~ [2a] Cytoscape format ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
            OUT.write('    <att name="networkMetadata">\n')
            OUT.write('        <rdf:RDF>\n')
            OUT.write(
                '            <rdf:Description rdf:about="http://www.cytoscape.org/">\n'
            )
            OUT.write('                <dc:source>RJE_XGMML</dc:source>\n')
            OUT.write(
                '                <dc:format>Cytoscape-XGMML</dc:format>\n')
            OUT.write('                <dc:description>%s</dc:description>\n' %
                      self.info['Description'])
            OUT.write('                <dc:date>%s</dc:date>\n' % date)
            OUT.write('                <dc:type>%s</dc:type>\n' %
                      self.info['Type'])
            OUT.write('                <dc:identifier>N/A</dc:identifier>\n')
            OUT.write('                <dc:title>%s</dc:title>\n' %
                      self.info['Name'])
            OUT.write('            </rdf:Description>\n')
            OUT.write('        </rdf:RDF>\n')
            OUT.write('    </att>\n\n')

            ### ~ [3] Output Nodes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            size = 35.0
            nodelist = rje.sortKeys(self.dict['Node'])
            (n, x, y) = (int(math.sqrt(len(nodelist))), 0, 0)
            for node in nodelist:
                try:
                    ## ~ [3a] Basic node attributes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                    OUT.write('    <node label="%s" id="%d">\n' %
                              (node, nodelist.index(node)))
                except:
                    self.errorLog('!')
                    continue
                try:
                    for att in rje.sortKeys(self.dict['Node'][node]):
                        if att not in self.dict['NodeAtt']: continue
                        type = self.dict['NodeAtt'][att]
                        value = string.replace(
                            '%s' % self.dict['Node'][node][att], '&', 'and')
                        OUT.write(
                            '        <att type="%s" name="%s" label="%s" value="%s"/>\n'
                            % (type, att, att, value))
                    ### ~ [3b] Graphics ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                    #!# Add control for these at some point! #!#
                    if node in self.dict['NodePos']:
                        (nx, ny) = self.dict['NodePos'][node]
                        try:
                            nx * size
                        except:
                            self.errorLog('%s nodepos X = %s' % (node, nx))
                            nx = x
                        try:
                            ny * size
                        except:
                            self.errorLog('%s nodepos Y = %s' % (node, ny))
                            ny = y
                    else:
                        [nx, ny] = [x, y]
                    if self.getBool('XGMMLAtt'):
                        OUT.write(
                            '        <graphics w="%.1f" h="%.1f" width="1" type="ellipse" outline="#000000" fill="#ff9999" y="%.1f" x="%.1f">\n'
                            % (size, size, ny * 2 * size, nx * 2 * size))
                        OUT.write(
                            '            <att name="cytoscapeNodeGraphicsAttributes">\n'
                        )
                        OUT.write(
                            '                <att name="nodeTransparency" value="1.0"/>\n'
                        )
                        #OUT.write('                <att name="nodeLabelFont" value="Default-0-12"/>\n')
                        OUT.write(
                            '                <att name="borderLineType" value="solid"/>\n'
                        )
                        OUT.write('            </att>\n')
                    else:
                        OUT.write('        <graphics y="%.1f" x="%.1f">\n' %
                                  (ny * 2 * size, nx * 2 * size))
                    OUT.write('        </graphics>\n')
                    x += 1
                    if x > n: (x, y) = (0, y + 1)
                    ### ~ [3c] Finish ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                except:
                    self.errorLog('!')
                OUT.write('    </node>\n')

            ### ~ [4] Output Edges ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            for etype in rje.sortKeys(self.dict['Edge']):
                for edge in rje.sortKeys(self.dict['Edge'][etype]):
                    try:
                        ## ~ [3a] Basic edge attributes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                        id = '%s (%s) %s' % (edge[0], etype, edge[1])
                        OUT.write(
                            '    <edge label="%s" id="%s" target="%d" source="%d">\n'
                            % (id, id, nodelist.index(
                                edge[1]), nodelist.index(edge[0])))
                    except:
                        self.errorLog('!')
                        continue
                    try:
                        OUT.write(
                            '        <att type="string" name="canonicalName" label="canonicalName" value="%s"/>\n'
                            % id)
                        OUT.write(
                            '        <att type="string" name="TYPE" label="TYPE" value="%s"/>\n'
                            % etype)
                        if 'interaction' not in self.dict['EdgeAtt']:
                            OUT.write(
                                '        <att type="string" name="interaction" label="interaction" value="%s"/>\n'
                                % etype)
                        OUT.write(
                            '        <att type="string" name="EDGE_TYPE" label="EDGE_TYPE" value="DefaultEdge"/>\n'
                        )
                        for att in self.dict['Edge'][etype][edge]:
                            if att.lower() == 'type': continue
                            if att not in self.dict['EdgeAtt']: continue
                            type = self.dict['EdgeAtt'][att]
                            value = string.replace(
                                '%s' % self.dict['Edge'][etype][edge][att],
                                '&', 'and')
                            OUT.write(
                                '        <att type="%s" name="%s" label="%s" value="%s"/>\n'
                                % (type, att, att, value))
                        ### ~ [3b] Graphics ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                        #!# Update these at some point! #!#
                        #OUT.write('        <graphics width="1" fill="#0000ff">\n')
                        #OUT.write('            <att name="cytoscapeEdgeGraphicsAttributes">\n')
                        #OUT.write('                <att name="sourceArrow" value="0"/>\n')
                        #OUT.write('                <att name="targetArrow" value="0"/>\n')
                        #OUT.write('                <att name="edgeLabelFont" value="Default-0-10"/>\n')
                        #OUT.write('                <att name="edgeLineType" value="SOLID"/>\n')
                        #OUT.write('                <att name="sourceArrowColor" value="#000000"/>\n')
                        #OUT.write('                <att name="targetArrowColor" value="#000000"/>\n')
                        #OUT.write('                <att name="curved" value="STRAIGHT_LINES"/>\n')
                        #OUT.write('            </att>\n')
                        #OUT.write('        </graphics>\n')
                        ### ~ [3c] Finish ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                    except:
                        self.errorLog('!')
                    OUT.write('    </edge>\n')

            ### ~ [5] Finish ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            OUT.write('</graph>\n')
            OUT.close()
            self.log.printLog(
                '\r#XGMML', 'Output of XGMML file %s for %s complete.' %
                (filename, format))
        except:
            self.log.errorLog(rje_zen.Zen().wisdom())
Exemple #5
0
    def makeHistory(self):  ### Extracts history information from docstrings.
        '''Extracts history information from docstrings.'''
        try:  ### ~ [0] Setup ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            hdb = self.db('history')
            mdb = self.db('Module')
            pydoc = self.obj['PyDoc']
            uhtml = []  # Update HTML text
            udir = ''

            ### ~ [1] Work through python modules ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            for mkey in mdb.dataKeys():
                entry = mdb.data(mkey)
                pyfile = entry['File']
                mod = entry['Module']
                prev = '-'
                lastv = ''
                ## ~ [1a] Parse out history text ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                history = []  # History lines
                updates = []  # Version number entries
                for mentry in self.db('Method').indexEntries('File', pyfile):
                    if mentry['Method'] == 'history':
                        try:
                            history = string.split(mentry['DocString'], '\n')
                            break
                        except:
                            history = []
                            self.errorLog('History parsing problem: %s' %
                                          mentry,
                                          printerror=False)
                for dline in history:
                    if rje.matchExp('# (\d+\.\d+\.?\d*)\s?-\s(\S.+)$', dline):
                        (v,
                         text) = rje.matchExp('# (\d\.\d+\.?\d*)\s?-\s(\S.+)$',
                                              dline)
                        if v == lastv:  # Continuation of update
                            if prev == lastv: continue  # In previous release
                            updates[-1]['Update'] += ' %s' % text
                            continue
                        lastv = v
                        ventry = {
                            'Dir': entry['SourceDir'],
                            'Module': mod,
                            'Version': v,
                            'Update': text,
                            'Release': rje.dateTime(dateonly=True)
                        }
                        vkey = hdb.makeKey(ventry)
                        if hdb.data(vkey): prev = v
                        else: updates.append(ventry)
                ## ~ [1b] Assess/report updates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                if prev != lastv:
                    if entry['SourceDir'] != udir:
                        uhtml.append('<h2>Updates in %s/:</h2>\n' %
                                     entry['SourceDir'])
                        udir = entry['SourceDir']
                if prev == '-' and lastv:
                    self.printLog(
                        '#VNUM',
                        '%s: Creation -> Version %s' % (mod, entry['Version']))
                    uhtml.append(
                        '<p><b>&bull; %s:</b> <i>Created/Renamed/moved.</i>' %
                        mod)
                elif prev not in ['-', lastv]:
                    self.printLog(
                        '#VNUM', '%s: Version %s -> Version %s' %
                        (mod, prev, entry['Version']))
                    uhtml.append(
                        '<p><b>&bull; %s:</b> <i>Updated from Version %s.</i>'
                        % (mod, prev))
                for ventry in updates:
                    self.printLog('#V%s' % ventry['Version'], ventry['Update'])
                    uhtml.append('<br>&rarr; Version %s: %s' %
                                 (ventry['Version'], ventry['Update']))
                    hdb.addEntry(ventry)
                if uhtml and uhtml[-1] != '</p>': uhtml.append('</p>')
                if lastv != entry['Version']:
                    self.warnLog(
                        'Module %s Version %s but history() ends at %s' %
                        (mod, entry['Version'], lastv))
                self.deBug('>>>')
            if 'history' in self.list['Output']: hdb.saveToFile(backup=False)

            ### ~ [2] Make updates.html file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            if 'updates' in self.list['Output']:
                htmlfile = '%s.updates.html' % self.basefile()
                title = 'SLiMSuite updates'
                stylesheets = []
                for css in pydoc.list['StyleSheets']:
                    stylesheets.append(pydoc.getStr('StylePath') + css)
                htmlhead = rje_html.htmlHead(
                    title,
                    stylesheets,
                    tabber=True,
                    frontpage=False,
                    nobots=False,
                    keywords=pydoc.list['Keywords'],
                    javascript=pydoc.getStr('StylePath'))
                htmlbody = string.join(['<h1>SLiMSuite updates</h1>'] + uhtml,
                                       '\n')
                htmltail = rje_html.htmlTail(
                    '%s %s' %
                    (pydoc.getStr('Author'),
                     string.split(time.asctime(time.localtime(
                         time.time())))[-1]))
                open(htmlfile, 'w').write(htmlhead + htmlbody + htmltail)
                self.printLog('#HTML',
                              'HTML update summary output to %s' % (htmlfile))
        except:
            self.errorLog('Error in %s.makeHistory()' % self.prog())
Exemple #6
0
    def makeHistory(self):  ### Extracts history information from docstrings.
        '''Extracts history information from docstrings.'''
        try:### ~ [0] Setup ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            hdb = self.db('history')
            mdb = self.db('Module')
            pydoc = self.obj['PyDoc']
            uhtml = []  # Update HTML text
            udir = ''

            ### ~ [1] Work through python modules ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            for mkey in mdb.dataKeys():
                entry = mdb.data(mkey)
                pyfile = entry['File']
                mod = entry['Module']
                prev = '-'
                lastv = ''
                ## ~ [1a] Parse out history text ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                history = []    # History lines
                updates = []    # Version number entries
                for mentry in self.db('Method').indexEntries('File',pyfile):
                    if mentry['Method'] == 'history':
                        try: history = string.split(mentry['DocString'],'\n'); break
                        except:
                            history = []
                            self.errorLog('History parsing problem: %s' % mentry,printerror=False)
                for dline in history:
                    if rje.matchExp('# (\d+\.\d+\.?\d*)\s?-\s(\S.+)$',dline):
                        (v,text) = rje.matchExp('# (\d\.\d+\.?\d*)\s?-\s(\S.+)$',dline)
                        if v == lastv:  # Continuation of update
                            if prev == lastv: continue  # In previous release
                            updates[-1]['Update'] += ' %s' % text
                            continue
                        lastv = v
                        ventry = {'Dir':entry['SourceDir'],'Module':mod,'Version':v,'Update':text,'Release':rje.dateTime(dateonly=True)}
                        vkey = hdb.makeKey(ventry)
                        if hdb.data(vkey): prev = v
                        else: updates.append(ventry)
                ## ~ [1b] Assess/report updates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                if prev != lastv:
                    if entry['SourceDir'] != udir: uhtml.append('<h2>Updates in %s/:</h2>\n' % entry['SourceDir']); udir = entry['SourceDir']
                if prev == '-' and lastv:
                    self.printLog('#VNUM','%s: Creation -> Version %s' % (mod,entry['Version']))
                    uhtml.append('<p><b>&bull; %s:</b> <i>Created/Renamed/moved.</i>' % mod)
                elif prev not in ['-',lastv]:
                    self.printLog('#VNUM','%s: Version %s -> Version %s' % (mod,prev,entry['Version']))
                    uhtml.append('<p><b>&bull; %s:</b> <i>Updated from Version %s.</i>' % (mod,prev))
                for ventry in updates:
                    self.printLog('#V%s' % ventry['Version'],ventry['Update'])
                    uhtml.append('<br>&rarr; Version %s: %s' % (ventry['Version'],ventry['Update']))
                    hdb.addEntry(ventry)
                if uhtml and uhtml[-1] != '</p>': uhtml.append('</p>')
                if lastv != entry['Version']: self.warnLog('Module %s Version %s but history() ends at %s' % (mod,entry['Version'],lastv))
                self.deBug('>>>')
            if 'history' in self.list['Output']: hdb.saveToFile(backup=False)

            ### ~ [2] Make updates.html file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            if 'updates' in self.list['Output']:
                htmlfile = '%s.updates.html' % self.basefile()
                title = 'SLiMSuite updates'
                stylesheets = []
                for css in pydoc.list['StyleSheets']: stylesheets.append(pydoc.getStr('StylePath')+css)
                htmlhead = rje_html.htmlHead(title,stylesheets,tabber=True,frontpage=False,nobots=False,keywords=pydoc.list['Keywords'],javascript=pydoc.getStr('StylePath'))
                htmlbody = string.join(['<h1>SLiMSuite updates</h1>'] + uhtml,'\n')
                htmltail = rje_html.htmlTail('%s %s' % (pydoc.getStr('Author'),string.split(time.asctime(time.localtime(time.time())))[-1]))
                open(htmlfile,'w').write(htmlhead+htmlbody+htmltail)
                self.printLog('#HTML','HTML update summary output to %s' % (htmlfile))
        except: self.errorLog('Error in %s.makeHistory()' % self.prog())
Exemple #7
0
    def saveXGMML(self,filename=None,format='Cytoscape'):       ### Saves object data to file in XGMML format
        '''
        Saves object data to file in XGMML format.
        >> filename:str [None] = Output file. Will use name.xgmml if None.
        >> format:str [Cytoscape] = Target for output file
        '''
        try:### ~ [1] Setup ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            if not filename or filename.lower() == 'none': filename = '%s.xgmml' % self.info['Name']
            self.log.printLog('#XGMML','Output of XGMML file %s for %s...' % (filename,format),log=False,newline=False)
            rje.backup(self,filename)
            date = rje.dateTime()
            OUT = open(filename,'w')
            
            ### ~ [2] Output headers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            OUT.write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n')
            OUT.write('<graph label="%s" id="%s" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns="http://www.cs.rpi.edu/XGMML" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n' % (self.info['Name'],self.info['Name']))
            OUT.write('    <att name="documentVersion" value="1.0"/>\n')
            ## ~ [2a] Cytoscape format ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
            OUT.write('    <att name="networkMetadata">\n')
            OUT.write('        <rdf:RDF>\n')
            OUT.write('            <rdf:Description rdf:about="http://www.cytoscape.org/">\n')
            OUT.write('                <dc:source>RJE_XGMML</dc:source>\n')
            OUT.write('                <dc:format>Cytoscape-XGMML</dc:format>\n')
            OUT.write('                <dc:description>%s</dc:description>\n' % self.info['Description'])  
            OUT.write('                <dc:date>%s</dc:date>\n' % date)
            OUT.write('                <dc:type>%s</dc:type>\n' % self.info['Type'])
            OUT.write('                <dc:identifier>N/A</dc:identifier>\n')
            OUT.write('                <dc:title>%s</dc:title>\n' % self.info['Name'])
            OUT.write('            </rdf:Description>\n')
            OUT.write('        </rdf:RDF>\n')
            OUT.write('    </att>\n\n')

            ### ~ [3] Output Nodes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            size = 35.0
            nodelist = rje.sortKeys(self.dict['Node'])
            (n,x,y) = (int(math.sqrt(len(nodelist))),0,0)
            for node in nodelist:
                try:
                    ## ~ [3a] Basic node attributes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                    OUT.write('    <node label="%s" id="%d">\n' % (node,nodelist.index(node)))
                except: self.errorLog('!'); continue
                try:
                    for att in rje.sortKeys(self.dict['Node'][node]):
                        if att not in self.dict['NodeAtt']: continue
                        type = self.dict['NodeAtt'][att]
                        value = string.replace('%s' % self.dict['Node'][node][att],'&','and')
                        OUT.write('        <att type="%s" name="%s" label="%s" value="%s"/>\n' % (type,att,att,value))
                    ### ~ [3b] Graphics ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                    #!# Add control for these at some point! #!#
                    if node in self.dict['NodePos']:
                        (nx,ny) = self.dict['NodePos'][node]
                        try: nx * size
                        except: self.errorLog('%s nodepos X = %s' % (node,nx)); nx = x
                        try: ny * size
                        except: self.errorLog('%s nodepos Y = %s' % (node,ny)); ny = y
                    else: [nx,ny] = [x,y]
                    if self.getBool('XGMMLAtt'):
                        OUT.write('        <graphics w="%.1f" h="%.1f" width="1" type="ellipse" outline="#000000" fill="#ff9999" y="%.1f" x="%.1f">\n' % (size,size,ny*2*size,nx*2*size))
                        OUT.write('            <att name="cytoscapeNodeGraphicsAttributes">\n')
                        OUT.write('                <att name="nodeTransparency" value="1.0"/>\n')
                        #OUT.write('                <att name="nodeLabelFont" value="Default-0-12"/>\n')
                        OUT.write('                <att name="borderLineType" value="solid"/>\n')
                        OUT.write('            </att>\n')
                    else:
                        OUT.write('        <graphics y="%.1f" x="%.1f">\n' % (ny*2*size,nx*2*size))
                    OUT.write('        </graphics>\n')
                    x += 1
                    if x > n: (x,y) = (0,y+1)
                    ### ~ [3c] Finish ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                except: self.errorLog('!')
                OUT.write('    </node>\n')
            
            ### ~ [4] Output Edges ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            for etype in rje.sortKeys(self.dict['Edge']):
                for edge in rje.sortKeys(self.dict['Edge'][etype]):
                    try:
                        ## ~ [3a] Basic edge attributes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                        id = '%s (%s) %s' % (edge[0],etype,edge[1])
                        OUT.write('    <edge label="%s" id="%s" target="%d" source="%d">\n' % (id,id,nodelist.index(edge[1]),nodelist.index(edge[0])))
                    except: self.errorLog('!'); continue
                    try:
                        OUT.write('        <att type="string" name="canonicalName" label="canonicalName" value="%s"/>\n' % id)
                        OUT.write('        <att type="string" name="TYPE" label="TYPE" value="%s"/>\n' % etype)
                        if 'interaction' not in self.dict['EdgeAtt']: OUT.write('        <att type="string" name="interaction" label="interaction" value="%s"/>\n' % etype)
                        OUT.write('        <att type="string" name="EDGE_TYPE" label="EDGE_TYPE" value="DefaultEdge"/>\n')
                        for att in self.dict['Edge'][etype][edge]:
                            if att.lower() == 'type': continue
                            if att not in self.dict['EdgeAtt']: continue
                            type = self.dict['EdgeAtt'][att]
                            value = string.replace('%s' % self.dict['Edge'][etype][edge][att],'&','and')
                            OUT.write('        <att type="%s" name="%s" label="%s" value="%s"/>\n' % (type,att,att,value))
                        ### ~ [3b] Graphics ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                        #!# Update these at some point! #!#
                        #OUT.write('        <graphics width="1" fill="#0000ff">\n')
                        #OUT.write('            <att name="cytoscapeEdgeGraphicsAttributes">\n')
                        #OUT.write('                <att name="sourceArrow" value="0"/>\n')
                        #OUT.write('                <att name="targetArrow" value="0"/>\n')
                        #OUT.write('                <att name="edgeLabelFont" value="Default-0-10"/>\n')
                        #OUT.write('                <att name="edgeLineType" value="SOLID"/>\n')
                        #OUT.write('                <att name="sourceArrowColor" value="#000000"/>\n')
                        #OUT.write('                <att name="targetArrowColor" value="#000000"/>\n')
                        #OUT.write('                <att name="curved" value="STRAIGHT_LINES"/>\n')
                        #OUT.write('            </att>\n')
                        #OUT.write('        </graphics>\n')
                        ### ~ [3c] Finish ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                    except: self.errorLog('!')
                    OUT.write('    </edge>\n')
                            
            ### ~ [5] Finish ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
            OUT.write('</graph>\n')
            OUT.close()
            self.log.printLog('\r#XGMML','Output of XGMML file %s for %s complete.' % (filename,format))
        except: self.log.errorLog(rje_zen.Zen().wisdom())