:name: ensemble
:description: plots for ensemble members
:ndims: 2
:nvars: 1
:vizshot_method: ensemble
:setting_html: |
  <div>
    <label for="analysis_ensemble_style">style</label>
    <select name="analysis[ensemble_style]" id="analysis_ensemble_style">
      <option>lines</option>
      <option>bar</option>
      <option>box</option>
      <option>percentile</option>
    </select>
  </div>

:attributes:
- :name: style
  :default: lines
  :type: string
  :parser: ggraph
:script: |
  newfrm = opt.delete(:newfrm)
  GGraph::ensemble(gphys, newfrm, opt)

:ggraph: |
  gropn_1_if_not_yet
  unless defined?(@@ensemble_options)
    @@ensemble_options = Misc::KeywordOptAutoHelp.new(
      ['title', nil, 'Title of the figure'],
      ['annotate', true, 'if false, do not put texts on the right margin even when newframe==true'],
      ['index', 1, 'mark index'],
      ['type', 2, 'mark type'],
      ['style', 'lines', 'plot style'],
      ['transpose', false, 'transpose']
    )
  end
  opts = @@ensemble_options.interpret(options)
  gphys = gphys.first2D.copy
  axnames = gphys.axnames
  td = axnames.index("validtime")
  md = axnames.index("member")
  if td && md.nil?
    md = td==0 ? 1 : 0
  elsif md && td.nil?
    td = md==0 ? 1 : 0
  elsif td.nil? && md.nil?
    if transpose
      td = 0
      md = 1
    else
      td = 1
      md = 0
    end
  end
  t = gphys.coord(td)
  nm = gphys.coord(md).length
  data = gphys.data
  if newframe
    fig(t,data)
    axes(t,nil)
    title( opts['title'] )
    annotate(gphys.lost_axes) if opts['annotate']
  end
  ind = Array.new(2)
  ind[td] = true
  data = data.val
  t = t.val
  case opts['style']
  when "lines"
    nm.times{|n|
      ind[md] = n
      DCL::sgplzu(t, data[*ind], 1, 1)
    }
  when "bar"
    mean = data.mean(md)
    std = data.stddev(md)
    DCL::sgplzu(t, mean, 1, 2)
    DCL::uverbz(t, mean-std, mean+std, 1, 1, 0.01)
  when "box"
    mean = data.mean(md)
    std = data.stddev(md)
    max = data.max(md)
    min = data.min(md)
    DCL::uvbrfz(t, mean-std, mean+std, 1, 1, 0.01)
    DCL::uverbz(t, mean-std, min, 1, 1, 0.01)
    DCL::uverbz(t, mean+std, max, 1, 1, 0.01)
  when "percentile"
    data = data.transpose(1,0).sort(0)
    nl = 5
    cols = [98999, 95999, 91999, 88999, 84999]
    dn = nm.to_f/(nl*2-1)
    nh = (nm-1).to_f/2
    nl.times{|n|
      i = (nh+dn*(nl-n-0.5)).round
      j = (nh-dn*(nl-n-0.5)).round
      i = -1 if i >= nm
      j = 0 if j < 0
      d1 = data[i,true]
      d2 = data[j,true]
      DCL::uvdifz(t, d1, d2, cols[n], cols[n])
      DCL::sgplzu(t, d1, 1, 1)
      DCL::sgplzu(t, d2, 1, 1)
    }
  else
    raise "style (#{opts['style']}) is invalid"
  end

