id
int32
0
252k
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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
700
poppy-project/pypot
pypot/kinematics.py
Link.get_transformation_matrix
def get_transformation_matrix(self, theta): """ Computes the homogeneous transformation matrix for this link. """ ct = numpy.cos(theta + self.theta) st = numpy.sin(theta + self.theta) ca = numpy.cos(self.alpha) sa = numpy.sin(self.alpha) return numpy.matrix(((ct, -st * ca, st * sa, self.a * ct), (st, ct * ca, -ct * sa, self.a * st), (0, sa, ca, self.d), (0, 0, 0, 1)))
python
def get_transformation_matrix(self, theta): """ Computes the homogeneous transformation matrix for this link. """ ct = numpy.cos(theta + self.theta) st = numpy.sin(theta + self.theta) ca = numpy.cos(self.alpha) sa = numpy.sin(self.alpha) return numpy.matrix(((ct, -st * ca, st * sa, self.a * ct), (st, ct * ca, -ct * sa, self.a * st), (0, sa, ca, self.d), (0, 0, 0, 1)))
[ "def", "get_transformation_matrix", "(", "self", ",", "theta", ")", ":", "ct", "=", "numpy", ".", "cos", "(", "theta", "+", "self", ".", "theta", ")", "st", "=", "numpy", ".", "sin", "(", "theta", "+", "self", ".", "theta", ")", "ca", "=", "numpy", ".", "cos", "(", "self", ".", "alpha", ")", "sa", "=", "numpy", ".", "sin", "(", "self", ".", "alpha", ")", "return", "numpy", ".", "matrix", "(", "(", "(", "ct", ",", "-", "st", "*", "ca", ",", "st", "*", "sa", ",", "self", ".", "a", "*", "ct", ")", ",", "(", "st", ",", "ct", "*", "ca", ",", "-", "ct", "*", "sa", ",", "self", ".", "a", "*", "st", ")", ",", "(", "0", ",", "sa", ",", "ca", ",", "self", ".", "d", ")", ",", "(", "0", ",", "0", ",", "0", ",", "1", ")", ")", ")" ]
Computes the homogeneous transformation matrix for this link.
[ "Computes", "the", "homogeneous", "transformation", "matrix", "for", "this", "link", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/kinematics.py#L27-L37
701
poppy-project/pypot
pypot/kinematics.py
Chain.forward_kinematics
def forward_kinematics(self, q): """ Computes the homogeneous transformation matrix of the end effector of the chain. :param vector q: vector of the joint angles (theta 1, theta 2, ..., theta n) """ q = numpy.array(q).flatten() if len(q) != len(self.links): raise ValueError('q must contain as element as the number of links') tr = self.base.copy() l = [] for link, theta in zip(self.links, q): tr = tr * link.get_transformation_matrix(theta) l.append(tr) tr = tr * self.tool l.append(tr) return tr, numpy.asarray(l)
python
def forward_kinematics(self, q): """ Computes the homogeneous transformation matrix of the end effector of the chain. :param vector q: vector of the joint angles (theta 1, theta 2, ..., theta n) """ q = numpy.array(q).flatten() if len(q) != len(self.links): raise ValueError('q must contain as element as the number of links') tr = self.base.copy() l = [] for link, theta in zip(self.links, q): tr = tr * link.get_transformation_matrix(theta) l.append(tr) tr = tr * self.tool l.append(tr) return tr, numpy.asarray(l)
[ "def", "forward_kinematics", "(", "self", ",", "q", ")", ":", "q", "=", "numpy", ".", "array", "(", "q", ")", ".", "flatten", "(", ")", "if", "len", "(", "q", ")", "!=", "len", "(", "self", ".", "links", ")", ":", "raise", "ValueError", "(", "'q must contain as element as the number of links'", ")", "tr", "=", "self", ".", "base", ".", "copy", "(", ")", "l", "=", "[", "]", "for", "link", ",", "theta", "in", "zip", "(", "self", ".", "links", ",", "q", ")", ":", "tr", "=", "tr", "*", "link", ".", "get_transformation_matrix", "(", "theta", ")", "l", ".", "append", "(", "tr", ")", "tr", "=", "tr", "*", "self", ".", "tool", "l", ".", "append", "(", "tr", ")", "return", "tr", ",", "numpy", ".", "asarray", "(", "l", ")" ]
Computes the homogeneous transformation matrix of the end effector of the chain. :param vector q: vector of the joint angles (theta 1, theta 2, ..., theta n)
[ "Computes", "the", "homogeneous", "transformation", "matrix", "of", "the", "end", "effector", "of", "the", "chain", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/kinematics.py#L51-L73
702
poppy-project/pypot
pypot/kinematics.py
Chain.inverse_kinematics
def inverse_kinematics(self, end_effector_transformation, q=None, max_iter=1000, tolerance=0.05, mask=numpy.ones(6), use_pinv=False): """ Computes the joint angles corresponding to the end effector transformation. :param end_effector_transformation: the end effector homogeneous transformation matrix :param vector q: initial estimate of the joint angles :param int max_iter: maximum number of iteration :param float tolerance: tolerance before convergence :param mask: specify the cartesian DOF that will be ignore (in the case of a chain with less than 6 joints). :rtype: vector of the joint angles (theta 1, theta 2, ..., theta n) """ if q is None: q = numpy.zeros((len(self.links), 1)) q = numpy.matrix(q.reshape(-1, 1)) best_e = numpy.ones(6) * numpy.inf best_q = None alpha = 1.0 for _ in range(max_iter): e = numpy.multiply(transform_difference(self.forward_kinematics(q)[0], end_effector_transformation), mask) d = numpy.linalg.norm(e) if d < numpy.linalg.norm(best_e): best_e = e.copy() best_q = q.copy() alpha *= 2.0 ** (1.0 / 8.0) else: q = best_q.copy() e = best_e.copy() alpha *= 0.5 if use_pinv: dq = numpy.linalg.pinv(self._jacob0(q)) * e.reshape((-1, 1)) else: dq = self._jacob0(q).T * e.reshape((-1, 1)) q += alpha * dq # d = numpy.linalg.norm(dq) if d < tolerance: return q else: raise ValueError('could not converge d={}'.format(numpy.linalg.norm(best_e)))
python
def inverse_kinematics(self, end_effector_transformation, q=None, max_iter=1000, tolerance=0.05, mask=numpy.ones(6), use_pinv=False): """ Computes the joint angles corresponding to the end effector transformation. :param end_effector_transformation: the end effector homogeneous transformation matrix :param vector q: initial estimate of the joint angles :param int max_iter: maximum number of iteration :param float tolerance: tolerance before convergence :param mask: specify the cartesian DOF that will be ignore (in the case of a chain with less than 6 joints). :rtype: vector of the joint angles (theta 1, theta 2, ..., theta n) """ if q is None: q = numpy.zeros((len(self.links), 1)) q = numpy.matrix(q.reshape(-1, 1)) best_e = numpy.ones(6) * numpy.inf best_q = None alpha = 1.0 for _ in range(max_iter): e = numpy.multiply(transform_difference(self.forward_kinematics(q)[0], end_effector_transformation), mask) d = numpy.linalg.norm(e) if d < numpy.linalg.norm(best_e): best_e = e.copy() best_q = q.copy() alpha *= 2.0 ** (1.0 / 8.0) else: q = best_q.copy() e = best_e.copy() alpha *= 0.5 if use_pinv: dq = numpy.linalg.pinv(self._jacob0(q)) * e.reshape((-1, 1)) else: dq = self._jacob0(q).T * e.reshape((-1, 1)) q += alpha * dq # d = numpy.linalg.norm(dq) if d < tolerance: return q else: raise ValueError('could not converge d={}'.format(numpy.linalg.norm(best_e)))
[ "def", "inverse_kinematics", "(", "self", ",", "end_effector_transformation", ",", "q", "=", "None", ",", "max_iter", "=", "1000", ",", "tolerance", "=", "0.05", ",", "mask", "=", "numpy", ".", "ones", "(", "6", ")", ",", "use_pinv", "=", "False", ")", ":", "if", "q", "is", "None", ":", "q", "=", "numpy", ".", "zeros", "(", "(", "len", "(", "self", ".", "links", ")", ",", "1", ")", ")", "q", "=", "numpy", ".", "matrix", "(", "q", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", "best_e", "=", "numpy", ".", "ones", "(", "6", ")", "*", "numpy", ".", "inf", "best_q", "=", "None", "alpha", "=", "1.0", "for", "_", "in", "range", "(", "max_iter", ")", ":", "e", "=", "numpy", ".", "multiply", "(", "transform_difference", "(", "self", ".", "forward_kinematics", "(", "q", ")", "[", "0", "]", ",", "end_effector_transformation", ")", ",", "mask", ")", "d", "=", "numpy", ".", "linalg", ".", "norm", "(", "e", ")", "if", "d", "<", "numpy", ".", "linalg", ".", "norm", "(", "best_e", ")", ":", "best_e", "=", "e", ".", "copy", "(", ")", "best_q", "=", "q", ".", "copy", "(", ")", "alpha", "*=", "2.0", "**", "(", "1.0", "/", "8.0", ")", "else", ":", "q", "=", "best_q", ".", "copy", "(", ")", "e", "=", "best_e", ".", "copy", "(", ")", "alpha", "*=", "0.5", "if", "use_pinv", ":", "dq", "=", "numpy", ".", "linalg", ".", "pinv", "(", "self", ".", "_jacob0", "(", "q", ")", ")", "*", "e", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "else", ":", "dq", "=", "self", ".", "_jacob0", "(", "q", ")", ".", "T", "*", "e", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "q", "+=", "alpha", "*", "dq", "# d = numpy.linalg.norm(dq)", "if", "d", "<", "tolerance", ":", "return", "q", "else", ":", "raise", "ValueError", "(", "'could not converge d={}'", ".", "format", "(", "numpy", ".", "linalg", ".", "norm", "(", "best_e", ")", ")", ")" ]
Computes the joint angles corresponding to the end effector transformation. :param end_effector_transformation: the end effector homogeneous transformation matrix :param vector q: initial estimate of the joint angles :param int max_iter: maximum number of iteration :param float tolerance: tolerance before convergence :param mask: specify the cartesian DOF that will be ignore (in the case of a chain with less than 6 joints). :rtype: vector of the joint angles (theta 1, theta 2, ..., theta n)
[ "Computes", "the", "joint", "angles", "corresponding", "to", "the", "end", "effector", "transformation", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/kinematics.py#L75-L122
703
poppy-project/pypot
pypot/dynamixel/__init__.py
_get_available_ports
def _get_available_ports(): """ Tries to find the available serial ports on your system. """ if platform.system() == 'Darwin': return glob.glob('/dev/tty.usb*') elif platform.system() == 'Linux': return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyAMA*') elif sys.platform.lower() == 'cygwin': return glob.glob('/dev/com*') elif platform.system() == 'Windows': import _winreg import itertools ports = [] path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path) for i in itertools.count(): try: ports.append(str(_winreg.EnumValue(key, i)[1])) except WindowsError: return ports else: raise EnvironmentError('{} is an unsupported platform, cannot find serial ports !'.format(platform.system())) return []
python
def _get_available_ports(): """ Tries to find the available serial ports on your system. """ if platform.system() == 'Darwin': return glob.glob('/dev/tty.usb*') elif platform.system() == 'Linux': return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyAMA*') elif sys.platform.lower() == 'cygwin': return glob.glob('/dev/com*') elif platform.system() == 'Windows': import _winreg import itertools ports = [] path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path) for i in itertools.count(): try: ports.append(str(_winreg.EnumValue(key, i)[1])) except WindowsError: return ports else: raise EnvironmentError('{} is an unsupported platform, cannot find serial ports !'.format(platform.system())) return []
[ "def", "_get_available_ports", "(", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "'Darwin'", ":", "return", "glob", ".", "glob", "(", "'/dev/tty.usb*'", ")", "elif", "platform", ".", "system", "(", ")", "==", "'Linux'", ":", "return", "glob", ".", "glob", "(", "'/dev/ttyACM*'", ")", "+", "glob", ".", "glob", "(", "'/dev/ttyUSB*'", ")", "+", "glob", ".", "glob", "(", "'/dev/ttyAMA*'", ")", "elif", "sys", ".", "platform", ".", "lower", "(", ")", "==", "'cygwin'", ":", "return", "glob", ".", "glob", "(", "'/dev/com*'", ")", "elif", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "import", "_winreg", "import", "itertools", "ports", "=", "[", "]", "path", "=", "'HARDWARE\\\\DEVICEMAP\\\\SERIALCOMM'", "key", "=", "_winreg", ".", "OpenKey", "(", "_winreg", ".", "HKEY_LOCAL_MACHINE", ",", "path", ")", "for", "i", "in", "itertools", ".", "count", "(", ")", ":", "try", ":", "ports", ".", "append", "(", "str", "(", "_winreg", ".", "EnumValue", "(", "key", ",", "i", ")", "[", "1", "]", ")", ")", "except", "WindowsError", ":", "return", "ports", "else", ":", "raise", "EnvironmentError", "(", "'{} is an unsupported platform, cannot find serial ports !'", ".", "format", "(", "platform", ".", "system", "(", ")", ")", ")", "return", "[", "]" ]
Tries to find the available serial ports on your system.
[ "Tries", "to", "find", "the", "available", "serial", "ports", "on", "your", "system", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/__init__.py#L20-L46
704
poppy-project/pypot
pypot/dynamixel/__init__.py
find_port
def find_port(ids, strict=True): """ Find the port with the specified attached motor ids. :param list ids: list of motor ids to find :param bool strict: specify if all ids should be find (when set to False, only half motor must be found) .. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned. """ ids_founds = [] for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): try: with DxlIOCls(port) as dxl: _ids_founds = dxl.scan(ids) ids_founds += _ids_founds if strict and len(_ids_founds) == len(ids): return port if not strict and len(_ids_founds) >= len(ids) / 2: logger.warning('Missing ids: {}'.format(ids, list(set(ids) - set(_ids_founds)))) return port if len(ids_founds) > 0: logger.warning('Port:{} ids found:{}'.format(port, _ids_founds)) except DxlError: logger.warning('DxlError on port {}'.format(port)) continue raise IndexError('No suitable port found for ids {}. These ids are missing {} !'.format( ids, list(set(ids) - set(ids_founds))))
python
def find_port(ids, strict=True): """ Find the port with the specified attached motor ids. :param list ids: list of motor ids to find :param bool strict: specify if all ids should be find (when set to False, only half motor must be found) .. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned. """ ids_founds = [] for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): try: with DxlIOCls(port) as dxl: _ids_founds = dxl.scan(ids) ids_founds += _ids_founds if strict and len(_ids_founds) == len(ids): return port if not strict and len(_ids_founds) >= len(ids) / 2: logger.warning('Missing ids: {}'.format(ids, list(set(ids) - set(_ids_founds)))) return port if len(ids_founds) > 0: logger.warning('Port:{} ids found:{}'.format(port, _ids_founds)) except DxlError: logger.warning('DxlError on port {}'.format(port)) continue raise IndexError('No suitable port found for ids {}. These ids are missing {} !'.format( ids, list(set(ids) - set(ids_founds))))
[ "def", "find_port", "(", "ids", ",", "strict", "=", "True", ")", ":", "ids_founds", "=", "[", "]", "for", "port", "in", "get_available_ports", "(", ")", ":", "for", "DxlIOCls", "in", "(", "DxlIO", ",", "Dxl320IO", ")", ":", "try", ":", "with", "DxlIOCls", "(", "port", ")", "as", "dxl", ":", "_ids_founds", "=", "dxl", ".", "scan", "(", "ids", ")", "ids_founds", "+=", "_ids_founds", "if", "strict", "and", "len", "(", "_ids_founds", ")", "==", "len", "(", "ids", ")", ":", "return", "port", "if", "not", "strict", "and", "len", "(", "_ids_founds", ")", ">=", "len", "(", "ids", ")", "/", "2", ":", "logger", ".", "warning", "(", "'Missing ids: {}'", ".", "format", "(", "ids", ",", "list", "(", "set", "(", "ids", ")", "-", "set", "(", "_ids_founds", ")", ")", ")", ")", "return", "port", "if", "len", "(", "ids_founds", ")", ">", "0", ":", "logger", ".", "warning", "(", "'Port:{} ids found:{}'", ".", "format", "(", "port", ",", "_ids_founds", ")", ")", "except", "DxlError", ":", "logger", ".", "warning", "(", "'DxlError on port {}'", ".", "format", "(", "port", ")", ")", "continue", "raise", "IndexError", "(", "'No suitable port found for ids {}. These ids are missing {} !'", ".", "format", "(", "ids", ",", "list", "(", "set", "(", "ids", ")", "-", "set", "(", "ids_founds", ")", ")", ")", ")" ]
Find the port with the specified attached motor ids. :param list ids: list of motor ids to find :param bool strict: specify if all ids should be find (when set to False, only half motor must be found) .. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned.
[ "Find", "the", "port", "with", "the", "specified", "attached", "motor", "ids", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/__init__.py#L74-L106
705
poppy-project/pypot
pypot/sensor/depth/sonar.py
Sonar._filter
def _filter(self, data): """ Apply a filter to reduce noisy data. Return the median value of a heap of data. """ filtered_data = [] for queue, data in zip(self._raw_data_queues, data): queue.append(data) filtered_data.append(numpy.median(queue)) return filtered_data
python
def _filter(self, data): """ Apply a filter to reduce noisy data. Return the median value of a heap of data. """ filtered_data = [] for queue, data in zip(self._raw_data_queues, data): queue.append(data) filtered_data.append(numpy.median(queue)) return filtered_data
[ "def", "_filter", "(", "self", ",", "data", ")", ":", "filtered_data", "=", "[", "]", "for", "queue", ",", "data", "in", "zip", "(", "self", ".", "_raw_data_queues", ",", "data", ")", ":", "queue", ".", "append", "(", "data", ")", "filtered_data", ".", "append", "(", "numpy", ".", "median", "(", "queue", ")", ")", "return", "filtered_data" ]
Apply a filter to reduce noisy data. Return the median value of a heap of data.
[ "Apply", "a", "filter", "to", "reduce", "noisy", "data", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/sensor/depth/sonar.py#L87-L98
706
poppy-project/pypot
pypot/dynamixel/syncloop.py
MetaDxlController.setup
def setup(self): """ Starts all the synchronization loops. """ [c.start() for c in self.controllers] [c.wait_to_start() for c in self.controllers]
python
def setup(self): """ Starts all the synchronization loops. """ [c.start() for c in self.controllers] [c.wait_to_start() for c in self.controllers]
[ "def", "setup", "(", "self", ")", ":", "[", "c", ".", "start", "(", ")", "for", "c", "in", "self", ".", "controllers", "]", "[", "c", ".", "wait_to_start", "(", ")", "for", "c", "in", "self", ".", "controllers", "]" ]
Starts all the synchronization loops.
[ "Starts", "all", "the", "synchronization", "loops", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/syncloop.py#L20-L23
707
poppy-project/pypot
pypot/creatures/ik.py
IKChain.from_poppy_creature
def from_poppy_creature(cls, poppy, motors, passiv, tip, reversed_motors=[]): """ Creates an kinematic chain from motors of a Poppy Creature. :param poppy: PoppyCreature used :param list motors: list of all motors that composed the kinematic chain :param list passiv: list of motors which are passiv in the chain (they will not move) :param list tip: [x, y, z] translation of the tip of the chain (in meters) :param list reversed_motors: list of motors that should be manually reversed (due to a problem in the URDF?) """ chain_elements = get_chain_from_joints(poppy.urdf_file, [m.name for m in motors]) activ = [False] + [m not in passiv for m in motors] + [True] chain = cls.from_urdf_file(poppy.urdf_file, base_elements=chain_elements, last_link_vector=tip, active_links_mask=activ) chain.motors = [getattr(poppy, l.name) for l in chain.links[1:-1]] for m, l in zip(chain.motors, chain.links[1:-1]): # Force an access to angle limit to retrieve real values # This is quite an ugly fix and should be handled better m.angle_limit bounds = m.__dict__['lower_limit'], m.__dict__['upper_limit'] l.bounds = tuple(map(rad2deg, bounds)) chain._reversed = array([(-1 if m in reversed_motors else 1) for m in motors]) return chain
python
def from_poppy_creature(cls, poppy, motors, passiv, tip, reversed_motors=[]): """ Creates an kinematic chain from motors of a Poppy Creature. :param poppy: PoppyCreature used :param list motors: list of all motors that composed the kinematic chain :param list passiv: list of motors which are passiv in the chain (they will not move) :param list tip: [x, y, z] translation of the tip of the chain (in meters) :param list reversed_motors: list of motors that should be manually reversed (due to a problem in the URDF?) """ chain_elements = get_chain_from_joints(poppy.urdf_file, [m.name for m in motors]) activ = [False] + [m not in passiv for m in motors] + [True] chain = cls.from_urdf_file(poppy.urdf_file, base_elements=chain_elements, last_link_vector=tip, active_links_mask=activ) chain.motors = [getattr(poppy, l.name) for l in chain.links[1:-1]] for m, l in zip(chain.motors, chain.links[1:-1]): # Force an access to angle limit to retrieve real values # This is quite an ugly fix and should be handled better m.angle_limit bounds = m.__dict__['lower_limit'], m.__dict__['upper_limit'] l.bounds = tuple(map(rad2deg, bounds)) chain._reversed = array([(-1 if m in reversed_motors else 1) for m in motors]) return chain
[ "def", "from_poppy_creature", "(", "cls", ",", "poppy", ",", "motors", ",", "passiv", ",", "tip", ",", "reversed_motors", "=", "[", "]", ")", ":", "chain_elements", "=", "get_chain_from_joints", "(", "poppy", ".", "urdf_file", ",", "[", "m", ".", "name", "for", "m", "in", "motors", "]", ")", "activ", "=", "[", "False", "]", "+", "[", "m", "not", "in", "passiv", "for", "m", "in", "motors", "]", "+", "[", "True", "]", "chain", "=", "cls", ".", "from_urdf_file", "(", "poppy", ".", "urdf_file", ",", "base_elements", "=", "chain_elements", ",", "last_link_vector", "=", "tip", ",", "active_links_mask", "=", "activ", ")", "chain", ".", "motors", "=", "[", "getattr", "(", "poppy", ",", "l", ".", "name", ")", "for", "l", "in", "chain", ".", "links", "[", "1", ":", "-", "1", "]", "]", "for", "m", ",", "l", "in", "zip", "(", "chain", ".", "motors", ",", "chain", ".", "links", "[", "1", ":", "-", "1", "]", ")", ":", "# Force an access to angle limit to retrieve real values", "# This is quite an ugly fix and should be handled better", "m", ".", "angle_limit", "bounds", "=", "m", ".", "__dict__", "[", "'lower_limit'", "]", ",", "m", ".", "__dict__", "[", "'upper_limit'", "]", "l", ".", "bounds", "=", "tuple", "(", "map", "(", "rad2deg", ",", "bounds", ")", ")", "chain", ".", "_reversed", "=", "array", "(", "[", "(", "-", "1", "if", "m", "in", "reversed_motors", "else", "1", ")", "for", "m", "in", "motors", "]", ")", "return", "chain" ]
Creates an kinematic chain from motors of a Poppy Creature. :param poppy: PoppyCreature used :param list motors: list of all motors that composed the kinematic chain :param list passiv: list of motors which are passiv in the chain (they will not move) :param list tip: [x, y, z] translation of the tip of the chain (in meters) :param list reversed_motors: list of motors that should be manually reversed (due to a problem in the URDF?)
[ "Creates", "an", "kinematic", "chain", "from", "motors", "of", "a", "Poppy", "Creature", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/creatures/ik.py#L14-L48
708
poppy-project/pypot
pypot/creatures/ik.py
IKChain.goto
def goto(self, position, duration, wait=False, accurate=False): """ Goes to a given cartesian position. :param list position: [x, y, z] representing the target position (in meters) :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computation time. By default, use the not so accurate but fast version. """ if len(position) != 3: raise ValueError('Position should be a list [x, y, z]!') M = eye(4) M[:3, 3] = position self._goto(M, duration, wait, accurate)
python
def goto(self, position, duration, wait=False, accurate=False): """ Goes to a given cartesian position. :param list position: [x, y, z] representing the target position (in meters) :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computation time. By default, use the not so accurate but fast version. """ if len(position) != 3: raise ValueError('Position should be a list [x, y, z]!') M = eye(4) M[:3, 3] = position self._goto(M, duration, wait, accurate)
[ "def", "goto", "(", "self", ",", "position", ",", "duration", ",", "wait", "=", "False", ",", "accurate", "=", "False", ")", ":", "if", "len", "(", "position", ")", "!=", "3", ":", "raise", "ValueError", "(", "'Position should be a list [x, y, z]!'", ")", "M", "=", "eye", "(", "4", ")", "M", "[", ":", "3", ",", "3", "]", "=", "position", "self", ".", "_goto", "(", "M", ",", "duration", ",", "wait", ",", "accurate", ")" ]
Goes to a given cartesian position. :param list position: [x, y, z] representing the target position (in meters) :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computation time. By default, use the not so accurate but fast version.
[ "Goes", "to", "a", "given", "cartesian", "position", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/creatures/ik.py#L61-L75
709
poppy-project/pypot
pypot/creatures/ik.py
IKChain._goto
def _goto(self, pose, duration, wait, accurate): """ Goes to a given cartesian pose. :param matrix pose: homogeneous matrix representing the target position :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computation time. By default, use the not so accurate but fast version. """ kwargs = {} if not accurate: kwargs['max_iter'] = 3 q0 = self.convert_to_ik_angles(self.joints_position) q = self.inverse_kinematics(pose, initial_position=q0, **kwargs) joints = self.convert_from_ik_angles(q) last = self.motors[-1] for m, pos in list(zip(self.motors, joints)): m.goto_position(pos, duration, wait=False if m != last else wait)
python
def _goto(self, pose, duration, wait, accurate): """ Goes to a given cartesian pose. :param matrix pose: homogeneous matrix representing the target position :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computation time. By default, use the not so accurate but fast version. """ kwargs = {} if not accurate: kwargs['max_iter'] = 3 q0 = self.convert_to_ik_angles(self.joints_position) q = self.inverse_kinematics(pose, initial_position=q0, **kwargs) joints = self.convert_from_ik_angles(q) last = self.motors[-1] for m, pos in list(zip(self.motors, joints)): m.goto_position(pos, duration, wait=False if m != last else wait)
[ "def", "_goto", "(", "self", ",", "pose", ",", "duration", ",", "wait", ",", "accurate", ")", ":", "kwargs", "=", "{", "}", "if", "not", "accurate", ":", "kwargs", "[", "'max_iter'", "]", "=", "3", "q0", "=", "self", ".", "convert_to_ik_angles", "(", "self", ".", "joints_position", ")", "q", "=", "self", ".", "inverse_kinematics", "(", "pose", ",", "initial_position", "=", "q0", ",", "*", "*", "kwargs", ")", "joints", "=", "self", ".", "convert_from_ik_angles", "(", "q", ")", "last", "=", "self", ".", "motors", "[", "-", "1", "]", "for", "m", ",", "pos", "in", "list", "(", "zip", "(", "self", ".", "motors", ",", "joints", ")", ")", ":", "m", ".", "goto_position", "(", "pos", ",", "duration", ",", "wait", "=", "False", "if", "m", "!=", "last", "else", "wait", ")" ]
Goes to a given cartesian pose. :param matrix pose: homogeneous matrix representing the target position :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computation time. By default, use the not so accurate but fast version.
[ "Goes", "to", "a", "given", "cartesian", "pose", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/creatures/ik.py#L77-L99
710
poppy-project/pypot
pypot/creatures/ik.py
IKChain.convert_to_ik_angles
def convert_to_ik_angles(self, joints): """ Convert from poppy representation to IKPY internal representation. """ if len(joints) != len(self.motors): raise ValueError('Incompatible data, len(joints) should be {}!'.format(len(self.motors))) raw_joints = [(j + m.offset) * (1 if m.direct else -1) for j, m in zip(joints, self.motors)] raw_joints *= self._reversed return [0] + [deg2rad(j) for j in raw_joints] + [0]
python
def convert_to_ik_angles(self, joints): """ Convert from poppy representation to IKPY internal representation. """ if len(joints) != len(self.motors): raise ValueError('Incompatible data, len(joints) should be {}!'.format(len(self.motors))) raw_joints = [(j + m.offset) * (1 if m.direct else -1) for j, m in zip(joints, self.motors)] raw_joints *= self._reversed return [0] + [deg2rad(j) for j in raw_joints] + [0]
[ "def", "convert_to_ik_angles", "(", "self", ",", "joints", ")", ":", "if", "len", "(", "joints", ")", "!=", "len", "(", "self", ".", "motors", ")", ":", "raise", "ValueError", "(", "'Incompatible data, len(joints) should be {}!'", ".", "format", "(", "len", "(", "self", ".", "motors", ")", ")", ")", "raw_joints", "=", "[", "(", "j", "+", "m", ".", "offset", ")", "*", "(", "1", "if", "m", ".", "direct", "else", "-", "1", ")", "for", "j", ",", "m", "in", "zip", "(", "joints", ",", "self", ".", "motors", ")", "]", "raw_joints", "*=", "self", ".", "_reversed", "return", "[", "0", "]", "+", "[", "deg2rad", "(", "j", ")", "for", "j", "in", "raw_joints", "]", "+", "[", "0", "]" ]
Convert from poppy representation to IKPY internal representation.
[ "Convert", "from", "poppy", "representation", "to", "IKPY", "internal", "representation", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/creatures/ik.py#L101-L111
711
poppy-project/pypot
pypot/creatures/ik.py
IKChain.convert_from_ik_angles
def convert_from_ik_angles(self, joints): """ Convert from IKPY internal representation to poppy representation. """ if len(joints) != len(self.motors) + 2: raise ValueError('Incompatible data, len(joints) should be {}!'.format(len(self.motors) + 2)) joints = [rad2deg(j) for j in joints[1:-1]] joints *= self._reversed return [(j * (1 if m.direct else -1)) - m.offset for j, m in zip(joints, self.motors)]
python
def convert_from_ik_angles(self, joints): """ Convert from IKPY internal representation to poppy representation. """ if len(joints) != len(self.motors) + 2: raise ValueError('Incompatible data, len(joints) should be {}!'.format(len(self.motors) + 2)) joints = [rad2deg(j) for j in joints[1:-1]] joints *= self._reversed return [(j * (1 if m.direct else -1)) - m.offset for j, m in zip(joints, self.motors)]
[ "def", "convert_from_ik_angles", "(", "self", ",", "joints", ")", ":", "if", "len", "(", "joints", ")", "!=", "len", "(", "self", ".", "motors", ")", "+", "2", ":", "raise", "ValueError", "(", "'Incompatible data, len(joints) should be {}!'", ".", "format", "(", "len", "(", "self", ".", "motors", ")", "+", "2", ")", ")", "joints", "=", "[", "rad2deg", "(", "j", ")", "for", "j", "in", "joints", "[", "1", ":", "-", "1", "]", "]", "joints", "*=", "self", ".", "_reversed", "return", "[", "(", "j", "*", "(", "1", "if", "m", ".", "direct", "else", "-", "1", ")", ")", "-", "m", ".", "offset", "for", "j", ",", "m", "in", "zip", "(", "joints", ",", "self", ".", "motors", ")", "]" ]
Convert from IKPY internal representation to poppy representation.
[ "Convert", "from", "IKPY", "internal", "representation", "to", "poppy", "representation", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/creatures/ik.py#L113-L122
712
poppy-project/pypot
pypot/dynamixel/io/io_320.py
Dxl320IO.factory_reset
def factory_reset(self, ids, except_ids=False, except_baudrate_and_ids=False): """ Reset all motors on the bus to their factory default settings. """ mode = (0x02 if except_baudrate_and_ids else 0x01 if except_ids else 0xFF) for id in ids: try: self._send_packet(self._protocol.DxlResetPacket(id, mode)) except (DxlTimeoutError, DxlCommunicationError): pass
python
def factory_reset(self, ids, except_ids=False, except_baudrate_and_ids=False): """ Reset all motors on the bus to their factory default settings. """ mode = (0x02 if except_baudrate_and_ids else 0x01 if except_ids else 0xFF) for id in ids: try: self._send_packet(self._protocol.DxlResetPacket(id, mode)) except (DxlTimeoutError, DxlCommunicationError): pass
[ "def", "factory_reset", "(", "self", ",", "ids", ",", "except_ids", "=", "False", ",", "except_baudrate_and_ids", "=", "False", ")", ":", "mode", "=", "(", "0x02", "if", "except_baudrate_and_ids", "else", "0x01", "if", "except_ids", "else", "0xFF", ")", "for", "id", "in", "ids", ":", "try", ":", "self", ".", "_send_packet", "(", "self", ".", "_protocol", ".", "DxlResetPacket", "(", "id", ",", "mode", ")", ")", "except", "(", "DxlTimeoutError", ",", "DxlCommunicationError", ")", ":", "pass" ]
Reset all motors on the bus to their factory default settings.
[ "Reset", "all", "motors", "on", "the", "bus", "to", "their", "factory", "default", "settings", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/io_320.py#L32-L43
713
poppy-project/pypot
pypot/primitive/primitive.py
Primitive.stop
def stop(self, wait=True): """ Requests the primitive to stop. """ logger.info("Primitive %s stopped.", self) StoppableThread.stop(self, wait)
python
def stop(self, wait=True): """ Requests the primitive to stop. """ logger.info("Primitive %s stopped.", self) StoppableThread.stop(self, wait)
[ "def", "stop", "(", "self", ",", "wait", "=", "True", ")", ":", "logger", ".", "info", "(", "\"Primitive %s stopped.\"", ",", "self", ")", "StoppableThread", ".", "stop", "(", "self", ",", "wait", ")" ]
Requests the primitive to stop.
[ "Requests", "the", "primitive", "to", "stop", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/primitive.py#L126-L129
714
poppy-project/pypot
pypot/primitive/primitive.py
LoopPrimitive.recent_update_frequencies
def recent_update_frequencies(self): """ Returns the 10 most recent update frequencies. The given frequencies are computed as short-term frequencies! The 0th element of the list corresponds to the most recent frequency. """ return list(reversed([(1.0 / p) for p in numpy.diff(self._recent_updates)]))
python
def recent_update_frequencies(self): """ Returns the 10 most recent update frequencies. The given frequencies are computed as short-term frequencies! The 0th element of the list corresponds to the most recent frequency. """ return list(reversed([(1.0 / p) for p in numpy.diff(self._recent_updates)]))
[ "def", "recent_update_frequencies", "(", "self", ")", ":", "return", "list", "(", "reversed", "(", "[", "(", "1.0", "/", "p", ")", "for", "p", "in", "numpy", ".", "diff", "(", "self", ".", "_recent_updates", ")", "]", ")", ")" ]
Returns the 10 most recent update frequencies. The given frequencies are computed as short-term frequencies! The 0th element of the list corresponds to the most recent frequency.
[ "Returns", "the", "10", "most", "recent", "update", "frequencies", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/primitive.py#L174-L180
715
poppy-project/pypot
pypot/primitive/primitive.py
MockupMotor.goto_position
def goto_position(self, position, duration, control=None, wait=False): """ Automatically sets the goal position and the moving speed to reach the desired position within the duration. """ if control is None: control = self.goto_behavior if control == 'minjerk': goto_min_jerk = GotoMinJerk(self, position, duration) goto_min_jerk.start() if wait: goto_min_jerk.wait_to_stop() elif control == 'dummy': dp = abs(self.present_position - position) speed = (dp / float(duration)) if duration > 0 else numpy.inf self.moving_speed = speed self.goal_position = position if wait: time.sleep(duration)
python
def goto_position(self, position, duration, control=None, wait=False): """ Automatically sets the goal position and the moving speed to reach the desired position within the duration. """ if control is None: control = self.goto_behavior if control == 'minjerk': goto_min_jerk = GotoMinJerk(self, position, duration) goto_min_jerk.start() if wait: goto_min_jerk.wait_to_stop() elif control == 'dummy': dp = abs(self.present_position - position) speed = (dp / float(duration)) if duration > 0 else numpy.inf self.moving_speed = speed self.goal_position = position if wait: time.sleep(duration)
[ "def", "goto_position", "(", "self", ",", "position", ",", "duration", ",", "control", "=", "None", ",", "wait", "=", "False", ")", ":", "if", "control", "is", "None", ":", "control", "=", "self", ".", "goto_behavior", "if", "control", "==", "'minjerk'", ":", "goto_min_jerk", "=", "GotoMinJerk", "(", "self", ",", "position", ",", "duration", ")", "goto_min_jerk", ".", "start", "(", ")", "if", "wait", ":", "goto_min_jerk", ".", "wait_to_stop", "(", ")", "elif", "control", "==", "'dummy'", ":", "dp", "=", "abs", "(", "self", ".", "present_position", "-", "position", ")", "speed", "=", "(", "dp", "/", "float", "(", "duration", ")", ")", "if", "duration", ">", "0", "else", "numpy", ".", "inf", "self", ".", "moving_speed", "=", "speed", "self", ".", "goal_position", "=", "position", "if", "wait", ":", "time", ".", "sleep", "(", "duration", ")" ]
Automatically sets the goal position and the moving speed to reach the desired position within the duration.
[ "Automatically", "sets", "the", "goal", "position", "and", "the", "moving", "speed", "to", "reach", "the", "desired", "position", "within", "the", "duration", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/primitive.py#L257-L277
716
poppy-project/pypot
pypot/primitive/move.py
MoveRecorder.add_tracked_motors
def add_tracked_motors(self, tracked_motors): """Add new motors to the recording""" new_mockup_motors = map(self.get_mockup_motor, tracked_motors) self.tracked_motors = list(set(self.tracked_motors + new_mockup_motors))
python
def add_tracked_motors(self, tracked_motors): """Add new motors to the recording""" new_mockup_motors = map(self.get_mockup_motor, tracked_motors) self.tracked_motors = list(set(self.tracked_motors + new_mockup_motors))
[ "def", "add_tracked_motors", "(", "self", ",", "tracked_motors", ")", ":", "new_mockup_motors", "=", "map", "(", "self", ".", "get_mockup_motor", ",", "tracked_motors", ")", "self", ".", "tracked_motors", "=", "list", "(", "set", "(", "self", ".", "tracked_motors", "+", "new_mockup_motors", ")", ")" ]
Add new motors to the recording
[ "Add", "new", "motors", "to", "the", "recording" ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/move.py#L137-L140
717
poppy-project/pypot
pypot/primitive/manager.py
PrimitiveManager.update
def update(self): """ Combined at a predefined frequency the request orders and affect them to the real motors. """ with self.syncing: for m in self._motors: to_set = defaultdict(list) for p in self._prim: for key, val in getattr(p.robot, m.name)._to_set.iteritems(): to_set[key].append(val) for key, val in to_set.iteritems(): if key == 'led': colors = set(val) if len(colors) > 1: colors -= {'off'} filtred_val = colors.pop() else: filtred_val = self._filter(val) logger.debug('Combined %s.%s from %s to %s', m.name, key, val, filtred_val) setattr(m, key, filtred_val) [p._synced.set() for p in self._prim]
python
def update(self): """ Combined at a predefined frequency the request orders and affect them to the real motors. """ with self.syncing: for m in self._motors: to_set = defaultdict(list) for p in self._prim: for key, val in getattr(p.robot, m.name)._to_set.iteritems(): to_set[key].append(val) for key, val in to_set.iteritems(): if key == 'led': colors = set(val) if len(colors) > 1: colors -= {'off'} filtred_val = colors.pop() else: filtred_val = self._filter(val) logger.debug('Combined %s.%s from %s to %s', m.name, key, val, filtred_val) setattr(m, key, filtred_val) [p._synced.set() for p in self._prim]
[ "def", "update", "(", "self", ")", ":", "with", "self", ".", "syncing", ":", "for", "m", "in", "self", ".", "_motors", ":", "to_set", "=", "defaultdict", "(", "list", ")", "for", "p", "in", "self", ".", "_prim", ":", "for", "key", ",", "val", "in", "getattr", "(", "p", ".", "robot", ",", "m", ".", "name", ")", ".", "_to_set", ".", "iteritems", "(", ")", ":", "to_set", "[", "key", "]", ".", "append", "(", "val", ")", "for", "key", ",", "val", "in", "to_set", ".", "iteritems", "(", ")", ":", "if", "key", "==", "'led'", ":", "colors", "=", "set", "(", "val", ")", "if", "len", "(", "colors", ")", ">", "1", ":", "colors", "-=", "{", "'off'", "}", "filtred_val", "=", "colors", ".", "pop", "(", ")", "else", ":", "filtred_val", "=", "self", ".", "_filter", "(", "val", ")", "logger", ".", "debug", "(", "'Combined %s.%s from %s to %s'", ",", "m", ".", "name", ",", "key", ",", "val", ",", "filtred_val", ")", "setattr", "(", "m", ",", "key", ",", "filtred_val", ")", "[", "p", ".", "_synced", ".", "set", "(", ")", "for", "p", "in", "self", ".", "_prim", "]" ]
Combined at a predefined frequency the request orders and affect them to the real motors.
[ "Combined", "at", "a", "predefined", "frequency", "the", "request", "orders", "and", "affect", "them", "to", "the", "real", "motors", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/manager.py#L51-L74
718
poppy-project/pypot
pypot/primitive/manager.py
PrimitiveManager.stop
def stop(self): """ Stop the primitive manager. """ for p in self.primitives[:]: p.stop() StoppableLoopThread.stop(self)
python
def stop(self): """ Stop the primitive manager. """ for p in self.primitives[:]: p.stop() StoppableLoopThread.stop(self)
[ "def", "stop", "(", "self", ")", ":", "for", "p", "in", "self", ".", "primitives", "[", ":", "]", ":", "p", ".", "stop", "(", ")", "StoppableLoopThread", ".", "stop", "(", "self", ")" ]
Stop the primitive manager.
[ "Stop", "the", "primitive", "manager", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/manager.py#L76-L81
719
poppy-project/pypot
pypot/vrep/io.py
VrepIO.load_scene
def load_scene(self, scene_path, start=False): """ Loads a scene on the V-REP server. :param str scene_path: path to a V-REP scene file :param bool start: whether to directly start the simulation after loading the scene .. note:: It is assumed that the scene file is always available on the server side. """ self.stop_simulation() if not os.path.exists(scene_path): raise IOError("No such file or directory: '{}'".format(scene_path)) self.call_remote_api('simxLoadScene', scene_path, True) if start: self.start_simulation()
python
def load_scene(self, scene_path, start=False): """ Loads a scene on the V-REP server. :param str scene_path: path to a V-REP scene file :param bool start: whether to directly start the simulation after loading the scene .. note:: It is assumed that the scene file is always available on the server side. """ self.stop_simulation() if not os.path.exists(scene_path): raise IOError("No such file or directory: '{}'".format(scene_path)) self.call_remote_api('simxLoadScene', scene_path, True) if start: self.start_simulation()
[ "def", "load_scene", "(", "self", ",", "scene_path", ",", "start", "=", "False", ")", ":", "self", ".", "stop_simulation", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "scene_path", ")", ":", "raise", "IOError", "(", "\"No such file or directory: '{}'\"", ".", "format", "(", "scene_path", ")", ")", "self", ".", "call_remote_api", "(", "'simxLoadScene'", ",", "scene_path", ",", "True", ")", "if", "start", ":", "self", ".", "start_simulation", "(", ")" ]
Loads a scene on the V-REP server. :param str scene_path: path to a V-REP scene file :param bool start: whether to directly start the simulation after loading the scene .. note:: It is assumed that the scene file is always available on the server side.
[ "Loads", "a", "scene", "on", "the", "V", "-", "REP", "server", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L91-L108
720
poppy-project/pypot
pypot/vrep/io.py
VrepIO.get_motor_position
def get_motor_position(self, motor_name): """ Gets the motor current position. """ return self.call_remote_api('simxGetJointPosition', self.get_object_handle(motor_name), streaming=True)
python
def get_motor_position(self, motor_name): """ Gets the motor current position. """ return self.call_remote_api('simxGetJointPosition', self.get_object_handle(motor_name), streaming=True)
[ "def", "get_motor_position", "(", "self", ",", "motor_name", ")", ":", "return", "self", ".", "call_remote_api", "(", "'simxGetJointPosition'", ",", "self", ".", "get_object_handle", "(", "motor_name", ")", ",", "streaming", "=", "True", ")" ]
Gets the motor current position.
[ "Gets", "the", "motor", "current", "position", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L143-L147
721
poppy-project/pypot
pypot/vrep/io.py
VrepIO.set_motor_position
def set_motor_position(self, motor_name, position): """ Sets the motor target position. """ self.call_remote_api('simxSetJointTargetPosition', self.get_object_handle(motor_name), position, sending=True)
python
def set_motor_position(self, motor_name, position): """ Sets the motor target position. """ self.call_remote_api('simxSetJointTargetPosition', self.get_object_handle(motor_name), position, sending=True)
[ "def", "set_motor_position", "(", "self", ",", "motor_name", ",", "position", ")", ":", "self", ".", "call_remote_api", "(", "'simxSetJointTargetPosition'", ",", "self", ".", "get_object_handle", "(", "motor_name", ")", ",", "position", ",", "sending", "=", "True", ")" ]
Sets the motor target position.
[ "Sets", "the", "motor", "target", "position", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L149-L154
722
poppy-project/pypot
pypot/vrep/io.py
VrepIO.set_motor_force
def set_motor_force(self, motor_name, force): """ Sets the maximum force or torque that a joint can exert. """ self.call_remote_api('simxSetJointForce', self.get_object_handle(motor_name), force, sending=True)
python
def set_motor_force(self, motor_name, force): """ Sets the maximum force or torque that a joint can exert. """ self.call_remote_api('simxSetJointForce', self.get_object_handle(motor_name), force, sending=True)
[ "def", "set_motor_force", "(", "self", ",", "motor_name", ",", "force", ")", ":", "self", ".", "call_remote_api", "(", "'simxSetJointForce'", ",", "self", ".", "get_object_handle", "(", "motor_name", ")", ",", "force", ",", "sending", "=", "True", ")" ]
Sets the maximum force or torque that a joint can exert.
[ "Sets", "the", "maximum", "force", "or", "torque", "that", "a", "joint", "can", "exert", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L162-L167
723
poppy-project/pypot
pypot/vrep/io.py
VrepIO.get_object_position
def get_object_position(self, object_name, relative_to_object=None): """ Gets the object position. """ h = self.get_object_handle(object_name) relative_handle = (-1 if relative_to_object is None else self.get_object_handle(relative_to_object)) return self.call_remote_api('simxGetObjectPosition', h, relative_handle, streaming=True)
python
def get_object_position(self, object_name, relative_to_object=None): """ Gets the object position. """ h = self.get_object_handle(object_name) relative_handle = (-1 if relative_to_object is None else self.get_object_handle(relative_to_object)) return self.call_remote_api('simxGetObjectPosition', h, relative_handle, streaming=True)
[ "def", "get_object_position", "(", "self", ",", "object_name", ",", "relative_to_object", "=", "None", ")", ":", "h", "=", "self", ".", "get_object_handle", "(", "object_name", ")", "relative_handle", "=", "(", "-", "1", "if", "relative_to_object", "is", "None", "else", "self", ".", "get_object_handle", "(", "relative_to_object", ")", ")", "return", "self", ".", "call_remote_api", "(", "'simxGetObjectPosition'", ",", "h", ",", "relative_handle", ",", "streaming", "=", "True", ")" ]
Gets the object position.
[ "Gets", "the", "object", "position", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L169-L177
724
poppy-project/pypot
pypot/vrep/io.py
VrepIO.set_object_position
def set_object_position(self, object_name, position=[0, 0, 0]): """ Sets the object position. """ h = self.get_object_handle(object_name) return self.call_remote_api('simxSetObjectPosition', h, -1, position, sending=True)
python
def set_object_position(self, object_name, position=[0, 0, 0]): """ Sets the object position. """ h = self.get_object_handle(object_name) return self.call_remote_api('simxSetObjectPosition', h, -1, position, sending=True)
[ "def", "set_object_position", "(", "self", ",", "object_name", ",", "position", "=", "[", "0", ",", "0", ",", "0", "]", ")", ":", "h", "=", "self", ".", "get_object_handle", "(", "object_name", ")", "return", "self", ".", "call_remote_api", "(", "'simxSetObjectPosition'", ",", "h", ",", "-", "1", ",", "position", ",", "sending", "=", "True", ")" ]
Sets the object position.
[ "Sets", "the", "object", "position", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L179-L185
725
poppy-project/pypot
pypot/vrep/io.py
VrepIO.get_object_handle
def get_object_handle(self, obj): """ Gets the vrep object handle. """ if obj not in self._object_handles: self._object_handles[obj] = self._get_object_handle(obj=obj) return self._object_handles[obj]
python
def get_object_handle(self, obj): """ Gets the vrep object handle. """ if obj not in self._object_handles: self._object_handles[obj] = self._get_object_handle(obj=obj) return self._object_handles[obj]
[ "def", "get_object_handle", "(", "self", ",", "obj", ")", ":", "if", "obj", "not", "in", "self", ".", "_object_handles", ":", "self", ".", "_object_handles", "[", "obj", "]", "=", "self", ".", "_get_object_handle", "(", "obj", "=", "obj", ")", "return", "self", ".", "_object_handles", "[", "obj", "]" ]
Gets the vrep object handle.
[ "Gets", "the", "vrep", "object", "handle", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L200-L205
726
poppy-project/pypot
pypot/vrep/io.py
VrepIO.get_collision_state
def get_collision_state(self, collision_name): """ Gets the collision state. """ return self.call_remote_api('simxReadCollision', self.get_collision_handle(collision_name), streaming=True)
python
def get_collision_state(self, collision_name): """ Gets the collision state. """ return self.call_remote_api('simxReadCollision', self.get_collision_handle(collision_name), streaming=True)
[ "def", "get_collision_state", "(", "self", ",", "collision_name", ")", ":", "return", "self", ".", "call_remote_api", "(", "'simxReadCollision'", ",", "self", ".", "get_collision_handle", "(", "collision_name", ")", ",", "streaming", "=", "True", ")" ]
Gets the collision state.
[ "Gets", "the", "collision", "state", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L207-L211
727
poppy-project/pypot
pypot/vrep/io.py
VrepIO.get_collision_handle
def get_collision_handle(self, collision): """ Gets a vrep collisions handle. """ if collision not in self._object_handles: h = self._get_collision_handle(collision) self._object_handles[collision] = h return self._object_handles[collision]
python
def get_collision_handle(self, collision): """ Gets a vrep collisions handle. """ if collision not in self._object_handles: h = self._get_collision_handle(collision) self._object_handles[collision] = h return self._object_handles[collision]
[ "def", "get_collision_handle", "(", "self", ",", "collision", ")", ":", "if", "collision", "not", "in", "self", ".", "_object_handles", ":", "h", "=", "self", ".", "_get_collision_handle", "(", "collision", ")", "self", ".", "_object_handles", "[", "collision", "]", "=", "h", "return", "self", ".", "_object_handles", "[", "collision", "]" ]
Gets a vrep collisions handle.
[ "Gets", "a", "vrep", "collisions", "handle", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L216-L222
728
poppy-project/pypot
pypot/vrep/io.py
VrepIO.change_object_name
def change_object_name(self, old_name, new_name): """ Change object name """ h = self._get_object_handle(old_name) if old_name in self._object_handles: self._object_handles.pop(old_name) lua_code = "simSetObjectName({}, '{}')".format(h, new_name) self._inject_lua_code(lua_code)
python
def change_object_name(self, old_name, new_name): """ Change object name """ h = self._get_object_handle(old_name) if old_name in self._object_handles: self._object_handles.pop(old_name) lua_code = "simSetObjectName({}, '{}')".format(h, new_name) self._inject_lua_code(lua_code)
[ "def", "change_object_name", "(", "self", ",", "old_name", ",", "new_name", ")", ":", "h", "=", "self", ".", "_get_object_handle", "(", "old_name", ")", "if", "old_name", "in", "self", ".", "_object_handles", ":", "self", ".", "_object_handles", ".", "pop", "(", "old_name", ")", "lua_code", "=", "\"simSetObjectName({}, '{}')\"", ".", "format", "(", "h", ",", "new_name", ")", "self", ".", "_inject_lua_code", "(", "lua_code", ")" ]
Change object name
[ "Change", "object", "name" ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L255-L261
729
poppy-project/pypot
pypot/vrep/io.py
VrepIO._create_pure_shape
def _create_pure_shape(self, primitive_type, options, sizes, mass, precision): """ Create Pure Shape """ lua_code = "simCreatePureShape({}, {}, {{{}, {}, {}}}, {}, {{{}, {}}})".format( primitive_type, options, sizes[0], sizes[1], sizes[2], mass, precision[0], precision[1]) self._inject_lua_code(lua_code)
python
def _create_pure_shape(self, primitive_type, options, sizes, mass, precision): """ Create Pure Shape """ lua_code = "simCreatePureShape({}, {}, {{{}, {}, {}}}, {}, {{{}, {}}})".format( primitive_type, options, sizes[0], sizes[1], sizes[2], mass, precision[0], precision[1]) self._inject_lua_code(lua_code)
[ "def", "_create_pure_shape", "(", "self", ",", "primitive_type", ",", "options", ",", "sizes", ",", "mass", ",", "precision", ")", ":", "lua_code", "=", "\"simCreatePureShape({}, {}, {{{}, {}, {}}}, {}, {{{}, {}}})\"", ".", "format", "(", "primitive_type", ",", "options", ",", "sizes", "[", "0", "]", ",", "sizes", "[", "1", "]", ",", "sizes", "[", "2", "]", ",", "mass", ",", "precision", "[", "0", "]", ",", "precision", "[", "1", "]", ")", "self", ".", "_inject_lua_code", "(", "lua_code", ")" ]
Create Pure Shape
[ "Create", "Pure", "Shape" ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L263-L267
730
poppy-project/pypot
pypot/vrep/io.py
VrepIO._inject_lua_code
def _inject_lua_code(self, lua_code): """ Sends raw lua code and evaluate it wihtout any checking! """ msg = (ctypes.c_ubyte * len(lua_code)).from_buffer_copy(lua_code.encode()) self.call_remote_api('simxWriteStringStream', 'my_lua_code', msg)
python
def _inject_lua_code(self, lua_code): """ Sends raw lua code and evaluate it wihtout any checking! """ msg = (ctypes.c_ubyte * len(lua_code)).from_buffer_copy(lua_code.encode()) self.call_remote_api('simxWriteStringStream', 'my_lua_code', msg)
[ "def", "_inject_lua_code", "(", "self", ",", "lua_code", ")", ":", "msg", "=", "(", "ctypes", ".", "c_ubyte", "*", "len", "(", "lua_code", ")", ")", ".", "from_buffer_copy", "(", "lua_code", ".", "encode", "(", ")", ")", "self", ".", "call_remote_api", "(", "'simxWriteStringStream'", ",", "'my_lua_code'", ",", "msg", ")" ]
Sends raw lua code and evaluate it wihtout any checking!
[ "Sends", "raw", "lua", "code", "and", "evaluate", "it", "wihtout", "any", "checking!" ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L269-L272
731
poppy-project/pypot
pypot/vrep/io.py
VrepIO.call_remote_api
def call_remote_api(self, func_name, *args, **kwargs): """ Calls any remote API func in a thread_safe way. :param str func_name: name of the remote API func to call :param args: args to pass to the remote API call :param kwargs: args to pass to the remote API call .. note:: You can add an extra keyword to specify if you want to use the streaming or sending mode. The oneshot_wait mode is used by default (see `here <http://www.coppeliarobotics.com/helpFiles/en/remoteApiConstants.htm#operationModes>`_ for details about possible modes). .. warning:: You should not pass the clientId and the operationMode as arguments. They will be automatically added. As an example you can retrieve all joints name using the following call:: vrep_io.remote_api_call('simxGetObjectGroupData', vrep_io.remote_api.sim_object_joint_type, 0, streaming=True) """ f = getattr(remote_api, func_name) mode = self._extract_mode(kwargs) kwargs['operationMode'] = vrep_mode[mode] # hard_retry = True if '_force' in kwargs: del kwargs['_force'] _force = True else: _force = False for _ in range(VrepIO.MAX_ITER): with self._lock: ret = f(self.client_id, *args, **kwargs) if _force: return if mode == 'sending' or isinstance(ret, int): err, res = ret, None else: err, res = ret[0], ret[1:] res = res[0] if len(res) == 1 else res err = [bool((err >> i) & 1) for i in range(len(vrep_error))] if remote_api.simx_return_novalue_flag not in err: break time.sleep(VrepIO.TIMEOUT) # if any(err) and hard_retry: # print "HARD RETRY" # self.stop_simulation() #nope # # notconnected = True # while notconnected: # self.close() # close_all_connections() # time.sleep(0.5) # try: # self.open_io() # notconnected = False # except: # print 'CONNECTION ERROR' # pass # # self.start_simulation() # # with self._lock: # ret = f(self.client_id, *args, **kwargs) # # if mode == 'sending' or isinstance(ret, int): # err, res = ret, None # else: # err, res = ret[0], ret[1:] # res = res[0] if len(res) == 1 else res # # err = [bool((err >> i) & 1) for i in range(len(vrep_error))] # # return res if any(err): msg = ' '.join([vrep_error[2 ** i] for i, e in enumerate(err) if e]) raise VrepIOErrors(msg) return res
python
def call_remote_api(self, func_name, *args, **kwargs): """ Calls any remote API func in a thread_safe way. :param str func_name: name of the remote API func to call :param args: args to pass to the remote API call :param kwargs: args to pass to the remote API call .. note:: You can add an extra keyword to specify if you want to use the streaming or sending mode. The oneshot_wait mode is used by default (see `here <http://www.coppeliarobotics.com/helpFiles/en/remoteApiConstants.htm#operationModes>`_ for details about possible modes). .. warning:: You should not pass the clientId and the operationMode as arguments. They will be automatically added. As an example you can retrieve all joints name using the following call:: vrep_io.remote_api_call('simxGetObjectGroupData', vrep_io.remote_api.sim_object_joint_type, 0, streaming=True) """ f = getattr(remote_api, func_name) mode = self._extract_mode(kwargs) kwargs['operationMode'] = vrep_mode[mode] # hard_retry = True if '_force' in kwargs: del kwargs['_force'] _force = True else: _force = False for _ in range(VrepIO.MAX_ITER): with self._lock: ret = f(self.client_id, *args, **kwargs) if _force: return if mode == 'sending' or isinstance(ret, int): err, res = ret, None else: err, res = ret[0], ret[1:] res = res[0] if len(res) == 1 else res err = [bool((err >> i) & 1) for i in range(len(vrep_error))] if remote_api.simx_return_novalue_flag not in err: break time.sleep(VrepIO.TIMEOUT) # if any(err) and hard_retry: # print "HARD RETRY" # self.stop_simulation() #nope # # notconnected = True # while notconnected: # self.close() # close_all_connections() # time.sleep(0.5) # try: # self.open_io() # notconnected = False # except: # print 'CONNECTION ERROR' # pass # # self.start_simulation() # # with self._lock: # ret = f(self.client_id, *args, **kwargs) # # if mode == 'sending' or isinstance(ret, int): # err, res = ret, None # else: # err, res = ret[0], ret[1:] # res = res[0] if len(res) == 1 else res # # err = [bool((err >> i) & 1) for i in range(len(vrep_error))] # # return res if any(err): msg = ' '.join([vrep_error[2 ** i] for i, e in enumerate(err) if e]) raise VrepIOErrors(msg) return res
[ "def", "call_remote_api", "(", "self", ",", "func_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "f", "=", "getattr", "(", "remote_api", ",", "func_name", ")", "mode", "=", "self", ".", "_extract_mode", "(", "kwargs", ")", "kwargs", "[", "'operationMode'", "]", "=", "vrep_mode", "[", "mode", "]", "# hard_retry = True", "if", "'_force'", "in", "kwargs", ":", "del", "kwargs", "[", "'_force'", "]", "_force", "=", "True", "else", ":", "_force", "=", "False", "for", "_", "in", "range", "(", "VrepIO", ".", "MAX_ITER", ")", ":", "with", "self", ".", "_lock", ":", "ret", "=", "f", "(", "self", ".", "client_id", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "_force", ":", "return", "if", "mode", "==", "'sending'", "or", "isinstance", "(", "ret", ",", "int", ")", ":", "err", ",", "res", "=", "ret", ",", "None", "else", ":", "err", ",", "res", "=", "ret", "[", "0", "]", ",", "ret", "[", "1", ":", "]", "res", "=", "res", "[", "0", "]", "if", "len", "(", "res", ")", "==", "1", "else", "res", "err", "=", "[", "bool", "(", "(", "err", ">>", "i", ")", "&", "1", ")", "for", "i", "in", "range", "(", "len", "(", "vrep_error", ")", ")", "]", "if", "remote_api", ".", "simx_return_novalue_flag", "not", "in", "err", ":", "break", "time", ".", "sleep", "(", "VrepIO", ".", "TIMEOUT", ")", "# if any(err) and hard_retry:", "# print \"HARD RETRY\"", "# self.stop_simulation() #nope", "#", "# notconnected = True", "# while notconnected:", "# self.close()", "# close_all_connections()", "# time.sleep(0.5)", "# try:", "# self.open_io()", "# notconnected = False", "# except:", "# print 'CONNECTION ERROR'", "# pass", "#", "# self.start_simulation()", "#", "# with self._lock:", "# ret = f(self.client_id, *args, **kwargs)", "#", "# if mode == 'sending' or isinstance(ret, int):", "# err, res = ret, None", "# else:", "# err, res = ret[0], ret[1:]", "# res = res[0] if len(res) == 1 else res", "#", "# err = [bool((err >> i) & 1) for i in range(len(vrep_error))]", "#", "# return res", "if", "any", "(", "err", ")", ":", "msg", "=", "' '", ".", "join", "(", "[", "vrep_error", "[", "2", "**", "i", "]", "for", "i", ",", "e", "in", "enumerate", "(", "err", ")", "if", "e", "]", ")", "raise", "VrepIOErrors", "(", "msg", ")", "return", "res" ]
Calls any remote API func in a thread_safe way. :param str func_name: name of the remote API func to call :param args: args to pass to the remote API call :param kwargs: args to pass to the remote API call .. note:: You can add an extra keyword to specify if you want to use the streaming or sending mode. The oneshot_wait mode is used by default (see `here <http://www.coppeliarobotics.com/helpFiles/en/remoteApiConstants.htm#operationModes>`_ for details about possible modes). .. warning:: You should not pass the clientId and the operationMode as arguments. They will be automatically added. As an example you can retrieve all joints name using the following call:: vrep_io.remote_api_call('simxGetObjectGroupData', vrep_io.remote_api.sim_object_joint_type, 0, streaming=True)
[ "Calls", "any", "remote", "API", "func", "in", "a", "thread_safe", "way", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L274-L361
732
poppy-project/pypot
pypot/server/httpserver.py
HTTPRobotServer.run
def run(self, **kwargs): """ Start the tornado server, run forever""" try: loop = IOLoop() app = self.make_app() app.listen(self.port) loop.start() except socket.error as serr: # Re raise the socket error if not "[Errno 98] Address already in use" if serr.errno != errno.EADDRINUSE: raise serr else: logger.warning('The webserver port {} is already used. May be the HttpRobotServer is already running or another software is using this port.'.format(self.port))
python
def run(self, **kwargs): """ Start the tornado server, run forever""" try: loop = IOLoop() app = self.make_app() app.listen(self.port) loop.start() except socket.error as serr: # Re raise the socket error if not "[Errno 98] Address already in use" if serr.errno != errno.EADDRINUSE: raise serr else: logger.warning('The webserver port {} is already used. May be the HttpRobotServer is already running or another software is using this port.'.format(self.port))
[ "def", "run", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "loop", "=", "IOLoop", "(", ")", "app", "=", "self", ".", "make_app", "(", ")", "app", ".", "listen", "(", "self", ".", "port", ")", "loop", ".", "start", "(", ")", "except", "socket", ".", "error", "as", "serr", ":", "# Re raise the socket error if not \"[Errno 98] Address already in use\"", "if", "serr", ".", "errno", "!=", "errno", ".", "EADDRINUSE", ":", "raise", "serr", "else", ":", "logger", ".", "warning", "(", "'The webserver port {} is already used. May be the HttpRobotServer is already running or another software is using this port.'", ".", "format", "(", "self", ".", "port", ")", ")" ]
Start the tornado server, run forever
[ "Start", "the", "tornado", "server", "run", "forever" ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/server/httpserver.py#L253-L267
733
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.close
def close(self, _force_lock=False): """ Closes the serial communication if opened. """ if not self.closed: with self.__force_lock(_force_lock) or self._serial_lock: self._serial.close() self.__used_ports.remove(self.port) logger.info("Closing port '%s'", self.port, extra={'port': self.port, 'baudrate': self.baudrate, 'timeout': self.timeout})
python
def close(self, _force_lock=False): """ Closes the serial communication if opened. """ if not self.closed: with self.__force_lock(_force_lock) or self._serial_lock: self._serial.close() self.__used_ports.remove(self.port) logger.info("Closing port '%s'", self.port, extra={'port': self.port, 'baudrate': self.baudrate, 'timeout': self.timeout})
[ "def", "close", "(", "self", ",", "_force_lock", "=", "False", ")", ":", "if", "not", "self", ".", "closed", ":", "with", "self", ".", "__force_lock", "(", "_force_lock", ")", "or", "self", ".", "_serial_lock", ":", "self", ".", "_serial", ".", "close", "(", ")", "self", ".", "__used_ports", ".", "remove", "(", "self", ".", "port", ")", "logger", ".", "info", "(", "\"Closing port '%s'\"", ",", "self", ".", "port", ",", "extra", "=", "{", "'port'", ":", "self", ".", "port", ",", "'baudrate'", ":", "self", ".", "baudrate", ",", "'timeout'", ":", "self", ".", "timeout", "}", ")" ]
Closes the serial communication if opened.
[ "Closes", "the", "serial", "communication", "if", "opened", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L145-L155
734
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.ping
def ping(self, id): """ Pings the motor with the specified id. .. note:: The motor id should always be included in [0, 253]. 254 is used for broadcast. """ pp = self._protocol.DxlPingPacket(id) try: self._send_packet(pp, error_handler=None) return True except DxlTimeoutError: return False
python
def ping(self, id): """ Pings the motor with the specified id. .. note:: The motor id should always be included in [0, 253]. 254 is used for broadcast. """ pp = self._protocol.DxlPingPacket(id) try: self._send_packet(pp, error_handler=None) return True except DxlTimeoutError: return False
[ "def", "ping", "(", "self", ",", "id", ")", ":", "pp", "=", "self", ".", "_protocol", ".", "DxlPingPacket", "(", "id", ")", "try", ":", "self", ".", "_send_packet", "(", "pp", ",", "error_handler", "=", "None", ")", "return", "True", "except", "DxlTimeoutError", ":", "return", "False" ]
Pings the motor with the specified id. .. note:: The motor id should always be included in [0, 253]. 254 is used for broadcast.
[ "Pings", "the", "motor", "with", "the", "specified", "id", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L205-L217
735
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.scan
def scan(self, ids=range(254)): """ Pings all ids within the specified list, by default it finds all the motors connected to the bus. """ return [id for id in ids if self.ping(id)]
python
def scan(self, ids=range(254)): """ Pings all ids within the specified list, by default it finds all the motors connected to the bus. """ return [id for id in ids if self.ping(id)]
[ "def", "scan", "(", "self", ",", "ids", "=", "range", "(", "254", ")", ")", ":", "return", "[", "id", "for", "id", "in", "ids", "if", "self", ".", "ping", "(", "id", ")", "]" ]
Pings all ids within the specified list, by default it finds all the motors connected to the bus.
[ "Pings", "all", "ids", "within", "the", "specified", "list", "by", "default", "it", "finds", "all", "the", "motors", "connected", "to", "the", "bus", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L219-L221
736
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.get_model
def get_model(self, ids): """ Gets the model for the specified motors. """ to_get_ids = [i for i in ids if i not in self._known_models] models = [dxl_to_model(m) for m in self._get_model(to_get_ids, convert=False)] self._known_models.update(zip(to_get_ids, models)) return tuple(self._known_models[id] for id in ids)
python
def get_model(self, ids): """ Gets the model for the specified motors. """ to_get_ids = [i for i in ids if i not in self._known_models] models = [dxl_to_model(m) for m in self._get_model(to_get_ids, convert=False)] self._known_models.update(zip(to_get_ids, models)) return tuple(self._known_models[id] for id in ids)
[ "def", "get_model", "(", "self", ",", "ids", ")", ":", "to_get_ids", "=", "[", "i", "for", "i", "in", "ids", "if", "i", "not", "in", "self", ".", "_known_models", "]", "models", "=", "[", "dxl_to_model", "(", "m", ")", "for", "m", "in", "self", ".", "_get_model", "(", "to_get_ids", ",", "convert", "=", "False", ")", "]", "self", ".", "_known_models", ".", "update", "(", "zip", "(", "to_get_ids", ",", "models", ")", ")", "return", "tuple", "(", "self", ".", "_known_models", "[", "id", "]", "for", "id", "in", "ids", ")" ]
Gets the model for the specified motors.
[ "Gets", "the", "model", "for", "the", "specified", "motors", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L225-L231
737
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.change_baudrate
def change_baudrate(self, baudrate_for_ids): """ Changes the baudrate of the specified motors. """ self._change_baudrate(baudrate_for_ids) for motor_id in baudrate_for_ids: if motor_id in self._known_models: del self._known_models[motor_id] if motor_id in self._known_mode: del self._known_mode[motor_id]
python
def change_baudrate(self, baudrate_for_ids): """ Changes the baudrate of the specified motors. """ self._change_baudrate(baudrate_for_ids) for motor_id in baudrate_for_ids: if motor_id in self._known_models: del self._known_models[motor_id] if motor_id in self._known_mode: del self._known_mode[motor_id]
[ "def", "change_baudrate", "(", "self", ",", "baudrate_for_ids", ")", ":", "self", ".", "_change_baudrate", "(", "baudrate_for_ids", ")", "for", "motor_id", "in", "baudrate_for_ids", ":", "if", "motor_id", "in", "self", ".", "_known_models", ":", "del", "self", ".", "_known_models", "[", "motor_id", "]", "if", "motor_id", "in", "self", ".", "_known_mode", ":", "del", "self", ".", "_known_mode", "[", "motor_id", "]" ]
Changes the baudrate of the specified motors.
[ "Changes", "the", "baudrate", "of", "the", "specified", "motors", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L252-L260
738
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.get_status_return_level
def get_status_return_level(self, ids, **kwargs): """ Gets the status level for the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else self._convert srl = [] for id in ids: try: srl.extend(self._get_status_return_level((id, ), error_handler=None, convert=convert)) except DxlTimeoutError as e: if self.ping(id): srl.append('never' if convert else 0) else: if self._error_handler: self._error_handler.handle_timeout(e) return () else: raise e return tuple(srl)
python
def get_status_return_level(self, ids, **kwargs): """ Gets the status level for the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else self._convert srl = [] for id in ids: try: srl.extend(self._get_status_return_level((id, ), error_handler=None, convert=convert)) except DxlTimeoutError as e: if self.ping(id): srl.append('never' if convert else 0) else: if self._error_handler: self._error_handler.handle_timeout(e) return () else: raise e return tuple(srl)
[ "def", "get_status_return_level", "(", "self", ",", "ids", ",", "*", "*", "kwargs", ")", ":", "convert", "=", "kwargs", "[", "'convert'", "]", "if", "'convert'", "in", "kwargs", "else", "self", ".", "_convert", "srl", "=", "[", "]", "for", "id", "in", "ids", ":", "try", ":", "srl", ".", "extend", "(", "self", ".", "_get_status_return_level", "(", "(", "id", ",", ")", ",", "error_handler", "=", "None", ",", "convert", "=", "convert", ")", ")", "except", "DxlTimeoutError", "as", "e", ":", "if", "self", ".", "ping", "(", "id", ")", ":", "srl", ".", "append", "(", "'never'", "if", "convert", "else", "0", ")", "else", ":", "if", "self", ".", "_error_handler", ":", "self", ".", "_error_handler", ".", "handle_timeout", "(", "e", ")", "return", "(", ")", "else", ":", "raise", "e", "return", "tuple", "(", "srl", ")" ]
Gets the status level for the specified motors.
[ "Gets", "the", "status", "level", "for", "the", "specified", "motors", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L262-L280
739
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.set_status_return_level
def set_status_return_level(self, srl_for_id, **kwargs): """ Sets status return level to the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else self._convert if convert: srl_for_id = dict(zip(srl_for_id.keys(), [('never', 'read', 'always').index(s) for s in srl_for_id.values()])) self._set_status_return_level(srl_for_id, convert=False)
python
def set_status_return_level(self, srl_for_id, **kwargs): """ Sets status return level to the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else self._convert if convert: srl_for_id = dict(zip(srl_for_id.keys(), [('never', 'read', 'always').index(s) for s in srl_for_id.values()])) self._set_status_return_level(srl_for_id, convert=False)
[ "def", "set_status_return_level", "(", "self", ",", "srl_for_id", ",", "*", "*", "kwargs", ")", ":", "convert", "=", "kwargs", "[", "'convert'", "]", "if", "'convert'", "in", "kwargs", "else", "self", ".", "_convert", "if", "convert", ":", "srl_for_id", "=", "dict", "(", "zip", "(", "srl_for_id", ".", "keys", "(", ")", ",", "[", "(", "'never'", ",", "'read'", ",", "'always'", ")", ".", "index", "(", "s", ")", "for", "s", "in", "srl_for_id", ".", "values", "(", ")", "]", ")", ")", "self", ".", "_set_status_return_level", "(", "srl_for_id", ",", "convert", "=", "False", ")" ]
Sets status return level to the specified motors.
[ "Sets", "status", "return", "level", "to", "the", "specified", "motors", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L282-L288
740
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.switch_led_on
def switch_led_on(self, ids): """ Switches on the LED of the motors with the specified ids. """ self._set_LED(dict(zip(ids, itertools.repeat(True))))
python
def switch_led_on(self, ids): """ Switches on the LED of the motors with the specified ids. """ self._set_LED(dict(zip(ids, itertools.repeat(True))))
[ "def", "switch_led_on", "(", "self", ",", "ids", ")", ":", "self", ".", "_set_LED", "(", "dict", "(", "zip", "(", "ids", ",", "itertools", ".", "repeat", "(", "True", ")", ")", ")", ")" ]
Switches on the LED of the motors with the specified ids.
[ "Switches", "on", "the", "LED", "of", "the", "motors", "with", "the", "specified", "ids", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L290-L292
741
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.switch_led_off
def switch_led_off(self, ids): """ Switches off the LED of the motors with the specified ids. """ self._set_LED(dict(zip(ids, itertools.repeat(False))))
python
def switch_led_off(self, ids): """ Switches off the LED of the motors with the specified ids. """ self._set_LED(dict(zip(ids, itertools.repeat(False))))
[ "def", "switch_led_off", "(", "self", ",", "ids", ")", ":", "self", ".", "_set_LED", "(", "dict", "(", "zip", "(", "ids", ",", "itertools", ".", "repeat", "(", "False", ")", ")", ")", ")" ]
Switches off the LED of the motors with the specified ids.
[ "Switches", "off", "the", "LED", "of", "the", "motors", "with", "the", "specified", "ids", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L294-L296
742
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
743
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
744
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
745
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
746
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
747
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
748
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
749
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
750
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
751
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
752
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
753
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
754
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
755
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
756
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
757
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
758
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
759
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
760
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
761
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
762
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
763
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
764
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
765
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
766
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
767
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
768
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
769
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
770
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
771
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
772
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
773
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
774
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
775
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
776
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
777
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
778
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
779
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
780
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
781
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
782
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
783
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
784
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
785
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
786
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
787
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
788
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
789
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
790
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
791
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
792
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
793
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
794
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
795
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
796
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
797
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
798
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
799
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