Exemple #1
0
def read_results(filename, only_names=None):
    """
    Read probing results from a file.

    Parameters
    ----------
    filename : str or file object
        The probe results file name.

    Returns
    -------
    header : Struct instance
        The probe data header.
    results : dict
        The dictionary of probing results. Keys are data names, values are
        the probed values.
    """
    from sfepy.base.ioutils import read_array

    only_names = get_default(only_names, [])

    fd = open(filename, 'r') if isinstance(filename, basestr) else filename

    header = read_header(fd)
    results = {}
    for name, nc in get_data_name(fd):
        if name not in only_names: continue

        result = read_array(fd, header.n_point, nc + 1, nm.float64)
        results[name] = result

    return header, results
Exemple #2
0
    def read_boundin_box(self, ret_fd=False, ret_dim=False):
        fd = open(self.filename, "r")
        while 1:
            try:
                line = fd.readline().split()
                if line[0] == "POINTS":
                    nod = read_array(fd, 1, -1, nm.float64)
                    dim = nod.shape[1]
                    break
            except:
                output("reading " + fd.name + " failed!")
                raise

        bbox = [[nod[0][0]] * 2, [nod[0][1]] * 2, [nod[0][2]] * 2]

        for inod in nod[1:]:
            for idim in range(dim):
                if inod[idim] < bbox[idim][0]:
                    bbox[idim][0] = inod[idim]
                if inod[idim] > bbox[idim][1]:
                    bbox[idim][1] = inod[idim]

        if ret_dim:
            if ret_fd:
                return bbox, dim, fd
            else:
                fd.close()
                return bbox, dim
        else:
            if ret_fd:
                return bbox, fd
            else:
                fd.close()
                return bbox
Exemple #3
0
def read_results(filename, only_names=None):
    """
    Read probing results from a file.

    Parameters
    ----------
    filename : str or file object
        The probe results file name.

    Returns
    -------
    header : Struct instance
        The probe data header.
    results : dict
        The dictionary of probing results. Keys are data names, values are
        the probed values.
    """
    from sfepy.base.ioutils import read_array

    only_names = get_default(only_names, [])

    fd = open(filename, 'r') if isinstance(filename, basestr) else filename

    header = read_header(fd)
    results = {}
    for name, nc in get_data_name(fd):
        if name not in only_names: continue

        result = read_array(fd, header.n_point, nc + 1, nm.float64)
        results[name] = result

    return header, results
Exemple #4
0
    def read_boundin_box(self, ret_fd=False, ret_dim=False):
        fd = open(self.filename, "r")

        while 1:
            try:
                line = fd.readline()
            except:
                output("reading " + fd.name + " failed!")
                raise
            if len(line) == 0:
                break
            if len(line) == 1:
                continue
            if line[0] == "#":
                continue
            aux = line.split()
            if aux[0] == "Dimension":
                if len(aux) == 2:
                    dim = int(aux[1])
                else:
                    dim = int(fd.readline())
            elif aux[0] == "Vertices":
                num = int(read_token(fd))
                nod = read_array(fd, num, dim + 1, nm.float64)
                break

        bbox = [[nod[0][0]] * 2, [nod[0][1]] * 2, [nod[0][2]] * 2]

        for inod in nod[1:]:
            for idim in range(dim):
                if inod[idim] < bbox[idim][0]:
                    bbox[idim][0] = inod[idim]
                if inod[idim] > bbox[idim][1]:
                    bbox[idim][1] = inod[idim]

        if ret_dim:
            if ret_fd:
                return bbox, dim, fd
            else:
                fd.close()
                return bbox, dim
        else:
            if ret_fd:
                return bbox, fd
            else:
                fd.close()
                return bbox
Exemple #5
0
    def read_dimension(self, ret_fd=False):
        fd = open(self.filename, "r")
        while 1:
            try:
                line = fd.readline().split()
                if not line:
                    continue
                if line[0] == "CELL_TYPES":
                    cell_types = read_array(fd, 1, -1, nm.int32)
                    dim = vtk_dims[cell_types[0, 0]]
                    break
            except:
                output("reading " + fd.name + " failed!")
                raise

        if ret_fd:
            return dim, fd
        else:
            fd.close()
            return dim
Exemple #6
0
def postprocess(filename_input, filename_results, options):
    """
    Postprocess probe data files - replot, integrate data.
    """
    from matplotlib import pyplot as plt

    only_names = options.only_names

    fd = open(filename_input, 'r')

    header = read_header(fd)
    output(header)

    fig = plt.figure()
    for name in get_data_name(fd):
        if (only_names is not None) and (name not in only_names): continue

        data = read_array(fd, header.n_point, 2, nm.float64)
        pars, vals = data[:, 0], data[:, 1]

        ii = nm.where(nm.isfinite(vals))[0]
        # Nans only at the edges.
        assert_(nm.diff(ii).sum() == (len(ii) - 1))

        val = integrate_along_line(pars[ii], vals[ii], options.radial)

        label = r'%s: $\int\ %s' % (name, name)
        if options.radial:
            label += ' (r)'
        label += '$ = %.5e' % val

        plt.plot(pars, vals, label=label, lw=0.2, marker='+', ms=1)
        plt.ylabel('probed data')
        plt.xlabel('probe coordinate')

        output(label)

    plt.legend()

    fig.savefig(filename_results)
    fd.close()
Exemple #7
0
def postprocess(filename_input, filename_results, options):
    """
    Postprocess probe data files - replot, integrate data.
    """
    from matplotlib import pyplot as plt

    only_names = options.only_names

    fd = open(filename_input, 'r')

    header = read_header(fd)
    output(header)

    fig = plt.figure()
    for name in get_data_name(fd):
        if (only_names is not None) and (name not in only_names): continue

        data = read_array(fd, header.n_point, 2, nm.float64)
        pars, vals = data[:,0], data[:,1]

        ii = nm.where(nm.isfinite(vals))[0]
        # Nans only at the edges.
        assert_(nm.diff(ii).sum() == (len(ii)-1))

        val = integrate_along_line(pars[ii], vals[ii], options.radial)

        label = r'%s: $\int\ %s' % (name, name)
        if options.radial:
            label += ' (r)'
        label += '$ = %.5e'% val

        plt.plot(pars, vals, label=label, lw=0.2, marker='+', ms=1)
        plt.ylabel('probed data')
        plt.xlabel('probe coordinate')

        output(label)

    plt.legend()

    fig.savefig(filename_results)
    fd.close()
Exemple #8
0
    def read(self, mesh, **kwargs):

        self.fd = fd = open(self.filename, "r")
        mode = "header"

        nod = conns = desc = None
        while 1:
            if mode == "header":
                line = skip_read_line(fd)

                n_tags = self._read_commented_int()
                for ii in xrange(n_tags):
                    skip_read_line(fd)
                n_types = self._read_commented_int()
                for ii in xrange(n_types):
                    skip_read_line(fd)

                skip_read_line(fd)
                assert_(skip_read_line(fd).split()[1] == "Mesh")
                skip_read_line(fd)
                dim = self._read_commented_int()
                assert_((dim == 2) or (dim == 3))
                n_nod = self._read_commented_int()
                i0 = self._read_commented_int()
                mode = "points"

            elif mode == "points":
                nod = read_array(fd, n_nod, dim, nm.float64)
                mode = "cells"

            elif mode == "cells":

                n_types = self._read_commented_int()
                conns = []
                descs = []
                mat_ids = []
                for it in xrange(n_types):
                    t_name = skip_read_line(fd).split()[1]
                    n_ep = self._read_commented_int()
                    n_el = self._read_commented_int()
                    if dim == 2:
                        aux = read_array(fd, n_el, n_ep, nm.int32)
                        if t_name == "tri":
                            conns.append(aux)
                            descs.append("2_3")
                            is_conn = True
                        else:
                            is_conn = False
                    else:
                        raise NotImplementedError

                    # Skip parameters.
                    n_pv = self._read_commented_int()
                    n_par = self._read_commented_int()
                    for ii in xrange(n_par):
                        skip_read_line(fd)

                    n_domain = self._read_commented_int()
                    assert_(n_domain == n_el)
                    if is_conn:
                        mat_id = read_array(fd, n_domain, 1, nm.int32)
                        mat_ids.append(mat_id)
                    else:
                        for ii in xrange(n_domain):
                            skip_read_line(fd)

                    # Skip up/down pairs.
                    n_ud = self._read_commented_int()
                    for ii in xrange(n_ud):
                        skip_read_line(fd)
                break

        nod = nm.concatenate((nod, nm.zeros((n_nod, 1), dtype=nm.int32)), 1)
        nod = nm.ascontiguousarray(nod)

        dim = nod.shape[1] - 1

        conns2 = []
        for ii, conn in enumerate(conns):
            conns2.append(nm.c_[conn, mat_ids[ii]])

        conns_in, mat_ids = sort_by_mat_id(conns2)
        conns, mat_ids, descs = split_by_mat_id(conns_in, mat_ids, descs)
        mesh._set_data(nod, conns, mat_ids, descs)

        #        mesh.write( 'pokus.mesh', io = 'auto' )

        self.fd = None
        return mesh
Exemple #9
0
    def read(self, mesh, **kwargs):
        fd = open(self.filename, "r")
        mode = "header"
        mode_status = 0
        nod = conns = desc = mat_id = None
        while 1:
            try:
                line = fd.readline()
                if len(line) == 0:
                    break
                elif len(line) == 1:
                    continue
                if line[0] == "#":
                    continue
            except EOFError:
                break
            except:
                output("reading " + fd.name + " failed!")
                raise

            if mode == "header":
                if mode_status == 0:
                    if line.strip() == "ASCII":
                        mode_status = 1
                elif mode_status == 1:
                    if line.strip() == "DATASET UNSTRUCTURED_GRID":
                        mode_status = 0
                        mode = "points"

            elif mode == "points":
                line = line.split()
                if line[0] == "POINTS":
                    n_nod = int(line[1])
                    nod = read_array(fd, n_nod, -1, nm.float64)
                    mode = "cells"

            elif mode == "cells":
                line = line.split()
                if line[0] == "CELLS":
                    n_el, n_val = map(int, line[1:3])
                    raw_conn = read_list(fd, n_val, int)
                    mode = "cell_types"

            elif mode == "cell_types":
                line = line.split()
                if line[0] == "CELL_TYPES":
                    assert_(int(line[1]) == n_el)
                    cell_types = read_array(fd, n_el, -1, nm.int32)
                    mode = "mat_id"

            elif mode == "mat_id":
                if mode_status == 0:
                    line = line.split()
                    if line[0] == "CELL_DATA":
                        assert_(int(line[1]) == n_el)
                        mode_status = 1
                elif mode_status == 1:
                    if line.strip() == "SCALARS mat_id float 1":
                        mode_status = 2
                elif mode_status == 2:
                    if line.strip() == "LOOKUP_TABLE default":
                        mat_id = read_list(fd, n_el, int)
                        mode_status = 0
                        mode = "finished"
            elif mode == "finished":
                break
        fd.close()

        if mat_id is None:
            mat_id = [[0]] * n_el

        dim = vtk_dims[cell_types[0, 0]]
        if dim == 3:
            nod = nm.concatenate((nod, nm.zeros((n_nod, 1), dtype=nm.int32)), 1)
        else:
            nod[:, 2] = 0.0
        nod = nm.ascontiguousarray(nod)

        dim = nod.shape[1] - 1
        cell_types = cell_types.squeeze()

        dconns = {}
        for iel, row in enumerate(raw_conn):
            ct = vtk_inverse_cell_types[(cell_types[iel], dim)]
            dconns.setdefault(ct, []).append(row[1:] + mat_id[iel])

        desc = []
        conns = []
        for key, conn in dconns.iteritems():
            desc.append(key)
            conns.append(nm.array(conn, dtype=nm.int32))

        conns_in, mat_ids = sort_by_mat_id(conns)
        conns, mat_ids, descs = split_by_mat_id(conns_in, mat_ids, desc)
        mesh._set_data(nod, conns, mat_ids, descs)

        return mesh
Exemple #10
0
    def read(self, mesh, **kwargs):
        dim, fd = self.read_dimension(ret_fd=True)

        conns_in = []
        descs = []
        while 1:
            try:
                line = fd.readline()
                if len(line) == 0:
                    break
                if len(line) == 1:
                    continue
            except EOFError:
                break
            except:
                output("reading " + fd.name + " failed!")
                raise
            ls = line.strip()
            if ls == "Vertices":
                num = int(read_token(fd))
                nod = read_array(fd, num, dim + 1, nm.float64)
            ##                 print nod
            elif ls == "Tetrahedra":
                num = int(read_token(fd))
                conns_in.append(read_array(fd, num, 5, nm.int32))
                conns_in[-1][:, :-1] -= 1
                descs.append("3_4")
            elif ls == "Hexahedra":
                num = int(read_token(fd))
                conns_in.append(read_array(fd, num, 9, nm.int32))
                conns_in[-1][:, :-1] -= 1
                descs.append("3_8")
            elif ls == "Triangles":
                num = int(read_token(fd))
                conns_in.append(read_array(fd, num, 4, nm.int32))
                conns_in[-1][:, :-1] -= 1
                descs.append("2_3")
            elif ls == "Quadrilaterals":
                num = int(read_token(fd))
                conns_in.append(read_array(fd, num, 5, nm.int32))
                conns_in[-1][:, :-1] -= 1
                descs.append("2_4")
            elif ls == "End":
                break
            elif line[0] == "#":
                continue
            else:
                msg = "corrupted file (line '%s')!" % line
                raise ValueError(msg)
        fd.close()

        conns_in, mat_ids = sort_by_mat_id(conns_in)

        # Detect wedges and pyramides -> separate groups.
        if "3_8" in descs:
            ic = descs.index("3_8")

            conn_in = conns_in.pop(ic)
            flag = nm.zeros((conn_in.shape[0],), nm.int32)
            for ii, el in enumerate(conn_in):
                if el[4] == el[5]:
                    if el[5] == el[6]:
                        flag[ii] = 2
                    else:
                        flag[ii] = 1

            conn = []
            desc = []

            ib = nm.where(flag == 0)[0]
            if len(ib) > 0:
                conn.append(conn_in[ib])
                desc.append("3_8")

            iw = nm.where(flag == 1)[0]
            if len(iw) > 0:
                ar = nm.array([0, 1, 2, 3, 4, 6, 8], nm.int32)
                conn.append(la.rect(conn_in, iw, ar))
                desc.append("3_6")

            ip = nm.where(flag == 2)[0]
            if len(ip) > 0:
                ar = nm.array([0, 1, 2, 3, 4, 8], nm.int32)
                conn.append(la.rect(conn_in, ip, ar))
                desc.append("3_5")

            ##             print "brick split:", ic, ":", ib, iw, ip, desc

            conns_in[ic:ic] = conn
            del (descs[ic])
            descs[ic:ic] = desc

        conns, mat_ids, descs = split_by_mat_id(conns_in, mat_ids, descs)
        mesh._set_data(nod, conns, mat_ids, descs)

        return mesh