示例#1
0
文件: t.py 项目: zhangweiiowa/qtcm
    def test_exceptions(self):
        """Test some exceptions.
        """
        #- Run a 5 day test case for use to test method against:

        model = qtcm.Qtcm(compiled_form='parts', ntout=1, ntouti=1)
        rundirname = 'test'
        dirbasepath = tempfile.mkdtemp()
        model.outdir.value = dirbasepath
        model.runname.value = rundirname
        model.bnddir.value = \
            os.path.join( os.getcwd(), 'bnddir', 'r64x42' )
        model.SSTdir.value = \
            os.path.join( os.getcwd(), 'bnddir', 'r64x42', 'SST_Reynolds' )
        model.lastday.value = 5
        model.run_session()

        self.failUnlessRaises(ValueError,
                              model.plotm,
                              'Qc',
                              lat=0.0,
                              lon=[20, 100],
                              time=[0, 4])

        if os.path.exists(dirbasepath): shutil.rmtree(dirbasepath)
        if os.path.exists('qtcm_00010101.restart'):
            os.remove('qtcm_00010101.restart')
示例#2
0
def qtcminit_runlist_to_latex(path=os.curdir):
    """Write LaTeX code describing the qtcminit runlist.

    The file qtcminit_runlist.tex is outputted by this function,
    which is the qtcminit runlist in the runlists attribute.  The
    file is formatted so it can go into a codeblock.

    This method works best if this module is located in the same
    directory as path, i.e., that the output written out from the
    method is also in path.

    Keyword Input Parameter:
    * path:  Path of the location to write out the files containing
      the LaTeX tables to, specified in file.  String.  Default is
      os.curdir.
    """
    #- Instantiate a model:

    model = qtcm.Qtcm(compiled_form='parts')

    #- Convert code into string.  Put a carriage return after a
    #  comma, i.e., between elements:

    ilistname = 'qtcminit'
    output = str(model.runlists[ilistname]).strip()
    output = output.replace(',', ', \\\\\n')

    #- Replace special LaTeX characters.  The characters must be
    #  replaced in the order given in replace_list, otherwise there
    #  will be errors.  Note this dictionary and list have curly
    #  braces, because this LaTeX file has no environments:

    replace_dict = {
        '%': '\\%',
        '$': '\\$',
        '#': '\\#',
        '_': '\\_',
        '^2': '$^2$',
        '^3': '$^3$',
        '~': '$\\sim$',
        '<': '$<$',
        '>': '$>$',
        '{': '\\{',
        '}': '\\}'
    }
    replace_list = ['%', '$', '#', '_', '^2', '^3', '~', '<', '>', '{', '}']

    for istr in replace_list:
        output = output.replace(istr, replace_dict[istr])

    #- Add comment line at top and write file:

    output = """% This file is automatically generated by
% code_to_latex.py.  It lists the code of the qtcminit
% runlist.

""" + output

    fn = os.path.join(path, 'qtcminit_runlist.tex')
    fileobj = open(fn, mode='w')
    fileobj.write(output)
    fileobj.close()
示例#3
0
def write_parts_init_to_latex(path=os.curdir):
    """Write LaTeX table of initial field values.

    The "initial field values" are the state of all the fields that
    are Python-accessible prior to the beginning of looping at the
    atmosphere-ocean coupling step.  Two tables are output, one
    with scalars and the other with arrays.  The two files written
    out are init_scalars.tex and init_arrays.tex, in the path path.

    Note that this method assumes that model boundary condition
    files are in ../../test/bnddir, relative to path, which is the
    directory configuration if this script is in doc/latex and
    bnddir is in ../../test.  This method conducts the beginnings
    of a model run with output written to a temporary file generated
    by tempfile.mkdtemp().  The temporary directory is deleted at
    the end of this partial model run.

    This method works best if this module is located in the same
    directory as path, i.e., that the output written out from the
    method is also in path.  Numerical values are rounded using the
    %g format code.

    Keyword Input Parameter:
    * path:  Path of the location to write out the files containing
      the LaTeX tables to, specified in file.  String.  Default is
      os.curdir.
    """
    #- Make a model "run", at least as far as to get initialization.
    #  Use the boundary conditions in ../../test/bnddir:

    model = qtcm.Qtcm(compiled_form='parts')
    rundirname = 'test'
    dirbasepath = tempfile.mkdtemp()
    model.outdir.value = dirbasepath
    model.runname.value = rundirname
    model.bnddir.value = \
        os.path.join( path, os.pardir, os.pardir, 'test',
                      'bnddir', 'r64x42' )
    model.SSTdir.value = \
        os.path.join( path, os.pardir, os.pardir, 'test',
                      'bnddir', 'r64x42', 'SST_Reynolds' )
    model.lastday.value = 0
    model.run_session()

    if os.path.exists(dirbasepath): shutil.rmtree(dirbasepath)
    if os.path.exists('qtcm_00010101.restart'):
        os.remove('qtcm_00010101.restart')

    #- Set LaTeX file headers:

    header_scalars = """
\\begin{longtable}{l|c|c|p{0.42\\linewidth}}
\\textbf{Field} & \\textbf{Value} & \\textbf{Units} & 
                                \\textbf{Description} \\\\
\\hline
\\endhead
"""
    header_arrays = """
\\begin{longtable}{l|c|c|c|c|p{0.3\\linewidth}}
\\textbf{Field} & \\textbf{Shape} & \\textbf{Max} & \\textbf{Min} &
                                \\textbf{Units} & \\textbf{Description} \\\\
\\hline
\\endhead
"""

    #- Write body for table:

    qtcm_fields_ids_sorted = copy.copy(qtcm_fields_ids)
    qtcm_fields_ids_sorted.sort()
    body_scalars = ''
    body_arrays = ''

    for ikey in qtcm_fields_ids_sorted:

        ifield = getattr(model, ikey)

        long_name = str(ifield.long_name).strip()  #+ capitalize
        if len(long_name) > 0:  #  first letter
            long_name0 = long_name[0].capitalize()  #  of long_name
            long_name = long_name0 + long_name[1:]

        if N.rank(ifield.value) == 0:
            if type(ifield.value) == type('a'):
                if ifield.id != 'SSTmode':
                    value = 'value varies'
                else:
                    value = ifield.value.strip()
            else:
                value = '%g' % ifield.value  #+ round value
                value = value.strip()
            addline = '\\vars{' + ikey.strip() + '} & ' + \
                      value + ' & ' + \
                      str(ifield.units).strip() + ' & ' + \
                      long_name + ' \\\\\n'
            body_scalars = body_scalars + addline

        else:
            shpval = N.shape(ifield.value)
            maxval = N.max(ifield.value)
            minval = N.min(ifield.value)

            addline = '\\vars{' + ikey.strip() + '} & ' + \
                      str(shpval).strip() + ' & ' + \
                      ('%g' % maxval).strip() + ' & ' + \
                      ('%g' % minval).strip() + ' & ' + \
                      str(ifield.units).strip() + ' & ' + \
                      long_name + ' \\\\\n'
            body_arrays = body_arrays + addline

    #- Replace special LaTeX characters.  The characters must be
    #  replaced in the order given in replace_list, otherwise there
    #  will be errors.  Set header comment line:

    replace_dict = {
        '%': '\\%',
        '$': '\\$',
        '#': '\\#',
        '_': '\\_',
        '^2': '$^2$',
        '^3': '$^3$',
        '~': '$\\sim$',
        '<': '$<$',
        '>': '$>$'
    }
    replace_list = ['%', '$', '#', '_', '^2', '^3', '~', '<', '>']

    for istr in replace_list:
        body_scalars = body_scalars.replace(istr, replace_dict[istr])
        body_arrays = body_arrays.replace(istr, replace_dict[istr])

    header_comment = """% This file is automatically generated by the script
% code_to_latex.py in the doc/latex directory.  It is based
% upon the values found after model initialization, and should
% not be hand-edited if you want the values to correspond to
% the values in a Qtcm instance, for compiled_form='parts'.

"""

    #- Write footer for table:

    footer = """\\end{longtable}
"""

    #- Check there are no occurences of ^ that are not math-related:

    for istr in [
            header_comment, header_scalars, body_scalars, header_arrays,
            body_arrays, footer
    ]:
        numcaret = istr.count('^')
        nummath = istr.count('$^')
        if numcaret != nummath:
            raise ValueError, 'unhandled carets exist'

    #- Write out to files and delete model instance:

    fn = os.path.join(path, 'init_scalars.tex')
    fileobj = open(fn, mode='w')
    fileobj.write(header_comment + header_scalars + body_scalars + footer)
    fileobj.close()

    fn = os.path.join(path, 'init_arrays.tex')
    fileobj = open(fn, mode='w')
    fileobj.write(header_comment + header_arrays + body_arrays + footer)
    fileobj.close()

    del model
示例#4
0
def snapshot_vars_to_latex(path=os.curdir):
    """Write LaTeX code describing the variables of a snapshot.

    The file snapshot_vars.tex is outputted by this function, which
    lists as a table the variables saved in a snapshot.

    This method works best if this module is located in the same
    directory as path, i.e., that the output written out from the
    method is also in path.

    Keyword Input Parameter:
    * path:  Path of the location to write out the files containing
      the LaTeX tables to, specified in file.  String.  Default is
      os.curdir.
    """
    #- Make a model 2 day run to get variables to take a snapshot of.
    #  Use the boundary conditions in ../../test/bnddir:

    model = qtcm.Qtcm(compiled_form='parts')
    rundirname = 'test'
    dirbasepath = tempfile.mkdtemp()
    model.outdir.value = dirbasepath
    model.runname.value = rundirname
    model.bnddir.value = \
        os.path.join( path, os.pardir, os.pardir, 'test',
                      'bnddir', 'r64x42' )
    model.SSTdir.value = \
        os.path.join( path, os.pardir, os.pardir, 'test',
                      'bnddir', 'r64x42', 'SST_Reynolds' )
    model.lastday.value = 2
    model.run_session()
    model.make_snapshot()

    if os.path.exists(dirbasepath): shutil.rmtree(dirbasepath)
    if os.path.exists('qtcm_00010102.restart'):
        os.remove('qtcm_00010102.restart')

    #- Create table:

    header = """
\\begin{longtable}{l|c|c|p{0.4\\linewidth}}
\\textbf{Field} & \\textbf{Shape} &
                                \\textbf{Units} & \\textbf{Description} \\\\
\\hline
\\endhead
    """

    body = ''
    sorted_keys = model.snapshot.keys()
    sorted_keys.sort()
    for ikey in sorted_keys:
        ivar = model.snapshot[ikey]  #+ Set variable
        long_name = str(ivar.long_name).strip()  #+ Capitalize
        if len(long_name) > 0:  #  first letter
            long_name0 = long_name[0].capitalize()  #  of long_name
            long_name = long_name0 + long_name[1:]

        body = body \
            + "\\vars{" + ivar.id + "} & "

        if N.isscalar(ivar.value):  #+ Add value shape
            body = body + "     & "
        else:
            body = body + str(N.shape(ivar.value)).strip() + " & "

        body = body \
            + ivar.units.strip() + " & " \
            + long_name + " \\\\\n"

    footer = """\\end{longtable}"""

    output = header + body + footer

    #- Replace special LaTeX characters.  The characters must be
    #  replaced in the order given in replace_list, otherwise there
    #  will be errors.  Set header comment line:

    replace_dict = {
        '%': '\\%',
        '$': '\\$',
        '#': '\\#',
        '_': '\\_',
        '^2': '$^2$',
        '^3': '$^3$',
        '~': '$\\sim$',
        '<': '$<$',
        '>': '$>$'
    }
    replace_list = ['%', '$', '#', '_', '^2', '^3', '~', '<', '>']

    for istr in replace_list:
        output = output.replace(istr, replace_dict[istr])

    #- Add comment line at top and write file:

    output = """% This file is automatically generated by
% code_to_latex.py.  It lists all the snapshot variables.

""" + output

    fn = os.path.join(path, 'snapshot_vars.tex')
    fileobj = open(fn, mode='w')
    fileobj.write(output)
    fileobj.close()
示例#5
0
def runlists_to_latex(path=os.curdir):
    """Write LaTeX code describing the standard runlists.

    The file runlists.tex is outputted by this function, which is
    a table of all runlists in the runlists attribute.

    This method works best if this module is located in the same
    directory as path, i.e., that the output written out from the
    method is also in path.

    Keyword Input Parameter:
    * path:  Path of the location to write out the files containing
      the LaTeX tables to, specified in file.  String.  Default is
      os.curdir.
    """
    #- Instantiate a model:

    model = qtcm.Qtcm(compiled_form='parts')

    #- Create table header and footer:

    header = """
\\begin{longtable}{l|lc}
\\textbf{Run List Name/Description} & \\textbf{List Element(s) Name(s)} & 
                                                   \\textbf{\\# Arg(s)} \\\\
\\hline
\\endhead
"""

    footer = """\\end{longtable}"""

    #- Cycle through all run lists and write out all into table:

    sorted_list_names = model.runlists.keys()
    sorted_list_names.sort()

    output = ''
    for ilistname in sorted_list_names:

        #+ num entries for each run list:
        nentries = len(model.runlists[ilistname])

        #+ runlist name and description:
        output = output + '\\multirow{' + str(nentries) \
               + '}{*}{\\parbox{0.4\\linewidth}{' \
               + ilistname.strip() + ' (' \
               + model._runlists_long_names[ilistname].strip() + ')}} & '

        ielem = model.runlists[ilistname][0]  #+ first item in
        if type(ielem) == type({}):  #  runlist
            elem_name = ielem.keys()[0].strip()
            output = output + elem_name \
                   + ' & ' + str(len(ielem[elem_name])).strip() \
                   + '\\\\\n'
        else:
            output = output + ielem.strip() + ' & None \\\\\n'

        for ielem in model.runlists[ilistname][1:]:  #+ other items in
            if type(ielem) == type({}):  #  runlist
                elem_name = ielem.keys()[0].strip()
                output = output + '         & ' + elem_name \
                       + ' & ' + str(len(ielem[elem_name])).strip() \
                       + '\\\\\n'
            else:
                output = output + '         & ' \
                       + ielem.strip() + ' & None \\\\\n'

        if ilistname == sorted_list_names[-1]:  #+ line under runlist
            pass  #  except at end
        else:
            output = output + "\\hline\n"

    #- Replace special LaTeX characters.  The characters must be
    #  replaced in the order given in replace_list, otherwise there
    #  will be errors.  Set header comment line:

    replace_dict = {
        '%': '\\%',
        '$': '\\$',
        '#': '\\#',
        '_': '\\_',
        '^2': '$^2$',
        '^3': '$^3$',
        '~': '$\\sim$',
        '<': '$<$',
        '>': '$>$'
    }
    replace_list = ['%', '$', '#', '_', '^2', '^3', '~', '<', '>']

    for istr in replace_list:
        output = output.replace(istr, replace_dict[istr])

    #- Add comment line at top and write file:

    output = """% This file is automatically generated by
% code_to_latex.py.  It lists all the standard 
% runlists in the class.

""" + header + output + footer

    fn = os.path.join(path, 'runlists.tex')
    fileobj = open(fn, mode='w')
    fileobj.write(output)
    fileobj.close()