repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
fronzbot/blinkpy | blinkpy/sync_module.py | BlinkSyncModule.arm | def arm(self, value):
"""Arm or disarm system."""
if value:
return api.request_system_arm(self.blink, self.network_id)
return api.request_system_disarm(self.blink, self.network_id) | python | def arm(self, value):
"""Arm or disarm system."""
if value:
return api.request_system_arm(self.blink, self.network_id)
return api.request_system_disarm(self.blink, self.network_id) | [
"def",
"arm",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
":",
"return",
"api",
".",
"request_system_arm",
"(",
"self",
".",
"blink",
",",
"self",
".",
"network_id",
")",
"return",
"api",
".",
"request_system_disarm",
"(",
"self",
".",
"blink",
",",
"self",
".",
"network_id",
")"
] | Arm or disarm system. | [
"Arm",
"or",
"disarm",
"system",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/sync_module.py#L73-L78 | train | 238,100 |
fronzbot/blinkpy | blinkpy/sync_module.py | BlinkSyncModule.start | def start(self):
"""Initialize the system."""
response = api.request_syncmodule(self.blink,
self.network_id,
force=True)
try:
self.summary = response['syncmodule']
self.network_id = self.summary['network_id']
except (TypeError, KeyError):
_LOGGER.error(("Could not retrieve sync module information "
"with response: %s"), response, exc_info=True)
return False
try:
self.sync_id = self.summary['id']
self.serial = self.summary['serial']
self.status = self.summary['status']
except KeyError:
_LOGGER.error("Could not extract some sync module info: %s",
response,
exc_info=True)
self.network_info = api.request_network_status(self.blink,
self.network_id)
self.check_new_videos()
try:
for camera_config in self.camera_list:
if 'name' not in camera_config:
break
name = camera_config['name']
self.cameras[name] = BlinkCamera(self)
self.motion[name] = False
camera_info = self.get_camera_info(camera_config['id'])
self.cameras[name].update(camera_info,
force_cache=True,
force=True)
except KeyError:
_LOGGER.error("Could not create cameras instances for %s",
self.name,
exc_info=True)
return False
return True | python | def start(self):
"""Initialize the system."""
response = api.request_syncmodule(self.blink,
self.network_id,
force=True)
try:
self.summary = response['syncmodule']
self.network_id = self.summary['network_id']
except (TypeError, KeyError):
_LOGGER.error(("Could not retrieve sync module information "
"with response: %s"), response, exc_info=True)
return False
try:
self.sync_id = self.summary['id']
self.serial = self.summary['serial']
self.status = self.summary['status']
except KeyError:
_LOGGER.error("Could not extract some sync module info: %s",
response,
exc_info=True)
self.network_info = api.request_network_status(self.blink,
self.network_id)
self.check_new_videos()
try:
for camera_config in self.camera_list:
if 'name' not in camera_config:
break
name = camera_config['name']
self.cameras[name] = BlinkCamera(self)
self.motion[name] = False
camera_info = self.get_camera_info(camera_config['id'])
self.cameras[name].update(camera_info,
force_cache=True,
force=True)
except KeyError:
_LOGGER.error("Could not create cameras instances for %s",
self.name,
exc_info=True)
return False
return True | [
"def",
"start",
"(",
"self",
")",
":",
"response",
"=",
"api",
".",
"request_syncmodule",
"(",
"self",
".",
"blink",
",",
"self",
".",
"network_id",
",",
"force",
"=",
"True",
")",
"try",
":",
"self",
".",
"summary",
"=",
"response",
"[",
"'syncmodule'",
"]",
"self",
".",
"network_id",
"=",
"self",
".",
"summary",
"[",
"'network_id'",
"]",
"except",
"(",
"TypeError",
",",
"KeyError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"(",
"\"Could not retrieve sync module information \"",
"\"with response: %s\"",
")",
",",
"response",
",",
"exc_info",
"=",
"True",
")",
"return",
"False",
"try",
":",
"self",
".",
"sync_id",
"=",
"self",
".",
"summary",
"[",
"'id'",
"]",
"self",
".",
"serial",
"=",
"self",
".",
"summary",
"[",
"'serial'",
"]",
"self",
".",
"status",
"=",
"self",
".",
"summary",
"[",
"'status'",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not extract some sync module info: %s\"",
",",
"response",
",",
"exc_info",
"=",
"True",
")",
"self",
".",
"network_info",
"=",
"api",
".",
"request_network_status",
"(",
"self",
".",
"blink",
",",
"self",
".",
"network_id",
")",
"self",
".",
"check_new_videos",
"(",
")",
"try",
":",
"for",
"camera_config",
"in",
"self",
".",
"camera_list",
":",
"if",
"'name'",
"not",
"in",
"camera_config",
":",
"break",
"name",
"=",
"camera_config",
"[",
"'name'",
"]",
"self",
".",
"cameras",
"[",
"name",
"]",
"=",
"BlinkCamera",
"(",
"self",
")",
"self",
".",
"motion",
"[",
"name",
"]",
"=",
"False",
"camera_info",
"=",
"self",
".",
"get_camera_info",
"(",
"camera_config",
"[",
"'id'",
"]",
")",
"self",
".",
"cameras",
"[",
"name",
"]",
".",
"update",
"(",
"camera_info",
",",
"force_cache",
"=",
"True",
",",
"force",
"=",
"True",
")",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not create cameras instances for %s\"",
",",
"self",
".",
"name",
",",
"exc_info",
"=",
"True",
")",
"return",
"False",
"return",
"True"
] | Initialize the system. | [
"Initialize",
"the",
"system",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/sync_module.py#L80-L123 | train | 238,101 |
fronzbot/blinkpy | blinkpy/sync_module.py | BlinkSyncModule.get_events | def get_events(self, **kwargs):
"""Retrieve events from server."""
force = kwargs.pop('force', False)
response = api.request_sync_events(self.blink,
self.network_id,
force=force)
try:
return response['event']
except (TypeError, KeyError):
_LOGGER.error("Could not extract events: %s",
response,
exc_info=True)
return False | python | def get_events(self, **kwargs):
"""Retrieve events from server."""
force = kwargs.pop('force', False)
response = api.request_sync_events(self.blink,
self.network_id,
force=force)
try:
return response['event']
except (TypeError, KeyError):
_LOGGER.error("Could not extract events: %s",
response,
exc_info=True)
return False | [
"def",
"get_events",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"force",
"=",
"kwargs",
".",
"pop",
"(",
"'force'",
",",
"False",
")",
"response",
"=",
"api",
".",
"request_sync_events",
"(",
"self",
".",
"blink",
",",
"self",
".",
"network_id",
",",
"force",
"=",
"force",
")",
"try",
":",
"return",
"response",
"[",
"'event'",
"]",
"except",
"(",
"TypeError",
",",
"KeyError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not extract events: %s\"",
",",
"response",
",",
"exc_info",
"=",
"True",
")",
"return",
"False"
] | Retrieve events from server. | [
"Retrieve",
"events",
"from",
"server",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/sync_module.py#L125-L137 | train | 238,102 |
fronzbot/blinkpy | blinkpy/sync_module.py | BlinkSyncModule.get_camera_info | def get_camera_info(self, camera_id):
"""Retrieve camera information."""
response = api.request_camera_info(self.blink,
self.network_id,
camera_id)
try:
return response['camera'][0]
except (TypeError, KeyError):
_LOGGER.error("Could not extract camera info: %s",
response,
exc_info=True)
return [] | python | def get_camera_info(self, camera_id):
"""Retrieve camera information."""
response = api.request_camera_info(self.blink,
self.network_id,
camera_id)
try:
return response['camera'][0]
except (TypeError, KeyError):
_LOGGER.error("Could not extract camera info: %s",
response,
exc_info=True)
return [] | [
"def",
"get_camera_info",
"(",
"self",
",",
"camera_id",
")",
":",
"response",
"=",
"api",
".",
"request_camera_info",
"(",
"self",
".",
"blink",
",",
"self",
".",
"network_id",
",",
"camera_id",
")",
"try",
":",
"return",
"response",
"[",
"'camera'",
"]",
"[",
"0",
"]",
"except",
"(",
"TypeError",
",",
"KeyError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not extract camera info: %s\"",
",",
"response",
",",
"exc_info",
"=",
"True",
")",
"return",
"[",
"]"
] | Retrieve camera information. | [
"Retrieve",
"camera",
"information",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/sync_module.py#L139-L150 | train | 238,103 |
fronzbot/blinkpy | blinkpy/sync_module.py | BlinkSyncModule.refresh | def refresh(self, force_cache=False):
"""Get all blink cameras and pulls their most recent status."""
self.network_info = api.request_network_status(self.blink,
self.network_id)
self.check_new_videos()
for camera_name in self.cameras.keys():
camera_id = self.cameras[camera_name].camera_id
camera_info = self.get_camera_info(camera_id)
self.cameras[camera_name].update(camera_info,
force_cache=force_cache) | python | def refresh(self, force_cache=False):
"""Get all blink cameras and pulls their most recent status."""
self.network_info = api.request_network_status(self.blink,
self.network_id)
self.check_new_videos()
for camera_name in self.cameras.keys():
camera_id = self.cameras[camera_name].camera_id
camera_info = self.get_camera_info(camera_id)
self.cameras[camera_name].update(camera_info,
force_cache=force_cache) | [
"def",
"refresh",
"(",
"self",
",",
"force_cache",
"=",
"False",
")",
":",
"self",
".",
"network_info",
"=",
"api",
".",
"request_network_status",
"(",
"self",
".",
"blink",
",",
"self",
".",
"network_id",
")",
"self",
".",
"check_new_videos",
"(",
")",
"for",
"camera_name",
"in",
"self",
".",
"cameras",
".",
"keys",
"(",
")",
":",
"camera_id",
"=",
"self",
".",
"cameras",
"[",
"camera_name",
"]",
".",
"camera_id",
"camera_info",
"=",
"self",
".",
"get_camera_info",
"(",
"camera_id",
")",
"self",
".",
"cameras",
"[",
"camera_name",
"]",
".",
"update",
"(",
"camera_info",
",",
"force_cache",
"=",
"force_cache",
")"
] | Get all blink cameras and pulls their most recent status. | [
"Get",
"all",
"blink",
"cameras",
"and",
"pulls",
"their",
"most",
"recent",
"status",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/sync_module.py#L152-L161 | train | 238,104 |
fronzbot/blinkpy | blinkpy/sync_module.py | BlinkSyncModule.check_new_videos | def check_new_videos(self):
"""Check if new videos since last refresh."""
resp = api.request_videos(self.blink,
time=self.blink.last_refresh,
page=0)
for camera in self.cameras.keys():
self.motion[camera] = False
try:
info = resp['videos']
except (KeyError, TypeError):
_LOGGER.warning("Could not check for motion. Response: %s", resp)
return False
for entry in info:
try:
name = entry['camera_name']
clip = entry['address']
timestamp = entry['created_at']
self.motion[name] = True
self.last_record[name] = {'clip': clip, 'time': timestamp}
except KeyError:
_LOGGER.debug("No new videos since last refresh.")
return True | python | def check_new_videos(self):
"""Check if new videos since last refresh."""
resp = api.request_videos(self.blink,
time=self.blink.last_refresh,
page=0)
for camera in self.cameras.keys():
self.motion[camera] = False
try:
info = resp['videos']
except (KeyError, TypeError):
_LOGGER.warning("Could not check for motion. Response: %s", resp)
return False
for entry in info:
try:
name = entry['camera_name']
clip = entry['address']
timestamp = entry['created_at']
self.motion[name] = True
self.last_record[name] = {'clip': clip, 'time': timestamp}
except KeyError:
_LOGGER.debug("No new videos since last refresh.")
return True | [
"def",
"check_new_videos",
"(",
"self",
")",
":",
"resp",
"=",
"api",
".",
"request_videos",
"(",
"self",
".",
"blink",
",",
"time",
"=",
"self",
".",
"blink",
".",
"last_refresh",
",",
"page",
"=",
"0",
")",
"for",
"camera",
"in",
"self",
".",
"cameras",
".",
"keys",
"(",
")",
":",
"self",
".",
"motion",
"[",
"camera",
"]",
"=",
"False",
"try",
":",
"info",
"=",
"resp",
"[",
"'videos'",
"]",
"except",
"(",
"KeyError",
",",
"TypeError",
")",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Could not check for motion. Response: %s\"",
",",
"resp",
")",
"return",
"False",
"for",
"entry",
"in",
"info",
":",
"try",
":",
"name",
"=",
"entry",
"[",
"'camera_name'",
"]",
"clip",
"=",
"entry",
"[",
"'address'",
"]",
"timestamp",
"=",
"entry",
"[",
"'created_at'",
"]",
"self",
".",
"motion",
"[",
"name",
"]",
"=",
"True",
"self",
".",
"last_record",
"[",
"name",
"]",
"=",
"{",
"'clip'",
":",
"clip",
",",
"'time'",
":",
"timestamp",
"}",
"except",
"KeyError",
":",
"_LOGGER",
".",
"debug",
"(",
"\"No new videos since last refresh.\"",
")",
"return",
"True"
] | Check if new videos since last refresh. | [
"Check",
"if",
"new",
"videos",
"since",
"last",
"refresh",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/sync_module.py#L163-L188 | train | 238,105 |
fronzbot/blinkpy | blinkpy/camera.py | BlinkCamera.attributes | def attributes(self):
"""Return dictionary of all camera attributes."""
attributes = {
'name': self.name,
'camera_id': self.camera_id,
'serial': self.serial,
'temperature': self.temperature,
'temperature_c': self.temperature_c,
'temperature_calibrated': self.temperature_calibrated,
'battery': self.battery,
'thumbnail': self.thumbnail,
'video': self.clip,
'motion_enabled': self.motion_enabled,
'motion_detected': self.motion_detected,
'wifi_strength': self.wifi_strength,
'network_id': self.sync.network_id,
'sync_module': self.sync.name,
'last_record': self.last_record
}
return attributes | python | def attributes(self):
"""Return dictionary of all camera attributes."""
attributes = {
'name': self.name,
'camera_id': self.camera_id,
'serial': self.serial,
'temperature': self.temperature,
'temperature_c': self.temperature_c,
'temperature_calibrated': self.temperature_calibrated,
'battery': self.battery,
'thumbnail': self.thumbnail,
'video': self.clip,
'motion_enabled': self.motion_enabled,
'motion_detected': self.motion_detected,
'wifi_strength': self.wifi_strength,
'network_id': self.sync.network_id,
'sync_module': self.sync.name,
'last_record': self.last_record
}
return attributes | [
"def",
"attributes",
"(",
"self",
")",
":",
"attributes",
"=",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'camera_id'",
":",
"self",
".",
"camera_id",
",",
"'serial'",
":",
"self",
".",
"serial",
",",
"'temperature'",
":",
"self",
".",
"temperature",
",",
"'temperature_c'",
":",
"self",
".",
"temperature_c",
",",
"'temperature_calibrated'",
":",
"self",
".",
"temperature_calibrated",
",",
"'battery'",
":",
"self",
".",
"battery",
",",
"'thumbnail'",
":",
"self",
".",
"thumbnail",
",",
"'video'",
":",
"self",
".",
"clip",
",",
"'motion_enabled'",
":",
"self",
".",
"motion_enabled",
",",
"'motion_detected'",
":",
"self",
".",
"motion_detected",
",",
"'wifi_strength'",
":",
"self",
".",
"wifi_strength",
",",
"'network_id'",
":",
"self",
".",
"sync",
".",
"network_id",
",",
"'sync_module'",
":",
"self",
".",
"sync",
".",
"name",
",",
"'last_record'",
":",
"self",
".",
"last_record",
"}",
"return",
"attributes"
] | Return dictionary of all camera attributes. | [
"Return",
"dictionary",
"of",
"all",
"camera",
"attributes",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/camera.py#L34-L53 | train | 238,106 |
fronzbot/blinkpy | blinkpy/camera.py | BlinkCamera.snap_picture | def snap_picture(self):
"""Take a picture with camera to create a new thumbnail."""
return api.request_new_image(self.sync.blink,
self.network_id,
self.camera_id) | python | def snap_picture(self):
"""Take a picture with camera to create a new thumbnail."""
return api.request_new_image(self.sync.blink,
self.network_id,
self.camera_id) | [
"def",
"snap_picture",
"(",
"self",
")",
":",
"return",
"api",
".",
"request_new_image",
"(",
"self",
".",
"sync",
".",
"blink",
",",
"self",
".",
"network_id",
",",
"self",
".",
"camera_id",
")"
] | Take a picture with camera to create a new thumbnail. | [
"Take",
"a",
"picture",
"with",
"camera",
"to",
"create",
"a",
"new",
"thumbnail",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/camera.py#L79-L83 | train | 238,107 |
fronzbot/blinkpy | blinkpy/camera.py | BlinkCamera.set_motion_detect | def set_motion_detect(self, enable):
"""Set motion detection."""
if enable:
return api.request_motion_detection_enable(self.sync.blink,
self.network_id,
self.camera_id)
return api.request_motion_detection_disable(self.sync.blink,
self.network_id,
self.camera_id) | python | def set_motion_detect(self, enable):
"""Set motion detection."""
if enable:
return api.request_motion_detection_enable(self.sync.blink,
self.network_id,
self.camera_id)
return api.request_motion_detection_disable(self.sync.blink,
self.network_id,
self.camera_id) | [
"def",
"set_motion_detect",
"(",
"self",
",",
"enable",
")",
":",
"if",
"enable",
":",
"return",
"api",
".",
"request_motion_detection_enable",
"(",
"self",
".",
"sync",
".",
"blink",
",",
"self",
".",
"network_id",
",",
"self",
".",
"camera_id",
")",
"return",
"api",
".",
"request_motion_detection_disable",
"(",
"self",
".",
"sync",
".",
"blink",
",",
"self",
".",
"network_id",
",",
"self",
".",
"camera_id",
")"
] | Set motion detection. | [
"Set",
"motion",
"detection",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/camera.py#L85-L93 | train | 238,108 |
fronzbot/blinkpy | blinkpy/camera.py | BlinkCamera.update | def update(self, config, force_cache=False, **kwargs):
"""Update camera info."""
# force = kwargs.pop('force', False)
self.name = config['name']
self.camera_id = str(config['id'])
self.network_id = str(config['network_id'])
self.serial = config['serial']
self.motion_enabled = config['enabled']
self.battery_voltage = config['battery_voltage']
self.battery_state = config['battery_state']
self.temperature = config['temperature']
self.wifi_strength = config['wifi_strength']
# Retrieve calibrated temperature from special endpoint
resp = api.request_camera_sensors(self.sync.blink,
self.network_id,
self.camera_id)
try:
self.temperature_calibrated = resp['temp']
except KeyError:
self.temperature_calibrated = self.temperature
_LOGGER.warning("Could not retrieve calibrated temperature.")
# Check if thumbnail exists in config, if not try to
# get it from the homescreen info in teh sync module
# otherwise set it to None and log an error
new_thumbnail = None
if config['thumbnail']:
thumb_addr = config['thumbnail']
else:
thumb_addr = self.get_thumb_from_homescreen()
if thumb_addr is not None:
new_thumbnail = "{}{}.jpg".format(self.sync.urls.base_url,
thumb_addr)
try:
self.motion_detected = self.sync.motion[self.name]
except KeyError:
self.motion_detected = False
clip_addr = None
if self.name in self.sync.last_record:
clip_addr = self.sync.last_record[self.name]['clip']
self.last_record = self.sync.last_record[self.name]['time']
self.clip = "{}{}".format(self.sync.urls.base_url,
clip_addr)
# If the thumbnail or clip have changed, update the cache
update_cached_image = False
if new_thumbnail != self.thumbnail or self._cached_image is None:
update_cached_image = True
self.thumbnail = new_thumbnail
update_cached_video = False
if self._cached_video is None or self.motion_detected:
update_cached_video = True
if new_thumbnail is not None and (update_cached_image or force_cache):
self._cached_image = api.http_get(self.sync.blink,
url=self.thumbnail,
stream=True,
json=False)
if clip_addr is not None and (update_cached_video or force_cache):
self._cached_video = api.http_get(self.sync.blink,
url=self.clip,
stream=True,
json=False) | python | def update(self, config, force_cache=False, **kwargs):
"""Update camera info."""
# force = kwargs.pop('force', False)
self.name = config['name']
self.camera_id = str(config['id'])
self.network_id = str(config['network_id'])
self.serial = config['serial']
self.motion_enabled = config['enabled']
self.battery_voltage = config['battery_voltage']
self.battery_state = config['battery_state']
self.temperature = config['temperature']
self.wifi_strength = config['wifi_strength']
# Retrieve calibrated temperature from special endpoint
resp = api.request_camera_sensors(self.sync.blink,
self.network_id,
self.camera_id)
try:
self.temperature_calibrated = resp['temp']
except KeyError:
self.temperature_calibrated = self.temperature
_LOGGER.warning("Could not retrieve calibrated temperature.")
# Check if thumbnail exists in config, if not try to
# get it from the homescreen info in teh sync module
# otherwise set it to None and log an error
new_thumbnail = None
if config['thumbnail']:
thumb_addr = config['thumbnail']
else:
thumb_addr = self.get_thumb_from_homescreen()
if thumb_addr is not None:
new_thumbnail = "{}{}.jpg".format(self.sync.urls.base_url,
thumb_addr)
try:
self.motion_detected = self.sync.motion[self.name]
except KeyError:
self.motion_detected = False
clip_addr = None
if self.name in self.sync.last_record:
clip_addr = self.sync.last_record[self.name]['clip']
self.last_record = self.sync.last_record[self.name]['time']
self.clip = "{}{}".format(self.sync.urls.base_url,
clip_addr)
# If the thumbnail or clip have changed, update the cache
update_cached_image = False
if new_thumbnail != self.thumbnail or self._cached_image is None:
update_cached_image = True
self.thumbnail = new_thumbnail
update_cached_video = False
if self._cached_video is None or self.motion_detected:
update_cached_video = True
if new_thumbnail is not None and (update_cached_image or force_cache):
self._cached_image = api.http_get(self.sync.blink,
url=self.thumbnail,
stream=True,
json=False)
if clip_addr is not None and (update_cached_video or force_cache):
self._cached_video = api.http_get(self.sync.blink,
url=self.clip,
stream=True,
json=False) | [
"def",
"update",
"(",
"self",
",",
"config",
",",
"force_cache",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# force = kwargs.pop('force', False)",
"self",
".",
"name",
"=",
"config",
"[",
"'name'",
"]",
"self",
".",
"camera_id",
"=",
"str",
"(",
"config",
"[",
"'id'",
"]",
")",
"self",
".",
"network_id",
"=",
"str",
"(",
"config",
"[",
"'network_id'",
"]",
")",
"self",
".",
"serial",
"=",
"config",
"[",
"'serial'",
"]",
"self",
".",
"motion_enabled",
"=",
"config",
"[",
"'enabled'",
"]",
"self",
".",
"battery_voltage",
"=",
"config",
"[",
"'battery_voltage'",
"]",
"self",
".",
"battery_state",
"=",
"config",
"[",
"'battery_state'",
"]",
"self",
".",
"temperature",
"=",
"config",
"[",
"'temperature'",
"]",
"self",
".",
"wifi_strength",
"=",
"config",
"[",
"'wifi_strength'",
"]",
"# Retrieve calibrated temperature from special endpoint",
"resp",
"=",
"api",
".",
"request_camera_sensors",
"(",
"self",
".",
"sync",
".",
"blink",
",",
"self",
".",
"network_id",
",",
"self",
".",
"camera_id",
")",
"try",
":",
"self",
".",
"temperature_calibrated",
"=",
"resp",
"[",
"'temp'",
"]",
"except",
"KeyError",
":",
"self",
".",
"temperature_calibrated",
"=",
"self",
".",
"temperature",
"_LOGGER",
".",
"warning",
"(",
"\"Could not retrieve calibrated temperature.\"",
")",
"# Check if thumbnail exists in config, if not try to",
"# get it from the homescreen info in teh sync module",
"# otherwise set it to None and log an error",
"new_thumbnail",
"=",
"None",
"if",
"config",
"[",
"'thumbnail'",
"]",
":",
"thumb_addr",
"=",
"config",
"[",
"'thumbnail'",
"]",
"else",
":",
"thumb_addr",
"=",
"self",
".",
"get_thumb_from_homescreen",
"(",
")",
"if",
"thumb_addr",
"is",
"not",
"None",
":",
"new_thumbnail",
"=",
"\"{}{}.jpg\"",
".",
"format",
"(",
"self",
".",
"sync",
".",
"urls",
".",
"base_url",
",",
"thumb_addr",
")",
"try",
":",
"self",
".",
"motion_detected",
"=",
"self",
".",
"sync",
".",
"motion",
"[",
"self",
".",
"name",
"]",
"except",
"KeyError",
":",
"self",
".",
"motion_detected",
"=",
"False",
"clip_addr",
"=",
"None",
"if",
"self",
".",
"name",
"in",
"self",
".",
"sync",
".",
"last_record",
":",
"clip_addr",
"=",
"self",
".",
"sync",
".",
"last_record",
"[",
"self",
".",
"name",
"]",
"[",
"'clip'",
"]",
"self",
".",
"last_record",
"=",
"self",
".",
"sync",
".",
"last_record",
"[",
"self",
".",
"name",
"]",
"[",
"'time'",
"]",
"self",
".",
"clip",
"=",
"\"{}{}\"",
".",
"format",
"(",
"self",
".",
"sync",
".",
"urls",
".",
"base_url",
",",
"clip_addr",
")",
"# If the thumbnail or clip have changed, update the cache",
"update_cached_image",
"=",
"False",
"if",
"new_thumbnail",
"!=",
"self",
".",
"thumbnail",
"or",
"self",
".",
"_cached_image",
"is",
"None",
":",
"update_cached_image",
"=",
"True",
"self",
".",
"thumbnail",
"=",
"new_thumbnail",
"update_cached_video",
"=",
"False",
"if",
"self",
".",
"_cached_video",
"is",
"None",
"or",
"self",
".",
"motion_detected",
":",
"update_cached_video",
"=",
"True",
"if",
"new_thumbnail",
"is",
"not",
"None",
"and",
"(",
"update_cached_image",
"or",
"force_cache",
")",
":",
"self",
".",
"_cached_image",
"=",
"api",
".",
"http_get",
"(",
"self",
".",
"sync",
".",
"blink",
",",
"url",
"=",
"self",
".",
"thumbnail",
",",
"stream",
"=",
"True",
",",
"json",
"=",
"False",
")",
"if",
"clip_addr",
"is",
"not",
"None",
"and",
"(",
"update_cached_video",
"or",
"force_cache",
")",
":",
"self",
".",
"_cached_video",
"=",
"api",
".",
"http_get",
"(",
"self",
".",
"sync",
".",
"blink",
",",
"url",
"=",
"self",
".",
"clip",
",",
"stream",
"=",
"True",
",",
"json",
"=",
"False",
")"
] | Update camera info. | [
"Update",
"camera",
"info",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/camera.py#L95-L162 | train | 238,109 |
fronzbot/blinkpy | blinkpy/camera.py | BlinkCamera.image_to_file | def image_to_file(self, path):
"""
Write image to file.
:param path: Path to write file
"""
_LOGGER.debug("Writing image from %s to %s", self.name, path)
response = self._cached_image
if response.status_code == 200:
with open(path, 'wb') as imgfile:
copyfileobj(response.raw, imgfile)
else:
_LOGGER.error("Cannot write image to file, response %s",
response.status_code,
exc_info=True) | python | def image_to_file(self, path):
"""
Write image to file.
:param path: Path to write file
"""
_LOGGER.debug("Writing image from %s to %s", self.name, path)
response = self._cached_image
if response.status_code == 200:
with open(path, 'wb') as imgfile:
copyfileobj(response.raw, imgfile)
else:
_LOGGER.error("Cannot write image to file, response %s",
response.status_code,
exc_info=True) | [
"def",
"image_to_file",
"(",
"self",
",",
"path",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Writing image from %s to %s\"",
",",
"self",
".",
"name",
",",
"path",
")",
"response",
"=",
"self",
".",
"_cached_image",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"imgfile",
":",
"copyfileobj",
"(",
"response",
".",
"raw",
",",
"imgfile",
")",
"else",
":",
"_LOGGER",
".",
"error",
"(",
"\"Cannot write image to file, response %s\"",
",",
"response",
".",
"status_code",
",",
"exc_info",
"=",
"True",
")"
] | Write image to file.
:param path: Path to write file | [
"Write",
"image",
"to",
"file",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/camera.py#L164-L178 | train | 238,110 |
fronzbot/blinkpy | blinkpy/camera.py | BlinkCamera.video_to_file | def video_to_file(self, path):
"""Write video to file.
:param path: Path to write file
"""
_LOGGER.debug("Writing video from %s to %s", self.name, path)
response = self._cached_video
if response is None:
_LOGGER.error("No saved video exist for %s.",
self.name,
exc_info=True)
return
with open(path, 'wb') as vidfile:
copyfileobj(response.raw, vidfile) | python | def video_to_file(self, path):
"""Write video to file.
:param path: Path to write file
"""
_LOGGER.debug("Writing video from %s to %s", self.name, path)
response = self._cached_video
if response is None:
_LOGGER.error("No saved video exist for %s.",
self.name,
exc_info=True)
return
with open(path, 'wb') as vidfile:
copyfileobj(response.raw, vidfile) | [
"def",
"video_to_file",
"(",
"self",
",",
"path",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Writing video from %s to %s\"",
",",
"self",
".",
"name",
",",
"path",
")",
"response",
"=",
"self",
".",
"_cached_video",
"if",
"response",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"No saved video exist for %s.\"",
",",
"self",
".",
"name",
",",
"exc_info",
"=",
"True",
")",
"return",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"vidfile",
":",
"copyfileobj",
"(",
"response",
".",
"raw",
",",
"vidfile",
")"
] | Write video to file.
:param path: Path to write file | [
"Write",
"video",
"to",
"file",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/camera.py#L180-L193 | train | 238,111 |
fronzbot/blinkpy | blinkpy/camera.py | BlinkCamera.get_thumb_from_homescreen | def get_thumb_from_homescreen(self):
"""Retrieve thumbnail from homescreen."""
for device in self.sync.homescreen['devices']:
try:
device_type = device['device_type']
device_name = device['name']
device_thumb = device['thumbnail']
if device_type == 'camera' and device_name == self.name:
return device_thumb
except KeyError:
pass
_LOGGER.error("Could not find thumbnail for camera %s",
self.name,
exc_info=True)
return None | python | def get_thumb_from_homescreen(self):
"""Retrieve thumbnail from homescreen."""
for device in self.sync.homescreen['devices']:
try:
device_type = device['device_type']
device_name = device['name']
device_thumb = device['thumbnail']
if device_type == 'camera' and device_name == self.name:
return device_thumb
except KeyError:
pass
_LOGGER.error("Could not find thumbnail for camera %s",
self.name,
exc_info=True)
return None | [
"def",
"get_thumb_from_homescreen",
"(",
"self",
")",
":",
"for",
"device",
"in",
"self",
".",
"sync",
".",
"homescreen",
"[",
"'devices'",
"]",
":",
"try",
":",
"device_type",
"=",
"device",
"[",
"'device_type'",
"]",
"device_name",
"=",
"device",
"[",
"'name'",
"]",
"device_thumb",
"=",
"device",
"[",
"'thumbnail'",
"]",
"if",
"device_type",
"==",
"'camera'",
"and",
"device_name",
"==",
"self",
".",
"name",
":",
"return",
"device_thumb",
"except",
"KeyError",
":",
"pass",
"_LOGGER",
".",
"error",
"(",
"\"Could not find thumbnail for camera %s\"",
",",
"self",
".",
"name",
",",
"exc_info",
"=",
"True",
")",
"return",
"None"
] | Retrieve thumbnail from homescreen. | [
"Retrieve",
"thumbnail",
"from",
"homescreen",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/camera.py#L195-L209 | train | 238,112 |
fronzbot/blinkpy | blinkpy/helpers/util.py | get_time | def get_time(time_to_convert=None):
"""Create blink-compatible timestamp."""
if time_to_convert is None:
time_to_convert = time.time()
return time.strftime(TIMESTAMP_FORMAT, time.localtime(time_to_convert)) | python | def get_time(time_to_convert=None):
"""Create blink-compatible timestamp."""
if time_to_convert is None:
time_to_convert = time.time()
return time.strftime(TIMESTAMP_FORMAT, time.localtime(time_to_convert)) | [
"def",
"get_time",
"(",
"time_to_convert",
"=",
"None",
")",
":",
"if",
"time_to_convert",
"is",
"None",
":",
"time_to_convert",
"=",
"time",
".",
"time",
"(",
")",
"return",
"time",
".",
"strftime",
"(",
"TIMESTAMP_FORMAT",
",",
"time",
".",
"localtime",
"(",
"time_to_convert",
")",
")"
] | Create blink-compatible timestamp. | [
"Create",
"blink",
"-",
"compatible",
"timestamp",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/helpers/util.py#L14-L18 | train | 238,113 |
fronzbot/blinkpy | blinkpy/helpers/util.py | merge_dicts | def merge_dicts(dict_a, dict_b):
"""Merge two dictionaries into one."""
duplicates = [val for val in dict_a if val in dict_b]
if duplicates:
_LOGGER.warning(("Duplicates found during merge: %s. "
"Renaming is recommended."), duplicates)
return {**dict_a, **dict_b} | python | def merge_dicts(dict_a, dict_b):
"""Merge two dictionaries into one."""
duplicates = [val for val in dict_a if val in dict_b]
if duplicates:
_LOGGER.warning(("Duplicates found during merge: %s. "
"Renaming is recommended."), duplicates)
return {**dict_a, **dict_b} | [
"def",
"merge_dicts",
"(",
"dict_a",
",",
"dict_b",
")",
":",
"duplicates",
"=",
"[",
"val",
"for",
"val",
"in",
"dict_a",
"if",
"val",
"in",
"dict_b",
"]",
"if",
"duplicates",
":",
"_LOGGER",
".",
"warning",
"(",
"(",
"\"Duplicates found during merge: %s. \"",
"\"Renaming is recommended.\"",
")",
",",
"duplicates",
")",
"return",
"{",
"*",
"*",
"dict_a",
",",
"*",
"*",
"dict_b",
"}"
] | Merge two dictionaries into one. | [
"Merge",
"two",
"dictionaries",
"into",
"one",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/helpers/util.py#L21-L27 | train | 238,114 |
fronzbot/blinkpy | blinkpy/helpers/util.py | attempt_reauthorization | def attempt_reauthorization(blink):
"""Attempt to refresh auth token and links."""
_LOGGER.info("Auth token expired, attempting reauthorization.")
headers = blink.get_auth_token(is_retry=True)
return headers | python | def attempt_reauthorization(blink):
"""Attempt to refresh auth token and links."""
_LOGGER.info("Auth token expired, attempting reauthorization.")
headers = blink.get_auth_token(is_retry=True)
return headers | [
"def",
"attempt_reauthorization",
"(",
"blink",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Auth token expired, attempting reauthorization.\"",
")",
"headers",
"=",
"blink",
".",
"get_auth_token",
"(",
"is_retry",
"=",
"True",
")",
"return",
"headers"
] | Attempt to refresh auth token and links. | [
"Attempt",
"to",
"refresh",
"auth",
"token",
"and",
"links",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/helpers/util.py#L36-L40 | train | 238,115 |
fronzbot/blinkpy | blinkpy/helpers/util.py | http_req | def http_req(blink, url='http://example.com', data=None, headers=None,
reqtype='get', stream=False, json_resp=True, is_retry=False):
"""
Perform server requests and check if reauthorization neccessary.
:param blink: Blink instance
:param url: URL to perform request
:param data: Data to send (default: None)
:param headers: Headers to send (default: None)
:param reqtype: Can be 'get' or 'post' (default: 'get')
:param stream: Stream response? True/FALSE
:param json_resp: Return JSON response? TRUE/False
:param is_retry: Is this a retry attempt? True/FALSE
"""
if reqtype == 'post':
req = Request('POST', url, headers=headers, data=data)
elif reqtype == 'get':
req = Request('GET', url, headers=headers)
else:
_LOGGER.error("Invalid request type: %s", reqtype)
raise BlinkException(ERROR.REQUEST)
prepped = req.prepare()
try:
response = blink.session.send(prepped, stream=stream, timeout=10)
if json_resp and 'code' in response.json():
if is_retry:
_LOGGER.error("Cannot obtain new token for server auth.")
return None
else:
headers = attempt_reauthorization(blink)
if not headers:
raise exceptions.ConnectionError
return http_req(blink, url=url, data=data, headers=headers,
reqtype=reqtype, stream=stream,
json_resp=json_resp, is_retry=True)
except (exceptions.ConnectionError, exceptions.Timeout):
_LOGGER.info("Cannot connect to server with url %s.", url)
if not is_retry:
headers = attempt_reauthorization(blink)
return http_req(blink, url=url, data=data, headers=headers,
reqtype=reqtype, stream=stream,
json_resp=json_resp, is_retry=True)
_LOGGER.error("Endpoint %s failed. Possible issue with Blink servers.",
url)
return None
if json_resp:
return response.json()
return response | python | def http_req(blink, url='http://example.com', data=None, headers=None,
reqtype='get', stream=False, json_resp=True, is_retry=False):
"""
Perform server requests and check if reauthorization neccessary.
:param blink: Blink instance
:param url: URL to perform request
:param data: Data to send (default: None)
:param headers: Headers to send (default: None)
:param reqtype: Can be 'get' or 'post' (default: 'get')
:param stream: Stream response? True/FALSE
:param json_resp: Return JSON response? TRUE/False
:param is_retry: Is this a retry attempt? True/FALSE
"""
if reqtype == 'post':
req = Request('POST', url, headers=headers, data=data)
elif reqtype == 'get':
req = Request('GET', url, headers=headers)
else:
_LOGGER.error("Invalid request type: %s", reqtype)
raise BlinkException(ERROR.REQUEST)
prepped = req.prepare()
try:
response = blink.session.send(prepped, stream=stream, timeout=10)
if json_resp and 'code' in response.json():
if is_retry:
_LOGGER.error("Cannot obtain new token for server auth.")
return None
else:
headers = attempt_reauthorization(blink)
if not headers:
raise exceptions.ConnectionError
return http_req(blink, url=url, data=data, headers=headers,
reqtype=reqtype, stream=stream,
json_resp=json_resp, is_retry=True)
except (exceptions.ConnectionError, exceptions.Timeout):
_LOGGER.info("Cannot connect to server with url %s.", url)
if not is_retry:
headers = attempt_reauthorization(blink)
return http_req(blink, url=url, data=data, headers=headers,
reqtype=reqtype, stream=stream,
json_resp=json_resp, is_retry=True)
_LOGGER.error("Endpoint %s failed. Possible issue with Blink servers.",
url)
return None
if json_resp:
return response.json()
return response | [
"def",
"http_req",
"(",
"blink",
",",
"url",
"=",
"'http://example.com'",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"reqtype",
"=",
"'get'",
",",
"stream",
"=",
"False",
",",
"json_resp",
"=",
"True",
",",
"is_retry",
"=",
"False",
")",
":",
"if",
"reqtype",
"==",
"'post'",
":",
"req",
"=",
"Request",
"(",
"'POST'",
",",
"url",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"data",
")",
"elif",
"reqtype",
"==",
"'get'",
":",
"req",
"=",
"Request",
"(",
"'GET'",
",",
"url",
",",
"headers",
"=",
"headers",
")",
"else",
":",
"_LOGGER",
".",
"error",
"(",
"\"Invalid request type: %s\"",
",",
"reqtype",
")",
"raise",
"BlinkException",
"(",
"ERROR",
".",
"REQUEST",
")",
"prepped",
"=",
"req",
".",
"prepare",
"(",
")",
"try",
":",
"response",
"=",
"blink",
".",
"session",
".",
"send",
"(",
"prepped",
",",
"stream",
"=",
"stream",
",",
"timeout",
"=",
"10",
")",
"if",
"json_resp",
"and",
"'code'",
"in",
"response",
".",
"json",
"(",
")",
":",
"if",
"is_retry",
":",
"_LOGGER",
".",
"error",
"(",
"\"Cannot obtain new token for server auth.\"",
")",
"return",
"None",
"else",
":",
"headers",
"=",
"attempt_reauthorization",
"(",
"blink",
")",
"if",
"not",
"headers",
":",
"raise",
"exceptions",
".",
"ConnectionError",
"return",
"http_req",
"(",
"blink",
",",
"url",
"=",
"url",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"reqtype",
"=",
"reqtype",
",",
"stream",
"=",
"stream",
",",
"json_resp",
"=",
"json_resp",
",",
"is_retry",
"=",
"True",
")",
"except",
"(",
"exceptions",
".",
"ConnectionError",
",",
"exceptions",
".",
"Timeout",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Cannot connect to server with url %s.\"",
",",
"url",
")",
"if",
"not",
"is_retry",
":",
"headers",
"=",
"attempt_reauthorization",
"(",
"blink",
")",
"return",
"http_req",
"(",
"blink",
",",
"url",
"=",
"url",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"reqtype",
"=",
"reqtype",
",",
"stream",
"=",
"stream",
",",
"json_resp",
"=",
"json_resp",
",",
"is_retry",
"=",
"True",
")",
"_LOGGER",
".",
"error",
"(",
"\"Endpoint %s failed. Possible issue with Blink servers.\"",
",",
"url",
")",
"return",
"None",
"if",
"json_resp",
":",
"return",
"response",
".",
"json",
"(",
")",
"return",
"response"
] | Perform server requests and check if reauthorization neccessary.
:param blink: Blink instance
:param url: URL to perform request
:param data: Data to send (default: None)
:param headers: Headers to send (default: None)
:param reqtype: Can be 'get' or 'post' (default: 'get')
:param stream: Stream response? True/FALSE
:param json_resp: Return JSON response? TRUE/False
:param is_retry: Is this a retry attempt? True/FALSE | [
"Perform",
"server",
"requests",
"and",
"check",
"if",
"reauthorization",
"neccessary",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/helpers/util.py#L43-L94 | train | 238,116 |
fronzbot/blinkpy | blinkpy/blinkpy.py | Blink.start | def start(self):
"""
Perform full system setup.
Method logs in and sets auth token, urls, and ids for future requests.
Essentially this is just a wrapper function for ease of use.
"""
if self._username is None or self._password is None:
if not self.login():
return
elif not self.get_auth_token():
return
camera_list = self.get_cameras()
networks = self.get_ids()
for network_name, network_id in networks.items():
if network_id not in camera_list.keys():
camera_list[network_id] = {}
_LOGGER.warning("No cameras found for %s", network_name)
sync_module = BlinkSyncModule(self,
network_name,
network_id,
camera_list[network_id])
sync_module.start()
self.sync[network_name] = sync_module
self.cameras = self.merge_cameras() | python | def start(self):
"""
Perform full system setup.
Method logs in and sets auth token, urls, and ids for future requests.
Essentially this is just a wrapper function for ease of use.
"""
if self._username is None or self._password is None:
if not self.login():
return
elif not self.get_auth_token():
return
camera_list = self.get_cameras()
networks = self.get_ids()
for network_name, network_id in networks.items():
if network_id not in camera_list.keys():
camera_list[network_id] = {}
_LOGGER.warning("No cameras found for %s", network_name)
sync_module = BlinkSyncModule(self,
network_name,
network_id,
camera_list[network_id])
sync_module.start()
self.sync[network_name] = sync_module
self.cameras = self.merge_cameras() | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_username",
"is",
"None",
"or",
"self",
".",
"_password",
"is",
"None",
":",
"if",
"not",
"self",
".",
"login",
"(",
")",
":",
"return",
"elif",
"not",
"self",
".",
"get_auth_token",
"(",
")",
":",
"return",
"camera_list",
"=",
"self",
".",
"get_cameras",
"(",
")",
"networks",
"=",
"self",
".",
"get_ids",
"(",
")",
"for",
"network_name",
",",
"network_id",
"in",
"networks",
".",
"items",
"(",
")",
":",
"if",
"network_id",
"not",
"in",
"camera_list",
".",
"keys",
"(",
")",
":",
"camera_list",
"[",
"network_id",
"]",
"=",
"{",
"}",
"_LOGGER",
".",
"warning",
"(",
"\"No cameras found for %s\"",
",",
"network_name",
")",
"sync_module",
"=",
"BlinkSyncModule",
"(",
"self",
",",
"network_name",
",",
"network_id",
",",
"camera_list",
"[",
"network_id",
"]",
")",
"sync_module",
".",
"start",
"(",
")",
"self",
".",
"sync",
"[",
"network_name",
"]",
"=",
"sync_module",
"self",
".",
"cameras",
"=",
"self",
".",
"merge_cameras",
"(",
")"
] | Perform full system setup.
Method logs in and sets auth token, urls, and ids for future requests.
Essentially this is just a wrapper function for ease of use. | [
"Perform",
"full",
"system",
"setup",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/blinkpy.py#L82-L107 | train | 238,117 |
fronzbot/blinkpy | blinkpy/blinkpy.py | Blink.login | def login(self):
"""Prompt user for username and password."""
self._username = input("Username:")
self._password = getpass.getpass("Password:")
if self.get_auth_token():
_LOGGER.debug("Login successful!")
return True
_LOGGER.warning("Unable to login with %s.", self._username)
return False | python | def login(self):
"""Prompt user for username and password."""
self._username = input("Username:")
self._password = getpass.getpass("Password:")
if self.get_auth_token():
_LOGGER.debug("Login successful!")
return True
_LOGGER.warning("Unable to login with %s.", self._username)
return False | [
"def",
"login",
"(",
"self",
")",
":",
"self",
".",
"_username",
"=",
"input",
"(",
"\"Username:\"",
")",
"self",
".",
"_password",
"=",
"getpass",
".",
"getpass",
"(",
"\"Password:\"",
")",
"if",
"self",
".",
"get_auth_token",
"(",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Login successful!\"",
")",
"return",
"True",
"_LOGGER",
".",
"warning",
"(",
"\"Unable to login with %s.\"",
",",
"self",
".",
"_username",
")",
"return",
"False"
] | Prompt user for username and password. | [
"Prompt",
"user",
"for",
"username",
"and",
"password",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/blinkpy.py#L109-L117 | train | 238,118 |
fronzbot/blinkpy | blinkpy/blinkpy.py | Blink.get_auth_token | def get_auth_token(self, is_retry=False):
"""Retrieve the authentication token from Blink."""
if not isinstance(self._username, str):
raise BlinkAuthenticationException(ERROR.USERNAME)
if not isinstance(self._password, str):
raise BlinkAuthenticationException(ERROR.PASSWORD)
login_urls = [LOGIN_URL, OLD_LOGIN_URL, LOGIN_BACKUP_URL]
response = self.login_request(login_urls, is_retry=is_retry)
if not response:
return False
self._host = "{}.{}".format(self.region_id, BLINK_URL)
self._token = response['authtoken']['authtoken']
self.networks = response['networks']
self._auth_header = {'Host': self._host,
'TOKEN_AUTH': self._token}
self.urls = BlinkURLHandler(self.region_id)
return self._auth_header | python | def get_auth_token(self, is_retry=False):
"""Retrieve the authentication token from Blink."""
if not isinstance(self._username, str):
raise BlinkAuthenticationException(ERROR.USERNAME)
if not isinstance(self._password, str):
raise BlinkAuthenticationException(ERROR.PASSWORD)
login_urls = [LOGIN_URL, OLD_LOGIN_URL, LOGIN_BACKUP_URL]
response = self.login_request(login_urls, is_retry=is_retry)
if not response:
return False
self._host = "{}.{}".format(self.region_id, BLINK_URL)
self._token = response['authtoken']['authtoken']
self.networks = response['networks']
self._auth_header = {'Host': self._host,
'TOKEN_AUTH': self._token}
self.urls = BlinkURLHandler(self.region_id)
return self._auth_header | [
"def",
"get_auth_token",
"(",
"self",
",",
"is_retry",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_username",
",",
"str",
")",
":",
"raise",
"BlinkAuthenticationException",
"(",
"ERROR",
".",
"USERNAME",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_password",
",",
"str",
")",
":",
"raise",
"BlinkAuthenticationException",
"(",
"ERROR",
".",
"PASSWORD",
")",
"login_urls",
"=",
"[",
"LOGIN_URL",
",",
"OLD_LOGIN_URL",
",",
"LOGIN_BACKUP_URL",
"]",
"response",
"=",
"self",
".",
"login_request",
"(",
"login_urls",
",",
"is_retry",
"=",
"is_retry",
")",
"if",
"not",
"response",
":",
"return",
"False",
"self",
".",
"_host",
"=",
"\"{}.{}\"",
".",
"format",
"(",
"self",
".",
"region_id",
",",
"BLINK_URL",
")",
"self",
".",
"_token",
"=",
"response",
"[",
"'authtoken'",
"]",
"[",
"'authtoken'",
"]",
"self",
".",
"networks",
"=",
"response",
"[",
"'networks'",
"]",
"self",
".",
"_auth_header",
"=",
"{",
"'Host'",
":",
"self",
".",
"_host",
",",
"'TOKEN_AUTH'",
":",
"self",
".",
"_token",
"}",
"self",
".",
"urls",
"=",
"BlinkURLHandler",
"(",
"self",
".",
"region_id",
")",
"return",
"self",
".",
"_auth_header"
] | Retrieve the authentication token from Blink. | [
"Retrieve",
"the",
"authentication",
"token",
"from",
"Blink",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/blinkpy.py#L119-L141 | train | 238,119 |
fronzbot/blinkpy | blinkpy/blinkpy.py | Blink.login_request | def login_request(self, login_urls, is_retry=False):
"""Make a login request."""
try:
login_url = login_urls.pop(0)
except IndexError:
_LOGGER.error("Could not login to blink servers.")
return False
_LOGGER.info("Attempting login with %s", login_url)
response = api.request_login(self,
login_url,
self._username,
self._password,
is_retry=is_retry)
try:
if response.status_code != 200:
response = self.login_request(login_urls)
response = response.json()
(self.region_id, self.region), = response['region'].items()
except AttributeError:
_LOGGER.error("Login API endpoint failed with response %s",
response,
exc_info=True)
return False
except KeyError:
_LOGGER.warning("Could not extract region info.")
self.region_id = 'piri'
self.region = 'UNKNOWN'
self._login_url = login_url
return response | python | def login_request(self, login_urls, is_retry=False):
"""Make a login request."""
try:
login_url = login_urls.pop(0)
except IndexError:
_LOGGER.error("Could not login to blink servers.")
return False
_LOGGER.info("Attempting login with %s", login_url)
response = api.request_login(self,
login_url,
self._username,
self._password,
is_retry=is_retry)
try:
if response.status_code != 200:
response = self.login_request(login_urls)
response = response.json()
(self.region_id, self.region), = response['region'].items()
except AttributeError:
_LOGGER.error("Login API endpoint failed with response %s",
response,
exc_info=True)
return False
except KeyError:
_LOGGER.warning("Could not extract region info.")
self.region_id = 'piri'
self.region = 'UNKNOWN'
self._login_url = login_url
return response | [
"def",
"login_request",
"(",
"self",
",",
"login_urls",
",",
"is_retry",
"=",
"False",
")",
":",
"try",
":",
"login_url",
"=",
"login_urls",
".",
"pop",
"(",
"0",
")",
"except",
"IndexError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not login to blink servers.\"",
")",
"return",
"False",
"_LOGGER",
".",
"info",
"(",
"\"Attempting login with %s\"",
",",
"login_url",
")",
"response",
"=",
"api",
".",
"request_login",
"(",
"self",
",",
"login_url",
",",
"self",
".",
"_username",
",",
"self",
".",
"_password",
",",
"is_retry",
"=",
"is_retry",
")",
"try",
":",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"response",
"=",
"self",
".",
"login_request",
"(",
"login_urls",
")",
"response",
"=",
"response",
".",
"json",
"(",
")",
"(",
"self",
".",
"region_id",
",",
"self",
".",
"region",
")",
",",
"=",
"response",
"[",
"'region'",
"]",
".",
"items",
"(",
")",
"except",
"AttributeError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Login API endpoint failed with response %s\"",
",",
"response",
",",
"exc_info",
"=",
"True",
")",
"return",
"False",
"except",
"KeyError",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Could not extract region info.\"",
")",
"self",
".",
"region_id",
"=",
"'piri'",
"self",
".",
"region",
"=",
"'UNKNOWN'",
"self",
".",
"_login_url",
"=",
"login_url",
"return",
"response"
] | Make a login request. | [
"Make",
"a",
"login",
"request",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/blinkpy.py#L143-L176 | train | 238,120 |
fronzbot/blinkpy | blinkpy/blinkpy.py | Blink.get_ids | def get_ids(self):
"""Set the network ID and Account ID."""
response = api.request_networks(self)
all_networks = []
network_dict = {}
for network, status in self.networks.items():
if status['onboarded']:
all_networks.append('{}'.format(network))
network_dict[status['name']] = network
# For the first onboarded network we find, grab the account id
for resp in response['networks']:
if str(resp['id']) in all_networks:
self.account_id = resp['account_id']
break
self.network_ids = all_networks
return network_dict | python | def get_ids(self):
"""Set the network ID and Account ID."""
response = api.request_networks(self)
all_networks = []
network_dict = {}
for network, status in self.networks.items():
if status['onboarded']:
all_networks.append('{}'.format(network))
network_dict[status['name']] = network
# For the first onboarded network we find, grab the account id
for resp in response['networks']:
if str(resp['id']) in all_networks:
self.account_id = resp['account_id']
break
self.network_ids = all_networks
return network_dict | [
"def",
"get_ids",
"(",
"self",
")",
":",
"response",
"=",
"api",
".",
"request_networks",
"(",
"self",
")",
"all_networks",
"=",
"[",
"]",
"network_dict",
"=",
"{",
"}",
"for",
"network",
",",
"status",
"in",
"self",
".",
"networks",
".",
"items",
"(",
")",
":",
"if",
"status",
"[",
"'onboarded'",
"]",
":",
"all_networks",
".",
"append",
"(",
"'{}'",
".",
"format",
"(",
"network",
")",
")",
"network_dict",
"[",
"status",
"[",
"'name'",
"]",
"]",
"=",
"network",
"# For the first onboarded network we find, grab the account id",
"for",
"resp",
"in",
"response",
"[",
"'networks'",
"]",
":",
"if",
"str",
"(",
"resp",
"[",
"'id'",
"]",
")",
"in",
"all_networks",
":",
"self",
".",
"account_id",
"=",
"resp",
"[",
"'account_id'",
"]",
"break",
"self",
".",
"network_ids",
"=",
"all_networks",
"return",
"network_dict"
] | Set the network ID and Account ID. | [
"Set",
"the",
"network",
"ID",
"and",
"Account",
"ID",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/blinkpy.py#L178-L195 | train | 238,121 |
fronzbot/blinkpy | blinkpy/blinkpy.py | Blink.get_cameras | def get_cameras(self):
"""Retrieve a camera list for each onboarded network."""
response = api.request_homescreen(self)
try:
all_cameras = {}
for camera in response['cameras']:
camera_network = str(camera['network_id'])
camera_name = camera['name']
camera_id = camera['id']
camera_info = {'name': camera_name, 'id': camera_id}
if camera_network not in all_cameras:
all_cameras[camera_network] = []
all_cameras[camera_network].append(camera_info)
return all_cameras
except KeyError:
_LOGGER.error("Initialization failue. Could not retrieve cameras.")
return {} | python | def get_cameras(self):
"""Retrieve a camera list for each onboarded network."""
response = api.request_homescreen(self)
try:
all_cameras = {}
for camera in response['cameras']:
camera_network = str(camera['network_id'])
camera_name = camera['name']
camera_id = camera['id']
camera_info = {'name': camera_name, 'id': camera_id}
if camera_network not in all_cameras:
all_cameras[camera_network] = []
all_cameras[camera_network].append(camera_info)
return all_cameras
except KeyError:
_LOGGER.error("Initialization failue. Could not retrieve cameras.")
return {} | [
"def",
"get_cameras",
"(",
"self",
")",
":",
"response",
"=",
"api",
".",
"request_homescreen",
"(",
"self",
")",
"try",
":",
"all_cameras",
"=",
"{",
"}",
"for",
"camera",
"in",
"response",
"[",
"'cameras'",
"]",
":",
"camera_network",
"=",
"str",
"(",
"camera",
"[",
"'network_id'",
"]",
")",
"camera_name",
"=",
"camera",
"[",
"'name'",
"]",
"camera_id",
"=",
"camera",
"[",
"'id'",
"]",
"camera_info",
"=",
"{",
"'name'",
":",
"camera_name",
",",
"'id'",
":",
"camera_id",
"}",
"if",
"camera_network",
"not",
"in",
"all_cameras",
":",
"all_cameras",
"[",
"camera_network",
"]",
"=",
"[",
"]",
"all_cameras",
"[",
"camera_network",
"]",
".",
"append",
"(",
"camera_info",
")",
"return",
"all_cameras",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Initialization failue. Could not retrieve cameras.\"",
")",
"return",
"{",
"}"
] | Retrieve a camera list for each onboarded network. | [
"Retrieve",
"a",
"camera",
"list",
"for",
"each",
"onboarded",
"network",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/blinkpy.py#L197-L214 | train | 238,122 |
fronzbot/blinkpy | blinkpy/blinkpy.py | Blink.refresh | def refresh(self, force_cache=False):
"""
Perform a system refresh.
:param force_cache: Force an update of the camera cache
"""
if self.check_if_ok_to_update() or force_cache:
for sync_name, sync_module in self.sync.items():
_LOGGER.debug("Attempting refresh of sync %s", sync_name)
sync_module.refresh(force_cache=force_cache)
if not force_cache:
# Prevents rapid clearing of motion detect property
self.last_refresh = int(time.time())
return True
return False | python | def refresh(self, force_cache=False):
"""
Perform a system refresh.
:param force_cache: Force an update of the camera cache
"""
if self.check_if_ok_to_update() or force_cache:
for sync_name, sync_module in self.sync.items():
_LOGGER.debug("Attempting refresh of sync %s", sync_name)
sync_module.refresh(force_cache=force_cache)
if not force_cache:
# Prevents rapid clearing of motion detect property
self.last_refresh = int(time.time())
return True
return False | [
"def",
"refresh",
"(",
"self",
",",
"force_cache",
"=",
"False",
")",
":",
"if",
"self",
".",
"check_if_ok_to_update",
"(",
")",
"or",
"force_cache",
":",
"for",
"sync_name",
",",
"sync_module",
"in",
"self",
".",
"sync",
".",
"items",
"(",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Attempting refresh of sync %s\"",
",",
"sync_name",
")",
"sync_module",
".",
"refresh",
"(",
"force_cache",
"=",
"force_cache",
")",
"if",
"not",
"force_cache",
":",
"# Prevents rapid clearing of motion detect property",
"self",
".",
"last_refresh",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"return",
"True",
"return",
"False"
] | Perform a system refresh.
:param force_cache: Force an update of the camera cache | [
"Perform",
"a",
"system",
"refresh",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/blinkpy.py#L217-L231 | train | 238,123 |
fronzbot/blinkpy | blinkpy/blinkpy.py | Blink.check_if_ok_to_update | def check_if_ok_to_update(self):
"""Check if it is ok to perform an http request."""
current_time = int(time.time())
last_refresh = self.last_refresh
if last_refresh is None:
last_refresh = 0
if current_time >= (last_refresh + self.refresh_rate):
return True
return False | python | def check_if_ok_to_update(self):
"""Check if it is ok to perform an http request."""
current_time = int(time.time())
last_refresh = self.last_refresh
if last_refresh is None:
last_refresh = 0
if current_time >= (last_refresh + self.refresh_rate):
return True
return False | [
"def",
"check_if_ok_to_update",
"(",
"self",
")",
":",
"current_time",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"last_refresh",
"=",
"self",
".",
"last_refresh",
"if",
"last_refresh",
"is",
"None",
":",
"last_refresh",
"=",
"0",
"if",
"current_time",
">=",
"(",
"last_refresh",
"+",
"self",
".",
"refresh_rate",
")",
":",
"return",
"True",
"return",
"False"
] | Check if it is ok to perform an http request. | [
"Check",
"if",
"it",
"is",
"ok",
"to",
"perform",
"an",
"http",
"request",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/blinkpy.py#L233-L241 | train | 238,124 |
fronzbot/blinkpy | blinkpy/blinkpy.py | Blink.merge_cameras | def merge_cameras(self):
"""Merge all sync camera dicts into one."""
combined = CaseInsensitiveDict({})
for sync in self.sync:
combined = merge_dicts(combined, self.sync[sync].cameras)
return combined | python | def merge_cameras(self):
"""Merge all sync camera dicts into one."""
combined = CaseInsensitiveDict({})
for sync in self.sync:
combined = merge_dicts(combined, self.sync[sync].cameras)
return combined | [
"def",
"merge_cameras",
"(",
"self",
")",
":",
"combined",
"=",
"CaseInsensitiveDict",
"(",
"{",
"}",
")",
"for",
"sync",
"in",
"self",
".",
"sync",
":",
"combined",
"=",
"merge_dicts",
"(",
"combined",
",",
"self",
".",
"sync",
"[",
"sync",
"]",
".",
"cameras",
")",
"return",
"combined"
] | Merge all sync camera dicts into one. | [
"Merge",
"all",
"sync",
"camera",
"dicts",
"into",
"one",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/blinkpy.py#L243-L248 | train | 238,125 |
fronzbot/blinkpy | blinkpy/blinkpy.py | Blink.download_videos | def download_videos(self, path, since=None, camera='all', stop=10):
"""
Download all videos from server since specified time.
:param path: Path to write files. /path/<cameraname>_<recorddate>.mp4
:param since: Date and time to get videos from.
Ex: "2018/07/28 12:33:00" to retrieve videos since
July 28th 2018 at 12:33:00
:param camera: Camera name to retrieve. Defaults to "all".
Use a list for multiple cameras.
:param stop: Page to stop on (~25 items per page. Default page 10).
"""
if since is None:
since_epochs = self.last_refresh
else:
parsed_datetime = parse(since, fuzzy=True)
since_epochs = parsed_datetime.timestamp()
formatted_date = get_time(time_to_convert=since_epochs)
_LOGGER.info("Retrieving videos since %s", formatted_date)
if not isinstance(camera, list):
camera = [camera]
for page in range(1, stop):
response = api.request_videos(self, time=since_epochs, page=page)
_LOGGER.debug("Processing page %s", page)
try:
result = response['videos']
if not result:
raise IndexError
except (KeyError, IndexError):
_LOGGER.info("No videos found on page %s. Exiting.", page)
break
self._parse_downloaded_items(result, camera, path) | python | def download_videos(self, path, since=None, camera='all', stop=10):
"""
Download all videos from server since specified time.
:param path: Path to write files. /path/<cameraname>_<recorddate>.mp4
:param since: Date and time to get videos from.
Ex: "2018/07/28 12:33:00" to retrieve videos since
July 28th 2018 at 12:33:00
:param camera: Camera name to retrieve. Defaults to "all".
Use a list for multiple cameras.
:param stop: Page to stop on (~25 items per page. Default page 10).
"""
if since is None:
since_epochs = self.last_refresh
else:
parsed_datetime = parse(since, fuzzy=True)
since_epochs = parsed_datetime.timestamp()
formatted_date = get_time(time_to_convert=since_epochs)
_LOGGER.info("Retrieving videos since %s", formatted_date)
if not isinstance(camera, list):
camera = [camera]
for page in range(1, stop):
response = api.request_videos(self, time=since_epochs, page=page)
_LOGGER.debug("Processing page %s", page)
try:
result = response['videos']
if not result:
raise IndexError
except (KeyError, IndexError):
_LOGGER.info("No videos found on page %s. Exiting.", page)
break
self._parse_downloaded_items(result, camera, path) | [
"def",
"download_videos",
"(",
"self",
",",
"path",
",",
"since",
"=",
"None",
",",
"camera",
"=",
"'all'",
",",
"stop",
"=",
"10",
")",
":",
"if",
"since",
"is",
"None",
":",
"since_epochs",
"=",
"self",
".",
"last_refresh",
"else",
":",
"parsed_datetime",
"=",
"parse",
"(",
"since",
",",
"fuzzy",
"=",
"True",
")",
"since_epochs",
"=",
"parsed_datetime",
".",
"timestamp",
"(",
")",
"formatted_date",
"=",
"get_time",
"(",
"time_to_convert",
"=",
"since_epochs",
")",
"_LOGGER",
".",
"info",
"(",
"\"Retrieving videos since %s\"",
",",
"formatted_date",
")",
"if",
"not",
"isinstance",
"(",
"camera",
",",
"list",
")",
":",
"camera",
"=",
"[",
"camera",
"]",
"for",
"page",
"in",
"range",
"(",
"1",
",",
"stop",
")",
":",
"response",
"=",
"api",
".",
"request_videos",
"(",
"self",
",",
"time",
"=",
"since_epochs",
",",
"page",
"=",
"page",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Processing page %s\"",
",",
"page",
")",
"try",
":",
"result",
"=",
"response",
"[",
"'videos'",
"]",
"if",
"not",
"result",
":",
"raise",
"IndexError",
"except",
"(",
"KeyError",
",",
"IndexError",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"No videos found on page %s. Exiting.\"",
",",
"page",
")",
"break",
"self",
".",
"_parse_downloaded_items",
"(",
"result",
",",
"camera",
",",
"path",
")"
] | Download all videos from server since specified time.
:param path: Path to write files. /path/<cameraname>_<recorddate>.mp4
:param since: Date and time to get videos from.
Ex: "2018/07/28 12:33:00" to retrieve videos since
July 28th 2018 at 12:33:00
:param camera: Camera name to retrieve. Defaults to "all".
Use a list for multiple cameras.
:param stop: Page to stop on (~25 items per page. Default page 10). | [
"Download",
"all",
"videos",
"from",
"server",
"since",
"specified",
"time",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/blinkpy.py#L250-L285 | train | 238,126 |
fronzbot/blinkpy | blinkpy/blinkpy.py | Blink._parse_downloaded_items | def _parse_downloaded_items(self, result, camera, path):
"""Parse downloaded videos."""
for item in result:
try:
created_at = item['created_at']
camera_name = item['camera_name']
is_deleted = item['deleted']
address = item['address']
except KeyError:
_LOGGER.info("Missing clip information, skipping...")
continue
if camera_name not in camera and 'all' not in camera:
_LOGGER.debug("Skipping videos for %s.", camera_name)
continue
if is_deleted:
_LOGGER.debug("%s: %s is marked as deleted.",
camera_name,
address)
continue
clip_address = "{}{}".format(self.urls.base_url, address)
filename = "{}_{}.mp4".format(camera_name, created_at)
filename = os.path.join(path, filename)
if os.path.isfile(filename):
_LOGGER.info("%s already exists, skipping...", filename)
continue
response = api.http_get(self, url=clip_address,
stream=True, json=False)
with open(filename, 'wb') as vidfile:
copyfileobj(response.raw, vidfile)
_LOGGER.info("Downloaded video to %s", filename) | python | def _parse_downloaded_items(self, result, camera, path):
"""Parse downloaded videos."""
for item in result:
try:
created_at = item['created_at']
camera_name = item['camera_name']
is_deleted = item['deleted']
address = item['address']
except KeyError:
_LOGGER.info("Missing clip information, skipping...")
continue
if camera_name not in camera and 'all' not in camera:
_LOGGER.debug("Skipping videos for %s.", camera_name)
continue
if is_deleted:
_LOGGER.debug("%s: %s is marked as deleted.",
camera_name,
address)
continue
clip_address = "{}{}".format(self.urls.base_url, address)
filename = "{}_{}.mp4".format(camera_name, created_at)
filename = os.path.join(path, filename)
if os.path.isfile(filename):
_LOGGER.info("%s already exists, skipping...", filename)
continue
response = api.http_get(self, url=clip_address,
stream=True, json=False)
with open(filename, 'wb') as vidfile:
copyfileobj(response.raw, vidfile)
_LOGGER.info("Downloaded video to %s", filename) | [
"def",
"_parse_downloaded_items",
"(",
"self",
",",
"result",
",",
"camera",
",",
"path",
")",
":",
"for",
"item",
"in",
"result",
":",
"try",
":",
"created_at",
"=",
"item",
"[",
"'created_at'",
"]",
"camera_name",
"=",
"item",
"[",
"'camera_name'",
"]",
"is_deleted",
"=",
"item",
"[",
"'deleted'",
"]",
"address",
"=",
"item",
"[",
"'address'",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"info",
"(",
"\"Missing clip information, skipping...\"",
")",
"continue",
"if",
"camera_name",
"not",
"in",
"camera",
"and",
"'all'",
"not",
"in",
"camera",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Skipping videos for %s.\"",
",",
"camera_name",
")",
"continue",
"if",
"is_deleted",
":",
"_LOGGER",
".",
"debug",
"(",
"\"%s: %s is marked as deleted.\"",
",",
"camera_name",
",",
"address",
")",
"continue",
"clip_address",
"=",
"\"{}{}\"",
".",
"format",
"(",
"self",
".",
"urls",
".",
"base_url",
",",
"address",
")",
"filename",
"=",
"\"{}_{}.mp4\"",
".",
"format",
"(",
"camera_name",
",",
"created_at",
")",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"%s already exists, skipping...\"",
",",
"filename",
")",
"continue",
"response",
"=",
"api",
".",
"http_get",
"(",
"self",
",",
"url",
"=",
"clip_address",
",",
"stream",
"=",
"True",
",",
"json",
"=",
"False",
")",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"vidfile",
":",
"copyfileobj",
"(",
"response",
".",
"raw",
",",
"vidfile",
")",
"_LOGGER",
".",
"info",
"(",
"\"Downloaded video to %s\"",
",",
"filename",
")"
] | Parse downloaded videos. | [
"Parse",
"downloaded",
"videos",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/blinkpy.py#L287-L322 | train | 238,127 |
fronzbot/blinkpy | blinkpy/api.py | request_login | def request_login(blink, url, username, password, is_retry=False):
"""
Login request.
:param blink: Blink instance.
:param url: Login url.
:param username: Blink username.
:param password: Blink password.
:param is_retry: Is this part of a re-authorization attempt?
"""
headers = {
'Host': DEFAULT_URL,
'Content-Type': 'application/json'
}
data = dumps({
'email': username,
'password': password,
'client_specifier': 'iPhone 9.2 | 2.2 | 222'
})
return http_req(blink, url=url, headers=headers, data=data,
json_resp=False, reqtype='post', is_retry=is_retry) | python | def request_login(blink, url, username, password, is_retry=False):
"""
Login request.
:param blink: Blink instance.
:param url: Login url.
:param username: Blink username.
:param password: Blink password.
:param is_retry: Is this part of a re-authorization attempt?
"""
headers = {
'Host': DEFAULT_URL,
'Content-Type': 'application/json'
}
data = dumps({
'email': username,
'password': password,
'client_specifier': 'iPhone 9.2 | 2.2 | 222'
})
return http_req(blink, url=url, headers=headers, data=data,
json_resp=False, reqtype='post', is_retry=is_retry) | [
"def",
"request_login",
"(",
"blink",
",",
"url",
",",
"username",
",",
"password",
",",
"is_retry",
"=",
"False",
")",
":",
"headers",
"=",
"{",
"'Host'",
":",
"DEFAULT_URL",
",",
"'Content-Type'",
":",
"'application/json'",
"}",
"data",
"=",
"dumps",
"(",
"{",
"'email'",
":",
"username",
",",
"'password'",
":",
"password",
",",
"'client_specifier'",
":",
"'iPhone 9.2 | 2.2 | 222'",
"}",
")",
"return",
"http_req",
"(",
"blink",
",",
"url",
"=",
"url",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"data",
",",
"json_resp",
"=",
"False",
",",
"reqtype",
"=",
"'post'",
",",
"is_retry",
"=",
"is_retry",
")"
] | Login request.
:param blink: Blink instance.
:param url: Login url.
:param username: Blink username.
:param password: Blink password.
:param is_retry: Is this part of a re-authorization attempt? | [
"Login",
"request",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L14-L34 | train | 238,128 |
fronzbot/blinkpy | blinkpy/api.py | request_networks | def request_networks(blink):
"""Request all networks information."""
url = "{}/networks".format(blink.urls.base_url)
return http_get(blink, url) | python | def request_networks(blink):
"""Request all networks information."""
url = "{}/networks".format(blink.urls.base_url)
return http_get(blink, url) | [
"def",
"request_networks",
"(",
"blink",
")",
":",
"url",
"=",
"\"{}/networks\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
")",
"return",
"http_get",
"(",
"blink",
",",
"url",
")"
] | Request all networks information. | [
"Request",
"all",
"networks",
"information",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L37-L40 | train | 238,129 |
fronzbot/blinkpy | blinkpy/api.py | request_network_status | def request_network_status(blink, network):
"""
Request network information.
:param blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/network/{}".format(blink.urls.base_url, network)
return http_get(blink, url) | python | def request_network_status(blink, network):
"""
Request network information.
:param blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/network/{}".format(blink.urls.base_url, network)
return http_get(blink, url) | [
"def",
"request_network_status",
"(",
"blink",
",",
"network",
")",
":",
"url",
"=",
"\"{}/network/{}\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"network",
")",
"return",
"http_get",
"(",
"blink",
",",
"url",
")"
] | Request network information.
:param blink: Blink instance.
:param network: Sync module network id. | [
"Request",
"network",
"information",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L44-L52 | train | 238,130 |
fronzbot/blinkpy | blinkpy/api.py | request_syncmodule | def request_syncmodule(blink, network):
"""
Request sync module info.
:param blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/network/{}/syncmodules".format(blink.urls.base_url, network)
return http_get(blink, url) | python | def request_syncmodule(blink, network):
"""
Request sync module info.
:param blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/network/{}/syncmodules".format(blink.urls.base_url, network)
return http_get(blink, url) | [
"def",
"request_syncmodule",
"(",
"blink",
",",
"network",
")",
":",
"url",
"=",
"\"{}/network/{}/syncmodules\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"network",
")",
"return",
"http_get",
"(",
"blink",
",",
"url",
")"
] | Request sync module info.
:param blink: Blink instance.
:param network: Sync module network id. | [
"Request",
"sync",
"module",
"info",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L56-L64 | train | 238,131 |
fronzbot/blinkpy | blinkpy/api.py | request_system_arm | def request_system_arm(blink, network):
"""
Arm system.
:param blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/network/{}/arm".format(blink.urls.base_url, network)
return http_post(blink, url) | python | def request_system_arm(blink, network):
"""
Arm system.
:param blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/network/{}/arm".format(blink.urls.base_url, network)
return http_post(blink, url) | [
"def",
"request_system_arm",
"(",
"blink",
",",
"network",
")",
":",
"url",
"=",
"\"{}/network/{}/arm\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"network",
")",
"return",
"http_post",
"(",
"blink",
",",
"url",
")"
] | Arm system.
:param blink: Blink instance.
:param network: Sync module network id. | [
"Arm",
"system",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L68-L76 | train | 238,132 |
fronzbot/blinkpy | blinkpy/api.py | request_system_disarm | def request_system_disarm(blink, network):
"""
Disarm system.
:param blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/network/{}/disarm".format(blink.urls.base_url, network)
return http_post(blink, url) | python | def request_system_disarm(blink, network):
"""
Disarm system.
:param blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/network/{}/disarm".format(blink.urls.base_url, network)
return http_post(blink, url) | [
"def",
"request_system_disarm",
"(",
"blink",
",",
"network",
")",
":",
"url",
"=",
"\"{}/network/{}/disarm\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"network",
")",
"return",
"http_post",
"(",
"blink",
",",
"url",
")"
] | Disarm system.
:param blink: Blink instance.
:param network: Sync module network id. | [
"Disarm",
"system",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L80-L88 | train | 238,133 |
fronzbot/blinkpy | blinkpy/api.py | request_command_status | def request_command_status(blink, network, command_id):
"""
Request command status.
:param blink: Blink instance.
:param network: Sync module network id.
:param command_id: Command id to check.
"""
url = "{}/network/{}/command/{}".format(blink.urls.base_url,
network,
command_id)
return http_get(blink, url) | python | def request_command_status(blink, network, command_id):
"""
Request command status.
:param blink: Blink instance.
:param network: Sync module network id.
:param command_id: Command id to check.
"""
url = "{}/network/{}/command/{}".format(blink.urls.base_url,
network,
command_id)
return http_get(blink, url) | [
"def",
"request_command_status",
"(",
"blink",
",",
"network",
",",
"command_id",
")",
":",
"url",
"=",
"\"{}/network/{}/command/{}\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"network",
",",
"command_id",
")",
"return",
"http_get",
"(",
"blink",
",",
"url",
")"
] | Request command status.
:param blink: Blink instance.
:param network: Sync module network id.
:param command_id: Command id to check. | [
"Request",
"command",
"status",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L91-L102 | train | 238,134 |
fronzbot/blinkpy | blinkpy/api.py | request_homescreen | def request_homescreen(blink):
"""Request homescreen info."""
url = "{}/api/v3/accounts/{}/homescreen".format(blink.urls.base_url,
blink.account_id)
return http_get(blink, url) | python | def request_homescreen(blink):
"""Request homescreen info."""
url = "{}/api/v3/accounts/{}/homescreen".format(blink.urls.base_url,
blink.account_id)
return http_get(blink, url) | [
"def",
"request_homescreen",
"(",
"blink",
")",
":",
"url",
"=",
"\"{}/api/v3/accounts/{}/homescreen\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"blink",
".",
"account_id",
")",
"return",
"http_get",
"(",
"blink",
",",
"url",
")"
] | Request homescreen info. | [
"Request",
"homescreen",
"info",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L106-L110 | train | 238,135 |
fronzbot/blinkpy | blinkpy/api.py | request_sync_events | def request_sync_events(blink, network):
"""
Request events from sync module.
:param blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/events/network/{}".format(blink.urls.base_url, network)
return http_get(blink, url) | python | def request_sync_events(blink, network):
"""
Request events from sync module.
:param blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/events/network/{}".format(blink.urls.base_url, network)
return http_get(blink, url) | [
"def",
"request_sync_events",
"(",
"blink",
",",
"network",
")",
":",
"url",
"=",
"\"{}/events/network/{}\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"network",
")",
"return",
"http_get",
"(",
"blink",
",",
"url",
")"
] | Request events from sync module.
:param blink: Blink instance.
:param network: Sync module network id. | [
"Request",
"events",
"from",
"sync",
"module",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L114-L122 | train | 238,136 |
fronzbot/blinkpy | blinkpy/api.py | request_video_count | def request_video_count(blink):
"""Request total video count."""
url = "{}/api/v2/videos/count".format(blink.urls.base_url)
return http_get(blink, url) | python | def request_video_count(blink):
"""Request total video count."""
url = "{}/api/v2/videos/count".format(blink.urls.base_url)
return http_get(blink, url) | [
"def",
"request_video_count",
"(",
"blink",
")",
":",
"url",
"=",
"\"{}/api/v2/videos/count\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
")",
"return",
"http_get",
"(",
"blink",
",",
"url",
")"
] | Request total video count. | [
"Request",
"total",
"video",
"count",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L156-L159 | train | 238,137 |
fronzbot/blinkpy | blinkpy/api.py | request_videos | def request_videos(blink, time=None, page=0):
"""
Perform a request for videos.
:param blink: Blink instance.
:param time: Get videos since this time. In epoch seconds.
:param page: Page number to get videos from.
"""
timestamp = get_time(time)
url = "{}/api/v2/videos/changed?since={}&page={}".format(
blink.urls.base_url, timestamp, page)
return http_get(blink, url) | python | def request_videos(blink, time=None, page=0):
"""
Perform a request for videos.
:param blink: Blink instance.
:param time: Get videos since this time. In epoch seconds.
:param page: Page number to get videos from.
"""
timestamp = get_time(time)
url = "{}/api/v2/videos/changed?since={}&page={}".format(
blink.urls.base_url, timestamp, page)
return http_get(blink, url) | [
"def",
"request_videos",
"(",
"blink",
",",
"time",
"=",
"None",
",",
"page",
"=",
"0",
")",
":",
"timestamp",
"=",
"get_time",
"(",
"time",
")",
"url",
"=",
"\"{}/api/v2/videos/changed?since={}&page={}\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"timestamp",
",",
"page",
")",
"return",
"http_get",
"(",
"blink",
",",
"url",
")"
] | Perform a request for videos.
:param blink: Blink instance.
:param time: Get videos since this time. In epoch seconds.
:param page: Page number to get videos from. | [
"Perform",
"a",
"request",
"for",
"videos",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L162-L173 | train | 238,138 |
fronzbot/blinkpy | blinkpy/api.py | request_cameras | def request_cameras(blink, network):
"""
Request all camera information.
:param Blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/network/{}/cameras".format(blink.urls.base_url, network)
return http_get(blink, url) | python | def request_cameras(blink, network):
"""
Request all camera information.
:param Blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/network/{}/cameras".format(blink.urls.base_url, network)
return http_get(blink, url) | [
"def",
"request_cameras",
"(",
"blink",
",",
"network",
")",
":",
"url",
"=",
"\"{}/network/{}/cameras\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"network",
")",
"return",
"http_get",
"(",
"blink",
",",
"url",
")"
] | Request all camera information.
:param Blink: Blink instance.
:param network: Sync module network id. | [
"Request",
"all",
"camera",
"information",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L177-L185 | train | 238,139 |
fronzbot/blinkpy | blinkpy/api.py | request_camera_sensors | def request_camera_sensors(blink, network, camera_id):
"""
Request camera sensor info for one camera.
:param blink: Blink instance.
:param network: Sync module network id.
:param camera_id: Camera ID of camera to request sesnor info from.
"""
url = "{}/network/{}/camera/{}/signals".format(blink.urls.base_url,
network,
camera_id)
return http_get(blink, url) | python | def request_camera_sensors(blink, network, camera_id):
"""
Request camera sensor info for one camera.
:param blink: Blink instance.
:param network: Sync module network id.
:param camera_id: Camera ID of camera to request sesnor info from.
"""
url = "{}/network/{}/camera/{}/signals".format(blink.urls.base_url,
network,
camera_id)
return http_get(blink, url) | [
"def",
"request_camera_sensors",
"(",
"blink",
",",
"network",
",",
"camera_id",
")",
":",
"url",
"=",
"\"{}/network/{}/camera/{}/signals\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"network",
",",
"camera_id",
")",
"return",
"http_get",
"(",
"blink",
",",
"url",
")"
] | Request camera sensor info for one camera.
:param blink: Blink instance.
:param network: Sync module network id.
:param camera_id: Camera ID of camera to request sesnor info from. | [
"Request",
"camera",
"sensor",
"info",
"for",
"one",
"camera",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L202-L213 | train | 238,140 |
fronzbot/blinkpy | blinkpy/api.py | request_motion_detection_enable | def request_motion_detection_enable(blink, network, camera_id):
"""
Enable motion detection for a camera.
:param blink: Blink instance.
:param network: Sync module network id.
:param camera_id: Camera ID of camera to enable.
"""
url = "{}/network/{}/camera/{}/enable".format(blink.urls.base_url,
network,
camera_id)
return http_post(blink, url) | python | def request_motion_detection_enable(blink, network, camera_id):
"""
Enable motion detection for a camera.
:param blink: Blink instance.
:param network: Sync module network id.
:param camera_id: Camera ID of camera to enable.
"""
url = "{}/network/{}/camera/{}/enable".format(blink.urls.base_url,
network,
camera_id)
return http_post(blink, url) | [
"def",
"request_motion_detection_enable",
"(",
"blink",
",",
"network",
",",
"camera_id",
")",
":",
"url",
"=",
"\"{}/network/{}/camera/{}/enable\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"network",
",",
"camera_id",
")",
"return",
"http_post",
"(",
"blink",
",",
"url",
")"
] | Enable motion detection for a camera.
:param blink: Blink instance.
:param network: Sync module network id.
:param camera_id: Camera ID of camera to enable. | [
"Enable",
"motion",
"detection",
"for",
"a",
"camera",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L217-L228 | train | 238,141 |
fronzbot/blinkpy | blinkpy/api.py | http_get | def http_get(blink, url, stream=False, json=True, is_retry=False):
"""
Perform an http get request.
:param url: URL to perform get request.
:param stream: Stream response? True/FALSE
:param json: Return json response? TRUE/False
:param is_retry: Is this part of a re-auth attempt?
"""
if blink.auth_header is None:
raise BlinkException(ERROR.AUTH_TOKEN)
_LOGGER.debug("Making GET request to %s", url)
return http_req(blink, url=url, headers=blink.auth_header,
reqtype='get', stream=stream, json_resp=json,
is_retry=is_retry) | python | def http_get(blink, url, stream=False, json=True, is_retry=False):
"""
Perform an http get request.
:param url: URL to perform get request.
:param stream: Stream response? True/FALSE
:param json: Return json response? TRUE/False
:param is_retry: Is this part of a re-auth attempt?
"""
if blink.auth_header is None:
raise BlinkException(ERROR.AUTH_TOKEN)
_LOGGER.debug("Making GET request to %s", url)
return http_req(blink, url=url, headers=blink.auth_header,
reqtype='get', stream=stream, json_resp=json,
is_retry=is_retry) | [
"def",
"http_get",
"(",
"blink",
",",
"url",
",",
"stream",
"=",
"False",
",",
"json",
"=",
"True",
",",
"is_retry",
"=",
"False",
")",
":",
"if",
"blink",
".",
"auth_header",
"is",
"None",
":",
"raise",
"BlinkException",
"(",
"ERROR",
".",
"AUTH_TOKEN",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Making GET request to %s\"",
",",
"url",
")",
"return",
"http_req",
"(",
"blink",
",",
"url",
"=",
"url",
",",
"headers",
"=",
"blink",
".",
"auth_header",
",",
"reqtype",
"=",
"'get'",
",",
"stream",
"=",
"stream",
",",
"json_resp",
"=",
"json",
",",
"is_retry",
"=",
"is_retry",
")"
] | Perform an http get request.
:param url: URL to perform get request.
:param stream: Stream response? True/FALSE
:param json: Return json response? TRUE/False
:param is_retry: Is this part of a re-auth attempt? | [
"Perform",
"an",
"http",
"get",
"request",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L245-L259 | train | 238,142 |
fronzbot/blinkpy | blinkpy/api.py | http_post | def http_post(blink, url, is_retry=False):
"""
Perform an http post request.
:param url: URL to perfom post request.
:param is_retry: Is this part of a re-auth attempt?
"""
if blink.auth_header is None:
raise BlinkException(ERROR.AUTH_TOKEN)
_LOGGER.debug("Making POST request to %s", url)
return http_req(blink, url=url, headers=blink.auth_header,
reqtype='post', is_retry=is_retry) | python | def http_post(blink, url, is_retry=False):
"""
Perform an http post request.
:param url: URL to perfom post request.
:param is_retry: Is this part of a re-auth attempt?
"""
if blink.auth_header is None:
raise BlinkException(ERROR.AUTH_TOKEN)
_LOGGER.debug("Making POST request to %s", url)
return http_req(blink, url=url, headers=blink.auth_header,
reqtype='post', is_retry=is_retry) | [
"def",
"http_post",
"(",
"blink",
",",
"url",
",",
"is_retry",
"=",
"False",
")",
":",
"if",
"blink",
".",
"auth_header",
"is",
"None",
":",
"raise",
"BlinkException",
"(",
"ERROR",
".",
"AUTH_TOKEN",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Making POST request to %s\"",
",",
"url",
")",
"return",
"http_req",
"(",
"blink",
",",
"url",
"=",
"url",
",",
"headers",
"=",
"blink",
".",
"auth_header",
",",
"reqtype",
"=",
"'post'",
",",
"is_retry",
"=",
"is_retry",
")"
] | Perform an http post request.
:param url: URL to perfom post request.
:param is_retry: Is this part of a re-auth attempt? | [
"Perform",
"an",
"http",
"post",
"request",
"."
] | bfdc1e47bdd84903f1aca653605846f3c99bcfac | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L262-L273 | train | 238,143 |
loli/medpy | medpy/filter/image.py | sls | def sls(minuend, subtrahend, metric = "ssd", noise = "global", signed = True,
sn_size = None, sn_footprint = None, sn_mode = "reflect", sn_cval = 0.0,
pn_size = None, pn_footprint = None, pn_mode = "reflect", pn_cval = 0.0):
r"""
Computes the signed local similarity between two images.
Compares a patch around each voxel of the minuend array to a number of patches
centered at the points of a search neighbourhood in the subtrahend. Thus, creates
a multi-dimensional measure of patch similarity between the minuend and a
corresponding search area in the subtrahend.
This filter can also be used to compute local self-similarity, obtaining a
descriptor similar to the one described in [1]_.
Parameters
----------
minuend : array_like
Input array from which to subtract the subtrahend.
subtrahend : array_like
Input array to subtract from the minuend.
metric : {'ssd', 'mi', 'nmi', 'ncc'}, optional
The `metric` parameter determines the metric used to compute the
filter output. Default is 'ssd'.
noise : {'global', 'local'}, optional
The `noise` parameter determines how the noise is handled. If set
to 'global', the variance determining the noise is a scalar, if
set to 'local', it is a Gaussian smoothed field of estimated local
noise. Default is 'global'.
signed : bool, optional
Whether the filter output should be signed or not. If set to 'False',
only the absolute values will be returned. Default is 'True'.
sn_size : scalar or tuple, optional
See sn_footprint, below
sn_footprint : array, optional
The search neighbourhood.
Either `sn_size` or `sn_footprint` must be defined. `sn_size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`sn_footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``sn_size=(n,m)`` is equivalent
to ``sn_footprint=np.ones((n,m))``. We adjust `sn_size` to the number
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `sn_size` is 2, then the actual size used is
(2,2,2).
sn_mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The `sn_mode` parameter determines how the array borders are
handled, where `sn_cval` is the value when mode is equal to
'constant'. Default is 'reflect'
sn_cval : scalar, optional
Value to fill past edges of input if `sn_mode` is 'constant'. Default
is 0.0
pn_size : scalar or tuple, optional
See pn_footprint, below
pn_footprint : array, optional
The patch over which the distance measure is applied.
Either `pn_size` or `pn_footprint` must be defined. `pn_size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`pn_footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``pn_size=(n,m)`` is equivalent
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `pn_size` is 2, then the actual size used is
(2,2,2).
pn_mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The `pn_mode` parameter determines how the array borders are
handled, where `pn_cval` is the value when mode is equal to
'constant'. Default is 'reflect'
pn_cval : scalar, optional
Value to fill past edges of input if `pn_mode` is 'constant'. Default
is 0.0
Returns
-------
sls : ndarray
The signed local similarity image between subtrahend and minuend.
References
----------
.. [1] Mattias P. Heinrich, Mark Jenkinson, Manav Bhushan, Tahreema Matin, Fergus V. Gleeson, Sir Michael Brady, Julia A. Schnabel
MIND: Modality independent neighbourhood descriptor for multi-modal deformable registration
Medical Image Analysis, Volume 16, Issue 7, October 2012, Pages 1423-1435, ISSN 1361-8415
http://dx.doi.org/10.1016/j.media.2012.05.008
"""
minuend = numpy.asarray(minuend)
subtrahend = numpy.asarray(subtrahend)
if numpy.iscomplexobj(minuend):
raise TypeError('complex type not supported')
if numpy.iscomplexobj(subtrahend):
raise TypeError('complex type not supported')
mshape = [ii for ii in minuend.shape if ii > 0]
sshape = [ii for ii in subtrahend.shape if ii > 0]
if not len(mshape) == len(sshape):
raise RuntimeError("minuend and subtrahend must be of same shape")
if not numpy.all([sm == ss for sm, ss in zip(mshape, sshape)]):
raise RuntimeError("minuend and subtrahend must be of same shape")
sn_footprint = __make_footprint(minuend, sn_size, sn_footprint)
sn_fshape = [ii for ii in sn_footprint.shape if ii > 0]
if len(sn_fshape) != minuend.ndim:
raise RuntimeError('search neighbourhood footprint array has incorrect shape.')
#!TODO: Is this required?
if not sn_footprint.flags.contiguous:
sn_footprint = sn_footprint.copy()
# created a padded copy of the subtrahend, whereas the padding mode is always 'reflect'
subtrahend = pad(subtrahend, footprint=sn_footprint, mode=sn_mode, cval=sn_cval)
# compute slicers for position where the search neighbourhood sn_footprint is TRUE
slicers = [[slice(x, (x + 1) - d if 0 != (x + 1) - d else None) for x in range(d)] for d in sn_fshape]
slicers = [sl for sl, tv in zip(itertools.product(*slicers), sn_footprint.flat) if tv]
# compute difference images and sign images for search neighbourhood elements
ssds = [ssd(minuend, subtrahend[slicer], normalized=True, signed=signed, size=pn_size, footprint=pn_footprint, mode=pn_mode, cval=pn_cval) for slicer in slicers]
distance = [x[0] for x in ssds]
distance_sign = [x[1] for x in ssds]
# compute local variance, which constitutes an approximation of local noise, out of patch-distances over the neighbourhood structure
variance = numpy.average(distance, 0)
variance = gaussian_filter(variance, sigma=3) #!TODO: Figure out if a fixed sigma is desirable here... I think that yes
if 'global' == noise:
variance = variance.sum() / float(numpy.product(variance.shape))
# variance[variance < variance_global / 10.] = variance_global / 10. #!TODO: Should I keep this i.e. regularizing the variance to be at least 10% of the global one?
# compute sls
sls = [dist_sign * numpy.exp(-1 * (dist / variance)) for dist_sign, dist in zip(distance_sign, distance)]
# convert into sls image, swapping dimensions to have varying patches in the last dimension
return numpy.rollaxis(numpy.asarray(sls), 0, minuend.ndim + 1) | python | def sls(minuend, subtrahend, metric = "ssd", noise = "global", signed = True,
sn_size = None, sn_footprint = None, sn_mode = "reflect", sn_cval = 0.0,
pn_size = None, pn_footprint = None, pn_mode = "reflect", pn_cval = 0.0):
r"""
Computes the signed local similarity between two images.
Compares a patch around each voxel of the minuend array to a number of patches
centered at the points of a search neighbourhood in the subtrahend. Thus, creates
a multi-dimensional measure of patch similarity between the minuend and a
corresponding search area in the subtrahend.
This filter can also be used to compute local self-similarity, obtaining a
descriptor similar to the one described in [1]_.
Parameters
----------
minuend : array_like
Input array from which to subtract the subtrahend.
subtrahend : array_like
Input array to subtract from the minuend.
metric : {'ssd', 'mi', 'nmi', 'ncc'}, optional
The `metric` parameter determines the metric used to compute the
filter output. Default is 'ssd'.
noise : {'global', 'local'}, optional
The `noise` parameter determines how the noise is handled. If set
to 'global', the variance determining the noise is a scalar, if
set to 'local', it is a Gaussian smoothed field of estimated local
noise. Default is 'global'.
signed : bool, optional
Whether the filter output should be signed or not. If set to 'False',
only the absolute values will be returned. Default is 'True'.
sn_size : scalar or tuple, optional
See sn_footprint, below
sn_footprint : array, optional
The search neighbourhood.
Either `sn_size` or `sn_footprint` must be defined. `sn_size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`sn_footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``sn_size=(n,m)`` is equivalent
to ``sn_footprint=np.ones((n,m))``. We adjust `sn_size` to the number
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `sn_size` is 2, then the actual size used is
(2,2,2).
sn_mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The `sn_mode` parameter determines how the array borders are
handled, where `sn_cval` is the value when mode is equal to
'constant'. Default is 'reflect'
sn_cval : scalar, optional
Value to fill past edges of input if `sn_mode` is 'constant'. Default
is 0.0
pn_size : scalar or tuple, optional
See pn_footprint, below
pn_footprint : array, optional
The patch over which the distance measure is applied.
Either `pn_size` or `pn_footprint` must be defined. `pn_size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`pn_footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``pn_size=(n,m)`` is equivalent
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `pn_size` is 2, then the actual size used is
(2,2,2).
pn_mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The `pn_mode` parameter determines how the array borders are
handled, where `pn_cval` is the value when mode is equal to
'constant'. Default is 'reflect'
pn_cval : scalar, optional
Value to fill past edges of input if `pn_mode` is 'constant'. Default
is 0.0
Returns
-------
sls : ndarray
The signed local similarity image between subtrahend and minuend.
References
----------
.. [1] Mattias P. Heinrich, Mark Jenkinson, Manav Bhushan, Tahreema Matin, Fergus V. Gleeson, Sir Michael Brady, Julia A. Schnabel
MIND: Modality independent neighbourhood descriptor for multi-modal deformable registration
Medical Image Analysis, Volume 16, Issue 7, October 2012, Pages 1423-1435, ISSN 1361-8415
http://dx.doi.org/10.1016/j.media.2012.05.008
"""
minuend = numpy.asarray(minuend)
subtrahend = numpy.asarray(subtrahend)
if numpy.iscomplexobj(minuend):
raise TypeError('complex type not supported')
if numpy.iscomplexobj(subtrahend):
raise TypeError('complex type not supported')
mshape = [ii for ii in minuend.shape if ii > 0]
sshape = [ii for ii in subtrahend.shape if ii > 0]
if not len(mshape) == len(sshape):
raise RuntimeError("minuend and subtrahend must be of same shape")
if not numpy.all([sm == ss for sm, ss in zip(mshape, sshape)]):
raise RuntimeError("minuend and subtrahend must be of same shape")
sn_footprint = __make_footprint(minuend, sn_size, sn_footprint)
sn_fshape = [ii for ii in sn_footprint.shape if ii > 0]
if len(sn_fshape) != minuend.ndim:
raise RuntimeError('search neighbourhood footprint array has incorrect shape.')
#!TODO: Is this required?
if not sn_footprint.flags.contiguous:
sn_footprint = sn_footprint.copy()
# created a padded copy of the subtrahend, whereas the padding mode is always 'reflect'
subtrahend = pad(subtrahend, footprint=sn_footprint, mode=sn_mode, cval=sn_cval)
# compute slicers for position where the search neighbourhood sn_footprint is TRUE
slicers = [[slice(x, (x + 1) - d if 0 != (x + 1) - d else None) for x in range(d)] for d in sn_fshape]
slicers = [sl for sl, tv in zip(itertools.product(*slicers), sn_footprint.flat) if tv]
# compute difference images and sign images for search neighbourhood elements
ssds = [ssd(minuend, subtrahend[slicer], normalized=True, signed=signed, size=pn_size, footprint=pn_footprint, mode=pn_mode, cval=pn_cval) for slicer in slicers]
distance = [x[0] for x in ssds]
distance_sign = [x[1] for x in ssds]
# compute local variance, which constitutes an approximation of local noise, out of patch-distances over the neighbourhood structure
variance = numpy.average(distance, 0)
variance = gaussian_filter(variance, sigma=3) #!TODO: Figure out if a fixed sigma is desirable here... I think that yes
if 'global' == noise:
variance = variance.sum() / float(numpy.product(variance.shape))
# variance[variance < variance_global / 10.] = variance_global / 10. #!TODO: Should I keep this i.e. regularizing the variance to be at least 10% of the global one?
# compute sls
sls = [dist_sign * numpy.exp(-1 * (dist / variance)) for dist_sign, dist in zip(distance_sign, distance)]
# convert into sls image, swapping dimensions to have varying patches in the last dimension
return numpy.rollaxis(numpy.asarray(sls), 0, minuend.ndim + 1) | [
"def",
"sls",
"(",
"minuend",
",",
"subtrahend",
",",
"metric",
"=",
"\"ssd\"",
",",
"noise",
"=",
"\"global\"",
",",
"signed",
"=",
"True",
",",
"sn_size",
"=",
"None",
",",
"sn_footprint",
"=",
"None",
",",
"sn_mode",
"=",
"\"reflect\"",
",",
"sn_cval",
"=",
"0.0",
",",
"pn_size",
"=",
"None",
",",
"pn_footprint",
"=",
"None",
",",
"pn_mode",
"=",
"\"reflect\"",
",",
"pn_cval",
"=",
"0.0",
")",
":",
"minuend",
"=",
"numpy",
".",
"asarray",
"(",
"minuend",
")",
"subtrahend",
"=",
"numpy",
".",
"asarray",
"(",
"subtrahend",
")",
"if",
"numpy",
".",
"iscomplexobj",
"(",
"minuend",
")",
":",
"raise",
"TypeError",
"(",
"'complex type not supported'",
")",
"if",
"numpy",
".",
"iscomplexobj",
"(",
"subtrahend",
")",
":",
"raise",
"TypeError",
"(",
"'complex type not supported'",
")",
"mshape",
"=",
"[",
"ii",
"for",
"ii",
"in",
"minuend",
".",
"shape",
"if",
"ii",
">",
"0",
"]",
"sshape",
"=",
"[",
"ii",
"for",
"ii",
"in",
"subtrahend",
".",
"shape",
"if",
"ii",
">",
"0",
"]",
"if",
"not",
"len",
"(",
"mshape",
")",
"==",
"len",
"(",
"sshape",
")",
":",
"raise",
"RuntimeError",
"(",
"\"minuend and subtrahend must be of same shape\"",
")",
"if",
"not",
"numpy",
".",
"all",
"(",
"[",
"sm",
"==",
"ss",
"for",
"sm",
",",
"ss",
"in",
"zip",
"(",
"mshape",
",",
"sshape",
")",
"]",
")",
":",
"raise",
"RuntimeError",
"(",
"\"minuend and subtrahend must be of same shape\"",
")",
"sn_footprint",
"=",
"__make_footprint",
"(",
"minuend",
",",
"sn_size",
",",
"sn_footprint",
")",
"sn_fshape",
"=",
"[",
"ii",
"for",
"ii",
"in",
"sn_footprint",
".",
"shape",
"if",
"ii",
">",
"0",
"]",
"if",
"len",
"(",
"sn_fshape",
")",
"!=",
"minuend",
".",
"ndim",
":",
"raise",
"RuntimeError",
"(",
"'search neighbourhood footprint array has incorrect shape.'",
")",
"#!TODO: Is this required?",
"if",
"not",
"sn_footprint",
".",
"flags",
".",
"contiguous",
":",
"sn_footprint",
"=",
"sn_footprint",
".",
"copy",
"(",
")",
"# created a padded copy of the subtrahend, whereas the padding mode is always 'reflect' ",
"subtrahend",
"=",
"pad",
"(",
"subtrahend",
",",
"footprint",
"=",
"sn_footprint",
",",
"mode",
"=",
"sn_mode",
",",
"cval",
"=",
"sn_cval",
")",
"# compute slicers for position where the search neighbourhood sn_footprint is TRUE",
"slicers",
"=",
"[",
"[",
"slice",
"(",
"x",
",",
"(",
"x",
"+",
"1",
")",
"-",
"d",
"if",
"0",
"!=",
"(",
"x",
"+",
"1",
")",
"-",
"d",
"else",
"None",
")",
"for",
"x",
"in",
"range",
"(",
"d",
")",
"]",
"for",
"d",
"in",
"sn_fshape",
"]",
"slicers",
"=",
"[",
"sl",
"for",
"sl",
",",
"tv",
"in",
"zip",
"(",
"itertools",
".",
"product",
"(",
"*",
"slicers",
")",
",",
"sn_footprint",
".",
"flat",
")",
"if",
"tv",
"]",
"# compute difference images and sign images for search neighbourhood elements",
"ssds",
"=",
"[",
"ssd",
"(",
"minuend",
",",
"subtrahend",
"[",
"slicer",
"]",
",",
"normalized",
"=",
"True",
",",
"signed",
"=",
"signed",
",",
"size",
"=",
"pn_size",
",",
"footprint",
"=",
"pn_footprint",
",",
"mode",
"=",
"pn_mode",
",",
"cval",
"=",
"pn_cval",
")",
"for",
"slicer",
"in",
"slicers",
"]",
"distance",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"ssds",
"]",
"distance_sign",
"=",
"[",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"ssds",
"]",
"# compute local variance, which constitutes an approximation of local noise, out of patch-distances over the neighbourhood structure",
"variance",
"=",
"numpy",
".",
"average",
"(",
"distance",
",",
"0",
")",
"variance",
"=",
"gaussian_filter",
"(",
"variance",
",",
"sigma",
"=",
"3",
")",
"#!TODO: Figure out if a fixed sigma is desirable here... I think that yes",
"if",
"'global'",
"==",
"noise",
":",
"variance",
"=",
"variance",
".",
"sum",
"(",
")",
"/",
"float",
"(",
"numpy",
".",
"product",
"(",
"variance",
".",
"shape",
")",
")",
"# variance[variance < variance_global / 10.] = variance_global / 10. #!TODO: Should I keep this i.e. regularizing the variance to be at least 10% of the global one?",
"# compute sls",
"sls",
"=",
"[",
"dist_sign",
"*",
"numpy",
".",
"exp",
"(",
"-",
"1",
"*",
"(",
"dist",
"/",
"variance",
")",
")",
"for",
"dist_sign",
",",
"dist",
"in",
"zip",
"(",
"distance_sign",
",",
"distance",
")",
"]",
"# convert into sls image, swapping dimensions to have varying patches in the last dimension",
"return",
"numpy",
".",
"rollaxis",
"(",
"numpy",
".",
"asarray",
"(",
"sls",
")",
",",
"0",
",",
"minuend",
".",
"ndim",
"+",
"1",
")"
] | r"""
Computes the signed local similarity between two images.
Compares a patch around each voxel of the minuend array to a number of patches
centered at the points of a search neighbourhood in the subtrahend. Thus, creates
a multi-dimensional measure of patch similarity between the minuend and a
corresponding search area in the subtrahend.
This filter can also be used to compute local self-similarity, obtaining a
descriptor similar to the one described in [1]_.
Parameters
----------
minuend : array_like
Input array from which to subtract the subtrahend.
subtrahend : array_like
Input array to subtract from the minuend.
metric : {'ssd', 'mi', 'nmi', 'ncc'}, optional
The `metric` parameter determines the metric used to compute the
filter output. Default is 'ssd'.
noise : {'global', 'local'}, optional
The `noise` parameter determines how the noise is handled. If set
to 'global', the variance determining the noise is a scalar, if
set to 'local', it is a Gaussian smoothed field of estimated local
noise. Default is 'global'.
signed : bool, optional
Whether the filter output should be signed or not. If set to 'False',
only the absolute values will be returned. Default is 'True'.
sn_size : scalar or tuple, optional
See sn_footprint, below
sn_footprint : array, optional
The search neighbourhood.
Either `sn_size` or `sn_footprint` must be defined. `sn_size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`sn_footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``sn_size=(n,m)`` is equivalent
to ``sn_footprint=np.ones((n,m))``. We adjust `sn_size` to the number
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `sn_size` is 2, then the actual size used is
(2,2,2).
sn_mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The `sn_mode` parameter determines how the array borders are
handled, where `sn_cval` is the value when mode is equal to
'constant'. Default is 'reflect'
sn_cval : scalar, optional
Value to fill past edges of input if `sn_mode` is 'constant'. Default
is 0.0
pn_size : scalar or tuple, optional
See pn_footprint, below
pn_footprint : array, optional
The patch over which the distance measure is applied.
Either `pn_size` or `pn_footprint` must be defined. `pn_size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`pn_footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``pn_size=(n,m)`` is equivalent
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `pn_size` is 2, then the actual size used is
(2,2,2).
pn_mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The `pn_mode` parameter determines how the array borders are
handled, where `pn_cval` is the value when mode is equal to
'constant'. Default is 'reflect'
pn_cval : scalar, optional
Value to fill past edges of input if `pn_mode` is 'constant'. Default
is 0.0
Returns
-------
sls : ndarray
The signed local similarity image between subtrahend and minuend.
References
----------
.. [1] Mattias P. Heinrich, Mark Jenkinson, Manav Bhushan, Tahreema Matin, Fergus V. Gleeson, Sir Michael Brady, Julia A. Schnabel
MIND: Modality independent neighbourhood descriptor for multi-modal deformable registration
Medical Image Analysis, Volume 16, Issue 7, October 2012, Pages 1423-1435, ISSN 1361-8415
http://dx.doi.org/10.1016/j.media.2012.05.008 | [
"r",
"Computes",
"the",
"signed",
"local",
"similarity",
"between",
"two",
"images",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/filter/image.py#L37-L170 | train | 238,144 |
loli/medpy | medpy/filter/image.py | average_filter | def average_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0):
r"""
Calculates a multi-dimensional average filter.
Parameters
----------
input : array-like
input array to filter
size : scalar or tuple, optional
See footprint, below
footprint : array, optional
Either `size` or `footprint` must be defined. `size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``size=(n,m)`` is equivalent
to ``footprint=np.ones((n,m))``. We adjust `size` to the number
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `size` is 2, then the actual size used is
(2,2,2).
output : array, optional
The ``output`` parameter passes an array in which to store the
filter output.
mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
The ``mode`` parameter determines how the array borders are
handled, where ``cval`` is the value when mode is equal to
'constant'. Default is 'reflect'
cval : scalar, optional
Value to fill past edges of input if ``mode`` is 'constant'. Default
is 0.0
origin : scalar, optional
The ``origin`` parameter controls the placement of the filter.
Default 0
Returns
-------
average_filter : ndarray
Returned array of same shape as `input`.
Notes
-----
Convenience implementation employing convolve.
See Also
--------
scipy.ndimage.filters.convolve : Convolve an image with a kernel.
"""
footprint = __make_footprint(input, size, footprint)
filter_size = footprint.sum()
output = _get_output(output, input)
sum_filter(input, footprint=footprint, output=output, mode=mode, cval=cval, origin=origin)
output /= filter_size
return output | python | def average_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0):
r"""
Calculates a multi-dimensional average filter.
Parameters
----------
input : array-like
input array to filter
size : scalar or tuple, optional
See footprint, below
footprint : array, optional
Either `size` or `footprint` must be defined. `size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``size=(n,m)`` is equivalent
to ``footprint=np.ones((n,m))``. We adjust `size` to the number
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `size` is 2, then the actual size used is
(2,2,2).
output : array, optional
The ``output`` parameter passes an array in which to store the
filter output.
mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
The ``mode`` parameter determines how the array borders are
handled, where ``cval`` is the value when mode is equal to
'constant'. Default is 'reflect'
cval : scalar, optional
Value to fill past edges of input if ``mode`` is 'constant'. Default
is 0.0
origin : scalar, optional
The ``origin`` parameter controls the placement of the filter.
Default 0
Returns
-------
average_filter : ndarray
Returned array of same shape as `input`.
Notes
-----
Convenience implementation employing convolve.
See Also
--------
scipy.ndimage.filters.convolve : Convolve an image with a kernel.
"""
footprint = __make_footprint(input, size, footprint)
filter_size = footprint.sum()
output = _get_output(output, input)
sum_filter(input, footprint=footprint, output=output, mode=mode, cval=cval, origin=origin)
output /= filter_size
return output | [
"def",
"average_filter",
"(",
"input",
",",
"size",
"=",
"None",
",",
"footprint",
"=",
"None",
",",
"output",
"=",
"None",
",",
"mode",
"=",
"\"reflect\"",
",",
"cval",
"=",
"0.0",
",",
"origin",
"=",
"0",
")",
":",
"footprint",
"=",
"__make_footprint",
"(",
"input",
",",
"size",
",",
"footprint",
")",
"filter_size",
"=",
"footprint",
".",
"sum",
"(",
")",
"output",
"=",
"_get_output",
"(",
"output",
",",
"input",
")",
"sum_filter",
"(",
"input",
",",
"footprint",
"=",
"footprint",
",",
"output",
"=",
"output",
",",
"mode",
"=",
"mode",
",",
"cval",
"=",
"cval",
",",
"origin",
"=",
"origin",
")",
"output",
"/=",
"filter_size",
"return",
"output"
] | r"""
Calculates a multi-dimensional average filter.
Parameters
----------
input : array-like
input array to filter
size : scalar or tuple, optional
See footprint, below
footprint : array, optional
Either `size` or `footprint` must be defined. `size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``size=(n,m)`` is equivalent
to ``footprint=np.ones((n,m))``. We adjust `size` to the number
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `size` is 2, then the actual size used is
(2,2,2).
output : array, optional
The ``output`` parameter passes an array in which to store the
filter output.
mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
The ``mode`` parameter determines how the array borders are
handled, where ``cval`` is the value when mode is equal to
'constant'. Default is 'reflect'
cval : scalar, optional
Value to fill past edges of input if ``mode`` is 'constant'. Default
is 0.0
origin : scalar, optional
The ``origin`` parameter controls the placement of the filter.
Default 0
Returns
-------
average_filter : ndarray
Returned array of same shape as `input`.
Notes
-----
Convenience implementation employing convolve.
See Also
--------
scipy.ndimage.filters.convolve : Convolve an image with a kernel. | [
"r",
"Calculates",
"a",
"multi",
"-",
"dimensional",
"average",
"filter",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/filter/image.py#L230-L284 | train | 238,145 |
loli/medpy | medpy/filter/image.py | sum_filter | def sum_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0):
r"""
Calculates a multi-dimensional sum filter.
Parameters
----------
input : array-like
input array to filter
size : scalar or tuple, optional
See footprint, below
footprint : array, optional
Either `size` or `footprint` must be defined. `size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``size=(n,m)`` is equivalent
to ``footprint=np.ones((n,m))``. We adjust `size` to the number
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `size` is 2, then the actual size used is
(2,2,2).
output : array, optional
The ``output`` parameter passes an array in which to store the
filter output.
mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
The ``mode`` parameter determines how the array borders are
handled, where ``cval`` is the value when mode is equal to
'constant'. Default is 'reflect'
cval : scalar, optional
Value to fill past edges of input if ``mode`` is 'constant'. Default
is 0.0
origin : scalar, optional
The ``origin`` parameter controls the placement of the filter.
Default 0
Returns
-------
sum_filter : ndarray
Returned array of same shape as `input`.
Notes
-----
Convenience implementation employing convolve.
See Also
--------
scipy.ndimage.filters.convolve : Convolve an image with a kernel.
"""
footprint = __make_footprint(input, size, footprint)
slicer = [slice(None, None, -1)] * footprint.ndim
return convolve(input, footprint[slicer], output, mode, cval, origin) | python | def sum_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0):
r"""
Calculates a multi-dimensional sum filter.
Parameters
----------
input : array-like
input array to filter
size : scalar or tuple, optional
See footprint, below
footprint : array, optional
Either `size` or `footprint` must be defined. `size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``size=(n,m)`` is equivalent
to ``footprint=np.ones((n,m))``. We adjust `size` to the number
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `size` is 2, then the actual size used is
(2,2,2).
output : array, optional
The ``output`` parameter passes an array in which to store the
filter output.
mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
The ``mode`` parameter determines how the array borders are
handled, where ``cval`` is the value when mode is equal to
'constant'. Default is 'reflect'
cval : scalar, optional
Value to fill past edges of input if ``mode`` is 'constant'. Default
is 0.0
origin : scalar, optional
The ``origin`` parameter controls the placement of the filter.
Default 0
Returns
-------
sum_filter : ndarray
Returned array of same shape as `input`.
Notes
-----
Convenience implementation employing convolve.
See Also
--------
scipy.ndimage.filters.convolve : Convolve an image with a kernel.
"""
footprint = __make_footprint(input, size, footprint)
slicer = [slice(None, None, -1)] * footprint.ndim
return convolve(input, footprint[slicer], output, mode, cval, origin) | [
"def",
"sum_filter",
"(",
"input",
",",
"size",
"=",
"None",
",",
"footprint",
"=",
"None",
",",
"output",
"=",
"None",
",",
"mode",
"=",
"\"reflect\"",
",",
"cval",
"=",
"0.0",
",",
"origin",
"=",
"0",
")",
":",
"footprint",
"=",
"__make_footprint",
"(",
"input",
",",
"size",
",",
"footprint",
")",
"slicer",
"=",
"[",
"slice",
"(",
"None",
",",
"None",
",",
"-",
"1",
")",
"]",
"*",
"footprint",
".",
"ndim",
"return",
"convolve",
"(",
"input",
",",
"footprint",
"[",
"slicer",
"]",
",",
"output",
",",
"mode",
",",
"cval",
",",
"origin",
")"
] | r"""
Calculates a multi-dimensional sum filter.
Parameters
----------
input : array-like
input array to filter
size : scalar or tuple, optional
See footprint, below
footprint : array, optional
Either `size` or `footprint` must be defined. `size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``size=(n,m)`` is equivalent
to ``footprint=np.ones((n,m))``. We adjust `size` to the number
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `size` is 2, then the actual size used is
(2,2,2).
output : array, optional
The ``output`` parameter passes an array in which to store the
filter output.
mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
The ``mode`` parameter determines how the array borders are
handled, where ``cval`` is the value when mode is equal to
'constant'. Default is 'reflect'
cval : scalar, optional
Value to fill past edges of input if ``mode`` is 'constant'. Default
is 0.0
origin : scalar, optional
The ``origin`` parameter controls the placement of the filter.
Default 0
Returns
-------
sum_filter : ndarray
Returned array of same shape as `input`.
Notes
-----
Convenience implementation employing convolve.
See Also
--------
scipy.ndimage.filters.convolve : Convolve an image with a kernel. | [
"r",
"Calculates",
"a",
"multi",
"-",
"dimensional",
"sum",
"filter",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/filter/image.py#L287-L337 | train | 238,146 |
loli/medpy | medpy/features/histogram.py | _gaussian_membership_sigma | def _gaussian_membership_sigma(smoothness, eps = 0.0005): # 275us @ smothness=10
r"""Compute the sigma required for a gaussian, such that in a neighbourhood of
smoothness the maximum error is 'eps'.
The error is here the difference between the clipped integral and one.
"""
error = 0
deltas = [0.1, 0.01, 0.001, 0.0001]
sigma = smoothness * 0.3
point = -1. * (smoothness + 0.5)
for delta in deltas:
while error < eps:
sigma += delta
error = scipy.stats.norm.cdf(0.5, point, sigma) - scipy.stats.norm.cdf(-0.5, point, sigma) # x, mu, sigma
sigma -= delta
return sigma | python | def _gaussian_membership_sigma(smoothness, eps = 0.0005): # 275us @ smothness=10
r"""Compute the sigma required for a gaussian, such that in a neighbourhood of
smoothness the maximum error is 'eps'.
The error is here the difference between the clipped integral and one.
"""
error = 0
deltas = [0.1, 0.01, 0.001, 0.0001]
sigma = smoothness * 0.3
point = -1. * (smoothness + 0.5)
for delta in deltas:
while error < eps:
sigma += delta
error = scipy.stats.norm.cdf(0.5, point, sigma) - scipy.stats.norm.cdf(-0.5, point, sigma) # x, mu, sigma
sigma -= delta
return sigma | [
"def",
"_gaussian_membership_sigma",
"(",
"smoothness",
",",
"eps",
"=",
"0.0005",
")",
":",
"# 275us @ smothness=10",
"error",
"=",
"0",
"deltas",
"=",
"[",
"0.1",
",",
"0.01",
",",
"0.001",
",",
"0.0001",
"]",
"sigma",
"=",
"smoothness",
"*",
"0.3",
"point",
"=",
"-",
"1.",
"*",
"(",
"smoothness",
"+",
"0.5",
")",
"for",
"delta",
"in",
"deltas",
":",
"while",
"error",
"<",
"eps",
":",
"sigma",
"+=",
"delta",
"error",
"=",
"scipy",
".",
"stats",
".",
"norm",
".",
"cdf",
"(",
"0.5",
",",
"point",
",",
"sigma",
")",
"-",
"scipy",
".",
"stats",
".",
"norm",
".",
"cdf",
"(",
"-",
"0.5",
",",
"point",
",",
"sigma",
")",
"# x, mu, sigma",
"sigma",
"-=",
"delta",
"return",
"sigma"
] | r"""Compute the sigma required for a gaussian, such that in a neighbourhood of
smoothness the maximum error is 'eps'.
The error is here the difference between the clipped integral and one. | [
"r",
"Compute",
"the",
"sigma",
"required",
"for",
"a",
"gaussian",
"such",
"that",
"in",
"a",
"neighbourhood",
"of",
"smoothness",
"the",
"maximum",
"error",
"is",
"eps",
".",
"The",
"error",
"is",
"here",
"the",
"difference",
"between",
"the",
"clipped",
"integral",
"and",
"one",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/histogram.py#L361-L375 | train | 238,147 |
loli/medpy | doc/numpydoc/numpydoc/plot_directive.py | out_of_date | def out_of_date(original, derived):
"""
Returns True if derivative is out-of-date wrt original,
both of which are full file paths.
"""
return (not os.path.exists(derived)
or os.stat(derived).st_mtime < os.stat(original).st_mtime) | python | def out_of_date(original, derived):
"""
Returns True if derivative is out-of-date wrt original,
both of which are full file paths.
"""
return (not os.path.exists(derived)
or os.stat(derived).st_mtime < os.stat(original).st_mtime) | [
"def",
"out_of_date",
"(",
"original",
",",
"derived",
")",
":",
"return",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"derived",
")",
"or",
"os",
".",
"stat",
"(",
"derived",
")",
".",
"st_mtime",
"<",
"os",
".",
"stat",
"(",
"original",
")",
".",
"st_mtime",
")"
] | Returns True if derivative is out-of-date wrt original,
both of which are full file paths. | [
"Returns",
"True",
"if",
"derivative",
"is",
"out",
"-",
"of",
"-",
"date",
"wrt",
"original",
"both",
"of",
"which",
"are",
"full",
"file",
"paths",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/plot_directive.py#L481-L487 | train | 238,148 |
loli/medpy | medpy/features/texture.py | local_maxima | def local_maxima(vector,min_distance = 4, brd_mode = "wrap"):
"""
Internal finder for local maxima .
Returns UNSORTED indices of maxima in input vector.
"""
fits = gaussian_filter(numpy.asarray(vector,dtype=numpy.float32),1., mode=brd_mode)
for ii in range(len(fits)):
if fits[ii] == fits[ii-1]:
fits[ii-1] = 0.0
maxfits = maximum_filter(fits, size=min_distance, mode=brd_mode)
maxima_mask = fits == maxfits
maximum = numpy.transpose(maxima_mask.nonzero())
return numpy.asarray(maximum) | python | def local_maxima(vector,min_distance = 4, brd_mode = "wrap"):
"""
Internal finder for local maxima .
Returns UNSORTED indices of maxima in input vector.
"""
fits = gaussian_filter(numpy.asarray(vector,dtype=numpy.float32),1., mode=brd_mode)
for ii in range(len(fits)):
if fits[ii] == fits[ii-1]:
fits[ii-1] = 0.0
maxfits = maximum_filter(fits, size=min_distance, mode=brd_mode)
maxima_mask = fits == maxfits
maximum = numpy.transpose(maxima_mask.nonzero())
return numpy.asarray(maximum) | [
"def",
"local_maxima",
"(",
"vector",
",",
"min_distance",
"=",
"4",
",",
"brd_mode",
"=",
"\"wrap\"",
")",
":",
"fits",
"=",
"gaussian_filter",
"(",
"numpy",
".",
"asarray",
"(",
"vector",
",",
"dtype",
"=",
"numpy",
".",
"float32",
")",
",",
"1.",
",",
"mode",
"=",
"brd_mode",
")",
"for",
"ii",
"in",
"range",
"(",
"len",
"(",
"fits",
")",
")",
":",
"if",
"fits",
"[",
"ii",
"]",
"==",
"fits",
"[",
"ii",
"-",
"1",
"]",
":",
"fits",
"[",
"ii",
"-",
"1",
"]",
"=",
"0.0",
"maxfits",
"=",
"maximum_filter",
"(",
"fits",
",",
"size",
"=",
"min_distance",
",",
"mode",
"=",
"brd_mode",
")",
"maxima_mask",
"=",
"fits",
"==",
"maxfits",
"maximum",
"=",
"numpy",
".",
"transpose",
"(",
"maxima_mask",
".",
"nonzero",
"(",
")",
")",
"return",
"numpy",
".",
"asarray",
"(",
"maximum",
")"
] | Internal finder for local maxima .
Returns UNSORTED indices of maxima in input vector. | [
"Internal",
"finder",
"for",
"local",
"maxima",
".",
"Returns",
"UNSORTED",
"indices",
"of",
"maxima",
"in",
"input",
"vector",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/texture.py#L268-L280 | train | 238,149 |
loli/medpy | medpy/features/texture.py | local_minima | def local_minima(vector,min_distance = 4, brd_mode = "wrap"):
"""
Internal finder for local minima .
Returns UNSORTED indices of minima in input vector.
"""
fits = gaussian_filter(numpy.asarray(vector,dtype=numpy.float32),1., mode=brd_mode)
for ii in range(len(fits)):
if fits[ii] == fits[ii-1]:
fits[ii-1] = numpy.pi/2.0
minfits = minimum_filter(fits, size=min_distance, mode=brd_mode)
minima_mask = fits == minfits
minima = numpy.transpose(minima_mask.nonzero())
return numpy.asarray(minima) | python | def local_minima(vector,min_distance = 4, brd_mode = "wrap"):
"""
Internal finder for local minima .
Returns UNSORTED indices of minima in input vector.
"""
fits = gaussian_filter(numpy.asarray(vector,dtype=numpy.float32),1., mode=brd_mode)
for ii in range(len(fits)):
if fits[ii] == fits[ii-1]:
fits[ii-1] = numpy.pi/2.0
minfits = minimum_filter(fits, size=min_distance, mode=brd_mode)
minima_mask = fits == minfits
minima = numpy.transpose(minima_mask.nonzero())
return numpy.asarray(minima) | [
"def",
"local_minima",
"(",
"vector",
",",
"min_distance",
"=",
"4",
",",
"brd_mode",
"=",
"\"wrap\"",
")",
":",
"fits",
"=",
"gaussian_filter",
"(",
"numpy",
".",
"asarray",
"(",
"vector",
",",
"dtype",
"=",
"numpy",
".",
"float32",
")",
",",
"1.",
",",
"mode",
"=",
"brd_mode",
")",
"for",
"ii",
"in",
"range",
"(",
"len",
"(",
"fits",
")",
")",
":",
"if",
"fits",
"[",
"ii",
"]",
"==",
"fits",
"[",
"ii",
"-",
"1",
"]",
":",
"fits",
"[",
"ii",
"-",
"1",
"]",
"=",
"numpy",
".",
"pi",
"/",
"2.0",
"minfits",
"=",
"minimum_filter",
"(",
"fits",
",",
"size",
"=",
"min_distance",
",",
"mode",
"=",
"brd_mode",
")",
"minima_mask",
"=",
"fits",
"==",
"minfits",
"minima",
"=",
"numpy",
".",
"transpose",
"(",
"minima_mask",
".",
"nonzero",
"(",
")",
")",
"return",
"numpy",
".",
"asarray",
"(",
"minima",
")"
] | Internal finder for local minima .
Returns UNSORTED indices of minima in input vector. | [
"Internal",
"finder",
"for",
"local",
"minima",
".",
"Returns",
"UNSORTED",
"indices",
"of",
"minima",
"in",
"input",
"vector",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/texture.py#L282-L294 | train | 238,150 |
loli/medpy | medpy/features/texture.py | find_valley_range | def find_valley_range(vector, min_distance = 4):
"""
Internal finder peaks and valley ranges.
Returns UNSORTED indices of maxima in input vector.
Returns range of valleys before and after maximum
"""
# http://users.monash.edu.au/~dengs/resource/papers/icme08.pdf
# find min and max with mode = wrap
mode = "wrap"
minima = local_minima(vector,min_distance,mode)
maxima = local_maxima(vector,min_distance,mode)
if len(maxima)>len(minima):
if vector[maxima[0]] >= vector[maxima[-1]]:
maxima=maxima[1:]
else:
maxima=maxima[:-1]
if len(maxima)==len(minima):
valley_range = numpy.asarray([minima[ii+1] - minima[ii] for ii in range(len(minima)-1)] + [len(vector)-minima[-1]+minima[0]])
if minima[0] < maxima[0]:
minima = numpy.asarray(list(minima) + [minima[0]])
else:
minima = numpy.asarray(list(minima) + [minima[-1]])
else:
valley_range = numpy.asarray([minima[ii+1] - minima[ii] for ii in range(len(maxima))])
return maxima, minima, valley_range | python | def find_valley_range(vector, min_distance = 4):
"""
Internal finder peaks and valley ranges.
Returns UNSORTED indices of maxima in input vector.
Returns range of valleys before and after maximum
"""
# http://users.monash.edu.au/~dengs/resource/papers/icme08.pdf
# find min and max with mode = wrap
mode = "wrap"
minima = local_minima(vector,min_distance,mode)
maxima = local_maxima(vector,min_distance,mode)
if len(maxima)>len(minima):
if vector[maxima[0]] >= vector[maxima[-1]]:
maxima=maxima[1:]
else:
maxima=maxima[:-1]
if len(maxima)==len(minima):
valley_range = numpy.asarray([minima[ii+1] - minima[ii] for ii in range(len(minima)-1)] + [len(vector)-minima[-1]+minima[0]])
if minima[0] < maxima[0]:
minima = numpy.asarray(list(minima) + [minima[0]])
else:
minima = numpy.asarray(list(minima) + [minima[-1]])
else:
valley_range = numpy.asarray([minima[ii+1] - minima[ii] for ii in range(len(maxima))])
return maxima, minima, valley_range | [
"def",
"find_valley_range",
"(",
"vector",
",",
"min_distance",
"=",
"4",
")",
":",
"# http://users.monash.edu.au/~dengs/resource/papers/icme08.pdf",
"# find min and max with mode = wrap",
"mode",
"=",
"\"wrap\"",
"minima",
"=",
"local_minima",
"(",
"vector",
",",
"min_distance",
",",
"mode",
")",
"maxima",
"=",
"local_maxima",
"(",
"vector",
",",
"min_distance",
",",
"mode",
")",
"if",
"len",
"(",
"maxima",
")",
">",
"len",
"(",
"minima",
")",
":",
"if",
"vector",
"[",
"maxima",
"[",
"0",
"]",
"]",
">=",
"vector",
"[",
"maxima",
"[",
"-",
"1",
"]",
"]",
":",
"maxima",
"=",
"maxima",
"[",
"1",
":",
"]",
"else",
":",
"maxima",
"=",
"maxima",
"[",
":",
"-",
"1",
"]",
"if",
"len",
"(",
"maxima",
")",
"==",
"len",
"(",
"minima",
")",
":",
"valley_range",
"=",
"numpy",
".",
"asarray",
"(",
"[",
"minima",
"[",
"ii",
"+",
"1",
"]",
"-",
"minima",
"[",
"ii",
"]",
"for",
"ii",
"in",
"range",
"(",
"len",
"(",
"minima",
")",
"-",
"1",
")",
"]",
"+",
"[",
"len",
"(",
"vector",
")",
"-",
"minima",
"[",
"-",
"1",
"]",
"+",
"minima",
"[",
"0",
"]",
"]",
")",
"if",
"minima",
"[",
"0",
"]",
"<",
"maxima",
"[",
"0",
"]",
":",
"minima",
"=",
"numpy",
".",
"asarray",
"(",
"list",
"(",
"minima",
")",
"+",
"[",
"minima",
"[",
"0",
"]",
"]",
")",
"else",
":",
"minima",
"=",
"numpy",
".",
"asarray",
"(",
"list",
"(",
"minima",
")",
"+",
"[",
"minima",
"[",
"-",
"1",
"]",
"]",
")",
"else",
":",
"valley_range",
"=",
"numpy",
".",
"asarray",
"(",
"[",
"minima",
"[",
"ii",
"+",
"1",
"]",
"-",
"minima",
"[",
"ii",
"]",
"for",
"ii",
"in",
"range",
"(",
"len",
"(",
"maxima",
")",
")",
"]",
")",
"return",
"maxima",
",",
"minima",
",",
"valley_range"
] | Internal finder peaks and valley ranges.
Returns UNSORTED indices of maxima in input vector.
Returns range of valleys before and after maximum | [
"Internal",
"finder",
"peaks",
"and",
"valley",
"ranges",
".",
"Returns",
"UNSORTED",
"indices",
"of",
"maxima",
"in",
"input",
"vector",
".",
"Returns",
"range",
"of",
"valleys",
"before",
"and",
"after",
"maximum"
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/texture.py#L296-L324 | train | 238,151 |
loli/medpy | medpy/filter/smoothing.py | gauss_xminus1d | def gauss_xminus1d(img, sigma, dim=2):
r"""
Applies a X-1D gauss to a copy of a XD image, slicing it along dim.
Essentially uses `scipy.ndimage.filters.gaussian_filter`, but
applies it to a dimension less than the image has.
Parameters
----------
img : array_like
The image to smooth.
sigma : integer
The sigma i.e. gaussian kernel size in pixel
dim : integer
The dimension along which to apply the filter.
Returns
-------
gauss_xminus1d : ndarray
The input image ``img`` smoothed by a gaussian kernel along dimension ``dim``.
"""
img = numpy.array(img, copy=False)
return xminus1d(img, gaussian_filter, dim, sigma=sigma) | python | def gauss_xminus1d(img, sigma, dim=2):
r"""
Applies a X-1D gauss to a copy of a XD image, slicing it along dim.
Essentially uses `scipy.ndimage.filters.gaussian_filter`, but
applies it to a dimension less than the image has.
Parameters
----------
img : array_like
The image to smooth.
sigma : integer
The sigma i.e. gaussian kernel size in pixel
dim : integer
The dimension along which to apply the filter.
Returns
-------
gauss_xminus1d : ndarray
The input image ``img`` smoothed by a gaussian kernel along dimension ``dim``.
"""
img = numpy.array(img, copy=False)
return xminus1d(img, gaussian_filter, dim, sigma=sigma) | [
"def",
"gauss_xminus1d",
"(",
"img",
",",
"sigma",
",",
"dim",
"=",
"2",
")",
":",
"img",
"=",
"numpy",
".",
"array",
"(",
"img",
",",
"copy",
"=",
"False",
")",
"return",
"xminus1d",
"(",
"img",
",",
"gaussian_filter",
",",
"dim",
",",
"sigma",
"=",
"sigma",
")"
] | r"""
Applies a X-1D gauss to a copy of a XD image, slicing it along dim.
Essentially uses `scipy.ndimage.filters.gaussian_filter`, but
applies it to a dimension less than the image has.
Parameters
----------
img : array_like
The image to smooth.
sigma : integer
The sigma i.e. gaussian kernel size in pixel
dim : integer
The dimension along which to apply the filter.
Returns
-------
gauss_xminus1d : ndarray
The input image ``img`` smoothed by a gaussian kernel along dimension ``dim``. | [
"r",
"Applies",
"a",
"X",
"-",
"1D",
"gauss",
"to",
"a",
"copy",
"of",
"a",
"XD",
"image",
"slicing",
"it",
"along",
"dim",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/filter/smoothing.py#L34-L56 | train | 238,152 |
loli/medpy | medpy/filter/smoothing.py | anisotropic_diffusion | def anisotropic_diffusion(img, niter=1, kappa=50, gamma=0.1, voxelspacing=None, option=1):
r"""
Edge-preserving, XD Anisotropic diffusion.
Parameters
----------
img : array_like
Input image (will be cast to numpy.float).
niter : integer
Number of iterations.
kappa : integer
Conduction coefficient, e.g. 20-100. ``kappa`` controls conduction
as a function of the gradient. If ``kappa`` is low small intensity
gradients are able to block conduction and hence diffusion across
steep edges. A large value reduces the influence of intensity gradients
on conduction.
gamma : float
Controls the speed of diffusion. Pick a value :math:`<= .25` for stability.
voxelspacing : tuple of floats or array_like
The distance between adjacent pixels in all img.ndim directions
option : {1, 2, 3}
Whether to use the Perona Malik diffusion equation No. 1 or No. 2,
or Tukey's biweight function.
Equation 1 favours high contrast edges over low contrast ones, while
equation 2 favours wide regions over smaller ones. See [1]_ for details.
Equation 3 preserves sharper boundaries than previous formulations and
improves the automatic stopping of the diffusion. See [2]_ for details.
Returns
-------
anisotropic_diffusion : ndarray
Diffused image.
Notes
-----
Original MATLAB code by Peter Kovesi,
School of Computer Science & Software Engineering,
The University of Western Australia,
pk @ csse uwa edu au,
<http://www.csse.uwa.edu.au>
Translated to Python and optimised by Alistair Muldal,
Department of Pharmacology,
University of Oxford,
<alistair.muldal@pharm.ox.ac.uk>
Adapted to arbitrary dimensionality and added to the MedPy library Oskar Maier,
Institute for Medical Informatics,
Universitaet Luebeck,
<oskar.maier@googlemail.com>
June 2000 original version. -
March 2002 corrected diffusion eqn No 2. -
July 2012 translated to Python -
August 2013 incorporated into MedPy, arbitrary dimensionality -
References
----------
.. [1] P. Perona and J. Malik.
Scale-space and edge detection using ansotropic diffusion.
IEEE Transactions on Pattern Analysis and Machine Intelligence,
12(7):629-639, July 1990.
.. [2] M.J. Black, G. Sapiro, D. Marimont, D. Heeger
Robust anisotropic diffusion.
IEEE Transactions on Image Processing,
7(3):421-432, March 1998.
"""
# define conduction gradients functions
if option == 1:
def condgradient(delta, spacing):
return numpy.exp(-(delta/kappa)**2.)/float(spacing)
elif option == 2:
def condgradient(delta, spacing):
return 1./(1.+(delta/kappa)**2.)/float(spacing)
elif option == 3:
kappa_s = kappa * (2**0.5)
def condgradient(delta, spacing):
top = 0.5*((1.-(delta/kappa_s)**2.)**2.)/float(spacing)
return numpy.where(numpy.abs(delta) <= kappa_s, top, 0)
# initialize output array
out = numpy.array(img, dtype=numpy.float32, copy=True)
# set default voxel spacing if not supplied
if voxelspacing is None:
voxelspacing = tuple([1.] * img.ndim)
# initialize some internal variables
deltas = [numpy.zeros_like(out) for _ in range(out.ndim)]
for _ in range(niter):
# calculate the diffs
for i in range(out.ndim):
slicer = [slice(None, -1) if j == i else slice(None) for j in range(out.ndim)]
deltas[i][slicer] = numpy.diff(out, axis=i)
# update matrices
matrices = [condgradient(delta, spacing) * delta for delta, spacing in zip(deltas, voxelspacing)]
# subtract a copy that has been shifted ('Up/North/West' in 3D case) by one
# pixel. Don't as questions. just do it. trust me.
for i in range(out.ndim):
slicer = [slice(1, None) if j == i else slice(None) for j in range(out.ndim)]
matrices[i][slicer] = numpy.diff(matrices[i], axis=i)
# update the image
out += gamma * (numpy.sum(matrices, axis=0))
return out | python | def anisotropic_diffusion(img, niter=1, kappa=50, gamma=0.1, voxelspacing=None, option=1):
r"""
Edge-preserving, XD Anisotropic diffusion.
Parameters
----------
img : array_like
Input image (will be cast to numpy.float).
niter : integer
Number of iterations.
kappa : integer
Conduction coefficient, e.g. 20-100. ``kappa`` controls conduction
as a function of the gradient. If ``kappa`` is low small intensity
gradients are able to block conduction and hence diffusion across
steep edges. A large value reduces the influence of intensity gradients
on conduction.
gamma : float
Controls the speed of diffusion. Pick a value :math:`<= .25` for stability.
voxelspacing : tuple of floats or array_like
The distance between adjacent pixels in all img.ndim directions
option : {1, 2, 3}
Whether to use the Perona Malik diffusion equation No. 1 or No. 2,
or Tukey's biweight function.
Equation 1 favours high contrast edges over low contrast ones, while
equation 2 favours wide regions over smaller ones. See [1]_ for details.
Equation 3 preserves sharper boundaries than previous formulations and
improves the automatic stopping of the diffusion. See [2]_ for details.
Returns
-------
anisotropic_diffusion : ndarray
Diffused image.
Notes
-----
Original MATLAB code by Peter Kovesi,
School of Computer Science & Software Engineering,
The University of Western Australia,
pk @ csse uwa edu au,
<http://www.csse.uwa.edu.au>
Translated to Python and optimised by Alistair Muldal,
Department of Pharmacology,
University of Oxford,
<alistair.muldal@pharm.ox.ac.uk>
Adapted to arbitrary dimensionality and added to the MedPy library Oskar Maier,
Institute for Medical Informatics,
Universitaet Luebeck,
<oskar.maier@googlemail.com>
June 2000 original version. -
March 2002 corrected diffusion eqn No 2. -
July 2012 translated to Python -
August 2013 incorporated into MedPy, arbitrary dimensionality -
References
----------
.. [1] P. Perona and J. Malik.
Scale-space and edge detection using ansotropic diffusion.
IEEE Transactions on Pattern Analysis and Machine Intelligence,
12(7):629-639, July 1990.
.. [2] M.J. Black, G. Sapiro, D. Marimont, D. Heeger
Robust anisotropic diffusion.
IEEE Transactions on Image Processing,
7(3):421-432, March 1998.
"""
# define conduction gradients functions
if option == 1:
def condgradient(delta, spacing):
return numpy.exp(-(delta/kappa)**2.)/float(spacing)
elif option == 2:
def condgradient(delta, spacing):
return 1./(1.+(delta/kappa)**2.)/float(spacing)
elif option == 3:
kappa_s = kappa * (2**0.5)
def condgradient(delta, spacing):
top = 0.5*((1.-(delta/kappa_s)**2.)**2.)/float(spacing)
return numpy.where(numpy.abs(delta) <= kappa_s, top, 0)
# initialize output array
out = numpy.array(img, dtype=numpy.float32, copy=True)
# set default voxel spacing if not supplied
if voxelspacing is None:
voxelspacing = tuple([1.] * img.ndim)
# initialize some internal variables
deltas = [numpy.zeros_like(out) for _ in range(out.ndim)]
for _ in range(niter):
# calculate the diffs
for i in range(out.ndim):
slicer = [slice(None, -1) if j == i else slice(None) for j in range(out.ndim)]
deltas[i][slicer] = numpy.diff(out, axis=i)
# update matrices
matrices = [condgradient(delta, spacing) * delta for delta, spacing in zip(deltas, voxelspacing)]
# subtract a copy that has been shifted ('Up/North/West' in 3D case) by one
# pixel. Don't as questions. just do it. trust me.
for i in range(out.ndim):
slicer = [slice(1, None) if j == i else slice(None) for j in range(out.ndim)]
matrices[i][slicer] = numpy.diff(matrices[i], axis=i)
# update the image
out += gamma * (numpy.sum(matrices, axis=0))
return out | [
"def",
"anisotropic_diffusion",
"(",
"img",
",",
"niter",
"=",
"1",
",",
"kappa",
"=",
"50",
",",
"gamma",
"=",
"0.1",
",",
"voxelspacing",
"=",
"None",
",",
"option",
"=",
"1",
")",
":",
"# define conduction gradients functions",
"if",
"option",
"==",
"1",
":",
"def",
"condgradient",
"(",
"delta",
",",
"spacing",
")",
":",
"return",
"numpy",
".",
"exp",
"(",
"-",
"(",
"delta",
"/",
"kappa",
")",
"**",
"2.",
")",
"/",
"float",
"(",
"spacing",
")",
"elif",
"option",
"==",
"2",
":",
"def",
"condgradient",
"(",
"delta",
",",
"spacing",
")",
":",
"return",
"1.",
"/",
"(",
"1.",
"+",
"(",
"delta",
"/",
"kappa",
")",
"**",
"2.",
")",
"/",
"float",
"(",
"spacing",
")",
"elif",
"option",
"==",
"3",
":",
"kappa_s",
"=",
"kappa",
"*",
"(",
"2",
"**",
"0.5",
")",
"def",
"condgradient",
"(",
"delta",
",",
"spacing",
")",
":",
"top",
"=",
"0.5",
"*",
"(",
"(",
"1.",
"-",
"(",
"delta",
"/",
"kappa_s",
")",
"**",
"2.",
")",
"**",
"2.",
")",
"/",
"float",
"(",
"spacing",
")",
"return",
"numpy",
".",
"where",
"(",
"numpy",
".",
"abs",
"(",
"delta",
")",
"<=",
"kappa_s",
",",
"top",
",",
"0",
")",
"# initialize output array",
"out",
"=",
"numpy",
".",
"array",
"(",
"img",
",",
"dtype",
"=",
"numpy",
".",
"float32",
",",
"copy",
"=",
"True",
")",
"# set default voxel spacing if not supplied",
"if",
"voxelspacing",
"is",
"None",
":",
"voxelspacing",
"=",
"tuple",
"(",
"[",
"1.",
"]",
"*",
"img",
".",
"ndim",
")",
"# initialize some internal variables",
"deltas",
"=",
"[",
"numpy",
".",
"zeros_like",
"(",
"out",
")",
"for",
"_",
"in",
"range",
"(",
"out",
".",
"ndim",
")",
"]",
"for",
"_",
"in",
"range",
"(",
"niter",
")",
":",
"# calculate the diffs",
"for",
"i",
"in",
"range",
"(",
"out",
".",
"ndim",
")",
":",
"slicer",
"=",
"[",
"slice",
"(",
"None",
",",
"-",
"1",
")",
"if",
"j",
"==",
"i",
"else",
"slice",
"(",
"None",
")",
"for",
"j",
"in",
"range",
"(",
"out",
".",
"ndim",
")",
"]",
"deltas",
"[",
"i",
"]",
"[",
"slicer",
"]",
"=",
"numpy",
".",
"diff",
"(",
"out",
",",
"axis",
"=",
"i",
")",
"# update matrices",
"matrices",
"=",
"[",
"condgradient",
"(",
"delta",
",",
"spacing",
")",
"*",
"delta",
"for",
"delta",
",",
"spacing",
"in",
"zip",
"(",
"deltas",
",",
"voxelspacing",
")",
"]",
"# subtract a copy that has been shifted ('Up/North/West' in 3D case) by one",
"# pixel. Don't as questions. just do it. trust me.",
"for",
"i",
"in",
"range",
"(",
"out",
".",
"ndim",
")",
":",
"slicer",
"=",
"[",
"slice",
"(",
"1",
",",
"None",
")",
"if",
"j",
"==",
"i",
"else",
"slice",
"(",
"None",
")",
"for",
"j",
"in",
"range",
"(",
"out",
".",
"ndim",
")",
"]",
"matrices",
"[",
"i",
"]",
"[",
"slicer",
"]",
"=",
"numpy",
".",
"diff",
"(",
"matrices",
"[",
"i",
"]",
",",
"axis",
"=",
"i",
")",
"# update the image",
"out",
"+=",
"gamma",
"*",
"(",
"numpy",
".",
"sum",
"(",
"matrices",
",",
"axis",
"=",
"0",
")",
")",
"return",
"out"
] | r"""
Edge-preserving, XD Anisotropic diffusion.
Parameters
----------
img : array_like
Input image (will be cast to numpy.float).
niter : integer
Number of iterations.
kappa : integer
Conduction coefficient, e.g. 20-100. ``kappa`` controls conduction
as a function of the gradient. If ``kappa`` is low small intensity
gradients are able to block conduction and hence diffusion across
steep edges. A large value reduces the influence of intensity gradients
on conduction.
gamma : float
Controls the speed of diffusion. Pick a value :math:`<= .25` for stability.
voxelspacing : tuple of floats or array_like
The distance between adjacent pixels in all img.ndim directions
option : {1, 2, 3}
Whether to use the Perona Malik diffusion equation No. 1 or No. 2,
or Tukey's biweight function.
Equation 1 favours high contrast edges over low contrast ones, while
equation 2 favours wide regions over smaller ones. See [1]_ for details.
Equation 3 preserves sharper boundaries than previous formulations and
improves the automatic stopping of the diffusion. See [2]_ for details.
Returns
-------
anisotropic_diffusion : ndarray
Diffused image.
Notes
-----
Original MATLAB code by Peter Kovesi,
School of Computer Science & Software Engineering,
The University of Western Australia,
pk @ csse uwa edu au,
<http://www.csse.uwa.edu.au>
Translated to Python and optimised by Alistair Muldal,
Department of Pharmacology,
University of Oxford,
<alistair.muldal@pharm.ox.ac.uk>
Adapted to arbitrary dimensionality and added to the MedPy library Oskar Maier,
Institute for Medical Informatics,
Universitaet Luebeck,
<oskar.maier@googlemail.com>
June 2000 original version. -
March 2002 corrected diffusion eqn No 2. -
July 2012 translated to Python -
August 2013 incorporated into MedPy, arbitrary dimensionality -
References
----------
.. [1] P. Perona and J. Malik.
Scale-space and edge detection using ansotropic diffusion.
IEEE Transactions on Pattern Analysis and Machine Intelligence,
12(7):629-639, July 1990.
.. [2] M.J. Black, G. Sapiro, D. Marimont, D. Heeger
Robust anisotropic diffusion.
IEEE Transactions on Image Processing,
7(3):421-432, March 1998. | [
"r",
"Edge",
"-",
"preserving",
"XD",
"Anisotropic",
"diffusion",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/filter/smoothing.py#L58-L169 | train | 238,153 |
loli/medpy | medpy/graphcut/generate.py | __voxel_4conectedness | def __voxel_4conectedness(shape):
"""
Returns the number of edges for the supplied image shape assuming 4-connectedness.
The name of the function has historical reasons. Essentially it returns the number
of edges assuming 4-connectedness only for 2D. For 3D it assumes 6-connectedness,
etc.
@param shape the shape of the image
@type shape sequence
@return the number of edges
@rtype int
"""
shape = list(shape)
while 1 in shape: shape.remove(1) # empty resp. 1-sized dimensions have to be removed (equal to scipy.squeeze on the array)
return int(round(sum([(dim - 1)/float(dim) for dim in shape]) * scipy.prod(shape))) | python | def __voxel_4conectedness(shape):
"""
Returns the number of edges for the supplied image shape assuming 4-connectedness.
The name of the function has historical reasons. Essentially it returns the number
of edges assuming 4-connectedness only for 2D. For 3D it assumes 6-connectedness,
etc.
@param shape the shape of the image
@type shape sequence
@return the number of edges
@rtype int
"""
shape = list(shape)
while 1 in shape: shape.remove(1) # empty resp. 1-sized dimensions have to be removed (equal to scipy.squeeze on the array)
return int(round(sum([(dim - 1)/float(dim) for dim in shape]) * scipy.prod(shape))) | [
"def",
"__voxel_4conectedness",
"(",
"shape",
")",
":",
"shape",
"=",
"list",
"(",
"shape",
")",
"while",
"1",
"in",
"shape",
":",
"shape",
".",
"remove",
"(",
"1",
")",
"# empty resp. 1-sized dimensions have to be removed (equal to scipy.squeeze on the array)",
"return",
"int",
"(",
"round",
"(",
"sum",
"(",
"[",
"(",
"dim",
"-",
"1",
")",
"/",
"float",
"(",
"dim",
")",
"for",
"dim",
"in",
"shape",
"]",
")",
"*",
"scipy",
".",
"prod",
"(",
"shape",
")",
")",
")"
] | Returns the number of edges for the supplied image shape assuming 4-connectedness.
The name of the function has historical reasons. Essentially it returns the number
of edges assuming 4-connectedness only for 2D. For 3D it assumes 6-connectedness,
etc.
@param shape the shape of the image
@type shape sequence
@return the number of edges
@rtype int | [
"Returns",
"the",
"number",
"of",
"edges",
"for",
"the",
"supplied",
"image",
"shape",
"assuming",
"4",
"-",
"connectedness",
".",
"The",
"name",
"of",
"the",
"function",
"has",
"historical",
"reasons",
".",
"Essentially",
"it",
"returns",
"the",
"number",
"of",
"edges",
"assuming",
"4",
"-",
"connectedness",
"only",
"for",
"2D",
".",
"For",
"3D",
"it",
"assumes",
"6",
"-",
"connectedness",
"etc",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/graphcut/generate.py#L316-L331 | train | 238,154 |
loli/medpy | medpy/graphcut/energy_voxel.py | __skeleton_base | def __skeleton_base(graph, image, boundary_term, neighbourhood_function, spacing):
"""
Base of the skeleton for voxel based boundary term calculation.
This function holds the low level procedures shared by nearly all boundary terms.
@param graph An initialized graph.GCGraph object
@type graph.GCGraph
@param image The image containing the voxel intensity values
@type image numpy.ndarray
@param boundary_term A function to compute the boundary term over an array of
absolute intensity differences
@type boundary_term function
@param neighbourhood_function A function that takes two arrays of neighbouring pixels
and computes an intensity term from them that is
returned as a single array of the same shape
@type neighbourhood_function function
@param spacing A sequence containing the slice spacing used for weighting the
computed neighbourhood weight value for different dimensions. If
False, no distance based weighting of the graph edges is performed.
@param spacing sequence | False
"""
image = scipy.asarray(image)
image = image.astype(scipy.float_)
# iterate over the image dimensions and for each create the appropriate edges and compute the associated weights
for dim in range(image.ndim):
# construct slice-objects for the current dimension
slices_exclude_last = [slice(None)] * image.ndim
slices_exclude_last[dim] = slice(-1)
slices_exclude_first = [slice(None)] * image.ndim
slices_exclude_first[dim] = slice(1, None)
# compute difference between all layers in the current dimensions direction
neighbourhood_intensity_term = neighbourhood_function(image[slices_exclude_last], image[slices_exclude_first])
# apply boundary term
neighbourhood_intensity_term = boundary_term(neighbourhood_intensity_term)
# compute key offset for relative key difference
offset_key = [1 if i == dim else 0 for i in range(image.ndim)]
offset = __flatten_index(offset_key, image.shape)
# generate index offset function for index dependent offset
idx_offset_divider = (image.shape[dim] - 1) * offset
idx_offset = lambda x: int(x / idx_offset_divider) * offset
# weight the computed distanced in dimension dim by the corresponding slice spacing provided
if spacing: neighbourhood_intensity_term /= spacing[dim]
for key, value in enumerate(neighbourhood_intensity_term.ravel()):
# apply index dependent offset
key += idx_offset(key)
# add edges and set the weight
graph.set_nweight(key, key + offset, value, value) | python | def __skeleton_base(graph, image, boundary_term, neighbourhood_function, spacing):
"""
Base of the skeleton for voxel based boundary term calculation.
This function holds the low level procedures shared by nearly all boundary terms.
@param graph An initialized graph.GCGraph object
@type graph.GCGraph
@param image The image containing the voxel intensity values
@type image numpy.ndarray
@param boundary_term A function to compute the boundary term over an array of
absolute intensity differences
@type boundary_term function
@param neighbourhood_function A function that takes two arrays of neighbouring pixels
and computes an intensity term from them that is
returned as a single array of the same shape
@type neighbourhood_function function
@param spacing A sequence containing the slice spacing used for weighting the
computed neighbourhood weight value for different dimensions. If
False, no distance based weighting of the graph edges is performed.
@param spacing sequence | False
"""
image = scipy.asarray(image)
image = image.astype(scipy.float_)
# iterate over the image dimensions and for each create the appropriate edges and compute the associated weights
for dim in range(image.ndim):
# construct slice-objects for the current dimension
slices_exclude_last = [slice(None)] * image.ndim
slices_exclude_last[dim] = slice(-1)
slices_exclude_first = [slice(None)] * image.ndim
slices_exclude_first[dim] = slice(1, None)
# compute difference between all layers in the current dimensions direction
neighbourhood_intensity_term = neighbourhood_function(image[slices_exclude_last], image[slices_exclude_first])
# apply boundary term
neighbourhood_intensity_term = boundary_term(neighbourhood_intensity_term)
# compute key offset for relative key difference
offset_key = [1 if i == dim else 0 for i in range(image.ndim)]
offset = __flatten_index(offset_key, image.shape)
# generate index offset function for index dependent offset
idx_offset_divider = (image.shape[dim] - 1) * offset
idx_offset = lambda x: int(x / idx_offset_divider) * offset
# weight the computed distanced in dimension dim by the corresponding slice spacing provided
if spacing: neighbourhood_intensity_term /= spacing[dim]
for key, value in enumerate(neighbourhood_intensity_term.ravel()):
# apply index dependent offset
key += idx_offset(key)
# add edges and set the weight
graph.set_nweight(key, key + offset, value, value) | [
"def",
"__skeleton_base",
"(",
"graph",
",",
"image",
",",
"boundary_term",
",",
"neighbourhood_function",
",",
"spacing",
")",
":",
"image",
"=",
"scipy",
".",
"asarray",
"(",
"image",
")",
"image",
"=",
"image",
".",
"astype",
"(",
"scipy",
".",
"float_",
")",
"# iterate over the image dimensions and for each create the appropriate edges and compute the associated weights",
"for",
"dim",
"in",
"range",
"(",
"image",
".",
"ndim",
")",
":",
"# construct slice-objects for the current dimension",
"slices_exclude_last",
"=",
"[",
"slice",
"(",
"None",
")",
"]",
"*",
"image",
".",
"ndim",
"slices_exclude_last",
"[",
"dim",
"]",
"=",
"slice",
"(",
"-",
"1",
")",
"slices_exclude_first",
"=",
"[",
"slice",
"(",
"None",
")",
"]",
"*",
"image",
".",
"ndim",
"slices_exclude_first",
"[",
"dim",
"]",
"=",
"slice",
"(",
"1",
",",
"None",
")",
"# compute difference between all layers in the current dimensions direction",
"neighbourhood_intensity_term",
"=",
"neighbourhood_function",
"(",
"image",
"[",
"slices_exclude_last",
"]",
",",
"image",
"[",
"slices_exclude_first",
"]",
")",
"# apply boundary term",
"neighbourhood_intensity_term",
"=",
"boundary_term",
"(",
"neighbourhood_intensity_term",
")",
"# compute key offset for relative key difference",
"offset_key",
"=",
"[",
"1",
"if",
"i",
"==",
"dim",
"else",
"0",
"for",
"i",
"in",
"range",
"(",
"image",
".",
"ndim",
")",
"]",
"offset",
"=",
"__flatten_index",
"(",
"offset_key",
",",
"image",
".",
"shape",
")",
"# generate index offset function for index dependent offset",
"idx_offset_divider",
"=",
"(",
"image",
".",
"shape",
"[",
"dim",
"]",
"-",
"1",
")",
"*",
"offset",
"idx_offset",
"=",
"lambda",
"x",
":",
"int",
"(",
"x",
"/",
"idx_offset_divider",
")",
"*",
"offset",
"# weight the computed distanced in dimension dim by the corresponding slice spacing provided",
"if",
"spacing",
":",
"neighbourhood_intensity_term",
"/=",
"spacing",
"[",
"dim",
"]",
"for",
"key",
",",
"value",
"in",
"enumerate",
"(",
"neighbourhood_intensity_term",
".",
"ravel",
"(",
")",
")",
":",
"# apply index dependent offset",
"key",
"+=",
"idx_offset",
"(",
"key",
")",
"# add edges and set the weight",
"graph",
".",
"set_nweight",
"(",
"key",
",",
"key",
"+",
"offset",
",",
"value",
",",
"value",
")"
] | Base of the skeleton for voxel based boundary term calculation.
This function holds the low level procedures shared by nearly all boundary terms.
@param graph An initialized graph.GCGraph object
@type graph.GCGraph
@param image The image containing the voxel intensity values
@type image numpy.ndarray
@param boundary_term A function to compute the boundary term over an array of
absolute intensity differences
@type boundary_term function
@param neighbourhood_function A function that takes two arrays of neighbouring pixels
and computes an intensity term from them that is
returned as a single array of the same shape
@type neighbourhood_function function
@param spacing A sequence containing the slice spacing used for weighting the
computed neighbourhood weight value for different dimensions. If
False, no distance based weighting of the graph edges is performed.
@param spacing sequence | False | [
"Base",
"of",
"the",
"skeleton",
"for",
"voxel",
"based",
"boundary",
"term",
"calculation",
".",
"This",
"function",
"holds",
"the",
"low",
"level",
"procedures",
"shared",
"by",
"nearly",
"all",
"boundary",
"terms",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/graphcut/energy_voxel.py#L590-L640 | train | 238,155 |
loli/medpy | medpy/metric/image.py | __range | def __range(a, bins):
'''Compute the histogram range of the values in the array a according to
scipy.stats.histogram.'''
a = numpy.asarray(a)
a_max = a.max()
a_min = a.min()
s = 0.5 * (a_max - a_min) / float(bins - 1)
return (a_min - s, a_max + s) | python | def __range(a, bins):
'''Compute the histogram range of the values in the array a according to
scipy.stats.histogram.'''
a = numpy.asarray(a)
a_max = a.max()
a_min = a.min()
s = 0.5 * (a_max - a_min) / float(bins - 1)
return (a_min - s, a_max + s) | [
"def",
"__range",
"(",
"a",
",",
"bins",
")",
":",
"a",
"=",
"numpy",
".",
"asarray",
"(",
"a",
")",
"a_max",
"=",
"a",
".",
"max",
"(",
")",
"a_min",
"=",
"a",
".",
"min",
"(",
")",
"s",
"=",
"0.5",
"*",
"(",
"a_max",
"-",
"a_min",
")",
"/",
"float",
"(",
"bins",
"-",
"1",
")",
"return",
"(",
"a_min",
"-",
"s",
",",
"a_max",
"+",
"s",
")"
] | Compute the histogram range of the values in the array a according to
scipy.stats.histogram. | [
"Compute",
"the",
"histogram",
"range",
"of",
"the",
"values",
"in",
"the",
"array",
"a",
"according",
"to",
"scipy",
".",
"stats",
".",
"histogram",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/metric/image.py#L103-L110 | train | 238,156 |
loli/medpy | medpy/features/intensity.py | centerdistance | def centerdistance(image, voxelspacing = None, mask = slice(None)):
r"""
Takes a simple or multi-spectral image and returns its voxel-wise center distance in
mm. A multi-spectral image must be supplied as a list or tuple of its spectra.
Optionally a binary mask can be supplied to select the voxels for which the feature
should be extracted.
The center distance is the exact euclidean distance in mm of each voxels center to
the central point of the overal image volume.
Note that this feature is independent of the actual image content, but depends
solely on its shape. Therefore always a one-dimensional feature is returned, even if
a multi-spectral image has been supplied.
Parameters
----------
image : array_like or list/tuple of array_like
A single image or a list/tuple of images (for multi-spectral case).
voxelspacing : sequence of floats
The side-length of each voxel.
mask : array_like
A binary mask for the image.
Returns
-------
centerdistance : ndarray
The distance of each voxel to the images center.
See Also
--------
centerdistance_xdminus1
"""
if type(image) == tuple or type(image) == list:
image = image[0]
return _extract_feature(_extract_centerdistance, image, mask, voxelspacing = voxelspacing) | python | def centerdistance(image, voxelspacing = None, mask = slice(None)):
r"""
Takes a simple or multi-spectral image and returns its voxel-wise center distance in
mm. A multi-spectral image must be supplied as a list or tuple of its spectra.
Optionally a binary mask can be supplied to select the voxels for which the feature
should be extracted.
The center distance is the exact euclidean distance in mm of each voxels center to
the central point of the overal image volume.
Note that this feature is independent of the actual image content, but depends
solely on its shape. Therefore always a one-dimensional feature is returned, even if
a multi-spectral image has been supplied.
Parameters
----------
image : array_like or list/tuple of array_like
A single image or a list/tuple of images (for multi-spectral case).
voxelspacing : sequence of floats
The side-length of each voxel.
mask : array_like
A binary mask for the image.
Returns
-------
centerdistance : ndarray
The distance of each voxel to the images center.
See Also
--------
centerdistance_xdminus1
"""
if type(image) == tuple or type(image) == list:
image = image[0]
return _extract_feature(_extract_centerdistance, image, mask, voxelspacing = voxelspacing) | [
"def",
"centerdistance",
"(",
"image",
",",
"voxelspacing",
"=",
"None",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
")",
":",
"if",
"type",
"(",
"image",
")",
"==",
"tuple",
"or",
"type",
"(",
"image",
")",
"==",
"list",
":",
"image",
"=",
"image",
"[",
"0",
"]",
"return",
"_extract_feature",
"(",
"_extract_centerdistance",
",",
"image",
",",
"mask",
",",
"voxelspacing",
"=",
"voxelspacing",
")"
] | r"""
Takes a simple or multi-spectral image and returns its voxel-wise center distance in
mm. A multi-spectral image must be supplied as a list or tuple of its spectra.
Optionally a binary mask can be supplied to select the voxels for which the feature
should be extracted.
The center distance is the exact euclidean distance in mm of each voxels center to
the central point of the overal image volume.
Note that this feature is independent of the actual image content, but depends
solely on its shape. Therefore always a one-dimensional feature is returned, even if
a multi-spectral image has been supplied.
Parameters
----------
image : array_like or list/tuple of array_like
A single image or a list/tuple of images (for multi-spectral case).
voxelspacing : sequence of floats
The side-length of each voxel.
mask : array_like
A binary mask for the image.
Returns
-------
centerdistance : ndarray
The distance of each voxel to the images center.
See Also
--------
centerdistance_xdminus1 | [
"r",
"Takes",
"a",
"simple",
"or",
"multi",
"-",
"spectral",
"image",
"and",
"returns",
"its",
"voxel",
"-",
"wise",
"center",
"distance",
"in",
"mm",
".",
"A",
"multi",
"-",
"spectral",
"image",
"must",
"be",
"supplied",
"as",
"a",
"list",
"or",
"tuple",
"of",
"its",
"spectra",
".",
"Optionally",
"a",
"binary",
"mask",
"can",
"be",
"supplied",
"to",
"select",
"the",
"voxels",
"for",
"which",
"the",
"feature",
"should",
"be",
"extracted",
".",
"The",
"center",
"distance",
"is",
"the",
"exact",
"euclidean",
"distance",
"in",
"mm",
"of",
"each",
"voxels",
"center",
"to",
"the",
"central",
"point",
"of",
"the",
"overal",
"image",
"volume",
".",
"Note",
"that",
"this",
"feature",
"is",
"independent",
"of",
"the",
"actual",
"image",
"content",
"but",
"depends",
"solely",
"on",
"its",
"shape",
".",
"Therefore",
"always",
"a",
"one",
"-",
"dimensional",
"feature",
"is",
"returned",
"even",
"if",
"a",
"multi",
"-",
"spectral",
"image",
"has",
"been",
"supplied",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L59-L96 | train | 238,157 |
loli/medpy | medpy/features/intensity.py | mask_distance | def mask_distance(image, voxelspacing = None, mask = slice(None)):
r"""
Computes the distance of each point under the mask to the mask border taking the
voxel-spacing into account.
Note that this feature is independent of the actual image content, but depends
solely the mask image. Therefore always a one-dimensional feature is returned,
even if a multi-spectral image has been supplied.
If no mask has been supplied, the distances to the image borders are returned.
Parameters
----------
image : array_like or list/tuple of array_like
A single image or a list/tuple of images (for multi-spectral case).
voxelspacing : sequence of floats
The side-length of each voxel.
mask : array_like
A binary mask for the image.
Returns
-------
mask_distance : ndarray
Each voxels distance to the mask borders.
"""
if type(image) == tuple or type(image) == list:
image = image[0]
return _extract_mask_distance(image, mask = mask, voxelspacing = voxelspacing) | python | def mask_distance(image, voxelspacing = None, mask = slice(None)):
r"""
Computes the distance of each point under the mask to the mask border taking the
voxel-spacing into account.
Note that this feature is independent of the actual image content, but depends
solely the mask image. Therefore always a one-dimensional feature is returned,
even if a multi-spectral image has been supplied.
If no mask has been supplied, the distances to the image borders are returned.
Parameters
----------
image : array_like or list/tuple of array_like
A single image or a list/tuple of images (for multi-spectral case).
voxelspacing : sequence of floats
The side-length of each voxel.
mask : array_like
A binary mask for the image.
Returns
-------
mask_distance : ndarray
Each voxels distance to the mask borders.
"""
if type(image) == tuple or type(image) == list:
image = image[0]
return _extract_mask_distance(image, mask = mask, voxelspacing = voxelspacing) | [
"def",
"mask_distance",
"(",
"image",
",",
"voxelspacing",
"=",
"None",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
")",
":",
"if",
"type",
"(",
"image",
")",
"==",
"tuple",
"or",
"type",
"(",
"image",
")",
"==",
"list",
":",
"image",
"=",
"image",
"[",
"0",
"]",
"return",
"_extract_mask_distance",
"(",
"image",
",",
"mask",
"=",
"mask",
",",
"voxelspacing",
"=",
"voxelspacing",
")"
] | r"""
Computes the distance of each point under the mask to the mask border taking the
voxel-spacing into account.
Note that this feature is independent of the actual image content, but depends
solely the mask image. Therefore always a one-dimensional feature is returned,
even if a multi-spectral image has been supplied.
If no mask has been supplied, the distances to the image borders are returned.
Parameters
----------
image : array_like or list/tuple of array_like
A single image or a list/tuple of images (for multi-spectral case).
voxelspacing : sequence of floats
The side-length of each voxel.
mask : array_like
A binary mask for the image.
Returns
-------
mask_distance : ndarray
Each voxels distance to the mask borders. | [
"r",
"Computes",
"the",
"distance",
"of",
"each",
"point",
"under",
"the",
"mask",
"to",
"the",
"mask",
"border",
"taking",
"the",
"voxel",
"-",
"spacing",
"into",
"account",
".",
"Note",
"that",
"this",
"feature",
"is",
"independent",
"of",
"the",
"actual",
"image",
"content",
"but",
"depends",
"solely",
"the",
"mask",
"image",
".",
"Therefore",
"always",
"a",
"one",
"-",
"dimensional",
"feature",
"is",
"returned",
"even",
"if",
"a",
"multi",
"-",
"spectral",
"image",
"has",
"been",
"supplied",
".",
"If",
"no",
"mask",
"has",
"been",
"supplied",
"the",
"distances",
"to",
"the",
"image",
"borders",
"are",
"returned",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L246-L275 | train | 238,158 |
loli/medpy | medpy/features/intensity.py | _extract_hemispheric_difference | def _extract_hemispheric_difference(image, mask = slice(None), sigma_active = 7, sigma_reference = 7, cut_plane = 0, voxelspacing = None):
"""
Internal, single-image version of `hemispheric_difference`.
"""
# constants
INTERPOLATION_RANGE = int(10) # how many neighbouring values to take into account when interpolating the medial longitudinal fissure slice
# check arguments
if cut_plane >= image.ndim:
raise ArgumentError('The suppliedc cut-plane ({}) is invalid, the image has only {} dimensions.'.format(cut_plane, image.ndim))
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# compute the (presumed) location of the medial longitudinal fissure, treating also the special of an odd number of slices, in which case a cut into two equal halves is not possible
medial_longitudinal_fissure = int(image.shape[cut_plane] / 2)
medial_longitudinal_fissure_excluded = image.shape[cut_plane] % 2
# split the head into a dexter and sinister half along the saggital plane
# this is assumed to be consistent with a cut of the brain along the medial longitudinal fissure, thus separating it into its hemispheres
slicer = [slice(None)] * image.ndim
slicer[cut_plane] = slice(None, medial_longitudinal_fissure)
left_hemisphere = image[slicer]
slicer[cut_plane] = slice(medial_longitudinal_fissure + medial_longitudinal_fissure_excluded, None)
right_hemisphere = image[slicer]
# flip right hemisphere image along cut plane
slicer[cut_plane] = slice(None, None, -1)
right_hemisphere = right_hemisphere[slicer]
# substract once left from right and once right from left hemisphere, including smoothing steps
right_hemisphere_difference = _substract_hemispheres(right_hemisphere, left_hemisphere, sigma_active, sigma_reference, voxelspacing)
left_hemisphere_difference = _substract_hemispheres(left_hemisphere, right_hemisphere, sigma_active, sigma_reference, voxelspacing)
# re-flip right hemisphere image to original orientation
right_hemisphere_difference = right_hemisphere_difference[slicer]
# estimate the medial longitudinal fissure if required
if 1 == medial_longitudinal_fissure_excluded:
left_slicer = [slice(None)] * image.ndim
right_slicer = [slice(None)] * image.ndim
left_slicer[cut_plane] = slice(-1 * INTERPOLATION_RANGE, None)
right_slicer[cut_plane] = slice(None, INTERPOLATION_RANGE)
interp_data_left = left_hemisphere_difference[left_slicer]
interp_data_right = right_hemisphere_difference[right_slicer]
interp_indices_left = list(range(-1 * interp_data_left.shape[cut_plane], 0))
interp_indices_right = list(range(1, interp_data_right.shape[cut_plane] + 1))
interp_data = numpy.concatenate((left_hemisphere_difference[left_slicer], right_hemisphere_difference[right_slicer]), cut_plane)
interp_indices = numpy.concatenate((interp_indices_left, interp_indices_right), 0)
medial_longitudinal_fissure_estimated = interp1d(interp_indices, interp_data, kind='cubic', axis=cut_plane)(0)
# add singleton dimension
slicer[cut_plane] = numpy.newaxis
medial_longitudinal_fissure_estimated = medial_longitudinal_fissure_estimated[slicer]
# stich images back together
if 1 == medial_longitudinal_fissure_excluded:
hemisphere_difference = numpy.concatenate((left_hemisphere_difference, medial_longitudinal_fissure_estimated, right_hemisphere_difference), cut_plane)
else:
hemisphere_difference = numpy.concatenate((left_hemisphere_difference, right_hemisphere_difference), cut_plane)
# extract intensities and return
return _extract_intensities(hemisphere_difference, mask) | python | def _extract_hemispheric_difference(image, mask = slice(None), sigma_active = 7, sigma_reference = 7, cut_plane = 0, voxelspacing = None):
"""
Internal, single-image version of `hemispheric_difference`.
"""
# constants
INTERPOLATION_RANGE = int(10) # how many neighbouring values to take into account when interpolating the medial longitudinal fissure slice
# check arguments
if cut_plane >= image.ndim:
raise ArgumentError('The suppliedc cut-plane ({}) is invalid, the image has only {} dimensions.'.format(cut_plane, image.ndim))
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# compute the (presumed) location of the medial longitudinal fissure, treating also the special of an odd number of slices, in which case a cut into two equal halves is not possible
medial_longitudinal_fissure = int(image.shape[cut_plane] / 2)
medial_longitudinal_fissure_excluded = image.shape[cut_plane] % 2
# split the head into a dexter and sinister half along the saggital plane
# this is assumed to be consistent with a cut of the brain along the medial longitudinal fissure, thus separating it into its hemispheres
slicer = [slice(None)] * image.ndim
slicer[cut_plane] = slice(None, medial_longitudinal_fissure)
left_hemisphere = image[slicer]
slicer[cut_plane] = slice(medial_longitudinal_fissure + medial_longitudinal_fissure_excluded, None)
right_hemisphere = image[slicer]
# flip right hemisphere image along cut plane
slicer[cut_plane] = slice(None, None, -1)
right_hemisphere = right_hemisphere[slicer]
# substract once left from right and once right from left hemisphere, including smoothing steps
right_hemisphere_difference = _substract_hemispheres(right_hemisphere, left_hemisphere, sigma_active, sigma_reference, voxelspacing)
left_hemisphere_difference = _substract_hemispheres(left_hemisphere, right_hemisphere, sigma_active, sigma_reference, voxelspacing)
# re-flip right hemisphere image to original orientation
right_hemisphere_difference = right_hemisphere_difference[slicer]
# estimate the medial longitudinal fissure if required
if 1 == medial_longitudinal_fissure_excluded:
left_slicer = [slice(None)] * image.ndim
right_slicer = [slice(None)] * image.ndim
left_slicer[cut_plane] = slice(-1 * INTERPOLATION_RANGE, None)
right_slicer[cut_plane] = slice(None, INTERPOLATION_RANGE)
interp_data_left = left_hemisphere_difference[left_slicer]
interp_data_right = right_hemisphere_difference[right_slicer]
interp_indices_left = list(range(-1 * interp_data_left.shape[cut_plane], 0))
interp_indices_right = list(range(1, interp_data_right.shape[cut_plane] + 1))
interp_data = numpy.concatenate((left_hemisphere_difference[left_slicer], right_hemisphere_difference[right_slicer]), cut_plane)
interp_indices = numpy.concatenate((interp_indices_left, interp_indices_right), 0)
medial_longitudinal_fissure_estimated = interp1d(interp_indices, interp_data, kind='cubic', axis=cut_plane)(0)
# add singleton dimension
slicer[cut_plane] = numpy.newaxis
medial_longitudinal_fissure_estimated = medial_longitudinal_fissure_estimated[slicer]
# stich images back together
if 1 == medial_longitudinal_fissure_excluded:
hemisphere_difference = numpy.concatenate((left_hemisphere_difference, medial_longitudinal_fissure_estimated, right_hemisphere_difference), cut_plane)
else:
hemisphere_difference = numpy.concatenate((left_hemisphere_difference, right_hemisphere_difference), cut_plane)
# extract intensities and return
return _extract_intensities(hemisphere_difference, mask) | [
"def",
"_extract_hemispheric_difference",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
",",
"sigma_active",
"=",
"7",
",",
"sigma_reference",
"=",
"7",
",",
"cut_plane",
"=",
"0",
",",
"voxelspacing",
"=",
"None",
")",
":",
"# constants",
"INTERPOLATION_RANGE",
"=",
"int",
"(",
"10",
")",
"# how many neighbouring values to take into account when interpolating the medial longitudinal fissure slice",
"# check arguments",
"if",
"cut_plane",
">=",
"image",
".",
"ndim",
":",
"raise",
"ArgumentError",
"(",
"'The suppliedc cut-plane ({}) is invalid, the image has only {} dimensions.'",
".",
"format",
"(",
"cut_plane",
",",
"image",
".",
"ndim",
")",
")",
"# set voxel spacing",
"if",
"voxelspacing",
"is",
"None",
":",
"voxelspacing",
"=",
"[",
"1.",
"]",
"*",
"image",
".",
"ndim",
"# compute the (presumed) location of the medial longitudinal fissure, treating also the special of an odd number of slices, in which case a cut into two equal halves is not possible",
"medial_longitudinal_fissure",
"=",
"int",
"(",
"image",
".",
"shape",
"[",
"cut_plane",
"]",
"/",
"2",
")",
"medial_longitudinal_fissure_excluded",
"=",
"image",
".",
"shape",
"[",
"cut_plane",
"]",
"%",
"2",
"# split the head into a dexter and sinister half along the saggital plane",
"# this is assumed to be consistent with a cut of the brain along the medial longitudinal fissure, thus separating it into its hemispheres",
"slicer",
"=",
"[",
"slice",
"(",
"None",
")",
"]",
"*",
"image",
".",
"ndim",
"slicer",
"[",
"cut_plane",
"]",
"=",
"slice",
"(",
"None",
",",
"medial_longitudinal_fissure",
")",
"left_hemisphere",
"=",
"image",
"[",
"slicer",
"]",
"slicer",
"[",
"cut_plane",
"]",
"=",
"slice",
"(",
"medial_longitudinal_fissure",
"+",
"medial_longitudinal_fissure_excluded",
",",
"None",
")",
"right_hemisphere",
"=",
"image",
"[",
"slicer",
"]",
"# flip right hemisphere image along cut plane",
"slicer",
"[",
"cut_plane",
"]",
"=",
"slice",
"(",
"None",
",",
"None",
",",
"-",
"1",
")",
"right_hemisphere",
"=",
"right_hemisphere",
"[",
"slicer",
"]",
"# substract once left from right and once right from left hemisphere, including smoothing steps",
"right_hemisphere_difference",
"=",
"_substract_hemispheres",
"(",
"right_hemisphere",
",",
"left_hemisphere",
",",
"sigma_active",
",",
"sigma_reference",
",",
"voxelspacing",
")",
"left_hemisphere_difference",
"=",
"_substract_hemispheres",
"(",
"left_hemisphere",
",",
"right_hemisphere",
",",
"sigma_active",
",",
"sigma_reference",
",",
"voxelspacing",
")",
"# re-flip right hemisphere image to original orientation",
"right_hemisphere_difference",
"=",
"right_hemisphere_difference",
"[",
"slicer",
"]",
"# estimate the medial longitudinal fissure if required",
"if",
"1",
"==",
"medial_longitudinal_fissure_excluded",
":",
"left_slicer",
"=",
"[",
"slice",
"(",
"None",
")",
"]",
"*",
"image",
".",
"ndim",
"right_slicer",
"=",
"[",
"slice",
"(",
"None",
")",
"]",
"*",
"image",
".",
"ndim",
"left_slicer",
"[",
"cut_plane",
"]",
"=",
"slice",
"(",
"-",
"1",
"*",
"INTERPOLATION_RANGE",
",",
"None",
")",
"right_slicer",
"[",
"cut_plane",
"]",
"=",
"slice",
"(",
"None",
",",
"INTERPOLATION_RANGE",
")",
"interp_data_left",
"=",
"left_hemisphere_difference",
"[",
"left_slicer",
"]",
"interp_data_right",
"=",
"right_hemisphere_difference",
"[",
"right_slicer",
"]",
"interp_indices_left",
"=",
"list",
"(",
"range",
"(",
"-",
"1",
"*",
"interp_data_left",
".",
"shape",
"[",
"cut_plane",
"]",
",",
"0",
")",
")",
"interp_indices_right",
"=",
"list",
"(",
"range",
"(",
"1",
",",
"interp_data_right",
".",
"shape",
"[",
"cut_plane",
"]",
"+",
"1",
")",
")",
"interp_data",
"=",
"numpy",
".",
"concatenate",
"(",
"(",
"left_hemisphere_difference",
"[",
"left_slicer",
"]",
",",
"right_hemisphere_difference",
"[",
"right_slicer",
"]",
")",
",",
"cut_plane",
")",
"interp_indices",
"=",
"numpy",
".",
"concatenate",
"(",
"(",
"interp_indices_left",
",",
"interp_indices_right",
")",
",",
"0",
")",
"medial_longitudinal_fissure_estimated",
"=",
"interp1d",
"(",
"interp_indices",
",",
"interp_data",
",",
"kind",
"=",
"'cubic'",
",",
"axis",
"=",
"cut_plane",
")",
"(",
"0",
")",
"# add singleton dimension",
"slicer",
"[",
"cut_plane",
"]",
"=",
"numpy",
".",
"newaxis",
"medial_longitudinal_fissure_estimated",
"=",
"medial_longitudinal_fissure_estimated",
"[",
"slicer",
"]",
"# stich images back together",
"if",
"1",
"==",
"medial_longitudinal_fissure_excluded",
":",
"hemisphere_difference",
"=",
"numpy",
".",
"concatenate",
"(",
"(",
"left_hemisphere_difference",
",",
"medial_longitudinal_fissure_estimated",
",",
"right_hemisphere_difference",
")",
",",
"cut_plane",
")",
"else",
":",
"hemisphere_difference",
"=",
"numpy",
".",
"concatenate",
"(",
"(",
"left_hemisphere_difference",
",",
"right_hemisphere_difference",
")",
",",
"cut_plane",
")",
"# extract intensities and return",
"return",
"_extract_intensities",
"(",
"hemisphere_difference",
",",
"mask",
")"
] | Internal, single-image version of `hemispheric_difference`. | [
"Internal",
"single",
"-",
"image",
"version",
"of",
"hemispheric_difference",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L522-L585 | train | 238,159 |
loli/medpy | medpy/features/intensity.py | _extract_local_histogram | def _extract_local_histogram(image, mask=slice(None), bins=19, rang="image", cutoffp=(0.0, 100.0), size=None, footprint=None, output=None, mode="ignore", origin=0):
"""
Internal, single-image version of @see local_histogram
Note: Values outside of the histograms range are not considered.
Note: Mode constant is not available, instead a mode "ignore" is provided.
Note: Default dtype of returned values is float.
"""
if "constant" == mode:
raise RuntimeError('boundary mode not supported')
elif "ignore" == mode:
mode = "constant"
if 'image' == rang:
rang = tuple(numpy.percentile(image[mask], cutoffp))
elif not 2 == len(rang):
raise RuntimeError('the rang must contain exactly two elements or the string "image"')
_, bin_edges = numpy.histogram([], bins=bins, range=rang)
output = _get_output(numpy.float if None == output else output, image, shape = [bins] + list(image.shape))
# threshold the image into the histogram bins represented by the output images first dimension, treat last bin separately, since upper border is inclusive
for i in range(bins - 1):
output[i] = (image >= bin_edges[i]) & (image < bin_edges[i + 1])
output[-1] = (image >= bin_edges[-2]) & (image <= bin_edges[-1])
# apply the sum filter to each dimension, then normalize by dividing through the sum of elements in the bins of each histogram
for i in range(bins):
output[i] = sum_filter(output[i], size=size, footprint=footprint, output=None, mode=mode, cval=0.0, origin=origin)
divident = numpy.sum(output, 0)
divident[0 == divident] = 1
output /= divident
# Notes on modes:
# mode=constant with a cval outside histogram range for the histogram equals a mode=constant with a cval = 0 for the sum_filter
# mode=constant with a cval inside histogram range for the histogram has no equal for the sum_filter (and does not make much sense)
# mode=X for the histogram equals mode=X for the sum_filter
# treat as multi-spectral image which intensities to extracted
return _extract_feature(_extract_intensities, [h for h in output], mask) | python | def _extract_local_histogram(image, mask=slice(None), bins=19, rang="image", cutoffp=(0.0, 100.0), size=None, footprint=None, output=None, mode="ignore", origin=0):
"""
Internal, single-image version of @see local_histogram
Note: Values outside of the histograms range are not considered.
Note: Mode constant is not available, instead a mode "ignore" is provided.
Note: Default dtype of returned values is float.
"""
if "constant" == mode:
raise RuntimeError('boundary mode not supported')
elif "ignore" == mode:
mode = "constant"
if 'image' == rang:
rang = tuple(numpy.percentile(image[mask], cutoffp))
elif not 2 == len(rang):
raise RuntimeError('the rang must contain exactly two elements or the string "image"')
_, bin_edges = numpy.histogram([], bins=bins, range=rang)
output = _get_output(numpy.float if None == output else output, image, shape = [bins] + list(image.shape))
# threshold the image into the histogram bins represented by the output images first dimension, treat last bin separately, since upper border is inclusive
for i in range(bins - 1):
output[i] = (image >= bin_edges[i]) & (image < bin_edges[i + 1])
output[-1] = (image >= bin_edges[-2]) & (image <= bin_edges[-1])
# apply the sum filter to each dimension, then normalize by dividing through the sum of elements in the bins of each histogram
for i in range(bins):
output[i] = sum_filter(output[i], size=size, footprint=footprint, output=None, mode=mode, cval=0.0, origin=origin)
divident = numpy.sum(output, 0)
divident[0 == divident] = 1
output /= divident
# Notes on modes:
# mode=constant with a cval outside histogram range for the histogram equals a mode=constant with a cval = 0 for the sum_filter
# mode=constant with a cval inside histogram range for the histogram has no equal for the sum_filter (and does not make much sense)
# mode=X for the histogram equals mode=X for the sum_filter
# treat as multi-spectral image which intensities to extracted
return _extract_feature(_extract_intensities, [h for h in output], mask) | [
"def",
"_extract_local_histogram",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
",",
"bins",
"=",
"19",
",",
"rang",
"=",
"\"image\"",
",",
"cutoffp",
"=",
"(",
"0.0",
",",
"100.0",
")",
",",
"size",
"=",
"None",
",",
"footprint",
"=",
"None",
",",
"output",
"=",
"None",
",",
"mode",
"=",
"\"ignore\"",
",",
"origin",
"=",
"0",
")",
":",
"if",
"\"constant\"",
"==",
"mode",
":",
"raise",
"RuntimeError",
"(",
"'boundary mode not supported'",
")",
"elif",
"\"ignore\"",
"==",
"mode",
":",
"mode",
"=",
"\"constant\"",
"if",
"'image'",
"==",
"rang",
":",
"rang",
"=",
"tuple",
"(",
"numpy",
".",
"percentile",
"(",
"image",
"[",
"mask",
"]",
",",
"cutoffp",
")",
")",
"elif",
"not",
"2",
"==",
"len",
"(",
"rang",
")",
":",
"raise",
"RuntimeError",
"(",
"'the rang must contain exactly two elements or the string \"image\"'",
")",
"_",
",",
"bin_edges",
"=",
"numpy",
".",
"histogram",
"(",
"[",
"]",
",",
"bins",
"=",
"bins",
",",
"range",
"=",
"rang",
")",
"output",
"=",
"_get_output",
"(",
"numpy",
".",
"float",
"if",
"None",
"==",
"output",
"else",
"output",
",",
"image",
",",
"shape",
"=",
"[",
"bins",
"]",
"+",
"list",
"(",
"image",
".",
"shape",
")",
")",
"# threshold the image into the histogram bins represented by the output images first dimension, treat last bin separately, since upper border is inclusive",
"for",
"i",
"in",
"range",
"(",
"bins",
"-",
"1",
")",
":",
"output",
"[",
"i",
"]",
"=",
"(",
"image",
">=",
"bin_edges",
"[",
"i",
"]",
")",
"&",
"(",
"image",
"<",
"bin_edges",
"[",
"i",
"+",
"1",
"]",
")",
"output",
"[",
"-",
"1",
"]",
"=",
"(",
"image",
">=",
"bin_edges",
"[",
"-",
"2",
"]",
")",
"&",
"(",
"image",
"<=",
"bin_edges",
"[",
"-",
"1",
"]",
")",
"# apply the sum filter to each dimension, then normalize by dividing through the sum of elements in the bins of each histogram",
"for",
"i",
"in",
"range",
"(",
"bins",
")",
":",
"output",
"[",
"i",
"]",
"=",
"sum_filter",
"(",
"output",
"[",
"i",
"]",
",",
"size",
"=",
"size",
",",
"footprint",
"=",
"footprint",
",",
"output",
"=",
"None",
",",
"mode",
"=",
"mode",
",",
"cval",
"=",
"0.0",
",",
"origin",
"=",
"origin",
")",
"divident",
"=",
"numpy",
".",
"sum",
"(",
"output",
",",
"0",
")",
"divident",
"[",
"0",
"==",
"divident",
"]",
"=",
"1",
"output",
"/=",
"divident",
"# Notes on modes:",
"# mode=constant with a cval outside histogram range for the histogram equals a mode=constant with a cval = 0 for the sum_filter",
"# mode=constant with a cval inside histogram range for the histogram has no equal for the sum_filter (and does not make much sense)",
"# mode=X for the histogram equals mode=X for the sum_filter",
"# treat as multi-spectral image which intensities to extracted",
"return",
"_extract_feature",
"(",
"_extract_intensities",
",",
"[",
"h",
"for",
"h",
"in",
"output",
"]",
",",
"mask",
")"
] | Internal, single-image version of @see local_histogram
Note: Values outside of the histograms range are not considered.
Note: Mode constant is not available, instead a mode "ignore" is provided.
Note: Default dtype of returned values is float. | [
"Internal",
"single",
"-",
"image",
"version",
"of"
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L587-L625 | train | 238,160 |
loli/medpy | medpy/features/intensity.py | _extract_median | def _extract_median(image, mask = slice(None), size = 1, voxelspacing = None):
"""
Internal, single-image version of `median`.
"""
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# determine structure element size in voxel units
size = _create_structure_array(size, voxelspacing)
return _extract_intensities(median_filter(image, size), mask) | python | def _extract_median(image, mask = slice(None), size = 1, voxelspacing = None):
"""
Internal, single-image version of `median`.
"""
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# determine structure element size in voxel units
size = _create_structure_array(size, voxelspacing)
return _extract_intensities(median_filter(image, size), mask) | [
"def",
"_extract_median",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
",",
"size",
"=",
"1",
",",
"voxelspacing",
"=",
"None",
")",
":",
"# set voxel spacing",
"if",
"voxelspacing",
"is",
"None",
":",
"voxelspacing",
"=",
"[",
"1.",
"]",
"*",
"image",
".",
"ndim",
"# determine structure element size in voxel units",
"size",
"=",
"_create_structure_array",
"(",
"size",
",",
"voxelspacing",
")",
"return",
"_extract_intensities",
"(",
"median_filter",
"(",
"image",
",",
"size",
")",
",",
"mask",
")"
] | Internal, single-image version of `median`. | [
"Internal",
"single",
"-",
"image",
"version",
"of",
"median",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L627-L638 | train | 238,161 |
loli/medpy | medpy/features/intensity.py | _extract_gaussian_gradient_magnitude | def _extract_gaussian_gradient_magnitude(image, mask = slice(None), sigma = 1, voxelspacing = None):
"""
Internal, single-image version of `gaussian_gradient_magnitude`.
"""
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# determine gaussian kernel size in voxel units
sigma = _create_structure_array(sigma, voxelspacing)
return _extract_intensities(scipy_gaussian_gradient_magnitude(image, sigma), mask) | python | def _extract_gaussian_gradient_magnitude(image, mask = slice(None), sigma = 1, voxelspacing = None):
"""
Internal, single-image version of `gaussian_gradient_magnitude`.
"""
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# determine gaussian kernel size in voxel units
sigma = _create_structure_array(sigma, voxelspacing)
return _extract_intensities(scipy_gaussian_gradient_magnitude(image, sigma), mask) | [
"def",
"_extract_gaussian_gradient_magnitude",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
",",
"sigma",
"=",
"1",
",",
"voxelspacing",
"=",
"None",
")",
":",
"# set voxel spacing",
"if",
"voxelspacing",
"is",
"None",
":",
"voxelspacing",
"=",
"[",
"1.",
"]",
"*",
"image",
".",
"ndim",
"# determine gaussian kernel size in voxel units",
"sigma",
"=",
"_create_structure_array",
"(",
"sigma",
",",
"voxelspacing",
")",
"return",
"_extract_intensities",
"(",
"scipy_gaussian_gradient_magnitude",
"(",
"image",
",",
"sigma",
")",
",",
"mask",
")"
] | Internal, single-image version of `gaussian_gradient_magnitude`. | [
"Internal",
"single",
"-",
"image",
"version",
"of",
"gaussian_gradient_magnitude",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L640-L651 | train | 238,162 |
loli/medpy | medpy/features/intensity.py | _extract_shifted_mean_gauss | def _extract_shifted_mean_gauss(image, mask = slice(None), offset = None, sigma = 1, voxelspacing = None):
"""
Internal, single-image version of `shifted_mean_gauss`.
"""
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# set offset
if offset is None:
offset = [0] * image.ndim
# determine gaussian kernel size in voxel units
sigma = _create_structure_array(sigma, voxelspacing)
# compute smoothed version of image
smoothed = gaussian_filter(image, sigma)
shifted = numpy.zeros_like(smoothed)
in_slicer = []
out_slicer = []
for o in offset:
in_slicer.append(slice(o, None))
out_slicer.append(slice(None, -1 * o))
shifted[out_slicer] = smoothed[in_slicer]
return _extract_intensities(shifted, mask) | python | def _extract_shifted_mean_gauss(image, mask = slice(None), offset = None, sigma = 1, voxelspacing = None):
"""
Internal, single-image version of `shifted_mean_gauss`.
"""
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# set offset
if offset is None:
offset = [0] * image.ndim
# determine gaussian kernel size in voxel units
sigma = _create_structure_array(sigma, voxelspacing)
# compute smoothed version of image
smoothed = gaussian_filter(image, sigma)
shifted = numpy.zeros_like(smoothed)
in_slicer = []
out_slicer = []
for o in offset:
in_slicer.append(slice(o, None))
out_slicer.append(slice(None, -1 * o))
shifted[out_slicer] = smoothed[in_slicer]
return _extract_intensities(shifted, mask) | [
"def",
"_extract_shifted_mean_gauss",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
",",
"offset",
"=",
"None",
",",
"sigma",
"=",
"1",
",",
"voxelspacing",
"=",
"None",
")",
":",
"# set voxel spacing",
"if",
"voxelspacing",
"is",
"None",
":",
"voxelspacing",
"=",
"[",
"1.",
"]",
"*",
"image",
".",
"ndim",
"# set offset",
"if",
"offset",
"is",
"None",
":",
"offset",
"=",
"[",
"0",
"]",
"*",
"image",
".",
"ndim",
"# determine gaussian kernel size in voxel units",
"sigma",
"=",
"_create_structure_array",
"(",
"sigma",
",",
"voxelspacing",
")",
"# compute smoothed version of image",
"smoothed",
"=",
"gaussian_filter",
"(",
"image",
",",
"sigma",
")",
"shifted",
"=",
"numpy",
".",
"zeros_like",
"(",
"smoothed",
")",
"in_slicer",
"=",
"[",
"]",
"out_slicer",
"=",
"[",
"]",
"for",
"o",
"in",
"offset",
":",
"in_slicer",
".",
"append",
"(",
"slice",
"(",
"o",
",",
"None",
")",
")",
"out_slicer",
".",
"append",
"(",
"slice",
"(",
"None",
",",
"-",
"1",
"*",
"o",
")",
")",
"shifted",
"[",
"out_slicer",
"]",
"=",
"smoothed",
"[",
"in_slicer",
"]",
"return",
"_extract_intensities",
"(",
"shifted",
",",
"mask",
")"
] | Internal, single-image version of `shifted_mean_gauss`. | [
"Internal",
"single",
"-",
"image",
"version",
"of",
"shifted_mean_gauss",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L653-L678 | train | 238,163 |
loli/medpy | medpy/features/intensity.py | _extract_mask_distance | def _extract_mask_distance(image, mask = slice(None), voxelspacing = None):
"""
Internal, single-image version of `mask_distance`.
"""
if isinstance(mask, slice):
mask = numpy.ones(image.shape, numpy.bool)
distance_map = distance_transform_edt(mask, sampling=voxelspacing)
return _extract_intensities(distance_map, mask) | python | def _extract_mask_distance(image, mask = slice(None), voxelspacing = None):
"""
Internal, single-image version of `mask_distance`.
"""
if isinstance(mask, slice):
mask = numpy.ones(image.shape, numpy.bool)
distance_map = distance_transform_edt(mask, sampling=voxelspacing)
return _extract_intensities(distance_map, mask) | [
"def",
"_extract_mask_distance",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
",",
"voxelspacing",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"mask",
",",
"slice",
")",
":",
"mask",
"=",
"numpy",
".",
"ones",
"(",
"image",
".",
"shape",
",",
"numpy",
".",
"bool",
")",
"distance_map",
"=",
"distance_transform_edt",
"(",
"mask",
",",
"sampling",
"=",
"voxelspacing",
")",
"return",
"_extract_intensities",
"(",
"distance_map",
",",
"mask",
")"
] | Internal, single-image version of `mask_distance`. | [
"Internal",
"single",
"-",
"image",
"version",
"of",
"mask_distance",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L680-L689 | train | 238,164 |
loli/medpy | medpy/features/intensity.py | _extract_local_mean_gauss | def _extract_local_mean_gauss(image, mask = slice(None), sigma = 1, voxelspacing = None):
"""
Internal, single-image version of `local_mean_gauss`.
"""
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# determine gaussian kernel size in voxel units
sigma = _create_structure_array(sigma, voxelspacing)
return _extract_intensities(gaussian_filter(image, sigma), mask) | python | def _extract_local_mean_gauss(image, mask = slice(None), sigma = 1, voxelspacing = None):
"""
Internal, single-image version of `local_mean_gauss`.
"""
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# determine gaussian kernel size in voxel units
sigma = _create_structure_array(sigma, voxelspacing)
return _extract_intensities(gaussian_filter(image, sigma), mask) | [
"def",
"_extract_local_mean_gauss",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
",",
"sigma",
"=",
"1",
",",
"voxelspacing",
"=",
"None",
")",
":",
"# set voxel spacing",
"if",
"voxelspacing",
"is",
"None",
":",
"voxelspacing",
"=",
"[",
"1.",
"]",
"*",
"image",
".",
"ndim",
"# determine gaussian kernel size in voxel units",
"sigma",
"=",
"_create_structure_array",
"(",
"sigma",
",",
"voxelspacing",
")",
"return",
"_extract_intensities",
"(",
"gaussian_filter",
"(",
"image",
",",
"sigma",
")",
",",
"mask",
")"
] | Internal, single-image version of `local_mean_gauss`. | [
"Internal",
"single",
"-",
"image",
"version",
"of",
"local_mean_gauss",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L691-L702 | train | 238,165 |
loli/medpy | medpy/features/intensity.py | _extract_centerdistance | def _extract_centerdistance(image, mask = slice(None), voxelspacing = None):
"""
Internal, single-image version of `centerdistance`.
"""
image = numpy.array(image, copy=False)
if None == voxelspacing:
voxelspacing = [1.] * image.ndim
# get image center and an array holding the images indices
centers = [(x - 1) / 2. for x in image.shape]
indices = numpy.indices(image.shape, dtype=numpy.float)
# shift to center of image and correct spacing to real world coordinates
for dim_indices, c, vs in zip(indices, centers, voxelspacing):
dim_indices -= c
dim_indices *= vs
# compute euclidean distance to image center
return numpy.sqrt(numpy.sum(numpy.square(indices), 0))[mask].ravel() | python | def _extract_centerdistance(image, mask = slice(None), voxelspacing = None):
"""
Internal, single-image version of `centerdistance`.
"""
image = numpy.array(image, copy=False)
if None == voxelspacing:
voxelspacing = [1.] * image.ndim
# get image center and an array holding the images indices
centers = [(x - 1) / 2. for x in image.shape]
indices = numpy.indices(image.shape, dtype=numpy.float)
# shift to center of image and correct spacing to real world coordinates
for dim_indices, c, vs in zip(indices, centers, voxelspacing):
dim_indices -= c
dim_indices *= vs
# compute euclidean distance to image center
return numpy.sqrt(numpy.sum(numpy.square(indices), 0))[mask].ravel() | [
"def",
"_extract_centerdistance",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
",",
"voxelspacing",
"=",
"None",
")",
":",
"image",
"=",
"numpy",
".",
"array",
"(",
"image",
",",
"copy",
"=",
"False",
")",
"if",
"None",
"==",
"voxelspacing",
":",
"voxelspacing",
"=",
"[",
"1.",
"]",
"*",
"image",
".",
"ndim",
"# get image center and an array holding the images indices",
"centers",
"=",
"[",
"(",
"x",
"-",
"1",
")",
"/",
"2.",
"for",
"x",
"in",
"image",
".",
"shape",
"]",
"indices",
"=",
"numpy",
".",
"indices",
"(",
"image",
".",
"shape",
",",
"dtype",
"=",
"numpy",
".",
"float",
")",
"# shift to center of image and correct spacing to real world coordinates",
"for",
"dim_indices",
",",
"c",
",",
"vs",
"in",
"zip",
"(",
"indices",
",",
"centers",
",",
"voxelspacing",
")",
":",
"dim_indices",
"-=",
"c",
"dim_indices",
"*=",
"vs",
"# compute euclidean distance to image center",
"return",
"numpy",
".",
"sqrt",
"(",
"numpy",
".",
"sum",
"(",
"numpy",
".",
"square",
"(",
"indices",
")",
",",
"0",
")",
")",
"[",
"mask",
"]",
".",
"ravel",
"(",
")"
] | Internal, single-image version of `centerdistance`. | [
"Internal",
"single",
"-",
"image",
"version",
"of",
"centerdistance",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L705-L724 | train | 238,166 |
loli/medpy | medpy/features/intensity.py | _extract_intensities | def _extract_intensities(image, mask = slice(None)):
"""
Internal, single-image version of `intensities`.
"""
return numpy.array(image, copy=True)[mask].ravel() | python | def _extract_intensities(image, mask = slice(None)):
"""
Internal, single-image version of `intensities`.
"""
return numpy.array(image, copy=True)[mask].ravel() | [
"def",
"_extract_intensities",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
")",
":",
"return",
"numpy",
".",
"array",
"(",
"image",
",",
"copy",
"=",
"True",
")",
"[",
"mask",
"]",
".",
"ravel",
"(",
")"
] | Internal, single-image version of `intensities`. | [
"Internal",
"single",
"-",
"image",
"version",
"of",
"intensities",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L727-L731 | train | 238,167 |
loli/medpy | medpy/features/intensity.py | _substract_hemispheres | def _substract_hemispheres(active, reference, active_sigma, reference_sigma, voxel_spacing):
"""
Helper function for `_extract_hemispheric_difference`.
Smoothes both images and then substracts the reference from the active image.
"""
active_kernel = _create_structure_array(active_sigma, voxel_spacing)
active_smoothed = gaussian_filter(active, sigma = active_kernel)
reference_kernel = _create_structure_array(reference_sigma, voxel_spacing)
reference_smoothed = gaussian_filter(reference, sigma = reference_kernel)
return active_smoothed - reference_smoothed | python | def _substract_hemispheres(active, reference, active_sigma, reference_sigma, voxel_spacing):
"""
Helper function for `_extract_hemispheric_difference`.
Smoothes both images and then substracts the reference from the active image.
"""
active_kernel = _create_structure_array(active_sigma, voxel_spacing)
active_smoothed = gaussian_filter(active, sigma = active_kernel)
reference_kernel = _create_structure_array(reference_sigma, voxel_spacing)
reference_smoothed = gaussian_filter(reference, sigma = reference_kernel)
return active_smoothed - reference_smoothed | [
"def",
"_substract_hemispheres",
"(",
"active",
",",
"reference",
",",
"active_sigma",
",",
"reference_sigma",
",",
"voxel_spacing",
")",
":",
"active_kernel",
"=",
"_create_structure_array",
"(",
"active_sigma",
",",
"voxel_spacing",
")",
"active_smoothed",
"=",
"gaussian_filter",
"(",
"active",
",",
"sigma",
"=",
"active_kernel",
")",
"reference_kernel",
"=",
"_create_structure_array",
"(",
"reference_sigma",
",",
"voxel_spacing",
")",
"reference_smoothed",
"=",
"gaussian_filter",
"(",
"reference",
",",
"sigma",
"=",
"reference_kernel",
")",
"return",
"active_smoothed",
"-",
"reference_smoothed"
] | Helper function for `_extract_hemispheric_difference`.
Smoothes both images and then substracts the reference from the active image. | [
"Helper",
"function",
"for",
"_extract_hemispheric_difference",
".",
"Smoothes",
"both",
"images",
"and",
"then",
"substracts",
"the",
"reference",
"from",
"the",
"active",
"image",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L733-L744 | train | 238,168 |
loli/medpy | doc/numpydoc/numpydoc/compiler_unparse.py | UnparseCompilerAst._dispatch | def _dispatch(self, tree):
"_dispatcher function, _dispatching tree type T to method _T."
if isinstance(tree, list):
for t in tree:
self._dispatch(t)
return
meth = getattr(self, "_"+tree.__class__.__name__)
if tree.__class__.__name__ == 'NoneType' and not self._do_indent:
return
meth(tree) | python | def _dispatch(self, tree):
"_dispatcher function, _dispatching tree type T to method _T."
if isinstance(tree, list):
for t in tree:
self._dispatch(t)
return
meth = getattr(self, "_"+tree.__class__.__name__)
if tree.__class__.__name__ == 'NoneType' and not self._do_indent:
return
meth(tree) | [
"def",
"_dispatch",
"(",
"self",
",",
"tree",
")",
":",
"if",
"isinstance",
"(",
"tree",
",",
"list",
")",
":",
"for",
"t",
"in",
"tree",
":",
"self",
".",
"_dispatch",
"(",
"t",
")",
"return",
"meth",
"=",
"getattr",
"(",
"self",
",",
"\"_\"",
"+",
"tree",
".",
"__class__",
".",
"__name__",
")",
"if",
"tree",
".",
"__class__",
".",
"__name__",
"==",
"'NoneType'",
"and",
"not",
"self",
".",
"_do_indent",
":",
"return",
"meth",
"(",
"tree",
")"
] | _dispatcher function, _dispatching tree type T to method _T. | [
"_dispatcher",
"function",
"_dispatching",
"tree",
"type",
"T",
"to",
"method",
"_T",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/compiler_unparse.py#L80-L89 | train | 238,169 |
loli/medpy | doc/numpydoc/numpydoc/compiler_unparse.py | UnparseCompilerAst._AssAttr | def _AssAttr(self, t):
""" Handle assigning an attribute of an object
"""
self._dispatch(t.expr)
self._write('.'+t.attrname) | python | def _AssAttr(self, t):
""" Handle assigning an attribute of an object
"""
self._dispatch(t.expr)
self._write('.'+t.attrname) | [
"def",
"_AssAttr",
"(",
"self",
",",
"t",
")",
":",
"self",
".",
"_dispatch",
"(",
"t",
".",
"expr",
")",
"self",
".",
"_write",
"(",
"'.'",
"+",
"t",
".",
"attrname",
")"
] | Handle assigning an attribute of an object | [
"Handle",
"assigning",
"an",
"attribute",
"of",
"an",
"object"
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/compiler_unparse.py#L110-L114 | train | 238,170 |
loli/medpy | doc/numpydoc/numpydoc/compiler_unparse.py | UnparseCompilerAst._Assign | def _Assign(self, t):
""" Expression Assignment such as "a = 1".
This only handles assignment in expressions. Keyword assignment
is handled separately.
"""
self._fill()
for target in t.nodes:
self._dispatch(target)
self._write(" = ")
self._dispatch(t.expr)
if not self._do_indent:
self._write('; ') | python | def _Assign(self, t):
""" Expression Assignment such as "a = 1".
This only handles assignment in expressions. Keyword assignment
is handled separately.
"""
self._fill()
for target in t.nodes:
self._dispatch(target)
self._write(" = ")
self._dispatch(t.expr)
if not self._do_indent:
self._write('; ') | [
"def",
"_Assign",
"(",
"self",
",",
"t",
")",
":",
"self",
".",
"_fill",
"(",
")",
"for",
"target",
"in",
"t",
".",
"nodes",
":",
"self",
".",
"_dispatch",
"(",
"target",
")",
"self",
".",
"_write",
"(",
"\" = \"",
")",
"self",
".",
"_dispatch",
"(",
"t",
".",
"expr",
")",
"if",
"not",
"self",
".",
"_do_indent",
":",
"self",
".",
"_write",
"(",
"'; '",
")"
] | Expression Assignment such as "a = 1".
This only handles assignment in expressions. Keyword assignment
is handled separately. | [
"Expression",
"Assignment",
"such",
"as",
"a",
"=",
"1",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/compiler_unparse.py#L116-L128 | train | 238,171 |
loli/medpy | doc/numpydoc/numpydoc/compiler_unparse.py | UnparseCompilerAst._AssTuple | def _AssTuple(self, t):
""" Tuple on left hand side of an expression.
"""
# _write each elements, separated by a comma.
for element in t.nodes[:-1]:
self._dispatch(element)
self._write(", ")
# Handle the last one without writing comma
last_element = t.nodes[-1]
self._dispatch(last_element) | python | def _AssTuple(self, t):
""" Tuple on left hand side of an expression.
"""
# _write each elements, separated by a comma.
for element in t.nodes[:-1]:
self._dispatch(element)
self._write(", ")
# Handle the last one without writing comma
last_element = t.nodes[-1]
self._dispatch(last_element) | [
"def",
"_AssTuple",
"(",
"self",
",",
"t",
")",
":",
"# _write each elements, separated by a comma.",
"for",
"element",
"in",
"t",
".",
"nodes",
"[",
":",
"-",
"1",
"]",
":",
"self",
".",
"_dispatch",
"(",
"element",
")",
"self",
".",
"_write",
"(",
"\", \"",
")",
"# Handle the last one without writing comma",
"last_element",
"=",
"t",
".",
"nodes",
"[",
"-",
"1",
"]",
"self",
".",
"_dispatch",
"(",
"last_element",
")"
] | Tuple on left hand side of an expression. | [
"Tuple",
"on",
"left",
"hand",
"side",
"of",
"an",
"expression",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/compiler_unparse.py#L137-L148 | train | 238,172 |
loli/medpy | doc/numpydoc/numpydoc/compiler_unparse.py | UnparseCompilerAst._CallFunc | def _CallFunc(self, t):
""" Function call.
"""
self._dispatch(t.node)
self._write("(")
comma = False
for e in t.args:
if comma: self._write(", ")
else: comma = True
self._dispatch(e)
if t.star_args:
if comma: self._write(", ")
else: comma = True
self._write("*")
self._dispatch(t.star_args)
if t.dstar_args:
if comma: self._write(", ")
else: comma = True
self._write("**")
self._dispatch(t.dstar_args)
self._write(")") | python | def _CallFunc(self, t):
""" Function call.
"""
self._dispatch(t.node)
self._write("(")
comma = False
for e in t.args:
if comma: self._write(", ")
else: comma = True
self._dispatch(e)
if t.star_args:
if comma: self._write(", ")
else: comma = True
self._write("*")
self._dispatch(t.star_args)
if t.dstar_args:
if comma: self._write(", ")
else: comma = True
self._write("**")
self._dispatch(t.dstar_args)
self._write(")") | [
"def",
"_CallFunc",
"(",
"self",
",",
"t",
")",
":",
"self",
".",
"_dispatch",
"(",
"t",
".",
"node",
")",
"self",
".",
"_write",
"(",
"\"(\"",
")",
"comma",
"=",
"False",
"for",
"e",
"in",
"t",
".",
"args",
":",
"if",
"comma",
":",
"self",
".",
"_write",
"(",
"\", \"",
")",
"else",
":",
"comma",
"=",
"True",
"self",
".",
"_dispatch",
"(",
"e",
")",
"if",
"t",
".",
"star_args",
":",
"if",
"comma",
":",
"self",
".",
"_write",
"(",
"\", \"",
")",
"else",
":",
"comma",
"=",
"True",
"self",
".",
"_write",
"(",
"\"*\"",
")",
"self",
".",
"_dispatch",
"(",
"t",
".",
"star_args",
")",
"if",
"t",
".",
"dstar_args",
":",
"if",
"comma",
":",
"self",
".",
"_write",
"(",
"\", \"",
")",
"else",
":",
"comma",
"=",
"True",
"self",
".",
"_write",
"(",
"\"**\"",
")",
"self",
".",
"_dispatch",
"(",
"t",
".",
"dstar_args",
")",
"self",
".",
"_write",
"(",
"\")\"",
")"
] | Function call. | [
"Function",
"call",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/compiler_unparse.py#L183-L203 | train | 238,173 |
loli/medpy | doc/numpydoc/numpydoc/compiler_unparse.py | UnparseCompilerAst._From | def _From(self, t):
""" Handle "from xyz import foo, bar as baz".
"""
# fixme: Are From and ImportFrom handled differently?
self._fill("from ")
self._write(t.modname)
self._write(" import ")
for i, (name,asname) in enumerate(t.names):
if i != 0:
self._write(", ")
self._write(name)
if asname is not None:
self._write(" as "+asname) | python | def _From(self, t):
""" Handle "from xyz import foo, bar as baz".
"""
# fixme: Are From and ImportFrom handled differently?
self._fill("from ")
self._write(t.modname)
self._write(" import ")
for i, (name,asname) in enumerate(t.names):
if i != 0:
self._write(", ")
self._write(name)
if asname is not None:
self._write(" as "+asname) | [
"def",
"_From",
"(",
"self",
",",
"t",
")",
":",
"# fixme: Are From and ImportFrom handled differently?",
"self",
".",
"_fill",
"(",
"\"from \"",
")",
"self",
".",
"_write",
"(",
"t",
".",
"modname",
")",
"self",
".",
"_write",
"(",
"\" import \"",
")",
"for",
"i",
",",
"(",
"name",
",",
"asname",
")",
"in",
"enumerate",
"(",
"t",
".",
"names",
")",
":",
"if",
"i",
"!=",
"0",
":",
"self",
".",
"_write",
"(",
"\", \"",
")",
"self",
".",
"_write",
"(",
"name",
")",
"if",
"asname",
"is",
"not",
"None",
":",
"self",
".",
"_write",
"(",
"\" as \"",
"+",
"asname",
")"
] | Handle "from xyz import foo, bar as baz". | [
"Handle",
"from",
"xyz",
"import",
"foo",
"bar",
"as",
"baz",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/compiler_unparse.py#L244-L256 | train | 238,174 |
loli/medpy | doc/numpydoc/numpydoc/compiler_unparse.py | UnparseCompilerAst._Function | def _Function(self, t):
""" Handle function definitions
"""
if t.decorators is not None:
self._fill("@")
self._dispatch(t.decorators)
self._fill("def "+t.name + "(")
defaults = [None] * (len(t.argnames) - len(t.defaults)) + list(t.defaults)
for i, arg in enumerate(zip(t.argnames, defaults)):
self._write(arg[0])
if arg[1] is not None:
self._write('=')
self._dispatch(arg[1])
if i < len(t.argnames)-1:
self._write(', ')
self._write(")")
if self._single_func:
self._do_indent = False
self._enter()
self._dispatch(t.code)
self._leave()
self._do_indent = True | python | def _Function(self, t):
""" Handle function definitions
"""
if t.decorators is not None:
self._fill("@")
self._dispatch(t.decorators)
self._fill("def "+t.name + "(")
defaults = [None] * (len(t.argnames) - len(t.defaults)) + list(t.defaults)
for i, arg in enumerate(zip(t.argnames, defaults)):
self._write(arg[0])
if arg[1] is not None:
self._write('=')
self._dispatch(arg[1])
if i < len(t.argnames)-1:
self._write(', ')
self._write(")")
if self._single_func:
self._do_indent = False
self._enter()
self._dispatch(t.code)
self._leave()
self._do_indent = True | [
"def",
"_Function",
"(",
"self",
",",
"t",
")",
":",
"if",
"t",
".",
"decorators",
"is",
"not",
"None",
":",
"self",
".",
"_fill",
"(",
"\"@\"",
")",
"self",
".",
"_dispatch",
"(",
"t",
".",
"decorators",
")",
"self",
".",
"_fill",
"(",
"\"def \"",
"+",
"t",
".",
"name",
"+",
"\"(\"",
")",
"defaults",
"=",
"[",
"None",
"]",
"*",
"(",
"len",
"(",
"t",
".",
"argnames",
")",
"-",
"len",
"(",
"t",
".",
"defaults",
")",
")",
"+",
"list",
"(",
"t",
".",
"defaults",
")",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"zip",
"(",
"t",
".",
"argnames",
",",
"defaults",
")",
")",
":",
"self",
".",
"_write",
"(",
"arg",
"[",
"0",
"]",
")",
"if",
"arg",
"[",
"1",
"]",
"is",
"not",
"None",
":",
"self",
".",
"_write",
"(",
"'='",
")",
"self",
".",
"_dispatch",
"(",
"arg",
"[",
"1",
"]",
")",
"if",
"i",
"<",
"len",
"(",
"t",
".",
"argnames",
")",
"-",
"1",
":",
"self",
".",
"_write",
"(",
"', '",
")",
"self",
".",
"_write",
"(",
"\")\"",
")",
"if",
"self",
".",
"_single_func",
":",
"self",
".",
"_do_indent",
"=",
"False",
"self",
".",
"_enter",
"(",
")",
"self",
".",
"_dispatch",
"(",
"t",
".",
"code",
")",
"self",
".",
"_leave",
"(",
")",
"self",
".",
"_do_indent",
"=",
"True"
] | Handle function definitions | [
"Handle",
"function",
"definitions"
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/compiler_unparse.py#L258-L279 | train | 238,175 |
loli/medpy | doc/numpydoc/numpydoc/compiler_unparse.py | UnparseCompilerAst._Getattr | def _Getattr(self, t):
""" Handle getting an attribute of an object
"""
if isinstance(t.expr, (Div, Mul, Sub, Add)):
self._write('(')
self._dispatch(t.expr)
self._write(')')
else:
self._dispatch(t.expr)
self._write('.'+t.attrname) | python | def _Getattr(self, t):
""" Handle getting an attribute of an object
"""
if isinstance(t.expr, (Div, Mul, Sub, Add)):
self._write('(')
self._dispatch(t.expr)
self._write(')')
else:
self._dispatch(t.expr)
self._write('.'+t.attrname) | [
"def",
"_Getattr",
"(",
"self",
",",
"t",
")",
":",
"if",
"isinstance",
"(",
"t",
".",
"expr",
",",
"(",
"Div",
",",
"Mul",
",",
"Sub",
",",
"Add",
")",
")",
":",
"self",
".",
"_write",
"(",
"'('",
")",
"self",
".",
"_dispatch",
"(",
"t",
".",
"expr",
")",
"self",
".",
"_write",
"(",
"')'",
")",
"else",
":",
"self",
".",
"_dispatch",
"(",
"t",
".",
"expr",
")",
"self",
".",
"_write",
"(",
"'.'",
"+",
"t",
".",
"attrname",
")"
] | Handle getting an attribute of an object | [
"Handle",
"getting",
"an",
"attribute",
"of",
"an",
"object"
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/compiler_unparse.py#L281-L291 | train | 238,176 |
loli/medpy | doc/numpydoc/numpydoc/compiler_unparse.py | UnparseCompilerAst._Import | def _Import(self, t):
""" Handle "import xyz.foo".
"""
self._fill("import ")
for i, (name,asname) in enumerate(t.names):
if i != 0:
self._write(", ")
self._write(name)
if asname is not None:
self._write(" as "+asname) | python | def _Import(self, t):
""" Handle "import xyz.foo".
"""
self._fill("import ")
for i, (name,asname) in enumerate(t.names):
if i != 0:
self._write(", ")
self._write(name)
if asname is not None:
self._write(" as "+asname) | [
"def",
"_Import",
"(",
"self",
",",
"t",
")",
":",
"self",
".",
"_fill",
"(",
"\"import \"",
")",
"for",
"i",
",",
"(",
"name",
",",
"asname",
")",
"in",
"enumerate",
"(",
"t",
".",
"names",
")",
":",
"if",
"i",
"!=",
"0",
":",
"self",
".",
"_write",
"(",
"\", \"",
")",
"self",
".",
"_write",
"(",
"name",
")",
"if",
"asname",
"is",
"not",
"None",
":",
"self",
".",
"_write",
"(",
"\" as \"",
"+",
"asname",
")"
] | Handle "import xyz.foo". | [
"Handle",
"import",
"xyz",
".",
"foo",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/compiler_unparse.py#L326-L336 | train | 238,177 |
loli/medpy | doc/numpydoc/numpydoc/compiler_unparse.py | UnparseCompilerAst._Keyword | def _Keyword(self, t):
""" Keyword value assignment within function calls and definitions.
"""
self._write(t.name)
self._write("=")
self._dispatch(t.expr) | python | def _Keyword(self, t):
""" Keyword value assignment within function calls and definitions.
"""
self._write(t.name)
self._write("=")
self._dispatch(t.expr) | [
"def",
"_Keyword",
"(",
"self",
",",
"t",
")",
":",
"self",
".",
"_write",
"(",
"t",
".",
"name",
")",
"self",
".",
"_write",
"(",
"\"=\"",
")",
"self",
".",
"_dispatch",
"(",
"t",
".",
"expr",
")"
] | Keyword value assignment within function calls and definitions. | [
"Keyword",
"value",
"assignment",
"within",
"function",
"calls",
"and",
"definitions",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/compiler_unparse.py#L338-L343 | train | 238,178 |
loli/medpy | medpy/utilities/argparseu.py | __sequenceAscendingStrict | def __sequenceAscendingStrict(l):
"Test a sequences values to be in strictly ascending order."
it = iter(l)
next(it)
if not all(b > a for a, b in zip(l, it)):
raise argparse.ArgumentTypeError('All values must be given in strictly ascending order.')
return l | python | def __sequenceAscendingStrict(l):
"Test a sequences values to be in strictly ascending order."
it = iter(l)
next(it)
if not all(b > a for a, b in zip(l, it)):
raise argparse.ArgumentTypeError('All values must be given in strictly ascending order.')
return l | [
"def",
"__sequenceAscendingStrict",
"(",
"l",
")",
":",
"it",
"=",
"iter",
"(",
"l",
")",
"next",
"(",
"it",
")",
"if",
"not",
"all",
"(",
"b",
">",
"a",
"for",
"a",
",",
"b",
"in",
"zip",
"(",
"l",
",",
"it",
")",
")",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"'All values must be given in strictly ascending order.'",
")",
"return",
"l"
] | Test a sequences values to be in strictly ascending order. | [
"Test",
"a",
"sequences",
"values",
"to",
"be",
"in",
"strictly",
"ascending",
"order",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/utilities/argparseu.py#L238-L244 | train | 238,179 |
loli/medpy | medpy/filter/IntensityRangeStandardization.py | IntensityRangeStandardization.__check_mapping | def __check_mapping(self, landmarks):
"""
Checks whether the image, from which the supplied landmarks were extracted, can
be transformed to the learned standard intensity space without loss of
information.
"""
sc_udiff = numpy.asarray(self.__sc_umaxs)[1:] - numpy.asarray(self.__sc_umins)[:-1]
l_diff = numpy.asarray(landmarks)[1:] - numpy.asarray(landmarks)[:-1]
return numpy.all(sc_udiff > numpy.asarray(l_diff)) | python | def __check_mapping(self, landmarks):
"""
Checks whether the image, from which the supplied landmarks were extracted, can
be transformed to the learned standard intensity space without loss of
information.
"""
sc_udiff = numpy.asarray(self.__sc_umaxs)[1:] - numpy.asarray(self.__sc_umins)[:-1]
l_diff = numpy.asarray(landmarks)[1:] - numpy.asarray(landmarks)[:-1]
return numpy.all(sc_udiff > numpy.asarray(l_diff)) | [
"def",
"__check_mapping",
"(",
"self",
",",
"landmarks",
")",
":",
"sc_udiff",
"=",
"numpy",
".",
"asarray",
"(",
"self",
".",
"__sc_umaxs",
")",
"[",
"1",
":",
"]",
"-",
"numpy",
".",
"asarray",
"(",
"self",
".",
"__sc_umins",
")",
"[",
":",
"-",
"1",
"]",
"l_diff",
"=",
"numpy",
".",
"asarray",
"(",
"landmarks",
")",
"[",
"1",
":",
"]",
"-",
"numpy",
".",
"asarray",
"(",
"landmarks",
")",
"[",
":",
"-",
"1",
"]",
"return",
"numpy",
".",
"all",
"(",
"sc_udiff",
">",
"numpy",
".",
"asarray",
"(",
"l_diff",
")",
")"
] | Checks whether the image, from which the supplied landmarks were extracted, can
be transformed to the learned standard intensity space without loss of
information. | [
"Checks",
"whether",
"the",
"image",
"from",
"which",
"the",
"supplied",
"landmarks",
"were",
"extracted",
"can",
"be",
"transformed",
"to",
"the",
"learned",
"standard",
"intensity",
"space",
"without",
"loss",
"of",
"information",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/filter/IntensityRangeStandardization.py#L459-L467 | train | 238,180 |
loli/medpy | medpy/filter/IntensityRangeStandardization.py | IntensityRangeStandardization.is_in_interval | def is_in_interval(n, l, r, border = 'included'):
"""
Checks whether a number is inside the interval l, r.
"""
if 'included' == border:
return (n >= l) and (n <= r)
elif 'excluded' == border:
return (n > l) and (n < r)
else:
raise ValueError('borders must be either \'included\' or \'excluded\'') | python | def is_in_interval(n, l, r, border = 'included'):
"""
Checks whether a number is inside the interval l, r.
"""
if 'included' == border:
return (n >= l) and (n <= r)
elif 'excluded' == border:
return (n > l) and (n < r)
else:
raise ValueError('borders must be either \'included\' or \'excluded\'') | [
"def",
"is_in_interval",
"(",
"n",
",",
"l",
",",
"r",
",",
"border",
"=",
"'included'",
")",
":",
"if",
"'included'",
"==",
"border",
":",
"return",
"(",
"n",
">=",
"l",
")",
"and",
"(",
"n",
"<=",
"r",
")",
"elif",
"'excluded'",
"==",
"border",
":",
"return",
"(",
"n",
">",
"l",
")",
"and",
"(",
"n",
"<",
"r",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'borders must be either \\'included\\' or \\'excluded\\''",
")"
] | Checks whether a number is inside the interval l, r. | [
"Checks",
"whether",
"a",
"number",
"is",
"inside",
"the",
"interval",
"l",
"r",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/filter/IntensityRangeStandardization.py#L497-L506 | train | 238,181 |
loli/medpy | medpy/filter/IntensityRangeStandardization.py | IntensityRangeStandardization.are_in_interval | def are_in_interval(s, l, r, border = 'included'):
"""
Checks whether all number in the sequence s lie inside the interval formed by
l and r.
"""
return numpy.all([IntensityRangeStandardization.is_in_interval(x, l, r, border) for x in s]) | python | def are_in_interval(s, l, r, border = 'included'):
"""
Checks whether all number in the sequence s lie inside the interval formed by
l and r.
"""
return numpy.all([IntensityRangeStandardization.is_in_interval(x, l, r, border) for x in s]) | [
"def",
"are_in_interval",
"(",
"s",
",",
"l",
",",
"r",
",",
"border",
"=",
"'included'",
")",
":",
"return",
"numpy",
".",
"all",
"(",
"[",
"IntensityRangeStandardization",
".",
"is_in_interval",
"(",
"x",
",",
"l",
",",
"r",
",",
"border",
")",
"for",
"x",
"in",
"s",
"]",
")"
] | Checks whether all number in the sequence s lie inside the interval formed by
l and r. | [
"Checks",
"whether",
"all",
"number",
"in",
"the",
"sequence",
"s",
"lie",
"inside",
"the",
"interval",
"formed",
"by",
"l",
"and",
"r",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/filter/IntensityRangeStandardization.py#L509-L514 | train | 238,182 |
loli/medpy | medpy/filter/houghtransform.py | template_sphere | def template_sphere (radius, dimensions):
r"""
Returns a spherical binary structure of a of the supplied radius that can be used as
template input to the generalized hough transform.
Parameters
----------
radius : integer
The circles radius in voxels.
dimensions : integer
The dimensionality of the circle
Returns
-------
template_sphere : ndarray
A boolean array containing a sphere.
"""
if int(dimensions) != dimensions:
raise TypeError('The supplied dimension parameter must be of type integer.')
dimensions = int(dimensions)
return template_ellipsoid(dimensions * [radius * 2]) | python | def template_sphere (radius, dimensions):
r"""
Returns a spherical binary structure of a of the supplied radius that can be used as
template input to the generalized hough transform.
Parameters
----------
radius : integer
The circles radius in voxels.
dimensions : integer
The dimensionality of the circle
Returns
-------
template_sphere : ndarray
A boolean array containing a sphere.
"""
if int(dimensions) != dimensions:
raise TypeError('The supplied dimension parameter must be of type integer.')
dimensions = int(dimensions)
return template_ellipsoid(dimensions * [radius * 2]) | [
"def",
"template_sphere",
"(",
"radius",
",",
"dimensions",
")",
":",
"if",
"int",
"(",
"dimensions",
")",
"!=",
"dimensions",
":",
"raise",
"TypeError",
"(",
"'The supplied dimension parameter must be of type integer.'",
")",
"dimensions",
"=",
"int",
"(",
"dimensions",
")",
"return",
"template_ellipsoid",
"(",
"dimensions",
"*",
"[",
"radius",
"*",
"2",
"]",
")"
] | r"""
Returns a spherical binary structure of a of the supplied radius that can be used as
template input to the generalized hough transform.
Parameters
----------
radius : integer
The circles radius in voxels.
dimensions : integer
The dimensionality of the circle
Returns
-------
template_sphere : ndarray
A boolean array containing a sphere. | [
"r",
"Returns",
"a",
"spherical",
"binary",
"structure",
"of",
"a",
"of",
"the",
"supplied",
"radius",
"that",
"can",
"be",
"used",
"as",
"template",
"input",
"to",
"the",
"generalized",
"hough",
"transform",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/filter/houghtransform.py#L156-L177 | train | 238,183 |
loli/medpy | doc/numpydoc/numpydoc/traitsdoc.py | looks_like_issubclass | def looks_like_issubclass(obj, classname):
""" Return True if the object has a class or superclass with the given class
name.
Ignores old-style classes.
"""
t = obj
if t.__name__ == classname:
return True
for klass in t.__mro__:
if klass.__name__ == classname:
return True
return False | python | def looks_like_issubclass(obj, classname):
""" Return True if the object has a class or superclass with the given class
name.
Ignores old-style classes.
"""
t = obj
if t.__name__ == classname:
return True
for klass in t.__mro__:
if klass.__name__ == classname:
return True
return False | [
"def",
"looks_like_issubclass",
"(",
"obj",
",",
"classname",
")",
":",
"t",
"=",
"obj",
"if",
"t",
".",
"__name__",
"==",
"classname",
":",
"return",
"True",
"for",
"klass",
"in",
"t",
".",
"__mro__",
":",
"if",
"klass",
".",
"__name__",
"==",
"classname",
":",
"return",
"True",
"return",
"False"
] | Return True if the object has a class or superclass with the given class
name.
Ignores old-style classes. | [
"Return",
"True",
"if",
"the",
"object",
"has",
"a",
"class",
"or",
"superclass",
"with",
"the",
"given",
"class",
"name",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/traitsdoc.py#L102-L114 | train | 238,184 |
loli/medpy | medpy/filter/utilities.py | __make_footprint | def __make_footprint(input, size, footprint):
"Creates a standard footprint element ala scipy.ndimage."
if footprint is None:
if size is None:
raise RuntimeError("no footprint or filter size provided")
sizes = _ni_support._normalize_sequence(size, input.ndim)
footprint = numpy.ones(sizes, dtype=bool)
else:
footprint = numpy.asarray(footprint, dtype=bool)
return footprint | python | def __make_footprint(input, size, footprint):
"Creates a standard footprint element ala scipy.ndimage."
if footprint is None:
if size is None:
raise RuntimeError("no footprint or filter size provided")
sizes = _ni_support._normalize_sequence(size, input.ndim)
footprint = numpy.ones(sizes, dtype=bool)
else:
footprint = numpy.asarray(footprint, dtype=bool)
return footprint | [
"def",
"__make_footprint",
"(",
"input",
",",
"size",
",",
"footprint",
")",
":",
"if",
"footprint",
"is",
"None",
":",
"if",
"size",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"no footprint or filter size provided\"",
")",
"sizes",
"=",
"_ni_support",
".",
"_normalize_sequence",
"(",
"size",
",",
"input",
".",
"ndim",
")",
"footprint",
"=",
"numpy",
".",
"ones",
"(",
"sizes",
",",
"dtype",
"=",
"bool",
")",
"else",
":",
"footprint",
"=",
"numpy",
".",
"asarray",
"(",
"footprint",
",",
"dtype",
"=",
"bool",
")",
"return",
"footprint"
] | Creates a standard footprint element ala scipy.ndimage. | [
"Creates",
"a",
"standard",
"footprint",
"element",
"ala",
"scipy",
".",
"ndimage",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/filter/utilities.py#L246-L255 | train | 238,185 |
loli/medpy | medpy/graphcut/energy_label.py | __check_label_image | def __check_label_image(label_image):
"""Check the label image for consistent labelling starting from 1."""
encountered_indices = scipy.unique(label_image)
expected_indices = scipy.arange(1, label_image.max() + 1)
if not encountered_indices.size == expected_indices.size or \
not (encountered_indices == expected_indices).all():
raise AttributeError('The supplied label image does either not contain any regions or they are not labeled consecutively starting from 1.') | python | def __check_label_image(label_image):
"""Check the label image for consistent labelling starting from 1."""
encountered_indices = scipy.unique(label_image)
expected_indices = scipy.arange(1, label_image.max() + 1)
if not encountered_indices.size == expected_indices.size or \
not (encountered_indices == expected_indices).all():
raise AttributeError('The supplied label image does either not contain any regions or they are not labeled consecutively starting from 1.') | [
"def",
"__check_label_image",
"(",
"label_image",
")",
":",
"encountered_indices",
"=",
"scipy",
".",
"unique",
"(",
"label_image",
")",
"expected_indices",
"=",
"scipy",
".",
"arange",
"(",
"1",
",",
"label_image",
".",
"max",
"(",
")",
"+",
"1",
")",
"if",
"not",
"encountered_indices",
".",
"size",
"==",
"expected_indices",
".",
"size",
"or",
"not",
"(",
"encountered_indices",
"==",
"expected_indices",
")",
".",
"all",
"(",
")",
":",
"raise",
"AttributeError",
"(",
"'The supplied label image does either not contain any regions or they are not labeled consecutively starting from 1.'",
")"
] | Check the label image for consistent labelling starting from 1. | [
"Check",
"the",
"label",
"image",
"for",
"consistent",
"labelling",
"starting",
"from",
"1",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/graphcut/energy_label.py#L407-L413 | train | 238,186 |
loli/medpy | bin/medpy_graphcut_label_bgreduced.py | __xd_iterator_pass_on | def __xd_iterator_pass_on(arr, view, fun):
"""
Like xd_iterator, but the fun return values are always passed on to the next and only the last returned.
"""
# create list of iterations
iterations = [[None] if dim in view else list(range(arr.shape[dim])) for dim in range(arr.ndim)]
# iterate, create slicer, execute function and collect results
passon = None
for indices in itertools.product(*iterations):
slicer = [slice(None) if idx is None else slice(idx, idx + 1) for idx in indices]
passon = fun(scipy.squeeze(arr[slicer]), passon)
return passon | python | def __xd_iterator_pass_on(arr, view, fun):
"""
Like xd_iterator, but the fun return values are always passed on to the next and only the last returned.
"""
# create list of iterations
iterations = [[None] if dim in view else list(range(arr.shape[dim])) for dim in range(arr.ndim)]
# iterate, create slicer, execute function and collect results
passon = None
for indices in itertools.product(*iterations):
slicer = [slice(None) if idx is None else slice(idx, idx + 1) for idx in indices]
passon = fun(scipy.squeeze(arr[slicer]), passon)
return passon | [
"def",
"__xd_iterator_pass_on",
"(",
"arr",
",",
"view",
",",
"fun",
")",
":",
"# create list of iterations",
"iterations",
"=",
"[",
"[",
"None",
"]",
"if",
"dim",
"in",
"view",
"else",
"list",
"(",
"range",
"(",
"arr",
".",
"shape",
"[",
"dim",
"]",
")",
")",
"for",
"dim",
"in",
"range",
"(",
"arr",
".",
"ndim",
")",
"]",
"# iterate, create slicer, execute function and collect results",
"passon",
"=",
"None",
"for",
"indices",
"in",
"itertools",
".",
"product",
"(",
"*",
"iterations",
")",
":",
"slicer",
"=",
"[",
"slice",
"(",
"None",
")",
"if",
"idx",
"is",
"None",
"else",
"slice",
"(",
"idx",
",",
"idx",
"+",
"1",
")",
"for",
"idx",
"in",
"indices",
"]",
"passon",
"=",
"fun",
"(",
"scipy",
".",
"squeeze",
"(",
"arr",
"[",
"slicer",
"]",
")",
",",
"passon",
")",
"return",
"passon"
] | Like xd_iterator, but the fun return values are always passed on to the next and only the last returned. | [
"Like",
"xd_iterator",
"but",
"the",
"fun",
"return",
"values",
"are",
"always",
"passed",
"on",
"to",
"the",
"next",
"and",
"only",
"the",
"last",
"returned",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/bin/medpy_graphcut_label_bgreduced.py#L176-L189 | train | 238,187 |
loli/medpy | medpy/io/header.py | set_pixel_spacing | def set_pixel_spacing(hdr, spacing):
r"""Depreciated synonym of `~medpy.io.header.set_voxel_spacing`."""
warnings.warn('get_pixel_spacing() is depreciated, use set_voxel_spacing() instead', category=DeprecationWarning)
set_voxel_spacing(hdr, spacing) | python | def set_pixel_spacing(hdr, spacing):
r"""Depreciated synonym of `~medpy.io.header.set_voxel_spacing`."""
warnings.warn('get_pixel_spacing() is depreciated, use set_voxel_spacing() instead', category=DeprecationWarning)
set_voxel_spacing(hdr, spacing) | [
"def",
"set_pixel_spacing",
"(",
"hdr",
",",
"spacing",
")",
":",
"warnings",
".",
"warn",
"(",
"'get_pixel_spacing() is depreciated, use set_voxel_spacing() instead'",
",",
"category",
"=",
"DeprecationWarning",
")",
"set_voxel_spacing",
"(",
"hdr",
",",
"spacing",
")"
] | r"""Depreciated synonym of `~medpy.io.header.set_voxel_spacing`. | [
"r",
"Depreciated",
"synonym",
"of",
"~medpy",
".",
"io",
".",
"header",
".",
"set_voxel_spacing",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/io/header.py#L100-L103 | train | 238,188 |
loli/medpy | medpy/io/header.py | Header.copy_to | def copy_to(self, sitkimage):
"""
Copy all stored meta information info to an sitk Image.
Note that only the spacing and the offset/origin information
are guaranteed to be preserved, although the method also
tries to copy other meta information such as DICOM tags.
Parameters
----------
sitkimage : sitk.Image
the sitk Image object to which to copy the information
Returns
-------
sitkimage : sitk.Image
the passed sitk Image object
"""
if self.sitkimage is not None:
for k in self.sitkimage.GetMetaDataKeys():
sitkimage.SetMetaData(k, self.sitkimage.GetMetaData(k))
ndim = len(sitkimage.GetSize())
spacing, offset, direction = self.get_info_consistent(ndim)
sitkimage.SetSpacing(spacing)
sitkimage.SetOrigin(offset)
sitkimage.SetDirection(tuple(direction.flatten()))
return sitkimage | python | def copy_to(self, sitkimage):
"""
Copy all stored meta information info to an sitk Image.
Note that only the spacing and the offset/origin information
are guaranteed to be preserved, although the method also
tries to copy other meta information such as DICOM tags.
Parameters
----------
sitkimage : sitk.Image
the sitk Image object to which to copy the information
Returns
-------
sitkimage : sitk.Image
the passed sitk Image object
"""
if self.sitkimage is not None:
for k in self.sitkimage.GetMetaDataKeys():
sitkimage.SetMetaData(k, self.sitkimage.GetMetaData(k))
ndim = len(sitkimage.GetSize())
spacing, offset, direction = self.get_info_consistent(ndim)
sitkimage.SetSpacing(spacing)
sitkimage.SetOrigin(offset)
sitkimage.SetDirection(tuple(direction.flatten()))
return sitkimage | [
"def",
"copy_to",
"(",
"self",
",",
"sitkimage",
")",
":",
"if",
"self",
".",
"sitkimage",
"is",
"not",
"None",
":",
"for",
"k",
"in",
"self",
".",
"sitkimage",
".",
"GetMetaDataKeys",
"(",
")",
":",
"sitkimage",
".",
"SetMetaData",
"(",
"k",
",",
"self",
".",
"sitkimage",
".",
"GetMetaData",
"(",
"k",
")",
")",
"ndim",
"=",
"len",
"(",
"sitkimage",
".",
"GetSize",
"(",
")",
")",
"spacing",
",",
"offset",
",",
"direction",
"=",
"self",
".",
"get_info_consistent",
"(",
"ndim",
")",
"sitkimage",
".",
"SetSpacing",
"(",
"spacing",
")",
"sitkimage",
".",
"SetOrigin",
"(",
"offset",
")",
"sitkimage",
".",
"SetDirection",
"(",
"tuple",
"(",
"direction",
".",
"flatten",
"(",
")",
")",
")",
"return",
"sitkimage"
] | Copy all stored meta information info to an sitk Image.
Note that only the spacing and the offset/origin information
are guaranteed to be preserved, although the method also
tries to copy other meta information such as DICOM tags.
Parameters
----------
sitkimage : sitk.Image
the sitk Image object to which to copy the information
Returns
-------
sitkimage : sitk.Image
the passed sitk Image object | [
"Copy",
"all",
"stored",
"meta",
"information",
"info",
"to",
"an",
"sitk",
"Image",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/io/header.py#L213-L242 | train | 238,189 |
loli/medpy | medpy/io/header.py | Header.get_info_consistent | def get_info_consistent(self, ndim):
"""
Returns the main meta-data information adapted to the supplied
image dimensionality.
It will try to resolve inconsistencies and other conflicts,
altering the information avilable int he most plausible way.
Parameters
----------
ndim : int
image's dimensionality
Returns
-------
spacing : tuple of floats
offset : tuple of floats
direction : ndarray
"""
if ndim > len(self.spacing):
spacing = self.spacing + (1.0, ) * (ndim - len(self.spacing))
else:
spacing = self.spacing[:ndim]
if ndim > len(self.offset):
offset = self.offset + (0.0, ) * (ndim - len(self.offset))
else:
offset = self.offset[:ndim]
if ndim > self.direction.shape[0]:
direction = np.identity(ndim)
direction[:self.direction.shape[0], :self.direction.shape[0]] = self.direction
else:
direction = self.direction[:ndim, :ndim]
return spacing, offset, direction | python | def get_info_consistent(self, ndim):
"""
Returns the main meta-data information adapted to the supplied
image dimensionality.
It will try to resolve inconsistencies and other conflicts,
altering the information avilable int he most plausible way.
Parameters
----------
ndim : int
image's dimensionality
Returns
-------
spacing : tuple of floats
offset : tuple of floats
direction : ndarray
"""
if ndim > len(self.spacing):
spacing = self.spacing + (1.0, ) * (ndim - len(self.spacing))
else:
spacing = self.spacing[:ndim]
if ndim > len(self.offset):
offset = self.offset + (0.0, ) * (ndim - len(self.offset))
else:
offset = self.offset[:ndim]
if ndim > self.direction.shape[0]:
direction = np.identity(ndim)
direction[:self.direction.shape[0], :self.direction.shape[0]] = self.direction
else:
direction = self.direction[:ndim, :ndim]
return spacing, offset, direction | [
"def",
"get_info_consistent",
"(",
"self",
",",
"ndim",
")",
":",
"if",
"ndim",
">",
"len",
"(",
"self",
".",
"spacing",
")",
":",
"spacing",
"=",
"self",
".",
"spacing",
"+",
"(",
"1.0",
",",
")",
"*",
"(",
"ndim",
"-",
"len",
"(",
"self",
".",
"spacing",
")",
")",
"else",
":",
"spacing",
"=",
"self",
".",
"spacing",
"[",
":",
"ndim",
"]",
"if",
"ndim",
">",
"len",
"(",
"self",
".",
"offset",
")",
":",
"offset",
"=",
"self",
".",
"offset",
"+",
"(",
"0.0",
",",
")",
"*",
"(",
"ndim",
"-",
"len",
"(",
"self",
".",
"offset",
")",
")",
"else",
":",
"offset",
"=",
"self",
".",
"offset",
"[",
":",
"ndim",
"]",
"if",
"ndim",
">",
"self",
".",
"direction",
".",
"shape",
"[",
"0",
"]",
":",
"direction",
"=",
"np",
".",
"identity",
"(",
"ndim",
")",
"direction",
"[",
":",
"self",
".",
"direction",
".",
"shape",
"[",
"0",
"]",
",",
":",
"self",
".",
"direction",
".",
"shape",
"[",
"0",
"]",
"]",
"=",
"self",
".",
"direction",
"else",
":",
"direction",
"=",
"self",
".",
"direction",
"[",
":",
"ndim",
",",
":",
"ndim",
"]",
"return",
"spacing",
",",
"offset",
",",
"direction"
] | Returns the main meta-data information adapted to the supplied
image dimensionality.
It will try to resolve inconsistencies and other conflicts,
altering the information avilable int he most plausible way.
Parameters
----------
ndim : int
image's dimensionality
Returns
-------
spacing : tuple of floats
offset : tuple of floats
direction : ndarray | [
"Returns",
"the",
"main",
"meta",
"-",
"data",
"information",
"adapted",
"to",
"the",
"supplied",
"image",
"dimensionality",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/io/header.py#L244-L279 | train | 238,190 |
loli/medpy | medpy/metric/binary.py | hd95 | def hd95(result, reference, voxelspacing=None, connectivity=1):
"""
95th percentile of the Hausdorff Distance.
Computes the 95th percentile of the (symmetric) Hausdorff Distance (HD) between the binary objects in two
images. Compared to the Hausdorff Distance, this metric is slightly more stable to small outliers and is
commonly used in Biomedical Segmentation challenges.
Parameters
----------
result : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
reference : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
voxelspacing : float or sequence of floats, optional
The voxelspacing in a distance unit i.e. spacing of elements
along each dimension. If a sequence, must be of length equal to
the input rank; if a single number, this is used for all axes. If
not specified, a grid spacing of unity is implied.
connectivity : int
The neighbourhood/connectivity considered when determining the surface
of the binary objects. This value is passed to
`scipy.ndimage.morphology.generate_binary_structure` and should usually be :math:`> 1`.
Note that the connectivity influences the result in the case of the Hausdorff distance.
Returns
-------
hd : float
The symmetric Hausdorff Distance between the object(s) in ```result``` and the
object(s) in ```reference```. The distance unit is the same as for the spacing of
elements along each dimension, which is usually given in mm.
See also
--------
:func:`hd`
Notes
-----
This is a real metric. The binary images can therefore be supplied in any order.
"""
hd1 = __surface_distances(result, reference, voxelspacing, connectivity)
hd2 = __surface_distances(reference, result, voxelspacing, connectivity)
hd95 = numpy.percentile(numpy.hstack((hd1, hd2)), 95)
return hd95 | python | def hd95(result, reference, voxelspacing=None, connectivity=1):
"""
95th percentile of the Hausdorff Distance.
Computes the 95th percentile of the (symmetric) Hausdorff Distance (HD) between the binary objects in two
images. Compared to the Hausdorff Distance, this metric is slightly more stable to small outliers and is
commonly used in Biomedical Segmentation challenges.
Parameters
----------
result : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
reference : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
voxelspacing : float or sequence of floats, optional
The voxelspacing in a distance unit i.e. spacing of elements
along each dimension. If a sequence, must be of length equal to
the input rank; if a single number, this is used for all axes. If
not specified, a grid spacing of unity is implied.
connectivity : int
The neighbourhood/connectivity considered when determining the surface
of the binary objects. This value is passed to
`scipy.ndimage.morphology.generate_binary_structure` and should usually be :math:`> 1`.
Note that the connectivity influences the result in the case of the Hausdorff distance.
Returns
-------
hd : float
The symmetric Hausdorff Distance between the object(s) in ```result``` and the
object(s) in ```reference```. The distance unit is the same as for the spacing of
elements along each dimension, which is usually given in mm.
See also
--------
:func:`hd`
Notes
-----
This is a real metric. The binary images can therefore be supplied in any order.
"""
hd1 = __surface_distances(result, reference, voxelspacing, connectivity)
hd2 = __surface_distances(reference, result, voxelspacing, connectivity)
hd95 = numpy.percentile(numpy.hstack((hd1, hd2)), 95)
return hd95 | [
"def",
"hd95",
"(",
"result",
",",
"reference",
",",
"voxelspacing",
"=",
"None",
",",
"connectivity",
"=",
"1",
")",
":",
"hd1",
"=",
"__surface_distances",
"(",
"result",
",",
"reference",
",",
"voxelspacing",
",",
"connectivity",
")",
"hd2",
"=",
"__surface_distances",
"(",
"reference",
",",
"result",
",",
"voxelspacing",
",",
"connectivity",
")",
"hd95",
"=",
"numpy",
".",
"percentile",
"(",
"numpy",
".",
"hstack",
"(",
"(",
"hd1",
",",
"hd2",
")",
")",
",",
"95",
")",
"return",
"hd95"
] | 95th percentile of the Hausdorff Distance.
Computes the 95th percentile of the (symmetric) Hausdorff Distance (HD) between the binary objects in two
images. Compared to the Hausdorff Distance, this metric is slightly more stable to small outliers and is
commonly used in Biomedical Segmentation challenges.
Parameters
----------
result : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
reference : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
voxelspacing : float or sequence of floats, optional
The voxelspacing in a distance unit i.e. spacing of elements
along each dimension. If a sequence, must be of length equal to
the input rank; if a single number, this is used for all axes. If
not specified, a grid spacing of unity is implied.
connectivity : int
The neighbourhood/connectivity considered when determining the surface
of the binary objects. This value is passed to
`scipy.ndimage.morphology.generate_binary_structure` and should usually be :math:`> 1`.
Note that the connectivity influences the result in the case of the Hausdorff distance.
Returns
-------
hd : float
The symmetric Hausdorff Distance between the object(s) in ```result``` and the
object(s) in ```reference```. The distance unit is the same as for the spacing of
elements along each dimension, which is usually given in mm.
See also
--------
:func:`hd`
Notes
-----
This is a real metric. The binary images can therefore be supplied in any order. | [
"95th",
"percentile",
"of",
"the",
"Hausdorff",
"Distance",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/metric/binary.py#L354-L399 | train | 238,191 |
loli/medpy | medpy/metric/binary.py | __surface_distances | def __surface_distances(result, reference, voxelspacing=None, connectivity=1):
"""
The distances between the surface voxel of binary objects in result and their
nearest partner surface voxel of a binary object in reference.
"""
result = numpy.atleast_1d(result.astype(numpy.bool))
reference = numpy.atleast_1d(reference.astype(numpy.bool))
if voxelspacing is not None:
voxelspacing = _ni_support._normalize_sequence(voxelspacing, result.ndim)
voxelspacing = numpy.asarray(voxelspacing, dtype=numpy.float64)
if not voxelspacing.flags.contiguous:
voxelspacing = voxelspacing.copy()
# binary structure
footprint = generate_binary_structure(result.ndim, connectivity)
# test for emptiness
if 0 == numpy.count_nonzero(result):
raise RuntimeError('The first supplied array does not contain any binary object.')
if 0 == numpy.count_nonzero(reference):
raise RuntimeError('The second supplied array does not contain any binary object.')
# extract only 1-pixel border line of objects
result_border = result ^ binary_erosion(result, structure=footprint, iterations=1)
reference_border = reference ^ binary_erosion(reference, structure=footprint, iterations=1)
# compute average surface distance
# Note: scipys distance transform is calculated only inside the borders of the
# foreground objects, therefore the input has to be reversed
dt = distance_transform_edt(~reference_border, sampling=voxelspacing)
sds = dt[result_border]
return sds | python | def __surface_distances(result, reference, voxelspacing=None, connectivity=1):
"""
The distances between the surface voxel of binary objects in result and their
nearest partner surface voxel of a binary object in reference.
"""
result = numpy.atleast_1d(result.astype(numpy.bool))
reference = numpy.atleast_1d(reference.astype(numpy.bool))
if voxelspacing is not None:
voxelspacing = _ni_support._normalize_sequence(voxelspacing, result.ndim)
voxelspacing = numpy.asarray(voxelspacing, dtype=numpy.float64)
if not voxelspacing.flags.contiguous:
voxelspacing = voxelspacing.copy()
# binary structure
footprint = generate_binary_structure(result.ndim, connectivity)
# test for emptiness
if 0 == numpy.count_nonzero(result):
raise RuntimeError('The first supplied array does not contain any binary object.')
if 0 == numpy.count_nonzero(reference):
raise RuntimeError('The second supplied array does not contain any binary object.')
# extract only 1-pixel border line of objects
result_border = result ^ binary_erosion(result, structure=footprint, iterations=1)
reference_border = reference ^ binary_erosion(reference, structure=footprint, iterations=1)
# compute average surface distance
# Note: scipys distance transform is calculated only inside the borders of the
# foreground objects, therefore the input has to be reversed
dt = distance_transform_edt(~reference_border, sampling=voxelspacing)
sds = dt[result_border]
return sds | [
"def",
"__surface_distances",
"(",
"result",
",",
"reference",
",",
"voxelspacing",
"=",
"None",
",",
"connectivity",
"=",
"1",
")",
":",
"result",
"=",
"numpy",
".",
"atleast_1d",
"(",
"result",
".",
"astype",
"(",
"numpy",
".",
"bool",
")",
")",
"reference",
"=",
"numpy",
".",
"atleast_1d",
"(",
"reference",
".",
"astype",
"(",
"numpy",
".",
"bool",
")",
")",
"if",
"voxelspacing",
"is",
"not",
"None",
":",
"voxelspacing",
"=",
"_ni_support",
".",
"_normalize_sequence",
"(",
"voxelspacing",
",",
"result",
".",
"ndim",
")",
"voxelspacing",
"=",
"numpy",
".",
"asarray",
"(",
"voxelspacing",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"if",
"not",
"voxelspacing",
".",
"flags",
".",
"contiguous",
":",
"voxelspacing",
"=",
"voxelspacing",
".",
"copy",
"(",
")",
"# binary structure",
"footprint",
"=",
"generate_binary_structure",
"(",
"result",
".",
"ndim",
",",
"connectivity",
")",
"# test for emptiness",
"if",
"0",
"==",
"numpy",
".",
"count_nonzero",
"(",
"result",
")",
":",
"raise",
"RuntimeError",
"(",
"'The first supplied array does not contain any binary object.'",
")",
"if",
"0",
"==",
"numpy",
".",
"count_nonzero",
"(",
"reference",
")",
":",
"raise",
"RuntimeError",
"(",
"'The second supplied array does not contain any binary object.'",
")",
"# extract only 1-pixel border line of objects",
"result_border",
"=",
"result",
"^",
"binary_erosion",
"(",
"result",
",",
"structure",
"=",
"footprint",
",",
"iterations",
"=",
"1",
")",
"reference_border",
"=",
"reference",
"^",
"binary_erosion",
"(",
"reference",
",",
"structure",
"=",
"footprint",
",",
"iterations",
"=",
"1",
")",
"# compute average surface distance ",
"# Note: scipys distance transform is calculated only inside the borders of the",
"# foreground objects, therefore the input has to be reversed",
"dt",
"=",
"distance_transform_edt",
"(",
"~",
"reference_border",
",",
"sampling",
"=",
"voxelspacing",
")",
"sds",
"=",
"dt",
"[",
"result_border",
"]",
"return",
"sds"
] | The distances between the surface voxel of binary objects in result and their
nearest partner surface voxel of a binary object in reference. | [
"The",
"distances",
"between",
"the",
"surface",
"voxel",
"of",
"binary",
"objects",
"in",
"result",
"and",
"their",
"nearest",
"partner",
"surface",
"voxel",
"of",
"a",
"binary",
"object",
"in",
"reference",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/metric/binary.py#L1195-L1227 | train | 238,192 |
loli/medpy | medpy/metric/histogram.py | __minowski_low_positive_integer_p | def __minowski_low_positive_integer_p(h1, h2, p = 2): # 11..43 us for p = 1..24 \w 100 bins
"""
A faster implementation of the Minowski distance for positive integer < 25.
@note do not use this function directly, but the general @link minowski() method.
@note the passed histograms must be scipy arrays.
"""
mult = scipy.absolute(h1 - h2)
dif = mult
for _ in range(p - 1): dif = scipy.multiply(dif, mult)
return math.pow(scipy.sum(dif), 1./p) | python | def __minowski_low_positive_integer_p(h1, h2, p = 2): # 11..43 us for p = 1..24 \w 100 bins
"""
A faster implementation of the Minowski distance for positive integer < 25.
@note do not use this function directly, but the general @link minowski() method.
@note the passed histograms must be scipy arrays.
"""
mult = scipy.absolute(h1 - h2)
dif = mult
for _ in range(p - 1): dif = scipy.multiply(dif, mult)
return math.pow(scipy.sum(dif), 1./p) | [
"def",
"__minowski_low_positive_integer_p",
"(",
"h1",
",",
"h2",
",",
"p",
"=",
"2",
")",
":",
"# 11..43 us for p = 1..24 \\w 100 bins",
"mult",
"=",
"scipy",
".",
"absolute",
"(",
"h1",
"-",
"h2",
")",
"dif",
"=",
"mult",
"for",
"_",
"in",
"range",
"(",
"p",
"-",
"1",
")",
":",
"dif",
"=",
"scipy",
".",
"multiply",
"(",
"dif",
",",
"mult",
")",
"return",
"math",
".",
"pow",
"(",
"scipy",
".",
"sum",
"(",
"dif",
")",
",",
"1.",
"/",
"p",
")"
] | A faster implementation of the Minowski distance for positive integer < 25.
@note do not use this function directly, but the general @link minowski() method.
@note the passed histograms must be scipy arrays. | [
"A",
"faster",
"implementation",
"of",
"the",
"Minowski",
"distance",
"for",
"positive",
"integer",
"<",
"25",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/metric/histogram.py#L95-L104 | train | 238,193 |
loli/medpy | medpy/metric/histogram.py | __kullback_leibler | def __kullback_leibler(h1, h2): # 36.3 us
"""
The actual KL implementation. @see kullback_leibler() for details.
Expects the histograms to be of type scipy.ndarray.
"""
result = h1.astype(scipy.float_)
mask = h1 != 0
result[mask] = scipy.multiply(h1[mask], scipy.log(h1[mask] / h2[mask]))
return scipy.sum(result) | python | def __kullback_leibler(h1, h2): # 36.3 us
"""
The actual KL implementation. @see kullback_leibler() for details.
Expects the histograms to be of type scipy.ndarray.
"""
result = h1.astype(scipy.float_)
mask = h1 != 0
result[mask] = scipy.multiply(h1[mask], scipy.log(h1[mask] / h2[mask]))
return scipy.sum(result) | [
"def",
"__kullback_leibler",
"(",
"h1",
",",
"h2",
")",
":",
"# 36.3 us",
"result",
"=",
"h1",
".",
"astype",
"(",
"scipy",
".",
"float_",
")",
"mask",
"=",
"h1",
"!=",
"0",
"result",
"[",
"mask",
"]",
"=",
"scipy",
".",
"multiply",
"(",
"h1",
"[",
"mask",
"]",
",",
"scipy",
".",
"log",
"(",
"h1",
"[",
"mask",
"]",
"/",
"h2",
"[",
"mask",
"]",
")",
")",
"return",
"scipy",
".",
"sum",
"(",
"result",
")"
] | The actual KL implementation. @see kullback_leibler() for details.
Expects the histograms to be of type scipy.ndarray. | [
"The",
"actual",
"KL",
"implementation",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/metric/histogram.py#L562-L570 | train | 238,194 |
loli/medpy | medpy/metric/histogram.py | __prepare_histogram | def __prepare_histogram(h1, h2):
"""Convert the histograms to scipy.ndarrays if required."""
h1 = h1 if scipy.ndarray == type(h1) else scipy.asarray(h1)
h2 = h2 if scipy.ndarray == type(h2) else scipy.asarray(h2)
if h1.shape != h2.shape or h1.size != h2.size:
raise ValueError('h1 and h2 must be of same shape and size')
return h1, h2 | python | def __prepare_histogram(h1, h2):
"""Convert the histograms to scipy.ndarrays if required."""
h1 = h1 if scipy.ndarray == type(h1) else scipy.asarray(h1)
h2 = h2 if scipy.ndarray == type(h2) else scipy.asarray(h2)
if h1.shape != h2.shape or h1.size != h2.size:
raise ValueError('h1 and h2 must be of same shape and size')
return h1, h2 | [
"def",
"__prepare_histogram",
"(",
"h1",
",",
"h2",
")",
":",
"h1",
"=",
"h1",
"if",
"scipy",
".",
"ndarray",
"==",
"type",
"(",
"h1",
")",
"else",
"scipy",
".",
"asarray",
"(",
"h1",
")",
"h2",
"=",
"h2",
"if",
"scipy",
".",
"ndarray",
"==",
"type",
"(",
"h2",
")",
"else",
"scipy",
".",
"asarray",
"(",
"h2",
")",
"if",
"h1",
".",
"shape",
"!=",
"h2",
".",
"shape",
"or",
"h1",
".",
"size",
"!=",
"h2",
".",
"size",
":",
"raise",
"ValueError",
"(",
"'h1 and h2 must be of same shape and size'",
")",
"return",
"h1",
",",
"h2"
] | Convert the histograms to scipy.ndarrays if required. | [
"Convert",
"the",
"histograms",
"to",
"scipy",
".",
"ndarrays",
"if",
"required",
"."
] | 95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5 | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/metric/histogram.py#L1246-L1252 | train | 238,195 |
minrk/findspark | findspark.py | find | def find():
"""Find a local spark installation.
Will first check the SPARK_HOME env variable, and otherwise
search common installation locations, e.g. from homebrew
"""
spark_home = os.environ.get('SPARK_HOME', None)
if not spark_home:
for path in [
'/usr/local/opt/apache-spark/libexec', # OS X Homebrew
'/usr/lib/spark/', # AWS Amazon EMR
'/usr/local/spark/', # common linux path for spark
'/opt/spark/', # other common linux path for spark
# Any other common places to look?
]:
if os.path.exists(path):
spark_home = path
break
if not spark_home:
raise ValueError("Couldn't find Spark, make sure SPARK_HOME env is set"
" or Spark is in an expected location (e.g. from homebrew installation).")
return spark_home | python | def find():
"""Find a local spark installation.
Will first check the SPARK_HOME env variable, and otherwise
search common installation locations, e.g. from homebrew
"""
spark_home = os.environ.get('SPARK_HOME', None)
if not spark_home:
for path in [
'/usr/local/opt/apache-spark/libexec', # OS X Homebrew
'/usr/lib/spark/', # AWS Amazon EMR
'/usr/local/spark/', # common linux path for spark
'/opt/spark/', # other common linux path for spark
# Any other common places to look?
]:
if os.path.exists(path):
spark_home = path
break
if not spark_home:
raise ValueError("Couldn't find Spark, make sure SPARK_HOME env is set"
" or Spark is in an expected location (e.g. from homebrew installation).")
return spark_home | [
"def",
"find",
"(",
")",
":",
"spark_home",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SPARK_HOME'",
",",
"None",
")",
"if",
"not",
"spark_home",
":",
"for",
"path",
"in",
"[",
"'/usr/local/opt/apache-spark/libexec'",
",",
"# OS X Homebrew",
"'/usr/lib/spark/'",
",",
"# AWS Amazon EMR",
"'/usr/local/spark/'",
",",
"# common linux path for spark",
"'/opt/spark/'",
",",
"# other common linux path for spark",
"# Any other common places to look?",
"]",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"spark_home",
"=",
"path",
"break",
"if",
"not",
"spark_home",
":",
"raise",
"ValueError",
"(",
"\"Couldn't find Spark, make sure SPARK_HOME env is set\"",
"\" or Spark is in an expected location (e.g. from homebrew installation).\"",
")",
"return",
"spark_home"
] | Find a local spark installation.
Will first check the SPARK_HOME env variable, and otherwise
search common installation locations, e.g. from homebrew | [
"Find",
"a",
"local",
"spark",
"installation",
"."
] | 20c945d5136269ca56b1341786c49087faa7c75e | https://github.com/minrk/findspark/blob/20c945d5136269ca56b1341786c49087faa7c75e/findspark.py#L14-L38 | train | 238,196 |
minrk/findspark | findspark.py | change_rc | def change_rc(spark_home, spark_python, py4j):
"""Persists changes to environment by changing shell config.
Adds lines to .bashrc to set environment variables
including the adding of dependencies to the system path. Will only
edit this file if they already exist. Currently only works for bash.
Parameters
----------
spark_home : str
Path to Spark installation.
spark_python : str
Path to python subdirectory of Spark installation.
py4j : str
Path to py4j library.
"""
bashrc_location = os.path.expanduser("~/.bashrc")
if os.path.isfile(bashrc_location):
with open(bashrc_location, 'a') as bashrc:
bashrc.write("\n# Added by findspark\n")
bashrc.write("export SPARK_HOME=" + spark_home + "\n")
bashrc.write("export PYTHONPATH=" + spark_python + ":" +
py4j + ":$PYTHONPATH\n\n") | python | def change_rc(spark_home, spark_python, py4j):
"""Persists changes to environment by changing shell config.
Adds lines to .bashrc to set environment variables
including the adding of dependencies to the system path. Will only
edit this file if they already exist. Currently only works for bash.
Parameters
----------
spark_home : str
Path to Spark installation.
spark_python : str
Path to python subdirectory of Spark installation.
py4j : str
Path to py4j library.
"""
bashrc_location = os.path.expanduser("~/.bashrc")
if os.path.isfile(bashrc_location):
with open(bashrc_location, 'a') as bashrc:
bashrc.write("\n# Added by findspark\n")
bashrc.write("export SPARK_HOME=" + spark_home + "\n")
bashrc.write("export PYTHONPATH=" + spark_python + ":" +
py4j + ":$PYTHONPATH\n\n") | [
"def",
"change_rc",
"(",
"spark_home",
",",
"spark_python",
",",
"py4j",
")",
":",
"bashrc_location",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~/.bashrc\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"bashrc_location",
")",
":",
"with",
"open",
"(",
"bashrc_location",
",",
"'a'",
")",
"as",
"bashrc",
":",
"bashrc",
".",
"write",
"(",
"\"\\n# Added by findspark\\n\"",
")",
"bashrc",
".",
"write",
"(",
"\"export SPARK_HOME=\"",
"+",
"spark_home",
"+",
"\"\\n\"",
")",
"bashrc",
".",
"write",
"(",
"\"export PYTHONPATH=\"",
"+",
"spark_python",
"+",
"\":\"",
"+",
"py4j",
"+",
"\":$PYTHONPATH\\n\\n\"",
")"
] | Persists changes to environment by changing shell config.
Adds lines to .bashrc to set environment variables
including the adding of dependencies to the system path. Will only
edit this file if they already exist. Currently only works for bash.
Parameters
----------
spark_home : str
Path to Spark installation.
spark_python : str
Path to python subdirectory of Spark installation.
py4j : str
Path to py4j library. | [
"Persists",
"changes",
"to",
"environment",
"by",
"changing",
"shell",
"config",
"."
] | 20c945d5136269ca56b1341786c49087faa7c75e | https://github.com/minrk/findspark/blob/20c945d5136269ca56b1341786c49087faa7c75e/findspark.py#L41-L65 | train | 238,197 |
minrk/findspark | findspark.py | edit_ipython_profile | def edit_ipython_profile(spark_home, spark_python, py4j):
"""Adds a startup file to the current IPython profile to import pyspark.
The startup file sets the required environment variables and imports pyspark.
Parameters
----------
spark_home : str
Path to Spark installation.
spark_python : str
Path to python subdirectory of Spark installation.
py4j : str
Path to py4j library.
"""
from IPython import get_ipython
ip = get_ipython()
if ip:
profile_dir = ip.profile_dir.location
else:
from IPython.utils.path import locate_profile
profile_dir = locate_profile()
startup_file_loc = os.path.join(profile_dir, "startup", "findspark.py")
with open(startup_file_loc, 'w') as startup_file:
#Lines of code to be run when IPython starts
startup_file.write("import sys, os\n")
startup_file.write("os.environ['SPARK_HOME'] = '" + spark_home + "'\n")
startup_file.write("sys.path[:0] = " + str([spark_python, py4j]) + "\n")
startup_file.write("import pyspark\n") | python | def edit_ipython_profile(spark_home, spark_python, py4j):
"""Adds a startup file to the current IPython profile to import pyspark.
The startup file sets the required environment variables and imports pyspark.
Parameters
----------
spark_home : str
Path to Spark installation.
spark_python : str
Path to python subdirectory of Spark installation.
py4j : str
Path to py4j library.
"""
from IPython import get_ipython
ip = get_ipython()
if ip:
profile_dir = ip.profile_dir.location
else:
from IPython.utils.path import locate_profile
profile_dir = locate_profile()
startup_file_loc = os.path.join(profile_dir, "startup", "findspark.py")
with open(startup_file_loc, 'w') as startup_file:
#Lines of code to be run when IPython starts
startup_file.write("import sys, os\n")
startup_file.write("os.environ['SPARK_HOME'] = '" + spark_home + "'\n")
startup_file.write("sys.path[:0] = " + str([spark_python, py4j]) + "\n")
startup_file.write("import pyspark\n") | [
"def",
"edit_ipython_profile",
"(",
"spark_home",
",",
"spark_python",
",",
"py4j",
")",
":",
"from",
"IPython",
"import",
"get_ipython",
"ip",
"=",
"get_ipython",
"(",
")",
"if",
"ip",
":",
"profile_dir",
"=",
"ip",
".",
"profile_dir",
".",
"location",
"else",
":",
"from",
"IPython",
".",
"utils",
".",
"path",
"import",
"locate_profile",
"profile_dir",
"=",
"locate_profile",
"(",
")",
"startup_file_loc",
"=",
"os",
".",
"path",
".",
"join",
"(",
"profile_dir",
",",
"\"startup\"",
",",
"\"findspark.py\"",
")",
"with",
"open",
"(",
"startup_file_loc",
",",
"'w'",
")",
"as",
"startup_file",
":",
"#Lines of code to be run when IPython starts",
"startup_file",
".",
"write",
"(",
"\"import sys, os\\n\"",
")",
"startup_file",
".",
"write",
"(",
"\"os.environ['SPARK_HOME'] = '\"",
"+",
"spark_home",
"+",
"\"'\\n\"",
")",
"startup_file",
".",
"write",
"(",
"\"sys.path[:0] = \"",
"+",
"str",
"(",
"[",
"spark_python",
",",
"py4j",
"]",
")",
"+",
"\"\\n\"",
")",
"startup_file",
".",
"write",
"(",
"\"import pyspark\\n\"",
")"
] | Adds a startup file to the current IPython profile to import pyspark.
The startup file sets the required environment variables and imports pyspark.
Parameters
----------
spark_home : str
Path to Spark installation.
spark_python : str
Path to python subdirectory of Spark installation.
py4j : str
Path to py4j library. | [
"Adds",
"a",
"startup",
"file",
"to",
"the",
"current",
"IPython",
"profile",
"to",
"import",
"pyspark",
"."
] | 20c945d5136269ca56b1341786c49087faa7c75e | https://github.com/minrk/findspark/blob/20c945d5136269ca56b1341786c49087faa7c75e/findspark.py#L68-L98 | train | 238,198 |
minrk/findspark | findspark.py | init | def init(spark_home=None, python_path=None, edit_rc=False, edit_profile=False):
"""Make pyspark importable.
Sets environment variables and adds dependencies to sys.path.
If no Spark location is provided, will try to find an installation.
Parameters
----------
spark_home : str, optional, default = None
Path to Spark installation, will try to find automatically
if not provided.
python_path : str, optional, default = None
Path to Python for Spark workers (PYSPARK_PYTHON),
will use the currently running Python if not provided.
edit_rc : bool, optional, default = False
Whether to attempt to persist changes by appending to shell
config.
edit_profile : bool, optional, default = False
Whether to create an IPython startup file to automatically
configure and import pyspark.
"""
if not spark_home:
spark_home = find()
if not python_path:
python_path = os.environ.get('PYSPARK_PYTHON', sys.executable)
# ensure SPARK_HOME is defined
os.environ['SPARK_HOME'] = spark_home
# ensure PYSPARK_PYTHON is defined
os.environ['PYSPARK_PYTHON'] = python_path
if not os.environ.get("PYSPARK_SUBMIT_ARGS", None):
os.environ["PYSPARK_SUBMIT_ARGS"] = ''
# add pyspark to sys.path
spark_python = os.path.join(spark_home, 'python')
py4j = glob(os.path.join(spark_python, 'lib', 'py4j-*.zip'))[0]
sys.path[:0] = [spark_python, py4j]
if edit_rc:
change_rc(spark_home, spark_python, py4j)
if edit_profile:
edit_ipython_profile(spark_home, spark_python, py4j) | python | def init(spark_home=None, python_path=None, edit_rc=False, edit_profile=False):
"""Make pyspark importable.
Sets environment variables and adds dependencies to sys.path.
If no Spark location is provided, will try to find an installation.
Parameters
----------
spark_home : str, optional, default = None
Path to Spark installation, will try to find automatically
if not provided.
python_path : str, optional, default = None
Path to Python for Spark workers (PYSPARK_PYTHON),
will use the currently running Python if not provided.
edit_rc : bool, optional, default = False
Whether to attempt to persist changes by appending to shell
config.
edit_profile : bool, optional, default = False
Whether to create an IPython startup file to automatically
configure and import pyspark.
"""
if not spark_home:
spark_home = find()
if not python_path:
python_path = os.environ.get('PYSPARK_PYTHON', sys.executable)
# ensure SPARK_HOME is defined
os.environ['SPARK_HOME'] = spark_home
# ensure PYSPARK_PYTHON is defined
os.environ['PYSPARK_PYTHON'] = python_path
if not os.environ.get("PYSPARK_SUBMIT_ARGS", None):
os.environ["PYSPARK_SUBMIT_ARGS"] = ''
# add pyspark to sys.path
spark_python = os.path.join(spark_home, 'python')
py4j = glob(os.path.join(spark_python, 'lib', 'py4j-*.zip'))[0]
sys.path[:0] = [spark_python, py4j]
if edit_rc:
change_rc(spark_home, spark_python, py4j)
if edit_profile:
edit_ipython_profile(spark_home, spark_python, py4j) | [
"def",
"init",
"(",
"spark_home",
"=",
"None",
",",
"python_path",
"=",
"None",
",",
"edit_rc",
"=",
"False",
",",
"edit_profile",
"=",
"False",
")",
":",
"if",
"not",
"spark_home",
":",
"spark_home",
"=",
"find",
"(",
")",
"if",
"not",
"python_path",
":",
"python_path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PYSPARK_PYTHON'",
",",
"sys",
".",
"executable",
")",
"# ensure SPARK_HOME is defined",
"os",
".",
"environ",
"[",
"'SPARK_HOME'",
"]",
"=",
"spark_home",
"# ensure PYSPARK_PYTHON is defined",
"os",
".",
"environ",
"[",
"'PYSPARK_PYTHON'",
"]",
"=",
"python_path",
"if",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"\"PYSPARK_SUBMIT_ARGS\"",
",",
"None",
")",
":",
"os",
".",
"environ",
"[",
"\"PYSPARK_SUBMIT_ARGS\"",
"]",
"=",
"''",
"# add pyspark to sys.path",
"spark_python",
"=",
"os",
".",
"path",
".",
"join",
"(",
"spark_home",
",",
"'python'",
")",
"py4j",
"=",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"spark_python",
",",
"'lib'",
",",
"'py4j-*.zip'",
")",
")",
"[",
"0",
"]",
"sys",
".",
"path",
"[",
":",
"0",
"]",
"=",
"[",
"spark_python",
",",
"py4j",
"]",
"if",
"edit_rc",
":",
"change_rc",
"(",
"spark_home",
",",
"spark_python",
",",
"py4j",
")",
"if",
"edit_profile",
":",
"edit_ipython_profile",
"(",
"spark_home",
",",
"spark_python",
",",
"py4j",
")"
] | Make pyspark importable.
Sets environment variables and adds dependencies to sys.path.
If no Spark location is provided, will try to find an installation.
Parameters
----------
spark_home : str, optional, default = None
Path to Spark installation, will try to find automatically
if not provided.
python_path : str, optional, default = None
Path to Python for Spark workers (PYSPARK_PYTHON),
will use the currently running Python if not provided.
edit_rc : bool, optional, default = False
Whether to attempt to persist changes by appending to shell
config.
edit_profile : bool, optional, default = False
Whether to create an IPython startup file to automatically
configure and import pyspark. | [
"Make",
"pyspark",
"importable",
"."
] | 20c945d5136269ca56b1341786c49087faa7c75e | https://github.com/minrk/findspark/blob/20c945d5136269ca56b1341786c49087faa7c75e/findspark.py#L101-L147 | train | 238,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.