Example #1
0
def write_plot3d_grid(domain, grid_file, planes=False, binary=True,
                      big_endian=False, single_precision=True,
                      unformatted=True, logger=None):
    """
    Writes `domain` to `grid_file` in Plot3D format.

    domain: DomainObj
        The domain to be written.

    grid_file: string
        Grid filename.
    """
    logger = logger or NullLogger()

    mode = 'wb' if binary else 'w'
    with open(grid_file, mode) as out:
        logger.info("writing grid file '%s'", grid_file)
        stream = Stream(out, binary, big_endian, single_precision, False,
                        unformatted, False)
        if len(domain.zones) > 1:
            # Write number of zones.
            stream.write_int(len(domain.zones), full_record=True)

        # Write zone dimensions.
        _write_plot3d_dims(domain, stream, logger)

        # Write zone coordinates.
        for zone in domain.zones:
            name = domain.zone_name(zone)
            logger.debug('writing coords for %s', name)
            _write_plot3d_coords(zone, stream, planes, logger)
Example #2
0
def write_plot3d_f(domain, grid_file, f_file, varnames=None, planes=False,
                   binary=True, big_endian=False, single_precision=True,
                   unformatted=True, logger=None):
    """
    Writes `domain` to `grid_file` and `f_file` in Plot3D format.
    If `varnames` is None, then all arrays and then all vectors are written.

    domain: DomainObj
        The domain to be written.

    grid_file: string
        Grid filename.

    f_file: string
        Function data filename.
    """
    logger = logger or NullLogger()

    if varnames is None:
        flow = domain.zones[0].flow_solution
        varnames = [flow.name_of_obj(obj) for obj in flow.arrays]
        varnames.extend([flow.name_of_obj(obj) for obj in flow.vectors])

    # Verify we have the needed data.
    for zone in domain.zones:
        flow = zone.flow_solution
        missing = []
        for name in varnames:
            if not hasattr(flow, name):
                missing.append(name)
        if missing:
            raise AttributeError('zone %s flow_solution is missing %s' \
                                 % (domain.zone_name(zone), missing))
    # Write grid file.
    write_plot3d_grid(domain, grid_file, planes, binary, big_endian,
                      single_precision, unformatted, logger)
    # Write F file.
    mode = 'wb' if binary else 'w'
    with open(f_file, mode) as out:
        logger.info("writing F file '%s'", f_file)
        stream = Stream(out, binary, big_endian, single_precision, False,
                        unformatted, False)
        if len(domain.zones) > 1:
            # Write number of zones.
            stream.write_int(len(domain.zones), full_record=True)

        # Write zone dimensions.
        _write_plot3d_dims(domain, stream, logger, varnames)

        # Write zone variables.
        for zone in domain.zones:
            name = domain.zone_name(zone)
            logger.debug('writing data for %s', name)
            _write_plot3d_vars(zone, stream, varnames, planes, logger)
Example #3
0
def write_plot3d_q(domain, grid_file, q_file, planes=False, binary=True,
                   big_endian=False, single_precision=True, unformatted=True,
                   logger=None):
    """
    Writes `domain` to `grid_file` and `q_file` in Plot3D format.
    Requires 'density', 'momentum', and 'energy_stagnation_density' variables
    as well as 'mach', 'alpha', 'reynolds', and 'time' scalars.

    domain: DomainObj
        The domain to be written.

    grid_file: string
        Grid filename.

    q_file: string
        Q data filename.
    """
    logger = logger or NullLogger()

    # Verify we have the needed data.
    for zone in domain.zones:
        flow = zone.flow_solution
        missing = []
        for name in ('mach', 'alpha', 'reynolds', 'time',
                     'density', 'momentum', 'energy_stagnation_density'):
            if not hasattr(flow, name):
                missing.append(name)
        if missing:
            raise AttributeError('zone %s flow_solution is missing %s' \
                                 % (domain.zone_name(zone), missing))
    # Write grid file.
    write_plot3d_grid(domain, grid_file, planes, binary, big_endian,
                      single_precision, unformatted, logger)
    # Write Q file.
    mode = 'wb' if binary else 'w'
    with open(q_file, mode) as out:
        logger.info("writing Q file '%s'", q_file)
        stream = Stream(out, binary, big_endian, single_precision, False,
                        unformatted, False)
        if len(domain.zones) > 1:
            # Write number of zones.
            stream.write_int(len(domain.zones), full_record=True)

        # Write zone dimensions.
        _write_plot3d_dims(domain, stream, logger)

        # Write zone scalars and variables.
        varnames = ('density', 'momentum', 'energy_stagnation_density')
        for zone in domain.zones:
            name = domain.zone_name(zone)
            logger.debug('writing data for %s', name)
            _write_plot3d_qscalars(zone, stream, logger)
            _write_plot3d_vars(zone, stream, varnames, planes, logger)
Example #4
0
def write_plot3d_grid(domain, grid_file, planes=False, binary=True,
                      big_endian=False, single_precision=True,
                      unformatted=True, logger=None):
    """
    Writes `domain` to `grid_file` in Plot3D format.
    Ghost data is not written.

    domain: :class:`DomainObj` or :class:`Zone`
        The domain or zone to be written.

    grid_file: string
        Grid filename.
    """
    logger = logger or NullLogger()

    if isinstance(domain, DomainObj):
        writing_domain = True
        zones = domain.zones
    elif isinstance(domain, Zone):
        writing_domain = False
        zones = [domain]
    else:
        raise TypeError("'domain' argument must be a DomainObj or Zone")

    mode = 'wb' if binary else 'w'
    with open(grid_file, mode) as out:
        logger.info('writing grid file %r', grid_file)
        stream = Stream(out, binary, big_endian, single_precision, False,
                        unformatted, False)
        if len(zones) > 1:
            # Write number of zones.
            stream.write_int(len(zones), full_record=True)

        # Write zone dimensions.
        _write_plot3d_dims(domain, stream, logger)

        # Write zone coordinates.
        for zone in zones:
            if writing_domain:
                name = domain.zone_name(zone)
            else:
                name = 'zone'
            logger.debug('writing coords for %s', name)
            _write_plot3d_coords(zone, stream, planes, logger)
Example #5
0
def write_plot3d_f(domain, grid_file, f_file, varnames=None, planes=False,
                   binary=True, big_endian=False, single_precision=True,
                   unformatted=True, logger=None):
    """
    Writes `domain` to `grid_file` and `f_file` in Plot3D format.
    If `varnames` is None, then all arrays and then all vectors are written.
    Ghost data is not written.

    domain: :class:`DomainObj` or :class:`Zone`
        The domain or zone to be written.

    grid_file: string
        Grid filename.

    f_file: string
        Function data filename.
    """
    logger = logger or NullLogger()

    if isinstance(domain, DomainObj):
        writing_domain = True
        zones = domain.zones
    elif isinstance(domain, Zone):
        writing_domain = False
        zones = [domain]
    else:
        raise TypeError("'domain' argument must be a DomainObj or Zone")

    if varnames is None:
        flow = zones[0].flow_solution
        varnames = [flow.name_of_obj(obj) for obj in flow.arrays]
        varnames.extend([flow.name_of_obj(obj) for obj in flow.vectors])

    # Verify we have the needed data.
    for zone in zones:
        flow = zone.flow_solution
        missing = []
        for name in varnames:
            if not hasattr(flow, name):
                missing.append(name)
        if missing:
            if writing_domain:
                name = domain.zone_name(zone)
            else:
                name = ''
            raise AttributeError('zone %s flow_solution is missing %s'
                                 % (name, missing))
    # Write grid file.
    write_plot3d_grid(domain, grid_file, planes, binary, big_endian,
                      single_precision, unformatted, logger)
    # Write F file.
    mode = 'wb' if binary else 'w'
    with open(f_file, mode) as out:
        logger.info('writing F file %r', f_file)
        stream = Stream(out, binary, big_endian, single_precision, False,
                        unformatted, False)
        if len(zones) > 1:
            # Write number of zones.
            stream.write_int(len(zones), full_record=True)

        # Write zone dimensions.
        _write_plot3d_dims(domain, stream, logger, varnames)

        # Write zone variables.
        for zone in zones:
            if writing_domain:
                name = domain.zone_name(zone)
            else:
                name = 'zone'
            logger.debug('writing data for %s', name)
            _write_plot3d_vars(zone, stream, varnames, planes, logger)
Example #6
0
def write_plot3d_q(domain, grid_file, q_file, planes=False, binary=True,
                   big_endian=False, single_precision=True, unformatted=True,
                   logger=None):
    """
    Writes `domain` to `grid_file` and `q_file` in Plot3D format.
    Requires 'density', 'momentum', and 'energy_stagnation_density' variables
    as well as 'mach', 'alpha', 'reynolds', and 'time' scalars.
    Ghost data is not written.

    domain: :class:`DomainObj` or :class:`Zone`
        The domain or zone to be written.

    grid_file: string
        Grid filename.

    q_file: string
        Q data filename.
    """
    logger = logger or NullLogger()

    if isinstance(domain, DomainObj):
        writing_domain = True
        zones = domain.zones
    elif isinstance(domain, Zone):
        writing_domain = False
        zones = [domain]
    else:
        raise TypeError("'domain' argument must be a DomainObj or Zone")

    # Verify we have the needed data.
    for zone in zones:
        flow = zone.flow_solution
        missing = []
        for name in ('mach', 'alpha', 'reynolds', 'time',
                     'density', 'momentum', 'energy_stagnation_density'):
            if not hasattr(flow, name):
                missing.append(name)
        if missing:
            if writing_domain:
                name = domain.zone_name(zone)
            else:
                name = ''
            raise AttributeError('zone %s flow_solution is missing %s'
                                 % (name, missing))
    # Write grid file.
    write_plot3d_grid(domain, grid_file, planes, binary, big_endian,
                      single_precision, unformatted, logger)
    # Write Q file.
    mode = 'wb' if binary else 'w'
    with open(q_file, mode) as out:
        logger.info('writing Q file %r', q_file)
        stream = Stream(out, binary, big_endian, single_precision, False,
                        unformatted, False)
        if len(zones) > 1:
            # Write number of zones.
            stream.write_int(len(zones), full_record=True)

        # Write zone dimensions.
        _write_plot3d_dims(domain, stream, logger)

        # Write zone scalars and variables.
        varnames = ('density', 'momentum', 'energy_stagnation_density')
        for zone in zones:
            if writing_domain:
                name = domain.zone_name(zone)
            else:
                name = 'zone'
            logger.debug('writing data for %s', name)
            _write_plot3d_qscalars(zone, stream, logger)
            _write_plot3d_vars(zone, stream, varnames, planes, logger)
def write(domain, casename, logger, suffix='restart.new'):
    """
    Write domain as ADPAC .mesh and .restart files.

    NOTE: if any zones are cylindrical, their grid_coordinates are changed
          to cartesian and then back to cylindrical.  This will affect the
          coordinate values slightly.
    """

# FIXME: don't mess up mesh!
    # Write (cartesian) mesh.
    cylindricals = []
    for zone in domain.zones:
        if zone.coordinate_system == 'Cylindrical':
            logger.debug('Converting %s to cartesian coordinates',
                         domain.zone_name(zone))
            cylindricals.append(zone)
            zone.grid_coordinates.make_cartesian(axis='x')
    try:
        write_plot3d_grid(domain, casename+'.mesh', big_endian=True,
                          unformatted=False, logger=logger)
    finally:
        for zone in cylindricals:
            logger.debug('Converting %s back to cylindrical coordinates',
                         domain.zone_name(zone))
            zone.grid_coordinates.make_cylindrical(axis='x')

    # Write restart.
    restart = casename+suffix
    with open(restart, 'wb') as out:
        logger.info('writing restart file %r', restart)
        stream = Stream(out, binary=True, big_endian=True,
                        single_precision=True, integer_8=False,
                        unformatted=False, recordmark_8=False)

        # Write number of zones.
        stream.write_int(len(domain.zones))

        # Write zone dimensions.
        for zone in domain.zones:
            name = domain.zone_name(zone)
            imax, jmax, kmax = zone.shape
            logger.debug('    %s: %dx%dx%d', name, imax+1, jmax+1, kmax+1)
            stream.write_ints((imax+1, jmax+1, kmax+1))

        # Write zone variables.
        for zone in domain.zones:
            name = domain.zone_name(zone)
            logger.debug('writing data for %s', name)

            arr = zone.flow_solution.density
            logger.debug('    density min %g, max %g', arr.min(), arr.max())
            stream.write_floats(arr, order='Fortran')

            if zone.coordinate_system == 'Cartesian':
                arr = zone.flow_solution.momentum.x
                logger.debug('    momentum.x min %g, max %g',
                             arr.min(), arr.max())
                stream.write_floats(zone.flow_solution.momentum.x,
                                    order='Fortran')

                arr = zone.flow_solution.momentum.y
                logger.debug('    momentum.y min %g, max %g',
                             arr.min(), arr.max())
                stream.write_floats(zone.flow_solution.momentum.y,
                                    order='Fortran')

                arr = zone.flow_solution.momentum.z
                logger.debug('    momentum.z min %g, max %g',
                             arr.min(), arr.max())
                stream.write_floats(zone.flow_solution.momentum.z,
                                    order='Fortran')
            else:
                arr = zone.flow_solution.momentum.z
                logger.debug('    momentum.z min %g, max %g',
                             arr.min(), arr.max())
                stream.write_floats(zone.flow_solution.momentum.z,
                                    order='Fortran')

                arr = zone.flow_solution.momentum.r
                logger.debug('    momentum.r min %g, max %g',
                             arr.min(), arr.max())
                stream.write_floats(zone.flow_solution.momentum.r,
                                    order='Fortran')

                arr = zone.flow_solution.momentum.t
                logger.debug('    momentum.t min %g, max %g',
                             arr.min(), arr.max())
                stream.write_floats(zone.flow_solution.momentum.t,
                                    order='Fortran')

            arr = zone.flow_solution.energy_stagnation_density
            logger.debug('    energy_stagnation_density min %g, max %g',
                         arr.min(), arr.max())
            stream.write_floats(zone.flow_solution.energy_stagnation_density,
                                order='Fortran')

            arr = zone.flow_solution.pressure
            logger.debug('    pressure min %g, max %g', arr.min(), arr.max())
            stream.write_floats(zone.flow_solution.pressure, order='Fortran')

        # Write zone scalars.
        ncyc = []
        dtheta = []
        omegal = []
        for zone in domain.zones:
            ncyc.append(zone.flow_solution.ncyc)
            dtheta.append(zone.flow_solution.dtheta)
            omegal.append(zone.flow_solution.omegal)
        logger.debug('    ncyc %s', str(ncyc))
        logger.debug('    dtheta %s', str(dtheta))
        logger.debug('    omegal %s', str(omegal))
        stream.write_ints(ncyc)
        stream.write_floats(dtheta)
        stream.write_floats(omegal)

        # Implicit calculation data not supported.
        stream.write_int(0)
    def test_int32(self):
        logging.debug('')
        logging.debug('test_int32')

        # 'Normal' integers.
        data = numpy.arange(0, 10, dtype=numpy.int32)
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True)
            stream.write_ints(data)
        self.assertEqual(os.path.getsize(self.filename), 40)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True)
            new_data = stream.read_ints(data.size)
        numpy.testing.assert_array_equal(new_data, data)

        # Text scalar.
        with open(self.filename, 'w') as out:
            stream = Stream(out)
            stream.write_int(4, sep=' ')
            stream.write_int(2, full_record=True)
        size = 5 if sys.platform == 'win32' else 4  # CR LF
        self.assertEqual(os.path.getsize(self.filename), size)
        with open(self.filename, 'r') as inp:
            new_data = inp.read()
            self.assertEqual(new_data, '4 2\n')

        # Unformatted scalar.
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, unformatted=True)
            stream.write_int(1, full_record=True)
        self.assertEqual(os.path.getsize(self.filename), 12)
        with open(self.filename, 'rb') as inp:
            new_data = inp.read()
            self.assertEqual(new_data, UNF_I4)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True)
            new_data = stream.read_int()
        try:
            self.assertEqual(new_data, 1)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, unformatted=True)
            new_data = stream.read_int(full_record=True)
        self.assertEqual(new_data, 1)

        # Unformatted array.
        data = numpy.arange(1, 9, dtype=numpy.int32)
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, unformatted=True)
            stream.write_ints(data, full_record=True)
        self.assertEqual(os.path.getsize(self.filename), 40)
        with open(self.filename, 'rb') as inp:
            new_data = inp.read()
            self.assertEqual(new_data, UNF_I4A)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True)
            new_data = stream.read_ints(data.size)
        try:
            numpy.testing.assert_array_equal(new_data, data)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, unformatted=True)
            new_data = stream.read_ints(data.size, full_record=True)
        numpy.testing.assert_array_equal(new_data, data)

        # Byteswapped.
        swap_endian = sys.byteorder == 'little'
        wrong_endian = not swap_endian
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, big_endian=swap_endian)
            stream.write_ints(data)
        self.assertEqual(os.path.getsize(self.filename), 32)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, big_endian=wrong_endian)
            new_data = stream.read_ints(data.size)
        try:
            numpy.testing.assert_array_equal(new_data, data)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, big_endian=swap_endian)
            new_data = stream.read_ints(data.size)
        numpy.testing.assert_array_equal(new_data, data)

        # Write as 8-byte integers.
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, integer_8=True)
            stream.write_ints(data)
        self.assertEqual(os.path.getsize(self.filename), 64)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True)
            new_data = stream.read_ints(data.size)
        numpy.testing.assert_array_equal(new_data, data)

        # Write from list.
        data = list(data)
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True)
            stream.write_ints(data)
        self.assertEqual(os.path.getsize(self.filename), 32)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True)
            new_data = stream.read_ints(len(data))
        numpy.testing.assert_array_equal(new_data, data)
    def test_int64(self):
        logging.debug('')
        logging.debug('test_int64')

        # Big integers, which are default on some machines.
        data = numpy.arange(1, 9, dtype=numpy.int64)
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, integer_8=True)
            stream.write_ints(data)
        self.assertEqual(os.path.getsize(self.filename), 64)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True)
            new_data = stream.read_ints(data.size)
        numpy.testing.assert_array_equal(new_data, data)

        # Unformatted scalar.
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, integer_8=True, unformatted=True)
            stream.write_int(1, full_record=True)
        self.assertEqual(os.path.getsize(self.filename), 16)
        with open(self.filename, 'rb') as inp:
            new_data = inp.read()
            self.assertEqual(new_data, UNF_I8)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True)
            new_data = stream.read_int()
        try:
            self.assertEqual(new_data, 1)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True, unformatted=True)
            new_data = stream.read_int(full_record=True)
        self.assertEqual(new_data, 1)

        # Unformatted array.
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, integer_8=True, unformatted=True)
            stream.write_ints(data, full_record=True)
        self.assertEqual(os.path.getsize(self.filename), 72)
        with open(self.filename, 'rb') as inp:
            new_data = inp.read()
            self.assertEqual(new_data, UNF_I8A)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True)
            new_data = stream.read_ints(data.size)
        try:
            numpy.testing.assert_array_equal(new_data, data)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True, unformatted=True)
            new_data = stream.read_ints(data.size, full_record=True)
        numpy.testing.assert_array_equal(new_data, data)

        # Write as 4-byte integers.
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True)
            stream.write_ints(data)
        self.assertEqual(os.path.getsize(self.filename), 32)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True)
            new_data = stream.read_ints(data.size)
        numpy.testing.assert_array_equal(new_data, data)

        # Row-major.
        data = numpy.arange(0, 10, dtype=numpy.int64)
        arr2d = data.reshape((5, 2))
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, integer_8=True)
            stream.write_ints(arr2d)
        self.assertEqual(os.path.getsize(self.filename), 80)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True)
            new_data = stream.read_ints((5, 2))
        numpy.testing.assert_array_equal(new_data, arr2d)

        # Row-major text.
        with open(self.filename, 'w') as out:
            stream = Stream(out)
            stream.write_ints(arr2d, linecount=4)
        with open(self.filename, 'r') as inp:
            stream = Stream(inp)
            new_data = stream.read_ints((5, 2), order='Fortran')
        try:
            numpy.testing.assert_array_equal(new_data, arr2d)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'r') as inp:
            stream = Stream(inp)
            new_data = stream.read_ints((5, 2), order='C')
        numpy.testing.assert_array_equal(new_data, arr2d)

        # Column-major.
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, integer_8=True)
            stream.write_ints(arr2d, order='Fortran')
        self.assertEqual(os.path.getsize(self.filename), 80)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True)
            new_data = stream.read_ints((5, 2))
        try:
            numpy.testing.assert_array_equal(new_data, arr2d)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True)
            new_data = stream.read_ints((5, 2), order='Fortran')
        numpy.testing.assert_array_equal(new_data, arr2d)

        # Column-major text.
        with open(self.filename, 'w') as out:
            stream = Stream(out)
            stream.write_ints(arr2d, order='Fortran', linecount=4)
        with open(self.filename, 'r') as inp:
            stream = Stream(inp)
            new_data = stream.read_ints((5, 2))
        try:
            numpy.testing.assert_array_equal(new_data, arr2d)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'r') as inp:
            stream = Stream(inp)
            new_data = stream.read_ints((5, 2), order='Fortran')
        numpy.testing.assert_array_equal(new_data, arr2d)

        # Illegal-order text.
        with open(self.filename, 'w') as out:
            stream = Stream(out)
            assert_raises(self, "stream.write_ints(arr2d, order='Unknown')",
                          globals(), locals(), ValueError,
                          "order must be 'C' or 'Fortran'")
    def test_int32(self):
        logging.debug('')
        logging.debug('test_int32')

        # 'Normal' integers.
        data = numpy.arange(0, 10, dtype=numpy.int32)
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True)
            stream.write_ints(data)
        self.assertEqual(os.path.getsize(self.filename), 40)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True)
            new_data = stream.read_ints(data.size)
        numpy.testing.assert_array_equal(new_data, data)

        # Text scalar.
        with open(self.filename, 'w') as out:
            stream = Stream(out)
            stream.write_int(4, sep=' ')
            stream.write_int(2, full_record=True)
        size = 5 if sys.platform == 'win32' else 4  # CR LF
        self.assertEqual(os.path.getsize(self.filename), size)
        with open(self.filename, 'r') as inp:
            new_data = inp.read()
            self.assertEqual(new_data, '4 2\n')

        # Unformatted scalar.
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, unformatted=True)
            stream.write_int(1, full_record=True)
        self.assertEqual(os.path.getsize(self.filename), 12)
        with open(self.filename, 'rb') as inp:
            new_data = inp.read()
            self.assertEqual(new_data, UNF_I4)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True)
            new_data = stream.read_int()
        try:
            self.assertEqual(new_data, 1)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, unformatted=True)
            new_data = stream.read_int(full_record=True)
        self.assertEqual(new_data, 1)

        # Unformatted array.
        data = numpy.arange(1, 9, dtype=numpy.int32)
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, unformatted=True)
            stream.write_ints(data, full_record=True)
        self.assertEqual(os.path.getsize(self.filename), 40)
        with open(self.filename, 'rb') as inp:
            new_data = inp.read()
            self.assertEqual(new_data, UNF_I4A)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True)
            new_data = stream.read_ints(data.size)
        try:
            numpy.testing.assert_array_equal(new_data, data)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, unformatted=True)
            new_data = stream.read_ints(data.size, full_record=True)
        numpy.testing.assert_array_equal(new_data, data)

        # Byteswapped.
        swap_endian = sys.byteorder == 'little'
        wrong_endian = not swap_endian
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, big_endian=swap_endian)
            stream.write_ints(data)
        self.assertEqual(os.path.getsize(self.filename), 32)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, big_endian=wrong_endian)
            new_data = stream.read_ints(data.size)
        try:
            numpy.testing.assert_array_equal(new_data, data)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, big_endian=swap_endian)
            new_data = stream.read_ints(data.size)
        numpy.testing.assert_array_equal(new_data, data)

        # Write as 8-byte integers.
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, integer_8=True)
            stream.write_ints(data)
        self.assertEqual(os.path.getsize(self.filename), 64)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True)
            new_data = stream.read_ints(data.size)
        numpy.testing.assert_array_equal(new_data, data)

        # Write from list.
        data = list(data)
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True)
            stream.write_ints(data)
        self.assertEqual(os.path.getsize(self.filename), 32)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True)
            new_data = stream.read_ints(len(data))
        numpy.testing.assert_array_equal(new_data, data)
    def test_int64(self):
        logging.debug('')
        logging.debug('test_int64')

        # Big integers, which are default on some machines.
        data = numpy.arange(1, 9, dtype=numpy.int64)
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, integer_8=True)
            stream.write_ints(data)
        self.assertEqual(os.path.getsize(self.filename), 64)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True)
            new_data = stream.read_ints(data.size)
        numpy.testing.assert_array_equal(new_data, data)

        # Unformatted scalar.
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, integer_8=True, unformatted=True)
            stream.write_int(1, full_record=True)
        self.assertEqual(os.path.getsize(self.filename), 16)
        with open(self.filename, 'rb') as inp:
            new_data = inp.read()
            self.assertEqual(new_data, UNF_I8)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True)
            new_data = stream.read_int()
        try:
            self.assertEqual(new_data, 1)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True, unformatted=True)
            new_data = stream.read_int(full_record=True)
        self.assertEqual(new_data, 1)

        # Unformatted array.
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, integer_8=True, unformatted=True)
            stream.write_ints(data, full_record=True)
        self.assertEqual(os.path.getsize(self.filename), 72)
        with open(self.filename, 'rb') as inp:
            new_data = inp.read()
            self.assertEqual(new_data, UNF_I8A)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True)
            new_data = stream.read_ints(data.size)
        try:
            numpy.testing.assert_array_equal(new_data, data)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True, unformatted=True)
            new_data = stream.read_ints(data.size, full_record=True)
        numpy.testing.assert_array_equal(new_data, data)

        # Write as 4-byte integers.
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True)
            stream.write_ints(data)
        self.assertEqual(os.path.getsize(self.filename), 32)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True)
            new_data = stream.read_ints(data.size)
        numpy.testing.assert_array_equal(new_data, data)

        # Row-major.
        data = numpy.arange(0, 10, dtype=numpy.int64)
        arr2d = data.reshape((5, 2))
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, integer_8=True)
            stream.write_ints(arr2d)
        self.assertEqual(os.path.getsize(self.filename), 80)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True)
            new_data = stream.read_ints((5, 2))
        numpy.testing.assert_array_equal(new_data, arr2d)

        # Row-major text.
        with open(self.filename, 'w') as out:
            stream = Stream(out)
            stream.write_ints(arr2d, linecount=4)
        with open(self.filename, 'r') as inp:
            stream = Stream(inp)
            new_data = stream.read_ints((5, 2), order='Fortran')
        try:
            numpy.testing.assert_array_equal(new_data, arr2d)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'r') as inp:
            stream = Stream(inp)
            new_data = stream.read_ints((5, 2), order='C')
        numpy.testing.assert_array_equal(new_data, arr2d)

        # Column-major.
        with open(self.filename, 'wb') as out:
            stream = Stream(out, binary=True, integer_8=True)
            stream.write_ints(arr2d, order='Fortran')
        self.assertEqual(os.path.getsize(self.filename), 80)
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True)
            new_data = stream.read_ints((5, 2))
        try:
            numpy.testing.assert_array_equal(new_data, arr2d)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'rb') as inp:
            stream = Stream(inp, binary=True, integer_8=True)
            new_data = stream.read_ints((5, 2), order='Fortran')
        numpy.testing.assert_array_equal(new_data, arr2d)

        # Column-major text.
        with open(self.filename, 'w') as out:
            stream = Stream(out)
            stream.write_ints(arr2d, order='Fortran', linecount=4)
        with open(self.filename, 'r') as inp:
            stream = Stream(inp)
            new_data = stream.read_ints((5, 2))
        try:
            numpy.testing.assert_array_equal(new_data, arr2d)
        except AssertionError:
            pass
        else:
            self.fail('Expected AssertionError')
        with open(self.filename, 'r') as inp:
            stream = Stream(inp)
            new_data = stream.read_ints((5, 2), order='Fortran')
        numpy.testing.assert_array_equal(new_data, arr2d)

        # Illegal-order text.
        with open(self.filename, 'w') as out:
            stream = Stream(out)
            assert_raises(self, "stream.write_ints(arr2d, order='Unknown')",
                          globals(), locals(), ValueError,
                          "order must be 'C' or 'Fortran'")
Example #12
0
def write(domain, casename, logger, suffix='restart.new'):
    """
    Write domain as ADPAC .mesh and .restart files.

    NOTE: if any zones are cylindrical, their grid_coordinates are changed
          to cartesian and then back to cylindrical.  This will affect the
          coordinate values slightly.
    """

    # FIXME: don't mess up mesh!
    # Write (cartesian) mesh.
    cylindricals = []
    for zone in domain.zones:
        if zone.coordinate_system == 'Cylindrical':
            logger.debug('Converting %s to cartesian coordinates',
                         domain.zone_name(zone))
            cylindricals.append(zone)
            zone.grid_coordinates.make_cartesian(axis='x')
    try:
        write_plot3d_grid(domain,
                          casename + '.mesh',
                          big_endian=True,
                          unformatted=False,
                          logger=logger)
    finally:
        for zone in cylindricals:
            logger.debug('Converting %s back to cylindrical coordinates',
                         domain.zone_name(zone))
            zone.grid_coordinates.make_cylindrical(axis='x')

    # Write restart.
    restart = casename + suffix
    with open(restart, 'wb') as out:
        logger.info('writing restart file %r', restart)
        stream = Stream(out,
                        binary=True,
                        big_endian=True,
                        single_precision=True,
                        integer_8=False,
                        unformatted=False,
                        recordmark_8=False)

        # Write number of zones.
        stream.write_int(len(domain.zones))

        # Write zone dimensions.
        for zone in domain.zones:
            name = domain.zone_name(zone)
            imax, jmax, kmax = zone.shape
            logger.debug('    %s: %dx%dx%d', name, imax + 1, jmax + 1,
                         kmax + 1)
            stream.write_ints((imax + 1, jmax + 1, kmax + 1))

        # Write zone variables.
        for zone in domain.zones:
            name = domain.zone_name(zone)
            logger.debug('writing data for %s', name)

            arr = zone.flow_solution.density
            logger.debug('    density min %g, max %g', arr.min(), arr.max())
            stream.write_floats(arr, order='Fortran')

            if zone.coordinate_system == 'Cartesian':
                arr = zone.flow_solution.momentum.x
                logger.debug('    momentum.x min %g, max %g', arr.min(),
                             arr.max())
                stream.write_floats(zone.flow_solution.momentum.x,
                                    order='Fortran')

                arr = zone.flow_solution.momentum.y
                logger.debug('    momentum.y min %g, max %g', arr.min(),
                             arr.max())
                stream.write_floats(zone.flow_solution.momentum.y,
                                    order='Fortran')

                arr = zone.flow_solution.momentum.z
                logger.debug('    momentum.z min %g, max %g', arr.min(),
                             arr.max())
                stream.write_floats(zone.flow_solution.momentum.z,
                                    order='Fortran')
            else:
                arr = zone.flow_solution.momentum.z
                logger.debug('    momentum.z min %g, max %g', arr.min(),
                             arr.max())
                stream.write_floats(zone.flow_solution.momentum.z,
                                    order='Fortran')

                arr = zone.flow_solution.momentum.r
                logger.debug('    momentum.r min %g, max %g', arr.min(),
                             arr.max())
                stream.write_floats(zone.flow_solution.momentum.r,
                                    order='Fortran')

                arr = zone.flow_solution.momentum.t
                logger.debug('    momentum.t min %g, max %g', arr.min(),
                             arr.max())
                stream.write_floats(zone.flow_solution.momentum.t,
                                    order='Fortran')

            arr = zone.flow_solution.energy_stagnation_density
            logger.debug('    energy_stagnation_density min %g, max %g',
                         arr.min(), arr.max())
            stream.write_floats(zone.flow_solution.energy_stagnation_density,
                                order='Fortran')

            arr = zone.flow_solution.pressure
            logger.debug('    pressure min %g, max %g', arr.min(), arr.max())
            stream.write_floats(zone.flow_solution.pressure, order='Fortran')

        # Write zone scalars.
        ncyc = []
        dtheta = []
        omegal = []
        for zone in domain.zones:
            ncyc.append(zone.flow_solution.ncyc)
            dtheta.append(zone.flow_solution.dtheta)
            omegal.append(zone.flow_solution.omegal)
        logger.debug('    ncyc %s', str(ncyc))
        logger.debug('    dtheta %s', str(dtheta))
        logger.debug('    omegal %s', str(omegal))
        stream.write_ints(ncyc)
        stream.write_floats(dtheta)
        stream.write_floats(omegal)

        # Implicit calculation data not supported.
        stream.write_int(0)