Ejemplo n.º 1
0
def main():

    # data_dir = os.environ.get('OneDrive') + r'\data\dti_navigation\joonas'
    #
    # filenames = {'T1': 'sub-S1_ses-S8741_T1w',
    #              'STL_INVESALIUS': 'half_head_inv',
    #              'STL_WORLD': 'half_head_world'}

    subj_id = 7
    item = 'brain'
    data_dir = os.environ.get(
        'OneDrive') + r'\data\nexstim_coord\mri\ppM1_S{}'.format(subj_id)

    filenames = {
        'T1': 'ppM1_S{}'.format(subj_id),
        'STL_INVESALIUS': 'ppM1_S{}_{}_shell_inv'.format(subj_id, item),
        'STL_WORLD': 'ppM1_S{}_{}_shell_world'.format(subj_id, item)
    }

    img_path = os.path.join(data_dir, filenames['T1'] + '.nii')
    stl_invesalius_path = os.path.join(data_dir,
                                       filenames['STL_INVESALIUS'] + '.stl')
    stl_world_path = os.path.join(data_dir, filenames['STL_WORLD'] + '.stl')

    imagedata, affine = imf.load_image(img_path)
    # mri2inv_mat = imf.mri2inv(imagedata, affine)
    inv2mri_mat = imf.inv2mri(imagedata, affine)

    matrix_vtk = vtk.vtkMatrix4x4()

    for row in range(0, 4):
        for col in range(0, 4):
            matrix_vtk.SetElement(row, col, inv2mri_mat[row, col])

    reader = vtk.vtkSTLReader()
    reader.SetFileName(stl_invesalius_path)
    reader.Update()

    # poly_normals = vtk.vtkPolyDataNormals()
    # poly_normals.SetInputData(reader.GetOutput())
    # poly_normals.ConsistencyOn()
    # poly_normals.AutoOrientNormalsOn()
    # poly_normals.SplittingOff()
    # poly_normals.UpdateInformation()
    # poly_normals.Update()

    transform = vtk.vtkTransform()
    transform.SetMatrix(matrix_vtk)

    transform_polydata = vtk.vtkTransformPolyDataFilter()
    transform_polydata.SetTransform(transform)
    transform_polydata.SetInputData(reader.GetOutput())
    transform_polydata.Update()

    stl_writer = vtk.vtkSTLWriter()
    stl_writer.SetFileTypeToBinary()
    stl_writer.SetFileName(stl_world_path)
    stl_writer.SetInputConnection(transform_polydata.GetOutputPort())
    stl_writer.Write()
Ejemplo n.º 2
0
def main():
    SHOW_WINDOW = True
    SHOW_AXES = True
    TRANFORM_SCANNER = True
    SAVE_SCANNER = True

    subject_id = 0
    subject = ['joonas', 'pantelis', 'baran', 'victor']
    marker_file = {
        'joonas': '20211123-200911-T1-markers_all_repeated',
        'pantelis': '20211126-121334-T1-markers_all_repeated',
        'baran': '20211123-205329-T1-markers_all_repeated',
        'victor': '20211126-132408-T1-markers_all_repeated'
    }

    target_names = ['M1', 'V1', 'BROCA', 'DLPFC']
    columns_export = ['label', 'x_seed', 'y_seed', 'z_seed', 'is_target']

    root_dir = os.environ.get('OneDrive') + r'\data\dti_navigation\normMRI'
    data_dir = os.path.join(root_dir, subject[subject_id])

    filenames = {
        'MKSS': marker_file[subject[subject_id]],
        'COIL': 'magstim_fig8_coil',
        'T1': 'T1',
        'BRAINSIM': 'wm',
        'HEADSIM': 'skin'
    }

    # mkss_path = os.path.join(data_dir, filenames['MKSS'] + '.mkss')
    mkss_path = os.path.join(data_dir, filenames['MKSS'] + '.mkss')
    head_sim_path = os.path.join(data_dir, filenames['HEADSIM'] + '.stl')
    brain_sim_path = os.path.join(data_dir, filenames['BRAINSIM'] + '.stl')
    coil_path = os.path.join(root_dir, filenames['COIL'] + '.stl')
    img_path = os.path.join(data_dir, filenames['T1'] + '.nii')
    save_path = os.path.join(data_dir, filenames['MKSS'] + '_scanner.csv')

    imagedata, affine = imf.load_image(img_path)
    inv2mri_mat = imf.inv2mri(imagedata, affine)

    data = imf.load_mkss(mkss_path)
    coord_list = data.iloc[:, 16:19].values
    orient_list = data.iloc[:, 19:].values
    colour_list = data.iloc[:, 6:9].values
    size_list = data.iloc[:, 9].values
    label_list = data.iloc[:, 10].values.tolist()
    seed_list = data.iloc[:, 11:14].values
    # coord_list, orient_list, colour_list, size_list, id_list, seed_list, tg_list = imf.load_mks(mkss_path)

    seed_list_w = np.hstack((seed_list, np.ones([seed_list.shape[0],
                                                 1]))).transpose()
    seed_list_w = inv2mri_mat @ seed_list_w
    seed_list_w = seed_list_w.transpose()[:, :3]

    id_fids = ['LEI', 'REI', 'NAI']
    index_coord = label_list.index('BROCA')
    index_fids = [label_list.index(n) for n in id_fids]

    if TRANFORM_SCANNER:
        data_out = data[columns_export].copy()
        data_out.iloc[:, 1:4] = seed_list_w
        data_out['distance'] = -1 * np.ones([seed_list_w.shape[0], 1])
        data_out['distance_coil'] = -1 * np.ones([seed_list_w.shape[0], 1])
        for n in target_names:
            index_coord = label_list.index(n)
            distances = np.linalg.norm(seed_list_w - seed_list_w[index_coord],
                                       axis=1)
            distances_coil = np.linalg.norm(coord_list -
                                            coord_list[index_coord],
                                            axis=1)
            repeats_id = np.where((distances_coil != 0.0)
                                  & (distances_coil <= 5))
            target_id = np.where((distances_coil == 0.0))
            data_out.loc[repeats_id[0], 'label'] = n
            data_out.loc[target_id[0], 'is_target'] = True
            data_out.loc[repeats_id[0], 'distance'] = distances[repeats_id[0]]
            data_out.loc[repeats_id[0],
                         'distance_coil'] = distances_coil[repeats_id[0]]

    if SAVE_SCANNER:
        data_out.to_csv(save_path, sep=';', index=False, float_format="%.3f")

    distance = np.linalg.norm(coord_list[index_coord] -
                              seed_list_w[index_coord])
    print("Distance between seed and coil center: {}".format(distance))

    if SHOW_WINDOW:
        # Create a rendering window and renderer
        ren, ren_win, iren = vf.create_window()

        # 0: red, 1: green, 2: blue, 3: maroon (dark red),
        # 4: purple, 5: teal (petrol blue), 6: yellow, 7: orange
        colours = [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.], [1., .0, 1.],
                   [0.45, 0., 0.5], [0., .5, .5], [1., 1., 0.], [1., .4, .0]]

        repos = [0., 0., 0., 0., 0., 0.]

        _ = vf.load_stl(head_sim_path,
                        ren,
                        opacity=.4,
                        colour="SkinColor",
                        replace=repos,
                        user_matrix=np.identity(4))

        _ = vf.load_stl(brain_sim_path,
                        ren,
                        opacity=.6,
                        colour=[1., 1., 1.],
                        replace=repos,
                        user_matrix=np.identity(4))

        # create fiducial markers
        for n in index_fids:
            _ = vf.add_marker(coord_list[n], ren, colours[n], radius=2)
        # --- fiducial markers

        # create coil vectors
        coil_pos = np.hstack(
            (coord_list[index_coord], orient_list[index_coord]))
        m_coil = imf.coil_transform_matrix(coil_pos)

        vec_length = 75
        repos_coil = [0., 0., 0., 0., 0., 90.]

        # coil vectors in invesalius 3D space
        p1 = m_coil[:-1, -1]
        coil_dir = m_coil[:-1, 0]
        coil_face = m_coil[:-1, 1]
        p2_face = p1 + vec_length * coil_face
        p2_dir = p1 + vec_length * coil_dir
        coil_norm = np.cross(coil_dir, coil_face)
        p2_norm = p1 - vec_length * coil_norm

        # offset = 40
        # coil_norm = coil_norm/np.linalg.norm(coil_norm)
        # coord_offset = p1 - offset * coil_norm

        _ = vf.load_stl(coil_path,
                        ren,
                        opacity=.6,
                        replace=repos_coil,
                        colour=[1., 1., 1.],
                        user_matrix=m_coil)

        _ = vf.add_line(ren, p1, p2_dir, color=[1.0, .0, .0])
        _ = vf.add_line(ren, p1, p2_face, color=[.0, 1.0, .0])
        _ = vf.add_line(ren, p1, p2_norm, color=[.0, .0, 1.0])

        _ = vf.add_marker(p1, ren, colours[4], radius=2)
        # --- coil vectors

        # seed markers
        _ = vf.add_marker(seed_list_w[index_coord], ren, colours[5], radius=2)
        # _ = vf.add_marker(seed_list[index_coord], ren, colours[6], radius=2)
        # --- seed markers

        # Add axes to scene origin
        if SHOW_AXES:
            _ = vf.add_line(ren, [0, 0, 0], [150, 0, 0], color=[1.0, 0.0, 0.0])
            _ = vf.add_line(ren, [0, 0, 0], [0, 150, 0], color=[0.0, 1.0, 0.0])
            _ = vf.add_line(ren, [0, 0, 0], [0, 0, 150], color=[0.0, 0.0, 1.0])

        # Initialize window and interactor
        iren.Initialize()
        ren_win.Render()
        iren.Start()
Ejemplo n.º 3
0
def main():
    SHOW_WINDOW = True
    SHOW_AXES = True
    COMP_ACT_SEED = True

    SEED_OFFSET = 25

    data_dir = os.environ.get('OneDrive') + r'\data\dti_navigation\joonas'
    # markers_20210304_all_before_rep_scan
    # markers_20210304_rep_left_m1_dlpfc_broca_V1_final_scan_seed
    # markers_20210304_rep_left_m1_dlpfc_broca_V1_final_labeled_scanner
    filenames = {
        'MKSS':
        'markers_20210304_rep_left_m1_dlpfc_broca_V1_final_labeled_scanner',
        'COIL': 'magstim_fig8_coil',
        'BRAINSIM': 'wm',
        'HEADSIM': 'skin',
        'ACT': 'trekkerACTlabels',
        'T1': 'sub-S1_ses-S8741_T1w'
    }

    mkss_path = os.path.join(data_dir, filenames['MKSS'] + '.mkss')
    head_sim_path = os.path.join(data_dir, filenames['HEADSIM'] + '.stl')
    brain_sim_path = os.path.join(data_dir, filenames['BRAINSIM'] + '.stl')
    coil_path = os.path.join(data_dir, filenames['COIL'] + '.stl')
    act_path = os.path.join(data_dir, filenames['ACT'] + '.nii')
    # img_path = os.path.join(data_dir, filenames['T1'] + '.nii')

    coord_list, orient_list, colour_list, size_list, id_list, seed_list, tg_list = imf.load_mks(
        mkss_path)

    id_fids = ['LEI', 'REI', 'NAI']
    index_coord = id_list.index('m1-left')
    index_fids = [id_list.index(n) for n in id_fids]

    if COMP_ACT_SEED:
        imagedata, affine = imf.load_image(act_path)
        # imagedata2, affine2 = imf.load_image(img_path)
        img_shape = imagedata.header.get_data_shape()
        act_data = imagedata.get_fdata()
        mri2inv_mat = imf.mri2inv(imagedata, affine)

    if SHOW_WINDOW:
        # Create a rendering window and renderer
        ren, ren_win, iren = vf.create_window()

        # 0: red, 1: green, 2: blue, 3: maroon (dark red),
        # 4: purple, 5: teal (petrol blue), 6: yellow, 7: orange
        colours = [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.], [1., .0, 1.],
                   [0.45, 0., 0.5], [0., .5, .5], [1., 1., 0.], [1., .4, .0]]

        repos = [0., 0., 0., 0., 0., 0.]

        _ = vf.load_stl(head_sim_path,
                        ren,
                        opacity=.4,
                        colour="SkinColor",
                        replace=repos,
                        user_matrix=np.identity(4))

        _ = vf.load_stl(brain_sim_path,
                        ren,
                        opacity=.6,
                        colour=[1., 1., 1.],
                        replace=repos,
                        user_matrix=np.identity(4))

        # if COMP_ACT_SEED:
        #     _ = vf.load_stl(brain_sim_path, ren, opacity=.6, colour=[1., 1., 1.], replace=repos,
        #                     user_matrix=np.linalg.inv(affine))
        #     _ = vf.load_stl(brain_sim_path, ren, opacity=.6, colour=[1., 1., 0.], replace=repos,
        #                     user_matrix=mri2inv_mat)

        # create fiducial markers
        for n in index_fids:
            _ = vf.add_marker(coord_list[n], ren, colours[n], radius=2)
        # --- fiducial markers

        # create coil vectors
        coil_pos = np.hstack(
            (coord_list[index_coord], orient_list[index_coord]))
        m_coil = imf.coil_transform_matrix(coil_pos)

        vec_length = 75
        repos_coil = [0., 0., 0., 0., 0., 90.]

        # coil vectors in invesalius 3D space
        p1 = m_coil[:-1, -1]
        coil_dir = m_coil[:-1, 0]
        coil_face = m_coil[:-1, 1]
        p2_face = p1 + vec_length * coil_face
        p2_dir = p1 + vec_length * coil_dir
        coil_norm = np.cross(coil_dir, coil_face)
        p2_norm = p1 - vec_length * coil_norm

        if COMP_ACT_SEED:
            coord_list_w = imf.create_grid((-2, 2), (0, 20), SEED_OFFSET - 5,
                                           1)
            coord_list_w_tr = m_coil @ coord_list_w
            coord_offset = imf.grid_offset(act_data,
                                           coord_list_w_tr,
                                           affine=affine)
            # coord_list_w_tr_inv = mri2inv_mat @ m_coil @ coord_list_w
            # coord_list_inv = imf.grid_offset_inv(act_data, coord_list_w_tr_inv, img_shape[1])
            # coord_list_mri = np.squeeze(coord_list_inv + np.array([[0, img_shape[1], 0]]))

        # offset = 40
        # coil_norm = coil_norm/np.linalg.norm(coil_norm)
        # coord_offset = p1 - offset * coil_norm

        # _ = vf.load_stl(coil_path, ren, opacity=.6, replace=repos_coil, colour=[1., 1., 1.], user_matrix=m_coil)

        _ = vf.add_line(ren, p1, p2_dir, color=[1.0, .0, .0])
        _ = vf.add_line(ren, p1, p2_face, color=[.0, 1.0, .0])
        _ = vf.add_line(ren, p1, p2_norm, color=[.0, .0, 1.0])

        _ = vf.add_marker(p1, ren, colours[4], radius=2)

        # --- coil vectors

        # seed markers
        _ = vf.add_marker(seed_list[index_coord], ren, colours[5], radius=.5)
        _ = vf.add_marker(coord_offset, ren, colours[6], radius=.5)
        # _ = vf.add_marker(coord_list_inv, ren, colours[0], radius=.5)
        # _ = vf.add_marker(coord_list_mri, ren, colours[0], radius=.5)

        # for n in coord_list_w_tr.T:
        #     _ = vf.add_marker(n[:3], ren, colours[7], radius=.5, opacity=.2)
        # --- seed markers

        # Add axes to scene origin
        if SHOW_AXES:
            _ = vf.add_line(ren, [0, 0, 0], [150, 0, 0], color=[1.0, 0.0, 0.0])
            _ = vf.add_line(ren, [0, 0, 0], [0, 150, 0], color=[0.0, 1.0, 0.0])
            _ = vf.add_line(ren, [0, 0, 0], [0, 0, 150], color=[0.0, 0.0, 1.0])

        # Initialize window and interactor
        iren.Initialize()
        ren_win.Render()
        iren.Start()
Ejemplo n.º 4
0
def main():
    FIX_MKS = False
    SAVE_FIX = False
    SAVE_SCAN = True
    RECOMPUTE_SEED = True

    SEED_OFFSET = 25

    data_dir = os.environ.get('OneDrive') + r'\data\dti_navigation\joonas'

    filenames = {
        'T1': 'sub-S1_ses-S8741_T1w',
        'MKS': 'markers_20210304_rep_left_m1_dlpfc_broca_V1_final_labeled',
        'MKS_CORR':
        'markers_20210304_rep_left_m1_dlpfc_broca_V1_final_labeled',
        'ACT': 'trekkerACTlabels'
    }

    img_path = os.path.join(data_dir, filenames['T1'] + '.nii')
    act_path = os.path.join(data_dir, filenames['ACT'] + '.nii')
    mkss_path = os.path.join(data_dir, filenames['MKS'] + '.mkss')
    mkss_save_path = os.path.join(data_dir,
                                  filenames['MKS'] + '_scanner_fixedgrid.mkss')

    if FIX_MKS:
        mks_corrupt_path = os.path.join(data_dir,
                                        filenames['MKS_CORR'] + '.mks')
        content = imf.load_mks_corrupt(mks_corrupt_path)
        content_fixed = imf.fix_mks_corrupt(
            content, problems=['0.5019607843137255', '1.0'])

        if SAVE_FIX:
            mkss_fix_path = os.path.join(data_dir,
                                         filenames['MKS_CORR'] + '_fix.mkss')
            imf.save_mks(mkss_fix_path, content_fixed)

    else:
        imagedata, affine = imf.load_image(img_path)
        # mri2inv_mat = imf.mri2inv(imagedata, affine)
        inv2mri_mat = imf.inv2mri(imagedata, affine)
        recomp_seed = {
            'recompute': False,
            'recompute': False,
            'seed_offset': 25,
            'act_data': None,
            'affine': None
        }

        if RECOMPUTE_SEED:
            imagedata_act, _ = imf.load_image(act_path)
            act_data = imagedata_act.get_fdata()
            recomp_seed = {
                'recompute': RECOMPUTE_SEED,
                'seed_offset': SEED_OFFSET,
                'act_data': act_data,
                'affine': affine
            }

        coord_list, orient_list, colour_list, size_list, id_list, seed_list, tg_list = imf.load_mks(
            mkss_path)
        coil_pos_scan, seed_scan = imf.mks2mkss(coord_list,
                                                orient_list,
                                                seed_list,
                                                user_matrix=inv2mri_mat,
                                                recompute_seed=recomp_seed)

        if SAVE_SCAN:
            # content_scan = coil_pos_scan.tolist(), colour_list, size_list, id_list, seed_scan.tolist(), tg_list
            content_scan = coil_pos_scan, colour_list, size_list, id_list, seed_scan, tg_list
            imf.save_mkss_scan(filename=mkss_save_path, content=content_scan)
def main():
    SHOW_WINDOW = True
    SHOW_AXES = True

    # data_dir = os.environ.get('OneDrive') + r'\data\dti_navigation\joonas'

    # filenames = {'T1': 'sub-S1_ses-S8741_T1w', 'MKSS': 'markers_20210304_m1',
    #              'ACT': 'trekkerACTlabels', 'COIL': 'magstim_fig8_coil',
    #              'HEAD': 'half_head_world', 'BRAIN': 'brain_inv', 'BRAINSIM': 'wm',
    #              'HEADSIM': 'skin', 'MKS': 'ana_markers3'}

    subj_id = 7
    data_dir = os.environ.get(
        'OneDrive') + r'\data\nexstim_coord\mri\ppM1_S{}'.format(subj_id)

    filenames = {
        'T1': 'ppM1_S{}'.format(subj_id),
        'HEAD': 'ppM1_S{}_scalp_shell_world'.format(subj_id),
        'HEADSIM': 'ppM1_S{}_brain_shell_world'.format(subj_id),
        'BRAIN': 'brain_inv',
        'BRAINSIM': 'wm'
    }

    img_path = os.path.join(data_dir, filenames['T1'] + '.nii')
    head_inv_path = os.path.join(data_dir, filenames['HEAD'] + '.stl')
    # brain_inv_path = os.path.join(data_dir, filenames['BRAIN'] + '.stl')
    head_sim_path = os.path.join(data_dir, filenames['HEADSIM'] + '.stl')
    # brain_sim_path = os.path.join(data_dir, filenames['BRAINSIM'] + '.stl')

    imagedata, affine = imf.load_image(img_path)
    mri2inv_mat = imf.mri2inv(imagedata, affine)
    inv2mri_mat = imf.inv2mri(imagedata, affine)

    if SHOW_WINDOW:
        # Create a rendering window and renderer
        ren, ren_win, iren = vf.create_window()

        # 0: red, 1: green, 2: blue, 3: maroon (dark red),
        # 4: purple, 5: teal (petrol blue), 6: yellow, 7: orange
        colours = [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.], [1., .0, 1.],
                   [0.45, 0., 0.5], [0., .5, .5], [1., 1., 0.], [1., .4, .0]]

        repos = [0., 0., 0., 0., 0., 0.]

        _ = vf.load_stl(head_inv_path,
                        ren,
                        opacity=.4,
                        colour=[0.482, 0.627, 0.698],
                        replace=repos,
                        user_matrix=np.identity(4))
        _ = vf.load_stl(head_sim_path,
                        ren,
                        opacity=0.4,
                        colour="SkinColor",
                        replace=repos,
                        user_matrix=np.identity(4))

        # _ = vf.load_stl(brain_sim_path, ren, opacity=.6, colour=[1., 1., 1.], replace=repos, user_matrix=mri2inv_mat)
        # _ = vf.load_stl(brain_sim_path, ren, opacity=.6, colour=[1., 1., 1.], replace=repos,
        #              user_matrix=np.identity(4))

        pix_dim = 0.48828125
        img_shape = 512
        offset = pix_dim * (img_shape - 1)

        # _ = vf.add_marker([31.25201835082943, 69, -25.883510303223446], ren, colours[0], radius=2)
        _ = vf.add_marker(
            [-2.8687858387879146, 102.87724194445669, -62.21162745582136],
            ren,
            colours[1],
            radius=1)

        # Add axes to scene origin
        if SHOW_AXES:
            _ = vf.add_line(ren, [0, 0, 0], [150, 0, 0], color=[1.0, 0.0, 0.0])
            _ = vf.add_line(ren, [0, 0, 0], [0, 150, 0], color=[0.0, 1.0, 0.0])
            _ = vf.add_line(ren, [0, 0, 0], [0, 0, 150], color=[0.0, 0.0, 1.0])

        # Initialize window and interactor
        iren.Initialize()
        ren_win.Render()
        iren.Start()
Ejemplo n.º 6
0
def main():
    SAVE_SCAN = True

    intensity = [110, 120]
    muscles = ['FCP', 'FRC', 'ADM']
    # subject = [4, 5, 7, 9]
    subject = [11]

    data_dir = os.environ.get(
        'OneDrive') + r'\data\dti_navigation\motor_mapping'

    for subj_ in subject:
        for int_ in intensity:
            for musc_ in muscles:

                # filenames = {'T1': 'subject04_victor', 'XLS': '04_110_MRI_ADM_processed',
                #              'XLS_CORR': '04_110_MRI_ADM_processed_scanner'}

                filenames = {
                    'T1': 'T1_sub-{:02d}'.format(subj_),
                    'XLS':
                    '{:02d}_{}_MRI_{}_processed'.format(subj_, int_, musc_)
                }

                img_path = os.path.join(data_dir, filenames['T1'] + '.nii')
                xls_path = os.path.join(data_dir, filenames['XLS'] + '.xlsx')
                csv_save_path = os.path.join(data_dir,
                                             filenames['XLS'] + '_scanner.csv')

                imagedata, affine = imf.load_image(img_path)
                # mri2inv_mat = imf.mri2inv(imagedata, affine)
                inv2mri_mat = imf.inv2mri(imagedata, affine)

                header = [
                    'x', 'y', 'z', 'ch1_amp', 'ch1_lat', 'ch2_amp', 'ch2_lat',
                    'ch3_amp', 'ch3_lat'
                ]
                data = pd.read_excel(xls_path,
                                     header=None,
                                     names=header,
                                     usecols='D:F,I:N')
                data.drop(labels=range(6), axis=0, inplace=True)
                data_arr = data.to_numpy()
                data_arr = data_arr.astype(float)

                coord_list = data_arr[:, :3].copy()
                orient_list = np.zeros([data_arr.shape[0], 3])

                coil_pos_scan = imf.array2scanner(coord_list,
                                                  orient_list,
                                                  user_matrix=inv2mri_mat)

                data_scanner = data_arr.copy()
                data_scanner[:, :3] = coil_pos_scan[:, :3]

                if SAVE_SCAN:
                    with open(csv_save_path, 'w', newline='') as f:
                        writer = csv.writer(f, delimiter=';')
                        # write the header
                        writer.writerow(header)
                        # write multiple rows
                        writer.writerows(data_scanner)
Ejemplo n.º 7
0
def main():
    SHOW_WINDOW = True
    SHOW_AXES = True
    SHOW_EEG = True
    SAVE_EEG = False

    reorder = [0, 2, 1]
    flipx = [True, False, False]

    data_dir = r'P:\tms_eeg\mTMS\projects\2019 EEG-based target automatization\Analysis\EEG electrode transformation\Locations of interest in Nexstim coords'

    filenames = {
        'T1': 'EEGTA04',
        'EEG': 'EEGTA04_electrode_locations_Nexstim',
        'TARGET': 'EEGTA04_preSMA_target',
        'SAVE_EEG': 'EEGTA04_electrode_locations_MRI'
    }

    img_path = os.path.join(data_dir, filenames['T1'] + '.nii')
    eeg_path = os.path.join(data_dir, filenames['EEG'] + '.mat')
    target_path = os.path.join(data_dir, filenames['TARGET'] + '.mat')
    save_eeg_path = os.path.join(data_dir, filenames['SAVE_EEG'] + '.csv')
    # brain_inv_path = os.path.join(data_dir, filenames['BRAIN'] + '.stl')
    # head_sim_path = os.path.join(data_dir, filenames['HEADSIM'] + '.stl')
    # brain_sim_path = os.path.join(data_dir, filenames['BRAINSIM'] + '.stl')
    # coil_path = os.path.join(data_dir, filenames['COIL'] + '.stl')

    coord_list = imf.load_eeg_mat(eeg_path)
    n_points = coord_list.shape[0]

    imagedata, affine = imf.load_image(img_path, closest=True)
    img_shape = imagedata.header.get_data_shape()
    # mri2inv_mat = imf.mri2inv(imagedata, affine)
    # inv2mri_mat = imf.inv2mri(imagedata, affine)

    coords_np = np.zeros([n_points, 3])
    for n, coord in enumerate(coord_list):
        # the flipx and reorder are needed to transform from nexstim to mri space
        coords_np[n, :] = n2m.coord_change(coord, img_shape, affine, flipx,
                                           reorder)
        # export the coordinates changed only by the affine
        # coords_np[n, :] = n2m.coord_change(coord, img_shape, affine)

    if SAVE_EEG:
        np.savetxt(save_eeg_path, coords_np, delimiter=";")

    if SHOW_WINDOW:
        # Create a rendering window and renderer
        ren, ren_win, iren = vf.create_window()

        if SHOW_EEG:
            for coord in coords_np:
                _ = vf.add_marker(coord, ren, [1., 0., 0.], radius=2)

        # Add axes to scene origin
        if SHOW_AXES:
            _ = vf.add_line(ren, [0, 0, 0], [150, 0, 0], color=[1.0, 0.0, 0.0])
            _ = vf.add_line(ren, [0, 0, 0], [0, 150, 0], color=[0.0, 1.0, 0.0])
            _ = vf.add_line(ren, [0, 0, 0], [0, 0, 150], color=[0.0, 0.0, 1.0])

        # Initialize window and interactor
        iren.Initialize()
        ren_win.Render()
        iren.Start()
Ejemplo n.º 8
0
def main():
    SHOW_WINDOW = True
    SHOW_AXES = True

    data_dir = os.environ.get('OneDrive') + r'\data\dti_navigation\joonas'

    filenames = {
        'T1': 'sub-S1_ses-S8741_T1w',
        'MKSS': 'markers_20210304_m1',
        'ACT': 'trekkerACTlabels',
        'COIL': 'magstim_fig8_coil',
        'HEAD': 'head_inv',
        'BRAIN': 'brain_inv',
        'BRAINSIM': 'wm',
        'HEADSIM': 'skin',
        'MKS': 'ana_markers3'
    }

    img_path = os.path.join(data_dir, filenames['T1'] + '.nii')
    mkss_path = os.path.join(data_dir, filenames['MKS'] + '.mks')
    # mkss_path = os.path.join(data_dir, filenames['MKSS'] + '.mkss')
    # head_inv_path = os.path.join(data_dir, filenames['HEAD'] + '.stl')
    # brain_inv_path = os.path.join(data_dir, filenames['BRAIN'] + '.stl')
    head_sim_path = os.path.join(data_dir, filenames['HEADSIM'] + '.stl')
    brain_sim_path = os.path.join(data_dir, filenames['BRAINSIM'] + '.stl')
    coil_path = os.path.join(data_dir, filenames['COIL'] + '.stl')

    coord_list, orient_list, colour_list, size_list, id_list, seed_list, tg_list = imf.load_mks(
        mkss_path)
    n_points = coord_list.shape[0]

    coord_w = np.hstack((coord_list, np.ones((n_points, 1))))
    seed_w = np.hstack((seed_list, np.ones((n_points, 1))))

    imagedata, affine = imf.load_image(img_path)
    mri2inv_mat = imf.mri2inv(imagedata, affine)
    inv2mri_mat = imf.inv2mri(imagedata, affine)

    if SHOW_WINDOW:
        # Create a rendering window and renderer
        ren, ren_win, iren = vf.create_window()

        # 0: red, 1: green, 2: blue, 3: maroon (dark red),
        # 4: purple, 5: teal (petrol blue), 6: yellow, 7: orange
        colours = [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.], [1., .0, 1.],
                   [0.45, 0., 0.5], [0., .5, .5], [1., 1., 0.], [1., .4, .0]]

        repos = [0., 0., 0., 0., 0., 0.]

        _ = vf.load_stl(head_sim_path,
                        ren,
                        opacity=.4,
                        colour=[0.482, 0.627, 0.698],
                        replace=repos,
                        user_matrix=mri2inv_mat)
        _ = vf.load_stl(head_sim_path,
                        ren,
                        opacity=.4,
                        colour="SkinColor",
                        replace=repos,
                        user_matrix=np.identity(4))

        _ = vf.load_stl(brain_sim_path,
                        ren,
                        opacity=.6,
                        colour=[1., 1., 1.],
                        replace=repos,
                        user_matrix=mri2inv_mat)
        _ = vf.load_stl(brain_sim_path,
                        ren,
                        opacity=.6,
                        colour=[1., 1., 1.],
                        replace=repos,
                        user_matrix=np.identity(4))

        # create fiducial markers
        fids_inv_vtk = coord_w[:3, :].copy()
        # from the invesalius exported fiducial markers you have to multiply the Y coordinate by -1 to
        # transform to the regular 3D invesalius space where coil location is saved
        fids_inv_vtk[:, 1] *= -1
        fids_vis = fids_inv_vtk[:, :3]
        fids_scan = inv2mri_mat @ fids_inv_vtk.T
        fids_scan_vis = fids_scan.T[:3, :3]

        for n in range(3):
            _ = vf.add_marker(fids_scan_vis[n, :], ren, colours[n], radius=2)

        for n in range(3):
            _ = vf.add_marker(fids_vis[n, :], ren, colours[n], radius=2)
        # --- fiducial markers

        # create coil vectors
        coil_pos = np.hstack((coord_w[-1, :3], orient_list[-1, :]))
        coil_pos[1] *= -1
        m_coil = imf.coil_transform_matrix(coil_pos)

        vec_length = 75
        repos_coil = [0., 0., 0., 0., 0., 90.]

        # coil vectors in invesalius 3D space
        p1 = m_coil[:-1, -1]
        coil_dir = m_coil[:-1, 0]
        coil_face = m_coil[:-1, 1]
        p2_face = p1 + vec_length * coil_face
        p2_dir = p1 + vec_length * coil_dir
        coil_norm = np.cross(coil_dir, coil_face)
        p2_norm = p1 - vec_length * coil_norm

        # offset = 40
        # coil_norm = coil_norm/np.linalg.norm(coil_norm)
        # coord_offset_nav = p1 - offset * coil_norm

        _ = vf.load_stl(coil_path,
                        ren,
                        opacity=.6,
                        replace=repos_coil,
                        colour=[1., 1., 1.],
                        user_matrix=m_coil)

        _ = vf.add_line(ren, p1, p2_dir, color=[1.0, .0, .0])
        _ = vf.add_line(ren, p1, p2_face, color=[.0, 1.0, .0])
        _ = vf.add_line(ren, p1, p2_norm, color=[.0, .0, 1.0])

        _ = vf.add_marker(p1, ren, colours[4], radius=2)

        # coil vectors in MRI space
        m_coil_scan = inv2mri_mat @ m_coil
        p1_scan = m_coil_scan[:-1, -1]
        coil_dir_scan = m_coil_scan[:-1, 0]
        coil_face_scan = m_coil_scan[:-1, 1]
        p2_face_scan = p1_scan + vec_length * coil_face_scan
        p2_dir_scan = p1_scan + vec_length * coil_dir_scan
        coil_norm_scan = np.cross(coil_dir_scan, coil_face_scan)
        p2_norm_scan = p1_scan - vec_length * coil_norm_scan

        _ = vf.load_stl(coil_path,
                        ren,
                        opacity=.6,
                        replace=repos_coil,
                        colour=[1., 1., 1.],
                        user_matrix=m_coil_scan)

        _ = vf.add_line(ren, p1_scan, p2_dir_scan, color=[1.0, .0, .0])
        _ = vf.add_line(ren, p1_scan, p2_face_scan, color=[.0, 1.0, .0])
        _ = vf.add_line(ren, p1_scan, p2_norm_scan, color=[.0, .0, 1.0])

        _ = vf.add_marker(p1_scan, ren, colours[4], radius=2)
        # --- coil vectors

        # seed markers
        seed_3dinv = seed_w[np.newaxis, -1, :].copy()
        seed_vis = seed_3dinv[0, :3]
        seed_scan = inv2mri_mat @ seed_3dinv.T
        seed_scan_vis = seed_scan.T[0, :3]

        _ = vf.add_marker(seed_vis, ren, colours[5], radius=2)
        _ = vf.add_marker(seed_scan_vis, ren, colours[6], radius=2)
        # --- seed markers

        # Add axes to scene origin
        if SHOW_AXES:
            _ = vf.add_line(ren, [0, 0, 0], [150, 0, 0], color=[1.0, 0.0, 0.0])
            _ = vf.add_line(ren, [0, 0, 0], [0, 150, 0], color=[0.0, 1.0, 0.0])
            _ = vf.add_line(ren, [0, 0, 0], [0, 0, 150], color=[0.0, 0.0, 1.0])

        # Initialize window and interactor
        iren.Initialize()
        ren_win.Render()
        iren.Start()