예제 #1
0
    def rss2(feed, pretty_print=True):
        indent = '\n    ' if pretty_print else ''
        indent2 = '\n      ' if pretty_print else ''

        rss = Element('rss', version='2.0')
        rss.text = '\n  ' if pretty_print else ''

        channel = SubElement(rss, 'channel')
        channel.text = indent
        channel.tail = '\n' if pretty_print else ''

        set_rss2_text(SubElement(channel, 'title'), feed.title)
        set_rss2_text(SubElement(channel, 'description'), feed.subtitle or '')
        SubElement(channel, 'link').text = feed.link
        SubElement(channel, 'lastBuildDate').text = rss2_date(feed.updated)
        if feed.language: SubElement(channel, 'language').text = feed.language
        if feed.rights: SubElement(channel, 'copyright').text = feed.rights
        if feed.logo:
            image = SubElement(channel, 'image')
            image.text = indent2
            SubElement(image, 'url').text = feed.logo
            SubElement(image, 'title').text = ''
            SubElement(image, 'link').text = feed.link
            for child in image: child.tail = indent2
            image[-1].tail = '\n    ' if pretty_print else ''

        for entry in feed.entries:
            item = entry.rss2(pretty_print)
            item[-1].tail = indent
            channel.append(item)

        for child in channel: child.tail = indent
        channel[-1].tail = '\n  ' if pretty_print else ''
        return rss
예제 #2
0
def makerss(titletext, top, root, files):
    print 'Building %s' % os.path.join(root, 'photos.rss')
    dirlen = len(top) + len(os.path.sep)
    rootpath = root[dirlen:]
    rootlen = len(rootpath) > 0 and len(rootpath) + len(os.path.sep) or 0
    rss = Element('rss', version='2.0')
    rss.attrib['xmlns:atom'] = NS_ATOM
    rss.attrib['xmlns:media'] = NS_MEDIA
    channel = SubElement(rss, 'channel')
    title = SubElement(channel, 'title')
    title.text = titletext
    description = SubElement(channel, 'description')
    description.text = _(
        'This feed enables cooliris http://www.cooliris.com/ in your web browser'
    )
    channel.append(Comment('must have a link for rss'))
    link = SubElement(channel, 'link')
    link.text = 'http://localhost/'
    result = []
    for image in files:
        imagepath = util.www_image_path(image, '.images')
        if not options.noimages:
            util.www_image_create(os.path.join(top, image),
                                  force=options.force,
                                  verbose=options.verbose)
        thumbpath = util.www_image_path(image, '.thumbs')
        if not options.nothumbs:
            util.www_thumb_create(os.path.join(top, image),
                                  force=options.force,
                                  verbose=options.verbose)
        if options.verbose >= 3:
            print 'rootpath:', rootpath, 'image:', image, 'imagepath:', imagepath, 'thumbpath:', thumbpath
            print 'imagepath[rootlen:]:', imagepath[
                rootlen:], 'thumbpath[rootlen:]:', thumbpath[rootlen:]
        result.append(os.path.join(rootpath, image))
        image = image[rootlen:]
        item = SubElement(channel, 'item')
        title = SubElement(item, 'title')
        title.text = image
        link = SubElement(item, 'link')
        link.text = urllib.quote(imagepath)
        description = SubElement(item, 'media:description')
        description.text = convert_entities(
            os.path.splitext(os.path.basename(image))[0])
        # need to double quote special characters
        thumbnail = SubElement(item,
                               'media:thumbnail',
                               url=urllib.quote(
                                   urllib.quote(thumbpath[rootlen:])))
        content = SubElement(item,
                             'media:content',
                             url=urllib.quote(urllib.quote(
                                 imagepath[rootlen:])))

    indent(rss)
    file = open(os.path.join(root, 'photos.rss'), 'w')
    print >> file, '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    print >> file, tostring(rss)
    file.close()
    return result
예제 #3
0
    def _create_embedded_devices(self):
        if self.device.is_root_device():
            embedded_devices = self.device.devices

            if len(embedded_devices) > 0:
                device_list_element = SubElement(self.device_element,
                                                 "deviceList")
                for embedded_device in embedded_devices.values():
                    embedded_device_description = DeviceXMLGenerator(
                        embedded_device)
                    device_list_element.append(
                        embedded_device_description.generate())
예제 #4
0
    def _create_embedded_devices(self):
        if self.device.is_root_device():
            embedded_devices = self.device.devices

            if len(embedded_devices) > 0:
                device_list_element = SubElement(self.device_element,
                                                 "deviceList")
                for embedded_device in embedded_devices.values():
                    embedded_device_description = DeviceXMLGenerator(
                                                            embedded_device)
                    device_list_element.append(embedded_device_description.
                                               generate())
예제 #5
0
 def test_writer(self):
     a = Element('a')
     b = SubElement(a, 'b')
     b.append(Comment('a comment'))
     c = SubElement(b, 'c', d = 'e')
     f = SubElement(c, 'f')
     f.text = 'g'
     h = SubElement(c, 'h')
     h.text = 'i << >> << &&'
     b.append(ProcessingInstruction('pdk', 'processing instruction'))
     tree = ElementTree(a)
     output = stringio()
     write_pretty_xml(tree, output)
     self.assert_equals_long(expected_xml_output, output.getvalue())
예제 #6
0
 def gpx(self,gpx):
   "Construct an ElementTree for the given GPX file"
   root = Element("gpx",xmlns=NS,version="1.1",creator=self.creator)
   for wpt in gpx.waypoints:
     root.append(self.wpt(wpt,"wpt"))
   for route in gpx.routes:
     el = self.path(route,"rte","rtept")
     xmlutil.write(el,route,Route._scheme)
     root.append(el) 
   for track in gpx.tracks:
     el = SubElement(root,"trk")
     xmlutil.write(el,track,Track._scheme)
     for seg in track:
       el.append(self.path(seg,"trkseg","trkpt"))
   return root
예제 #7
0
def makerss(titletext, top, root, files):
    print 'Building %s' % os.path.join(root, 'photos.rss')
    dirlen = len(top)+len(os.path.sep)
    rootpath = root[dirlen:]
    rootlen = len(rootpath) > 0 and len(rootpath)+len(os.path.sep) or 0
    rss = Element('rss', version='2.0')
    rss.attrib['xmlns:atom'] = NS_ATOM
    rss.attrib['xmlns:media'] = NS_MEDIA
    channel = SubElement(rss, 'channel')
    title = SubElement(channel, 'title')
    title.text = titletext
    description = SubElement(channel, 'description')
    description.text = _('This feed enables cooliris http://www.cooliris.com/ in your web browser')
    channel.append(Comment('must have a link for rss'))
    link = SubElement(channel, 'link')
    link.text = 'http://localhost/'
    result = []
    for image in files:
        imagepath = util.www_image_path(image, '.images')
        if not options.noimages:
            util.www_image_create(os.path.join(top, image), force=options.force, verbose=options.verbose)
        thumbpath = util.www_image_path(image, '.thumbs')
        if not options.nothumbs:
            util.www_thumb_create(os.path.join(top, image), force=options.force, verbose=options.verbose)
        if options.verbose >= 3:
            print 'rootpath:', rootpath, 'image:', image, 'imagepath:', imagepath, 'thumbpath:', thumbpath
            print 'imagepath[rootlen:]:', imagepath[rootlen:], 'thumbpath[rootlen:]:', thumbpath[rootlen:]
        result.append(os.path.join(rootpath, image))
        image = image[rootlen:]
        item = SubElement(channel, 'item')
        title = SubElement(item, 'title')
        title.text = image
        link = SubElement(item, 'link')
        link.text = urllib.quote(imagepath)
        description = SubElement(item, 'media:description')
        description.text = convert_entities(os.path.splitext(os.path.basename(image))[0])
        # need to double quote special characters
        thumbnail = SubElement(item, 'media:thumbnail', url=urllib.quote(urllib.quote(thumbpath[rootlen:])))
        content = SubElement(item, 'media:content', url=urllib.quote(urllib.quote(imagepath[rootlen:])))

    indent(rss)
    file = open(os.path.join(root, 'photos.rss'), 'w')
    print >>file, '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    print >>file, tostring(rss)
    file.close()
    return result
    def rss2(feed, pretty_print=True):
        indent = '\n    ' if pretty_print else ''
        indent2 = '\n      ' if pretty_print else ''

        rss = Element('rss', version='2.0')
        rss.text = '\n  ' if pretty_print else ''

        channel = SubElement(rss, 'channel')
        channel.text = indent
        channel.tail = '\n' if pretty_print else ''

        set_rss2_text(SubElement(channel, 'title'), feed.title)
        set_rss2_text(SubElement(channel, 'description'), feed.subtitle or '')
        SubElement(channel, 'link').text = feed.link
        SubElement(channel, 'lastBuildDate').text = rss2_date(feed.updated)
        if feed.language: SubElement(channel, 'language').text = feed.language
        if feed.rights: SubElement(channel, 'copyright').text = feed.rights
        if feed.logo:
            image = SubElement(channel, 'image')
            image.text = indent2
            SubElement(image, 'url').text = feed.logo
            SubElement(image, 'title').text = ''
            SubElement(image, 'link').text = feed.link
            for child in image:
                child.tail = indent2
            image[-1].tail = '\n    ' if pretty_print else ''

        for entry in feed.entries:
            item = entry.rss2(pretty_print)
            item[-1].tail = indent
            channel.append(item)

        for child in channel:
            child.tail = indent
        channel[-1].tail = '\n  ' if pretty_print else ''
        return rss
예제 #9
0
def apply_msgfdb(in_file, msms_run_summary, modifications, num_mods):
    """ Read output file of MS-GFDB and add child elements to msms_run_summary """
    spectrum2element = {}
    enzyme_list = [ArgC,LysC,Trypsin,LysCP,Chymotrypsin,TrypChymo,TrypsinP,PepsinA,
                   CNBr,V8E,AspN,Formic_acid,AspNambic,V8DE]
    semi_list = []
    sample_enzyme = msms_run_summary.find('sample_enzyme')
    for f in read_msgfdb(in_file):
        spectrum = '%(name)s.%(scan)05i.%(scan)05i.%(charge)i' % \
            {'name': remove_file_extention(f['#SpecFile']),
             'scan': f['Scan#'], 'charge': f['Charge']}
        enzyme_list, semi_list = what_enzyme(enzyme_list, semi_list, f['Peptide'])
        peptide_prev_aa = f['Peptide'][0]
        if peptide_prev_aa == '_':
            peptide_prev_aa = '-'
        peptide_middle = f['Peptide'][2:-2]
        peptide_next_aa = f['Peptide'][-1]
        if peptide_next_aa == '_':
            peptide_next_aa = '-'
        if ' ' in f['Protein']:
            protein_name, protein_descr = f['Protein'].split(' ', 1)
        else:
            protein_name = f['Protein']
            protein_descr = ''
        precursor_neutral_mass = f['Precursor'] * f['Charge'] - f['Charge'] * H_plus

        if spectrum not in spectrum2element:
            spectrum_query = SubElement(msms_run_summary, 'spectrum_query')
            spectrum2element[spectrum] = spectrum_query
            spectrum_query.append(Element('search_result'))
            spectrum_query.set('spectrum', spectrum)
            spectrum_query.set('start_scan', str(f['Scan#']))
            spectrum_query.set('end_scan', str(f['Scan#']))
            spectrum_query.set('assumed_charge', str(f['Charge']))
            spectrum_query.set('precursor_neutral_mass', str(precursor_neutral_mass))

        spectrum_query = spectrum2element[spectrum]
        search_result = spectrum_query.find('search_result')
        search_hit = SubElement(search_result, 'search_hit')
        search_hit.set('peptide', "".join(aa for aa in peptide_middle if aa.isalpha()))
        search_hit.set('peptide_prev_aa', peptide_prev_aa)
        search_hit.set('peptide_next_aa', peptide_next_aa)
        search_hit.set('protein', protein_name)
        search_hit.set('protein_descr', protein_descr)

        modification_instances = sum((find_modifications(mod, peptide_middle) for mod in modifications), [])
        calc_neutral_pep_mass = modified_peptide_mass(modification_instances, peptide_middle, num_mods)
        if modification_instances:
            modification_info = SubElement(search_hit, 'modification_info')
            for mass, mass_diff, aa_number, is_opt in modification_instances:
                maam = SubElement(modification_info, 'mod_aminoacid_mass')
                maam.set('position', str(aa_number))
                maam.set('mass', str(mass))
        search_hit.set('calc_neutral_pep_mass', str(calc_neutral_pep_mass))
        search_hit.set('massdiff', str(precursor_neutral_mass - calc_neutral_pep_mass))
        for field in score_fields:
            if field in f:
                SubElement(search_hit, 'search_score', name=field, value=f[field])
#    sample_enzyme.set('fidelity',flag)
    if enzyme_list == []:
        if semi_list == []:
            sample_enzyme.set('name','NoEnzyme')
            sample_enzyme.set('fidelity','nonspecific')
        else:
            sample_enzyme.set('fidelity','semispecific')
            enzyme = re.split("\|",enzyme2name[re.search(r'<(\w+)>',semi_list[0][0]).group(1)])
    else:
        sample_enzyme.set('fidelity','specific')
        enzyme = re.split("\|",enzyme2name[re.search(r'<(\w+)>',enzyme_list[0][0]).group(1)])
    if not(enzyme_list == [] and semi_list == []):
        sample_enzyme.set('name',enzyme[0])
        specificity = SubElement(sample_enzyme, 'specificity')
        specificity.set('cut',enzyme[1])
        if enzyme[2]:
            specificity.set('no_cut',enzyme[2])
        specificity.set('sense',enzyme[3])
예제 #10
0
class Document(object):
    """building output waebric xhtml document """

    def __init__(self, output, verbose=False):
        self.lastElement = Element('html')
        self.tree = ET.ElementTree(self.lastElement)
        self.trees = [self.tree]
        self.output = output
        self.verbose = verbose

    #@trace
    def addElement(self, name):
        self.lastElement = SubElement(self.lastElement, name)
        return self.lastElement

    #@trace
    def addText(self, string):
        if not len(self.lastElement):
            e = self.lastElement
            txt = "%s%s" % (e.text, string) if e.text else string
            e.text = txt
        else:
            e = self.lastElement[-1]
            txt = "%s%s" % (e.tail, string) if e.tail else string
            e.tail = txt

    def addAttribute(self,name,value):
        if self.lastElement.get(name):
            value = "%s %s" % (self.lastElement.get(name),value)
        self.lastElement.set(name, value)

    def addComment(self, string):
        self.lastElement.append(ET.Comment(string))

    def getFile(self, filename):
        if self.output:
            filename = "%s/%s" % (self.output, filename)
        try:
            _file = open(filename,'w')
        except IOError:
            print "file name %s cannot be opened, no output written" % filename
            return
        return _file

    def setGoodRootElement(self):
        """make sure we have the correct root ellement according to the
           wae standard. It could be needed to remove the top html
           element because i ad it to work correctly with elementtree Libary.
        """
        r = self.tree.getroot()
        if len(r) == 1 and not r.text and not r[-1].tail:
            child = r.getchildren()[0]
            if isinstance(child.tag, str):#check needed for comment element.
                self.tree._setroot(r[0])

    def writeOutput(self, filename):

        self.setGoodRootElement()
        _file = self.getFile(filename)

        DTD = """<?xml version="1.0" encoding="UTF-8"?>\n"""
        _file.write(DTD)
        for tree in self.trees:
            if isinstance(tree, ET.ElementTree):
                self.tree.write(_file)
            else: #could be data string.
                _file.write(tree)
        _file.write('\n')
        _file.close()

        if self.verbose:
            output = open(_file.name)
            print output.read()

    def writeEmptyFile(self, filename):
        _file = self.getFile(filename)
        _file.write('')
        _file.close()
예제 #11
0
def apply_msgfdb(in_file, msms_run_summary, modifications, num_mods):
    """ Read output file of MS-GFDB and add child elements to msms_run_summary """
    spectrum2element = {}
    enzyme_list = [
        ArgC, LysC, Trypsin, LysCP, Chymotrypsin, TrypChymo, TrypsinP, PepsinA,
        CNBr, V8E, AspN, Formic_acid, AspNambic, V8DE
    ]
    semi_list = []
    sample_enzyme = msms_run_summary.find('sample_enzyme')
    for f in read_msgfdb(in_file):
        spectrum = '%(name)s.%(scan)05i.%(scan)05i.%(charge)i' % \
            {'name': remove_file_extention(f['#SpecFile']),
             'scan': f['Scan#'], 'charge': f['Charge']}
        enzyme_list, semi_list = what_enzyme(enzyme_list, semi_list,
                                             f['Peptide'])
        peptide_prev_aa = f['Peptide'][0]
        if peptide_prev_aa == '_':
            peptide_prev_aa = '-'
        peptide_middle = f['Peptide'][2:-2]
        peptide_next_aa = f['Peptide'][-1]
        if peptide_next_aa == '_':
            peptide_next_aa = '-'
        if ' ' in f['Protein']:
            protein_name, protein_descr = f['Protein'].split(' ', 1)
        else:
            protein_name = f['Protein']
            protein_descr = ''
        precursor_neutral_mass = f['Precursor'] * f['Charge'] - f[
            'Charge'] * H_plus

        if spectrum not in spectrum2element:
            spectrum_query = SubElement(msms_run_summary, 'spectrum_query')
            spectrum2element[spectrum] = spectrum_query
            spectrum_query.append(Element('search_result'))
            spectrum_query.set('spectrum', spectrum)
            spectrum_query.set('start_scan', str(f['Scan#']))
            spectrum_query.set('end_scan', str(f['Scan#']))
            spectrum_query.set('assumed_charge', str(f['Charge']))
            spectrum_query.set('precursor_neutral_mass',
                               str(precursor_neutral_mass))

        spectrum_query = spectrum2element[spectrum]
        search_result = spectrum_query.find('search_result')
        search_hit = SubElement(search_result, 'search_hit')
        search_hit.set('peptide',
                       "".join(aa for aa in peptide_middle if aa.isalpha()))
        search_hit.set('peptide_prev_aa', peptide_prev_aa)
        search_hit.set('peptide_next_aa', peptide_next_aa)
        search_hit.set('protein', protein_name)
        search_hit.set('protein_descr', protein_descr)

        modification_instances = sum((find_modifications(mod, peptide_middle)
                                      for mod in modifications), [])
        calc_neutral_pep_mass = modified_peptide_mass(modification_instances,
                                                      peptide_middle, num_mods)
        if modification_instances:
            modification_info = SubElement(search_hit, 'modification_info')
            for mass, mass_diff, aa_number, is_opt in modification_instances:
                maam = SubElement(modification_info, 'mod_aminoacid_mass')
                maam.set('position', str(aa_number))
                maam.set('mass', str(mass))
        search_hit.set('calc_neutral_pep_mass', str(calc_neutral_pep_mass))
        search_hit.set('massdiff',
                       str(precursor_neutral_mass - calc_neutral_pep_mass))
        for field in score_fields:
            if field in f:
                SubElement(search_hit,
                           'search_score',
                           name=field,
                           value=f[field])


#    sample_enzyme.set('fidelity',flag)
    if enzyme_list == []:
        if semi_list == []:
            sample_enzyme.set('name', 'NoEnzyme')
            sample_enzyme.set('fidelity', 'nonspecific')
        else:
            sample_enzyme.set('fidelity', 'semispecific')
            enzyme = re.split(
                "\|", enzyme2name[re.search(r'<(\w+)>',
                                            semi_list[0][0]).group(1)])
    else:
        sample_enzyme.set('fidelity', 'specific')
        enzyme = re.split(
            "\|", enzyme2name[re.search(r'<(\w+)>',
                                        enzyme_list[0][0]).group(1)])
    if not (enzyme_list == [] and semi_list == []):
        sample_enzyme.set('name', enzyme[0])
        specificity = SubElement(sample_enzyme, 'specificity')
        specificity.set('cut', enzyme[1])
        if enzyme[2]:
            specificity.set('no_cut', enzyme[2])
        specificity.set('sense', enzyme[3])
예제 #12
0
class Document(object):
    """building output waebric xhtml document """
    def __init__(self, output, verbose=False):
        self.lastElement = Element('html')
        self.tree = ET.ElementTree(self.lastElement)
        self.trees = [self.tree]
        self.output = output
        self.verbose = verbose

    #@trace
    def addElement(self, name):
        self.lastElement = SubElement(self.lastElement, name)
        return self.lastElement

    #@trace
    def addText(self, string):
        if not len(self.lastElement):
            e = self.lastElement
            txt = "%s%s" % (e.text, string) if e.text else string
            e.text = txt
        else:
            e = self.lastElement[-1]
            txt = "%s%s" % (e.tail, string) if e.tail else string
            e.tail = txt

    def addAttribute(self, name, value):
        if self.lastElement.get(name):
            value = "%s %s" % (self.lastElement.get(name), value)
        self.lastElement.set(name, value)

    def addComment(self, string):
        self.lastElement.append(ET.Comment(string))

    def getFile(self, filename):
        if self.output:
            filename = "%s/%s" % (self.output, filename)
        try:
            _file = open(filename, 'w')
        except IOError:
            print "file name %s cannot be opened, no output written" % filename
            return
        return _file

    def setGoodRootElement(self):
        """make sure we have the correct root ellement according to the
           wae standard. It could be needed to remove the top html
           element because i ad it to work correctly with elementtree Libary.
        """
        r = self.tree.getroot()
        if len(r) == 1 and not r.text and not r[-1].tail:
            child = r.getchildren()[0]
            if isinstance(child.tag, str):  #check needed for comment element.
                self.tree._setroot(r[0])

    def writeOutput(self, filename):

        self.setGoodRootElement()
        _file = self.getFile(filename)

        DTD = """<?xml version="1.0" encoding="UTF-8"?>\n"""
        _file.write(DTD)
        for tree in self.trees:
            if isinstance(tree, ET.ElementTree):
                self.tree.write(_file)
            else:  #could be data string.
                _file.write(tree)
        _file.write('\n')
        _file.close()

        if self.verbose:
            output = open(_file.name)
            print output.read()

    def writeEmptyFile(self, filename):
        _file = self.getFile(filename)
        _file.write('')
        _file.close()