Esempio n. 1
0
    def _load_eles(self, rallocs, mesh, initsoln):
        basismap = {b.name: b for b in subclasses(BaseBasis, just_leaf=True)}

        # Look for and load each element type from the mesh
        elemap = OrderedDict()
        for f in mesh:
            m = re.match('spt_(.+?)_p%d$' % rallocs.prank, f)
            if m:
                # Element type
                t = m.group(1)

                elemap[t] = self.elementscls(basismap[t], mesh[f], self._cfg)

        # Construct a proxylist to simplify collective operations
        eles = proxylist(elemap.values())

        # Set the initial conditions either from a pyfrs file or from
        # explicit expressions in the config file
        if initsoln:
            # Load the config used to produce the solution
            solncfg = Inifile(initsoln['config'].item())

            # Process the solution
            for k, ele in elemap.iteritems():
                soln = initsoln['soln_%s_p%d' % (k, rallocs.prank)]
                ele.set_ics_from_soln(soln, solncfg)
        else:
            eles.set_ics_from_cfg()

        # Allocate these elements on the backend
        eles.set_backend(self._backend, self._nreg)

        return eles, elemap
Esempio n. 2
0
    def _load_eles(self, rallocs, mesh, initsoln):
        basismap = {b.name: b for b in subclasses(BaseShape, just_leaf=True)}

        # Look for and load each element type from the mesh
        elemap = OrderedDict()
        for f in mesh:
            m = re.match('spt_(.+?)_p%d$' % rallocs.prank, f)
            if m:
                # Element type
                t = m.group(1)

                elemap[t] = self.elementscls(basismap[t], mesh[f], self._cfg)

        # Construct a proxylist to simplify collective operations
        eles = proxylist(elemap.values())

        # Set the initial conditions either from a pyfrs file or from
        # explicit expressions in the config file
        if initsoln:
            # Load the config used to produce the solution
            solncfg = Inifile(initsoln['config'])

            # Process the solution
            for k, ele in elemap.iteritems():
                soln = initsoln['soln_%s_p%d' % (k, rallocs.prank)]
                ele.set_ics_from_soln(soln, solncfg)
        else:
            eles.set_ics_from_cfg()

        # Allocate these elements on the backend
        eles.set_backend(self._backend, self._nreg)

        return eles, elemap
Esempio n. 3
0
    def array_info(self):
        """Indexes element types and data array shapes in an archive by file

        Returns a dictionary of information about the numpy array
        files containing pyfr {mesh, solution} data in a .pyfr{m, s}
        archive.

        The dictionary is indexed by array file name, and is ordered
        such that element type counts faster than partition number.
        Dictionary values contain the pyfr element type as a string,
        and the shape of the array as a tuple.

        :return: Element type and array shape of data arrays, indexed
                 by array file name.
        :rtype: :class:`collections.OrderedDict`

        :Example:

        >>> from pyfr.readers import native
        >>> example = read_pyfr_data('example.pyfrm')
        >>> example.get_array_info
        OrderedDict([('spt_hex_p0', ('hex', (27,  4, 3))),
                     ('spt_tet_p0', ('tet', (27, 20, 3))),
                     ('spt_hex_p1', ('hex', (27,  8, 3)))])

        """
        info = OrderedDict()

        # Retrieve list of {mesh, solution} array names, and set name prefix.
        if self.spt_files:
            ls_files = self.spt_files
            prfx = 'spt'

        elif self.soln_files:
            ls_files = self.soln_files
            prfx = 'soln'

        else:
            raise RuntimeError('"%s" does not contain solution or shape point '
                               'files' % (self.fname))

        # Element types known to PyFR
        eletypes = [
            b.name for b in subclasses(BaseShape) if hasattr(b, 'name')
        ]

        # Assembles possible array file names, then checks if present
        # in .pyfr{m, s} archive.  If so, the element type and array
        # shape are assigned to the array file name in info.
        prt = 0
        while len(info) < len(ls_files):
            for et in eletypes:
                name = '%s_%s_p%d' % (prfx, et, prt)

                if name in ls_files:
                    info[name] = (et, self[name].shape)

            prt += 1

        return info
Esempio n. 4
0
    def array_info(self):
        """Indexes element types and data array shapes in an archive by file

        Returns a dictionary of information about the numpy array
        files containing pyfr {mesh, solution} data in a .pyfr{m, s}
        archive.

        The dictionary is indexed by array file name, and is ordered
        such that element type counts faster than partition number.
        Dictionary values contain the pyfr element type as a string,
        and the shape of the array as a tuple.

        :return: Element type and array shape of data arrays, indexed
                 by array file name.
        :rtype: :class:`collections.OrderedDict`

        :Example:

        >>> from pyfr.readers import native
        >>> example = read_pyfr_data('example.pyfrm')
        >>> example.get_array_info
        OrderedDict([('spt_hex_p0', ('hex', (27,  4, 3))),
                     ('spt_tet_p0', ('tet', (27, 20, 3))),
                     ('spt_hex_p1', ('hex', (27,  8, 3)))])

        """
        info = OrderedDict()

        # Retrieve list of {mesh, solution} array names, and set name prefix.
        if self.spt_files:
            ls_files = self.spt_files
            prfx = 'spt'

        elif self.soln_files:
            ls_files = self.soln_files
            prfx = 'soln'

        else:
            raise RuntimeError('"%s" does not contain solution or shape point '
                               'files' % (self.fname))

        # Element types known to PyFR
        eletypes = [b.name for b in subclasses(BaseShape)
                    if hasattr(b, 'name')]

        # Assembles possible array file names, then checks if present
        # in .pyfr{m, s} archive.  If so, the element type and array
        # shape are assigned to the array file name in info.
        prt = 0
        while len(info) < len(ls_files):
            for et in eletypes:
                name = '%s_%s_p%d' % (prfx, et, prt)

                if name in ls_files:
                    info[name] = (et, self.get_shape(name))

            prt += 1

        return info
Esempio n. 5
0
def process_partition(args):
    # Ensure outd is a directory
    if not os.path.isdir(args.outd):
        raise ValueError('Invalid output directory')

    # Partition weights
    if ':' in args.np:
        pwts = [int(w) for w in args.np.split(':')]
    else:
        pwts = [1]*int(args.np)

    # Element weights
    if args.elewts:
        ewts = {e: int(w) for e, w in (ew.split(':') for ew in args.elewts)}
    else:
        ewts = {'quad': 6, 'tri': 3, 'tet': 3, 'hex': 18, 'pri': 10, 'pyr': 6}

    # Partitioner-specific options
    opts = dict(s.split(':', 1) for s in args.popts)

    # Create the partitioner
    if args.partitioner:
        part = get_partitioner(args.partitioner, pwts, ewts, opts=opts)
    else:
        for name in sorted(cls.name for cls in subclasses(BasePartitioner)):
            try:
                part = get_partitioner(name, pwts, ewts)
                break
            except OSError:
                pass
        else:
            raise RuntimeError('No partitioners available')

    # Partition the mesh
    mesh, rnum, part_soln_fn = part.partition(NativeReader(args.mesh))

    # Prepare the solutions
    solnit = (part_soln_fn(NativeReader(s)) for s in args.solns)

    # Output paths/files
    paths = it.chain([args.mesh], args.solns)
    files = it.chain([mesh], solnit)

    # Iterate over the output mesh/solutions
    for path, data in zip(paths, files):
        # Compute the output path
        path = os.path.join(args.outd, os.path.basename(path.rstrip('/')))

        # Save to disk
        write_pyfrms(path, data)

    # Write out the renumbering table
    if args.rnumf:
        print('etype,pold,iold,pnew,inew', file=args.rnumf)

        for etype, emap in sorted(rnum.items()):
            for k, v in sorted(emap.items()):
                print(etype, *k, *v, sep=',', file=args.rnumf)
Esempio n. 6
0
def process_partition(args):
    # Ensure outd is a directory
    if not os.path.isdir(args.outd):
        raise ValueError('Invalid output directory')

    # Partition weights
    if ':' in args.np:
        pwts = [int(w) for w in args.np.split(':')]
    else:
        pwts = [1]*int(args.np)

    # Partitioner-specific options
    opts = dict(s.split(':', 1) for s in args.popts)

    # Create the partitioner
    if args.partitioner:
        part = get_partitioner(args.partitioner, pwts, order=args.order,
                               opts=opts)
    else:
        for name in sorted(cls.name for cls in subclasses(BasePartitioner)):
            try:
                part = get_partitioner(name, pwts, order=args.order)
                break
            except OSError:
                pass
        else:
            raise RuntimeError('No partitioners available')

    # Partition the mesh
    mesh, rnum, part_soln_fn = part.partition(NativeReader(args.mesh))

    # Prepare the solutions
    solnit = (part_soln_fn(NativeReader(s)) for s in args.solns)

    # Output paths/files
    paths = it.chain([args.mesh], args.solns)
    files = it.chain([mesh], solnit)

    # Iterate over the output mesh/solutions
    for path, data in zip(paths, files):
        # Compute the output path
        path = os.path.join(args.outd, os.path.basename(path.rstrip('/')))

        # Save to disk
        with h5py.File(path, 'w') as f:
            for k, v in data.items():
                f[k] = v

    # Write out the renumbering table
    if args.rnumf:
        print('etype,pold,iold,pnew,inew', file=args.rnumf)

        for etype, emap in sorted(rnum.items()):
            for k, v in sorted(emap.items()):
                print(','.join(map(str, (etype, *k, *v))), file=args.rnumf)
Esempio n. 7
0
    def _load_eles(self, rallocs, mesh, initsoln, nregs, nonce):
        basismap = {b.name: b for b in subclasses(BaseShape, just_leaf=True)}

        # Look for and load each element type from the mesh
        elemap = {}
        for f in mesh:
            if (m := re.match(f'spt_(.+?)_p{rallocs.prank}$', f)):
                # Element type
                t = m.group(1)

                elemap[t] = self.elementscls(basismap[t], mesh[f], self.cfg)
Esempio n. 8
0
    def _load_eles(self, rallocs, mesh, initsoln, nregs, nonce):
        basismap = {b.name: b for b in subclasses(BaseShape, just_leaf=True)}

        # Look for and load each element type from the mesh
        elemap = {}
        for f in mesh:
            m = re.match(f'spt_(.+?)_p{rallocs.prank}$', f)
            if m:
                # Element type
                t = m.group(1)

                elemap[t] = self.elementscls(basismap[t], mesh[f], self.cfg)

        # Construct a proxylist to simplify collective operations
        eles = proxylist(elemap.values())

        # Set the initial conditions
        if initsoln:
            # Load the config and stats files from the solution
            solncfg = Inifile(initsoln['config'])
            solnsts = Inifile(initsoln['stats'])

            # Get the names of the conserved variables (fields)
            solnfields = solnsts.get('data', 'fields', '')
            currfields = ','.join(eles[0].convarmap[eles[0].ndims])

            # Ensure they match up
            if solnfields and solnfields != currfields:
                raise RuntimeError('Invalid solution for system')

            # Process the solution
            for etype, ele in elemap.items():
                soln = initsoln[f'soln_{etype}_p{rallocs.prank}']
                ele.set_ics_from_soln(soln, solncfg)
        else:
            eles.set_ics_from_cfg()

        # Allocate these elements on the backend
        for etype, ele in elemap.items():
            k = f'spt_{etype}_p{rallocs.prank}'

            try:
                curved = ~mesh[k, 'linear']
                linoff = np.max(*np.nonzero(curved), initial=-1) + 1
            except KeyError:
                linoff = ele.neles

            ele.set_backend(self.backend, nregs, nonce, linoff)

        return eles, elemap
Esempio n. 9
0
def main():
    ap = ArgumentParser(prog='pyfr-mesh', description='Generates and '
                        'manipulates PyFR mesh files')

    sp = ap.add_subparsers(help='sub-command help')

    # Mesh format conversion
    ap_convert = sp.add_parser('convert', help='convert --help')
    ap_convert.add_argument('inmesh', type=FileType('r'),
                            help='input mesh file')
    ap_convert.add_argument('outmesh', type=FileType('wb'),
                            help='output PyFR mesh file')
    types = sorted(cls.name for cls in subclasses(BaseReader))
    ap_convert.add_argument('-t', dest='type', choices=types,
                            help='input file type; this is usually inferred '
                            'from the extension of inmesh')
    ap_convert.set_defaults(process=process_convert)

    # Mesh and solution partitioning
    ap_partition = sp.add_parser('partition', help='partition --help')
    ap_partition.add_argument('np', help='number of partitions or a colon '
                              'delimited list of weighs')
    ap_partition.add_argument('mesh', help='input mesh file')
    ap_partition.add_argument('solns', nargs='*',
                              help='input solution files')
    ap_partition.add_argument(dest='outd', help='output directory')
    partitioners = sorted(cls.name for cls in subclasses(BasePartitioner))
    ap_partition.add_argument('-p', dest='partitioner', choices=partitioners,
                              help='partitioner to use')
    ap_partition.add_argument('--popt', dest='popts', action='append',
                              default=[], metavar='key:value',
                              help='partitioner-specific option ')
    ap_partition.set_defaults(process=process_partition)

    args = ap.parse_args()
    args.process(args)
Esempio n. 10
0
def process_partition(args):
    # Ensure outd is a directory
    if not os.path.isdir(args.outd):
        raise ValueError('Invalid output directory')

    # Partition weights
    if ':' in args.np:
        pwts = [int(w) for w in args.np.split(':')]
    else:
        pwts = [1]*int(args.np)

    # Partitioner-specific options
    opts = dict(s.split(':', 1) for s in args.popts)

    # Create the partitioner
    if args.partitioner:
        part = get_partitioner(args.partitioner, pwts, order=args.order,
                               opts=opts)
    else:
        for name in sorted(cls.name for cls in subclasses(BasePartitioner)):
            try:
                part = get_partitioner(name, pwts, order=args.order)
                break
            except OSError:
                pass
        else:
            raise RuntimeError('No partitioners available')

    # Partition the mesh
    mesh, part_soln_fn = part.partition(NativeReader(args.mesh))

    # Prepare the solutions
    solnit = (part_soln_fn(NativeReader(s)) for s in args.solns)

    # Output paths/files
    paths = it.chain([args.mesh], args.solns)
    files = it.chain([mesh], solnit)

    # Iterate over the output mesh/solutions
    for path, data in zip(paths, files):
        # Compute the output path
        path = os.path.join(args.outd, os.path.basename(path.rstrip('/')))

        # Save to disk
        with h5py.File(path, 'w') as f:
            for k, v in data.items():
                f[k] = v
Esempio n. 11
0
def process_partition(args):
    # Ensure outd is a directory
    if not os.path.isdir(args.outd):
        raise ValueError('Invalid output directory')

    # Partition weights
    if ':' in args.np:
        pwts = [int(w) for w in args.np.split(':')]
    else:
        pwts = [1]*int(args.np)

    # Partitioner-specific options
    opts = dict(s.split(':', 1) for s in args.popts)

    # Create the partitioner
    if args.partitioner:
        part = get_partitioner_by_name(args.partitioner, pwts, opts)
    else:
        for name in sorted(cls.name for cls in subclasses(BasePartitioner)):
            try:
                part = get_partitioner_by_name(name, pwts)
                break
            except RuntimeError:
                pass
        else:
            raise RuntimeError('No partitioners available')

    # Partition the mesh
    mesh, part_soln_fn = part.partition(read_pyfr_data(args.mesh))

    # Prepare the solutions
    solnit = (part_soln_fn(read_pyfr_data(s)) for s in args.solns)

    # Output paths/files
    paths = it.chain([args.mesh], args.solns)
    files = it.chain([mesh], solnit)

    # Iterate over the output mesh/solutions
    for path, data in it.izip(paths, files):
        # Compute the output path
        path = os.path.join(args.outd, os.path.basename(path.rstrip('/')))

        # Open and save
        with open(path, 'wb') as f:
            np.savez(f, **data)
Esempio n. 12
0
    def _load_eles(self, rallocs, mesh, initsoln, nregs, nonce):
        basismap = {b.name: b for b in subclasses(BaseShape, just_leaf=True)}

        # Look for and load each element type from the mesh
        elemap = OrderedDict()
        for f in mesh:
            m = re.match('spt_(.+?)_p{0}$'.format(rallocs.prank), f)
            if m:
                # Element type
                t = m.group(1)

                elemap[t] = self.elementscls(basismap[t], mesh[f], self.cfg)

        # Construct a proxylist to simplify collective operations
        eles = proxylist(elemap.values())

        # Set the initial conditions
        if initsoln:
            # Load the config and stats files from the solution
            solncfg = Inifile(initsoln['config'])
            solnsts = Inifile(initsoln['stats'])

            # Get the names of the conserved variables (fields)
            solnfields = solnsts.get('data', 'fields', '')
            currfields = ','.join(eles[0].convarmap[eles[0].ndims])

            # Ensure they match up
            if solnfields and solnfields != currfields:
                raise RuntimeError('Invalid solution for system')

            # Process the solution
            for etype, ele in elemap.items():
                soln = initsoln['soln_{0}_p{1}'.format(etype, rallocs.prank)]
                ele.set_ics_from_soln(soln, solncfg)
        else:
            eles.set_ics_from_cfg()

        # Compute the index of first strictly interior element
        intoffs = self._compute_int_offsets(rallocs, mesh)

        # Allocate these elements on the backend
        for etype, ele in elemap.items():
            ele.set_backend(self.backend, nregs, nonce, intoffs[etype])

        return eles, elemap
Esempio n. 13
0
    def _load_eles(self, rallocs, mesh, initsoln, nreg):
        basismap = {b.name: b for b in subclasses(BaseShape, just_leaf=True)}

        # Look for and load each element type from the mesh
        elemap = OrderedDict()
        for f in mesh:
            m = re.match('spt_(.+?)_p%d$' % rallocs.prank, f)
            if m:
                # Element type
                t = m.group(1)

                elemap[t] = self.elementscls(basismap[t], mesh[f], self.cfg)

        # Construct a proxylist to simplify collective operations
        eles = proxylist(elemap.values())

        # Set the initial conditions either from a pyfrs file or from
        # explicit expressions in the config file
        if initsoln:
            # Load the config and stats files from the solution
            solncfg = Inifile(initsoln['config'])
            solnsts = Inifile(initsoln['stats'])

            # Get the names of the conserved variables (fields)
            solnfields = solnsts.get('data', 'fields', '')
            currfields = ','.join(eles[0].convarmap[eles[0].ndims])

            # Ensure they match up
            if solnfields and solnfields != currfields:
                raise RuntimeError('Invalid solution for system')

            # Process the solution
            for k, ele in elemap.items():
                soln = initsoln['soln_%s_p%d' % (k, rallocs.prank)]
                ele.set_ics_from_soln(soln, solncfg)
        else:
            eles.set_ics_from_cfg()

        # Allocate these elements on the backend
        eles.set_backend(self.backend, nreg)

        return eles, elemap
Esempio n. 14
0
def main():
    ap = ArgumentParser(prog='pyfr-mesh', description='Generates and '
                        'manipulates PyFR mesh files')

    sp = ap.add_subparsers(help='sub-command help')

    # Mesh format conversion
    ap_convert = sp.add_parser('convert', help='convert --help')
    ap_convert.add_argument('inmesh', type=FileType('r'),
                            help='Input mesh file')
    ap_convert.add_argument('outmesh', type=FileType('wb'),
                            help='Output PyFR mesh file')
    types = [cls.name for cls in subclasses(BaseReader)]
    ap_convert.add_argument('-t', dest='type', choices=types, required=False,
                            help='Input file type; this is usually inferred '
                            'from the extension of inmesh')
    ap_convert.set_defaults(process=process_convert)

    args = ap.parse_args()
    args.process(args)
Esempio n. 15
0
    def _load_bc_inters(self, rallocs, mesh, elemap):
        bccls = self.bbcinterscls
        bcmap = {b.type: b for b in subclasses(bccls, just_leaf=True)}

        bc_inters = proxylist([])
        for f in mesh:
            m = re.match('bcon_(.+?)_p%d$' % rallocs.prank, f)
            if m:
                # Get the region name
                rgn = m.group(1)

                # Determine the config file section
                cfgsect = 'soln-bcs-%s' % rgn

                # Instantiate
                bcclass = bcmap[self._cfg.get(cfgsect, 'type')]
                bciface = bcclass(self._backend, mesh[f], elemap, cfgsect,
                                  self._cfg)
                bc_inters.append(bciface)

        return bc_inters
Esempio n. 16
0
    def _load_bc_inters(self, rallocs, mesh, elemap):
        bccls = self.bbcinterscls
        bcmap = {b.type: b for b in subclasses(bccls, just_leaf=True)}

        bc_inters = []
        for f in mesh:
            if (m := re.match(f'bcon_(.+?)_p{rallocs.prank}$', f)):
                # Get the region name
                rgn = m.group(1)

                # Determine the config file section
                cfgsect = f'soln-bcs-{rgn}'

                # Get the interface
                interarr = mesh[f].astype('U4,i4,i1,i2').tolist()

                # Instantiate
                bcclass = bcmap[self.cfg.get(cfgsect, 'type')]
                bciface = bcclass(self.backend, interarr, elemap, cfgsect,
                                  self.cfg)
                bc_inters.append(bciface)
Esempio n. 17
0
    def _load_bc_inters(self, rallocs, mesh, elemap):
        bccls = self.bbcinterscls
        bcmap = {b.type: b for b in subclasses(bccls, just_leaf=True)}

        bc_inters = proxylist([])
        for f in mesh:
            m = re.match('bcon_(.+?)_p%d$' % rallocs.prank, f)
            if m:
                # Get the region name
                rgn = m.group(1)

                # Determine the config file section
                cfgsect = 'soln-bcs-%s' % rgn

                # Instantiate
                bcclass = bcmap[self._cfg.get(cfgsect, 'type')]
                bciface = bcclass(self._backend, mesh[f].tolist(), elemap,
                                  cfgsect, self._cfg)
                bc_inters.append(bciface)

        return bc_inters
Esempio n. 18
0
    def __init__(self):
        self.mpi_init = False

        self.ap = ArgumentParser(prog='pyfr')
        self.sp = self.ap.add_subparsers(dest='cmd', help='sub-command help')

        # Common options
        self.ap.add_argument('--verbose', '-v', action='count')

        # Run command
        self.ap_run = self.sp.add_parser('run', help='run --help')
        self.ap_run.add_argument('mesh', help='mesh file')
        self.ap_run.add_argument('cfg', type=FileType('r'), help='config file')
        self.ap_run.set_defaults(process=self.process_run)

        # Restart command
        self.ap_restart = self.sp.add_parser('restart', help='restart --help')
        self.ap_restart.add_argument('mesh', help='mesh file')
        self.ap_restart.add_argument('soln', help='solution file')
        self.ap_restart.add_argument('cfg',
                                     nargs='?',
                                     type=FileType('r'),
                                     help='new config file')
        self.ap_restart.set_defaults(process=self.process_restart)

        # Options common to run and restart
        backends = sorted(cls.name for cls in subclasses(BaseBackend))
        for p in [self.ap_run, self.ap_restart]:
            p.add_argument('--backend',
                           '-b',
                           choices=backends,
                           required=True,
                           help='backend to use')
            p.add_argument('--progress',
                           '-p',
                           action='store_true',
                           help='show a progress bar')

        self.base_dir = os.path.dirname(__file__)
Esempio n. 19
0
def get_reader_by_extn(extn, *args, **kwargs):
    reader_map = {ex: cls
                  for cls in subclasses(BaseReader)
                  for ex in cls.extn}

    return reader_map[extn](*args, **kwargs)
Esempio n. 20
0
def main():
    ap = ArgumentParser(prog='pyfr-postp', description='Post processes a '
                        'PyFR simulation')

    sp = ap.add_subparsers(help='sub-command help')

    ap_pack = sp.add_parser('pack', help='pack --help', description='Packs a '
                            'pyfr[ms]-directory into a pyfr[ms]-file.  If no '
                            'output file is specified then that of the '
                            'input directory is taken.  This command will '
                            'replace any existing file or directory.')
    ap_pack.add_argument('indir', metavar='in',
                         help='Input PyFR mesh/solution directory')
    ap_pack.add_argument('outf', metavar='out', nargs='?',
                         help='Out PyFR mesh/solution file')
    ap_pack.set_defaults(process=process_pack)

    ap_unpack = sp.add_parser('unpack', help='unpack --help', description=
                              'Unpacks a pyfr[ms]-file into a '
                              'pyfr[ms]-directory. If no output directory '
                              'name is specified then a directory named '
                              'after the input file is taken. This command '
                              'will remove any existing output file or '
                              'directory.')
    ap_unpack.add_argument('inf', metavar='in', type=FileType('rb'),
                           help='Input PyFR mesh/solution file')
    ap_unpack.add_argument('outdir', metavar='out', nargs='?',
                           help='Out PyFR mesh/solution directory')
    ap_unpack.set_defaults(process=process_unpack)

    ap_conv = sp.add_parser('convert', help='convert --help', description=
                            'Converts .pyfr[ms] files for visualisation '
                            'in external software.')
    ap_conv.add_argument('meshf', help='PyFR mesh file to be converted')
    ap_conv.add_argument('solnf', help='PyFR solution file to be converted')
    ap_conv.add_argument('outf', type=FileType('wb'), help='Output filename')
    types = [cls.name for cls in subclasses(BaseWriter)]
    ap_conv.add_argument('-t', dest='type', choices=types, required=False,
                         help='Output file type; this is usually inferred '
                         'from the extension of outf')

    ap_pop = ap_conv.add_subparsers(help='Choose output mode for high-order '
                                    'data.')

    ap_pdiv = ap_pop.add_parser('divide', help='paraview *args divide --help',
                                description='Divides high-order elements '
                                'into multiple low-order elements.  All '
                                'elements are split to the same level.')

    ap_pdiv.add_argument('-d', '--divisor', type=int, choices=range(1, 17),
                         default=0, help='Sets the level to which high '
                         'order elements are divided along each edge. The '
                         'total node count produced by divisor is equivalent '
                         'to that of solution order, which is used as the '
                         'default. Note: the output is linear between '
                         'nodes, so increased resolution may be required.')
    ap_pdiv.add_argument('-p', '--precision', choices=['single', 'double'],
                         default='single', help='Selects the precision of '
                         'floating point numbers written to the output file; '
                         'single is the default.')
    ap_pdiv.set_defaults(process=process_convert)

    ap_pap = ap_pop.add_parser('append', help='paraview *args append --help',
                               description='High-order solutions are written '
                               'as high-order data appended to low-order '
                               'elements.  A Paraview plugin recursively '
                               'bisects each element to achieve a requirement '
                               'on the relative error of a solution variable. '
                               'Paraview requires the high-order plugin '
                               'written by Sébastien Blaise, available from: '
                               'http://perso.uclouvain.be/sebastien.blaise/'
                               'tools.html')
    ap_pap.set_defaults(divisor=None, precision='double',
                        process=process_convert)

    ap_tavg = sp.add_parser('time-avg', help='time-avg --help',
                            description='Computes the mean solution of a '
                            'time-wise series of pyfrs files.')
    ap_tavg.add_argument('outf', type=str, help='Output PyFR solution file '
                         'name.')
    ap_tavg.add_argument('infs', type=str, nargs='+', help='Input '
                         'PyFR solution files to be time-averaged.')
    ap_tavg.add_argument('-l', '--limits', nargs=2, type=float,
                         help='Exclude solution files (passed in the infs '
                         'argument) that lie outside minimum and maximum '
                         'solution time limits.')
    ap_tavg.set_defaults(process=process_tavg)

    # Parse the arguments
    args = ap.parse_args()
    args.process(args)
Esempio n. 21
0
def get_reader_by_extn(extn, *args, **kwargs):
    reader_map = {ex: cls
                  for cls in subclasses(BaseReader)
                  for ex in cls.extn}

    return reader_map[extn](*args, **kwargs)
Esempio n. 22
0
def main():
    ap = ArgumentParser(prog='pyfr')
    sp = ap.add_subparsers(dest='cmd', help='sub-command help')

    # Common options
    ap.add_argument('--verbose', '-v', action='count')

    # Import command
    ap_import = sp.add_parser('import', help='import --help')
    ap_import.add_argument('inmesh', type=FileType('r'),
                           help='input mesh file')
    ap_import.add_argument('outmesh', help='output PyFR mesh file')
    types = sorted(cls.name for cls in subclasses(BaseReader))
    ap_import.add_argument('-t', dest='type', choices=types,
                           help='input file type; this is usually inferred '
                           'from the extension of inmesh')
    ap_import.set_defaults(process=process_import)

    # Partition command
    ap_partition = sp.add_parser('partition', help='partition --help')
    ap_partition.add_argument('np', help='number of partitions or a colon '
                              'delimited list of weighs')
    ap_partition.add_argument('mesh', help='input mesh file')
    ap_partition.add_argument('solns', nargs='*',
                              help='input solution files')
    ap_partition.add_argument(dest='outd', help='output directory')
    partitioners = sorted(cls.name for cls in subclasses(BasePartitioner))
    ap_partition.add_argument('-p', dest='partitioner', choices=partitioners,
                              help='partitioner to use')
    ap_partition.add_argument('--popt', dest='popts', action='append',
                              default=[], metavar='key:value',
                              help='partitioner-specific option')
    ap_partition.set_defaults(process=process_partition)

    # Export command
    ap_export = sp.add_parser('export', help='export --help',
                              description='Converts .pyfr[ms] files for '
                              'visualisation in external software.')
    ap_export.add_argument('meshf', help='PyFR mesh file to be converted')
    ap_export.add_argument('solnf', help='PyFR solution file to be converted')
    ap_export.add_argument('outf', type=str, help='Output filename')
    types = [cls.name for cls in subclasses(BaseWriter)]
    ap_export.add_argument('-t', dest='type', choices=types, required=False,
                           help='Output file type; this is usually inferred '
                           'from the extension of outf')
    ap_export.add_argument('-d', '--divisor', type=int, default=0,
                           help='Sets the level to which high order elements '
                           'are divided along each edge. The total node count '
                           'produced by divisor is equivalent to that of '
                           'solution order, which is used as the default. '
                           'Note: the output is linear between nodes, so '
                           'increased resolution may be required.')
    ap_export.add_argument('-p', '--precision', choices=['single', 'double'],
                           default='single', help='Selects the precision of '
                           'floating point numbers written to the output file; '
                           'single is the default.')
    ap_export.set_defaults(process=process_export)

    # Run command
    ap_run = sp.add_parser('run', help='run --help')
    ap_run.add_argument('mesh', help='mesh file')
    ap_run.add_argument('cfg', type=FileType('r'), help='config file')
    ap_run.set_defaults(process=process_run)

    # Restart command
    ap_restart = sp.add_parser('restart', help='restart --help')
    ap_restart.add_argument('mesh', help='mesh file')
    ap_restart.add_argument('soln', help='solution file')
    ap_restart.add_argument('cfg', nargs='?', type=FileType('r'),
                            help='new config file')
    ap_restart.set_defaults(process=process_restart)

    # Options common to run and restart
    for p in [ap_run, ap_restart]:
        p.add_argument('--backend', '-b', default='cuda',
                       help='Backend to use')
        p.add_argument('--progress', '-p', action='store_true',
                       help='show a progress bar')

    # Parse the arguments
    args = ap.parse_args()

    # Invoke the process method
    if hasattr(args, 'process'):
        args.process(args)
    else:
        ap.print_help()
Esempio n. 23
0
def main():
    ap = ArgumentParser(prog='pyfr-postp',
                        description='Post processes a '
                        'PyFR simulation')

    sp = ap.add_subparsers(help='sub-command help')

    ap_pack = sp.add_parser('pack',
                            help='pack --help',
                            description='Packs a '
                            'pyfr[ms]-directory into a pyfr[ms]-file.  If no '
                            'output file is specified then that of the '
                            'input directory is taken.  This command will '
                            'replace any existing file or directory.')
    ap_pack.add_argument('indir',
                         metavar='in',
                         help='Input PyFR mesh/solution directory')
    ap_pack.add_argument('outf',
                         metavar='out',
                         nargs='?',
                         help='Out PyFR mesh/solution file')
    ap_pack.set_defaults(process=process_pack)

    ap_unpack = sp.add_parser('unpack',
                              help='unpack --help',
                              description='Unpacks a pyfr[ms]-file into a '
                              'pyfr[ms]-directory. If no output directory '
                              'name is specified then a directory named '
                              'after the input file is taken. This command '
                              'will remove any existing output file or '
                              'directory.')
    ap_unpack.add_argument('inf',
                           metavar='in',
                           type=FileType('rb'),
                           help='Input PyFR mesh/solution file')
    ap_unpack.add_argument('outdir',
                           metavar='out',
                           nargs='?',
                           help='Out PyFR mesh/solution directory')
    ap_unpack.set_defaults(process=process_unpack)

    ap_conv = sp.add_parser(
        'convert',
        help='convert --help',
        description='Converts .pyfr[ms] files for visualisation '
        'in external software.')
    ap_conv.add_argument('meshf', help='PyFR mesh file to be converted')
    ap_conv.add_argument('solnf', help='PyFR solution file to be converted')
    ap_conv.add_argument('outf', type=FileType('wb'), help='Output filename')
    types = [cls.name for cls in subclasses(BaseWriter)]
    ap_conv.add_argument('-t',
                         dest='type',
                         choices=types,
                         required=False,
                         help='Output file type; this is usually inferred '
                         'from the extension of outf')

    ap_pop = ap_conv.add_subparsers(help='Choose output mode for high-order '
                                    'data.')

    ap_pdiv = ap_pop.add_parser('divide',
                                help='paraview *args divide --help',
                                description='Divides high-order elements '
                                'into multiple low-order elements.  All '
                                'elements are split to the same level.')

    ap_pdiv.add_argument('-d',
                         '--divisor',
                         type=int,
                         choices=range(1, 17),
                         default=0,
                         help='Sets the level to which high '
                         'order elements are divided along each edge. The '
                         'total node count produced by divisor is equivalent '
                         'to that of solution order, which is used as the '
                         'default. Note: the output is linear between '
                         'nodes, so increased resolution may be required.')
    ap_pdiv.add_argument('-p',
                         '--precision',
                         choices=['single', 'double'],
                         default='single',
                         help='Selects the precision of '
                         'floating point numbers written to the output file; '
                         'single is the default.')
    ap_pdiv.set_defaults(process=process_convert)

    ap_pap = ap_pop.add_parser('append',
                               help='paraview *args append --help',
                               description='High-order solutions are written '
                               'as high-order data appended to low-order '
                               'elements.  A Paraview plugin recursively '
                               'bisects each element to achieve a requirement '
                               'on the relative error of a solution variable. '
                               'Paraview requires the high-order plugin '
                               'written by Sébastien Blaise, available from: '
                               'http://perso.uclouvain.be/sebastien.blaise/'
                               'tools.html')
    ap_pap.set_defaults(divisor=None,
                        precision='double',
                        process=process_convert)

    ap_tavg = sp.add_parser('time-avg',
                            help='time-avg --help',
                            description='Computes the mean solution of a '
                            'time-wise series of pyfrs files.')
    ap_tavg.add_argument('outf',
                         type=str,
                         help='Output PyFR solution file '
                         'name.')
    ap_tavg.add_argument('infs',
                         type=str,
                         nargs='+',
                         help='Input '
                         'PyFR solution files to be time-averaged.')
    ap_tavg.add_argument('-l',
                         '--limits',
                         nargs=2,
                         type=float,
                         help='Exclude solution files (passed in the infs '
                         'argument) that lie outside minimum and maximum '
                         'solution time limits.')
    ap_tavg.set_defaults(process=process_tavg)

    # Parse the arguments
    args = ap.parse_args()
    args.process(args)
Esempio n. 24
0
def get_writer_by_extn(extn, *args, **kwargs):
    writer_map = {ex: cls for cls in subclasses(BaseWriter) for ex in cls.extn}

    return writer_map[extn](*args, **kwargs)
Esempio n. 25
0
def get_writer_by_extn(extn, *args, **kwargs):
    writer_map = {ex: cls
                  for cls in subclasses(BaseWriter)
                  for ex in cls.extn}

    return writer_map[extn](*args, **kwargs)
Esempio n. 26
0
def main():
    ap = ArgumentParser(prog='pyfr')
    sp = ap.add_subparsers(dest='cmd', help='sub-command help')

    # Common options
    ap.add_argument('--verbose', '-v', action='count')

    # Import command
    ap_import = sp.add_parser('import', help='import --help')
    ap_import.add_argument('inmesh', type=FileType('r'),
                           help='input mesh file')
    ap_import.add_argument('outmesh', help='output PyFR mesh file')
    types = sorted(cls.name for cls in subclasses(BaseReader))
    ap_import.add_argument('-t', dest='type', choices=types,
                           help='input file type; this is usually inferred '
                           'from the extension of inmesh')
    ap_import.set_defaults(process=process_import)

    # Partition command
    ap_partition = sp.add_parser('partition', help='partition --help')
    ap_partition.add_argument('np', help='number of partitions or a colon '
                              'delimited list of weighs')
    ap_partition.add_argument('mesh', help='input mesh file')
    ap_partition.add_argument('solns', nargs='*',
                              help='input solution files')
    ap_partition.add_argument(dest='outd', help='output directory')
    partitioners = sorted(cls.name for cls in subclasses(BasePartitioner))
    ap_partition.add_argument('-p', dest='partitioner', choices=partitioners,
                              help='partitioner to use')
    ap_partition.add_argument('--popt', dest='popts', action='append',
                              default=[], metavar='key:value',
                              help='partitioner-specific option')
    ap_partition.set_defaults(process=process_partition)

    # Export command
    ap_export = sp.add_parser('export', help='export --help',
                              description='Converts .pyfr[ms] files for '
                              'visualisation in external software.')
    ap_export.add_argument('meshf', help='PyFR mesh file to be converted')
    ap_export.add_argument('solnf', help='PyFR solution file to be converted')
    ap_export.add_argument('outf', type=str, help='Output filename')
    types = [cls.name for cls in subclasses(BaseWriter)]
    ap_export.add_argument('-t', dest='type', choices=types, required=False,
                           help='Output file type; this is usually inferred '
                           'from the extension of outf')
    ap_export.add_argument('-d', '--divisor', type=int, default=0,
                           help='Sets the level to which high order elements '
                           'are divided; output is linear between nodes, so '
                           'increased resolution may be required')
    ap_export.add_argument('-g', '--gradients', action='store_true',
                           help='Compute gradients')
    ap_export.add_argument('-p', '--precision', choices=['single', 'double'],
                           default='single', help='Output number precision, '
                           'defaults to single')
    ap_export.set_defaults(process=process_export)

    # Run command
    ap_run = sp.add_parser('run', help='run --help')
    ap_run.add_argument('mesh', help='mesh file')
    ap_run.add_argument('cfg', type=FileType('r'), help='config file')
    ap_run.set_defaults(process=process_run)

    # Restart command
    ap_restart = sp.add_parser('restart', help='restart --help')
    ap_restart.add_argument('mesh', help='mesh file')
    ap_restart.add_argument('soln', help='solution file')
    ap_restart.add_argument('cfg', nargs='?', type=FileType('r'),
                            help='new config file')
    ap_restart.set_defaults(process=process_restart)

    # Options common to run and restart
    backends = sorted(cls.name for cls in subclasses(BaseBackend))
    for p in [ap_run, ap_restart]:
        p.add_argument('--backend', '-b', choices=backends, required=True,
                       help='Backend to use')
        p.add_argument('--progress', '-p', action='store_true',
                       help='show a progress bar')

    # Parse the arguments
    args = ap.parse_args()

    # Invoke the process method
    if hasattr(args, 'process'):
        args.process(args)
    else:
        ap.print_help()
Esempio n. 27
0
def main():
    ap = ArgumentParser(prog='pyfr')
    sp = ap.add_subparsers(dest='cmd', help='sub-command help')

    # Common options
    ap.add_argument('--verbose', '-v', action='count')

    # Import command
    ap_import = sp.add_parser('import', help='import --help')
    ap_import.add_argument('inmesh', type=FileType('r'),
                           help='input mesh file')
    ap_import.add_argument('outmesh', help='output PyFR mesh file')
    types = sorted(cls.name for cls in subclasses(BaseReader))
    ap_import.add_argument('-t', dest='type', choices=types,
                           help='input file type; this is usually inferred '
                           'from the extension of inmesh')
    ap_import.add_argument('-l', dest='lintol', type=float, default=1e-5,
                           help='linearisation tolerance')
    ap_import.set_defaults(process=process_import)

    # Partition command
    ap_partition = sp.add_parser('partition', help='partition --help')
    ap_partition.add_argument('np', help='number of partitions or a colon '
                              'delimited list of weights')
    ap_partition.add_argument('mesh', help='input mesh file')
    ap_partition.add_argument('solns', metavar='soln', nargs='*',
                              help='input solution files')
    ap_partition.add_argument('outd', help='output directory')
    partitioners = sorted(cls.name for cls in subclasses(BasePartitioner))
    ap_partition.add_argument('-p', dest='partitioner', choices=partitioners,
                              help='partitioner to use')
    ap_partition.add_argument('-r', dest='rnumf', type=FileType('w'),
                              help='output renumbering file')
    ap_partition.add_argument('-e', dest='elewts', action='append',
                              default=[], metavar='shape:weight',
                              help='element weighting factor')
    ap_partition.add_argument('--popt', dest='popts', action='append',
                              default=[], metavar='key:value',
                              help='partitioner-specific option')
    ap_partition.set_defaults(process=process_partition)

    # Export command
    ap_export = sp.add_parser('export', help='export --help')
    ap_export.add_argument('meshf', help='PyFR mesh file to be converted')
    ap_export.add_argument('solnf', help='PyFR solution file to be converted')
    ap_export.add_argument('outf', type=str, help='output file')
    types = [cls.name for cls in subclasses(BaseWriter)]
    ap_export.add_argument('-t', dest='type', choices=types, required=False,
                           help='output file type; this is usually inferred '
                           'from the extension of outf')
    output_options = ap_export.add_mutually_exclusive_group(required=False)
    output_options.add_argument('-d', '--divisor', type=int,
                                help='sets the level to which high order '
                                'elements are divided; output is linear '
                                'between nodes, so increased resolution '
                                'may be required')
    output_options.add_argument('-k', '--order', type=int, dest="order",
                                help='sets the order of high order elements')
    ap_export.add_argument('-g', '--gradients', action='store_true',
                           help='compute gradients')
    ap_export.add_argument('-p', '--precision', choices=['single', 'double'],
                           default='single', help='output number precision; '
                           'defaults to single')
    ap_export.set_defaults(process=process_export)

    # Run command
    ap_run = sp.add_parser('run', help='run --help')
    ap_run.add_argument('mesh', help='mesh file')
    ap_run.add_argument('cfg', type=FileType('r'), help='config file')
    ap_run.set_defaults(process=process_run)

    # Restart command
    ap_restart = sp.add_parser('restart', help='restart --help')
    ap_restart.add_argument('mesh', help='mesh file')
    ap_restart.add_argument('soln', help='solution file')
    ap_restart.add_argument('cfg', nargs='?', type=FileType('r'),
                            help='new config file')
    ap_restart.set_defaults(process=process_restart)

    # Options common to run and restart
    backends = sorted(cls.name for cls in subclasses(BaseBackend))
    for p in [ap_run, ap_restart]:
        p.add_argument('--backend', '-b', choices=backends, required=True,
                       help='backend to use')
        p.add_argument('--progress', '-p', action='store_true',
                       help='show a progress bar')

    # Parse the arguments
    args = ap.parse_args()

    # Invoke the process method
    if hasattr(args, 'process'):
        args.process(args)
    else:
        ap.print_help()
Esempio n. 28
0
def main():
    ap = ArgumentParser(prog="pyfr")
    sp = ap.add_subparsers(dest="cmd", help="sub-command help")

    # Common options
    ap.add_argument("--verbose", "-v", action="count")

    # Import command
    ap_import = sp.add_parser("import", help="import --help")
    ap_import.add_argument("inmesh", type=FileType("r"), help="input mesh file")
    ap_import.add_argument("outmesh", help="output PyFR mesh file")
    types = sorted(cls.name for cls in subclasses(BaseReader))
    ap_import.add_argument(
        "-t",
        dest="type",
        choices=types,
        help="input file type; this is usually inferred " "from the extension of inmesh",
    )
    ap_import.set_defaults(process=process_import)

    # Partition command
    ap_partition = sp.add_parser("partition", help="partition --help")
    ap_partition.add_argument("np", help="number of partitions or a colon " "delimited list of weighs")
    ap_partition.add_argument("mesh", help="input mesh file")
    ap_partition.add_argument("solns", nargs="*", help="input solution files")
    ap_partition.add_argument(dest="outd", help="output directory")
    partitioners = sorted(cls.name for cls in subclasses(BasePartitioner))
    ap_partition.add_argument("-p", dest="partitioner", choices=partitioners, help="partitioner to use")
    ap_partition.add_argument(
        "--popt", dest="popts", action="append", default=[], metavar="key:value", help="partitioner-specific option"
    )
    ap_partition.set_defaults(process=process_partition)

    # Export command
    ap_export = sp.add_parser(
        "export",
        help="export --help",
        description="Converts .pyfr[ms] files for " "visualisation in external software.",
    )
    ap_export.add_argument("meshf", help="PyFR mesh file to be converted")
    ap_export.add_argument("solnf", help="PyFR solution file to be converted")
    ap_export.add_argument("outf", type=str, help="Output filename")
    types = [cls.name for cls in subclasses(BaseWriter)]
    ap_export.add_argument(
        "-t",
        dest="type",
        choices=types,
        required=False,
        help="Output file type; this is usually inferred " "from the extension of outf",
    )
    ap_export.add_argument(
        "-d",
        "--divisor",
        type=int,
        default=0,
        help="Sets the level to which high order elements "
        "are divided along each edge. The total node count "
        "produced by divisor is equivalent to that of "
        "solution order, which is used as the default. "
        "Note: the output is linear between nodes, so "
        "increased resolution may be required.",
    )
    ap_export.add_argument(
        "-p",
        "--precision",
        choices=["single", "double"],
        default="single",
        help="Selects the precision of " "floating point numbers written to the output file; " "single is the default.",
    )
    ap_export.set_defaults(process=process_export)

    # Run command
    ap_run = sp.add_parser("run", help="run --help")
    ap_run.add_argument("mesh", help="mesh file")
    ap_run.add_argument("cfg", type=FileType("r"), help="config file")
    ap_run.set_defaults(process=process_run)

    # Restart command
    ap_restart = sp.add_parser("restart", help="restart --help")
    ap_restart.add_argument("mesh", help="mesh file")
    ap_restart.add_argument("soln", help="solution file")
    ap_restart.add_argument("cfg", nargs="?", type=FileType("r"), help="new config file")
    ap_restart.set_defaults(process=process_restart)

    # Options common to run and restart
    for p in [ap_run, ap_restart]:
        p.add_argument("--backend", "-b", default="cuda", help="Backend to use")
        p.add_argument("--progress", "-p", action="store_true", help="show a progress bar")

    # Time average command
    ap_tavg = sp.add_parser(
        "time-avg",
        help="time-avg --help",
        description="Computes the mean solution of a " "time-wise series of pyfrs files.",
    )
    ap_tavg.add_argument("outf", type=str, help="Output PyFR solution file " "name.")
    ap_tavg.add_argument("infs", type=str, nargs="+", help="Input " "PyFR solution files to be time-averaged.")
    ap_tavg.add_argument(
        "-l",
        "--limits",
        nargs=2,
        type=float,
        help="Exclude solution files (passed in the infs "
        "argument) that lie outside minimum and maximum "
        "solution time limits.",
    )
    ap_tavg.set_defaults(process=process_tavg)

    # Parse the arguments
    args = ap.parse_args()

    # Invoke the process method
    if hasattr(args, "process"):
        args.process(args)
    else:
        ap.print_help()