def get_jhtd_parameters(filename):
    keys = ['t0', 'tl', 'x0', 'xl', 'y0', 'yl', 'z0', 'zl', 'tstep', 'xstep', 'ystep', 'zstep']
    print filename
    param = {}
    for key in keys:
        try:
            param[key] = int(fs.get_float_from_str(filename, key + '_', '_'))
        except RuntimeError:
            print '... RuntimeError raised. Try something else...'
            param[key] = int(fs.get_float_from_str(filename, key + '_', '.h5'))
            print '... Worked. '
    return param
Example #2
0
def extract_frame_rate(fn):
    import library.basics.formatstring as fs
    """Pick out the frame rate from the file name

    Parameters
    ----------
    fn : str
        file name with '_175fps' or '_175pps' in it for 175 Hz framerate

    Returns
    -------
    frame_rate : float
        The frame rate as discerned by the file name
    """
    print 'fn = ', fn
    if 'fps' in fn:
        #frame_rate = float(fn.split('fps')[0].split('_D')[-1])
        frame_rate = fs.get_float_from_str(fn, 'fps', '_D')
    elif 'pps' in fn:
        frame_rate = float(fn.split('pps')[0].split('_D')[-1])
    else:
        raise RuntimeError('No frame rate in the filename. Cine framerate discernment is unreliable. Exiting.')

    return frame_rate
        # Load hdf5 data generated by piston_tracking.py
        data_tracking_dir, ext = os.path.splitext(csv_file)
        data_tracking_dir_head, data_tracking_dir_tail = os.path.split(data_tracking_dir)
        print data_tracking_basedir
        print data_tracking_dir
        print data_tracking_dir_tail
        #time_hdf5, x_pos_hdf5, y_pos_hdf5 = get_position_from_step_hdf5(data_tracking_dir)
        time_hdf5, x_pos_hdf5, y_pos_hdf5 = get_position_from_step_hdf5(data_tracking_dir)


        x_pos_hdf5[:] = (x_pos_hdf5[:] - np.min(x_pos_hdf5)) * args.fx
        y_pos_hdf5[:] = (y_pos_hdf5[:] - np.min(y_pos_hdf5)) * args.fx

        # Get experimental parameters from file name
        frame_rate = fs.get_float_from_str(data_tracking_dir_tail, '_', 'fps')
        span = fs.get_float_from_str(data_tracking_dir_tail, 'span', 'mm')
        vp_commanded = fs.get_float_from_str(data_tracking_dir_tail, '_v', 'mms')
        freq = fs.get_float_from_str(data_tracking_dir_tail, 'mms_f', 'Hz')
        # # Compute velocity from position
        # u_hdf5 = np.gradient(x_pos_hdf5) * frame_rate
        # v_hdf5 = np.gradient(y_pos_hdf5) * frame_rate

        # Delete some elements from arrays if commanded on terminal
        if not args.end==0:
            x_pos_hdf5 = x_pos_hdf5[args.start:-args.end]
            # y_pos_hdf5 = y_pos_hdf5[args.start:-args.end]
            # u_hdf5 = u_hdf5[args.start:-args.end]
            # v_hdf5 = v_hdf5[args.start:-args.end]
            #print 'Number of frames in cine: %d' % len(time_hdf5)
            time_hdf5 = time_hdf5[args.start:-args.end]
Example #4
0
        cxlist, cylist = [], []
        time = []

        # LOAD CINE FILE AND GRUB IMAGE SIZE
        movie = cine.open(cine_file)
        imsize = np.shape(movie[0])

        # GENERATE FILE ARCHITECTURE
        date_dir, cine_name = os.path.split(cine_file)
        name, ext = os.path.splitext(cine_name)
        # cine_dir = os.path.join(date_dir, name)
        resultsdir = date_dir + '/PIV_AnalysisResults/' + name  #ABS PATH TO OUTPUT DIRECTORY

        # Get stroke length from name of cine file
        try:
            span = fs.get_float_from_str(name, 'piston', 'mm_freq')
        except ValueError:
            span = float(browse.replace_letter_in_string(span, 'p', '.'))

        print 'Working on Cine file: ', name

        # # CREATE A DIRECTORY TO STORE RESULTS
        # if not os.path.exists(resultsdir):
        #     os.makedirs(resultsdir)

        # CREATE A DIRECTORY TO STORE RESULTS OF CIRCULATION COMPUTATION
        circulation_dir = resultsdir + '/circulation/'
        if not os.path.exists(circulation_dir):
            os.makedirs(circulation_dir)

        # GRAB A DIRECTORY NAME WHERE PIVLAB-GENERATED txt FILES ARE STORED
    '/Volumes/labshared3-1/takumi/JHTD-sample/JHT_Database/Data/synthetic_data_from_bob/double_oseen_PIV_gamma17000_NP50000_r40_D150_cx640_cy400_fps500_w1280_h800_psize3_dx200'
)

args = parser.parse_args()

if args.use_strinput:
    # File architecture
    filedir = args.paramstr
    try:
        dirname = os.path.split(filedir)[1]
        savedir = os.path.join(filedir, 'vel_field/')
    except:
        savedir = './vel_field/'

    # Parameter extraction
    gamma = fs.get_float_from_str(dirname, 'gamma', '_NP')  # mm^2/s
    rr = fs.get_float_from_str(dirname, '_r',
                               '_D') / 10.  # core radius of vortex # mm
    dd = fs.get_float_from_str(dirname, '_D',
                               '_cx')  # spacing between two vortices # mm
    npts = fs.get_float_from_str(dirname, 'NP', '_r')
    cx = fs.get_float_from_str(dirname, 'cx', '_cy')  # px
    cy = fs.get_float_from_str(dirname, 'cy', '_fps')  # px
    fps = fs.get_float_from_str(dirname, 'fps', '_w12')  # frame per sec
    width = fs.get_float_from_str(dirname, '_w', '_h')  # px
    height = fs.get_float_from_str(dirname, '_h', '_psize')  # px
    dx = fs.get_float_from_str(dirname, 'dx', '') / 1000.  # mm/px

# Convert mm,s -> px, frame
gamma_px2frame = gamma / dx / dx / fps
dd_px = dd / dx
params = {'figure.figsize': (20, 10)
          }
disp_min, disp_max = -0.01, 0.01
graph.update_figure_params(params)

if not os.path.exists(datafilepath) or args.overwrite:
    # Initialize
    disps, iws = [], []
    sigmas_ux, gammas_ux, gauss_peaks_ux, lorentz_peaks_ux = [], [], [], []
    sigmas_ux_err, gammas_ux_err, gauss_peaks_ux_err, lorentz_peaks_ux_err = [], [], [], []
    sigmas_uy, gammas_uy, gauss_peaks_uy, lorentz_peaks_uy = [], [], [], []
    sigmas_uy_err, gammas_uy_err, gauss_peaks_uy_err, lorentz_peaks_uy_err = [], [], [], []

    for parentdir in parentdirs:
        print parentdir
        iw = int(fs.get_float_from_str(parentdir, 'W', 'px')) # interrogation window width
        pivdata_loc = glob.glob(parentdir + '/PIVlab*')
        resultdir = os.path.join(parentdir, resultdirname)

        for pivdatum_loc in pivdata_loc:
            # Extract desired displacement
            if args.mode == 'constant':
                mag = fs.get_float_from_str(pivdatum_loc, 'mag', '.h5')  # velocity magnitude
                mag_str = fs.convert_float_to_decimalstr(mag)
                mag_str_2 = fs.convert_float_to_decimalstr(mag, zpad=4) # for naming scheme


                # Plotting settings Part 2
                vmin, vmax = mag * 0, mag * 1.2

                # Load pivlab output
Example #7
0
args = parser.parse_args()

# Data architecture
parentdirs = glob.glob(args.datadir + '*')
fakedata = glob.glob(args.fakedatadir + 'unidirectional*')
resultdirname = 'comparison_pivlab_org'  # name of directory where figures will be stored

# Plotting settings Part 1
cmap = 'RdBu'
cmap2 = 'Blues'
params = {'figure.figsize': (24, 10)}
graph.update_figure_params(params)

for parentdir in parentdirs:
    print parentdir
    iw = int(fs.get_float_from_str(parentdir, 'W',
                                   'px'))  # interrogation width
    pivdata_loc = glob.glob(parentdir + '/PIVlab*')
    resultdir = os.path.join(parentdir, resultdirname)

    for pivdatum_loc in pivdata_loc:
        # Extract desired displacement
        if args.mode == 'constant':
            mag = fs.get_float_from_str(pivdatum_loc, 'mag',
                                        '.h5')  # velocity magnitude
            mag_str = fs.convert_float_to_decimalstr(mag)
            mag_str_2 = fs.convert_float_to_decimalstr(
                mag, zpad=4)  # for naming scheme

            # Plotting settings Part 2
            vmin, vmax = mag * 0, mag * 1.2
Example #8
0
def fit_func_for_vring_vs_veff(x, a, b):
    return a * x * (np.log(x) + b)


vr_all, gammar_all, veff_all = [], [], []

for i, data_PIV_basedir in enumerate(data_PIV_basedir_list):
    veff_dict, gammar_dict, gammar_err_dict, actual_span_dict, actual_span_ratio_dict = {}, {}, {}, {}, {}
    vr_dict, vr_err_dict = {}, {}
    print '!!!!!!!!!!!!'
    print data_PIV_basedir
    data_PIV_dir_list = glob.glob(data_PIV_basedir + '*')
    for data_PIV_dir in data_PIV_dir_list:
        # Get stroke length, commanded velocity, and freq from filename
        fn_head, fn_tail = os.path.split(data_PIV_dir)
        span = fs.get_float_from_str(fn_tail, 'piston', 'mm_freq')
        vc = fs.get_float_from_str(fn_tail, 'Hz_v', 'mms')
        freq = fs.get_float_from_str(fn_tail, 'freq', 'Hz')
        # get some strings from filename
        span_str = fs.get_str_from_str(fn_tail, 'piston', 'mm_freq')
        vc_str = fs.get_str_from_str(fn_tail, 'Hz_v', 'mms')
        freq_str = fs.get_str_from_str(fn_tail, 'freq', 'Hz')
        # try:
        #     trial_no_str = fs.get_str_from_str(fn_tail, 'trial', '')
        #     print fn_tail
        # except NameError:
        #     trial_no_str = fn_tail[-1]
        #     print fn_tail
        date_str = fs.get_str_from_str(data_PIV_dir, base_dir, '/singlering')
        date_str = date_str.replace('_', '')
        trial_no_str = fn_tail[-1]
                rows, cols, duration = data['ux'].shape  # (y, x, t)

            # initialize arrays to store experimental data
            newshape1 = (cols, rows, setup['nslice'] * ndata
                         )  # used for coordinate data organizing
            newshape2 = (cols, rows, setup['nslice'] * ndata, duration
                         )  # used for coordinate data organizing
            xdata, ydata, zdata = np.empty(newshape1), np.empty(
                newshape1), np.empty(newshape1)
            uxdata, uydata, uzdata = np.empty(newshape2), np.empty(
                newshape2), np.empty(newshape2)
            coord_data, vel_data = [xdata, ydata,
                                    zdata], [uxdata, uydata, uzdata]

        for i, h5file in enumerate(sorted(h5files)):
            sliceno = int(fs.get_float_from_str(h5file, 'slice', '.h5'))
            print sliceno, setup['nslice'] - sliceno - 1
            sliceno = setup['nslice'] - sliceno - 1
            print 'Check: Slice No must be ordered! 0-%d: %02d' % (
                setup['nslice'], sliceno)
            data = h5py.File(h5file, 'r')
            x_raw, y_raw = np.asarray(data['x']), np.asarray(data['y'])
            ux_raw, uy_raw = np.asarray(data['ux']), np.asarray(data['uy'])

            # position correction
            # uz is just a projection of ux_raw here
            x, y, z = transform_coord(x_raw, y_raw, z0 / scale, sliceno,
                                      setup)  # 2d arrays
            ux, uy, uz = transform_vel(
                ux_raw, uy_raw, 0,
                dtheta * (sliceno - (setup['nslice'] - 1) / 2.))  # 2d arrays
Example #10
0
            y_pos_enc[00:100])
        time_enc = time_enc - np.min(time_enc) + 0.267
        y_pos_enc = y_pos_enc - np.min(y_pos_enc)

        time_v_enc, vel_enc = process.compute_velocity_simple(
            time_enc, y_pos_enc)
        time_v_enc = time_v_enc - 0.002
        print len(y_pos_enc)
        # plt.plot(time_enc, y_pos_enc)
        # plt.show()

        x_pos_hdf5[:] = (x_pos_hdf5[:] - np.min(x_pos_hdf5)) * args.fx
        y_pos_hdf5[:] = (y_pos_hdf5[:] - np.min(y_pos_hdf5)) * args.fx

        # Get experimental parameters from file name
        frame_rate = fs.get_float_from_str(data_tracking_dir_tail, 'fps', '_D')
        span = fs.get_float_from_str(data_tracking_dir_tail, 'piston', 'mm_v')
        vp_commanded = fs.get_float_from_str(data_tracking_dir_tail, '_v',
                                             'mms')
        freq = fs.get_float_from_str(data_tracking_dir_tail, 'freq', 'Hz')

        # # Compute velocity from position (hdf5)
        u_hdf5 = np.gradient(x_pos_hdf5) * frame_rate
        v_hdf5 = np.gradient(y_pos_hdf5) * frame_rate

        # Delete some elements from arrays if commanded on terminal
        if not args.end == 0:
            x_pos_hdf5 = x_pos_hdf5[args.start:-args.end]
            y_pos_hdf5 = y_pos_hdf5[args.start:-args.end]
            u_hdf5 = u_hdf5[args.start:-args.end]
            v_hdf5 = v_hdf5[args.start:-args.end]
Example #11
0
        # load data from the hdf5 file
        time, x_pos, y_pos = get_position_from_step_hdf5(fn_noext)
        xm_pos, ym_pos = np.mean(x_pos), np.mean(y_pos)

        # Convert px->mm
        x_pos[:] = (x_pos[:] - np.min(x_pos)) * args.fx
        y_pos[:] = (y_pos[:] - np.min(y_pos)) * args.fx
        xm_pos, ym_pos = xm_pos * args.fx, ym_pos * args.fx

        #frame_rate = fs.get_float_from_str(fn_noext, '20180220_', 'fps')
        #frame_rate = ht.extract_frame_rate(fns[i])
        try:
            frame_rate = ht.extract_frame_rate(fns[i])
        except ValueError:
            frame_rate = fs.get_float_from_str(fn_noext_tail, 'frate', 'fps')
        span = fs.get_float_from_str(fn_noext_tail, 'span', 'mm')
        vp_commanded = fs.get_float_from_str(fn_noext_tail, '_v', 'mms')
        freq = fs.get_float_from_str(fn_noext_tail, 'mms_f', 'Hz')
        #freq = args.freq

        # Compute velocity from position
        u = np.gradient(x_pos) * frame_rate
        v = np.gradient(y_pos) * frame_rate

        # Piston tracking plot: x, y, u, v vs time
        title = os.path.split(fn_noext)[1]
        fig3, ax1 = graph.plot(time,
                               x_pos,
                               fignum=3,
                               subplot=221,
Example #12
0
        time = []
        d12_list, d13_list, d24_list, d34_list = [], [], [], []

        # LOAD CINE FILE AND GRUB IMAGE SIZE
        movie = cine.open(cine_file)
        imsize = np.shape(movie[0])

        # GENERATE FILE ARCHITECTURE
        date_dir, cine_name = os.path.split(cine_file)
        name, ext = os.path.splitext(cine_name)
        # cine_dir = os.path.join(date_dir, name)
        resultsdir = date_dir + '/PIV_AnalysisResults/' + name  #ABS PATH TO OUTPUT DIRECTORY

        # Get stroke length from name of cine file
        try:
            span = fs.get_float_from_str(name, 'piston', 'mm_freq')
            vp_c = fs.get_float_from_str(name, 'Hz_v', 'mms')
        except ValueError:
            span = float(browse.replace_letter_in_string(span, 'p', '.'))
            vp_c = fs.get_float_from_str(name, 'Hz_v', 'mms')

        print '-----------------------------------------------------------'
        print 'Working on Cine file: ', name

        # # CREATE A DIRECTORY TO STORE RESULTS
        # if not os.path.exists(resultsdir):
        #     os.makedirs(resultsdir)

        # CREATE A DIRECTORY TO STORE RESULTS OF CIRCULATION COMPUTATION
        circulation_dir = resultsdir + '/circulation/'
        if not os.path.exists(circulation_dir):
    keys = [
        u'bins_ux_diff_avg', u'bins_ux_diff_c', u'bins_uy_diff_avg',
        u'bins_uy_diff_c', u'hist_ux_diff_avg', u'hist_ux_diff_c',
        u'hist_uy_diff_avg', u'hist_uy_diff_c'
    ]
    titles = [r'$W=8$px', '$W=16$px', '$W=32$px', '$W=64$px']
    suptitles = [
        r'$\Delta U_x$', r'$\Delta U_{x,center}$', r'$\Delta U_y$',
        r'$\Delta U_{y,center}$'
    ]
    iws = [8, 16, 32, 64]
    subplots = [221, 222, 223, 224]
    subplot_tpl = zip(iws, subplots)

    deltat = fs.get_float_from_str(
        histdata_path, 'Dt_', '_'
    )  # number of DNS steps between image A and image B = deltat * 10 for isotropic1024coarse
    iw = fs.get_float_from_str(histdata_path, 'W',
                               'pix')  # interrogation window size in px
    lt = fs.get_float_from_str(histdata_path, 'lt',
                               '_')  # laser thickness in px

    # Plotting settings 2
    subplot = search_tuple(
        subplot_tpl,
        iw)[0][1]  # 3 digit subplot index obtained from subplot_tpl
    # label = '$\Delta t$=%d DNS steps = %.3f (a.u)' % (deltat * dt_spacing, deltat * dt_spacing * dt_sim)
    label = '$\Delta t = %.3f $ (a.u)' % (deltat * dt_spacing * dt_sim)

    vmax = 1024 / 2 * dt_sim * (deltat * dt_spacing)  # px/frame
    # vmax = iw * 8 / 2
# Processing starts now...


# Load jhtd data
# jhtd_data[vel_key] has a structure (z, y, x, ui)... vel_key is time
jhtd_data = h5py.File(args.jhtddatapath, mode='r')
vel_keys = [jhtd_key for jhtd_key in jhtd_data.keys() if jhtd_key.startswith('u')]

for i, pivlab_output in enumerate(pivlab_outputs):
    print pivlab_output
    # File architecture 2
    resultsubdirname = fs.get_filename_wo_ext(pivlab_output)
    resultdir = os.path.join(parentdir + '/tstep%d' % param['tstep'], 'comp_jhtd_pivlab/' + resultsubdirname)


    iw = int(fs.get_float_from_str(pivlab_output, 'W', 'pix'))  # size of final interrogation window in multi-pass
    lt = fs.get_float_from_str(pivlab_output, 'lt', '_')  # laser thickness in px
    npt = int(fs.get_float_from_str(pivlab_output, 'npt', '_'))  # number of particles used to generate fake piv images
    fwhm = lt / np.sqrt(2) # fwhm of a gaussian beam

    # field averaged over illuminated plane thickness
    print 'Center of illuminated plane %d, FWHM of a Gaussian beam: %.2f' % (zpos, fwhm)
    z_start, z_end = max(int(zpos - fwhm/2), 0), min(int(zpos + fwhm/2), zdim-1)
    print 'z of illuminatied volume: [%d, %d] (px)' % (z_start, z_end)


    # graph.color_plot(xx, yy, ux_mean, fignum=1)
    # graph.color_plot(xx, yy, ux_center, fignum=2)

    # Load pivlab-processed data
    # piv_data has a structure (x, y, t)