Exemplo n.º 1
0
def get_grid_pixel_from_piv_file(path, index_pass=-1):
    """Recompute 1d arrays containing the approximate positions of the vectors

    Useful to compute a grid on which we can interpolate the displacement fields.

    Parameters
    ----------

    path: str

      Path of a PIV file.

    index_pass: int

      Index of the pass

    Returns
    -------

    xs1d: np.ndarray

      Indices (2nd, direction "x") of the pixel in the image

    ys1d: np.ndarray

      Indices (1st, direction "y") of the pixel in the image

    """
    with h5py.File(path) as f:
        params = ParamContainer(hdf5_object=f["params"])
        shape_images = f["couple/shape_images"].value

    return get_grid_pixel(params, shape_images, index_pass)
Exemplo n.º 2
0
def get_points(points_file):
    """Get grid points extracted from calibration images
    """
    imgpts = ParamContainer(path_file=points_file)
    tidy_container(imgpts)
    imgpts = imgpts.geometry_calib.source_calib.__dict__
    points = [x for x in imgpts.keys() if "point_" in x or "Point" in x]
    points.sort()

    # [X, Y, Z, x, y]
    results = [[], [], [], [], []]
    # X, Y and Z are coordinate in real space (physical unit)
    # x and y are the indices of the pixel in the image
    for point in points:
        numbers = get_number_from_string2(imgpts[point])

        for i, result in enumerate(results):
            result.append(numbers[i])

    results = [np.array(result) for result in results]

    # particularity for Z
    results[2] = results[2][0]

    # particularity for X, Y, Z
    for i in range(3):
        results[i] /= 100.0

    return results
Exemplo n.º 3
0
    def open_file(self):
        path_file = QtWidgets.QFileDialog.getOpenFileName(
            self.centralwidget, "OpenFile")

        params = ParamContainer(path_file=path_file)
        print(params)
        raise NotImplementedError
Exemplo n.º 4
0
def create_oper(type_fft=None, coef_dealiasing=2.0 / 3):

    params = ParamContainer(tag="params")

    params._set_attrib("ONLY_COARSE_OPER", False)
    params._set_attrib("f", 0)
    params._set_attrib("c2", 100)
    params._set_attrib("kd2", 0)

    OperatorsPseudoSpectralSW1L._complete_params_with_default(params)

    if mpi.nb_proc == 1:
        nh = 9
    else:
        nh = 8

    params.oper.nx = nh
    params.oper.ny = nh
    Lh = 6.0
    params.oper.Lx = Lh
    params.oper.Ly = Lh

    if type_fft is not None:
        params.oper.type_fft = type_fft

    params.oper.coef_dealiasing = coef_dealiasing

    oper = OperatorsPseudoSpectralSW1L(params=params)

    return oper
Exemplo n.º 5
0
    def create_default_params(cls):
        """Class method returning the default parameters."""
        params = ParamContainer(tag='params')
        params._set_child('preproc')
        params.preproc._set_child('series', attribs={'path': ''})

        PreprocTools._complete_class_with_tools(params)

        return params
Exemplo n.º 6
0
def pandas_from_path(p, key, as_df=False):
    init_field, c, nh, Bu, init_field_const = keyparams_from_path(p)
    params_xml_path = os.path.join(p, "params_simul.xml")
    params = ParamContainer(path_file=params_xml_path)
    # sim = fls.load_sim_for_plot(p, merge_missing_params=True)

    c = int(c)
    kf = _k_f(params)
    Lf = np.pi / kf
    kd_kf = _k_diss(params) / kf
    # ts = _t_stationary(path=p)
    # eps = _eps(t_start=ts, path=p)
    eps, E, ts, tmax = epsetstmax(p)
    efr = params.preprocess.init_field_const
    if params.nu_2 > 0:
        Re = eps**(1 / 3) * Lf**(4 / 3) / params.nu_2
    else:
        Re = np.nan  # defined differently

    Fr = (eps * Lf)**(1.0 / 3) / c
    try:
        Ro = (eps / Lf**2)**(1.0 / 3) / params.f
    except ZeroDivisionError:
        Ro = np.inf
    minh = 0
    maxuc = 0
    # del sim
    gc.collect()
    data = [
        nh,
        c,
        params.nu_8,
        params.nu_2,
        params.f,
        eps,
        kd_kf,
        Fr,
        Ro,
        Re,
        Re * Fr**(2 / 3),
        Bu,
        # minh, maxuc,
        efr,
        E,
        ts,
        tmax,
        key,
    ]
    if as_df:
        return pd.DataFrame(data, columns=pd_columns)
    else:
        return pd.Series(data, index=pd_columns)
Exemplo n.º 7
0
 def save(self, zs, ret, mtx, dist, rvecs, tvecs):
     self.params = params = ParamContainer(tag="CalibCV")
     params._set_attribs({
         "class": self.__class__.__name__,
         "module": self.__module__,
         "f": np.diag(mtx)[:2],
         "C": mtx[0:2, 2],
         "cam_mtx": mtx,
         "kc": dist.T[0],
         "rotation": np.array(rvecs),
         "translate": tvecs,
         "zs": np.array(zs),
     })
     path_dir = os.path.dirname(self.path_file)
     os.makedirs(path_dir, exist_ok=True)
     if os.path.exists(self.path_file):
         print(f"WARNING: {self.path_file} already exists. Skipping save.")
     else:
         params._save_as_hdf5(self.path_file)
Exemplo n.º 8
0
 def create_default_params(cls):
     "Create an object containing the default parameters (class method)."
     params = ParamContainer(tag="params")
     cls._complete_params_with_default(params)
     return params
Exemplo n.º 9
0
 def create_default_params(cls):
     params = ParamContainer(tag="params")
     cls._complete_params_with_default(params)
     return params
Exemplo n.º 10
0
def params_from_path(p):
    params_xml_path = os.path.join(p, "params_simul.xml")
    params = ParamContainer(path_file=params_xml_path)
    return params
Exemplo n.º 11
0
def create_default_params():
    """Class method returning the default parameters.

    For developers: cf. fluidsim.base.params

    """
    params = ParamContainer(tag="params")

    params._set_child(
        "series",
        attribs={
            "path": "",
            "strcouple": "i:i+2",
            "ind_start": 0,
            "ind_stop": None,
            "ind_step": 1,
        },
    )

    params.series._set_doc(
        """
Parameters indicating the input series of images.

path : str, {''}

String indicating the input images (can be a full path towards an image
file or a string given to `glob`).

strcouple : 'i:i+2'

String indicating as a Python slicing how couples of images are formed.
There is one couple per value of `i`. The values of `i` are set with the
other parameters `ind_start`, `ind_step` and `ind_stop` approximately with
the function range (`range(ind_start, ind_stop, ind_step)`).

Python slicing is a very powerful notation to define subset from a
(possibly multidimensional) set of images. For a user, an alternative is to
understand how Python slicing works. See for example this page:
http://stackoverflow.com/questions/509211/explain-pythons-slice-notation.

Another possibility is to follow simple examples:

For single-frame images (im0, im1, im2, im3, ...), we keep the default
value 'i:i+2' to form the couples (im0, im1), (im1, im2), ...

To see what it gives, one can use ipython and range:

>>> i = 0
>>> list(range(10))[i:i+2]
[0, 1]

>>> list(range(10))[i:i+4:2]
[0, 2]

We see that we can also use the value 'i:i+4:2' to form the couples (im0,
im2), (im1, im3), ...

For double-frame images (im1a, im1b, im2a, im2b, ...) you can write

>>> params.series.strcouple = 'i, 0:2'

In this case, the first couple will be (im1a, im1b).

To get the first couple (im1a, im1a), we would have to write

>>> params.series.strcouple = 'i:i+2, 0'

ind_start : int, {0}

ind_step : int, {1}

int_stop : None

"""
    )

    params._set_child(
        "saving", attribs={"path": None, "how": "ask", "postfix": "piv"}
    )

    params.saving._set_doc(
        """Saving of the results.

path : None or str

Path of the directory where the data will be saved. If None, the path is
obtained from the input path and the parameter `postfix`.

how : str {'ask'}

'ask', 'new_dir', 'complete' or 'recompute'.

postfix : str

Postfix from which the output file is computed.
"""
    )

    WorkPIV._complete_params_with_default(params)

    params._set_internal_attr(
        "_value_text",
        json.dumps(
            {
                "program": "fluidimage",
                "module": "fluidimage.topologies.piv",
                "class": "TopologyPIV",
            }
        ),
    )

    params._set_child("preproc")
    image2image.complete_im2im_params_with_default(params.preproc)

    return params
Exemplo n.º 12
0
 def __init__(self, path_file="cam.h5"):
     self.path_file = str(path_file)
     if os.path.exists(path_file):
         print(f"Loading {path_file}.")
         self.params = ParamContainer(path_file=self.path_file)
Exemplo n.º 13
0
def create_info_simul(info_solver, params):
    """Create a ParamContainer instance gathering info_solver and params."""
    info = ParamContainer(tag="info_simul")
    info._set_as_child(info_solver)
    info._set_as_child(params)
    return info
Exemplo n.º 14
0
def make_params_calibration(path_file):
    """Make a tidy parameter container from a UVmat file.

    """
    params = ParamContainer(tag="calib")

    calib_uvmat = ParamContainer(path_file=str(path_file))
    tidy_container(calib_uvmat)

    calib_uvmat = calib_uvmat["geometry_calib"]

    f = [float(n) for n in np.array(get_number_from_string(calib_uvmat.fx_fy))]
    C = np.array(get_number_from_string(calib_uvmat.cx__cy))
    kc = np.array(calib_uvmat.kc)
    T = np.array(get_number_from_string(calib_uvmat.tx__ty__tz))

    R = []
    for i in range(3):
        R = np.hstack(
            [R, get_number_from_string(calib_uvmat["r_{}".format(i + 1)])]
        )

    omc = np.array(get_number_from_string(calib_uvmat["omc"]))

    params._set_attribs({"f": f, "C": C, "kc": kc, "T": T, "R": R, "omc": omc})

    if calib_uvmat.nb_slice is not None:

        nb_slice = np.array(calib_uvmat["nb_slice"])
        zslice_coord = np.zeros([nb_slice, 3])

        if calib_uvmat.nb_slice == 1:
            zslice_coord[:] = get_number_from_string(calib_uvmat["slice_coord"])
            if (
                hasattr(calib_uvmat, "slice_angle")
                and calib_uvmat["slice_angle"] is not None
            ):
                slice_angle = np.zeros([nb_slice, 3])
                slice_angle[:] = get_number_from_string(
                    calib_uvmat["slice_angle"]
                )
            else:
                slice_angle = [0, 0, 0]
        else:
            for i in range(nb_slice):
                zslice_coord[i][:] = get_number_from_string(
                    calib_uvmat["slice_coord_{}".format(i + 1)]
                )

            if (
                hasattr(calib_uvmat, "slice_angle_1")
                and calib_uvmat["slice_angle_1"] is not None
            ):
                slice_angle = np.zeros([nb_slice, 3])
                for i in range(nb_slice):
                    slice_angle[i][:] = get_number_from_string(
                        calib_uvmat["slice_angle_{}".format(i + 1)]
                    )
            else:
                slice_angle = [0, 0, 0]

        params._set_child(
            "slices",
            attribs={
                "nb_slice": nb_slice,
                "zslice_coord": zslice_coord,
                "slice_angle": slice_angle,
            },
        )

    if hasattr(calib_uvmat, "refraction_index"):
        params._set_attrib("refraction_index", calib_uvmat.refraction_index)

    if hasattr(calib_uvmat, "interface_coord"):
        params._set_attrib(
            "interface_coord",
            get_number_from_string(calib_uvmat["interface_coord"]),
        )

    return params
def load_params(path):
    if os.path.isdir(path):
        path = os.path.join(path, "params_simul.xml")
    return ParamContainer(path_file=path)