コード例 #1
0
ファイル: elap.py プロジェクト: chbicibi/cfd_solver
def main():
    plt.figure()
    ymax = 100
    for file in ut.iglobm('*/nitr.csv'):
        if 'fix' in file or 'colab' in file:
            continue
        label = os.path.dirname(file)

        df = pd.read_csv(file)
        a = np.asarray(df, dtype=np.float64)

        num = 1000
        a[:, 1] = np.asarray(
            [a[max(i - num + 1, 0):i + 1, 1].mean() for i in range(len(a))])

        plt.plot(*a.T, lw=1, label=label)
        if a.shape[0] > 5000:
            ymax = max(ymax, a[5000:, 1].max() + 10)

    plt.xlim(0, 20000)
    # plt.ylim(0, ymax)
    plt.yscale('log')
    plt.xlabel('cycle')
    plt.ylabel('itr')
    # plt.show()
    png = 'nitr.png'
    plt.legend()
    plt.savefig(png, bbox_inches='tight', pad_inches=0.1, dpi=600)
コード例 #2
0
ファイル: compress.py プロジェクト: chbicibi/cfd_solver
def comp_main():
    def read(files):
        for file in files:
            name = re.search(r'out_\d+', file)[0]
            print(name, end=' \r')
            yield name, np.load(file)

    for d in ut.fsort(os.listdir('.')):
        loc = f'{d}/result'
        if not os.path.isdir(loc):
            continue

        try:
            with ut.chdir(loc):
                # if any(ut.iglobm('*.npz')):
                #     continue

                if any(ut.iglobm('*.npy')):
                    print(loc)

                for i in range(10):
                    out = f'out_{i:03d}.npz'
                    if os.path.isfile(out):
                        continue

                    l = i * 100
                    u = (i + 1) * 100 if i < 9 else 1001
                    files = [f'out_{j:04d}.plt.npy' for j in range(l, u)]

                    if not all(map(os.path.isfile, files)):
                        continue

                    print(f'{l}=>{u}', ' ' * 20, end='\r')
                    h = dict(read(files))

                    try:
                        np.savez_compressed(out, **h)

                    except:
                        if os.path.isfile(out):
                            os.remove(out)
                        raise

                    ck = np.load(out)
                    for nm in ck.files:
                        f = f'{nm}.plt.npy'
                        if os.path.isfile(f):
                            os.remove(f)

        except OSError:
            print('OSError')
            time.sleep(10)
            continue
コード例 #3
0
ファイル: elap.py プロジェクト: chbicibi/cfd_solver
def main1():
    odir = 'test'
    with ut.chdir(odir):
        times = sorted((os.path.getmtime(file), file)
                       for file in ut.iglobm('__raw__/*.plt')
                       if int(re.search(r'\d+', file)[0]) < 1000)
        a = np.array([t2[0] - t1[0] for t1, t2 in zip(times[:-1], times[1:])])
        list(map(print, (t[1] for t in times)))
        plt.plot(a)
        plt.xlim(0, len(a) - 1)
        # plt.ylim(0, 1000)
        plt.show()
コード例 #4
0
ファイル: image.py プロジェクト: chbicibi/cfd_solver
def plot(dest, force=False):
    flag = False
    with ut.chdir(dest):
        ut.mkdir(nm)
        # files = ut.iglobm('result/*.npy')
        files = ut.iglobm('result/*.dat')

        for file in files:
            basename = ut.basename(file, '.*')
            image = f'{nm}/{basename}.png'
            if os.path.isfile(image) and not force:
                continue
            print(dest, basename, end=' \r')

            # data = np.load(file)
            data = cm.read_raw(file)

            # print(data.shape)
            val = data[:, :, n]  # ((u, v, p, w), ...)
            if n == 2:
                # a = val[val.shape[0]//2, val.shape[1]//4]
                val -= val.mean()

            fig, ax = plt.subplots(figsize=(6, 4))
            fig.subplots_adjust(left=0.08, right=1, bottom=0, top=1)

            colors = [(0, '#ff0000'), (0.5, '#000000'), (1, '#00ff00')]
            cmap = plc.LinearSegmentedColormap.from_list('custom_cmap', colors)
            im = ax.imshow(val, cmap=cmap, vmin=-vr, vmax=vr)
            cax = fig.colorbar(im)

            ax_pos = ax.get_position()
            cax_pos0 = cax.ax.get_position()
            cax_pos1 = [
                cax_pos0.x0, ax_pos.y0, cax_pos0.x1 - cax_pos0.x0,
                ax_pos.y1 - ax_pos.y0
            ]
            cax.ax.set_position(cax_pos1)

            # plt.show()
            fig.savefig(image, bbox_inches='tight', pad_inches=0.1)
            plt.close('all')
            flag = True
    return flag
コード例 #5
0
ファイル: compress.py プロジェクト: chbicibi/cfd_solver
def zip_main():
    for loc in ut.fsort(ut.iglobm('**/image_*')):
        # loc = f'{d}/image_w'
        if not os.path.isdir(loc):
            continue

        with ut.chdir(loc):
            file = f'{ut.basename(loc)}.zip'
            if os.path.isfile(file):
                continue

            print(loc)
            # subprocess.run('zip image_w *.png', shell=True)

            try:

                def f_():
                    for png in ut.fsort(ut.iglobm('*.png')):
                        print(png, os.path.getsize(png), end='\r')
                        with open(png, 'rb'):
                            yield png

                pngs = list(f_())
                if not pngs:
                    continue

                with ZipFile(file, 'w', compression=ZIP_DEFLATED) as z:
                    for png in pngs:
                        z.write(png)
            except:
                if os.path.isfile(file):
                    os.remove(file)
                raise

            assert os.path.isfile(file)

            if os.path.isfile(file):
                with ZipFile(file) as z:
                    for png in z.namelist():
                        if os.path.isfile(png):
                            print(png)
                            os.remove(png)
コード例 #6
0
ファイル: compress.py プロジェクト: chbicibi/cfd_solver
 def f_():
     for png in ut.fsort(ut.iglobm('*.png')):
         print(png, os.path.getsize(png), end='\r')
         with open(png, 'rb'):
             yield png
コード例 #7
0
ファイル: main.py プロジェクト: chbicibi/cfd_solver
def main(opts=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('--cycle', '-n', type=int, default=None,
                        help='number of cycles')
    parser.add_argument('--out', '-o', type=str, default=None,
                        help='output directory name')
    parser.add_argument('--resume', '-r', type=str, default=None,
                        help='filename for resume calculation')
    args = parser.parse_args(args=opts)

    conf = read_inputfile('in2d.txt')
    if args.cycle:
        cycle = args.cycle
    else:
        cycle = conf.cycle
    if args.out:
        out = args.out
    else:
        out = conf.dest
    itr_max = conf.nitr
    save_interval = conf.save

    nx = np.array(conf.nx, dtype=np.int32)
    ny = np.array(conf.ny, dtype=np.int32)
    u = np.zeros((2, ny+2, nx+1), dtype=np.float64) # x方向速度
    v = np.zeros((2, ny+1, nx+2), dtype=np.float64) # y方向速度
    p = np.zeros((ny+2, nx+2), dtype=np.float64) # 圧力
    t = np.zeros((ny+2, nx+2), dtype=np.float64) # 温度
    f = np.ones((ny+2, nx+2), dtype=np.float64) # 流れ場情報(0=>物体上, 1=>流体)
    m = np.zeros((120,), dtype=np.uint8) # メッセージ格納用配列
    flg = np.array(0, dtype=np.int32) # 圧力計算収束確認用
    itr_hist = []
    save_count = 0

    register_functions()
    f_read_inputfile()
    f_initialize()

    with open('grid.csv') as fp:
        f[1:-1, 1:-1] = np.array(list(csv.reader(fp)), dtype=np.float64)

    if args.resume:
        u[0], v[0], p[:] = load_value(args.resume)

    for file in ut.iglobm('image/*.png'):
        os.remove(file)

    with ut.stopwatch('calc'):
        with ut.chdir(out):
            with tqdm(total=cycle, mininterval=1) as bar:
                for i in range(1, cycle+1):
                    f_calc_velociry(u[0], v[0], p, t, u[1], v[1], nx, ny)
                    f_bind_velocity(u[1], v[1], f, nx, ny)

                    for j in range(1, itr_max+1):
                        itr = np.array(j, dtype=np.int32)
                        m.fill(ord(' '))
                        f_calc_pressure(u[1], v[1], p, itr, flg, nx, ny, m)
                        f_bind_velocity(u[1], v[1], f, nx, ny)

                        if j % 100 == 0:
                            msg = ''.join(map(chr, m)).rstrip()
                            bar.write(f'cycle={i} {msg}')

                        if flg == 0:
                            if i % 100 == 0:
                                msg = ''.join(map(chr, m)).rstrip()
                                bar.write(f'cycle={i} {msg}')
                            break

                    itr_hist.append(j)
                    u[0] = u[1]
                    v[0] = v[1]

                    if i % save_interval == 0:
                        k = save_count
                        with ut.chdir('result'):
                            dump_data(f'out_{k:05d}.npy', u[0], v[0], p)

                        with ut.chdir('image'):
                            plot_w(vorticity(u[0], v[0]), f'out_{k:05d}.png')
                            plot_nitr(itr_hist, 'nitr.png')
                        save_count += 1

                    bar.update()