Esempio n. 1
0
def createisomap(iso, mapscale, name, name_en):

    map_width = int(mapscale[0])
    map_height = int(mapscale[1])

    map_minx = float(mapscale[2])
    map_maxx = float(mapscale[3])
    map_miny = float(mapscale[4])
    map_maxy = float(mapscale[5])

    print("mapdata:", map_width, map_height, map_maxx, map_maxy, map_minx,
          map_miny)

    geojsonfile = '/osm/service/' + CONTINENT + '/' + iso + '/poly/osm.geojson'

    m = mapnik.Map(
        map_width,
        map_height)  # create a map with a given width and height in pixels
    # note: m.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    # the 'map.srs' is the target projection of the map and can be whatever you wish
    m.background = mapnik.Color(
        '#000000')  # set background colour to 'steelblue'.

    s = mapnik.Style()  # style object to hold rules
    r = mapnik.Rule()  # rule object to hold symbolizers
    # to fill a polygon we create a PolygonSymbolizer

    psymbolizer = mapnik.PolygonSymbolizer()
    #psymbolizer.fill = mapnik.Color('#f2eff9')
    psymbolizer.fill = mapnik.Color('#000000')
    r.symbols.append(psymbolizer)

    lsymbolizer = mapnik.LineSymbolizer()
    #lsymbolizer.stroke = mapnik.Color('rgb(50%,50%,50%)')
    lsymbolizer.stroke = mapnik.Color('#FFA500')
    lsymbolizer.stroke_width = 0.8
    r.symbols.append(lsymbolizer)

    s.rules.append(r)  # now add the rule to the style and we're done

    m.append_style(
        'My Style',
        s)  # Styles are given names only as they are applied to the map

    ds = mapnik.Ogr(file=geojsonfile, layer_by_index=0)
    print(ds)

    ds.envelope()

    layer = mapnik.Layer(
        'world')  # new layer called 'world' (we could name it anything)
    # note: layer.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'

    layer.datasource = ds
    layer.styles.append('My Style')

    m.layers.append(layer)

    bbox = mapnik.Box2d(map_maxx, map_maxy, map_minx, map_miny)
    m.zoom_to_box(bbox)

    # Write the data to a png image called world.png the current directory

    img_directory = '/osm/service/' + CONTINENT + '/' + iso + '/img/'
    if not os.path.exists(img_directory):
        os.makedirs(img_directory)

    os.system("rm -f " + img_directory + "*")

    mapnik.render_to_file(m, img_directory + 'dbackground0.png', 'png')

    gdalw1 = 'gdalwarp    -te {} {} {} {}  -ts {} {} '.format(
        map_minx, map_miny, map_maxx, map_maxy, map_width, map_height)
    # NE1_HR_LC_SR_W_DR.tif
    gdalw2 = ' -of GTiff   /osm/ne/ne.tif {}  '.format(img_directory +
                                                       'nebackground.geotif')

    print("gdalw:", gdalw1, gdalw2)

    os.system(gdalw1 + gdalw2)

    os.system('gdal_translate -of PNG  {} {} '.format(
        img_directory + 'nebackground.geotif',
        img_directory + 'nebackground.png'))

    os.system('convert   {} -transparent Black {} '.format(
        img_directory + 'dbackground0.png',
        img_directory + 'tdbackground.png'))
    os.system('composite {} -compose over   {} {} '.format(
        img_directory + 'tdbackground.png', img_directory + 'nebackground.png',
        img_directory + 'dbackground.png'))

    ######################  flag ##################################

    im_cmd1 = r'convert /osm/setup/osmlogo.png -font DejaVu-Serif -fill darkblue  -pointsize 34 -gravity center -draw "text 16,-18'
    im_cmd2 = r" '." + iso[:2] + "' "
    im_cmd3 = r'"  ' + img_directory + 'dflag.png'

    os.system(im_cmd1 + im_cmd2 + im_cmd3)

    ####################  Logo #####################################

    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 448, 98)
    ctx = cairo.Context(surface)
    ctx.select_font_face("Courier", cairo.FONT_SLANT_NORMAL,
                         cairo.FONT_WEIGHT_BOLD)

    ctx.set_font_size(42)
    ctx.move_to(2, 50)
    ctx.set_source_rgb(0.0, 0.0, 0.15)
    ctx.show_text('Taginfo-' + CONTINENT + '-' + iso)

    ctx.select_font_face('Sans')
    if len(name_en) > 26:
        ctx.set_font_size(20)
    elif len(name_en) > 18:
        ctx.set_font_size(26)
    else:
        ctx.set_font_size(30)

    ctx.move_to(1, 90)
    ctx.set_source_rgb(0.0, 0.0, 0.35)
    ctx.show_text(name_en)

    # finish up
    ctx.stroke()
    surface.write_to_png(img_directory + 'dlogo.png')
Esempio n. 2
0
         ds.variables['longitude'][:]), ds.variables['u10'][t0:tn])
v = rgi((ds.variables['time'][t0:tn], ds.variables['latitude'][:],
         ds.variables['longitude'][:]), ds.variables['v10'][t0:tn])
temp = rgi((ds.variables['time'][t0:tn], ds.variables['latitude'][:],
            ds.variables['longitude'][:]), ds.variables['t2m'][t0:tn])
ds.close()

print("Interpolating data finished; plotting countries.")

# Get countries from shapefile.
sf = shapefile.Reader("lib/countries.shp")
countries = sf.shapes()

# Plot countries.
overlay = cairo.ImageSurface(cairo.FORMAT_ARGB32, outx, outy)
ctx2 = cairo.Context(overlay)
ctx2.set_line_width(3)
ctx2.set_line_join(cairo.LINE_JOIN_BEVEL)
bbox = [-15, 43, 13, 57.5]
for c in countries:
    ctx2.move_to((c.points[0][0] - bbox[0]) * ar * 60 * 10,
                 -(c.points[0][1]) * 60)
    for i, p in enumerate(c.points):
        if i in c.parts:
            ctx2.move_to((p[0] - bbox[0]) * 60 * 4 * ar,
                         -(p[1] - bbox[3]) * 60 * 4)
        else:
            ctx2.line_to((p[0] - bbox[0]) * 60 * 4 * ar,
                         -(p[1] - bbox[3]) * 60 * 4)
    ctx2.set_operator(cairo.Operator.SOURCE)
    ctx2.set_source_rgba(1, 1, 1, 0.5)
Esempio n. 3
0
def white_borders(model, selection, pdfqueue):
    crop = []
    for path in selection:
        it = model.get_iter(path)
        p = model.get_value(it, 0)
        pdfdoc = pdfqueue[p.nfile - 1]

        page = pdfdoc.document.get_page(p.npage - 1)
        # Always render pages at 72 dpi whatever the zoom or scale of the page
        w, h = page.get_size()
        # FIXME: No longer ignore p.crop so we could do nested white border crop
        w = int(w)
        h = int(h)
        thumbnail = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
        cr = cairo.Context(thumbnail)
        page.render(cr)
        # TODO: python list are dead slow compared to memoryview. It would
        # be faster to create a memoryview full of 0 and then compare each row
        # to it. memoryview have full native __eq__ operator which is fast.
        data = thumbnail.get_data().cast("i", shape=[h, w]).tolist()

        crop_this_page = [0.0, 0.0, 0.0, 0.0]
        # TODO: Those 4 copy/past should be factorized
        # Left
        allwhite = True
        for col in range(w - 1):
            for row in range(h - 1):
                if data[row][col] != 0:
                    allwhite = False
                    crop_this_page[0] = (col) / w
                    break
            if not allwhite:
                break

        # Right
        allwhite = True
        for col in range(w - 1, 0, -1):
            for row in range(h - 1):
                if data[row][col] != 0:
                    allwhite = False
                    crop_this_page[1] = (w - col) / w
                    break
            if not allwhite:
                break

        # Top
        allwhite = True
        for row in range(h - 1):
            for col in range(w - 1):
                if data[row][col] != 0:
                    allwhite = False
                    crop_this_page[2] = (row) / h
                    break
            if not allwhite:
                break

        # Bottom
        allwhite = True
        for row in range(h - 1, 0, -1):
            for col in range(w - 1):
                if data[row][col] != 0:
                    allwhite = False
                    crop_this_page[3] = (h - row) / h
                    break
            if not allwhite:
                break

        crop.append(p.rotate_crop(crop_this_page, p.rotate_times(p.angle)))
    return crop
Esempio n. 4
0
    for v in range(V):
        top_branch[v] = max(vy[v], vy[spouses[v]]) + 1/(My-my)
    for v in range(V):
        low_branch[v] = min([vy[di[c]] for c in getChildren(v)]) - 5/(My-my)

    # Node colors
    colors = {-1:np.array([0,0,0])}
    for v in range(V):
        if parents[i[v]] == 0:
            colors[i[v]] = rs.random_sample(3)
        else:
            pa = di[df.loc[i[v], "Father"]]
            ma = di[df.loc[i[v], "Mother"]]
            colors[i[v]] = (colors[pa]+colors[ma])/2

    cr = cairo.Context(surface)

    cr.scale(WIDTH, HEIGHT)  # Normalizing the canvas

    for v in range(V):
        # if node has children, draw tree paths
        if children[v] > 0:
            # Draw joining line
            cr.set_source_rgb(*((colors[v]+colors[spouses[v]])/2))
            cr.move_to(vx[v], vy[v])
            cr.set_line_width(0.001)
            cr.line_to(vx[v], top_branch[v])
            cr.stroke()
            cr.move_to(vx[v], top_branch[v])
            cr.line_to((vx[v]+vx[spouses[v]])/2, top_branch[v])
            cr.stroke()
Esempio n. 5
0
    def renderTo(self, fileName):
        xAttribs = self.xAttribs
        yAttribs = self.yAttribs
        xAttribs.setMinMax(self.xMin, self.xMax)

        # Create the image surface and cairo context
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                     330 + int(xAttribs.size + 0.5),
                                     55 + int(yAttribs.size + 0.5))
        cr = cairo.Context(surface)
        cr.set_source_rgb(1, 1, 1)
        cr.paint()
        cr.set_miter_limit(1.414)
        cr.translate(80, 8 + yAttribs.size)

        # Draw axes
        labelFont = createScaledFont('Arial', 13)
        with Saved(cr):
            cr.set_line_width(1)
            cr.set_source_rgb(.4, .4, .4)

            # Horizontal axis
            cr.move_to(0, -0.5)
            cr.rel_line_to(xAttribs.size + 1, 0)
            cr.stroke()
            for pos, label in xAttribs.iterLabels():  # Labels
                x = math.floor(pos + 0.5)
                with Saved(cr):
                    cr.translate(x, 9)
                    fillAlignedText(cr, 0, 6, labelFont, label, 0.5)

            # Vertical axis
            cr.set_source_rgb(*colorTuple('f0f0f0'))
            for pos, label in yAttribs.iterLabels():  # Background lines
                if label == '0':
                    continue
                y = -math.floor(pos + 0.5) - 0.5
                cr.move_to(1, y)
                cr.rel_line_to(xAttribs.size + 1, 0)
            cr.stroke()
            cr.set_source_rgb(.4, .4, .4)
            cr.move_to(0.5, 0)
            cr.rel_line_to(0, -yAttribs.size - 0.5)
            if False:
                for pos, label in yAttribs.iterLabels():  # Tick marks
                    if label == '0':
                        continue
                    y = -math.floor(pos + 0.5) - 0.5
                    cr.move_to(1, y)
                    cr.rel_line_to(-4, 0)
            cr.stroke()
            for pos, label in yAttribs.iterLabels():  # Labels
                if label == '0':
                    continue
                fillAlignedText(cr, -4, -pos + 4, labelFont, label, 1)
        """
        with Saved(cr):
            x = xAttribs.size - 70.5 + 80
            y = -234.5
            cr.rectangle(x, y, 120, 82)
            cr.set_source_rgb(*colorTuple('ffffff'))                
            cr.fill()
            cr.set_source_rgb(*colorTuple('f0f0f0'))                
            cr.rectangle(x, y, 120, 82)
            cr.set_line_width(1)
            cr.stroke()
        """

        # Draw curves
        for cn, curve in enumerate(self.curves):
            points = curve.points
            color = curve.color
            width = 1.75
            #if color == colorTuple('ff4040'):
            #width = 2
            with Saved(cr):
                cr.set_line_width(width)
                cr.set_source_rgba(*color)
                #if color == colorTuple('9090b0'):
                #    cr.set_dash([9, 2])
                with Saved(cr):
                    cr.rectangle(0, 5, xAttribs.size, -yAttribs.size - 15)
                    cr.clip()
                    x, y = points[0]
                    cr.move_to(xAttribs.mapAxisValue(x),
                               -yAttribs.mapAxisValue(y))
                    for x, y in points[1:]:
                        cr.line_to(
                            xAttribs.mapAxisValue(x) + 0.5,
                            -yAttribs.mapAxisValue(y) - 0.5)
                    cr.stroke()
                for x, y in points:
                    cr.rectangle(
                        xAttribs.mapAxisValue(x) - 2.5,
                        -yAttribs.mapAxisValue(y) - 2.5, 5, 5)
                cr.fill()

                x = xAttribs.size + 40
                y = -120 + (5 - cn) * 14
                cr.move_to(x - 4.5, y - 4.5)
                cr.rel_line_to(-21, 0)
                cr.stroke()

                # Label
                weight = cairo.FONT_WEIGHT_NORMAL
                if color == colorTuple('ff4040'):
                    weight = cairo.FONT_WEIGHT_BOLD
                labelFont = createScaledFont('Arial', 13, weight=weight)
                label = curve.name
                #x, y = points[-1]
                #fillAlignedText(cr, xAttribs.mapAxisValue(x) + 3, -yAttribs.mapAxisValue(y) + 4, labelFont, label, 0)
                x = xAttribs.size + 40
                y = -120 + (5 - cn) * 14
                fillAlignedText(cr, x, y, labelFont, label, 0)

        # Draw axis names
        cr.set_source_rgb(0, 0, 0)
        axisFont = createScaledFont('Helvetica',
                                    16,
                                    weight=cairo.FONT_WEIGHT_BOLD)
        with Saved(cr):
            cr.translate(-66, -yAttribs.size / 2.0)
            cr.rotate(-math.pi / 2)
            fillAlignedText(cr, 0, 0, axisFont, 'Map Operations / Sec', 0.5)
        with Saved(cr):
            axisFont2 = createScaledFont('Helvetica', 13)
            cr.translate(-50, -yAttribs.size / 2.0)
            cr.rotate(-math.pi / 2)
            cr.set_source_rgba(*colorTuple('808080'))
            fillAlignedText(cr, 0, 0, axisFont2, '(Total Across All Threads)',
                            0.5)
        fillAlignedText(cr, xAttribs.size / 2.0, 42, axisFont, 'Threads', 0.5)

        # Save PNG file
        surface.write_to_png(fileName)
Esempio n. 6
0
import cairo

surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 300, 200)
ctx = cairo.Context(surface)

ctx.rectangle(25, 50, 50, 120)
ctx.set_source_rgb(1, 0, 0)
ctx.fill()

surface.write_to_png('rectangle.png')
Esempio n. 7
0
def render(opts, trace):
    if opts.verbose:
        print '[II] Identifying relevant tasks and CPUs...',
        sys.stdout.flush()
    tasks, cores = trace.active_in_interval(opts.start, opts.end)
    if opts.verbose:
        print '%d tasks, %d cores.' % (len(tasks), len(cores))

    # scale is given in points/ms, we need points/ns
    xscale = opts.xscale/1E6
    yscale = opts.yscale/YRES
    width  = ceil(opts.margin * 2 + (opts.end - opts.start) * xscale + YLABEL_MARGIN)

    height = ceil(opts.margin * 2 + (len(tasks) * YRES)  * yscale + XLABEL_MARGIN)

    if opts.verbose:
        print '[II] Canvas size: %dpt x %dpt' % (width, height)

    pdf = cairo.PDFSurface(opts.output, width, height)

    task_idx = {}
    for i, t in enumerate(sorted(tasks)):
        task_idx[t] = i


    c = cairo.Context(pdf)
    c.translate(opts.margin + YLABEL_MARGIN, opts.margin)

    # draw box
#     c.rectangle(0, 0, width - opts.margin * 2, height - opts.margin * 2)
#     c.stroke()

    def xpos(x):
        return (x - opts.start) * xscale

    def ypos(y):
        return (y * YRES) * yscale

#    c.scale(xscale, yscale)

    if opts.verbose:
        print '[II] Drawing grid...',
        sys.stdout.flush()

    # draw minor tick lines
    if opts.minor_ticks:
        c.set_source_rgb(*MINOR_TICK_COLOR)
        c.set_line_width(MINOR_TICK_WIDTH)
        time = opts.start
        while time <= opts.end:
            x = xpos(time)
            y = ypos(len(tasks))
            c.new_path()
            c.move_to(x, y)
            c.line_to(x, 0)
            c.stroke()
            time += opts.minor_ticks * 1E6


    # draw major tick lines
    if opts.major_ticks:
        c.set_source_rgb(*MAJOR_TICK_COLOR)
        c.set_line_width(MAJOR_TICK_WIDTH)
        c.set_font_size(MAJOR_TICK_FONT_SIZE)
        time = opts.start
        while time <= opts.end:
            x = xpos(time)
            y = ypos(len(tasks) + 0.2)
            c.new_path()
            c.move_to(x, y)
            c.line_to(x, 0)
            c.stroke()
            y = ypos(len(tasks) + 0.3)
            center_text(c, x, y, "%dms" % ((time - opts.start) / 1E6))
            time += opts.major_ticks * 1E6

    # draw task labels
    c.set_font_size(TASK_LABEL_FONT_SIZE)
    c.set_source_rgb(*TASK_LABEL_COLOR)
    for pid in tasks:
        x = -24
        y = ypos(task_idx[pid] + 0.25)
        vcenter_right_align_text(c, x, y, "%s/%d" % (trace.task_names[pid], pid))
        y = ypos(task_idx[pid] + 0.75)
        vcenter_right_align_text(c, x, y,
            "(%.2fms, %.2fms)" % (trace.task_wcets[pid] / 1E6,
                                  trace.task_periods[pid] / 1E6))

    if opts.verbose:
        print 'done.'
        print '[II] Drawing CPU allocations...',
        sys.stdout.flush()


    # raw allocations
    box_height = ALLOC_HEIGHT * YRES * yscale
    c.set_font_size(TAG_FONT_SIZE)
    for (to, away) in trace.scheduling_intervals_in_range(opts.start, opts.end):
        delta = (event_time(away) - event_time(to)) * xscale
        pid = event_pid(to)
        y = ypos(task_idx[pid] + (1 - ALLOC_HEIGHT))
        x = xpos(event_time(to))
        c.new_path()
        c.rectangle(x, y, delta, box_height)
        c.set_source_rgb(*cpu_color(event_cpu(to)))
        c.fill()

        c.set_source_rgb(*TAG_COLOR)
        text_left_align_below(c, x + 2, y + 2, '%d' % event_cpu(to))

    # draw task base lines
    c.set_source_rgb(*GRID_COLOR)
    c.set_line_width(GRID_WIDTH)
    for t in tasks:
        c.new_path()
        y = ypos(task_idx[t] + 1)
        x = xpos(opts.start)
        c.move_to(x, y)
        x = xpos(opts.end)
        c.line_to(x, y)
        c.stroke()

    if opts.verbose:
        print 'done.'
        print '[II] Drawing releases and deadlines...',
        sys.stdout.flush()

    # draw releases and deadlines
    c.set_source_rgb(*JOB_EVENT_COLOR)
    c.set_line_width(ARROW_LINE_WIDTH)
#    c.set_line_cap(cairo.LINE_JOIN_ROUND)
    c.set_line_join(cairo.LINE_JOIN_ROUND)
    c.set_font_size(JOB_ID_FONT_SIZE)
    arrow_width  = ARROW_WIDTH / 2
    arrow_height = ARROW_HEIGHT * YRES * yscale
    for rec in trace.events_in_range_of_type(opts.start, opts.end, 'ST_RELEASE'):
        pid = event_pid(rec)
        y   = ypos(task_idx[pid] + 1)

        rel = xpos(event_time(rec))
        c.new_path()
        c.move_to(rel, y - (GRID_WIDTH - 1))
        c.rel_line_to(0, -arrow_height)
        c.rel_line_to(-arrow_width, arrow_width)
        c.rel_move_to(arrow_width, -arrow_width)
        c.rel_line_to(arrow_width, arrow_width)
        c.stroke()

        if opts.show_job_ids:
            text_left_align_above(c, rel + 4, y - arrow_height - 4,
                            "%d" % event_job_id(rec))

        dl  = xpos(rec[-1])
        c.new_path()
        c.move_to(dl, y - arrow_height - (GRID_WIDTH - 1))
        c.rel_line_to(0, arrow_height)
        c.rel_line_to(-arrow_width, -arrow_width)
        c.rel_move_to(arrow_width, arrow_width)
        c.rel_line_to(arrow_width, -arrow_width)
        c.stroke()


    if opts.verbose:
        print 'done.'
        print '[II] Drawing job completions...',
        sys.stdout.flush()

    # draw job completions
    for rec in trace.events_in_range_of_type(opts.start, opts.end, 'ST_COMPLETION'):
        pid = event_pid(rec)
        y   = ypos(task_idx[pid] + 1)
        x   = xpos(event_time(rec))
        c.new_path()
        c.move_to(x, y - (GRID_WIDTH - 1))
        c.rel_line_to(0, -arrow_height)
        c.rel_move_to(-arrow_width, 0)
        c.rel_line_to(2 * arrow_width, 0)
        c.stroke()

        if opts.show_job_ids:
            text_left_align_above(c, x + 4, y - arrow_height - 4,
                            "%d" % event_job_id(rec))

    if opts.verbose:
        print 'done.'
        print '[II] Drawing job suspensions...',
        sys.stdout.flush()

    # draw job suspensions
    c.set_line_width(1)
    for rec in trace.events_in_range_of_type(opts.start, opts.end, 'ST_BLOCK'):
        pid = event_pid(rec)
        y  = ypos(task_idx[pid] + (1 - ALLOC_HEIGHT) + 0.5 * ALLOC_HEIGHT)
        y1 = ypos(task_idx[pid] + (1 - ALLOC_HEIGHT) + 0.4 * ALLOC_HEIGHT)
        y2 = ypos(task_idx[pid] + (1 - ALLOC_HEIGHT) + 0.6 * ALLOC_HEIGHT)
        x   = xpos(event_time(rec))
        c.new_path()
        c.move_to(x, y1)
        c.line_to(x, y2)
        c.line_to(x - arrow_width, y)
        c.line_to(x, y1)
        c.close_path()
        c.stroke()


    if opts.verbose:
        print 'done.'
        print '[II] Drawing job wake-ups...',
        sys.stdout.flush()

    # draw job suspensions
    c.set_line_width(1)
    for rec in trace.events_in_range_of_type(opts.start, opts.end, 'ST_RESUME'):
        pid = event_pid(rec)
        y  = ypos(task_idx[pid] + (1 - ALLOC_HEIGHT) + 0.5 * ALLOC_HEIGHT)
        y1 = ypos(task_idx[pid] + (1 - ALLOC_HEIGHT) + 0.4 * ALLOC_HEIGHT)
        y2 = ypos(task_idx[pid] + (1 - ALLOC_HEIGHT) + 0.6 * ALLOC_HEIGHT)
        x   = xpos(event_time(rec))
        c.new_path()
        c.move_to(x, y1)
        c.line_to(x, y2)
        c.line_to(x + arrow_width, y)
        c.line_to(x, y1)
        c.close_path()
        c.stroke()

    if opts.verbose:
        print 'done.'
        print '[II] Finishing PDF...',
        sys.stdout.flush()

    pdf.finish()

    if opts.verbose:
        print 'done.'

    if opts.verbose:
        print '[II] Flushing PDF...',
        sys.stdout.flush()

    pdf.flush()

    if opts.verbose:
        print 'done.'

    del pdf
Esempio n. 8
0
def main(argv=sys.argv[1:]):
    def message(msg):
        """
        Print message if user set verbose mode.
        """
        if options.verbose:
            print(msg, file=sys.stderr)

    usage = "usage: %prog [options] file1 file2..."

    parser = optparse.OptionParser(usage=usage)

    parser.add_option(
        "-v", "--verbose", dest="verbose", action="store_true", help="verbose output"
    )
    parser.add_option(
        "-u",
        "--use-underscores",
        dest="underscores",
        action="store_true",
        help="use underscores instead of spaces for output filenames",
    )
    parser.add_option(
        "-d", "--dir", dest="dir", metavar="directory", help="output to directory"
    )
    parser.add_option(
        "-f",
        "--format",
        dest="format",
        metavar="format",
        help="output file format, default pdf",
        default="pdf",
        choices=["pdf", "svg", "png"],
    )
    parser.add_option(
        "-r",
        "--regex",
        dest="regex",
        metavar="regex",
        help="process diagrams which name matches given regular expresion;"
        " name includes package name; regular expressions are case insensitive",
    )

    (options, args) = parser.parse_args(argv)

    if not args:
        parser.print_help()

    Application.init(
        services=["event_manager", "component_registry", "element_factory"]
    )
    factory = Application.get_service("element_factory")

    name_re = None
    if options.regex:
        name_re = re.compile(options.regex, re.I)

    # we should have some gaphor files to be processed at this point
    for model in args:
        message(f"loading model {model}")
        storage.load(model, factory)
        message("ready for rendering")

        for diagram in factory.select(lambda e: e.isKindOf(UML.Diagram)):
            odir = pkg2dir(diagram.package)

            # just diagram name
            dname = diagram.name
            # full diagram name including package path
            pname = f"{odir}/{dname}"

            if options.underscores:
                odir = odir.replace(" ", "_")
                dname = dname.replace(" ", "_")

            if name_re and not name_re.search(pname):
                message(f"skipping {pname}")
                continue

            if options.dir:
                odir = f"{options.dir}/{odir}"

            outfilename = f"{odir}/{dname}.{options.format}"

            if not os.path.exists(odir):
                message(f"creating dir {odir}")
                os.makedirs(odir)

            message(f"rendering: {pname} -> {outfilename}...")

            view = View(diagram.canvas)
            view.painter = ItemPainter()

            tmpsurface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0)
            tmpcr = cairo.Context(tmpsurface)
            view.update_bounding_box(tmpcr)
            tmpcr.show_page()
            tmpsurface.flush()

            w, h = view.bounding_box.width, view.bounding_box.height
            if options.format == "pdf":
                surface = cairo.PDFSurface(outfilename, w, h)
            elif options.format == "svg":
                surface = cairo.SVGSurface(outfilename, w, h)
            elif options.format == "png":
                surface = cairo.ImageSurface(
                    cairo.FORMAT_ARGB32, int(w + 1), int(h + 1)
                )
            else:
                assert False, f"unknown format {options.format}"
            cr = cairo.Context(surface)
            view.matrix.translate(-view.bounding_box.x, -view.bounding_box.y)
            paint(view, cr)
            cr.show_page()

            if options.format == "png":
                surface.write_to_png(outfilename)

            surface.flush()
            surface.finish()
Esempio n. 9
0
def visualize(fun, l: list, width: int, height: int, name: str):
    surface = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height)

    sorted_list = l.copy()
    swaps = [s for s in fun(sorted_list)]

    sctx = cairo.Context(surface)
    sctx.scale(width, height)
    sctx.rectangle(0, 0, 1, 1)
    sctx.set_source_rgb(1, 1, 1)
    sctx.fill()

    MAX_VALUE = sorted_list[-1]
    MIN_VALUE = sorted_list[0]
    LIST_LENGTH = len(l)
    SWAP_LENGTH = len(swaps)
    X_UNIT = width / (SWAP_LENGTH + 2)
    # print(X_UNIT)
    VIOLET = (0.7, 0, 0.9)
    BLUE = (0.7, 0.9, 1)
    Y_UNIT = height / (LIST_LENGTH * 1.05)
    # print(Y_UNIT)

    contexts = [None] * len(l)
    for i, val in enumerate(l):
        percent_max = (val - MIN_VALUE) / (MAX_VALUE - MIN_VALUE)
        color = [
            percent_max * c1 + (1 - percent_max) * c2
            for c1, c2 in zip(VIOLET, BLUE)
        ]

        ctx = cairo.Context(surface)
        ctx.set_source_rgb(*color)

        y_value = i * Y_UNIT

        ctx.translate(0, 0.05 * height)
        ctx.move_to(0, y_value)
        ctx.set_line_width(0.3 * Y_UNIT)
        ctx.line_to(X_UNIT, y_value)

        contexts[i] = ctx

    for i, swap in enumerate(swaps):
        x_value = (i + 2) * X_UNIT
        swap_0 = swap[0]
        swap_1 = swap[1]
        for j, ctx in enumerate(contexts):
            if swap_0 == j:
                ctx.line_to(x_value, swap_1 * Y_UNIT)

            elif swap_1 == j:
                ctx.line_to(x_value, swap_0 * Y_UNIT)

            else:
                ctx.line_to(x_value, j * Y_UNIT)

        contexts[swap_0], contexts[swap_1] = contexts[swap_1], contexts[swap_0]

    for i, ctx in enumerate(contexts):
        ctx.line_to(width, i * Y_UNIT)
        ctx.stroke()

    surface.write_to_png(f'{name}.png')
Esempio n. 10
0
            hitEdge = walkers[index].edges()
            if hitEdge or hitLine:
                walk = False

            count = count + 1
        index = index + 1

    for walker in walkers:
        walker.draw(context)


# Call the main function and save an image
if __name__ == '__main__':
    if fileFormat == 'PNG':
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
        context = cairo.Context(surface)
        main()
        fileName = uuid.uuid4().hex[:8]
        surface.write_to_png('Images/Vertical_Lines/' + str(fileName) + '.png')
    elif fileFormat == 'SVG':
        fileName = uuid.uuid4().hex[:8]
        surface = cairo.SVGSurface(
                'Images/Vertical_Lines/0-svg/' + str(fileName) + '.svg',
                width,
                height
        )
        context = cairo.Context(surface)
        main()
        context.finish()
Esempio n. 11
0
def cairo_surf(tree: libginger.Tree,
               colour: ty.Tuple[float, float, float, float] = (0., 0., 0., 1.),
               line_width: float = 1.0,
               font_size: int = 20,
               token_node_distance: int = 20,
               node_part_margin: int = None,
               label_shift: int = 5,
               arrow_shift: int = 6,
               energy: float = 0.5) -> 'cairo.RecordingSurface':
    r'''
    Render a tree in a cairo recording surface.

    ## Parameters
      - `colour`  the colour of the drawing as an RGBA vector in $[0, 1]⁴$
      - `line_width`  the width of the lines, obviously
      - `font_size`  the font size used
      - `token_node_distance`  the horizontal spacing between two nodes
      - `node_part_margin`  the vertical spacing between node attributes
        (default: `$⌈\texttt{token\_node\_distance`/3}⌉$`)
      - `label_shift`  the space between arrow and their labels
      - `arrow_shift`  the horizontal padding between arrows of opposite directions
      - `energy`  the magnitude of the tangent at the origin of an arc etween two nodes is $E×d$
         where $E$ is the energy and $d$ the distance between those nodes. Increase this to make
         the arcs go higher.
    '''

    if cairo is None:
        raise NotImplementedError

    if node_part_margin is None:
        node_part_margin = math.ceil(token_node_distance / 3)

    res = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, None)
    context = cairo.Context(res)
    context.set_font_size(font_size)

    # For every token, we need to take account the width of the largest of the stacked attributes :
    # `form`, `lemma`, `upostag` This dict associate every node to its Rect
    node_rects = {}  # type: ty.Dict[libginger.Node, Rect]
    current_x = 0
    for n in tree.word_sequence:
        parts_extents = [
            context.text_extents(s if s is not None else '_')
            for s in (n.form, n.lemma, n.upostag)
        ]
        w = max(e[2] for e in parts_extents)
        h = sum(e[3] for e in parts_extents) + 3 * node_part_margin
        node_rects[n] = Rect(current_x, 0, w, h)
        current_x += w + token_node_distance

    # Normalise the height of the nodes to the largest
    part_height = math.ceil(max(h for _, _, _, h in node_rects.values()) / 3)
    nodes_height = 3 * part_height
    # And take into account in node rects
    node_rects = {
        n: Rect(x, y, w, nodes_height)
        for n, (x, y, w, h) in node_rects.items()
    }

    # Now draw
    context.set_source_rgba(*colour)
    context.set_line_width(line_width)

    # First draw the nodes
    context.move_to(0, 0)
    for node, (x, y, w, h) in ((n, node_rects[n]) for n in tree.word_sequence):
        parts = (s if s is not None else '_'
                 for s in (node.form, node.lemma, node.upostag))
        for i, p in enumerate(parts, start=1):
            margin = math.floor((w - context.text_extents(p)[2]) / 2)
            context.move_to(x + margin, y + i * part_height)
            context.show_text(p)
    context.stroke()

    # Find out the largest arc height
    # First, get the relations
    deps = [(node.head, node, node.deprel) for node in tree.word_sequence
            if node.head is not tree.root]

    # Now draw the arcs
    arrowhead_size = font_size / 3
    for head, foot, tag in deps:
        # Arc
        head_rect, foot_rect = node_rects[head], node_rects[foot]
        start = Point(
            head_rect.x + head_rect.w / 2 +
            (-arrow_shift if foot.identifier < head.identifier else
             arrow_shift), head_rect.y)
        end = Point(foot_rect.x + foot_rect.w / 2,
                    foot_rect.y - arrowhead_size)
        origin_speed = math.floor(abs(end.x - start.x) * energy)
        control1 = (start.x, start.y - origin_speed)
        control2 = (end.x, end.y - origin_speed)
        context.move_to(*start)
        context.curve_to(*control1, *control2, *end)
        arrow_extents = context.path_extents()
        context.stroke()
        arrowhead(context, arrowhead_size, end)
        tag_w = context.text_extents(tag)[2]
        context.move_to((arrow_extents[0] + arrow_extents[2] - tag_w) / 2,
                        arrow_extents[1] - label_shift)
        context.show_text(tag)

    # Root arrow
    head_rect = node_rects[next(node for node in tree.word_sequence
                                if node.head is tree.root)]
    root_x = head_rect.x + head_rect.w / 2
    _, root_y, *_ = res.ink_extents()
    root_w = context.text_extents('root')[2] - label_shift
    context.move_to(root_x - root_w / 2, root_y)
    context.show_text('root')
    context.move_to(root_x, root_y)
    context.line_to(root_x, head_rect.y)
    context.stroke()
    arrowhead(context, arrowhead_size, Point(root_x, head_rect.y))
    return res
Esempio n. 12
0
def _scroll(tdw, model, width=1920, height=1080,
            zoom=1.0, mirrored=False, rotation=0.0,
            turns=8, turn_steps=8, turn_radius=0.3,
            save_pngs=False,
            set_modes=None,
            use_background=True):
    """Test scroll performance

    Scroll around in a circle centred on the virtual display, testing
    the same sort of render that's used for display - albeit to an
    in-memory surface.

    This tests rendering and cache performance quite well, though it
    discounts Cairo acceleration.

    """
    num_undos_needed = 0
    if set_modes:
        for path, mode in set_modes.items():
            model.select_layer(path=path)
            num_undos_needed += 1
            model.set_current_layer_mode(mode)
            num_undos_needed += 1
            assert model.layer_stack.deepget(path, None).mode == mode
    model.layer_stack.background_visible = use_background
    model.layer_stack._render_cache.clear()

    radius = min(width, height) * turn_radius
    fakealloc = namedtuple("FakeAlloc", ["x", "y", "width", "height"])
    alloc = fakealloc(0, 0, width, height)
    tdw.set_allocation(alloc)
    surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)

    tdw.set_rotation(rotation)
    tdw.set_zoom(zoom)
    tdw.set_mirrored(mirrored)
    tdw.recenter_document()

    start = time.clock()
    cx, cy = tdw.get_center()
    last_x = cx
    last_y = cy
    nframes = 0
    for turn_i in xrange(turns):
        for step_i in xrange(turn_steps):
            t = 2 * math.pi * (step_i / turn_steps)
            x = cx + math.cos(t) * radius
            y = cy + math.sin(t) * radius
            dx = x - last_x
            dy = y - last_y
            cr = cairo.Context(surf)
            cr.rectangle(*alloc)
            cr.clip()
            tdw.scroll(dx, dy)
            tdw.renderer._draw_cb(tdw, cr)
            surf.flush()
            last_x = x
            last_y = y
            if save_pngs:
                filename = "/tmp/scroll-%03d-%03d.png" % (turn_i, step_i)
                surf.write_to_png(filename)
            nframes += 1
    dt = time.clock() - start
    for i in range(num_undos_needed):
        model.undo()
    if set_modes:
        for path in set_modes.keys():
            mode = model.layer_stack.deepget(path, None).mode
            assert mode == mypaintlib.CombineNormal
    return (nframes, dt)
Esempio n. 13
0
 def __init__(self, renderer):
     GraphicsContextBase.__init__(self)
     self.renderer = renderer
     self.ctx = cairo.Context()