Example #1
0
def plot_bscan(dataset_name, save=False, noshow=False):
    conf = arim.io.load_conf(dataset_name)
    frame = common.load_frame(conf,
                              apply_filter=True,
                              expand=False,
                              warn_if_fallback_vel=True)
    result_dir = conf["result_dir"]
    # plot bscan
    ax, imag = aplt.plot_bscan_pulse_echo(frame,
                                          clim=[-40, 0],
                                          filename=str(result_dir / "bscan"),
                                          savefig=save)
    if noshow:
        plt.close("all")
    else:
        plt.show()
Example #2
0
# %% Load datafile (exported from BRAIN)

expdata_filename = r"example-datasets/contact_notch_aluminium.mat"
frame = arim.io.load_expdata(expdata_filename)

print("Frame:")
pp(frame.metadata)
print(frame)
print()
print("Probe:")
print(frame.probe)
pp(frame.probe.metadata)

# %% Plot Bscans (unfiltered)

aplt.plot_bscan_pulse_echo(frame)
plt.draw()

# %% Filter data

filt = arim.signal.Hilbert() + arim.signal.ButterworthBandpass(
    order=5, cutoff_min=0.5e6, cutoff_max=6e6, time=frame.time)
frame_raw = frame
frame = frame_raw.apply_filter(filt)

# %% Plot timetraces
plt.figure()
tx, rx = (19, 19)
plt.plot(frame_raw.time.samples, frame_raw.get_timetrace(tx, rx), label="raw")
plt.plot(frame.time.samples,
         np.abs(frame.get_timetrace(tx, rx)),
Example #3
0
def measure_probe_location(dataset_name, save=False, noshow=False):
    # %%
    conf = arim.io.load_conf(dataset_name)

    logger.info(f"dataset_name: {dataset_name}")

    frame = common.load_frame(conf,
                              apply_filter=True,
                              expand=False,
                              warn_if_fallback_vel=False)
    result_dir = conf["result_dir"]

    # Prepare
    frame = frame.apply_filter(arim.signal.Abs())

    plt.figure()
    plt.plot(frame.time.samples, frame.scanlines[0])
    plt.gca().yaxis.set_major_formatter(aplt.micro_formatter)
    plt.title(f"{dataset_name}\nA-scan")

    # plot bscan
    ax, imag = aplt.plot_bscan_pulse_echo(frame,
                                          clim=[-40, 0],
                                          filename=str(result_dir / "bscan"),
                                          savefig=save)

    # Detect frontwall:
    probe_standoff, probe_angle, time_to_surface = arim.measurement.find_probe_loc_from_frontwall(
        frame,
        frame.examination_object.couplant_material,
        tmin=10e-6,
        tmax=None)

    plt.figure()
    plt.plot(time_to_surface[frame.tx == frame.rx])
    plt.xlabel("element")
    plt.ylabel("time (µs)")
    plt.gca().yaxis.set_major_formatter(aplt.micro_formatter)
    plt.gca().yaxis.set_minor_formatter(aplt.micro_formatter)
    plt.title(
        f"{dataset_name}\ntime between elements and frontwall - must be a line!"
    )
    if save:
        plt.savefig(str(result_dir / "frontwall_detection"))

    new_conf = dict(
        probe_location={
            "standoff": probe_standoff.tolist(),
            "angle_deg": np.rad2deg(probe_angle).tolist(),
        })

    conf_file = conf["root_dir"] / "conf.d/10probe_loc.yaml"
    if save:
        with conf_file.open("w", encoding="utf8") as stream:
            stream.write("# generated by measure_probe_loc.py\n")
            yaml.dump(dict(new_conf), stream=stream, default_flow_style=False)

    if noshow:
        plt.close("all")
    else:
        plt.show()
Example #4
0
def test_fulltime_model(use_multifreq, show_plots):
    # Setup
    couplant = arim.Material(longitudinal_vel=1480.0,
                             density=1000.0,
                             state_of_matter="liquid")
    block = arim.Material(
        longitudinal_vel=6320.0,
        transverse_vel=3130.0,
        density=2700.0,
        state_of_matter="solid",
        longitudinal_att=arim.material_attenuation_factory("constant", 2.0),
        transverse_att=arim.material_attenuation_factory("constant", 20.0),
    )

    probe = arim.Probe.make_matrix_probe(20, 1e-3, 1, np.nan, 5e6)
    probe_element_width = 0.8e-3
    probe.set_reference_element("first")
    probe.reset_position()
    probe.translate([0.0, 0.0, -5e-3])
    probe.rotate(arim.geometry.rotation_matrix_y(np.deg2rad(10)))

    probe_p = probe.to_oriented_points()
    frontwall = arim.geometry.points_1d_wall_z(numpoints=1000,
                                               xmin=0.0e-3,
                                               xmax=40.0e-3,
                                               z=0.0,
                                               name="Frontwall")
    backwall = arim.geometry.points_1d_wall_z(numpoints=1000,
                                              xmin=0.0e-3,
                                              xmax=40.0e-3,
                                              z=30.0e-3,
                                              name="Backwall")
    scatterer_p = arim.geometry.default_oriented_points(
        arim.Points([[35e-3, 0.0, 20e-3]]))
    all_points = [probe_p, frontwall, backwall, scatterer_p]

    # if show_plots:
    #     import arim.plot as aplt
    #     aplt.plot_interfaces(
    #         all_points, markers=["o", "o", "o", "d"], show_orientations=True
    #     )
    #     aplt.plt.show()

    exam_obj = arim.BlockInImmersion(block, couplant, frontwall, backwall,
                                     scatterer_p)
    scat_obj = arim.scat.scat_factory(material=block,
                                      kind="sdh",
                                      radius=0.5e-3)
    scat_funcs = scat_obj.as_angles_funcs(probe.frequency)
    scat_angle = 0.0

    tx_list, rx_list = arim.ut.fmc(probe.numelements)

    # Toneburst
    dt = 0.25 / probe.frequency  # to adjust so that the whole toneburst is sampled
    toneburst_time, toneburst, toneburst_t0_idx = arim.model.make_toneburst2(
        5, probe.frequency, dt, num_before=1)
    toneburst_f = np.fft.rfft(toneburst)
    toneburst_freq = np.fft.rfftfreq(len(toneburst_time), dt)

    # Allocate a long enough time vector for the timetraces
    views = bim.make_views(
        exam_obj,
        probe_p,
        scatterer_p,
        max_number_of_reflection=0,
        tfm_unique_only=False,
    )
    arim.ray.ray_tracing(views.values())
    max_delay = max(
        (view.tx_path.rays.times.max() + view.rx_path.rays.times.max()
         for view in views.values()))
    timetraces_time = arim.Time(
        0.0, dt,
        math.ceil(max_delay / dt) + len(toneburst_time))
    timetraces = None

    # Run model
    if use_multifreq:
        model_freq_array = toneburst_freq
    else:
        model_freq_array = probe.frequency

    transfer_function_iterator = bim.scat_unshifted_transfer_functions(
        views,
        tx_list,
        rx_list,
        model_freq_array,
        scat_obj,
        probe_element_width=probe_element_width,
        use_directivity=True,
        use_beamspread=True,
        use_transrefl=True,
        use_attenuation=True,
        scat_angle=scat_angle,
        numangles_for_scat_precomp=120,
    )

    for unshifted_transfer_func, delays in transfer_function_iterator:
        timetraces = arim.model.transfer_func_to_timetraces(
            unshifted_transfer_func,
            delays,
            timetraces_time,
            toneburst_time,
            toneburst_freq,
            toneburst_f,
            toneburst_t0_idx,
            timetraces=timetraces,
        )
    frame = arim.Frame(timetraces, timetraces_time, tx_list, rx_list, probe,
                       exam_obj)
    if show_plots:
        import matplotlib.pyplot as plt
        import arim.plot as aplt

        aplt.plot_bscan_pulse_echo(frame)
        plt.title(
            f"test_fulltime_model - Bscan - use_multifreq={use_multifreq}")

        tx = 0
        rx = probe.numelements - 1
        plt.figure()
        plt.plot(np.real(frame.get_timetrace(tx, rx)),
                 label=f"tx={tx}, rx={rx}")
        plt.plot(np.real(frame.get_timetrace(rx, tx)),
                 label=f"tx={rx}, rx={tx}")
        plt.title(f"test_fulltime_model - use_multifreq={use_multifreq}")
        plt.legend()
        plt.show()
Example #5
0
def locate_artefact(dataset_name, save):
    # %%
    conf = arim.io.load_conf(dataset_name)
    # conf['grid']['pixel_size'] = 2e-3  # debug
    conf["grid"]["pixel_size"] = 0.5e-3  # hardcode to make faster
    aplt.conf["savefig"] = False

    result_dir = conf["result_dir"]

    logger.info(f"dataset_name: {dataset_name}")

    # Load frame
    frame = common.load_frame(conf, apply_filter=True, expand=True)

    # Make grid
    z_backwall = conf["backwall"]["z"]
    assert not np.isnan(z_backwall)

    grid = common.make_grid_tfm(conf)
    grid_p = grid.to_oriented_points()
    probe_p = frame.probe.to_oriented_points()

    # Make views
    views = bim.make_views(
        frame.examination_object,
        probe_p,
        grid_p,
        tfm_unique_only=True,
        max_number_of_reflection=1,
    )

    # %% Plot Bscan
    bscan_ax, _ = aplt.plot_bscan_pulse_echo(frame,
                                             clim=[-60, -20],
                                             interpolation="bilinear")
    bscan_ax.figure.canvas.set_window_title("Bscan")

    # %% Perform ray tracing

    arim.ray.ray_tracing(views.values(), convert_to_fortran_order=True)

    # %% Run TFM

    tfms = OrderedDict()
    for i, view in enumerate(views.values()):
        with arim.helpers.timeit("TFM {}".format(view.name), logger=logger):
            tfms[view.name] = arim.im.tfm.tfm_for_view(frame,
                                                       grid,
                                                       view,
                                                       fillvalue=0.0)

    # %% Plot all TFM

    try:
        reference_rect = common.reference_rect(conf)
        reference_area = grid.points_in_rectbox(**reference_rect)
    except common.NoDefect:
        reference_rect = None
        reference_area = None

    if USE_DYNAMIC_SCALE:
        scale = aplt.common_dynamic_db_scale(
            [tfm.res for tfm in tfms.values()], reference_area)
    else:
        scale = itertools.repeat((None, None))

    tfm_axes = {}

    ncols = 3
    nrows = 7
    fig, axes = plt.subplots(ncols=ncols,
                             nrows=nrows,
                             figsize=(9, 12),
                             sharex=False,
                             sharey=False)
    xmin = grid.xmin
    xmax = grid.xmax
    zmin = conf["frontwall"]["z"]
    zmax = conf["backwall"]["z"]

    for i, ((viewname, tfm), ax) in enumerate(zip(tfms.items(), axes.ravel())):
        ref_db, clim = next(scale)
        clim = [-40, 0.0]
        ax, im = aplt.plot_tfm(
            tfm,
            ax=ax,
            scale="db",
            ref_db=ref_db,
            clim=clim,
            interpolation="none",
            savefig=False,
            draw_cbar=False,
        )
        ax.set_title(viewname, y=0.9, size="small")
        ax.set_adjustable("box")
        ax.axis([xmin, xmax, zmax, zmin])
        tfm_axes[viewname] = ax

        if ax in axes[-1, :]:
            ax.set_xlabel("x (mm)")
            ax.set_xticks(
                [xmin, xmax,
                 np.round((xmin + xmax) / 2, decimals=3)])
        else:
            ax.set_xlabel("")
            ax.set_xticks([])
        if ax in axes[:, 0]:
            ax.set_ylabel("z (mm)")
            ax.set_yticks(
                [zmax, zmin,
                 np.round((zmin + zmax) / 2, decimals=3)])
        else:
            ax.set_ylabel("")
            ax.set_yticks([])

    cbar = fig.colorbar(im,
                        ax=axes.ravel().tolist(),
                        location="top",
                        fraction=0.05,
                        aspect=40,
                        pad=0.03)
    cbar.ax.set_ylabel("dB")
    ax.figure.canvas.set_window_title(f"TFMs")

    return bscan_ax, tfm_axes, tfms, views