def getMetricsFromAparcStats(fn, metric):
    print(
        "Getting metrics from aparc stats - this is a flag that this function is ever called"
    )
    # Get the two aparc.stats filenames from the base filename
    rhfn = fn.replace("aseg.stats", "rh.aparc.stats")
    lhfn = fn.replace("aseg.stats", "lh.aparc.stats")

    # Read the stats in for each hemisphere
    rhStats = CorticalParcellationStats.read(rhfn)
    lhStats = CorticalParcellationStats.read(lhfn)

    # Depending on the metric, need to look at different values
    if metric == "CSF":
        # Get whole brain values from the stats
        rhDf = rhStats.whole_brain_measurements
        lhDf = lhStats.whole_brain_measurements

        # Get left and right CSF
        rCsf = rhDf['brain_segmentation_volume_mm^3'].values[0] - rhDf[
            'brain_segmentation_volume_without_ventricles_mm^3'].values[0]
        lCsf = lhDf['brain_segmentation_volume_mm^3'].values[0] - lhDf[
            'brain_segmentation_volume_without_ventricles_mm^3'].values[0]

        # sum values together
        measure = rCsf + lCsf

    elif "Cortical" in metric:
        # Get all of the rows at the bottom of the aparg.stats file
        rhDf = rhStats.structural_measurements
        lhDf = lhStats.structural_measurements

        if "SurfaceArea" in metric:
            # Sum the values in the SurfArea column
            measure = sum(rhDf['surface_area_mm^2']) + sum(
                lhDf['surface_area_mm^2'])
        elif "ThickAvg":
            # Sum the values in the ThickAvg column
            measure = sum(rhDf['average_thickness_mm']) + sum(
                lhDf['average_thickness_mm'])

            if metric.startswith("Avg"):
                denom = len(rhDf['average_thickness_mm']) + len(
                    lhDf['average_thickness_mm'])
                measure = measure / denom

    else:
        measure = -1

    return measure
Esempio n. 2
0
def test__parse_whole_brain_measurements_line(line, expected_column_name,
                                              expected_value):
    # pylint: disable=protected-access
    column_name, value = CorticalParcellationStats._parse_whole_brain_measurements_line(
        line)
    assert column_name == expected_column_name
    assert numpy.allclose(value, [expected_value])
Esempio n. 3
0
def test_read(path, headers, hemisphere, whole_brain_measurements,
              structural_measurements):
    stats = CorticalParcellationStats.read(path)
    assert headers == stats.headers
    assert hemisphere == stats.hemisphere
    pandas.util.testing.assert_frame_equal(
        left=pandas.DataFrame([whole_brain_measurements]),
        right=stats.whole_brain_measurements,
        check_like=True,  # ignore the order of index & columns
        check_dtype=True,
        check_names=True,
    )
    assert list(stats.structural_measurements.columns) == [
        'structure_name',
        'number_of_vertices',
        'surface_area_mm^2',
        'gray_matter_volume_mm^3',
        'average_thickness_mm',
        'thickness_stddev_mm',
        'integrated_rectified_mean_curvature_mm^-1',
        'integrated_rectified_gaussian_curvature_mm^-2',
        'folding_index',
        'intrinsic_curvature_index',
    ]
    pandas.util.testing.assert_frame_equal(
        left=pandas.DataFrame(structural_measurements),
        right=stats.structural_measurements,
        check_like=True,  # ignore the order of index & columns
        check_dtype=True,
        check_names=True,
    )
def getCorticalThicknessIfs(fn, side, statsBase):
    # Get the two aparc.stats filenames from the base filename
    newFn = fn.replace(statsBase, side + ".aparc.stats")

    # Read the stats in for each hemisphere
    stats = CorticalParcellationStats.read(newFn)

    # Get all of the rows at the bottom of the aparg.stats file
    df = stats.structural_measurements

    #      if "SurfaceArea" in metric:
    #          # Sum the values in the SurfArea column
    #          measure = sum(rhDf['surface_area_mm^2']) + sum(lhDf['surface_area_mm^2'])
    # Sum the values in the ThickAvg column
    measure = sum(df['average_thickness_mm'])
    denom = len(df['average_thickness_mm'])
    measure = measure / denom

    return measure
Esempio n. 5
0
def test_read(
    path,
    headers,
    hemisphere,
    whole_brain_measurements,
    structural_measurements_length,
    structural_measurements_subset,
):
    stats = CorticalParcellationStats.read(path)
    assert headers == stats.headers
    assert hemisphere == stats.hemisphere
    pandas.util.testing.assert_frame_equal(
        left=pandas.DataFrame([whole_brain_measurements]),
        right=stats.whole_brain_measurements,
        check_like=True,  # ignore the order of index & columns
        check_dtype=True,
        check_names=True,
    )
    assert list(stats.structural_measurements.columns) == [
        "structure_name",
        "number_of_vertices",
        "surface_area_mm^2",
        "gray_matter_volume_mm^3",
        "average_thickness_mm",
        "thickness_stddev_mm",
        "integrated_rectified_mean_curvature_mm^-1",
        "integrated_rectified_gaussian_curvature_mm^-2",
        "folding_index",
        "intrinsic_curvature_index",
    ]
    assert len(stats.structural_measurements) == structural_measurements_length
    pandas.util.testing.assert_frame_equal(
        left=pandas.DataFrame(structural_measurements_subset),
        right=stats.structural_measurements.iloc[:3],
        check_like=True,  # ignore the order of index & columns
        check_dtype=True,
        check_names=True,
    )
Esempio n. 6
0
    tot = lines_var[16]
    tot = tot.replace(',', '')
    lh_wm_vol = float(lh.split()[10])
    rh_wm_vol = float(rh.split()[10])
    tot_wm_vol = float(tot.split()[9])

    return [lh_wm_vol, rh_wm_vol, tot_wm_vol]


with open('config.json') as config_f:
    config = json.load(config_f)
    output_dir = config["freesurfer"]
    parc = config["parcellation"]

# left hemisphere
lh_stats = CorticalParcellationStats.read(output_dir + '/stats/lh.' + parc +
                                          '.stats')
dfl = lh_stats.structural_measurements
dfl.to_csv('lh.cortex.csv')

# right hemisphere
rh_stats = CorticalParcellationStats.read(output_dir + '/stats/rh.' + parc +
                                          '.stats')
dfr = rh_stats.structural_measurements
dfr.to_csv('rh.cortex.csv')

# whole brain
white_matter_stats = open(output_dir + '/stats/wmparc.stats')
[lh_wm_vol, rh_wm_vol, tot_wm_vol] = extract_wm_stats(white_matter_stats)

whole_brain = lh_stats.whole_brain_measurements[[
    'brain_segmentation_volume_mm^3',
                "l": 175,
                "b": 30,
            }
        }
    }
    results["brainlife"].append(graph)

    for parc in [
            "aparc", "aparc.a2009s", "aparc.DKTatlas", "aparc.DKTatlas40"
    ]:

        if os.path.exists(freesurfer_dir + '/stats/lh.' + parc + '.stats'):

            #convert stats to csv
            lh_stats = CorticalParcellationStats.read(freesurfer_dir +
                                                      '/stats/lh.' + parc +
                                                      '.stats')
            dfl = lh_stats.structural_measurements
            dfl.to_csv("secondary/" + parc + '_lh-cortex.csv')

            rh_stats = CorticalParcellationStats.read(freesurfer_dir +
                                                      '/stats/rh.' + parc +
                                                      '.stats')
            dfr = rh_stats.structural_measurements
            dfr.to_csv("secondary/" + parc + '_rh-cortex.csv')

            #these value are very close between different parcellation, so let's just output for aparc
            if parc == "aparc":
                ######################### volume ###################################################
                x = []
                y = []
Esempio n. 8
0
def test_read_https(url: str):
    stats = CorticalParcellationStats.read(url)
    assert stats.headers["generating_program"] == "mris_anatomical_stats"
Esempio n. 9
0
def test_read_pathlib(path_str: str):
    stats_str = CorticalParcellationStats.read(path_str)
    stats_pathlib = CorticalParcellationStats.read(pathlib.Path(path_str))
    assert stats_str.headers == stats_pathlib.headers
Esempio n. 10
0
def test__parse_whole_brain_measurements_line_parse_error(line):
    # pylint: disable=protected-access
    with pytest.raises(ValueError):
        CorticalParcellationStats._parse_whole_brain_measurements_line(line)
Esempio n. 11
0
def test_read_structural_measurements_length(path,
                                             structural_measurements_length):
    # simple test to verify no exception gets raised, see test_read for comprehensive test
    stats = CorticalParcellationStats.read(path)
    assert len(stats.structural_measurements) == structural_measurements_length