repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
icometrix/dicom2nifti
dicom2nifti/common.py
write_bval_file
def write_bval_file(bvals, bval_file): """ Write an array of bvals to a bval file :param bvals: array with the values :param bval_file: filepath to write to """ if bval_file is None: return logger.info('Saving BVAL file: %s' % bval_file) with open(bval_file, 'w') as text_file: # join the bvals using a space and write to the file text_file.write('%s\n' % ' '.join(map(str, bvals)))
python
def write_bval_file(bvals, bval_file): if bval_file is None: return logger.info('Saving BVAL file: %s' % bval_file) with open(bval_file, 'w') as text_file: text_file.write('%s\n' % ' '.join(map(str, bvals)))
[ "def", "write_bval_file", "(", "bvals", ",", "bval_file", ")", ":", "if", "bval_file", "is", "None", ":", "return", "logger", ".", "info", "(", "'Saving BVAL file: %s'", "%", "bval_file", ")", "with", "open", "(", "bval_file", ",", "'w'", ")", "as", "text_file", ":", "# join the bvals using a space and write to the file", "text_file", ".", "write", "(", "'%s\\n'", "%", "' '", ".", "join", "(", "map", "(", "str", ",", "bvals", ")", ")", ")" ]
Write an array of bvals to a bval file :param bvals: array with the values :param bval_file: filepath to write to
[ "Write", "an", "array", "of", "bvals", "to", "a", "bval", "file" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L495-L507
icometrix/dicom2nifti
dicom2nifti/common.py
create_affine
def create_affine(sorted_dicoms): """ Function to generate the affine matrix for a dicom series This method was based on (http://nipy.org/nibabel/dicom/dicom_orientation.html) :param sorted_dicoms: list with sorted dicom files """ # Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine) image_orient1 = numpy.array(sorted_dicoms[0].ImageOrientationPatient)[0:3] image_orient2 = numpy.array(sorted_dicoms[0].ImageOrientationPatient)[3:6] delta_r = float(sorted_dicoms[0].PixelSpacing[0]) delta_c = float(sorted_dicoms[0].PixelSpacing[1]) image_pos = numpy.array(sorted_dicoms[0].ImagePositionPatient) last_image_pos = numpy.array(sorted_dicoms[-1].ImagePositionPatient) if len(sorted_dicoms) == 1: # Single slice step = [0, 0, -1] else: step = (image_pos - last_image_pos) / (1 - len(sorted_dicoms)) # check if this is actually a volume and not all slices on the same location if numpy.linalg.norm(step) == 0.0: raise ConversionError("NOT_A_VOLUME") affine = numpy.array( [[-image_orient1[0] * delta_c, -image_orient2[0] * delta_r, -step[0], -image_pos[0]], [-image_orient1[1] * delta_c, -image_orient2[1] * delta_r, -step[1], -image_pos[1]], [image_orient1[2] * delta_c, image_orient2[2] * delta_r, step[2], image_pos[2]], [0, 0, 0, 1]] ) return affine, numpy.linalg.norm(step)
python
def create_affine(sorted_dicoms): image_orient1 = numpy.array(sorted_dicoms[0].ImageOrientationPatient)[0:3] image_orient2 = numpy.array(sorted_dicoms[0].ImageOrientationPatient)[3:6] delta_r = float(sorted_dicoms[0].PixelSpacing[0]) delta_c = float(sorted_dicoms[0].PixelSpacing[1]) image_pos = numpy.array(sorted_dicoms[0].ImagePositionPatient) last_image_pos = numpy.array(sorted_dicoms[-1].ImagePositionPatient) if len(sorted_dicoms) == 1: step = [0, 0, -1] else: step = (image_pos - last_image_pos) / (1 - len(sorted_dicoms)) if numpy.linalg.norm(step) == 0.0: raise ConversionError("NOT_A_VOLUME") affine = numpy.array( [[-image_orient1[0] * delta_c, -image_orient2[0] * delta_r, -step[0], -image_pos[0]], [-image_orient1[1] * delta_c, -image_orient2[1] * delta_r, -step[1], -image_pos[1]], [image_orient1[2] * delta_c, image_orient2[2] * delta_r, step[2], image_pos[2]], [0, 0, 0, 1]] ) return affine, numpy.linalg.norm(step)
[ "def", "create_affine", "(", "sorted_dicoms", ")", ":", "# Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine)", "image_orient1", "=", "numpy", ".", "array", "(", "sorted_dicoms", "[", "0", "]", ".", "ImageOrientationPatient", ")", "[", "0", ":", "3", "]", "image_orient2", "=", "numpy", ".", "array", "(", "sorted_dicoms", "[", "0", "]", ".", "ImageOrientationPatient", ")", "[", "3", ":", "6", "]", "delta_r", "=", "float", "(", "sorted_dicoms", "[", "0", "]", ".", "PixelSpacing", "[", "0", "]", ")", "delta_c", "=", "float", "(", "sorted_dicoms", "[", "0", "]", ".", "PixelSpacing", "[", "1", "]", ")", "image_pos", "=", "numpy", ".", "array", "(", "sorted_dicoms", "[", "0", "]", ".", "ImagePositionPatient", ")", "last_image_pos", "=", "numpy", ".", "array", "(", "sorted_dicoms", "[", "-", "1", "]", ".", "ImagePositionPatient", ")", "if", "len", "(", "sorted_dicoms", ")", "==", "1", ":", "# Single slice", "step", "=", "[", "0", ",", "0", ",", "-", "1", "]", "else", ":", "step", "=", "(", "image_pos", "-", "last_image_pos", ")", "/", "(", "1", "-", "len", "(", "sorted_dicoms", ")", ")", "# check if this is actually a volume and not all slices on the same location", "if", "numpy", ".", "linalg", ".", "norm", "(", "step", ")", "==", "0.0", ":", "raise", "ConversionError", "(", "\"NOT_A_VOLUME\"", ")", "affine", "=", "numpy", ".", "array", "(", "[", "[", "-", "image_orient1", "[", "0", "]", "*", "delta_c", ",", "-", "image_orient2", "[", "0", "]", "*", "delta_r", ",", "-", "step", "[", "0", "]", ",", "-", "image_pos", "[", "0", "]", "]", ",", "[", "-", "image_orient1", "[", "1", "]", "*", "delta_c", ",", "-", "image_orient2", "[", "1", "]", "*", "delta_r", ",", "-", "step", "[", "1", "]", ",", "-", "image_pos", "[", "1", "]", "]", ",", "[", "image_orient1", "[", "2", "]", "*", "delta_c", ",", "image_orient2", "[", "2", "]", "*", "delta_r", ",", "step", "[", "2", "]", ",", "image_pos", "[", "2", "]", "]", ",", "[", "0", ",", "0", ",", "0", ",", "1", "]", "]", ")", "return", "affine", ",", "numpy", ".", "linalg", ".", "norm", "(", "step", ")" ]
Function to generate the affine matrix for a dicom series This method was based on (http://nipy.org/nibabel/dicom/dicom_orientation.html) :param sorted_dicoms: list with sorted dicom files
[ "Function", "to", "generate", "the", "affine", "matrix", "for", "a", "dicom", "series", "This", "method", "was", "based", "on", "(", "http", ":", "//", "nipy", ".", "org", "/", "nibabel", "/", "dicom", "/", "dicom_orientation", ".", "html", ")" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L510-L545
icometrix/dicom2nifti
dicom2nifti/common.py
is_orthogonal
def is_orthogonal(dicoms, log_details=False): """ Validate that volume is orthonormal :param dicoms: check that we have a volume without skewing """ first_image_orient1 = numpy.array(dicoms[0].ImageOrientationPatient)[0:3] first_image_orient2 = numpy.array(dicoms[0].ImageOrientationPatient)[3:6] first_image_pos = numpy.array(dicoms[0].ImagePositionPatient) last_image_pos = numpy.array(dicoms[-1].ImagePositionPatient) first_image_dir = numpy.cross(first_image_orient1, first_image_orient2) first_image_dir /= numpy.linalg.norm(first_image_dir) combined_dir = last_image_pos - first_image_pos combined_dir /= numpy.linalg.norm(combined_dir) if not numpy.allclose(first_image_dir, combined_dir, rtol=0.05, atol=0.05) \ and not numpy.allclose(first_image_dir, -combined_dir, rtol=0.05, atol=0.05): if log_details: logger.warning('Orthogonality check failed: non cubical image') logger.warning('---------------------------------------------------------') logger.warning(first_image_dir) logger.warning(combined_dir) logger.warning('---------------------------------------------------------') return False return True
python
def is_orthogonal(dicoms, log_details=False): first_image_orient1 = numpy.array(dicoms[0].ImageOrientationPatient)[0:3] first_image_orient2 = numpy.array(dicoms[0].ImageOrientationPatient)[3:6] first_image_pos = numpy.array(dicoms[0].ImagePositionPatient) last_image_pos = numpy.array(dicoms[-1].ImagePositionPatient) first_image_dir = numpy.cross(first_image_orient1, first_image_orient2) first_image_dir /= numpy.linalg.norm(first_image_dir) combined_dir = last_image_pos - first_image_pos combined_dir /= numpy.linalg.norm(combined_dir) if not numpy.allclose(first_image_dir, combined_dir, rtol=0.05, atol=0.05) \ and not numpy.allclose(first_image_dir, -combined_dir, rtol=0.05, atol=0.05): if log_details: logger.warning('Orthogonality check failed: non cubical image') logger.warning('---------------------------------------------------------') logger.warning(first_image_dir) logger.warning(combined_dir) logger.warning('---------------------------------------------------------') return False return True
[ "def", "is_orthogonal", "(", "dicoms", ",", "log_details", "=", "False", ")", ":", "first_image_orient1", "=", "numpy", ".", "array", "(", "dicoms", "[", "0", "]", ".", "ImageOrientationPatient", ")", "[", "0", ":", "3", "]", "first_image_orient2", "=", "numpy", ".", "array", "(", "dicoms", "[", "0", "]", ".", "ImageOrientationPatient", ")", "[", "3", ":", "6", "]", "first_image_pos", "=", "numpy", ".", "array", "(", "dicoms", "[", "0", "]", ".", "ImagePositionPatient", ")", "last_image_pos", "=", "numpy", ".", "array", "(", "dicoms", "[", "-", "1", "]", ".", "ImagePositionPatient", ")", "first_image_dir", "=", "numpy", ".", "cross", "(", "first_image_orient1", ",", "first_image_orient2", ")", "first_image_dir", "/=", "numpy", ".", "linalg", ".", "norm", "(", "first_image_dir", ")", "combined_dir", "=", "last_image_pos", "-", "first_image_pos", "combined_dir", "/=", "numpy", ".", "linalg", ".", "norm", "(", "combined_dir", ")", "if", "not", "numpy", ".", "allclose", "(", "first_image_dir", ",", "combined_dir", ",", "rtol", "=", "0.05", ",", "atol", "=", "0.05", ")", "and", "not", "numpy", ".", "allclose", "(", "first_image_dir", ",", "-", "combined_dir", ",", "rtol", "=", "0.05", ",", "atol", "=", "0.05", ")", ":", "if", "log_details", ":", "logger", ".", "warning", "(", "'Orthogonality check failed: non cubical image'", ")", "logger", ".", "warning", "(", "'---------------------------------------------------------'", ")", "logger", ".", "warning", "(", "first_image_dir", ")", "logger", ".", "warning", "(", "combined_dir", ")", "logger", ".", "warning", "(", "'---------------------------------------------------------'", ")", "return", "False", "return", "True" ]
Validate that volume is orthonormal :param dicoms: check that we have a volume without skewing
[ "Validate", "that", "volume", "is", "orthonormal" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L558-L585
icometrix/dicom2nifti
dicom2nifti/common.py
is_orthogonal_nifti
def is_orthogonal_nifti(nifti_file): """ Validate that volume is orthonormal :param dicoms: check that we have a volume without skewing """ nifti_image = nibabel.load(nifti_file) affine = nifti_image.affine transformed_x = numpy.transpose(numpy.dot(affine, [[1], [0], [0], [0]]))[0][:3] transformed_y = numpy.transpose(numpy.dot(affine, [[0], [1], [0], [0]]))[0][:3] transformed_z = numpy.transpose(numpy.dot(affine, [[0], [0], [1], [0]]))[0][:3] transformed_x /= numpy.linalg.norm(transformed_x) transformed_y /= numpy.linalg.norm(transformed_y) transformed_z /= numpy.linalg.norm(transformed_z) perpendicular = numpy.cross(transformed_x, transformed_y) perpendicular /= numpy.linalg.norm(perpendicular) if not numpy.allclose(transformed_z, perpendicular, rtol=0.05, atol=0.05) \ and not numpy.allclose(transformed_z, -perpendicular, rtol=0.05, atol=0.05): return False return True
python
def is_orthogonal_nifti(nifti_file): nifti_image = nibabel.load(nifti_file) affine = nifti_image.affine transformed_x = numpy.transpose(numpy.dot(affine, [[1], [0], [0], [0]]))[0][:3] transformed_y = numpy.transpose(numpy.dot(affine, [[0], [1], [0], [0]]))[0][:3] transformed_z = numpy.transpose(numpy.dot(affine, [[0], [0], [1], [0]]))[0][:3] transformed_x /= numpy.linalg.norm(transformed_x) transformed_y /= numpy.linalg.norm(transformed_y) transformed_z /= numpy.linalg.norm(transformed_z) perpendicular = numpy.cross(transformed_x, transformed_y) perpendicular /= numpy.linalg.norm(perpendicular) if not numpy.allclose(transformed_z, perpendicular, rtol=0.05, atol=0.05) \ and not numpy.allclose(transformed_z, -perpendicular, rtol=0.05, atol=0.05): return False return True
[ "def", "is_orthogonal_nifti", "(", "nifti_file", ")", ":", "nifti_image", "=", "nibabel", ".", "load", "(", "nifti_file", ")", "affine", "=", "nifti_image", ".", "affine", "transformed_x", "=", "numpy", ".", "transpose", "(", "numpy", ".", "dot", "(", "affine", ",", "[", "[", "1", "]", ",", "[", "0", "]", ",", "[", "0", "]", ",", "[", "0", "]", "]", ")", ")", "[", "0", "]", "[", ":", "3", "]", "transformed_y", "=", "numpy", ".", "transpose", "(", "numpy", ".", "dot", "(", "affine", ",", "[", "[", "0", "]", ",", "[", "1", "]", ",", "[", "0", "]", ",", "[", "0", "]", "]", ")", ")", "[", "0", "]", "[", ":", "3", "]", "transformed_z", "=", "numpy", ".", "transpose", "(", "numpy", ".", "dot", "(", "affine", ",", "[", "[", "0", "]", ",", "[", "0", "]", ",", "[", "1", "]", ",", "[", "0", "]", "]", ")", ")", "[", "0", "]", "[", ":", "3", "]", "transformed_x", "/=", "numpy", ".", "linalg", ".", "norm", "(", "transformed_x", ")", "transformed_y", "/=", "numpy", ".", "linalg", ".", "norm", "(", "transformed_y", ")", "transformed_z", "/=", "numpy", ".", "linalg", ".", "norm", "(", "transformed_z", ")", "perpendicular", "=", "numpy", ".", "cross", "(", "transformed_x", ",", "transformed_y", ")", "perpendicular", "/=", "numpy", ".", "linalg", ".", "norm", "(", "perpendicular", ")", "if", "not", "numpy", ".", "allclose", "(", "transformed_z", ",", "perpendicular", ",", "rtol", "=", "0.05", ",", "atol", "=", "0.05", ")", "and", "not", "numpy", ".", "allclose", "(", "transformed_z", ",", "-", "perpendicular", ",", "rtol", "=", "0.05", ",", "atol", "=", "0.05", ")", ":", "return", "False", "return", "True" ]
Validate that volume is orthonormal :param dicoms: check that we have a volume without skewing
[ "Validate", "that", "volume", "is", "orthonormal" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L588-L611
icometrix/dicom2nifti
dicom2nifti/common.py
sort_dicoms
def sort_dicoms(dicoms): """ Sort the dicoms based om the image possition patient :param dicoms: list of dicoms """ # find most significant axis to use during sorting # the original way of sorting (first x than y than z) does not work in certain border situations # where for exampe the X will only slightly change causing the values to remain equal on multiple slices # messing up the sorting completely) dicom_input_sorted_x = sorted(dicoms, key=lambda x: (x.ImagePositionPatient[0])) dicom_input_sorted_y = sorted(dicoms, key=lambda x: (x.ImagePositionPatient[1])) dicom_input_sorted_z = sorted(dicoms, key=lambda x: (x.ImagePositionPatient[2])) diff_x = abs(dicom_input_sorted_x[-1].ImagePositionPatient[0] - dicom_input_sorted_x[0].ImagePositionPatient[0]) diff_y = abs(dicom_input_sorted_y[-1].ImagePositionPatient[1] - dicom_input_sorted_y[0].ImagePositionPatient[1]) diff_z = abs(dicom_input_sorted_z[-1].ImagePositionPatient[2] - dicom_input_sorted_z[0].ImagePositionPatient[2]) if diff_x >= diff_y and diff_x >= diff_z: return dicom_input_sorted_x if diff_y >= diff_x and diff_y >= diff_z: return dicom_input_sorted_y if diff_z >= diff_x and diff_z >= diff_y: return dicom_input_sorted_z
python
def sort_dicoms(dicoms): dicom_input_sorted_x = sorted(dicoms, key=lambda x: (x.ImagePositionPatient[0])) dicom_input_sorted_y = sorted(dicoms, key=lambda x: (x.ImagePositionPatient[1])) dicom_input_sorted_z = sorted(dicoms, key=lambda x: (x.ImagePositionPatient[2])) diff_x = abs(dicom_input_sorted_x[-1].ImagePositionPatient[0] - dicom_input_sorted_x[0].ImagePositionPatient[0]) diff_y = abs(dicom_input_sorted_y[-1].ImagePositionPatient[1] - dicom_input_sorted_y[0].ImagePositionPatient[1]) diff_z = abs(dicom_input_sorted_z[-1].ImagePositionPatient[2] - dicom_input_sorted_z[0].ImagePositionPatient[2]) if diff_x >= diff_y and diff_x >= diff_z: return dicom_input_sorted_x if diff_y >= diff_x and diff_y >= diff_z: return dicom_input_sorted_y if diff_z >= diff_x and diff_z >= diff_y: return dicom_input_sorted_z
[ "def", "sort_dicoms", "(", "dicoms", ")", ":", "# find most significant axis to use during sorting", "# the original way of sorting (first x than y than z) does not work in certain border situations", "# where for exampe the X will only slightly change causing the values to remain equal on multiple slices", "# messing up the sorting completely)", "dicom_input_sorted_x", "=", "sorted", "(", "dicoms", ",", "key", "=", "lambda", "x", ":", "(", "x", ".", "ImagePositionPatient", "[", "0", "]", ")", ")", "dicom_input_sorted_y", "=", "sorted", "(", "dicoms", ",", "key", "=", "lambda", "x", ":", "(", "x", ".", "ImagePositionPatient", "[", "1", "]", ")", ")", "dicom_input_sorted_z", "=", "sorted", "(", "dicoms", ",", "key", "=", "lambda", "x", ":", "(", "x", ".", "ImagePositionPatient", "[", "2", "]", ")", ")", "diff_x", "=", "abs", "(", "dicom_input_sorted_x", "[", "-", "1", "]", ".", "ImagePositionPatient", "[", "0", "]", "-", "dicom_input_sorted_x", "[", "0", "]", ".", "ImagePositionPatient", "[", "0", "]", ")", "diff_y", "=", "abs", "(", "dicom_input_sorted_y", "[", "-", "1", "]", ".", "ImagePositionPatient", "[", "1", "]", "-", "dicom_input_sorted_y", "[", "0", "]", ".", "ImagePositionPatient", "[", "1", "]", ")", "diff_z", "=", "abs", "(", "dicom_input_sorted_z", "[", "-", "1", "]", ".", "ImagePositionPatient", "[", "2", "]", "-", "dicom_input_sorted_z", "[", "0", "]", ".", "ImagePositionPatient", "[", "2", "]", ")", "if", "diff_x", ">=", "diff_y", "and", "diff_x", ">=", "diff_z", ":", "return", "dicom_input_sorted_x", "if", "diff_y", ">=", "diff_x", "and", "diff_y", ">=", "diff_z", ":", "return", "dicom_input_sorted_y", "if", "diff_z", ">=", "diff_x", "and", "diff_z", ">=", "diff_y", ":", "return", "dicom_input_sorted_z" ]
Sort the dicoms based om the image possition patient :param dicoms: list of dicoms
[ "Sort", "the", "dicoms", "based", "om", "the", "image", "possition", "patient" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L614-L635
icometrix/dicom2nifti
dicom2nifti/common.py
validate_slice_increment
def validate_slice_increment(dicoms): """ Validate that the distance between all slices is equal (or very close to) :param dicoms: list of dicoms """ first_image_position = numpy.array(dicoms[0].ImagePositionPatient) previous_image_position = numpy.array(dicoms[1].ImagePositionPatient) increment = first_image_position - previous_image_position for dicom_ in dicoms[2:]: current_image_position = numpy.array(dicom_.ImagePositionPatient) current_increment = previous_image_position - current_image_position if not numpy.allclose(increment, current_increment, rtol=0.05, atol=0.1): logger.warning('Slice increment not consistent through all slices') logger.warning('---------------------------------------------------------') logger.warning('%s %s' % (previous_image_position, increment)) logger.warning('%s %s' % (current_image_position, current_increment)) if 'InstanceNumber' in dicom_: logger.warning('Instance Number: %s' % dicom_.InstanceNumber) logger.warning('---------------------------------------------------------') raise ConversionValidationError('SLICE_INCREMENT_INCONSISTENT') previous_image_position = current_image_position
python
def validate_slice_increment(dicoms): first_image_position = numpy.array(dicoms[0].ImagePositionPatient) previous_image_position = numpy.array(dicoms[1].ImagePositionPatient) increment = first_image_position - previous_image_position for dicom_ in dicoms[2:]: current_image_position = numpy.array(dicom_.ImagePositionPatient) current_increment = previous_image_position - current_image_position if not numpy.allclose(increment, current_increment, rtol=0.05, atol=0.1): logger.warning('Slice increment not consistent through all slices') logger.warning('---------------------------------------------------------') logger.warning('%s %s' % (previous_image_position, increment)) logger.warning('%s %s' % (current_image_position, current_increment)) if 'InstanceNumber' in dicom_: logger.warning('Instance Number: %s' % dicom_.InstanceNumber) logger.warning('---------------------------------------------------------') raise ConversionValidationError('SLICE_INCREMENT_INCONSISTENT') previous_image_position = current_image_position
[ "def", "validate_slice_increment", "(", "dicoms", ")", ":", "first_image_position", "=", "numpy", ".", "array", "(", "dicoms", "[", "0", "]", ".", "ImagePositionPatient", ")", "previous_image_position", "=", "numpy", ".", "array", "(", "dicoms", "[", "1", "]", ".", "ImagePositionPatient", ")", "increment", "=", "first_image_position", "-", "previous_image_position", "for", "dicom_", "in", "dicoms", "[", "2", ":", "]", ":", "current_image_position", "=", "numpy", ".", "array", "(", "dicom_", ".", "ImagePositionPatient", ")", "current_increment", "=", "previous_image_position", "-", "current_image_position", "if", "not", "numpy", ".", "allclose", "(", "increment", ",", "current_increment", ",", "rtol", "=", "0.05", ",", "atol", "=", "0.1", ")", ":", "logger", ".", "warning", "(", "'Slice increment not consistent through all slices'", ")", "logger", ".", "warning", "(", "'---------------------------------------------------------'", ")", "logger", ".", "warning", "(", "'%s %s'", "%", "(", "previous_image_position", ",", "increment", ")", ")", "logger", ".", "warning", "(", "'%s %s'", "%", "(", "current_image_position", ",", "current_increment", ")", ")", "if", "'InstanceNumber'", "in", "dicom_", ":", "logger", ".", "warning", "(", "'Instance Number: %s'", "%", "dicom_", ".", "InstanceNumber", ")", "logger", ".", "warning", "(", "'---------------------------------------------------------'", ")", "raise", "ConversionValidationError", "(", "'SLICE_INCREMENT_INCONSISTENT'", ")", "previous_image_position", "=", "current_image_position" ]
Validate that the distance between all slices is equal (or very close to) :param dicoms: list of dicoms
[ "Validate", "that", "the", "distance", "between", "all", "slices", "is", "equal", "(", "or", "very", "close", "to", ")" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L638-L660
icometrix/dicom2nifti
dicom2nifti/common.py
is_slice_increment_inconsistent
def is_slice_increment_inconsistent(dicoms): """ Validate that the distance between all slices is equal (or very close to) :param dicoms: list of dicoms """ sliceincrement_inconsistent = False first_image_position = numpy.array(dicoms[0].ImagePositionPatient) previous_image_position = numpy.array(dicoms[1].ImagePositionPatient) increment = first_image_position - previous_image_position for dicom_ in dicoms[2:]: current_image_position = numpy.array(dicom_.ImagePositionPatient) current_increment = previous_image_position - current_image_position if not numpy.allclose(increment, current_increment, rtol=0.05, atol=0.1): sliceincrement_inconsistent = True break return sliceincrement_inconsistent
python
def is_slice_increment_inconsistent(dicoms): sliceincrement_inconsistent = False first_image_position = numpy.array(dicoms[0].ImagePositionPatient) previous_image_position = numpy.array(dicoms[1].ImagePositionPatient) increment = first_image_position - previous_image_position for dicom_ in dicoms[2:]: current_image_position = numpy.array(dicom_.ImagePositionPatient) current_increment = previous_image_position - current_image_position if not numpy.allclose(increment, current_increment, rtol=0.05, atol=0.1): sliceincrement_inconsistent = True break return sliceincrement_inconsistent
[ "def", "is_slice_increment_inconsistent", "(", "dicoms", ")", ":", "sliceincrement_inconsistent", "=", "False", "first_image_position", "=", "numpy", ".", "array", "(", "dicoms", "[", "0", "]", ".", "ImagePositionPatient", ")", "previous_image_position", "=", "numpy", ".", "array", "(", "dicoms", "[", "1", "]", ".", "ImagePositionPatient", ")", "increment", "=", "first_image_position", "-", "previous_image_position", "for", "dicom_", "in", "dicoms", "[", "2", ":", "]", ":", "current_image_position", "=", "numpy", ".", "array", "(", "dicom_", ".", "ImagePositionPatient", ")", "current_increment", "=", "previous_image_position", "-", "current_image_position", "if", "not", "numpy", ".", "allclose", "(", "increment", ",", "current_increment", ",", "rtol", "=", "0.05", ",", "atol", "=", "0.1", ")", ":", "sliceincrement_inconsistent", "=", "True", "break", "return", "sliceincrement_inconsistent" ]
Validate that the distance between all slices is equal (or very close to) :param dicoms: list of dicoms
[ "Validate", "that", "the", "distance", "between", "all", "slices", "is", "equal", "(", "or", "very", "close", "to", ")" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L663-L680
icometrix/dicom2nifti
dicom2nifti/common.py
validate_orientation
def validate_orientation(dicoms): """ Validate that all dicoms have the same orientation :param dicoms: list of dicoms """ first_image_orient1 = numpy.array(dicoms[0].ImageOrientationPatient)[0:3] first_image_orient2 = numpy.array(dicoms[0].ImageOrientationPatient)[3:6] for dicom_ in dicoms: # Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine) image_orient1 = numpy.array(dicom_.ImageOrientationPatient)[0:3] image_orient2 = numpy.array(dicom_.ImageOrientationPatient)[3:6] if not numpy.allclose(image_orient1, first_image_orient1, rtol=0.001, atol=0.001) \ or not numpy.allclose(image_orient2, first_image_orient2, rtol=0.001, atol=0.001): logger.warning('Image orientations not consistent through all slices') logger.warning('---------------------------------------------------------') logger.warning('%s %s' % (image_orient1, first_image_orient1)) logger.warning('%s %s' % (image_orient2, first_image_orient2)) logger.warning('---------------------------------------------------------') raise ConversionValidationError('IMAGE_ORIENTATION_INCONSISTENT')
python
def validate_orientation(dicoms): first_image_orient1 = numpy.array(dicoms[0].ImageOrientationPatient)[0:3] first_image_orient2 = numpy.array(dicoms[0].ImageOrientationPatient)[3:6] for dicom_ in dicoms: image_orient1 = numpy.array(dicom_.ImageOrientationPatient)[0:3] image_orient2 = numpy.array(dicom_.ImageOrientationPatient)[3:6] if not numpy.allclose(image_orient1, first_image_orient1, rtol=0.001, atol=0.001) \ or not numpy.allclose(image_orient2, first_image_orient2, rtol=0.001, atol=0.001): logger.warning('Image orientations not consistent through all slices') logger.warning('---------------------------------------------------------') logger.warning('%s %s' % (image_orient1, first_image_orient1)) logger.warning('%s %s' % (image_orient2, first_image_orient2)) logger.warning('---------------------------------------------------------') raise ConversionValidationError('IMAGE_ORIENTATION_INCONSISTENT')
[ "def", "validate_orientation", "(", "dicoms", ")", ":", "first_image_orient1", "=", "numpy", ".", "array", "(", "dicoms", "[", "0", "]", ".", "ImageOrientationPatient", ")", "[", "0", ":", "3", "]", "first_image_orient2", "=", "numpy", ".", "array", "(", "dicoms", "[", "0", "]", ".", "ImageOrientationPatient", ")", "[", "3", ":", "6", "]", "for", "dicom_", "in", "dicoms", ":", "# Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine)", "image_orient1", "=", "numpy", ".", "array", "(", "dicom_", ".", "ImageOrientationPatient", ")", "[", "0", ":", "3", "]", "image_orient2", "=", "numpy", ".", "array", "(", "dicom_", ".", "ImageOrientationPatient", ")", "[", "3", ":", "6", "]", "if", "not", "numpy", ".", "allclose", "(", "image_orient1", ",", "first_image_orient1", ",", "rtol", "=", "0.001", ",", "atol", "=", "0.001", ")", "or", "not", "numpy", ".", "allclose", "(", "image_orient2", ",", "first_image_orient2", ",", "rtol", "=", "0.001", ",", "atol", "=", "0.001", ")", ":", "logger", ".", "warning", "(", "'Image orientations not consistent through all slices'", ")", "logger", ".", "warning", "(", "'---------------------------------------------------------'", ")", "logger", ".", "warning", "(", "'%s %s'", "%", "(", "image_orient1", ",", "first_image_orient1", ")", ")", "logger", ".", "warning", "(", "'%s %s'", "%", "(", "image_orient2", ",", "first_image_orient2", ")", ")", "logger", ".", "warning", "(", "'---------------------------------------------------------'", ")", "raise", "ConversionValidationError", "(", "'IMAGE_ORIENTATION_INCONSISTENT'", ")" ]
Validate that all dicoms have the same orientation :param dicoms: list of dicoms
[ "Validate", "that", "all", "dicoms", "have", "the", "same", "orientation" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L696-L715
icometrix/dicom2nifti
dicom2nifti/common.py
set_tr_te
def set_tr_te(nifti_image, repetition_time, echo_time): """ Set the tr and te in the nifti headers :param echo_time: echo time :param repetition_time: repetition time :param nifti_image: nifti image to set the info to """ # set the repetition time in pixdim nifti_image.header.structarr['pixdim'][4] = repetition_time / 1000.0 # set tr and te in db_name field nifti_image.header.structarr['db_name'] = '?TR:%.3f TE:%d' % (repetition_time, echo_time) return nifti_image
python
def set_tr_te(nifti_image, repetition_time, echo_time): nifti_image.header.structarr['pixdim'][4] = repetition_time / 1000.0 nifti_image.header.structarr['db_name'] = '?TR:%.3f TE:%d' % (repetition_time, echo_time) return nifti_image
[ "def", "set_tr_te", "(", "nifti_image", ",", "repetition_time", ",", "echo_time", ")", ":", "# set the repetition time in pixdim", "nifti_image", ".", "header", ".", "structarr", "[", "'pixdim'", "]", "[", "4", "]", "=", "repetition_time", "/", "1000.0", "# set tr and te in db_name field", "nifti_image", ".", "header", ".", "structarr", "[", "'db_name'", "]", "=", "'?TR:%.3f TE:%d'", "%", "(", "repetition_time", ",", "echo_time", ")", "return", "nifti_image" ]
Set the tr and te in the nifti headers :param echo_time: echo time :param repetition_time: repetition time :param nifti_image: nifti image to set the info to
[ "Set", "the", "tr", "and", "te", "in", "the", "nifti", "headers" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L718-L732
icometrix/dicom2nifti
dicom2nifti/convert_ge.py
dicom_to_nifti
def dicom_to_nifti(dicom_input, output_file=None): """ This is the main dicom to nifti conversion fuction for ge images. As input ge images are required. It will then determine the type of images and do the correct conversion Examples: See unit test :param output_file: the filepath to the output nifti file :param dicom_input: list with dicom objects """ assert common.is_ge(dicom_input) logger.info('Reading and sorting dicom files') grouped_dicoms = _get_grouped_dicoms(dicom_input) if _is_4d(grouped_dicoms): logger.info('Found sequence type: 4D') return _4d_to_nifti(grouped_dicoms, output_file) logger.info('Assuming anatomical data') return convert_generic.dicom_to_nifti(dicom_input, output_file)
python
def dicom_to_nifti(dicom_input, output_file=None): assert common.is_ge(dicom_input) logger.info('Reading and sorting dicom files') grouped_dicoms = _get_grouped_dicoms(dicom_input) if _is_4d(grouped_dicoms): logger.info('Found sequence type: 4D') return _4d_to_nifti(grouped_dicoms, output_file) logger.info('Assuming anatomical data') return convert_generic.dicom_to_nifti(dicom_input, output_file)
[ "def", "dicom_to_nifti", "(", "dicom_input", ",", "output_file", "=", "None", ")", ":", "assert", "common", ".", "is_ge", "(", "dicom_input", ")", "logger", ".", "info", "(", "'Reading and sorting dicom files'", ")", "grouped_dicoms", "=", "_get_grouped_dicoms", "(", "dicom_input", ")", "if", "_is_4d", "(", "grouped_dicoms", ")", ":", "logger", ".", "info", "(", "'Found sequence type: 4D'", ")", "return", "_4d_to_nifti", "(", "grouped_dicoms", ",", "output_file", ")", "logger", ".", "info", "(", "'Assuming anatomical data'", ")", "return", "convert_generic", ".", "dicom_to_nifti", "(", "dicom_input", ",", "output_file", ")" ]
This is the main dicom to nifti conversion fuction for ge images. As input ge images are required. It will then determine the type of images and do the correct conversion Examples: See unit test :param output_file: the filepath to the output nifti file :param dicom_input: list with dicom objects
[ "This", "is", "the", "main", "dicom", "to", "nifti", "conversion", "fuction", "for", "ge", "images", ".", "As", "input", "ge", "images", "are", "required", ".", "It", "will", "then", "determine", "the", "type", "of", "images", "and", "do", "the", "correct", "conversion" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_ge.py#L32-L52
icometrix/dicom2nifti
dicom2nifti/convert_ge.py
_is_diffusion_imaging
def _is_diffusion_imaging(grouped_dicoms): """ Use this function to detect if a dicom series is a ge dti dataset NOTE: We already assume this is a 4D dataset """ # we already assume 4D images as input # check if contains dti bval information bval_tag = Tag(0x0043, 0x1039) # put this there as this is a slow step and used a lot found_bval = False for header in list(itertools.chain.from_iterable(grouped_dicoms)): if bval_tag in header and int(header[bval_tag].value[0]) != 0: found_bval = True break if not found_bval: return False return True
python
def _is_diffusion_imaging(grouped_dicoms): bval_tag = Tag(0x0043, 0x1039) found_bval = False for header in list(itertools.chain.from_iterable(grouped_dicoms)): if bval_tag in header and int(header[bval_tag].value[0]) != 0: found_bval = True break if not found_bval: return False return True
[ "def", "_is_diffusion_imaging", "(", "grouped_dicoms", ")", ":", "# we already assume 4D images as input", "# check if contains dti bval information", "bval_tag", "=", "Tag", "(", "0x0043", ",", "0x1039", ")", "# put this there as this is a slow step and used a lot", "found_bval", "=", "False", "for", "header", "in", "list", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "grouped_dicoms", ")", ")", ":", "if", "bval_tag", "in", "header", "and", "int", "(", "header", "[", "bval_tag", "]", ".", "value", "[", "0", "]", ")", "!=", "0", ":", "found_bval", "=", "True", "break", "if", "not", "found_bval", ":", "return", "False", "return", "True" ]
Use this function to detect if a dicom series is a ge dti dataset NOTE: We already assume this is a 4D dataset
[ "Use", "this", "function", "to", "detect", "if", "a", "dicom", "series", "is", "a", "ge", "dti", "dataset", "NOTE", ":", "We", "already", "assume", "this", "is", "a", "4D", "dataset" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_ge.py#L71-L88
icometrix/dicom2nifti
dicom2nifti/convert_ge.py
_4d_to_nifti
def _4d_to_nifti(grouped_dicoms, output_file): """ This function will convert ge 4d series to a nifti """ # Create mosaic block logger.info('Creating data block') full_block = _get_full_block(grouped_dicoms) logger.info('Creating affine') # Create the nifti header info affine, slice_increment = common.create_affine(grouped_dicoms[0]) logger.info('Creating nifti') # Convert to nifti nii_image = nibabel.Nifti1Image(full_block, affine) common.set_tr_te(nii_image, float(grouped_dicoms[0][0].RepetitionTime), float(grouped_dicoms[0][0].EchoTime)) logger.info('Saving nifti to disk %s' % output_file) # Save to disk if output_file is not None: nii_image.to_filename(output_file) if _is_diffusion_imaging(grouped_dicoms): bval_file = None bvec_file = None # Create the bval en bevec files if output_file is not None: base_path = os.path.dirname(output_file) base_name = os.path.splitext(os.path.splitext(os.path.basename(output_file))[0])[0] logger.info('Creating bval en bvec files') bval_file = '%s/%s.bval' % (base_path, base_name) bvec_file = '%s/%s.bvec' % (base_path, base_name) bval, bvec = _create_bvals_bvecs(grouped_dicoms, bval_file, bvec_file) return {'NII_FILE': output_file, 'BVAL_FILE': bval_file, 'BVEC_FILE': bvec_file, 'NII': nii_image, 'BVAL': bval, 'BVEC': bvec, 'MAX_SLICE_INCREMENT': slice_increment } return {'NII_FILE': output_file, 'NII': nii_image}
python
def _4d_to_nifti(grouped_dicoms, output_file): logger.info('Creating data block') full_block = _get_full_block(grouped_dicoms) logger.info('Creating affine') affine, slice_increment = common.create_affine(grouped_dicoms[0]) logger.info('Creating nifti') nii_image = nibabel.Nifti1Image(full_block, affine) common.set_tr_te(nii_image, float(grouped_dicoms[0][0].RepetitionTime), float(grouped_dicoms[0][0].EchoTime)) logger.info('Saving nifti to disk %s' % output_file) if output_file is not None: nii_image.to_filename(output_file) if _is_diffusion_imaging(grouped_dicoms): bval_file = None bvec_file = None if output_file is not None: base_path = os.path.dirname(output_file) base_name = os.path.splitext(os.path.splitext(os.path.basename(output_file))[0])[0] logger.info('Creating bval en bvec files') bval_file = '%s/%s.bval' % (base_path, base_name) bvec_file = '%s/%s.bvec' % (base_path, base_name) bval, bvec = _create_bvals_bvecs(grouped_dicoms, bval_file, bvec_file) return {'NII_FILE': output_file, 'BVAL_FILE': bval_file, 'BVEC_FILE': bvec_file, 'NII': nii_image, 'BVAL': bval, 'BVEC': bvec, 'MAX_SLICE_INCREMENT': slice_increment } return {'NII_FILE': output_file, 'NII': nii_image}
[ "def", "_4d_to_nifti", "(", "grouped_dicoms", ",", "output_file", ")", ":", "# Create mosaic block", "logger", ".", "info", "(", "'Creating data block'", ")", "full_block", "=", "_get_full_block", "(", "grouped_dicoms", ")", "logger", ".", "info", "(", "'Creating affine'", ")", "# Create the nifti header info", "affine", ",", "slice_increment", "=", "common", ".", "create_affine", "(", "grouped_dicoms", "[", "0", "]", ")", "logger", ".", "info", "(", "'Creating nifti'", ")", "# Convert to nifti", "nii_image", "=", "nibabel", ".", "Nifti1Image", "(", "full_block", ",", "affine", ")", "common", ".", "set_tr_te", "(", "nii_image", ",", "float", "(", "grouped_dicoms", "[", "0", "]", "[", "0", "]", ".", "RepetitionTime", ")", ",", "float", "(", "grouped_dicoms", "[", "0", "]", "[", "0", "]", ".", "EchoTime", ")", ")", "logger", ".", "info", "(", "'Saving nifti to disk %s'", "%", "output_file", ")", "# Save to disk", "if", "output_file", "is", "not", "None", ":", "nii_image", ".", "to_filename", "(", "output_file", ")", "if", "_is_diffusion_imaging", "(", "grouped_dicoms", ")", ":", "bval_file", "=", "None", "bvec_file", "=", "None", "# Create the bval en bevec files", "if", "output_file", "is", "not", "None", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "output_file", ")", "base_name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "output_file", ")", ")", "[", "0", "]", ")", "[", "0", "]", "logger", ".", "info", "(", "'Creating bval en bvec files'", ")", "bval_file", "=", "'%s/%s.bval'", "%", "(", "base_path", ",", "base_name", ")", "bvec_file", "=", "'%s/%s.bvec'", "%", "(", "base_path", ",", "base_name", ")", "bval", ",", "bvec", "=", "_create_bvals_bvecs", "(", "grouped_dicoms", ",", "bval_file", ",", "bvec_file", ")", "return", "{", "'NII_FILE'", ":", "output_file", ",", "'BVAL_FILE'", ":", "bval_file", ",", "'BVEC_FILE'", ":", "bvec_file", ",", "'NII'", ":", "nii_image", ",", "'BVAL'", ":", "bval", ",", "'BVEC'", ":", "bvec", ",", "'MAX_SLICE_INCREMENT'", ":", "slice_increment", "}", "return", "{", "'NII_FILE'", ":", "output_file", ",", "'NII'", ":", "nii_image", "}" ]
This function will convert ge 4d series to a nifti
[ "This", "function", "will", "convert", "ge", "4d", "series", "to", "a", "nifti" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_ge.py#L91-L136
icometrix/dicom2nifti
dicom2nifti/convert_ge.py
_get_full_block
def _get_full_block(grouped_dicoms): """ Generate a full datablock containing all timepoints """ # For each slice / mosaic create a data volume block data_blocks = [] for index in range(0, len(grouped_dicoms)): logger.info('Creating block %s of %s' % (index + 1, len(grouped_dicoms))) data_blocks.append(_timepoint_to_block(grouped_dicoms[index])) # Add the data_blocks together to one 4d block size_x = numpy.shape(data_blocks[0])[0] size_y = numpy.shape(data_blocks[0])[1] size_z = numpy.shape(data_blocks[0])[2] size_t = len(data_blocks) full_block = numpy.zeros((size_x, size_y, size_z, size_t), dtype=data_blocks[0].dtype) for index in range(0, size_t): if full_block[:, :, :, index].shape != data_blocks[index].shape: logger.warning('Missing slices (slice count mismatch between timepoint %s and %s)' % (index - 1, index)) logger.warning('---------------------------------------------------------') logger.warning(full_block[:, :, :, index].shape) logger.warning(data_blocks[index].shape) logger.warning('---------------------------------------------------------') raise ConversionError("MISSING_DICOM_FILES") full_block[:, :, :, index] = data_blocks[index] return full_block
python
def _get_full_block(grouped_dicoms): data_blocks = [] for index in range(0, len(grouped_dicoms)): logger.info('Creating block %s of %s' % (index + 1, len(grouped_dicoms))) data_blocks.append(_timepoint_to_block(grouped_dicoms[index])) size_x = numpy.shape(data_blocks[0])[0] size_y = numpy.shape(data_blocks[0])[1] size_z = numpy.shape(data_blocks[0])[2] size_t = len(data_blocks) full_block = numpy.zeros((size_x, size_y, size_z, size_t), dtype=data_blocks[0].dtype) for index in range(0, size_t): if full_block[:, :, :, index].shape != data_blocks[index].shape: logger.warning('Missing slices (slice count mismatch between timepoint %s and %s)' % (index - 1, index)) logger.warning('---------------------------------------------------------') logger.warning(full_block[:, :, :, index].shape) logger.warning(data_blocks[index].shape) logger.warning('---------------------------------------------------------') raise ConversionError("MISSING_DICOM_FILES") full_block[:, :, :, index] = data_blocks[index] return full_block
[ "def", "_get_full_block", "(", "grouped_dicoms", ")", ":", "# For each slice / mosaic create a data volume block", "data_blocks", "=", "[", "]", "for", "index", "in", "range", "(", "0", ",", "len", "(", "grouped_dicoms", ")", ")", ":", "logger", ".", "info", "(", "'Creating block %s of %s'", "%", "(", "index", "+", "1", ",", "len", "(", "grouped_dicoms", ")", ")", ")", "data_blocks", ".", "append", "(", "_timepoint_to_block", "(", "grouped_dicoms", "[", "index", "]", ")", ")", "# Add the data_blocks together to one 4d block", "size_x", "=", "numpy", ".", "shape", "(", "data_blocks", "[", "0", "]", ")", "[", "0", "]", "size_y", "=", "numpy", ".", "shape", "(", "data_blocks", "[", "0", "]", ")", "[", "1", "]", "size_z", "=", "numpy", ".", "shape", "(", "data_blocks", "[", "0", "]", ")", "[", "2", "]", "size_t", "=", "len", "(", "data_blocks", ")", "full_block", "=", "numpy", ".", "zeros", "(", "(", "size_x", ",", "size_y", ",", "size_z", ",", "size_t", ")", ",", "dtype", "=", "data_blocks", "[", "0", "]", ".", "dtype", ")", "for", "index", "in", "range", "(", "0", ",", "size_t", ")", ":", "if", "full_block", "[", ":", ",", ":", ",", ":", ",", "index", "]", ".", "shape", "!=", "data_blocks", "[", "index", "]", ".", "shape", ":", "logger", ".", "warning", "(", "'Missing slices (slice count mismatch between timepoint %s and %s)'", "%", "(", "index", "-", "1", ",", "index", ")", ")", "logger", ".", "warning", "(", "'---------------------------------------------------------'", ")", "logger", ".", "warning", "(", "full_block", "[", ":", ",", ":", ",", ":", ",", "index", "]", ".", "shape", ")", "logger", ".", "warning", "(", "data_blocks", "[", "index", "]", ".", "shape", ")", "logger", ".", "warning", "(", "'---------------------------------------------------------'", ")", "raise", "ConversionError", "(", "\"MISSING_DICOM_FILES\"", ")", "full_block", "[", ":", ",", ":", ",", ":", ",", "index", "]", "=", "data_blocks", "[", "index", "]", "return", "full_block" ]
Generate a full datablock containing all timepoints
[ "Generate", "a", "full", "datablock", "containing", "all", "timepoints" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_ge.py#L139-L165
icometrix/dicom2nifti
dicom2nifti/convert_ge.py
_get_grouped_dicoms
def _get_grouped_dicoms(dicom_input): """ Search all dicoms in the dicom directory, sort and validate them fast_read = True will only read the headers not the data """ # Order all dicom files by InstanceNumber dicoms = sorted(dicom_input, key=lambda x: x.InstanceNumber) # now group per stack grouped_dicoms = [[]] # list with first element a list stack_index = 0 # loop over all sorted dicoms and sort them by stack # for this we use the position and direction of the slices so we can detect a new stack easily previous_position = None previous_direction = None for dicom_ in dicoms: current_direction = None # if the stack number decreases we moved to the next stack if previous_position is not None: current_direction = numpy.array(dicom_.ImagePositionPatient) - previous_position current_direction = current_direction / numpy.linalg.norm(current_direction) if current_direction is not None and \ previous_direction is not None and \ not numpy.allclose(current_direction, previous_direction, rtol=0.05, atol=0.05): previous_position = numpy.array(dicom_.ImagePositionPatient) previous_direction = None stack_index += 1 else: previous_position = numpy.array(dicom_.ImagePositionPatient) previous_direction = current_direction if stack_index >= len(grouped_dicoms): grouped_dicoms.append([]) grouped_dicoms[stack_index].append(dicom_) return grouped_dicoms
python
def _get_grouped_dicoms(dicom_input): dicoms = sorted(dicom_input, key=lambda x: x.InstanceNumber) grouped_dicoms = [[]] stack_index = 0 previous_position = None previous_direction = None for dicom_ in dicoms: current_direction = None if previous_position is not None: current_direction = numpy.array(dicom_.ImagePositionPatient) - previous_position current_direction = current_direction / numpy.linalg.norm(current_direction) if current_direction is not None and \ previous_direction is not None and \ not numpy.allclose(current_direction, previous_direction, rtol=0.05, atol=0.05): previous_position = numpy.array(dicom_.ImagePositionPatient) previous_direction = None stack_index += 1 else: previous_position = numpy.array(dicom_.ImagePositionPatient) previous_direction = current_direction if stack_index >= len(grouped_dicoms): grouped_dicoms.append([]) grouped_dicoms[stack_index].append(dicom_) return grouped_dicoms
[ "def", "_get_grouped_dicoms", "(", "dicom_input", ")", ":", "# Order all dicom files by InstanceNumber", "dicoms", "=", "sorted", "(", "dicom_input", ",", "key", "=", "lambda", "x", ":", "x", ".", "InstanceNumber", ")", "# now group per stack", "grouped_dicoms", "=", "[", "[", "]", "]", "# list with first element a list", "stack_index", "=", "0", "# loop over all sorted dicoms and sort them by stack", "# for this we use the position and direction of the slices so we can detect a new stack easily", "previous_position", "=", "None", "previous_direction", "=", "None", "for", "dicom_", "in", "dicoms", ":", "current_direction", "=", "None", "# if the stack number decreases we moved to the next stack", "if", "previous_position", "is", "not", "None", ":", "current_direction", "=", "numpy", ".", "array", "(", "dicom_", ".", "ImagePositionPatient", ")", "-", "previous_position", "current_direction", "=", "current_direction", "/", "numpy", ".", "linalg", ".", "norm", "(", "current_direction", ")", "if", "current_direction", "is", "not", "None", "and", "previous_direction", "is", "not", "None", "and", "not", "numpy", ".", "allclose", "(", "current_direction", ",", "previous_direction", ",", "rtol", "=", "0.05", ",", "atol", "=", "0.05", ")", ":", "previous_position", "=", "numpy", ".", "array", "(", "dicom_", ".", "ImagePositionPatient", ")", "previous_direction", "=", "None", "stack_index", "+=", "1", "else", ":", "previous_position", "=", "numpy", ".", "array", "(", "dicom_", ".", "ImagePositionPatient", ")", "previous_direction", "=", "current_direction", "if", "stack_index", ">=", "len", "(", "grouped_dicoms", ")", ":", "grouped_dicoms", ".", "append", "(", "[", "]", ")", "grouped_dicoms", "[", "stack_index", "]", ".", "append", "(", "dicom_", ")", "return", "grouped_dicoms" ]
Search all dicoms in the dicom directory, sort and validate them fast_read = True will only read the headers not the data
[ "Search", "all", "dicoms", "in", "the", "dicom", "directory", "sort", "and", "validate", "them" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_ge.py#L176-L214
icometrix/dicom2nifti
dicom2nifti/convert_ge.py
_get_bvals_bvecs
def _get_bvals_bvecs(grouped_dicoms): """ Write the bvals from the sorted dicom files to a bval file """ # loop over all timepoints and create a list with all bvals and bvecs bvals = numpy.zeros([len(grouped_dicoms)], dtype=numpy.int32) bvecs = numpy.zeros([len(grouped_dicoms), 3]) for group_index in range(0, len(grouped_dicoms)): dicom_ = grouped_dicoms[group_index][0] # 0019:10bb: Diffusion X # 0019:10bc: Diffusion Y # 0019:10bd: Diffusion Z # 0043:1039: B-values (4 values, 1st value is actual B value) # bval can be stored both in string as number format in dicom so implement both # some workarounds needed for implicit transfer syntax to work if isinstance(dicom_[Tag(0x0043, 0x1039)].value, string_types): # this works for python2.7 original_bval = float(dicom_[Tag(0x0043, 0x1039)].value.split('\\')[0]) elif isinstance(dicom_[Tag(0x0043, 0x1039)].value, bytes): # this works for python3.o original_bval = float(dicom_[Tag(0x0043, 0x1039)].value.decode("utf-8").split('\\')[0]) else: original_bval = dicom_[Tag(0x0043, 0x1039)][0] original_bvec = numpy.array([0, 0, 0], dtype=numpy.float) original_bvec[0] = -float(dicom_[Tag(0x0019, 0x10bb)].value) # invert based upon mricron output original_bvec[1] = float(dicom_[Tag(0x0019, 0x10bc)].value) original_bvec[2] = float(dicom_[Tag(0x0019, 0x10bd)].value) # Add calculated B Value if original_bval != 0: # only normalize if there is a value corrected_bval = original_bval * pow(numpy.linalg.norm(original_bvec), 2) if numpy.linalg.norm(original_bvec) != 0: normalized_bvec = original_bvec / numpy.linalg.norm(original_bvec) else: normalized_bvec = original_bvec else: corrected_bval = original_bval normalized_bvec = original_bvec bvals[group_index] = int(round(corrected_bval)) # we want the original numbers back as in the protocol bvecs[group_index, :] = normalized_bvec return bvals, bvecs
python
def _get_bvals_bvecs(grouped_dicoms): bvals = numpy.zeros([len(grouped_dicoms)], dtype=numpy.int32) bvecs = numpy.zeros([len(grouped_dicoms), 3]) for group_index in range(0, len(grouped_dicoms)): dicom_ = grouped_dicoms[group_index][0] if isinstance(dicom_[Tag(0x0043, 0x1039)].value, string_types): original_bval = float(dicom_[Tag(0x0043, 0x1039)].value.split('\\')[0]) elif isinstance(dicom_[Tag(0x0043, 0x1039)].value, bytes): original_bval = float(dicom_[Tag(0x0043, 0x1039)].value.decode("utf-8").split('\\')[0]) else: original_bval = dicom_[Tag(0x0043, 0x1039)][0] original_bvec = numpy.array([0, 0, 0], dtype=numpy.float) original_bvec[0] = -float(dicom_[Tag(0x0019, 0x10bb)].value) original_bvec[1] = float(dicom_[Tag(0x0019, 0x10bc)].value) original_bvec[2] = float(dicom_[Tag(0x0019, 0x10bd)].value) if original_bval != 0: corrected_bval = original_bval * pow(numpy.linalg.norm(original_bvec), 2) if numpy.linalg.norm(original_bvec) != 0: normalized_bvec = original_bvec / numpy.linalg.norm(original_bvec) else: normalized_bvec = original_bvec else: corrected_bval = original_bval normalized_bvec = original_bvec bvals[group_index] = int(round(corrected_bval)) bvecs[group_index, :] = normalized_bvec return bvals, bvecs
[ "def", "_get_bvals_bvecs", "(", "grouped_dicoms", ")", ":", "# loop over all timepoints and create a list with all bvals and bvecs", "bvals", "=", "numpy", ".", "zeros", "(", "[", "len", "(", "grouped_dicoms", ")", "]", ",", "dtype", "=", "numpy", ".", "int32", ")", "bvecs", "=", "numpy", ".", "zeros", "(", "[", "len", "(", "grouped_dicoms", ")", ",", "3", "]", ")", "for", "group_index", "in", "range", "(", "0", ",", "len", "(", "grouped_dicoms", ")", ")", ":", "dicom_", "=", "grouped_dicoms", "[", "group_index", "]", "[", "0", "]", "# 0019:10bb: Diffusion X", "# 0019:10bc: Diffusion Y", "# 0019:10bd: Diffusion Z", "# 0043:1039: B-values (4 values, 1st value is actual B value)", "# bval can be stored both in string as number format in dicom so implement both", "# some workarounds needed for implicit transfer syntax to work", "if", "isinstance", "(", "dicom_", "[", "Tag", "(", "0x0043", ",", "0x1039", ")", "]", ".", "value", ",", "string_types", ")", ":", "# this works for python2.7", "original_bval", "=", "float", "(", "dicom_", "[", "Tag", "(", "0x0043", ",", "0x1039", ")", "]", ".", "value", ".", "split", "(", "'\\\\'", ")", "[", "0", "]", ")", "elif", "isinstance", "(", "dicom_", "[", "Tag", "(", "0x0043", ",", "0x1039", ")", "]", ".", "value", ",", "bytes", ")", ":", "# this works for python3.o", "original_bval", "=", "float", "(", "dicom_", "[", "Tag", "(", "0x0043", ",", "0x1039", ")", "]", ".", "value", ".", "decode", "(", "\"utf-8\"", ")", ".", "split", "(", "'\\\\'", ")", "[", "0", "]", ")", "else", ":", "original_bval", "=", "dicom_", "[", "Tag", "(", "0x0043", ",", "0x1039", ")", "]", "[", "0", "]", "original_bvec", "=", "numpy", ".", "array", "(", "[", "0", ",", "0", ",", "0", "]", ",", "dtype", "=", "numpy", ".", "float", ")", "original_bvec", "[", "0", "]", "=", "-", "float", "(", "dicom_", "[", "Tag", "(", "0x0019", ",", "0x10bb", ")", "]", ".", "value", ")", "# invert based upon mricron output", "original_bvec", "[", "1", "]", "=", "float", "(", "dicom_", "[", "Tag", "(", "0x0019", ",", "0x10bc", ")", "]", ".", "value", ")", "original_bvec", "[", "2", "]", "=", "float", "(", "dicom_", "[", "Tag", "(", "0x0019", ",", "0x10bd", ")", "]", ".", "value", ")", "# Add calculated B Value", "if", "original_bval", "!=", "0", ":", "# only normalize if there is a value", "corrected_bval", "=", "original_bval", "*", "pow", "(", "numpy", ".", "linalg", ".", "norm", "(", "original_bvec", ")", ",", "2", ")", "if", "numpy", ".", "linalg", ".", "norm", "(", "original_bvec", ")", "!=", "0", ":", "normalized_bvec", "=", "original_bvec", "/", "numpy", ".", "linalg", ".", "norm", "(", "original_bvec", ")", "else", ":", "normalized_bvec", "=", "original_bvec", "else", ":", "corrected_bval", "=", "original_bval", "normalized_bvec", "=", "original_bvec", "bvals", "[", "group_index", "]", "=", "int", "(", "round", "(", "corrected_bval", ")", ")", "# we want the original numbers back as in the protocol", "bvecs", "[", "group_index", ",", ":", "]", "=", "normalized_bvec", "return", "bvals", ",", "bvecs" ]
Write the bvals from the sorted dicom files to a bval file
[ "Write", "the", "bvals", "from", "the", "sorted", "dicom", "files", "to", "a", "bval", "file" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_ge.py#L217-L259
icometrix/dicom2nifti
dicom2nifti/convert_ge.py
_create_bvals_bvecs
def _create_bvals_bvecs(grouped_dicoms, bval_file, bvec_file): """ Write the bvals from the sorted dicom files to a bval file """ # get the bvals and bvecs bvals, bvecs = _get_bvals_bvecs(grouped_dicoms) # save the found bvecs to the file common.write_bval_file(bvals, bval_file) common.write_bvec_file(bvecs, bvec_file) return bvals, bvecs
python
def _create_bvals_bvecs(grouped_dicoms, bval_file, bvec_file): bvals, bvecs = _get_bvals_bvecs(grouped_dicoms) common.write_bval_file(bvals, bval_file) common.write_bvec_file(bvecs, bvec_file) return bvals, bvecs
[ "def", "_create_bvals_bvecs", "(", "grouped_dicoms", ",", "bval_file", ",", "bvec_file", ")", ":", "# get the bvals and bvecs", "bvals", ",", "bvecs", "=", "_get_bvals_bvecs", "(", "grouped_dicoms", ")", "# save the found bvecs to the file", "common", ".", "write_bval_file", "(", "bvals", ",", "bval_file", ")", "common", ".", "write_bvec_file", "(", "bvecs", ",", "bvec_file", ")", "return", "bvals", ",", "bvecs" ]
Write the bvals from the sorted dicom files to a bval file
[ "Write", "the", "bvals", "from", "the", "sorted", "dicom", "files", "to", "a", "bval", "file" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_ge.py#L262-L274
icometrix/dicom2nifti
dicom2nifti/convert_hitachi.py
dicom_to_nifti
def dicom_to_nifti(dicom_input, output_file=None): """ This is the main dicom to nifti conversion fuction for hitachi images. As input hitachi images are required. It will then determine the type of images and do the correct conversion Examples: See unit test :param output_file: file path to the output nifti :param dicom_input: directory with dicom files for 1 scan """ assert common.is_hitachi(dicom_input) # TODO add validations and conversion for DTI and fMRI once testdata is available logger.info('Assuming anatomical data') return convert_generic.dicom_to_nifti(dicom_input, output_file)
python
def dicom_to_nifti(dicom_input, output_file=None): assert common.is_hitachi(dicom_input) logger.info('Assuming anatomical data') return convert_generic.dicom_to_nifti(dicom_input, output_file)
[ "def", "dicom_to_nifti", "(", "dicom_input", ",", "output_file", "=", "None", ")", ":", "assert", "common", ".", "is_hitachi", "(", "dicom_input", ")", "# TODO add validations and conversion for DTI and fMRI once testdata is available", "logger", ".", "info", "(", "'Assuming anatomical data'", ")", "return", "convert_generic", ".", "dicom_to_nifti", "(", "dicom_input", ",", "output_file", ")" ]
This is the main dicom to nifti conversion fuction for hitachi images. As input hitachi images are required. It will then determine the type of images and do the correct conversion Examples: See unit test :param output_file: file path to the output nifti :param dicom_input: directory with dicom files for 1 scan
[ "This", "is", "the", "main", "dicom", "to", "nifti", "conversion", "fuction", "for", "hitachi", "images", ".", "As", "input", "hitachi", "images", "are", "required", ".", "It", "will", "then", "determine", "the", "type", "of", "images", "and", "do", "the", "correct", "conversion" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_hitachi.py#L25-L41
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
dicom_to_nifti
def dicom_to_nifti(dicom_input, output_file=None): """ This is the main dicom to nifti conversion function for ge images. As input ge images are required. It will then determine the type of images and do the correct conversion :param output_file: filepath to the output nifti :param dicom_input: directory with dicom files for 1 scan """ assert common.is_siemens(dicom_input) if _is_4d(dicom_input): logger.info('Found sequence type: MOSAIC 4D') return _mosaic_4d_to_nifti(dicom_input, output_file) grouped_dicoms = _classic_get_grouped_dicoms(dicom_input) if _is_classic_4d(grouped_dicoms): logger.info('Found sequence type: CLASSIC 4D') return _classic_4d_to_nifti(grouped_dicoms, output_file) logger.info('Assuming anatomical data') return convert_generic.dicom_to_nifti(dicom_input, output_file)
python
def dicom_to_nifti(dicom_input, output_file=None): assert common.is_siemens(dicom_input) if _is_4d(dicom_input): logger.info('Found sequence type: MOSAIC 4D') return _mosaic_4d_to_nifti(dicom_input, output_file) grouped_dicoms = _classic_get_grouped_dicoms(dicom_input) if _is_classic_4d(grouped_dicoms): logger.info('Found sequence type: CLASSIC 4D') return _classic_4d_to_nifti(grouped_dicoms, output_file) logger.info('Assuming anatomical data') return convert_generic.dicom_to_nifti(dicom_input, output_file)
[ "def", "dicom_to_nifti", "(", "dicom_input", ",", "output_file", "=", "None", ")", ":", "assert", "common", ".", "is_siemens", "(", "dicom_input", ")", "if", "_is_4d", "(", "dicom_input", ")", ":", "logger", ".", "info", "(", "'Found sequence type: MOSAIC 4D'", ")", "return", "_mosaic_4d_to_nifti", "(", "dicom_input", ",", "output_file", ")", "grouped_dicoms", "=", "_classic_get_grouped_dicoms", "(", "dicom_input", ")", "if", "_is_classic_4d", "(", "grouped_dicoms", ")", ":", "logger", ".", "info", "(", "'Found sequence type: CLASSIC 4D'", ")", "return", "_classic_4d_to_nifti", "(", "grouped_dicoms", ",", "output_file", ")", "logger", ".", "info", "(", "'Assuming anatomical data'", ")", "return", "convert_generic", ".", "dicom_to_nifti", "(", "dicom_input", ",", "output_file", ")" ]
This is the main dicom to nifti conversion function for ge images. As input ge images are required. It will then determine the type of images and do the correct conversion :param output_file: filepath to the output nifti :param dicom_input: directory with dicom files for 1 scan
[ "This", "is", "the", "main", "dicom", "to", "nifti", "conversion", "function", "for", "ge", "images", ".", "As", "input", "ge", "images", "are", "required", ".", "It", "will", "then", "determine", "the", "type", "of", "images", "and", "do", "the", "correct", "conversion" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L45-L66
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_is_mosaic
def _is_mosaic(dicom_input): """ Use this function to detect if a dicom series is a siemens 4d dataset NOTE: Only the first slice will be checked so you can only provide an already sorted dicom directory (containing one series) """ # for grouped dicoms if type(dicom_input) is list and type(dicom_input[0]) is list: header = dicom_input[0][0] else: # all the others header = dicom_input[0] # check if image type contains m and mosaic if 'ImageType' not in header or 'MOSAIC' not in header.ImageType: return False if 'AcquisitionMatrix' not in header or header.AcquisitionMatrix is None: return False return True
python
def _is_mosaic(dicom_input): if type(dicom_input) is list and type(dicom_input[0]) is list: header = dicom_input[0][0] else: header = dicom_input[0] if 'ImageType' not in header or 'MOSAIC' not in header.ImageType: return False if 'AcquisitionMatrix' not in header or header.AcquisitionMatrix is None: return False return True
[ "def", "_is_mosaic", "(", "dicom_input", ")", ":", "# for grouped dicoms", "if", "type", "(", "dicom_input", ")", "is", "list", "and", "type", "(", "dicom_input", "[", "0", "]", ")", "is", "list", ":", "header", "=", "dicom_input", "[", "0", "]", "[", "0", "]", "else", ":", "# all the others", "header", "=", "dicom_input", "[", "0", "]", "# check if image type contains m and mosaic", "if", "'ImageType'", "not", "in", "header", "or", "'MOSAIC'", "not", "in", "header", ".", "ImageType", ":", "return", "False", "if", "'AcquisitionMatrix'", "not", "in", "header", "or", "header", ".", "AcquisitionMatrix", "is", "None", ":", "return", "False", "return", "True" ]
Use this function to detect if a dicom series is a siemens 4d dataset NOTE: Only the first slice will be checked so you can only provide an already sorted dicom directory (containing one series)
[ "Use", "this", "function", "to", "detect", "if", "a", "dicom", "series", "is", "a", "siemens", "4d", "dataset", "NOTE", ":", "Only", "the", "first", "slice", "will", "be", "checked", "so", "you", "can", "only", "provide", "an", "already", "sorted", "dicom", "directory", "(", "containing", "one", "series", ")" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L69-L88
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_mosaic_4d_to_nifti
def _mosaic_4d_to_nifti(dicom_input, output_file): """ This function will convert siemens 4d series to a nifti Some inspiration on which fields can be used was taken from http://slicer.org/doc/html/DICOMDiffusionVolumePlugin_8py_source.html """ # Get the sorted mosaics logger.info('Sorting dicom slices') sorted_mosaics = _get_sorted_mosaics(dicom_input) common.validate_orientation(sorted_mosaics) # Create mosaic block logger.info('Creating data block') full_block = _mosaic_get_full_block(sorted_mosaics) logger.info('Creating affine') # Create the nifti header info affine = _create_affine_siemens_mosaic(dicom_input) logger.info('Creating nifti') # Convert to nifti nii_image = nibabel.Nifti1Image(full_block, affine) common.set_tr_te(nii_image, float(sorted_mosaics[0].RepetitionTime), float(sorted_mosaics[0].EchoTime)) logger.info('Saving nifti to disk') # Save to disk if output_file is not None: nii_image.to_filename(output_file) if _is_diffusion_imaging(dicom_input[0]): # Create the bval en bvec files logger.info('Creating bval en bvec') bval_file = None bvec_file = None if output_file is not None: base_path = os.path.dirname(output_file) base_name = os.path.splitext(os.path.splitext(os.path.basename(output_file))[0])[0] logger.info('Saving bval en bvec files') bval_file = '%s/%s.bval' % (base_path, base_name) bvec_file = '%s/%s.bvec' % (base_path, base_name) bvals = _create_bvals(sorted_mosaics, bval_file) bvecs = _create_bvecs(sorted_mosaics, bvec_file) return {'NII_FILE': output_file, 'BVAL_FILE': bval_file, 'BVEC_FILE': bvec_file, 'NII': nii_image, 'BVAL': bvals, 'BVEC': bvecs} return {'NII_FILE': output_file, 'NII': nii_image}
python
def _mosaic_4d_to_nifti(dicom_input, output_file): logger.info('Sorting dicom slices') sorted_mosaics = _get_sorted_mosaics(dicom_input) common.validate_orientation(sorted_mosaics) logger.info('Creating data block') full_block = _mosaic_get_full_block(sorted_mosaics) logger.info('Creating affine') affine = _create_affine_siemens_mosaic(dicom_input) logger.info('Creating nifti') nii_image = nibabel.Nifti1Image(full_block, affine) common.set_tr_te(nii_image, float(sorted_mosaics[0].RepetitionTime), float(sorted_mosaics[0].EchoTime)) logger.info('Saving nifti to disk') if output_file is not None: nii_image.to_filename(output_file) if _is_diffusion_imaging(dicom_input[0]): logger.info('Creating bval en bvec') bval_file = None bvec_file = None if output_file is not None: base_path = os.path.dirname(output_file) base_name = os.path.splitext(os.path.splitext(os.path.basename(output_file))[0])[0] logger.info('Saving bval en bvec files') bval_file = '%s/%s.bval' % (base_path, base_name) bvec_file = '%s/%s.bvec' % (base_path, base_name) bvals = _create_bvals(sorted_mosaics, bval_file) bvecs = _create_bvecs(sorted_mosaics, bvec_file) return {'NII_FILE': output_file, 'BVAL_FILE': bval_file, 'BVEC_FILE': bvec_file, 'NII': nii_image, 'BVAL': bvals, 'BVEC': bvecs} return {'NII_FILE': output_file, 'NII': nii_image}
[ "def", "_mosaic_4d_to_nifti", "(", "dicom_input", ",", "output_file", ")", ":", "# Get the sorted mosaics", "logger", ".", "info", "(", "'Sorting dicom slices'", ")", "sorted_mosaics", "=", "_get_sorted_mosaics", "(", "dicom_input", ")", "common", ".", "validate_orientation", "(", "sorted_mosaics", ")", "# Create mosaic block", "logger", ".", "info", "(", "'Creating data block'", ")", "full_block", "=", "_mosaic_get_full_block", "(", "sorted_mosaics", ")", "logger", ".", "info", "(", "'Creating affine'", ")", "# Create the nifti header info", "affine", "=", "_create_affine_siemens_mosaic", "(", "dicom_input", ")", "logger", ".", "info", "(", "'Creating nifti'", ")", "# Convert to nifti", "nii_image", "=", "nibabel", ".", "Nifti1Image", "(", "full_block", ",", "affine", ")", "common", ".", "set_tr_te", "(", "nii_image", ",", "float", "(", "sorted_mosaics", "[", "0", "]", ".", "RepetitionTime", ")", ",", "float", "(", "sorted_mosaics", "[", "0", "]", ".", "EchoTime", ")", ")", "logger", ".", "info", "(", "'Saving nifti to disk'", ")", "# Save to disk", "if", "output_file", "is", "not", "None", ":", "nii_image", ".", "to_filename", "(", "output_file", ")", "if", "_is_diffusion_imaging", "(", "dicom_input", "[", "0", "]", ")", ":", "# Create the bval en bvec files", "logger", ".", "info", "(", "'Creating bval en bvec'", ")", "bval_file", "=", "None", "bvec_file", "=", "None", "if", "output_file", "is", "not", "None", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "output_file", ")", "base_name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "output_file", ")", ")", "[", "0", "]", ")", "[", "0", "]", "logger", ".", "info", "(", "'Saving bval en bvec files'", ")", "bval_file", "=", "'%s/%s.bval'", "%", "(", "base_path", ",", "base_name", ")", "bvec_file", "=", "'%s/%s.bvec'", "%", "(", "base_path", ",", "base_name", ")", "bvals", "=", "_create_bvals", "(", "sorted_mosaics", ",", "bval_file", ")", "bvecs", "=", "_create_bvecs", "(", "sorted_mosaics", ",", "bvec_file", ")", "return", "{", "'NII_FILE'", ":", "output_file", ",", "'BVAL_FILE'", ":", "bval_file", ",", "'BVEC_FILE'", ":", "bvec_file", ",", "'NII'", ":", "nii_image", ",", "'BVAL'", ":", "bvals", ",", "'BVEC'", ":", "bvecs", "}", "return", "{", "'NII_FILE'", ":", "output_file", ",", "'NII'", ":", "nii_image", "}" ]
This function will convert siemens 4d series to a nifti Some inspiration on which fields can be used was taken from http://slicer.org/doc/html/DICOMDiffusionVolumePlugin_8py_source.html
[ "This", "function", "will", "convert", "siemens", "4d", "series", "to", "a", "nifti", "Some", "inspiration", "on", "which", "fields", "can", "be", "used", "was", "taken", "from", "http", ":", "//", "slicer", ".", "org", "/", "doc", "/", "html", "/", "DICOMDiffusionVolumePlugin_8py_source", ".", "html" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L133-L182
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_classic_4d_to_nifti
def _classic_4d_to_nifti(grouped_dicoms, output_file): """ This function will convert siemens 4d series to a nifti Some inspiration on which fields can be used was taken from http://slicer.org/doc/html/DICOMDiffusionVolumePlugin_8py_source.html """ # Get the sorted mosaics all_dicoms = [i for sl in grouped_dicoms for i in sl] # combine into 1 list for validating common.validate_orientation(all_dicoms) # Create mosaic block logger.info('Creating data block') full_block = _classic_get_full_block(grouped_dicoms) logger.info('Creating affine') # Create the nifti header info affine, slice_increment = common.create_affine(grouped_dicoms[0]) logger.info('Creating nifti') # Convert to nifti nii_image = nibabel.Nifti1Image(full_block, affine) common.set_tr_te(nii_image, float(grouped_dicoms[0][0].RepetitionTime), float(grouped_dicoms[0][0].EchoTime)) logger.info('Saving nifti to disk') # Save to disk if output_file is not None: nii_image.to_filename(output_file) if _is_diffusion_imaging(grouped_dicoms[0][0]): logger.info('Creating bval en bvec') bval_file = None bvec_file = None if output_file is not None: base_path = os.path.dirname(output_file) base_name = os.path.splitext(os.path.splitext(os.path.basename(output_file))[0])[0] logger.info('Creating bval en bvec files') bval_file = '%s/%s.bval' % (base_path, base_name) bvec_file = '%s/%s.bvec' % (base_path, base_name) bval = _create_bvals(grouped_dicoms, bval_file) bvec = _create_bvecs(grouped_dicoms, bvec_file) return {'NII_FILE': output_file, 'BVAL_FILE': bval_file, 'BVEC_FILE': bvec_file, 'NII': nii_image, 'BVAL': bval, 'BVEC': bvec, 'MAX_SLICE_INCREMENT': slice_increment} return {'NII_FILE': output_file, 'NII': nii_image, 'MAX_SLICE_INCREMENT': slice_increment}
python
def _classic_4d_to_nifti(grouped_dicoms, output_file): all_dicoms = [i for sl in grouped_dicoms for i in sl] common.validate_orientation(all_dicoms) logger.info('Creating data block') full_block = _classic_get_full_block(grouped_dicoms) logger.info('Creating affine') affine, slice_increment = common.create_affine(grouped_dicoms[0]) logger.info('Creating nifti') nii_image = nibabel.Nifti1Image(full_block, affine) common.set_tr_te(nii_image, float(grouped_dicoms[0][0].RepetitionTime), float(grouped_dicoms[0][0].EchoTime)) logger.info('Saving nifti to disk') if output_file is not None: nii_image.to_filename(output_file) if _is_diffusion_imaging(grouped_dicoms[0][0]): logger.info('Creating bval en bvec') bval_file = None bvec_file = None if output_file is not None: base_path = os.path.dirname(output_file) base_name = os.path.splitext(os.path.splitext(os.path.basename(output_file))[0])[0] logger.info('Creating bval en bvec files') bval_file = '%s/%s.bval' % (base_path, base_name) bvec_file = '%s/%s.bvec' % (base_path, base_name) bval = _create_bvals(grouped_dicoms, bval_file) bvec = _create_bvecs(grouped_dicoms, bvec_file) return {'NII_FILE': output_file, 'BVAL_FILE': bval_file, 'BVEC_FILE': bvec_file, 'NII': nii_image, 'BVAL': bval, 'BVEC': bvec, 'MAX_SLICE_INCREMENT': slice_increment} return {'NII_FILE': output_file, 'NII': nii_image, 'MAX_SLICE_INCREMENT': slice_increment}
[ "def", "_classic_4d_to_nifti", "(", "grouped_dicoms", ",", "output_file", ")", ":", "# Get the sorted mosaics", "all_dicoms", "=", "[", "i", "for", "sl", "in", "grouped_dicoms", "for", "i", "in", "sl", "]", "# combine into 1 list for validating", "common", ".", "validate_orientation", "(", "all_dicoms", ")", "# Create mosaic block", "logger", ".", "info", "(", "'Creating data block'", ")", "full_block", "=", "_classic_get_full_block", "(", "grouped_dicoms", ")", "logger", ".", "info", "(", "'Creating affine'", ")", "# Create the nifti header info", "affine", ",", "slice_increment", "=", "common", ".", "create_affine", "(", "grouped_dicoms", "[", "0", "]", ")", "logger", ".", "info", "(", "'Creating nifti'", ")", "# Convert to nifti", "nii_image", "=", "nibabel", ".", "Nifti1Image", "(", "full_block", ",", "affine", ")", "common", ".", "set_tr_te", "(", "nii_image", ",", "float", "(", "grouped_dicoms", "[", "0", "]", "[", "0", "]", ".", "RepetitionTime", ")", ",", "float", "(", "grouped_dicoms", "[", "0", "]", "[", "0", "]", ".", "EchoTime", ")", ")", "logger", ".", "info", "(", "'Saving nifti to disk'", ")", "# Save to disk", "if", "output_file", "is", "not", "None", ":", "nii_image", ".", "to_filename", "(", "output_file", ")", "if", "_is_diffusion_imaging", "(", "grouped_dicoms", "[", "0", "]", "[", "0", "]", ")", ":", "logger", ".", "info", "(", "'Creating bval en bvec'", ")", "bval_file", "=", "None", "bvec_file", "=", "None", "if", "output_file", "is", "not", "None", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "output_file", ")", "base_name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "output_file", ")", ")", "[", "0", "]", ")", "[", "0", "]", "logger", ".", "info", "(", "'Creating bval en bvec files'", ")", "bval_file", "=", "'%s/%s.bval'", "%", "(", "base_path", ",", "base_name", ")", "bvec_file", "=", "'%s/%s.bvec'", "%", "(", "base_path", ",", "base_name", ")", "bval", "=", "_create_bvals", "(", "grouped_dicoms", ",", "bval_file", ")", "bvec", "=", "_create_bvecs", "(", "grouped_dicoms", ",", "bvec_file", ")", "return", "{", "'NII_FILE'", ":", "output_file", ",", "'BVAL_FILE'", ":", "bval_file", ",", "'BVEC_FILE'", ":", "bvec_file", ",", "'NII'", ":", "nii_image", ",", "'BVAL'", ":", "bval", ",", "'BVEC'", ":", "bvec", ",", "'MAX_SLICE_INCREMENT'", ":", "slice_increment", "}", "return", "{", "'NII_FILE'", ":", "output_file", ",", "'NII'", ":", "nii_image", ",", "'MAX_SLICE_INCREMENT'", ":", "slice_increment", "}" ]
This function will convert siemens 4d series to a nifti Some inspiration on which fields can be used was taken from http://slicer.org/doc/html/DICOMDiffusionVolumePlugin_8py_source.html
[ "This", "function", "will", "convert", "siemens", "4d", "series", "to", "a", "nifti", "Some", "inspiration", "on", "which", "fields", "can", "be", "used", "was", "taken", "from", "http", ":", "//", "slicer", ".", "org", "/", "doc", "/", "html", "/", "DICOMDiffusionVolumePlugin_8py_source", ".", "html" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L185-L236
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_classic_get_grouped_dicoms
def _classic_get_grouped_dicoms(dicom_input): """ Search all dicoms in the dicom directory, sort and validate them fast_read = True will only read the headers not the data """ # Loop overall files and build dict # Order all dicom files by InstanceNumber if [d for d in dicom_input if 'InstanceNumber' in d]: dicoms = sorted(dicom_input, key=lambda x: x.InstanceNumber) else: dicoms = common.sort_dicoms(dicom_input) # now group per stack grouped_dicoms = [] # loop over all sorted dicoms stack_position_tag = Tag(0x0020, 0x0012) # in this case it is the acquisition number for index in range(0, len(dicoms)): dicom_ = dicoms[index] if stack_position_tag not in dicom_: stack_index = 0 else: stack_index = dicom_[stack_position_tag].value - 1 while len(grouped_dicoms) <= stack_index: grouped_dicoms.append([]) grouped_dicoms[stack_index].append(dicom_) return grouped_dicoms
python
def _classic_get_grouped_dicoms(dicom_input): if [d for d in dicom_input if 'InstanceNumber' in d]: dicoms = sorted(dicom_input, key=lambda x: x.InstanceNumber) else: dicoms = common.sort_dicoms(dicom_input) grouped_dicoms = [] stack_position_tag = Tag(0x0020, 0x0012) for index in range(0, len(dicoms)): dicom_ = dicoms[index] if stack_position_tag not in dicom_: stack_index = 0 else: stack_index = dicom_[stack_position_tag].value - 1 while len(grouped_dicoms) <= stack_index: grouped_dicoms.append([]) grouped_dicoms[stack_index].append(dicom_) return grouped_dicoms
[ "def", "_classic_get_grouped_dicoms", "(", "dicom_input", ")", ":", "# Loop overall files and build dict", "# Order all dicom files by InstanceNumber", "if", "[", "d", "for", "d", "in", "dicom_input", "if", "'InstanceNumber'", "in", "d", "]", ":", "dicoms", "=", "sorted", "(", "dicom_input", ",", "key", "=", "lambda", "x", ":", "x", ".", "InstanceNumber", ")", "else", ":", "dicoms", "=", "common", ".", "sort_dicoms", "(", "dicom_input", ")", "# now group per stack", "grouped_dicoms", "=", "[", "]", "# loop over all sorted dicoms", "stack_position_tag", "=", "Tag", "(", "0x0020", ",", "0x0012", ")", "# in this case it is the acquisition number", "for", "index", "in", "range", "(", "0", ",", "len", "(", "dicoms", ")", ")", ":", "dicom_", "=", "dicoms", "[", "index", "]", "if", "stack_position_tag", "not", "in", "dicom_", ":", "stack_index", "=", "0", "else", ":", "stack_index", "=", "dicom_", "[", "stack_position_tag", "]", ".", "value", "-", "1", "while", "len", "(", "grouped_dicoms", ")", "<=", "stack_index", ":", "grouped_dicoms", ".", "append", "(", "[", "]", ")", "grouped_dicoms", "[", "stack_index", "]", ".", "append", "(", "dicom_", ")", "return", "grouped_dicoms" ]
Search all dicoms in the dicom directory, sort and validate them fast_read = True will only read the headers not the data
[ "Search", "all", "dicoms", "in", "the", "dicom", "directory", "sort", "and", "validate", "them" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L239-L267
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_classic_get_full_block
def _classic_get_full_block(grouped_dicoms): """ Generate a full datablock containing all timepoints """ # For each slice / mosaic create a data volume block data_blocks = [] for index in range(0, len(grouped_dicoms)): logger.info('Creating block %s of %s' % (index + 1, len(grouped_dicoms))) data_blocks.append(_classic_timepoint_to_block(grouped_dicoms[index])) # Add the data_blocks together to one 4d block size_x = numpy.shape(data_blocks[0])[0] size_y = numpy.shape(data_blocks[0])[1] size_z = numpy.shape(data_blocks[0])[2] size_t = len(data_blocks) full_block = numpy.zeros((size_x, size_y, size_z, size_t), dtype=data_blocks[0].dtype) for index in range(0, size_t): full_block[:, :, :, index] = data_blocks[index] return full_block
python
def _classic_get_full_block(grouped_dicoms): data_blocks = [] for index in range(0, len(grouped_dicoms)): logger.info('Creating block %s of %s' % (index + 1, len(grouped_dicoms))) data_blocks.append(_classic_timepoint_to_block(grouped_dicoms[index])) size_x = numpy.shape(data_blocks[0])[0] size_y = numpy.shape(data_blocks[0])[1] size_z = numpy.shape(data_blocks[0])[2] size_t = len(data_blocks) full_block = numpy.zeros((size_x, size_y, size_z, size_t), dtype=data_blocks[0].dtype) for index in range(0, size_t): full_block[:, :, :, index] = data_blocks[index] return full_block
[ "def", "_classic_get_full_block", "(", "grouped_dicoms", ")", ":", "# For each slice / mosaic create a data volume block", "data_blocks", "=", "[", "]", "for", "index", "in", "range", "(", "0", ",", "len", "(", "grouped_dicoms", ")", ")", ":", "logger", ".", "info", "(", "'Creating block %s of %s'", "%", "(", "index", "+", "1", ",", "len", "(", "grouped_dicoms", ")", ")", ")", "data_blocks", ".", "append", "(", "_classic_timepoint_to_block", "(", "grouped_dicoms", "[", "index", "]", ")", ")", "# Add the data_blocks together to one 4d block", "size_x", "=", "numpy", ".", "shape", "(", "data_blocks", "[", "0", "]", ")", "[", "0", "]", "size_y", "=", "numpy", ".", "shape", "(", "data_blocks", "[", "0", "]", ")", "[", "1", "]", "size_z", "=", "numpy", ".", "shape", "(", "data_blocks", "[", "0", "]", ")", "[", "2", "]", "size_t", "=", "len", "(", "data_blocks", ")", "full_block", "=", "numpy", ".", "zeros", "(", "(", "size_x", ",", "size_y", ",", "size_z", ",", "size_t", ")", ",", "dtype", "=", "data_blocks", "[", "0", "]", ".", "dtype", ")", "for", "index", "in", "range", "(", "0", ",", "size_t", ")", ":", "full_block", "[", ":", ",", ":", ",", ":", ",", "index", "]", "=", "data_blocks", "[", "index", "]", "return", "full_block" ]
Generate a full datablock containing all timepoints
[ "Generate", "a", "full", "datablock", "containing", "all", "timepoints" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L270-L289
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_mosaic_get_full_block
def _mosaic_get_full_block(sorted_mosaics): """ Generate a full datablock containing all timepoints """ # For each slice / mosaic create a data volume block data_blocks = [] for index in range(0, len(sorted_mosaics)): data_blocks.append(_mosaic_to_block(sorted_mosaics[index])) # Add the data_blocks together to one 4d block size_x = numpy.shape(data_blocks[0])[0] size_y = numpy.shape(data_blocks[0])[1] size_z = numpy.shape(data_blocks[0])[2] size_t = len(data_blocks) full_block = numpy.zeros((size_x, size_y, size_z, size_t), dtype=data_blocks[0].dtype) for index in range(0, size_t): full_block[:, :, :, index] = data_blocks[index] # Apply the rescaling if needed common.apply_scaling(full_block, sorted_mosaics[0]) return full_block
python
def _mosaic_get_full_block(sorted_mosaics): data_blocks = [] for index in range(0, len(sorted_mosaics)): data_blocks.append(_mosaic_to_block(sorted_mosaics[index])) size_x = numpy.shape(data_blocks[0])[0] size_y = numpy.shape(data_blocks[0])[1] size_z = numpy.shape(data_blocks[0])[2] size_t = len(data_blocks) full_block = numpy.zeros((size_x, size_y, size_z, size_t), dtype=data_blocks[0].dtype) for index in range(0, size_t): full_block[:, :, :, index] = data_blocks[index] common.apply_scaling(full_block, sorted_mosaics[0]) return full_block
[ "def", "_mosaic_get_full_block", "(", "sorted_mosaics", ")", ":", "# For each slice / mosaic create a data volume block", "data_blocks", "=", "[", "]", "for", "index", "in", "range", "(", "0", ",", "len", "(", "sorted_mosaics", ")", ")", ":", "data_blocks", ".", "append", "(", "_mosaic_to_block", "(", "sorted_mosaics", "[", "index", "]", ")", ")", "# Add the data_blocks together to one 4d block", "size_x", "=", "numpy", ".", "shape", "(", "data_blocks", "[", "0", "]", ")", "[", "0", "]", "size_y", "=", "numpy", ".", "shape", "(", "data_blocks", "[", "0", "]", ")", "[", "1", "]", "size_z", "=", "numpy", ".", "shape", "(", "data_blocks", "[", "0", "]", ")", "[", "2", "]", "size_t", "=", "len", "(", "data_blocks", ")", "full_block", "=", "numpy", ".", "zeros", "(", "(", "size_x", ",", "size_y", ",", "size_z", ",", "size_t", ")", ",", "dtype", "=", "data_blocks", "[", "0", "]", ".", "dtype", ")", "for", "index", "in", "range", "(", "0", ",", "size_t", ")", ":", "full_block", "[", ":", ",", ":", ",", ":", ",", "index", "]", "=", "data_blocks", "[", "index", "]", "# Apply the rescaling if needed", "common", ".", "apply_scaling", "(", "full_block", ",", "sorted_mosaics", "[", "0", "]", ")", "return", "full_block" ]
Generate a full datablock containing all timepoints
[ "Generate", "a", "full", "datablock", "containing", "all", "timepoints" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L300-L321
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_get_sorted_mosaics
def _get_sorted_mosaics(dicom_input): """ Search all mosaics in the dicom directory, sort and validate them """ # Order all dicom files by acquisition number sorted_mosaics = sorted(dicom_input, key=lambda x: x.AcquisitionNumber) for index in range(0, len(sorted_mosaics) - 1): # Validate that there are no duplicate AcquisitionNumber if sorted_mosaics[index].AcquisitionNumber >= sorted_mosaics[index + 1].AcquisitionNumber: raise ConversionValidationError("INCONSISTENT_ACQUISITION_NUMBERS") return sorted_mosaics
python
def _get_sorted_mosaics(dicom_input): sorted_mosaics = sorted(dicom_input, key=lambda x: x.AcquisitionNumber) for index in range(0, len(sorted_mosaics) - 1): if sorted_mosaics[index].AcquisitionNumber >= sorted_mosaics[index + 1].AcquisitionNumber: raise ConversionValidationError("INCONSISTENT_ACQUISITION_NUMBERS") return sorted_mosaics
[ "def", "_get_sorted_mosaics", "(", "dicom_input", ")", ":", "# Order all dicom files by acquisition number", "sorted_mosaics", "=", "sorted", "(", "dicom_input", ",", "key", "=", "lambda", "x", ":", "x", ".", "AcquisitionNumber", ")", "for", "index", "in", "range", "(", "0", ",", "len", "(", "sorted_mosaics", ")", "-", "1", ")", ":", "# Validate that there are no duplicate AcquisitionNumber", "if", "sorted_mosaics", "[", "index", "]", ".", "AcquisitionNumber", ">=", "sorted_mosaics", "[", "index", "+", "1", "]", ".", "AcquisitionNumber", ":", "raise", "ConversionValidationError", "(", "\"INCONSISTENT_ACQUISITION_NUMBERS\"", ")", "return", "sorted_mosaics" ]
Search all mosaics in the dicom directory, sort and validate them
[ "Search", "all", "mosaics", "in", "the", "dicom", "directory", "sort", "and", "validate", "them" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L324-L336
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_get_asconv_headers
def _get_asconv_headers(mosaic): """ Getter for the asconv headers (asci header info stored in the dicom) """ asconv_headers = re.findall(r'### ASCCONV BEGIN(.*)### ASCCONV END ###', mosaic[Tag(0x0029, 0x1020)].value.decode(encoding='ISO-8859-1'), re.DOTALL)[0] return asconv_headers
python
def _get_asconv_headers(mosaic): asconv_headers = re.findall(r' mosaic[Tag(0x0029, 0x1020)].value.decode(encoding='ISO-8859-1'), re.DOTALL)[0] return asconv_headers
[ "def", "_get_asconv_headers", "(", "mosaic", ")", ":", "asconv_headers", "=", "re", ".", "findall", "(", "r'### ASCCONV BEGIN(.*)### ASCCONV END ###'", ",", "mosaic", "[", "Tag", "(", "0x0029", ",", "0x1020", ")", "]", ".", "value", ".", "decode", "(", "encoding", "=", "'ISO-8859-1'", ")", ",", "re", ".", "DOTALL", ")", "[", "0", "]", "return", "asconv_headers" ]
Getter for the asconv headers (asci header info stored in the dicom)
[ "Getter", "for", "the", "asconv", "headers", "(", "asci", "header", "info", "stored", "in", "the", "dicom", ")" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L339-L347
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_get_mosaic_type
def _get_mosaic_type(mosaic): """ Check the extra ascconv headers for the mosaic type based on the slice position We always assume axial in this case the implementation resembles the last lines of documentation in https://www.icts.uiowa.edu/confluence/plugins/viewsource/viewpagesrc.action?pageId=54756326 """ ascconv_headers = _get_asconv_headers(mosaic) try: size = int(re.findall(r'sSliceArray\.lSize\s*=\s*(\d+)', ascconv_headers)[0]) # get the locations of the slices slice_location = [None] * size for index in range(size): axial_result = re.findall( r'sSliceArray\.asSlice\[%s\]\.sPosition\.dTra\s*=\s*([-+]?[0-9]*\.?[0-9]*)' % index, ascconv_headers) if len(axial_result) > 0: axial = float(axial_result[0]) else: axial = 0.0 slice_location[index] = axial # should we invert (https://www.icts.uiowa.edu/confluence/plugins/viewsource/viewpagesrc.action?pageId=54756326) invert = False invert_result = re.findall(r'sSliceArray\.ucImageNumbTra\s*=\s*([-+]?0?x?[0-9]+)', ascconv_headers) if len(invert_result) > 0: invert_value = int(invert_result[0], 16) if invert_value >= 0: invert = True # return the correct slice types if slice_location[0] <= slice_location[1]: if not invert: return MosaicType.ASCENDING else: return MosaicType.DESCENDING else: if not invert: return MosaicType.DESCENDING else: return MosaicType.ASCENDING except: traceback.print_exc() raise ConversionError("MOSAIC_TYPE_NOT_SUPPORTED")
python
def _get_mosaic_type(mosaic): ascconv_headers = _get_asconv_headers(mosaic) try: size = int(re.findall(r'sSliceArray\.lSize\s*=\s*(\d+)', ascconv_headers)[0]) slice_location = [None] * size for index in range(size): axial_result = re.findall( r'sSliceArray\.asSlice\[%s\]\.sPosition\.dTra\s*=\s*([-+]?[0-9]*\.?[0-9]*)' % index, ascconv_headers) if len(axial_result) > 0: axial = float(axial_result[0]) else: axial = 0.0 slice_location[index] = axial invert = False invert_result = re.findall(r'sSliceArray\.ucImageNumbTra\s*=\s*([-+]?0?x?[0-9]+)', ascconv_headers) if len(invert_result) > 0: invert_value = int(invert_result[0], 16) if invert_value >= 0: invert = True if slice_location[0] <= slice_location[1]: if not invert: return MosaicType.ASCENDING else: return MosaicType.DESCENDING else: if not invert: return MosaicType.DESCENDING else: return MosaicType.ASCENDING except: traceback.print_exc() raise ConversionError("MOSAIC_TYPE_NOT_SUPPORTED")
[ "def", "_get_mosaic_type", "(", "mosaic", ")", ":", "ascconv_headers", "=", "_get_asconv_headers", "(", "mosaic", ")", "try", ":", "size", "=", "int", "(", "re", ".", "findall", "(", "r'sSliceArray\\.lSize\\s*=\\s*(\\d+)'", ",", "ascconv_headers", ")", "[", "0", "]", ")", "# get the locations of the slices", "slice_location", "=", "[", "None", "]", "*", "size", "for", "index", "in", "range", "(", "size", ")", ":", "axial_result", "=", "re", ".", "findall", "(", "r'sSliceArray\\.asSlice\\[%s\\]\\.sPosition\\.dTra\\s*=\\s*([-+]?[0-9]*\\.?[0-9]*)'", "%", "index", ",", "ascconv_headers", ")", "if", "len", "(", "axial_result", ")", ">", "0", ":", "axial", "=", "float", "(", "axial_result", "[", "0", "]", ")", "else", ":", "axial", "=", "0.0", "slice_location", "[", "index", "]", "=", "axial", "# should we invert (https://www.icts.uiowa.edu/confluence/plugins/viewsource/viewpagesrc.action?pageId=54756326)", "invert", "=", "False", "invert_result", "=", "re", ".", "findall", "(", "r'sSliceArray\\.ucImageNumbTra\\s*=\\s*([-+]?0?x?[0-9]+)'", ",", "ascconv_headers", ")", "if", "len", "(", "invert_result", ")", ">", "0", ":", "invert_value", "=", "int", "(", "invert_result", "[", "0", "]", ",", "16", ")", "if", "invert_value", ">=", "0", ":", "invert", "=", "True", "# return the correct slice types", "if", "slice_location", "[", "0", "]", "<=", "slice_location", "[", "1", "]", ":", "if", "not", "invert", ":", "return", "MosaicType", ".", "ASCENDING", "else", ":", "return", "MosaicType", ".", "DESCENDING", "else", ":", "if", "not", "invert", ":", "return", "MosaicType", ".", "DESCENDING", "else", ":", "return", "MosaicType", ".", "ASCENDING", "except", ":", "traceback", ".", "print_exc", "(", ")", "raise", "ConversionError", "(", "\"MOSAIC_TYPE_NOT_SUPPORTED\"", ")" ]
Check the extra ascconv headers for the mosaic type based on the slice position We always assume axial in this case the implementation resembles the last lines of documentation in https://www.icts.uiowa.edu/confluence/plugins/viewsource/viewpagesrc.action?pageId=54756326
[ "Check", "the", "extra", "ascconv", "headers", "for", "the", "mosaic", "type", "based", "on", "the", "slice", "position", "We", "always", "assume", "axial", "in", "this", "case", "the", "implementation", "resembles", "the", "last", "lines", "of", "documentation", "in", "https", ":", "//", "www", ".", "icts", ".", "uiowa", ".", "edu", "/", "confluence", "/", "plugins", "/", "viewsource", "/", "viewpagesrc", ".", "action?pageId", "=", "54756326" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L350-L396
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_mosaic_to_block
def _mosaic_to_block(mosaic): """ Convert a mosaic slice to a block of data by reading the headers, splitting the mosaic and appending """ # get the mosaic type mosaic_type = _get_mosaic_type(mosaic) # get the size of one tile format is 64p*64 or 80*80 or something similar matches = re.findall(r'(\d+)\D+(\d+)\D*', str(mosaic[Tag(0x0051, 0x100b)].value))[0] ascconv_headers = _get_asconv_headers(mosaic) size = [int(matches[0]), int(matches[1]), int(re.findall(r'sSliceArray\.lSize\s*=\s*(\d+)', ascconv_headers)[0])] # get the number of rows and columns number_x = int(mosaic.Rows / size[0]) number_y = int(mosaic.Columns / size[1]) # recreate 2d slice data_2d = mosaic.pixel_array # create 3d block data_3d = numpy.zeros((size[2], size[1], size[0]), dtype=data_2d.dtype) # fill 3d block by taking the correct portions of the slice z_index = 0 for y_index in range(0, number_y): if z_index >= size[2]: break for x_index in range(0, number_x): if mosaic_type == MosaicType.ASCENDING: data_3d[z_index, :, :] = data_2d[size[1] * y_index:size[1] * (y_index + 1), size[0] * x_index:size[0] * (x_index + 1)] else: data_3d[size[2] - (z_index + 1), :, :] = data_2d[size[1] * y_index:size[1] * (y_index + 1), size[0] * x_index:size[0] * (x_index + 1)] z_index += 1 if z_index >= size[2]: break # reorient the block of data data_3d = numpy.transpose(data_3d, (2, 1, 0)) return data_3d
python
def _mosaic_to_block(mosaic): mosaic_type = _get_mosaic_type(mosaic) matches = re.findall(r'(\d+)\D+(\d+)\D*', str(mosaic[Tag(0x0051, 0x100b)].value))[0] ascconv_headers = _get_asconv_headers(mosaic) size = [int(matches[0]), int(matches[1]), int(re.findall(r'sSliceArray\.lSize\s*=\s*(\d+)', ascconv_headers)[0])] number_x = int(mosaic.Rows / size[0]) number_y = int(mosaic.Columns / size[1]) data_2d = mosaic.pixel_array data_3d = numpy.zeros((size[2], size[1], size[0]), dtype=data_2d.dtype) z_index = 0 for y_index in range(0, number_y): if z_index >= size[2]: break for x_index in range(0, number_x): if mosaic_type == MosaicType.ASCENDING: data_3d[z_index, :, :] = data_2d[size[1] * y_index:size[1] * (y_index + 1), size[0] * x_index:size[0] * (x_index + 1)] else: data_3d[size[2] - (z_index + 1), :, :] = data_2d[size[1] * y_index:size[1] * (y_index + 1), size[0] * x_index:size[0] * (x_index + 1)] z_index += 1 if z_index >= size[2]: break data_3d = numpy.transpose(data_3d, (2, 1, 0)) return data_3d
[ "def", "_mosaic_to_block", "(", "mosaic", ")", ":", "# get the mosaic type", "mosaic_type", "=", "_get_mosaic_type", "(", "mosaic", ")", "# get the size of one tile format is 64p*64 or 80*80 or something similar", "matches", "=", "re", ".", "findall", "(", "r'(\\d+)\\D+(\\d+)\\D*'", ",", "str", "(", "mosaic", "[", "Tag", "(", "0x0051", ",", "0x100b", ")", "]", ".", "value", ")", ")", "[", "0", "]", "ascconv_headers", "=", "_get_asconv_headers", "(", "mosaic", ")", "size", "=", "[", "int", "(", "matches", "[", "0", "]", ")", ",", "int", "(", "matches", "[", "1", "]", ")", ",", "int", "(", "re", ".", "findall", "(", "r'sSliceArray\\.lSize\\s*=\\s*(\\d+)'", ",", "ascconv_headers", ")", "[", "0", "]", ")", "]", "# get the number of rows and columns", "number_x", "=", "int", "(", "mosaic", ".", "Rows", "/", "size", "[", "0", "]", ")", "number_y", "=", "int", "(", "mosaic", ".", "Columns", "/", "size", "[", "1", "]", ")", "# recreate 2d slice", "data_2d", "=", "mosaic", ".", "pixel_array", "# create 3d block", "data_3d", "=", "numpy", ".", "zeros", "(", "(", "size", "[", "2", "]", ",", "size", "[", "1", "]", ",", "size", "[", "0", "]", ")", ",", "dtype", "=", "data_2d", ".", "dtype", ")", "# fill 3d block by taking the correct portions of the slice", "z_index", "=", "0", "for", "y_index", "in", "range", "(", "0", ",", "number_y", ")", ":", "if", "z_index", ">=", "size", "[", "2", "]", ":", "break", "for", "x_index", "in", "range", "(", "0", ",", "number_x", ")", ":", "if", "mosaic_type", "==", "MosaicType", ".", "ASCENDING", ":", "data_3d", "[", "z_index", ",", ":", ",", ":", "]", "=", "data_2d", "[", "size", "[", "1", "]", "*", "y_index", ":", "size", "[", "1", "]", "*", "(", "y_index", "+", "1", ")", ",", "size", "[", "0", "]", "*", "x_index", ":", "size", "[", "0", "]", "*", "(", "x_index", "+", "1", ")", "]", "else", ":", "data_3d", "[", "size", "[", "2", "]", "-", "(", "z_index", "+", "1", ")", ",", ":", ",", ":", "]", "=", "data_2d", "[", "size", "[", "1", "]", "*", "y_index", ":", "size", "[", "1", "]", "*", "(", "y_index", "+", "1", ")", ",", "size", "[", "0", "]", "*", "x_index", ":", "size", "[", "0", "]", "*", "(", "x_index", "+", "1", ")", "]", "z_index", "+=", "1", "if", "z_index", ">=", "size", "[", "2", "]", ":", "break", "# reorient the block of data", "data_3d", "=", "numpy", ".", "transpose", "(", "data_3d", ",", "(", "2", ",", "1", ",", "0", ")", ")", "return", "data_3d" ]
Convert a mosaic slice to a block of data by reading the headers, splitting the mosaic and appending
[ "Convert", "a", "mosaic", "slice", "to", "a", "block", "of", "data", "by", "reading", "the", "headers", "splitting", "the", "mosaic", "and", "appending" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L399-L440
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_create_affine_siemens_mosaic
def _create_affine_siemens_mosaic(dicom_input): """ Function to create the affine matrix for a siemens mosaic dataset This will work for siemens dti and 4d if in mosaic format """ # read dicom series with pds dicom_header = dicom_input[0] # Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine) image_orient1 = numpy.array(dicom_header.ImageOrientationPatient)[0:3] image_orient2 = numpy.array(dicom_header.ImageOrientationPatient)[3:6] normal = numpy.cross(image_orient1, image_orient2) delta_r = float(dicom_header.PixelSpacing[0]) delta_c = float(dicom_header.PixelSpacing[1]) image_pos = dicom_header.ImagePositionPatient delta_s = dicom_header.SpacingBetweenSlices return numpy.array( [[-image_orient1[0] * delta_c, -image_orient2[0] * delta_r, -delta_s * normal[0], -image_pos[0]], [-image_orient1[1] * delta_c, -image_orient2[1] * delta_r, -delta_s * normal[1], -image_pos[1]], [image_orient1[2] * delta_c, image_orient2[2] * delta_r, delta_s * normal[2], image_pos[2]], [0, 0, 0, 1]])
python
def _create_affine_siemens_mosaic(dicom_input): dicom_header = dicom_input[0] image_orient1 = numpy.array(dicom_header.ImageOrientationPatient)[0:3] image_orient2 = numpy.array(dicom_header.ImageOrientationPatient)[3:6] normal = numpy.cross(image_orient1, image_orient2) delta_r = float(dicom_header.PixelSpacing[0]) delta_c = float(dicom_header.PixelSpacing[1]) image_pos = dicom_header.ImagePositionPatient delta_s = dicom_header.SpacingBetweenSlices return numpy.array( [[-image_orient1[0] * delta_c, -image_orient2[0] * delta_r, -delta_s * normal[0], -image_pos[0]], [-image_orient1[1] * delta_c, -image_orient2[1] * delta_r, -delta_s * normal[1], -image_pos[1]], [image_orient1[2] * delta_c, image_orient2[2] * delta_r, delta_s * normal[2], image_pos[2]], [0, 0, 0, 1]])
[ "def", "_create_affine_siemens_mosaic", "(", "dicom_input", ")", ":", "# read dicom series with pds", "dicom_header", "=", "dicom_input", "[", "0", "]", "# Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine)", "image_orient1", "=", "numpy", ".", "array", "(", "dicom_header", ".", "ImageOrientationPatient", ")", "[", "0", ":", "3", "]", "image_orient2", "=", "numpy", ".", "array", "(", "dicom_header", ".", "ImageOrientationPatient", ")", "[", "3", ":", "6", "]", "normal", "=", "numpy", ".", "cross", "(", "image_orient1", ",", "image_orient2", ")", "delta_r", "=", "float", "(", "dicom_header", ".", "PixelSpacing", "[", "0", "]", ")", "delta_c", "=", "float", "(", "dicom_header", ".", "PixelSpacing", "[", "1", "]", ")", "image_pos", "=", "dicom_header", ".", "ImagePositionPatient", "delta_s", "=", "dicom_header", ".", "SpacingBetweenSlices", "return", "numpy", ".", "array", "(", "[", "[", "-", "image_orient1", "[", "0", "]", "*", "delta_c", ",", "-", "image_orient2", "[", "0", "]", "*", "delta_r", ",", "-", "delta_s", "*", "normal", "[", "0", "]", ",", "-", "image_pos", "[", "0", "]", "]", ",", "[", "-", "image_orient1", "[", "1", "]", "*", "delta_c", ",", "-", "image_orient2", "[", "1", "]", "*", "delta_r", ",", "-", "delta_s", "*", "normal", "[", "1", "]", ",", "-", "image_pos", "[", "1", "]", "]", ",", "[", "image_orient1", "[", "2", "]", "*", "delta_c", ",", "image_orient2", "[", "2", "]", "*", "delta_r", ",", "delta_s", "*", "normal", "[", "2", "]", ",", "image_pos", "[", "2", "]", "]", ",", "[", "0", ",", "0", ",", "0", ",", "1", "]", "]", ")" ]
Function to create the affine matrix for a siemens mosaic dataset This will work for siemens dti and 4d if in mosaic format
[ "Function", "to", "create", "the", "affine", "matrix", "for", "a", "siemens", "mosaic", "dataset", "This", "will", "work", "for", "siemens", "dti", "and", "4d", "if", "in", "mosaic", "format" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L443-L467
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_create_bvals
def _create_bvals(sorted_dicoms, bval_file): """ Write the bvals from the sorted dicom files to a bval file """ bvals = [] for index in range(0, len(sorted_dicoms)): if type(sorted_dicoms[0]) is list: dicom_headers = sorted_dicoms[index][0] else: dicom_headers = sorted_dicoms[index] bvals.append(common.get_is_value(dicom_headers[Tag(0x0019, 0x100c)])) # save the found bvecs to the file common.write_bval_file(bvals, bval_file) return numpy.array(bvals)
python
def _create_bvals(sorted_dicoms, bval_file): bvals = [] for index in range(0, len(sorted_dicoms)): if type(sorted_dicoms[0]) is list: dicom_headers = sorted_dicoms[index][0] else: dicom_headers = sorted_dicoms[index] bvals.append(common.get_is_value(dicom_headers[Tag(0x0019, 0x100c)])) common.write_bval_file(bvals, bval_file) return numpy.array(bvals)
[ "def", "_create_bvals", "(", "sorted_dicoms", ",", "bval_file", ")", ":", "bvals", "=", "[", "]", "for", "index", "in", "range", "(", "0", ",", "len", "(", "sorted_dicoms", ")", ")", ":", "if", "type", "(", "sorted_dicoms", "[", "0", "]", ")", "is", "list", ":", "dicom_headers", "=", "sorted_dicoms", "[", "index", "]", "[", "0", "]", "else", ":", "dicom_headers", "=", "sorted_dicoms", "[", "index", "]", "bvals", ".", "append", "(", "common", ".", "get_is_value", "(", "dicom_headers", "[", "Tag", "(", "0x0019", ",", "0x100c", ")", "]", ")", ")", "# save the found bvecs to the file", "common", ".", "write_bval_file", "(", "bvals", ",", "bval_file", ")", "return", "numpy", ".", "array", "(", "bvals", ")" ]
Write the bvals from the sorted dicom files to a bval file
[ "Write", "the", "bvals", "from", "the", "sorted", "dicom", "files", "to", "a", "bval", "file" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L470-L484
icometrix/dicom2nifti
dicom2nifti/convert_siemens.py
_create_bvecs
def _create_bvecs(sorted_dicoms, bvec_file): """ Calculate the bvecs and write the to a bvec file # inspired by dicom2nii from mricron # see http://users.fmrib.ox.ac.uk/~robson/internal/Dicom2Nifti111.m """ if type(sorted_dicoms[0]) is list: dicom_headers = sorted_dicoms[0][0] else: dicom_headers = sorted_dicoms[0] # get the patient orientation image_orientation = dicom_headers.ImageOrientationPatient read_vector = numpy.array([float(image_orientation[0]), float(image_orientation[1]), float(image_orientation[2])]) phase_vector = numpy.array([float(image_orientation[3]), float(image_orientation[4]), float(image_orientation[5])]) mosaic_vector = numpy.cross(read_vector, phase_vector) # normalize the vectors read_vector /= numpy.linalg.norm(read_vector) phase_vector /= numpy.linalg.norm(phase_vector) mosaic_vector /= numpy.linalg.norm(mosaic_vector) # create an empty array for the new bvecs bvecs = numpy.zeros([len(sorted_dicoms), 3]) # for each slice calculate the new bvec for index in range(0, len(sorted_dicoms)): if type(sorted_dicoms[0]) is list: dicom_headers = sorted_dicoms[index][0] else: dicom_headers = sorted_dicoms[index] # get the bval als this is needed in some checks bval = common.get_is_value(dicom_headers[Tag(0x0019, 0x100c)]) # get the bvec if it exists in the headers bvec = numpy.array([0, 0, 0]) if Tag(0x0019, 0x100e) in dicom_headers: # in case of implicit VR the private field cannot be split into an array, we do this here bvec = numpy.array(common.get_fd_array_value(dicom_headers[Tag(0x0019, 0x100e)], 3)) # if bval is 0 or the vector is 0 no projection is needed and the vector is 0,0,0 new_bvec = numpy.array([0, 0, 0]) if bval > 0 and not (bvec == [0, 0, 0]).all(): # project the bvec and invert the y direction new_bvec = numpy.array( [numpy.dot(bvec, read_vector), -numpy.dot(bvec, phase_vector), numpy.dot(bvec, mosaic_vector)]) # normalize the bvec new_bvec /= numpy.linalg.norm(new_bvec) bvecs[index, :] = new_bvec # save the found bvecs to the file common.write_bvec_file(bvecs, bvec_file) return numpy.array(bvecs)
python
def _create_bvecs(sorted_dicoms, bvec_file): if type(sorted_dicoms[0]) is list: dicom_headers = sorted_dicoms[0][0] else: dicom_headers = sorted_dicoms[0] image_orientation = dicom_headers.ImageOrientationPatient read_vector = numpy.array([float(image_orientation[0]), float(image_orientation[1]), float(image_orientation[2])]) phase_vector = numpy.array([float(image_orientation[3]), float(image_orientation[4]), float(image_orientation[5])]) mosaic_vector = numpy.cross(read_vector, phase_vector) read_vector /= numpy.linalg.norm(read_vector) phase_vector /= numpy.linalg.norm(phase_vector) mosaic_vector /= numpy.linalg.norm(mosaic_vector) bvecs = numpy.zeros([len(sorted_dicoms), 3]) for index in range(0, len(sorted_dicoms)): if type(sorted_dicoms[0]) is list: dicom_headers = sorted_dicoms[index][0] else: dicom_headers = sorted_dicoms[index] bval = common.get_is_value(dicom_headers[Tag(0x0019, 0x100c)]) bvec = numpy.array([0, 0, 0]) if Tag(0x0019, 0x100e) in dicom_headers: bvec = numpy.array(common.get_fd_array_value(dicom_headers[Tag(0x0019, 0x100e)], 3)) new_bvec = numpy.array([0, 0, 0]) if bval > 0 and not (bvec == [0, 0, 0]).all(): new_bvec = numpy.array( [numpy.dot(bvec, read_vector), -numpy.dot(bvec, phase_vector), numpy.dot(bvec, mosaic_vector)]) new_bvec /= numpy.linalg.norm(new_bvec) bvecs[index, :] = new_bvec common.write_bvec_file(bvecs, bvec_file) return numpy.array(bvecs)
[ "def", "_create_bvecs", "(", "sorted_dicoms", ",", "bvec_file", ")", ":", "if", "type", "(", "sorted_dicoms", "[", "0", "]", ")", "is", "list", ":", "dicom_headers", "=", "sorted_dicoms", "[", "0", "]", "[", "0", "]", "else", ":", "dicom_headers", "=", "sorted_dicoms", "[", "0", "]", "# get the patient orientation", "image_orientation", "=", "dicom_headers", ".", "ImageOrientationPatient", "read_vector", "=", "numpy", ".", "array", "(", "[", "float", "(", "image_orientation", "[", "0", "]", ")", ",", "float", "(", "image_orientation", "[", "1", "]", ")", ",", "float", "(", "image_orientation", "[", "2", "]", ")", "]", ")", "phase_vector", "=", "numpy", ".", "array", "(", "[", "float", "(", "image_orientation", "[", "3", "]", ")", ",", "float", "(", "image_orientation", "[", "4", "]", ")", ",", "float", "(", "image_orientation", "[", "5", "]", ")", "]", ")", "mosaic_vector", "=", "numpy", ".", "cross", "(", "read_vector", ",", "phase_vector", ")", "# normalize the vectors", "read_vector", "/=", "numpy", ".", "linalg", ".", "norm", "(", "read_vector", ")", "phase_vector", "/=", "numpy", ".", "linalg", ".", "norm", "(", "phase_vector", ")", "mosaic_vector", "/=", "numpy", ".", "linalg", ".", "norm", "(", "mosaic_vector", ")", "# create an empty array for the new bvecs", "bvecs", "=", "numpy", ".", "zeros", "(", "[", "len", "(", "sorted_dicoms", ")", ",", "3", "]", ")", "# for each slice calculate the new bvec", "for", "index", "in", "range", "(", "0", ",", "len", "(", "sorted_dicoms", ")", ")", ":", "if", "type", "(", "sorted_dicoms", "[", "0", "]", ")", "is", "list", ":", "dicom_headers", "=", "sorted_dicoms", "[", "index", "]", "[", "0", "]", "else", ":", "dicom_headers", "=", "sorted_dicoms", "[", "index", "]", "# get the bval als this is needed in some checks", "bval", "=", "common", ".", "get_is_value", "(", "dicom_headers", "[", "Tag", "(", "0x0019", ",", "0x100c", ")", "]", ")", "# get the bvec if it exists in the headers", "bvec", "=", "numpy", ".", "array", "(", "[", "0", ",", "0", ",", "0", "]", ")", "if", "Tag", "(", "0x0019", ",", "0x100e", ")", "in", "dicom_headers", ":", "# in case of implicit VR the private field cannot be split into an array, we do this here", "bvec", "=", "numpy", ".", "array", "(", "common", ".", "get_fd_array_value", "(", "dicom_headers", "[", "Tag", "(", "0x0019", ",", "0x100e", ")", "]", ",", "3", ")", ")", "# if bval is 0 or the vector is 0 no projection is needed and the vector is 0,0,0", "new_bvec", "=", "numpy", ".", "array", "(", "[", "0", ",", "0", ",", "0", "]", ")", "if", "bval", ">", "0", "and", "not", "(", "bvec", "==", "[", "0", ",", "0", ",", "0", "]", ")", ".", "all", "(", ")", ":", "# project the bvec and invert the y direction", "new_bvec", "=", "numpy", ".", "array", "(", "[", "numpy", ".", "dot", "(", "bvec", ",", "read_vector", ")", ",", "-", "numpy", ".", "dot", "(", "bvec", ",", "phase_vector", ")", ",", "numpy", ".", "dot", "(", "bvec", ",", "mosaic_vector", ")", "]", ")", "# normalize the bvec", "new_bvec", "/=", "numpy", ".", "linalg", ".", "norm", "(", "new_bvec", ")", "bvecs", "[", "index", ",", ":", "]", "=", "new_bvec", "# save the found bvecs to the file", "common", ".", "write_bvec_file", "(", "bvecs", ",", "bvec_file", ")", "return", "numpy", ".", "array", "(", "bvecs", ")" ]
Calculate the bvecs and write the to a bvec file # inspired by dicom2nii from mricron # see http://users.fmrib.ox.ac.uk/~robson/internal/Dicom2Nifti111.m
[ "Calculate", "the", "bvecs", "and", "write", "the", "to", "a", "bvec", "file", "#", "inspired", "by", "dicom2nii", "from", "mricron", "#", "see", "http", ":", "//", "users", ".", "fmrib", ".", "ox", ".", "ac", ".", "uk", "/", "~robson", "/", "internal", "/", "Dicom2Nifti111", ".", "m" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L487-L536
icometrix/dicom2nifti
dicom2nifti/resample.py
resample_single_nifti
def resample_single_nifti(input_nifti): """ Resample a gantry tilted image in place """ # read the input image input_image = nibabel.load(input_nifti) output_image = resample_nifti_images([input_image]) output_image.to_filename(input_nifti)
python
def resample_single_nifti(input_nifti): input_image = nibabel.load(input_nifti) output_image = resample_nifti_images([input_image]) output_image.to_filename(input_nifti)
[ "def", "resample_single_nifti", "(", "input_nifti", ")", ":", "# read the input image", "input_image", "=", "nibabel", ".", "load", "(", "input_nifti", ")", "output_image", "=", "resample_nifti_images", "(", "[", "input_image", "]", ")", "output_image", ".", "to_filename", "(", "input_nifti", ")" ]
Resample a gantry tilted image in place
[ "Resample", "a", "gantry", "tilted", "image", "in", "place" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/resample.py#L15-L22
icometrix/dicom2nifti
dicom2nifti/resample.py
resample_nifti_images
def resample_nifti_images(nifti_images): """ In this function we will create an orthogonal image and resample the original images to this space In this calculation we work in 3 spaces / coordinate systems - original image coordinates - world coordinates - "projected" coordinates This last one is a new rotated "orthogonal" coordinates system in mm where x and y are perpendicular with the x and y or the image We do the following steps - calculate a new "projection" coordinate system - calculate the world coordinates of all corners of the image in world coordinates - project the world coordinates of the corners on the projection coordinate system - calculate the min and max corners to get the orthogonal bounding box of the image in projected space - translate the origin back to world coordinages We now have the new xyz axis, origin and size and can create the new affine used for resampling """ # get the smallest voxelsize and use that voxel_size = nifti_images[0].header.get_zooms() for nifti_image in nifti_images[1:]: voxel_size = numpy.minimum(voxel_size, nifti_image.header.get_zooms()) x_axis_world = numpy.transpose(numpy.dot(nifti_images[0].affine, [[1], [0], [0], [0]]))[0, :3] y_axis_world = numpy.transpose(numpy.dot(nifti_images[0].affine, [[0], [1], [0], [0]]))[0, :3] x_axis_world /= numpy.linalg.norm(x_axis_world) # normalization y_axis_world /= numpy.linalg.norm(y_axis_world) # normalization z_axis_world = numpy.cross(y_axis_world, x_axis_world) z_axis_world /= numpy.linalg.norm(z_axis_world) # calculate new z y_axis_world = numpy.cross(x_axis_world, z_axis_world) # recalculate y in case x and y where not perpendicular y_axis_world /= numpy.linalg.norm(y_axis_world) points_world = [] for nifti_image in nifti_images: original_size = nifti_image.shape points_image = [[0, 0, 0], [original_size[0], 0, 0], [0, original_size[1], 0], [original_size[0], original_size[1], 0], [0, 0, original_size[2]], [original_size[0], 0, original_size[2]], [0, original_size[1], original_size[2]], [original_size[0], original_size[1], original_size[2]]] minaffine = nifti_images[0].affine maxaffine = nifti_images[-1].affine for point in points_image[:4]: points_world.append(numpy.transpose(numpy.dot(minaffine, [[point[0]], [point[1]], [point[2]], [1]]))[0, :3]) for point in points_image[4:]: points_world.append(numpy.transpose(numpy.dot(maxaffine, [[point[0]], [point[1]], [point[2]], [1]]))[0, :3]) projections = [] for point in points_world: projection = [numpy.dot(point, x_axis_world), numpy.dot(point, y_axis_world), numpy.dot(point, z_axis_world)] projections.append(projection) projections = numpy.array(projections) min_projected = numpy.amin(projections, axis=0) max_projected = numpy.amax(projections, axis=0) new_size_mm = max_projected - min_projected origin = min_projected[0] * x_axis_world + \ min_projected[1] * y_axis_world + \ min_projected[2] * z_axis_world new_voxelsize = voxel_size new_shape = numpy.ceil(new_size_mm / new_voxelsize).astype(numpy.int16) new_affine = _create_affine(x_axis_world, y_axis_world, z_axis_world, origin, voxel_size) # Resample each image resampled_images = [] for nifti_image in nifti_images: image_affine = nifti_image.affine combined_affine = numpy.linalg.inv(new_affine).dot(image_affine) matrix, offset = nibabel.affines.to_matvec(numpy.linalg.inv(combined_affine)) resampled_images.append(scipy.ndimage.affine_transform(nifti_image.get_data(), matrix=matrix, offset=offset, output_shape=new_shape, output=nifti_image.get_data().dtype, order=settings.resample_spline_interpolation_order, mode='constant', cval=settings.resample_padding, prefilter=False)) combined_image_data = numpy.full(new_shape, settings.resample_padding, dtype=resampled_images[0].dtype) for resampled_image in resampled_images: combined_image_data[combined_image_data == settings.resample_padding] = \ resampled_image[combined_image_data == settings.resample_padding] return nibabel.Nifti1Image(combined_image_data, new_affine)
python
def resample_nifti_images(nifti_images): voxel_size = nifti_images[0].header.get_zooms() for nifti_image in nifti_images[1:]: voxel_size = numpy.minimum(voxel_size, nifti_image.header.get_zooms()) x_axis_world = numpy.transpose(numpy.dot(nifti_images[0].affine, [[1], [0], [0], [0]]))[0, :3] y_axis_world = numpy.transpose(numpy.dot(nifti_images[0].affine, [[0], [1], [0], [0]]))[0, :3] x_axis_world /= numpy.linalg.norm(x_axis_world) y_axis_world /= numpy.linalg.norm(y_axis_world) z_axis_world = numpy.cross(y_axis_world, x_axis_world) z_axis_world /= numpy.linalg.norm(z_axis_world) y_axis_world = numpy.cross(x_axis_world, z_axis_world) y_axis_world /= numpy.linalg.norm(y_axis_world) points_world = [] for nifti_image in nifti_images: original_size = nifti_image.shape points_image = [[0, 0, 0], [original_size[0], 0, 0], [0, original_size[1], 0], [original_size[0], original_size[1], 0], [0, 0, original_size[2]], [original_size[0], 0, original_size[2]], [0, original_size[1], original_size[2]], [original_size[0], original_size[1], original_size[2]]] minaffine = nifti_images[0].affine maxaffine = nifti_images[-1].affine for point in points_image[:4]: points_world.append(numpy.transpose(numpy.dot(minaffine, [[point[0]], [point[1]], [point[2]], [1]]))[0, :3]) for point in points_image[4:]: points_world.append(numpy.transpose(numpy.dot(maxaffine, [[point[0]], [point[1]], [point[2]], [1]]))[0, :3]) projections = [] for point in points_world: projection = [numpy.dot(point, x_axis_world), numpy.dot(point, y_axis_world), numpy.dot(point, z_axis_world)] projections.append(projection) projections = numpy.array(projections) min_projected = numpy.amin(projections, axis=0) max_projected = numpy.amax(projections, axis=0) new_size_mm = max_projected - min_projected origin = min_projected[0] * x_axis_world + \ min_projected[1] * y_axis_world + \ min_projected[2] * z_axis_world new_voxelsize = voxel_size new_shape = numpy.ceil(new_size_mm / new_voxelsize).astype(numpy.int16) new_affine = _create_affine(x_axis_world, y_axis_world, z_axis_world, origin, voxel_size) resampled_images = [] for nifti_image in nifti_images: image_affine = nifti_image.affine combined_affine = numpy.linalg.inv(new_affine).dot(image_affine) matrix, offset = nibabel.affines.to_matvec(numpy.linalg.inv(combined_affine)) resampled_images.append(scipy.ndimage.affine_transform(nifti_image.get_data(), matrix=matrix, offset=offset, output_shape=new_shape, output=nifti_image.get_data().dtype, order=settings.resample_spline_interpolation_order, mode='constant', cval=settings.resample_padding, prefilter=False)) combined_image_data = numpy.full(new_shape, settings.resample_padding, dtype=resampled_images[0].dtype) for resampled_image in resampled_images: combined_image_data[combined_image_data == settings.resample_padding] = \ resampled_image[combined_image_data == settings.resample_padding] return nibabel.Nifti1Image(combined_image_data, new_affine)
[ "def", "resample_nifti_images", "(", "nifti_images", ")", ":", "# get the smallest voxelsize and use that", "voxel_size", "=", "nifti_images", "[", "0", "]", ".", "header", ".", "get_zooms", "(", ")", "for", "nifti_image", "in", "nifti_images", "[", "1", ":", "]", ":", "voxel_size", "=", "numpy", ".", "minimum", "(", "voxel_size", ",", "nifti_image", ".", "header", ".", "get_zooms", "(", ")", ")", "x_axis_world", "=", "numpy", ".", "transpose", "(", "numpy", ".", "dot", "(", "nifti_images", "[", "0", "]", ".", "affine", ",", "[", "[", "1", "]", ",", "[", "0", "]", ",", "[", "0", "]", ",", "[", "0", "]", "]", ")", ")", "[", "0", ",", ":", "3", "]", "y_axis_world", "=", "numpy", ".", "transpose", "(", "numpy", ".", "dot", "(", "nifti_images", "[", "0", "]", ".", "affine", ",", "[", "[", "0", "]", ",", "[", "1", "]", ",", "[", "0", "]", ",", "[", "0", "]", "]", ")", ")", "[", "0", ",", ":", "3", "]", "x_axis_world", "/=", "numpy", ".", "linalg", ".", "norm", "(", "x_axis_world", ")", "# normalization", "y_axis_world", "/=", "numpy", ".", "linalg", ".", "norm", "(", "y_axis_world", ")", "# normalization", "z_axis_world", "=", "numpy", ".", "cross", "(", "y_axis_world", ",", "x_axis_world", ")", "z_axis_world", "/=", "numpy", ".", "linalg", ".", "norm", "(", "z_axis_world", ")", "# calculate new z", "y_axis_world", "=", "numpy", ".", "cross", "(", "x_axis_world", ",", "z_axis_world", ")", "# recalculate y in case x and y where not perpendicular", "y_axis_world", "/=", "numpy", ".", "linalg", ".", "norm", "(", "y_axis_world", ")", "points_world", "=", "[", "]", "for", "nifti_image", "in", "nifti_images", ":", "original_size", "=", "nifti_image", ".", "shape", "points_image", "=", "[", "[", "0", ",", "0", ",", "0", "]", ",", "[", "original_size", "[", "0", "]", ",", "0", ",", "0", "]", ",", "[", "0", ",", "original_size", "[", "1", "]", ",", "0", "]", ",", "[", "original_size", "[", "0", "]", ",", "original_size", "[", "1", "]", ",", "0", "]", ",", "[", "0", ",", "0", ",", "original_size", "[", "2", "]", "]", ",", "[", "original_size", "[", "0", "]", ",", "0", ",", "original_size", "[", "2", "]", "]", ",", "[", "0", ",", "original_size", "[", "1", "]", ",", "original_size", "[", "2", "]", "]", ",", "[", "original_size", "[", "0", "]", ",", "original_size", "[", "1", "]", ",", "original_size", "[", "2", "]", "]", "]", "minaffine", "=", "nifti_images", "[", "0", "]", ".", "affine", "maxaffine", "=", "nifti_images", "[", "-", "1", "]", ".", "affine", "for", "point", "in", "points_image", "[", ":", "4", "]", ":", "points_world", ".", "append", "(", "numpy", ".", "transpose", "(", "numpy", ".", "dot", "(", "minaffine", ",", "[", "[", "point", "[", "0", "]", "]", ",", "[", "point", "[", "1", "]", "]", ",", "[", "point", "[", "2", "]", "]", ",", "[", "1", "]", "]", ")", ")", "[", "0", ",", ":", "3", "]", ")", "for", "point", "in", "points_image", "[", "4", ":", "]", ":", "points_world", ".", "append", "(", "numpy", ".", "transpose", "(", "numpy", ".", "dot", "(", "maxaffine", ",", "[", "[", "point", "[", "0", "]", "]", ",", "[", "point", "[", "1", "]", "]", ",", "[", "point", "[", "2", "]", "]", ",", "[", "1", "]", "]", ")", ")", "[", "0", ",", ":", "3", "]", ")", "projections", "=", "[", "]", "for", "point", "in", "points_world", ":", "projection", "=", "[", "numpy", ".", "dot", "(", "point", ",", "x_axis_world", ")", ",", "numpy", ".", "dot", "(", "point", ",", "y_axis_world", ")", ",", "numpy", ".", "dot", "(", "point", ",", "z_axis_world", ")", "]", "projections", ".", "append", "(", "projection", ")", "projections", "=", "numpy", ".", "array", "(", "projections", ")", "min_projected", "=", "numpy", ".", "amin", "(", "projections", ",", "axis", "=", "0", ")", "max_projected", "=", "numpy", ".", "amax", "(", "projections", ",", "axis", "=", "0", ")", "new_size_mm", "=", "max_projected", "-", "min_projected", "origin", "=", "min_projected", "[", "0", "]", "*", "x_axis_world", "+", "min_projected", "[", "1", "]", "*", "y_axis_world", "+", "min_projected", "[", "2", "]", "*", "z_axis_world", "new_voxelsize", "=", "voxel_size", "new_shape", "=", "numpy", ".", "ceil", "(", "new_size_mm", "/", "new_voxelsize", ")", ".", "astype", "(", "numpy", ".", "int16", ")", "new_affine", "=", "_create_affine", "(", "x_axis_world", ",", "y_axis_world", ",", "z_axis_world", ",", "origin", ",", "voxel_size", ")", "# Resample each image", "resampled_images", "=", "[", "]", "for", "nifti_image", "in", "nifti_images", ":", "image_affine", "=", "nifti_image", ".", "affine", "combined_affine", "=", "numpy", ".", "linalg", ".", "inv", "(", "new_affine", ")", ".", "dot", "(", "image_affine", ")", "matrix", ",", "offset", "=", "nibabel", ".", "affines", ".", "to_matvec", "(", "numpy", ".", "linalg", ".", "inv", "(", "combined_affine", ")", ")", "resampled_images", ".", "append", "(", "scipy", ".", "ndimage", ".", "affine_transform", "(", "nifti_image", ".", "get_data", "(", ")", ",", "matrix", "=", "matrix", ",", "offset", "=", "offset", ",", "output_shape", "=", "new_shape", ",", "output", "=", "nifti_image", ".", "get_data", "(", ")", ".", "dtype", ",", "order", "=", "settings", ".", "resample_spline_interpolation_order", ",", "mode", "=", "'constant'", ",", "cval", "=", "settings", ".", "resample_padding", ",", "prefilter", "=", "False", ")", ")", "combined_image_data", "=", "numpy", ".", "full", "(", "new_shape", ",", "settings", ".", "resample_padding", ",", "dtype", "=", "resampled_images", "[", "0", "]", ".", "dtype", ")", "for", "resampled_image", "in", "resampled_images", ":", "combined_image_data", "[", "combined_image_data", "==", "settings", ".", "resample_padding", "]", "=", "resampled_image", "[", "combined_image_data", "==", "settings", ".", "resample_padding", "]", "return", "nibabel", ".", "Nifti1Image", "(", "combined_image_data", ",", "new_affine", ")" ]
In this function we will create an orthogonal image and resample the original images to this space In this calculation we work in 3 spaces / coordinate systems - original image coordinates - world coordinates - "projected" coordinates This last one is a new rotated "orthogonal" coordinates system in mm where x and y are perpendicular with the x and y or the image We do the following steps - calculate a new "projection" coordinate system - calculate the world coordinates of all corners of the image in world coordinates - project the world coordinates of the corners on the projection coordinate system - calculate the min and max corners to get the orthogonal bounding box of the image in projected space - translate the origin back to world coordinages We now have the new xyz axis, origin and size and can create the new affine used for resampling
[ "In", "this", "function", "we", "will", "create", "an", "orthogonal", "image", "and", "resample", "the", "original", "images", "to", "this", "space" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/resample.py#L25-L128
icometrix/dicom2nifti
dicom2nifti/resample.py
_create_affine
def _create_affine(x_axis, y_axis, z_axis, image_pos, voxel_sizes): """ Function to generate the affine matrix for a dicom series This method was based on (http://nipy.org/nibabel/dicom/dicom_orientation.html) :param sorted_dicoms: list with sorted dicom files """ # Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine) affine = numpy.array( [[x_axis[0] * voxel_sizes[0], y_axis[0] * voxel_sizes[1], z_axis[0] * voxel_sizes[2], image_pos[0]], [x_axis[1] * voxel_sizes[0], y_axis[1] * voxel_sizes[1], z_axis[1] * voxel_sizes[2], image_pos[1]], [x_axis[2] * voxel_sizes[0], y_axis[2] * voxel_sizes[1], z_axis[2] * voxel_sizes[2], image_pos[2]], [0, 0, 0, 1]]) return affine
python
def _create_affine(x_axis, y_axis, z_axis, image_pos, voxel_sizes): affine = numpy.array( [[x_axis[0] * voxel_sizes[0], y_axis[0] * voxel_sizes[1], z_axis[0] * voxel_sizes[2], image_pos[0]], [x_axis[1] * voxel_sizes[0], y_axis[1] * voxel_sizes[1], z_axis[1] * voxel_sizes[2], image_pos[1]], [x_axis[2] * voxel_sizes[0], y_axis[2] * voxel_sizes[1], z_axis[2] * voxel_sizes[2], image_pos[2]], [0, 0, 0, 1]]) return affine
[ "def", "_create_affine", "(", "x_axis", ",", "y_axis", ",", "z_axis", ",", "image_pos", ",", "voxel_sizes", ")", ":", "# Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine)", "affine", "=", "numpy", ".", "array", "(", "[", "[", "x_axis", "[", "0", "]", "*", "voxel_sizes", "[", "0", "]", ",", "y_axis", "[", "0", "]", "*", "voxel_sizes", "[", "1", "]", ",", "z_axis", "[", "0", "]", "*", "voxel_sizes", "[", "2", "]", ",", "image_pos", "[", "0", "]", "]", ",", "[", "x_axis", "[", "1", "]", "*", "voxel_sizes", "[", "0", "]", ",", "y_axis", "[", "1", "]", "*", "voxel_sizes", "[", "1", "]", ",", "z_axis", "[", "1", "]", "*", "voxel_sizes", "[", "2", "]", ",", "image_pos", "[", "1", "]", "]", ",", "[", "x_axis", "[", "2", "]", "*", "voxel_sizes", "[", "0", "]", ",", "y_axis", "[", "2", "]", "*", "voxel_sizes", "[", "1", "]", ",", "z_axis", "[", "2", "]", "*", "voxel_sizes", "[", "2", "]", ",", "image_pos", "[", "2", "]", "]", ",", "[", "0", ",", "0", ",", "0", ",", "1", "]", "]", ")", "return", "affine" ]
Function to generate the affine matrix for a dicom series This method was based on (http://nipy.org/nibabel/dicom/dicom_orientation.html) :param sorted_dicoms: list with sorted dicom files
[ "Function", "to", "generate", "the", "affine", "matrix", "for", "a", "dicom", "series", "This", "method", "was", "based", "on", "(", "http", ":", "//", "nipy", ".", "org", "/", "nibabel", "/", "dicom", "/", "dicom_orientation", ".", "html", ")" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/resample.py#L131-L146
icometrix/dicom2nifti
dicom2nifti/convert_dir.py
convert_directory
def convert_directory(dicom_directory, output_folder, compression=True, reorient=True): """ This function will order all dicom files by series and order them one by one :param compression: enable or disable gzip compression :param reorient: reorient the dicoms according to LAS orientation :param output_folder: folder to write the nifti files to :param dicom_directory: directory with dicom files """ # sort dicom files by series uid dicom_series = {} for root, _, files in os.walk(dicom_directory): for dicom_file in files: file_path = os.path.join(root, dicom_file) # noinspection PyBroadException try: if compressed_dicom.is_dicom_file(file_path): # read the dicom as fast as possible # (max length for SeriesInstanceUID is 64 so defer_size 100 should be ok) dicom_headers = compressed_dicom.read_file(file_path, defer_size="1 KB", stop_before_pixels=False, force=dicom2nifti.settings.pydicom_read_force) if not _is_valid_imaging_dicom(dicom_headers): logger.info("Skipping: %s" % file_path) continue logger.info("Organizing: %s" % file_path) if dicom_headers.SeriesInstanceUID not in dicom_series: dicom_series[dicom_headers.SeriesInstanceUID] = [] dicom_series[dicom_headers.SeriesInstanceUID].append(dicom_headers) except: # Explicitly capturing all errors here to be able to continue processing all the rest logger.warning("Unable to read: %s" % file_path) traceback.print_exc() # start converting one by one for series_id, dicom_input in iteritems(dicom_series): base_filename = "" # noinspection PyBroadException try: # construct the filename for the nifti base_filename = "" if 'SeriesNumber' in dicom_input[0]: base_filename = _remove_accents('%s' % dicom_input[0].SeriesNumber) if 'SeriesDescription' in dicom_input[0]: base_filename = _remove_accents('%s_%s' % (base_filename, dicom_input[0].SeriesDescription)) elif 'SequenceName' in dicom_input[0]: base_filename = _remove_accents('%s_%s' % (base_filename, dicom_input[0].SequenceName)) elif 'ProtocolName' in dicom_input[0]: base_filename = _remove_accents('%s_%s' % (base_filename, dicom_input[0].ProtocolName)) else: base_filename = _remove_accents(dicom_input[0].SeriesInstanceUID) logger.info('--------------------------------------------') logger.info('Start converting %s' % base_filename) if compression: nifti_file = os.path.join(output_folder, base_filename + '.nii.gz') else: nifti_file = os.path.join(output_folder, base_filename + '.nii') convert_dicom.dicom_array_to_nifti(dicom_input, nifti_file, reorient) gc.collect() except: # Explicitly capturing app exceptions here to be able to continue processing logger.info("Unable to convert: %s" % base_filename) traceback.print_exc()
python
def convert_directory(dicom_directory, output_folder, compression=True, reorient=True): dicom_series = {} for root, _, files in os.walk(dicom_directory): for dicom_file in files: file_path = os.path.join(root, dicom_file) try: if compressed_dicom.is_dicom_file(file_path): dicom_headers = compressed_dicom.read_file(file_path, defer_size="1 KB", stop_before_pixels=False, force=dicom2nifti.settings.pydicom_read_force) if not _is_valid_imaging_dicom(dicom_headers): logger.info("Skipping: %s" % file_path) continue logger.info("Organizing: %s" % file_path) if dicom_headers.SeriesInstanceUID not in dicom_series: dicom_series[dicom_headers.SeriesInstanceUID] = [] dicom_series[dicom_headers.SeriesInstanceUID].append(dicom_headers) except: logger.warning("Unable to read: %s" % file_path) traceback.print_exc() for series_id, dicom_input in iteritems(dicom_series): base_filename = "" try: base_filename = "" if 'SeriesNumber' in dicom_input[0]: base_filename = _remove_accents('%s' % dicom_input[0].SeriesNumber) if 'SeriesDescription' in dicom_input[0]: base_filename = _remove_accents('%s_%s' % (base_filename, dicom_input[0].SeriesDescription)) elif 'SequenceName' in dicom_input[0]: base_filename = _remove_accents('%s_%s' % (base_filename, dicom_input[0].SequenceName)) elif 'ProtocolName' in dicom_input[0]: base_filename = _remove_accents('%s_%s' % (base_filename, dicom_input[0].ProtocolName)) else: base_filename = _remove_accents(dicom_input[0].SeriesInstanceUID) logger.info('--------------------------------------------') logger.info('Start converting %s' % base_filename) if compression: nifti_file = os.path.join(output_folder, base_filename + '.nii.gz') else: nifti_file = os.path.join(output_folder, base_filename + '.nii') convert_dicom.dicom_array_to_nifti(dicom_input, nifti_file, reorient) gc.collect() except: logger.info("Unable to convert: %s" % base_filename) traceback.print_exc()
[ "def", "convert_directory", "(", "dicom_directory", ",", "output_folder", ",", "compression", "=", "True", ",", "reorient", "=", "True", ")", ":", "# sort dicom files by series uid", "dicom_series", "=", "{", "}", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "dicom_directory", ")", ":", "for", "dicom_file", "in", "files", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "dicom_file", ")", "# noinspection PyBroadException", "try", ":", "if", "compressed_dicom", ".", "is_dicom_file", "(", "file_path", ")", ":", "# read the dicom as fast as possible", "# (max length for SeriesInstanceUID is 64 so defer_size 100 should be ok)", "dicom_headers", "=", "compressed_dicom", ".", "read_file", "(", "file_path", ",", "defer_size", "=", "\"1 KB\"", ",", "stop_before_pixels", "=", "False", ",", "force", "=", "dicom2nifti", ".", "settings", ".", "pydicom_read_force", ")", "if", "not", "_is_valid_imaging_dicom", "(", "dicom_headers", ")", ":", "logger", ".", "info", "(", "\"Skipping: %s\"", "%", "file_path", ")", "continue", "logger", ".", "info", "(", "\"Organizing: %s\"", "%", "file_path", ")", "if", "dicom_headers", ".", "SeriesInstanceUID", "not", "in", "dicom_series", ":", "dicom_series", "[", "dicom_headers", ".", "SeriesInstanceUID", "]", "=", "[", "]", "dicom_series", "[", "dicom_headers", ".", "SeriesInstanceUID", "]", ".", "append", "(", "dicom_headers", ")", "except", ":", "# Explicitly capturing all errors here to be able to continue processing all the rest", "logger", ".", "warning", "(", "\"Unable to read: %s\"", "%", "file_path", ")", "traceback", ".", "print_exc", "(", ")", "# start converting one by one", "for", "series_id", ",", "dicom_input", "in", "iteritems", "(", "dicom_series", ")", ":", "base_filename", "=", "\"\"", "# noinspection PyBroadException", "try", ":", "# construct the filename for the nifti", "base_filename", "=", "\"\"", "if", "'SeriesNumber'", "in", "dicom_input", "[", "0", "]", ":", "base_filename", "=", "_remove_accents", "(", "'%s'", "%", "dicom_input", "[", "0", "]", ".", "SeriesNumber", ")", "if", "'SeriesDescription'", "in", "dicom_input", "[", "0", "]", ":", "base_filename", "=", "_remove_accents", "(", "'%s_%s'", "%", "(", "base_filename", ",", "dicom_input", "[", "0", "]", ".", "SeriesDescription", ")", ")", "elif", "'SequenceName'", "in", "dicom_input", "[", "0", "]", ":", "base_filename", "=", "_remove_accents", "(", "'%s_%s'", "%", "(", "base_filename", ",", "dicom_input", "[", "0", "]", ".", "SequenceName", ")", ")", "elif", "'ProtocolName'", "in", "dicom_input", "[", "0", "]", ":", "base_filename", "=", "_remove_accents", "(", "'%s_%s'", "%", "(", "base_filename", ",", "dicom_input", "[", "0", "]", ".", "ProtocolName", ")", ")", "else", ":", "base_filename", "=", "_remove_accents", "(", "dicom_input", "[", "0", "]", ".", "SeriesInstanceUID", ")", "logger", ".", "info", "(", "'--------------------------------------------'", ")", "logger", ".", "info", "(", "'Start converting %s'", "%", "base_filename", ")", "if", "compression", ":", "nifti_file", "=", "os", ".", "path", ".", "join", "(", "output_folder", ",", "base_filename", "+", "'.nii.gz'", ")", "else", ":", "nifti_file", "=", "os", ".", "path", ".", "join", "(", "output_folder", ",", "base_filename", "+", "'.nii'", ")", "convert_dicom", ".", "dicom_array_to_nifti", "(", "dicom_input", ",", "nifti_file", ",", "reorient", ")", "gc", ".", "collect", "(", ")", "except", ":", "# Explicitly capturing app exceptions here to be able to continue processing", "logger", ".", "info", "(", "\"Unable to convert: %s\"", "%", "base_filename", ")", "traceback", ".", "print_exc", "(", ")" ]
This function will order all dicom files by series and order them one by one :param compression: enable or disable gzip compression :param reorient: reorient the dicoms according to LAS orientation :param output_folder: folder to write the nifti files to :param dicom_directory: directory with dicom files
[ "This", "function", "will", "order", "all", "dicom", "files", "by", "series", "and", "order", "them", "one", "by", "one" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_dir.py#L34-L99
icometrix/dicom2nifti
dicom2nifti/convert_dir.py
_is_valid_imaging_dicom
def _is_valid_imaging_dicom(dicom_header): """ Function will do some basic checks to see if this is a valid imaging dicom """ # if it is philips and multiframe dicom then we assume it is ok try: if common.is_philips([dicom_header]): if common.is_multiframe_dicom([dicom_header]): return True if "SeriesInstanceUID" not in dicom_header: return False if "InstanceNumber" not in dicom_header: return False if "ImageOrientationPatient" not in dicom_header or len(dicom_header.ImageOrientationPatient) < 6: return False if "ImagePositionPatient" not in dicom_header or len(dicom_header.ImagePositionPatient) < 3: return False # for all others if there is image position patient we assume it is ok if Tag(0x0020, 0x0037) not in dicom_header: return False return True except (KeyError, AttributeError): return False
python
def _is_valid_imaging_dicom(dicom_header): try: if common.is_philips([dicom_header]): if common.is_multiframe_dicom([dicom_header]): return True if "SeriesInstanceUID" not in dicom_header: return False if "InstanceNumber" not in dicom_header: return False if "ImageOrientationPatient" not in dicom_header or len(dicom_header.ImageOrientationPatient) < 6: return False if "ImagePositionPatient" not in dicom_header or len(dicom_header.ImagePositionPatient) < 3: return False if Tag(0x0020, 0x0037) not in dicom_header: return False return True except (KeyError, AttributeError): return False
[ "def", "_is_valid_imaging_dicom", "(", "dicom_header", ")", ":", "# if it is philips and multiframe dicom then we assume it is ok", "try", ":", "if", "common", ".", "is_philips", "(", "[", "dicom_header", "]", ")", ":", "if", "common", ".", "is_multiframe_dicom", "(", "[", "dicom_header", "]", ")", ":", "return", "True", "if", "\"SeriesInstanceUID\"", "not", "in", "dicom_header", ":", "return", "False", "if", "\"InstanceNumber\"", "not", "in", "dicom_header", ":", "return", "False", "if", "\"ImageOrientationPatient\"", "not", "in", "dicom_header", "or", "len", "(", "dicom_header", ".", "ImageOrientationPatient", ")", "<", "6", ":", "return", "False", "if", "\"ImagePositionPatient\"", "not", "in", "dicom_header", "or", "len", "(", "dicom_header", ".", "ImagePositionPatient", ")", "<", "3", ":", "return", "False", "# for all others if there is image position patient we assume it is ok", "if", "Tag", "(", "0x0020", ",", "0x0037", ")", "not", "in", "dicom_header", ":", "return", "False", "return", "True", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "False" ]
Function will do some basic checks to see if this is a valid imaging dicom
[ "Function", "will", "do", "some", "basic", "checks", "to", "see", "if", "this", "is", "a", "valid", "imaging", "dicom" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_dir.py#L102-L130
icometrix/dicom2nifti
dicom2nifti/convert_dir.py
_remove_accents
def _remove_accents(filename): """ Function that will try to remove accents from a unicode string to be used in a filename. input filename should be either an ascii or unicode string """ # noinspection PyBroadException try: filename = filename.replace(" ", "_") if isinstance(filename, type(six.u(''))): unicode_filename = filename else: unicode_filename = six.u(filename) cleaned_filename = unicodedata.normalize('NFKD', unicode_filename).encode('ASCII', 'ignore').decode('ASCII') cleaned_filename = re.sub(r'[^\w\s-]', '', cleaned_filename.strip().lower()) cleaned_filename = re.sub(r'[-\s]+', '-', cleaned_filename) return cleaned_filename except: traceback.print_exc() return filename
python
def _remove_accents(filename): try: filename = filename.replace(" ", "_") if isinstance(filename, type(six.u(''))): unicode_filename = filename else: unicode_filename = six.u(filename) cleaned_filename = unicodedata.normalize('NFKD', unicode_filename).encode('ASCII', 'ignore').decode('ASCII') cleaned_filename = re.sub(r'[^\w\s-]', '', cleaned_filename.strip().lower()) cleaned_filename = re.sub(r'[-\s]+', '-', cleaned_filename) return cleaned_filename except: traceback.print_exc() return filename
[ "def", "_remove_accents", "(", "filename", ")", ":", "# noinspection PyBroadException", "try", ":", "filename", "=", "filename", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", "if", "isinstance", "(", "filename", ",", "type", "(", "six", ".", "u", "(", "''", ")", ")", ")", ":", "unicode_filename", "=", "filename", "else", ":", "unicode_filename", "=", "six", ".", "u", "(", "filename", ")", "cleaned_filename", "=", "unicodedata", ".", "normalize", "(", "'NFKD'", ",", "unicode_filename", ")", ".", "encode", "(", "'ASCII'", ",", "'ignore'", ")", ".", "decode", "(", "'ASCII'", ")", "cleaned_filename", "=", "re", ".", "sub", "(", "r'[^\\w\\s-]'", ",", "''", ",", "cleaned_filename", ".", "strip", "(", ")", ".", "lower", "(", ")", ")", "cleaned_filename", "=", "re", ".", "sub", "(", "r'[-\\s]+'", ",", "'-'", ",", "cleaned_filename", ")", "return", "cleaned_filename", "except", ":", "traceback", ".", "print_exc", "(", ")", "return", "filename" ]
Function that will try to remove accents from a unicode string to be used in a filename. input filename should be either an ascii or unicode string
[ "Function", "that", "will", "try", "to", "remove", "accents", "from", "a", "unicode", "string", "to", "be", "used", "in", "a", "filename", ".", "input", "filename", "should", "be", "either", "an", "ascii", "or", "unicode", "string" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_dir.py#L133-L153
icometrix/dicom2nifti
dicom2nifti/convert_dir.py
_remove_accents_
def _remove_accents_(filename): """ Function that will try to remove accents from a unicode string to be used in a filename. input filename should be either an ascii or unicode string """ if isinstance(filename, type(six.u(''))): unicode_filename = filename else: unicode_filename = six.u(filename) valid_characters = bytes(b'-_.() 1234567890abcdefghijklmnopqrstuvwxyz') cleaned_filename = unicodedata.normalize('NFKD', unicode_filename).encode('ASCII', 'ignore') new_filename = six.u('') for char_int in bytes(cleaned_filename): char_byte = bytes([char_int]) if char_byte in valid_characters: new_filename += char_byte.decode() return new_filename
python
def _remove_accents_(filename): if isinstance(filename, type(six.u(''))): unicode_filename = filename else: unicode_filename = six.u(filename) valid_characters = bytes(b'-_.() 1234567890abcdefghijklmnopqrstuvwxyz') cleaned_filename = unicodedata.normalize('NFKD', unicode_filename).encode('ASCII', 'ignore') new_filename = six.u('') for char_int in bytes(cleaned_filename): char_byte = bytes([char_int]) if char_byte in valid_characters: new_filename += char_byte.decode() return new_filename
[ "def", "_remove_accents_", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "type", "(", "six", ".", "u", "(", "''", ")", ")", ")", ":", "unicode_filename", "=", "filename", "else", ":", "unicode_filename", "=", "six", ".", "u", "(", "filename", ")", "valid_characters", "=", "bytes", "(", "b'-_.() 1234567890abcdefghijklmnopqrstuvwxyz'", ")", "cleaned_filename", "=", "unicodedata", ".", "normalize", "(", "'NFKD'", ",", "unicode_filename", ")", ".", "encode", "(", "'ASCII'", ",", "'ignore'", ")", "new_filename", "=", "six", ".", "u", "(", "''", ")", "for", "char_int", "in", "bytes", "(", "cleaned_filename", ")", ":", "char_byte", "=", "bytes", "(", "[", "char_int", "]", ")", "if", "char_byte", "in", "valid_characters", ":", "new_filename", "+=", "char_byte", ".", "decode", "(", ")", "return", "new_filename" ]
Function that will try to remove accents from a unicode string to be used in a filename. input filename should be either an ascii or unicode string
[ "Function", "that", "will", "try", "to", "remove", "accents", "from", "a", "unicode", "string", "to", "be", "used", "in", "a", "filename", ".", "input", "filename", "should", "be", "either", "an", "ascii", "or", "unicode", "string" ]
train
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_dir.py#L156-L175
aegirhall/console-menu
consolemenu/menu_formatter.py
MenuFormatBuilder.set_border_style
def set_border_style(self, border_style): """ Set the border style using the specified MenuBorderStyle instance. :param border_style: the instance of MenuBorderStyle to use for border style formatting. """ if not isinstance(border_style, MenuBorderStyle): raise TypeError('border_style must be type MenuBorderStyle') self.__header.style.border_style = border_style self.__prologue.style.border_style = border_style self.__items_section.style.border_style = border_style self.__epilogue.style.border_style = border_style self.__footer.style.border_style = border_style self.__prompt.style.border_style = border_style return self
python
def set_border_style(self, border_style): if not isinstance(border_style, MenuBorderStyle): raise TypeError('border_style must be type MenuBorderStyle') self.__header.style.border_style = border_style self.__prologue.style.border_style = border_style self.__items_section.style.border_style = border_style self.__epilogue.style.border_style = border_style self.__footer.style.border_style = border_style self.__prompt.style.border_style = border_style return self
[ "def", "set_border_style", "(", "self", ",", "border_style", ")", ":", "if", "not", "isinstance", "(", "border_style", ",", "MenuBorderStyle", ")", ":", "raise", "TypeError", "(", "'border_style must be type MenuBorderStyle'", ")", "self", ".", "__header", ".", "style", ".", "border_style", "=", "border_style", "self", ".", "__prologue", ".", "style", ".", "border_style", "=", "border_style", "self", ".", "__items_section", ".", "style", ".", "border_style", "=", "border_style", "self", ".", "__epilogue", ".", "style", ".", "border_style", "=", "border_style", "self", ".", "__footer", ".", "style", ".", "border_style", "=", "border_style", "self", ".", "__prompt", ".", "style", ".", "border_style", "=", "border_style", "return", "self" ]
Set the border style using the specified MenuBorderStyle instance. :param border_style: the instance of MenuBorderStyle to use for border style formatting.
[ "Set", "the", "border", "style", "using", "the", "specified", "MenuBorderStyle", "instance", ".", ":", "param", "border_style", ":", "the", "instance", "of", "MenuBorderStyle", "to", "use", "for", "border", "style", "formatting", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_formatter.py#L31-L44
aegirhall/console-menu
consolemenu/menu_formatter.py
MenuFormatBuilder.set_border_style_type
def set_border_style_type(self, border_style_type): """ Set the border style using the specified border style type. The border style type should be an integer value recognized by the border style factory for this formatter instance. The built-in border style types are provided by the `MenuBorderStyleType` class, or custom border style types can be provided if using a custom border style factory. :param border_style_type: an integer value representing the border style type. """ style = self.__border_style_factory.create_border(border_style_type) self.set_border_style(style) return self
python
def set_border_style_type(self, border_style_type): style = self.__border_style_factory.create_border(border_style_type) self.set_border_style(style) return self
[ "def", "set_border_style_type", "(", "self", ",", "border_style_type", ")", ":", "style", "=", "self", ".", "__border_style_factory", ".", "create_border", "(", "border_style_type", ")", "self", ".", "set_border_style", "(", "style", ")", "return", "self" ]
Set the border style using the specified border style type. The border style type should be an integer value recognized by the border style factory for this formatter instance. The built-in border style types are provided by the `MenuBorderStyleType` class, or custom border style types can be provided if using a custom border style factory. :param border_style_type: an integer value representing the border style type.
[ "Set", "the", "border", "style", "using", "the", "specified", "border", "style", "type", ".", "The", "border", "style", "type", "should", "be", "an", "integer", "value", "recognized", "by", "the", "border", "style", "factory", "for", "this", "formatter", "instance", ".", "The", "built", "-", "in", "border", "style", "types", "are", "provided", "by", "the", "MenuBorderStyleType", "class", "or", "custom", "border", "style", "types", "can", "be", "provided", "if", "using", "a", "custom", "border", "style", "factory", ".", ":", "param", "border_style_type", ":", "an", "integer", "value", "representing", "the", "border", "style", "type", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_formatter.py#L46-L56
aegirhall/console-menu
consolemenu/menu_formatter.py
MenuFormatBuilder.set_bottom_margin
def set_bottom_margin(self, bottom_margin): """ Set the bottom margin of the menu. This will determine the number of console lines appear between the bottom of the menu border and the menu input prompt. :param bottom_margin: an integer value """ self.__footer.style.margins.bottom = bottom_margin return self
python
def set_bottom_margin(self, bottom_margin): self.__footer.style.margins.bottom = bottom_margin return self
[ "def", "set_bottom_margin", "(", "self", ",", "bottom_margin", ")", ":", "self", ".", "__footer", ".", "style", ".", "margins", ".", "bottom", "=", "bottom_margin", "return", "self" ]
Set the bottom margin of the menu. This will determine the number of console lines appear between the bottom of the menu border and the menu input prompt. :param bottom_margin: an integer value
[ "Set", "the", "bottom", "margin", "of", "the", "menu", ".", "This", "will", "determine", "the", "number", "of", "console", "lines", "appear", "between", "the", "bottom", "of", "the", "menu", "border", "and", "the", "menu", "input", "prompt", ".", ":", "param", "bottom_margin", ":", "an", "integer", "value" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_formatter.py#L70-L77
aegirhall/console-menu
consolemenu/menu_formatter.py
MenuFormatBuilder.set_left_margin
def set_left_margin(self, left_margin): """ Set the left margin of the menu. This will determine the number of spaces between the left edge of the screen and the left menu border. :param left_margin: an integer value """ self.__header.style.margins.left = left_margin self.__prologue.style.margins.left = left_margin self.__items_section.style.margins.left = left_margin self.__epilogue.style.margins.left = left_margin self.__footer.style.margins.left = left_margin self.__prompt.style.margins.left = left_margin return self
python
def set_left_margin(self, left_margin): self.__header.style.margins.left = left_margin self.__prologue.style.margins.left = left_margin self.__items_section.style.margins.left = left_margin self.__epilogue.style.margins.left = left_margin self.__footer.style.margins.left = left_margin self.__prompt.style.margins.left = left_margin return self
[ "def", "set_left_margin", "(", "self", ",", "left_margin", ")", ":", "self", ".", "__header", ".", "style", ".", "margins", ".", "left", "=", "left_margin", "self", ".", "__prologue", ".", "style", ".", "margins", ".", "left", "=", "left_margin", "self", ".", "__items_section", ".", "style", ".", "margins", ".", "left", "=", "left_margin", "self", ".", "__epilogue", ".", "style", ".", "margins", ".", "left", "=", "left_margin", "self", ".", "__footer", ".", "style", ".", "margins", ".", "left", "=", "left_margin", "self", ".", "__prompt", ".", "style", ".", "margins", ".", "left", "=", "left_margin", "return", "self" ]
Set the left margin of the menu. This will determine the number of spaces between the left edge of the screen and the left menu border. :param left_margin: an integer value
[ "Set", "the", "left", "margin", "of", "the", "menu", ".", "This", "will", "determine", "the", "number", "of", "spaces", "between", "the", "left", "edge", "of", "the", "screen", "and", "the", "left", "menu", "border", ".", ":", "param", "left_margin", ":", "an", "integer", "value" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_formatter.py#L79-L91
aegirhall/console-menu
consolemenu/menu_formatter.py
MenuFormatBuilder.set_right_margin
def set_right_margin(self, right_margin): """ Set the right margin of the menu. This will determine the number of spaces between the right edge of the screen and the right menu border. :param right_margin: an integer value """ self.__header.style.margins.right = right_margin self.__prologue.style.margins.right = right_margin self.__items_section.style.margins.right = right_margin self.__epilogue.style.margins.right = right_margin self.__footer.style.margins.right = right_margin self.__prompt.style.margins.right = right_margin return self
python
def set_right_margin(self, right_margin): self.__header.style.margins.right = right_margin self.__prologue.style.margins.right = right_margin self.__items_section.style.margins.right = right_margin self.__epilogue.style.margins.right = right_margin self.__footer.style.margins.right = right_margin self.__prompt.style.margins.right = right_margin return self
[ "def", "set_right_margin", "(", "self", ",", "right_margin", ")", ":", "self", ".", "__header", ".", "style", ".", "margins", ".", "right", "=", "right_margin", "self", ".", "__prologue", ".", "style", ".", "margins", ".", "right", "=", "right_margin", "self", ".", "__items_section", ".", "style", ".", "margins", ".", "right", "=", "right_margin", "self", ".", "__epilogue", ".", "style", ".", "margins", ".", "right", "=", "right_margin", "self", ".", "__footer", ".", "style", ".", "margins", ".", "right", "=", "right_margin", "self", ".", "__prompt", ".", "style", ".", "margins", ".", "right", "=", "right_margin", "return", "self" ]
Set the right margin of the menu. This will determine the number of spaces between the right edge of the screen and the right menu border. :param right_margin: an integer value
[ "Set", "the", "right", "margin", "of", "the", "menu", ".", "This", "will", "determine", "the", "number", "of", "spaces", "between", "the", "right", "edge", "of", "the", "screen", "and", "the", "right", "menu", "border", ".", ":", "param", "right_margin", ":", "an", "integer", "value" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_formatter.py#L93-L105
aegirhall/console-menu
consolemenu/menu_formatter.py
MenuFormatBuilder.set_top_margin
def set_top_margin(self, top_margin): """ Set the top margin of the menu. This will determine the number of console lines between the top edge of the screen and the top menu border. :param top_margin: an integer value """ self.__header.style.margins.top = top_margin return self
python
def set_top_margin(self, top_margin): self.__header.style.margins.top = top_margin return self
[ "def", "set_top_margin", "(", "self", ",", "top_margin", ")", ":", "self", ".", "__header", ".", "style", ".", "margins", ".", "top", "=", "top_margin", "return", "self" ]
Set the top margin of the menu. This will determine the number of console lines between the top edge of the screen and the top menu border. :param top_margin: an integer value
[ "Set", "the", "top", "margin", "of", "the", "menu", ".", "This", "will", "determine", "the", "number", "of", "console", "lines", "between", "the", "top", "edge", "of", "the", "screen", "and", "the", "top", "menu", "border", ".", ":", "param", "top_margin", ":", "an", "integer", "value" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_formatter.py#L107-L114
aegirhall/console-menu
consolemenu/menu_formatter.py
MenuFormatBuilder.clear_data
def clear_data(self): """ Clear menu data from previous menu generation. """ self.__header.title = None self.__header.subtitle = None self.__prologue.text = None self.__epilogue.text = None self.__items_section.items = None
python
def clear_data(self): self.__header.title = None self.__header.subtitle = None self.__prologue.text = None self.__epilogue.text = None self.__items_section.items = None
[ "def", "clear_data", "(", "self", ")", ":", "self", ".", "__header", ".", "title", "=", "None", "self", ".", "__header", ".", "subtitle", "=", "None", "self", ".", "__prologue", ".", "text", "=", "None", "self", ".", "__epilogue", ".", "text", "=", "None", "self", ".", "__items_section", ".", "items", "=", "None" ]
Clear menu data from previous menu generation.
[ "Clear", "menu", "data", "from", "previous", "menu", "generation", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_formatter.py#L246-L254
aegirhall/console-menu
consolemenu/menu_formatter.py
MenuFormatBuilder.format
def format(self, title=None, subtitle=None, prologue_text=None, epilogue_text=None, items=None): """ Format the menu and return as a string. :return: a string representation of the formatted menu. """ self.clear_data() content = '' # Header Section if title is not None: self.__header.title = title if subtitle is not None: self.__header.subtitle = subtitle sections = [self.__header] # Prologue Section if prologue_text is not None: self.__prologue.text = prologue_text sections.append(self.__prologue) # Items Section if items is not None: self.__items_section.items = items sections.append(self.__items_section) # Epilogue Section if epilogue_text is not None: self.__epilogue.text = epilogue_text sections.append(self.__epilogue) sections.append(self.__footer) sections.append(self.__prompt) for sect in sections: content += "\n".join(sect.generate()) # Don't add newline to prompt so input is on same line as prompt if not isinstance(sect, MenuPrompt): content += "\n" return content
python
def format(self, title=None, subtitle=None, prologue_text=None, epilogue_text=None, items=None): self.clear_data() content = '' if title is not None: self.__header.title = title if subtitle is not None: self.__header.subtitle = subtitle sections = [self.__header] if prologue_text is not None: self.__prologue.text = prologue_text sections.append(self.__prologue) if items is not None: self.__items_section.items = items sections.append(self.__items_section) if epilogue_text is not None: self.__epilogue.text = epilogue_text sections.append(self.__epilogue) sections.append(self.__footer) sections.append(self.__prompt) for sect in sections: content += "\n".join(sect.generate()) if not isinstance(sect, MenuPrompt): content += "\n" return content
[ "def", "format", "(", "self", ",", "title", "=", "None", ",", "subtitle", "=", "None", ",", "prologue_text", "=", "None", ",", "epilogue_text", "=", "None", ",", "items", "=", "None", ")", ":", "self", ".", "clear_data", "(", ")", "content", "=", "''", "# Header Section", "if", "title", "is", "not", "None", ":", "self", ".", "__header", ".", "title", "=", "title", "if", "subtitle", "is", "not", "None", ":", "self", ".", "__header", ".", "subtitle", "=", "subtitle", "sections", "=", "[", "self", ".", "__header", "]", "# Prologue Section", "if", "prologue_text", "is", "not", "None", ":", "self", ".", "__prologue", ".", "text", "=", "prologue_text", "sections", ".", "append", "(", "self", ".", "__prologue", ")", "# Items Section", "if", "items", "is", "not", "None", ":", "self", ".", "__items_section", ".", "items", "=", "items", "sections", ".", "append", "(", "self", ".", "__items_section", ")", "# Epilogue Section", "if", "epilogue_text", "is", "not", "None", ":", "self", ".", "__epilogue", ".", "text", "=", "epilogue_text", "sections", ".", "append", "(", "self", ".", "__epilogue", ")", "sections", ".", "append", "(", "self", ".", "__footer", ")", "sections", ".", "append", "(", "self", ".", "__prompt", ")", "for", "sect", "in", "sections", ":", "content", "+=", "\"\\n\"", ".", "join", "(", "sect", ".", "generate", "(", ")", ")", "# Don't add newline to prompt so input is on same line as prompt", "if", "not", "isinstance", "(", "sect", ",", "MenuPrompt", ")", ":", "content", "+=", "\"\\n\"", "return", "content" ]
Format the menu and return as a string. :return: a string representation of the formatted menu.
[ "Format", "the", "menu", "and", "return", "as", "a", "string", ".", ":", "return", ":", "a", "string", "representation", "of", "the", "formatted", "menu", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_formatter.py#L256-L288
aegirhall/console-menu
consolemenu/validators/url.py
UrlValidator.validate
def validate(self, input_string): """ Validate url :return: True if match / False otherwise """ parsed_url = urlparse(url=input_string) return bool(parsed_url.scheme and parsed_url.netloc)
python
def validate(self, input_string): parsed_url = urlparse(url=input_string) return bool(parsed_url.scheme and parsed_url.netloc)
[ "def", "validate", "(", "self", ",", "input_string", ")", ":", "parsed_url", "=", "urlparse", "(", "url", "=", "input_string", ")", "return", "bool", "(", "parsed_url", ".", "scheme", "and", "parsed_url", ".", "netloc", ")" ]
Validate url :return: True if match / False otherwise
[ "Validate", "url" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/validators/url.py#L19-L26
aegirhall/console-menu
consolemenu/menu_component.py
MenuComponent.calculate_border_width
def calculate_border_width(self): """ Calculate the width of the menu border. This will be the width of the maximum allowable dimensions (usually the screen size), minus the left and right margins and the newline character. For example, given a maximum width of 80 characters, with left and right margins both set to 1, the border width would be 77 (80 - 1 - 1 - 1 = 77). Returns: int: the menu border width in columns. """ return self.max_dimension.width - self.margins.left - self.margins.right - 1
python
def calculate_border_width(self): return self.max_dimension.width - self.margins.left - self.margins.right - 1
[ "def", "calculate_border_width", "(", "self", ")", ":", "return", "self", ".", "max_dimension", ".", "width", "-", "self", ".", "margins", ".", "left", "-", "self", ".", "margins", ".", "right", "-", "1" ]
Calculate the width of the menu border. This will be the width of the maximum allowable dimensions (usually the screen size), minus the left and right margins and the newline character. For example, given a maximum width of 80 characters, with left and right margins both set to 1, the border width would be 77 (80 - 1 - 1 - 1 = 77). Returns: int: the menu border width in columns.
[ "Calculate", "the", "width", "of", "the", "menu", "border", ".", "This", "will", "be", "the", "width", "of", "the", "maximum", "allowable", "dimensions", "(", "usually", "the", "screen", "size", ")", "minus", "the", "left", "and", "right", "margins", "and", "the", "newline", "character", ".", "For", "example", "given", "a", "maximum", "width", "of", "80", "characters", "with", "left", "and", "right", "margins", "both", "set", "to", "1", "the", "border", "width", "would", "be", "77", "(", "80", "-", "1", "-", "1", "-", "1", "=", "77", ")", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L80-L90
aegirhall/console-menu
consolemenu/menu_component.py
MenuComponent.calculate_content_width
def calculate_content_width(self): """ Calculate the width of inner content of the border. This will be the width of the menu borders, minus the left and right padding, and minus the two vertical border characters. For example, given a border width of 77, with left and right margins each set to 2, the content width would be 71 (77 - 2 - 2 - 2 = 71). Returns: int: the inner content width in columns. """ return self.calculate_border_width() - self.padding.left - self.padding.right - 2
python
def calculate_content_width(self): return self.calculate_border_width() - self.padding.left - self.padding.right - 2
[ "def", "calculate_content_width", "(", "self", ")", ":", "return", "self", ".", "calculate_border_width", "(", ")", "-", "self", ".", "padding", ".", "left", "-", "self", ".", "padding", ".", "right", "-", "2" ]
Calculate the width of inner content of the border. This will be the width of the menu borders, minus the left and right padding, and minus the two vertical border characters. For example, given a border width of 77, with left and right margins each set to 2, the content width would be 71 (77 - 2 - 2 - 2 = 71). Returns: int: the inner content width in columns.
[ "Calculate", "the", "width", "of", "inner", "content", "of", "the", "border", ".", "This", "will", "be", "the", "width", "of", "the", "menu", "borders", "minus", "the", "left", "and", "right", "padding", "and", "minus", "the", "two", "vertical", "border", "characters", ".", "For", "example", "given", "a", "border", "width", "of", "77", "with", "left", "and", "right", "margins", "each", "set", "to", "2", "the", "content", "width", "would", "be", "71", "(", "77", "-", "2", "-", "2", "-", "2", "=", "71", ")", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L92-L102
aegirhall/console-menu
consolemenu/menu_component.py
MenuComponent.inner_horizontal_border
def inner_horizontal_border(self): """ The complete inner horizontal border section, including the left and right border verticals. Returns: str: The complete inner horizontal border. """ return u"{lm}{lv}{hz}{rv}".format(lm=' ' * self.margins.left, lv=self.border_style.outer_vertical_inner_right, rv=self.border_style.outer_vertical_inner_left, hz=self.inner_horizontals())
python
def inner_horizontal_border(self): return u"{lm}{lv}{hz}{rv}".format(lm=' ' * self.margins.left, lv=self.border_style.outer_vertical_inner_right, rv=self.border_style.outer_vertical_inner_left, hz=self.inner_horizontals())
[ "def", "inner_horizontal_border", "(", "self", ")", ":", "return", "u\"{lm}{lv}{hz}{rv}\"", ".", "format", "(", "lm", "=", "' '", "*", "self", ".", "margins", ".", "left", ",", "lv", "=", "self", ".", "border_style", ".", "outer_vertical_inner_right", ",", "rv", "=", "self", ".", "border_style", ".", "outer_vertical_inner_left", ",", "hz", "=", "self", ".", "inner_horizontals", "(", ")", ")" ]
The complete inner horizontal border section, including the left and right border verticals. Returns: str: The complete inner horizontal border.
[ "The", "complete", "inner", "horizontal", "border", "section", "including", "the", "left", "and", "right", "border", "verticals", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L123-L133
aegirhall/console-menu
consolemenu/menu_component.py
MenuComponent.outer_horizontal_border_bottom
def outer_horizontal_border_bottom(self): """ The complete outer bottom horizontal border section, including left and right margins. Returns: str: The bottom menu border. """ return u"{lm}{lv}{hz}{rv}".format(lm=' ' * self.margins.left, lv=self.border_style.bottom_left_corner, rv=self.border_style.bottom_right_corner, hz=self.outer_horizontals())
python
def outer_horizontal_border_bottom(self): return u"{lm}{lv}{hz}{rv}".format(lm=' ' * self.margins.left, lv=self.border_style.bottom_left_corner, rv=self.border_style.bottom_right_corner, hz=self.outer_horizontals())
[ "def", "outer_horizontal_border_bottom", "(", "self", ")", ":", "return", "u\"{lm}{lv}{hz}{rv}\"", ".", "format", "(", "lm", "=", "' '", "*", "self", ".", "margins", ".", "left", ",", "lv", "=", "self", ".", "border_style", ".", "bottom_left_corner", ",", "rv", "=", "self", ".", "border_style", ".", "bottom_right_corner", ",", "hz", "=", "self", ".", "outer_horizontals", "(", ")", ")" ]
The complete outer bottom horizontal border section, including left and right margins. Returns: str: The bottom menu border.
[ "The", "complete", "outer", "bottom", "horizontal", "border", "section", "including", "left", "and", "right", "margins", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L145-L155
aegirhall/console-menu
consolemenu/menu_component.py
MenuComponent.outer_horizontal_border_top
def outer_horizontal_border_top(self): """ The complete outer top horizontal border section, including left and right margins. Returns: str: The top menu border. """ return u"{lm}{lv}{hz}{rv}".format(lm=' ' * self.margins.left, lv=self.border_style.top_left_corner, rv=self.border_style.top_right_corner, hz=self.outer_horizontals())
python
def outer_horizontal_border_top(self): return u"{lm}{lv}{hz}{rv}".format(lm=' ' * self.margins.left, lv=self.border_style.top_left_corner, rv=self.border_style.top_right_corner, hz=self.outer_horizontals())
[ "def", "outer_horizontal_border_top", "(", "self", ")", ":", "return", "u\"{lm}{lv}{hz}{rv}\"", ".", "format", "(", "lm", "=", "' '", "*", "self", ".", "margins", ".", "left", ",", "lv", "=", "self", ".", "border_style", ".", "top_left_corner", ",", "rv", "=", "self", ".", "border_style", ".", "top_right_corner", ",", "hz", "=", "self", ".", "outer_horizontals", "(", ")", ")" ]
The complete outer top horizontal border section, including left and right margins. Returns: str: The top menu border.
[ "The", "complete", "outer", "top", "horizontal", "border", "section", "including", "left", "and", "right", "margins", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L157-L167
aegirhall/console-menu
consolemenu/menu_component.py
MenuComponent.row
def row(self, content='', align='left'): """ A row of the menu, which comprises the left and right verticals plus the given content. Returns: str: A row of this menu component with the specified content. """ return u"{lm}{vert}{cont}{vert}".format(lm=' ' * self.margins.left, vert=self.border_style.outer_vertical, cont=self._format_content(content, align))
python
def row(self, content='', align='left'): return u"{lm}{vert}{cont}{vert}".format(lm=' ' * self.margins.left, vert=self.border_style.outer_vertical, cont=self._format_content(content, align))
[ "def", "row", "(", "self", ",", "content", "=", "''", ",", "align", "=", "'left'", ")", ":", "return", "u\"{lm}{vert}{cont}{vert}\"", ".", "format", "(", "lm", "=", "' '", "*", "self", ".", "margins", ".", "left", ",", "vert", "=", "self", ".", "border_style", ".", "outer_vertical", ",", "cont", "=", "self", ".", "_format_content", "(", "content", ",", "align", ")", ")" ]
A row of the menu, which comprises the left and right verticals plus the given content. Returns: str: A row of this menu component with the specified content.
[ "A", "row", "of", "the", "menu", "which", "comprises", "the", "left", "and", "right", "verticals", "plus", "the", "given", "content", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L169-L178
aegirhall/console-menu
consolemenu/menu_component.py
MenuItemsSection.show_item_bottom_border
def show_item_bottom_border(self, item_text, flag): """ Sets a flag that will show a bottom border for an item with the specified text. :param item_text: the text property of the item :param flag: boolean specifying if the border should be shown. """ if flag: self.__bottom_border_dict[item_text] = True else: self.__bottom_border_dict.pop(item_text, None)
python
def show_item_bottom_border(self, item_text, flag): if flag: self.__bottom_border_dict[item_text] = True else: self.__bottom_border_dict.pop(item_text, None)
[ "def", "show_item_bottom_border", "(", "self", ",", "item_text", ",", "flag", ")", ":", "if", "flag", ":", "self", ".", "__bottom_border_dict", "[", "item_text", "]", "=", "True", "else", ":", "self", ".", "__bottom_border_dict", ".", "pop", "(", "item_text", ",", "None", ")" ]
Sets a flag that will show a bottom border for an item with the specified text. :param item_text: the text property of the item :param flag: boolean specifying if the border should be shown.
[ "Sets", "a", "flag", "that", "will", "show", "a", "bottom", "border", "for", "an", "item", "with", "the", "specified", "text", ".", ":", "param", "item_text", ":", "the", "text", "property", "of", "the", "item", ":", "param", "flag", ":", "boolean", "specifying", "if", "the", "border", "should", "be", "shown", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L297-L306
aegirhall/console-menu
consolemenu/menu_component.py
MenuItemsSection.show_item_top_border
def show_item_top_border(self, item_text, flag): """ Sets a flag that will show a top border for an item with the specified text. :param item_text: the text property of the item :param flag: boolean specifying if the border should be shown. """ if flag: self.__top_border_dict[item_text] = True else: self.__top_border_dict.pop(item_text, None)
python
def show_item_top_border(self, item_text, flag): if flag: self.__top_border_dict[item_text] = True else: self.__top_border_dict.pop(item_text, None)
[ "def", "show_item_top_border", "(", "self", ",", "item_text", ",", "flag", ")", ":", "if", "flag", ":", "self", ".", "__top_border_dict", "[", "item_text", "]", "=", "True", "else", ":", "self", ".", "__top_border_dict", ".", "pop", "(", "item_text", ",", "None", ")" ]
Sets a flag that will show a top border for an item with the specified text. :param item_text: the text property of the item :param flag: boolean specifying if the border should be shown.
[ "Sets", "a", "flag", "that", "will", "show", "a", "top", "border", "for", "an", "item", "with", "the", "specified", "text", ".", ":", "param", "item_text", ":", "the", "text", "property", "of", "the", "item", ":", "param", "flag", ":", "boolean", "specifying", "if", "the", "border", "should", "be", "shown", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L308-L317
aegirhall/console-menu
consolemenu/format/menu_borders.py
MenuBorderStyleFactory.create_border
def create_border(self, border_style_type): """ Create a new MenuBorderStyle instance based on the given border style type. Args: border_style_type (int): an integer value from :obj:`MenuBorderStyleType`. Returns: :obj:`MenuBorderStyle`: a new MenuBorderStyle instance of the specified style. """ if border_style_type == MenuBorderStyleType.ASCII_BORDER: return self.create_ascii_border() elif border_style_type == MenuBorderStyleType.LIGHT_BORDER: return self.create_light_border() elif border_style_type == MenuBorderStyleType.HEAVY_BORDER: return self.create_heavy_border() elif border_style_type == MenuBorderStyleType.DOUBLE_LINE_BORDER: return self.create_doubleline_border() elif border_style_type == MenuBorderStyleType.HEAVY_OUTER_LIGHT_INNER_BORDER: return self.create_heavy_outer_light_inner_border() elif border_style_type == MenuBorderStyleType.DOUBLE_LINE_OUTER_LIGHT_INNER_BORDER: return self.create_doubleline_outer_light_inner_border() else: # Use ASCII if we don't recognize the type self.logger.info('Unrecognized border style type: {}. Defaulting to ASCII.'.format(border_style_type)) return self.create_ascii_border()
python
def create_border(self, border_style_type): if border_style_type == MenuBorderStyleType.ASCII_BORDER: return self.create_ascii_border() elif border_style_type == MenuBorderStyleType.LIGHT_BORDER: return self.create_light_border() elif border_style_type == MenuBorderStyleType.HEAVY_BORDER: return self.create_heavy_border() elif border_style_type == MenuBorderStyleType.DOUBLE_LINE_BORDER: return self.create_doubleline_border() elif border_style_type == MenuBorderStyleType.HEAVY_OUTER_LIGHT_INNER_BORDER: return self.create_heavy_outer_light_inner_border() elif border_style_type == MenuBorderStyleType.DOUBLE_LINE_OUTER_LIGHT_INNER_BORDER: return self.create_doubleline_outer_light_inner_border() else: self.logger.info('Unrecognized border style type: {}. Defaulting to ASCII.'.format(border_style_type)) return self.create_ascii_border()
[ "def", "create_border", "(", "self", ",", "border_style_type", ")", ":", "if", "border_style_type", "==", "MenuBorderStyleType", ".", "ASCII_BORDER", ":", "return", "self", ".", "create_ascii_border", "(", ")", "elif", "border_style_type", "==", "MenuBorderStyleType", ".", "LIGHT_BORDER", ":", "return", "self", ".", "create_light_border", "(", ")", "elif", "border_style_type", "==", "MenuBorderStyleType", ".", "HEAVY_BORDER", ":", "return", "self", ".", "create_heavy_border", "(", ")", "elif", "border_style_type", "==", "MenuBorderStyleType", ".", "DOUBLE_LINE_BORDER", ":", "return", "self", ".", "create_doubleline_border", "(", ")", "elif", "border_style_type", "==", "MenuBorderStyleType", ".", "HEAVY_OUTER_LIGHT_INNER_BORDER", ":", "return", "self", ".", "create_heavy_outer_light_inner_border", "(", ")", "elif", "border_style_type", "==", "MenuBorderStyleType", ".", "DOUBLE_LINE_OUTER_LIGHT_INNER_BORDER", ":", "return", "self", ".", "create_doubleline_outer_light_inner_border", "(", ")", "else", ":", "# Use ASCII if we don't recognize the type", "self", ".", "logger", ".", "info", "(", "'Unrecognized border style type: {}. Defaulting to ASCII.'", ".", "format", "(", "border_style_type", ")", ")", "return", "self", ".", "create_ascii_border", "(", ")" ]
Create a new MenuBorderStyle instance based on the given border style type. Args: border_style_type (int): an integer value from :obj:`MenuBorderStyleType`. Returns: :obj:`MenuBorderStyle`: a new MenuBorderStyle instance of the specified style.
[ "Create", "a", "new", "MenuBorderStyle", "instance", "based", "on", "the", "given", "border", "style", "type", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/format/menu_borders.py#L352-L378
aegirhall/console-menu
consolemenu/format/menu_borders.py
MenuBorderStyleFactory.is_win_python35_or_earlier
def is_win_python35_or_earlier(): """ Convenience method to determine if the current platform is Windows and Python version 3.5 or earlier. Returns: bool: True if the current platform is Windows and the Python interpreter is 3.5 or earlier; False otherwise. """ return sys.platform.startswith("win") and sys.version_info.major < 3 or ( sys.version_info.major == 3 and sys.version_info.minor < 6)
python
def is_win_python35_or_earlier(): return sys.platform.startswith("win") and sys.version_info.major < 3 or ( sys.version_info.major == 3 and sys.version_info.minor < 6)
[ "def", "is_win_python35_or_earlier", "(", ")", ":", "return", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", "and", "sys", ".", "version_info", ".", "major", "<", "3", "or", "(", "sys", ".", "version_info", ".", "major", "==", "3", "and", "sys", ".", "version_info", ".", "minor", "<", "6", ")" ]
Convenience method to determine if the current platform is Windows and Python version 3.5 or earlier. Returns: bool: True if the current platform is Windows and the Python interpreter is 3.5 or earlier; False otherwise.
[ "Convenience", "method", "to", "determine", "if", "the", "current", "platform", "is", "Windows", "and", "Python", "version", "3", ".", "5", "or", "earlier", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/format/menu_borders.py#L454-L463
aegirhall/console-menu
consolemenu/items/submenu_item.py
SubmenuItem.set_menu
def set_menu(self, menu): """ Sets the menu of this item. Should be used instead of directly accessing the menu attribute for this class. :param ConsoleMenu menu: the menu """ self.menu = menu self.submenu.parent = menu
python
def set_menu(self, menu): self.menu = menu self.submenu.parent = menu
[ "def", "set_menu", "(", "self", ",", "menu", ")", ":", "self", ".", "menu", "=", "menu", "self", ".", "submenu", ".", "parent", "=", "menu" ]
Sets the menu of this item. Should be used instead of directly accessing the menu attribute for this class. :param ConsoleMenu menu: the menu
[ "Sets", "the", "menu", "of", "this", "item", ".", "Should", "be", "used", "instead", "of", "directly", "accessing", "the", "menu", "attribute", "for", "this", "class", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/items/submenu_item.py#L19-L27
aegirhall/console-menu
consolemenu/items/submenu_item.py
SubmenuItem.clean_up
def clean_up(self): """ This class overrides this method """ self.submenu.join() self.menu.clear_screen() self.menu.resume()
python
def clean_up(self): self.submenu.join() self.menu.clear_screen() self.menu.resume()
[ "def", "clean_up", "(", "self", ")", ":", "self", ".", "submenu", ".", "join", "(", ")", "self", ".", "menu", ".", "clear_screen", "(", ")", "self", ".", "menu", ".", "resume", "(", ")" ]
This class overrides this method
[ "This", "class", "overrides", "this", "method" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/items/submenu_item.py#L42-L48
aegirhall/console-menu
consolemenu/prompt_utils.py
PromptFormatter.format_prompt
def format_prompt(prompt=None, default=None, enable_quit=False, quit_string='q', quit_message='(enter q to Quit)'): """ Format the prompt. :param prompt: the prompt message. :param default: the default answer if user does not provide a response. :param enable_quit: specifies whether the user can cancel out of the input prompt. :param quit_string: the string whcih the user must input in order to quit. :param quit_message: the message to explain how to quit. :return: the formatted prompt string. """ if prompt is None: return None prompt = prompt.rstrip() prompt = prompt.rstrip(':') if enable_quit: prompt = "{0} {1}".format(prompt, quit_message) if default: prompt = "{0} [{1}]".format(prompt, default) return "{0}: ".format(prompt)
python
def format_prompt(prompt=None, default=None, enable_quit=False, quit_string='q', quit_message='(enter q to Quit)'): if prompt is None: return None prompt = prompt.rstrip() prompt = prompt.rstrip(':') if enable_quit: prompt = "{0} {1}".format(prompt, quit_message) if default: prompt = "{0} [{1}]".format(prompt, default) return "{0}: ".format(prompt)
[ "def", "format_prompt", "(", "prompt", "=", "None", ",", "default", "=", "None", ",", "enable_quit", "=", "False", ",", "quit_string", "=", "'q'", ",", "quit_message", "=", "'(enter q to Quit)'", ")", ":", "if", "prompt", "is", "None", ":", "return", "None", "prompt", "=", "prompt", ".", "rstrip", "(", ")", "prompt", "=", "prompt", ".", "rstrip", "(", "':'", ")", "if", "enable_quit", ":", "prompt", "=", "\"{0} {1}\"", ".", "format", "(", "prompt", ",", "quit_message", ")", "if", "default", ":", "prompt", "=", "\"{0} [{1}]\"", ".", "format", "(", "prompt", ",", "default", ")", "return", "\"{0}: \"", ".", "format", "(", "prompt", ")" ]
Format the prompt. :param prompt: the prompt message. :param default: the default answer if user does not provide a response. :param enable_quit: specifies whether the user can cancel out of the input prompt. :param quit_string: the string whcih the user must input in order to quit. :param quit_message: the message to explain how to quit. :return: the formatted prompt string.
[ "Format", "the", "prompt", ".", ":", "param", "prompt", ":", "the", "prompt", "message", ".", ":", "param", "default", ":", "the", "default", "answer", "if", "user", "does", "not", "provide", "a", "response", ".", ":", "param", "enable_quit", ":", "specifies", "whether", "the", "user", "can", "cancel", "out", "of", "the", "input", "prompt", ".", ":", "param", "quit_string", ":", "the", "string", "whcih", "the", "user", "must", "input", "in", "order", "to", "quit", ".", ":", "param", "quit_message", ":", "the", "message", "to", "explain", "how", "to", "quit", ".", ":", "return", ":", "the", "formatted", "prompt", "string", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/prompt_utils.py#L15-L34
aegirhall/console-menu
consolemenu/prompt_utils.py
PromptUtils.confirm_answer
def confirm_answer(self, answer, message=None): """ Prompts the user to confirm a question with a yes/no prompt. If no message is specified, the default message is: "You entered {}. Is this correct?" :param answer: the answer to confirm. :param message: a message to display rather than the default message. :return: True if the user confirmed Yes, or False if user specified No. """ if message is None: message = "\nYou entered {0}. Is this correct?".format(answer) return self.prompt_for_yes_or_no(message)
python
def confirm_answer(self, answer, message=None): if message is None: message = "\nYou entered {0}. Is this correct?".format(answer) return self.prompt_for_yes_or_no(message)
[ "def", "confirm_answer", "(", "self", ",", "answer", ",", "message", "=", "None", ")", ":", "if", "message", "is", "None", ":", "message", "=", "\"\\nYou entered {0}. Is this correct?\"", ".", "format", "(", "answer", ")", "return", "self", ".", "prompt_for_yes_or_no", "(", "message", ")" ]
Prompts the user to confirm a question with a yes/no prompt. If no message is specified, the default message is: "You entered {}. Is this correct?" :param answer: the answer to confirm. :param message: a message to display rather than the default message. :return: True if the user confirmed Yes, or False if user specified No.
[ "Prompts", "the", "user", "to", "confirm", "a", "question", "with", "a", "yes", "/", "no", "prompt", ".", "If", "no", "message", "is", "specified", "the", "default", "message", "is", ":", "You", "entered", "{}", ".", "Is", "this", "correct?", ":", "param", "answer", ":", "the", "answer", "to", "confirm", ".", ":", "param", "message", ":", "a", "message", "to", "display", "rather", "than", "the", "default", "message", ".", ":", "return", ":", "True", "if", "the", "user", "confirmed", "Yes", "or", "False", "if", "user", "specified", "No", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/prompt_utils.py#L64-L74
aegirhall/console-menu
consolemenu/prompt_utils.py
PromptUtils.enter_to_continue
def enter_to_continue(self, message=None): """ Creates a console prompt with the given message, or defaults to 'Press [Enter] to continue' if no message is provided. :param message: """ if message: message = message.rstrip() + ' ' else: message = 'Press [Enter] to continue ' self.__screen.input(message)
python
def enter_to_continue(self, message=None): if message: message = message.rstrip() + ' ' else: message = 'Press [Enter] to continue ' self.__screen.input(message)
[ "def", "enter_to_continue", "(", "self", ",", "message", "=", "None", ")", ":", "if", "message", ":", "message", "=", "message", ".", "rstrip", "(", ")", "+", "' '", "else", ":", "message", "=", "'Press [Enter] to continue '", "self", ".", "__screen", ".", "input", "(", "message", ")" ]
Creates a console prompt with the given message, or defaults to 'Press [Enter] to continue' if no message is provided. :param message:
[ "Creates", "a", "console", "prompt", "with", "the", "given", "message", "or", "defaults", "to", "Press", "[", "Enter", "]", "to", "continue", "if", "no", "message", "is", "provided", ".", ":", "param", "message", ":" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/prompt_utils.py#L76-L86
aegirhall/console-menu
consolemenu/prompt_utils.py
PromptUtils.input
def input(self, prompt=None, default=None, validators=None, enable_quit=False, quit_string='q', quit_message='(enter q to Quit)'): """ Prompt the user for input. :param prompt: the message to prompt the user. :param default: the default value to suggest as an answer. :param validators: list of validators to perform input validation. :param enable_quit: specifies whether the user can cancel out of the input prompt. :param quit_string: the string whcih the user must input in order to quit. :param quit_message: the message to explain how to quit. :return: an InputResult tuple. """ prompt = self.__prompt_formatter.format_prompt(prompt=prompt, default=default, enable_quit=enable_quit, quit_string=quit_string, quit_message=quit_message) input_string = self.__screen.input(prompt=prompt) if enable_quit and quit_string == input_string: raise UserQuit if default is not None and input_string.strip() == '': input_string = default validation_result = self.validate_input(input_string, validators) return InputResult(input_string=input_string, validation_result=validation_result)
python
def input(self, prompt=None, default=None, validators=None, enable_quit=False, quit_string='q', quit_message='(enter q to Quit)'): prompt = self.__prompt_formatter.format_prompt(prompt=prompt, default=default, enable_quit=enable_quit, quit_string=quit_string, quit_message=quit_message) input_string = self.__screen.input(prompt=prompt) if enable_quit and quit_string == input_string: raise UserQuit if default is not None and input_string.strip() == '': input_string = default validation_result = self.validate_input(input_string, validators) return InputResult(input_string=input_string, validation_result=validation_result)
[ "def", "input", "(", "self", ",", "prompt", "=", "None", ",", "default", "=", "None", ",", "validators", "=", "None", ",", "enable_quit", "=", "False", ",", "quit_string", "=", "'q'", ",", "quit_message", "=", "'(enter q to Quit)'", ")", ":", "prompt", "=", "self", ".", "__prompt_formatter", ".", "format_prompt", "(", "prompt", "=", "prompt", ",", "default", "=", "default", ",", "enable_quit", "=", "enable_quit", ",", "quit_string", "=", "quit_string", ",", "quit_message", "=", "quit_message", ")", "input_string", "=", "self", ".", "__screen", ".", "input", "(", "prompt", "=", "prompt", ")", "if", "enable_quit", "and", "quit_string", "==", "input_string", ":", "raise", "UserQuit", "if", "default", "is", "not", "None", "and", "input_string", ".", "strip", "(", ")", "==", "''", ":", "input_string", "=", "default", "validation_result", "=", "self", ".", "validate_input", "(", "input_string", ",", "validators", ")", "return", "InputResult", "(", "input_string", "=", "input_string", ",", "validation_result", "=", "validation_result", ")" ]
Prompt the user for input. :param prompt: the message to prompt the user. :param default: the default value to suggest as an answer. :param validators: list of validators to perform input validation. :param enable_quit: specifies whether the user can cancel out of the input prompt. :param quit_string: the string whcih the user must input in order to quit. :param quit_message: the message to explain how to quit. :return: an InputResult tuple.
[ "Prompt", "the", "user", "for", "input", ".", ":", "param", "prompt", ":", "the", "message", "to", "prompt", "the", "user", ".", ":", "param", "default", ":", "the", "default", "value", "to", "suggest", "as", "an", "answer", ".", ":", "param", "validators", ":", "list", "of", "validators", "to", "perform", "input", "validation", ".", ":", "param", "enable_quit", ":", "specifies", "whether", "the", "user", "can", "cancel", "out", "of", "the", "input", "prompt", ".", ":", "param", "quit_string", ":", "the", "string", "whcih", "the", "user", "must", "input", "in", "order", "to", "quit", ".", ":", "param", "quit_message", ":", "the", "message", "to", "explain", "how", "to", "quit", ".", ":", "return", ":", "an", "InputResult", "tuple", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/prompt_utils.py#L88-L114
aegirhall/console-menu
consolemenu/prompt_utils.py
PromptUtils.input_password
def input_password(self, message=None): """ Prompt the user for a password. This is equivalent to the input() method, but does not echo inputted characters to the screen. :param message: the prompt message. """ message = self.__prompt_formatter.format_prompt(message) try: if message: return getpass.getpass(message) else: return getpass.getpass() except BaseException: self.__screen.println('Warning: Unable to mask input; characters will be echoed to console') return self.input(message)
python
def input_password(self, message=None): message = self.__prompt_formatter.format_prompt(message) try: if message: return getpass.getpass(message) else: return getpass.getpass() except BaseException: self.__screen.println('Warning: Unable to mask input; characters will be echoed to console') return self.input(message)
[ "def", "input_password", "(", "self", ",", "message", "=", "None", ")", ":", "message", "=", "self", ".", "__prompt_formatter", ".", "format_prompt", "(", "message", ")", "try", ":", "if", "message", ":", "return", "getpass", ".", "getpass", "(", "message", ")", "else", ":", "return", "getpass", ".", "getpass", "(", ")", "except", "BaseException", ":", "self", ".", "__screen", ".", "println", "(", "'Warning: Unable to mask input; characters will be echoed to console'", ")", "return", "self", ".", "input", "(", "message", ")" ]
Prompt the user for a password. This is equivalent to the input() method, but does not echo inputted characters to the screen. :param message: the prompt message.
[ "Prompt", "the", "user", "for", "a", "password", ".", "This", "is", "equivalent", "to", "the", "input", "()", "method", "but", "does", "not", "echo", "inputted", "characters", "to", "the", "screen", ".", ":", "param", "message", ":", "the", "prompt", "message", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/prompt_utils.py#L116-L130
aegirhall/console-menu
consolemenu/prompt_utils.py
PromptUtils.prompt_and_confirm_password
def prompt_and_confirm_password(self, message): """ Method to prompt for a password using the given message, then prompt for a confirmation password, and verify that they match. :param message: the prompt message :return: the password """ while True: pwd = self.input_password(message) cpwd = self.input_password("Confirm password") if pwd == cpwd: return pwd else: self.__screen.cprintln("Passwords do not match.")
python
def prompt_and_confirm_password(self, message): while True: pwd = self.input_password(message) cpwd = self.input_password("Confirm password") if pwd == cpwd: return pwd else: self.__screen.cprintln("Passwords do not match.")
[ "def", "prompt_and_confirm_password", "(", "self", ",", "message", ")", ":", "while", "True", ":", "pwd", "=", "self", ".", "input_password", "(", "message", ")", "cpwd", "=", "self", ".", "input_password", "(", "\"Confirm password\"", ")", "if", "pwd", "==", "cpwd", ":", "return", "pwd", "else", ":", "self", ".", "__screen", ".", "cprintln", "(", "\"Passwords do not match.\"", ")" ]
Method to prompt for a password using the given message, then prompt for a confirmation password, and verify that they match. :param message: the prompt message :return: the password
[ "Method", "to", "prompt", "for", "a", "password", "using", "the", "given", "message", "then", "prompt", "for", "a", "confirmation", "password", "and", "verify", "that", "they", "match", ".", ":", "param", "message", ":", "the", "prompt", "message", ":", "return", ":", "the", "password" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/prompt_utils.py#L146-L159
aegirhall/console-menu
consolemenu/prompt_utils.py
PromptUtils.prompt_for_bilateral_choice
def prompt_for_bilateral_choice(self, prompt, option1, option2): """ Prompt the user for a response that must be one of the two supplied choices. NOTE: The user input verification is case-insensitive, but will return the original case provided by the given options. """ if prompt is None: prompt = '' prompt = prompt.rstrip() + ' (' + option1 + '/' + option2 + ')' while True: user_input = self.__screen.input(prompt) if str(user_input).lower() == option1.lower(): return option1 elif str(user_input).lower() == option2.lower(): return option2
python
def prompt_for_bilateral_choice(self, prompt, option1, option2): if prompt is None: prompt = '' prompt = prompt.rstrip() + ' (' + option1 + '/' + option2 + ')' while True: user_input = self.__screen.input(prompt) if str(user_input).lower() == option1.lower(): return option1 elif str(user_input).lower() == option2.lower(): return option2
[ "def", "prompt_for_bilateral_choice", "(", "self", ",", "prompt", ",", "option1", ",", "option2", ")", ":", "if", "prompt", "is", "None", ":", "prompt", "=", "''", "prompt", "=", "prompt", ".", "rstrip", "(", ")", "+", "' ('", "+", "option1", "+", "'/'", "+", "option2", "+", "')'", "while", "True", ":", "user_input", "=", "self", ".", "__screen", ".", "input", "(", "prompt", ")", "if", "str", "(", "user_input", ")", ".", "lower", "(", ")", "==", "option1", ".", "lower", "(", ")", ":", "return", "option1", "elif", "str", "(", "user_input", ")", ".", "lower", "(", ")", "==", "option2", ".", "lower", "(", ")", ":", "return", "option2" ]
Prompt the user for a response that must be one of the two supplied choices. NOTE: The user input verification is case-insensitive, but will return the original case provided by the given options.
[ "Prompt", "the", "user", "for", "a", "response", "that", "must", "be", "one", "of", "the", "two", "supplied", "choices", ".", "NOTE", ":", "The", "user", "input", "verification", "is", "case", "-", "insensitive", "but", "will", "return", "the", "original", "case", "provided", "by", "the", "given", "options", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/prompt_utils.py#L161-L175
aegirhall/console-menu
consolemenu/prompt_utils.py
PromptUtils.prompt_for_trilateral_choice
def prompt_for_trilateral_choice(self, prompt, option1, option2, option3): """ Prompt the user for a response that must be one of the three supplied choices. NOTE: The user input verification is case-insensitive, but will return the original case provided by the given options. """ if prompt is None: prompt = '' prompt = prompt.rstrip() + ' (' + option1 + '/' + option2 + '/' + option3 + ')' while True: user_input = self.__screen.input(prompt) if str(user_input).lower() == option1.lower(): return option1 elif str(user_input).lower() == option2.lower(): return option2 elif str(user_input).lower() == option3.lower(): return option3
python
def prompt_for_trilateral_choice(self, prompt, option1, option2, option3): if prompt is None: prompt = '' prompt = prompt.rstrip() + ' (' + option1 + '/' + option2 + '/' + option3 + ')' while True: user_input = self.__screen.input(prompt) if str(user_input).lower() == option1.lower(): return option1 elif str(user_input).lower() == option2.lower(): return option2 elif str(user_input).lower() == option3.lower(): return option3
[ "def", "prompt_for_trilateral_choice", "(", "self", ",", "prompt", ",", "option1", ",", "option2", ",", "option3", ")", ":", "if", "prompt", "is", "None", ":", "prompt", "=", "''", "prompt", "=", "prompt", ".", "rstrip", "(", ")", "+", "' ('", "+", "option1", "+", "'/'", "+", "option2", "+", "'/'", "+", "option3", "+", "')'", "while", "True", ":", "user_input", "=", "self", ".", "__screen", ".", "input", "(", "prompt", ")", "if", "str", "(", "user_input", ")", ".", "lower", "(", ")", "==", "option1", ".", "lower", "(", ")", ":", "return", "option1", "elif", "str", "(", "user_input", ")", ".", "lower", "(", ")", "==", "option2", ".", "lower", "(", ")", ":", "return", "option2", "elif", "str", "(", "user_input", ")", ".", "lower", "(", ")", "==", "option3", ".", "lower", "(", ")", ":", "return", "option3" ]
Prompt the user for a response that must be one of the three supplied choices. NOTE: The user input verification is case-insensitive, but will return the original case provided by the given options.
[ "Prompt", "the", "user", "for", "a", "response", "that", "must", "be", "one", "of", "the", "three", "supplied", "choices", ".", "NOTE", ":", "The", "user", "input", "verification", "is", "case", "-", "insensitive", "but", "will", "return", "the", "original", "case", "provided", "by", "the", "given", "options", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/prompt_utils.py#L177-L193
aegirhall/console-menu
consolemenu/prompt_utils.py
PromptUtils.prompt_for_numbered_choice
def prompt_for_numbered_choice(self, choices, title=None, prompt=">"): """ Displays a numbered vertical list of choices from the provided list of strings. :param choices: list of choices to display :param title: optional title to display above the numbered list :param prompt: prompt string. Default is ">" :return: an int representing the selected index. """ if choices is None or len(choices) < 1: raise Exception('choices list must contain at least one element.') while True: self.clear() if title: self.screen.println(title + "\n") for i in range(0, len(choices)): print(' {:<4}{choice}'.format(str(i + 1) + ') ', choice=choices[i])) answer = self.screen.input('\n{} '.format(prompt)) try: index = int(answer) - 1 if 0 <= index < len(choices): return index except Exception as e: continue
python
def prompt_for_numbered_choice(self, choices, title=None, prompt=">"): if choices is None or len(choices) < 1: raise Exception('choices list must contain at least one element.') while True: self.clear() if title: self.screen.println(title + "\n") for i in range(0, len(choices)): print(' {:<4}{choice}'.format(str(i + 1) + ') ', choice=choices[i])) answer = self.screen.input('\n{} '.format(prompt)) try: index = int(answer) - 1 if 0 <= index < len(choices): return index except Exception as e: continue
[ "def", "prompt_for_numbered_choice", "(", "self", ",", "choices", ",", "title", "=", "None", ",", "prompt", "=", "\">\"", ")", ":", "if", "choices", "is", "None", "or", "len", "(", "choices", ")", "<", "1", ":", "raise", "Exception", "(", "'choices list must contain at least one element.'", ")", "while", "True", ":", "self", ".", "clear", "(", ")", "if", "title", ":", "self", ".", "screen", ".", "println", "(", "title", "+", "\"\\n\"", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "choices", ")", ")", ":", "print", "(", "' {:<4}{choice}'", ".", "format", "(", "str", "(", "i", "+", "1", ")", "+", "') '", ",", "choice", "=", "choices", "[", "i", "]", ")", ")", "answer", "=", "self", ".", "screen", ".", "input", "(", "'\\n{} '", ".", "format", "(", "prompt", ")", ")", "try", ":", "index", "=", "int", "(", "answer", ")", "-", "1", "if", "0", "<=", "index", "<", "len", "(", "choices", ")", ":", "return", "index", "except", "Exception", "as", "e", ":", "continue" ]
Displays a numbered vertical list of choices from the provided list of strings. :param choices: list of choices to display :param title: optional title to display above the numbered list :param prompt: prompt string. Default is ">" :return: an int representing the selected index.
[ "Displays", "a", "numbered", "vertical", "list", "of", "choices", "from", "the", "provided", "list", "of", "strings", ".", ":", "param", "choices", ":", "list", "of", "choices", "to", "display", ":", "param", "title", ":", "optional", "title", "to", "display", "above", "the", "numbered", "list", ":", "param", "prompt", ":", "prompt", "string", ".", "Default", "is", ">", ":", "return", ":", "an", "int", "representing", "the", "selected", "index", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/prompt_utils.py#L204-L231
aegirhall/console-menu
consolemenu/prompt_utils.py
PromptUtils.validate_input
def validate_input(self, input_string, validators): """ Validate the given input string against the specified list of validators. :param input_string: the input string to verify. :param validators: the list of validators. :raises InvalidValidator if the list of validators does not provide a valid InputValidator class. :return: a boolean representing the validation result. True if the input string is valid; False otherwise. """ validation_result = True if isinstance(validators, BaseValidator): validators = [validators] elif validators is None: validators = [] if isinstance(validators, list): validation_results = [] for validator in validators: if isinstance(validator, BaseValidator): validation_results.append(validator.validate(input_string=input_string)) else: raise InvalidValidator("Validator {} is not a valid validator".format(validator)) validation_result = all(validation_results) else: raise InvalidValidator("Validator {} is not a valid validator".format(validators)) return validation_result
python
def validate_input(self, input_string, validators): validation_result = True if isinstance(validators, BaseValidator): validators = [validators] elif validators is None: validators = [] if isinstance(validators, list): validation_results = [] for validator in validators: if isinstance(validator, BaseValidator): validation_results.append(validator.validate(input_string=input_string)) else: raise InvalidValidator("Validator {} is not a valid validator".format(validator)) validation_result = all(validation_results) else: raise InvalidValidator("Validator {} is not a valid validator".format(validators)) return validation_result
[ "def", "validate_input", "(", "self", ",", "input_string", ",", "validators", ")", ":", "validation_result", "=", "True", "if", "isinstance", "(", "validators", ",", "BaseValidator", ")", ":", "validators", "=", "[", "validators", "]", "elif", "validators", "is", "None", ":", "validators", "=", "[", "]", "if", "isinstance", "(", "validators", ",", "list", ")", ":", "validation_results", "=", "[", "]", "for", "validator", "in", "validators", ":", "if", "isinstance", "(", "validator", ",", "BaseValidator", ")", ":", "validation_results", ".", "append", "(", "validator", ".", "validate", "(", "input_string", "=", "input_string", ")", ")", "else", ":", "raise", "InvalidValidator", "(", "\"Validator {} is not a valid validator\"", ".", "format", "(", "validator", ")", ")", "validation_result", "=", "all", "(", "validation_results", ")", "else", ":", "raise", "InvalidValidator", "(", "\"Validator {} is not a valid validator\"", ".", "format", "(", "validators", ")", ")", "return", "validation_result" ]
Validate the given input string against the specified list of validators. :param input_string: the input string to verify. :param validators: the list of validators. :raises InvalidValidator if the list of validators does not provide a valid InputValidator class. :return: a boolean representing the validation result. True if the input string is valid; False otherwise.
[ "Validate", "the", "given", "input", "string", "against", "the", "specified", "list", "of", "validators", ".", ":", "param", "input_string", ":", "the", "input", "string", "to", "verify", ".", ":", "param", "validators", ":", "the", "list", "of", "validators", ".", ":", "raises", "InvalidValidator", "if", "the", "list", "of", "validators", "does", "not", "provide", "a", "valid", "InputValidator", "class", ".", ":", "return", ":", "a", "boolean", "representing", "the", "validation", "result", ".", "True", "if", "the", "input", "string", "is", "valid", ";", "False", "otherwise", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/prompt_utils.py#L233-L260
aegirhall/console-menu
consolemenu/validators/regex.py
RegexValidator.validate
def validate(self, input_string): """ Validate input_string against a regex pattern :return: True if match / False otherwise """ validation_result = False try: validation_result = bool(match(pattern=self.pattern, string=input_string)) except TypeError as e: self.log.error( 'Exception while validating Regex, pattern={}, input_string={} - exception: {}'.format(self.pattern, input_string, e)) return validation_result
python
def validate(self, input_string): validation_result = False try: validation_result = bool(match(pattern=self.pattern, string=input_string)) except TypeError as e: self.log.error( 'Exception while validating Regex, pattern={}, input_string={} - exception: {}'.format(self.pattern, input_string, e)) return validation_result
[ "def", "validate", "(", "self", ",", "input_string", ")", ":", "validation_result", "=", "False", "try", ":", "validation_result", "=", "bool", "(", "match", "(", "pattern", "=", "self", ".", "pattern", ",", "string", "=", "input_string", ")", ")", "except", "TypeError", "as", "e", ":", "self", ".", "log", ".", "error", "(", "'Exception while validating Regex, pattern={}, input_string={} - exception: {}'", ".", "format", "(", "self", ".", "pattern", ",", "input_string", ",", "e", ")", ")", "return", "validation_result" ]
Validate input_string against a regex pattern :return: True if match / False otherwise
[ "Validate", "input_string", "against", "a", "regex", "pattern" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/validators/regex.py#L16-L30
aegirhall/console-menu
consolemenu/multiselect_menu.py
MultiSelectMenu.append_item
def append_item(self, item): """ Add an item to the end of the menu before the exit item. Note that Multi-Select Menus will not allow a SubmenuItem to be added, as multi-select menus are expected to be used only for executing multiple actions. Args: item (:obj:`MenuItem`): The item to be added Raises: TypeError: If the specified MenuIem is a SubmenuItem. """ if isinstance(item, SubmenuItem): raise TypeError("SubmenuItems cannot be added to a MultiSelectMenu") super(MultiSelectMenu, self).append_item(item)
python
def append_item(self, item): if isinstance(item, SubmenuItem): raise TypeError("SubmenuItems cannot be added to a MultiSelectMenu") super(MultiSelectMenu, self).append_item(item)
[ "def", "append_item", "(", "self", ",", "item", ")", ":", "if", "isinstance", "(", "item", ",", "SubmenuItem", ")", ":", "raise", "TypeError", "(", "\"SubmenuItems cannot be added to a MultiSelectMenu\"", ")", "super", "(", "MultiSelectMenu", ",", "self", ")", ".", "append_item", "(", "item", ")" ]
Add an item to the end of the menu before the exit item. Note that Multi-Select Menus will not allow a SubmenuItem to be added, as multi-select menus are expected to be used only for executing multiple actions. Args: item (:obj:`MenuItem`): The item to be added Raises: TypeError: If the specified MenuIem is a SubmenuItem.
[ "Add", "an", "item", "to", "the", "end", "of", "the", "menu", "before", "the", "exit", "item", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/multiselect_menu.py#L26-L41
aegirhall/console-menu
consolemenu/multiselect_menu.py
MultiSelectMenu.process_user_input
def process_user_input(self): """ This overrides the method in ConsoleMenu to allow for comma-delimited and range inputs. Examples: All of the following inputs would have the same result: * 1,2,3,4 * 1-4 * 1-2,3-4 * 1 - 4 * 1, 2, 3, 4 Raises: ValueError: If the input cannot be correctly parsed. """ user_input = self.screen.input() try: indexes = self.__parse_range_list(user_input) # Subtract 1 from each number for its actual index number indexes[:] = [x - 1 for x in indexes if 0 < x < len(self.items) + 1] for index in indexes: self.current_option = index self.select() except Exception as e: return
python
def process_user_input(self): user_input = self.screen.input() try: indexes = self.__parse_range_list(user_input) indexes[:] = [x - 1 for x in indexes if 0 < x < len(self.items) + 1] for index in indexes: self.current_option = index self.select() except Exception as e: return
[ "def", "process_user_input", "(", "self", ")", ":", "user_input", "=", "self", ".", "screen", ".", "input", "(", ")", "try", ":", "indexes", "=", "self", ".", "__parse_range_list", "(", "user_input", ")", "# Subtract 1 from each number for its actual index number", "indexes", "[", ":", "]", "=", "[", "x", "-", "1", "for", "x", "in", "indexes", "if", "0", "<", "x", "<", "len", "(", "self", ".", "items", ")", "+", "1", "]", "for", "index", "in", "indexes", ":", "self", ".", "current_option", "=", "index", "self", ".", "select", "(", ")", "except", "Exception", "as", "e", ":", "return" ]
This overrides the method in ConsoleMenu to allow for comma-delimited and range inputs. Examples: All of the following inputs would have the same result: * 1,2,3,4 * 1-4 * 1-2,3-4 * 1 - 4 * 1, 2, 3, 4 Raises: ValueError: If the input cannot be correctly parsed.
[ "This", "overrides", "the", "method", "in", "ConsoleMenu", "to", "allow", "for", "comma", "-", "delimited", "and", "range", "inputs", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/multiselect_menu.py#L43-L67
aegirhall/console-menu
consolemenu/console_menu.py
ConsoleMenu.selected_item
def selected_item(self): """ :obj:`consolemenu.items.MenuItem`: The item in :attr:`items` that the user most recently selected, or None. """ if self.items and self.selected_option != -1: return self.items[self.current_option] else: return None
python
def selected_item(self): if self.items and self.selected_option != -1: return self.items[self.current_option] else: return None
[ "def", "selected_item", "(", "self", ")", ":", "if", "self", ".", "items", "and", "self", ".", "selected_option", "!=", "-", "1", ":", "return", "self", ".", "items", "[", "self", ".", "current_option", "]", "else", ":", "return", "None" ]
:obj:`consolemenu.items.MenuItem`: The item in :attr:`items` that the user most recently selected, or None.
[ ":", "obj", ":", "consolemenu", ".", "items", ".", "MenuItem", ":", "The", "item", "in", ":", "attr", ":", "items", "that", "the", "user", "most", "recently", "selected", "or", "None", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L93-L100
aegirhall/console-menu
consolemenu/console_menu.py
ConsoleMenu.append_item
def append_item(self, item): """ Add an item to the end of the menu before the exit item. Args: item (MenuItem): The item to be added. """ did_remove = self.remove_exit() item.menu = self self.items.append(item) if did_remove: self.add_exit()
python
def append_item(self, item): did_remove = self.remove_exit() item.menu = self self.items.append(item) if did_remove: self.add_exit()
[ "def", "append_item", "(", "self", ",", "item", ")", ":", "did_remove", "=", "self", ".", "remove_exit", "(", ")", "item", ".", "menu", "=", "self", "self", ".", "items", ".", "append", "(", "item", ")", "if", "did_remove", ":", "self", ".", "add_exit", "(", ")" ]
Add an item to the end of the menu before the exit item. Args: item (MenuItem): The item to be added.
[ "Add", "an", "item", "to", "the", "end", "of", "the", "menu", "before", "the", "exit", "item", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L102-L114
aegirhall/console-menu
consolemenu/console_menu.py
ConsoleMenu.remove_item
def remove_item(self, item): """ Remove the specified item from the menu. Args: item (MenuItem): the item to be removed. Returns: bool: True if the item was removed; False otherwise. """ for idx, _item in enumerate(self.items): if item == _item: del self.items[idx] return True return False
python
def remove_item(self, item): for idx, _item in enumerate(self.items): if item == _item: del self.items[idx] return True return False
[ "def", "remove_item", "(", "self", ",", "item", ")", ":", "for", "idx", ",", "_item", "in", "enumerate", "(", "self", ".", "items", ")", ":", "if", "item", "==", "_item", ":", "del", "self", ".", "items", "[", "idx", "]", "return", "True", "return", "False" ]
Remove the specified item from the menu. Args: item (MenuItem): the item to be removed. Returns: bool: True if the item was removed; False otherwise.
[ "Remove", "the", "specified", "item", "from", "the", "menu", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L116-L130
aegirhall/console-menu
consolemenu/console_menu.py
ConsoleMenu.remove_exit
def remove_exit(self): """ Remove the exit item if necessary. Used to make sure we only remove the exit item, not something else. Returns: bool: True if item needed to be removed, False otherwise. """ if self.items: if self.items[-1] is self.exit_item: del self.items[-1] return True return False
python
def remove_exit(self): if self.items: if self.items[-1] is self.exit_item: del self.items[-1] return True return False
[ "def", "remove_exit", "(", "self", ")", ":", "if", "self", ".", "items", ":", "if", "self", ".", "items", "[", "-", "1", "]", "is", "self", ".", "exit_item", ":", "del", "self", ".", "items", "[", "-", "1", "]", "return", "True", "return", "False" ]
Remove the exit item if necessary. Used to make sure we only remove the exit item, not something else. Returns: bool: True if item needed to be removed, False otherwise.
[ "Remove", "the", "exit", "item", "if", "necessary", ".", "Used", "to", "make", "sure", "we", "only", "remove", "the", "exit", "item", "not", "something", "else", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L144-L155
aegirhall/console-menu
consolemenu/console_menu.py
ConsoleMenu.start
def start(self, show_exit_option=None): """ Start the menu in a new thread and allow the user to interact with it. The thread is a daemon, so :meth:`join()<consolemenu.ConsoleMenu.join>` should be called if there's a possibility that the main thread will exit before the menu is done Args: show_exit_option (bool): Specify whether the exit item should be shown, defaults to the value set in the constructor """ self.previous_active_menu = ConsoleMenu.currently_active_menu ConsoleMenu.currently_active_menu = None self.should_exit = False if show_exit_option is None: show_exit_option = self.show_exit_option if show_exit_option: self.add_exit() else: self.remove_exit() try: self._main_thread = threading.Thread(target=self._wrap_start, daemon=True) except TypeError: self._main_thread = threading.Thread(target=self._wrap_start) self._main_thread.daemon = True self._main_thread.start()
python
def start(self, show_exit_option=None): self.previous_active_menu = ConsoleMenu.currently_active_menu ConsoleMenu.currently_active_menu = None self.should_exit = False if show_exit_option is None: show_exit_option = self.show_exit_option if show_exit_option: self.add_exit() else: self.remove_exit() try: self._main_thread = threading.Thread(target=self._wrap_start, daemon=True) except TypeError: self._main_thread = threading.Thread(target=self._wrap_start) self._main_thread.daemon = True self._main_thread.start()
[ "def", "start", "(", "self", ",", "show_exit_option", "=", "None", ")", ":", "self", ".", "previous_active_menu", "=", "ConsoleMenu", ".", "currently_active_menu", "ConsoleMenu", ".", "currently_active_menu", "=", "None", "self", ".", "should_exit", "=", "False", "if", "show_exit_option", "is", "None", ":", "show_exit_option", "=", "self", ".", "show_exit_option", "if", "show_exit_option", ":", "self", ".", "add_exit", "(", ")", "else", ":", "self", ".", "remove_exit", "(", ")", "try", ":", "self", ".", "_main_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_wrap_start", ",", "daemon", "=", "True", ")", "except", "TypeError", ":", "self", ".", "_main_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_wrap_start", ")", "self", ".", "_main_thread", ".", "daemon", "=", "True", "self", ".", "_main_thread", ".", "start", "(", ")" ]
Start the menu in a new thread and allow the user to interact with it. The thread is a daemon, so :meth:`join()<consolemenu.ConsoleMenu.join>` should be called if there's a possibility that the main thread will exit before the menu is done Args: show_exit_option (bool): Specify whether the exit item should be shown, defaults to the value set in the constructor
[ "Start", "the", "menu", "in", "a", "new", "thread", "and", "allow", "the", "user", "to", "interact", "with", "it", ".", "The", "thread", "is", "a", "daemon", "so", ":", "meth", ":", "join", "()", "<consolemenu", ".", "ConsoleMenu", ".", "join", ">", "should", "be", "called", "if", "there", "s", "a", "possibility", "that", "the", "main", "thread", "will", "exit", "before", "the", "menu", "is", "done" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L172-L202
aegirhall/console-menu
consolemenu/console_menu.py
ConsoleMenu.draw
def draw(self): """ Refresh the screen and redraw the menu. Should be called whenever something changes that needs to be redrawn. """ self.screen.printf(self.formatter.format(title=self.title, subtitle=self.subtitle, items=self.items, prologue_text=self.prologue_text, epilogue_text=self.epilogue_text))
python
def draw(self): self.screen.printf(self.formatter.format(title=self.title, subtitle=self.subtitle, items=self.items, prologue_text=self.prologue_text, epilogue_text=self.epilogue_text))
[ "def", "draw", "(", "self", ")", ":", "self", ".", "screen", ".", "printf", "(", "self", ".", "formatter", ".", "format", "(", "title", "=", "self", ".", "title", ",", "subtitle", "=", "self", ".", "subtitle", ",", "items", "=", "self", ".", "items", ",", "prologue_text", "=", "self", ".", "prologue_text", ",", "epilogue_text", "=", "self", ".", "epilogue_text", ")", ")" ]
Refresh the screen and redraw the menu. Should be called whenever something changes that needs to be redrawn.
[ "Refresh", "the", "screen", "and", "redraw", "the", "menu", ".", "Should", "be", "called", "whenever", "something", "changes", "that", "needs", "to", "be", "redrawn", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L226-L231
aegirhall/console-menu
consolemenu/console_menu.py
ConsoleMenu.process_user_input
def process_user_input(self): """ Gets the next single character and decides what to do with it """ user_input = self.get_input() try: num = int(user_input) except Exception: return if 0 < num < len(self.items) + 1: self.current_option = num - 1 self.select() return user_input
python
def process_user_input(self): user_input = self.get_input() try: num = int(user_input) except Exception: return if 0 < num < len(self.items) + 1: self.current_option = num - 1 self.select() return user_input
[ "def", "process_user_input", "(", "self", ")", ":", "user_input", "=", "self", ".", "get_input", "(", ")", "try", ":", "num", "=", "int", "(", "user_input", ")", "except", "Exception", ":", "return", "if", "0", "<", "num", "<", "len", "(", "self", ".", "items", ")", "+", "1", ":", "self", ".", "current_option", "=", "num", "-", "1", "self", ".", "select", "(", ")", "return", "user_input" ]
Gets the next single character and decides what to do with it
[ "Gets", "the", "next", "single", "character", "and", "decides", "what", "to", "do", "with", "it" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L297-L311
aegirhall/console-menu
consolemenu/console_menu.py
ConsoleMenu.go_down
def go_down(self): """ Go down one, wrap to beginning if necessary """ if self.current_option < len(self.items) - 1: self.current_option += 1 else: self.current_option = 0 self.draw()
python
def go_down(self): if self.current_option < len(self.items) - 1: self.current_option += 1 else: self.current_option = 0 self.draw()
[ "def", "go_down", "(", "self", ")", ":", "if", "self", ".", "current_option", "<", "len", "(", "self", ".", "items", ")", "-", "1", ":", "self", ".", "current_option", "+=", "1", "else", ":", "self", ".", "current_option", "=", "0", "self", ".", "draw", "(", ")" ]
Go down one, wrap to beginning if necessary
[ "Go", "down", "one", "wrap", "to", "beginning", "if", "necessary" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L323-L331
aegirhall/console-menu
consolemenu/console_menu.py
ConsoleMenu.go_up
def go_up(self): """ Go up one, wrap to end if necessary """ if self.current_option > 0: self.current_option += -1 else: self.current_option = len(self.items) - 1 self.draw()
python
def go_up(self): if self.current_option > 0: self.current_option += -1 else: self.current_option = len(self.items) - 1 self.draw()
[ "def", "go_up", "(", "self", ")", ":", "if", "self", ".", "current_option", ">", "0", ":", "self", ".", "current_option", "+=", "-", "1", "else", ":", "self", ".", "current_option", "=", "len", "(", "self", ".", "items", ")", "-", "1", "self", ".", "draw", "(", ")" ]
Go up one, wrap to end if necessary
[ "Go", "up", "one", "wrap", "to", "end", "if", "necessary" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L333-L341
aegirhall/console-menu
consolemenu/console_menu.py
ExitItem.show
def show(self, index): """ This class overrides this method """ if self.menu and self.menu.parent: self.text = "Return to %s" % self.menu.parent.title # Check if menu title ends with menu. (Some menus will include Menu in the name). if not self.text.strip().lower().endswith("menu"): self.text += " menu" else: self.text = "Exit" return super(ExitItem, self).show(index)
python
def show(self, index): if self.menu and self.menu.parent: self.text = "Return to %s" % self.menu.parent.title if not self.text.strip().lower().endswith("menu"): self.text += " menu" else: self.text = "Exit" return super(ExitItem, self).show(index)
[ "def", "show", "(", "self", ",", "index", ")", ":", "if", "self", ".", "menu", "and", "self", ".", "menu", ".", "parent", ":", "self", ".", "text", "=", "\"Return to %s\"", "%", "self", ".", "menu", ".", "parent", ".", "title", "# Check if menu title ends with menu. (Some menus will include Menu in the name).", "if", "not", "self", ".", "text", ".", "strip", "(", ")", ".", "lower", "(", ")", ".", "endswith", "(", "\"menu\"", ")", ":", "self", ".", "text", "+=", "\" menu\"", "else", ":", "self", ".", "text", "=", "\"Exit\"", "return", "super", "(", "ExitItem", ",", "self", ")", ".", "show", "(", "index", ")" ]
This class overrides this method
[ "This", "class", "overrides", "this", "method" ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L446-L457
aegirhall/console-menu
consolemenu/selection_menu.py
SelectionMenu.get_selection
def get_selection(cls, strings, title="Select an option", subtitle=None, exit_option=True, _menu=None): """ Single-method way of getting a selection out of a list of strings. Args: strings (:obj:`list` of :obj:`str`): The list of strings this menu should be built from. title (str): The title of the menu. subtitle (str): The subtitle of the menu. exit_option (bool): Specifies whether this menu should show an exit item by default. Defaults to True. _menu: Should probably only be used for testing, pass in a list and the created menu used internally by the method will be appended to it Returns: int: The index of the selected option. """ menu = cls(strings, title, subtitle, exit_option) if _menu is not None: _menu.append(menu) menu.show() menu.join() return menu.selected_option
python
def get_selection(cls, strings, title="Select an option", subtitle=None, exit_option=True, _menu=None): menu = cls(strings, title, subtitle, exit_option) if _menu is not None: _menu.append(menu) menu.show() menu.join() return menu.selected_option
[ "def", "get_selection", "(", "cls", ",", "strings", ",", "title", "=", "\"Select an option\"", ",", "subtitle", "=", "None", ",", "exit_option", "=", "True", ",", "_menu", "=", "None", ")", ":", "menu", "=", "cls", "(", "strings", ",", "title", ",", "subtitle", ",", "exit_option", ")", "if", "_menu", "is", "not", "None", ":", "_menu", ".", "append", "(", "menu", ")", "menu", ".", "show", "(", ")", "menu", ".", "join", "(", ")", "return", "menu", ".", "selected_option" ]
Single-method way of getting a selection out of a list of strings. Args: strings (:obj:`list` of :obj:`str`): The list of strings this menu should be built from. title (str): The title of the menu. subtitle (str): The subtitle of the menu. exit_option (bool): Specifies whether this menu should show an exit item by default. Defaults to True. _menu: Should probably only be used for testing, pass in a list and the created menu used internally by the method will be appended to it Returns: int: The index of the selected option.
[ "Single", "-", "method", "way", "of", "getting", "a", "selection", "out", "of", "a", "list", "of", "strings", "." ]
train
https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/selection_menu.py#L29-L50
timothyb0912/pylogit
pylogit/choice_tools.py
get_dataframe_from_data
def get_dataframe_from_data(data): """ Parameters ---------- data : string or pandas dataframe. If string, data should be an absolute or relative path to a CSV file containing the long format data for this choice model. Note long format has one row per available alternative for each observation. If pandas dataframe, the dataframe should be the long format data for the choice model. Returns ------- dataframe : pandas dataframe of the long format data for the choice model. """ if isinstance(data, str): if data.endswith(".csv"): dataframe = pd.read_csv(data) else: msg_1 = "data = {} is of unknown file type." msg_2 = " Please pass path to csv." raise ValueError(msg_1.format(data) + msg_2) elif isinstance(data, pd.DataFrame): dataframe = data else: msg_1 = "type(data) = {} is an invalid type." msg_2 = " Please pass pandas dataframe or path to csv." raise TypeError(msg_1.format(type(data)) + msg_2) return dataframe
python
def get_dataframe_from_data(data): if isinstance(data, str): if data.endswith(".csv"): dataframe = pd.read_csv(data) else: msg_1 = "data = {} is of unknown file type." msg_2 = " Please pass path to csv." raise ValueError(msg_1.format(data) + msg_2) elif isinstance(data, pd.DataFrame): dataframe = data else: msg_1 = "type(data) = {} is an invalid type." msg_2 = " Please pass pandas dataframe or path to csv." raise TypeError(msg_1.format(type(data)) + msg_2) return dataframe
[ "def", "get_dataframe_from_data", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "if", "data", ".", "endswith", "(", "\".csv\"", ")", ":", "dataframe", "=", "pd", ".", "read_csv", "(", "data", ")", "else", ":", "msg_1", "=", "\"data = {} is of unknown file type.\"", "msg_2", "=", "\" Please pass path to csv.\"", "raise", "ValueError", "(", "msg_1", ".", "format", "(", "data", ")", "+", "msg_2", ")", "elif", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "dataframe", "=", "data", "else", ":", "msg_1", "=", "\"type(data) = {} is an invalid type.\"", "msg_2", "=", "\" Please pass pandas dataframe or path to csv.\"", "raise", "TypeError", "(", "msg_1", ".", "format", "(", "type", "(", "data", ")", ")", "+", "msg_2", ")", "return", "dataframe" ]
Parameters ---------- data : string or pandas dataframe. If string, data should be an absolute or relative path to a CSV file containing the long format data for this choice model. Note long format has one row per available alternative for each observation. If pandas dataframe, the dataframe should be the long format data for the choice model. Returns ------- dataframe : pandas dataframe of the long format data for the choice model.
[ "Parameters", "----------", "data", ":", "string", "or", "pandas", "dataframe", ".", "If", "string", "data", "should", "be", "an", "absolute", "or", "relative", "path", "to", "a", "CSV", "file", "containing", "the", "long", "format", "data", "for", "this", "choice", "model", ".", "Note", "long", "format", "has", "one", "row", "per", "available", "alternative", "for", "each", "observation", ".", "If", "pandas", "dataframe", "the", "dataframe", "should", "be", "the", "long", "format", "data", "for", "the", "choice", "model", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L23-L52
timothyb0912/pylogit
pylogit/choice_tools.py
ensure_object_is_ordered_dict
def ensure_object_is_ordered_dict(item, title): """ Checks that the item is an OrderedDict. If not, raises ValueError. """ assert isinstance(title, str) if not isinstance(item, OrderedDict): msg = "{} must be an OrderedDict. {} passed instead." raise TypeError(msg.format(title, type(item))) return None
python
def ensure_object_is_ordered_dict(item, title): assert isinstance(title, str) if not isinstance(item, OrderedDict): msg = "{} must be an OrderedDict. {} passed instead." raise TypeError(msg.format(title, type(item))) return None
[ "def", "ensure_object_is_ordered_dict", "(", "item", ",", "title", ")", ":", "assert", "isinstance", "(", "title", ",", "str", ")", "if", "not", "isinstance", "(", "item", ",", "OrderedDict", ")", ":", "msg", "=", "\"{} must be an OrderedDict. {} passed instead.\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "title", ",", "type", "(", "item", ")", ")", ")", "return", "None" ]
Checks that the item is an OrderedDict. If not, raises ValueError.
[ "Checks", "that", "the", "item", "is", "an", "OrderedDict", ".", "If", "not", "raises", "ValueError", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L73-L83
timothyb0912/pylogit
pylogit/choice_tools.py
ensure_object_is_string
def ensure_object_is_string(item, title): """ Checks that the item is a string. If not, raises ValueError. """ assert isinstance(title, str) if not isinstance(item, str): msg = "{} must be a string. {} passed instead." raise TypeError(msg.format(title, type(item))) return None
python
def ensure_object_is_string(item, title): assert isinstance(title, str) if not isinstance(item, str): msg = "{} must be a string. {} passed instead." raise TypeError(msg.format(title, type(item))) return None
[ "def", "ensure_object_is_string", "(", "item", ",", "title", ")", ":", "assert", "isinstance", "(", "title", ",", "str", ")", "if", "not", "isinstance", "(", "item", ",", "str", ")", ":", "msg", "=", "\"{} must be a string. {} passed instead.\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "title", ",", "type", "(", "item", ")", ")", ")", "return", "None" ]
Checks that the item is a string. If not, raises ValueError.
[ "Checks", "that", "the", "item", "is", "a", "string", ".", "If", "not", "raises", "ValueError", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L86-L96
timothyb0912/pylogit
pylogit/choice_tools.py
ensure_object_is_ndarray
def ensure_object_is_ndarray(item, title): """ Ensures that a given mapping matrix is a dense numpy array. Raises a helpful TypeError if otherwise. """ assert isinstance(title, str) if not isinstance(item, np.ndarray): msg = "{} must be a np.ndarray. {} passed instead." raise TypeError(msg.format(title, type(item))) return None
python
def ensure_object_is_ndarray(item, title): assert isinstance(title, str) if not isinstance(item, np.ndarray): msg = "{} must be a np.ndarray. {} passed instead." raise TypeError(msg.format(title, type(item))) return None
[ "def", "ensure_object_is_ndarray", "(", "item", ",", "title", ")", ":", "assert", "isinstance", "(", "title", ",", "str", ")", "if", "not", "isinstance", "(", "item", ",", "np", ".", "ndarray", ")", ":", "msg", "=", "\"{} must be a np.ndarray. {} passed instead.\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "title", ",", "type", "(", "item", ")", ")", ")", "return", "None" ]
Ensures that a given mapping matrix is a dense numpy array. Raises a helpful TypeError if otherwise.
[ "Ensures", "that", "a", "given", "mapping", "matrix", "is", "a", "dense", "numpy", "array", ".", "Raises", "a", "helpful", "TypeError", "if", "otherwise", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L99-L110
timothyb0912/pylogit
pylogit/choice_tools.py
ensure_columns_are_in_dataframe
def ensure_columns_are_in_dataframe(columns, dataframe, col_title='', data_title='data'): """ Checks whether each column in `columns` is in `dataframe`. Raises ValueError if any of the columns are not in the dataframe. Parameters ---------- columns : list of strings. Each string should represent a column heading in dataframe. dataframe : pandas DataFrame. Dataframe containing the data for the choice model to be estimated. col_title : str, optional. Denotes the title of the columns that were passed to the function. data_title : str, optional. Denotes the title of the dataframe that is being checked to see whether it contains the passed columns. Default == 'data' Returns ------- None. """ # Make sure columns is an iterable assert isinstance(columns, Iterable) # Make sure dataframe is a pandas dataframe assert isinstance(dataframe, pd.DataFrame) # Make sure title is a string assert isinstance(col_title, str) assert isinstance(data_title, str) problem_cols = [col for col in columns if col not in dataframe.columns] if problem_cols != []: if col_title == '': msg = "{} not in {}.columns" final_msg = msg.format(problem_cols, data_title) else: msg = "The following columns in {} are not in {}.columns: {}" final_msg = msg.format(col_title, data_title, problem_cols) raise ValueError(final_msg) return None
python
def ensure_columns_are_in_dataframe(columns, dataframe, col_title='', data_title='data'): assert isinstance(columns, Iterable) assert isinstance(dataframe, pd.DataFrame) assert isinstance(col_title, str) assert isinstance(data_title, str) problem_cols = [col for col in columns if col not in dataframe.columns] if problem_cols != []: if col_title == '': msg = "{} not in {}.columns" final_msg = msg.format(problem_cols, data_title) else: msg = "The following columns in {} are not in {}.columns: {}" final_msg = msg.format(col_title, data_title, problem_cols) raise ValueError(final_msg) return None
[ "def", "ensure_columns_are_in_dataframe", "(", "columns", ",", "dataframe", ",", "col_title", "=", "''", ",", "data_title", "=", "'data'", ")", ":", "# Make sure columns is an iterable", "assert", "isinstance", "(", "columns", ",", "Iterable", ")", "# Make sure dataframe is a pandas dataframe", "assert", "isinstance", "(", "dataframe", ",", "pd", ".", "DataFrame", ")", "# Make sure title is a string", "assert", "isinstance", "(", "col_title", ",", "str", ")", "assert", "isinstance", "(", "data_title", ",", "str", ")", "problem_cols", "=", "[", "col", "for", "col", "in", "columns", "if", "col", "not", "in", "dataframe", ".", "columns", "]", "if", "problem_cols", "!=", "[", "]", ":", "if", "col_title", "==", "''", ":", "msg", "=", "\"{} not in {}.columns\"", "final_msg", "=", "msg", ".", "format", "(", "problem_cols", ",", "data_title", ")", "else", ":", "msg", "=", "\"The following columns in {} are not in {}.columns: {}\"", "final_msg", "=", "msg", ".", "format", "(", "col_title", ",", "data_title", ",", "problem_cols", ")", "raise", "ValueError", "(", "final_msg", ")", "return", "None" ]
Checks whether each column in `columns` is in `dataframe`. Raises ValueError if any of the columns are not in the dataframe. Parameters ---------- columns : list of strings. Each string should represent a column heading in dataframe. dataframe : pandas DataFrame. Dataframe containing the data for the choice model to be estimated. col_title : str, optional. Denotes the title of the columns that were passed to the function. data_title : str, optional. Denotes the title of the dataframe that is being checked to see whether it contains the passed columns. Default == 'data' Returns ------- None.
[ "Checks", "whether", "each", "column", "in", "columns", "is", "in", "dataframe", ".", "Raises", "ValueError", "if", "any", "of", "the", "columns", "are", "not", "in", "the", "dataframe", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L113-L156
timothyb0912/pylogit
pylogit/choice_tools.py
check_argument_type
def check_argument_type(long_form, specification_dict): """ Ensures that long_form is a pandas dataframe and that specification_dict is an OrderedDict, raising a ValueError otherwise. Parameters ---------- long_form : pandas dataframe. Contains one row for each available alternative, for each observation. specification_dict : OrderedDict. Keys are a proper subset of the columns in `long_form_df`. Values are either a list or a single string, `"all_diff"` or `"all_same"`. If a list, the elements should be: - single objects that are within the alternative ID column of `long_form_df` - lists of objects that are within the alternative ID column of `long_form_df`. For each single object in the list, a unique column will be created (i.e. there will be a unique coefficient for that variable in the corresponding utility equation of the corresponding alternative). For lists within the `specification_dict` values, a single column will be created for all the alternatives within iterable (i.e. there will be one common coefficient for the variables in the iterable). Returns ------- None. """ if not isinstance(long_form, pd.DataFrame): msg = "long_form should be a pandas dataframe. It is a {}" raise TypeError(msg.format(type(long_form))) ensure_object_is_ordered_dict(specification_dict, "specification_dict") return None
python
def check_argument_type(long_form, specification_dict): if not isinstance(long_form, pd.DataFrame): msg = "long_form should be a pandas dataframe. It is a {}" raise TypeError(msg.format(type(long_form))) ensure_object_is_ordered_dict(specification_dict, "specification_dict") return None
[ "def", "check_argument_type", "(", "long_form", ",", "specification_dict", ")", ":", "if", "not", "isinstance", "(", "long_form", ",", "pd", ".", "DataFrame", ")", ":", "msg", "=", "\"long_form should be a pandas dataframe. It is a {}\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "type", "(", "long_form", ")", ")", ")", "ensure_object_is_ordered_dict", "(", "specification_dict", ",", "\"specification_dict\"", ")", "return", "None" ]
Ensures that long_form is a pandas dataframe and that specification_dict is an OrderedDict, raising a ValueError otherwise. Parameters ---------- long_form : pandas dataframe. Contains one row for each available alternative, for each observation. specification_dict : OrderedDict. Keys are a proper subset of the columns in `long_form_df`. Values are either a list or a single string, `"all_diff"` or `"all_same"`. If a list, the elements should be: - single objects that are within the alternative ID column of `long_form_df` - lists of objects that are within the alternative ID column of `long_form_df`. For each single object in the list, a unique column will be created (i.e. there will be a unique coefficient for that variable in the corresponding utility equation of the corresponding alternative). For lists within the `specification_dict` values, a single column will be created for all the alternatives within iterable (i.e. there will be one common coefficient for the variables in the iterable). Returns ------- None.
[ "Ensures", "that", "long_form", "is", "a", "pandas", "dataframe", "and", "that", "specification_dict", "is", "an", "OrderedDict", "raising", "a", "ValueError", "otherwise", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L159-L194
timothyb0912/pylogit
pylogit/choice_tools.py
ensure_alt_id_in_long_form
def ensure_alt_id_in_long_form(alt_id_col, long_form): """ Ensures alt_id_col is in long_form, and raises a ValueError if not. Parameters ---------- alt_id_col : str. Column name which denotes the column in `long_form` that contains the alternative ID for each row in `long_form`. long_form : pandas dataframe. Contains one row for each available alternative, for each observation. Returns ------- None. """ if alt_id_col not in long_form.columns: msg = "alt_id_col == {} is not a column in long_form." raise ValueError(msg.format(alt_id_col)) return None
python
def ensure_alt_id_in_long_form(alt_id_col, long_form): if alt_id_col not in long_form.columns: msg = "alt_id_col == {} is not a column in long_form." raise ValueError(msg.format(alt_id_col)) return None
[ "def", "ensure_alt_id_in_long_form", "(", "alt_id_col", ",", "long_form", ")", ":", "if", "alt_id_col", "not", "in", "long_form", ".", "columns", ":", "msg", "=", "\"alt_id_col == {} is not a column in long_form.\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "alt_id_col", ")", ")", "return", "None" ]
Ensures alt_id_col is in long_form, and raises a ValueError if not. Parameters ---------- alt_id_col : str. Column name which denotes the column in `long_form` that contains the alternative ID for each row in `long_form`. long_form : pandas dataframe. Contains one row for each available alternative, for each observation. Returns ------- None.
[ "Ensures", "alt_id_col", "is", "in", "long_form", "and", "raises", "a", "ValueError", "if", "not", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L197-L217
timothyb0912/pylogit
pylogit/choice_tools.py
ensure_specification_cols_are_in_dataframe
def ensure_specification_cols_are_in_dataframe(specification, dataframe): """ Checks whether each column in `specification` is in `dataframe`. Raises ValueError if any of the columns are not in the dataframe. Parameters ---------- specification : OrderedDict. Keys are a proper subset of the columns in `data`. Values are either a list or a single string, "all_diff" or "all_same". If a list, the elements should be: - single objects that are in the alternative ID column of `data` - lists of objects that are within the alternative ID column of `data`. For each single object in the list, a unique column will be created (i.e. there will be a unique coefficient for that variable in the corresponding utility equation of the corresponding alternative). For lists within the `specification` values, a single column will be created for all the alternatives within the iterable (i.e. there will be one common coefficient for the variables in the iterable). dataframe : pandas DataFrame. Dataframe containing the data for the choice model to be estimated. Returns ------- None. """ # Make sure specification is an OrderedDict try: assert isinstance(specification, OrderedDict) except AssertionError: raise TypeError("`specification` must be an OrderedDict.") # Make sure dataframe is a pandas dataframe assert isinstance(dataframe, pd.DataFrame) problem_cols = [] dataframe_cols = dataframe.columns for key in specification: if key not in dataframe_cols: problem_cols.append(key) if problem_cols != []: msg = "The following keys in the specification are not in 'data':\n{}" raise ValueError(msg.format(problem_cols)) return None
python
def ensure_specification_cols_are_in_dataframe(specification, dataframe): try: assert isinstance(specification, OrderedDict) except AssertionError: raise TypeError("`specification` must be an OrderedDict.") assert isinstance(dataframe, pd.DataFrame) problem_cols = [] dataframe_cols = dataframe.columns for key in specification: if key not in dataframe_cols: problem_cols.append(key) if problem_cols != []: msg = "The following keys in the specification are not in 'data':\n{}" raise ValueError(msg.format(problem_cols)) return None
[ "def", "ensure_specification_cols_are_in_dataframe", "(", "specification", ",", "dataframe", ")", ":", "# Make sure specification is an OrderedDict", "try", ":", "assert", "isinstance", "(", "specification", ",", "OrderedDict", ")", "except", "AssertionError", ":", "raise", "TypeError", "(", "\"`specification` must be an OrderedDict.\"", ")", "# Make sure dataframe is a pandas dataframe", "assert", "isinstance", "(", "dataframe", ",", "pd", ".", "DataFrame", ")", "problem_cols", "=", "[", "]", "dataframe_cols", "=", "dataframe", ".", "columns", "for", "key", "in", "specification", ":", "if", "key", "not", "in", "dataframe_cols", ":", "problem_cols", ".", "append", "(", "key", ")", "if", "problem_cols", "!=", "[", "]", ":", "msg", "=", "\"The following keys in the specification are not in 'data':\\n{}\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "problem_cols", ")", ")", "return", "None" ]
Checks whether each column in `specification` is in `dataframe`. Raises ValueError if any of the columns are not in the dataframe. Parameters ---------- specification : OrderedDict. Keys are a proper subset of the columns in `data`. Values are either a list or a single string, "all_diff" or "all_same". If a list, the elements should be: - single objects that are in the alternative ID column of `data` - lists of objects that are within the alternative ID column of `data`. For each single object in the list, a unique column will be created (i.e. there will be a unique coefficient for that variable in the corresponding utility equation of the corresponding alternative). For lists within the `specification` values, a single column will be created for all the alternatives within the iterable (i.e. there will be one common coefficient for the variables in the iterable). dataframe : pandas DataFrame. Dataframe containing the data for the choice model to be estimated. Returns ------- None.
[ "Checks", "whether", "each", "column", "in", "specification", "is", "in", "dataframe", ".", "Raises", "ValueError", "if", "any", "of", "the", "columns", "are", "not", "in", "the", "dataframe", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L220-L264
timothyb0912/pylogit
pylogit/choice_tools.py
check_type_and_values_of_specification_dict
def check_type_and_values_of_specification_dict(specification_dict, unique_alternatives): """ Verifies that the values of specification_dict have the correct type, have the correct structure, and have valid values (i.e. are actually in the set of possible alternatives). Will raise various errors if / when appropriate. Parameters ---------- specification_dict : OrderedDict. Keys are a proper subset of the columns in `long_form_df`. Values are either a list or a single string, `"all_diff"` or `"all_same"`. If a list, the elements should be: - single objects that are within the alternative ID column of `long_form_df` - lists of objects that are within the alternative ID column of `long_form_df`. For each single object in the list, a unique column will be created (i.e. there will be a unique coefficient for that variable in the corresponding utility equation of the corresponding alternative). For lists within the `specification_dict` values, a single column will be created for all the alternatives within iterable (i.e. there will be one common coefficient for the variables in the iterable). unique_alternatives : 1D ndarray. Should contain the possible alternative id's for this dataset. Returns ------- None. """ for key in specification_dict: specification = specification_dict[key] if isinstance(specification, str): if specification not in ["all_same", "all_diff"]: msg = "specification_dict[{}] not in ['all_same', 'all_diff']" raise ValueError(msg.format(key)) elif isinstance(specification, list): # Imagine that the specification is [[1, 2], 3] # group would be [1, 2] # group_item would be 1 or 2. group_item should never be a list. for group in specification: group_is_list = isinstance(group, list) if group_is_list: for group_item in group: if isinstance(group_item, list): msg = "Wrong structure for specification_dict[{}]" msg_2 = " Values can be a list of lists of ints," msg_3 = " not lists of lists of lists of ints." total_msg = msg.format(key) + msg_2 + msg_3 raise ValueError(total_msg) elif group_item not in unique_alternatives: msg_1 = "{} in {} in specification_dict[{}]" msg_2 = " is not in long_format[alt_id_col]" total_msg = (msg_1.format(group_item, group, key) + msg_2) raise ValueError(total_msg) else: if group not in unique_alternatives: msg_1 = "{} in specification_dict[{}]" msg_2 = " is not in long_format[alt_id_col]" raise ValueError(msg_1.format(group, key) + msg_2) else: msg = "specification_dict[{}] must be 'all_same', 'all_diff', or" msg_2 = " a list." raise TypeError(msg.format(key) + msg_2) return None
python
def check_type_and_values_of_specification_dict(specification_dict, unique_alternatives): for key in specification_dict: specification = specification_dict[key] if isinstance(specification, str): if specification not in ["all_same", "all_diff"]: msg = "specification_dict[{}] not in ['all_same', 'all_diff']" raise ValueError(msg.format(key)) elif isinstance(specification, list): for group in specification: group_is_list = isinstance(group, list) if group_is_list: for group_item in group: if isinstance(group_item, list): msg = "Wrong structure for specification_dict[{}]" msg_2 = " Values can be a list of lists of ints," msg_3 = " not lists of lists of lists of ints." total_msg = msg.format(key) + msg_2 + msg_3 raise ValueError(total_msg) elif group_item not in unique_alternatives: msg_1 = "{} in {} in specification_dict[{}]" msg_2 = " is not in long_format[alt_id_col]" total_msg = (msg_1.format(group_item, group, key) + msg_2) raise ValueError(total_msg) else: if group not in unique_alternatives: msg_1 = "{} in specification_dict[{}]" msg_2 = " is not in long_format[alt_id_col]" raise ValueError(msg_1.format(group, key) + msg_2) else: msg = "specification_dict[{}] must be 'all_same', 'all_diff', or" msg_2 = " a list." raise TypeError(msg.format(key) + msg_2) return None
[ "def", "check_type_and_values_of_specification_dict", "(", "specification_dict", ",", "unique_alternatives", ")", ":", "for", "key", "in", "specification_dict", ":", "specification", "=", "specification_dict", "[", "key", "]", "if", "isinstance", "(", "specification", ",", "str", ")", ":", "if", "specification", "not", "in", "[", "\"all_same\"", ",", "\"all_diff\"", "]", ":", "msg", "=", "\"specification_dict[{}] not in ['all_same', 'all_diff']\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "key", ")", ")", "elif", "isinstance", "(", "specification", ",", "list", ")", ":", "# Imagine that the specification is [[1, 2], 3]", "# group would be [1, 2]", "# group_item would be 1 or 2. group_item should never be a list.", "for", "group", "in", "specification", ":", "group_is_list", "=", "isinstance", "(", "group", ",", "list", ")", "if", "group_is_list", ":", "for", "group_item", "in", "group", ":", "if", "isinstance", "(", "group_item", ",", "list", ")", ":", "msg", "=", "\"Wrong structure for specification_dict[{}]\"", "msg_2", "=", "\" Values can be a list of lists of ints,\"", "msg_3", "=", "\" not lists of lists of lists of ints.\"", "total_msg", "=", "msg", ".", "format", "(", "key", ")", "+", "msg_2", "+", "msg_3", "raise", "ValueError", "(", "total_msg", ")", "elif", "group_item", "not", "in", "unique_alternatives", ":", "msg_1", "=", "\"{} in {} in specification_dict[{}]\"", "msg_2", "=", "\" is not in long_format[alt_id_col]\"", "total_msg", "=", "(", "msg_1", ".", "format", "(", "group_item", ",", "group", ",", "key", ")", "+", "msg_2", ")", "raise", "ValueError", "(", "total_msg", ")", "else", ":", "if", "group", "not", "in", "unique_alternatives", ":", "msg_1", "=", "\"{} in specification_dict[{}]\"", "msg_2", "=", "\" is not in long_format[alt_id_col]\"", "raise", "ValueError", "(", "msg_1", ".", "format", "(", "group", ",", "key", ")", "+", "msg_2", ")", "else", ":", "msg", "=", "\"specification_dict[{}] must be 'all_same', 'all_diff', or\"", "msg_2", "=", "\" a list.\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "key", ")", "+", "msg_2", ")", "return", "None" ]
Verifies that the values of specification_dict have the correct type, have the correct structure, and have valid values (i.e. are actually in the set of possible alternatives). Will raise various errors if / when appropriate. Parameters ---------- specification_dict : OrderedDict. Keys are a proper subset of the columns in `long_form_df`. Values are either a list or a single string, `"all_diff"` or `"all_same"`. If a list, the elements should be: - single objects that are within the alternative ID column of `long_form_df` - lists of objects that are within the alternative ID column of `long_form_df`. For each single object in the list, a unique column will be created (i.e. there will be a unique coefficient for that variable in the corresponding utility equation of the corresponding alternative). For lists within the `specification_dict` values, a single column will be created for all the alternatives within iterable (i.e. there will be one common coefficient for the variables in the iterable). unique_alternatives : 1D ndarray. Should contain the possible alternative id's for this dataset. Returns ------- None.
[ "Verifies", "that", "the", "values", "of", "specification_dict", "have", "the", "correct", "type", "have", "the", "correct", "structure", "and", "have", "valid", "values", "(", "i", ".", "e", ".", "are", "actually", "in", "the", "set", "of", "possible", "alternatives", ")", ".", "Will", "raise", "various", "errors", "if", "/", "when", "appropriate", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L267-L337
timothyb0912/pylogit
pylogit/choice_tools.py
check_keys_and_values_of_name_dictionary
def check_keys_and_values_of_name_dictionary(names, specification_dict, num_alts): """ Check the validity of the keys and values in the names dictionary. Parameters ---------- names : OrderedDict, optional. Should have the same keys as `specification_dict`. For each key: - if the corresponding value in `specification_dict` is "all_same", then there should be a single string as the value in names. - if the corresponding value in `specification_dict` is "all_diff", then there should be a list of strings as the value in names. There should be one string in the value in names for each possible alternative. - if the corresponding value in `specification_dict` is a list, then there should be a list of strings as the value in names. There should be one string the value in names per item in the value in `specification_dict`. specification_dict : OrderedDict. Keys are a proper subset of the columns in `long_form_df`. Values are either a list or a single string, `"all_diff"` or `"all_same"`. If a list, the elements should be: - single objects that are within the alternative ID column of `long_form_df` - lists of objects that are within the alternative ID column of `long_form_df`. For each single object in the list, a unique column will be created (i.e. there will be a unique coefficient for that variable in the corresponding utility equation of the corresponding alternative). For lists within the `specification_dict` values, a single column will be created for all the alternatives within iterable (i.e. there will be one common coefficient for the variables in the iterable). num_alts : int. The number of alternatives in this dataset's universal choice set. Returns ------- None. """ if names.keys() != specification_dict.keys(): msg = "names.keys() does not equal specification_dict.keys()" raise ValueError(msg) for key in names: specification = specification_dict[key] name_object = names[key] if isinstance(specification, list): try: assert isinstance(name_object, list) assert len(name_object) == len(specification) assert all([isinstance(x, str) for x in name_object]) except AssertionError: msg = "names[{}] must be a list AND it must have the same" msg_2 = " number of strings as there are elements of the" msg_3 = " corresponding list in specification_dict" raise ValueError(msg.format(key) + msg_2 + msg_3) else: if specification == "all_same": if not isinstance(name_object, str): msg = "names[{}] should be a string".format(key) raise TypeError(msg) else: # This means speciffication == 'all_diff' try: assert isinstance(name_object, list) assert len(name_object) == num_alts except AssertionError: msg_1 = "names[{}] should be a list with {} elements," msg_2 = " 1 element for each possible alternative" msg = (msg_1.format(key, num_alts) + msg_2) raise ValueError(msg) return None
python
def check_keys_and_values_of_name_dictionary(names, specification_dict, num_alts): if names.keys() != specification_dict.keys(): msg = "names.keys() does not equal specification_dict.keys()" raise ValueError(msg) for key in names: specification = specification_dict[key] name_object = names[key] if isinstance(specification, list): try: assert isinstance(name_object, list) assert len(name_object) == len(specification) assert all([isinstance(x, str) for x in name_object]) except AssertionError: msg = "names[{}] must be a list AND it must have the same" msg_2 = " number of strings as there are elements of the" msg_3 = " corresponding list in specification_dict" raise ValueError(msg.format(key) + msg_2 + msg_3) else: if specification == "all_same": if not isinstance(name_object, str): msg = "names[{}] should be a string".format(key) raise TypeError(msg) else: try: assert isinstance(name_object, list) assert len(name_object) == num_alts except AssertionError: msg_1 = "names[{}] should be a list with {} elements," msg_2 = " 1 element for each possible alternative" msg = (msg_1.format(key, num_alts) + msg_2) raise ValueError(msg) return None
[ "def", "check_keys_and_values_of_name_dictionary", "(", "names", ",", "specification_dict", ",", "num_alts", ")", ":", "if", "names", ".", "keys", "(", ")", "!=", "specification_dict", ".", "keys", "(", ")", ":", "msg", "=", "\"names.keys() does not equal specification_dict.keys()\"", "raise", "ValueError", "(", "msg", ")", "for", "key", "in", "names", ":", "specification", "=", "specification_dict", "[", "key", "]", "name_object", "=", "names", "[", "key", "]", "if", "isinstance", "(", "specification", ",", "list", ")", ":", "try", ":", "assert", "isinstance", "(", "name_object", ",", "list", ")", "assert", "len", "(", "name_object", ")", "==", "len", "(", "specification", ")", "assert", "all", "(", "[", "isinstance", "(", "x", ",", "str", ")", "for", "x", "in", "name_object", "]", ")", "except", "AssertionError", ":", "msg", "=", "\"names[{}] must be a list AND it must have the same\"", "msg_2", "=", "\" number of strings as there are elements of the\"", "msg_3", "=", "\" corresponding list in specification_dict\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "key", ")", "+", "msg_2", "+", "msg_3", ")", "else", ":", "if", "specification", "==", "\"all_same\"", ":", "if", "not", "isinstance", "(", "name_object", ",", "str", ")", ":", "msg", "=", "\"names[{}] should be a string\"", ".", "format", "(", "key", ")", "raise", "TypeError", "(", "msg", ")", "else", ":", "# This means speciffication == 'all_diff'", "try", ":", "assert", "isinstance", "(", "name_object", ",", "list", ")", "assert", "len", "(", "name_object", ")", "==", "num_alts", "except", "AssertionError", ":", "msg_1", "=", "\"names[{}] should be a list with {} elements,\"", "msg_2", "=", "\" 1 element for each possible alternative\"", "msg", "=", "(", "msg_1", ".", "format", "(", "key", ",", "num_alts", ")", "+", "msg_2", ")", "raise", "ValueError", "(", "msg", ")", "return", "None" ]
Check the validity of the keys and values in the names dictionary. Parameters ---------- names : OrderedDict, optional. Should have the same keys as `specification_dict`. For each key: - if the corresponding value in `specification_dict` is "all_same", then there should be a single string as the value in names. - if the corresponding value in `specification_dict` is "all_diff", then there should be a list of strings as the value in names. There should be one string in the value in names for each possible alternative. - if the corresponding value in `specification_dict` is a list, then there should be a list of strings as the value in names. There should be one string the value in names per item in the value in `specification_dict`. specification_dict : OrderedDict. Keys are a proper subset of the columns in `long_form_df`. Values are either a list or a single string, `"all_diff"` or `"all_same"`. If a list, the elements should be: - single objects that are within the alternative ID column of `long_form_df` - lists of objects that are within the alternative ID column of `long_form_df`. For each single object in the list, a unique column will be created (i.e. there will be a unique coefficient for that variable in the corresponding utility equation of the corresponding alternative). For lists within the `specification_dict` values, a single column will be created for all the alternatives within iterable (i.e. there will be one common coefficient for the variables in the iterable). num_alts : int. The number of alternatives in this dataset's universal choice set. Returns ------- None.
[ "Check", "the", "validity", "of", "the", "keys", "and", "values", "in", "the", "names", "dictionary", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L340-L417
timothyb0912/pylogit
pylogit/choice_tools.py
ensure_all_columns_are_used
def ensure_all_columns_are_used(num_vars_accounted_for, dataframe, data_title='long_data'): """ Ensure that all of the columns from dataframe are in the list of used_cols. Will raise a helpful UserWarning if otherwise. Parameters ---------- num_vars_accounted_for : int. Denotes the number of variables used in one's function. dataframe : pandas dataframe. Contains all of the data to be converted from one format to another. data_title : str, optional. Denotes the title by which `dataframe` should be referred in the UserWarning. Returns ------- None. """ dataframe_vars = set(dataframe.columns.tolist()) num_dataframe_vars = len(dataframe_vars) if num_vars_accounted_for == num_dataframe_vars: pass elif num_vars_accounted_for < num_dataframe_vars: msg = "Note, there are {:,} variables in {} but the inputs" msg_2 = " ind_vars, alt_specific_vars, and subset_specific_vars only" msg_3 = " account for {:,} variables." warnings.warn(msg.format(num_dataframe_vars, data_title) + msg_2 + msg_3.format(num_vars_accounted_for)) else: # This means num_vars_accounted_for > num_dataframe_vars msg = "There are more variable specified in ind_vars, " msg_2 = "alt_specific_vars, and subset_specific_vars ({:,}) than there" msg_3 = " are variables in {} ({:,})" warnings.warn(msg + msg_2.format(num_vars_accounted_for) + msg_3.format(data_title, num_dataframe_vars)) return None
python
def ensure_all_columns_are_used(num_vars_accounted_for, dataframe, data_title='long_data'): dataframe_vars = set(dataframe.columns.tolist()) num_dataframe_vars = len(dataframe_vars) if num_vars_accounted_for == num_dataframe_vars: pass elif num_vars_accounted_for < num_dataframe_vars: msg = "Note, there are {:,} variables in {} but the inputs" msg_2 = " ind_vars, alt_specific_vars, and subset_specific_vars only" msg_3 = " account for {:,} variables." warnings.warn(msg.format(num_dataframe_vars, data_title) + msg_2 + msg_3.format(num_vars_accounted_for)) else: msg = "There are more variable specified in ind_vars, " msg_2 = "alt_specific_vars, and subset_specific_vars ({:,}) than there" msg_3 = " are variables in {} ({:,})" warnings.warn(msg + msg_2.format(num_vars_accounted_for) + msg_3.format(data_title, num_dataframe_vars)) return None
[ "def", "ensure_all_columns_are_used", "(", "num_vars_accounted_for", ",", "dataframe", ",", "data_title", "=", "'long_data'", ")", ":", "dataframe_vars", "=", "set", "(", "dataframe", ".", "columns", ".", "tolist", "(", ")", ")", "num_dataframe_vars", "=", "len", "(", "dataframe_vars", ")", "if", "num_vars_accounted_for", "==", "num_dataframe_vars", ":", "pass", "elif", "num_vars_accounted_for", "<", "num_dataframe_vars", ":", "msg", "=", "\"Note, there are {:,} variables in {} but the inputs\"", "msg_2", "=", "\" ind_vars, alt_specific_vars, and subset_specific_vars only\"", "msg_3", "=", "\" account for {:,} variables.\"", "warnings", ".", "warn", "(", "msg", ".", "format", "(", "num_dataframe_vars", ",", "data_title", ")", "+", "msg_2", "+", "msg_3", ".", "format", "(", "num_vars_accounted_for", ")", ")", "else", ":", "# This means num_vars_accounted_for > num_dataframe_vars", "msg", "=", "\"There are more variable specified in ind_vars, \"", "msg_2", "=", "\"alt_specific_vars, and subset_specific_vars ({:,}) than there\"", "msg_3", "=", "\" are variables in {} ({:,})\"", "warnings", ".", "warn", "(", "msg", "+", "msg_2", ".", "format", "(", "num_vars_accounted_for", ")", "+", "msg_3", ".", "format", "(", "data_title", ",", "num_dataframe_vars", ")", ")", "return", "None" ]
Ensure that all of the columns from dataframe are in the list of used_cols. Will raise a helpful UserWarning if otherwise. Parameters ---------- num_vars_accounted_for : int. Denotes the number of variables used in one's function. dataframe : pandas dataframe. Contains all of the data to be converted from one format to another. data_title : str, optional. Denotes the title by which `dataframe` should be referred in the UserWarning. Returns ------- None.
[ "Ensure", "that", "all", "of", "the", "columns", "from", "dataframe", "are", "in", "the", "list", "of", "used_cols", ".", "Will", "raise", "a", "helpful", "UserWarning", "if", "otherwise", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L420-L463
timothyb0912/pylogit
pylogit/choice_tools.py
check_dataframe_for_duplicate_records
def check_dataframe_for_duplicate_records(obs_id_col, alt_id_col, df): """ Checks a cross-sectional dataframe of long-format data for duplicate observations. Duplicate observations are defined as rows with the same observation id value and the same alternative id value. Parameters ---------- obs_id_col : str. Denotes the column in `df` that contains the observation ID values for each row. alt_id_col : str. Denotes the column in `df` that contains the alternative ID values for each row. df : pandas dataframe. The dataframe of long format data that is to be checked for duplicates. Returns ------- None. """ if df.duplicated(subset=[obs_id_col, alt_id_col]).any(): msg = "One or more observation-alternative_id pairs is not unique." raise ValueError(msg) return None
python
def check_dataframe_for_duplicate_records(obs_id_col, alt_id_col, df): if df.duplicated(subset=[obs_id_col, alt_id_col]).any(): msg = "One or more observation-alternative_id pairs is not unique." raise ValueError(msg) return None
[ "def", "check_dataframe_for_duplicate_records", "(", "obs_id_col", ",", "alt_id_col", ",", "df", ")", ":", "if", "df", ".", "duplicated", "(", "subset", "=", "[", "obs_id_col", ",", "alt_id_col", "]", ")", ".", "any", "(", ")", ":", "msg", "=", "\"One or more observation-alternative_id pairs is not unique.\"", "raise", "ValueError", "(", "msg", ")", "return", "None" ]
Checks a cross-sectional dataframe of long-format data for duplicate observations. Duplicate observations are defined as rows with the same observation id value and the same alternative id value. Parameters ---------- obs_id_col : str. Denotes the column in `df` that contains the observation ID values for each row. alt_id_col : str. Denotes the column in `df` that contains the alternative ID values for each row. df : pandas dataframe. The dataframe of long format data that is to be checked for duplicates. Returns ------- None.
[ "Checks", "a", "cross", "-", "sectional", "dataframe", "of", "long", "-", "format", "data", "for", "duplicate", "observations", ".", "Duplicate", "observations", "are", "defined", "as", "rows", "with", "the", "same", "observation", "id", "value", "and", "the", "same", "alternative", "id", "value", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L466-L491
timothyb0912/pylogit
pylogit/choice_tools.py
ensure_num_chosen_alts_equals_num_obs
def ensure_num_chosen_alts_equals_num_obs(obs_id_col, choice_col, df): """ Checks that the total number of recorded choices equals the total number of observations. If this is not the case, raise helpful ValueError messages. Parameters ---------- obs_id_col : str. Denotes the column in `df` that contains the observation ID values for each row. choice_col : str. Denotes the column in `long_data` that contains a one if the alternative pertaining to the given row was the observed outcome for the observation pertaining to the given row and a zero otherwise. df : pandas dataframe. The dataframe whose choices and observations will be checked. Returns ------- None. """ num_obs = df[obs_id_col].unique().shape[0] num_choices = df[choice_col].sum() if num_choices < num_obs: msg = "One or more observations have not chosen one " msg_2 = "of the alternatives available to him/her" raise ValueError(msg + msg_2) if num_choices > num_obs: msg = "One or more observations has chosen multiple alternatives" raise ValueError(msg) return None
python
def ensure_num_chosen_alts_equals_num_obs(obs_id_col, choice_col, df): num_obs = df[obs_id_col].unique().shape[0] num_choices = df[choice_col].sum() if num_choices < num_obs: msg = "One or more observations have not chosen one " msg_2 = "of the alternatives available to him/her" raise ValueError(msg + msg_2) if num_choices > num_obs: msg = "One or more observations has chosen multiple alternatives" raise ValueError(msg) return None
[ "def", "ensure_num_chosen_alts_equals_num_obs", "(", "obs_id_col", ",", "choice_col", ",", "df", ")", ":", "num_obs", "=", "df", "[", "obs_id_col", "]", ".", "unique", "(", ")", ".", "shape", "[", "0", "]", "num_choices", "=", "df", "[", "choice_col", "]", ".", "sum", "(", ")", "if", "num_choices", "<", "num_obs", ":", "msg", "=", "\"One or more observations have not chosen one \"", "msg_2", "=", "\"of the alternatives available to him/her\"", "raise", "ValueError", "(", "msg", "+", "msg_2", ")", "if", "num_choices", ">", "num_obs", ":", "msg", "=", "\"One or more observations has chosen multiple alternatives\"", "raise", "ValueError", "(", "msg", ")", "return", "None" ]
Checks that the total number of recorded choices equals the total number of observations. If this is not the case, raise helpful ValueError messages. Parameters ---------- obs_id_col : str. Denotes the column in `df` that contains the observation ID values for each row. choice_col : str. Denotes the column in `long_data` that contains a one if the alternative pertaining to the given row was the observed outcome for the observation pertaining to the given row and a zero otherwise. df : pandas dataframe. The dataframe whose choices and observations will be checked. Returns ------- None.
[ "Checks", "that", "the", "total", "number", "of", "recorded", "choices", "equals", "the", "total", "number", "of", "observations", ".", "If", "this", "is", "not", "the", "case", "raise", "helpful", "ValueError", "messages", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L494-L526
timothyb0912/pylogit
pylogit/choice_tools.py
check_type_and_values_of_alt_name_dict
def check_type_and_values_of_alt_name_dict(alt_name_dict, alt_id_col, df): """ Ensures that `alt_name_dict` is a dictionary and that its keys are in the alternative id column of `df`. Raises helpful errors if either condition is not met. Parameters ---------- alt_name_dict : dict. A dictionary whose keys are the possible values in `df[alt_id_col].unique()`. The values should be the name that one wants to associate with each alternative id. alt_id_col : str. Denotes the column in `df` that contains the alternative ID values for each row. df : pandas dataframe. The dataframe of long format data that contains the alternative IDs. Returns ------- None. """ if not isinstance(alt_name_dict, dict): msg = "alt_name_dict should be a dictionary. Passed value was a {}" raise TypeError(msg.format(type(alt_name_dict))) if not all([x in df[alt_id_col].values for x in alt_name_dict.keys()]): msg = "One or more of alt_name_dict's keys are not " msg_2 = "in long_data[alt_id_col]" raise ValueError(msg + msg_2) return None
python
def check_type_and_values_of_alt_name_dict(alt_name_dict, alt_id_col, df): if not isinstance(alt_name_dict, dict): msg = "alt_name_dict should be a dictionary. Passed value was a {}" raise TypeError(msg.format(type(alt_name_dict))) if not all([x in df[alt_id_col].values for x in alt_name_dict.keys()]): msg = "One or more of alt_name_dict's keys are not " msg_2 = "in long_data[alt_id_col]" raise ValueError(msg + msg_2) return None
[ "def", "check_type_and_values_of_alt_name_dict", "(", "alt_name_dict", ",", "alt_id_col", ",", "df", ")", ":", "if", "not", "isinstance", "(", "alt_name_dict", ",", "dict", ")", ":", "msg", "=", "\"alt_name_dict should be a dictionary. Passed value was a {}\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "type", "(", "alt_name_dict", ")", ")", ")", "if", "not", "all", "(", "[", "x", "in", "df", "[", "alt_id_col", "]", ".", "values", "for", "x", "in", "alt_name_dict", ".", "keys", "(", ")", "]", ")", ":", "msg", "=", "\"One or more of alt_name_dict's keys are not \"", "msg_2", "=", "\"in long_data[alt_id_col]\"", "raise", "ValueError", "(", "msg", "+", "msg_2", ")", "return", "None" ]
Ensures that `alt_name_dict` is a dictionary and that its keys are in the alternative id column of `df`. Raises helpful errors if either condition is not met. Parameters ---------- alt_name_dict : dict. A dictionary whose keys are the possible values in `df[alt_id_col].unique()`. The values should be the name that one wants to associate with each alternative id. alt_id_col : str. Denotes the column in `df` that contains the alternative ID values for each row. df : pandas dataframe. The dataframe of long format data that contains the alternative IDs. Returns ------- None.
[ "Ensures", "that", "alt_name_dict", "is", "a", "dictionary", "and", "that", "its", "keys", "are", "in", "the", "alternative", "id", "column", "of", "df", ".", "Raises", "helpful", "errors", "if", "either", "condition", "is", "not", "met", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L529-L560
timothyb0912/pylogit
pylogit/choice_tools.py
ensure_ridge_is_scalar_or_none
def ensure_ridge_is_scalar_or_none(ridge): """ Ensures that `ridge` is either None or a scalar value. Raises a helpful TypeError otherwise. Parameters ---------- ridge : int, float, long, or None. Scalar value or None, determining the L2-ridge regression penalty. Returns ------- None. """ if (ridge is not None) and not isinstance(ridge, Number): msg_1 = "ridge should be None or an int, float, or long." msg_2 = "The passed value of ridge had type: {}".format(type(ridge)) raise TypeError(msg_1 + msg_2) return None
python
def ensure_ridge_is_scalar_or_none(ridge): if (ridge is not None) and not isinstance(ridge, Number): msg_1 = "ridge should be None or an int, float, or long." msg_2 = "The passed value of ridge had type: {}".format(type(ridge)) raise TypeError(msg_1 + msg_2) return None
[ "def", "ensure_ridge_is_scalar_or_none", "(", "ridge", ")", ":", "if", "(", "ridge", "is", "not", "None", ")", "and", "not", "isinstance", "(", "ridge", ",", "Number", ")", ":", "msg_1", "=", "\"ridge should be None or an int, float, or long.\"", "msg_2", "=", "\"The passed value of ridge had type: {}\"", ".", "format", "(", "type", "(", "ridge", ")", ")", "raise", "TypeError", "(", "msg_1", "+", "msg_2", ")", "return", "None" ]
Ensures that `ridge` is either None or a scalar value. Raises a helpful TypeError otherwise. Parameters ---------- ridge : int, float, long, or None. Scalar value or None, determining the L2-ridge regression penalty. Returns ------- None.
[ "Ensures", "that", "ridge", "is", "either", "None", "or", "a", "scalar", "value", ".", "Raises", "a", "helpful", "TypeError", "otherwise", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L563-L582
timothyb0912/pylogit
pylogit/choice_tools.py
create_design_matrix
def create_design_matrix(long_form, specification_dict, alt_id_col, names=None): """ Parameters ---------- long_form : pandas dataframe. Contains one row for each available alternative, for each observation. specification_dict : OrderedDict. Keys are a proper subset of the columns in `long_form_df`. Values are either a list or a single string, `"all_diff"` or `"all_same"`. If a list, the elements should be: - single objects that are within the alternative ID column of `long_form_df` - lists of objects that are within the alternative ID column of `long_form_df`. For each single object in the list, a unique column will be created (i.e. there will be a unique coefficient for that variable in the corresponding utility equation of the corresponding alternative). For lists within the `specification_dict` values, a single column will be created for all the alternatives within iterable (i.e. there will be one common coefficient for the variables in the iterable). alt_id_col : str. Column name which denotes the column in `long_form` that contains the alternative ID for each row in `long_form`. names : OrderedDict, optional. Should have the same keys as `specification_dict`. For each key: - if the corresponding value in `specification_dict` is "all_same", then there should be a single string as the value in names. - if the corresponding value in `specification_dict` is "all_diff", then there should be a list of strings as the value in names. There should be one string in the value in names for each possible alternative. - if the corresponding value in `specification_dict` is a list, then there should be a list of strings as the value in names. There should be one string the value in names per item in the value in `specification_dict`. Default == None. Returns ------- design_matrix, var_names: tuple with two elements. First element is the design matrix, a numpy array with some number of columns and as many rows as are in `long_form`. Each column corresponds to a coefficient to be estimated. The second element is a list of strings denoting the names of each coefficient, with one variable name per column in the design matrix. """ ########## # Check that the arguments meet this functions assumptions. # Fail gracefully if the arguments do not meet the function's requirements. ######### check_argument_type(long_form, specification_dict) ensure_alt_id_in_long_form(alt_id_col, long_form) ensure_specification_cols_are_in_dataframe(specification_dict, long_form) # Find out what and how many possible alternatives there are unique_alternatives = np.sort(long_form[alt_id_col].unique()) num_alternatives = len(unique_alternatives) check_type_and_values_of_specification_dict(specification_dict, unique_alternatives) # Check the user passed dictionary of names if the user passed such a list if names is not None: ensure_object_is_ordered_dict(names, "names") check_keys_and_values_of_name_dictionary(names, specification_dict, num_alternatives) ########## # Actually create the design matrix ########## # Create a list of the columns of independent variables independent_vars = [] # Create a list of variable names var_names = [] # Create the columns of the design matrix based on the specification dict. for variable in specification_dict: specification = specification_dict[variable] if specification == "all_same": # Create the variable column independent_vars.append(long_form[variable].values) # Create the column name var_names.append(variable) elif specification == "all_diff": for alt in unique_alternatives: # Create the variable column independent_vars.append((long_form[alt_id_col] == alt).values * long_form[variable].values) # create the column name var_names.append("{}_{}".format(variable, alt)) else: for group in specification: if isinstance(group, list): # Create the variable column independent_vars.append( long_form[alt_id_col].isin(group).values * long_form[variable].values) # Create the column name var_names.append("{}_{}".format(variable, str(group))) else: # the group is an integer # Create the variable column new_col_vals = ((long_form[alt_id_col] == group).values * long_form[variable].values) independent_vars.append(new_col_vals) # Create the column name var_names.append("{}_{}".format(variable, group)) # Create the final design matrix design_matrix = np.hstack((x[:, None] for x in independent_vars)) # Use the list of names passed by the user, if the user passed such a list if names is not None: var_names = [] for value in names.values(): if isinstance(value, str): var_names.append(value) else: for inner_name in value: var_names.append(inner_name) return design_matrix, var_names
python
def create_design_matrix(long_form, specification_dict, alt_id_col, names=None): check_argument_type(long_form, specification_dict) ensure_alt_id_in_long_form(alt_id_col, long_form) ensure_specification_cols_are_in_dataframe(specification_dict, long_form) unique_alternatives = np.sort(long_form[alt_id_col].unique()) num_alternatives = len(unique_alternatives) check_type_and_values_of_specification_dict(specification_dict, unique_alternatives) if names is not None: ensure_object_is_ordered_dict(names, "names") check_keys_and_values_of_name_dictionary(names, specification_dict, num_alternatives) independent_vars = [] var_names = [] for variable in specification_dict: specification = specification_dict[variable] if specification == "all_same": independent_vars.append(long_form[variable].values) var_names.append(variable) elif specification == "all_diff": for alt in unique_alternatives: independent_vars.append((long_form[alt_id_col] == alt).values * long_form[variable].values) var_names.append("{}_{}".format(variable, alt)) else: for group in specification: if isinstance(group, list): independent_vars.append( long_form[alt_id_col].isin(group).values * long_form[variable].values) var_names.append("{}_{}".format(variable, str(group))) else: new_col_vals = ((long_form[alt_id_col] == group).values * long_form[variable].values) independent_vars.append(new_col_vals) var_names.append("{}_{}".format(variable, group)) design_matrix = np.hstack((x[:, None] for x in independent_vars)) if names is not None: var_names = [] for value in names.values(): if isinstance(value, str): var_names.append(value) else: for inner_name in value: var_names.append(inner_name) return design_matrix, var_names
[ "def", "create_design_matrix", "(", "long_form", ",", "specification_dict", ",", "alt_id_col", ",", "names", "=", "None", ")", ":", "##########", "# Check that the arguments meet this functions assumptions.", "# Fail gracefully if the arguments do not meet the function's requirements.", "#########", "check_argument_type", "(", "long_form", ",", "specification_dict", ")", "ensure_alt_id_in_long_form", "(", "alt_id_col", ",", "long_form", ")", "ensure_specification_cols_are_in_dataframe", "(", "specification_dict", ",", "long_form", ")", "# Find out what and how many possible alternatives there are", "unique_alternatives", "=", "np", ".", "sort", "(", "long_form", "[", "alt_id_col", "]", ".", "unique", "(", ")", ")", "num_alternatives", "=", "len", "(", "unique_alternatives", ")", "check_type_and_values_of_specification_dict", "(", "specification_dict", ",", "unique_alternatives", ")", "# Check the user passed dictionary of names if the user passed such a list", "if", "names", "is", "not", "None", ":", "ensure_object_is_ordered_dict", "(", "names", ",", "\"names\"", ")", "check_keys_and_values_of_name_dictionary", "(", "names", ",", "specification_dict", ",", "num_alternatives", ")", "##########", "# Actually create the design matrix", "##########", "# Create a list of the columns of independent variables", "independent_vars", "=", "[", "]", "# Create a list of variable names", "var_names", "=", "[", "]", "# Create the columns of the design matrix based on the specification dict.", "for", "variable", "in", "specification_dict", ":", "specification", "=", "specification_dict", "[", "variable", "]", "if", "specification", "==", "\"all_same\"", ":", "# Create the variable column", "independent_vars", ".", "append", "(", "long_form", "[", "variable", "]", ".", "values", ")", "# Create the column name", "var_names", ".", "append", "(", "variable", ")", "elif", "specification", "==", "\"all_diff\"", ":", "for", "alt", "in", "unique_alternatives", ":", "# Create the variable column", "independent_vars", ".", "append", "(", "(", "long_form", "[", "alt_id_col", "]", "==", "alt", ")", ".", "values", "*", "long_form", "[", "variable", "]", ".", "values", ")", "# create the column name", "var_names", ".", "append", "(", "\"{}_{}\"", ".", "format", "(", "variable", ",", "alt", ")", ")", "else", ":", "for", "group", "in", "specification", ":", "if", "isinstance", "(", "group", ",", "list", ")", ":", "# Create the variable column", "independent_vars", ".", "append", "(", "long_form", "[", "alt_id_col", "]", ".", "isin", "(", "group", ")", ".", "values", "*", "long_form", "[", "variable", "]", ".", "values", ")", "# Create the column name", "var_names", ".", "append", "(", "\"{}_{}\"", ".", "format", "(", "variable", ",", "str", "(", "group", ")", ")", ")", "else", ":", "# the group is an integer", "# Create the variable column", "new_col_vals", "=", "(", "(", "long_form", "[", "alt_id_col", "]", "==", "group", ")", ".", "values", "*", "long_form", "[", "variable", "]", ".", "values", ")", "independent_vars", ".", "append", "(", "new_col_vals", ")", "# Create the column name", "var_names", ".", "append", "(", "\"{}_{}\"", ".", "format", "(", "variable", ",", "group", ")", ")", "# Create the final design matrix", "design_matrix", "=", "np", ".", "hstack", "(", "(", "x", "[", ":", ",", "None", "]", "for", "x", "in", "independent_vars", ")", ")", "# Use the list of names passed by the user, if the user passed such a list", "if", "names", "is", "not", "None", ":", "var_names", "=", "[", "]", "for", "value", "in", "names", ".", "values", "(", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "var_names", ".", "append", "(", "value", ")", "else", ":", "for", "inner_name", "in", "value", ":", "var_names", ".", "append", "(", "inner_name", ")", "return", "design_matrix", ",", "var_names" ]
Parameters ---------- long_form : pandas dataframe. Contains one row for each available alternative, for each observation. specification_dict : OrderedDict. Keys are a proper subset of the columns in `long_form_df`. Values are either a list or a single string, `"all_diff"` or `"all_same"`. If a list, the elements should be: - single objects that are within the alternative ID column of `long_form_df` - lists of objects that are within the alternative ID column of `long_form_df`. For each single object in the list, a unique column will be created (i.e. there will be a unique coefficient for that variable in the corresponding utility equation of the corresponding alternative). For lists within the `specification_dict` values, a single column will be created for all the alternatives within iterable (i.e. there will be one common coefficient for the variables in the iterable). alt_id_col : str. Column name which denotes the column in `long_form` that contains the alternative ID for each row in `long_form`. names : OrderedDict, optional. Should have the same keys as `specification_dict`. For each key: - if the corresponding value in `specification_dict` is "all_same", then there should be a single string as the value in names. - if the corresponding value in `specification_dict` is "all_diff", then there should be a list of strings as the value in names. There should be one string in the value in names for each possible alternative. - if the corresponding value in `specification_dict` is a list, then there should be a list of strings as the value in names. There should be one string the value in names per item in the value in `specification_dict`. Default == None. Returns ------- design_matrix, var_names: tuple with two elements. First element is the design matrix, a numpy array with some number of columns and as many rows as are in `long_form`. Each column corresponds to a coefficient to be estimated. The second element is a list of strings denoting the names of each coefficient, with one variable name per column in the design matrix.
[ "Parameters", "----------", "long_form", ":", "pandas", "dataframe", ".", "Contains", "one", "row", "for", "each", "available", "alternative", "for", "each", "observation", ".", "specification_dict", ":", "OrderedDict", ".", "Keys", "are", "a", "proper", "subset", "of", "the", "columns", "in", "long_form_df", ".", "Values", "are", "either", "a", "list", "or", "a", "single", "string", "all_diff", "or", "all_same", ".", "If", "a", "list", "the", "elements", "should", "be", ":" ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L585-L715
timothyb0912/pylogit
pylogit/choice_tools.py
get_original_order_unique_ids
def get_original_order_unique_ids(id_array): """ Get the unique id's of id_array, in their original order of appearance. Parameters ---------- id_array : 1D ndarray. Should contain the ids that we want to extract the unique values from. Returns ------- original_order_unique_ids : 1D ndarray. Contains the unique ids from `id_array`, in their original order of appearance. """ assert isinstance(id_array, np.ndarray) assert len(id_array.shape) == 1 # Get the indices of the unique IDs in their order of appearance # Note the [1] is because the np.unique() call will return both the sorted # unique IDs and the indices original_unique_id_indices =\ np.sort(np.unique(id_array, return_index=True)[1]) # Get the unique ids, in their original order of appearance original_order_unique_ids = id_array[original_unique_id_indices] return original_order_unique_ids
python
def get_original_order_unique_ids(id_array): assert isinstance(id_array, np.ndarray) assert len(id_array.shape) == 1 original_unique_id_indices =\ np.sort(np.unique(id_array, return_index=True)[1]) original_order_unique_ids = id_array[original_unique_id_indices] return original_order_unique_ids
[ "def", "get_original_order_unique_ids", "(", "id_array", ")", ":", "assert", "isinstance", "(", "id_array", ",", "np", ".", "ndarray", ")", "assert", "len", "(", "id_array", ".", "shape", ")", "==", "1", "# Get the indices of the unique IDs in their order of appearance", "# Note the [1] is because the np.unique() call will return both the sorted", "# unique IDs and the indices", "original_unique_id_indices", "=", "np", ".", "sort", "(", "np", ".", "unique", "(", "id_array", ",", "return_index", "=", "True", ")", "[", "1", "]", ")", "# Get the unique ids, in their original order of appearance", "original_order_unique_ids", "=", "id_array", "[", "original_unique_id_indices", "]", "return", "original_order_unique_ids" ]
Get the unique id's of id_array, in their original order of appearance. Parameters ---------- id_array : 1D ndarray. Should contain the ids that we want to extract the unique values from. Returns ------- original_order_unique_ids : 1D ndarray. Contains the unique ids from `id_array`, in their original order of appearance.
[ "Get", "the", "unique", "id", "s", "of", "id_array", "in", "their", "original", "order", "of", "appearance", "." ]
train
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L718-L745