Exemple #1
0
    def draw_line(self, segments, ax, **kwargs):
        key = (ax, kwargs.pop('key', self.keyfor(segments)))
        ec = kwargs.pop('ec', 'k')
        t = kwargs.pop('transform', None)
        zorder = kwargs.pop('zorder', 1)

        if key not in self.items:
            l = LineCollection(segments)
            ax.add_collection(l)
            self.items[key] = dict(lines=l)

        d = self.items[key]
        l = d['lines']

        l.set_segments(segments)
        l.set_edgecolors(ec)
        if t is not None:
            l.set_transform(mplt.Affine2D(matrix=t) + ax.transData)

        # u += drawer.draw_line(
        #     np.array([
        #         [0,10],
        #         [0,10]
        #     ]).T.reshape(1,2,2),
        #     ax
        # )

        return l,
Exemple #2
0
def _generate_straight_edges(edges, pos, styles, *, ax):
    N = len(edges)
    if not N:
        return None, None
    proto_edge = next(iter(edges))
    edge_pos = [None] * N
    edge_indx = [None] * N
    properties = {
        k: [None] * N
        for k in styles[proto_edge] if k in _VALID_EDGE_STYLE
    }

    for j, (u, v) in enumerate(edges):
        edge_pos[j] = (pos[u], pos[v])
        for key, values in properties.items():
            values[j] = styles[(u, v)][key]
        edge_indx[j] = (u, v)
    key_map = {
        'color': 'colors',
        'width': 'linewidths',
        'style': 'linestyle',
    }

    renamed_properties = {key_map[k]: v for k, v in properties.items()}
    line_art = LineCollection(edge_pos,
                              transOffset=ax.transData,
                              zorder=1,
                              **renamed_properties)
    line_art.set_transform(ax.transData)
    return line_art, edge_indx
Exemple #3
0
 def changeVecteur(self, ech=1.0, col=None):
     """ modifie les valeurs de vecteurs existants"""
     self.drawVecteur(False)
     if type(ech) == type((3, 4)):
         if len(ech) >= 1:
             ech = ech[0]
     # previous object
     obj = self.getObjFromType("vecteur")
     if obj == None:
         return
     # change coordinates
     dep, arr_old, ech_old = obj.getData()
     arr = dep + (arr_old - dep) * ech / ech_old
     # new object
     lc1 = LineCollection(zip(dep, arr))
     lc1.set_transform(self.transform)
     if col == None:
         col = wx.Color(0, 0, 255)
     a = col.Get()
     col = (a[0] / 255, a[1] / 255, a[2] / 255)
     lc1.set_color(col)
     obj = GraphicObject("vecteur", lc1, False, None)
     obj.setData([dep, arr, ech])
     self.addGraphicObject(obj)
     self.cnv.collections[0] = lc1
     self.redraw()
Exemple #4
0
 def shape(self, height, yrange, rotated):
     g = rlg2mpl.Group()
     trans = TransformScalePart(g.combined_transform)
     y = height/2.0
     segments = [[(x1,y),(x2,y)] for (x1,x2) in self.segments]
     a = LineCollection(segments, edgecolor='k', facecolor='k')
     a.set_linewidth(2)
     g.add(a)
     a.set_transform(g.combined_transform)
     return g
Exemple #5
0
 def shape(self, height, yrange, rotated):
     g = rlg2mpl.Group()
     trans = TransformScalePart(g.combined_transform)
     y = height / 2.0
     segments = [[(x1, y), (x2, y)] for (x1, x2) in self.segments]
     a = LineCollection(segments, edgecolor='k', facecolor='k')
     a.set_linewidth(2)
     g.add(a)
     a.set_transform(g.combined_transform)
     return g
Exemple #6
0
 def shape(self, height, yrange, rotated):
     g = rlg2mpl.Group()
     trans = TransformScalePart(g.combined_transform)
     segment = [(0.1, 0), (0.9, 0)]
     if rotated:
         segment = [(y, x) for (x, y) in segment]
     a = LineCollection([segment], colors=self.cvalues, offsets=self.offsets, transOffset=g.combined_transform)
     a.set_linewidth(3)
     g.add(a)
     a.set_transform(trans)
     return g
Exemple #7
0
 def shape(self, height, yrange, rotated):
     g = rlg2mpl.Group()
     trans = TransformScalePart(g.combined_transform)
     segment = [(.1,0),(.9,0)]
     if rotated:
         segment = [(y,x) for (x,y) in segment]
     a = LineCollection([segment], colors=self.cvalues, 
             offsets=self.offsets, transOffset=g.combined_transform)
     a.set_linewidth(3)
     g.add(a)
     a.set_transform(trans)
     return g
Exemple #8
0
    def make_range_frame(self):
        
        xline = [(self.xbounds[0], self.xpos), (self.xbounds[1], self.xpos)]
        yline = [(self.ypos, self.ybounds[0]), (self.ypos, self.ybounds[1])]

        range_lines = LineCollection(segments=[xline, yline],
                                     linewidths=[self.linewidth],
                                     colors=[self.color])

        range_lines.set_transform(self.axes.transAxes)
        range_lines.set_zorder(10)

        return range_lines
    def make_range_frame(self):

        xminf, xmaxf = data_bounds_on_axis(self.axes.viewLim.intervalx, self.xbounds)

        yminf, ymaxf = data_bounds_on_axis(self.axes.viewLim.intervaly, self.ybounds)

        xline = [(xminf, 0), (xmaxf, 0)]
        yline = [(0, yminf), (0, ymaxf)]

        range_lines = LineCollection(segments=[xline, yline], linewidths=[self.linewidth], colors=[self.color])

        range_lines.set_transform(self.axes.transAxes)
        range_lines.set_zorder(10)

        return range_lines
Exemple #10
0
class MyCell(matplotlib.table.CustomCell):
    """ Extending matplotlib tables.
        
        Adapted from https://stackoverflow.com/a/53573651/505698
    """
    def __init__(self, *args, visible_edges, **kwargs):
        super().__init__(*args, visible_edges=visible_edges, **kwargs)
        seg = np.array([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0],
                        [0.0, 0.0]]).reshape(-1, 1, 2)
        segments = np.concatenate([seg[:-1], seg[1:]], axis=1)
        self.edgelines = LineCollection(segments,
                                        edgecolor=kwargs.get("edgecolor"))
        self._text.set_zorder(2)
        self.set_zorder(1)

    def set_transform(self, trans):
        self.edgelines.set_transform(trans)
        super().set_transform(trans)

    def draw(self, renderer):
        c = self.get_edgecolor()
        self.set_edgecolor((1, 1, 1, 0))
        super().draw(renderer)
        self.update_segments(c)
        self.edgelines.draw(renderer)
        self.set_edgecolor(c)

    def update_segments(self, color):
        x, y = self.get_xy()
        w, h = self.get_width(), self.get_height()
        seg = np.array([[x, y], [x + w, y], [x + w, y + h], [x, y + h],
                        [x, y]]).reshape(-1, 1, 2)
        segments = np.concatenate([seg[:-1], seg[1:]], axis=1)
        self.edgelines.set_segments(segments)
        self.edgelines.set_linewidth(self.get_linewidth())
        colors = [
            color if edge in self._visible_edges else (1, 1, 1, 0)
            for edge in self._edges
        ]
        self.edgelines.set_edgecolor(colors)

    def get_path(self):
        codes = [Path.MOVETO] + [Path.LINETO] * 3 + [Path.CLOSEPOLY]
        return Path(
            [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]],
            codes,
            readonly=True,
        )
Exemple #11
0
    def make_range_frame (self):

        rx = self.axes.get_xlim()
        ry = self.axes.get_ylim()
        px = pl.prctile ( self.x )
        py = pl.prctile ( self.y )

        if self.trim:
            if px[2]-px[0]>1.5*(px[3]-px[1]):
                px[0] = self.x[self.x>px[2]-1.5*(px[3]-px[1])].min()
            if px[4]-px[2]>1.5*(px[3]-px[1]):
                px[4] = self.x[self.x<px[2]+1.5*(px[3]-px[1])].min()

        x = px-rx[0]
        x /= rx[1]-rx[0]
        y = py-ry[0]
        y /= ry[1]-ry[0]
        ex = .003
        ey = .003
        xline = [
                [(x[0],0),(x[1],0)],
                [(x[1],ey),(x[2]-ex,ey)],
                [(x[2]+ex,ey),(x[3],ey)],
                [(x[3],0),(x[4],0)]
                ]
        yline = [
                [(0,y[0]),(0,y[1])],
                [(ex,y[1]),(ex,y[2]-ey)],
                [(ex,y[2]+ey),(ex,y[3])],
                [(0,y[3]),(0,y[4])]
                ]
        widths = [1,1,1,1]
        range_lines = LineCollection(
                segments=pl.clip(xline+yline,0,1),
                linewidths=widths+widths,
                colors=[[0]*3]*2*len(widths) )
        range_lines.set_transform ( self.axes.transAxes )
        range_lines.set_zorder(10)

        self.axes.get_xaxis().tick_bottom()
        self.axes.get_yaxis().tick_left()
        self.axes.set_xticks(px)
        self.axes.set_yticks(py)
        self.axes.tick_params ( width=0 )

        return range_lines
Exemple #12
0
 def make_box_plot (self):
     x = self.x
     rx = self.axes.get_xlim()
     ry = self.axes.get_ylim()
     ex = self.offset*(rx[1]-rx[0])
     ey = self.offset*(ry[1]-ry[0])
     if self.vert == 1:
         ex,ey = ey,ex
     p = self.boxstats['main']
     n = self.boxstats['notch']
     f_lo,f_hi = self.boxstats['fliers']
     if self.notch:
         lines = [ [(x,p[0]),(x,p[1])],
                 [(x+ex,p[1]),(x+ex,n[0])],
                 [(x+ex,n[0]),(x-ex,p[2]-ey)],
                 [(x-ex,p[2]+ey),(x+ex,n[1])],
                 [(x+ex,n[1]),(x+ex,p[3])],
                 [(x,p[3]),(x,p[4])] ]
     else:
         lines = [ [(x,p[0]),(x,p[1])],
                 [(x+ex,p[1]),(x+ex,p[2]-ey)],
                 [(x+ex,p[2]+ey),(x+ex,p[3])],
                 [(x,p[3]),(x,p[4])] ]
     lines = pl.array(lines)
     if self.vert==1:
         lines = pl.array([ pl.c_[l[:,1],l[:,0]] for l in lines ])
         pt = self.axes.plot ( f_lo, [x]*len(f_lo), '.', color=self.color,
                 markersize=self.lw ) + \
             self.axes.plot ( f_hi, [x]*len(f_hi), '.', color=self.color,
                 markersize=self.lw )
         dummy = self.axes.plot ( [p[0],p[-1]],[x-ex,x+ex], '.', markersize=0 )
     else:
         pt = self.axes.plot ( [x]*len(f_lo), f_lo, '.', color=self.color,
                 markersize=1 ) + \
             self.axes.plot ( [x]*len(f_hi), f_hi, '.', color=self.color,
                 markersize=1 )
         dummy = self.axes.plot ( [x-ex,x+ex], [p[0],p[-1]], '.', markersize=0 )
     box = LineCollection (
             segments=lines,
             linewidths=[self.lw]*lines.shape[0],
             colors=[self.color]*lines.shape[0] )
     box.set_transform ( self.axes.transData )
     box.set_zorder(10)
     return box, pt[0],dummy[0]
    def make_range_frame(self):

        xminf, xmaxf = data_bounds_on_axis(self.axes.viewLim.intervalx,
                                           self.xbounds)

        yminf, ymaxf = data_bounds_on_axis(self.axes.viewLim.intervaly,
                                           self.ybounds)

        xline = [(xminf, 0), (xmaxf, 0)]
        yline = [(0, yminf), (0, ymaxf)]

        range_lines = LineCollection(segments=[xline, yline],
                                     linewidths=[self.linewidth],
                                     colors=[self.color])

        range_lines.set_transform(self.axes.transAxes)
        range_lines.set_zorder(10)

        return range_lines
Exemple #14
0
 def createVecteur(self, X, Y, U, V, ech=1., col=None):
     """ modifie les valeurs de vecteurs existants"""
     self.drawVecteur(False)
     #print shape(X),shape(Y),shape(U),shape(V)
     # new coordinates
     #vm = mean(median(median(U)),median(median(V)));
     #dmx = max(X[0,1]-X[0,0],Y[0,1]-Y[0,0])
     u, v = U, V  #/vm*dmx*ech/2
     l = len(ravel(X))
     dep = concatenate([X.reshape((l, 1)), Y.reshape((l, 1))], axis=1)
     b = X + u
     c = Y + v
     arr = concatenate([b.reshape((l, 1)), c.reshape((l, 1))], axis=1)
     lc1 = LineCollection(zip(dep, arr))
     lc1.set_transform(self.transform)
     obj = GraphicObject('vecteur', lc1, False, None)
     obj.setData([dep, arr, ech])
     self.addGraphicObject(obj)
     if len(self.cnv.collections) > 0: self.cnv.collections[0] = lc1
     else: self.cnv.collections = [lc1]
     self.redraw()
Exemple #15
0
 def createVecteur(self, X, Y, U, V, ech=1.0, col=None):
     """ modifie les valeurs de vecteurs existants"""
     self.drawVecteur(False)
     # print shape(X),shape(Y),shape(U),shape(V)
     # new coordinates
     # vm = mean(median(median(U)),median(median(V)));
     # dmx = max(X[0,1]-X[0,0],Y[0,1]-Y[0,0])
     u, v = U, V  # /vm*dmx*ech/2
     l = len(ravel(X))
     dep = concatenate([X.reshape((l, 1)), Y.reshape((l, 1))], axis=1)
     b = X + u
     c = Y + v
     arr = concatenate([b.reshape((l, 1)), c.reshape((l, 1))], axis=1)
     lc1 = LineCollection(zip(dep, arr))
     lc1.set_transform(self.transform)
     obj = GraphicObject("vecteur", lc1, False, None)
     obj.setData([dep, arr, ech])
     self.addGraphicObject(obj)
     if len(self.cnv.collections) > 0:
         self.cnv.collections[0] = lc1
     else:
         self.cnv.collections = [lc1]
     self.redraw()
Exemple #16
0
 def changeVecteur(self, ech=1., col=None):
     """ modifie les valeurs de vecteurs existants"""
     self.drawVecteur(False)
     if type(ech) == type((3, 4)):
         if len(ech) >= 1: ech = ech[0]
     # previous object
     obj = self.getObjFromType('vecteur')
     if obj == None: return
     #change coordinates
     dep, arr_old, ech_old = obj.getData()
     arr = dep + (arr_old - dep) * ech / ech_old
     # new object
     lc1 = LineCollection(zip(dep, arr))
     lc1.set_transform(self.transform)
     if col == None: col = wx.Color(0, 0, 255)
     a = col.Get()
     col = (a[0] / 255, a[1] / 255, a[2] / 255)
     lc1.set_color(col)
     obj = GraphicObject('vecteur', lc1, False, None)
     obj.setData([dep, arr, ech])
     self.addGraphicObject(obj)
     self.cnv.collections[0] = lc1
     self.redraw()
Exemple #17
0
    def _make_line_collection(segments,
                              cvals,
                              min_val,
                              max_val,
                              cmap,
                              line_width,
                              zorder=100):
        """Takes in parameters to make colorbased paths LineCollection.

        :param segments: linesegments to be plotted
        :type segments: 2D array or list
        :param cvals: list corresponding to the segments
        :type cvals: list
        :param min_val: min normalization value
        :type min_val: float
        :param max_val: max normalization value
        :type max_val: float
        :param cmap: colorbar
        :type cmap: str
        :param line_width: width of the lineplotted.
        :type line_width: float
        :param zorder: plotting priority
        :type zorder: int
        :return:
        """

        lc = LineCollection(segments,
                            cvals,
                            cmap=plt.get_cmap(cmap),
                            norm=plt.Normalize(0, max_val - min_val),
                            zorder=zorder)

        lc.set_transform(ccrs.Geodetic())
        lc.set_array(cvals)
        lc.set_linewidth(line_width)

        return lc
Exemple #18
0
    def initDomain(self):
        # changement de la valeur des axes
        grd = self.model.Aquifere.getFullGrid()
        self.xlim = (grd['x0'], grd['x1'])
        self.ylim = (grd['y0'], grd['y1'])
        p, = pl.plot([0, 1], 'b')
        self.transform = p.get_transform()
        obj = GraphicObject('grille', p, True, None)
        self.addGraphicObject(obj)
        self.changeDomain()

        # add basic vector as a linecollection
        dep = rand(2, 2) * 0.
        arr = dep * 1.
        ech = 1.
        lc1 = LineCollection(zip(dep, arr))
        lc1.set_transform(self.transform)
        pl.setp(lc1, linewidth=.5)
        self.cnv.collections = [lc1]
        #self.cnv.add_patch(lc1);
        obj = GraphicObject('vecteur', lc1, False, None)
        obj.setData([dep, arr, ech])
        self.addGraphicObject(obj)
        self.draw()
Exemple #19
0
    def initDomain(self):
        # changement de la valeur des axes
        grd = self.model.Aquifere.getFullGrid()
        self.xlim = (grd["x0"], grd["x1"])
        self.ylim = (grd["y0"], grd["y1"])
        p, = pl.plot([0, 1], "b")
        self.transform = p.get_transform()
        obj = GraphicObject("grille", p, True, None)
        self.addGraphicObject(obj)
        self.changeDomain()

        # add basic vector as a linecollection
        dep = rand(2, 2) * 0.0
        arr = dep * 1.0
        ech = 1.0
        lc1 = LineCollection(zip(dep, arr))
        lc1.set_transform(self.transform)
        pl.setp(lc1, linewidth=0.5)
        self.cnv.collections = [lc1]
        # self.cnv.add_patch(lc1);
        obj = GraphicObject("vecteur", lc1, False, None)
        obj.setData([dep, arr, ech])
        self.addGraphicObject(obj)
        self.draw()
Exemple #20
0
def plot_day_summary2_ohlc(
    ax,
    opens,
    highs,
    lows,
    closes,
    ticksize=4,
    colorup='k',
    colordown='r',
):
    """Represent the time, open, high, low, close as a vertical line
    ranging from low to high.  The left tick is the open and the right
    tick is the close.
    *opens*, *highs*, *lows* and *closes* must have the same length.
    NOTE: this code assumes if any value open, high, low, close is
    missing (*-1*) they all are missing

    Parameters
    ----------
    ax : `Axes`
        an Axes instance to plot to
    opens : sequence
        sequence of opening values
    highs : sequence
        sequence of high values
    lows : sequence
        sequence of low values
    closes : sequence
        sequence of closing values
    ticksize : int
        size of open and close ticks in points
    colorup : color
        the color of the lines where close >= open
    colordown : color
         the color of the lines where close <  open

    Returns
    -------
    ret : list
        a list of lines added to the axes
    """

    _check_input(opens, highs, lows, closes)

    rangeSegments = [((i, low), (i, high))
                     for i, low, high in zip(xrange(len(lows)), lows, highs)
                     if low != -1]

    # the ticks will be from ticksize to 0 in points at the origin and
    # we'll translate these to the i, close location
    openSegments = [((-ticksize, 0), (0, 0))]

    # the ticks will be from 0 to ticksize in points at the origin and
    # we'll translate these to the i, close location
    closeSegments = [((0, 0), (ticksize, 0))]

    offsetsOpen = [(i, open) for i, open in zip(xrange(len(opens)), opens)
                   if open != -1]

    offsetsClose = [(i, close) for i, close in zip(xrange(len(closes)), closes)
                    if close != -1]

    scale = ax.figure.dpi * (1.0 / 72.0)

    tickTransform = Affine2D().scale(scale, 0.0)

    colorup = mcolors.to_rgba(colorup)
    colordown = mcolors.to_rgba(colordown)
    colord = {True: colorup, False: colordown}
    colors = [
        colord[open < close] for open, close in zip(opens, closes)
        if open != -1 and close != -1
    ]

    useAA = 0,  # use tuple here
    lw = 1,  # and here
    rangeCollection = LineCollection(
        rangeSegments,
        colors=colors,
        linewidths=lw,
        antialiaseds=useAA,
    )

    openCollection = LineCollection(
        openSegments,
        colors=colors,
        antialiaseds=useAA,
        linewidths=lw,
        offsets=offsetsOpen,
        transOffset=ax.transData,
    )
    openCollection.set_transform(tickTransform)

    closeCollection = LineCollection(
        closeSegments,
        colors=colors,
        antialiaseds=useAA,
        linewidths=lw,
        offsets=offsetsClose,
        transOffset=ax.transData,
    )
    closeCollection.set_transform(tickTransform)

    minpy, maxx = (0, len(rangeSegments))
    miny = min([low for low in lows if low != -1])
    maxy = max([high for high in highs if high != -1])
    corners = (minpy, miny), (maxx, maxy)
    ax.update_datalim(corners)
    ax.autoscale_view()

    # add these last
    ax.add_collection(rangeCollection)
    ax.add_collection(openCollection)
    ax.add_collection(closeCollection)
    return rangeCollection, openCollection, closeCollection
Exemple #21
0
def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4,
                      colorup='k', colordown='r',
                     ):
    """

    Represent the time, open, close, high, low as a vertical line
    ranging from low to high.  The left tick is the open and the right
    tick is the close.

    ax          : an Axes instance to plot to
    ticksize    : size of open and close ticks in points
    colorup     : the color of the lines where close >= open
    colordown   : the color of the lines where close <  open

    return value is a list of lines added
    """

    # note this code assumes if any value open, close, low, high is
    # missing they all are missing

    rangeSegments = [ ((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1 ]

    # the ticks will be from ticksize to 0 in points at the origin and
    # we'll translate these to the i, close location
    openSegments = [  ((-ticksize, 0), (0, 0)) ]

    # the ticks will be from 0 to ticksize in points at the origin and
    # we'll translate these to the i, close location
    closeSegments = [ ((0, 0), (ticksize, 0)) ]


    offsetsOpen = [ (i, open) for i, open in zip(xrange(len(opens)), opens) if open != -1 ]

    offsetsClose = [ (i, close) for i, close in zip(xrange(len(closes)), closes) if close != -1 ]


    scale = ax.figure.dpi * (1.0/72.0)

    tickTransform = Affine2D().scale(scale, 0.0)

    r,g,b = colorConverter.to_rgb(colorup)
    colorup = r,g,b,1
    r,g,b = colorConverter.to_rgb(colordown)
    colordown = r,g,b,1
    colord = { True : colorup,
               False : colordown,
               }
    colors = [colord[open<close] for open, close in zip(opens, closes) if open!=-1 and close !=-1]

    assert(len(rangeSegments)==len(offsetsOpen))
    assert(len(offsetsOpen)==len(offsetsClose))
    assert(len(offsetsClose)==len(colors))

    useAA = 0,   # use tuple here
    lw = 1,      # and here
    rangeCollection = LineCollection(rangeSegments,
                                     colors       = colors,
                                     linewidths   = lw,
                                     antialiaseds = useAA,
                                     )

    openCollection = LineCollection(openSegments,
                                    colors       = colors,
                                    antialiaseds = useAA,
                                    linewidths   = lw,
                                    offsets      = offsetsOpen,
                                    transOffset  = ax.transData,
                                   )
    openCollection.set_transform(tickTransform)

    closeCollection = LineCollection(closeSegments,
                                     colors       = colors,
                                     antialiaseds = useAA,
                                     linewidths   = lw,
                                     offsets      = offsetsClose,
                                     transOffset  = ax.transData,
                                     )
    closeCollection.set_transform(tickTransform)

    minpy, maxx = (0, len(rangeSegments))
    miny = min([low for low in lows if low !=-1])
    maxy = max([high for high in highs if high != -1])
    corners = (minpy, miny), (maxx, maxy)
    ax.update_datalim(corners)
    ax.autoscale_view()

    # add these last
    ax.add_collection(rangeCollection)
    ax.add_collection(openCollection)
    ax.add_collection(closeCollection)
    return rangeCollection, openCollection, closeCollection
Exemple #22
0
class Visualisation(FigureCanvasWxAgg):
    def __init__(self, gui):

        self.fig = pl.figure()  #(9,8), 90)
        FigureCanvasWxAgg.__init__(self, gui, -1, self.fig)
        self.xlim, self.ylim, self.dataon = (), (), False

        # c'est la GUI e tle modele
        self.gui, self.core = gui, gui.core
        # polygone d'interaction sur une zone (pour pouvoir la modifier)
        self.polyInteract = None

        # liste de variables, sert pour la GUI et le combobox sur les variables
        self.listeNomVar = []
        for mod in self.core.modelList:
            for k in gui.linesDic[mod].keys():
                self.listeNomVar.extend(gui.linesDic[mod][k])
        self.curVar, self.curContour = None, 'Charge'  # variable courante selectionne
        self.curMedia, self.curOri, self.curPlan, self.curGroupe = 0, 'Z', 0, None
        # variable pour savoir si on est en cours de tracage d'une zone
        self.typeZone = -1

        # coordonnees et zone de la zone que l'on est en train de creer
        self.curZone = None  # objet graphique (ligne, point, rect..)
        self.x1, self.y1 = [], []
        self.tempZoneVal = []  # liste de values pour polyV
        self.calcE = 0
        self.calcT = 0
        self.calcR = 0
        # dit si calcule effectue ou non

        # dictionnaire qui est compose des variables de l'Aquifere
        # a chaque variable est associe une liste de zones
        self.listeZone, self.listeZoneText, self.listeZmedia = {}, {}, {}
        for i in range(len(self.listeNomVar)):
            #print self.listeNomVar[i]
            self.listeZone[self.listeNomVar[i]] = []
            self.listeZoneText[self.listeNomVar[i]] = []
            self.listeZmedia[self.listeNomVar[i]] = []

        # toolbar de la visu, de type NavigationToolbar2Wx
        self.toolbar = NavigationToolbar2Wx(self)
        self.toolbar.Realize()
        # ajout du subplot a la figure
        self.cnv = self.fig.add_axes([.05, .05, .9,
                                      .88])  #left,bottom, wide,height
        self.toolbar.update()
        self.pos = self.mpl_connect('motion_notify_event', self.onPosition)

        # create teh major objects:
        self.Contour, self.ContourF, self.ContourLabel, self.Vector = None, None, None, None
        self.Grid, self.Particles, self.Image, self.Map = None, None, None, None

    #####################################################################
    #                     Divers accesseur/mutateurs
    #####################################################################

    def GetToolBar(self):
        return self.toolbar

    def getcurVisu(self):
        return [self.curGroupe, self.curNom, self.curObj]

    def onPosition(self, evt):
        self.gui.onPosition(' x: ' + str(evt.xdata)[:6] + ' y: ' +
                            str(evt.ydata)[:6])

    def delAllObjects(self):
        for v in self.listeZone:
            self.listeZone[v] = []
            self.listeZoneText[v] = []
        self.cnv.lines = []
        self.cnv.collections = []
        self.cnv.artists = []
        self.cnv.images = []
        self.cnv.cla()
        self.draw()

    def setVisu(self, core):
        """creer les objets graphiques a partir des caracteristiques d'un modele
        importe.
        creer les zones avec setAllzones, puis le contour et les vectors ecoult,
        les lignes etle contour pour tracer, contour pour reaction
        depend de l'etat du systeme de la liste graphique
        comme ca tout ca pourra etre visualise sans faire de nouveau calcul
        """
        self.delAllObjects()
        for mod in self.core.modelList:
            self.setAllZones(core.diczone[mod].dic)
        self.initDomain()
        self.draw()

    def setDataOn(self, bool):
        """definit l'affichage ou non des donnees qaund contour"""
        self.dataon = bool

    def redraw(self):
        #self.cnv.set_xlim(self.xlim)
        #self.cnv.set_ylim(self.ylim)
        self.draw()

#    def changeTitre(self,titre):
#        s='';ori=self.curOri
#        if ori in ['X','Y','Z']:
#            plan=self.curPlan;
#            x1,y1 = self.model.Aquifere.getXYticks()
#            zl = self.model.Aquifere.getParm('zList')
#        if ori=='Z': s=' Z = '+ str(zl[plan])
#        if ori=='X': s=' X = '+ str(x1[plan])
#        if ori=='Y': s=' Y = '+ str(y1[plan])
#        pl.title(self.traduit(str(titre))+s[:9],fontsize=20)

    def createAndShowObject(self, dataM, dataV, opt, value=None, color=None):
        """create the Contour, Vector, opt is contour or vector
        """
        if dataM == None: self.drawContour(False)
        else: self.createContour(dataM, value, color)
        if dataV == None: self.drawVector(False)
        else: self.createVector(dataV)

    def drawObject(self, typObj, bool):
        if typObj == 'Map' and self.Map == None and bool == False: return
        exec('self.draw' + typObj + '(' + str(bool) + ')')

    def changeObject(self, groupe, name, value, color):
        if name == 'Grid': self.changeGrid(color)
        elif name == 'Particles':
            self.changeParticles(value=value, color=color)
        elif name == 'Veloc-vect':
            self.changeVector(value, color)
            #elif name=='Visible': self.changeData(value,color)
        else:
            self.changeContour(value, color)

    #####################################################################
    #             Gestion de l'affichage de la grid/map
    #####################################################################
    # methode qui change la taille du domaine d'etude (les values de l'axe
    # de la figure matplotlib en fait) et la taille des cellules d'etude
    def initDomain(self):
        # change value of the axes
        grd = self.core.addin.getFullGrid()
        self.xlim = (grd['x0'], grd['x1'])
        self.ylim = (grd['y0'], grd['y1'])
        p, = pl.plot([0, 1], 'b')
        p.set_visible(False)
        self.transform = p.get_transform()
        self.cnv.set_xlim(self.xlim)
        self.cnv.set_ylim(self.ylim)
        self.createGrid()
        # add basic vector as a linecollection
        dep = rand(2, 2) * 0.
        arr = dep * 1.
        self.Vector = LineCollection(zip(dep, arr))
        self.Vector.set_transform(self.transform)
        self.Vector.set_visible(False)
        #pl.setp(lc,linewidth=.5);
        self.cnv.collections.append(self.Vector)
        self.Vector.data = [0, 0, None, None]


#    def changeDomain(self):
#        self.changeAxesOri('Z',0)
#

    def changeAxesOri(self, ori):
        # change orientation de la visu
        zb = self.core.Zblock
        zlim = (amin(zb), amax(zb))
        if ori == 'Z':
            self.cnv.set_xlim(self.xlim)
            self.cnv.set_ylim(self.ylim)
        elif ori == 'X':
            self.cnv.set_xlim(self.ylim)
            self.cnv.set_ylim(zlim)
        elif ori == 'Y':
            self.cnv.set_xlim(self.xlim)
            self.cnv.set_ylim(zlim)
        self.draw()

    def createGrid(self, col=None):
        if self.Grid == None:
            col = (.6, .6, .6)
            self.Grid = [0, 0, col]
            #self.cnv.collections=[0,0];
        else:
            for i in range(2):
                self.Grid[i].set_visible(False)
        if col == None: col = self.Grid[2]
        else: self.Grid[2] = col
        #print 'create grid',self.Grid,col
        nx, ny, xt, yt = getXYvects(self.core)
        #print 'visu,grid',nx,ny,xt,yt
        if len(self.cnv.collections) < 2: self.cnv.collections = [0, 0]
        l = len(ravel(xt))
        dep = concatenate([xt.reshape((l, 1)), ones((l, 1)) * min(yt)], axis=1)
        arr = concatenate([xt.reshape((l, 1)), ones((l, 1)) * max(yt)], axis=1)
        self.Grid[0] = LineCollection(zip(dep, arr))
        self.cnv.collections[0] = self.Grid[0]
        l = len(ravel(yt))
        dep = concatenate([ones((l, 1)) * min(xt), yt.reshape((l, 1))], axis=1)
        arr = concatenate([ones((l, 1)) * max(xt), yt.reshape((l, 1))], axis=1)
        self.Grid[1] = LineCollection(zip(dep, arr))
        self.cnv.collections[1] = self.Grid[1]
        for i in [0, 1]:
            self.Grid[i].set_transform(self.transform)
            self.Grid[i].set_color(col)
        self.redraw()

    def drawGrid(self, bool):  # works only to remove not to recreate
        col = self.Grid[2]
        for i in [0, 1]:
            self.Grid[i].set_visible(bool)
            self.Grid[i].set_color(col)
        self.redraw()

    def changeGrid(self, color):
        a = color.Get()
        col = (a[0] / 255, a[1] / 255, a[2] / 255)
        for i in [0, 1]:
            self.Grid[i].set_color(col)
        self.Grid[2] = col
        self.redraw()

    #####################################################################
    #             Affichage d'une variable sous forme d'image
    #####################################################################
    # l'image se met en position 1 dans la liste des images
    def createMap(self):
        file = self.gui.map
        mat = Im.imread(file)
        org = 'upper'
        ext = (self.xlim[0], self.xlim[1], self.ylim[0], self.ylim[1])
        self.Map = pl.imshow(mat,
                             origin=org,
                             extent=ext,
                             aspect='auto',
                             interpolation='nearest')
        self.cnv.images = [self.Map]  #
        self.cnv.images[0].set_visible(True)
        self.redraw()

    def drawMap(self, bool):
        if self.Map == None: self.createMap()
        #        self.Map.set_visible(bool)
        self.cnv.images = [self.Map]  #
        self.cnv.images[0].set_visible(bool)
        self.redraw()

    def createImage(self, data):
        #print 'vis img',len(xt),len(yt),shape(mat)
        X, Y, Z = data
        image = pl.pcolormesh(X, Y, Z)  #,norm='Normalize')
        self.cnv.images = [image]
        self.redraw()

    def drawImage(self, bool):
        if len(self.cnv.images) > 0:
            self.cnv.images[0].set_visible(bool)
            self.redraw()

    #####################################################################
    #             Gestion de l'affichage des contours
    #####################################################################

    def createContour(self, data, value=None, col=None):
        """ calcul des contour sa partir de value : value[0] : min
        [1] : max, [2] nb contours, [3] decimales, [4] : 'lin' log' ou 'fix',
        si [4]:fix, alors [5] est la serie des values de contours"""
        X, Y, Z = data
        #print 'visu controu',value,col
        self.cnv.collections = self.cnv.collections[:3]
        self.cnv.artists = []
        V = 11
        Zmin = amin(amin(Z))
        Zmax = amax(amax(Z * (Z < 1e5)))
        if Zmax == Zmin:  # test min=max -> pas de contour
            self.gui.onMessage(' values all equal to ' + str(Zmin))
            return
        if value == None:
            value = [Zmin, Zmax, (Zmax - Zmin) / 10., 2, 'auto', []]
        # adapter le namebre et la value des contours
        val2 = [float(a) for a in value[:3]]
        if value[4] == 'log':  # cas echelle log
            n = int((log10(val2[1]) - log10(max(val2[0], 1e-4))) / val2[2]) + 1
            V = logspace(log10(max(val2[0], 1e-4)), log10(val2[1]), n)
        elif (value[4]
              == 'fix') and (value[5] != None):  # fixes par l'utilisateur
            V = value[5] * 1
            V.append(V[-1] * 2.)
            n = len(V)
        elif value[4] == 'lin':  # cas echelle lineaire
            n = int((val2[1] - val2[0]) / val2[2]) + 1
            V = linspace(val2[0], val2[1], n)
        else:  # cas automatique
            n = 11
            V = linspace(Zmin, Zmax, n)
        # ONE DIMENSIONAL
        r, c = shape(X)
        if r == 1:
            X = concatenate([X, X])
            Y = concatenate([Y - Y * .45, Y + Y * .45])
            Z = concatenate([Z, Z])
        Z2 = ma.masked_where(Z.copy() > 1e5, Z.copy())
        #print value,n,V
        # definir les couleurs des contours
        if col == None:  # or (col==[(0,0,0),(0,0,0),(0,0,0),10]):
            cf = pl.contourf(pl.array(X), pl.array(Y), Z2, V)
            c = pl.contour(pl.array(X), pl.array(Y), Z2, V)
            col = [(0, 0, 255), (0, 255, 0), (255, 0, 0), 10]
        else:
            r, g, b = [], [], []
            lim=((0.,1.,0.,0.),(.1,1.,0.,0.),(.25,.8,0.,0.),(.35,0.,.8,0.),(.45,0.,1.,0.),\
                 (.55,0.,1.,0.),(.65,0.,.8,0.),(.75,0.,0.,.8),(.9,0.,0.,1.),(1.,0.,0.,1.))
            for i in range(len(lim)):
                c1 = lim[i][1] * col[0][0] / 255. + lim[i][2] * col[1][
                    0] / 255. + lim[i][3] * col[2][0] / 255.
                r.append((lim[i][0], c1, c1))
                c2 = lim[i][1] * col[0][1] / 255. + lim[i][2] * col[1][
                    1] / 255. + lim[i][3] * col[2][1] / 255.
                g.append((lim[i][0], c2, c2))
                c3 = lim[i][1] * col[0][2] / 255. + lim[i][2] * col[1][
                    2] / 255. + lim[i][3] * col[2][2] / 255.
                b.append((lim[i][0], c3, c3))
            cdict = {'red': r, 'green': g, 'blue': b}
            my_cmap = mpl.colors.LinearSegmentedColormap(
                'my_colormap', cdict, 256)
            cf = pl.contourf(pl.array(X), pl.array(Y), Z2, V, cmap=my_cmap)
            c = pl.contour(pl.array(X), pl.array(Y), Z2, V, cmap=my_cmap)
        #print col[3]
        for c0 in cf.collections:
            c0.set_alpha(int(col[3]) / 100.)
            #print cl
        if value == None: fmt = '%1.3f'
        else: fmt = '%1.' + str(value[3]) + 'f'
        cl = pl.clabel(c, color='black', fontsize=9, fmt=fmt)
        self.Contour = c
        self.ContourF = cf
        self.ContourLabel = cl
        self.Contour.data = data
        self.redraw()

    def changeContour(self, value, col):
        """ modifie les values d'un contour existant"""
        self.drawContour(False)
        self.createContour(self.Contour.data, value, col)

    def drawContour(self, bool):
        self.cnv.collections = self.cnv.collections[:3]
        self.cnv.artists = []
        self.draw()
        #~ for c in self.Contour.collections :c.set_visible(False)
        #~ for c in self.ContourF.collections :c.set_visible(False)
        #~ for a in self.ContourLabel: a.set_visible(False)
        #~ #self.cnv.collections = self.cnv.collections[:3]
        #~ self.redraw()

    #####################################################################
    #             Gestion de l'affichage de vectors
    #####################################################################
    """vector has been created as the first item of lincollection list
    during domain intialization"""

    def createVector(self, data):
        X, Y, U, V = data
        """ modifie les values de vectors existants"""
        if self.Vector.data[3] == None:  #first vector no color
            ech = 1.
            col = (0, 0, 1)
        else:
            a, b, ech, col = self.Vector.data
            self.drawVector(False)
        l = len(ravel(X))
        dep = concatenate([X.reshape((l, 1)), Y.reshape((l, 1))], axis=1)
        b = X + U * ech
        c = Y + V * ech
        arr = concatenate([b.reshape((l, 1)), c.reshape((l, 1))], axis=1)
        self.Vector = LineCollection(zip(dep, arr))
        self.Vector.set_transform(self.transform)
        self.Vector.set_color(col)
        if len(self.cnv.collections) > 2: self.cnv.collections[2] = self.Vector
        else: self.cnv.collections.append(self.Vector)
        self.Vector.set_visible(True)
        self.Vector.data = [dep, arr, ech, col]
        #print self.Vector.data
        self.redraw()

    def drawVector(self, bool):
        """ dessine les vectors vitesse a partir de x,y,u,v et du
        booleen qui dit s'il faut dessiner ou non """
        self.Vector.set_visible(bool)
        self.redraw()

    def changeVector(self, ech, col=wx.Color(0, 0, 255)):
        """ modifie les values de vectors existants"""
        #self.drawVector(False)
        ech = float(ech)
        #change coordinates
        dep, arr_old, ech_old, col_old = self.Vector.data
        #print shape(dep),shape(arr_old),ech,ech_old
        arr = dep + (arr_old - dep) * ech / ech_old
        # new object
        #self.Vector = LineCollection(zip(dep,arr))
        self.Vector.set_segments(zip(dep, arr))
        #self.Vector.set_transform(self.transform)
        a = col.Get()
        col = (a[0] / 255, a[1] / 255, a[2] / 255)
        self.Vector.set_color(col)
        self.Vector.set_visible(True)
        #self.cnv.collections[2]=self.Vector
        self.Vector.data = [dep, arr, ech, col]
        self.redraw()

    #####################################################################
    #             Gestion de l'affichage de particules
    #####################################################################
    def startParticles(self):
        if self.Particles != None:
            self.partVisible(False)
        self.Particles = {
            'line': [],
            'txt': [],
            'data': [],
            'color': wx.Color(255, 0, 0)
        }
        self.mpl_disconnect(self.toolbar._idPress)
        self.mpl_disconnect(self.toolbar._idRelease)
        self.mpl_disconnect(self.toolbar._idDrag)
        # on capte le clic gauche de la souris
        self.m3 = self.mpl_connect('button_press_event', self.mouseParticles)
        self.stop = False
        #self.createParticles()
        #wx.EVT_LEAVE_WINDOW(self,self.finParticules)  # arrete particules qd on sort de visu

    def mouseParticles(self, evt):
        #test pour savoir si le curseur est bien dans les axes de la figure
        if self.stop: return
        if evt.inaxes is None: return
        if evt.button == 1:
            [xp, yp, tp] = self.core.addin.calcParticle(evt.xdata, evt.ydata)
            #print xp,yp,tp
            self.updateParticles(xp, yp, tp)
        elif evt.button == 3:
            self.mpl_disconnect(self.m3)
            self.stop = True
            self.gui.actions('zoneEnd')

    def updateParticles(self, X, Y, T, freq=10):
        """ rajouter une ligne dans le groupe de particules"""
        ligne, = pl.plot(pl.array(X), pl.array(Y), 'r')
        if freq > 0:
            tx, ty, tt = X[0::freq], Y[0::freq], T[0::freq]
            txt = []
            for i in range(len(tx)):
                a = str(tt[i])
                b = a.split('.')
                ln = max(4, len(b[0]))
                txt.append(pl.text(tx[i], ty[i], a[:ln], fontsize='8'))
        self.Particles['line'].append(ligne)
        self.Particles['txt'].append(txt)
        self.Particles['data'].append((X, Y, T))
        self.gui_repaint()  # bug matplotlib v2.6 for direct draw!!!
        self.draw()

    def drawParticles(self, bool, value=None):
        if self.Particles == None: return
        self.partVisible(bool)
        self.gui_repaint()
        self.draw()

    def changeParticles(self, value=None, color=wx.Color(255, 0, 0)):
        self.partVisible(False)
        self.Particles['color'], self.Particles['txt'] = color, []
        for i, data in enumerate(self.Particles['data']):
            X, Y, T = data
            tx, ty, tt = self.ptsPartic(X, Y, T, float(value))
            txt = []
            for i in range(len(tx)):
                a = str(tt[i])
                b = a.split('.')
                ln = max(4, len(b[0]))
                txt.append(pl.text(tx[i], ty[i], a[:ln], fontsize='8'))
            self.Particles['txt'].append(txt)
        self.partVisible(True)
        self.gui_repaint()
        self.draw()

    def partVisible(self, bool):
        a = self.Particles['color'].Get()
        color = (a[0] / 255, a[1] / 255, a[2] / 255)
        for line in self.Particles['line']:
            line.set_visible(bool)
            line.set_color(color)
        for points in self.Particles['txt']:
            for txt in points:
                txt.set_visible(bool)

    def ptsPartic(self, X, Y, T, dt):
        #tx,ty,tt,i1=iphtC1.ptsLigne(X,Y,T,dt);
        tmin = amin(T)
        tmax = amax(T)
        t1 = linspace(tmin, tmax, int((tmax - tmin) / dt))
        f = interp1d(T, X)
        xn = f(t1)
        f = interp1d(T, Y)
        yn = f(t1)
        return xn, yn, t1

    #####################################################################
    #                   Gestion des zones de la visu
    #####################################################################
    # affichage de toutes les zones d'une variable
    def showVar(self, var, media):
        self.setUnvisibleZones()
        self.curVar, self.curMedia = var, media
        for i in range(len(self.listeZone[var])):
            #print 'vis showvar',self.listeZmedia[var][i]
            if (media in self.listeZmedia[var][i]) or (media == -1):
                self.listeZone[var][i].set_visible(True)
                self.visibleText(self.listeZoneText[var][i], True)
        #self.changeTitre(var)
        self.redraw()

    def showData(self, liForage, liData):
        self.setUnvisibleZones()
        self.curVar = 'data'
        self.listeZoneText['data'] = []
        for zone in self.listeZone['Forages']:
            zone.set_visible(True)
        lZone = self.model.Aquifere.getZoneList('Forages')
        txt = []
        for z in lZone:
            x, y = zip(*z.getXy())
            name = z.getNom()
            if name in liForage:
                ind = liForage.index(name)
                txt.append(
                    pl.text(mean(x), mean(y), name + '\n' + str(liData[ind])))
        obj = GraphicObject('zoneText', txt, True, None)
        self.addGraphicObject(obj)
        self.redraw()

    def changeData(self, taille, col):
        obj = self.listeZoneText['data'][0].getObject()
        for txt in obj:
            txt.set_size(taille)
            txt.set_color(col)

    def getcurZone(self):
        return self.curZone

    def setcurZone(self, zone):
        self.curZone = zone

    # methode qui efface toutes les zones de toutes les variables
    def setUnvisibleZones(self):
        for v in self.listeZone:
            for zone in self.listeZone[v]:
                zone.set_visible(False)
            for txt in self.listeZoneText[v]:
                if type(txt) == type([5, 6]):
                    for t in txt:
                        t.set_visible(False)
                else:
                    txt.set_visible(False)

    # methode appelee par la GUI lorsqu'on veut creer une nouvelle zone
    def setZoneReady(self, typeZone, curVar):
        self.typeZone = typeZone
        self.curVar = curVar
        self.tempZoneVal = []
        # on deconnecte la toolbar pour activer la formaiton de zones
        self.mpl_disconnect(self.toolbar._idPress)
        self.mpl_disconnect(self.toolbar._idRelease)
        self.mpl_disconnect(self.toolbar._idDrag)
        # on capte le clic gauche de la souris
        self.m1 = self.mpl_connect('button_press_event', self.mouse_clic)

    def setZoneEnd(self, evt):
        # on informe la GUI qui informera le model
        xv, yv = self.getcurZone().get_xdata(), self.getcurZone().get_ydata()
        if len(self.tempZoneVal) > 1: xy = zip(xv, yv, self.tempZoneVal)
        else: xy = zip(xv, yv)
        # effacer zone pour si cancel, remettre de l'ordre
        self.curZone.set_visible(False)
        self.curZone = None
        self.x1, self.y1 = [], []
        self.gui.addBox.onZoneCreate(self.typeZone, xy)

    def addZone(self, media, name, val, coords, visible=True):
        """ ajout de la zone et du texte (name+value) sur visu 
        """
        #print 'visu',coords
        a = zip(*coords)
        txt = []
        #print name,a
        if len(a) == 0: return
        if len(a) == 2: x, y = a
        elif len(a) == 3: x, y, z = a
        if len(x) == 1:
            zone = Line2D(x, y, marker='+', markersize=10, markeredgecolor='r')
        else:
            zone = Line2D(x, y)
        zone.verts = coords
        zone.set_visible(visible)
        if type(media) != type([2]): media = [int(media)]
        self.curMedia = media
        self.cnv.add_line(zone)
        if self.typeZone == "POLYV" or len(coords[0]) == 3:
            txt = [
                pl.text(
                    mean(x) * .1 + x[0] * .9,
                    mean(y) * .1 + y[0] * .9, name + '\n' + str(val)[:16])
            ]
            for i in range(len(x)):
                t = pl.text(x[i], y[i], str(z[i]))
                t.set_visible(visible)
                txt.append(t)
        else:
            txt = pl.text(
                mean(x) * .1 + x[0] * .9,
                mean(y) * .1 + y[0] * .9, name + '\n' + str(val)[:16])
        self.listeZone[self.curVar].append(zone)
        self.listeZmedia[self.curVar].append(media)
        self.listeZoneText[self.curVar].append(txt)
        if visible: self.redraw()

    def delZone(self, Variable, ind):
        """methode de suppression de la zone d'indice ind de Variable
        """
        if self.listeZone.has_key(Variable) == False: return
        if len(self.listeZone[Variable]) > ind:
            self.listeZone[Variable][ind].set_visible(False)
            self.visibleText(self.listeZoneText[Variable][ind], False)
            self.listeZone[Variable][ind:ind + 1] = []
            self.listeZoneText[Variable][ind:ind + 1] = []
            self.listeZmedia[Variable].pop(ind)
            self.redraw()

    def visibleText(self, text, bool):
        if type(text) == type([5, 6]):
            for t in text:
                t.set_visible(bool)
        else:
            text.set_visible(bool)

    def delAllZones(self, Variable):
        lz = self.listeZone[Variable]
        for i in range(len(lz)):
            lz[i].setVisible(False)
            self.listeZoneText[Variable][i].set_visible(False)
        self.listeZone[Variable] = []
        self.listeZmedia[Variable] = []
        self.listeZoneText[Variable] = []
        self.redraw()

    def modifValZone(self, nameVar, ind, val, xy):
        """modify the value (or list of value) for the zone nameVar 
        the text contains name et value"""

    def modifZoneAttr(self, nameVar, ind, val, media, xy):
        # modify xy
        zone = self.listeZone[nameVar][ind]
        if len(xy[0]) == 3: x, y, z = zip(*xy)
        else: x, y = zip(*xy)
        zone.set_data(x, y)
        # modify media
        if type(media) != type([2]): media = [int(media)]
        self.listeZmedia[nameVar][ind] = media
        # modify text
        textObj = self.listeZoneText[nameVar][ind]
        if type(textObj) == type([2, 3]):
            name = pl.getp(textObj[0], 'text').split('\n')[0]
            pl.setp(textObj[0], text=name + '\n' + str(val)[:16])
            for i in range(len(z)):
                pl.setp(textObj[i + 1], text=str(z[i]))
        else:
            name = pl.getp(textObj, 'text').split('\n')[0]
            pl.setp(textObj, text=name + '\n' + str(val)[:16])
        self.redraw()

    def modifZone(self, nameVar, ind):
        """ modification interactive des points de la zone d'indice ind de name nameVar
        """
        zone = self.listeZone[nameVar][ind]
        self.polyInteract = PolygonInteractor(self, zone, nameVar, ind)
        zone.set_visible(False)
        self.cnv.add_line(self.polyInteract.line)
        self.draw()

    def finModifZone(self):
        """fonction qui met fin a la modification de la zone courante"""
        if self.polyInteract != None:
            self.polyInteract.set_visible(False)
            self.polyInteract.disable()
            # on informe la GUI des nouvelles coordonnees
            var, ind = self.polyInteract.typeVariable, self.polyInteract.ind
            x, y = self.polyInteract.lx, self.polyInteract.ly
            #print x,y
            xy = zip(x, y)
            self.gui.modifBox.onModifZoneCoord(var, ind, xy)
            zone = self.listeZone[var][ind]
            zone.set_data(x, y)
            zone.set_visible(True)
            # on modifie la position du texte
            txt = self.listeZoneText[var][ind]
            if type(txt) == type([5, 6]):
                txt[0].set_position((x[0], y[0]))
                for i in range(1, len(txt)):
                    txt[i].set_position((x[i - 1], y[i - 1]))
            else:
                txt.set_position(
                    (mean(x) * .1 + x[0] * .9, mean(y) * .1 + y[0] * .9))
            self.draw()

    def setAllZones(self, dicZone):
        """updates all zones when a file is imported
        """
        for var in dicZone.keys():
            self.listeZone[var] = []
            self.curVar = var
            lz = dicZone[var]
            nbz = len(lz['name'])
            for i in range(nbz):
                if lz['name'][i] == '': continue
                coords = lz['coords'][i]
                self.addZone(lz['media'][i], lz['name'][i], lz['value'][i],
                             coords)
        self.setUnvisibleZones()
        #self.redraw()

    #####################################################################
    #             Gestion de l'interaction de la souris
    #             pour la creation des zones
    #####################################################################

    #methode executee lors d'un clic de souris dans le canvas
    def mouse_clic(self, evt):
        if evt.inaxes is None:
            return
        if self.curZone == None:  # au depart
            self.x1 = [float(str(evt.xdata)[:6])
                       ]  # pour aovir chiffre pas trop long
            self.y1 = [float(str(evt.ydata)[:6])]
            self.setcurZone(Line2D(self.x1, self.y1))
            self.cnv.add_line(self.curZone)
            self.m2 = self.mpl_connect('motion_notify_event',
                                       self.mouse_motion)
            if self.typeZone == "POLYV":
                self.polyVdialog()
            if self.typeZone == "POINT":
                self.deconnecte()
                self.setZoneEnd(evt)

        else:  # points suivants
            if self.typeZone == "POLYV":  # and evt.button ==1:
                if evt.button == 3: self.deconnecte()
                rep = self.polyVdialog()  # dialog for the current value of z
                if rep == False: return
            self.x1.append(float(str(evt.xdata)[:6]))
            self.y1.append(float(str(evt.ydata)[:6]))
            if self.typeZone == "LINE" or self.typeZone == "RECT":
                self.deconnecte()  #fin des le 2eme point
                self.setZoneEnd(evt)
            if self.typeZone in ["POLY", "POLYV"
                                 ] and evt.button == 3:  # fin du polygone
                self.deconnecte()
                self.setZoneEnd(evt)

    #methode executee lors du deplacement de la souris dans le canvas suite a un mouse_clic
    def mouse_motion(self, evt):
        time.sleep(0.1)
        if evt.inaxes is None: return
        lx, ly = self.x1 * 1, self.y1 * 1
        if self.typeZone == "RECT":
            xr, yr = self.creeRectangle(self.x1[0], self.y1[0], evt.xdata,
                                        evt.ydata)
            self.curZone.set_data(xr, yr)
        else:  # autres cas
            lx.append(evt.xdata)
            ly.append(evt.ydata)
            self.curZone.set_data(lx, ly)
        self.draw()

    def polyVdialog(self):
        lst0 = [('Value', 'Text', 0)]
        dialg = config.dialogs.genericDialog(self.gui, 'value', lst0)
        values = dialg.getValues()
        if values != None:
            val = float(values[0])
            #print val*2
            self.tempZoneVal.append(val)
            return True
        else:
            return False

    def creeRectangle(self, x1, y1, x2, y2):
        xr = [x1, x2, x2, x1, x1]
        yr = [y1, y1, y2, y2, y1]
        return [xr, yr]

    def deconnecte(self):
        # deconnecter la souris
        self.mpl_disconnect(self.m1)
        self.mpl_disconnect(self.m2)

    ###################################################################
    #   deplacer une zone ##############################

    def startMoveZone(self, nameVar, ind):
        """ methode qui demarre les interactions avec la souris"""
        # reperer la zone et rajouter un point de couleur
        self.nameVar, self.ind = nameVar, ind
        zone = self.listeZone[nameVar][ind]
        self.curZone = zone
        self.lx, self.ly = zone.get_xdata(), zone.get_ydata()
        self.xstart = self.lx[0] * 1.
        self.ystart = self.ly[0] * 1.
        self.ptstart = Line2D([self.xstart], [self.ystart],
                              marker='o',
                              markersize=7,
                              markerfacecolor='r')
        self.cnv.add_line(self.ptstart)
        self.m1 = self.mpl_connect('button_press_event', self.zoneM_clic)
        self.draw()

    def zoneM_clic(self, evt):
        """ action au premier clic"""
        if evt.inaxes is None: return
        #if evt.button==3: self.finMoveZone(evt) # removed OA 6/2/13
        d = sqrt((evt.xdata - self.xstart)**2 + (evt.ydata - self.ystart)**2)
        xmn, xmx = self.xlim
        ymn, ymx = self.ylim
        dmax = sqrt((xmx - xmn)**2 + (ymx - ymn)**2) / 100
        if d > dmax: return
        self.m2 = self.mpl_connect('motion_notify_event', self.zone_motion)
        self.m3 = self.mpl_connect('button_release_event', self.finMoveZone)
        self.mpl_disconnect(self.m1)

    def zone_motion(self, evt):
        """ methode pour deplacer la zone quand on deplace la souris"""
        # reperer le curseur proche du point de couleur
        time.sleep(0.1)
        if evt.inaxes is None: return
        # changer els coord du polygone lorsque l'on deplace la souris
        lx = [a + evt.xdata - self.xstart for a in self.lx]
        ly = [a + evt.ydata - self.ystart for a in self.ly]
        self.ptstart.set_data(lx[0], ly[0])
        self.curZone.set_data(lx, ly)
        self.draw()

    def finMoveZone(self, evt):
        """ methode pour arret de deplacement de la zone"""
        # lorsque l'on relache la souris arreter les mpl connect
        self.mpl_disconnect(self.m2)
        self.mpl_disconnect(self.m3)
        # renvoyer les nouvelels coordonnes au modele
        lx, ly = self.curZone.get_xdata(), self.curZone.get_ydata()
        self.listeZone[self.nameVar][self.ind].set_data(lx, ly)
        xy = zip(lx, ly)
        self.gui.modifBox.onModifZoneCoord(self.nameVar, self.ind, xy)
        # on modifie la position du texte
        txt = self.listeZoneText[self.nameVar][self.ind]
        if type(txt) == type([5, 6]):
            txt[0].set_position((lx[0], ly[0]))
            for i in range(1, len(txt)):
                txt[i].set_position(
                    (lx[i - 1],
                     ly[i - 1]))  #-1 because 1st position zone names
        else:
            txt.set_position(
                (mean(lx) * .1 + lx[0] * .9, mean(ly) * .1 + ly[0] * .9))
        self.ptstart.set_visible(False)
        self.ptstart = None
        self.curZone = None
        self.draw()
Exemple #23
0
def plot_day_summary2_ohlc(ax, opens, highs, lows, closes, ticksize=4,
                          colorup='k', colordown='r',
                          ):

    """Represent the time, open, high, low, close as a vertical line
    ranging from low to high.  The left tick is the open and the right
    tick is the close.
    *opens*, *highs*, *lows* and *closes* must have the same length.
    NOTE: this code assumes if any value open, high, low, close is
    missing (*-1*) they all are missing

    Parameters
    ----------
    ax : `Axes`
        an Axes instance to plot to
    opens : sequence
        sequence of opening values
    highs : sequence
        sequence of high values
    lows : sequence
        sequence of low values
    closes : sequence
        sequence of closing values
    ticksize : int
        size of open and close ticks in points
    colorup : color
        the color of the lines where close >= open
    colordown : color
         the color of the lines where close <  open

    Returns
    -------
    ret : list
        a list of lines added to the axes
    """

    _check_input(opens, highs, lows, closes)

    rangeSegments = [((i, low), (i, high)) for i, low, high in
                     zip(xrange(len(lows)), lows, highs) if low != -1]

    # the ticks will be from ticksize to 0 in points at the origin and
    # we'll translate these to the i, close location
    openSegments = [((-ticksize, 0), (0, 0))]

    # the ticks will be from 0 to ticksize in points at the origin and
    # we'll translate these to the i, close location
    closeSegments = [((0, 0), (ticksize, 0))]

    offsetsOpen = [(i, open) for i, open in
                   zip(xrange(len(opens)), opens) if open != -1]

    offsetsClose = [(i, close) for i, close in
                    zip(xrange(len(closes)), closes) if close != -1]

    scale = ax.figure.dpi * (1.0 / 72.0)

    tickTransform = Affine2D().scale(scale, 0.0)

    colorup = mcolors.to_rgba(colorup)
    colordown = mcolors.to_rgba(colordown)
    colord = {True: colorup, False: colordown}
    colors = [colord[open < close] for open, close in
              zip(opens, closes) if open != -1 and close != -1]

    useAA = 0,   # use tuple here
    lw = 1,      # and here
    rangeCollection = LineCollection(rangeSegments,
                                     colors=colors,
                                     linewidths=lw,
                                     antialiaseds=useAA,
                                     )

    openCollection = LineCollection(openSegments,
                                    colors=colors,
                                    antialiaseds=useAA,
                                    linewidths=lw,
                                    offsets=offsetsOpen,
                                    transOffset=ax.transData,
                                    )
    openCollection.set_transform(tickTransform)

    closeCollection = LineCollection(closeSegments,
                                     colors=colors,
                                     antialiaseds=useAA,
                                     linewidths=lw,
                                     offsets=offsetsClose,
                                     transOffset=ax.transData,
                                     )
    closeCollection.set_transform(tickTransform)

    minpy, maxx = (0, len(rangeSegments))
    miny = min([low for low in lows if low != -1])
    maxy = max([high for high in highs if high != -1])
    corners = (minpy, miny), (maxx, maxy)
    ax.update_datalim(corners)
    ax.autoscale_view()

    # add these last
    ax.add_collection(rangeCollection)
    ax.add_collection(openCollection)
    ax.add_collection(closeCollection)
    return rangeCollection, openCollection, closeCollection