Beispiel #1
0
  def plot_data(self,**kargs):
    prjtype=kargs.pop('prjtype','nice')

    from matplotlib.cm import gist_earth_r

    if 0:
      j=np.ceil(np.median(range(len(self)))).astype('i')
      ht=ticks.loose_label_n(self[j].h.min(),self[j].h.max(),7)
    else:
      ht=ticks.loose_label_n(self[0].h.min(),self[0].h.max(),7)

    if len(self)>1:
      ht2=ticks.loose_label_n(ht[0],ht[1]/2,5)[1:]
      ht=np.concatenate(([ht[0]],ht2,ht[1:]))
      ht=np.unique(np.sort(ht))

    ht=kargs.get('field__cvals',ht)
    ht=kargs.get('cvals',ht)

    # contour colors:
    from matplotlib import rcParams
    colors=rcParams['axes.prop_cycle']()

    for c,i in enumerate(self):
      h=np.ma.masked_where(i.mask==0,i.h)
      b=vis.Data(x=i.lon,y=i.lat,v=h)
      b.set_param(field__plot='contourf',field__cvals=ht,field__cmap=gist_earth_r)
      b.set_param(**kargs)
      if c==0:
        a=b
      else:
        a.extra+=[b]

      c=vis.Data(x=i.lon,y=i.lat,v=h)
      c.set_param(field__plot='contour',field__cvals=ht,field__cmap=next(colors)['color'],
                  field__linewidths=0.5,plot__zorder=2) # show above everything else
      c.label='bathy'
      a.extra+=[c]

    # show all borders:
    for i in self:
      xb,yb=i.border()
      c=vis.Data(x=xb,v=yb)
      c.set_param(d1_line__options=dict(lw=0.5,color='k',ls='-'))
      a.extra+=[c]


    # about projection:
    if prjtype=='original' and self[0].proj_info['basemap_opts0']: d=self[0].proj_info['basemap_opts0']
    elif prjtype=='nice': d=self[0].proj_info['basemap_opts']

    a.set_projection(d)

    return vis.MData([a])
Beispiel #2
0
  def plot_data(self,**kargs):
    prjtype=kargs.pop('prjtype','nice')

    from matplotlib.cm import gist_earth_r

    if 0:
      j=np.ceil(np.median(range(len(self)))).astype('i')
      ht=ticks.loose_label_n(self[j].h.min(),self[j].h.max(),7)
    else:
      ht=ticks.loose_label_n(self[0].h.min(),self[0].h.max(),7)

    if len(self)>1:
      ht2=ticks.loose_label_n(ht[0],ht[1]/2,5)[1:]
      ht=np.concatenate(([ht[0]],ht2,ht[1:]))
      ht=np.unique(np.sort(ht))

    ht=kargs.get('field__cvals',ht)
    ht=kargs.get('cvals',ht)

    # contour colors:
    from matplotlib import rcParams
    colors=rcParams['axes.prop_cycle']()

    for c,i in enumerate(self):
      h=np.ma.masked_where(i.mask==0,i.h)
      b=vis.Data(x=i.lon,y=i.lat,v=h)
      b.set_param(field__plot='contourf',field__cvals=ht,field__cmap=gist_earth_r)
      b.set_param(**kargs)
      if c==0:
        a=b
      else:
        a.extra+=[b]

      c=vis.Data(x=i.lon,y=i.lat,v=h)
      c.set_param(field__plot='contour',field__cvals=ht,field__cmap=next(colors)['color'],
                  field__linewidths=0.5,plot__zorder=2) # show above everything else
      c.label='bathy'
      a.extra+=[c]

    # show all borders:
    for i in self:
      xb,yb=i.border()
      c=vis.Data(x=xb,v=yb)
      c.set_param(d1_line__options=dict(lw=0.5,color='k',ls='-'))
      a.extra+=[c]


    # about projection:
    if prjtype=='original' and self[0].proj_info['basemap_opts0']: d=self[0].proj_info['basemap_opts0']
    elif prjtype=='nice': d=self[0].proj_info['basemap_opts']

    a.set_projection(d)

    return vis.MData([a])
Beispiel #3
0
  def plot(self,**kargs):
    from okean import vis
    from matplotlib.cm import gist_earth_r
    h=np.ma.masked_where(self.mask==0,self.h)
    a=vis.Data(x=self.lon,y=self.lat,v=h)
    ht=ticks.loose_label_n(self.h.min(),self.h.max(),7)
    a.set_param(field__plot='contourf',field__cvals=ht,field__cmap=gist_earth_r)
    a.set_param(**kargs)

    # also show domain boundary:
    xb,yb=self.border()
    b=vis.Data(x=xb,v=yb)
    b.set_param(d1_line__options=dict(lw=0.5,color='k',ls='-'))
    a.extra=[b]

    a.plot(labels=0)

    return a
Beispiel #4
0
  def plot(self,**kargs):
    from okean import vis
    from matplotlib.cm import gist_earth_r
    h=np.ma.masked_where(self.mask==0,self.h)
    a=vis.Data(x=self.lon,y=self.lat,v=h)
    ht=ticks.loose_label_n(self.h.min(),self.h.max(),7)
    a.set_param(field__plot='contourf',field__cvals=ht,field__cmap=gist_earth_r)
    a.set_param(**kargs)

    # also show domain boundary:
    xb,yb=self.border()
    b=vis.Data(x=xb,v=yb)
    b.set_param(d1_line__options=dict(lw=0.5,color='k',ls='-'))
    a.extra=[b]

    a.plot(labels=0)

    return a
Beispiel #5
0
  def plot_data(self,**kargs):
    prjtype=kargs.pop('prjtype','nice')
    from matplotlib.cm import gist_earth_r
    h=np.ma.masked_where(self.mask==0,self.h)
    a=vis.Data(x=self.lon,y=self.lat,v=h)
    ht=ticks.loose_label_n(self.h.min(),self.h.max(),7)
    a.set_param(field__plot='contourf',field__cvals=ht,field__cmap=gist_earth_r)
    a.set_param(**kargs)

    # also show domain boundary:
    xb,yb=self.border()
    b=vis.Data(x=xb,v=yb)
    b.set_param(d1_line__options=dict(lw=0.5,color='k',ls='-'))
    a.extra=[b]

    # about projection:
    if prjtype=='original' and self.proj_info['basemap_opts0']: d=self.proj_info['basemap_opts0']
    elif prjtype=='nice': d=self.proj_info['basemap_opts']

    a.set_projection(d)

    return a
Beispiel #6
0
  def plot_data(self,**kargs):
    prjtype=kargs.pop('prjtype','nice')
    from matplotlib.cm import gist_earth_r
    h=np.ma.masked_where(self.mask==0,self.h)
    a=vis.Data(x=self.lon,y=self.lat,v=h)
    ht=ticks.loose_label_n(self.h.min(),self.h.max(),7)
    a.set_param(field__plot='contourf',field__cvals=ht,field__cmap=gist_earth_r)
    a.set_param(**kargs)

    # also show domain boundary:
    xb,yb=self.border()
    b=vis.Data(x=xb,v=yb)
    b.set_param(d1_line__options=dict(lw=0.5,color='k',ls='-'))
    a.extra=[b]

    # about projection:
    if prjtype=='original' and self.proj_info['basemap_opts0']: d=self.proj_info['basemap_opts0']
    elif prjtype=='nice': d=self.proj_info['basemap_opts']

    a.set_projection(d)

    return a
Beispiel #7
0
  def _slice(self,slc,varname,ind,it0,**opts):
##    border=opts.get('border',1)

    if slc=='ll': x,y=ind

    o=[]
    It,twarn=self.tinds(it0)
    for c,i in enumerate(self):
      meth=getattr(i,'slice'+slc)
      if slc=='uv':  o+=[meth(ind,It[c],**opts)]
      elif slc=='ll':o+=[meth(varname,x,y,It[c],**opts)]
      else:          o+=[meth(varname,ind,It[c],**opts)]
      #if msg[c]:
      #  if o[-1].msg: o[-1].msg+='\n'
      #  o[-1].msg+=msg[c]


    # add filled border for next domain:
    if slc in ['i','j','k','z','iso']:#,'uv']:
      for i in range(len(self)-1):
        xb,yb=self[i+1].grid.border()
        o[i].extra+=[vis.Data(xb,yb)]
        o[i].extra[-1].label='border grid %d'%(i+1)
        #if i>0:
        o[i].extra[-1].config['d1.plot']='fill'
        o[i].extra[-1].config['d1_fill.options']['lw']=0
        o[i].extra[-1].config['d1_fill.options']['facecolor']='w'
        #o[i].extra[-1].config['plot.zorder']=1
        #else:
        #  o[i].extra[-1].config['d1.plot']='plot'
    elif slc=='uv': # for uv, better to mask arrows inside child domains
      if not hasattr(self.grid,'ingrd'): self.grid._set_ingrid('p')
      from functools import reduce
      for c,i in enumerate(o):
        if not i.v is None:
          if len(self.grid[c].ingrd_p):
            mask=reduce(lambda i,j: i&j,self.grid[c].ingrd_p)
            mask=mask&(~i.v.mask)
            i.nmask=mask # nested domains mask
            i.v.mask=i.v.mask|i.nmask
          else: i.nmask=None



    # vfield settings:
    if not o[0].v is None:
      vfield=o[0].get_param('vfield')
      if not vfield['options']['scale']:
        vfield['options']={'units':'width','scale':10}

      # use same vfield settings for all slices:
      for i in o:
        for k in vfield: i.config['vfield.'+k]=vfield[k]

      # no key for slices[1:]:
      for i in o[1:]:
        i.config['vfield.key_XYU']=0,0,0


    # field settings:
    if not o[0].v is None:
      field=o[0].get_param('field')

      if field['clim'] is False:
        if np.iscomplexobj(o[0].v):
          field['clim']=np.abs(o[0].v).min(),np.abs(o[0].v).max()
        else:
          field['clim']=o[0].v.min(),o[0].v.max()

        if field['clim'][0]==field['clim'][1]:
          field['clim']=field['clim'][0]-1,field['clim'][0]+1

      if field['cvals'] is False:
        tk=ticks.loose_label_n(field['clim'][0],field['clim'][1],7)
        field['cvals']=tk

      # use same field settings for all slices:
      for i in o:
        for k in field: i.config['field.'+k]=field[k]


    # also same settings for extras like bathy contours:
    Lab=['bathy']
    for lab in Lab:
      for e in o[0].extra:
        if e.label==lab and not e.v is None:
          field=e.get_param('field')
          if field['clim'] is False: field['clim']=e.v.min(),e.v.max()
          if field['cvals'] is False or  not calc.isiterable(field['cvals']):
            # the isiterable here is because it can be an integer (nof fixed set)
            tk=ticks.loose_label_n(field['clim'][0],field['clim'][1],3)
            field['cvals']=tk

      for i in o:
        for e in i.extra:
          if e.label==lab:
            for k in field: e.config['field.'+k]=field[k]

    # add border for all domains:
#    xb,yb=self.grid.border()
#    o[0].extra+=[vis.Data(x=xb,v=yb)]
    borders=[]
    for i in self:
      xb,yb=i.grid.border()
      c=vis.Data(x=xb,v=yb)
      c.set_param(d1_line__options=dict(lw=0.5,color='k',ls='-'))
      borders+=[c]

    o[-1].extra+=borders

    # set zorder:
    c=1
    for i in o:
      c+=0.1
      i.config['plot.zorder']=c
      for j in i.extra:
        c+=0.1
        j.config['plot.zorder']=c

    # place some stuff above continents:
    z=o[0].config['proj.continents']['zorder']
    z+=0.1
    # vfield:
    if slc=='uv':
      for i in o: i.config['plot.zorder']=z

    # place borders above continents:
    for b in borders: b.config['plot.zorder']=z


    return vis.MData(o,warnings=twarn)
Beispiel #8
0
  def plot(self,**kargs):
    bathy      = kargs.get('bathy','contourf')
    hvals      = kargs.get('hvals','auto')
    resolution = kargs.get('res','i')
    rivers     = kargs.get('rivers',False)
    parallels  = kargs.get('parallels','auto')
    meridians  = kargs.get('meridians','auto')
    scale      = kargs.get('scale',False)
    states     = kargs.get('states',False)
    xlim       = kargs.get('xlim',False)
    ylim       = kargs.get('ylim',False)
    title      = kargs.get('title','auto')
    cmap       = kargs.get('cmap',pylab.cm.gist_earth_r)
    proj       = kargs.get('proj','merc')
    ax         = kargs.get('ax',False)

    if not ax:
      fig=pylab.figure()
      ax=pylab.axes()
    else: fig=ax.figure

    h=np.ma.masked_where(self.mask==0,self.h)
    xb,yb=self.border()

    xt=ticks.loose_label(self.lon.min(),self.lon.max())
    yt=ticks.loose_label(self.lat.min(),self.lat.max())
    ht=ticks.loose_label_n(self.h.min(),self.h.max(),7)

    if xlim: Lonlims=xlim
    else:  Lonlims=xt[0],xt[-1]

    if ylim: Latlims=ylim
    else: Latlims=yt[0],yt[-1]

    if hvals=='auto': hvals=ht

    if parallels=='auto': parallels=yt
    if meridians=='auto': meridians=xt

    if Basemap and proj:
      m = Basemap(projection=proj,lat_ts=0.0,
                  #lon_0=self.lon[0].mean(),
                  resolution=resolution,
                  urcrnrlon=Lonlims[1], urcrnrlat=Latlims[1],
                  llcrnrlon=Lonlims[0], llcrnrlat=Latlims[0])

      m.drawcoastlines(ax=ax)
      m.fillcontinents(ax=ax,color=(0.7604,    1.0000,    0.7459))
      if rivers: m.drawrivers(color='b')

      m.drawcountries(ax=ax)
      # m.drawlsmask()
      # m.drawmapboundary()
      if scale:
        dx=Lonlims[1]-Lonlims[0]
        dy=Latlims[1]-Latlims[0]
        lon=Lonlims[1]-dx/10
        lat=Latlims[0]+dy/10
        lon0=lon
        lat0=lat
        length=100

        m.drawmapscale(lon,lat,lon0,lat0,length,ax=ax)

      if states: m.drawstates(ax=ax)

      m.drawparallels(parallels, labels=[1,0,0,0],ax=ax)
      m.drawmeridians(meridians, labels=[0,0,0,1],ax=ax)

      x, y = m(self.lon, self.lat)
      pch=False
      if bathy in ['pcolor','pcolormesh']:
        pch = ax.pcolormesh(x,y,h,cmap=cmap)
      elif bathy=='contour':
        pch = ax.contour(x,y,h,hvals,cmap=cmap)
      elif bathy=='contourf':
        pch = ax.contourf(x,y,h,hvals,cmap=cmap)

      if pch:
        if m.xmax-m.xmin<m.ymax-m.ymin: orientation='horizontal'
        else: orientation='vetical'

        cbh = pylab.colorbar(pch,orientation=orientation,ax=ax)
        cbh.set_label('Depth')
        if title=='auto': ax.set_title(self.name)
        elif title: ax.set_title(title)

      xb, yb = m(xb,yb)
      ax.plot(xb,yb)
      ax.axis([m.xmin, m.xmax, m.ymin, m.ymax])
      return m

    else:
      ax.pcolormesh(self.lon,self.lat,h,cmap=cmap)
      ax.contour(self.lon,self.lat,self.h,hvals,colors='w')
      ax.plot(xb,yb)
Beispiel #9
0
def wind_rose(D,F,**kargs):
  '''
  Example:
  import numpy as np

  d=np.arange(0,360,10)
  D=np.array(())
  V=np.array(())
  for i in range(len(d)):
    n=d[i]/10.
    D=np.append(D,np.ones(n)*d[i])
    V=np.append(V,np.arange(n))

  wind_rose(D,V)

  '''

  D=np.asarray(D)
  F=np.asarray(F)

  ax          = kargs.get('ax',          pl.gca())
  bg          = kargs.get('bg',          'w')
  dtype       = kargs.get('dtype',       'standard')
  nAngles     = kargs.get('n',           36)
  ri          = kargs.get('ri',          1/30.)
  quad        = kargs.get('quad',        0)
  legType     = kargs.get('legtype',     0)
  percBg      = kargs.get('percbg',      'w')
  titStr      = kargs.get('title',       '')
  legStr      = kargs.get('legend',      '')
  cmap        = kargs.get('cmap',        None)
  colors      = kargs.get('colors',      [])
  Ag          = kargs.get('di',          False) # intensity subdivs
  ci          = kargs.get('ci',          []) # percentage circles
  lineColors  = kargs.get('lcolor',      'k')
  borderColor = kargs.get('bcolor',      False)
  iflip       = kargs.get('iflip',       0)
  inorm       = kargs.get('inorm',       0)
  IncHiLow    = kargs.get('incout',      1) # include values higher and lower that the limits of Ag
  FontSize    = kargs.get('fontsize',    8)
  LineWidth   = kargs.get('linewidth',   0.5)
  legTickLab  = kargs.get('lablegticks', True)
  NSEWlab     = kargs.get('NSEWlab',     True)
  labels      = kargs.get('labels',      True)
  percLabels  = kargs.get('percLabels',  True)

  if not labels:
    legTickLab=NSEWlab=percLabels=False

  # other options:
  # size of the full rectangle:
  rs=1.2
  rl=1.7
  # axes W/H = (rs+rl)/(2*rs)

  # directions conversion:
  if dtype=='meteo': D=np.mod(-90-D,360)


  # angles subdivisons:
  D=np.mod(D,360.)
  Ay=np.linspace(0,360,nAngles+1)-0.5*360/nAngles

  # calc instensity subdivisions:
  if Ag is False:
    from okean import ticks
    Ag=ticks.loose_label_n(F.min(),F.max(),ntick=7)

  E=np.zeros([len(Ay)-1,len(Ag)-1])
  for i in range(len(Ay)-1):
    if i==0:
      I=( (D>=Ay[i]) & (D<Ay[i+1]) ) | (D>=Ay[-1])
    else:
      I=(D>=Ay[i]) & (D<Ay[i+1])

    b=F[I]

    for j in range(len(Ag)-1):
      if j==len(Ag)-2:
        J=((b>=Ag[j]) & (b<=Ag[j+1])) # include data with last Ag
      else:
        J=((b>=Ag[j]) & (b<Ag[j+1]))
      E[i,j]=len(np.where(J)[0])

    if IncHiLow:
      E[i,0]=len(np.where(b<Ag[1])[0])
      E[i,-1]=len(np.where(b>=Ag[-2])[0])

  b=np.sum(E,1)/len(D)*100

  # normalize data: TODO

  # check if has values higher or lower than the Ag limits
  hasH=len(np.where(F>Ag[-1])[0])
  hasL=len(np.where(F<Ag[0])[0])

  # calc number of percentage circles to draw:
  if not ci:
    if inorm:
      ci=[25, 50, 75]
      g=120
      ncircles=3
    else:
      dcircles=np.array([1, 2, 5, 10, 15, 20, 25, 30, 50])
      ncircles=3
      d=abs(1./(dcircles/max(b))-ncircles)

      i=np.where(d==np.min(d))[0]
      d=dcircles[i[0]]
      if d*ncircles<max(b): ncircles=ncircles+1
      ci=np.arange(1,ncircles+1)*d
      g=ncircles*d
  else:
    ncircles=len(ci)
    g=max(max(ci),max(b))

  # plot axes, percentage circles and percent. data:
  ri=g*ri
  if bg: ax.fill([-rs*g, rl*g, rl*g, -rs*g],[-rs*g, -rs*g, rs*g, rs*g],
                 bg,edgecolor='w',linewidth=LineWidth,label='wr_bg')

  ax.plot([-g-ri, -ri, np.nan, ri, g+ri, np.nan, 0, 0, np.nan, 0, 0],
          [0, 0, np.nan, 0, 0, np.nan, -g-ri, -ri, np.nan, ri, g+ri],
          ':',color=lineColors,linewidth=LineWidth)

  t0=np.arange(0,361)*np.pi/180
  labs=[]
  Ang=np.array([1, 3, 5, 7])/4.*np.pi

  Valign='top', 'top', 'bottom', 'bottom'
  Halign='center', 'left', 'left', 'right'

  for i in range(ncircles):
    x=(ci[i]+ri)*np.cos(t0)
    y=(ci[i]+ri)*np.sin(t0)

    ax.plot(x,y,':',color=lineColors,linewidth=LineWidth);

    if percLabels: ax.text((ci[i]+ri)*np.cos(Ang[quad]),(ci[i]+ri)*np.sin(Ang[quad]),str(ci[i])+'%',
      verticalalignment=Valign[quad],horizontalalignment=Halign[quad],
      backgroundcolor=percBg,fontsize=FontSize)


  # calc colors:
  if not colors:
    cor=range(len(Ag)-1)
    q=pl.cm.ScalarMappable(cmap=cmap)
    q.set_clim([Ag[0], Ag[-2]])
    for j in range(len(Ag)-1):
      cor[j]=q.to_rgba(Ag[j])
  else:
    cor=colors

  # fill data:
  n=np.sum(E,1)
  #if  iflip...
  for i in range(len(Ay)-1):
    if n[i]:
      t=np.linspace(Ay[i],Ay[i+1],20)*np.pi/180
      r1=ri
      for j in range(len(Ag)-1):
        r2=E[i,j]/n[i] *b[i] +r1

        x=np.array(r1*np.cos(t[0]))
        x=np.append(x,r2*np.cos(t))
        x=np.append(x,r1*np.cos(np.flipud(t)))

        y=np.array(r1*np.sin(t[0]))
        y=np.append(y,r2*np.sin(t))
        y=np.append(y,r1*np.sin(np.flipud(t)))

      #if iflip, jcor=length(Ag)-1-j+1;
      #else, jcor=j;
      #end

        if E[i,j]>0: ax.fill(x,y,facecolor=cor[j],linewidth=LineWidth)
        r1=r2;


  # N S E W labels:
  if NSEWlab:
    bg='none';
    args={'backgroundcolor':bg,'fontsize':FontSize}
    ax.text(-g-ri, 0,'WEST', verticalalignment='top',   horizontalalignment='left', **args);
    ax.text( g+ri, 0,'EAST', verticalalignment='top',   horizontalalignment='right',**args);
    ax.text( 0,-g-ri,'SOUTH',verticalalignment='bottom',horizontalalignment='left', **args);
    ax.text( 0, g+ri,'NORTH',verticalalignment='top',   horizontalalignment='left', **args);


  # scale legend:
  L=(g*rl-g-ri)/7.
  h=(g+ri)/10.
  dy=h/3

  x0=g+ri+(g*rl-g-ri)/7.
  x1=x0+L
  y0=-g-ri

  if legType==1: # contimuous
    for j in range(len(Ag)-1):
      lab=str(Ag[j])
      if j==0 and hasL and IncHiLow:
        lab=''

      y1=y0+h
      ax.fill([x0, x1, x1, x0],[y0, y0, y1, y1],facecolor=cor[j],linewidth=LineWidth)
      if legTickLab: ax.text(x1+L/4,y0,lab,verticalalignment='center',fontsize=FontSize)
      y0=y1

    if legTickLab and not (hasH and IncHiLow):
      ax.text(x1+L/4,y0,str(Ag[-1]),verticalalignment='center',fontsize=FontSize)

  elif legType==2:
     for j in range(len(Ag)-1):
      lab=str(Ag[j])+ ' - '+ str(Ag[j+1])
      if j==0 and hasL and  IncHiLow:
        lab='<'+str(Ag[1])

      if j==len(Ag)-2 and hasH and IncHiLow:
        lab='>='+str(Ag[j])

      y1=y0+h
      ax.fill([x0, x1, x1, x0],[y0+dy, y0+dy, y1, y1],facecolor=cor[j],linewidth=LineWidth)
      if legTickLab: ax.text(x1+L/4,(y0+dy+y1)/2,lab,verticalalignment='center',fontsize=FontSize)
      y0=y1


  # title and legend label:
  x=np.mean([-g*rs,g*rl])
  y=np.mean([g+ri,g*rs])
  ax.text(x,y,titStr,horizontalalignment='center',fontsize=FontSize)

  if legType in [0,1]:
    x=x0
    y=y1+dy
    ax.text(x,y,legStr,horizontalalignment='left',verticalalignment='bottom',fontsize=FontSize)


  ax.axis('equal') #'image')
  ax.axis('off')
Beispiel #10
0
    def plot(self, **kargs):
        bathy = kargs.get("bathy", "contourf")
        hvals = kargs.get("hvals", "auto")
        resolution = kargs.get("res", "i")
        rivers = kargs.get("rivers", False)
        parallels = kargs.get("parallels", "auto")
        meridians = kargs.get("meridians", "auto")
        scale = kargs.get("scale", False)
        states = kargs.get("states", False)
        xlim = kargs.get("xlim", False)
        ylim = kargs.get("ylim", False)
        title = kargs.get("title", "auto")
        cmap = kargs.get("cmap", pylab.cm.gist_earth_r)
        proj = kargs.get("proj", "merc")
        ax = kargs.get("ax", False)

        if not ax:
            fig = pylab.figure()
            ax = pylab.axes()
        else:
            fig = ax.figure

        h = np.ma.masked_where(self.mask == 0, self.h)
        xb, yb = self.border()

        xt = ticks.loose_label(self.lon.min(), self.lon.max())
        yt = ticks.loose_label(self.lat.min(), self.lat.max())
        ht = ticks.loose_label_n(self.h.min(), self.h.max(), 7)

        if xlim:
            Lonlims = xlim
        else:
            Lonlims = xt[0], xt[-1]

        if ylim:
            Latlims = ylim
        else:
            Latlims = yt[0], yt[-1]

        if hvals == "auto":
            hvals = ht

        if parallels == "auto":
            parallels = yt
        if meridians == "auto":
            meridians = xt

        if Basemap and proj:
            m = Basemap(
                projection=proj,
                lat_ts=0.0,
                # lon_0=self.lon[0].mean(),
                resolution=resolution,
                urcrnrlon=Lonlims[1],
                urcrnrlat=Latlims[1],
                llcrnrlon=Lonlims[0],
                llcrnrlat=Latlims[0],
            )

            m.drawcoastlines(ax=ax)
            m.fillcontinents(ax=ax, color=(0.7604, 1.0000, 0.7459))
            if rivers:
                m.drawrivers(color="b")

            m.drawcountries(ax=ax)
            # m.drawlsmask()
            # m.drawmapboundary()
            if scale:
                dx = Lonlims[1] - Lonlims[0]
                dy = Latlims[1] - Latlims[0]
                lon = Lonlims[1] - dx / 10
                lat = Latlims[0] + dy / 10
                lon0 = lon
                lat0 = lat
                length = 100

                m.drawmapscale(lon, lat, lon0, lat0, length, ax=ax)

            if states:
                m.drawstates(ax=ax)

            m.drawparallels(parallels, labels=[1, 0, 0, 0], ax=ax)
            m.drawmeridians(meridians, labels=[0, 0, 0, 1], ax=ax)

            x, y = m(self.lon, self.lat)
            pch = False
            if bathy in ["pcolor", "pcolormesh"]:
                pch = ax.pcolormesh(x, y, h, cmap=cmap)
            elif bathy == "contour":
                pch = ax.contour(x, y, h, hvals, cmap=cmap)
            elif bathy == "contourf":
                pch = ax.contourf(x, y, h, hvals, cmap=cmap)

            if pch:
                if m.xmax - m.xmin < m.ymax - m.ymin:
                    orientation = "horizontal"
                else:
                    orientation = "vetical"

                cbh = pylab.colorbar(pch, orientation=orientation, ax=ax)
                cbh.set_label("Depth")
                if title == "auto":
                    ax.set_title(self.name)
                elif title:
                    ax.set_title(title)

            xb, yb = m(xb, yb)
            ax.plot(xb, yb)
            ax.axis([m.xmin, m.xmax, m.ymin, m.ymax])
            return m

        else:
            ax.pcolormesh(self.lon, self.lat, h, cmap=cmap)
            ax.contour(self.lon, self.lat, self.h, hvals, colors="w")
            ax.plot(xb, yb)
Beispiel #11
0
    def plot(self, **kargs):
        bathy = kargs.get('bathy', 'contourf')
        hvals = kargs.get('hvals', 'auto')
        resolution = kargs.get('res', 'i')
        rivers = kargs.get('rivers', False)
        parallels = kargs.get('parallels', 'auto')
        meridians = kargs.get('meridians', 'auto')
        scale = kargs.get('scale', False)
        states = kargs.get('states', False)
        xlim = kargs.get('xlim', False)
        ylim = kargs.get('ylim', False)
        title = kargs.get('title', 'auto')
        cmap = kargs.get('cmap', pylab.cm.gist_earth_r)
        proj = kargs.get('proj', 'merc')
        ax = kargs.get('ax', False)

        if not ax:
            fig = pylab.figure()
            ax = pylab.axes()
        else:
            fig = ax.figure

        h = np.ma.masked_where(self.mask == 0, self.h)
        xb, yb = self.border()

        xt = ticks.loose_label(self.lon.min(), self.lon.max())
        yt = ticks.loose_label(self.lat.min(), self.lat.max())
        ht = ticks.loose_label_n(self.h.min(), self.h.max(), 7)

        if xlim: Lonlims = xlim
        else: Lonlims = xt[0], xt[-1]

        if ylim: Latlims = ylim
        else: Latlims = yt[0], yt[-1]

        if hvals == 'auto': hvals = ht

        if parallels == 'auto': parallels = yt
        if meridians == 'auto': meridians = xt

        if Basemap and proj:
            m = Basemap(
                projection=proj,
                lat_ts=0.0,
                #lon_0=self.lon[0].mean(),
                resolution=resolution,
                urcrnrlon=Lonlims[1],
                urcrnrlat=Latlims[1],
                llcrnrlon=Lonlims[0],
                llcrnrlat=Latlims[0])

            m.drawcoastlines(ax=ax)
            m.fillcontinents(ax=ax, color=(0.7604, 1.0000, 0.7459))
            if rivers: m.drawrivers(color='b')

            m.drawcountries(ax=ax)
            # m.drawlsmask()
            # m.drawmapboundary()
            if scale:
                dx = Lonlims[1] - Lonlims[0]
                dy = Latlims[1] - Latlims[0]
                lon = Lonlims[1] - dx / 10
                lat = Latlims[0] + dy / 10
                lon0 = lon
                lat0 = lat
                length = 100

                m.drawmapscale(lon, lat, lon0, lat0, length, ax=ax)

            if states: m.drawstates(ax=ax)

            m.drawparallels(parallels, labels=[1, 0, 0, 0], ax=ax)
            m.drawmeridians(meridians, labels=[0, 0, 0, 1], ax=ax)

            x, y = m(self.lon, self.lat)
            pch = False
            if bathy in ['pcolor', 'pcolormesh']:
                pch = ax.pcolormesh(x, y, h, cmap=cmap)
            elif bathy == 'contour':
                pch = ax.contour(x, y, h, hvals, cmap=cmap)
            elif bathy == 'contourf':
                pch = ax.contourf(x, y, h, hvals, cmap=cmap)

            if pch:
                if m.xmax - m.xmin < m.ymax - m.ymin:
                    orientation = 'horizontal'
                else:
                    orientation = 'vetical'

                cbh = pylab.colorbar(pch, orientation=orientation, ax=ax)
                cbh.set_label('Depth')
                if title == 'auto': ax.set_title(self.name)
                elif title: ax.set_title(title)

            xb, yb = m(xb, yb)
            ax.plot(xb, yb)
            ax.axis([m.xmin, m.xmax, m.ymin, m.ymax])
            return m

        else:
            ax.pcolormesh(self.lon, self.lat, h, cmap=cmap)
            ax.contour(self.lon, self.lat, self.h, hvals, colors='w')
            ax.plot(xb, yb)
Beispiel #12
0
def wind_rose(D,F,**kargs):
  '''
  Example:
  import numpy as np

  d=np.arange(0,360,10)
  D=np.array(())
  V=np.array(())
  for i in range(len(d)):
    n=d[i]/10.
    D=np.append(D,np.ones(n)*d[i])
    V=np.append(V,np.arange(n))

  wind_rose(D,V)

  '''

  D=np.asarray(D)
  F=np.asarray(F)

  ax          = kargs.get('ax',          pl.gca())
  bg          = kargs.get('bg',          'w')
  dtype       = kargs.get('dtype',       'standard')
  nAngles     = kargs.get('n',           36)
  ri          = kargs.get('ri',          1/30.)
  quad        = kargs.get('quad',        0)
  legType     = kargs.get('legtype',     0)
  percBg      = kargs.get('percbg',      'w')
  titStr      = kargs.get('title',       '')
  legStr      = kargs.get('legend',      '')
  cmap        = kargs.get('cmap',        None)
  colors      = kargs.get('colors',      [])
  Ag          = kargs.get('di',          False) # intensity subdivs
  ci          = kargs.get('ci',          []) # percentage circles
  lineColors  = kargs.get('lcolor',      'k')
  borderColor = kargs.get('bcolor',      False)
  iflip       = kargs.get('iflip',       0)
  inorm       = kargs.get('inorm',       0)
  IncHiLow    = kargs.get('incout',      1) # include values higher and lower that the limits of Ag
  FontSize    = kargs.get('fontsize',    8)
  LineWidth   = kargs.get('linewidth',   0.5)
  legTickLab  = kargs.get('lablegticks', True)
  NSEWlab     = kargs.get('NSEWlab',     True)
  labels      = kargs.get('labels',      True)
  percLabels  = kargs.get('percLabels',  True)

  if not labels:
    legTickLab=NSEWlab=percLabels=False

  # other options:
  # size of the full rectangle:
  rs=1.2
  rl=1.7
  # axes W/H = (rs+rl)/(2*rs)

  # directions conversion:
  if dtype=='meteo': D=np.mod(-90-D,360)


  # angles subdivisons:
  D=np.mod(D,360.)
  Ay=np.linspace(0,360,nAngles+1)-0.5*360/nAngles

  # calc instensity subdivisions:
  if Ag is False:
    from okean import ticks
    Ag=ticks.loose_label_n(F.min(),F.max(),ntick=7)

  E=np.zeros([len(Ay)-1,len(Ag)-1])
  for i in range(len(Ay)-1):
    if i==0:
      I=( (D>=Ay[i]) & (D<Ay[i+1]) ) | (D>=Ay[-1])
    else:
      I=(D>=Ay[i]) & (D<Ay[i+1])

    b=F[I]

    for j in range(len(Ag)-1):
      if j==len(Ag)-2:
        J=((b>=Ag[j]) & (b<=Ag[j+1])) # include data with last Ag
      else:
        J=((b>=Ag[j]) & (b<Ag[j+1]))
      E[i,j]=len(np.where(J)[0])

    if IncHiLow:
      E[i,0]=len(np.where(b<Ag[1])[0])
      E[i,-1]=len(np.where(b>=Ag[-2])[0])

  b=np.sum(E,1)/len(D)*100

  # normalize data: TODO

  # check if has values higher or lower than the Ag limits
  hasH=len(np.where(F>Ag[-1])[0])
  hasL=len(np.where(F<Ag[0])[0])

  # calc number of percentage circles to draw:
  if not ci:
    if inorm:
      ci=[25, 50, 75]
      g=120
      ncircles=3
    else:
      dcircles=np.array([1, 2, 5, 10, 15, 20, 25, 30, 50])
      ncircles=3
      d=abs(1./(dcircles/max(b))-ncircles)

      i=np.where(d==np.min(d))[0]
      d=dcircles[i[0]]
      if d*ncircles<max(b): ncircles=ncircles+1
      ci=np.arange(1,ncircles+1)*d
      g=ncircles*d
  else:
    ncircles=len(ci)
    g=max(max(ci),max(b))

  # plot axes, percentage circles and percent. data:
  ri=g*ri
  if bg: ax.fill([-rs*g, rl*g, rl*g, -rs*g],[-rs*g, -rs*g, rs*g, rs*g],
                 bg,edgecolor='w',linewidth=LineWidth,label='wr_bg')

  ax.plot([-g-ri, -ri, np.nan, ri, g+ri, np.nan, 0, 0, np.nan, 0, 0],
          [0, 0, np.nan, 0, 0, np.nan, -g-ri, -ri, np.nan, ri, g+ri],
          ':',color=lineColors,linewidth=LineWidth)

  t0=np.arange(0,361)*np.pi/180
  labs=[]
  Ang=np.array([1, 3, 5, 7])/4.*np.pi

  Valign='top', 'top', 'bottom', 'bottom'
  Halign='center', 'left', 'left', 'right'

  for i in range(ncircles):
    x=(ci[i]+ri)*np.cos(t0)
    y=(ci[i]+ri)*np.sin(t0)

    ax.plot(x,y,':',color=lineColors,linewidth=LineWidth);

    if percLabels: ax.text((ci[i]+ri)*np.cos(Ang[quad]),(ci[i]+ri)*np.sin(Ang[quad]),str(ci[i])+'%',
      verticalalignment=Valign[quad],horizontalalignment=Halign[quad],
      backgroundcolor=percBg,fontsize=FontSize)


  # calc colors:
  if not colors:
    cor=range(len(Ag)-1)
    q=pl.cm.ScalarMappable(cmap=cmap)
    q.set_clim([Ag[0], Ag[-2]])
    for j in range(len(Ag)-1):
      cor[j]=q.to_rgba(Ag[j])
  else:
    cor=colors

  # fill data:
  n=np.sum(E,1)
  #if  iflip...
  for i in range(len(Ay)-1):
    if n[i]:
      t=np.linspace(Ay[i],Ay[i+1],20)*np.pi/180
      r1=ri
      for j in range(len(Ag)-1):
        r2=E[i,j]/n[i] *b[i] +r1

        x=np.array(r1*np.cos(t[0]))
        x=np.append(x,r2*np.cos(t))
        x=np.append(x,r1*np.cos(np.flipud(t)))

        y=np.array(r1*np.sin(t[0]))
        y=np.append(y,r2*np.sin(t))
        y=np.append(y,r1*np.sin(np.flipud(t)))

      #if iflip, jcor=length(Ag)-1-j+1;
      #else, jcor=j;
      #end

        if E[i,j]>0: ax.fill(x,y,facecolor=cor[j],linewidth=LineWidth)
        r1=r2;


  # N S E W labels:
  if NSEWlab:
    bg='none';
    args={'backgroundcolor':bg,'fontsize':FontSize}
    ax.text(-g-ri, 0,'WEST', verticalalignment='top',   horizontalalignment='left', **args);
    ax.text( g+ri, 0,'EAST', verticalalignment='top',   horizontalalignment='right',**args);
    ax.text( 0,-g-ri,'SOUTH',verticalalignment='bottom',horizontalalignment='left', **args);
    ax.text( 0, g+ri,'NORTH',verticalalignment='top',   horizontalalignment='left', **args);


  # scale legend:
  L=(g*rl-g-ri)/7.
  h=(g+ri)/10.
  dy=h/3

  x0=g+ri+(g*rl-g-ri)/7.
  x1=x0+L
  y0=-g-ri

  if legType==1: # contimuous
    for j in range(len(Ag)-1):
      lab=str(Ag[j])
      if j==0 and hasL and IncHiLow:
        lab=''

      y1=y0+h
      ax.fill([x0, x1, x1, x0],[y0, y0, y1, y1],facecolor=cor[j],linewidth=LineWidth)
      if legTickLab: ax.text(x1+L/4,y0,lab,verticalalignment='center',fontsize=FontSize)
      y0=y1

    if legTickLab and not (hasH and IncHiLow):
      ax.text(x1+L/4,y0,str(Ag[-1]),verticalalignment='center',fontsize=FontSize)

  else:
     for j in range(len(Ag)-1):
      lab=str(Ag[j])+ ' - '+ str(Ag[j+1])
      if j==0 and hasL and  IncHiLow:
        lab='<'+str(Ag[1])

      if j==len(Ag)-2 and hasH and IncHiLow:
        lab='>='+str(Ag[j])

      y1=y0+h
      ax.fill([x0, x1, x1, x0],[y0+dy, y0+dy, y1, y1],facecolor=cor[j],linewidth=LineWidth)
      if legTickLab: ax.text(x1+L/4,(y0+dy+y1)/2,lab,verticalalignment='center',fontsize=FontSize)
      y0=y1


  # title and legend label:
  x=np.mean([-g*rs,g*rl])
  y=np.mean([g+ri,g*rs])
  ax.text(x,y,titStr,horizontalalignment='center',fontsize=FontSize)

  x=x0
  y=y1+dy
  ax.text(x,y,legStr,horizontalalignment='left',verticalalignment='bottom',fontsize=FontSize)


  ax.axis('equal') #'image')
  ax.axis('off')
Beispiel #13
0
  def _slice(self,slc,varname,ind,it0,**opts):
##    border=opts.get('border',1)

    if slc=='ll': x,y=ind

    o=[]
    It,twarn=self.tinds(it0)
    for c,i in enumerate(self):
      meth=getattr(i,'slice'+slc)
      if slc=='uv':  o+=[meth(ind,It[c],**opts)]
      elif slc=='ll':o+=[meth(varname,x,y,It[c],**opts)]
      else:          o+=[meth(varname,ind,It[c],**opts)]
      #if msg[c]:
      #  if o[-1].msg: o[-1].msg+='\n'
      #  o[-1].msg+=msg[c]


    # add filled border for next domain:
    if slc in ['i','j','k','z','iso']:#,'uv']:
      for i in range(len(self)-1):
        xb,yb=self[i+1].grid.border()
        o[i].extra+=[vis.Data(xb,yb)]
        o[i].extra[-1].label='border grid %d'%(i+1)
        #if i>0:
        o[i].extra[-1].config['d1.plot']='fill'
        o[i].extra[-1].config['d1_fill.options']['lw']=0
        o[i].extra[-1].config['d1_fill.options']['facecolor']='w'
        #o[i].extra[-1].config['plot.zorder']=1
        #else:
        #  o[i].extra[-1].config['d1.plot']='plot'
    elif slc=='uv': # for uv, better to mask arrows inside child domains
      if not hasattr(self.grid,'ingrd'): self.grid._set_ingrid('p')
      from functools import reduce
      for c,i in enumerate(o):
        if not i.v is None:
          if len(self.grid[c].ingrd_p):
            mask=reduce(lambda i,j: i&j,self.grid[c].ingrd_p)
            mask=mask&(~i.v.mask)
            i.nmask=mask # nested domains mask
            i.v.mask=i.v.mask|i.nmask
          else: i.nmask=None



    # vfield settings:
    if not o[0].v is None:
      vfield=o[0].get_param('vfield')
      if not vfield['options']['scale']:
        vfield['options']={'units':'width','scale':10}

      # use same vfield settings for all slices:
      for i in o:
        for k in vfield: i.config['vfield.'+k]=vfield[k]

      # no key for slices[1:]:
      for i in o[1:]:
        i.config['vfield.key_XYU']=0,0,0


    # field settings:
    if not o[0].v is None:
      field=o[0].get_param('field')

      if field['clim'] is False:
        if np.iscomplexobj(o[0].v):
          field['clim']=np.abs(o[0].v).min(),np.abs(o[0].v).max()
        else:
          field['clim']=o[0].v.min(),o[0].v.max()

        if field['clim'][0]==field['clim'][1]:
          field['clim']=field['clim'][0]-1,field['clim'][0]+1

      if field['cvals'] is False:
        tk=ticks.loose_label_n(field['clim'][0],field['clim'][1],7)
        field['cvals']=tk

      # use same field settings for all slices:
      for i in o:
        for k in field: i.config['field.'+k]=field[k]


    # also same settings for extras like bathy contours:
    Lab=['bathy']
    for lab in Lab:
      for e in o[0].extra:
        if e.label==lab and not e.v is None:
          field=e.get_param('field')
          if field['clim'] is False: field['clim']=e.v.min(),e.v.max()
          if field['cvals'] is False or  not calc.isiterable(field['cvals']):
            # the isiterable here is because it can be an integer (nof fixed set)
            tk=ticks.loose_label_n(field['clim'][0],field['clim'][1],3)
            field['cvals']=tk

      for i in o:
        for e in i.extra:
          if e.label==lab:
            for k in field: e.config['field.'+k]=field[k]

    # add border for all domains:
#    xb,yb=self.grid.border()
#    o[0].extra+=[vis.Data(x=xb,v=yb)]
    borders=[]
    for i in self:
      xb,yb=i.grid.border()
      c=vis.Data(x=xb,v=yb)
      c.set_param(d1_line__options=dict(lw=0.5,color='k',ls='-'))
      borders+=[c]

    o[-1].extra+=borders

    # set zorder:
    c=1
    for i in o:
      c+=0.1
      i.config['plot.zorder']=c
      for j in i.extra:
        c+=0.1
        j.config['plot.zorder']=c

    # place some stuff above continents:
    z=o[0].config['proj.continents']['zorder']
    z+=0.1
    # vfield:
    if slc=='uv':
      for i in o: i.config['plot.zorder']=z

    # place borders above continents:
    for b in borders: b.config['plot.zorder']=z


    return vis.MData(o,warnings=twarn)