Commit af6b1816 authored by Paul McCarthy's avatar Paul McCarthy 🚵
Browse files

Merge branch 'rf/sparsity_logging' into 'master'

Rf/sparsity logging

See merge request fsl/ukbparse!116
parents a0c4ab45 9b3bfbbc
......@@ -2,6 +2,22 @@
======================
0.17.1 (Tuesday 23rd April 2019)
--------------------------------
Changed
^^^^^^^
* The :func:`.isSparse` function now returns the reason and value for
columns which fail the sparsity test.
* The ``--non_numeric_file`` will not be created if there are not any
non-numeric columns.
* The built-in ``fmrib`` configuration now includes verbosity and logging
settings.
0.17.0 (Monday 22nd April 2019)
-------------------------------
......@@ -12,8 +28,8 @@ Added
* New ``--non_numeric_file`` option allows non-numeric columns to be saved to
a separate file (TSV export only).
* Built-in ``fmrib.cfg`` configuration file, which can be used via ``-cfg
fmrib``.
* Built-in ``fmrib.cfg`` configuration file, which can be used via
``-cfg fmrib``.
Changed
......
......@@ -6,7 +6,7 @@
#
__version__ = '0.17.0'
__version__ = '0.17.1'
"""The ``ukbparse`` versioning scheme roughly follows Semantic Versioning
conventions.
"""
......
overwrite
import_all
noisy
noisy
noisy
log_file log.txt
unknown_vars_file unknowns.tsv
non_numeric_file non_numerics.tsv
icd10_map_file icd10_codes.tsv
......
......@@ -148,13 +148,21 @@ def exportTSV(dtable,
nonNumericCols = [c for c in towrite.columns
if not pdtypes.is_numeric_dtype(towrite[c])]
log.debug('Redirecting %i non-numeric columns to %s '
'(remaining %i columns will be written to %s)',
len(nonNumericCols), nonNumericFile,
len(numericCols), outfile)
numericChunk = towrite[numericCols]
nonNumericChunk = towrite[nonNumericCols]
if len(nonNumericCols) > 0:
log.debug('Redirecting %i non-numeric columns to %s '
'(remaining %i columns will be written to %s)',
len(nonNumericCols), nonNumericFile,
len(numericCols), outfile)
else:
log.debug('No non-numeric columns present - not creating '
'%s', nonNumericFile)
nonNumericFile = None
nonNumericCols = None
nonNumericChunk = None
numericChunk = towrite[numericCols]
if nonNumericCols is not None:
nonNumericChunk = towrite[nonNumericCols]
_writeChunk(numericChunk,
chunki,
......
......@@ -94,13 +94,16 @@ def removeIfSparse(dtable,
log.debug('Checking column %s for sparsity', col.name)
if core.isSparse(dtable[:, col.name],
vtype,
minpres=minpres,
minstd=minstd,
maxcat=maxcat,
absolute=absolute):
log.debug('Dropping sparse column %s', col.name)
isSparse, test, val = core.isSparse(dtable[:, col.name],
vtype,
minpres=minpres,
minstd=minstd,
maxcat=maxcat,
absolute=absolute)
if isSparse:
log.debug('Dropping sparse column %s (%s: %f)',
col.name, test, val)
remove.append(col)
return remove
......@@ -187,7 +190,7 @@ def binariseCategorical(dtable,
``True`` ``False`` '{vid}.{instance}_{value}'
``True`` ``True`` '{vid}_{value}'
================ =================== ==================================
"""
""" # noqa
defaultNameFormat = {
(False, False) : '{vid}-{visit}.{instance}_{value}',
......
......@@ -70,7 +70,17 @@ def isSparse(data,
an absolute count. Otherwise ``minpres`` is interpreted
as a proportion.
:returns: ``True`` if the data is sparse, ``False`` otherwise.
:returns: A tuple containing:
- ``True`` if the data is sparse, ``False`` otherwise.
- If the data is sparse, one of ``'minpres'``,
``'minstd'``, or ``'maxcat'``, indicating the cause of
its sparsity. ``None`` if the data is not sparse.
- If the data is sparse, the value of the criteria which
caused the data to fail the test. ``None`` if the data
is not sparse.
"""
presmask = data.notnull()
......@@ -95,13 +105,14 @@ def isSparse(data,
pres = float(len(present)) / len(data)
if pres < minpres:
return True
return True, 'minpres', pres
# stddev is not large enough (for
# numerical/categorical types)
if isnumeric and minstd is not None:
if (present - present.mean()).std() <= minstd:
return True
std = (present - present.mean()).std()
if std <= minstd:
return True, 'minstd', std
# for categorical types
if iscategorical and maxcat is not None:
......@@ -109,11 +120,11 @@ def isSparse(data,
# one category is too dominant
uniqvals = np.unique(present)
uniqcounts = [sum(present == u) for u in uniqvals]
catcount = float(max(uniqcounts)) / len(present)
if catcount >= maxcat:
return True, 'maxcat', catcount
if float(max(uniqcounts)) / len(present) >= maxcat:
return True
return False
return False, None, None
def redundantColumns(data, columns, corrthres, nathres=None):
......
......@@ -6,8 +6,10 @@
#
import warnings
import warnings
import os
import textwrap as tw
import os.path as op
import pandas as pd
import numpy as np
......@@ -586,3 +588,20 @@ def test_exporting_non_numeric():
assert expn .strip() == gotn .strip()
assert expnn.strip() == gotnn.strip()
# if no non-numeric columns,
# file should not be created
os.remove('non_numerics.txt')
with open('data.txt', 'wt') as f:
f.write(expn)
vartable, proctable, cattable, _ = gen_tables([1, 3])
dt, _ = importing.importData(
'data.txt', vartable, proctable, cattable)
exporting.exportData(dt,
'numerics.txt',
nonNumericFile='non_numerics.txt',
fileFormat='tsv')
gotn = open('numerics.txt').read().strip()
assert gotn == expn.strip()
assert not op.exists('non_numerics.txt')
......@@ -32,33 +32,52 @@ def test_isSparse_minpres():
data = pd.Series(data)
abs_result = core.isSparse(data, util.CTYPES.continuous,
minpres=threshold * size)
prop_result = core.isSparse(data, util.CTYPES.continuous,
minpres=threshold,
absolute=False)
assert expected == abs_result
assert expected == prop_result
absres = core.isSparse(
data, util.CTYPES.continuous, minpres=threshold * size)
propres = core.isSparse(
data, util.CTYPES.continuous, minpres=threshold, absolute=False)
if expected:
expcause = 'minpres'
expabsval = size - len(missing)
exppropval = (size - len(missing)) / size
else:
expcause = None
expabsval = None
exppropval = None
assert absres == (expected, expcause, expabsval)
assert propres[:2] == (expected, expcause)
if exppropval is not None:
assert np.isclose(propres[2], exppropval)
else:
assert propres[2] is None
# minpres should be ignored if
# number of points in data is
# less than or equal to it
data = np.random.random(10)
data[:2] = np.nan
assert core.isSparse(pd.Series(data),
util.CTYPES.continuous,
minpres=9)
assert core.isSparse(pd.Series(data),
util.CTYPES.continuous,
minpres=10)
assert not core.isSparse(pd.Series(data),
util.CTYPES.continuous,
minpres=11)
assert not core.isSparse(pd.Series(data),
util.CTYPES.continuous,
minpres=100)
res = core.isSparse(pd.Series(data),
util.CTYPES.continuous,
minpres=9)
assert res == (True, 'minpres', 8)
res = core.isSparse(pd.Series(data),
util.CTYPES.continuous,
minpres=10)
assert res == (True, 'minpres', 8)
res = core.isSparse(pd.Series(data),
util.CTYPES.continuous,
minpres=11)
assert res == (False, None, None)
res = core.isSparse(pd.Series(data),
util.CTYPES.continuous,
minpres=100)
assert res == (False, None, None)
def test_isSparse_minstd():
......@@ -77,7 +96,9 @@ def test_isSparse_minstd():
result = core.isSparse(data, util.CTYPES.continuous,
minstd=minstd)
assert expected == result
if expected:
assert result[:2] == (expected, 'minstd')
assert np.isclose(result[2], actualstd)
def test_isSparse_maxcat():
......@@ -96,21 +117,39 @@ def test_isSparse_maxcat():
expected = actualmaxcat >= maxcat
if expected:
expected = (expected, 'maxcat', actualmaxcat)
else:
expected = (expected, None, None)
# test should only be applied for integer/categoricals
assert not core.isSparse(data, util.CTYPES.continuous,
maxcat=maxcat)
result = core.isSparse(data, util.CTYPES.continuous,
maxcat=maxcat)
assert result == (False, None, None)
result = core.isSparse(data, util.CTYPES.integer,
maxcat=maxcat)
assert expected == result
maxcat=maxcat)
assert result[:2] == expected[:2]
if expected[2] is None:
assert result[2] is None
else:
assert np.isclose(result[2], expected[2])
result = core.isSparse(data, util.CTYPES.categorical_single,
maxcat=maxcat)
assert expected == result
assert result[:2] == expected[:2]
if expected[2] is None:
assert result[2] is None
else:
assert np.isclose(result[2], expected[2])
result = core.isSparse(data, util.CTYPES.categorical_multiple,
maxcat=maxcat)
assert expected == result
assert result[:2] == expected[:2]
if expected[2] is None:
assert result[2] is None
else:
assert np.isclose(result[2], expected[2])
def test_redundantColumns():
......
%% Cell type:markdown id: tags:
![image.png](attachment:image.png)
# `ukbparse`
> Paul McCarthy &lt;paul.mccarthy@ndcn.ox.ac.uk&gt; ([WIN@FMRIB](https://www.win.ox.ac.uk/))
`ukbparse` is a command-line program which you can use to extract data from UK BioBank (and other tabular) data.
You can give `ukbparse` one or more input files (e.g. `.csv`, `.tsv`), and it will merge them together, perform some preprocessing, and produce a single output file.
A large number of rules are built into `ukbparse` which are specific to the UK BioBank data set. But you can control and customise everything that `ukbparse` does to your data, including which rows and columns to extract, and which cleaning/processing steps to perform on each column.
The `ukbparse` source code is available at https://git.fmrib.ox.ac.uk/fsl/ukbparse. You can install `ukbparse` into a Python environment using `pip`:
pip install ukbparse
Get command-line help by typing:
ukbparse -h
*The examples in this notebook assume that you have installed `ukbparse` 0.17.0 or newer.*
*The examples in this notebook assume that you have installed `ukbparse` 0.17.1 or newer.*
%% Cell type:code id: tags:
``` bash
ukbparse -V
```
%% Output
ukbparse 0.17.0
ukbparse 0.17.1
%% Cell type:markdown id: tags:
### Contents
1. [Overview](#Overview)
1. [Import](#1.-Import)
2. [Cleaning](#2.-Cleaning)
3. [Processing](#3.-Processing)
4. [Export](#4.-Export)
2. [Examples](#Examples)
3. [Import examples](#Import-examples)
1. [Selecting variables (columns)](#Selecting-variables-(columns))
1. [Selecting individual variables](#Selecting-individual-variables)
2. [Selecting variable ranges](#Selecting-variable-ranges)
3. [Selecting variables with a file](#Selecting-variables-with-a-file)
4. [Selecting variables from pre-defined categories](#Selecting-variables-from-pre-defined-categories)
2. [Selecting subjects (rows)](#Selecting-subjects-(rows))
1. [Selecting individual subjects](#Selecting-individual-subjects)
2. [Selecting subject ranges](#Selecting-subject-ranges)
3. [Selecting subjects from a file](#Selecting-subjects-from-a-file)
4. [Selecting subjects by variable value](#Selecting-subjects-by-variable-value)
5. [Excluding subjects](#Excluding-subjects)
3. [Selecting visits](#Selecting-visits)
4. [Merging multiple input files](#Merging-multiple-input-files)
1. [Merging by subject](#Merging-by-subject)
2. [Merging by column](#Merging-by-column)
3. [Naive merging](#Merging-by-column)
4. [Cleaning examples](#Cleaning-examples)
1. [NA insertion](#NA-insertion)
2. [Variable-specific cleaning functions](#Variable-specific-cleaning-functions)
3. [Categorical recoding](#Categorical-recoding)
4. [Child value replacement](#Child-value-replacement)
5. [Processing examples](#Processing-examples)
1. [Sparsity check](#Sparsity-check)
2. [Redundancy check](#Redundancy-check)
3. [Categorical binarisation](#Categorical-binarisation)
6. [Custom cleaning, processing and loading - ukbparse plugins](#Custom-cleaning,-processing-and-loading---ukbparse-plugins)
1. [Custom cleaning functions](#Custom-cleaning-functions)
2. [Custom processing functions](#Custom-processing-functions)
3. [Custom file loaders](#Custom-file-loaders)
7. [Miscellaneous topics](#Miscellaneous-topics)
1. [Non-numeric data](#Non-numeric-data)
2. [Dry run](#Dry-run)
3. [Built-in rules](#Built-in-rules)
4. [Using a configuration file](#Using-a-configuration-file)
5. [Reporting unknown variables](#Reporting-unknown-variables)
6. [Low-memory mode](#Low-memory-mode)
%% Cell type:markdown id: tags:
# Overview
`ukbparse` performs the following steps:
## 1. Import
All data files are loaded in, unwanted columns and subjects are dropped, and the data files are merged into a single table (a.k.a. data frame). Multiple files can be merged according to an index column (e.g. subject ID). Or, if the input files contain the same columns/subjects, they can be naively concatenated along rows or columns.
## 2. Cleaning
The following cleaning steps are applied to each column:
1. **NA value replacement:** Specific values for some columns are replaced with NA, for example, variables where a value of `-1` indicates *Do not know*.
2. **Variable-specific cleaning functions:** Certain columns are re-formatted - for example, the [ICD10](https://en.wikipedia.org/wiki/ICD-10) disease codes are converted to integer representations.
3. **Categorical recoding:** Certain categorical columns are re-coded.
4. **Child value replacement:** NA values within some columns which are dependent upon other columns may have values inserted based on the values of their parent columns.
## 3. Processing
During the processing stage, columns may be removed, merged, or expanded into additional columns. For example, a categorical column may be expanded into a set of binary columns, one for each category.
A column may also be removed on the basis of being too sparse, or being redundant with respect to another column.
## 4. Export
The processed data can be saved as a `.csv`, `.tsv`, or `.hdf5` file.
%% Cell type:markdown id: tags:
# Examples
Throughout these examples, we are going to use a few command line options, which you will probably **not** normally want to use:
- `-nb` (short for `--no_builtins`): This tells `ukbparse` not to use the built-in processing rules, which are specifically tailored for UK BioBank data.
- `-ow` (short for `--overwrite`): This tells `ukbparse` not to complain if the output file already exists.
- `-q` (short for `--quiet`): This tells `ukbparse` to be quiet.
Without the `-q` option, `ukbparse` can be quite verbose, which can be annoying, but is very useful when things go wrong. A good strategy is to tell `ukbparse` to send all of its output to a log file with the `--log_file` (or `-lf`) option. For example:
ukbparse --log_file log.txt out.tsv in.tsv
Here's the first example input data set, with UK BioBank-style column names:
%% Cell type:code id: tags:
``` bash
cat data_01.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0 7-0.0 8-0.0 9-0.0 10-0.0
1 31 65 10 11 84 22 56 65 90 12
2 56 52 52 42 89 35 3 65 50 67
3 45 84 20 84 93 36 96 62 48 59
4 7 46 37 48 80 20 18 72 37 27
5 8 86 51 68 80 84 11 28 69 10
6 6 29 85 59 7 46 14 60 73 80
7 24 49 41 46 92 23 39 68 7 63
8 80 92 97 30 92 83 98 36 6 23
9 84 59 89 79 16 12 95 73 2 62
10 23 96 67 41 8 20 97 57 59 23
%% Cell type:markdown id: tags:
The numbers in each column name represent:
1. The variable ID
2. The visit, for variables which were collected at multiple points in time.
3. The "instance", for multi-valued variables.
Note that one **variable** is typically associated with several **columns**, although we're keeping things simple for this first example - there is only one visit for each variable, and there are no mulit-valued variables.
%% Cell type:markdown id: tags:
# Import examples
## Selecting variables (columns)
You can specify which variables you want to load in the following ways, using the `--variable` (`-v` for short) and `--category` (`-c` for short) command line options:
* By variable ID
* By variable ranges
* By a text file which contains the IDs you want to keep.
* By pre-defined variable categories
* By column name
### Selecting individual variables
Simply provide the IDs of the variables you want to extract:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -v 1 -v 5 out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 5-0.0
1 31 84
2 56 89
3 45 93
4 7 80
5 8 80
6 6 7
7 24 92
8 80 92
9 84 16
10 23 8
%% Cell type:markdown id: tags:
### Selecting variable ranges
The `--variable`/`-v` option accepts MATLAB-style ranges of the form `start:step:stop` (where the `stop` is inclusive):
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -v 1:3:10 out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 4-0.0 7-0.0 10-0.0
1 31 11 56 12
2 56 42 3 67
3 45 84 96 59
4 7 48 18 27
5 8 68 11 10
6 6 59 14 80
7 24 46 39 63
8 80 30 98 23
9 84 79 95 62
10 23 41 97 23
%% Cell type:markdown id: tags:
### Selecting variables with a file
If your variables of interest are listed in a plain-text file, you can simply pass that file:
%% Cell type:code id: tags:
``` bash
echo -e "1\n6\n9" > vars.txt
ukbparse -nb -q -ow -v vars.txt out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 6-0.0 9-0.0
1 31 22 90
2 56 35 50
3 45 36 48
4 7 20 37
5 8 84 69
6 6 46 73
7 24 23 7
8 80 83 6
9 84 12 2
10 23 20 59
%% Cell type:markdown id: tags:
### Selecting variables from pre-defined categories
Some UK BioBank-specific categories are baked into `ukbparse`, but you can also define your own categories - you just need to create a `.tsv` file, and pass it to `ukbparse` via the `--category_file` (`-cf` for short):
%% Cell type:code id: tags:
``` bash
echo -e "ID\tCategory\tVariables" > custom_categories.tsv
echo -e "1\tCool variables\t1:5,7" >> custom_categories.tsv
echo -e "2\tUncool variables\t6,8:10" >> custom_categories.tsv
```
%% Cell type:markdown id: tags:
Use the `--category` (`-c` for short) to select categories to output. You can refer to categories by their ID:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -cf custom_categories.tsv -c 1 out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 7-0.0
1 31 65 10 11 84 56
2 56 52 52 42 89 3
3 45 84 20 84 93 96
4 7 46 37 48 80 18
5 8 86 51 68 80 11
6 6 29 85 59 7 14
7 24 49 41 46 92 39
8 80 92 97 30 92 98
9 84 59 89 79 16 95
10 23 96 67 41 8 97
%% Cell type:markdown id: tags:
Or by name:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -cf custom_categories.tsv -c uncool out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 6-0.0 8-0.0 9-0.0 10-0.0
1 22 65 90 12
2 35 65 50 67
3 36 62 48 59
4 20 72 37 27
5 84 28 69 10
6 46 60 73 80
7 23 68 7 63
8 83 36 6 23
9 12 73 2 62
10 20 57 59 23
%% Cell type:markdown id: tags:
### Selecting column names
If you are working with data that has non-UK BioBank style column names, you can use the `--column` (`-co` for short) to select individual columns by their name, rather than the variable with which they are associated. The `--column` option accepts full column names, and also shell-style wildcard patterns:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -co 4-0.0 -co "??-0.0" out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 4-0.0 10-0.0
1 11 12
2 42 67
3 84 59
4 48 27
5 68 10
6 59 80
7 46 63
8 30 23
9 79 62
10 41 23
%% Cell type:markdown id: tags:
## Selecting subjects (rows)
`ukbparse` assumes that the first column in every input file is a subject ID. You can specify which subjects you want to load via the `--subject` (`-s` for short) option. You can specify subjects in the same way that you specified variables above, and also:
* By specifying a conditional expression on variable values - only subjects for which the expression evaluates to true will be imported
* By specifying subjects to exclude
### Selecting individual subjects
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -s 1 -s 3 -s 5 out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0 7-0.0 8-0.0 9-0.0 10-0.0
1 31 65 10 11 84 22 56 65 90 12
3 45 84 20 84 93 36 96 62 48 59
5 8 86 51 68 80 84 11 28 69 10
%% Cell type:markdown id: tags:
### Selecting subject ranges
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -s 2:2:10 out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0 7-0.0 8-0.0 9-0.0 10-0.0
2 56 52 52 42 89 35 3 65 50 67
4 7 46 37 48 80 20 18 72 37 27
6 6 29 85 59 7 46 14 60 73 80
8 80 92 97 30 92 83 98 36 6 23
10 23 96 67 41 8 20 97 57 59 23
%% Cell type:markdown id: tags:
### Selecting subjects from a file
%% Cell type:code id: tags:
``` bash
echo -e "5\n6\n7\n8\n9\n10" > subjects.txt
ukbparse -nb -q -ow -s subjects.txt out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0 7-0.0 8-0.0 9-0.0 10-0.0
5 8 86 51 68 80 84 11 28 69 10
6 6 29 85 59 7 46 14 60 73 80
7 24 49 41 46 92 23 39 68 7 63
8 80 92 97 30 92 83 98 36 6 23
9 84 59 89 79 16 12 95 73 2 62
10 23 96 67 41 8 20 97 57 59 23
%% Cell type:markdown id: tags:
### Selecting subjects by variable value
The `--subject` option accepts *variable expressions* - you can write an expression performing numerical comparisons on variables (denoted with a leading `v`) and combine these expressions using boolean algebra. Only subjects for which the expression evaluates to true will be imported. For example, to only import subjects where variable 1 is greater than 10, and variable 2 is less than 70, you can type:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -sp -s "v1 > 10 && v2 < 70" out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0 7-0.0 8-0.0 9-0.0 10-0.0
1 31 65 10 11 84 22 56 65 90 12
2 56 52 52 42 89 35 3 65 50 67
7 24 49 41 46 92 23 39 68 7 63
9 84 59 89 79 16 12 95 73 2 62
%% Cell type:markdown id: tags:
The following symbols can be used in variable expressions:
| Symbol | Meaning |
|---------------------------|--------------------------|
| `==` | equal to |
| `!=` | not equal to |
| `>` | greater than |
| `>=` | greater than or equal to |
| `<` | less than |
| `<=` | less than or equal to |
| `na` | N/A |
| `&&` | logical and |
| <code>&#x7c;&#x7c;</code> | logical or |
| `~` | logical not |
| `()` | To denote precedence |
### Excluding subjects
The `--exclude` (`-ex` for short) option allows you to exclude subjects - it accepts individual IDs, an ID range, or a file containing IDs. The `--exclude`/`-ex` option takes precedence over the `--subject`/`-s` option:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -s 1:8 -ex 5:10 out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0 7-0.0 8-0.0 9-0.0 10-0.0
1 31 65 10 11 84 22 56 65 90 12
2 56 52 52 42 89 35 3 65 50 67
3 45 84 20 84 93 36 96 62 48 59
4 7 46 37 48 80 20 18 72 37 27
%% Cell type:markdown id: tags:
## Selecting visits
%% Cell type:markdown id: tags:
Many variables in the UK BioBank data contain observations at multiple points in time, or visits. `ukbparse` allows you to specify which visits you are interested in. Here is an example data set with variables that have data for multiple visits (remember that the second number in the column names denotes the visit):
%% Cell type:code id: tags:
``` bash
cat data_02.tsv
```
%% Output
eid 1-0.0 2-0.0 2-1.0 2-2.0 3-0.0 3-1.0 4-0.0 5-0.0
1 86 76 82 75 34 99 50 5
2 20 25 40 44 30 57 54 44
3 85 2 48 42 23 77 84 27
4 23 30 18 97 44 55 97 20
5 83 45 76 51 18 64 8 33
%% Cell type:markdown id: tags:
We can use the `--visit` (`-vi` for short) option to get just the last visit for each variable:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -vi last out.tsv data_02.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-2.0 3-1.0 4-0.0 5-0.0
1 86 75 99 50 5
2 20 44 57 54 44
3 85 42 77 84 27
4 23 97 55 97 20
5 83 51 64 8 33
%% Cell type:markdown id: tags:
You can also specify which visit you want by its number:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -vi 1 out.tsv data_02.tsv
cat out.tsv
```
%% Output
eid 2-1.0 3-1.0
1 82 99
2 40 57
3 48 77
4 18 55
5 76 64
%% Cell type:markdown id: tags:
## Merging multiple input files
If your data is split across multiple files, you can specify how `ukbparse` should merge them together.
### Merging by subject
For example, let's say we have these two input files (shown side-by-side):
%% Cell type:code id: tags:
``` bash
echo " " | paste data_03.tsv - data_04.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 eid 4-0.0 5-0.0 6-0.0
1 89 47 26 2 19 17 62
2 94 37 70 3 41 12 7
3 63 5 97 4 8 86 9
4 98 97 91 5 7 65 71
5 37 10 11 6 3 23 15
%% Cell type:markdown id: tags:
Note that each file contains different variables, and different, but overlapping, subjects. By default, when you pass these files to `ukbparse`, it will output the intersection of the two files (more formally known as an *inner join*), i.e. subjects which are present in both files:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow out.tsv data_03.tsv data_04.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0
2 94 37 70 19 17 62
3 63 5 97 41 12 7
4 98 97 91 8 86 9
5 37 10 11 7 65 71
%% Cell type:markdown id: tags:
If you want to keep all subjects, you can instruct `ukbparse` to output the union (a.k.a. *outer join*) via the `--merge_strategy` (`-ms` for short) option:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -ms outer out.tsv data_03.tsv data_04.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0
1 89.0 47.0 26.0
2 94.0 37.0 70.0 19.0 17.0 62.0
3 63.0 5.0 97.0 41.0 12.0 7.0
4 98.0 97.0 91.0 8.0 86.0 9.0
5 37.0 10.0 11.0 7.0 65.0 71.0
6 3.0 23.0 15.0
%% Cell type:markdown id: tags:
### Merging by column
Your data may be organised in a different way. For example, these next two files contain different groups of subjects, but overlapping columns:
%% Cell type:code id: tags:
``` bash
echo " " | paste data_05.tsv - data_06.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 eid 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0
1 69 80 70 60 42 4 17 36 56 90 12
2 64 15 82 99 67 5 63 16 87 57 63
3 33 67 58 96 26 6 43 19 84 53 63
%% Cell type:markdown id: tags:
In this case, we need to tell `ukbparse` to merge along the row axis, rather than along the column axis. We can do this with the `--merge_axis` (`-ma` for short) option:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -ma rows out.tsv data_05.tsv data_06.tsv
cat out.tsv
```
%% Output
eid 2-0.0 3-0.0 4-0.0 5-0.0
1 80 70 60 42
2 15 82 99 67
3 67 58 96 26
4 17 36 56 90
5 63 16 87 57
6 43 19 84 53
%% Cell type:markdown id: tags:
Again, if we want to retain all columns, we can tell `ukbparse` to perform an outer join with the `-ms` option:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -ma rows -ms outer out.tsv data_05.tsv data_06.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0
1 69.0 80 70 60 42
2 64.0 15 82 99 67
3 33.0 67 58 96 26
4 17 36 56 90 12.0
5 63 16 87 57 63.0
6 43 19 84 53 63.0
%% Cell type:markdown id: tags:
### Naive merging
Finally, your data may be organised such that you simply want to "paste", or concatenate them together, along either rows or columns. For example, your data files might look like this:
%% Cell type:code id: tags:
``` bash
echo " " | paste data_07.tsv - data_08.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 eid 4-0.0 5-0.0 6-0.0
1 30 99 57 1 16 54 60
2 3 6 75 2 43 59 9
3 13 91 36 3 71 73 38
%% Cell type:markdown id: tags:
Here, we have columns for different variables on the same set of subjects, and we just need to concatenate them together horizontally. We do this by using `--merge_strategy naive` (`-ms naive` for short):
%% Cell type:code id: tags:
``` bash
ukbparse -q -ow -ms naive out.tsv data_07.tsv data_08.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0
1 30 99 57.0 16.0 54.0 60.0
2 3 6 75.0 43.0 59.0 9.0
3 13 91 36.0 71.0 73.0 38.0
%% Cell type:markdown id: tags:
For files which need to be concatenated vertically, such as these:
%% Cell type:code id: tags:
``` bash
echo " " | paste data_09.tsv - data_10.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 eid 1-0.0 2-0.0 3-0.0
1 16 34 10 4 40 89 58
2 62 78 16 5 25 75 9
3 72 29 53 6 28 74 57
%% Cell type:markdown id: tags:
We need to tell `ukbparse` which axis to concatenate along, again using the `-ma` option:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -ms naive -ma rows out.tsv data_09.tsv data_10.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0
1 16 34 10
2 62 78 16
3 72 29 53
4 40 89 58
5 25 75 9
6 28 74 57
%% Cell type:markdown id: tags:
# Cleaning examples
Once the data has been imported, a sequence of cleaning steps are applied to each column.
## NA insertion
For some variables it may make sense to discard or ignore certain values. For example, if an individual selects *"Do not know"* to a question such as *"How much milk did you drink yesterday?"*, that answer will be coded with a specific value (e.g. `-1`). It does not make any sense to included these values in most analyses, so `ukbparse` can be used to mark such values as *Not Available (NA)*.
A large number of NA insertion rules, specific to UK BioBank variables, are coded into `ukbparse` (although they will not be used in these examples, as we are using the `--no_builtins`/`-nb` option). You can also specify your own rules via the `--na_values` (`-nv` for short) option.
Let's say we have this data set:
%% Cell type:code id: tags:
``` bash
cat data_11.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0
1 4 1 6
2 2 6 0
3 7 0 -1
4 -1 6 1
5 2 8 4
6 0 2 7
7 -1 0 0
8 7 7 2
9 4 -1 -1
10 8 -1 2
%% Cell type:markdown id: tags:
For variable 1, we want to ignore values of -1, for variable 2 we want to ignore -1 and 0, and for variable 3 we want to ignore 1 and 2:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -nv 1 " -1" -nv 2 " -1,0" -nv 3 "1,2" out.tsv data_11.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0
1 4.0 1.0 6.0
2 2.0 6.0 0.0
3 7.0 -1.0
4 6.0
5 2.0 8.0 4.0
6 0.0 2.0 7.0
7 0.0
8 7.0 7.0
9 4.0 -1.0
10 8.0
%% Cell type:markdown id: tags:
> The `--na_values` option expects two arguments:
> * The variable ID
> * A comma-separated list of values to replace with NA
%% Cell type:markdown id: tags:
## Variable-specific cleaning functions
A small number of cleaning/preprocessing functions are built into `ukbparse`, which can be applied to specific variables. For example, some variables in the UK BioBank contain ICD10 disease codes, which may be more useful if converted to a numeric format. Imagine that we have some data with ICD10 codes:
%% Cell type:code id: tags:
``` bash
cat data_12.tsv
```
%% Output
eid 1-0.0
1 A481
2 A590
3 B391
4 D596
5 Z980
%% Cell type:markdown id: tags:
We can use the `--clean` (`-cl` for short) option with the built-in `convertICD10Codes` cleaning function to convert the codes to a numeric representation:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -cl 1 convertICD10Codes out.tsv data_12.tsv
cat out.tsv
```
%% Output
eid 1-0.0
1 11481
2 11590
3 12391
4 14596
5 36980
%% Cell type:markdown id: tags:
> The `--clean` option expects two arguments:
> * The variable ID
> * The cleaning function to apply. Some cleaning functions accept arguments - refer to the command-line help for a summary of available functions.
>
> You can define your own cleaning functions by passing them in as a `--plugin_file` (see the [section on custom plugins below](#Custom-cleaning,-processing-and-loading----ukbparse-plugins)).
### Example: flattening hierarchical data
Several variables in the UK Biobank (including the ICD10 disease categorisations) are organised in a hierarchical manner - each value is a child of a more general parent category. The `flattenHierarchical` cleaninng function can be used to replace each value in a data set with the value that corresponds to a parent category. Let's apply this to our example ICD10 data set.
> `ukbparse` needs to know the data coding of hierarchical variables, as it uses this to look up an internal table containing the hierarchy information. So in this example we are creating a dummy variable table file which tells `ukbparse` that the example data uses [data coding 19](https://biobank.ctsu.ox.ac.uk/crystal/coding.cgi?id=19), which is the ICD10 data coding.
%% Cell type:code id: tags:
``` bash
echo -e "ID\tType\tDescription\tDataCoding\tNAValues\tRawLevels\tNewLevels\tParentValues\tChildValues\tClean
1\t\t\t19
" > variables.tsv
ukbparse -nb -q -ow -vf variables.tsv -cl 1 flattenHierarchical out.tsv data_12.tsv
cat out.tsv
```
%% Output
eid 1-0.0
1 Chapter I
2 Chapter I
3 Chapter I
4 Chapter III
5 Chapter XXI
%% Cell type:markdown id: tags:
### Aside: ICD10 mapping file
`ukbparse` has a feature specific to these ICD10 disease categorisations - you can use the `--icd10_map_file` (`-imf` for short) option to tell `ukbparse` to save a file which contains a list of all ICD10 codes that were present in the input data, and the corresponding numerical codes that `ukbparse` generated:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -cl 1 convertICD10Codes -imf icd10_codes.tsv out.tsv data_12.tsv
cat icd10_codes.tsv
```
%% Output
code value description parent_descs
A481 11481 A48.1 Legionnaires' disease [Chapter I Certain infectious and parasitic diseases] [A30-A49 Other bacterial diseases] [A48 Other bacterial diseases, not elsewhere classified]
A590 11590 A59.0 Urogenital trichomoniasis [Chapter I Certain infectious and parasitic diseases] [A50-A64 Infections with a predominantly sexual mode of transmission] [A59 Trichomoniasis]
B391 12391 B39.1 Chronic pulmonary histoplasmosis capsulati [Chapter I Certain infectious and parasitic diseases] [B35-B49 Mycoses] [B39 Histoplasmosis]
D596 14596 D59.6 Haemoglobinuria due to haemolysis from other external causes [Chapter III Diseases of the blood and blood-forming organs and certain disorders involving the immune mechanism] [D55-D59 Haemolytic anaemias] [D59 Acquired haemolytic anaemia]
Z980 36980 Z98.0 Intestinal bypass and anastomosis status [Chapter XXI Factors influencing health status and contact with health services] [Z80-Z99 Persons with potential health hazards related to family and personal history and certain conditions influencing health status] [Z98 Other postsurgical states]
%% Cell type:markdown id: tags:
## Categorical recoding
%% Cell type:markdown id: tags:
You may have some categorical data which is coded in an awkward manner, such as in this example, which encodes the amount of some item that an individual has consumed:
<img src="attachment:image.png" width="100"/>
You can use the `--recoding` (`-re` for short) option to recode data like this into something more useful. For example, given this data:
%% Cell type:code id: tags:
``` bash
cat data_13.tsv
```
%% Output
eid 1-0.0
1 1
2 555
3 444
4 2
5 300
6 444
7 2
8 2
%% Cell type:markdown id: tags:
Let's recode it to be more monotonic:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -re 1 "300,444,555" "3,0.25,0.5" out.tsv data_13.tsv
cat out.tsv
```
%% Output
eid 1-0.0
1 1.0
2 0.5
3 0.25
4 2.0
5 3.0
6 0.25
7 2.0
8 2.0
%% Cell type:markdown id: tags:
The `--recoding` option expects three arguments:
* The variable ID
* A comma-separated list of the values to be replaced
* A comma-separated list of the values to replace them with
%% Cell type:markdown id: tags:
## Child value replacement
Imagine that we have these two questions:
* **1**: *Do you currently smoke cigarettes?*
* **2**: *How many cigarettes did you smoke yesterday?*
Now, question 2 was only asked if the answer to question 1 was *"Yes"*. So for all individuals who answered *"No"* to question 1, we will have a missing value for question 2. But for some analyses, it would make more sense to have a value of 0, rather than NA, for these subjects.
`ukbparse` can handle these sorts of dependencies by way of *child value replacement*. For question 2, we can define a conditional variable expression such that when both question 2 is NA and question 1 is *"No"*, we can insert a value of 0 into question 2.
This scenario is demonstrated in this example data set (where, for question 1 values of `1` and `0` represent *"Yes"* and *"No"* respectively):
%% Cell type:code id: tags:
``` bash
cat data_14.tsv
```
%% Output
eid 1-0.0 2-0.0
1 1 7
2 1 4
3 1 1
4 0
5 0
6 0
7 1 25
8 0
%% Cell type:markdown id: tags:
We can fill in the values for variable 2 by using the `--child_values` (`-cv` for short) option:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -cv 2 "v1 == 0" "0" out.tsv data_14.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0
1 1 7.0
2 1 4.0
3 1 1.0
4 0 0.0
5 0 0.0
6 0 0.0
7 1 25.0
8 0 0.0
%% Cell type:markdown id: tags:
> The `--child_values` option expects three arguments:
> * The variable ID
> * An expression evaluating some condition on the parent variable(s)
> * A value to replace NA with where the expression evaluates to true.
%% Cell type:markdown id: tags:
# Processing examples
After every column has been cleaned, the entire data set undergoes a series of processing steps. The processing stage may result in columns being removed or manipulated, or new columns being added.
The processing stage can be controlled with these options:
* `--prepend_process` (`-ppr` for short): Apply a processing function before the built-in processing
* `--append_process` (`-apr` for short): Apply a processing function after the built-in processing
(But remember that in these examples we are using the `--no_builtins`/`-nb` option, so the built-in processing steps are not applied.)
The `--prepend_process` and `--append_process` options require two arguments:
* The variable ID(s) to apply the function to, or `all` to denote all variables.
* The processing function to apply. The available processing functions are listed in the command line help, or you can write your own and pass it in as a plugin file ([see below](#Custom-cleaning,-processing-and-loading----ukbparse-plugins)).
## Sparsity check
The `removeIfSparse` process will remove columns that are deemed to have too many missing values. If we take this data set:
%% Cell type:code id: tags:
``` bash
cat data_15.tsv
```
%% Output
eid 1-0.0 2-0.0
1 7 24
2 2 37