Esempio n. 1
0
def cylinder(path = './', solver=None, cs='cfr'):
    if len(cs) > 1:
        for cs0 in cs:
            cylinder(path, solver, cs0)
        return
    path = os.path.abspath(path)
    solver = solver or postprocess.determineSolver(path)
    if solver == 'TruchasEnSight': solver = 'Truchas'
    U=1.
    R=0.05
    if solver == 'Gerris':
        gfsFile=glob.glob(os.path.join(path, '*.gfs'))[0]
        for l in open(gfsFile).readlines():
            if 'SurfaceBc U' in l:
                U = -float(l.split()[-1])
            if 'SolidMoving' in l:
                for i, w in enumerate(l.split()):
                    if w == 'scale':
                        R = 0.25 * float(l.split()[i+2])
            if 'Define R' in l:
                R = float(l.split()[-1])
    elif solver == 'Truchas':
        inpFile=glob.glob(os.path.join(path, '*.inp'))[0]
        for l in open(inpFile).readlines():
            l = l.split()
            if len(l) ==3 and l[0] == 'R' and l[1] == '=':
                R = float(l[2])
    elif solver == 'OpenFOAM':
        inpFile=glob.glob(os.path.join(path, 'system/snappyHexMeshDict'))[0]
        for l in open(inpFile).readlines():
            l = (l.replace(';', '')).split()
            if len(l) == 2 and l[0] == 'radius':
                R = float(l[1])
    position = { 'c':0, 'f' : -2*R, 'r' : 2*R }
    y0 = { 'c':R, 'f' : 0, 'r' : 0 }
    cs_name={ 'c':'center', 'f' : 'front', 'r' : 'rear'}
    
    fig = plt.figure()
    fig.subplots_adjust(0.15, 0.15, 0.95, None)
    if 'static' in path.lower(): 
        state = 'static'
    else:
        state = 'moving'
    if 'slip' in path:
        BC = 'slip'
    else:
        BC = 'outflow'

    plt.title('Cylinder - velocity profiles (' + ', '.join([solver, state, BC, cs_name[cs]]) + ')')
    
    r = np.linspace(y0[cs], 0.5, 100)

    ls=['-.', '--', '-', '-', '-']
    for i, caseDir in enumerate(sorted(glob.glob(os.path.join(path, '*[1-9]')))[:5]):
        vtks = postprocess.globFiles(caseDir, ext='.vtk', exit=0)
        if vtks:
            print 'Profiles:', caseDir, '*.vtk'
            line, u = sample_vtk(vtks[-1], [position[cs], y0[cs]], [position[cs], 0.5])
            if 'moving' in path:
                u = u+U     #we want relative speed
            plt.plot(u[:, 0], line[:, 2], label='Resolution '+caseDir[-1], ls=ls[i])
    
        files = glob.glob(os.path.join(caseDir, '*.ensight.CASE'))
        if files:
            file = files[0]
            print 'Profiles:', file
            ts = enSightTimeSteps(file)
            if len(glob.glob(os.path.join(caseDir, '*.ensight/P.*'))) == ts:  #check if computations are finished
                line, u = sample_ensight(file, [position[cs], y0[cs]], [position[cs], 0.5])
                if 'moving' in path:
                    u = u+U     #we want relative speed
                plt.plot(u[:, 0], line[:, 2], label='Resolution '+caseDir[-1], ls=ls[i])

    Vx, Vy = cylinderReference(position[cs], r, R)
    #plt.plot(U*(1+R**2/r**2), r, label='Reference', lw=2)
    plt.plot(Vx, r, label='Reference', c='k', lw=2.0)
    
    legend = { 'c':'upper right', 'f' : 'upper left', 'r' : 'upper left' }
    plt.legend(loc=legend[cs])
    #plt.ylim([0, line[:, 2].max()])
    #plt.ylim([0, 0.15])
    if cs == 'c':plt.xlim([1, 2])
    
    plt.ylabel('z $[m]$')
    plt.xlabel('Velocity $u_x$ $[\\frac{m}{s}]$')
    
    #name = os.path.split(path)[1]  #ex. cylinder-static, cylinder-moving
    plt.savefig('-'.join(['cylinder', solver, 'profiles', state, BC, cs]))
    plt.savefig('-'.join(['cylinder', solver, 'profiles', state, BC, cs])+'.pdf')
Esempio n. 2
0
def plotCrossSections(path,
                      time=None,
                      a=None,
                      solver=None,
                      x_c=25,
                      bw=0,
                      suffix='',
                      difference=False):
    """
    Plots the velocity profiles along vertical crossections of a solitary wave, for a single time step.
    In previous versions multiple timesteps were supported, but is not any more.

    :param difference: Take a difference between the reference solution and numerical results
    :type difference: bool
    """

    solver = solver or postprocess.determineSolver(path)
    a = a or postprocess.determineAmplitude(path)

    path = os.path.abspath(path)
    dirs = glob.glob(path + '/case[1-4]/*postprocessed.dat') + glob.glob(
        path + '/*-[1-4]/*postprocessed.dat')
    dirs = [os.path.split(dir)[0] for dir in dirs]
    dirs.sort()
    if not (dirs):
        print 'Empty directory:', path
        return 1
    else:
        print dirs

    #correct time:
    dt = postprocess.findDt(path)
    time_step = int(round(time / dt))
    time = time_step * dt

    ref_line, u_ref = get_reference(a, time, x_c)
    y_ref = ref_line[:, 1]
    ux_ref = u_ref[:, 0]

    ux_num_list, sample_line_z_list = [], []

    for path in dirs:
        vtk_file = postprocess.globFiles(path, ext='.vtk',
                                         verbose=False)[time_step]
        if difference:
            p1 = [x_c, np.min(y_ref)]
            p2 = [x_c, np.max(y_ref)]
            line, vel = sample_vtk(vtk_file, p1=p1, p2=p2, N_points=len(y_ref))
            vel[:, 0] = vel[:, 0] - ux_ref
        else:
            line, vel = sample_vtk(vtk_file, x_c=x_c)
        ux_num_list.append(vel[:, 0])  #x component
        sample_line_z_list.append(line[:, 2])  #vertical component

    print "Plotting..."

    gravity = 'sourceGrav' if 'sourceGrav' in path else ''
    results = ['VelCross', "A0{0:g}".format(a * 10), solver, gravity, suffix]
    results = [p for p in results if p]  #remove empty strings
    results = '_'.join(results)

    xlim = {0.1: [-0.03, 0.45], 0.3: [-0.3, 1.3]}
    plt.clf()
    fig = plt.figure()
    fig.subplots_adjust(0.15, 0.15, 0.95, None)
    #plt.title('Propagation of a {2:.1f} soliton, t={0:.2f} s, $\Delta x$={1:.2f}m, {3}'.format(t, x_c-15, a, solver))

    ls = ['-.', '--', '-']
    for j in range(len(ux_num_list)):
        case = dirs[j][-1:]
        u = ux_num_list[j]
        sample_line_z = sample_line_z_list[j]
        if bw:
            plt.plot(u,
                     sample_line_z,
                     label='Resolution ' + case,
                     ls=ls[j],
                     color='k')
        else:
            plt.plot(u, sample_line_z, label='Resolution ' + case, ls=ls[j])
Esempio n. 3
0
def plotCrossSections(path, time=None, a=None, solver=None, x_c=25, bw=0, suffix='', difference=False):
    """
    Plots the velocity profiles along vertical crossections of a solitary wave, for a single time step.
    In previous versions multiple timesteps were supported, but is not any more.

    :param difference: Take a difference between the reference solution and numerical results
    :type difference: bool
    """

    solver = solver or postprocess.determineSolver(path)
    a = a or postprocess.determineAmplitude(path)
    
    path=os.path.abspath(path)
    dirs = glob.glob(path + '/case[1-4]/*postprocessed.dat') + glob.glob(path + '/*-[1-4]/*postprocessed.dat')
    dirs = [os.path.split(dir)[0] for dir in dirs]
    dirs.sort()
    if not (dirs): 
        print 'Empty directory:', path
        return 1
    else: 
        print dirs
    
    #correct time:
    dt = postprocess.findDt(path)
    time_step = int(round(time/dt))
    time = time_step*dt

    ref_line, u_ref = get_reference(a, time, x_c)
    y_ref = ref_line[:, 1]
    ux_ref = u_ref[:, 0]

    ux_num_list, sample_line_z_list = [], []
    
    for path in dirs:
        vtk_file = postprocess.globFiles(path, ext='.vtk', verbose=False)[time_step]
        if difference:
            p1 = [x_c, np.min(y_ref)]
            p2 = [x_c, np.max(y_ref)]
            line, vel = sample_vtk(vtk_file, p1=p1, p2=p2, N_points=len(y_ref))
            vel[:, 0] = vel[:, 0] - ux_ref
        else:
            line, vel = sample_vtk(vtk_file, x_c=x_c)
        ux_num_list.append(vel[:, 0])  #x component
        sample_line_z_list.append(line[:, 2]) #vertical component
    
    print "Plotting..."
    
    gravity = 'sourceGrav' if 'sourceGrav' in path else ''
    results = ['VelCross', "A0{0:g}".format(a*10), solver, gravity, suffix]
    results = [p for p in results if p]  #remove empty strings
    results = '_'.join(results)
    
    xlim = {0.1: [-0.03, 0.45], 0.3: [-0.3, 1.3]}
    plt.clf()
    fig = plt.figure()
    fig.subplots_adjust(0.15, 0.15, 0.95, None)
    #plt.title('Propagation of a {2:.1f} soliton, t={0:.2f} s, $\Delta x$={1:.2f}m, {3}'.format(t, x_c-15, a, solver))
    
    ls = ['-.', '--', '-']
    for j in range(len(ux_num_list)):
        case = dirs[j][-1:]
        u = ux_num_list[j]
        sample_line_z = sample_line_z_list[j]
        if bw:
            plt.plot(u, sample_line_z, label='Resolution ' + case, ls=ls[j], color='k')
        else:
            plt.plot(u, sample_line_z, label='Resolution ' + case, ls=ls[j])
    if not difference:
        plt.plot(ux_ref, y_ref, label='Reference', color='k', ls='-', lw=2)
    plt.legend(loc='best')
    
    plt.ylabel('z $[m]$')
    plt.xlabel('Velocity $[\\frac{m}{s}]$')
    plt.ylim(-1, np.max(sample_line_z))
    plt.xlim(xlim[a])
    if bw:
        results = results+'_bw'
    plt.savefig(results+'.png'.format(time))
    plt.savefig(results+'.pdf'.format(time))
Esempio n. 4
0
def cylinder(path='./', solver=None, cs='cfr'):
    if len(cs) > 1:
        for cs0 in cs:
            cylinder(path, solver, cs0)
        return
    path = os.path.abspath(path)
    solver = solver or postprocess.determineSolver(path)
    if solver == 'TruchasEnSight': solver = 'Truchas'
    U = 1.
    R = 0.05
    if solver == 'Gerris':
        gfsFile = glob.glob(os.path.join(path, '*.gfs'))[0]
        for l in open(gfsFile).readlines():
            if 'SurfaceBc U' in l:
                U = -float(l.split()[-1])
            if 'SolidMoving' in l:
                for i, w in enumerate(l.split()):
                    if w == 'scale':
                        R = 0.25 * float(l.split()[i + 2])
            if 'Define R' in l:
                R = float(l.split()[-1])
    elif solver == 'Truchas':
        inpFile = glob.glob(os.path.join(path, '*.inp'))[0]
        for l in open(inpFile).readlines():
            l = l.split()
            if len(l) == 3 and l[0] == 'R' and l[1] == '=':
                R = float(l[2])
    elif solver == 'OpenFOAM':
        inpFile = glob.glob(os.path.join(path, 'system/snappyHexMeshDict'))[0]
        for l in open(inpFile).readlines():
            l = (l.replace(';', '')).split()
            if len(l) == 2 and l[0] == 'radius':
                R = float(l[1])
    position = {'c': 0, 'f': -2 * R, 'r': 2 * R}
    y0 = {'c': R, 'f': 0, 'r': 0}
    cs_name = {'c': 'center', 'f': 'front', 'r': 'rear'}

    fig = plt.figure()
    fig.subplots_adjust(0.15, 0.15, 0.95, None)
    if 'static' in path.lower():
        state = 'static'
    else:
        state = 'moving'
    if 'slip' in path:
        BC = 'slip'
    else:
        BC = 'outflow'

    plt.title('Cylinder - velocity profiles (' +
              ', '.join([solver, state, BC, cs_name[cs]]) + ')')

    r = np.linspace(y0[cs], 0.5, 100)

    ls = ['-.', '--', '-', '-', '-']
    for i, caseDir in enumerate(
            sorted(glob.glob(os.path.join(path, '*[1-9]')))[:5]):
        vtks = postprocess.globFiles(caseDir, ext='.vtk', exit=0)
        if vtks:
            print 'Profiles:', caseDir, '*.vtk'
            line, u = sample_vtk(vtks[-1], [position[cs], y0[cs]],
                                 [position[cs], 0.5])
            if 'moving' in path:
                u = u + U  #we want relative speed
            plt.plot(u[:, 0],
                     line[:, 2],
                     label='Resolution ' + caseDir[-1],
                     ls=ls[i])

        files = glob.glob(os.path.join(caseDir, '*.ensight.CASE'))
        if files:
            file = files[0]
            print 'Profiles:', file
            ts = enSightTimeSteps(file)
            if len(glob.glob(os.path.join(caseDir, '*.ensight/P.*'))
                   ) == ts:  #check if computations are finished
                line, u = sample_ensight(file, [position[cs], y0[cs]],
                                         [position[cs], 0.5])
                if 'moving' in path:
                    u = u + U  #we want relative speed
                plt.plot(u[:, 0],
                         line[:, 2],
                         label='Resolution ' + caseDir[-1],
                         ls=ls[i])

    Vx, Vy = cylinderReference(position[cs], r, R)
    #plt.plot(U*(1+R**2/r**2), r, label='Reference', lw=2)
    plt.plot(Vx, r, label='Reference', c='k', lw=2.0)

    legend = {'c': 'upper right', 'f': 'upper left', 'r': 'upper left'}
    plt.legend(loc=legend[cs])
    #plt.ylim([0, line[:, 2].max()])
    #plt.ylim([0, 0.15])
    if cs == 'c': plt.xlim([1, 2])

    plt.ylabel('z $[m]$')
    plt.xlabel('Velocity $u_x$ $[\\frac{m}{s}]$')

    #name = os.path.split(path)[1]  #ex. cylinder-static, cylinder-moving
    plt.savefig('-'.join(['cylinder', solver, 'profiles', state, BC, cs]))
    plt.savefig('-'.join(['cylinder', solver, 'profiles', state, BC, cs]) +
                '.pdf')