示例#1
0
def parse_xml_string(xml_string,
                     charset=u'utf-8',
                     parser=etree.XMLParser(remove_comments=True)):
    u'''
    Разбор строки, содержащей XML-документ с настраиваемым парсером.

    По умолчанию используется парсер, удаляющий комментарии из документа.

    :param  unicode xml_string:  Строка, содержащая XML-документ.
    :param  unicode charset:     Кодировка.
    :param  function parser:     Парсер, используемый для разбора строки.    
    :return: Корень XML-документа.
    :rtype:  lxml.Element
    '''
    try:
        try:
            root, xmlids = etree.XMLID(xml_string, parser)
        except XMLSyntaxError as err:
            raise Fault(unicode(err))
    except ValueError:
        try:
            root, xmlids = etree.XMLID(xml_string.encode(charset), parser)
        except XMLSyntaxError as err:
            raise Fault(unicode(err))
    return root
示例#2
0
def _parse_xml_string(xml_string, parser, charset=None):
    xml_string = iter(xml_string)
    chunk = next(xml_string)
    if isinstance(chunk, six.binary_type):
        string = b''.join(chain((chunk, ), xml_string))
    else:
        string = ''.join(chain((chunk, ), xml_string))

    if charset:
        string = string.decode(charset)

    try:
        try:
            root, xmlids = etree.XMLID(string, parser)

        except ValueError as e:
            logger.debug('ValueError: Deserializing from unicode strings with '
                         'encoding declaration is not supported by lxml.')
            root, xmlids = etree.XMLID(string.encode(charset), parser)

    except XMLSyntaxError as e:
        logger_invalid.error("%r in string %r", e, string)
        raise Fault('Client.XMLSyntaxError', str(e))

    return root, xmlids
示例#3
0
def _parse_xml_string(xml_string, charset=None):
    try:
        if charset is None:  # hack
            raise ValueError(charset)

        root, xmlids = etree.XMLID(xml_string.decode(charset))

    except ValueError, e:
        logger.debug('%s -- falling back to str decoding.' % (e))
        root, xmlids = etree.XMLID(xml_string)
示例#4
0
	def getDeviceInfo(self):
		logging.debug(">>")
		result = commands.getstatusoutput('garmin_get_info')
		logging.debug("Returns "+str(result))
		numError = 0
		if result[0] == 0:
			if result[1] != "garmin unit could not be opened!":
				try:
					#ToDo: review, always get "lxml.etree.XMLSyntaxError: PCDATA invalid Char value 28, line 6, column 29" error
					xmlString = result[1].rstrip()
					logging.debug("xmlString: "+str(xmlString))
					prueba = etree.XMLID(xmlString)
					logging.debug("Prueba: "+str(prueba))
					tree = etree.fromstring(xmlString)
					description = self.getProductDesc(tree)
					if description is not None:
						logging.info("Found "+str(description))
					else:
						raise Exception
				except:
					logging.error("Not able to identify GPS device. Continuing anyway...")
					pass
			else:
				logging.error(result[1])
				numError = -1
		else:
			logging.error("Can not find garmintools binaries, please check your installation")
			numError = -2
		logging.debug("<<")
		return numError
示例#5
0
def _parse_xml_string(xml_string, parser, charset=None):
    string = ''.join(xml_string)
    if charset:
        string = string.decode(charset)

    try:
        try:
            root, xmlids = etree.XMLID(string, parser)

        except ValueError, e:
            logger.debug('ValueError: Deserializing from unicode strings with '
                         'encoding declaration is not supported by lxml.')
            root, xmlids = etree.XMLID(string.encode(charset), parser)

    except XMLSyntaxError, e:
        logger_invalid.error(string)
        raise Fault('Client.XMLSyntaxError', str(e))
示例#6
0
    def _wof_parse_xml_string(self, xml_string, parser, charset=None):
        string = b''.join(xml_string)
        if charset:
            # string = string.decode(charset)
            string = string.decode('utf-8-sig')  # Remove BOM.
            string = string.encode(charset)  # Back to original encoding type.
        try:
            try:
                root, xmlids = etree.XMLID(string, parser)
            except ValueError as e:
                logging.debug(
                    'ValueError: de-serializing from unicode strings with '
                    'encoding declaration is not supported by lxml.')
                root, xmlids = etree.XMLID(string.encode(charset), parser)

        except XMLSyntaxError as e:
            logger_invalid.error("%r in string %r", e, string)
            raise Fault('Client.XMLSyntaxError', str(e))

        return root, xmlids
示例#7
0
def _parse_xml_string(xml_string, charset=None):
    if charset:
        string = ''.join([s.decode(charset) for s in xml_string])
    else:
        string = ''.join(xml_string)

    try:
        try:
            root, xmlids = etree.XMLID(string)

        except XMLSyntaxError, e:
            logger.error(string)
            raise Fault('Client.XMLSyntaxError', str(e))

    except ValueError, e:
        logger.debug('%r -- falling back to str decoding.' % (e))
        try:
            root, xmlids = etree.XMLID(string.encode(charset))
        except XMLSyntaxError, e:
            logger.error(string)
            raise Fault('Client.XMLSyntaxError', str(e))
示例#8
0
    def from_soap(self):
        sp_str = self.request.other.get('SOAPXML') or self.request['BODY']
        root, xmlids = etree.XMLID(sp_str)
        if xmlids:
            # resolve_hrefs operates on the root element
            resolve_hrefs(root, xmlids)
        body = None
        header = None
        for e in root.getchildren():
            name = e.tag.split('}')[-1].lower()
            if name == 'body':
                body = e
            elif name == 'header':
                header = e

        payload = None

        if len(body.getchildren()):
            payload = body.getchildren()[0]

        return payload, header
示例#9
0
def generate_legend(colormaps, output, output_format, orientation):

    # set ticklines out
    rcParams['xtick.direction'] = 'out'
    rcParams['ytick.direction'] = 'out'

    lc = len(colormaps)
    t = 0
    has_values = False

    for colormap in colormaps:
        if colormap.title != None:
            t = 0.15
        if colormap.legend != None:
            if colormap.legend.legend_type != "classification":
                has_values = True

    if orientation == 'horizontal':
        t = 0.15
        fig = pyplot.figure(figsize=(4.2, t + 0.8 + (1 * (lc - 1))))
    else:  # default vertical orientation
        fig = pyplot.figure(figsize=(1.5 + (2 * (lc - 1)), 3.2))

    colors = []
    colormap_entries = []
    colormap_count = 0
    labels = []
    label_index = []

    for colormap in colormaps:
        colormap_count += 1
        is_large_colormap = False
        center_ticks = False
        bounds = []
        ticks = []
        ticklabels = []
        legendcolors = []
        legendlabels = []

        if colormap.legend == None:
            entries = colormap.colormap_entries
            # ensure showTick and showLabel exist if no legend
            for idx in range(0, len(entries)):
                entries[idx].showtick = False
                entries[idx].showlabel = False
        else:
            entries = colormap.legend.legend_entries
            colormap.style = colormap.legend.legend_type
            if colormap.legend.legend_type != "classification":
                # clear colors if not classification
                colors = []
                colormap_entries = []

        # use only entries with showTick or showLabel in newer colormap schema
        show_all = True  #legacy schema
        for colormap_entry in entries:
            if colormap_entry.showtick == True or colormap_entry.showlabel == True:
                show_all = False

        for colormap_entry in entries:
            if colormap_entry.transparent == False:
                if colormap.style == "classification":
                    legendcolors.append(colormap_entry.color)
                    legendlabels.append(colormap_entry.label)
                    labels.append(colormap_entry.label)
                else:
                    if colormap_entry.color != None:
                        has_values = True
                        colormap_entries.append(colormap_entry)
                        colors.append(colormap_entry.color)

            if len(colors) > 12:
                # legacy linear interpolation of values if large colormap
                is_large_colormap = True

        if colormap.style != "classification":
            for idx in range(0, len(colormap_entries)):

                # legacy schema uses values instead of just the label
                if show_all == True:  # deprecated
                    if "(" in colormap_entries[
                            idx].value or "[" in colormap_entries[
                                idx].value and ',' not in colormap_entries[
                                    idx].value:
                        colormap_entries[idx].value = colormap_entries[
                            idx].value.replace('[', '').replace(']', '')
                    if colormap.style == "continuous" or (
                            "(" in colormap_entries[idx].value
                            or "[" in colormap_entries[idx].value
                    ):  # break apart values for ranges
                        bounds.append(
                            float(colormap_entries[idx].value.split(',')
                                  [0].replace('[',
                                              '').replace(']',
                                                          '').replace('(',
                                                                      '')))
                        if idx == 0:
                            # always add the first value
                            value = float(colormap_entries[idx].value.split(
                                ',')[0].replace('[', '').replace(']',
                                                                 '').replace(
                                                                     '(', ''))
                            if math.isinf(value) == True:
                                value = float(
                                    colormap_entries[idx].value.split(
                                        ',')[1].replace(')', '').replace(
                                            '[', '').replace(']', ''))
                            ticks.append(value)
                            ticklabels.append(value)
                        elif idx != len(colormap_entries) - 1:
                            if show_all == True or colormap_entries[
                                    idx].showtick == True or colormap_entries[
                                        idx].showlabel == True:
                                ticks.append(
                                    float(colormap_entries[idx].value.split(
                                        ',')[0].replace('[', '').replace(
                                            ']', '').replace('(', '')))
                            if show_all == True or colormap_entries[
                                    idx].showlabel == True:
                                ticklabels.append(
                                    float(colormap_entries[idx].value.split(
                                        ',')[0].replace('[', '').replace(
                                            ']', '').replace('(', '')))
                        if idx == len(colormap_entries) - 1 and (
                                "(" in colormap_entries[idx].value
                                or "[" in colormap_entries[idx].value
                        ):  # add ending range value
                            bounds.append(
                                float(colormap_entries[idx].value.split(',')
                                      [1].replace(')',
                                                  '').replace('[', '').replace(
                                                      ']', '')))
                            # always add the last value
                            value = float(colormap_entries[idx].value.split(
                                ',')[1].replace(')', '').replace('[',
                                                                 '').replace(
                                                                     ']', ''))
                            if math.isinf(value) == True:
                                value = float(
                                    colormap_entries[idx].value.split(
                                        ',')[0].replace('[', '').replace(
                                            ']', '').replace('(', ''))
                            ticks.append(value)
                            ticklabels.append(value)
                    else:  # discrete values
                        bounds.append(float(colormap_entries[idx].value))
                        center_ticks = True
                        if idx == len(colormap_entries) - 1:
                            increment = (
                                float(colormap_entries[idx].value) -
                                float(colormap_entries[idx - 1].value))
                            bounds.append(
                                float(colormap_entries[idx].value) + increment)
                            ticks.append(
                                float(colormap_entries[idx].value) +
                                increment / 2)
                            ticklabels.append(
                                float(colormap_entries[idx].value))
                        else:
                            increment = (float(colormap_entries[
                                idx + 1].value.split(',')[0].replace(
                                    '[', '').replace(']', '')) -
                                         float(colormap_entries[idx].value))
                            if show_all == True or colormap_entries[
                                    idx].showtick == True or colormap_entries[
                                        idx].showlabel == True or idx == 0:
                                ticks.append(
                                    float(colormap_entries[idx].value) +
                                    increment / 2)
                            if show_all == True or colormap_entries[
                                    idx].showlabel == True or idx == 0:
                                ticklabels.append(
                                    float(colormap_entries[idx].value))

                else:  # new schema
                    if colormap_entries[
                            idx].showtick == True or colormap_entries[
                                idx].showlabel == True or idx == 0 or idx == len(
                                    colormap_entries) - 1:
                        if colormap.style == "discrete":
                            ticks.append(idx + 0.5)
                        else:
                            if idx == len(colormap_entries) - 1:
                                ticks.append(idx + 1)  # add end label
                            else:
                                ticks.append(idx)
                        if colormap_entries[idx].showlabel == True:
                            ticklabels.append(colormap_entries[idx].label)
                            labels.append(colormap_entries[idx].label)
                        elif idx == 0 and colormap.legend.min_label != None:
                            ticklabels.append(colormap.legend.min_label)
                            labels.append(colormap.legend.min_label)
                        elif idx == len(
                                colormap_entries
                        ) - 1 and colormap.legend.max_label != None:
                            ticklabels.append(colormap.legend.max_label)
                            labels.append(colormap.legend.max_label)
                        else:
                            ticklabels.append("")
                            labels.append("")
                        label_index.append(idx)

        # Handle +/- INF
        lowerinf = False
        upperinf = False
        if len(bounds) > 0:
            lowerinf = math.isinf(bounds[0])
            upperinf = math.isinf(bounds[-1])
            bounds = [x for x in bounds if math.isinf(x) == False]
            ticks = [x for x in ticks if math.isinf(x) == False]

        # Check for long labels
        longlabels = False
        for legendlabel in legendlabels:
            if len(legendlabel) > 14:
                longlabels = True

        if orientation == 'horizontal':
            if lc == 1:
                bottom = 0.6 - t
            else:
                bottom = 0.90 - ((0.9 / lc) *
                                 (colormap_count - 1)) - (0.20 / lc)
            height = 0.20 / lc

            # use legend for classifications
            if colormap.style == "classification":
                if lc == 1:
                    fig.set_figheight(3)
                    if longlabels:
                        fig.set_figwidth(3)
                    else:
                        fig.set_figwidth(1.5)
                else:
                    bottom = bottom
                patches = []
                for color in legendcolors:
                    polygon = mpl.patches.Rectangle((0, 0),
                                                    10,
                                                    10,
                                                    facecolor=color)
                    polygon.set_linewidth(0.5)
                    patches.append(polygon)
                if len(legendcolors) < 7 and has_values == False:
                    if lc == 1:
                        fig.set_figheight(1.5)
                if len(legendcolors) <= (15 / lc):
                    col = 1
                    fontsize = 9
                if len(legendcolors) > (15 / lc):
                    if lc == 1:
                        fig.set_figwidth(3)
                    col = 2
                    fontsize = 8
                if len(legendcolors) > (30 / lc):
                    if lc == 1:
                        fig.set_figwidth(4.2)
                    col = 3
                    fontsize = 7
                if has_values == True:
                    if lc == 1:
                        fig.set_figwidth(4.2)
                    legend = fig.legend(
                        patches,
                        legendlabels,
                        bbox_to_anchor=[0.025, bottom + (0.3 / lc)],
                        loc='upper left',
                        ncol=col,
                        fancybox=True,
                        prop={'size': fontsize})
                    legend.get_frame().set_alpha(0)
                else:
                    legend = fig.legend(patches,
                                        legendlabels,
                                        bbox_to_anchor=[0.5, 0.5],
                                        loc='center',
                                        ncol=col,
                                        fancybox=True,
                                        prop={'size': fontsize})
                    legend.get_frame().set_alpha(0.5)

            if has_values == True and (colormap.style != "classification"
                                       or colormap.legend == None):
                ax = fig.add_axes([0.075, bottom, 0.85, height])
                cmap = mpl.colors.ListedColormap(colors)

                if show_all == True:
                    if is_large_colormap == True:
                        norm = mpl.colors.Normalize(bounds[0],
                                                    bounds[len(bounds) - 1])
                        v = np.linspace(bounds[0],
                                        bounds[len(bounds) - 1],
                                        9,
                                        endpoint=True)
                        cb = mpl.colorbar.ColorbarBase(ax,
                                                       cmap=cmap,
                                                       norm=norm,
                                                       ticks=v,
                                                       orientation=orientation)
                    else:
                        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
                        cb = mpl.colorbar.ColorbarBase(ax,
                                                       cmap=cmap,
                                                       norm=norm,
                                                       orientation=orientation)
                        if center_ticks == True:
                            cb.set_ticks(ticks)
                            cb.ax.set_xticklabels(ticklabels)
                else:
                    if len(bounds) > 0:
                        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
                        cb = mpl.colorbar.ColorbarBase(ax,
                                                       cmap=cmap,
                                                       norm=norm,
                                                       ticks=ticks,
                                                       orientation=orientation)
                        cb.ax.set_xticklabels(ticks)
                    else:
                        norm = mpl.colors.BoundaryNorm(range(len(colors) + 1),
                                                       cmap.N)
                        cb = mpl.colorbar.ColorbarBase(ax,
                                                       cmap=cmap,
                                                       norm=norm,
                                                       ticks=ticks,
                                                       orientation=orientation)
                        cb.ax.set_xticklabels(ticklabels)

                cb.solids.set_edgecolor("face")

                for tick in cb.ax.xaxis.get_ticklabels():
                    tick.set_fontsize(8)

                if colormap.legend != None and len(bounds) > 0:
                    if len(cb.ax.get_xticklabels()) > 0:
                        xticklabels = cb.ax.get_xticklabels()
                        xticklabels = [
                            label.get_text() for label in xticklabels
                        ]
                        # Check for infinity
                        if lowerinf:
                            xticklabels[0] = "<=" + xticklabels[0]
                        if upperinf:
                            xticklabels[-1] = ">=" + xticklabels[-1]

                        # show only those with showLabel
                        for idx in range(0, len(xticklabels)):
                            if center_ticks == True:
                                if show_all == False:
                                    if float(xticklabels[idx]) - (
                                            increment / 2) not in ticklabels:
                                        xticklabels[idx] = ""
                                    else:
                                        xticklabels[idx] = (
                                            float(xticklabels[idx]) -
                                            (increment / 2))
                                        if float(
                                                xticklabels[idx]).is_integer():
                                            xticklabels[idx] = int(
                                                float(xticklabels[idx]))
                                else:
                                    if float(xticklabels[idx]
                                             ) not in ticklabels:
                                        xticklabels[idx] = ""
                            else:
                                if show_all == False:
                                    try:
                                        if float(xticklabels[idx]
                                                 ) not in ticklabels:
                                            xticklabels[idx] = ""
                                        else:
                                            if float(xticklabels[idx]
                                                     ).is_integer():
                                                xticklabels[idx] = int(
                                                    float(xticklabels[idx]))
                                    except ValueError:
                                        xticklabels[idx] = ""

                        # Use min/max labels
                        if colormap.legend.min_label != None:
                            xticklabels[0] = colormap.legend.min_label
                        if colormap.legend.max_label != None:
                            xticklabels[-1] = colormap.legend.max_label

                        # use int labels if all values are integers
#                         xticklabels = [int(float(label)) for label in xticklabels if float(label).is_integer()]
                        cb.ax.set_xticklabels(xticklabels)

                if colormap.units != None:
                    fig.text(0.5,
                             bottom - height - (0.20 / lc),
                             colormap.units,
                             fontsize=10,
                             horizontalalignment='center')

            if colormap.title != None:
                if lc == 1:
                    title_loc = 1 - t
                else:
                    title_loc = bottom + height + (0.07 / lc)
                if colormap.style == "classification":
                    fig.text(0.125,
                             title_loc,
                             colormap.title,
                             fontsize=10,
                             horizontalalignment='center',
                             weight='bold')
                else:
                    fig.text(0.5,
                             title_loc,
                             colormap.title,
                             fontsize=10,
                             horizontalalignment='center',
                             weight='bold')

        else:  # default vertical orientation
            left = ((1.00 / lc) * colormap_count) - (0.73 / lc)
            width = 0.15 / lc

            # use legend for classifications
            if colormap.style == "classification":
                if longlabels and fig.get_figwidth() < 3:
                    fig.set_figwidth(3.2)
                patches = []
                for color in legendcolors:
                    polygon = mpl.patches.Rectangle((0, 0),
                                                    10,
                                                    10,
                                                    facecolor=color)
                    polygon.set_linewidth(0.5)
                    patches.append(polygon)
                if len(legendcolors) < 7 and has_values == False:
                    if lc <= 2:
                        fig.set_figheight(1.5)
                if len(legendcolors) <= 14:
                    col = 1
                    fontsize = 9
                if len(legendcolors) > 14:
                    if lc <= 2:
                        fig.set_figwidth(3.2)
                    col = 2
                    fontsize = 8
                if len(legendcolors) > 28:
                    if lc <= 2:
                        fig.set_figwidth(4.2)
                    col = 3
                    fontsize = 7
                if has_values == True:
                    if lc <= 2:
                        fig.set_figwidth(3.2)
                    legend = fig.legend(
                        patches,
                        legendlabels,
                        bbox_to_anchor=[left - (0.15 / lc), 0.9],
                        loc='upper left',
                        ncol=1,
                        fancybox=True,
                        prop={'size': fontsize})
                    legend.get_frame().set_alpha(0)
                else:
                    legend = fig.legend(patches,
                                        legendlabels,
                                        bbox_to_anchor=[0.5, 0.5],
                                        loc='center',
                                        ncol=col,
                                        fancybox=True,
                                        prop={'size': fontsize})
                    legend.get_frame().set_alpha(0.5)

            if has_values == True and (colormap.style != "classification"
                                       or colormap.legend == None):
                ax = fig.add_axes([left, 0.1, width, 0.8])
                cmap = mpl.colors.ListedColormap(colors)

                if show_all == True:
                    if is_large_colormap == True:
                        norm = mpl.colors.Normalize(bounds[0],
                                                    bounds[len(bounds) - 1])
                        v = np.linspace(bounds[0],
                                        bounds[len(bounds) - 1],
                                        9,
                                        endpoint=True)
                        cb = mpl.colorbar.ColorbarBase(ax,
                                                       cmap=cmap,
                                                       norm=norm,
                                                       ticks=v,
                                                       orientation=orientation)
                    else:
                        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
                        cb = mpl.colorbar.ColorbarBase(ax,
                                                       cmap=cmap,
                                                       norm=norm,
                                                       orientation=orientation)
                        if center_ticks == True:
                            cb.set_ticks(ticks)
                            cb.ax.set_yticklabels(ticklabels)
                else:
                    if len(bounds) > 0:
                        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
                        cb = mpl.colorbar.ColorbarBase(ax,
                                                       cmap=cmap,
                                                       norm=norm,
                                                       ticks=ticks,
                                                       orientation=orientation)
                        cb.ax.set_yticklabels(ticks)
                    else:
                        norm = mpl.colors.BoundaryNorm(range(len(colors) + 1),
                                                       cmap.N)
                        cb = mpl.colorbar.ColorbarBase(ax,
                                                       cmap=cmap,
                                                       norm=norm,
                                                       ticks=ticks,
                                                       orientation=orientation)
                        cb.ax.set_yticklabels(ticklabels)

                cb.solids.set_edgecolor("face")

                for tick in cb.ax.yaxis.get_ticklabels():
                    tick.set_fontsize(10)

                if colormap.legend != None and len(bounds) > 0:
                    if len(cb.ax.get_yticklabels()) > 0:
                        yticklabels = cb.ax.get_yticklabels()
                        yticklabels = [
                            label.get_text() for label in yticklabels
                        ]
                        # Check for infinity
                        if lowerinf:
                            yticklabels[0] = "<=" + yticklabels[0]
                        if upperinf:
                            yticklabels[-1] = ">=" + yticklabels[-1]

                        # show only those with showLabel
                        for idx in range(0, len(yticklabels)):
                            if center_ticks == True:
                                if show_all == False:
                                    if float(yticklabels[idx]) - (
                                            increment / 2) not in ticklabels:
                                        yticklabels[idx] = ""
                                    else:
                                        yticklabels[idx] = str(
                                            float(yticklabels[idx]) -
                                            (increment / 2))
                                        if float(
                                                yticklabels[idx]).is_integer():
                                            yticklabels[idx] = int(
                                                float(yticklabels[idx]))
                                else:
                                    if float(yticklabels[idx]
                                             ) not in ticklabels:
                                        yticklabels[idx] = ""
                            else:
                                if show_all == False:
                                    try:
                                        if float(yticklabels[idx]
                                                 ) not in ticklabels:
                                            yticklabels[idx] = ""
                                        else:
                                            if float(yticklabels[idx]
                                                     ).is_integer():
                                                yticklabels[idx] = int(
                                                    float(yticklabels[idx]))
#                                           yticklabels[idx] = "%.2f" % float(yticklabels[idx])
                                    except ValueError:
                                        yticklabels[idx] = ""

                        # Use min/max labels
                        if colormap.legend.min_label != None:
                            yticklabels[0] = colormap.legend.min_label
                        if colormap.legend.max_label != None:
                            yticklabels[-1] = colormap.legend.max_label

                        # use int labels if all values are integers
#                         yticklabels = [int(float(label)) for label in yticklabels if float(label).is_integer()]
                        cb.ax.set_yticklabels(yticklabels)

                if colormap.units != None:
                    fig.text(left + (0.08 / lc),
                             0.01,
                             colormap.units,
                             fontsize=10,
                             horizontalalignment='center')

            if colormap.title != None:
                title_left = left + (0.08 / lc)
                title_top = 0.935
                if colormap.style == "classification":
                    if lc == 1:
                        title_left = 0.5  #center if only one classification legend
                        title_top = 1 - t
                fs = 10
                if len(colormap.title) > 10:
                    fs = 9
                if len(colormap.title) > 14:
                    fs = 8
                if len(colormap.title) > 16:
                    title_words = colormap.title.split(" ")
                    half = (len(title_words) / 2)
                    if len(title_words) > 2: half += 1
                    title = ""
                    for word in title_words[0:half]:
                        title = title + word + " "
                    title = title + "\n"
                    for word in title_words[half:len(title_words)]:
                        title = title + word + " "
                    colormap.title = title
                fig.text(title_left,
                         title_top,
                         colormap.title,
                         fontsize=fs,
                         horizontalalignment='center',
                         weight='bold')

    fig.savefig(output, transparent=True, format=output_format)

    # Add tooltips to SVG
    if output_format == 'svg' and has_values == True:

        ax = fig.get_axes()[0]  # only supports one axis
        entries = colormaps[0].legend.legend_entries

        for i, entry in enumerate(entries):
            text = entry.value
            if orientation == "horizontal":
                position = (float(i) / float(len(entries)), 1)
            else:
                position = (1, float(i) / float(len(entries)))
            ax.annotate(
                text,
                xy=position,
                textcoords='offset points',
                color='black',
                ha='center',
                fontsize=10,
                gid='tooltip',
                bbox=dict(boxstyle='round,pad=.3',
                          fc=(1, 1, .9, 1),
                          ec=(.1, .1, .1),
                          lw=1,
                          zorder=1),
            )

        # Set id for the annotations
        for i, t in enumerate(ax.texts):
            t.set_gid('tooltip_%d' % i)

        # Save the figure
        f = StringIO()
        plt.savefig(f, transparent=True, format="svg")

        # Create XML tree from the SVG file
        tree, xmlid = ET.XMLID(f.getvalue())
        tree.set('onload', 'init(evt)')

        # Hide the tooltips
        for i, t in enumerate(ax.texts):
            try:
                el = xmlid['tooltip_%d' % i]
                el.set('visibility', 'hidden')
            except KeyError:
                None

        # Add mouseover events to color bar
        el = xmlid['QuadMesh_1']
        elements = list(el)
        elements.pop(0)  # remove definitions
        for i, t in enumerate(elements):
            el = elements[i]
            el.set('onmouseover', "ShowTooltip(" + str(i) + ")")
            el.set('onmouseout', "HideTooltip(" + str(i) + ")")

        # This is the script defining the ShowTooltip and HideTooltip functions.
        script = """
            <script type="text/ecmascript">
            <![CDATA[
            
            function init(evt) {
                if ( window.svgDocument == null ) {
                    svgDocument = evt.target.ownerDocument;
                    }
                }
                
            function ShowTooltip(idx) {
                var tip = svgDocument.getElementById('tooltip_'+idx);
                tip.setAttribute('visibility',"visible")
                }
                
            function HideTooltip(idx) {
                var tip = svgDocument.getElementById('tooltip_'+idx);
                tip.setAttribute('visibility',"hidden")
                }
                
            ]]>
            </script>
            """

        # Insert the script at the top of the file and save it.
        tree.insert(0, ET.XML(script))
        ET.ElementTree(tree).write(output)
        print "SVG tooltips added"

    print output + " generated successfully"
示例#10
0
def significance_drop(outfile, old, new, show_channel_names=None, **kwargs):
    """Plot the signifiance drop for each channel
    """
    channels = sorted(old.keys())
    if show_channel_names is None:
        show_channel_names = len(channels) <= 50

    plot = Plot(figsize=(18, 6))
    plot.subplots_adjust(left=.07, right=.93)
    ax = plot.gca()
    if show_channel_names:
        plot.subplots_adjust(bottom=.4)

    winner = sorted(old.items(), key=lambda x: x[1])[-1][0]

    for i, c in enumerate(channels):
        if c == winner:
            color = 'orange'
        elif old[c] > new[c]:
            color = 'dodgerblue'
        else:
            color = 'red'
        ax.plot([i, i], [old[c], new[c]], color=color, linestyle='-',
                marker='o', markersize=10, label=c, zorder=old[c])

    ax.set_xlim(-1, len(channels))
    ax.set_ybound(lower=0)

    # set xticks to show channel names
    if show_channel_names:
        ax.set_xticks(range(len(channels)))
        ax.set_xticklabels([c.replace('_','\_') for c in channels])
        for i, t in enumerate(ax.get_xticklabels()):
            t.set_rotation(270)
            t.set_verticalalignment('top')
            t.set_horizontalalignment('center')
            t.set_fontsize(8)
    # or just show systems of channels
    else:
        plot.canvas.draw()
        systems = {}
        for i, c in enumerate(channels):
            sys = c.split(':', 1)[1].split('-')[0].split('_')[0]
            try:
                systems[sys][1] += 1
            except KeyError:
                systems[sys] = [i, 1]
        systems = sorted(systems.items(), key=lambda x: x[1][0])
        labels, counts = zip(*systems)
        xticks, xmticks = zip(*[(a, a+b/2.) for (a, b) in counts])
        # show ticks at the edge of each group
        ax.set_xticks(xticks, minor=False)
        ax.set_xticklabels([], minor=False)
        # show label in the centre of each group
        ax.set_xticks(xmticks, minor=True)
        for t in ax.set_xticklabels(labels, minor=True):
            t.set_rotation(270)

    kwargs.setdefault('ylabel', 'Significance')

    # create interactivity
    if outfile.endswith('.svg'):
        _finalize_plot(plot, ax, outfile.replace('.svg', '.png'),
                       close=False, **kwargs)
        tooltips = []
        ylim = ax.get_ylim()
        yoffset = (ylim[1] - ylim[0]) * 0.061
        bbox = {'fc': 'w', 'ec': '.5', 'alpha': .9, 'boxstyle': 'round'}
        xthresh = len(channels) / 10.
        for i, l in enumerate(ax.lines):
            x = l.get_xdata()[1]
            if x < xthresh:
                ha = 'left'
            elif x > (len(channels) - xthresh):
                ha ='right'
            else:
                ha = 'center'
            y = l.get_ydata()[0] + yoffset
            c = l.get_label()
            tooltips.append(ax.annotate(c.replace('_', r'\_'), (x, y),
                                        ha=ha, zorder=ylim[1], bbox=bbox))
            l.set_gid('line-%d' % i)
            tooltips[-1].set_gid('tooltip-%d' % i)

        f = BytesIO()
        plot.savefig(f, format='svg')
        tree, xmlid = etree.XMLID(f.getvalue())
        tree.set('onload', 'init(evt)')
        for i in range(len(tooltips)):
            try:
                e = xmlid['tooltip-%d' % i]
            except KeyError:
                warnings.warn("Failed to recover tooltip %d" % i)
                continue
            e.set('visibility', 'hidden')
        for i, l in enumerate(ax.lines):
            e = xmlid['line-%d' % i]
            e.set('onmouseover', 'ShowTooltip(this)')
            e.set('onmouseout', 'HideTooltip(this)')
        tree.insert(0, etree.XML(SHOW_HIDE_JAVASCRIPT))
        etree.ElementTree(tree).write(outfile)
        plot.close()
    else:
        _finalize_plot(plot, ax, outfile, **kwargs)
示例#11
0
    if len(header_envelope) > 0 and len(header_envelope[0]) > 0:
        header = header_envelope[0].getchildren()[0]

    body=None
    if len(body_envelope) > 0 and len(body_envelope[0]) > 0:
        body = body_envelope[0].getchildren()[0]

    return header, body

def _parse_xml_string(xml_string, charset=None):
     xml_string = xml_string.replace('<?xml version="1.0" encoding="utf-8"?>', "")
    try:
        if charset is None: # hack
            raise ValueError(charset)

        root, xmlids = etree.XMLID(xml_string.decode(charset))

    except ValueError,e:
        logger.debug('%s -- falling back to str decoding.' % (e))
        root, xmlids = etree.XMLID(xml_string)

    return root, xmlids

# see http://www.w3.org/TR/2000/NOTE-SOAP-20000508/
# section 5.2.1 for an example of how the id and href attributes are used.
def resolve_hrefs(element, xmlids):
    for e in element:
        if e.get('id'):
            continue # don't need to resolve this element

        elif e.get('href'):
示例#12
0
文件: mixins.py 项目: pvasired/gwsumm
    def process_svg(self, outputfile):
        # render image
        super(SvgMixin, self).finalize(outputfile=StringIO(), close=False)
        ax = self.plot.axes[0]
        collections = [c for c in ax.collections if hasattr(c, '_ignore')]
        # reset labels
        labels = {}
        for i, t in enumerate(ax.get_yaxis().get_ticklabels()):
            text = t.get_text()
            if not text:
                continue
            x, y = t.get_position()
            m1 = re_bit_label.match(text)
            m2 = re_source_label.match(text)
            if m1:
                idx, label = m1.groups()
                t2 = ax.text(0.01,
                             y,
                             label,
                             ha='left',
                             fontsize=t.get_fontsize(),
                             va='center',
                             transform=t.get_transform())
                t2.set_bbox({
                    'alpha': 0.5,
                    'facecolor': 'white',
                    'edgecolor': 'none'
                })
                t.set_text(idx)
                t.set_bbox(None)
                t.set_position((0, y))
                t.set_ha('right')
                t.set_fontsize('14')
                labels[text] = (idx, t2)
            elif m2:
                label, flag = m2.groups()
                t2 = ax.text(x,
                             y,
                             text,
                             ha='left',
                             bbox=t._bbox.copy(),
                             fontsize=t.get_fontsize(),
                             va='center',
                             transform=t.get_transform())
                t.set_text(label)
                labels[text] = (label, t2)
        ax._insetlabels = None

        j = 0
        for i, collection in enumerate(collections):
            try:
                idx, tickl = labels[collection.get_label()]
            except KeyError:
                continue
            else:
                labels[collection] = tickl
            collection.set_label(idx)
            if not tickl.get_gid():
                tickl.set_gid('label_%d' % j)
                j += 1
            collection.set_gid('collection_%d_%s' % (i, tickl.get_gid()))

        # render as and parse SVG
        f = StringIO()
        self.plot.save(f, format='svg')
        tree, xmlid = etree.XMLID(f.getvalue())
        tree.set('onload', 'init(evt)')
        # set mouse events for visible labels
        for i, collection in enumerate(collections):
            try:
                tickl = labels[collection]
            except KeyError:
                continue
            cel = xmlid[collection.get_gid()]
            cel.set('cursor', 'pointer')
            cel.set('onmouseover', "ShowLabel(this)")
            cel.set('onmouseout', "HideLabel(this)")
            tel = xmlid[tickl.get_gid()]
            tel.set('class', 'mpl-label')
            if not self.preview_labels:
                tel.set('visibility', 'hidden')

        # ignore hover on text events
        for key in xmlid:
            if key.startswith('text_') or key.startswith('label_'):
                xmlid[key].set('style', 'pointer-events: none;')

        #self.plot.save(outputfile.replace('.svg', '.png'))
        return self.finalize_svg(tree, outputfile, script=HOVERSCRIPT)
示例#13
0
文件: mixins.py 项目: pvasired/gwsumm
    def process_svg(self, outputfile):
        for ax in self.plot.axes:
            for line in ax.lines:
                line.set_rasterized(True)

        # render image
        super(SvgMixin,
              self).finalize(outputfile=outputfile.replace('.svg', '.png'),
                             close=False)

        # make new text labels for the channel names
        ax = self.plot.axes[0]
        leg = ax.legend_
        texts = []
        if leg is not None:
            for i, (text,
                    line) in enumerate(zip(leg.get_texts(), leg.get_lines())):
                try:
                    label, source = re_source_label.match(
                        text.get_text()).groups()
                except (AttributeError, ValueError):
                    continue
                channel = label_to_latex(str(source))
                text.set_text(label)
                t2 = ax.text(0.994,
                             1.02,
                             channel,
                             ha='right',
                             va='bottom',
                             fontsize=text.get_fontsize(),
                             zorder=1000,
                             transform=ax.transAxes,
                             bbox={
                                 'facecolor': 'white',
                                 'edgecolor': 'lightgray',
                                 'pad': 10.
                             })
                text.set_gid('leg_text_%d' % i)
                line.set_gid('leg_patch_%d' % i)
                t2.set_gid('label_%d' % i)
                texts.append(t2)

        # tmp save
        f = StringIO()
        self.plot.save(f, format='svg')

        # parse svg
        tree, xmlid = etree.XMLID(f.getvalue())
        tree.set('onload', 'init(evt)')

        # add effects
        for i in range(len(texts)):
            pl = xmlid['leg_patch_%d' % i]
            ll = xmlid['leg_text_%d' % i]
            tl = xmlid['label_%d' % i]
            pl.set('cursor', 'pointer')
            pl.set('onmouseover', "ShowLabel(this)")
            pl.set('onmouseout', "HideLabel(this)")
            ll.set('cursor', 'pointer')
            ll.set('onmouseover', "ShowLabel(this)")
            ll.set('onmouseout', "HideLabel(this)")
            tl.set('class', 'mpl-label')
            tl.set('visibility', 'hidden')

        return self.finalize_svg(tree, outputfile, script=HOVERSCRIPT)