repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
poppy-project/pypot | pypot/dynamixel/io/abstract_io.py | AbstractDxlIO.enable_torque | def enable_torque(self, ids):
""" Enables torque of the motors with the specified ids. """
self._set_torque_enable(dict(zip(ids, itertools.repeat(True)))) | python | def enable_torque(self, ids):
""" Enables torque of the motors with the specified ids. """
self._set_torque_enable(dict(zip(ids, itertools.repeat(True)))) | [
"def",
"enable_torque",
"(",
"self",
",",
"ids",
")",
":",
"self",
".",
"_set_torque_enable",
"(",
"dict",
"(",
"zip",
"(",
"ids",
",",
"itertools",
".",
"repeat",
"(",
"True",
")",
")",
")",
")"
] | Enables torque of the motors with the specified ids. | [
"Enables",
"torque",
"of",
"the",
"motors",
"with",
"the",
"specified",
"ids",
"."
] | d9c6551bbc87d45d9d1f0bc15e35b616d0002afd | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L298-L300 | train | 233,600 |
poppy-project/pypot | pypot/dynamixel/io/abstract_io.py | AbstractDxlIO.disable_torque | def disable_torque(self, ids):
""" Disables torque of the motors with the specified ids. """
self._set_torque_enable(dict(zip(ids, itertools.repeat(False)))) | python | def disable_torque(self, ids):
""" Disables torque of the motors with the specified ids. """
self._set_torque_enable(dict(zip(ids, itertools.repeat(False)))) | [
"def",
"disable_torque",
"(",
"self",
",",
"ids",
")",
":",
"self",
".",
"_set_torque_enable",
"(",
"dict",
"(",
"zip",
"(",
"ids",
",",
"itertools",
".",
"repeat",
"(",
"False",
")",
")",
")",
")"
] | Disables torque of the motors with the specified ids. | [
"Disables",
"torque",
"of",
"the",
"motors",
"with",
"the",
"specified",
"ids",
"."
] | d9c6551bbc87d45d9d1f0bc15e35b616d0002afd | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L302-L304 | train | 233,601 |
poppy-project/pypot | pypot/dynamixel/io/abstract_io.py | AbstractDxlIO.get_pid_gain | def get_pid_gain(self, ids, **kwargs):
""" Gets the pid gain for the specified motors. """
return tuple([tuple(reversed(t)) for t in self._get_pid_gain(ids, **kwargs)]) | python | def get_pid_gain(self, ids, **kwargs):
""" Gets the pid gain for the specified motors. """
return tuple([tuple(reversed(t)) for t in self._get_pid_gain(ids, **kwargs)]) | [
"def",
"get_pid_gain",
"(",
"self",
",",
"ids",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"tuple",
"(",
"[",
"tuple",
"(",
"reversed",
"(",
"t",
")",
")",
"for",
"t",
"in",
"self",
".",
"_get_pid_gain",
"(",
"ids",
",",
"*",
"*",
"kwargs",
")",
"]",
")"
] | Gets the pid gain for the specified motors. | [
"Gets",
"the",
"pid",
"gain",
"for",
"the",
"specified",
"motors",
"."
] | d9c6551bbc87d45d9d1f0bc15e35b616d0002afd | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L306-L308 | train | 233,602 |
poppy-project/pypot | pypot/dynamixel/io/abstract_io.py | AbstractDxlIO.set_pid_gain | def set_pid_gain(self, pid_for_id, **kwargs):
""" Sets the pid gain to the specified motors. """
pid_for_id = dict(itertools.izip(pid_for_id.iterkeys(),
[tuple(reversed(t)) for t in pid_for_id.values()]))
self._set_pid_gain(pid_for_id, **kwargs) | python | def set_pid_gain(self, pid_for_id, **kwargs):
""" Sets the pid gain to the specified motors. """
pid_for_id = dict(itertools.izip(pid_for_id.iterkeys(),
[tuple(reversed(t)) for t in pid_for_id.values()]))
self._set_pid_gain(pid_for_id, **kwargs) | [
"def",
"set_pid_gain",
"(",
"self",
",",
"pid_for_id",
",",
"*",
"*",
"kwargs",
")",
":",
"pid_for_id",
"=",
"dict",
"(",
"itertools",
".",
"izip",
"(",
"pid_for_id",
".",
"iterkeys",
"(",
")",
",",
"[",
"tuple",
"(",
"reversed",
"(",
"t",
")",
")",
"for",
"t",
"in",
"pid_for_id",
".",
"values",
"(",
")",
"]",
")",
")",
"self",
".",
"_set_pid_gain",
"(",
"pid_for_id",
",",
"*",
"*",
"kwargs",
")"
] | Sets the pid gain to the specified motors. | [
"Sets",
"the",
"pid",
"gain",
"to",
"the",
"specified",
"motors",
"."
] | d9c6551bbc87d45d9d1f0bc15e35b616d0002afd | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L310-L314 | train | 233,603 |
poppy-project/pypot | pypot/dynamixel/io/abstract_io.py | AbstractDxlIO.get_control_table | def get_control_table(self, ids, **kwargs):
""" Gets the full control table for the specified motors.
..note:: This function requires the model for each motor to be known. Querring this additional information might add some extra delay.
"""
error_handler = kwargs['error_handler'] if ('error_handler' in kwargs) else self._error_handler
convert = kwargs['convert'] if ('convert' in kwargs) else self._convert
bl = ('goal position speed load', 'present position speed load')
controls = [c for c in self._AbstractDxlIO__controls if c.name not in bl]
res = []
for id, model in zip(ids, self.get_model(ids)):
controls = [c for c in controls if model in c.models]
controls = sorted(controls, key=lambda c: c.address)
address = controls[0].address
length = controls[-1].address + controls[-1].nb_elem * controls[-1].length
rp = self._protocol.DxlReadDataPacket(id, address, length)
sp = self._send_packet(rp, error_handler=error_handler)
d = OrderedDict()
for c in controls:
v = dxl_decode_all(sp.parameters[c.address:c.address + c.nb_elem * c.length], c.nb_elem)
d[c.name] = c.dxl_to_si(v, model) if convert else v
res.append(d)
return tuple(res) | python | def get_control_table(self, ids, **kwargs):
""" Gets the full control table for the specified motors.
..note:: This function requires the model for each motor to be known. Querring this additional information might add some extra delay.
"""
error_handler = kwargs['error_handler'] if ('error_handler' in kwargs) else self._error_handler
convert = kwargs['convert'] if ('convert' in kwargs) else self._convert
bl = ('goal position speed load', 'present position speed load')
controls = [c for c in self._AbstractDxlIO__controls if c.name not in bl]
res = []
for id, model in zip(ids, self.get_model(ids)):
controls = [c for c in controls if model in c.models]
controls = sorted(controls, key=lambda c: c.address)
address = controls[0].address
length = controls[-1].address + controls[-1].nb_elem * controls[-1].length
rp = self._protocol.DxlReadDataPacket(id, address, length)
sp = self._send_packet(rp, error_handler=error_handler)
d = OrderedDict()
for c in controls:
v = dxl_decode_all(sp.parameters[c.address:c.address + c.nb_elem * c.length], c.nb_elem)
d[c.name] = c.dxl_to_si(v, model) if convert else v
res.append(d)
return tuple(res) | [
"def",
"get_control_table",
"(",
"self",
",",
"ids",
",",
"*",
"*",
"kwargs",
")",
":",
"error_handler",
"=",
"kwargs",
"[",
"'error_handler'",
"]",
"if",
"(",
"'error_handler'",
"in",
"kwargs",
")",
"else",
"self",
".",
"_error_handler",
"convert",
"=",
"kwargs",
"[",
"'convert'",
"]",
"if",
"(",
"'convert'",
"in",
"kwargs",
")",
"else",
"self",
".",
"_convert",
"bl",
"=",
"(",
"'goal position speed load'",
",",
"'present position speed load'",
")",
"controls",
"=",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"_AbstractDxlIO__controls",
"if",
"c",
".",
"name",
"not",
"in",
"bl",
"]",
"res",
"=",
"[",
"]",
"for",
"id",
",",
"model",
"in",
"zip",
"(",
"ids",
",",
"self",
".",
"get_model",
"(",
"ids",
")",
")",
":",
"controls",
"=",
"[",
"c",
"for",
"c",
"in",
"controls",
"if",
"model",
"in",
"c",
".",
"models",
"]",
"controls",
"=",
"sorted",
"(",
"controls",
",",
"key",
"=",
"lambda",
"c",
":",
"c",
".",
"address",
")",
"address",
"=",
"controls",
"[",
"0",
"]",
".",
"address",
"length",
"=",
"controls",
"[",
"-",
"1",
"]",
".",
"address",
"+",
"controls",
"[",
"-",
"1",
"]",
".",
"nb_elem",
"*",
"controls",
"[",
"-",
"1",
"]",
".",
"length",
"rp",
"=",
"self",
".",
"_protocol",
".",
"DxlReadDataPacket",
"(",
"id",
",",
"address",
",",
"length",
")",
"sp",
"=",
"self",
".",
"_send_packet",
"(",
"rp",
",",
"error_handler",
"=",
"error_handler",
")",
"d",
"=",
"OrderedDict",
"(",
")",
"for",
"c",
"in",
"controls",
":",
"v",
"=",
"dxl_decode_all",
"(",
"sp",
".",
"parameters",
"[",
"c",
".",
"address",
":",
"c",
".",
"address",
"+",
"c",
".",
"nb_elem",
"*",
"c",
".",
"length",
"]",
",",
"c",
".",
"nb_elem",
")",
"d",
"[",
"c",
".",
"name",
"]",
"=",
"c",
".",
"dxl_to_si",
"(",
"v",
",",
"model",
")",
"if",
"convert",
"else",
"v",
"res",
".",
"append",
"(",
"d",
")",
"return",
"tuple",
"(",
"res",
")"
] | Gets the full control table for the specified motors.
..note:: This function requires the model for each motor to be known. Querring this additional information might add some extra delay. | [
"Gets",
"the",
"full",
"control",
"table",
"for",
"the",
"specified",
"motors",
"."
] | d9c6551bbc87d45d9d1f0bc15e35b616d0002afd | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L318-L350 | train | 233,604 |
poppy-project/pypot | pypot/robot/config.py | check_motor_eprom_configuration | def check_motor_eprom_configuration(config, dxl_io, motor_names):
""" Change the angles limits depanding on the robot configuration ;
Check if the return delay time is set to 0.
"""
changed_angle_limits = {}
changed_return_delay_time = {}
for name in motor_names:
m = config['motors'][name]
id = m['id']
try:
old_limits = dxl_io.get_angle_limit((id, ))[0]
old_return_delay_time = dxl_io.get_return_delay_time((id, ))[0]
except IndexError: # probably a broken motor so we just skip
continue
if old_return_delay_time != 0:
logger.warning("Return delay time of %s changed from %s to 0",
name, old_return_delay_time)
changed_return_delay_time[id] = 0
new_limits = m['angle_limit']
if 'wheel_mode' in m and m['wheel_mode']:
dxl_io.set_wheel_mode([m['id']])
time.sleep(0.5)
else:
# TODO: we probably need a better fix for this.
# dxl_io.set_joint_mode([m['id']])
d = numpy.linalg.norm(numpy.asarray(new_limits) - numpy.asarray(old_limits))
if d > 1:
logger.warning("Limits of '%s' changed from %s to %s",
name, old_limits, new_limits,
extra={'config': config})
changed_angle_limits[id] = new_limits
if changed_angle_limits:
dxl_io.set_angle_limit(changed_angle_limits)
time.sleep(0.5)
if changed_return_delay_time:
dxl_io.set_return_delay_time(changed_return_delay_time)
time.sleep(0.5) | python | def check_motor_eprom_configuration(config, dxl_io, motor_names):
""" Change the angles limits depanding on the robot configuration ;
Check if the return delay time is set to 0.
"""
changed_angle_limits = {}
changed_return_delay_time = {}
for name in motor_names:
m = config['motors'][name]
id = m['id']
try:
old_limits = dxl_io.get_angle_limit((id, ))[0]
old_return_delay_time = dxl_io.get_return_delay_time((id, ))[0]
except IndexError: # probably a broken motor so we just skip
continue
if old_return_delay_time != 0:
logger.warning("Return delay time of %s changed from %s to 0",
name, old_return_delay_time)
changed_return_delay_time[id] = 0
new_limits = m['angle_limit']
if 'wheel_mode' in m and m['wheel_mode']:
dxl_io.set_wheel_mode([m['id']])
time.sleep(0.5)
else:
# TODO: we probably need a better fix for this.
# dxl_io.set_joint_mode([m['id']])
d = numpy.linalg.norm(numpy.asarray(new_limits) - numpy.asarray(old_limits))
if d > 1:
logger.warning("Limits of '%s' changed from %s to %s",
name, old_limits, new_limits,
extra={'config': config})
changed_angle_limits[id] = new_limits
if changed_angle_limits:
dxl_io.set_angle_limit(changed_angle_limits)
time.sleep(0.5)
if changed_return_delay_time:
dxl_io.set_return_delay_time(changed_return_delay_time)
time.sleep(0.5) | [
"def",
"check_motor_eprom_configuration",
"(",
"config",
",",
"dxl_io",
",",
"motor_names",
")",
":",
"changed_angle_limits",
"=",
"{",
"}",
"changed_return_delay_time",
"=",
"{",
"}",
"for",
"name",
"in",
"motor_names",
":",
"m",
"=",
"config",
"[",
"'motors'",
"]",
"[",
"name",
"]",
"id",
"=",
"m",
"[",
"'id'",
"]",
"try",
":",
"old_limits",
"=",
"dxl_io",
".",
"get_angle_limit",
"(",
"(",
"id",
",",
")",
")",
"[",
"0",
"]",
"old_return_delay_time",
"=",
"dxl_io",
".",
"get_return_delay_time",
"(",
"(",
"id",
",",
")",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"# probably a broken motor so we just skip",
"continue",
"if",
"old_return_delay_time",
"!=",
"0",
":",
"logger",
".",
"warning",
"(",
"\"Return delay time of %s changed from %s to 0\"",
",",
"name",
",",
"old_return_delay_time",
")",
"changed_return_delay_time",
"[",
"id",
"]",
"=",
"0",
"new_limits",
"=",
"m",
"[",
"'angle_limit'",
"]",
"if",
"'wheel_mode'",
"in",
"m",
"and",
"m",
"[",
"'wheel_mode'",
"]",
":",
"dxl_io",
".",
"set_wheel_mode",
"(",
"[",
"m",
"[",
"'id'",
"]",
"]",
")",
"time",
".",
"sleep",
"(",
"0.5",
")",
"else",
":",
"# TODO: we probably need a better fix for this.",
"# dxl_io.set_joint_mode([m['id']])",
"d",
"=",
"numpy",
".",
"linalg",
".",
"norm",
"(",
"numpy",
".",
"asarray",
"(",
"new_limits",
")",
"-",
"numpy",
".",
"asarray",
"(",
"old_limits",
")",
")",
"if",
"d",
">",
"1",
":",
"logger",
".",
"warning",
"(",
"\"Limits of '%s' changed from %s to %s\"",
",",
"name",
",",
"old_limits",
",",
"new_limits",
",",
"extra",
"=",
"{",
"'config'",
":",
"config",
"}",
")",
"changed_angle_limits",
"[",
"id",
"]",
"=",
"new_limits",
"if",
"changed_angle_limits",
":",
"dxl_io",
".",
"set_angle_limit",
"(",
"changed_angle_limits",
")",
"time",
".",
"sleep",
"(",
"0.5",
")",
"if",
"changed_return_delay_time",
":",
"dxl_io",
".",
"set_return_delay_time",
"(",
"changed_return_delay_time",
")",
"time",
".",
"sleep",
"(",
"0.5",
")"
] | Change the angles limits depanding on the robot configuration ;
Check if the return delay time is set to 0. | [
"Change",
"the",
"angles",
"limits",
"depanding",
"on",
"the",
"robot",
"configuration",
";",
"Check",
"if",
"the",
"return",
"delay",
"time",
"is",
"set",
"to",
"0",
"."
] | d9c6551bbc87d45d9d1f0bc15e35b616d0002afd | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/robot/config.py#L209-L252 | train | 233,605 |
icometrix/dicom2nifti | dicom2nifti/compressed_dicom.py | _get_gdcmconv | def _get_gdcmconv():
"""
Get the full path to gdcmconv.
If not found raise error
"""
gdcmconv_executable = settings.gdcmconv_path
if gdcmconv_executable is None:
gdcmconv_executable = _which('gdcmconv')
if gdcmconv_executable is None:
gdcmconv_executable = _which('gdcmconv.exe')
if gdcmconv_executable is None:
raise ConversionError('GDCMCONV_NOT_FOUND')
return gdcmconv_executable | python | def _get_gdcmconv():
"""
Get the full path to gdcmconv.
If not found raise error
"""
gdcmconv_executable = settings.gdcmconv_path
if gdcmconv_executable is None:
gdcmconv_executable = _which('gdcmconv')
if gdcmconv_executable is None:
gdcmconv_executable = _which('gdcmconv.exe')
if gdcmconv_executable is None:
raise ConversionError('GDCMCONV_NOT_FOUND')
return gdcmconv_executable | [
"def",
"_get_gdcmconv",
"(",
")",
":",
"gdcmconv_executable",
"=",
"settings",
".",
"gdcmconv_path",
"if",
"gdcmconv_executable",
"is",
"None",
":",
"gdcmconv_executable",
"=",
"_which",
"(",
"'gdcmconv'",
")",
"if",
"gdcmconv_executable",
"is",
"None",
":",
"gdcmconv_executable",
"=",
"_which",
"(",
"'gdcmconv.exe'",
")",
"if",
"gdcmconv_executable",
"is",
"None",
":",
"raise",
"ConversionError",
"(",
"'GDCMCONV_NOT_FOUND'",
")",
"return",
"gdcmconv_executable"
] | Get the full path to gdcmconv.
If not found raise error | [
"Get",
"the",
"full",
"path",
"to",
"gdcmconv",
".",
"If",
"not",
"found",
"raise",
"error"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/compressed_dicom.py#L41-L55 | train | 233,606 |
icometrix/dicom2nifti | dicom2nifti/compressed_dicom.py | compress_directory | def compress_directory(dicom_directory):
"""
This function can be used to convert a folder of jpeg compressed images to an uncompressed ones
:param dicom_directory: directory of dicom files to compress
"""
if _is_compressed(dicom_directory):
return
logger.info('Compressing dicom files in %s' % dicom_directory)
for root, _, files in os.walk(dicom_directory):
for dicom_file in files:
if is_dicom_file(os.path.join(root, dicom_file)):
_compress_dicom(os.path.join(root, dicom_file)) | python | def compress_directory(dicom_directory):
"""
This function can be used to convert a folder of jpeg compressed images to an uncompressed ones
:param dicom_directory: directory of dicom files to compress
"""
if _is_compressed(dicom_directory):
return
logger.info('Compressing dicom files in %s' % dicom_directory)
for root, _, files in os.walk(dicom_directory):
for dicom_file in files:
if is_dicom_file(os.path.join(root, dicom_file)):
_compress_dicom(os.path.join(root, dicom_file)) | [
"def",
"compress_directory",
"(",
"dicom_directory",
")",
":",
"if",
"_is_compressed",
"(",
"dicom_directory",
")",
":",
"return",
"logger",
".",
"info",
"(",
"'Compressing dicom files in %s'",
"%",
"dicom_directory",
")",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dicom_directory",
")",
":",
"for",
"dicom_file",
"in",
"files",
":",
"if",
"is_dicom_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"dicom_file",
")",
")",
":",
"_compress_dicom",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"dicom_file",
")",
")"
] | This function can be used to convert a folder of jpeg compressed images to an uncompressed ones
:param dicom_directory: directory of dicom files to compress | [
"This",
"function",
"can",
"be",
"used",
"to",
"convert",
"a",
"folder",
"of",
"jpeg",
"compressed",
"images",
"to",
"an",
"uncompressed",
"ones"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/compressed_dicom.py#L58-L71 | train | 233,607 |
icometrix/dicom2nifti | dicom2nifti/compressed_dicom.py | is_dicom_file | def is_dicom_file(filename):
"""
Util function to check if file is a dicom file
the first 128 bytes are preamble
the next 4 bytes should contain DICM otherwise it is not a dicom
:param filename: file to check for the DICM header block
:type filename: six.string_types
:returns: True if it is a dicom file
"""
file_stream = open(filename, 'rb')
file_stream.seek(128)
data = file_stream.read(4)
file_stream.close()
if data == b'DICM':
return True
if settings.pydicom_read_force:
try:
dicom_headers = pydicom.read_file(filename, defer_size="1 KB", stop_before_pixels=True, force=True)
if dicom_headers is not None:
return True
except:
pass
return False | python | def is_dicom_file(filename):
"""
Util function to check if file is a dicom file
the first 128 bytes are preamble
the next 4 bytes should contain DICM otherwise it is not a dicom
:param filename: file to check for the DICM header block
:type filename: six.string_types
:returns: True if it is a dicom file
"""
file_stream = open(filename, 'rb')
file_stream.seek(128)
data = file_stream.read(4)
file_stream.close()
if data == b'DICM':
return True
if settings.pydicom_read_force:
try:
dicom_headers = pydicom.read_file(filename, defer_size="1 KB", stop_before_pixels=True, force=True)
if dicom_headers is not None:
return True
except:
pass
return False | [
"def",
"is_dicom_file",
"(",
"filename",
")",
":",
"file_stream",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"file_stream",
".",
"seek",
"(",
"128",
")",
"data",
"=",
"file_stream",
".",
"read",
"(",
"4",
")",
"file_stream",
".",
"close",
"(",
")",
"if",
"data",
"==",
"b'DICM'",
":",
"return",
"True",
"if",
"settings",
".",
"pydicom_read_force",
":",
"try",
":",
"dicom_headers",
"=",
"pydicom",
".",
"read_file",
"(",
"filename",
",",
"defer_size",
"=",
"\"1 KB\"",
",",
"stop_before_pixels",
"=",
"True",
",",
"force",
"=",
"True",
")",
"if",
"dicom_headers",
"is",
"not",
"None",
":",
"return",
"True",
"except",
":",
"pass",
"return",
"False"
] | Util function to check if file is a dicom file
the first 128 bytes are preamble
the next 4 bytes should contain DICM otherwise it is not a dicom
:param filename: file to check for the DICM header block
:type filename: six.string_types
:returns: True if it is a dicom file | [
"Util",
"function",
"to",
"check",
"if",
"file",
"is",
"a",
"dicom",
"file",
"the",
"first",
"128",
"bytes",
"are",
"preamble",
"the",
"next",
"4",
"bytes",
"should",
"contain",
"DICM",
"otherwise",
"it",
"is",
"not",
"a",
"dicom"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/compressed_dicom.py#L74-L97 | train | 233,608 |
icometrix/dicom2nifti | dicom2nifti/compressed_dicom.py | _is_compressed | def _is_compressed(dicom_file, force=False):
"""
Check if dicoms are compressed or not
"""
header = pydicom.read_file(dicom_file,
defer_size="1 KB",
stop_before_pixels=True,
force=force)
uncompressed_types = ["1.2.840.10008.1.2",
"1.2.840.10008.1.2.1",
"1.2.840.10008.1.2.1.99",
"1.2.840.10008.1.2.2"]
if 'TransferSyntaxUID' in header.file_meta and header.file_meta.TransferSyntaxUID in uncompressed_types:
return False
return True | python | def _is_compressed(dicom_file, force=False):
"""
Check if dicoms are compressed or not
"""
header = pydicom.read_file(dicom_file,
defer_size="1 KB",
stop_before_pixels=True,
force=force)
uncompressed_types = ["1.2.840.10008.1.2",
"1.2.840.10008.1.2.1",
"1.2.840.10008.1.2.1.99",
"1.2.840.10008.1.2.2"]
if 'TransferSyntaxUID' in header.file_meta and header.file_meta.TransferSyntaxUID in uncompressed_types:
return False
return True | [
"def",
"_is_compressed",
"(",
"dicom_file",
",",
"force",
"=",
"False",
")",
":",
"header",
"=",
"pydicom",
".",
"read_file",
"(",
"dicom_file",
",",
"defer_size",
"=",
"\"1 KB\"",
",",
"stop_before_pixels",
"=",
"True",
",",
"force",
"=",
"force",
")",
"uncompressed_types",
"=",
"[",
"\"1.2.840.10008.1.2\"",
",",
"\"1.2.840.10008.1.2.1\"",
",",
"\"1.2.840.10008.1.2.1.99\"",
",",
"\"1.2.840.10008.1.2.2\"",
"]",
"if",
"'TransferSyntaxUID'",
"in",
"header",
".",
"file_meta",
"and",
"header",
".",
"file_meta",
".",
"TransferSyntaxUID",
"in",
"uncompressed_types",
":",
"return",
"False",
"return",
"True"
] | Check if dicoms are compressed or not | [
"Check",
"if",
"dicoms",
"are",
"compressed",
"or",
"not"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/compressed_dicom.py#L100-L116 | train | 233,609 |
icometrix/dicom2nifti | dicom2nifti/compressed_dicom.py | _decompress_dicom | def _decompress_dicom(dicom_file, output_file):
"""
This function can be used to convert a jpeg compressed image to an uncompressed one for further conversion
:param input_file: single dicom file to decompress
"""
gdcmconv_executable = _get_gdcmconv()
subprocess.check_output([gdcmconv_executable, '-w', dicom_file, output_file]) | python | def _decompress_dicom(dicom_file, output_file):
"""
This function can be used to convert a jpeg compressed image to an uncompressed one for further conversion
:param input_file: single dicom file to decompress
"""
gdcmconv_executable = _get_gdcmconv()
subprocess.check_output([gdcmconv_executable, '-w', dicom_file, output_file]) | [
"def",
"_decompress_dicom",
"(",
"dicom_file",
",",
"output_file",
")",
":",
"gdcmconv_executable",
"=",
"_get_gdcmconv",
"(",
")",
"subprocess",
".",
"check_output",
"(",
"[",
"gdcmconv_executable",
",",
"'-w'",
",",
"dicom_file",
",",
"output_file",
"]",
")"
] | This function can be used to convert a jpeg compressed image to an uncompressed one for further conversion
:param input_file: single dicom file to decompress | [
"This",
"function",
"can",
"be",
"used",
"to",
"convert",
"a",
"jpeg",
"compressed",
"image",
"to",
"an",
"uncompressed",
"one",
"for",
"further",
"conversion"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/compressed_dicom.py#L119-L127 | train | 233,610 |
icometrix/dicom2nifti | scripts/dicomdiff.py | dicom_diff | def dicom_diff(file1, file2):
""" Shows the fields that differ between two DICOM images.
Inspired by https://code.google.com/p/pydicom/source/browse/source/dicom/examples/DicomDiff.py
"""
datasets = compressed_dicom.read_file(file1), compressed_dicom.read_file(file2)
rep = []
for dataset in datasets:
lines = (str(dataset.file_meta)+"\n"+str(dataset)).split('\n')
lines = [line + '\n' for line in lines] # add the newline to the end
rep.append(lines)
diff = difflib.Differ()
for line in diff.compare(rep[0], rep[1]):
if (line[0] == '+') or (line[0] == '-'):
sys.stdout.write(line) | python | def dicom_diff(file1, file2):
""" Shows the fields that differ between two DICOM images.
Inspired by https://code.google.com/p/pydicom/source/browse/source/dicom/examples/DicomDiff.py
"""
datasets = compressed_dicom.read_file(file1), compressed_dicom.read_file(file2)
rep = []
for dataset in datasets:
lines = (str(dataset.file_meta)+"\n"+str(dataset)).split('\n')
lines = [line + '\n' for line in lines] # add the newline to the end
rep.append(lines)
diff = difflib.Differ()
for line in diff.compare(rep[0], rep[1]):
if (line[0] == '+') or (line[0] == '-'):
sys.stdout.write(line) | [
"def",
"dicom_diff",
"(",
"file1",
",",
"file2",
")",
":",
"datasets",
"=",
"compressed_dicom",
".",
"read_file",
"(",
"file1",
")",
",",
"compressed_dicom",
".",
"read_file",
"(",
"file2",
")",
"rep",
"=",
"[",
"]",
"for",
"dataset",
"in",
"datasets",
":",
"lines",
"=",
"(",
"str",
"(",
"dataset",
".",
"file_meta",
")",
"+",
"\"\\n\"",
"+",
"str",
"(",
"dataset",
")",
")",
".",
"split",
"(",
"'\\n'",
")",
"lines",
"=",
"[",
"line",
"+",
"'\\n'",
"for",
"line",
"in",
"lines",
"]",
"# add the newline to the end",
"rep",
".",
"append",
"(",
"lines",
")",
"diff",
"=",
"difflib",
".",
"Differ",
"(",
")",
"for",
"line",
"in",
"diff",
".",
"compare",
"(",
"rep",
"[",
"0",
"]",
",",
"rep",
"[",
"1",
"]",
")",
":",
"if",
"(",
"line",
"[",
"0",
"]",
"==",
"'+'",
")",
"or",
"(",
"line",
"[",
"0",
"]",
"==",
"'-'",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"line",
")"
] | Shows the fields that differ between two DICOM images.
Inspired by https://code.google.com/p/pydicom/source/browse/source/dicom/examples/DicomDiff.py | [
"Shows",
"the",
"fields",
"that",
"differ",
"between",
"two",
"DICOM",
"images",
"."
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/scripts/dicomdiff.py#L14-L32 | train | 233,611 |
icometrix/dicom2nifti | dicom2nifti/image_volume.py | ImageVolume._get_number_of_slices | def _get_number_of_slices(self, slice_type):
"""
Get the number of slices in a certain direction
"""
if slice_type == SliceType.AXIAL:
return self.dimensions[self.axial_orientation.normal_component]
elif slice_type == SliceType.SAGITTAL:
return self.dimensions[self.sagittal_orientation.normal_component]
elif slice_type == SliceType.CORONAL:
return self.dimensions[self.coronal_orientation.normal_component] | python | def _get_number_of_slices(self, slice_type):
"""
Get the number of slices in a certain direction
"""
if slice_type == SliceType.AXIAL:
return self.dimensions[self.axial_orientation.normal_component]
elif slice_type == SliceType.SAGITTAL:
return self.dimensions[self.sagittal_orientation.normal_component]
elif slice_type == SliceType.CORONAL:
return self.dimensions[self.coronal_orientation.normal_component] | [
"def",
"_get_number_of_slices",
"(",
"self",
",",
"slice_type",
")",
":",
"if",
"slice_type",
"==",
"SliceType",
".",
"AXIAL",
":",
"return",
"self",
".",
"dimensions",
"[",
"self",
".",
"axial_orientation",
".",
"normal_component",
"]",
"elif",
"slice_type",
"==",
"SliceType",
".",
"SAGITTAL",
":",
"return",
"self",
".",
"dimensions",
"[",
"self",
".",
"sagittal_orientation",
".",
"normal_component",
"]",
"elif",
"slice_type",
"==",
"SliceType",
".",
"CORONAL",
":",
"return",
"self",
".",
"dimensions",
"[",
"self",
".",
"coronal_orientation",
".",
"normal_component",
"]"
] | Get the number of slices in a certain direction | [
"Get",
"the",
"number",
"of",
"slices",
"in",
"a",
"certain",
"direction"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/image_volume.py#L166-L175 | train | 233,612 |
icometrix/dicom2nifti | dicom2nifti/convert_dicom.py | _get_first_header | def _get_first_header(dicom_directory):
"""
Function to get the first dicom file form a directory and return the header
Useful to determine the type of data to convert
:param dicom_directory: directory with dicom files
"""
# looping over all files
for root, _, file_names in os.walk(dicom_directory):
# go over all the files and try to read the dicom header
for file_name in file_names:
file_path = os.path.join(root, file_name)
# check wither it is a dicom file
if not compressed_dicom.is_dicom_file(file_path):
continue
# read the headers
return compressed_dicom.read_file(file_path,
stop_before_pixels=True,
force=dicom2nifti.settings.pydicom_read_force)
# no dicom files found
raise ConversionError('NO_DICOM_FILES_FOUND') | python | def _get_first_header(dicom_directory):
"""
Function to get the first dicom file form a directory and return the header
Useful to determine the type of data to convert
:param dicom_directory: directory with dicom files
"""
# looping over all files
for root, _, file_names in os.walk(dicom_directory):
# go over all the files and try to read the dicom header
for file_name in file_names:
file_path = os.path.join(root, file_name)
# check wither it is a dicom file
if not compressed_dicom.is_dicom_file(file_path):
continue
# read the headers
return compressed_dicom.read_file(file_path,
stop_before_pixels=True,
force=dicom2nifti.settings.pydicom_read_force)
# no dicom files found
raise ConversionError('NO_DICOM_FILES_FOUND') | [
"def",
"_get_first_header",
"(",
"dicom_directory",
")",
":",
"# looping over all files",
"for",
"root",
",",
"_",
",",
"file_names",
"in",
"os",
".",
"walk",
"(",
"dicom_directory",
")",
":",
"# go over all the files and try to read the dicom header",
"for",
"file_name",
"in",
"file_names",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"file_name",
")",
"# check wither it is a dicom file",
"if",
"not",
"compressed_dicom",
".",
"is_dicom_file",
"(",
"file_path",
")",
":",
"continue",
"# read the headers",
"return",
"compressed_dicom",
".",
"read_file",
"(",
"file_path",
",",
"stop_before_pixels",
"=",
"True",
",",
"force",
"=",
"dicom2nifti",
".",
"settings",
".",
"pydicom_read_force",
")",
"# no dicom files found",
"raise",
"ConversionError",
"(",
"'NO_DICOM_FILES_FOUND'",
")"
] | Function to get the first dicom file form a directory and return the header
Useful to determine the type of data to convert
:param dicom_directory: directory with dicom files | [
"Function",
"to",
"get",
"the",
"first",
"dicom",
"file",
"form",
"a",
"directory",
"and",
"return",
"the",
"header",
"Useful",
"to",
"determine",
"the",
"type",
"of",
"data",
"to",
"convert"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_dicom.py#L196-L216 | train | 233,613 |
icometrix/dicom2nifti | dicom2nifti/image_reorientation.py | _reorient_3d | def _reorient_3d(image):
"""
Reorganize the data for a 3d nifti
"""
# Create empty array where x,y,z correspond to LR (sagittal), PA (coronal), IS (axial) directions and the size
# of the array in each direction is the same with the corresponding direction of the input image.
new_image = numpy.zeros([image.dimensions[image.sagittal_orientation.normal_component],
image.dimensions[image.coronal_orientation.normal_component],
image.dimensions[image.axial_orientation.normal_component]],
dtype=image.nifti_data.dtype)
# Fill the new image with the values of the input image but with matching the orientation with x,y,z
if image.coronal_orientation.y_inverted:
for i in range(new_image.shape[2]):
new_image[:, :, i] = numpy.fliplr(numpy.squeeze(image.get_slice(SliceType.AXIAL,
new_image.shape[2] - 1 - i).original_data))
else:
for i in range(new_image.shape[2]):
new_image[:, :, i] = numpy.fliplr(numpy.squeeze(image.get_slice(SliceType.AXIAL,
i).original_data))
return new_image | python | def _reorient_3d(image):
"""
Reorganize the data for a 3d nifti
"""
# Create empty array where x,y,z correspond to LR (sagittal), PA (coronal), IS (axial) directions and the size
# of the array in each direction is the same with the corresponding direction of the input image.
new_image = numpy.zeros([image.dimensions[image.sagittal_orientation.normal_component],
image.dimensions[image.coronal_orientation.normal_component],
image.dimensions[image.axial_orientation.normal_component]],
dtype=image.nifti_data.dtype)
# Fill the new image with the values of the input image but with matching the orientation with x,y,z
if image.coronal_orientation.y_inverted:
for i in range(new_image.shape[2]):
new_image[:, :, i] = numpy.fliplr(numpy.squeeze(image.get_slice(SliceType.AXIAL,
new_image.shape[2] - 1 - i).original_data))
else:
for i in range(new_image.shape[2]):
new_image[:, :, i] = numpy.fliplr(numpy.squeeze(image.get_slice(SliceType.AXIAL,
i).original_data))
return new_image | [
"def",
"_reorient_3d",
"(",
"image",
")",
":",
"# Create empty array where x,y,z correspond to LR (sagittal), PA (coronal), IS (axial) directions and the size",
"# of the array in each direction is the same with the corresponding direction of the input image.",
"new_image",
"=",
"numpy",
".",
"zeros",
"(",
"[",
"image",
".",
"dimensions",
"[",
"image",
".",
"sagittal_orientation",
".",
"normal_component",
"]",
",",
"image",
".",
"dimensions",
"[",
"image",
".",
"coronal_orientation",
".",
"normal_component",
"]",
",",
"image",
".",
"dimensions",
"[",
"image",
".",
"axial_orientation",
".",
"normal_component",
"]",
"]",
",",
"dtype",
"=",
"image",
".",
"nifti_data",
".",
"dtype",
")",
"# Fill the new image with the values of the input image but with matching the orientation with x,y,z",
"if",
"image",
".",
"coronal_orientation",
".",
"y_inverted",
":",
"for",
"i",
"in",
"range",
"(",
"new_image",
".",
"shape",
"[",
"2",
"]",
")",
":",
"new_image",
"[",
":",
",",
":",
",",
"i",
"]",
"=",
"numpy",
".",
"fliplr",
"(",
"numpy",
".",
"squeeze",
"(",
"image",
".",
"get_slice",
"(",
"SliceType",
".",
"AXIAL",
",",
"new_image",
".",
"shape",
"[",
"2",
"]",
"-",
"1",
"-",
"i",
")",
".",
"original_data",
")",
")",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"new_image",
".",
"shape",
"[",
"2",
"]",
")",
":",
"new_image",
"[",
":",
",",
":",
",",
"i",
"]",
"=",
"numpy",
".",
"fliplr",
"(",
"numpy",
".",
"squeeze",
"(",
"image",
".",
"get_slice",
"(",
"SliceType",
".",
"AXIAL",
",",
"i",
")",
".",
"original_data",
")",
")",
"return",
"new_image"
] | Reorganize the data for a 3d nifti | [
"Reorganize",
"the",
"data",
"for",
"a",
"3d",
"nifti"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/image_reorientation.py#L112-L133 | train | 233,614 |
icometrix/dicom2nifti | dicom2nifti/convert_philips.py | dicom_to_nifti | def dicom_to_nifti(dicom_input, output_file=None):
"""
This is the main dicom to nifti conversion fuction for philips images.
As input philips 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_philips(dicom_input)
if common.is_multiframe_dicom(dicom_input):
_assert_explicit_vr(dicom_input)
logger.info('Found multiframe dicom')
if _is_multiframe_4d(dicom_input):
logger.info('Found sequence type: MULTIFRAME 4D')
return _multiframe_to_nifti(dicom_input, output_file)
if _is_multiframe_anatomical(dicom_input):
logger.info('Found sequence type: MULTIFRAME ANATOMICAL')
return _multiframe_to_nifti(dicom_input, output_file)
else:
logger.info('Found singleframe dicom')
grouped_dicoms = _get_grouped_dicoms(dicom_input)
if _is_singleframe_4d(dicom_input):
logger.info('Found sequence type: SINGLEFRAME 4D')
return _singleframe_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):
"""
This is the main dicom to nifti conversion fuction for philips images.
As input philips 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_philips(dicom_input)
if common.is_multiframe_dicom(dicom_input):
_assert_explicit_vr(dicom_input)
logger.info('Found multiframe dicom')
if _is_multiframe_4d(dicom_input):
logger.info('Found sequence type: MULTIFRAME 4D')
return _multiframe_to_nifti(dicom_input, output_file)
if _is_multiframe_anatomical(dicom_input):
logger.info('Found sequence type: MULTIFRAME ANATOMICAL')
return _multiframe_to_nifti(dicom_input, output_file)
else:
logger.info('Found singleframe dicom')
grouped_dicoms = _get_grouped_dicoms(dicom_input)
if _is_singleframe_4d(dicom_input):
logger.info('Found sequence type: SINGLEFRAME 4D')
return _singleframe_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_philips",
"(",
"dicom_input",
")",
"if",
"common",
".",
"is_multiframe_dicom",
"(",
"dicom_input",
")",
":",
"_assert_explicit_vr",
"(",
"dicom_input",
")",
"logger",
".",
"info",
"(",
"'Found multiframe dicom'",
")",
"if",
"_is_multiframe_4d",
"(",
"dicom_input",
")",
":",
"logger",
".",
"info",
"(",
"'Found sequence type: MULTIFRAME 4D'",
")",
"return",
"_multiframe_to_nifti",
"(",
"dicom_input",
",",
"output_file",
")",
"if",
"_is_multiframe_anatomical",
"(",
"dicom_input",
")",
":",
"logger",
".",
"info",
"(",
"'Found sequence type: MULTIFRAME ANATOMICAL'",
")",
"return",
"_multiframe_to_nifti",
"(",
"dicom_input",
",",
"output_file",
")",
"else",
":",
"logger",
".",
"info",
"(",
"'Found singleframe dicom'",
")",
"grouped_dicoms",
"=",
"_get_grouped_dicoms",
"(",
"dicom_input",
")",
"if",
"_is_singleframe_4d",
"(",
"dicom_input",
")",
":",
"logger",
".",
"info",
"(",
"'Found sequence type: SINGLEFRAME 4D'",
")",
"return",
"_singleframe_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 philips images.
As input philips 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",
"philips",
"images",
".",
"As",
"input",
"philips",
"images",
"are",
"required",
".",
"It",
"will",
"then",
"determine",
"the",
"type",
"of",
"images",
"and",
"do",
"the",
"correct",
"conversion"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_philips.py#L31-L62 | train | 233,615 |
icometrix/dicom2nifti | dicom2nifti/convert_philips.py | _assert_explicit_vr | def _assert_explicit_vr(dicom_input):
"""
Assert that explicit vr is used
"""
if settings.validate_multiframe_implicit:
header = dicom_input[0]
if header.file_meta[0x0002, 0x0010].value == '1.2.840.10008.1.2':
raise ConversionError('IMPLICIT_VR_ENHANCED_DICOM') | python | def _assert_explicit_vr(dicom_input):
"""
Assert that explicit vr is used
"""
if settings.validate_multiframe_implicit:
header = dicom_input[0]
if header.file_meta[0x0002, 0x0010].value == '1.2.840.10008.1.2':
raise ConversionError('IMPLICIT_VR_ENHANCED_DICOM') | [
"def",
"_assert_explicit_vr",
"(",
"dicom_input",
")",
":",
"if",
"settings",
".",
"validate_multiframe_implicit",
":",
"header",
"=",
"dicom_input",
"[",
"0",
"]",
"if",
"header",
".",
"file_meta",
"[",
"0x0002",
",",
"0x0010",
"]",
".",
"value",
"==",
"'1.2.840.10008.1.2'",
":",
"raise",
"ConversionError",
"(",
"'IMPLICIT_VR_ENHANCED_DICOM'",
")"
] | Assert that explicit vr is used | [
"Assert",
"that",
"explicit",
"vr",
"is",
"used"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_philips.py#L65-L72 | train | 233,616 |
icometrix/dicom2nifti | dicom2nifti/convert_philips.py | _is_multiframe_4d | def _is_multiframe_4d(dicom_input):
"""
Use this function to detect if a dicom series is a philips multiframe 4D dataset
"""
# check if it is multi frame dicom
if not common.is_multiframe_dicom(dicom_input):
return False
header = dicom_input[0]
# check if there are multiple stacks
number_of_stack_slices = common.get_ss_value(header[Tag(0x2001, 0x105f)][0][Tag(0x2001, 0x102d)])
number_of_stacks = int(int(header.NumberOfFrames) / number_of_stack_slices)
if number_of_stacks <= 1:
return False
return True | python | def _is_multiframe_4d(dicom_input):
"""
Use this function to detect if a dicom series is a philips multiframe 4D dataset
"""
# check if it is multi frame dicom
if not common.is_multiframe_dicom(dicom_input):
return False
header = dicom_input[0]
# check if there are multiple stacks
number_of_stack_slices = common.get_ss_value(header[Tag(0x2001, 0x105f)][0][Tag(0x2001, 0x102d)])
number_of_stacks = int(int(header.NumberOfFrames) / number_of_stack_slices)
if number_of_stacks <= 1:
return False
return True | [
"def",
"_is_multiframe_4d",
"(",
"dicom_input",
")",
":",
"# check if it is multi frame dicom",
"if",
"not",
"common",
".",
"is_multiframe_dicom",
"(",
"dicom_input",
")",
":",
"return",
"False",
"header",
"=",
"dicom_input",
"[",
"0",
"]",
"# check if there are multiple stacks",
"number_of_stack_slices",
"=",
"common",
".",
"get_ss_value",
"(",
"header",
"[",
"Tag",
"(",
"0x2001",
",",
"0x105f",
")",
"]",
"[",
"0",
"]",
"[",
"Tag",
"(",
"0x2001",
",",
"0x102d",
")",
"]",
")",
"number_of_stacks",
"=",
"int",
"(",
"int",
"(",
"header",
".",
"NumberOfFrames",
")",
"/",
"number_of_stack_slices",
")",
"if",
"number_of_stacks",
"<=",
"1",
":",
"return",
"False",
"return",
"True"
] | Use this function to detect if a dicom series is a philips multiframe 4D dataset | [
"Use",
"this",
"function",
"to",
"detect",
"if",
"a",
"dicom",
"series",
"is",
"a",
"philips",
"multiframe",
"4D",
"dataset"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_philips.py#L98-L114 | train | 233,617 |
icometrix/dicom2nifti | dicom2nifti/convert_philips.py | _is_singleframe_4d | def _is_singleframe_4d(dicom_input):
"""
Use this function to detect if a dicom series is a philips singleframe 4D dataset
"""
header = dicom_input[0]
# check if there are stack information
slice_number_mr_tag = Tag(0x2001, 0x100a)
if slice_number_mr_tag not in header:
return False
# check if there are multiple timepoints
grouped_dicoms = _get_grouped_dicoms(dicom_input)
if len(grouped_dicoms) <= 1:
return False
return True | python | def _is_singleframe_4d(dicom_input):
"""
Use this function to detect if a dicom series is a philips singleframe 4D dataset
"""
header = dicom_input[0]
# check if there are stack information
slice_number_mr_tag = Tag(0x2001, 0x100a)
if slice_number_mr_tag not in header:
return False
# check if there are multiple timepoints
grouped_dicoms = _get_grouped_dicoms(dicom_input)
if len(grouped_dicoms) <= 1:
return False
return True | [
"def",
"_is_singleframe_4d",
"(",
"dicom_input",
")",
":",
"header",
"=",
"dicom_input",
"[",
"0",
"]",
"# check if there are stack information",
"slice_number_mr_tag",
"=",
"Tag",
"(",
"0x2001",
",",
"0x100a",
")",
"if",
"slice_number_mr_tag",
"not",
"in",
"header",
":",
"return",
"False",
"# check if there are multiple timepoints",
"grouped_dicoms",
"=",
"_get_grouped_dicoms",
"(",
"dicom_input",
")",
"if",
"len",
"(",
"grouped_dicoms",
")",
"<=",
"1",
":",
"return",
"False",
"return",
"True"
] | Use this function to detect if a dicom series is a philips singleframe 4D dataset | [
"Use",
"this",
"function",
"to",
"detect",
"if",
"a",
"dicom",
"series",
"is",
"a",
"philips",
"singleframe",
"4D",
"dataset"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_philips.py#L139-L155 | train | 233,618 |
icometrix/dicom2nifti | dicom2nifti/convert_philips.py | _is_bval_type_a | def _is_bval_type_a(grouped_dicoms):
"""
Check if the bvals are stored in the first of 2 currently known ways for single frame dti
"""
bval_tag = Tag(0x2001, 0x1003)
bvec_x_tag = Tag(0x2005, 0x10b0)
bvec_y_tag = Tag(0x2005, 0x10b1)
bvec_z_tag = Tag(0x2005, 0x10b2)
for group in grouped_dicoms:
if bvec_x_tag in group[0] and _is_float(common.get_fl_value(group[0][bvec_x_tag])) and \
bvec_y_tag in group[0] and _is_float(common.get_fl_value(group[0][bvec_y_tag])) and \
bvec_z_tag in group[0] and _is_float(common.get_fl_value(group[0][bvec_z_tag])) and \
bval_tag in group[0] and _is_float(common.get_fl_value(group[0][bval_tag])) and \
common.get_fl_value(group[0][bval_tag]) != 0:
return True
return False | python | def _is_bval_type_a(grouped_dicoms):
"""
Check if the bvals are stored in the first of 2 currently known ways for single frame dti
"""
bval_tag = Tag(0x2001, 0x1003)
bvec_x_tag = Tag(0x2005, 0x10b0)
bvec_y_tag = Tag(0x2005, 0x10b1)
bvec_z_tag = Tag(0x2005, 0x10b2)
for group in grouped_dicoms:
if bvec_x_tag in group[0] and _is_float(common.get_fl_value(group[0][bvec_x_tag])) and \
bvec_y_tag in group[0] and _is_float(common.get_fl_value(group[0][bvec_y_tag])) and \
bvec_z_tag in group[0] and _is_float(common.get_fl_value(group[0][bvec_z_tag])) and \
bval_tag in group[0] and _is_float(common.get_fl_value(group[0][bval_tag])) and \
common.get_fl_value(group[0][bval_tag]) != 0:
return True
return False | [
"def",
"_is_bval_type_a",
"(",
"grouped_dicoms",
")",
":",
"bval_tag",
"=",
"Tag",
"(",
"0x2001",
",",
"0x1003",
")",
"bvec_x_tag",
"=",
"Tag",
"(",
"0x2005",
",",
"0x10b0",
")",
"bvec_y_tag",
"=",
"Tag",
"(",
"0x2005",
",",
"0x10b1",
")",
"bvec_z_tag",
"=",
"Tag",
"(",
"0x2005",
",",
"0x10b2",
")",
"for",
"group",
"in",
"grouped_dicoms",
":",
"if",
"bvec_x_tag",
"in",
"group",
"[",
"0",
"]",
"and",
"_is_float",
"(",
"common",
".",
"get_fl_value",
"(",
"group",
"[",
"0",
"]",
"[",
"bvec_x_tag",
"]",
")",
")",
"and",
"bvec_y_tag",
"in",
"group",
"[",
"0",
"]",
"and",
"_is_float",
"(",
"common",
".",
"get_fl_value",
"(",
"group",
"[",
"0",
"]",
"[",
"bvec_y_tag",
"]",
")",
")",
"and",
"bvec_z_tag",
"in",
"group",
"[",
"0",
"]",
"and",
"_is_float",
"(",
"common",
".",
"get_fl_value",
"(",
"group",
"[",
"0",
"]",
"[",
"bvec_z_tag",
"]",
")",
")",
"and",
"bval_tag",
"in",
"group",
"[",
"0",
"]",
"and",
"_is_float",
"(",
"common",
".",
"get_fl_value",
"(",
"group",
"[",
"0",
"]",
"[",
"bval_tag",
"]",
")",
")",
"and",
"common",
".",
"get_fl_value",
"(",
"group",
"[",
"0",
"]",
"[",
"bval_tag",
"]",
")",
"!=",
"0",
":",
"return",
"True",
"return",
"False"
] | Check if the bvals are stored in the first of 2 currently known ways for single frame dti | [
"Check",
"if",
"the",
"bvals",
"are",
"stored",
"in",
"the",
"first",
"of",
"2",
"currently",
"known",
"ways",
"for",
"single",
"frame",
"dti"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_philips.py#L172-L187 | train | 233,619 |
icometrix/dicom2nifti | dicom2nifti/convert_philips.py | _is_bval_type_b | def _is_bval_type_b(grouped_dicoms):
"""
Check if the bvals are stored in the second of 2 currently known ways for single frame dti
"""
bval_tag = Tag(0x0018, 0x9087)
bvec_tag = Tag(0x0018, 0x9089)
for group in grouped_dicoms:
if bvec_tag in group[0] and bval_tag in group[0]:
bvec = common.get_fd_array_value(group[0][bvec_tag], 3)
bval = common.get_fd_value(group[0][bval_tag])
if _is_float(bvec[0]) and _is_float(bvec[1]) and _is_float(bvec[2]) and _is_float(bval) and bval != 0:
return True
return False | python | def _is_bval_type_b(grouped_dicoms):
"""
Check if the bvals are stored in the second of 2 currently known ways for single frame dti
"""
bval_tag = Tag(0x0018, 0x9087)
bvec_tag = Tag(0x0018, 0x9089)
for group in grouped_dicoms:
if bvec_tag in group[0] and bval_tag in group[0]:
bvec = common.get_fd_array_value(group[0][bvec_tag], 3)
bval = common.get_fd_value(group[0][bval_tag])
if _is_float(bvec[0]) and _is_float(bvec[1]) and _is_float(bvec[2]) and _is_float(bval) and bval != 0:
return True
return False | [
"def",
"_is_bval_type_b",
"(",
"grouped_dicoms",
")",
":",
"bval_tag",
"=",
"Tag",
"(",
"0x0018",
",",
"0x9087",
")",
"bvec_tag",
"=",
"Tag",
"(",
"0x0018",
",",
"0x9089",
")",
"for",
"group",
"in",
"grouped_dicoms",
":",
"if",
"bvec_tag",
"in",
"group",
"[",
"0",
"]",
"and",
"bval_tag",
"in",
"group",
"[",
"0",
"]",
":",
"bvec",
"=",
"common",
".",
"get_fd_array_value",
"(",
"group",
"[",
"0",
"]",
"[",
"bvec_tag",
"]",
",",
"3",
")",
"bval",
"=",
"common",
".",
"get_fd_value",
"(",
"group",
"[",
"0",
"]",
"[",
"bval_tag",
"]",
")",
"if",
"_is_float",
"(",
"bvec",
"[",
"0",
"]",
")",
"and",
"_is_float",
"(",
"bvec",
"[",
"1",
"]",
")",
"and",
"_is_float",
"(",
"bvec",
"[",
"2",
"]",
")",
"and",
"_is_float",
"(",
"bval",
")",
"and",
"bval",
"!=",
"0",
":",
"return",
"True",
"return",
"False"
] | Check if the bvals are stored in the second of 2 currently known ways for single frame dti | [
"Check",
"if",
"the",
"bvals",
"are",
"stored",
"in",
"the",
"second",
"of",
"2",
"currently",
"known",
"ways",
"for",
"single",
"frame",
"dti"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_philips.py#L190-L202 | train | 233,620 |
icometrix/dicom2nifti | dicom2nifti/convert_philips.py | _multiframe_to_nifti | def _multiframe_to_nifti(dicom_input, output_file):
"""
This function will convert philips 4D or anatomical multiframe series to a nifti
"""
# Read the multiframe dicom file
logger.info('Read dicom file')
multiframe_dicom = dicom_input[0]
# Create mosaic block
logger.info('Creating data block')
full_block = _multiframe_to_block(multiframe_dicom)
logger.info('Creating affine')
# Create the nifti header info
affine = _create_affine_multiframe(multiframe_dicom)
logger.info('Creating nifti')
# Convert to nifti
nii_image = nibabel.Nifti1Image(full_block, affine)
timing_parameters = multiframe_dicom.SharedFunctionalGroupsSequence[0].MRTimingAndRelatedParametersSequence[0]
first_frame = multiframe_dicom[Tag(0x5200, 0x9230)][0]
common.set_tr_te(nii_image, float(timing_parameters.RepetitionTime),
float(first_frame[0x2005, 0x140f][0].EchoTime))
# Save to disk
if output_file is not None:
logger.info('Saving nifti to disk %s' % output_file)
nii_image.to_filename(output_file)
if _is_multiframe_diffusion_imaging(dicom_input):
bval_file = None
bvec_file = None
if output_file is not None:
# Create the bval en bvec files
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, bval_file, bvec_file = _create_bvals_bvecs(multiframe_dicom, bval_file, bvec_file, nii_image,
output_file)
return {'NII_FILE': output_file,
'BVAL_FILE': bval_file,
'BVEC_FILE': bvec_file,
'NII': nii_image,
'BVAL': bval,
'BVEC': bvec}
return {'NII_FILE': output_file,
'NII': nii_image} | python | def _multiframe_to_nifti(dicom_input, output_file):
"""
This function will convert philips 4D or anatomical multiframe series to a nifti
"""
# Read the multiframe dicom file
logger.info('Read dicom file')
multiframe_dicom = dicom_input[0]
# Create mosaic block
logger.info('Creating data block')
full_block = _multiframe_to_block(multiframe_dicom)
logger.info('Creating affine')
# Create the nifti header info
affine = _create_affine_multiframe(multiframe_dicom)
logger.info('Creating nifti')
# Convert to nifti
nii_image = nibabel.Nifti1Image(full_block, affine)
timing_parameters = multiframe_dicom.SharedFunctionalGroupsSequence[0].MRTimingAndRelatedParametersSequence[0]
first_frame = multiframe_dicom[Tag(0x5200, 0x9230)][0]
common.set_tr_te(nii_image, float(timing_parameters.RepetitionTime),
float(first_frame[0x2005, 0x140f][0].EchoTime))
# Save to disk
if output_file is not None:
logger.info('Saving nifti to disk %s' % output_file)
nii_image.to_filename(output_file)
if _is_multiframe_diffusion_imaging(dicom_input):
bval_file = None
bvec_file = None
if output_file is not None:
# Create the bval en bvec files
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, bval_file, bvec_file = _create_bvals_bvecs(multiframe_dicom, bval_file, bvec_file, nii_image,
output_file)
return {'NII_FILE': output_file,
'BVAL_FILE': bval_file,
'BVEC_FILE': bvec_file,
'NII': nii_image,
'BVAL': bval,
'BVEC': bvec}
return {'NII_FILE': output_file,
'NII': nii_image} | [
"def",
"_multiframe_to_nifti",
"(",
"dicom_input",
",",
"output_file",
")",
":",
"# Read the multiframe dicom file",
"logger",
".",
"info",
"(",
"'Read dicom file'",
")",
"multiframe_dicom",
"=",
"dicom_input",
"[",
"0",
"]",
"# Create mosaic block",
"logger",
".",
"info",
"(",
"'Creating data block'",
")",
"full_block",
"=",
"_multiframe_to_block",
"(",
"multiframe_dicom",
")",
"logger",
".",
"info",
"(",
"'Creating affine'",
")",
"# Create the nifti header info",
"affine",
"=",
"_create_affine_multiframe",
"(",
"multiframe_dicom",
")",
"logger",
".",
"info",
"(",
"'Creating nifti'",
")",
"# Convert to nifti",
"nii_image",
"=",
"nibabel",
".",
"Nifti1Image",
"(",
"full_block",
",",
"affine",
")",
"timing_parameters",
"=",
"multiframe_dicom",
".",
"SharedFunctionalGroupsSequence",
"[",
"0",
"]",
".",
"MRTimingAndRelatedParametersSequence",
"[",
"0",
"]",
"first_frame",
"=",
"multiframe_dicom",
"[",
"Tag",
"(",
"0x5200",
",",
"0x9230",
")",
"]",
"[",
"0",
"]",
"common",
".",
"set_tr_te",
"(",
"nii_image",
",",
"float",
"(",
"timing_parameters",
".",
"RepetitionTime",
")",
",",
"float",
"(",
"first_frame",
"[",
"0x2005",
",",
"0x140f",
"]",
"[",
"0",
"]",
".",
"EchoTime",
")",
")",
"# Save to disk",
"if",
"output_file",
"is",
"not",
"None",
":",
"logger",
".",
"info",
"(",
"'Saving nifti to disk %s'",
"%",
"output_file",
")",
"nii_image",
".",
"to_filename",
"(",
"output_file",
")",
"if",
"_is_multiframe_diffusion_imaging",
"(",
"dicom_input",
")",
":",
"bval_file",
"=",
"None",
"bvec_file",
"=",
"None",
"if",
"output_file",
"is",
"not",
"None",
":",
"# Create the bval en bvec files",
"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",
",",
"bval_file",
",",
"bvec_file",
"=",
"_create_bvals_bvecs",
"(",
"multiframe_dicom",
",",
"bval_file",
",",
"bvec_file",
",",
"nii_image",
",",
"output_file",
")",
"return",
"{",
"'NII_FILE'",
":",
"output_file",
",",
"'BVAL_FILE'",
":",
"bval_file",
",",
"'BVEC_FILE'",
":",
"bvec_file",
",",
"'NII'",
":",
"nii_image",
",",
"'BVAL'",
":",
"bval",
",",
"'BVEC'",
":",
"bvec",
"}",
"return",
"{",
"'NII_FILE'",
":",
"output_file",
",",
"'NII'",
":",
"nii_image",
"}"
] | This function will convert philips 4D or anatomical multiframe series to a nifti | [
"This",
"function",
"will",
"convert",
"philips",
"4D",
"or",
"anatomical",
"multiframe",
"series",
"to",
"a",
"nifti"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_philips.py#L216-L268 | train | 233,621 |
icometrix/dicom2nifti | dicom2nifti/convert_philips.py | _singleframe_to_nifti | def _singleframe_to_nifti(grouped_dicoms, output_file):
"""
This function will convert a philips singleframe series to a nifti
"""
# Create mosaic block
logger.info('Creating data block')
full_block = _singleframe_to_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))
if output_file is not None:
# Save to disk
logger.info('Saving nifti to disk %s' % output_file)
nii_image.to_filename(output_file)
if _is_singleframe_diffusion_imaging(grouped_dicoms):
bval_file = None
bvec_file = None
# Create the bval en bvec files
if output_file is not None:
base_name = os.path.splitext(output_file)[0]
if base_name.endswith('.nii'):
base_name = os.path.splitext(base_name)[0]
logger.info('Creating bval en bvec files')
bval_file = '%s.bval' % base_name
bvec_file = '%s.bvec' % base_name
nii_image, bval, bvec, bval_file, bvec_file = _create_singleframe_bvals_bvecs(grouped_dicoms,
bval_file,
bvec_file,
nii_image,
output_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 _singleframe_to_nifti(grouped_dicoms, output_file):
"""
This function will convert a philips singleframe series to a nifti
"""
# Create mosaic block
logger.info('Creating data block')
full_block = _singleframe_to_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))
if output_file is not None:
# Save to disk
logger.info('Saving nifti to disk %s' % output_file)
nii_image.to_filename(output_file)
if _is_singleframe_diffusion_imaging(grouped_dicoms):
bval_file = None
bvec_file = None
# Create the bval en bvec files
if output_file is not None:
base_name = os.path.splitext(output_file)[0]
if base_name.endswith('.nii'):
base_name = os.path.splitext(base_name)[0]
logger.info('Creating bval en bvec files')
bval_file = '%s.bval' % base_name
bvec_file = '%s.bvec' % base_name
nii_image, bval, bvec, bval_file, bvec_file = _create_singleframe_bvals_bvecs(grouped_dicoms,
bval_file,
bvec_file,
nii_image,
output_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",
"_singleframe_to_nifti",
"(",
"grouped_dicoms",
",",
"output_file",
")",
":",
"# Create mosaic block",
"logger",
".",
"info",
"(",
"'Creating data block'",
")",
"full_block",
"=",
"_singleframe_to_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",
")",
")",
"if",
"output_file",
"is",
"not",
"None",
":",
"# Save to disk",
"logger",
".",
"info",
"(",
"'Saving nifti to disk %s'",
"%",
"output_file",
")",
"nii_image",
".",
"to_filename",
"(",
"output_file",
")",
"if",
"_is_singleframe_diffusion_imaging",
"(",
"grouped_dicoms",
")",
":",
"bval_file",
"=",
"None",
"bvec_file",
"=",
"None",
"# Create the bval en bvec files",
"if",
"output_file",
"is",
"not",
"None",
":",
"base_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"output_file",
")",
"[",
"0",
"]",
"if",
"base_name",
".",
"endswith",
"(",
"'.nii'",
")",
":",
"base_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"base_name",
")",
"[",
"0",
"]",
"logger",
".",
"info",
"(",
"'Creating bval en bvec files'",
")",
"bval_file",
"=",
"'%s.bval'",
"%",
"base_name",
"bvec_file",
"=",
"'%s.bvec'",
"%",
"base_name",
"nii_image",
",",
"bval",
",",
"bvec",
",",
"bval_file",
",",
"bvec_file",
"=",
"_create_singleframe_bvals_bvecs",
"(",
"grouped_dicoms",
",",
"bval_file",
",",
"bvec_file",
",",
"nii_image",
",",
"output_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 a philips singleframe series to a nifti | [
"This",
"function",
"will",
"convert",
"a",
"philips",
"singleframe",
"series",
"to",
"a",
"nifti"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_philips.py#L271-L322 | train | 233,622 |
icometrix/dicom2nifti | dicom2nifti/convert_philips.py | _create_affine_multiframe | def _create_affine_multiframe(multiframe_dicom):
"""
Function to create the affine matrix for a siemens mosaic dataset
This will work for siemens dti and 4D if in mosaic format
"""
first_frame = multiframe_dicom[Tag(0x5200, 0x9230)][0]
last_frame = multiframe_dicom[Tag(0x5200, 0x9230)][-1]
# Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine)
image_orient1 = numpy.array(first_frame.PlaneOrientationSequence[0].ImageOrientationPatient)[0:3].astype(float)
image_orient2 = numpy.array(first_frame.PlaneOrientationSequence[0].ImageOrientationPatient)[3:6].astype(float)
normal = numpy.cross(image_orient1, image_orient2)
delta_r = float(first_frame[0x2005, 0x140f][0].PixelSpacing[0])
delta_c = float(first_frame[0x2005, 0x140f][0].PixelSpacing[1])
image_pos = numpy.array(first_frame.PlanePositionSequence[0].ImagePositionPatient).astype(float)
last_image_pos = numpy.array(last_frame.PlanePositionSequence[0].ImagePositionPatient).astype(float)
number_of_stack_slices = int(common.get_ss_value(multiframe_dicom[Tag(0x2001, 0x105f)][0][Tag(0x2001, 0x102d)]))
delta_s = abs(numpy.linalg.norm(last_image_pos - image_pos)) / (number_of_stack_slices - 1)
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_multiframe(multiframe_dicom):
"""
Function to create the affine matrix for a siemens mosaic dataset
This will work for siemens dti and 4D if in mosaic format
"""
first_frame = multiframe_dicom[Tag(0x5200, 0x9230)][0]
last_frame = multiframe_dicom[Tag(0x5200, 0x9230)][-1]
# Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine)
image_orient1 = numpy.array(first_frame.PlaneOrientationSequence[0].ImageOrientationPatient)[0:3].astype(float)
image_orient2 = numpy.array(first_frame.PlaneOrientationSequence[0].ImageOrientationPatient)[3:6].astype(float)
normal = numpy.cross(image_orient1, image_orient2)
delta_r = float(first_frame[0x2005, 0x140f][0].PixelSpacing[0])
delta_c = float(first_frame[0x2005, 0x140f][0].PixelSpacing[1])
image_pos = numpy.array(first_frame.PlanePositionSequence[0].ImagePositionPatient).astype(float)
last_image_pos = numpy.array(last_frame.PlanePositionSequence[0].ImagePositionPatient).astype(float)
number_of_stack_slices = int(common.get_ss_value(multiframe_dicom[Tag(0x2001, 0x105f)][0][Tag(0x2001, 0x102d)]))
delta_s = abs(numpy.linalg.norm(last_image_pos - image_pos)) / (number_of_stack_slices - 1)
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_multiframe",
"(",
"multiframe_dicom",
")",
":",
"first_frame",
"=",
"multiframe_dicom",
"[",
"Tag",
"(",
"0x5200",
",",
"0x9230",
")",
"]",
"[",
"0",
"]",
"last_frame",
"=",
"multiframe_dicom",
"[",
"Tag",
"(",
"0x5200",
",",
"0x9230",
")",
"]",
"[",
"-",
"1",
"]",
"# Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine)",
"image_orient1",
"=",
"numpy",
".",
"array",
"(",
"first_frame",
".",
"PlaneOrientationSequence",
"[",
"0",
"]",
".",
"ImageOrientationPatient",
")",
"[",
"0",
":",
"3",
"]",
".",
"astype",
"(",
"float",
")",
"image_orient2",
"=",
"numpy",
".",
"array",
"(",
"first_frame",
".",
"PlaneOrientationSequence",
"[",
"0",
"]",
".",
"ImageOrientationPatient",
")",
"[",
"3",
":",
"6",
"]",
".",
"astype",
"(",
"float",
")",
"normal",
"=",
"numpy",
".",
"cross",
"(",
"image_orient1",
",",
"image_orient2",
")",
"delta_r",
"=",
"float",
"(",
"first_frame",
"[",
"0x2005",
",",
"0x140f",
"]",
"[",
"0",
"]",
".",
"PixelSpacing",
"[",
"0",
"]",
")",
"delta_c",
"=",
"float",
"(",
"first_frame",
"[",
"0x2005",
",",
"0x140f",
"]",
"[",
"0",
"]",
".",
"PixelSpacing",
"[",
"1",
"]",
")",
"image_pos",
"=",
"numpy",
".",
"array",
"(",
"first_frame",
".",
"PlanePositionSequence",
"[",
"0",
"]",
".",
"ImagePositionPatient",
")",
".",
"astype",
"(",
"float",
")",
"last_image_pos",
"=",
"numpy",
".",
"array",
"(",
"last_frame",
".",
"PlanePositionSequence",
"[",
"0",
"]",
".",
"ImagePositionPatient",
")",
".",
"astype",
"(",
"float",
")",
"number_of_stack_slices",
"=",
"int",
"(",
"common",
".",
"get_ss_value",
"(",
"multiframe_dicom",
"[",
"Tag",
"(",
"0x2001",
",",
"0x105f",
")",
"]",
"[",
"0",
"]",
"[",
"Tag",
"(",
"0x2001",
",",
"0x102d",
")",
"]",
")",
")",
"delta_s",
"=",
"abs",
"(",
"numpy",
".",
"linalg",
".",
"norm",
"(",
"last_image_pos",
"-",
"image_pos",
")",
")",
"/",
"(",
"number_of_stack_slices",
"-",
"1",
")",
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_philips.py#L393-L419 | train | 233,623 |
icometrix/dicom2nifti | dicom2nifti/convert_philips.py | _multiframe_to_block | def _multiframe_to_block(multiframe_dicom):
"""
Generate a full datablock containing all stacks
"""
# Calculate the amount of stacks and slices in the stack
number_of_stack_slices = int(common.get_ss_value(multiframe_dicom[Tag(0x2001, 0x105f)][0][Tag(0x2001, 0x102d)]))
number_of_stacks = int(int(multiframe_dicom.NumberOfFrames) / number_of_stack_slices)
# We create a numpy array
size_x = multiframe_dicom.pixel_array.shape[2]
size_y = multiframe_dicom.pixel_array.shape[1]
size_z = number_of_stack_slices
size_t = number_of_stacks
# get the format
format_string = common.get_numpy_type(multiframe_dicom)
# get header info needed for ordering
frame_info = multiframe_dicom[0x5200, 0x9230]
data_4d = numpy.zeros((size_z, size_y, size_x, size_t), dtype=format_string)
# loop over each slice and insert in datablock
t_location_index = _get_t_position_index(multiframe_dicom)
for slice_index in range(0, size_t * size_z):
z_location = frame_info[slice_index].FrameContentSequence[0].InStackPositionNumber - 1
if t_location_index is None:
t_location = frame_info[slice_index].FrameContentSequence[0].TemporalPositionIndex - 1
else:
t_location = frame_info[slice_index].FrameContentSequence[0].DimensionIndexValues[t_location_index] - 1
block_data = multiframe_dicom.pixel_array[slice_index, :, :]
# apply scaling
rescale_intercept = frame_info[slice_index].PixelValueTransformationSequence[0].RescaleIntercept
rescale_slope = frame_info[slice_index].PixelValueTransformationSequence[0].RescaleSlope
block_data = common.do_scaling(block_data,
rescale_slope, rescale_intercept)
# switch to float if needed
if block_data.dtype != data_4d.dtype:
data_4d = data_4d.astype(block_data.dtype)
data_4d[z_location, :, :, t_location] = block_data
full_block = numpy.zeros((size_x, size_y, size_z, size_t), dtype=data_4d.dtype)
# loop over each stack and reorganize the data
for t_index in range(0, size_t):
# transpose the block so the directions are correct
data_3d = numpy.transpose(data_4d[:, :, :, t_index], (2, 1, 0))
# add the block the the full data
full_block[:, :, :, t_index] = data_3d
return full_block | python | def _multiframe_to_block(multiframe_dicom):
"""
Generate a full datablock containing all stacks
"""
# Calculate the amount of stacks and slices in the stack
number_of_stack_slices = int(common.get_ss_value(multiframe_dicom[Tag(0x2001, 0x105f)][0][Tag(0x2001, 0x102d)]))
number_of_stacks = int(int(multiframe_dicom.NumberOfFrames) / number_of_stack_slices)
# We create a numpy array
size_x = multiframe_dicom.pixel_array.shape[2]
size_y = multiframe_dicom.pixel_array.shape[1]
size_z = number_of_stack_slices
size_t = number_of_stacks
# get the format
format_string = common.get_numpy_type(multiframe_dicom)
# get header info needed for ordering
frame_info = multiframe_dicom[0x5200, 0x9230]
data_4d = numpy.zeros((size_z, size_y, size_x, size_t), dtype=format_string)
# loop over each slice and insert in datablock
t_location_index = _get_t_position_index(multiframe_dicom)
for slice_index in range(0, size_t * size_z):
z_location = frame_info[slice_index].FrameContentSequence[0].InStackPositionNumber - 1
if t_location_index is None:
t_location = frame_info[slice_index].FrameContentSequence[0].TemporalPositionIndex - 1
else:
t_location = frame_info[slice_index].FrameContentSequence[0].DimensionIndexValues[t_location_index] - 1
block_data = multiframe_dicom.pixel_array[slice_index, :, :]
# apply scaling
rescale_intercept = frame_info[slice_index].PixelValueTransformationSequence[0].RescaleIntercept
rescale_slope = frame_info[slice_index].PixelValueTransformationSequence[0].RescaleSlope
block_data = common.do_scaling(block_data,
rescale_slope, rescale_intercept)
# switch to float if needed
if block_data.dtype != data_4d.dtype:
data_4d = data_4d.astype(block_data.dtype)
data_4d[z_location, :, :, t_location] = block_data
full_block = numpy.zeros((size_x, size_y, size_z, size_t), dtype=data_4d.dtype)
# loop over each stack and reorganize the data
for t_index in range(0, size_t):
# transpose the block so the directions are correct
data_3d = numpy.transpose(data_4d[:, :, :, t_index], (2, 1, 0))
# add the block the the full data
full_block[:, :, :, t_index] = data_3d
return full_block | [
"def",
"_multiframe_to_block",
"(",
"multiframe_dicom",
")",
":",
"# Calculate the amount of stacks and slices in the stack",
"number_of_stack_slices",
"=",
"int",
"(",
"common",
".",
"get_ss_value",
"(",
"multiframe_dicom",
"[",
"Tag",
"(",
"0x2001",
",",
"0x105f",
")",
"]",
"[",
"0",
"]",
"[",
"Tag",
"(",
"0x2001",
",",
"0x102d",
")",
"]",
")",
")",
"number_of_stacks",
"=",
"int",
"(",
"int",
"(",
"multiframe_dicom",
".",
"NumberOfFrames",
")",
"/",
"number_of_stack_slices",
")",
"# We create a numpy array",
"size_x",
"=",
"multiframe_dicom",
".",
"pixel_array",
".",
"shape",
"[",
"2",
"]",
"size_y",
"=",
"multiframe_dicom",
".",
"pixel_array",
".",
"shape",
"[",
"1",
"]",
"size_z",
"=",
"number_of_stack_slices",
"size_t",
"=",
"number_of_stacks",
"# get the format",
"format_string",
"=",
"common",
".",
"get_numpy_type",
"(",
"multiframe_dicom",
")",
"# get header info needed for ordering",
"frame_info",
"=",
"multiframe_dicom",
"[",
"0x5200",
",",
"0x9230",
"]",
"data_4d",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"size_z",
",",
"size_y",
",",
"size_x",
",",
"size_t",
")",
",",
"dtype",
"=",
"format_string",
")",
"# loop over each slice and insert in datablock",
"t_location_index",
"=",
"_get_t_position_index",
"(",
"multiframe_dicom",
")",
"for",
"slice_index",
"in",
"range",
"(",
"0",
",",
"size_t",
"*",
"size_z",
")",
":",
"z_location",
"=",
"frame_info",
"[",
"slice_index",
"]",
".",
"FrameContentSequence",
"[",
"0",
"]",
".",
"InStackPositionNumber",
"-",
"1",
"if",
"t_location_index",
"is",
"None",
":",
"t_location",
"=",
"frame_info",
"[",
"slice_index",
"]",
".",
"FrameContentSequence",
"[",
"0",
"]",
".",
"TemporalPositionIndex",
"-",
"1",
"else",
":",
"t_location",
"=",
"frame_info",
"[",
"slice_index",
"]",
".",
"FrameContentSequence",
"[",
"0",
"]",
".",
"DimensionIndexValues",
"[",
"t_location_index",
"]",
"-",
"1",
"block_data",
"=",
"multiframe_dicom",
".",
"pixel_array",
"[",
"slice_index",
",",
":",
",",
":",
"]",
"# apply scaling",
"rescale_intercept",
"=",
"frame_info",
"[",
"slice_index",
"]",
".",
"PixelValueTransformationSequence",
"[",
"0",
"]",
".",
"RescaleIntercept",
"rescale_slope",
"=",
"frame_info",
"[",
"slice_index",
"]",
".",
"PixelValueTransformationSequence",
"[",
"0",
"]",
".",
"RescaleSlope",
"block_data",
"=",
"common",
".",
"do_scaling",
"(",
"block_data",
",",
"rescale_slope",
",",
"rescale_intercept",
")",
"# switch to float if needed",
"if",
"block_data",
".",
"dtype",
"!=",
"data_4d",
".",
"dtype",
":",
"data_4d",
"=",
"data_4d",
".",
"astype",
"(",
"block_data",
".",
"dtype",
")",
"data_4d",
"[",
"z_location",
",",
":",
",",
":",
",",
"t_location",
"]",
"=",
"block_data",
"full_block",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"size_x",
",",
"size_y",
",",
"size_z",
",",
"size_t",
")",
",",
"dtype",
"=",
"data_4d",
".",
"dtype",
")",
"# loop over each stack and reorganize the data",
"for",
"t_index",
"in",
"range",
"(",
"0",
",",
"size_t",
")",
":",
"# transpose the block so the directions are correct",
"data_3d",
"=",
"numpy",
".",
"transpose",
"(",
"data_4d",
"[",
":",
",",
":",
",",
":",
",",
"t_index",
"]",
",",
"(",
"2",
",",
"1",
",",
"0",
")",
")",
"# add the block the the full data",
"full_block",
"[",
":",
",",
":",
",",
":",
",",
"t_index",
"]",
"=",
"data_3d",
"return",
"full_block"
] | Generate a full datablock containing all stacks | [
"Generate",
"a",
"full",
"datablock",
"containing",
"all",
"stacks"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_philips.py#L422-L473 | train | 233,624 |
icometrix/dicom2nifti | dicom2nifti/convert_philips.py | _fix_diffusion_images | def _fix_diffusion_images(bvals, bvecs, nifti, nifti_file):
"""
This function will remove the last timepoint from the nifti, bvals and bvecs if the last vector is 0,0,0
This is sometimes added at the end by philips
"""
# if all zero continue of if the last bvec is not all zero continue
if numpy.count_nonzero(bvecs) == 0 or not numpy.count_nonzero(bvals[-1]) == 0:
# nothing needs to be done here
return nifti, bvals, bvecs
# remove last elements from bvals and bvecs
bvals = bvals[:-1]
bvecs = bvecs[:-1]
# remove last elements from the nifti
new_nifti = nibabel.Nifti1Image(nifti.get_data()[:, :, :, :-1], nifti.affine)
new_nifti.to_filename(nifti_file)
return new_nifti, bvals, bvecs | python | def _fix_diffusion_images(bvals, bvecs, nifti, nifti_file):
"""
This function will remove the last timepoint from the nifti, bvals and bvecs if the last vector is 0,0,0
This is sometimes added at the end by philips
"""
# if all zero continue of if the last bvec is not all zero continue
if numpy.count_nonzero(bvecs) == 0 or not numpy.count_nonzero(bvals[-1]) == 0:
# nothing needs to be done here
return nifti, bvals, bvecs
# remove last elements from bvals and bvecs
bvals = bvals[:-1]
bvecs = bvecs[:-1]
# remove last elements from the nifti
new_nifti = nibabel.Nifti1Image(nifti.get_data()[:, :, :, :-1], nifti.affine)
new_nifti.to_filename(nifti_file)
return new_nifti, bvals, bvecs | [
"def",
"_fix_diffusion_images",
"(",
"bvals",
",",
"bvecs",
",",
"nifti",
",",
"nifti_file",
")",
":",
"# if all zero continue of if the last bvec is not all zero continue",
"if",
"numpy",
".",
"count_nonzero",
"(",
"bvecs",
")",
"==",
"0",
"or",
"not",
"numpy",
".",
"count_nonzero",
"(",
"bvals",
"[",
"-",
"1",
"]",
")",
"==",
"0",
":",
"# nothing needs to be done here",
"return",
"nifti",
",",
"bvals",
",",
"bvecs",
"# remove last elements from bvals and bvecs",
"bvals",
"=",
"bvals",
"[",
":",
"-",
"1",
"]",
"bvecs",
"=",
"bvecs",
"[",
":",
"-",
"1",
"]",
"# remove last elements from the nifti",
"new_nifti",
"=",
"nibabel",
".",
"Nifti1Image",
"(",
"nifti",
".",
"get_data",
"(",
")",
"[",
":",
",",
":",
",",
":",
",",
":",
"-",
"1",
"]",
",",
"nifti",
".",
"affine",
")",
"new_nifti",
".",
"to_filename",
"(",
"nifti_file",
")",
"return",
"new_nifti",
",",
"bvals",
",",
"bvecs"
] | This function will remove the last timepoint from the nifti, bvals and bvecs if the last vector is 0,0,0
This is sometimes added at the end by philips | [
"This",
"function",
"will",
"remove",
"the",
"last",
"timepoint",
"from",
"the",
"nifti",
"bvals",
"and",
"bvecs",
"if",
"the",
"last",
"vector",
"is",
"0",
"0",
"0",
"This",
"is",
"sometimes",
"added",
"at",
"the",
"end",
"by",
"philips"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_philips.py#L548-L565 | train | 233,625 |
icometrix/dicom2nifti | dicom2nifti/convert_generic.py | dicom_to_nifti | def dicom_to_nifti(dicom_input, output_file):
"""
This function will convert an anatomical dicom series to a nifti
Examples: See unit test
:param output_file: filepath to the output nifti
:param dicom_input: directory with the dicom files for a single scan, or list of read in dicoms
"""
if len(dicom_input) <= 0:
raise ConversionError('NO_DICOM_FILES_FOUND')
# remove duplicate slices based on position and data
dicom_input = _remove_duplicate_slices(dicom_input)
# remove localizers based on image type
dicom_input = _remove_localizers_by_imagetype(dicom_input)
if settings.validate_slicecount:
# remove_localizers based on image orientation (only valid if slicecount is validated)
dicom_input = _remove_localizers_by_orientation(dicom_input)
# validate all the dicom files for correct orientations
common.validate_slicecount(dicom_input)
if settings.validate_orientation:
# validate that all slices have the same orientation
common.validate_orientation(dicom_input)
if settings.validate_orthogonal:
# validate that we have an orthogonal image (to detect gantry tilting etc)
common.validate_orthogonal(dicom_input)
# sort the dicoms
dicom_input = common.sort_dicoms(dicom_input)
# validate slice increment inconsistent
slice_increment_inconsistent = False
if settings.validate_slice_increment:
# validate that all slices have a consistent slice increment
common.validate_slice_increment(dicom_input)
elif common.is_slice_increment_inconsistent(dicom_input):
slice_increment_inconsistent = True
# if inconsistent increment and we allow resampling then do the resampling based conversion to maintain the correct geometric shape
if slice_increment_inconsistent and settings.resample:
nii_image, max_slice_increment = _convert_slice_incement_inconsistencies(dicom_input)
# do the normal conversion
else:
# Get data; originally z,y,x, transposed to x,y,z
data = common.get_volume_pixeldata(dicom_input)
affine, max_slice_increment = common.create_affine(dicom_input)
# Convert to nifti
nii_image = nibabel.Nifti1Image(data, affine)
# Set TR and TE if available
if Tag(0x0018, 0x0081) in dicom_input[0] and Tag(0x0018, 0x0081) in dicom_input[0]:
common.set_tr_te(nii_image, float(dicom_input[0].RepetitionTime), float(dicom_input[0].EchoTime))
# Save to disk
if output_file is not None:
logger.info('Saving nifti to disk %s' % output_file)
nii_image.to_filename(output_file)
return {'NII_FILE': output_file,
'NII': nii_image,
'MAX_SLICE_INCREMENT': max_slice_increment} | python | def dicom_to_nifti(dicom_input, output_file):
"""
This function will convert an anatomical dicom series to a nifti
Examples: See unit test
:param output_file: filepath to the output nifti
:param dicom_input: directory with the dicom files for a single scan, or list of read in dicoms
"""
if len(dicom_input) <= 0:
raise ConversionError('NO_DICOM_FILES_FOUND')
# remove duplicate slices based on position and data
dicom_input = _remove_duplicate_slices(dicom_input)
# remove localizers based on image type
dicom_input = _remove_localizers_by_imagetype(dicom_input)
if settings.validate_slicecount:
# remove_localizers based on image orientation (only valid if slicecount is validated)
dicom_input = _remove_localizers_by_orientation(dicom_input)
# validate all the dicom files for correct orientations
common.validate_slicecount(dicom_input)
if settings.validate_orientation:
# validate that all slices have the same orientation
common.validate_orientation(dicom_input)
if settings.validate_orthogonal:
# validate that we have an orthogonal image (to detect gantry tilting etc)
common.validate_orthogonal(dicom_input)
# sort the dicoms
dicom_input = common.sort_dicoms(dicom_input)
# validate slice increment inconsistent
slice_increment_inconsistent = False
if settings.validate_slice_increment:
# validate that all slices have a consistent slice increment
common.validate_slice_increment(dicom_input)
elif common.is_slice_increment_inconsistent(dicom_input):
slice_increment_inconsistent = True
# if inconsistent increment and we allow resampling then do the resampling based conversion to maintain the correct geometric shape
if slice_increment_inconsistent and settings.resample:
nii_image, max_slice_increment = _convert_slice_incement_inconsistencies(dicom_input)
# do the normal conversion
else:
# Get data; originally z,y,x, transposed to x,y,z
data = common.get_volume_pixeldata(dicom_input)
affine, max_slice_increment = common.create_affine(dicom_input)
# Convert to nifti
nii_image = nibabel.Nifti1Image(data, affine)
# Set TR and TE if available
if Tag(0x0018, 0x0081) in dicom_input[0] and Tag(0x0018, 0x0081) in dicom_input[0]:
common.set_tr_te(nii_image, float(dicom_input[0].RepetitionTime), float(dicom_input[0].EchoTime))
# Save to disk
if output_file is not None:
logger.info('Saving nifti to disk %s' % output_file)
nii_image.to_filename(output_file)
return {'NII_FILE': output_file,
'NII': nii_image,
'MAX_SLICE_INCREMENT': max_slice_increment} | [
"def",
"dicom_to_nifti",
"(",
"dicom_input",
",",
"output_file",
")",
":",
"if",
"len",
"(",
"dicom_input",
")",
"<=",
"0",
":",
"raise",
"ConversionError",
"(",
"'NO_DICOM_FILES_FOUND'",
")",
"# remove duplicate slices based on position and data",
"dicom_input",
"=",
"_remove_duplicate_slices",
"(",
"dicom_input",
")",
"# remove localizers based on image type",
"dicom_input",
"=",
"_remove_localizers_by_imagetype",
"(",
"dicom_input",
")",
"if",
"settings",
".",
"validate_slicecount",
":",
"# remove_localizers based on image orientation (only valid if slicecount is validated)",
"dicom_input",
"=",
"_remove_localizers_by_orientation",
"(",
"dicom_input",
")",
"# validate all the dicom files for correct orientations",
"common",
".",
"validate_slicecount",
"(",
"dicom_input",
")",
"if",
"settings",
".",
"validate_orientation",
":",
"# validate that all slices have the same orientation",
"common",
".",
"validate_orientation",
"(",
"dicom_input",
")",
"if",
"settings",
".",
"validate_orthogonal",
":",
"# validate that we have an orthogonal image (to detect gantry tilting etc)",
"common",
".",
"validate_orthogonal",
"(",
"dicom_input",
")",
"# sort the dicoms",
"dicom_input",
"=",
"common",
".",
"sort_dicoms",
"(",
"dicom_input",
")",
"# validate slice increment inconsistent",
"slice_increment_inconsistent",
"=",
"False",
"if",
"settings",
".",
"validate_slice_increment",
":",
"# validate that all slices have a consistent slice increment",
"common",
".",
"validate_slice_increment",
"(",
"dicom_input",
")",
"elif",
"common",
".",
"is_slice_increment_inconsistent",
"(",
"dicom_input",
")",
":",
"slice_increment_inconsistent",
"=",
"True",
"# if inconsistent increment and we allow resampling then do the resampling based conversion to maintain the correct geometric shape",
"if",
"slice_increment_inconsistent",
"and",
"settings",
".",
"resample",
":",
"nii_image",
",",
"max_slice_increment",
"=",
"_convert_slice_incement_inconsistencies",
"(",
"dicom_input",
")",
"# do the normal conversion",
"else",
":",
"# Get data; originally z,y,x, transposed to x,y,z",
"data",
"=",
"common",
".",
"get_volume_pixeldata",
"(",
"dicom_input",
")",
"affine",
",",
"max_slice_increment",
"=",
"common",
".",
"create_affine",
"(",
"dicom_input",
")",
"# Convert to nifti",
"nii_image",
"=",
"nibabel",
".",
"Nifti1Image",
"(",
"data",
",",
"affine",
")",
"# Set TR and TE if available",
"if",
"Tag",
"(",
"0x0018",
",",
"0x0081",
")",
"in",
"dicom_input",
"[",
"0",
"]",
"and",
"Tag",
"(",
"0x0018",
",",
"0x0081",
")",
"in",
"dicom_input",
"[",
"0",
"]",
":",
"common",
".",
"set_tr_te",
"(",
"nii_image",
",",
"float",
"(",
"dicom_input",
"[",
"0",
"]",
".",
"RepetitionTime",
")",
",",
"float",
"(",
"dicom_input",
"[",
"0",
"]",
".",
"EchoTime",
")",
")",
"# Save to disk",
"if",
"output_file",
"is",
"not",
"None",
":",
"logger",
".",
"info",
"(",
"'Saving nifti to disk %s'",
"%",
"output_file",
")",
"nii_image",
".",
"to_filename",
"(",
"output_file",
")",
"return",
"{",
"'NII_FILE'",
":",
"output_file",
",",
"'NII'",
":",
"nii_image",
",",
"'MAX_SLICE_INCREMENT'",
":",
"max_slice_increment",
"}"
] | This function will convert an anatomical dicom series to a nifti
Examples: See unit test
:param output_file: filepath to the output nifti
:param dicom_input: directory with the dicom files for a single scan, or list of read in dicoms | [
"This",
"function",
"will",
"convert",
"an",
"anatomical",
"dicom",
"series",
"to",
"a",
"nifti"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_generic.py#L29-L94 | train | 233,626 |
icometrix/dicom2nifti | dicom2nifti/convert_generic.py | _convert_slice_incement_inconsistencies | def _convert_slice_incement_inconsistencies(dicom_input):
"""
If there is slice increment inconsistency detected, for the moment CT images, then split the volumes into subvolumes based on the slice increment and process each volume separately using a space constructed based on the highest resolution increment
"""
# Estimate the "first" slice increment based on the 2 first slices
increment = numpy.array(dicom_input[0].ImagePositionPatient) - numpy.array(dicom_input[1].ImagePositionPatient)
# Create as many volumes as many changes in slice increment. NB Increments might be repeated in different volumes
max_slice_increment = 0
slice_incement_groups = []
current_group = [dicom_input[0], dicom_input[1]]
previous_image_position = numpy.array(dicom_input[1].ImagePositionPatient)
for dicom in dicom_input[2:]:
current_image_position = numpy.array(dicom.ImagePositionPatient)
current_increment = previous_image_position - current_image_position
max_slice_increment = max(max_slice_increment, numpy.linalg.norm(current_increment))
if numpy.allclose(increment, current_increment, rtol=0.05, atol=0.1):
current_group.append(dicom)
if not numpy.allclose(increment, current_increment, rtol=0.05, atol=0.1):
slice_incement_groups.append(current_group)
current_group = [current_group[-1], dicom]
increment = current_increment
previous_image_position = current_image_position
slice_incement_groups.append(current_group)
# Create nibabel objects for each volume based on the corresponding headers
slice_incement_niftis = []
for dicom_slices in slice_incement_groups:
data = common.get_volume_pixeldata(dicom_slices)
affine, _ = common.create_affine(dicom_slices)
slice_incement_niftis.append(nibabel.Nifti1Image(data, affine))
nifti_volume = resample.resample_nifti_images(slice_incement_niftis)
return nifti_volume, max_slice_increment | python | def _convert_slice_incement_inconsistencies(dicom_input):
"""
If there is slice increment inconsistency detected, for the moment CT images, then split the volumes into subvolumes based on the slice increment and process each volume separately using a space constructed based on the highest resolution increment
"""
# Estimate the "first" slice increment based on the 2 first slices
increment = numpy.array(dicom_input[0].ImagePositionPatient) - numpy.array(dicom_input[1].ImagePositionPatient)
# Create as many volumes as many changes in slice increment. NB Increments might be repeated in different volumes
max_slice_increment = 0
slice_incement_groups = []
current_group = [dicom_input[0], dicom_input[1]]
previous_image_position = numpy.array(dicom_input[1].ImagePositionPatient)
for dicom in dicom_input[2:]:
current_image_position = numpy.array(dicom.ImagePositionPatient)
current_increment = previous_image_position - current_image_position
max_slice_increment = max(max_slice_increment, numpy.linalg.norm(current_increment))
if numpy.allclose(increment, current_increment, rtol=0.05, atol=0.1):
current_group.append(dicom)
if not numpy.allclose(increment, current_increment, rtol=0.05, atol=0.1):
slice_incement_groups.append(current_group)
current_group = [current_group[-1], dicom]
increment = current_increment
previous_image_position = current_image_position
slice_incement_groups.append(current_group)
# Create nibabel objects for each volume based on the corresponding headers
slice_incement_niftis = []
for dicom_slices in slice_incement_groups:
data = common.get_volume_pixeldata(dicom_slices)
affine, _ = common.create_affine(dicom_slices)
slice_incement_niftis.append(nibabel.Nifti1Image(data, affine))
nifti_volume = resample.resample_nifti_images(slice_incement_niftis)
return nifti_volume, max_slice_increment | [
"def",
"_convert_slice_incement_inconsistencies",
"(",
"dicom_input",
")",
":",
"# Estimate the \"first\" slice increment based on the 2 first slices",
"increment",
"=",
"numpy",
".",
"array",
"(",
"dicom_input",
"[",
"0",
"]",
".",
"ImagePositionPatient",
")",
"-",
"numpy",
".",
"array",
"(",
"dicom_input",
"[",
"1",
"]",
".",
"ImagePositionPatient",
")",
"# Create as many volumes as many changes in slice increment. NB Increments might be repeated in different volumes",
"max_slice_increment",
"=",
"0",
"slice_incement_groups",
"=",
"[",
"]",
"current_group",
"=",
"[",
"dicom_input",
"[",
"0",
"]",
",",
"dicom_input",
"[",
"1",
"]",
"]",
"previous_image_position",
"=",
"numpy",
".",
"array",
"(",
"dicom_input",
"[",
"1",
"]",
".",
"ImagePositionPatient",
")",
"for",
"dicom",
"in",
"dicom_input",
"[",
"2",
":",
"]",
":",
"current_image_position",
"=",
"numpy",
".",
"array",
"(",
"dicom",
".",
"ImagePositionPatient",
")",
"current_increment",
"=",
"previous_image_position",
"-",
"current_image_position",
"max_slice_increment",
"=",
"max",
"(",
"max_slice_increment",
",",
"numpy",
".",
"linalg",
".",
"norm",
"(",
"current_increment",
")",
")",
"if",
"numpy",
".",
"allclose",
"(",
"increment",
",",
"current_increment",
",",
"rtol",
"=",
"0.05",
",",
"atol",
"=",
"0.1",
")",
":",
"current_group",
".",
"append",
"(",
"dicom",
")",
"if",
"not",
"numpy",
".",
"allclose",
"(",
"increment",
",",
"current_increment",
",",
"rtol",
"=",
"0.05",
",",
"atol",
"=",
"0.1",
")",
":",
"slice_incement_groups",
".",
"append",
"(",
"current_group",
")",
"current_group",
"=",
"[",
"current_group",
"[",
"-",
"1",
"]",
",",
"dicom",
"]",
"increment",
"=",
"current_increment",
"previous_image_position",
"=",
"current_image_position",
"slice_incement_groups",
".",
"append",
"(",
"current_group",
")",
"# Create nibabel objects for each volume based on the corresponding headers",
"slice_incement_niftis",
"=",
"[",
"]",
"for",
"dicom_slices",
"in",
"slice_incement_groups",
":",
"data",
"=",
"common",
".",
"get_volume_pixeldata",
"(",
"dicom_slices",
")",
"affine",
",",
"_",
"=",
"common",
".",
"create_affine",
"(",
"dicom_slices",
")",
"slice_incement_niftis",
".",
"append",
"(",
"nibabel",
".",
"Nifti1Image",
"(",
"data",
",",
"affine",
")",
")",
"nifti_volume",
"=",
"resample",
".",
"resample_nifti_images",
"(",
"slice_incement_niftis",
")",
"return",
"nifti_volume",
",",
"max_slice_increment"
] | If there is slice increment inconsistency detected, for the moment CT images, then split the volumes into subvolumes based on the slice increment and process each volume separately using a space constructed based on the highest resolution increment | [
"If",
"there",
"is",
"slice",
"increment",
"inconsistency",
"detected",
"for",
"the",
"moment",
"CT",
"images",
"then",
"split",
"the",
"volumes",
"into",
"subvolumes",
"based",
"on",
"the",
"slice",
"increment",
"and",
"process",
"each",
"volume",
"separately",
"using",
"a",
"space",
"constructed",
"based",
"on",
"the",
"highest",
"resolution",
"increment"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_generic.py#L174-L209 | train | 233,627 |
icometrix/dicom2nifti | dicom2nifti/common.py | is_hitachi | def is_hitachi(dicom_input):
"""
Use this function to detect if a dicom series is a hitachi dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
return False # we try generic conversion in these cases
# check if Modality is mr
if header.Modality.upper() != 'MR':
return False
# check if manufacturer is hitachi
if 'HITACHI' not in header.Manufacturer.upper():
return False
return True | python | def is_hitachi(dicom_input):
"""
Use this function to detect if a dicom series is a hitachi dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
return False # we try generic conversion in these cases
# check if Modality is mr
if header.Modality.upper() != 'MR':
return False
# check if manufacturer is hitachi
if 'HITACHI' not in header.Manufacturer.upper():
return False
return True | [
"def",
"is_hitachi",
"(",
"dicom_input",
")",
":",
"# read dicom header",
"header",
"=",
"dicom_input",
"[",
"0",
"]",
"if",
"'Manufacturer'",
"not",
"in",
"header",
"or",
"'Modality'",
"not",
"in",
"header",
":",
"return",
"False",
"# we try generic conversion in these cases",
"# check if Modality is mr",
"if",
"header",
".",
"Modality",
".",
"upper",
"(",
")",
"!=",
"'MR'",
":",
"return",
"False",
"# check if manufacturer is hitachi",
"if",
"'HITACHI'",
"not",
"in",
"header",
".",
"Manufacturer",
".",
"upper",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | Use this function to detect if a dicom series is a hitachi dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header | [
"Use",
"this",
"function",
"to",
"detect",
"if",
"a",
"dicom",
"series",
"is",
"a",
"hitachi",
"dataset"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L57-L77 | train | 233,628 |
icometrix/dicom2nifti | dicom2nifti/common.py | is_ge | def is_ge(dicom_input):
"""
Use this function to detect if a dicom series is a GE dataset
:param dicom_input: list with dicom objects
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
return False # we try generic conversion in these cases
# check if Modality is mr
if header.Modality.upper() != 'MR':
return False
# check if manufacturer is GE
if 'GE MEDICAL SYSTEMS' not in header.Manufacturer.upper():
return False
return True | python | def is_ge(dicom_input):
"""
Use this function to detect if a dicom series is a GE dataset
:param dicom_input: list with dicom objects
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
return False # we try generic conversion in these cases
# check if Modality is mr
if header.Modality.upper() != 'MR':
return False
# check if manufacturer is GE
if 'GE MEDICAL SYSTEMS' not in header.Manufacturer.upper():
return False
return True | [
"def",
"is_ge",
"(",
"dicom_input",
")",
":",
"# read dicom header",
"header",
"=",
"dicom_input",
"[",
"0",
"]",
"if",
"'Manufacturer'",
"not",
"in",
"header",
"or",
"'Modality'",
"not",
"in",
"header",
":",
"return",
"False",
"# we try generic conversion in these cases",
"# check if Modality is mr",
"if",
"header",
".",
"Modality",
".",
"upper",
"(",
")",
"!=",
"'MR'",
":",
"return",
"False",
"# check if manufacturer is GE",
"if",
"'GE MEDICAL SYSTEMS'",
"not",
"in",
"header",
".",
"Manufacturer",
".",
"upper",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | Use this function to detect if a dicom series is a GE dataset
:param dicom_input: list with dicom objects | [
"Use",
"this",
"function",
"to",
"detect",
"if",
"a",
"dicom",
"series",
"is",
"a",
"GE",
"dataset"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L80-L100 | train | 233,629 |
icometrix/dicom2nifti | dicom2nifti/common.py | is_philips | def is_philips(dicom_input):
"""
Use this function to detect if a dicom series is a philips dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
return False # we try generic conversion in these cases
# check if Modality is mr
if header.Modality.upper() != 'MR':
return False
# check if manufacturer is Philips
if 'PHILIPS' not in header.Manufacturer.upper():
return False
return True | python | def is_philips(dicom_input):
"""
Use this function to detect if a dicom series is a philips dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
return False # we try generic conversion in these cases
# check if Modality is mr
if header.Modality.upper() != 'MR':
return False
# check if manufacturer is Philips
if 'PHILIPS' not in header.Manufacturer.upper():
return False
return True | [
"def",
"is_philips",
"(",
"dicom_input",
")",
":",
"# read dicom header",
"header",
"=",
"dicom_input",
"[",
"0",
"]",
"if",
"'Manufacturer'",
"not",
"in",
"header",
"or",
"'Modality'",
"not",
"in",
"header",
":",
"return",
"False",
"# we try generic conversion in these cases",
"# check if Modality is mr",
"if",
"header",
".",
"Modality",
".",
"upper",
"(",
")",
"!=",
"'MR'",
":",
"return",
"False",
"# check if manufacturer is Philips",
"if",
"'PHILIPS'",
"not",
"in",
"header",
".",
"Manufacturer",
".",
"upper",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | Use this function to detect if a dicom series is a philips dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header | [
"Use",
"this",
"function",
"to",
"detect",
"if",
"a",
"dicom",
"series",
"is",
"a",
"philips",
"dataset"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L103-L123 | train | 233,630 |
icometrix/dicom2nifti | dicom2nifti/common.py | is_siemens | def is_siemens(dicom_input):
"""
Use this function to detect if a dicom series is a siemens dataset
:param dicom_input: directory with dicom files for 1 scan
"""
# read dicom header
header = dicom_input[0]
# check if manufacturer is Siemens
if 'Manufacturer' not in header or 'Modality' not in header:
return False # we try generic conversion in these cases
# check if Modality is mr
if header.Modality.upper() != 'MR':
return False
if 'SIEMENS' not in header.Manufacturer.upper():
return False
return True | python | def is_siemens(dicom_input):
"""
Use this function to detect if a dicom series is a siemens dataset
:param dicom_input: directory with dicom files for 1 scan
"""
# read dicom header
header = dicom_input[0]
# check if manufacturer is Siemens
if 'Manufacturer' not in header or 'Modality' not in header:
return False # we try generic conversion in these cases
# check if Modality is mr
if header.Modality.upper() != 'MR':
return False
if 'SIEMENS' not in header.Manufacturer.upper():
return False
return True | [
"def",
"is_siemens",
"(",
"dicom_input",
")",
":",
"# read dicom header",
"header",
"=",
"dicom_input",
"[",
"0",
"]",
"# check if manufacturer is Siemens",
"if",
"'Manufacturer'",
"not",
"in",
"header",
"or",
"'Modality'",
"not",
"in",
"header",
":",
"return",
"False",
"# we try generic conversion in these cases",
"# check if Modality is mr",
"if",
"header",
".",
"Modality",
".",
"upper",
"(",
")",
"!=",
"'MR'",
":",
"return",
"False",
"if",
"'SIEMENS'",
"not",
"in",
"header",
".",
"Manufacturer",
".",
"upper",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | Use this function to detect if a dicom series is a siemens dataset
:param dicom_input: directory with dicom files for 1 scan | [
"Use",
"this",
"function",
"to",
"detect",
"if",
"a",
"dicom",
"series",
"is",
"a",
"siemens",
"dataset"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L126-L146 | train | 233,631 |
icometrix/dicom2nifti | dicom2nifti/common.py | _get_slice_pixeldata | def _get_slice_pixeldata(dicom_slice):
"""
the slice and intercept calculation can cause the slices to have different dtypes
we should get the correct dtype that can cover all of them
:type dicom_slice: pydicom object
:param dicom_slice: slice to get the pixeldata for
"""
data = dicom_slice.pixel_array
# fix overflow issues for signed data where BitsStored is lower than BitsAllocated and PixelReprentation = 1 (signed)
# for example a hitachi mri scan can have BitsAllocated 16 but BitsStored is 12 and HighBit 11
if dicom_slice.BitsAllocated != dicom_slice.BitsStored and \
dicom_slice.HighBit == dicom_slice.BitsStored - 1 and \
dicom_slice.PixelRepresentation == 1:
if dicom_slice.BitsAllocated == 16:
data = data.astype(numpy.int16) # assert that it is a signed type
max_value = pow(2, dicom_slice.HighBit) - 1
invert_value = -1 ^ max_value
data[data > max_value] = numpy.bitwise_or(data[data > max_value], invert_value)
pass
return apply_scaling(data, dicom_slice) | python | def _get_slice_pixeldata(dicom_slice):
"""
the slice and intercept calculation can cause the slices to have different dtypes
we should get the correct dtype that can cover all of them
:type dicom_slice: pydicom object
:param dicom_slice: slice to get the pixeldata for
"""
data = dicom_slice.pixel_array
# fix overflow issues for signed data where BitsStored is lower than BitsAllocated and PixelReprentation = 1 (signed)
# for example a hitachi mri scan can have BitsAllocated 16 but BitsStored is 12 and HighBit 11
if dicom_slice.BitsAllocated != dicom_slice.BitsStored and \
dicom_slice.HighBit == dicom_slice.BitsStored - 1 and \
dicom_slice.PixelRepresentation == 1:
if dicom_slice.BitsAllocated == 16:
data = data.astype(numpy.int16) # assert that it is a signed type
max_value = pow(2, dicom_slice.HighBit) - 1
invert_value = -1 ^ max_value
data[data > max_value] = numpy.bitwise_or(data[data > max_value], invert_value)
pass
return apply_scaling(data, dicom_slice) | [
"def",
"_get_slice_pixeldata",
"(",
"dicom_slice",
")",
":",
"data",
"=",
"dicom_slice",
".",
"pixel_array",
"# fix overflow issues for signed data where BitsStored is lower than BitsAllocated and PixelReprentation = 1 (signed)",
"# for example a hitachi mri scan can have BitsAllocated 16 but BitsStored is 12 and HighBit 11",
"if",
"dicom_slice",
".",
"BitsAllocated",
"!=",
"dicom_slice",
".",
"BitsStored",
"and",
"dicom_slice",
".",
"HighBit",
"==",
"dicom_slice",
".",
"BitsStored",
"-",
"1",
"and",
"dicom_slice",
".",
"PixelRepresentation",
"==",
"1",
":",
"if",
"dicom_slice",
".",
"BitsAllocated",
"==",
"16",
":",
"data",
"=",
"data",
".",
"astype",
"(",
"numpy",
".",
"int16",
")",
"# assert that it is a signed type",
"max_value",
"=",
"pow",
"(",
"2",
",",
"dicom_slice",
".",
"HighBit",
")",
"-",
"1",
"invert_value",
"=",
"-",
"1",
"^",
"max_value",
"data",
"[",
"data",
">",
"max_value",
"]",
"=",
"numpy",
".",
"bitwise_or",
"(",
"data",
"[",
"data",
">",
"max_value",
"]",
",",
"invert_value",
")",
"pass",
"return",
"apply_scaling",
"(",
"data",
",",
"dicom_slice",
")"
] | the slice and intercept calculation can cause the slices to have different dtypes
we should get the correct dtype that can cover all of them
:type dicom_slice: pydicom object
:param dicom_slice: slice to get the pixeldata for | [
"the",
"slice",
"and",
"intercept",
"calculation",
"can",
"cause",
"the",
"slices",
"to",
"have",
"different",
"dtypes",
"we",
"should",
"get",
"the",
"correct",
"dtype",
"that",
"can",
"cover",
"all",
"of",
"them"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L225-L245 | train | 233,632 |
icometrix/dicom2nifti | dicom2nifti/common.py | set_fd_value | def set_fd_value(tag, value):
"""
Setters for data that also work with implicit transfersyntax
:param value: the value to set on the tag
:param tag: the tag to read
"""
if tag.VR == 'OB' or tag.VR == 'UN':
value = struct.pack('d', value)
tag.value = value | python | def set_fd_value(tag, value):
"""
Setters for data that also work with implicit transfersyntax
:param value: the value to set on the tag
:param tag: the tag to read
"""
if tag.VR == 'OB' or tag.VR == 'UN':
value = struct.pack('d', value)
tag.value = value | [
"def",
"set_fd_value",
"(",
"tag",
",",
"value",
")",
":",
"if",
"tag",
".",
"VR",
"==",
"'OB'",
"or",
"tag",
".",
"VR",
"==",
"'UN'",
":",
"value",
"=",
"struct",
".",
"pack",
"(",
"'d'",
",",
"value",
")",
"tag",
".",
"value",
"=",
"value"
] | Setters for data that also work with implicit transfersyntax
:param value: the value to set on the tag
:param tag: the tag to read | [
"Setters",
"for",
"data",
"that",
"also",
"work",
"with",
"implicit",
"transfersyntax"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L309-L318 | train | 233,633 |
icometrix/dicom2nifti | dicom2nifti/common.py | set_ss_value | def set_ss_value(tag, value):
"""
Setter for data that also work with implicit transfersyntax
:param value: the value to set on the tag
:param tag: the tag to read
"""
if tag.VR == 'OB' or tag.VR == 'UN':
value = struct.pack('h', value)
tag.value = value | python | def set_ss_value(tag, value):
"""
Setter for data that also work with implicit transfersyntax
:param value: the value to set on the tag
:param tag: the tag to read
"""
if tag.VR == 'OB' or tag.VR == 'UN':
value = struct.pack('h', value)
tag.value = value | [
"def",
"set_ss_value",
"(",
"tag",
",",
"value",
")",
":",
"if",
"tag",
".",
"VR",
"==",
"'OB'",
"or",
"tag",
".",
"VR",
"==",
"'UN'",
":",
"value",
"=",
"struct",
".",
"pack",
"(",
"'h'",
",",
"value",
")",
"tag",
".",
"value",
"=",
"value"
] | Setter for data that also work with implicit transfersyntax
:param value: the value to set on the tag
:param tag: the tag to read | [
"Setter",
"for",
"data",
"that",
"also",
"work",
"with",
"implicit",
"transfersyntax"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L359-L368 | train | 233,634 |
icometrix/dicom2nifti | dicom2nifti/common.py | apply_scaling | def apply_scaling(data, dicom_headers):
"""
Rescale the data based on the RescaleSlope and RescaleOffset
Based on the scaling from pydicomseries
:param dicom_headers: dicom headers to use to retreive the scaling factors
:param data: the input data
"""
# Apply the rescaling if needed
private_scale_slope_tag = Tag(0x2005, 0x100E)
private_scale_intercept_tag = Tag(0x2005, 0x100D)
if 'RescaleSlope' in dicom_headers or 'RescaleIntercept' in dicom_headers \
or private_scale_slope_tag in dicom_headers or private_scale_intercept_tag in dicom_headers:
rescale_slope = 1
rescale_intercept = 0
if 'RescaleSlope' in dicom_headers:
rescale_slope = dicom_headers.RescaleSlope
if 'RescaleIntercept' in dicom_headers:
rescale_intercept = dicom_headers.RescaleIntercept
# try:
# # this section can sometimes fail due to unknown private fields
# if private_scale_slope_tag in dicom_headers:
# private_scale_slope = float(dicom_headers[private_scale_slope_tag].value)
# if private_scale_slope_tag in dicom_headers:
# private_scale_slope = float(dicom_headers[private_scale_slope_tag].value)
# except:
# pass
return do_scaling(data, rescale_slope, rescale_intercept)
else:
return data | python | def apply_scaling(data, dicom_headers):
"""
Rescale the data based on the RescaleSlope and RescaleOffset
Based on the scaling from pydicomseries
:param dicom_headers: dicom headers to use to retreive the scaling factors
:param data: the input data
"""
# Apply the rescaling if needed
private_scale_slope_tag = Tag(0x2005, 0x100E)
private_scale_intercept_tag = Tag(0x2005, 0x100D)
if 'RescaleSlope' in dicom_headers or 'RescaleIntercept' in dicom_headers \
or private_scale_slope_tag in dicom_headers or private_scale_intercept_tag in dicom_headers:
rescale_slope = 1
rescale_intercept = 0
if 'RescaleSlope' in dicom_headers:
rescale_slope = dicom_headers.RescaleSlope
if 'RescaleIntercept' in dicom_headers:
rescale_intercept = dicom_headers.RescaleIntercept
# try:
# # this section can sometimes fail due to unknown private fields
# if private_scale_slope_tag in dicom_headers:
# private_scale_slope = float(dicom_headers[private_scale_slope_tag].value)
# if private_scale_slope_tag in dicom_headers:
# private_scale_slope = float(dicom_headers[private_scale_slope_tag].value)
# except:
# pass
return do_scaling(data, rescale_slope, rescale_intercept)
else:
return data | [
"def",
"apply_scaling",
"(",
"data",
",",
"dicom_headers",
")",
":",
"# Apply the rescaling if needed",
"private_scale_slope_tag",
"=",
"Tag",
"(",
"0x2005",
",",
"0x100E",
")",
"private_scale_intercept_tag",
"=",
"Tag",
"(",
"0x2005",
",",
"0x100D",
")",
"if",
"'RescaleSlope'",
"in",
"dicom_headers",
"or",
"'RescaleIntercept'",
"in",
"dicom_headers",
"or",
"private_scale_slope_tag",
"in",
"dicom_headers",
"or",
"private_scale_intercept_tag",
"in",
"dicom_headers",
":",
"rescale_slope",
"=",
"1",
"rescale_intercept",
"=",
"0",
"if",
"'RescaleSlope'",
"in",
"dicom_headers",
":",
"rescale_slope",
"=",
"dicom_headers",
".",
"RescaleSlope",
"if",
"'RescaleIntercept'",
"in",
"dicom_headers",
":",
"rescale_intercept",
"=",
"dicom_headers",
".",
"RescaleIntercept",
"# try:",
"# # this section can sometimes fail due to unknown private fields",
"# if private_scale_slope_tag in dicom_headers:",
"# private_scale_slope = float(dicom_headers[private_scale_slope_tag].value)",
"# if private_scale_slope_tag in dicom_headers:",
"# private_scale_slope = float(dicom_headers[private_scale_slope_tag].value)",
"# except:",
"# pass",
"return",
"do_scaling",
"(",
"data",
",",
"rescale_slope",
",",
"rescale_intercept",
")",
"else",
":",
"return",
"data"
] | Rescale the data based on the RescaleSlope and RescaleOffset
Based on the scaling from pydicomseries
:param dicom_headers: dicom headers to use to retreive the scaling factors
:param data: the input data | [
"Rescale",
"the",
"data",
"based",
"on",
"the",
"RescaleSlope",
"and",
"RescaleOffset",
"Based",
"on",
"the",
"scaling",
"from",
"pydicomseries"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L371-L401 | train | 233,635 |
icometrix/dicom2nifti | dicom2nifti/common.py | write_bvec_file | def write_bvec_file(bvecs, bvec_file):
"""
Write an array of bvecs to a bvec file
:param bvecs: array with the vectors
:param bvec_file: filepath to write to
"""
if bvec_file is None:
return
logger.info('Saving BVEC file: %s' % bvec_file)
with open(bvec_file, 'w') as text_file:
# Map a dicection to string join them using a space and write to the file
text_file.write('%s\n' % ' '.join(map(str, bvecs[:, 0])))
text_file.write('%s\n' % ' '.join(map(str, bvecs[:, 1])))
text_file.write('%s\n' % ' '.join(map(str, bvecs[:, 2]))) | python | def write_bvec_file(bvecs, bvec_file):
"""
Write an array of bvecs to a bvec file
:param bvecs: array with the vectors
:param bvec_file: filepath to write to
"""
if bvec_file is None:
return
logger.info('Saving BVEC file: %s' % bvec_file)
with open(bvec_file, 'w') as text_file:
# Map a dicection to string join them using a space and write to the file
text_file.write('%s\n' % ' '.join(map(str, bvecs[:, 0])))
text_file.write('%s\n' % ' '.join(map(str, bvecs[:, 1])))
text_file.write('%s\n' % ' '.join(map(str, bvecs[:, 2]))) | [
"def",
"write_bvec_file",
"(",
"bvecs",
",",
"bvec_file",
")",
":",
"if",
"bvec_file",
"is",
"None",
":",
"return",
"logger",
".",
"info",
"(",
"'Saving BVEC file: %s'",
"%",
"bvec_file",
")",
"with",
"open",
"(",
"bvec_file",
",",
"'w'",
")",
"as",
"text_file",
":",
"# Map a dicection to string join them using a space and write to the file",
"text_file",
".",
"write",
"(",
"'%s\\n'",
"%",
"' '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"bvecs",
"[",
":",
",",
"0",
"]",
")",
")",
")",
"text_file",
".",
"write",
"(",
"'%s\\n'",
"%",
"' '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"bvecs",
"[",
":",
",",
"1",
"]",
")",
")",
")",
"text_file",
".",
"write",
"(",
"'%s\\n'",
"%",
"' '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"bvecs",
"[",
":",
",",
"2",
"]",
")",
")",
")"
] | Write an array of bvecs to a bvec file
:param bvecs: array with the vectors
:param bvec_file: filepath to write to | [
"Write",
"an",
"array",
"of",
"bvecs",
"to",
"a",
"bvec",
"file"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L478-L492 | train | 233,636 |
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):
"""
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))) | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L495-L507 | train | 233,637 |
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):
"""
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 | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L614-L635 | train | 233,638 |
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):
"""
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') | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L696-L715 | train | 233,639 |
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):
"""
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 | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L718-L732 | train | 233,640 |
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):
"""
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) | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_ge.py#L32-L52 | train | 233,641 |
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):
"""
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} | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_ge.py#L91-L136 | train | 233,642 |
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):
"""
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) | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_hitachi.py#L25-L41 | train | 233,643 |
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):
"""
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) | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L45-L66 | train | 233,644 |
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):
"""
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 | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L324-L336 | train | 233,645 |
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):
"""
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 | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L399-L440 | train | 233,646 |
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):
"""
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]]) | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_siemens.py#L443-L467 | train | 233,647 |
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):
"""
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) | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/resample.py#L15-L22 | train | 233,648 |
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):
"""
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() | [
"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"
] | 1462ae5dd979fa3f276fe7a78ceb9b028121536f | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_dir.py#L34-L99 | train | 233,649 |
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):
"""
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 | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_formatter.py#L246-L254 | train | 233,650 |
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):
"""
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()) | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L123-L133 | train | 233,651 |
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):
"""
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()) | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L145-L155 | train | 233,652 |
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):
"""
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()) | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L157-L167 | train | 233,653 |
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'):
"""
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)) | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L169-L178 | train | 233,654 |
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):
"""
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() | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/format/menu_borders.py#L352-L378 | train | 233,655 |
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():
"""
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) | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/format/menu_borders.py#L454-L463 | train | 233,656 |
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):
"""
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 | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/items/submenu_item.py#L19-L27 | train | 233,657 |
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):
"""
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 | [
"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"
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/validators/regex.py#L16-L30 | train | 233,658 |
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):
"""
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 | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/multiselect_menu.py#L43-L67 | train | 233,659 |
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):
"""
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 | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L116-L130 | train | 233,660 |
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):
"""
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 | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L144-L155 | train | 233,661 |
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):
"""
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)) | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L226-L231 | train | 233,662 |
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):
"""
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 | [
"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"
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L297-L311 | train | 233,663 |
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):
"""
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() | [
"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"
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L323-L331 | train | 233,664 |
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):
"""
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() | [
"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"
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/console_menu.py#L333-L341 | train | 233,665 |
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):
"""
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 | [
"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",
"."
] | 1a28959d6f1dd6ac79c87b11efd8529d05532422 | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/selection_menu.py#L29-L50 | train | 233,666 |
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):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L73-L83 | train | 233,667 |
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):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L86-L96 | train | 233,668 |
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):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L99-L110 | train | 233,669 |
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'):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L113-L156 | train | 233,670 |
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):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L159-L194 | train | 233,671 |
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):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L197-L217 | train | 233,672 |
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):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L220-L264 | train | 233,673 |
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):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L340-L417 | train | 233,674 |
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'):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L420-L463 | train | 233,675 |
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):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L466-L491 | train | 233,676 |
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):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L494-L526 | train | 233,677 |
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):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L529-L560 | train | 233,678 |
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):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L563-L582 | train | 233,679 |
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):
"""
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 | [
"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",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L718-L745 | train | 233,680 |
timothyb0912/pylogit | pylogit/choice_tools.py | create_sparse_mapping | def create_sparse_mapping(id_array, unique_ids=None):
"""
Will create a scipy.sparse compressed-sparse-row matrix that maps
each row represented by an element in id_array to the corresponding
value of the unique ids in id_array.
Parameters
----------
id_array : 1D ndarray of ints.
Each element should represent some id related to the corresponding row.
unique_ids : 1D ndarray of ints, or None, optional.
If not None, each element should be present in `id_array`. The elements
in `unique_ids` should be present in the order in which one wishes them
to appear in the columns of the resulting sparse array. For the
`row_to_obs` and `row_to_mixers` mappings, this should be the order of
appearance in `id_array`. If None, then the unique_ids will be created
from `id_array`, in the order of their appearance in `id_array`.
Returns
-------
mapping : 2D scipy.sparse CSR matrix.
Will contain only zeros and ones. `mapping[i, j] == 1` where
`id_array[i] == unique_ids[j]`. The id's corresponding to each column
are given by `unique_ids`. The rows correspond to the elements of
`id_array`.
"""
# Create unique_ids if necessary
if unique_ids is None:
unique_ids = get_original_order_unique_ids(id_array)
# Check function arguments for validity
assert isinstance(unique_ids, np.ndarray)
assert isinstance(id_array, np.ndarray)
assert unique_ids.ndim == 1
assert id_array.ndim == 1
# Figure out which ids in id_array are represented in unique_ids
represented_ids = np.in1d(id_array, unique_ids)
# Determine the number of rows in id_array that are in unique_ids
num_non_zero_rows = represented_ids.sum()
# Figure out the dimensions of the resulting sparse matrix
num_rows = id_array.size
num_cols = unique_ids.size
# Specify the non-zero values that will be present in the sparse matrix.
data = np.ones(num_non_zero_rows, dtype=int)
# Specify which rows will have non-zero entries in the sparse matrix.
row_indices = np.arange(num_rows)[represented_ids]
# Map the unique id's to their respective columns
unique_id_dict = dict(zip(unique_ids, np.arange(num_cols)))
# Figure out the column indices of the non-zero entries, and do so in a way
# that avoids a key error (i.e. only look up ids that are represented)
col_indices =\
np.array([unique_id_dict[x] for x in id_array[represented_ids]])
# Create and return the sparse matrix
return csr_matrix((data, (row_indices, col_indices)),
shape=(num_rows, num_cols)) | python | def create_sparse_mapping(id_array, unique_ids=None):
"""
Will create a scipy.sparse compressed-sparse-row matrix that maps
each row represented by an element in id_array to the corresponding
value of the unique ids in id_array.
Parameters
----------
id_array : 1D ndarray of ints.
Each element should represent some id related to the corresponding row.
unique_ids : 1D ndarray of ints, or None, optional.
If not None, each element should be present in `id_array`. The elements
in `unique_ids` should be present in the order in which one wishes them
to appear in the columns of the resulting sparse array. For the
`row_to_obs` and `row_to_mixers` mappings, this should be the order of
appearance in `id_array`. If None, then the unique_ids will be created
from `id_array`, in the order of their appearance in `id_array`.
Returns
-------
mapping : 2D scipy.sparse CSR matrix.
Will contain only zeros and ones. `mapping[i, j] == 1` where
`id_array[i] == unique_ids[j]`. The id's corresponding to each column
are given by `unique_ids`. The rows correspond to the elements of
`id_array`.
"""
# Create unique_ids if necessary
if unique_ids is None:
unique_ids = get_original_order_unique_ids(id_array)
# Check function arguments for validity
assert isinstance(unique_ids, np.ndarray)
assert isinstance(id_array, np.ndarray)
assert unique_ids.ndim == 1
assert id_array.ndim == 1
# Figure out which ids in id_array are represented in unique_ids
represented_ids = np.in1d(id_array, unique_ids)
# Determine the number of rows in id_array that are in unique_ids
num_non_zero_rows = represented_ids.sum()
# Figure out the dimensions of the resulting sparse matrix
num_rows = id_array.size
num_cols = unique_ids.size
# Specify the non-zero values that will be present in the sparse matrix.
data = np.ones(num_non_zero_rows, dtype=int)
# Specify which rows will have non-zero entries in the sparse matrix.
row_indices = np.arange(num_rows)[represented_ids]
# Map the unique id's to their respective columns
unique_id_dict = dict(zip(unique_ids, np.arange(num_cols)))
# Figure out the column indices of the non-zero entries, and do so in a way
# that avoids a key error (i.e. only look up ids that are represented)
col_indices =\
np.array([unique_id_dict[x] for x in id_array[represented_ids]])
# Create and return the sparse matrix
return csr_matrix((data, (row_indices, col_indices)),
shape=(num_rows, num_cols)) | [
"def",
"create_sparse_mapping",
"(",
"id_array",
",",
"unique_ids",
"=",
"None",
")",
":",
"# Create unique_ids if necessary",
"if",
"unique_ids",
"is",
"None",
":",
"unique_ids",
"=",
"get_original_order_unique_ids",
"(",
"id_array",
")",
"# Check function arguments for validity",
"assert",
"isinstance",
"(",
"unique_ids",
",",
"np",
".",
"ndarray",
")",
"assert",
"isinstance",
"(",
"id_array",
",",
"np",
".",
"ndarray",
")",
"assert",
"unique_ids",
".",
"ndim",
"==",
"1",
"assert",
"id_array",
".",
"ndim",
"==",
"1",
"# Figure out which ids in id_array are represented in unique_ids",
"represented_ids",
"=",
"np",
".",
"in1d",
"(",
"id_array",
",",
"unique_ids",
")",
"# Determine the number of rows in id_array that are in unique_ids",
"num_non_zero_rows",
"=",
"represented_ids",
".",
"sum",
"(",
")",
"# Figure out the dimensions of the resulting sparse matrix",
"num_rows",
"=",
"id_array",
".",
"size",
"num_cols",
"=",
"unique_ids",
".",
"size",
"# Specify the non-zero values that will be present in the sparse matrix.",
"data",
"=",
"np",
".",
"ones",
"(",
"num_non_zero_rows",
",",
"dtype",
"=",
"int",
")",
"# Specify which rows will have non-zero entries in the sparse matrix.",
"row_indices",
"=",
"np",
".",
"arange",
"(",
"num_rows",
")",
"[",
"represented_ids",
"]",
"# Map the unique id's to their respective columns",
"unique_id_dict",
"=",
"dict",
"(",
"zip",
"(",
"unique_ids",
",",
"np",
".",
"arange",
"(",
"num_cols",
")",
")",
")",
"# Figure out the column indices of the non-zero entries, and do so in a way",
"# that avoids a key error (i.e. only look up ids that are represented)",
"col_indices",
"=",
"np",
".",
"array",
"(",
"[",
"unique_id_dict",
"[",
"x",
"]",
"for",
"x",
"in",
"id_array",
"[",
"represented_ids",
"]",
"]",
")",
"# Create and return the sparse matrix",
"return",
"csr_matrix",
"(",
"(",
"data",
",",
"(",
"row_indices",
",",
"col_indices",
")",
")",
",",
"shape",
"=",
"(",
"num_rows",
",",
"num_cols",
")",
")"
] | Will create a scipy.sparse compressed-sparse-row matrix that maps
each row represented by an element in id_array to the corresponding
value of the unique ids in id_array.
Parameters
----------
id_array : 1D ndarray of ints.
Each element should represent some id related to the corresponding row.
unique_ids : 1D ndarray of ints, or None, optional.
If not None, each element should be present in `id_array`. The elements
in `unique_ids` should be present in the order in which one wishes them
to appear in the columns of the resulting sparse array. For the
`row_to_obs` and `row_to_mixers` mappings, this should be the order of
appearance in `id_array`. If None, then the unique_ids will be created
from `id_array`, in the order of their appearance in `id_array`.
Returns
-------
mapping : 2D scipy.sparse CSR matrix.
Will contain only zeros and ones. `mapping[i, j] == 1` where
`id_array[i] == unique_ids[j]`. The id's corresponding to each column
are given by `unique_ids`. The rows correspond to the elements of
`id_array`. | [
"Will",
"create",
"a",
"scipy",
".",
"sparse",
"compressed",
"-",
"sparse",
"-",
"row",
"matrix",
"that",
"maps",
"each",
"row",
"represented",
"by",
"an",
"element",
"in",
"id_array",
"to",
"the",
"corresponding",
"value",
"of",
"the",
"unique",
"ids",
"in",
"id_array",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L776-L832 | train | 233,681 |
timothyb0912/pylogit | pylogit/choice_tools.py | check_wide_data_for_blank_choices | def check_wide_data_for_blank_choices(choice_col, wide_data):
"""
Checks `wide_data` for null values in the choice column, and raises a
helpful ValueError if null values are found.
Parameters
----------
choice_col : str.
Denotes the column in `wide_data` that is used to record each
observation's choice.
wide_data : pandas dataframe.
Contains one row for each observation. Should contain `choice_col`.
Returns
-------
None.
"""
if wide_data[choice_col].isnull().any():
msg_1 = "One or more of the values in wide_data[choice_col] is null."
msg_2 = " Remove null values in the choice column or fill them in."
raise ValueError(msg_1 + msg_2)
return None | python | def check_wide_data_for_blank_choices(choice_col, wide_data):
"""
Checks `wide_data` for null values in the choice column, and raises a
helpful ValueError if null values are found.
Parameters
----------
choice_col : str.
Denotes the column in `wide_data` that is used to record each
observation's choice.
wide_data : pandas dataframe.
Contains one row for each observation. Should contain `choice_col`.
Returns
-------
None.
"""
if wide_data[choice_col].isnull().any():
msg_1 = "One or more of the values in wide_data[choice_col] is null."
msg_2 = " Remove null values in the choice column or fill them in."
raise ValueError(msg_1 + msg_2)
return None | [
"def",
"check_wide_data_for_blank_choices",
"(",
"choice_col",
",",
"wide_data",
")",
":",
"if",
"wide_data",
"[",
"choice_col",
"]",
".",
"isnull",
"(",
")",
".",
"any",
"(",
")",
":",
"msg_1",
"=",
"\"One or more of the values in wide_data[choice_col] is null.\"",
"msg_2",
"=",
"\" Remove null values in the choice column or fill them in.\"",
"raise",
"ValueError",
"(",
"msg_1",
"+",
"msg_2",
")",
"return",
"None"
] | Checks `wide_data` for null values in the choice column, and raises a
helpful ValueError if null values are found.
Parameters
----------
choice_col : str.
Denotes the column in `wide_data` that is used to record each
observation's choice.
wide_data : pandas dataframe.
Contains one row for each observation. Should contain `choice_col`.
Returns
-------
None. | [
"Checks",
"wide_data",
"for",
"null",
"values",
"in",
"the",
"choice",
"column",
"and",
"raises",
"a",
"helpful",
"ValueError",
"if",
"null",
"values",
"are",
"found",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L1258-L1280 | train | 233,682 |
timothyb0912/pylogit | pylogit/choice_tools.py | ensure_unique_obs_ids_in_wide_data | def ensure_unique_obs_ids_in_wide_data(obs_id_col, wide_data):
"""
Ensures that there is one observation per row in wide_data. Raises a
helpful ValueError if otherwise.
Parameters
----------
obs_id_col : str.
Denotes the column in `wide_data` that contains the observation ID
values for each row.
wide_data : pandas dataframe.
Contains one row for each observation. Should contain the specified
`obs_id_col` column.
Returns
-------
None.
"""
if len(wide_data[obs_id_col].unique()) != wide_data.shape[0]:
msg = "The values in wide_data[obs_id_col] are not unique, "
msg_2 = "but they need to be."
raise ValueError(msg + msg_2)
return None | python | def ensure_unique_obs_ids_in_wide_data(obs_id_col, wide_data):
"""
Ensures that there is one observation per row in wide_data. Raises a
helpful ValueError if otherwise.
Parameters
----------
obs_id_col : str.
Denotes the column in `wide_data` that contains the observation ID
values for each row.
wide_data : pandas dataframe.
Contains one row for each observation. Should contain the specified
`obs_id_col` column.
Returns
-------
None.
"""
if len(wide_data[obs_id_col].unique()) != wide_data.shape[0]:
msg = "The values in wide_data[obs_id_col] are not unique, "
msg_2 = "but they need to be."
raise ValueError(msg + msg_2)
return None | [
"def",
"ensure_unique_obs_ids_in_wide_data",
"(",
"obs_id_col",
",",
"wide_data",
")",
":",
"if",
"len",
"(",
"wide_data",
"[",
"obs_id_col",
"]",
".",
"unique",
"(",
")",
")",
"!=",
"wide_data",
".",
"shape",
"[",
"0",
"]",
":",
"msg",
"=",
"\"The values in wide_data[obs_id_col] are not unique, \"",
"msg_2",
"=",
"\"but they need to be.\"",
"raise",
"ValueError",
"(",
"msg",
"+",
"msg_2",
")",
"return",
"None"
] | Ensures that there is one observation per row in wide_data. Raises a
helpful ValueError if otherwise.
Parameters
----------
obs_id_col : str.
Denotes the column in `wide_data` that contains the observation ID
values for each row.
wide_data : pandas dataframe.
Contains one row for each observation. Should contain the specified
`obs_id_col` column.
Returns
-------
None. | [
"Ensures",
"that",
"there",
"is",
"one",
"observation",
"per",
"row",
"in",
"wide_data",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"otherwise",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L1283-L1306 | train | 233,683 |
timothyb0912/pylogit | pylogit/choice_tools.py | ensure_chosen_alternatives_are_in_user_alt_ids | def ensure_chosen_alternatives_are_in_user_alt_ids(choice_col,
wide_data,
availability_vars):
"""
Ensures that all chosen alternatives in `wide_df` are present in the
`availability_vars` dict. Raises a helpful ValueError if not.
Parameters
----------
choice_col : str.
Denotes the column in `wide_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.
wide_data : pandas dataframe.
Contains one row for each observation. Should contain the specified
`choice_col` column.
availability_vars : dict.
There should be one key value pair for each alternative that is
observed in the dataset. Each key should be the alternative id for the
alternative, and the value should be the column heading in `wide_data`
that denotes (using ones and zeros) whether an alternative is
available/unavailable, respectively, for a given observation.
Alternative id's, i.e. the keys, must be integers.
Returns
-------
None.
"""
if not wide_data[choice_col].isin(availability_vars.keys()).all():
msg = "One or more values in wide_data[choice_col] is not in the user "
msg_2 = "provided alternative ids in availability_vars.keys()"
raise ValueError(msg + msg_2)
return None | python | def ensure_chosen_alternatives_are_in_user_alt_ids(choice_col,
wide_data,
availability_vars):
"""
Ensures that all chosen alternatives in `wide_df` are present in the
`availability_vars` dict. Raises a helpful ValueError if not.
Parameters
----------
choice_col : str.
Denotes the column in `wide_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.
wide_data : pandas dataframe.
Contains one row for each observation. Should contain the specified
`choice_col` column.
availability_vars : dict.
There should be one key value pair for each alternative that is
observed in the dataset. Each key should be the alternative id for the
alternative, and the value should be the column heading in `wide_data`
that denotes (using ones and zeros) whether an alternative is
available/unavailable, respectively, for a given observation.
Alternative id's, i.e. the keys, must be integers.
Returns
-------
None.
"""
if not wide_data[choice_col].isin(availability_vars.keys()).all():
msg = "One or more values in wide_data[choice_col] is not in the user "
msg_2 = "provided alternative ids in availability_vars.keys()"
raise ValueError(msg + msg_2)
return None | [
"def",
"ensure_chosen_alternatives_are_in_user_alt_ids",
"(",
"choice_col",
",",
"wide_data",
",",
"availability_vars",
")",
":",
"if",
"not",
"wide_data",
"[",
"choice_col",
"]",
".",
"isin",
"(",
"availability_vars",
".",
"keys",
"(",
")",
")",
".",
"all",
"(",
")",
":",
"msg",
"=",
"\"One or more values in wide_data[choice_col] is not in the user \"",
"msg_2",
"=",
"\"provided alternative ids in availability_vars.keys()\"",
"raise",
"ValueError",
"(",
"msg",
"+",
"msg_2",
")",
"return",
"None"
] | Ensures that all chosen alternatives in `wide_df` are present in the
`availability_vars` dict. Raises a helpful ValueError if not.
Parameters
----------
choice_col : str.
Denotes the column in `wide_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.
wide_data : pandas dataframe.
Contains one row for each observation. Should contain the specified
`choice_col` column.
availability_vars : dict.
There should be one key value pair for each alternative that is
observed in the dataset. Each key should be the alternative id for the
alternative, and the value should be the column heading in `wide_data`
that denotes (using ones and zeros) whether an alternative is
available/unavailable, respectively, for a given observation.
Alternative id's, i.e. the keys, must be integers.
Returns
-------
None. | [
"Ensures",
"that",
"all",
"chosen",
"alternatives",
"in",
"wide_df",
"are",
"present",
"in",
"the",
"availability_vars",
"dict",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"not",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L1309-L1342 | train | 233,684 |
timothyb0912/pylogit | pylogit/choice_tools.py | ensure_each_wide_obs_chose_an_available_alternative | def ensure_each_wide_obs_chose_an_available_alternative(obs_id_col,
choice_col,
availability_vars,
wide_data):
"""
Checks whether or not each observation with a restricted choice set chose
an alternative that was personally available to him or her. Will raise a
helpful ValueError if this is not the case.
Parameters
----------
obs_id_col : str.
Denotes the column in `wide_data` that contains the observation ID
values for each row.
choice_col : str.
Denotes the column in `wide_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.
availability_vars : dict.
There should be one key value pair for each alternative that is
observed in the dataset. Each key should be the alternative id for the
alternative, and the value should be the column heading in `wide_data`
that denotes (using ones and zeros) whether an alternative is
available/unavailable, respectively, for a given observation.
Alternative id's, i.e. the keys, must be integers.
wide_data : pandas dataframe.
Contains one row for each observation. Should have the specified
`[obs_id_col, choice_col] + availability_vars.values()` columns.
Returns
-------
None
"""
# Determine the various availability values for each observation
wide_availability_values = wide_data[list(
availability_vars.values())].values
# Isolate observations for whom one or more alternatives are unavailable
unavailable_condition = ((wide_availability_values == 0).sum(axis=1)
.astype(bool))
# Iterate over the observations with one or more unavailable alternatives
# Check that each such observation's chosen alternative was available
problem_obs = []
for idx, row in wide_data.loc[unavailable_condition].iterrows():
if row.at[availability_vars[row.at[choice_col]]] != 1:
problem_obs.append(row.at[obs_id_col])
if problem_obs != []:
msg = "The following observations chose unavailable alternatives:\n{}"
raise ValueError(msg.format(problem_obs))
return None | python | def ensure_each_wide_obs_chose_an_available_alternative(obs_id_col,
choice_col,
availability_vars,
wide_data):
"""
Checks whether or not each observation with a restricted choice set chose
an alternative that was personally available to him or her. Will raise a
helpful ValueError if this is not the case.
Parameters
----------
obs_id_col : str.
Denotes the column in `wide_data` that contains the observation ID
values for each row.
choice_col : str.
Denotes the column in `wide_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.
availability_vars : dict.
There should be one key value pair for each alternative that is
observed in the dataset. Each key should be the alternative id for the
alternative, and the value should be the column heading in `wide_data`
that denotes (using ones and zeros) whether an alternative is
available/unavailable, respectively, for a given observation.
Alternative id's, i.e. the keys, must be integers.
wide_data : pandas dataframe.
Contains one row for each observation. Should have the specified
`[obs_id_col, choice_col] + availability_vars.values()` columns.
Returns
-------
None
"""
# Determine the various availability values for each observation
wide_availability_values = wide_data[list(
availability_vars.values())].values
# Isolate observations for whom one or more alternatives are unavailable
unavailable_condition = ((wide_availability_values == 0).sum(axis=1)
.astype(bool))
# Iterate over the observations with one or more unavailable alternatives
# Check that each such observation's chosen alternative was available
problem_obs = []
for idx, row in wide_data.loc[unavailable_condition].iterrows():
if row.at[availability_vars[row.at[choice_col]]] != 1:
problem_obs.append(row.at[obs_id_col])
if problem_obs != []:
msg = "The following observations chose unavailable alternatives:\n{}"
raise ValueError(msg.format(problem_obs))
return None | [
"def",
"ensure_each_wide_obs_chose_an_available_alternative",
"(",
"obs_id_col",
",",
"choice_col",
",",
"availability_vars",
",",
"wide_data",
")",
":",
"# Determine the various availability values for each observation",
"wide_availability_values",
"=",
"wide_data",
"[",
"list",
"(",
"availability_vars",
".",
"values",
"(",
")",
")",
"]",
".",
"values",
"# Isolate observations for whom one or more alternatives are unavailable",
"unavailable_condition",
"=",
"(",
"(",
"wide_availability_values",
"==",
"0",
")",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
".",
"astype",
"(",
"bool",
")",
")",
"# Iterate over the observations with one or more unavailable alternatives",
"# Check that each such observation's chosen alternative was available",
"problem_obs",
"=",
"[",
"]",
"for",
"idx",
",",
"row",
"in",
"wide_data",
".",
"loc",
"[",
"unavailable_condition",
"]",
".",
"iterrows",
"(",
")",
":",
"if",
"row",
".",
"at",
"[",
"availability_vars",
"[",
"row",
".",
"at",
"[",
"choice_col",
"]",
"]",
"]",
"!=",
"1",
":",
"problem_obs",
".",
"append",
"(",
"row",
".",
"at",
"[",
"obs_id_col",
"]",
")",
"if",
"problem_obs",
"!=",
"[",
"]",
":",
"msg",
"=",
"\"The following observations chose unavailable alternatives:\\n{}\"",
"raise",
"ValueError",
"(",
"msg",
".",
"format",
"(",
"problem_obs",
")",
")",
"return",
"None"
] | Checks whether or not each observation with a restricted choice set chose
an alternative that was personally available to him or her. Will raise a
helpful ValueError if this is not the case.
Parameters
----------
obs_id_col : str.
Denotes the column in `wide_data` that contains the observation ID
values for each row.
choice_col : str.
Denotes the column in `wide_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.
availability_vars : dict.
There should be one key value pair for each alternative that is
observed in the dataset. Each key should be the alternative id for the
alternative, and the value should be the column heading in `wide_data`
that denotes (using ones and zeros) whether an alternative is
available/unavailable, respectively, for a given observation.
Alternative id's, i.e. the keys, must be integers.
wide_data : pandas dataframe.
Contains one row for each observation. Should have the specified
`[obs_id_col, choice_col] + availability_vars.values()` columns.
Returns
-------
None | [
"Checks",
"whether",
"or",
"not",
"each",
"observation",
"with",
"a",
"restricted",
"choice",
"set",
"chose",
"an",
"alternative",
"that",
"was",
"personally",
"available",
"to",
"him",
"or",
"her",
".",
"Will",
"raise",
"a",
"helpful",
"ValueError",
"if",
"this",
"is",
"not",
"the",
"case",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L1345-L1397 | train | 233,685 |
timothyb0912/pylogit | pylogit/choice_tools.py | ensure_all_wide_alt_ids_are_chosen | def ensure_all_wide_alt_ids_are_chosen(choice_col,
alt_specific_vars,
availability_vars,
wide_data):
"""
Checks to make sure all user-specified alternative id's, both in
`alt_specific_vars` and `availability_vars` are observed in the choice
column of `wide_data`.
"""
sorted_alt_ids = np.sort(wide_data[choice_col].unique())
try:
problem_ids = [x for x in availability_vars
if x not in sorted_alt_ids]
problem_type = "availability_vars"
assert problem_ids == []
problem_ids = []
for new_column in alt_specific_vars:
for alt_id in alt_specific_vars[new_column]:
if alt_id not in sorted_alt_ids and alt_id not in problem_ids:
problem_ids.append(alt_id)
problem_type = "alt_specific_vars"
assert problem_ids == []
except AssertionError:
msg = "The following alternative ids from {} are not "
msg_2 = "observed in wide_data[choice_col]:\n{}"
raise ValueError(msg.format(problem_type) + msg_2.format(problem_ids))
return None | python | def ensure_all_wide_alt_ids_are_chosen(choice_col,
alt_specific_vars,
availability_vars,
wide_data):
"""
Checks to make sure all user-specified alternative id's, both in
`alt_specific_vars` and `availability_vars` are observed in the choice
column of `wide_data`.
"""
sorted_alt_ids = np.sort(wide_data[choice_col].unique())
try:
problem_ids = [x for x in availability_vars
if x not in sorted_alt_ids]
problem_type = "availability_vars"
assert problem_ids == []
problem_ids = []
for new_column in alt_specific_vars:
for alt_id in alt_specific_vars[new_column]:
if alt_id not in sorted_alt_ids and alt_id not in problem_ids:
problem_ids.append(alt_id)
problem_type = "alt_specific_vars"
assert problem_ids == []
except AssertionError:
msg = "The following alternative ids from {} are not "
msg_2 = "observed in wide_data[choice_col]:\n{}"
raise ValueError(msg.format(problem_type) + msg_2.format(problem_ids))
return None | [
"def",
"ensure_all_wide_alt_ids_are_chosen",
"(",
"choice_col",
",",
"alt_specific_vars",
",",
"availability_vars",
",",
"wide_data",
")",
":",
"sorted_alt_ids",
"=",
"np",
".",
"sort",
"(",
"wide_data",
"[",
"choice_col",
"]",
".",
"unique",
"(",
")",
")",
"try",
":",
"problem_ids",
"=",
"[",
"x",
"for",
"x",
"in",
"availability_vars",
"if",
"x",
"not",
"in",
"sorted_alt_ids",
"]",
"problem_type",
"=",
"\"availability_vars\"",
"assert",
"problem_ids",
"==",
"[",
"]",
"problem_ids",
"=",
"[",
"]",
"for",
"new_column",
"in",
"alt_specific_vars",
":",
"for",
"alt_id",
"in",
"alt_specific_vars",
"[",
"new_column",
"]",
":",
"if",
"alt_id",
"not",
"in",
"sorted_alt_ids",
"and",
"alt_id",
"not",
"in",
"problem_ids",
":",
"problem_ids",
".",
"append",
"(",
"alt_id",
")",
"problem_type",
"=",
"\"alt_specific_vars\"",
"assert",
"problem_ids",
"==",
"[",
"]",
"except",
"AssertionError",
":",
"msg",
"=",
"\"The following alternative ids from {} are not \"",
"msg_2",
"=",
"\"observed in wide_data[choice_col]:\\n{}\"",
"raise",
"ValueError",
"(",
"msg",
".",
"format",
"(",
"problem_type",
")",
"+",
"msg_2",
".",
"format",
"(",
"problem_ids",
")",
")",
"return",
"None"
] | Checks to make sure all user-specified alternative id's, both in
`alt_specific_vars` and `availability_vars` are observed in the choice
column of `wide_data`. | [
"Checks",
"to",
"make",
"sure",
"all",
"user",
"-",
"specified",
"alternative",
"id",
"s",
"both",
"in",
"alt_specific_vars",
"and",
"availability_vars",
"are",
"observed",
"in",
"the",
"choice",
"column",
"of",
"wide_data",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L1400-L1428 | train | 233,686 |
timothyb0912/pylogit | pylogit/choice_tools.py | ensure_contiguity_in_observation_rows | def ensure_contiguity_in_observation_rows(obs_id_vector):
"""
Ensures that all rows pertaining to a given choice situation are located
next to one another. Raises a helpful ValueError otherwise. This check is
needed because the hessian calculation function requires the design matrix
to have contiguity in rows with the same observation id.
Parameters
----------
rows_to_obs : 2D scipy sparse array.
Should map each row of the long format dataferame to the unique
observations in the dataset.
obs_id_vector : 1D ndarray of ints.
Should contain the id (i.e. a unique integer) that corresponds to each
choice situation in the dataset.
Returns
-------
None.
"""
# Check that the choice situation id for each row is larger than or equal
# to the choice situation id of the preceding row.
contiguity_check_array = (obs_id_vector[1:] - obs_id_vector[:-1]) >= 0
if not contiguity_check_array.all():
problem_ids = obs_id_vector[np.where(~contiguity_check_array)]
msg_1 = "All rows pertaining to a given choice situation must be "
msg_2 = "contiguous. \nRows pertaining to the following observation "
msg_3 = "id's are not contiguous: \n{}"
raise ValueError(msg_1 + msg_2 + msg_3.format(problem_ids.tolist()))
else:
return None | python | def ensure_contiguity_in_observation_rows(obs_id_vector):
"""
Ensures that all rows pertaining to a given choice situation are located
next to one another. Raises a helpful ValueError otherwise. This check is
needed because the hessian calculation function requires the design matrix
to have contiguity in rows with the same observation id.
Parameters
----------
rows_to_obs : 2D scipy sparse array.
Should map each row of the long format dataferame to the unique
observations in the dataset.
obs_id_vector : 1D ndarray of ints.
Should contain the id (i.e. a unique integer) that corresponds to each
choice situation in the dataset.
Returns
-------
None.
"""
# Check that the choice situation id for each row is larger than or equal
# to the choice situation id of the preceding row.
contiguity_check_array = (obs_id_vector[1:] - obs_id_vector[:-1]) >= 0
if not contiguity_check_array.all():
problem_ids = obs_id_vector[np.where(~contiguity_check_array)]
msg_1 = "All rows pertaining to a given choice situation must be "
msg_2 = "contiguous. \nRows pertaining to the following observation "
msg_3 = "id's are not contiguous: \n{}"
raise ValueError(msg_1 + msg_2 + msg_3.format(problem_ids.tolist()))
else:
return None | [
"def",
"ensure_contiguity_in_observation_rows",
"(",
"obs_id_vector",
")",
":",
"# Check that the choice situation id for each row is larger than or equal",
"# to the choice situation id of the preceding row.",
"contiguity_check_array",
"=",
"(",
"obs_id_vector",
"[",
"1",
":",
"]",
"-",
"obs_id_vector",
"[",
":",
"-",
"1",
"]",
")",
">=",
"0",
"if",
"not",
"contiguity_check_array",
".",
"all",
"(",
")",
":",
"problem_ids",
"=",
"obs_id_vector",
"[",
"np",
".",
"where",
"(",
"~",
"contiguity_check_array",
")",
"]",
"msg_1",
"=",
"\"All rows pertaining to a given choice situation must be \"",
"msg_2",
"=",
"\"contiguous. \\nRows pertaining to the following observation \"",
"msg_3",
"=",
"\"id's are not contiguous: \\n{}\"",
"raise",
"ValueError",
"(",
"msg_1",
"+",
"msg_2",
"+",
"msg_3",
".",
"format",
"(",
"problem_ids",
".",
"tolist",
"(",
")",
")",
")",
"else",
":",
"return",
"None"
] | Ensures that all rows pertaining to a given choice situation are located
next to one another. Raises a helpful ValueError otherwise. This check is
needed because the hessian calculation function requires the design matrix
to have contiguity in rows with the same observation id.
Parameters
----------
rows_to_obs : 2D scipy sparse array.
Should map each row of the long format dataferame to the unique
observations in the dataset.
obs_id_vector : 1D ndarray of ints.
Should contain the id (i.e. a unique integer) that corresponds to each
choice situation in the dataset.
Returns
-------
None. | [
"Ensures",
"that",
"all",
"rows",
"pertaining",
"to",
"a",
"given",
"choice",
"situation",
"are",
"located",
"next",
"to",
"one",
"another",
".",
"Raises",
"a",
"helpful",
"ValueError",
"otherwise",
".",
"This",
"check",
"is",
"needed",
"because",
"the",
"hessian",
"calculation",
"function",
"requires",
"the",
"design",
"matrix",
"to",
"have",
"contiguity",
"in",
"rows",
"with",
"the",
"same",
"observation",
"id",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L1431-L1461 | train | 233,687 |
timothyb0912/pylogit | pylogit/bootstrap_sampler.py | relate_obs_ids_to_chosen_alts | def relate_obs_ids_to_chosen_alts(obs_id_array,
alt_id_array,
choice_array):
"""
Creates a dictionary that relates each unique alternative id to the set of
observations ids that chose the given alternative.
Parameters
----------
obs_id_array : 1D ndarray of ints.
Should be a long-format array of observation ids. Each element should
correspond to the unique id of the unit of observation that corresponds
to the given row of the long-format data. Note that each unit of
observation may have more than one associated choice situation.
alt_id_array : 1D ndarray of ints.
Should be a long-format array of alternative ids. Each element should
denote the unique id of the alternative that corresponds to the given
row of the long format data.
choice_array : 1D ndarray of ints.
Each element should be either a one or a zero, indicating whether the
alternative on the given row of the long format data was chosen or not.
Returns
-------
chosen_alts_to_obs_ids : dict.
Each key will be a unique value from `alt_id_array`. Each key's value
will be a 1D ndarray that contains the sorted, unique observation ids
of those observational units that chose the given alternative.
"""
# Figure out which units of observation chose each alternative.
chosen_alts_to_obs_ids = {}
for alt_id in np.sort(np.unique(alt_id_array)):
# Determine which observations chose the current alternative.
selection_condition =\
np.where((alt_id_array == alt_id) & (choice_array == 1))
# Store the sorted, unique ids that chose the current alternative.
chosen_alts_to_obs_ids[alt_id] =\
np.sort(np.unique(obs_id_array[selection_condition]))
# Return the desired dictionary.
return chosen_alts_to_obs_ids | python | def relate_obs_ids_to_chosen_alts(obs_id_array,
alt_id_array,
choice_array):
"""
Creates a dictionary that relates each unique alternative id to the set of
observations ids that chose the given alternative.
Parameters
----------
obs_id_array : 1D ndarray of ints.
Should be a long-format array of observation ids. Each element should
correspond to the unique id of the unit of observation that corresponds
to the given row of the long-format data. Note that each unit of
observation may have more than one associated choice situation.
alt_id_array : 1D ndarray of ints.
Should be a long-format array of alternative ids. Each element should
denote the unique id of the alternative that corresponds to the given
row of the long format data.
choice_array : 1D ndarray of ints.
Each element should be either a one or a zero, indicating whether the
alternative on the given row of the long format data was chosen or not.
Returns
-------
chosen_alts_to_obs_ids : dict.
Each key will be a unique value from `alt_id_array`. Each key's value
will be a 1D ndarray that contains the sorted, unique observation ids
of those observational units that chose the given alternative.
"""
# Figure out which units of observation chose each alternative.
chosen_alts_to_obs_ids = {}
for alt_id in np.sort(np.unique(alt_id_array)):
# Determine which observations chose the current alternative.
selection_condition =\
np.where((alt_id_array == alt_id) & (choice_array == 1))
# Store the sorted, unique ids that chose the current alternative.
chosen_alts_to_obs_ids[alt_id] =\
np.sort(np.unique(obs_id_array[selection_condition]))
# Return the desired dictionary.
return chosen_alts_to_obs_ids | [
"def",
"relate_obs_ids_to_chosen_alts",
"(",
"obs_id_array",
",",
"alt_id_array",
",",
"choice_array",
")",
":",
"# Figure out which units of observation chose each alternative.",
"chosen_alts_to_obs_ids",
"=",
"{",
"}",
"for",
"alt_id",
"in",
"np",
".",
"sort",
"(",
"np",
".",
"unique",
"(",
"alt_id_array",
")",
")",
":",
"# Determine which observations chose the current alternative.",
"selection_condition",
"=",
"np",
".",
"where",
"(",
"(",
"alt_id_array",
"==",
"alt_id",
")",
"&",
"(",
"choice_array",
"==",
"1",
")",
")",
"# Store the sorted, unique ids that chose the current alternative.",
"chosen_alts_to_obs_ids",
"[",
"alt_id",
"]",
"=",
"np",
".",
"sort",
"(",
"np",
".",
"unique",
"(",
"obs_id_array",
"[",
"selection_condition",
"]",
")",
")",
"# Return the desired dictionary.",
"return",
"chosen_alts_to_obs_ids"
] | Creates a dictionary that relates each unique alternative id to the set of
observations ids that chose the given alternative.
Parameters
----------
obs_id_array : 1D ndarray of ints.
Should be a long-format array of observation ids. Each element should
correspond to the unique id of the unit of observation that corresponds
to the given row of the long-format data. Note that each unit of
observation may have more than one associated choice situation.
alt_id_array : 1D ndarray of ints.
Should be a long-format array of alternative ids. Each element should
denote the unique id of the alternative that corresponds to the given
row of the long format data.
choice_array : 1D ndarray of ints.
Each element should be either a one or a zero, indicating whether the
alternative on the given row of the long format data was chosen or not.
Returns
-------
chosen_alts_to_obs_ids : dict.
Each key will be a unique value from `alt_id_array`. Each key's value
will be a 1D ndarray that contains the sorted, unique observation ids
of those observational units that chose the given alternative. | [
"Creates",
"a",
"dictionary",
"that",
"relates",
"each",
"unique",
"alternative",
"id",
"to",
"the",
"set",
"of",
"observations",
"ids",
"that",
"chose",
"the",
"given",
"alternative",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_sampler.py#L13-L55 | train | 233,688 |
timothyb0912/pylogit | pylogit/bootstrap_sampler.py | create_cross_sectional_bootstrap_samples | def create_cross_sectional_bootstrap_samples(obs_id_array,
alt_id_array,
choice_array,
num_samples,
seed=None):
"""
Determines the unique observations that will be present in each bootstrap
sample. This function DOES NOT create the new design matrices or a new
long-format dataframe for each bootstrap sample. Note that these will be
correct bootstrap samples for cross-sectional datasets. This function will
not work correctly for panel datasets.
Parameters
----------
obs_id_array : 1D ndarray of ints.
Each element should denote a unique observation id for the
corresponding row of the long format array.
alt_id_array : 1D ndarray of ints.
Each element should denote a unique alternative id for the
corresponding row of the long format array.
choice_array : 1D ndarray of ints.
Each element should be a one or a zero. The values should denote a
whether or not the corresponding alternative in `alt_id_array` was
chosen by the observational unit in the corresponding row of
`obs_id_array.`
num_samples : int.
Denotes the number of bootstrap samples that need to be drawn.
seed : non-negative int or None, optional.
Denotes the random seed to be used in order to ensure reproducibility
of the bootstrap sample generation. Default is None. If None, no seed
will be used and the generation of the bootstrap samples will (in
general) not be reproducible.
Returns
-------
ids_per_sample : 2D ndarray.
Each row represents a complete bootstrap sample. Each column denotes a
selected bootstrap observation that comprises the bootstrap sample. The
elements of the array denote the observation ids of the chosen
observational units.
"""
# Determine the units of observation that chose each alternative.
chosen_alts_to_obs_ids =\
relate_obs_ids_to_chosen_alts(obs_id_array, alt_id_array, choice_array)
# Determine the number of unique units of observation per group and overall
num_obs_per_group, tot_num_obs =\
get_num_obs_choosing_each_alternative(chosen_alts_to_obs_ids)
# Initialize the array that will store the observation ids for each sample
ids_per_sample = np.empty((num_samples, tot_num_obs), dtype=float)
if seed is not None:
# Check the validity of the seed argument.
if not isinstance(seed, int):
msg = "`boot_seed` MUST be an int."
raise ValueError(msg)
# If desiring reproducibility, set the random seed within numpy
np.random.seed(seed)
# Initialize a variable to keep track of what column we're on.
col_idx = 0
for alt_id in num_obs_per_group:
# Get the set of observations that chose the current alternative.
relevant_ids = chosen_alts_to_obs_ids[alt_id]
# Determine the number of needed resampled ids.
resample_size = num_obs_per_group[alt_id]
# Resample, with replacement, observations who chose this alternative.
current_ids = (np.random.choice(relevant_ids,
size=resample_size * num_samples,
replace=True)
.reshape((num_samples, resample_size)))
# Determine the last column index to use when storing the resampled ids
end_col = col_idx + resample_size
# Assign the sampled ids to the correct columns of ids_per_sample
ids_per_sample[:, col_idx:end_col] = current_ids
# Update the column index
col_idx += resample_size
# Return the resampled observation ids.
return ids_per_sample | python | def create_cross_sectional_bootstrap_samples(obs_id_array,
alt_id_array,
choice_array,
num_samples,
seed=None):
"""
Determines the unique observations that will be present in each bootstrap
sample. This function DOES NOT create the new design matrices or a new
long-format dataframe for each bootstrap sample. Note that these will be
correct bootstrap samples for cross-sectional datasets. This function will
not work correctly for panel datasets.
Parameters
----------
obs_id_array : 1D ndarray of ints.
Each element should denote a unique observation id for the
corresponding row of the long format array.
alt_id_array : 1D ndarray of ints.
Each element should denote a unique alternative id for the
corresponding row of the long format array.
choice_array : 1D ndarray of ints.
Each element should be a one or a zero. The values should denote a
whether or not the corresponding alternative in `alt_id_array` was
chosen by the observational unit in the corresponding row of
`obs_id_array.`
num_samples : int.
Denotes the number of bootstrap samples that need to be drawn.
seed : non-negative int or None, optional.
Denotes the random seed to be used in order to ensure reproducibility
of the bootstrap sample generation. Default is None. If None, no seed
will be used and the generation of the bootstrap samples will (in
general) not be reproducible.
Returns
-------
ids_per_sample : 2D ndarray.
Each row represents a complete bootstrap sample. Each column denotes a
selected bootstrap observation that comprises the bootstrap sample. The
elements of the array denote the observation ids of the chosen
observational units.
"""
# Determine the units of observation that chose each alternative.
chosen_alts_to_obs_ids =\
relate_obs_ids_to_chosen_alts(obs_id_array, alt_id_array, choice_array)
# Determine the number of unique units of observation per group and overall
num_obs_per_group, tot_num_obs =\
get_num_obs_choosing_each_alternative(chosen_alts_to_obs_ids)
# Initialize the array that will store the observation ids for each sample
ids_per_sample = np.empty((num_samples, tot_num_obs), dtype=float)
if seed is not None:
# Check the validity of the seed argument.
if not isinstance(seed, int):
msg = "`boot_seed` MUST be an int."
raise ValueError(msg)
# If desiring reproducibility, set the random seed within numpy
np.random.seed(seed)
# Initialize a variable to keep track of what column we're on.
col_idx = 0
for alt_id in num_obs_per_group:
# Get the set of observations that chose the current alternative.
relevant_ids = chosen_alts_to_obs_ids[alt_id]
# Determine the number of needed resampled ids.
resample_size = num_obs_per_group[alt_id]
# Resample, with replacement, observations who chose this alternative.
current_ids = (np.random.choice(relevant_ids,
size=resample_size * num_samples,
replace=True)
.reshape((num_samples, resample_size)))
# Determine the last column index to use when storing the resampled ids
end_col = col_idx + resample_size
# Assign the sampled ids to the correct columns of ids_per_sample
ids_per_sample[:, col_idx:end_col] = current_ids
# Update the column index
col_idx += resample_size
# Return the resampled observation ids.
return ids_per_sample | [
"def",
"create_cross_sectional_bootstrap_samples",
"(",
"obs_id_array",
",",
"alt_id_array",
",",
"choice_array",
",",
"num_samples",
",",
"seed",
"=",
"None",
")",
":",
"# Determine the units of observation that chose each alternative.",
"chosen_alts_to_obs_ids",
"=",
"relate_obs_ids_to_chosen_alts",
"(",
"obs_id_array",
",",
"alt_id_array",
",",
"choice_array",
")",
"# Determine the number of unique units of observation per group and overall",
"num_obs_per_group",
",",
"tot_num_obs",
"=",
"get_num_obs_choosing_each_alternative",
"(",
"chosen_alts_to_obs_ids",
")",
"# Initialize the array that will store the observation ids for each sample",
"ids_per_sample",
"=",
"np",
".",
"empty",
"(",
"(",
"num_samples",
",",
"tot_num_obs",
")",
",",
"dtype",
"=",
"float",
")",
"if",
"seed",
"is",
"not",
"None",
":",
"# Check the validity of the seed argument.",
"if",
"not",
"isinstance",
"(",
"seed",
",",
"int",
")",
":",
"msg",
"=",
"\"`boot_seed` MUST be an int.\"",
"raise",
"ValueError",
"(",
"msg",
")",
"# If desiring reproducibility, set the random seed within numpy",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"# Initialize a variable to keep track of what column we're on.",
"col_idx",
"=",
"0",
"for",
"alt_id",
"in",
"num_obs_per_group",
":",
"# Get the set of observations that chose the current alternative.",
"relevant_ids",
"=",
"chosen_alts_to_obs_ids",
"[",
"alt_id",
"]",
"# Determine the number of needed resampled ids.",
"resample_size",
"=",
"num_obs_per_group",
"[",
"alt_id",
"]",
"# Resample, with replacement, observations who chose this alternative.",
"current_ids",
"=",
"(",
"np",
".",
"random",
".",
"choice",
"(",
"relevant_ids",
",",
"size",
"=",
"resample_size",
"*",
"num_samples",
",",
"replace",
"=",
"True",
")",
".",
"reshape",
"(",
"(",
"num_samples",
",",
"resample_size",
")",
")",
")",
"# Determine the last column index to use when storing the resampled ids",
"end_col",
"=",
"col_idx",
"+",
"resample_size",
"# Assign the sampled ids to the correct columns of ids_per_sample",
"ids_per_sample",
"[",
":",
",",
"col_idx",
":",
"end_col",
"]",
"=",
"current_ids",
"# Update the column index",
"col_idx",
"+=",
"resample_size",
"# Return the resampled observation ids.",
"return",
"ids_per_sample"
] | Determines the unique observations that will be present in each bootstrap
sample. This function DOES NOT create the new design matrices or a new
long-format dataframe for each bootstrap sample. Note that these will be
correct bootstrap samples for cross-sectional datasets. This function will
not work correctly for panel datasets.
Parameters
----------
obs_id_array : 1D ndarray of ints.
Each element should denote a unique observation id for the
corresponding row of the long format array.
alt_id_array : 1D ndarray of ints.
Each element should denote a unique alternative id for the
corresponding row of the long format array.
choice_array : 1D ndarray of ints.
Each element should be a one or a zero. The values should denote a
whether or not the corresponding alternative in `alt_id_array` was
chosen by the observational unit in the corresponding row of
`obs_id_array.`
num_samples : int.
Denotes the number of bootstrap samples that need to be drawn.
seed : non-negative int or None, optional.
Denotes the random seed to be used in order to ensure reproducibility
of the bootstrap sample generation. Default is None. If None, no seed
will be used and the generation of the bootstrap samples will (in
general) not be reproducible.
Returns
-------
ids_per_sample : 2D ndarray.
Each row represents a complete bootstrap sample. Each column denotes a
selected bootstrap observation that comprises the bootstrap sample. The
elements of the array denote the observation ids of the chosen
observational units. | [
"Determines",
"the",
"unique",
"observations",
"that",
"will",
"be",
"present",
"in",
"each",
"bootstrap",
"sample",
".",
"This",
"function",
"DOES",
"NOT",
"create",
"the",
"new",
"design",
"matrices",
"or",
"a",
"new",
"long",
"-",
"format",
"dataframe",
"for",
"each",
"bootstrap",
"sample",
".",
"Note",
"that",
"these",
"will",
"be",
"correct",
"bootstrap",
"samples",
"for",
"cross",
"-",
"sectional",
"datasets",
".",
"This",
"function",
"will",
"not",
"work",
"correctly",
"for",
"panel",
"datasets",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_sampler.py#L95-L177 | train | 233,689 |
timothyb0912/pylogit | pylogit/bootstrap_sampler.py | create_bootstrap_id_array | def create_bootstrap_id_array(obs_id_per_sample):
"""
Creates a 2D ndarray that contains the 'bootstrap ids' for each replication
of each unit of observation that is an the set of bootstrap samples.
Parameters
----------
obs_id_per_sample : 2D ndarray of ints.
Should have one row for each bootsrap sample. Should have one column
for each observational unit that is serving as a new bootstrap
observational unit.
Returns
-------
bootstrap_id_array : 2D ndarray of ints.
Will have the same shape as `obs_id_per_sample`. Each element will
denote the fake observational id in the new bootstrap dataset.
"""
# Determine the shape of the object to be returned.
n_rows, n_cols = obs_id_per_sample.shape
# Create the array of bootstrap ids.
bootstrap_id_array =\
np.tile(np.arange(n_cols) + 1, n_rows).reshape((n_rows, n_cols))
# Return the desired object
return bootstrap_id_array | python | def create_bootstrap_id_array(obs_id_per_sample):
"""
Creates a 2D ndarray that contains the 'bootstrap ids' for each replication
of each unit of observation that is an the set of bootstrap samples.
Parameters
----------
obs_id_per_sample : 2D ndarray of ints.
Should have one row for each bootsrap sample. Should have one column
for each observational unit that is serving as a new bootstrap
observational unit.
Returns
-------
bootstrap_id_array : 2D ndarray of ints.
Will have the same shape as `obs_id_per_sample`. Each element will
denote the fake observational id in the new bootstrap dataset.
"""
# Determine the shape of the object to be returned.
n_rows, n_cols = obs_id_per_sample.shape
# Create the array of bootstrap ids.
bootstrap_id_array =\
np.tile(np.arange(n_cols) + 1, n_rows).reshape((n_rows, n_cols))
# Return the desired object
return bootstrap_id_array | [
"def",
"create_bootstrap_id_array",
"(",
"obs_id_per_sample",
")",
":",
"# Determine the shape of the object to be returned.",
"n_rows",
",",
"n_cols",
"=",
"obs_id_per_sample",
".",
"shape",
"# Create the array of bootstrap ids.",
"bootstrap_id_array",
"=",
"np",
".",
"tile",
"(",
"np",
".",
"arange",
"(",
"n_cols",
")",
"+",
"1",
",",
"n_rows",
")",
".",
"reshape",
"(",
"(",
"n_rows",
",",
"n_cols",
")",
")",
"# Return the desired object",
"return",
"bootstrap_id_array"
] | Creates a 2D ndarray that contains the 'bootstrap ids' for each replication
of each unit of observation that is an the set of bootstrap samples.
Parameters
----------
obs_id_per_sample : 2D ndarray of ints.
Should have one row for each bootsrap sample. Should have one column
for each observational unit that is serving as a new bootstrap
observational unit.
Returns
-------
bootstrap_id_array : 2D ndarray of ints.
Will have the same shape as `obs_id_per_sample`. Each element will
denote the fake observational id in the new bootstrap dataset. | [
"Creates",
"a",
"2D",
"ndarray",
"that",
"contains",
"the",
"bootstrap",
"ids",
"for",
"each",
"replication",
"of",
"each",
"unit",
"of",
"observation",
"that",
"is",
"an",
"the",
"set",
"of",
"bootstrap",
"samples",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_sampler.py#L180-L204 | train | 233,690 |
timothyb0912/pylogit | pylogit/bootstrap_sampler.py | check_column_existence | def check_column_existence(col_name, df, presence=True):
"""
Checks whether or not `col_name` is in `df` and raises a helpful error msg
if the desired condition is not met.
Parameters
----------
col_name : str.
Should represent a column whose presence in `df` is to be checked.
df : pandas DataFrame.
The dataframe that will be checked for the presence of `col_name`.
presence : bool, optional.
If True, then this function checks for the PRESENCE of `col_name` from
`df`. If False, then this function checks for the ABSENCE of
`col_name` in `df`. Default == True.
Returns
-------
None.
"""
if presence:
if col_name not in df.columns:
msg = "Ensure that `{}` is in `df.columns`."
raise ValueError(msg.format(col_name))
else:
if col_name in df.columns:
msg = "Ensure that `{}` is not in `df.columns`."
raise ValueError(msg.format(col_name))
return None | python | def check_column_existence(col_name, df, presence=True):
"""
Checks whether or not `col_name` is in `df` and raises a helpful error msg
if the desired condition is not met.
Parameters
----------
col_name : str.
Should represent a column whose presence in `df` is to be checked.
df : pandas DataFrame.
The dataframe that will be checked for the presence of `col_name`.
presence : bool, optional.
If True, then this function checks for the PRESENCE of `col_name` from
`df`. If False, then this function checks for the ABSENCE of
`col_name` in `df`. Default == True.
Returns
-------
None.
"""
if presence:
if col_name not in df.columns:
msg = "Ensure that `{}` is in `df.columns`."
raise ValueError(msg.format(col_name))
else:
if col_name in df.columns:
msg = "Ensure that `{}` is not in `df.columns`."
raise ValueError(msg.format(col_name))
return None | [
"def",
"check_column_existence",
"(",
"col_name",
",",
"df",
",",
"presence",
"=",
"True",
")",
":",
"if",
"presence",
":",
"if",
"col_name",
"not",
"in",
"df",
".",
"columns",
":",
"msg",
"=",
"\"Ensure that `{}` is in `df.columns`.\"",
"raise",
"ValueError",
"(",
"msg",
".",
"format",
"(",
"col_name",
")",
")",
"else",
":",
"if",
"col_name",
"in",
"df",
".",
"columns",
":",
"msg",
"=",
"\"Ensure that `{}` is not in `df.columns`.\"",
"raise",
"ValueError",
"(",
"msg",
".",
"format",
"(",
"col_name",
")",
")",
"return",
"None"
] | Checks whether or not `col_name` is in `df` and raises a helpful error msg
if the desired condition is not met.
Parameters
----------
col_name : str.
Should represent a column whose presence in `df` is to be checked.
df : pandas DataFrame.
The dataframe that will be checked for the presence of `col_name`.
presence : bool, optional.
If True, then this function checks for the PRESENCE of `col_name` from
`df`. If False, then this function checks for the ABSENCE of
`col_name` in `df`. Default == True.
Returns
-------
None. | [
"Checks",
"whether",
"or",
"not",
"col_name",
"is",
"in",
"df",
"and",
"raises",
"a",
"helpful",
"error",
"msg",
"if",
"the",
"desired",
"condition",
"is",
"not",
"met",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_sampler.py#L245-L273 | train | 233,691 |
timothyb0912/pylogit | pylogit/bootstrap_sampler.py | ensure_resampled_obs_ids_in_df | def ensure_resampled_obs_ids_in_df(resampled_obs_ids, orig_obs_id_array):
"""
Checks whether all ids in `resampled_obs_ids` are in `orig_obs_id_array`.
Raises a helpful ValueError if not.
Parameters
----------
resampled_obs_ids : 1D ndarray of ints.
Should contain the observation ids of the observational units that will
be used in the current bootstrap sample.
orig_obs_id_array : 1D ndarray of ints.
Should countain the observation ids of the observational units in the
original dataframe containing the data for this model.
Returns
-------
None.
"""
if not np.in1d(resampled_obs_ids, orig_obs_id_array).all():
msg =\
"All values in `resampled_obs_ids` MUST be in `orig_obs_id_array`."
raise ValueError(msg)
return None | python | def ensure_resampled_obs_ids_in_df(resampled_obs_ids, orig_obs_id_array):
"""
Checks whether all ids in `resampled_obs_ids` are in `orig_obs_id_array`.
Raises a helpful ValueError if not.
Parameters
----------
resampled_obs_ids : 1D ndarray of ints.
Should contain the observation ids of the observational units that will
be used in the current bootstrap sample.
orig_obs_id_array : 1D ndarray of ints.
Should countain the observation ids of the observational units in the
original dataframe containing the data for this model.
Returns
-------
None.
"""
if not np.in1d(resampled_obs_ids, orig_obs_id_array).all():
msg =\
"All values in `resampled_obs_ids` MUST be in `orig_obs_id_array`."
raise ValueError(msg)
return None | [
"def",
"ensure_resampled_obs_ids_in_df",
"(",
"resampled_obs_ids",
",",
"orig_obs_id_array",
")",
":",
"if",
"not",
"np",
".",
"in1d",
"(",
"resampled_obs_ids",
",",
"orig_obs_id_array",
")",
".",
"all",
"(",
")",
":",
"msg",
"=",
"\"All values in `resampled_obs_ids` MUST be in `orig_obs_id_array`.\"",
"raise",
"ValueError",
"(",
"msg",
")",
"return",
"None"
] | Checks whether all ids in `resampled_obs_ids` are in `orig_obs_id_array`.
Raises a helpful ValueError if not.
Parameters
----------
resampled_obs_ids : 1D ndarray of ints.
Should contain the observation ids of the observational units that will
be used in the current bootstrap sample.
orig_obs_id_array : 1D ndarray of ints.
Should countain the observation ids of the observational units in the
original dataframe containing the data for this model.
Returns
-------
None. | [
"Checks",
"whether",
"all",
"ids",
"in",
"resampled_obs_ids",
"are",
"in",
"orig_obs_id_array",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"not",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_sampler.py#L276-L298 | train | 233,692 |
timothyb0912/pylogit | pylogit/bootstrap_sampler.py | create_bootstrap_dataframe | def create_bootstrap_dataframe(orig_df,
obs_id_col,
resampled_obs_ids_1d,
groupby_dict,
boot_id_col="bootstrap_id"):
"""
Will create the altered dataframe of data needed to estimate a choice model
with the particular observations that belong to the current bootstrap
sample.
Parameters
----------
orig_df : pandas DataFrame.
Should be long-format dataframe containing the data used to estimate
the desired choice model.
obs_id_col : str.
Should be a column name within `orig_df`. Should denote the original
observation id column.
resampled_obs_ids_1d : 1D ndarray of ints.
Each value should represent the alternative id of a given bootstrap
replicate.
groupby_dict : dict.
Each key will be a unique value in `orig_df[obs_id_col]` and each value
will be the rows of `orig_df` where `orig_df[obs_id_col] == key`.
boot_id_col : str, optional.
Denotes the new column that will be created to specify the bootstrap
observation ids for choice model estimation.
Returns
-------
bootstrap_df : pandas Dataframe.
Will contain all the same columns as `orig_df` as well as the
additional `boot_id_col`. For each value in `resampled_obs_ids_1d`,
`bootstrap_df` will contain the long format rows from `orig_df` that
have the given observation id.
"""
# Check the validity of the passed arguments.
check_column_existence(obs_id_col, orig_df, presence=True)
check_column_existence(boot_id_col, orig_df, presence=False)
# Alias the observation id column
obs_id_values = orig_df[obs_id_col].values
# Check the validity of the resampled observation ids.
ensure_resampled_obs_ids_in_df(resampled_obs_ids_1d, obs_id_values)
# Initialize a list to store the component dataframes that will be
# concatenated to form the final bootstrap_df
component_dfs = []
# Populate component_dfs
for boot_id, obs_id in enumerate(resampled_obs_ids_1d):
# Extract the dataframe that we desire.
extracted_df = groupby_dict[obs_id].copy()
# Add the bootstrap id value.
extracted_df[boot_id_col] = boot_id + 1
# Store the component dataframe
component_dfs.append(extracted_df)
# Create and return the desired dataframe.
bootstrap_df = pd.concat(component_dfs, axis=0, ignore_index=True)
return bootstrap_df | python | def create_bootstrap_dataframe(orig_df,
obs_id_col,
resampled_obs_ids_1d,
groupby_dict,
boot_id_col="bootstrap_id"):
"""
Will create the altered dataframe of data needed to estimate a choice model
with the particular observations that belong to the current bootstrap
sample.
Parameters
----------
orig_df : pandas DataFrame.
Should be long-format dataframe containing the data used to estimate
the desired choice model.
obs_id_col : str.
Should be a column name within `orig_df`. Should denote the original
observation id column.
resampled_obs_ids_1d : 1D ndarray of ints.
Each value should represent the alternative id of a given bootstrap
replicate.
groupby_dict : dict.
Each key will be a unique value in `orig_df[obs_id_col]` and each value
will be the rows of `orig_df` where `orig_df[obs_id_col] == key`.
boot_id_col : str, optional.
Denotes the new column that will be created to specify the bootstrap
observation ids for choice model estimation.
Returns
-------
bootstrap_df : pandas Dataframe.
Will contain all the same columns as `orig_df` as well as the
additional `boot_id_col`. For each value in `resampled_obs_ids_1d`,
`bootstrap_df` will contain the long format rows from `orig_df` that
have the given observation id.
"""
# Check the validity of the passed arguments.
check_column_existence(obs_id_col, orig_df, presence=True)
check_column_existence(boot_id_col, orig_df, presence=False)
# Alias the observation id column
obs_id_values = orig_df[obs_id_col].values
# Check the validity of the resampled observation ids.
ensure_resampled_obs_ids_in_df(resampled_obs_ids_1d, obs_id_values)
# Initialize a list to store the component dataframes that will be
# concatenated to form the final bootstrap_df
component_dfs = []
# Populate component_dfs
for boot_id, obs_id in enumerate(resampled_obs_ids_1d):
# Extract the dataframe that we desire.
extracted_df = groupby_dict[obs_id].copy()
# Add the bootstrap id value.
extracted_df[boot_id_col] = boot_id + 1
# Store the component dataframe
component_dfs.append(extracted_df)
# Create and return the desired dataframe.
bootstrap_df = pd.concat(component_dfs, axis=0, ignore_index=True)
return bootstrap_df | [
"def",
"create_bootstrap_dataframe",
"(",
"orig_df",
",",
"obs_id_col",
",",
"resampled_obs_ids_1d",
",",
"groupby_dict",
",",
"boot_id_col",
"=",
"\"bootstrap_id\"",
")",
":",
"# Check the validity of the passed arguments.",
"check_column_existence",
"(",
"obs_id_col",
",",
"orig_df",
",",
"presence",
"=",
"True",
")",
"check_column_existence",
"(",
"boot_id_col",
",",
"orig_df",
",",
"presence",
"=",
"False",
")",
"# Alias the observation id column",
"obs_id_values",
"=",
"orig_df",
"[",
"obs_id_col",
"]",
".",
"values",
"# Check the validity of the resampled observation ids.",
"ensure_resampled_obs_ids_in_df",
"(",
"resampled_obs_ids_1d",
",",
"obs_id_values",
")",
"# Initialize a list to store the component dataframes that will be",
"# concatenated to form the final bootstrap_df",
"component_dfs",
"=",
"[",
"]",
"# Populate component_dfs",
"for",
"boot_id",
",",
"obs_id",
"in",
"enumerate",
"(",
"resampled_obs_ids_1d",
")",
":",
"# Extract the dataframe that we desire.",
"extracted_df",
"=",
"groupby_dict",
"[",
"obs_id",
"]",
".",
"copy",
"(",
")",
"# Add the bootstrap id value.",
"extracted_df",
"[",
"boot_id_col",
"]",
"=",
"boot_id",
"+",
"1",
"# Store the component dataframe",
"component_dfs",
".",
"append",
"(",
"extracted_df",
")",
"# Create and return the desired dataframe.",
"bootstrap_df",
"=",
"pd",
".",
"concat",
"(",
"component_dfs",
",",
"axis",
"=",
"0",
",",
"ignore_index",
"=",
"True",
")",
"return",
"bootstrap_df"
] | Will create the altered dataframe of data needed to estimate a choice model
with the particular observations that belong to the current bootstrap
sample.
Parameters
----------
orig_df : pandas DataFrame.
Should be long-format dataframe containing the data used to estimate
the desired choice model.
obs_id_col : str.
Should be a column name within `orig_df`. Should denote the original
observation id column.
resampled_obs_ids_1d : 1D ndarray of ints.
Each value should represent the alternative id of a given bootstrap
replicate.
groupby_dict : dict.
Each key will be a unique value in `orig_df[obs_id_col]` and each value
will be the rows of `orig_df` where `orig_df[obs_id_col] == key`.
boot_id_col : str, optional.
Denotes the new column that will be created to specify the bootstrap
observation ids for choice model estimation.
Returns
-------
bootstrap_df : pandas Dataframe.
Will contain all the same columns as `orig_df` as well as the
additional `boot_id_col`. For each value in `resampled_obs_ids_1d`,
`bootstrap_df` will contain the long format rows from `orig_df` that
have the given observation id. | [
"Will",
"create",
"the",
"altered",
"dataframe",
"of",
"data",
"needed",
"to",
"estimate",
"a",
"choice",
"model",
"with",
"the",
"particular",
"observations",
"that",
"belong",
"to",
"the",
"current",
"bootstrap",
"sample",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_sampler.py#L301-L360 | train | 233,693 |
timothyb0912/pylogit | pylogit/bootstrap.py | get_param_names | def get_param_names(model_obj):
"""
Extracts all the names to be displayed for the estimated parameters.
Parameters
----------
model_obj : an instance of an MNDC object.
Should have the following attributes:
`['ind_var_names', 'intercept_names', 'shape_names', 'nest_names']`.
Returns
-------
all_names : list of strings.
There will be one element for each estimated parameter. The order of
the parameter names will be
`['nest_parameters', 'shape_parameters', 'outside_intercepts',
'index_coefficients']`.
"""
# Get the index coefficient names
all_names = deepcopy(model_obj.ind_var_names)
# Add the intercept names if any exist
if model_obj.intercept_names is not None:
all_names = model_obj.intercept_names + all_names
# Add the shape names if any exist
if model_obj.shape_names is not None:
all_names = model_obj.shape_names + all_names
# Add the nest names if any exist
if model_obj.nest_names is not None:
all_names = model_obj.nest_names + all_names
return all_names | python | def get_param_names(model_obj):
"""
Extracts all the names to be displayed for the estimated parameters.
Parameters
----------
model_obj : an instance of an MNDC object.
Should have the following attributes:
`['ind_var_names', 'intercept_names', 'shape_names', 'nest_names']`.
Returns
-------
all_names : list of strings.
There will be one element for each estimated parameter. The order of
the parameter names will be
`['nest_parameters', 'shape_parameters', 'outside_intercepts',
'index_coefficients']`.
"""
# Get the index coefficient names
all_names = deepcopy(model_obj.ind_var_names)
# Add the intercept names if any exist
if model_obj.intercept_names is not None:
all_names = model_obj.intercept_names + all_names
# Add the shape names if any exist
if model_obj.shape_names is not None:
all_names = model_obj.shape_names + all_names
# Add the nest names if any exist
if model_obj.nest_names is not None:
all_names = model_obj.nest_names + all_names
return all_names | [
"def",
"get_param_names",
"(",
"model_obj",
")",
":",
"# Get the index coefficient names",
"all_names",
"=",
"deepcopy",
"(",
"model_obj",
".",
"ind_var_names",
")",
"# Add the intercept names if any exist",
"if",
"model_obj",
".",
"intercept_names",
"is",
"not",
"None",
":",
"all_names",
"=",
"model_obj",
".",
"intercept_names",
"+",
"all_names",
"# Add the shape names if any exist",
"if",
"model_obj",
".",
"shape_names",
"is",
"not",
"None",
":",
"all_names",
"=",
"model_obj",
".",
"shape_names",
"+",
"all_names",
"# Add the nest names if any exist",
"if",
"model_obj",
".",
"nest_names",
"is",
"not",
"None",
":",
"all_names",
"=",
"model_obj",
".",
"nest_names",
"+",
"all_names",
"return",
"all_names"
] | Extracts all the names to be displayed for the estimated parameters.
Parameters
----------
model_obj : an instance of an MNDC object.
Should have the following attributes:
`['ind_var_names', 'intercept_names', 'shape_names', 'nest_names']`.
Returns
-------
all_names : list of strings.
There will be one element for each estimated parameter. The order of
the parameter names will be
`['nest_parameters', 'shape_parameters', 'outside_intercepts',
'index_coefficients']`. | [
"Extracts",
"all",
"the",
"names",
"to",
"be",
"displayed",
"for",
"the",
"estimated",
"parameters",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L46-L75 | train | 233,694 |
timothyb0912/pylogit | pylogit/bootstrap.py | get_param_list_for_prediction | def get_param_list_for_prediction(model_obj, replicates):
"""
Create the `param_list` argument for use with `model_obj.predict`.
Parameters
----------
model_obj : an instance of an MNDC object.
Should have the following attributes:
`['ind_var_names', 'intercept_names', 'shape_names', 'nest_names']`.
This model should have already undergone a complete estimation process.
I.e. its `fit_mle` method should have been called without
`just_point=True`.
replicates : 2D ndarray.
Should represent the set of parameter values that we now wish to
partition for use with the `model_obj.predict` method.
Returns
-------
param_list : list.
Contains four elements, each being a numpy array. Either all of the
arrays should be 1D or all of the arrays should be 2D. If 2D, the
arrays should have the same number of columns. Each column being a
particular set of parameter values that one wants to predict with.
The first element in the list should be the index coefficients. The
second element should contain the 'outside' intercept parameters if
there are any, or None otherwise. The third element should contain
the shape parameters if there are any or None otherwise. The fourth
element should contain the nest coefficients if there are any or
None otherwise. Default == None.
"""
# Check the validity of the passed arguments
ensure_samples_is_ndim_ndarray(replicates, ndim=2, name='replicates')
# Determine the number of index coefficients, outside intercepts,
# shape parameters, and nest parameters
num_idx_coefs = len(model_obj.ind_var_names)
intercept_names = model_obj.intercept_names
num_outside_intercepts =\
0 if intercept_names is None else len(intercept_names)
shape_names = model_obj.shape_names
num_shapes = 0 if shape_names is None else len(shape_names)
nest_names = model_obj.nest_names
num_nests = 0 if nest_names is None else len(nest_names)
parameter_numbers =\
[num_nests, num_shapes, num_outside_intercepts, num_idx_coefs]
current_idx = 0
param_list = []
for param_num in parameter_numbers:
if param_num == 0:
param_list.insert(0, None)
continue
upper_idx = current_idx + param_num
param_list.insert(0, replicates[:, current_idx:upper_idx].T)
current_idx += param_num
return param_list | python | def get_param_list_for_prediction(model_obj, replicates):
"""
Create the `param_list` argument for use with `model_obj.predict`.
Parameters
----------
model_obj : an instance of an MNDC object.
Should have the following attributes:
`['ind_var_names', 'intercept_names', 'shape_names', 'nest_names']`.
This model should have already undergone a complete estimation process.
I.e. its `fit_mle` method should have been called without
`just_point=True`.
replicates : 2D ndarray.
Should represent the set of parameter values that we now wish to
partition for use with the `model_obj.predict` method.
Returns
-------
param_list : list.
Contains four elements, each being a numpy array. Either all of the
arrays should be 1D or all of the arrays should be 2D. If 2D, the
arrays should have the same number of columns. Each column being a
particular set of parameter values that one wants to predict with.
The first element in the list should be the index coefficients. The
second element should contain the 'outside' intercept parameters if
there are any, or None otherwise. The third element should contain
the shape parameters if there are any or None otherwise. The fourth
element should contain the nest coefficients if there are any or
None otherwise. Default == None.
"""
# Check the validity of the passed arguments
ensure_samples_is_ndim_ndarray(replicates, ndim=2, name='replicates')
# Determine the number of index coefficients, outside intercepts,
# shape parameters, and nest parameters
num_idx_coefs = len(model_obj.ind_var_names)
intercept_names = model_obj.intercept_names
num_outside_intercepts =\
0 if intercept_names is None else len(intercept_names)
shape_names = model_obj.shape_names
num_shapes = 0 if shape_names is None else len(shape_names)
nest_names = model_obj.nest_names
num_nests = 0 if nest_names is None else len(nest_names)
parameter_numbers =\
[num_nests, num_shapes, num_outside_intercepts, num_idx_coefs]
current_idx = 0
param_list = []
for param_num in parameter_numbers:
if param_num == 0:
param_list.insert(0, None)
continue
upper_idx = current_idx + param_num
param_list.insert(0, replicates[:, current_idx:upper_idx].T)
current_idx += param_num
return param_list | [
"def",
"get_param_list_for_prediction",
"(",
"model_obj",
",",
"replicates",
")",
":",
"# Check the validity of the passed arguments",
"ensure_samples_is_ndim_ndarray",
"(",
"replicates",
",",
"ndim",
"=",
"2",
",",
"name",
"=",
"'replicates'",
")",
"# Determine the number of index coefficients, outside intercepts,",
"# shape parameters, and nest parameters",
"num_idx_coefs",
"=",
"len",
"(",
"model_obj",
".",
"ind_var_names",
")",
"intercept_names",
"=",
"model_obj",
".",
"intercept_names",
"num_outside_intercepts",
"=",
"0",
"if",
"intercept_names",
"is",
"None",
"else",
"len",
"(",
"intercept_names",
")",
"shape_names",
"=",
"model_obj",
".",
"shape_names",
"num_shapes",
"=",
"0",
"if",
"shape_names",
"is",
"None",
"else",
"len",
"(",
"shape_names",
")",
"nest_names",
"=",
"model_obj",
".",
"nest_names",
"num_nests",
"=",
"0",
"if",
"nest_names",
"is",
"None",
"else",
"len",
"(",
"nest_names",
")",
"parameter_numbers",
"=",
"[",
"num_nests",
",",
"num_shapes",
",",
"num_outside_intercepts",
",",
"num_idx_coefs",
"]",
"current_idx",
"=",
"0",
"param_list",
"=",
"[",
"]",
"for",
"param_num",
"in",
"parameter_numbers",
":",
"if",
"param_num",
"==",
"0",
":",
"param_list",
".",
"insert",
"(",
"0",
",",
"None",
")",
"continue",
"upper_idx",
"=",
"current_idx",
"+",
"param_num",
"param_list",
".",
"insert",
"(",
"0",
",",
"replicates",
"[",
":",
",",
"current_idx",
":",
"upper_idx",
"]",
".",
"T",
")",
"current_idx",
"+=",
"param_num",
"return",
"param_list"
] | Create the `param_list` argument for use with `model_obj.predict`.
Parameters
----------
model_obj : an instance of an MNDC object.
Should have the following attributes:
`['ind_var_names', 'intercept_names', 'shape_names', 'nest_names']`.
This model should have already undergone a complete estimation process.
I.e. its `fit_mle` method should have been called without
`just_point=True`.
replicates : 2D ndarray.
Should represent the set of parameter values that we now wish to
partition for use with the `model_obj.predict` method.
Returns
-------
param_list : list.
Contains four elements, each being a numpy array. Either all of the
arrays should be 1D or all of the arrays should be 2D. If 2D, the
arrays should have the same number of columns. Each column being a
particular set of parameter values that one wants to predict with.
The first element in the list should be the index coefficients. The
second element should contain the 'outside' intercept parameters if
there are any, or None otherwise. The third element should contain
the shape parameters if there are any or None otherwise. The fourth
element should contain the nest coefficients if there are any or
None otherwise. Default == None. | [
"Create",
"the",
"param_list",
"argument",
"for",
"use",
"with",
"model_obj",
".",
"predict",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L78-L135 | train | 233,695 |
timothyb0912/pylogit | pylogit/bootstrap.py | Boot.generate_bootstrap_replicates | def generate_bootstrap_replicates(self,
num_samples,
mnl_obj=None,
mnl_init_vals=None,
mnl_fit_kwargs=None,
extract_init_vals=None,
print_res=False,
method="BFGS",
loss_tol=1e-06,
gradient_tol=1e-06,
maxiter=1000,
ridge=None,
constrained_pos=None,
boot_seed=None,
weights=None):
"""
Generates the bootstrap replicates for one's given model and dataset.
Parameters
----------
num_samples : positive int.
Specifies the number of bootstrap samples that are to be drawn.
mnl_obj : an instance of pylogit.MNL or None, optional.
Should be the MNL model object that is used to provide starting
values for the final model being estimated. If None, then one's
final model should be an MNL model. Default == None.
mnl_init_vals : 1D ndarray or None, optional.
If the model that is being estimated is not an MNL, then
`mnl_init_val` should be passed. Should contain the values used to
begin the estimation process for the MNL model that is used to
provide starting values for our desired model. Default == None.
mnl_fit_kwargs : dict or None.
If the model that is being estimated is not an MNL, then
`mnl_fit_kwargs` should be passed.
extract_init_vals : callable or None, optional.
Should accept 3 arguments, in the following order. First, it should
accept `orig_model_obj`. Second, it should accept a pandas Series
of estimated parameters from the MNL model. The Series' index will
be the names of the coefficients from `mnl_names`. Thirdly, it
should accept an int denoting the number of parameters in the final
choice model. The callable should return a 1D ndarray of starting
values for the final choice model. Default == None.
print_res : bool, optional.
Determines whether the timing and initial and final log likelihood
results will be printed as they they are determined.
Default `== True`.
method : str, optional.
Should be a valid string for scipy.optimize.minimize. Determines
the optimization algorithm that is used for this problem.
Default `== 'bfgs'`.
loss_tol : float, optional.
Determines the tolerance on the difference in objective function
values from one iteration to the next that is needed to determine
convergence. Default `== 1e-06`.
gradient_tol : float, optional.
Determines the tolerance on the difference in gradient values from
one iteration to the next which is needed to determine convergence.
Default `== 1e-06`.
maxiter : int, optional.
Determines the maximum number of iterations used by the optimizer.
Default `== 1000`.
ridge : int, float, long, or None, optional.
Determines whether or not ridge regression is performed. If a
scalar is passed, then that scalar determines the ridge penalty for
the optimization. The scalar should be greater than or equal to
zero. Default `== None`.
constrained_pos : list or None, optional.
Denotes the positions of the array of estimated parameters that are
not to change from their initial values. If a list is passed, the
elements are to be integers where no such integer is greater than
`init_vals.size.` Default == None.
boot_seed = non-negative int or None, optional.
Denotes the random seed to be used when generating the bootstrap
samples. If None, the sample generation process will generally be
non-reproducible. Default == None.
weights : 1D ndarray or None, optional.
Allows for the calculation of weighted log-likelihoods. The weights
can represent various things. In stratified samples, the weights
may be the proportion of the observations in a given strata for a
sample in relation to the proportion of observations in that strata
in the population. In latent class models, the weights may be the
probability of being a particular class.
Returns
-------
None. Will store the bootstrap replicates on the
`self.bootstrap_replicates` attribute.
"""
print("Generating Bootstrap Replicates")
print(time.strftime("%a %m-%d-%Y %I:%M%p"))
sys.stdout.flush()
# Check the passed arguments for validity.
# Create an array of the observation ids
obs_id_array = self.model_obj.data[self.model_obj.obs_id_col].values
# Alias the alternative IDs and the Choice Array
alt_id_array = self.model_obj.alt_IDs
choice_array = self.model_obj.choices
# Determine how many parameters are being estimated.
num_params = self.mle_params.shape[0]
# Figure out which observations are in each bootstrap sample.
obs_id_per_sample =\
bs.create_cross_sectional_bootstrap_samples(obs_id_array,
alt_id_array,
choice_array,
num_samples,
seed=boot_seed)
# Get the dictionary of sub-dataframes for each observation id
dfs_by_obs_id =\
bs.create_deepcopied_groupby_dict(self.model_obj.data,
self.model_obj.obs_id_col)
# Create a column name for the bootstrap id columns.
boot_id_col = "bootstrap_id"
# Initialize an array to store the bootstrapped point estimates.
point_estimates = np.empty((num_samples, num_params), dtype=float)
# Get keyword arguments for final model estimation with new data.
fit_kwargs = {"print_res": print_res,
"method": method,
"loss_tol": loss_tol,
"gradient_tol": gradient_tol,
"maxiter": maxiter,
"ridge": ridge,
"constrained_pos": constrained_pos,
"just_point": True}
# Get the specification and name dictionary of the MNL model.
mnl_spec = None if mnl_obj is None else mnl_obj.specification
mnl_names = None if mnl_obj is None else mnl_obj.name_spec
# Create an iterable for iteration
iterable_for_iteration = PROGRESS(xrange(num_samples),
desc="Creating Bootstrap Replicates",
total=num_samples)
# Iterate through the bootstrap samples and perform the MLE
for row in iterable_for_iteration:
# Get the bootstrapped dataframe
bootstrap_df =\
bs.create_bootstrap_dataframe(self.model_obj.data,
self.model_obj.obs_id_col,
obs_id_per_sample[row, :],
dfs_by_obs_id,
boot_id_col=boot_id_col)
# Go through the necessary estimation routine to bootstrap the MLE.
current_results =\
retrieve_point_est(self.model_obj,
bootstrap_df,
boot_id_col,
num_params,
mnl_spec,
mnl_names,
mnl_init_vals,
mnl_fit_kwargs,
extract_init_vals=extract_init_vals,
**fit_kwargs)
# Store the bootstrapped point estimate.
point_estimates[row] = current_results["x"]
# Store the point estimates as a pandas dataframe
self.bootstrap_replicates =\
pd.DataFrame(point_estimates, columns=self.mle_params.index)
# Print a 'finished' message for users
print("Finished Generating Bootstrap Replicates")
print(time.strftime("%a %m-%d-%Y %I:%M%p"))
return None | python | def generate_bootstrap_replicates(self,
num_samples,
mnl_obj=None,
mnl_init_vals=None,
mnl_fit_kwargs=None,
extract_init_vals=None,
print_res=False,
method="BFGS",
loss_tol=1e-06,
gradient_tol=1e-06,
maxiter=1000,
ridge=None,
constrained_pos=None,
boot_seed=None,
weights=None):
"""
Generates the bootstrap replicates for one's given model and dataset.
Parameters
----------
num_samples : positive int.
Specifies the number of bootstrap samples that are to be drawn.
mnl_obj : an instance of pylogit.MNL or None, optional.
Should be the MNL model object that is used to provide starting
values for the final model being estimated. If None, then one's
final model should be an MNL model. Default == None.
mnl_init_vals : 1D ndarray or None, optional.
If the model that is being estimated is not an MNL, then
`mnl_init_val` should be passed. Should contain the values used to
begin the estimation process for the MNL model that is used to
provide starting values for our desired model. Default == None.
mnl_fit_kwargs : dict or None.
If the model that is being estimated is not an MNL, then
`mnl_fit_kwargs` should be passed.
extract_init_vals : callable or None, optional.
Should accept 3 arguments, in the following order. First, it should
accept `orig_model_obj`. Second, it should accept a pandas Series
of estimated parameters from the MNL model. The Series' index will
be the names of the coefficients from `mnl_names`. Thirdly, it
should accept an int denoting the number of parameters in the final
choice model. The callable should return a 1D ndarray of starting
values for the final choice model. Default == None.
print_res : bool, optional.
Determines whether the timing and initial and final log likelihood
results will be printed as they they are determined.
Default `== True`.
method : str, optional.
Should be a valid string for scipy.optimize.minimize. Determines
the optimization algorithm that is used for this problem.
Default `== 'bfgs'`.
loss_tol : float, optional.
Determines the tolerance on the difference in objective function
values from one iteration to the next that is needed to determine
convergence. Default `== 1e-06`.
gradient_tol : float, optional.
Determines the tolerance on the difference in gradient values from
one iteration to the next which is needed to determine convergence.
Default `== 1e-06`.
maxiter : int, optional.
Determines the maximum number of iterations used by the optimizer.
Default `== 1000`.
ridge : int, float, long, or None, optional.
Determines whether or not ridge regression is performed. If a
scalar is passed, then that scalar determines the ridge penalty for
the optimization. The scalar should be greater than or equal to
zero. Default `== None`.
constrained_pos : list or None, optional.
Denotes the positions of the array of estimated parameters that are
not to change from their initial values. If a list is passed, the
elements are to be integers where no such integer is greater than
`init_vals.size.` Default == None.
boot_seed = non-negative int or None, optional.
Denotes the random seed to be used when generating the bootstrap
samples. If None, the sample generation process will generally be
non-reproducible. Default == None.
weights : 1D ndarray or None, optional.
Allows for the calculation of weighted log-likelihoods. The weights
can represent various things. In stratified samples, the weights
may be the proportion of the observations in a given strata for a
sample in relation to the proportion of observations in that strata
in the population. In latent class models, the weights may be the
probability of being a particular class.
Returns
-------
None. Will store the bootstrap replicates on the
`self.bootstrap_replicates` attribute.
"""
print("Generating Bootstrap Replicates")
print(time.strftime("%a %m-%d-%Y %I:%M%p"))
sys.stdout.flush()
# Check the passed arguments for validity.
# Create an array of the observation ids
obs_id_array = self.model_obj.data[self.model_obj.obs_id_col].values
# Alias the alternative IDs and the Choice Array
alt_id_array = self.model_obj.alt_IDs
choice_array = self.model_obj.choices
# Determine how many parameters are being estimated.
num_params = self.mle_params.shape[0]
# Figure out which observations are in each bootstrap sample.
obs_id_per_sample =\
bs.create_cross_sectional_bootstrap_samples(obs_id_array,
alt_id_array,
choice_array,
num_samples,
seed=boot_seed)
# Get the dictionary of sub-dataframes for each observation id
dfs_by_obs_id =\
bs.create_deepcopied_groupby_dict(self.model_obj.data,
self.model_obj.obs_id_col)
# Create a column name for the bootstrap id columns.
boot_id_col = "bootstrap_id"
# Initialize an array to store the bootstrapped point estimates.
point_estimates = np.empty((num_samples, num_params), dtype=float)
# Get keyword arguments for final model estimation with new data.
fit_kwargs = {"print_res": print_res,
"method": method,
"loss_tol": loss_tol,
"gradient_tol": gradient_tol,
"maxiter": maxiter,
"ridge": ridge,
"constrained_pos": constrained_pos,
"just_point": True}
# Get the specification and name dictionary of the MNL model.
mnl_spec = None if mnl_obj is None else mnl_obj.specification
mnl_names = None if mnl_obj is None else mnl_obj.name_spec
# Create an iterable for iteration
iterable_for_iteration = PROGRESS(xrange(num_samples),
desc="Creating Bootstrap Replicates",
total=num_samples)
# Iterate through the bootstrap samples and perform the MLE
for row in iterable_for_iteration:
# Get the bootstrapped dataframe
bootstrap_df =\
bs.create_bootstrap_dataframe(self.model_obj.data,
self.model_obj.obs_id_col,
obs_id_per_sample[row, :],
dfs_by_obs_id,
boot_id_col=boot_id_col)
# Go through the necessary estimation routine to bootstrap the MLE.
current_results =\
retrieve_point_est(self.model_obj,
bootstrap_df,
boot_id_col,
num_params,
mnl_spec,
mnl_names,
mnl_init_vals,
mnl_fit_kwargs,
extract_init_vals=extract_init_vals,
**fit_kwargs)
# Store the bootstrapped point estimate.
point_estimates[row] = current_results["x"]
# Store the point estimates as a pandas dataframe
self.bootstrap_replicates =\
pd.DataFrame(point_estimates, columns=self.mle_params.index)
# Print a 'finished' message for users
print("Finished Generating Bootstrap Replicates")
print(time.strftime("%a %m-%d-%Y %I:%M%p"))
return None | [
"def",
"generate_bootstrap_replicates",
"(",
"self",
",",
"num_samples",
",",
"mnl_obj",
"=",
"None",
",",
"mnl_init_vals",
"=",
"None",
",",
"mnl_fit_kwargs",
"=",
"None",
",",
"extract_init_vals",
"=",
"None",
",",
"print_res",
"=",
"False",
",",
"method",
"=",
"\"BFGS\"",
",",
"loss_tol",
"=",
"1e-06",
",",
"gradient_tol",
"=",
"1e-06",
",",
"maxiter",
"=",
"1000",
",",
"ridge",
"=",
"None",
",",
"constrained_pos",
"=",
"None",
",",
"boot_seed",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"print",
"(",
"\"Generating Bootstrap Replicates\"",
")",
"print",
"(",
"time",
".",
"strftime",
"(",
"\"%a %m-%d-%Y %I:%M%p\"",
")",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"# Check the passed arguments for validity.",
"# Create an array of the observation ids",
"obs_id_array",
"=",
"self",
".",
"model_obj",
".",
"data",
"[",
"self",
".",
"model_obj",
".",
"obs_id_col",
"]",
".",
"values",
"# Alias the alternative IDs and the Choice Array",
"alt_id_array",
"=",
"self",
".",
"model_obj",
".",
"alt_IDs",
"choice_array",
"=",
"self",
".",
"model_obj",
".",
"choices",
"# Determine how many parameters are being estimated.",
"num_params",
"=",
"self",
".",
"mle_params",
".",
"shape",
"[",
"0",
"]",
"# Figure out which observations are in each bootstrap sample.",
"obs_id_per_sample",
"=",
"bs",
".",
"create_cross_sectional_bootstrap_samples",
"(",
"obs_id_array",
",",
"alt_id_array",
",",
"choice_array",
",",
"num_samples",
",",
"seed",
"=",
"boot_seed",
")",
"# Get the dictionary of sub-dataframes for each observation id",
"dfs_by_obs_id",
"=",
"bs",
".",
"create_deepcopied_groupby_dict",
"(",
"self",
".",
"model_obj",
".",
"data",
",",
"self",
".",
"model_obj",
".",
"obs_id_col",
")",
"# Create a column name for the bootstrap id columns.",
"boot_id_col",
"=",
"\"bootstrap_id\"",
"# Initialize an array to store the bootstrapped point estimates.",
"point_estimates",
"=",
"np",
".",
"empty",
"(",
"(",
"num_samples",
",",
"num_params",
")",
",",
"dtype",
"=",
"float",
")",
"# Get keyword arguments for final model estimation with new data.",
"fit_kwargs",
"=",
"{",
"\"print_res\"",
":",
"print_res",
",",
"\"method\"",
":",
"method",
",",
"\"loss_tol\"",
":",
"loss_tol",
",",
"\"gradient_tol\"",
":",
"gradient_tol",
",",
"\"maxiter\"",
":",
"maxiter",
",",
"\"ridge\"",
":",
"ridge",
",",
"\"constrained_pos\"",
":",
"constrained_pos",
",",
"\"just_point\"",
":",
"True",
"}",
"# Get the specification and name dictionary of the MNL model.",
"mnl_spec",
"=",
"None",
"if",
"mnl_obj",
"is",
"None",
"else",
"mnl_obj",
".",
"specification",
"mnl_names",
"=",
"None",
"if",
"mnl_obj",
"is",
"None",
"else",
"mnl_obj",
".",
"name_spec",
"# Create an iterable for iteration",
"iterable_for_iteration",
"=",
"PROGRESS",
"(",
"xrange",
"(",
"num_samples",
")",
",",
"desc",
"=",
"\"Creating Bootstrap Replicates\"",
",",
"total",
"=",
"num_samples",
")",
"# Iterate through the bootstrap samples and perform the MLE",
"for",
"row",
"in",
"iterable_for_iteration",
":",
"# Get the bootstrapped dataframe",
"bootstrap_df",
"=",
"bs",
".",
"create_bootstrap_dataframe",
"(",
"self",
".",
"model_obj",
".",
"data",
",",
"self",
".",
"model_obj",
".",
"obs_id_col",
",",
"obs_id_per_sample",
"[",
"row",
",",
":",
"]",
",",
"dfs_by_obs_id",
",",
"boot_id_col",
"=",
"boot_id_col",
")",
"# Go through the necessary estimation routine to bootstrap the MLE.",
"current_results",
"=",
"retrieve_point_est",
"(",
"self",
".",
"model_obj",
",",
"bootstrap_df",
",",
"boot_id_col",
",",
"num_params",
",",
"mnl_spec",
",",
"mnl_names",
",",
"mnl_init_vals",
",",
"mnl_fit_kwargs",
",",
"extract_init_vals",
"=",
"extract_init_vals",
",",
"*",
"*",
"fit_kwargs",
")",
"# Store the bootstrapped point estimate.",
"point_estimates",
"[",
"row",
"]",
"=",
"current_results",
"[",
"\"x\"",
"]",
"# Store the point estimates as a pandas dataframe",
"self",
".",
"bootstrap_replicates",
"=",
"pd",
".",
"DataFrame",
"(",
"point_estimates",
",",
"columns",
"=",
"self",
".",
"mle_params",
".",
"index",
")",
"# Print a 'finished' message for users",
"print",
"(",
"\"Finished Generating Bootstrap Replicates\"",
")",
"print",
"(",
"time",
".",
"strftime",
"(",
"\"%a %m-%d-%Y %I:%M%p\"",
")",
")",
"return",
"None"
] | Generates the bootstrap replicates for one's given model and dataset.
Parameters
----------
num_samples : positive int.
Specifies the number of bootstrap samples that are to be drawn.
mnl_obj : an instance of pylogit.MNL or None, optional.
Should be the MNL model object that is used to provide starting
values for the final model being estimated. If None, then one's
final model should be an MNL model. Default == None.
mnl_init_vals : 1D ndarray or None, optional.
If the model that is being estimated is not an MNL, then
`mnl_init_val` should be passed. Should contain the values used to
begin the estimation process for the MNL model that is used to
provide starting values for our desired model. Default == None.
mnl_fit_kwargs : dict or None.
If the model that is being estimated is not an MNL, then
`mnl_fit_kwargs` should be passed.
extract_init_vals : callable or None, optional.
Should accept 3 arguments, in the following order. First, it should
accept `orig_model_obj`. Second, it should accept a pandas Series
of estimated parameters from the MNL model. The Series' index will
be the names of the coefficients from `mnl_names`. Thirdly, it
should accept an int denoting the number of parameters in the final
choice model. The callable should return a 1D ndarray of starting
values for the final choice model. Default == None.
print_res : bool, optional.
Determines whether the timing and initial and final log likelihood
results will be printed as they they are determined.
Default `== True`.
method : str, optional.
Should be a valid string for scipy.optimize.minimize. Determines
the optimization algorithm that is used for this problem.
Default `== 'bfgs'`.
loss_tol : float, optional.
Determines the tolerance on the difference in objective function
values from one iteration to the next that is needed to determine
convergence. Default `== 1e-06`.
gradient_tol : float, optional.
Determines the tolerance on the difference in gradient values from
one iteration to the next which is needed to determine convergence.
Default `== 1e-06`.
maxiter : int, optional.
Determines the maximum number of iterations used by the optimizer.
Default `== 1000`.
ridge : int, float, long, or None, optional.
Determines whether or not ridge regression is performed. If a
scalar is passed, then that scalar determines the ridge penalty for
the optimization. The scalar should be greater than or equal to
zero. Default `== None`.
constrained_pos : list or None, optional.
Denotes the positions of the array of estimated parameters that are
not to change from their initial values. If a list is passed, the
elements are to be integers where no such integer is greater than
`init_vals.size.` Default == None.
boot_seed = non-negative int or None, optional.
Denotes the random seed to be used when generating the bootstrap
samples. If None, the sample generation process will generally be
non-reproducible. Default == None.
weights : 1D ndarray or None, optional.
Allows for the calculation of weighted log-likelihoods. The weights
can represent various things. In stratified samples, the weights
may be the proportion of the observations in a given strata for a
sample in relation to the proportion of observations in that strata
in the population. In latent class models, the weights may be the
probability of being a particular class.
Returns
-------
None. Will store the bootstrap replicates on the
`self.bootstrap_replicates` attribute. | [
"Generates",
"the",
"bootstrap",
"replicates",
"for",
"one",
"s",
"given",
"model",
"and",
"dataset",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L183-L356 | train | 233,696 |
timothyb0912/pylogit | pylogit/bootstrap.py | Boot.generate_jackknife_replicates | def generate_jackknife_replicates(self,
mnl_obj=None,
mnl_init_vals=None,
mnl_fit_kwargs=None,
extract_init_vals=None,
print_res=False,
method="BFGS",
loss_tol=1e-06,
gradient_tol=1e-06,
maxiter=1000,
ridge=None,
constrained_pos=None):
"""
Generates the jackknife replicates for one's given model and dataset.
Parameters
----------
mnl_obj : an instance of pylogit.MNL or None, optional.
Should be the MNL model object that is used to provide starting
values for the final model being estimated. If None, then one's
final model should be an MNL model. Default == None.
mnl_init_vals : 1D ndarray or None, optional.
If the model that is being estimated is not an MNL, then
`mnl_init_val` should be passed. Should contain the values used to
begin the estimation process for the MNL model that is used to
provide starting values for our desired model. Default == None.
mnl_fit_kwargs : dict or None.
If the model that is being estimated is not an MNL, then
`mnl_fit_kwargs` should be passed.
extract_init_vals : callable or None, optional.
Should accept 3 arguments, in the following order. First, it should
accept `orig_model_obj`. Second, it should accept a pandas Series
of estimated parameters from the MNL model. The Series' index will
be the names of the coefficients from `mnl_names`. Thirdly, it
should accept an int denoting the number of parameters in the final
choice model. The callable should return a 1D ndarray of starting
values for the final choice model. Default == None.
print_res : bool, optional.
Determines whether the timing and initial and final log likelihood
results will be printed as they they are determined.
Default `== True`.
method : str, optional.
Should be a valid string for scipy.optimize.minimize. Determines
the optimization algorithm that is used for this problem.
Default `== 'bfgs'`.
loss_tol : float, optional.
Determines the tolerance on the difference in objective function
values from one iteration to the next that is needed to determine
convergence. Default `== 1e-06`.
gradient_tol : float, optional.
Determines the tolerance on the difference in gradient values from
one iteration to the next which is needed to determine convergence.
Default `== 1e-06`.
maxiter : int, optional.
Determines the maximum number of iterations used by the optimizer.
Default `== 1000`.
ridge : int, float, long, or None, optional.
Determines whether or not ridge regression is performed. If a
scalar is passed, then that scalar determines the ridge penalty for
the optimization. The scalar should be greater than or equal to
zero. Default `== None`.
constrained_pos : list or None, optional.
Denotes the positions of the array of estimated parameters that are
not to change from their initial values. If a list is passed, the
elements are to be integers where no such integer is greater than
`init_vals.size.` Default == None.
Returns
-------
None. Will store the bootstrap replicates on the
`self.bootstrap_replicates` attribute.
"""
print("Generating Jackknife Replicates")
print(time.strftime("%a %m-%d-%Y %I:%M%p"))
sys.stdout.flush()
# Take note of the observation id column that is to be used
obs_id_col = self.model_obj.obs_id_col
# Get the array of original observation ids
orig_obs_id_array =\
self.model_obj.data[obs_id_col].values
# Get an array of the unique observation ids.
unique_obs_ids = np.sort(np.unique(orig_obs_id_array))
# Determine how many observations are in one's dataset.
num_obs = unique_obs_ids.size
# Determine how many parameters are being estimated.
num_params = self.mle_params.size
# Get keyword arguments for final model estimation with new data.
fit_kwargs = {"print_res": print_res,
"method": method,
"loss_tol": loss_tol,
"gradient_tol": gradient_tol,
"maxiter": maxiter,
"ridge": ridge,
"constrained_pos": constrained_pos,
"just_point": True}
# Get the specification and name dictionary of the MNL model.
mnl_spec = None if mnl_obj is None else mnl_obj.specification
mnl_names = None if mnl_obj is None else mnl_obj.name_spec
# Initialize the array of jackknife replicates
point_replicates = np.empty((num_obs, num_params), dtype=float)
# Create an iterable for iteration
iterable_for_iteration = PROGRESS(enumerate(unique_obs_ids),
desc="Creating Jackknife Replicates",
total=unique_obs_ids.size)
# Populate the array of jackknife replicates
for pos, obs_id in iterable_for_iteration:
# Create the dataframe without the current observation
new_df = self.model_obj.data.loc[orig_obs_id_array != obs_id]
# Get the point estimate for this new dataset
current_results =\
retrieve_point_est(self.model_obj,
new_df,
obs_id_col,
num_params,
mnl_spec,
mnl_names,
mnl_init_vals,
mnl_fit_kwargs,
extract_init_vals=extract_init_vals,
**fit_kwargs)
# Store the estimated parameters
point_replicates[pos] = current_results['x']
# Store the jackknife replicates as a pandas dataframe
self.jackknife_replicates =\
pd.DataFrame(point_replicates, columns=self.mle_params.index)
# Print a 'finished' message for users
print("Finished Generating Jackknife Replicates")
print(time.strftime("%a %m-%d-%Y %I:%M%p"))
return None | python | def generate_jackknife_replicates(self,
mnl_obj=None,
mnl_init_vals=None,
mnl_fit_kwargs=None,
extract_init_vals=None,
print_res=False,
method="BFGS",
loss_tol=1e-06,
gradient_tol=1e-06,
maxiter=1000,
ridge=None,
constrained_pos=None):
"""
Generates the jackknife replicates for one's given model and dataset.
Parameters
----------
mnl_obj : an instance of pylogit.MNL or None, optional.
Should be the MNL model object that is used to provide starting
values for the final model being estimated. If None, then one's
final model should be an MNL model. Default == None.
mnl_init_vals : 1D ndarray or None, optional.
If the model that is being estimated is not an MNL, then
`mnl_init_val` should be passed. Should contain the values used to
begin the estimation process for the MNL model that is used to
provide starting values for our desired model. Default == None.
mnl_fit_kwargs : dict or None.
If the model that is being estimated is not an MNL, then
`mnl_fit_kwargs` should be passed.
extract_init_vals : callable or None, optional.
Should accept 3 arguments, in the following order. First, it should
accept `orig_model_obj`. Second, it should accept a pandas Series
of estimated parameters from the MNL model. The Series' index will
be the names of the coefficients from `mnl_names`. Thirdly, it
should accept an int denoting the number of parameters in the final
choice model. The callable should return a 1D ndarray of starting
values for the final choice model. Default == None.
print_res : bool, optional.
Determines whether the timing and initial and final log likelihood
results will be printed as they they are determined.
Default `== True`.
method : str, optional.
Should be a valid string for scipy.optimize.minimize. Determines
the optimization algorithm that is used for this problem.
Default `== 'bfgs'`.
loss_tol : float, optional.
Determines the tolerance on the difference in objective function
values from one iteration to the next that is needed to determine
convergence. Default `== 1e-06`.
gradient_tol : float, optional.
Determines the tolerance on the difference in gradient values from
one iteration to the next which is needed to determine convergence.
Default `== 1e-06`.
maxiter : int, optional.
Determines the maximum number of iterations used by the optimizer.
Default `== 1000`.
ridge : int, float, long, or None, optional.
Determines whether or not ridge regression is performed. If a
scalar is passed, then that scalar determines the ridge penalty for
the optimization. The scalar should be greater than or equal to
zero. Default `== None`.
constrained_pos : list or None, optional.
Denotes the positions of the array of estimated parameters that are
not to change from their initial values. If a list is passed, the
elements are to be integers where no such integer is greater than
`init_vals.size.` Default == None.
Returns
-------
None. Will store the bootstrap replicates on the
`self.bootstrap_replicates` attribute.
"""
print("Generating Jackknife Replicates")
print(time.strftime("%a %m-%d-%Y %I:%M%p"))
sys.stdout.flush()
# Take note of the observation id column that is to be used
obs_id_col = self.model_obj.obs_id_col
# Get the array of original observation ids
orig_obs_id_array =\
self.model_obj.data[obs_id_col].values
# Get an array of the unique observation ids.
unique_obs_ids = np.sort(np.unique(orig_obs_id_array))
# Determine how many observations are in one's dataset.
num_obs = unique_obs_ids.size
# Determine how many parameters are being estimated.
num_params = self.mle_params.size
# Get keyword arguments for final model estimation with new data.
fit_kwargs = {"print_res": print_res,
"method": method,
"loss_tol": loss_tol,
"gradient_tol": gradient_tol,
"maxiter": maxiter,
"ridge": ridge,
"constrained_pos": constrained_pos,
"just_point": True}
# Get the specification and name dictionary of the MNL model.
mnl_spec = None if mnl_obj is None else mnl_obj.specification
mnl_names = None if mnl_obj is None else mnl_obj.name_spec
# Initialize the array of jackknife replicates
point_replicates = np.empty((num_obs, num_params), dtype=float)
# Create an iterable for iteration
iterable_for_iteration = PROGRESS(enumerate(unique_obs_ids),
desc="Creating Jackknife Replicates",
total=unique_obs_ids.size)
# Populate the array of jackknife replicates
for pos, obs_id in iterable_for_iteration:
# Create the dataframe without the current observation
new_df = self.model_obj.data.loc[orig_obs_id_array != obs_id]
# Get the point estimate for this new dataset
current_results =\
retrieve_point_est(self.model_obj,
new_df,
obs_id_col,
num_params,
mnl_spec,
mnl_names,
mnl_init_vals,
mnl_fit_kwargs,
extract_init_vals=extract_init_vals,
**fit_kwargs)
# Store the estimated parameters
point_replicates[pos] = current_results['x']
# Store the jackknife replicates as a pandas dataframe
self.jackknife_replicates =\
pd.DataFrame(point_replicates, columns=self.mle_params.index)
# Print a 'finished' message for users
print("Finished Generating Jackknife Replicates")
print(time.strftime("%a %m-%d-%Y %I:%M%p"))
return None | [
"def",
"generate_jackknife_replicates",
"(",
"self",
",",
"mnl_obj",
"=",
"None",
",",
"mnl_init_vals",
"=",
"None",
",",
"mnl_fit_kwargs",
"=",
"None",
",",
"extract_init_vals",
"=",
"None",
",",
"print_res",
"=",
"False",
",",
"method",
"=",
"\"BFGS\"",
",",
"loss_tol",
"=",
"1e-06",
",",
"gradient_tol",
"=",
"1e-06",
",",
"maxiter",
"=",
"1000",
",",
"ridge",
"=",
"None",
",",
"constrained_pos",
"=",
"None",
")",
":",
"print",
"(",
"\"Generating Jackknife Replicates\"",
")",
"print",
"(",
"time",
".",
"strftime",
"(",
"\"%a %m-%d-%Y %I:%M%p\"",
")",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"# Take note of the observation id column that is to be used",
"obs_id_col",
"=",
"self",
".",
"model_obj",
".",
"obs_id_col",
"# Get the array of original observation ids",
"orig_obs_id_array",
"=",
"self",
".",
"model_obj",
".",
"data",
"[",
"obs_id_col",
"]",
".",
"values",
"# Get an array of the unique observation ids.",
"unique_obs_ids",
"=",
"np",
".",
"sort",
"(",
"np",
".",
"unique",
"(",
"orig_obs_id_array",
")",
")",
"# Determine how many observations are in one's dataset.",
"num_obs",
"=",
"unique_obs_ids",
".",
"size",
"# Determine how many parameters are being estimated.",
"num_params",
"=",
"self",
".",
"mle_params",
".",
"size",
"# Get keyword arguments for final model estimation with new data.",
"fit_kwargs",
"=",
"{",
"\"print_res\"",
":",
"print_res",
",",
"\"method\"",
":",
"method",
",",
"\"loss_tol\"",
":",
"loss_tol",
",",
"\"gradient_tol\"",
":",
"gradient_tol",
",",
"\"maxiter\"",
":",
"maxiter",
",",
"\"ridge\"",
":",
"ridge",
",",
"\"constrained_pos\"",
":",
"constrained_pos",
",",
"\"just_point\"",
":",
"True",
"}",
"# Get the specification and name dictionary of the MNL model.",
"mnl_spec",
"=",
"None",
"if",
"mnl_obj",
"is",
"None",
"else",
"mnl_obj",
".",
"specification",
"mnl_names",
"=",
"None",
"if",
"mnl_obj",
"is",
"None",
"else",
"mnl_obj",
".",
"name_spec",
"# Initialize the array of jackknife replicates",
"point_replicates",
"=",
"np",
".",
"empty",
"(",
"(",
"num_obs",
",",
"num_params",
")",
",",
"dtype",
"=",
"float",
")",
"# Create an iterable for iteration",
"iterable_for_iteration",
"=",
"PROGRESS",
"(",
"enumerate",
"(",
"unique_obs_ids",
")",
",",
"desc",
"=",
"\"Creating Jackknife Replicates\"",
",",
"total",
"=",
"unique_obs_ids",
".",
"size",
")",
"# Populate the array of jackknife replicates",
"for",
"pos",
",",
"obs_id",
"in",
"iterable_for_iteration",
":",
"# Create the dataframe without the current observation",
"new_df",
"=",
"self",
".",
"model_obj",
".",
"data",
".",
"loc",
"[",
"orig_obs_id_array",
"!=",
"obs_id",
"]",
"# Get the point estimate for this new dataset",
"current_results",
"=",
"retrieve_point_est",
"(",
"self",
".",
"model_obj",
",",
"new_df",
",",
"obs_id_col",
",",
"num_params",
",",
"mnl_spec",
",",
"mnl_names",
",",
"mnl_init_vals",
",",
"mnl_fit_kwargs",
",",
"extract_init_vals",
"=",
"extract_init_vals",
",",
"*",
"*",
"fit_kwargs",
")",
"# Store the estimated parameters",
"point_replicates",
"[",
"pos",
"]",
"=",
"current_results",
"[",
"'x'",
"]",
"# Store the jackknife replicates as a pandas dataframe",
"self",
".",
"jackknife_replicates",
"=",
"pd",
".",
"DataFrame",
"(",
"point_replicates",
",",
"columns",
"=",
"self",
".",
"mle_params",
".",
"index",
")",
"# Print a 'finished' message for users",
"print",
"(",
"\"Finished Generating Jackknife Replicates\"",
")",
"print",
"(",
"time",
".",
"strftime",
"(",
"\"%a %m-%d-%Y %I:%M%p\"",
")",
")",
"return",
"None"
] | Generates the jackknife replicates for one's given model and dataset.
Parameters
----------
mnl_obj : an instance of pylogit.MNL or None, optional.
Should be the MNL model object that is used to provide starting
values for the final model being estimated. If None, then one's
final model should be an MNL model. Default == None.
mnl_init_vals : 1D ndarray or None, optional.
If the model that is being estimated is not an MNL, then
`mnl_init_val` should be passed. Should contain the values used to
begin the estimation process for the MNL model that is used to
provide starting values for our desired model. Default == None.
mnl_fit_kwargs : dict or None.
If the model that is being estimated is not an MNL, then
`mnl_fit_kwargs` should be passed.
extract_init_vals : callable or None, optional.
Should accept 3 arguments, in the following order. First, it should
accept `orig_model_obj`. Second, it should accept a pandas Series
of estimated parameters from the MNL model. The Series' index will
be the names of the coefficients from `mnl_names`. Thirdly, it
should accept an int denoting the number of parameters in the final
choice model. The callable should return a 1D ndarray of starting
values for the final choice model. Default == None.
print_res : bool, optional.
Determines whether the timing and initial and final log likelihood
results will be printed as they they are determined.
Default `== True`.
method : str, optional.
Should be a valid string for scipy.optimize.minimize. Determines
the optimization algorithm that is used for this problem.
Default `== 'bfgs'`.
loss_tol : float, optional.
Determines the tolerance on the difference in objective function
values from one iteration to the next that is needed to determine
convergence. Default `== 1e-06`.
gradient_tol : float, optional.
Determines the tolerance on the difference in gradient values from
one iteration to the next which is needed to determine convergence.
Default `== 1e-06`.
maxiter : int, optional.
Determines the maximum number of iterations used by the optimizer.
Default `== 1000`.
ridge : int, float, long, or None, optional.
Determines whether or not ridge regression is performed. If a
scalar is passed, then that scalar determines the ridge penalty for
the optimization. The scalar should be greater than or equal to
zero. Default `== None`.
constrained_pos : list or None, optional.
Denotes the positions of the array of estimated parameters that are
not to change from their initial values. If a list is passed, the
elements are to be integers where no such integer is greater than
`init_vals.size.` Default == None.
Returns
-------
None. Will store the bootstrap replicates on the
`self.bootstrap_replicates` attribute. | [
"Generates",
"the",
"jackknife",
"replicates",
"for",
"one",
"s",
"given",
"model",
"and",
"dataset",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L358-L495 | train | 233,697 |
timothyb0912/pylogit | pylogit/bootstrap.py | Boot.calc_log_likes_for_replicates | def calc_log_likes_for_replicates(self,
replicates='bootstrap',
num_draws=None,
seed=None):
"""
Calculate the log-likelihood value of one's replicates, given one's
dataset.
Parameters
----------
replicates : str in {'bootstrap', 'jackknife'}.
Denotes which set of replicates should have their log-likelihoods
calculated.
num_draws : int greater than zero or None, optional.
Denotes the number of random draws for mixed logit estimation. If
None, then no random draws will be made. Default == None.
seed : int greater than zero or None, optional.
Denotes the random seed to be used for mixed logit estimation.
If None, then no random seed will be set. Default == None.
Returns
-------
log_likelihoods : 1D ndarray.
Each element stores the log-likelihood of the associated parameter
values on the model object's dataset. The log-likelihoods are also
stored on the `replicates + '_log_likelihoods'` attribute.
"""
# Check the validity of the kwargs
ensure_replicates_kwarg_validity(replicates)
# Get the desired type of replicates
replicate_vec = getattr(self, replicates + "_replicates").values
# Determine the choice column
choice_col = self.model_obj.choice_col
# Split the control flow based on whether we're using a Nested Logit
current_model_type = self.model_obj.model_type
non_2d_predictions =\
[model_type_to_display_name["Nested Logit"],
model_type_to_display_name["Mixed Logit"]]
if current_model_type not in non_2d_predictions:
# Get the param list for this set of replicates
param_list =\
get_param_list_for_prediction(self.model_obj, replicate_vec)
# Get the 'chosen_probs' using the desired set of replicates
chosen_probs =\
self.model_obj.predict(self.model_obj.data,
param_list=param_list,
return_long_probs=False,
choice_col=choice_col)
else:
# Initialize a list of chosen probs
chosen_probs_list = []
# Create an iterable for iteration
iterable_for_iteration = PROGRESS(xrange(replicate_vec.shape[0]),
desc="Calculate Gradient Norms",
total=replicate_vec.shape[0])
# Populate the list of chosen probabilities for each vector of
# parameter values
for idx in iterable_for_iteration:
# Get the param list for this set of replicates
param_list =\
get_param_list_for_prediction(self.model_obj,
replicate_vec[idx][None, :])
# Use 1D parameters in the prediction function
param_list =\
[x.ravel() if x is not None else x for x in param_list]
# Get the 'chosen_probs' using the desired set of replicates
chosen_probs =\
self.model_obj.predict(self.model_obj.data,
param_list=param_list,
return_long_probs=False,
choice_col=choice_col,
num_draws=num_draws,
seed=seed)
# store those chosen prob_results
chosen_probs_list.append(chosen_probs[:, None])
# Get the final array of chosen probs
chosen_probs = np.concatenate(chosen_probs_list, axis=1)
# Calculate the log_likelihood
log_likelihoods = np.log(chosen_probs).sum(axis=0)
# Store the log-likelihood values
attribute_name = replicates + "_log_likelihoods"
log_like_series = pd.Series(log_likelihoods, name=attribute_name)
setattr(self, attribute_name, log_like_series)
return log_likelihoods | python | def calc_log_likes_for_replicates(self,
replicates='bootstrap',
num_draws=None,
seed=None):
"""
Calculate the log-likelihood value of one's replicates, given one's
dataset.
Parameters
----------
replicates : str in {'bootstrap', 'jackknife'}.
Denotes which set of replicates should have their log-likelihoods
calculated.
num_draws : int greater than zero or None, optional.
Denotes the number of random draws for mixed logit estimation. If
None, then no random draws will be made. Default == None.
seed : int greater than zero or None, optional.
Denotes the random seed to be used for mixed logit estimation.
If None, then no random seed will be set. Default == None.
Returns
-------
log_likelihoods : 1D ndarray.
Each element stores the log-likelihood of the associated parameter
values on the model object's dataset. The log-likelihoods are also
stored on the `replicates + '_log_likelihoods'` attribute.
"""
# Check the validity of the kwargs
ensure_replicates_kwarg_validity(replicates)
# Get the desired type of replicates
replicate_vec = getattr(self, replicates + "_replicates").values
# Determine the choice column
choice_col = self.model_obj.choice_col
# Split the control flow based on whether we're using a Nested Logit
current_model_type = self.model_obj.model_type
non_2d_predictions =\
[model_type_to_display_name["Nested Logit"],
model_type_to_display_name["Mixed Logit"]]
if current_model_type not in non_2d_predictions:
# Get the param list for this set of replicates
param_list =\
get_param_list_for_prediction(self.model_obj, replicate_vec)
# Get the 'chosen_probs' using the desired set of replicates
chosen_probs =\
self.model_obj.predict(self.model_obj.data,
param_list=param_list,
return_long_probs=False,
choice_col=choice_col)
else:
# Initialize a list of chosen probs
chosen_probs_list = []
# Create an iterable for iteration
iterable_for_iteration = PROGRESS(xrange(replicate_vec.shape[0]),
desc="Calculate Gradient Norms",
total=replicate_vec.shape[0])
# Populate the list of chosen probabilities for each vector of
# parameter values
for idx in iterable_for_iteration:
# Get the param list for this set of replicates
param_list =\
get_param_list_for_prediction(self.model_obj,
replicate_vec[idx][None, :])
# Use 1D parameters in the prediction function
param_list =\
[x.ravel() if x is not None else x for x in param_list]
# Get the 'chosen_probs' using the desired set of replicates
chosen_probs =\
self.model_obj.predict(self.model_obj.data,
param_list=param_list,
return_long_probs=False,
choice_col=choice_col,
num_draws=num_draws,
seed=seed)
# store those chosen prob_results
chosen_probs_list.append(chosen_probs[:, None])
# Get the final array of chosen probs
chosen_probs = np.concatenate(chosen_probs_list, axis=1)
# Calculate the log_likelihood
log_likelihoods = np.log(chosen_probs).sum(axis=0)
# Store the log-likelihood values
attribute_name = replicates + "_log_likelihoods"
log_like_series = pd.Series(log_likelihoods, name=attribute_name)
setattr(self, attribute_name, log_like_series)
return log_likelihoods | [
"def",
"calc_log_likes_for_replicates",
"(",
"self",
",",
"replicates",
"=",
"'bootstrap'",
",",
"num_draws",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"# Check the validity of the kwargs",
"ensure_replicates_kwarg_validity",
"(",
"replicates",
")",
"# Get the desired type of replicates",
"replicate_vec",
"=",
"getattr",
"(",
"self",
",",
"replicates",
"+",
"\"_replicates\"",
")",
".",
"values",
"# Determine the choice column",
"choice_col",
"=",
"self",
".",
"model_obj",
".",
"choice_col",
"# Split the control flow based on whether we're using a Nested Logit",
"current_model_type",
"=",
"self",
".",
"model_obj",
".",
"model_type",
"non_2d_predictions",
"=",
"[",
"model_type_to_display_name",
"[",
"\"Nested Logit\"",
"]",
",",
"model_type_to_display_name",
"[",
"\"Mixed Logit\"",
"]",
"]",
"if",
"current_model_type",
"not",
"in",
"non_2d_predictions",
":",
"# Get the param list for this set of replicates",
"param_list",
"=",
"get_param_list_for_prediction",
"(",
"self",
".",
"model_obj",
",",
"replicate_vec",
")",
"# Get the 'chosen_probs' using the desired set of replicates",
"chosen_probs",
"=",
"self",
".",
"model_obj",
".",
"predict",
"(",
"self",
".",
"model_obj",
".",
"data",
",",
"param_list",
"=",
"param_list",
",",
"return_long_probs",
"=",
"False",
",",
"choice_col",
"=",
"choice_col",
")",
"else",
":",
"# Initialize a list of chosen probs",
"chosen_probs_list",
"=",
"[",
"]",
"# Create an iterable for iteration",
"iterable_for_iteration",
"=",
"PROGRESS",
"(",
"xrange",
"(",
"replicate_vec",
".",
"shape",
"[",
"0",
"]",
")",
",",
"desc",
"=",
"\"Calculate Gradient Norms\"",
",",
"total",
"=",
"replicate_vec",
".",
"shape",
"[",
"0",
"]",
")",
"# Populate the list of chosen probabilities for each vector of",
"# parameter values",
"for",
"idx",
"in",
"iterable_for_iteration",
":",
"# Get the param list for this set of replicates",
"param_list",
"=",
"get_param_list_for_prediction",
"(",
"self",
".",
"model_obj",
",",
"replicate_vec",
"[",
"idx",
"]",
"[",
"None",
",",
":",
"]",
")",
"# Use 1D parameters in the prediction function",
"param_list",
"=",
"[",
"x",
".",
"ravel",
"(",
")",
"if",
"x",
"is",
"not",
"None",
"else",
"x",
"for",
"x",
"in",
"param_list",
"]",
"# Get the 'chosen_probs' using the desired set of replicates",
"chosen_probs",
"=",
"self",
".",
"model_obj",
".",
"predict",
"(",
"self",
".",
"model_obj",
".",
"data",
",",
"param_list",
"=",
"param_list",
",",
"return_long_probs",
"=",
"False",
",",
"choice_col",
"=",
"choice_col",
",",
"num_draws",
"=",
"num_draws",
",",
"seed",
"=",
"seed",
")",
"# store those chosen prob_results",
"chosen_probs_list",
".",
"append",
"(",
"chosen_probs",
"[",
":",
",",
"None",
"]",
")",
"# Get the final array of chosen probs",
"chosen_probs",
"=",
"np",
".",
"concatenate",
"(",
"chosen_probs_list",
",",
"axis",
"=",
"1",
")",
"# Calculate the log_likelihood",
"log_likelihoods",
"=",
"np",
".",
"log",
"(",
"chosen_probs",
")",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"# Store the log-likelihood values",
"attribute_name",
"=",
"replicates",
"+",
"\"_log_likelihoods\"",
"log_like_series",
"=",
"pd",
".",
"Series",
"(",
"log_likelihoods",
",",
"name",
"=",
"attribute_name",
")",
"setattr",
"(",
"self",
",",
"attribute_name",
",",
"log_like_series",
")",
"return",
"log_likelihoods"
] | Calculate the log-likelihood value of one's replicates, given one's
dataset.
Parameters
----------
replicates : str in {'bootstrap', 'jackknife'}.
Denotes which set of replicates should have their log-likelihoods
calculated.
num_draws : int greater than zero or None, optional.
Denotes the number of random draws for mixed logit estimation. If
None, then no random draws will be made. Default == None.
seed : int greater than zero or None, optional.
Denotes the random seed to be used for mixed logit estimation.
If None, then no random seed will be set. Default == None.
Returns
-------
log_likelihoods : 1D ndarray.
Each element stores the log-likelihood of the associated parameter
values on the model object's dataset. The log-likelihoods are also
stored on the `replicates + '_log_likelihoods'` attribute. | [
"Calculate",
"the",
"log",
"-",
"likelihood",
"value",
"of",
"one",
"s",
"replicates",
"given",
"one",
"s",
"dataset",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L497-L591 | train | 233,698 |
timothyb0912/pylogit | pylogit/bootstrap.py | Boot.calc_gradient_norm_for_replicates | def calc_gradient_norm_for_replicates(self,
replicates='bootstrap',
ridge=None,
constrained_pos=None,
weights=None):
"""
Calculate the Euclidean-norm of the gradient of one's replicates, given
one's dataset.
Parameters
----------
replicates : str in {'bootstrap', 'jackknife'}.
Denotes which set of replicates should have their log-likelihoods
calculated.
ridge : float or None, optional.
Denotes the ridge penalty used when estimating the replicates, and
to be used when calculating the gradient. If None, no ridge penalty
is used. Default == None.
constrained_pos : list or None, optional.
Denotes the positions of the array of estimated parameters that are
not to change from their initial values. If a list is passed, the
elements are to be integers where no such integer is greater than
`self.mle_params` Default == None.
weights : 1D ndarray or None, optional.
Allows for the calculation of weighted log-likelihoods. The weights
can represent various things. In stratified samples, the weights
may be the proportion of the observations in a given strata for a
sample in relation to the proportion of observations in that strata
in the population. In latent class models, the weights may be the
probability of being a particular class.
Returns
-------
log_likelihoods : 1D ndarray.
Each element stores the log-likelihood of the associated parameter
values on the model object's dataset. The log-likelihoods are also
stored on the `replicates + '_log_likelihoods'` attribute.
"""
# Check the validity of the kwargs
ensure_replicates_kwarg_validity(replicates)
# Create the estimation object
estimation_obj =\
create_estimation_obj(self.model_obj,
self.mle_params.values,
ridge=ridge,
constrained_pos=constrained_pos,
weights=weights)
# Prepare the estimation object to calculate the gradients
if hasattr(estimation_obj, "set_derivatives"):
estimation_obj.set_derivatives()
# Get the array of parameter replicates
replicate_array = getattr(self, replicates + "_replicates").values
# Determine the number of replicates
num_reps = replicate_array.shape[0]
# Initialize an empty array to store the gradient norms
gradient_norms = np.empty((num_reps,), dtype=float)
# Create an iterable for iteration
iterable_for_iteration = PROGRESS(xrange(num_reps),
desc="Calculating Gradient Norms",
total=num_reps)
# Iterate through the rows of the replicates and calculate and store
# the gradient norm for each replicated parameter vector.
for row in iterable_for_iteration:
current_params = replicate_array[row]
gradient = estimation_obj.convenience_calc_gradient(current_params)
gradient_norms[row] = np.linalg.norm(gradient)
return gradient_norms | python | def calc_gradient_norm_for_replicates(self,
replicates='bootstrap',
ridge=None,
constrained_pos=None,
weights=None):
"""
Calculate the Euclidean-norm of the gradient of one's replicates, given
one's dataset.
Parameters
----------
replicates : str in {'bootstrap', 'jackknife'}.
Denotes which set of replicates should have their log-likelihoods
calculated.
ridge : float or None, optional.
Denotes the ridge penalty used when estimating the replicates, and
to be used when calculating the gradient. If None, no ridge penalty
is used. Default == None.
constrained_pos : list or None, optional.
Denotes the positions of the array of estimated parameters that are
not to change from their initial values. If a list is passed, the
elements are to be integers where no such integer is greater than
`self.mle_params` Default == None.
weights : 1D ndarray or None, optional.
Allows for the calculation of weighted log-likelihoods. The weights
can represent various things. In stratified samples, the weights
may be the proportion of the observations in a given strata for a
sample in relation to the proportion of observations in that strata
in the population. In latent class models, the weights may be the
probability of being a particular class.
Returns
-------
log_likelihoods : 1D ndarray.
Each element stores the log-likelihood of the associated parameter
values on the model object's dataset. The log-likelihoods are also
stored on the `replicates + '_log_likelihoods'` attribute.
"""
# Check the validity of the kwargs
ensure_replicates_kwarg_validity(replicates)
# Create the estimation object
estimation_obj =\
create_estimation_obj(self.model_obj,
self.mle_params.values,
ridge=ridge,
constrained_pos=constrained_pos,
weights=weights)
# Prepare the estimation object to calculate the gradients
if hasattr(estimation_obj, "set_derivatives"):
estimation_obj.set_derivatives()
# Get the array of parameter replicates
replicate_array = getattr(self, replicates + "_replicates").values
# Determine the number of replicates
num_reps = replicate_array.shape[0]
# Initialize an empty array to store the gradient norms
gradient_norms = np.empty((num_reps,), dtype=float)
# Create an iterable for iteration
iterable_for_iteration = PROGRESS(xrange(num_reps),
desc="Calculating Gradient Norms",
total=num_reps)
# Iterate through the rows of the replicates and calculate and store
# the gradient norm for each replicated parameter vector.
for row in iterable_for_iteration:
current_params = replicate_array[row]
gradient = estimation_obj.convenience_calc_gradient(current_params)
gradient_norms[row] = np.linalg.norm(gradient)
return gradient_norms | [
"def",
"calc_gradient_norm_for_replicates",
"(",
"self",
",",
"replicates",
"=",
"'bootstrap'",
",",
"ridge",
"=",
"None",
",",
"constrained_pos",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"# Check the validity of the kwargs",
"ensure_replicates_kwarg_validity",
"(",
"replicates",
")",
"# Create the estimation object",
"estimation_obj",
"=",
"create_estimation_obj",
"(",
"self",
".",
"model_obj",
",",
"self",
".",
"mle_params",
".",
"values",
",",
"ridge",
"=",
"ridge",
",",
"constrained_pos",
"=",
"constrained_pos",
",",
"weights",
"=",
"weights",
")",
"# Prepare the estimation object to calculate the gradients",
"if",
"hasattr",
"(",
"estimation_obj",
",",
"\"set_derivatives\"",
")",
":",
"estimation_obj",
".",
"set_derivatives",
"(",
")",
"# Get the array of parameter replicates",
"replicate_array",
"=",
"getattr",
"(",
"self",
",",
"replicates",
"+",
"\"_replicates\"",
")",
".",
"values",
"# Determine the number of replicates",
"num_reps",
"=",
"replicate_array",
".",
"shape",
"[",
"0",
"]",
"# Initialize an empty array to store the gradient norms",
"gradient_norms",
"=",
"np",
".",
"empty",
"(",
"(",
"num_reps",
",",
")",
",",
"dtype",
"=",
"float",
")",
"# Create an iterable for iteration",
"iterable_for_iteration",
"=",
"PROGRESS",
"(",
"xrange",
"(",
"num_reps",
")",
",",
"desc",
"=",
"\"Calculating Gradient Norms\"",
",",
"total",
"=",
"num_reps",
")",
"# Iterate through the rows of the replicates and calculate and store",
"# the gradient norm for each replicated parameter vector.",
"for",
"row",
"in",
"iterable_for_iteration",
":",
"current_params",
"=",
"replicate_array",
"[",
"row",
"]",
"gradient",
"=",
"estimation_obj",
".",
"convenience_calc_gradient",
"(",
"current_params",
")",
"gradient_norms",
"[",
"row",
"]",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"gradient",
")",
"return",
"gradient_norms"
] | Calculate the Euclidean-norm of the gradient of one's replicates, given
one's dataset.
Parameters
----------
replicates : str in {'bootstrap', 'jackknife'}.
Denotes which set of replicates should have their log-likelihoods
calculated.
ridge : float or None, optional.
Denotes the ridge penalty used when estimating the replicates, and
to be used when calculating the gradient. If None, no ridge penalty
is used. Default == None.
constrained_pos : list or None, optional.
Denotes the positions of the array of estimated parameters that are
not to change from their initial values. If a list is passed, the
elements are to be integers where no such integer is greater than
`self.mle_params` Default == None.
weights : 1D ndarray or None, optional.
Allows for the calculation of weighted log-likelihoods. The weights
can represent various things. In stratified samples, the weights
may be the proportion of the observations in a given strata for a
sample in relation to the proportion of observations in that strata
in the population. In latent class models, the weights may be the
probability of being a particular class.
Returns
-------
log_likelihoods : 1D ndarray.
Each element stores the log-likelihood of the associated parameter
values on the model object's dataset. The log-likelihoods are also
stored on the `replicates + '_log_likelihoods'` attribute. | [
"Calculate",
"the",
"Euclidean",
"-",
"norm",
"of",
"the",
"gradient",
"of",
"one",
"s",
"replicates",
"given",
"one",
"s",
"dataset",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L593-L661 | train | 233,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.