Example #1
0
def bode(w,H,win=0,frame=0,lcolor='blue',color='black',tcolor='black',freq='rad'):
    """Plot a bode plot of the transfer function H as a function of w.
    """
    if freq == 'Hz':
        w = w /2.0 / pi
    subplot(2,1,win,hsep=120,frame=frame,color=color)
    gist.plsys(1)
    gist.plg(20*numpy.log10(abs(H)),w,type='solid',color=lcolor,marks=0)
    gist.logxy(1,0)
    gist.gridxy(1,1)
    if freq == 'Hz':
        xlabel('Frequency (Hz)',color=tcolor,deltay=-0.005)
    else:
        xlabel('Frequency (rad/s)',color=tcolor,deltay=-0.005)
    ylabel('Magnitude (dB)',color=tcolor,deltax=-0.005)
    title("Bode Plot",color=tcolor)
    gist.plsys(2)
    gist.plg(180/pi*numpy.unwrap(MLab.angle(H)),w,type='solid',color=lcolor,marks=0)
    gist.logxy(1,0)
    gist.gridxy(1,1)
    if freq == 'Hz':
        xlabel('Frequency (Hz)',color=tcolor,deltay=-0.005)
    else:
        xlabel('Frequency (rad/s)',color=tcolor,deltay=-0.005)
    ylabel('Phase (deg.)',color=tcolor,deltax=-0.005)
Example #2
0
def bode(w,H,win=0,frame=0,lcolor='blue',color='black',tcolor='black',freq='rad'):
    """Plot a bode plot of the transfer function H as a function of w.
    """
    if freq == 'Hz':
        w = w /2.0 / pi
    subplot(2,1,win,hsep=120,frame=frame,color=color)
    gist.plsys(1)
    gist.plg(20*numpy.log10(abs(H)),w,type='solid',color=lcolor,marks=0)
    gist.logxy(1,0)
    gist.gridxy(1,1)
    if freq == 'Hz':
        xlabel('Frequency (Hz)',color=tcolor,deltay=-0.005)
    else:
        xlabel('Frequency (rad/s)',color=tcolor,deltay=-0.005)
    ylabel('Magnitude (dB)',color=tcolor,deltax=-0.005)
    title("Bode Plot",color=tcolor)
    gist.plsys(2)
    gist.plg(180/pi*numpy.unwrap(numpy.angle(H)),w,type='solid',color=lcolor,marks=0)
    gist.logxy(1,0)
    gist.gridxy(1,1)
    if freq == 'Hz':
        xlabel('Frequency (Hz)',color=tcolor,deltay=-0.005)
    else:
        xlabel('Frequency (rad/s)',color=tcolor,deltay=-0.005)
    ylabel('Phase (deg.)',color=tcolor,deltax=-0.005)
Example #3
0
def imagesc(z,cmin=None,cmax=None,xryr=None,_style='default', palette=None,
            color='black',colormap=None):
    """Plot an image on axes.

    z -- The data
    cmin -- Value to map to lowest color in palette (min(z) if None)
    cmax -- Value to map to highest color in palette (max(z) if None)
    xryr -- (xmin, ymin, xmax, ymax) coordinates to print
            (0, 0, z.shape[1], z.shape[0]) if None
    _style -- A 'style-sheet' to use if desired (a default one will be used
              if 'default').  If None, then no style will be imposed.
    palette -- A string for a palette previously saved in a file (see write_palette)
               or an array specifying the red-green-blue values (2-d array N x 3) or
               gray-scale values (2-d array N x 1 or 1-d array).
    color -- The color to use for the axes.
    """
    if xryr is None:
        xryr = (0,0,z.shape[1],z.shape[0])
    try:
        _style = None
        saveval = gist.plsys(2)
        gist.plsys(saveval)
    except:
        _style = 'default'
        if not _hold:
            gist.fma()
        gist.animate(0)

    if _style is not None:
        if _style == "default":
            _style=os.path.join(_user_path,'image.gs')
            system = write_style.getsys(hticpos='below',vticpos='left',frame=1,
                                        color=color)
            fid = open(_style,'w')
            fid.write(write_style.style2string(system))
            fid.close()
        gist.window(style=_style)
        _current_style=_style
    if cmax is None:
        cmax = max(ravel(z))
    if cmin is None:
        cmin = min(ravel(z))
    cmax = float(cmax)
    cmin = float(cmin)
    byteimage = gist.bytscl(z,cmin=cmin,cmax=cmax)
    if (colormap is not None): palette=colormap
    change_palette(palette)
    gist.pli(byteimage,xryr[0],xryr[1],xryr[2],xryr[3])
    return
Example #4
0
def imagesc(z,cmin=None,cmax=None,xryr=None,_style='default', palette=None,
            color='black',colormap=None):
    """Plot an image on axes.

    z -- The data
    cmin -- Value to map to lowest color in palette (min(z) if None)
    cmax -- Value to map to highest color in palette (max(z) if None)
    xryr -- (xmin, ymin, xmax, ymax) coordinates to print
            (0, 0, z.shape[1], z.shape[0]) if None
    _style -- A 'style-sheet' to use if desired (a default one will be used
              if 'default').  If None, then no style will be imposed.
    palette -- A string for a palette previously saved in a file (see write_palette)
               or an array specifying the red-green-blue values (2-d array N x 3) or
               gray-scale values (2-d array N x 1 or 1-d array).
    color -- The color to use for the axes.
    """
    if xryr is None:
        xryr = (0,0,z.shape[1],z.shape[0])
    try:
        _style = None
        saveval = gist.plsys(2)
        gist.plsys(saveval)
    except:
        _style = 'default'
        if not _hold:
            gist.fma()
        gist.animate(0)

    if _style is not None:
        if _style == "default":
            _style=os.path.join(_user_path,'image.gs')
            system = write_style.getsys(hticpos='below',vticpos='left',frame=1,
                                        color=color)
            fid = open(_style,'w')
            fid.write(write_style.style2string(system))
            fid.close()
        gist.window(style=_style)
        _current_style=_style
    if cmax is None:
        cmax = max(ravel(z))
    if cmin is None:
        cmin = min(ravel(z))
    cmax = float(cmax)
    cmin = float(cmin)
    byteimage = gist.bytscl(z,cmin=cmin,cmax=cmax)
    if (colormap is not None): palette=colormap
    change_palette(palette)
    gist.pli(byteimage,xryr[0],xryr[1],xryr[2],xryr[3])
    return
Example #5
0
def errorbars(x,y,err,ptcolor='r',linecolor='B',pttype='o',linetype='-',fac=0.25):
    """Draw connected points with errorbars.

    Description:

      Plot connected points with errorbars.

    Inputs:

      x, y -- The points to plot.
      err -- The error in the y values.
      ptcolor -- The color for the points.
      linecolor -- The color of the connecting lines and error bars.
      pttype -- The type of point ('o', 'x', '+', '.', 'x', '*')
      linetype -- The type of line ('-', '|', ':', '-.', '-:')
      fac -- Adjusts how long the horizontal lines are which make the
             top and bottom of the error bars.
    """
    # create line arrays
    yb = y - err
    ye = y + err
    try:
        override = 1
        savesys = gist.plsys(2)
        gist.plsys(savesys)
    except:
        override = 0
    if _hold or override:
        pass
    else:
        gist.fma()
    y = where(numpy.isfinite(y),y,0)
    gist.plg(y,x,color=_colors[ptcolor],marker=_markers[pttype],type='none')
    gist.pldj(x,yb,x,ye,color=_colors[linecolor],type=_types[linetype])
    viewp = gist.viewport()
    plotlims = gist.limits()
    conv_factorx = (viewp[1] - viewp[0]) / (plotlims[1]-plotlims[0])
    conv_factory = (viewp[3] - viewp[2]) / (plotlims[3]-plotlims[2])
    width = fac*(x[1]-x[0])
    x0 = x-width/2.0
    x1 = x+width/2.0
    gist.pldj(x0,ye,x1,ye,color=_colors[linecolor],type=_types[linetype])
    gist.pldj(x0,yb,x1,yb,color=_colors[linecolor],type=_types[linetype])
    return
Example #6
0
def errorbars(x,y,err,ptcolor='r',linecolor='B',pttype='o',linetype='-',fac=0.25):
    """Draw connected points with errorbars.

    Description:

      Plot connected points with errorbars.

    Inputs:

      x, y -- The points to plot.
      err -- The error in the y values.
      ptcolor -- The color for the points.
      linecolor -- The color of the connecting lines and error bars.
      pttype -- The type of point ('o', 'x', '+', '.', 'x', '*')
      linetype -- The type of line ('-', '|', ':', '-.', '-:')
      fac -- Adjusts how long the horizontal lines are which make the
             top and bottom of the error bars.
    """
    # create line arrays
    yb = y - err
    ye = y + err
    try:
        override = 1
        savesys = gist.plsys(2)
        gist.plsys(savesys)
    except:
        override = 0
    if _hold or override:
        pass
    else:
        gist.fma()
    y = where(numpy.isfinite(y),y,0)
    gist.plg(y,x,color=_colors[ptcolor],marker=_markers[pttype],type='none')
    gist.pldj(x,yb,x,ye,color=_colors[linecolor],type=_types[linetype])
    viewp = gist.viewport()
    plotlims = gist.limits()
    conv_factorx = (viewp[1] - viewp[0]) / (plotlims[1]-plotlims[0])
    conv_factory = (viewp[3] - viewp[2]) / (plotlims[3]-plotlims[2])
    width = fac*(x[1]-x[0])
    x0 = x-width/2.0
    x1 = x+width/2.0
    gist.pldj(x0,ye,x1,ye,color=_colors[linecolor],type=_types[linetype])
    gist.pldj(x0,yb,x1,yb,color=_colors[linecolor],type=_types[linetype])
    return
Example #7
0
def stem(m, y, linetype='b-', mtype='mo', shift=0.013):
    y0 = Numeric.zeros(len(y),y.dtype.char)
    y1 = y
    x0 = m
    x1 = m
    try:
        override = 1
        savesys = gist.plsys(2)
        gist.plsys(savesys)
    except:
        override = 0
    if not (_hold or override):
        gist.fma()
    thetype,thecolor,themarker,tomark = _parse_type_arg(linetype,0)
    lcolor = thecolor
    gist.pldj(x0, y0, x1, y1, color=thecolor, type=thetype)
    thetype,thecolor,themarker,tomark = _parse_type_arg(mtype,0)
    if themarker not in ['o','x','.','*']:
        themarker = 'o'
    y = where(numpy.isfinite(y),y,0)
    gist.plg(y,m,color=thecolor,marker=themarker,type='none')
    gist.plg(Numeric.zeros(len(m)),m,color=lcolor,marks=0)
    gist.limits()
    lims = gist.limits()
    newlims = [None]*4
    vp = gist.viewport()
    factor1 = vp[1] - vp[0]
    factor2 = vp[3] - vp[2]
    cfactx = factor1 / (lims[1] - lims[0])
    cfacty = factor2 / (lims[3] - lims[2])
    d1 = shift / cfactx
    d2 = shift / cfacty
    newlims[0] = lims[0] - d1
    newlims[1] = lims[1] + d1
    newlims[2] = lims[2] - d2
    newlims[3] = lims[3] + d2
    gist.limits(*newlims)
    return
Example #8
0
def stem(m, y, linetype='b-', mtype='mo', shift=0.013):
    y0 = numpy.zeros(len(y),y.dtype.char)
    y1 = y
    x0 = m
    x1 = m
    try:
        override = 1
        savesys = gist.plsys(2)
        gist.plsys(savesys)
    except:
        override = 0
    if not (_hold or override):
        gist.fma()
    thetype,thecolor,themarker,tomark = _parse_type_arg(linetype,0)
    lcolor = thecolor
    gist.pldj(x0, y0, x1, y1, color=thecolor, type=thetype)
    thetype,thecolor,themarker,tomark = _parse_type_arg(mtype,0)
    if themarker not in ['o','x','.','*']:
        themarker = 'o'
    y = where(numpy.isfinite(y),y,0)
    gist.plg(y,m,color=thecolor,marker=themarker,type='none')
    gist.plg(numpy.zeros(len(m)),m,color=lcolor,marks=0)
    gist.limits()
    lims = gist.limits()
    newlims = [None]*4
    vp = gist.viewport()
    factor1 = vp[1] - vp[0]
    factor2 = vp[3] - vp[2]
    cfactx = factor1 / (lims[1] - lims[0])
    cfacty = factor2 / (lims[3] - lims[2])
    d1 = shift / cfactx
    d2 = shift / cfacty
    newlims[0] = lims[0] - d1
    newlims[1] = lims[1] + d1
    newlims[2] = lims[2] - d2
    newlims[3] = lims[3] + d2
    gist.limits(*newlims)
    return
Example #9
0
def barplot(x,y,width=0.8,color=0):
    """Plot a barplot.

    Description:

      Plot a barplot with centers at x and heights y with given color

    Inputs:

      x, y -- Centers and heights of bars
      width -- Relative width of the bars.
      color -- A number from the current palette.
    """
    N = 4*Numeric.ones(len(x))
    hw = width * (x[1]-x[0])/ 2.0
    Xa = x-hw
    Xb = x+hw
    Ya = Numeric.zeros(len(y),'d')
    Yb = y
    X = Numeric.array((Xa,Xa,Xb,Xb))
    Y = Numeric.array((Ya,Yb,Yb,Ya))
    X = Numeric.reshape(Numeric.transpose(X),(4*len(N),))
    Y = Numeric.reshape(Numeric.transpose(Y),(4*len(N),))
    try:
        override = 1
        savesys = gist.plsys(2)
        gist.plsys(savesys)
    except:
        override = 0
    if _hold or override:
        pass
    else:
        gist.fma()
    Z = color * Numeric.ones(len(N))
    gist.plfp(Z.astype('B'),Y,X,N)
    return
Example #10
0
def barplot(x,y,width=0.8,color=0):
    """Plot a barplot.

    Description:

      Plot a barplot with centers at x and heights y with given color

    Inputs:

      x, y -- Centers and heights of bars
      width -- Relative width of the bars.
      color -- A number from the current palette.
    """
    N = 4*numpy.ones(len(x), dtype=numpy.int32)
    hw = width * (x[1]-x[0])/ 2.0
    Xa = x-hw
    Xb = x+hw
    Ya = numpy.zeros(len(y),'d')
    Yb = y
    X = numpy.array((Xa,Xa,Xb,Xb))
    Y = numpy.array((Ya,Yb,Yb,Ya))
    X = numpy.reshape(numpy.transpose(X),(4*len(N),))
    Y = numpy.reshape(numpy.transpose(Y),(4*len(N),))
    try:
        override = 1
        savesys = gist.plsys(2)
        gist.plsys(savesys)
    except:
        override = 0
    if _hold or override:
        pass
    else:
        gist.fma()
    Z = color * numpy.ones(len(N))
    gist.plfp(Z.astype(numpy.uint8),Y,X,N)
    return
Example #11
0
def matplot(x,y=None,axis=-1):
    if y is None:   # no axis data
        y = x
        x = Numeric.arange(0,y.shape[axis])
    x,y = Numeric.asarray(x), Numeric.asarray(y)
    assert(len(y.shape)==2)
    assert(len(x)==y.shape[axis])
    otheraxis = (1+axis) % 2
    sliceobj = [slice(None)]*2
    if not _hold and gist.plsys() < 2:
        gist.fma()
    clear_global_linetype()
    for k in range(y.shape[otheraxis]):
        thiscolor = _colors[_corder[k % len(_corder)]]
        sliceobj[otheraxis] = k
        ysl = where(numpy.isfinite(y[sliceobj]),y[sliceobj],0)
        gist.plg(ysl,x,type='solid',color=thiscolor,marks=0)
        append_global_linetype(_rcolors[thiscolor]+'-')
Example #12
0
def matplot(x,y=None,axis=-1):
    if y is None:   # no axis data
        y = x
        x = numpy.arange(0,y.shape[axis])
    x,y = numpy.asarray(x), numpy.asarray(y)
    assert(len(y.shape)==2)
    assert(len(x)==y.shape[axis])
    otheraxis = (1+axis) % 2
    sliceobj = [slice(None)]*2
    if not _hold and gist.plsys() < 2:
        gist.fma()
    clear_global_linetype()
    for k in range(y.shape[otheraxis]):
        thiscolor = _colors[_corder[k % len(_corder)]]
        sliceobj[otheraxis] = k
        ysl = where(numpy.isfinite(y[sliceobj]),y[sliceobj],0)
        gist.plg(ysl,x,type='solid',color=thiscolor,marks=0)
        append_global_linetype(_rcolors[thiscolor]+'-')
Example #13
0
def plot(x,*args,**keywds):
    """Plot curves.

    Description:

      Plot one or more curves on the same graph.

    Inputs:

      There can be a variable number of inputs which consist of pairs or
      triples.  The second variable is plotted against the first using the
      linetype specified by the optional third variable in the triple.  If
      only two plots are being compared, the x-axis does not have to be
      repeated.
    """
    try:
        override = 1
        savesys = gist.plsys(2)
        gist.plsys(savesys)
    except:
        override = 0
    global _hold
    try: _hold=keywds['hold']
    except KeyError: pass
    try: linewidth=float(keywds['width'])
    except KeyError: linewidth=1.0
    try: msize = float(keywds['msize'])
    except KeyError: msize=1.0
    if _hold or override:
        pass
    else:
        gist.fma()
    gist.animate(0)
    savesys = gist.plsys()
    winnum = gist.window()
    if winnum < 0:
        gist.window(0)
    if savesys >= 0:
        gist.plsys(savesys)
    nargs = len(args)
    if nargs == 0:
        y = _minsqueeze(x)
        x = Numeric.arange(0,len(y))
        if numpy.iscomplexobj(y):
            print "Warning: complex data plotting real part."
            y = y.real
        y = where(numpy.isfinite(y),y,0)
        gist.plg(y,x,type='solid',color='blue',marks=0,width=linewidth)
        return
    y = args[0]
    argpos = 1
    nowplotting = 0
    clear_global_linetype()
    while 1:
        try:
            thearg = args[argpos]
        except IndexError:
            thearg = 0
        thetype,thecolor,themarker,tomark = _parse_type_arg(thearg,nowplotting)
        if themarker == 'Z':  # args[argpos] was data or non-existent.
            pass
            append_global_linetype(_rtypes[thetype]+_rcolors[thecolor])
        else:                 # args[argpos] was a string
            argpos = argpos + 1
            if tomark:
                append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]+_rmarkers[themarker])
            else:
                append_global_linetype(_rtypes[thetype]+_rcolors[thecolor])
        if numpy.iscomplexobj(x) or numpy.iscomplexobj(y):
            print "Warning: complex data provided, using only real part."
            x = numpy.real(x)
            y = numpy.real(y)
        y = where(numpy.isfinite(y),y,0)
        y = _minsqueeze(y)
        x = _minsqueeze(x)
        gist.plg(y,x,type=thetype,color=thecolor,marker=themarker,marks=tomark,msize=msize,width=linewidth)

        nowplotting = nowplotting + 1

        ## Argpos is pointing to the next potential triple of data.
        ## Now one of four things can happen:
        ##
        ##   1:  argpos points to data, argpos+1 is a string
        ##   2:  argpos points to data, end
        ##   3:  argpos points to data, argpos+1 is data
        ##   4:  argpos points to data, argpos+1 is data, argpos+2 is a string

        if argpos >= nargs: break      # no more data

        if argpos == nargs-1:          # this is a single data value.
            x = x
            y = args[argpos]
            argpos = argpos+1
        elif type(args[argpos+1]) is types.StringType:
            x = x
            y = args[argpos]
            argpos = argpos+1
        else:   # 3
            x = args[argpos]
            y = args[argpos+1]
            argpos = argpos+2
    return
Example #14
0
def legend(text,linetypes=None,lleft=None,color=None,tfont='helvetica',fontsize=14,nobox=0):
    """Construct and place a legend.

    Description:

      Build a legend and place it on the current plot with an interactive
      prompt.

    Inputs:

      text -- A list of strings which document the curves.
      linetypes -- If not given, then the text strings are associated
                   with the curves in the order they were originally
                   drawn.  Otherwise, associate the text strings with the
                   corresponding curve types given.  See plot for description.

    """
    global _hold
    global _textcolor
    if color is None:
        color = _textcolor
    else:
        _textcolor = color
    if color is None:
        color = 'black'

    sys = gist.plsys()
    if sys == 0:
        gist.plsys(1)
    viewp = gist.viewport()
    gist.plsys(sys)
    DX = viewp[1] - viewp[0]
    DY = viewp[3] - viewp[2]
    width = DY / 10.0;
    if lleft is None:
        lleft = gist.mouse(0,0,"Click on point for lower left coordinate.")
        llx = lleft[0]
        lly = lleft[1]
    else:
        llx,lly = lleft[:2]

    savesys = gist.plsys()
    dx = width / 3.0
    legarr = Numeric.arange(llx,llx+width,dx)
    legy = Numeric.ones(legarr.shape)
    dy = fontsize*points*1.2
    deltay = fontsize*points / 2.8
    deltax = fontsize*points / 2.6 * DX / DY
    ypos = lly + deltay;
    if linetypes is None:
        linetypes = _GLOBAL_LINE_TYPES[:]  # copy them out
    gist.plsys(0)
    savehold = _hold
    _hold = 1
    for k in range(len(text)):
        plot(legarr,ypos*legy,linetypes[k])
        print linetypes[k], text[k]
        print llx+width+deltax, ypos-deltay
        if text[k] != "":
            gist.plt(text[k],llx+width+deltax,ypos-deltay,
                     color=color,font=tfont,height=fontsize,tosys=0)
        ypos = ypos + dy
    _hold = savehold
    if nobox:
        pass
    else:
        gist.plsys(0)
        maxlen = MLab.max(map(len,text))
        c1 = (llx-deltax,lly-deltay)
        c2 = (llx + width + deltax + fontsize*points* maxlen/1.8 + deltax,
              lly + len(text)*dy)
        linesx0 = [c1[0],c1[0],c2[0],c2[0]]
        linesy0 = [c1[1],c2[1],c2[1],c1[1]]
        linesx1 = [c1[0],c2[0],c2[0],c1[0]]
        linesy1 = [c2[1],c2[1],c1[1],c1[1]]
        gist.pldj(linesx0,linesy0,linesx1,linesy1,color=color)
    gist.plsys(savesys)
    return
Example #15
0
def legend(text,linetypes=None,lleft=None,color=None,tfont='helvetica',fontsize=14,nobox=0):
    """Construct and place a legend.

    Description:

      Build a legend and place it on the current plot with an interactive
      prompt.

    Inputs:

      text -- A list of strings which document the curves.
      linetypes -- If not given, then the text strings are associated
                   with the curves in the order they were originally
                   drawn.  Otherwise, associate the text strings with the
                   corresponding curve types given.  See plot for description.

    """
    global _hold
    global _textcolor
    if color is None:
        color = _textcolor
    else:
        _textcolor = color
    if color is None:
        color = 'black'

    sys = gist.plsys()
    if sys == 0:
        gist.plsys(1)
    viewp = gist.viewport()
    gist.plsys(sys)
    DX = viewp[1] - viewp[0]
    DY = viewp[3] - viewp[2]
    width = DY / 10.0;
    if lleft is None:
        lleft = gist.mouse(0,0,"Click on point for lower left coordinate.")
        llx = lleft[0]
        lly = lleft[1]
    else:
        llx,lly = lleft[:2]

    savesys = gist.plsys()
    dx = width / 3.0
    legarr = numpy.arange(llx,llx+width,dx)
    legy = numpy.ones(legarr.shape)
    dy = fontsize*points*1.2
    deltay = fontsize*points / 2.8
    deltax = fontsize*points / 2.6 * DX / DY
    ypos = lly + deltay;
    if linetypes is None:
        linetypes = _GLOBAL_LINE_TYPES[:]  # copy them out
    gist.plsys(0)
    savehold = _hold
    _hold = 1
    for k in range(len(text)):
        plot(legarr,ypos*legy,linetypes[k])
        print linetypes[k], text[k]
        print llx+width+deltax, ypos-deltay
        if text[k] != "":
            gist.plt(text[k],llx+width+deltax,ypos-deltay,
                     color=color,font=tfont,height=fontsize,tosys=0)
        ypos = ypos + dy
    _hold = savehold
    if nobox:
        pass
    else:
        gist.plsys(0)
        maxlen = numpy.max(map(len,text))
        c1 = (llx-deltax,lly-deltay)
        c2 = (llx + width + deltax + fontsize*points* maxlen/1.8 + deltax,
              lly + len(text)*dy)
        linesx0 = [c1[0],c1[0],c2[0],c2[0]]
        linesy0 = [c1[1],c2[1],c2[1],c1[1]]
        linesx1 = [c1[0],c2[0],c2[0],c1[0]]
        linesy1 = [c2[1],c2[1],c1[1],c1[1]]
        gist.pldj(linesx0,linesy0,linesx1,linesy1,color=color)
    gist.plsys(savesys)
    return
Example #16
0
def twoplane(DATA,slice1,slice2,dx=[1,1,1],cmin=None,cmax=None,xb=None,xe=None,
             xlab="",ylab="",zlab="",clab="",titl="",
             totalheight=0.5,space=0.02, medfilt=5,
             font='helvetica',fontsize=16,color='black',lcolor='white',
             fcolor='black',  cb=1, line=1, palette=None):
    """ Visualize a 3d volume as a two connected slices.  The slices are
    given in the 2-tuple slice1 and slice2.

    These give the dimension and corresponding slice numbers to plot.
    The unchosen slice is the common dimension in the images.

    twoplane(img3d,(0,12),(2,60)) plots two images with a common "x"-axis
    as the first dimension.  The lower plot is img3d[12,:,:] with a line
    through row 60 corresponding to the slice transpose(img3d[:,:,60])
    plotted above this first plot.
    """
    if xb is None:
        xb = [0,0,0]
    if xe is None:
        xe = DATA.shape
    # get two image slices
    # make special style file so that pixels are square
    getdx = array([1,1,1])
    imgsl1 = [slice(None,None),slice(None,None),slice(None,None)]
    imgsl1[slice1[0]] = slice1[1]
    img1 = DATA[imgsl1]
    getdx1 = getdx.__copy__()
    getdx1[slice1[0]] = 0
    dx1 = compress(getdx1,dx,axis=-1)
    xb1 = compress(getdx1,xb,axis=-1)
    xe1 = compress(getdx1,xe,axis=-1)

    imgsl2 = [slice(None,None),slice(None,None),slice(None,None)]
    imgsl2[slice2[0]] = slice2[1]
    img2 = DATA[imgsl2]
    getdx2 = getdx.__copy__()
    getdx2[slice2[0]] = 0
    dx2 = compress(getdx2,dx,axis=-1)
    xb2 = compress(getdx2,xb,axis=-1)
    xe2 = compress(getdx2,xe,axis=-1)


    if (slice1[0] == slice2[0]):
        raise ValueError, "Same slice dimension.."

    for k in range(3):
        if k not in [slice1[0],slice2[0]]:
            samedim = k
            break
    if samedim == 2:
        pass
    elif samedim == 1:
        if samedim > slice1[0]:
            img1 = transpose(img1)
            dx1 = dx1[::-1]
            xb1 = xb1[::-1]
            xe1 = xe1[::-1]
        if samedim > slice2[0]:
            img2 = transpose(img2)
            dx2 = dx2[::-1]
            xb2 = xb2[::-1]
            xe2 = xe2[::-1]
    else:
        img1 = transpose(img1)
        dx1 = dx1[::-1]
        xb1 = xb1[::-1]
        xe1 = xe1[::-1]
        img2 = transpose(img2)
        dx2 = dx2[::-1]
        xb2 = xb2[::-1]
        xe2 = xe2[::-1]



    assert(img1.shape[1] == img2.shape[1])
    units = totalheight - space
    totaldist = img1.shape[0]*dx1[0] + img2.shape[0]*dx2[0]
    convfactor = units / float(totaldist)
    height1 = img1.shape[0]*dx1[0] * convfactor
    xwidth = img1.shape[1]*dx1[1]*convfactor
    if xwidth > 0.6:
        rescale = 0.6 / xwidth
        xwidth = rescale * xwidth
        height1 = rescale * height1
        totalheight = totalheight * rescale
        print xwidth, height1
    else:
        print xwidth
    ystart = 0.5 - totalheight / 2
    ypos1 = [ystart, ystart+height1]
    ypos2 = [ystart+height1+space,ystart+totalheight]
    xpos = [0.395-xwidth/2.0, 0.395+xwidth/2.0]

    systems = []
    system = write_style.getsys(hticpos='', vticpos='left')
    system['viewport'] = [xpos[0],xpos[1],ypos2[0],ypos2[1]]
    if fcolor not in ['black',None]:
        _add_color(system, _colornum[color])
    systems.append(system)
    system = write_style.getsys(hticpos='below', vticpos='left')
    system['viewport'] = [xpos[0],xpos[1],ypos1[0],ypos1[1]]
    if fcolor not in ['black',None]:
        _add_color(system, _colornum[color])
    systems.append(system)

    the_style = os.path.join(_user_path,"two-plane.gs")
    write_style.writestyle(the_style,systems)

    gist.window(style=the_style)
    _current_style = the_style
    change_palette(palette)
    gist.plsys(1)
    if medfilt > 1:
        img1 = signal.medfilt(img1,[medfilt,medfilt])
        img2 = signal.medfilt(img2,[medfilt,medfilt])
    if cmax is None:
        cmax = max(max(ravel(img1)),max(ravel(img2)))
    if cmin is None:
        cmin = min(min(ravel(img1)),min(ravel(img2)))
    cmax = float(cmax)
    cmin = float(cmin)
    byteimage = gist.bytscl(img2,cmin=cmin,cmax=cmax)
    gist.pli(byteimage,xb2[1],xb2[0],xe2[1],xe2[0])
    ylabel(zlab,color=color)
    if titl != "":
        title(titl,color=color)
    if line:
        xstart = xb2[1]
        xstop = xe2[1]
        yval = slice1[1]*(xe2[0] - xb2[0])/(img2.shape[0]) + xb2[0]
        gist.pldj([xstart],[yval],[xstop],[yval],type='dash',width=2,color='white')


    gist.plsys(2)
    ylabel(ylab,color=color)
    xlabel(xlab,color=color)
    byteimage = gist.bytscl(img1,cmin=cmin,cmax=cmax)
    gist.pli(byteimage,xb1[1],xb1[0],xe1[1],xe1[0])
    if line:
        xstart = xb1[1]
        xstop = xe1[1]
        yval = slice2[1]*(xe1[0] - xb1[0])/(img1.shape[0]) + xb1[0]
        gist.pldj([xstart],[yval],[xstop],[yval],type='dash',width=2,color='white')

    if cb:
        colorbar.color_bar(cmin,cmax,ncol=240,zlabel=clab,font=font,fontsize=fontsize,color=color,ymin=ystart,ymax=ystart+totalheight,xmin0=xpos[1]+0.02,xmax0=xpos[1]+0.04)
Example #17
0
def twoplane(DATA,slice1,slice2,dx=[1,1,1],cmin=None,cmax=None,xb=None,xe=None,
             xlab="",ylab="",zlab="",clab="",titl="",
             totalheight=0.5,space=0.02, medfilt=5,
             font='helvetica',fontsize=16,color='black',lcolor='white',
             fcolor='black',  cb=1, line=1, palette=None):
    """ Visualize a 3d volume as a two connected slices.  The slices are
    given in the 2-tuple slice1 and slice2.

    These give the dimension and corresponding slice numbers to plot.
    The unchosen slice is the common dimension in the images.

    twoplane(img3d,(0,12),(2,60)) plots two images with a common "x"-axis
    as the first dimension.  The lower plot is img3d[12,:,:] with a line
    through row 60 corresponding to the slice transpose(img3d[:,:,60])
    plotted above this first plot.
    """
    if xb is None:
        xb = [0,0,0]
    if xe is None:
        xe = DATA.shape
    # get two image slices
    # make special style file so that pixels are square
    getdx = array([1,1,1])
    imgsl1 = [slice(None,None),slice(None,None),slice(None,None)]
    imgsl1[slice1[0]] = slice1[1]
    img1 = DATA[imgsl1]
    getdx1 = getdx.__copy__()
    getdx1[slice1[0]] = 0
    dx1 = compress(getdx1,dx,axis=-1)
    xb1 = compress(getdx1,xb,axis=-1)
    xe1 = compress(getdx1,xe,axis=-1)

    imgsl2 = [slice(None,None),slice(None,None),slice(None,None)]
    imgsl2[slice2[0]] = slice2[1]
    img2 = DATA[imgsl2]
    getdx2 = getdx.__copy__()
    getdx2[slice2[0]] = 0
    dx2 = compress(getdx2,dx,axis=-1)
    xb2 = compress(getdx2,xb,axis=-1)
    xe2 = compress(getdx2,xe,axis=-1)


    if (slice1[0] == slice2[0]):
        raise ValueError, "Same slice dimension.."

    for k in range(3):
        if k not in [slice1[0],slice2[0]]:
            samedim = k
            break
    if samedim == 2:
        pass
    elif samedim == 1:
        if samedim > slice1[0]:
            img1 = transpose(img1)
            dx1 = dx1[::-1]
            xb1 = xb1[::-1]
            xe1 = xe1[::-1]
        if samedim > slice2[0]:
            img2 = transpose(img2)
            dx2 = dx2[::-1]
            xb2 = xb2[::-1]
            xe2 = xe2[::-1]
    else:
        img1 = transpose(img1)
        dx1 = dx1[::-1]
        xb1 = xb1[::-1]
        xe1 = xe1[::-1]
        img2 = transpose(img2)
        dx2 = dx2[::-1]
        xb2 = xb2[::-1]
        xe2 = xe2[::-1]



    assert(img1.shape[1] == img2.shape[1])
    units = totalheight - space
    totaldist = img1.shape[0]*dx1[0] + img2.shape[0]*dx2[0]
    convfactor = units / float(totaldist)
    height1 = img1.shape[0]*dx1[0] * convfactor
    xwidth = img1.shape[1]*dx1[1]*convfactor
    if xwidth > 0.6:
        rescale = 0.6 / xwidth
        xwidth = rescale * xwidth
        height1 = rescale * height1
        totalheight = totalheight * rescale
        print xwidth, height1
    else:
        print xwidth
    ystart = 0.5 - totalheight / 2
    ypos1 = [ystart, ystart+height1]
    ypos2 = [ystart+height1+space,ystart+totalheight]
    xpos = [0.395-xwidth/2.0, 0.395+xwidth/2.0]

    systems = []
    system = write_style.getsys(hticpos='', vticpos='left')
    system['viewport'] = [xpos[0],xpos[1],ypos2[0],ypos2[1]]
    if fcolor not in ['black',None]:
        _add_color(system, _colornum[color])
    systems.append(system)
    system = write_style.getsys(hticpos='below', vticpos='left')
    system['viewport'] = [xpos[0],xpos[1],ypos1[0],ypos1[1]]
    if fcolor not in ['black',None]:
        _add_color(system, _colornum[color])
    systems.append(system)

    the_style = os.path.join(_user_path,"two-plane.gs")
    write_style.writestyle(the_style,systems)

    gist.window(style=the_style)
    _current_style = the_style
    change_palette(palette)
    gist.plsys(1)
    if medfilt > 1:
        import scipy.signal
        img1 = scipy.signal.medfilt(img1,[medfilt,medfilt])
        img2 = scipy.signal.medfilt(img2,[medfilt,medfilt])
    if cmax is None:
        cmax = max(max(ravel(img1)),max(ravel(img2)))
    if cmin is None:
        cmin = min(min(ravel(img1)),min(ravel(img2)))
    cmax = float(cmax)
    cmin = float(cmin)
    byteimage = gist.bytscl(img2,cmin=cmin,cmax=cmax)
    gist.pli(byteimage,xb2[1],xb2[0],xe2[1],xe2[0])
    ylabel(zlab,color=color)
    if titl != "":
        title(titl,color=color)
    if line:
        xstart = xb2[1]
        xstop = xe2[1]
        yval = slice1[1]*(xe2[0] - xb2[0])/(img2.shape[0]) + xb2[0]
        gist.pldj([xstart],[yval],[xstop],[yval],type='dash',width=2,color='white')


    gist.plsys(2)
    ylabel(ylab,color=color)
    xlabel(xlab,color=color)
    byteimage = gist.bytscl(img1,cmin=cmin,cmax=cmax)
    gist.pli(byteimage,xb1[1],xb1[0],xe1[1],xe1[0])
    if line:
        xstart = xb1[1]
        xstop = xe1[1]
        yval = slice2[1]*(xe1[0] - xb1[0])/(img1.shape[0]) + xb1[0]
        gist.pldj([xstart],[yval],[xstop],[yval],type='dash',width=2,color='white')

    if cb:
        colorbar.color_bar(cmin,cmax,ncol=240,zlabel=clab,font=font,fontsize=fontsize,color=color,ymin=ystart,ymax=ystart+totalheight,xmin0=xpos[1]+0.02,xmax0=xpos[1]+0.04)
Example #18
0
def plot(x,*args,**keywds):
    """Plot curves.

    Description:

      Plot one or more curves on the same graph.

    Inputs:

      There can be a variable number of inputs which consist of pairs or
      triples.  The second variable is plotted against the first using the
      linetype specified by the optional third variable in the triple.  If
      only two plots are being compared, the x-axis does not have to be
      repeated.
    """
    try:
        override = 1
        savesys = gist.plsys(2)
        gist.plsys(savesys)
    except:
        override = 0
    global _hold
    try: _hold=keywds['hold']
    except KeyError: pass
    try: linewidth=float(keywds['width'])
    except KeyError: linewidth=1.0
    try: msize = float(keywds['msize'])
    except KeyError: msize=1.0
    if _hold or override:
        pass
    else:
        gist.fma()
    gist.animate(0)
    savesys = gist.plsys()
    winnum = gist.window()
    if winnum < 0:
        gist.window(0)
    if savesys >= 0:
        gist.plsys(savesys)
    nargs = len(args)
    if nargs == 0:
        y = _minsqueeze(x)
        x = numpy.arange(0,len(y))
        if numpy.iscomplexobj(y):
            print "Warning: complex data plotting real part."
            y = y.real
        y = where(numpy.isfinite(y),y,0)
        gist.plg(y,x,type='solid',color='blue',marks=0,width=linewidth)
        return
    y = args[0]
    argpos = 1
    nowplotting = 0
    clear_global_linetype()
    while 1:
        try:
            thearg = args[argpos]
        except IndexError:
            thearg = 0
        thetype,thecolor,themarker,tomark = _parse_type_arg(thearg,nowplotting)
        if themarker == 'Z':  # args[argpos] was data or non-existent.
            pass
            append_global_linetype(_rtypes[thetype]+_rcolors[thecolor])
        else:                 # args[argpos] was a string
            argpos = argpos + 1
            if tomark:
                append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]+_rmarkers[themarker])
            else:
                append_global_linetype(_rtypes[thetype]+_rcolors[thecolor])
        if numpy.iscomplexobj(x) or numpy.iscomplexobj(y):
            print "Warning: complex data provided, using only real part."
            x = numpy.real(x)
            y = numpy.real(y)
        y = where(numpy.isfinite(y),y,0)
        y = _minsqueeze(y)
        x = _minsqueeze(x)
        gist.plg(y,x,type=thetype,color=thecolor,marker=themarker,marks=tomark,msize=msize,width=linewidth)

        nowplotting = nowplotting + 1

        ## Argpos is pointing to the next potential triple of data.
        ## Now one of four things can happen:
        ##
        ##   1:  argpos points to data, argpos+1 is a string
        ##   2:  argpos points to data, end
        ##   3:  argpos points to data, argpos+1 is data
        ##   4:  argpos points to data, argpos+1 is data, argpos+2 is a string

        if argpos >= nargs: break      # no more data

        if argpos == nargs-1:          # this is a single data value.
            x = x
            y = args[argpos]
            argpos = argpos+1
        elif type(args[argpos+1]) is types.StringType:
            x = x
            y = args[argpos]
            argpos = argpos+1
        else:   # 3
            x = args[argpos]
            y = args[argpos+1]
            argpos = argpos+2
    return