convert from tsv to json with case enforcement
@@ -8,6 +8,8 @@ Utilities
from __future__ import absolute_import, division, print_function, unicode_literals
import os
+import re
+import json
import shutil
import numpy as np
import nibabel as nb
@@ -703,6 +705,46 @@ class JoinTSVColumns(SimpleInterface):
return runtime
+def _tsv2json(in_tsv, out_json, index_column, additional_metadata=None,
+ drop_columns=None, enforce_case=True):
+ # Taken from https://dev.to/rrampage/snake-case-to-camel-case-and- ...
+ # back-using-regular-expressions-and-python-m9j
+ re_to_camel = r'(.*?)_([a-zA-Z0-9])'
+ re_to_snake = r'(.+?)([A-Z0-9])'
+
+ def snake(match):
+ return '{}_{}'.format(match.group(1).lower(), match.group(2).lower())
+ def camel(match):
+ return '{}{}'.format(match.group(1), match.group(2).upper())
+
+ # from fmriprep
+ def less_breakable(a_string):
+ ''' hardens the string to different envs (i.e. case insensitive, no whitespace, '#' '''
+ return ''.join(a_string.split()).strip('#')
+
+ drop_columns = drop_columns or []
+ additional_metadata = additional_metadata or {}
+ tsv_data = pd.read_csv(in_tsv, '\t')
+ for k, v in additional_metadata.items():
+ tsv_data[k] = v
+ for col in drop_columns:
+ tsv_data.drop(labels=col, axis='columns', inplace=True)
+ tsv_data.set_index(index_column, drop=True, inplace=True)
+ if enforce_case:
+ tsv_data.index = [re.sub(re_to_snake, snake, less_breakable(i), 0)
+ for i in tsv_data.index]
+ tsv_data.columns = [re.sub(re_to_camel, camel,
+ less_breakable(i).title(), 0)
+ for i in tsv_data.columns]
+ json_data = tsv_data.to_json(orient='index')
+ json_data = json.JSONDecoder(
+ object_pairs_hook=OrderedDict).decode(json_data)
+
+ with open(out_json, 'w') as f:
+ json.dump(json_data, f, indent=4)
+ return out_json
+
+
def _tpm2roi(in_tpm, in_mask, mask_erosion_mm=None, erosion_mm=None,
mask_erosion_prop=None, erosion_prop=None, pthres=0.95,
newpath=None):
