def put_content(self, file_name):
        """
        @brief Writes the liquid boundaries file

        @param file_name (string): name of the liquid boundaries file
        """

        # standard part of the Conlim
        core = []
        for ifr in range(self.nptfr):
            if self.index[ifr] != 0:
                line = (' '.join(['{0[' + repr(i) + ']}' \
                            for i in range(len(self.bor[ifr]))]))\
                     .format(self.bor[ifr])
                if self.nptir != {} and self.ifapar != {}:
                    line += ' ' + repr(self.por[ifr][0])
                    line += ' ' + repr(float(self.por[ifr][1]))
                    line += ' ' + repr(float(self.por[ifr][2]))
                    line += ' ' + repr(self.por[ifr][3])
                core.append(line)

        if self.nptir != {} and self.ifapar != {}:
            # parrallel part 1 of the Conlim -- format with i7 /!\
            ntr = self.nptir.keys()
            ntr.sort()
            core.append(str(len(ntr)))
            for itr in ntr:
                line = self.nptir[itr]
                line.sort()
                line.extend([-1, -1, -1, -1, -1, -1, -1, -1, -1, -1])
                s_line = repr(itr+1).rjust(7) + ' ' + \
                    repr(line[0]).rjust(7) + ' ' + \
                    repr(line[1]).rjust(7) + ' ' + \
                    repr(line[2]).rjust(7) + ' ' + \
                    repr(line[3]).rjust(7) + ' ' + \
                    repr(line[4]).rjust(7) + ' ' + \
                    repr(line[5]).rjust(7) + ' ' + \
                    repr(line[6]).rjust(7) + ' ' + \
                    repr(line[7]).rjust(7) + ' ' + \
                    repr(line[8]).rjust(7)
                core.append(s_line)
        # parrallel part 2 of the Conlim -- format with i9 /!\
            ntr = self.ifapar.keys()
            ntr.sort()
            core.append(str(len(ntr)))
            for itr in ntr:
                line = self.ifapar[itr]
                s_line = repr(itr+1).rjust(9) + ' ' + \
                    repr(line[1]).rjust(9) + ' ' + \
                    repr(line[3]).rjust(9) + ' ' + \
                    repr(line[5]).rjust(9) + ' ' + \
                    repr(line[0]+1).rjust(9) + ' ' + \
                    repr(line[2]+1).rjust(9) + ' ' + \
                    repr(line[4]+1).rjust(9)
                core.append(s_line)

        core.append("")
        put_file_content(file_name, core)
Ejemplo n.º 2
0
def run_partel(partel, par_file, file_format, conlim, ncsize, bypass,
               section_name, zone_name, weir_name, geom, fmtgeom, i_part,
               concat):
    """
    @brief Runs PARTEL

    @param partel (string): the path of partel
    @param par_file (string): the name of the PARTEL file
    @param file_format (string): the format of the filee to partition
    @param conlim (string): the name of the *.cli file
    @param ncsize (int): the number of processors
    @param bypass (boolean): continue execution after exception was
        raised if True, kill the execution otherwise
    @param section_name (string): path to the section ascii input file. This
        file has to be split by partel at the same time as the geometry file.
        To do so, partel needs to know its name, which is why it is returned
        by process_lit.
    @param zone_name (string): path to the zone ascii input file. This file
        has the same treatment as the one above.
    @param weir_name (string): path to the weir ascii input file. This file
        has the same treatment as the one above.
    @param fmtgeom (string): format of the geometry file (serafin, serafind,
        med)
    @param i_part (int): type of partitionner, 1:metis; 2: scotch
    @param concat (boolean): If output is concatenate

    @return void
    """
    partel_input = 'partel_' + par_file + '.par'
    partel_log = 'partel_' + par_file + '.log'
    put_file_content(partel_input, [
        par_file, file_format, conlim,
        str(ncsize),
        str(i_part), section_name, zone_name, weir_name, geom, fmtgeom, concat,
        ''
    ])
    par_cmd = partel.replace('<partel.log>', partel_log)\
                    .replace('<partel.par>', partel_input).split(';')

    mes = Messages(size=10)
    for par in par_cmd:
        print('     +> ' + par)
        tail, code = mes.run_cmd(par, bypass)
        if code != 0:
            if path.exists(partel_log):
                log = "Here is the log:\n"+ \
                      '\n'.join(get_file_content(partel_log))
            else:
                log = "No log available check command:\n" + par_cmd
            raise TelemacException(\
                     'Could not split your file '+par_file\
                     +' with the error as follows:'\
                     +'\n        '+tail\
                     +'\n\n'+log)
def process_config(lang):
    """
    @brief Process the CONFIG file

    @param lan (int) Language to write in file (1:French, 2:English)

    @return True when file is correctly filled

    """

    # ~~ create CONFIG ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    put_file_content('CONFIG', ['2' if lang == 'en' else '1', '6', ''])
    return True
Ejemplo n.º 4
0
def run_gretel(gretel,
               gre_file,
               file_format,
               geom,
               geo_format,
               bnd,
               ncsize,
               nplan,
               method=1,
               bypass=False):
    """
    @brief Runs GRETEL, the functions that merges results

    @param gretel (string): the path of gredel
    @param gre_file (string): the name of the GRETEL file
    @param file_format (string): format of the GRETEL file
    @param geom (string): name of the geometry file
    @param geo_format (string): format of the geometry file
    @param bnd (string): name of the boundary file
    @param ncsize (int): number of processors
    @param nplan (int): number of vertical layers
    @param method (int): method for data merging
    @param bypass (boolean): continue execution after exception was
        raised if True, kill the execution otherwise

    @return None
    """

    # ~~ Run GRETEL ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    gretel_par = 'gretel_' + gre_file + '.par'
    gretel_log = 'gretel_' + gre_file + '.log'
    put_file_content(gretel_par, [
        geom, geo_format, bnd, gre_file, file_format,
        str(ncsize),
        str(nplan),
        str(method)
    ])
    mes = Messages(size=10)
    cmd = '{} < {} >> {}'.format(gretel, gretel_par, gretel_log)
    print('     +> ' + cmd)
    tail, code = mes.run_cmd(cmd, bypass)
    if code != 0:
        if path.exists(gretel_log):
            log = "Here is the log:\n" + \
                  '\n'.join(get_file_content(gretel_log))
        else:
            log = "No log available check command:\n" + cmd
        raise TelemacException('Could not split your file ' + gre_file +
                               ' (runcode=' + str(code) +
                               ') with the error as follows:' + '\n        ' +
                               tail + '\n\n' + log)
Ejemplo n.º 5
0
    def run_hpc_exe(self, options, job_id=''):
        """
        Run only the execution of telemac-mascaret executable in job scheduler

        @return job_id (integer) Id of the job that was launched
        """
        # /!\ This is being done in parallel when multiple cas_files
        # if not hpcpass:
        chdir(self.working_dir)
        # ~~> HPC Command line launching runcode
        hpccmd = get_hpc_cmd(self.cfg['HPC']).replace('<root>',
                                                      self.cfg['root'])
        hpccmd = hpccmd.replace('<wdir>', self.working_dir)
        if 'id_log' in options:
            hpccmd = hpccmd.replace('<id_log>', options.id_log)
        else:
            hpccmd = hpccmd.replace('<id_log>', 'id.log')
        # ~~> HPC dependency between jobs
        hpcjob = get_hpc_depend(self.cfg['HPC'])
        if hpcjob != '' and job_id != '':
            hpccmd = hpccmd + ' ' + hpcjob.replace('<jobid>', job_id)
        # ~~> HPC queueing script
        stdin_file = self.cfg['HPC']['STDIN'][0]  # only one key for now
        stdin = self.cfg['HPC']['STDIN'][1]
        stdin, sortie = self.fill_hpc_stdin(stdin, options)
        # working from working dir
        stdin = stdin.replace('<wdir>', self.working_dir)
        # ~~> Recreate the <mpi_exec> (option --hpc)
        stdin = stdin.replace('<exename>', self.run_cmd)
        # /!\ serial mode
        stdin = stdin.replace('<mpi_cmdexec>', self.run_cmd)

        # ~~> Write to HPC_STDIN
        chdir(self.working_dir)
        put_file_content(stdin_file, stdin.split('\n'))

        # ~~> here you go run
        run_code(hpccmd, sortie)

        job_id = get_file_content(sortie)[0].strip()
        print('... Your simulation (' + self.steering_file +
              ') has been launched through the queue.\n')
        print('   +> You need to wait for completion before re-collecting'
              'files using the option --merge\n')

        return job_id
Ejemplo n.º 6
0
    def put_content(self, file_name, head=None):

        geo = []
        # assuming the first polygon is the outside domain
        i_p = 0
        geo.extend(self.write_polygon(self.poly[i_p]))
        # add the other polygons
        for i_p in range(1, self.npoly):
            geo.extend(self.write_polygon(self.poly[i_p]))

        # make up surface with wholes
        psurf = self.isurf[-1]
        geo.append('Plane Surface(' + str(psurf + 1) + ') = {' +
                   ','.join([str(i) for i in self.iloop[1:]]) + '};')
        self.isurf.append(psurf + 1)

        # write up
        put_file_content(file_name, geo)
Ejemplo n.º 7
0
def put_lqd(fle, head, vrs, date0, time, xyz):

    # ~~ Write head ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    core = head
    from datetime import datetime
    core.append("#Date&Time: " +
                datetime(*date0).strftime("%d/%m/%Y %H:%M:%S"))

    names = 'T'
    units = 's'
    if xyz.ndim == 2:
        for name, unit in vrs:
            names += ' ' + name.strip().replace(' ', '_')
            units += ' ' + unit.strip().replace(' ', '_')
        core.append(names + '\n' + units)
    elif xyz.ndim == 3:
        for ivar in range(len(vrs[0])):
            for inod in vrs[1]:
                names += ' ' + vrs[0][ivar][0].strip().replace(' ', '_') + \
                            '(' + str(inod) + ')'
                units += ' ' + vrs[0][ivar][1].strip().replace(' ', '_')
        core.append(names + '\n' + units)
    if xyz.ndim == 2:
        for itim in range(xyz.shape[1]):
            line = str(time[itim])
            for ivar in range(xyz.shape[0]):
                line += ' ' + str(xyz[ivar][itim])
            core.append(line)
    elif xyz.ndim == 3:
        for itim in range(xyz.shape[2]):
            line = str(time[itim])
            for ivar in range(xyz.shape[0]):
                for inod in range(xyz.shape[1]):
                    line += ' ' + str(xyz[ivar][inod][itim])
            core.append(line)

    # ~~ Put all ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    put_file_content(fle, core)

    return
def put_scan_content(fle, root, content):
    """
         title: Writer of the cmdf file.
         brief:See format description at get_scan_content()
         @param
         @param fle(string) name of the cmdf file (with its path) to be saved as
         @param root(sting)  root of the system to replace reference to <root>
         @param bypass(boolean) whether exception raised should be bypassed or
                                not
         @return None
    """

    # ~~> return lines to be stored
    lines = []

    # ~~ Write-up [general] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    if 'general' in content:
        lines.append('[general]' + '\n' + 'path: ' +
                     content['general']['path'].replace(root, '<root>')\
                     .replace(sep, '|') +
                     '\n' + 'module: ' + content['general']['module'])
        lines.append('liborder: ' + ' '.join(content['general']['liborder']))
        lines.append('name: ' + content['general']['name'])
        if 'external' in content['general']:
            lines.append('external: ' + content['general']['external'])

    # ~~ Write-up [sections] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    for lib in sorted(content.keys()):
        if lib == 'general':
            continue
        lines.append('\n[' + lib + ']' + '\n' + 'path: ' +
                     content[lib]['path'].replace(root, '<root>')\
                     .replace(sep, '|') + '\n' +
                     'files: ' + '\n  '.join(content[lib]['files']))

    # ~~ Store to cmdf file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    put_file_content(fle, lines)

    return
Ejemplo n.º 9
0
    def generate_mpi_files(self):
        """
        Generate the PARAL and HOSTFILE files need by telemac-mascaret
        """

        if self.cfg['MPI'] != {}:
            # ~~> MPI host file ( may be re-written by the HPC INFILE script )
            hostfile = self.cfg['MPI']['HOSTFILE']
            hosts = []
            n = 0
            while n < self.ncsize:
                for i in self.cfg['MPI']['HOSTS'].split():
                    hosts.append(i)
                    n += 1
                    if n == self.ncsize:
                        break
            chdir(self.working_dir)
            # ~~> Creating the HOST file
            put_file_content(hostfile, hosts)
            # ~~> Creating the PARA file
            put_file_content('PARAL', [
                str(self.ncsize),
                str(len(self.working_dir + sep)), self.working_dir + sep, ''
            ])
Ejemplo n.º 10
0
def put_xyn(fle, head, file_type, xyz):

    # ~~ Write head ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    core = head
    # if head != []: core = head
    # <else: core = [':FileType '+file_type+' ASCII EnSim 1.0',
    #   ':Application BlueKenue', ':Version 3.2.24',
    #   ':WrittenBy sebourban', ':CreationDate Thu, Dec 08, 2011 02:47 PM',
    #   ':Name ' + path.basename(file_name),
    #   ':AttributeUnits 1 m',
    #   ':EndHeader' ]

    # ~~ Write body ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    if file_type == 'xy':
        for _ in xyz:
            core.append(str(xyz[0])+' '+str(xyz[1]))
    elif file_type == 'xyz':
        for _ in xyz:
            core.append(str(xyz[0])+' '+str(xyz[1])+' '+str(xyz[2]))

    # ~~ Put all ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    put_file_content(fle, core)

    return
def main():
    """
        Main function of doxygenTELEMAC
    """
    bypass = False  # /!\ Temporary bypass for subroutine within programs

# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
# ~~~~ Reads config file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    print('\n\nLoading Options and Configurations\n'+'~'*72+'\n')
    parser = ArgumentParser(\
        formatter_class=RawDescriptionHelpFormatter,
        description=('''\n
Generate the DOXYGEN documentation of the whole TELEMAC system.
        '''),
        usage=' (--help for help)\n---------\n       =>  '\
                '%(prog)s [options] \n---------')
    parser = add_config_argument(parser)
    parser.add_argument(\
        "-d", "--doxydir",
        dest="doxyDir", default='',
        help="specify the root, default is taken from config file")
    parser.add_argument(\
        "-m", "--modules",
        dest="modules", default='',
        help="specify the list modules, default is taken from config file")
    options = parser.parse_args()


# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
# ~~~~ Environment ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    update_config(options)

# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
# ~~~~ banners ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    svn_banner(CFGS.get_root())

# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
# ~~~~ Works for one configuration only ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
# ~~~~ Works for only one configuration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    cfg = CFGS.configs[CFGS.cfgname]

    # still in lower case
    if options.modules != '':
        cfg['modules'] = options.modules.replace(',', ' ')\
                                        .replace(';', ' ')\
                                        .replace('.', ' ')
    if options.doxyDir == '':
        cfg.update({'doxydocs':path.join(cfg['root'],
                                         'documentation',
                                         CFGS.cfgname)})
    else:
        cfg.update({'doxydocs':options.doxyDir})
    if not path.isdir(cfg['doxydocs']):
        create_directories(cfg['doxydocs'])
    # parsing for proper naming
    CFGS.compute_doxy_info()
    print('\n\nScanning the source code for:\n'+'~'*72+'\n')
    CFGS.light_dump()

    # ~~ Scans all source files to build a relation database ~~
    fic, _, _, _, _, _, _, racine = scan_sources(CFGS.cfgname, cfg, bypass)

    # ~~ Scann all source files to update Doxygen ~~~~~~~~~~~~~~~~
    for mod in fic:
        print('\nCreating the DOXYGEN headers for ' + mod + '\n'+'~'*72+'\n')
        for ifile in fic[mod]:

            # ~~ Read the content of the source file ~~~~~~~~~~~~
            ilines = get_file_content(ifile)
            # ~~ Update its Doxygen content ~~~~~~~~~~~~~~~~~~~~~
            olines = create_doxygen(ifile, ilines, mod, racine)
            # ~~ Make sure the distination exists ~~~~~~~~~~~~~~~
            ofile = ifile.replace(cfg['root'], cfg['doxydocs'])
            create_directories(path.dirname(ofile))
            # ~~ Write the content of the source file ~~~~~~~~~~~
            put_file_content(ofile, olines)

    # ~~ Run Doxygen ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    print('\nNow running DOXYGEN within ' + cfg['doxydocs'] + '\n'+'~'*72+'\n')
    chdir(cfg['doxydocs'])
    if not path.exists(cfg['cmd_doxygen']):
        raise Exception('Do not know where to find {}\n '
                        '... you can correct this through the key '
                        'cmd_doxygen in your configuration file'
                        ''.format(cfg['cmd_doxygen']))
    if sp.call([cfg['cmd_doxygen']]):
        raise Exception

    # ~~ Scan all HTML files and replace template in phases
    replace_doxygen(path.join(cfg['doxydocs'], 'html'))


# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
# ~~~~ Jenkins' success message ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    print('\n\nMy work is done\n\n')

    sys.exit(0)
def replace_doxygen(doxydocs):
    """
        Replace all the information required for the Documentation of TELEMAC
        (in htlm) preparing for Doxygen

        @param doxydocs(string) path to search the command of DOXYGENE
    """

    i_txt_lst = [('<!DOCTYPE HTML PUBLIC', '<BODY BGCOLOR="#FFFFFF">'),
                 ('<DIV class="div-page">', '<hr>'),
                 ('<div class="header">', '<div class="summary">'),
                 ('<hr>\n<div class="div-footer">', '</html>'),
                 ('<dl class="user"><dt><', '>'), \
                 ('</b></dt><d', 'd><br/>')]
    o_txt_lst = [r"""<!DOCTYPE install PUBLIC "-//Joomla! 2.5//DTD template 1.0//EN" "http://www.joomla.org/xml/dtd/1.6/template-install.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <meta name="keywords" content="open, telemac, mascaret, hydraulique, surface libre, houle, vague, hydraulic, free surface, wave, sediment" />
        <meta name="robots" content="index, follow" />
        <meta name="date" content="2013-07-24T16:49:04+0100"/>
        <meta name="description" content="The open TELEMAC-MASCARET system is a set of software for free surface numerical modelling of:\n* 2D, 3D Hydrodynamics,\n* Sediment (sand and muds),\n* Waves." />
        <title>The open TELEMAC-MASCARET system: 2D, 3D hydrodynamics sediment waves simulation system</title>
        <link rel="shortcut icon" href="./images/favicon.ico" type="image/vnd.microsoft.icon" />
        <script src="./images/jquery-1.4.2.min.js" type="text/javascript"></script>
        <link rel="stylesheet" href="./images/system.css" type="text/css" />
        <link rel="stylesheet" href="./images/position.css" type="text/css" media="screen,projection" />
        <link rel="stylesheet" href="./images/layout.css" type="text/css" media="screen,projection" />
        <link rel="stylesheet" href="./images/general.css" type="text/css" />
        <link rel="stylesheet" href="./images/principal.css" type="text/css" />
        <style type="text/css">
        #ahgalleryOTconsortium { margin-left: auto; margin-right: auto; margin-top: 0px !important; margin-bottom: 0px !important; width: 1000px; }
        #ahgalleryOTconsortium ul.hover_block0, #ahgalleryOTconsortium ul.hover_block1, #ahgalleryOTconsortium ul.hover_block2 { display: block; overflow: hidden; padding-top: 20px; padding-left: 2px; background: transparent; margin-left: 2px; margin-top: 0 !important; margin-bottom: 0 !important; }
        #ahgalleryOTconsortium ul.bottom_block { padding-bottom: 20px ; }
        #ahgalleryOTconsortium ul.hover_block0 li.item, #ahgalleryOTconsortium ul.hover_block1 li.item, #ahgalleryOTconsortium ul.hover_block2 li.item { margin-left: 0; padding-left: 0; list-style:none; list-style-position: inside; float:left; background: transparent; width: 150px; position: relative; }
        #ahgalleryOTconsortium ul.hover_block0 li a.teaser, #ahgalleryOTconsortium ul.hover_block1 li a.teaser , #ahgalleryOTconsortium ul.hover_block2 li a.teaser{ display: block; position: relative; overflow: hidden; height: 60px; width: 130px; padding: 1px; }
        #ahgalleryOTconsortium ul.hover_block0 li div.teaser, #ahgalleryOTconsortium ul.hover_block1 li div.teaser , #ahgalleryOTconsortium ul.hover_block2 li div.teaser { display: block; position: relative; overflow: hidden; height: 60px; width: 140px; padding: 1px; }
        #ahgalleryOTconsortium ul.hover_block0 li img.overlay, #ahgalleryOTconsortium ul.hover_block1 li img.overlay, #ahgalleryOTconsortium ul.hover_block2 li img.overlay { margin: 0; position: absolute; top: 5px; left: 0; border: 0; }
        </style>
        <script type="text/javascript" src="./images/hide.js"></script>
        <script type="text/javascript">
            window.addEvent(\'load\', function() {
                new JCaption(\'img.caption\');
            });
            window.addEvent(\'domready\', function() {
                $$(\'.hasTip\').each(function(el) {
                    var title = el.get(\'title\');
                    if (title) {
                        var parts = title.split(\'::\', 2);
                        el.store(\'tip:title\', parts[0]);
                        el.store(\'tip:text\', parts[1]);
                }});
                var JTooltips = new Tips($$(\'.hasTip\'), \
                                { maxTitleChars: 50, fixed: false});
            });
        </script>
        <link href="./images/tabsVTK.css" rel="stylesheet" type="text/css"/>
        <link href="./images/searchVTK.css" rel="stylesheet" type="text/css"/>
        <script type="text/javaScript" src="./images/searchVTK.js"></script>
        <link href="./images/doxygenVTK.css" rel="stylesheet" type="text/css"/>
        </HEAD>
    <BODY BGCOLOR="#FFFFFF">""",\
        """<div id="all">
     <div id="header">
          <div class="logoheader">
                <h1 id="logo">open TELEMAC-MASCARET               <span class="header1">The mathematically superior suite of solvers</span></h1>
            </div>
            <div class="bar-top" >
            <ul class="menu">
             <li><a href="http://www.opentelemac.org/" ><img src="./images/OTM_Home-icon_15pix_212-118-0.png" alt="Home" /><span class="image-title">Home</span> </a></li>
         <li><a href="http://www.opentelemac.org/index.php/contact2"><img src="./images/OTM_Mail-icon_15pix_212-118-0.png" alt="Contact"/><span class="image-title">CONTACT</span> </a></li>
         <li><span class="separator"><img src="./images/OTM_transparent_15x080pix.png" /><img src="./images/OTM_transparent_15x080pix.png" /></span></li>
         <li><a href="http://www.opentelemac.org/index.php/community"><span class="image-title">COMMUNITY</span> </a></li>
         <li><a href="http://www.opentelemac.org/index.php/user-conference"><span class="image-title">CONFERENCE</span> </a></li>
         <li><a href="http://www.opentelemac.org/index.php/download"><span class="image-title">DOWNLOAD</span> </a></li>
             <li><a href="http://docs.opentelemac.org/" style="color:#333;background:#ffd1a3;padding:10px;"><span class="image-title">DOXY DOCS</span> </a></li>
         <li><a href="http://www.opentelemac.org/index.php/kunena"><span class="image-title">FORUM</span> </a></li>
             <li><a href="http://wiki.opentelemac.org/doku.php"><span class="image-title">WIKI</span> </a></li>
                </ul>
                </div>
                </div>

        <!-- Generated by Doxygen 1.7.0 -->
        <script type="text/javascript">
        function hasClass(ele,cls) {
          return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
        }
        function addClass(ele,cls) {
          if (!this.hasClass(ele,cls)) ele.className += " "+cls;
        }
        function removeClass(ele,cls) {
          if (hasClass(ele,cls)) {
             var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
             ele.className=ele.className.replace(reg,' ');
          }
        }
        function toggleVisibility(linkObj) {
         var base = linkObj.getAttribute('id');
         var summary = document.getElementById(base + '-summary');
         var content = document.getElementById(base + '-content');
         var trigger = document.getElementById(base + '-trigger');
         if ( hasClass(linkObj,'closed') ) {
            summary.style.display = 'none';
            content.style.display = 'block';
            trigger.src = 'open.png';
            removeClass(linkObj,'closed');
            addClass(linkObj,'opened');
         } else if ( hasClass(linkObj,'opened') ) {
            summary.style.display = 'block';
            content.style.display = 'none';
            trigger.src = 'closed.png';
            removeClass(linkObj,'opened');
            addClass(linkObj,'closed');
         }
         return false;
        }
        </script>
        <br>""",\
        """<div  id="main" >
            <div  class="header" >
            <div  class="summary" >""",\
            """<br>
        </div></div>
                    <h2 class="unseen">Generated on Fri Aug 31 2013 18:12:58 by S.E.Bourban (HRW) using <A href="http://www.doxygen.org/index.html"><img class="footer" width=70px src="doxygen.png" alt="doxygen"/></A> 1.7.0</h2>
                    <div  id="footer-outer" ><div id="footer-inner"><div id="bottom"><div class="box box1"><div class="moduletable">
                    <script type="text/javascript">
                  jQuery.noConflict();
          jQuery(document).ready(function($)
            {
             $('#ahgalleryOTconsortium ul.hover_block0 li.item').hover(function(){
              $(this).find('img.overlay').animate({top:'60px'},{queue:false,duration:500});
             }, function(){
              $(this).find('img.overlay').animate({top:'5px'},{queue:false,duration:500});
             });
          });
          </script>
                    <div id="ahgalleryOTconsortium">
                        <ul class="hover_block0 bottom_block">
                            <li class="item"><a class="teaser" style="background-color:transparent !important;  font-weight: normal; text-decoration: none;" href="http://www.arteliagroup.com/" target="_blank"><img class="overlay" src="./images/Sogreah-Artelia.jpg" alt="" />
                                <span style="color:grey; font-size: 14px; font-weight: bold; line-height: 18px; font-family: arial; margin-bottom: 0.5em; margin-top: 0.5em; display: block; text-align: center;">Artelia</span>
                                <span style="color:white; display: block; font-size: 12px; font-weight: normal; font-family: arial; margin-bottom: 0.5em; margin-top: 0.5em;"></span></a></li>
                            <li class="item"><a class="teaser" style="background-color:transparent !important;  font-weight: normal; text-decoration: none;" href="http://www.baw.de/de/index.php.html" target="_blank"><img class="overlay" src="./images/logo_baw.png" alt="" />
                                <span style="color:grey; font-size: 14px; font-weight: bold; line-height: 18px; font-family: arial; margin-bottom: 0.5em; margin-top: 0.5em; display: block; text-align: center;">BundesAnstalt fur Wasserbau</span>
                                <span style="color:white; display: block; font-size: 12px; font-weight: normal; font-family: arial; margin-bottom: 0.5em; margin-top: 0.5em;"></span></a></li>
                            <li class="item"><a class="teaser" style="background-color:transparent !important;  font-weight: normal; text-decoration: none;" href="http://www.cetmef.equipement.gouv.fr/" target="_blank"><img class="overlay" src="./images/logo_cetmef_v2.png" alt="" />
                                <span style="color:grey; font-size: 14px; font-weight: bold; line-height: 18px; font-family: arial; margin-bottom: 0.5em; margin-top: 0.5em; display: block; text-align: center;">CETMEF</span>
                                <span style="color:white; display: block; font-size: 12px; font-weight: normal; font-family: arial; margin-bottom: 0.5em; margin-top: 0.5em;"></span></a></li>
                            <li class="item"><a class="teaser" style="background-color:transparent !important;  font-weight: normal; text-decoration: none;" href="http://www.stfc.ac.uk/About%20STFC/45.aspx" target="_blank"><img class="overlay" src="./images/logo_Daresbury_v3.gif" alt="" />
                                <span style="color:grey; font-size: 14px; font-weight: bold; line-height: 18px; font-family: arial; margin-bottom: 0.5em; margin-top: 0.5em; display: block; text-align: center;">Daresbury Laboratory</span>
                                <span style="color:white; display: block; font-size: 12px; font-weight: normal; font-family: arial; margin-bottom: 0.5em; margin-top: 0.5em;"></span></a></li>
                            <li class="item"><a class="teaser" style="background-color:transparent !important;  font-weight: normal; text-decoration: none;" href="http://research.edf.com/research-and-innovation-44204.html&amp;tab=44205" target="_blank"><img class="overlay" src="./images/logo_edfR&D.jpg" alt="" />
                                <span style="color:grey; font-size: 14px; font-weight: bold; line-height: 18px; font-family: arial; margin-bottom: 0.5em; margin-top: 0.5em; display: block; text-align: center;">EDF R&D</span>
                                <span style="color:white; display: block; font-size: 12px; font-weight: normal; font-family: arial; margin-bottom: 0.5em; margin-top: 0.5em;"></span></a></li>
                            <li class="item"><a class="teaser" style="background-color:transparent !important;  font-weight: normal; text-decoration: none;" href="http://www.hrwallingford.com" target="_blank"><img class="overlay" src="./images/logo_HRW.png" alt="" />
                                <span style="color:grey; font-size: 14px; font-weight: bold; line-height: 18px; font-family: arial; margin-bottom: 0.5em; margin-top: 0.5em; display: block; text-align: center;">HR Wallingford</span>
                                <span style="color:white; display: block; font-size: 12px; font-weight: normal; font-family: arial; margin-bottom: 0.5em; margin-top: 0.5em;"></span></a></li>
                        </ul></div>
          <div class="clr"></div>
         </div></div>
         </div></div>
                    <div id="footer-sub"><div id="footer">
                        <ul class="menu">
                            <li class="item-187"><a href="http://www.opentelemac.org/index.php/forum-rules" >Forum rules</a></li>
                            <li class="item-111"><a href="http://www.opentelemac.org/index.php/licence" >Licence</a></li>
                            <li class="item-112"><a href="http://www.opentelemac.org/index.php/privacy" >Privacy</a></li>
                            <li class="item-112"><a href="http://www.opentelemac.org/index.php/terms-and-conditions" >Terms &amp; Conditions</a></li>
                        </ul>
                    </div>
         </div></div>
        </body></html>""",\
        '<dl class="user"><dt><h3><b>',\
        '</b></h3></dt><dd><br/>']

    text = r'(?P<before>[\s\S]*?)(?P<text>%s)(?P<after>[\s\S]*)'
    if path.exists(doxydocs):
        dirpath, _, filenames = next(walk(doxydocs))
        for fle in filenames:
            _, tail = path.splitext(fle)
            if tail == '.html':
                print('    +> '+fle)
                lines = ''.join(get_file_content(path.join(dirpath, fle)))
                proc = True
                while proc:
                    proc = False
                    for itext, otext in zip(i_txt_lst, o_txt_lst):
                        proc0 = re.match(re.compile(text%(itext[0]), re.I), \
                                         lines)
                        if proc0:
                            bfr = proc0.group('before')
                            proc1 = re.match(re.compile(text%(itext[1]), re.I),
                                             proc0.group('after'))
                            if proc1:
                                proc = True
                                aftr = proc1.group('after')
                                lines = bfr + otext + aftr
                                #print('replacing: ',
                                #      proc0.group('text')+ \
                                #      proc1.group('before'))
                put_file_content(path.join(dirpath, fle), [lines])

    return
Ejemplo n.º 13
0
    def run_hpc_full(self, options, job_id=''):
        """
        Rerun whole script in jpbscheduler

        @return job_id (integer) Id of the job that was launched
        """
        chdir(self.working_dir)
        # ~~> HPC Command line launching runcode
        hpccmd = get_hpc_cmd(self.cfg['HPC']).replace('<root>',
                                                      self.cfg['root'])
        hpccmd = hpccmd.replace('<wdir>', self.working_dir)

        # ~~> HPC dependency between jobs
        hpcjob = get_hpc_depend(self.cfg['HPC'])
        if hpcjob != '' and job_id != '':
            hpccmd = hpccmd + ' ' + hpcjob.replace('<jobid>', job_id)

        # ~~> HPC queueing script
        stdin_file = self.cfg['HPC']['STDIN'][0]  # only one key for now

        stdin = self.cfg['HPC']['STDIN'][1]
        stdin = stdin.replace('<exename>', self.steering_file)
        # Replacing tags by options values
        stdin, sortie = self.fill_hpc_stdin(stdin, options)

        # Building runcode.py command
        runcmd = 'runcode.py ' + self.code_name + ' --mpi '
        if options.config_name != '':
            runcmd = runcmd + ' -c ' + options.cfgname
        if options.config_file != '':
            runcmd = runcmd + ' -f ' + options.config_file
        if options.root_dir != '':
            runcmd = runcmd + ' -r ' + options.root_dir
        runcmd = runcmd + ' -s '
        if options.tmpdirectory:
            runcmd = runcmd + ' -t '
        runcmd = runcmd + ' -w ' + self.working_dir
        runcmd = runcmd + ' --nctile ' + str(self.nctile)
        runcmd = runcmd + ' --ncnode ' + str(self.ncnode)
        runcmd = runcmd + ' --ncsize ' + str(self.ncsize)
        if options.split:
            runcmd = runcmd + ' --split '
        if options.compileonly:
            runcmd = runcmd + ' -x '
        if options.merge:
            runcmd = runcmd + ' --merge '
        if options.run:
            runcmd = runcmd + ' --run '
        runcmd = runcmd + ' ' + self.steering_file
        stdin = stdin.replace('<py_runcode>', runcmd)

        # ~~> Write to HPC_STDIN
        chdir(self.working_dir)
        put_file_content(stdin_file, stdin.split('\n'))

        # ~~> here you go run
        run_code(hpccmd, sortie)

        job_id = get_file_content(sortie)[0].strip()
        print('... Your simulation ('+self.steering_file+\
              ') has been launched through the queue.\n')
        print('    +> You need to wait for completion '\
              'before checking on results.\n')

        return job_id
def process_lit(cas, cas_dir, ncsize, tmp_dir, use_link):
    """
    @brief Process all the input files except FORTRAN files.

    Copy the input files in the temporary folder if necessary,
    store the ascii file names that have to be split by partel.

    @param cas (TelemacCas): Structure of the CAS file
    @param tmp_dir (string): complete name of the temporary directory where
        the simulation results will be written
    @param ncsize (int): total number of processors
    @param update (boolean): whether to force the source
                             copying / re-compilation
    @param use_link (boolean): only create a link in the temporary folder
        or copy the input files

    """

    # ~~> exception report
    #  xcpt will accumulate all input troubles before reporting a more
    #     comprehensive list of possible errors
    xcpt = []
    #
    #
    # ~~> loop over all (key,value) pairs of the CAS file
    #    and process those that are related to input file names
    #
    #    /!\ the FORTRAN file and its associated exe file are not included here
    #
    # Copying steering file and dictionary
    tmp_cas_name = cas.dico.data['STEERING FILE']['SUBMIT'].split(';')[1]
    print('         copying: ' + path.basename(cas.file_name) + ' -> ' +
          path.join(hide_root(tmp_dir), tmp_cas_name))
    shutil.copyfile(path.join(cas_dir, cas.file_name),
                    path.join(tmp_dir, tmp_cas_name))
    tmp_dico_name = cas.dico.data['DICTIONARY']['SUBMIT'].split(';')[1]
    print('         copying: ' + path.basename(cas.dico.file_name) + ' -> ' +
          path.join(hide_root(tmp_dir), tmp_dico_name))
    shutil.copyfile(cas.dico.file_name, path.join(tmp_dir, tmp_dico_name))

    for key in cas.in_files:
        submit = cas.in_files[key].split(';')
        file_type = submit[5]
        if file_type[0:7] == 'FORTRAN':
            tmp_fortran_dir = path.join(tmp_dir, "user_fortran")
            if not path.exists(tmp_fortran_dir):
                mkdir(tmp_fortran_dir)
            ori_file = cas.values[key]
            # If it is a file copying it
            if path.isfile(ori_file):
                new_name = path.join(tmp_fortran_dir, path.basename(ori_file))
                shutil.copyfile(ori_file, new_name)
            # Otherwise it is a folder
            else:
                for f in listdir(ori_file):
                    # only copying file that en
                    if path.isfile(path.join(ori_file, f)):
                        if f[0] == '.' or f[-1] == '~':
                            continue
                        shutil.copyfile(path.join(ori_file, f),
                                        path.join(tmp_fortran_dir, f))
            continue
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # ~~> checking presence of input files was done by TelemacCas
        file_name = cas.values[key]
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # ~~> checking validity of default files
        tmp_file_name = path.join(tmp_dir, submit[1])
        #  tmp_file_name: is the default input name as set in the temporary
        #  directory
        #  if tmp_file_name does not exists then file_name is copied as
        #  tmp_file_name again
        #  if file_name is newer than tmp_file_name then file_name is copied as
        #  tmp_file_name again
        if path.exists(tmp_file_name):
            if not is_newer(tmp_file_name, file_name) == 1:
                # ~~> further check are necessary depending on file type
                #TODO: Remove that ?
                if file_type[0:7] == 'SELAFIN' or \
                    file_type[0:5] == 'PARAL':
                    # ~~> check if all files are there
                    #    > while file_name is one file, tmp_file_name could
                    #    have been split already into multiple parallel files
                    found = True
                    for npsize in range(ncsize):
                        pll = tmp_file_name + '{0:05d}-{1:05d}'.format(
                            ncsize - 1, npsize)
                        if not path.isfile(pll):
                            found = False
                        elif not is_newer(pll, file_name) == 1:
                            found = False
                    if found:
                        #    > no partioning is required and no re-copying
                        #      either
                        cas.in_files[key] = \
                                cas.in_files[key].replace('SELAFIN', 'DONE')\
                                                 .replace('PARAL', 'DONE')
                        continue
                elif submit[0:3] == 'CAS':
                    # TODO: Adapt that
                    #    > force the copying of the CAS file for some reason
                    print('     re-copying: ' + tmp_file_name)
                    put_file_content(tmp_file_name, cas.steering_file)
                    continue
                else:
                    #    > you have passed all checks
                    #      you can ignore that file
                    print('        ignoring: '+ path.basename(file_name)+' '\
                          + tmp_file_name)
                    continue
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # ~~> files are otherwise copied (or linked)
        if use_link:
            print('         linking: ' + path.basename(file_name) + ' -> ' +
                  hide_root(tmp_file_name))
            symlink_file(path.join(getcwd(), file_name), tmp_file_name)
        else:
            print('         copying: ' + path.basename(file_name) + ' -> ' +
                  hide_root(tmp_file_name))
            shutil.copyfile(path.join(getcwd(), file_name), tmp_file_name)

    if xcpt != []:
        raise TelemacException(xcpt)  # raise full report
    return
def main():
    """ Main function of convertToSPE """

    # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    # ~~~~ Dependencies towards other modules ~~~~~~~~~~~~~~~~~~~~~~~~~~
    from argparse import ArgumentParser, RawDescriptionHelpFormatter
    from data_manip.formats.selafin import Selafin
    from data_manip.formats.conlim import Conlim
    from pretel.meshes import xys_locate_mesh

    # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    # ~~~~ Reads config file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    print('\n\nInterpreting command line options\n' + '~' * 72 + '\n')
    parser = ArgumentParser(\
        formatter_class=RawDescriptionHelpFormatter,
        description=('''\n
A script to map spectral outter model results, stored as SELAFIN files, onto the
    spatially and time varying boundary of a spatially contained SELAFIN file
    of your choosing (your MESH).
        '''),
        usage=' (--help for help)\n---------\n       => '\
                ' %(prog)s  open-bound.cli open-bound.slf in-outer-geo.slf '\
                'in-outer-spec.slf out-bound.slf \n---------')
    parser.add_argument(\
        "--ll2utm", dest="ll2utm", default=None,
        help="assume outer file is in lat-long and open-bound file in UTM")
    parser.add_argument("args", default='', nargs=5)
    options = parser.parse_args()

    # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    # ~~~~ cli+slf new mesh ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    cli_file = options.args[0]
    if not path.exists(cli_file):
        raise TelemacException(\
                '... the provided cli_file does not seem '
                'to exist: {}\n\n'.format(cli_file))
    geo_file = options.args[1]
    if not path.exists(geo_file):
        raise TelemacException(\
                '... the provided geo_file does not seem to exist: '
                '{}\n\n'.format(geo_file))

    # Read the new CLI file to get boundary node numbers
    print('   +> getting hold of the CONLIM file and of its liquid boundaries')
    cli = Conlim(cli_file)
    # Keeping only open boundary nodes
    bor = np.extract(cli.bor['lih'] != 2, cli.bor['n'])

    # Find corresponding (x,y) in corresponding new mesh
    print('   +> getting hold of the GEO file and of its bathymetry')
    geo = Selafin(geo_file)
    if options.ll2utm != None:
        zone = int(options.ll2utm)
        x, y = to_lat_long(geo.meshx[bor - 1], geo.meshy[bor - 1], zone)
    else:
        x = geo.meshx[bor - 1]
        y = geo.meshy[bor - 1]
    xys = np.vstack((x, y)).T

    # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    # ~~~~ slf+spe existing res ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    slf_file = options.args[2]
    if not path.exists(slf_file):
        raise TelemacException(\
                '... the provided slf_file does not seem to exist: '
                '{}\n\n'.format(slf_file))
    slf = Selafin(slf_file)
    slf.set_kd_tree()
    slf.set_mpl_tri()
    spe_file = options.args[3]
    if not path.exists(spe_file):
        raise TelemacException(\
                '... the provided slf_file does not seem to exist: '
                '{}\n\n'.format(spe_file))
    spe = Selafin(spe_file)

    print('   +> support extraction')
    # Extract triangles and weigths in 2D
    support2d = []
    ibar = 0
    pbar = ProgressBar(maxval=len(xys)).start()
    for xyi in xys:
        support2d.append(
            xys_locate_mesh(xyi, slf.ikle2, slf.meshx, slf.meshy, slf.tree,
                            slf.neighbours))
        ibar += 1
        pbar.update(ibar)
    pbar.finish()

    # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    # ~~~~ writes BND header ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    bnd_file = options.args[4]
    bnd = Selafin('')
    bnd.fole = {}
    bnd.fole.update({'hook': open(bnd_file, 'wb')})
    bnd.fole.update({'name': bnd_file})
    bnd.fole.update({'endian': ">"})  # big endian
    bnd.fole.update({'float': ('f', 4)})  # single precision

    # Meta data and variable names
    bnd.title = spe.title
    # spectrum for new locations / nodes
    for i in range(len(bor)):
        bnd.varnames.append(('F'+('00'+str(i))[-2:]+' PT2D'+('000000'+\
                                  str(bor[i]))[-6:]+'                ')[:16])
        bnd.varunits.append('UI              ')
    bnd.nbv1 = len(bnd.varnames)
    bnd.nvar = bnd.nbv1
    bnd.varindex = range(bnd.nvar)

    # sizes and mesh connectivity / spectrum
    bnd.nplan = spe.nplan
    bnd.ndp2 = spe.ndp2
    bnd.ndp3 = bnd.ndp2
    bnd.npoin2 = spe.npoin2
    bnd.npoin3 = spe.npoin3
    bnd.iparam = spe.iparam
    bnd.ipob2 = spe.ipob2
    bnd.ikle2 = spe.ikle2
    # Last few numbers
    bnd.nelem2 = len(bnd.ikle2)
    bnd.nelem3 = bnd.nelem2
    bnd.ipob3 = bnd.ipob2
    bnd.ikle3 = bnd.ikle2
    # Mesh coordinates
    bnd.meshx = spe.meshx
    bnd.meshy = spe.meshy

    print('   +> writing header')
    # Write header
    bnd.append_header_slf()

    # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    # ~~~~ writes BND core ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    print('   +> setting variables')
    # TIME and DATE extraction
    bnd.datetime = spe.datetime
    bnd.tags['times'] = spe.tags['times']

    # pointer initialisation
    f = spe.file['hook']
    endian = spe.file['endian']
    ftype, fsize = spe.file['float']

    # Identofy variables (required for support2d geo-locations)
    specloc = []
    for n, _ in support2d:
        specloc.extend(n)
    vars_indexes = np.unique(specloc)
    if fsize == 4:
        z = np.zeros((len(vars_indexes), spe.npoin2), dtype=np.float32)
        data = np.zeros(spe.npoin2, dtype=np.float32)
    else:
        z = np.zeros((len(vars_indexes), spe.npoin2), dtype=np.float64)
        data = np.zeros(spe.npoin2, dtype=np.float64)

    # Read / Write data, one time step at a time to support large files
    print('   +> reading / writing variables')
    pbar = ProgressBar(maxval=len(spe.tags['times'])).start()
    for itime in range(len(spe.tags['times'])):
        f.seek(
            spe.tags['cores'][itime])  # [itime] is the frame to be extracted
        f.seek(4 + fsize + 4, 1)  # the file pointer is initialised
        bnd.append_core_time_slf(itime)

        # Extract relevant spectrum, where
        #  vars_indexes only contains the relevant nodes
        #  jvar varies from 0 to len(vars_indexes)
        jvar = 0
        for ivar in range(spe.nvar):
            # the file pointer advances through all records to keep on track
            f.seek(4, 1)
            if ivar in vars_indexes:
                z[jvar, :] = unpack(endian+str(spe.npoin2)+\
                                         ftype, f.read(fsize*spe.npoin2))
                jvar += 1
            else:
                # the file pointer advances through all records to keep on track
                f.seek(fsize * spe.npoin2, 1)
            f.seek(4, 1)

        # linear interpolation
        ivar = 0
        for b_n, l_n in support2d:
            data[:] = 0.
            for inod in range(len(b_n)):
                jvar = np.where(vars_indexes == b_n[inod])[0][0]
                data += l_n[inod] * z[jvar, :]
            bnd.append_core_vars_slf([data])
            ivar += 1

        pbar.update(itime)
    pbar.finish()

    # Close bnd_file
    bnd.fole['hook'].close()

    print('   +> writing out the file with coordinate to impose')
    dat = [str(len(bor)) + ' 0']
    for i in np.sort(bor):
        dat.append(str(i) + ' ' + repr(geo.meshx[i-1]) + ' ' + \
                      repr(geo.meshy[i-1]) + ' 0.0')
    put_file_content(bnd_file + '.dat', dat)

    # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    # ~~~~ Jenkins' success message ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    print('\n\nMy work is done\n\n')

    sys.exit(0)
Ejemplo n.º 16
0
    def put_content(self, file_name, head=None):

        # ~~> file extension processing
        _, tail = path.splitext(file_name)
        if tail[1:] != self.file_type:
            if head is not None:
                head = ['\n'.join(head).replace(':FileType '+self.file_type,
                                                ':FileType '+tail[1:])]
            self.file_type = tail[1:]

        # ~~> write head
        if head != []:
            core = head
        else:
            core = [':FileType '+self.file_type+' ASCII EnSim 1.0',
                    ':Application BlueKenue',
                    ':Version 3.2.24',
                    ':WrittenBy sebourban',
                    ':CreationDate Thu, Dec 08, 2011 02:47 PM',
                    ':Name ' + path.basename(file_name),
                    # ':AttributeName 1 level',
                    # ':AttributeType 1 float',
                    # ':AttributeUnits 1 m',
                    ':EndHeader']

        # ~~> look for closed lines
        if self.type == []:
            for i_p in self.poly:
                if is_close(i_p[0][:2], i_p[len(i_p)-1][:2]):
                    self.type.append(1)
                else:
                    self.type.append(0)

        # ~~> fill-up empty attributes
        if self.atrbut == {}:
            self.atrbut = {1: ['ArbitraryName1']}
            for _ in self.poly:
                self.atrbut[1].append(0)
            self.oatrbut = [1]

        # ~~> fill-up attribute names
        if head == []:
            for i, val in enumerate(self.oatrbut):
                core.insert(-1, ':AttributeName '+repr(i+1)+' '+repr(val))

        # ~~ Write body ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        for i, ipoly, ival, itype in zip(range(len(self.poly)),
                                         self.poly,
                                         self.vals,
                                         self.type):
            i_l = len(ipoly)
            if i_l != 0 and not is_close(ipoly[0], ipoly[len(ipoly)-1]):
                i_l += itype
            line = repr(i_l)
            for oatr in self.oatrbut:
                line += ' ' + str(self.atrbut[oatr][i])
            core.append(line)
            if self.file_type == 'i2s':
                for xyi in ipoly:
                    core.append(repr(xyi[0])+' '+repr(xyi[1]))
                if i_l != len(ipoly):
                    core.append(repr(ipoly[0][0])+' '+repr(ipoly[0][1]))
            elif self.file_type == 'i3s':
                if np.shape(ival)[1] == 0:
                    for xyi in ipoly:
                        core.append(repr(xyi[0])+' '+repr(xyi[1])+' 0.0')
                    if i_l != len(ipoly):
                        core.append(repr(ipoly[0][0])+' ' +
                                    repr(ipoly[0][1])+' 0.0')
                else:
                    for xyi, val in zip(ipoly, ival):
                        core.append(repr(xyi[0])+' '+repr(xyi[1])+' ' +
                                    ' '.join([repr(v) for v in val]))
                    if i_l != len(ipoly):
                        core.append(repr(ipoly[0][0])+' '+repr(ipoly[0][1]) +
                                    ' '+' '.join([repr(v) for v in ival[0]]))

        # ~~ Put all ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        put_file_content(file_name, core)