repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | html_visit | def html_visit(self, node):
"""
Visitor method for Need-node of builder 'html'.
Does only wrap the Need-content into an extra <div> with class=need
"""
self.body.append(self.starttag(node, 'div', '', CLASS='need')) | python | def html_visit(self, node):
"""
Visitor method for Need-node of builder 'html'.
Does only wrap the Need-content into an extra <div> with class=need
"""
self.body.append(self.starttag(node, 'div', '', CLASS='need')) | [
"def",
"html_visit",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"body",
".",
"append",
"(",
"self",
".",
"starttag",
"(",
"node",
",",
"'div'",
",",
"''",
",",
"CLASS",
"=",
"'need'",
")",
")"
] | Visitor method for Need-node of builder 'html'.
Does only wrap the Need-content into an extra <div> with class=need | [
"Visitor",
"method",
"for",
"Need",
"-",
"node",
"of",
"builder",
"html",
".",
"Does",
"only",
"wrap",
"the",
"Need",
"-",
"content",
"into",
"an",
"extra",
"<div",
">",
"with",
"class",
"=",
"need"
] | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L662-L667 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | NeedDirective.merge_extra_options | def merge_extra_options(self, needs_info):
"""Add any extra options introduced via options_ext to needs_info"""
extra_keys = set(self.options.keys()).difference(set(needs_info.keys()))
for key in extra_keys:
needs_info[key] = self.options[key]
# Finally add all not used extra options with empty value to need_info.
# Needed for filters, which need to access these empty/not used options.
for key in self.option_spec:
if key not in needs_info.keys():
needs_info[key] = ""
return extra_keys | python | def merge_extra_options(self, needs_info):
"""Add any extra options introduced via options_ext to needs_info"""
extra_keys = set(self.options.keys()).difference(set(needs_info.keys()))
for key in extra_keys:
needs_info[key] = self.options[key]
# Finally add all not used extra options with empty value to need_info.
# Needed for filters, which need to access these empty/not used options.
for key in self.option_spec:
if key not in needs_info.keys():
needs_info[key] = ""
return extra_keys | [
"def",
"merge_extra_options",
"(",
"self",
",",
"needs_info",
")",
":",
"extra_keys",
"=",
"set",
"(",
"self",
".",
"options",
".",
"keys",
"(",
")",
")",
".",
"difference",
"(",
"set",
"(",
"needs_info",
".",
"keys",
"(",
")",
")",
")",
"for",
"key"... | Add any extra options introduced via options_ext to needs_info | [
"Add",
"any",
"extra",
"options",
"introduced",
"via",
"options_ext",
"to",
"needs_info"
] | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L299-L311 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | NeedDirective.merge_global_options | def merge_global_options(self, needs_info):
"""Add all global defined options to needs_info"""
global_options = getattr(self.env.app.config, 'needs_global_options', None)
if global_options is None:
return
for key, value in global_options.items():
# If key already exists in needs_info, this global_option got overwritten manually in current need
if key in needs_info.keys():
continue
needs_info[key] = value | python | def merge_global_options(self, needs_info):
"""Add all global defined options to needs_info"""
global_options = getattr(self.env.app.config, 'needs_global_options', None)
if global_options is None:
return
for key, value in global_options.items():
# If key already exists in needs_info, this global_option got overwritten manually in current need
if key in needs_info.keys():
continue
needs_info[key] = value | [
"def",
"merge_global_options",
"(",
"self",
",",
"needs_info",
")",
":",
"global_options",
"=",
"getattr",
"(",
"self",
".",
"env",
".",
"app",
".",
"config",
",",
"'needs_global_options'",
",",
"None",
")",
"if",
"global_options",
"is",
"None",
":",
"return... | Add all global defined options to needs_info | [
"Add",
"all",
"global",
"defined",
"options",
"to",
"needs_info"
] | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L313-L324 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | NeedDirective._get_full_title | def _get_full_title(self):
"""Determines the title for the need in order of precedence:
directive argument, first sentence of requirement (if
`:title_from_content:` was set, and '' if no title is to be derived."""
if len(self.arguments) > 0: # a title was passed
if 'title_from_content' in self.options:
self.log.warning(
'Needs: need "{}" has :title_from_content: set, '
'but a title was provided. (see file {})'
.format(self.arguments[0], self.docname)
)
return self.arguments[0]
elif self.title_from_content:
first_sentence = ' '.join(self.content).split('.', 1)[0]
if not first_sentence:
raise NeedsInvalidException(':title_from_content: set, but '
'no content provided. '
'(Line {} of file {}'
.format(self.lineno, self.docname))
return first_sentence
else:
return '' | python | def _get_full_title(self):
"""Determines the title for the need in order of precedence:
directive argument, first sentence of requirement (if
`:title_from_content:` was set, and '' if no title is to be derived."""
if len(self.arguments) > 0: # a title was passed
if 'title_from_content' in self.options:
self.log.warning(
'Needs: need "{}" has :title_from_content: set, '
'but a title was provided. (see file {})'
.format(self.arguments[0], self.docname)
)
return self.arguments[0]
elif self.title_from_content:
first_sentence = ' '.join(self.content).split('.', 1)[0]
if not first_sentence:
raise NeedsInvalidException(':title_from_content: set, but '
'no content provided. '
'(Line {} of file {}'
.format(self.lineno, self.docname))
return first_sentence
else:
return '' | [
"def",
"_get_full_title",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"arguments",
")",
">",
"0",
":",
"# a title was passed",
"if",
"'title_from_content'",
"in",
"self",
".",
"options",
":",
"self",
".",
"log",
".",
"warning",
"(",
"'Needs: need... | Determines the title for the need in order of precedence:
directive argument, first sentence of requirement (if
`:title_from_content:` was set, and '' if no title is to be derived. | [
"Determines",
"the",
"title",
"for",
"the",
"need",
"in",
"order",
"of",
"precedence",
":",
"directive",
"argument",
"first",
"sentence",
"of",
"requirement",
"(",
"if",
":",
"title_from_content",
":",
"was",
"set",
"and",
"if",
"no",
"title",
"is",
"to",
... | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L326-L347 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/needlist.py | process_needlist | def process_needlist(app, doctree, fromdocname):
"""
Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location.
"""
env = app.builder.env
for node in doctree.traverse(Needlist):
if not app.config.needs_include_needs:
# Ok, this is really dirty.
# If we replace a node, docutils checks, if it will not lose any attributes.
# But this is here the case, because we are using the attribute "ids" of a node.
# However, I do not understand, why losing an attribute is such a big deal, so we delete everything
# before docutils claims about it.
for att in ('ids', 'names', 'classes', 'dupnames'):
node[att] = []
node.replace_self([])
continue
id = node.attributes["ids"][0]
current_needfilter = env.need_all_needlists[id]
all_needs = env.needs_all_needs
content = []
all_needs = list(all_needs.values())
if current_needfilter["sort_by"] is not None:
if current_needfilter["sort_by"] == "id":
all_needs = sorted(all_needs, key=lambda node: node["id"])
elif current_needfilter["sort_by"] == "status":
all_needs = sorted(all_needs, key=status_sorter)
found_needs = procces_filters(all_needs, current_needfilter)
line_block = nodes.line_block()
for need_info in found_needs:
para = nodes.line()
description = "%s: %s" % (need_info["id"], need_info["title"])
if current_needfilter["show_status"] and need_info["status"] is not None:
description += " (%s)" % need_info["status"]
if current_needfilter["show_tags"] and need_info["tags"] is not None:
description += " [%s]" % "; ".join(need_info["tags"])
title = nodes.Text(description, description)
# Create a reference
if not need_info["hide"]:
ref = nodes.reference('', '')
ref['refdocname'] = need_info['docname']
ref['refuri'] = app.builder.get_relative_uri(
fromdocname, need_info['docname'])
ref['refuri'] += '#' + need_info['target_node']['refid']
ref.append(title)
para += ref
else:
para += title
line_block.append(para)
content.append(line_block)
if len(content) == 0:
content.append(no_needs_found_paragraph())
if current_needfilter["show_filters"]:
content.append(used_filter_paragraph(current_needfilter))
node.replace_self(content) | python | def process_needlist(app, doctree, fromdocname):
"""
Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location.
"""
env = app.builder.env
for node in doctree.traverse(Needlist):
if not app.config.needs_include_needs:
# Ok, this is really dirty.
# If we replace a node, docutils checks, if it will not lose any attributes.
# But this is here the case, because we are using the attribute "ids" of a node.
# However, I do not understand, why losing an attribute is such a big deal, so we delete everything
# before docutils claims about it.
for att in ('ids', 'names', 'classes', 'dupnames'):
node[att] = []
node.replace_self([])
continue
id = node.attributes["ids"][0]
current_needfilter = env.need_all_needlists[id]
all_needs = env.needs_all_needs
content = []
all_needs = list(all_needs.values())
if current_needfilter["sort_by"] is not None:
if current_needfilter["sort_by"] == "id":
all_needs = sorted(all_needs, key=lambda node: node["id"])
elif current_needfilter["sort_by"] == "status":
all_needs = sorted(all_needs, key=status_sorter)
found_needs = procces_filters(all_needs, current_needfilter)
line_block = nodes.line_block()
for need_info in found_needs:
para = nodes.line()
description = "%s: %s" % (need_info["id"], need_info["title"])
if current_needfilter["show_status"] and need_info["status"] is not None:
description += " (%s)" % need_info["status"]
if current_needfilter["show_tags"] and need_info["tags"] is not None:
description += " [%s]" % "; ".join(need_info["tags"])
title = nodes.Text(description, description)
# Create a reference
if not need_info["hide"]:
ref = nodes.reference('', '')
ref['refdocname'] = need_info['docname']
ref['refuri'] = app.builder.get_relative_uri(
fromdocname, need_info['docname'])
ref['refuri'] += '#' + need_info['target_node']['refid']
ref.append(title)
para += ref
else:
para += title
line_block.append(para)
content.append(line_block)
if len(content) == 0:
content.append(no_needs_found_paragraph())
if current_needfilter["show_filters"]:
content.append(used_filter_paragraph(current_needfilter))
node.replace_self(content) | [
"def",
"process_needlist",
"(",
"app",
",",
"doctree",
",",
"fromdocname",
")",
":",
"env",
"=",
"app",
".",
"builder",
".",
"env",
"for",
"node",
"in",
"doctree",
".",
"traverse",
"(",
"Needlist",
")",
":",
"if",
"not",
"app",
".",
"config",
".",
"n... | Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location. | [
"Replace",
"all",
"needlist",
"nodes",
"with",
"a",
"list",
"of",
"the",
"collected",
"needs",
".",
"Augment",
"each",
"need",
"with",
"a",
"backlink",
"to",
"the",
"original",
"location",
"."
] | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/needlist.py#L69-L135 |
mfussenegger/cr8 | cr8/misc.py | parse_version | def parse_version(version: str) -> tuple:
"""Parse a string formatted X[.Y.Z] version number into a tuple
>>> parse_version('10.2.3')
(10, 2, 3)
>>> parse_version('12')
(12, 0, 0)
"""
if not version:
return None
parts = version.split('.')
missing = 3 - len(parts)
return tuple(int(i) for i in parts + ([0] * missing)) | python | def parse_version(version: str) -> tuple:
"""Parse a string formatted X[.Y.Z] version number into a tuple
>>> parse_version('10.2.3')
(10, 2, 3)
>>> parse_version('12')
(12, 0, 0)
"""
if not version:
return None
parts = version.split('.')
missing = 3 - len(parts)
return tuple(int(i) for i in parts + ([0] * missing)) | [
"def",
"parse_version",
"(",
"version",
":",
"str",
")",
"->",
"tuple",
":",
"if",
"not",
"version",
":",
"return",
"None",
"parts",
"=",
"version",
".",
"split",
"(",
"'.'",
")",
"missing",
"=",
"3",
"-",
"len",
"(",
"parts",
")",
"return",
"tuple",... | Parse a string formatted X[.Y.Z] version number into a tuple
>>> parse_version('10.2.3')
(10, 2, 3)
>>> parse_version('12')
(12, 0, 0) | [
"Parse",
"a",
"string",
"formatted",
"X",
"[",
".",
"Y",
".",
"Z",
"]",
"version",
"number",
"into",
"a",
"tuple"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L33-L46 |
mfussenegger/cr8 | cr8/misc.py | parse_table | def parse_table(fq_table: str) -> Tuple[str, str]:
"""Parse a tablename into tuple(<schema>, <table>).
Schema defaults to doc if the table name doesn't contain a schema.
>>> parse_table('x.users')
('x', 'users')
>>> parse_table('users')
('doc', 'users')
"""
parts = fq_table.split('.')
if len(parts) == 1:
return 'doc', parts[0]
elif len(parts) == 2:
return parts[0], parts[1]
else:
raise ValueError | python | def parse_table(fq_table: str) -> Tuple[str, str]:
"""Parse a tablename into tuple(<schema>, <table>).
Schema defaults to doc if the table name doesn't contain a schema.
>>> parse_table('x.users')
('x', 'users')
>>> parse_table('users')
('doc', 'users')
"""
parts = fq_table.split('.')
if len(parts) == 1:
return 'doc', parts[0]
elif len(parts) == 2:
return parts[0], parts[1]
else:
raise ValueError | [
"def",
"parse_table",
"(",
"fq_table",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"parts",
"=",
"fq_table",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"return",
"'doc'",
",",
"parts",
"["... | Parse a tablename into tuple(<schema>, <table>).
Schema defaults to doc if the table name doesn't contain a schema.
>>> parse_table('x.users')
('x', 'users')
>>> parse_table('users')
('doc', 'users') | [
"Parse",
"a",
"tablename",
"into",
"tuple",
"(",
"<schema",
">",
"<table",
">",
")",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L49-L66 |
mfussenegger/cr8 | cr8/misc.py | as_bulk_queries | def as_bulk_queries(queries, bulk_size):
"""Group a iterable of (stmt, args) by stmt into (stmt, bulk_args).
bulk_args will be a list of the args grouped by stmt.
len(bulk_args) will be <= bulk_size
"""
stmt_dict = defaultdict(list)
for stmt, args in queries:
bulk_args = stmt_dict[stmt]
bulk_args.append(args)
if len(bulk_args) == bulk_size:
yield stmt, bulk_args
del stmt_dict[stmt]
for stmt, bulk_args in stmt_dict.items():
yield stmt, bulk_args | python | def as_bulk_queries(queries, bulk_size):
"""Group a iterable of (stmt, args) by stmt into (stmt, bulk_args).
bulk_args will be a list of the args grouped by stmt.
len(bulk_args) will be <= bulk_size
"""
stmt_dict = defaultdict(list)
for stmt, args in queries:
bulk_args = stmt_dict[stmt]
bulk_args.append(args)
if len(bulk_args) == bulk_size:
yield stmt, bulk_args
del stmt_dict[stmt]
for stmt, bulk_args in stmt_dict.items():
yield stmt, bulk_args | [
"def",
"as_bulk_queries",
"(",
"queries",
",",
"bulk_size",
")",
":",
"stmt_dict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"stmt",
",",
"args",
"in",
"queries",
":",
"bulk_args",
"=",
"stmt_dict",
"[",
"stmt",
"]",
"bulk_args",
".",
"append",
"(",
"... | Group a iterable of (stmt, args) by stmt into (stmt, bulk_args).
bulk_args will be a list of the args grouped by stmt.
len(bulk_args) will be <= bulk_size | [
"Group",
"a",
"iterable",
"of",
"(",
"stmt",
"args",
")",
"by",
"stmt",
"into",
"(",
"stmt",
"bulk_args",
")",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L69-L84 |
mfussenegger/cr8 | cr8/misc.py | get_lines | def get_lines(filename: str) -> Iterator[str]:
"""Create an iterator that returns the lines of a utf-8 encoded file."""
if filename.endswith('.gz'):
with gzip.open(filename, 'r') as f:
for line in f:
yield line.decode('utf-8')
else:
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
yield line | python | def get_lines(filename: str) -> Iterator[str]:
"""Create an iterator that returns the lines of a utf-8 encoded file."""
if filename.endswith('.gz'):
with gzip.open(filename, 'r') as f:
for line in f:
yield line.decode('utf-8')
else:
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
yield line | [
"def",
"get_lines",
"(",
"filename",
":",
"str",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
... | Create an iterator that returns the lines of a utf-8 encoded file. | [
"Create",
"an",
"iterator",
"that",
"returns",
"the",
"lines",
"of",
"a",
"utf",
"-",
"8",
"encoded",
"file",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L87-L96 |
mfussenegger/cr8 | cr8/misc.py | as_statements | def as_statements(lines: Iterator[str]) -> Iterator[str]:
"""Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered', 't;']))
['select * from t']
>>> list(as_statements(['a;', 'b', 'c;', 'd', ' ']))
['a', 'b c', 'd']
"""
lines = (l.strip() for l in lines if l)
lines = (l for l in lines if l and not l.startswith('--'))
parts = []
for line in lines:
parts.append(line.rstrip(';'))
if line.endswith(';'):
yield ' '.join(parts)
parts.clear()
if parts:
yield ' '.join(parts) | python | def as_statements(lines: Iterator[str]) -> Iterator[str]:
"""Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered', 't;']))
['select * from t']
>>> list(as_statements(['a;', 'b', 'c;', 'd', ' ']))
['a', 'b c', 'd']
"""
lines = (l.strip() for l in lines if l)
lines = (l for l in lines if l and not l.startswith('--'))
parts = []
for line in lines:
parts.append(line.rstrip(';'))
if line.endswith(';'):
yield ' '.join(parts)
parts.clear()
if parts:
yield ' '.join(parts) | [
"def",
"as_statements",
"(",
"lines",
":",
"Iterator",
"[",
"str",
"]",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"lines",
"=",
"(",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"lines",
"if",
"l",
")",
"lines",
"=",
"(",
"l",
"for",
"l",
... | Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered', 't;']))
['select * from t']
>>> list(as_statements(['a;', 'b', 'c;', 'd', ' ']))
['a', 'b c', 'd'] | [
"Create",
"an",
"iterator",
"that",
"transforms",
"lines",
"into",
"sql",
"statements",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L99-L120 |
mfussenegger/cr8 | cr8/misc.py | break_iterable | def break_iterable(iterable, pred):
"""Break a iterable on the item that matches the predicate into lists.
The item that matched the predicate is not included in the result.
>>> list(break_iterable([1, 2, 3, 4], lambda x: x == 3))
[[1, 2], [4]]
"""
sublist = []
for i in iterable:
if pred(i):
yield sublist
sublist = []
else:
sublist.append(i)
yield sublist | python | def break_iterable(iterable, pred):
"""Break a iterable on the item that matches the predicate into lists.
The item that matched the predicate is not included in the result.
>>> list(break_iterable([1, 2, 3, 4], lambda x: x == 3))
[[1, 2], [4]]
"""
sublist = []
for i in iterable:
if pred(i):
yield sublist
sublist = []
else:
sublist.append(i)
yield sublist | [
"def",
"break_iterable",
"(",
"iterable",
",",
"pred",
")",
":",
"sublist",
"=",
"[",
"]",
"for",
"i",
"in",
"iterable",
":",
"if",
"pred",
"(",
"i",
")",
":",
"yield",
"sublist",
"sublist",
"=",
"[",
"]",
"else",
":",
"sublist",
".",
"append",
"("... | Break a iterable on the item that matches the predicate into lists.
The item that matched the predicate is not included in the result.
>>> list(break_iterable([1, 2, 3, 4], lambda x: x == 3))
[[1, 2], [4]] | [
"Break",
"a",
"iterable",
"on",
"the",
"item",
"that",
"matches",
"the",
"predicate",
"into",
"lists",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L123-L138 |
nickmckay/LiPD-utilities | Python/lipd/bag.py | create_bag | def create_bag(dir_bag):
"""
Create a Bag out of given files.
:param str dir_bag: Directory that contains csv, jsonld, and changelog files.
:return obj: Bag
"""
logger_bagit.info("enter create_bag")
# if not dir_bag:
# dir_bag = os.getcwd()
try:
bag = bagit.make_bag(dir_bag, {'Name': 'LiPD Project', 'Reference': 'www.lipds.net', 'DOI-Resolved': 'True'})
logger_bagit.info("created bag")
return bag
except FileNotFoundError as e:
print("Error: directory not found to create bagit")
logger_bagit.debug("create_bag: FileNotFoundError: failed to create bagit, {}".format(e))
except Exception as e:
print("Error: failed to create bagit bag")
logger_bagit.debug("create_bag: Exception: failed to create bag, {}".format(e))
return None | python | def create_bag(dir_bag):
"""
Create a Bag out of given files.
:param str dir_bag: Directory that contains csv, jsonld, and changelog files.
:return obj: Bag
"""
logger_bagit.info("enter create_bag")
# if not dir_bag:
# dir_bag = os.getcwd()
try:
bag = bagit.make_bag(dir_bag, {'Name': 'LiPD Project', 'Reference': 'www.lipds.net', 'DOI-Resolved': 'True'})
logger_bagit.info("created bag")
return bag
except FileNotFoundError as e:
print("Error: directory not found to create bagit")
logger_bagit.debug("create_bag: FileNotFoundError: failed to create bagit, {}".format(e))
except Exception as e:
print("Error: failed to create bagit bag")
logger_bagit.debug("create_bag: Exception: failed to create bag, {}".format(e))
return None | [
"def",
"create_bag",
"(",
"dir_bag",
")",
":",
"logger_bagit",
".",
"info",
"(",
"\"enter create_bag\"",
")",
"# if not dir_bag:",
"# dir_bag = os.getcwd()",
"try",
":",
"bag",
"=",
"bagit",
".",
"make_bag",
"(",
"dir_bag",
",",
"{",
"'Name'",
":",
"'LiPD Pr... | Create a Bag out of given files.
:param str dir_bag: Directory that contains csv, jsonld, and changelog files.
:return obj: Bag | [
"Create",
"a",
"Bag",
"out",
"of",
"given",
"files",
".",
":",
"param",
"str",
"dir_bag",
":",
"Directory",
"that",
"contains",
"csv",
"jsonld",
"and",
"changelog",
"files",
".",
":",
"return",
"obj",
":",
"Bag"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/bag.py#L8-L27 |
nickmckay/LiPD-utilities | Python/lipd/bag.py | open_bag | def open_bag(dir_bag):
"""
Open Bag at the given path
:param str dir_bag: Path to Bag
:return obj: Bag
"""
logger_bagit.info("enter open_bag")
try:
bag = bagit.Bag(dir_bag)
logger_bagit.info("opened bag")
return bag
except Exception as e:
print("Error: failed to open bagit bag")
logger_bagit.debug("failed to open bag, {}".format(e))
return None | python | def open_bag(dir_bag):
"""
Open Bag at the given path
:param str dir_bag: Path to Bag
:return obj: Bag
"""
logger_bagit.info("enter open_bag")
try:
bag = bagit.Bag(dir_bag)
logger_bagit.info("opened bag")
return bag
except Exception as e:
print("Error: failed to open bagit bag")
logger_bagit.debug("failed to open bag, {}".format(e))
return None | [
"def",
"open_bag",
"(",
"dir_bag",
")",
":",
"logger_bagit",
".",
"info",
"(",
"\"enter open_bag\"",
")",
"try",
":",
"bag",
"=",
"bagit",
".",
"Bag",
"(",
"dir_bag",
")",
"logger_bagit",
".",
"info",
"(",
"\"opened bag\"",
")",
"return",
"bag",
"except",
... | Open Bag at the given path
:param str dir_bag: Path to Bag
:return obj: Bag | [
"Open",
"Bag",
"at",
"the",
"given",
"path",
":",
"param",
"str",
"dir_bag",
":",
"Path",
"to",
"Bag",
":",
"return",
"obj",
":",
"Bag"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/bag.py#L30-L44 |
nickmckay/LiPD-utilities | Python/lipd/bag.py | validate_md5 | def validate_md5(bag):
"""
Check if Bag is valid
:param obj bag: Bag
:return None:
"""
logger_bagit.info("validate_md5")
if bag.is_valid():
print("Valid md5")
# for path, fixity in bag.entries.items():
# print("path:{}\nmd5:{}\n".format(path, fixity["md5"]))
else:
print("Invalid md5")
logger_bagit.debug("invalid bag")
return | python | def validate_md5(bag):
"""
Check if Bag is valid
:param obj bag: Bag
:return None:
"""
logger_bagit.info("validate_md5")
if bag.is_valid():
print("Valid md5")
# for path, fixity in bag.entries.items():
# print("path:{}\nmd5:{}\n".format(path, fixity["md5"]))
else:
print("Invalid md5")
logger_bagit.debug("invalid bag")
return | [
"def",
"validate_md5",
"(",
"bag",
")",
":",
"logger_bagit",
".",
"info",
"(",
"\"validate_md5\"",
")",
"if",
"bag",
".",
"is_valid",
"(",
")",
":",
"print",
"(",
"\"Valid md5\"",
")",
"# for path, fixity in bag.entries.items():",
"# print(\"path:{}\\nmd5:{}\\n\".... | Check if Bag is valid
:param obj bag: Bag
:return None: | [
"Check",
"if",
"Bag",
"is",
"valid",
":",
"param",
"obj",
"bag",
":",
"Bag",
":",
"return",
"None",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/bag.py#L47-L61 |
nickmckay/LiPD-utilities | Python/lipd/bag.py | resolved_flag | def resolved_flag(bag):
"""
Check DOI flag in bag.info to see if doi_resolver has been previously run
:param obj bag: Bag
:return bool: Flag
"""
if 'DOI-Resolved' in bag.info:
logger_bagit.info("bagit resolved_flag: true")
return True
logger_bagit.info("bagit resolved_flag: false")
return False | python | def resolved_flag(bag):
"""
Check DOI flag in bag.info to see if doi_resolver has been previously run
:param obj bag: Bag
:return bool: Flag
"""
if 'DOI-Resolved' in bag.info:
logger_bagit.info("bagit resolved_flag: true")
return True
logger_bagit.info("bagit resolved_flag: false")
return False | [
"def",
"resolved_flag",
"(",
"bag",
")",
":",
"if",
"'DOI-Resolved'",
"in",
"bag",
".",
"info",
":",
"logger_bagit",
".",
"info",
"(",
"\"bagit resolved_flag: true\"",
")",
"return",
"True",
"logger_bagit",
".",
"info",
"(",
"\"bagit resolved_flag: false\"",
")",
... | Check DOI flag in bag.info to see if doi_resolver has been previously run
:param obj bag: Bag
:return bool: Flag | [
"Check",
"DOI",
"flag",
"in",
"bag",
".",
"info",
"to",
"see",
"if",
"doi_resolver",
"has",
"been",
"previously",
"run",
":",
"param",
"obj",
"bag",
":",
"Bag",
":",
"return",
"bool",
":",
"Flag"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/bag.py#L64-L74 |
nickmckay/LiPD-utilities | Python/lipd/bag.py | finish_bag | def finish_bag(dir_bag):
"""
Closing steps for creating a bag
:param obj dir_bag:
:return None:
"""
logger_bagit.info("enter finish_bag")
# Create a bag for the 3 files
new_bag = create_bag(dir_bag)
open_bag(dir_bag)
new_bag.save(manifests=True)
logger_bagit.info("exit finish_bag")
return | python | def finish_bag(dir_bag):
"""
Closing steps for creating a bag
:param obj dir_bag:
:return None:
"""
logger_bagit.info("enter finish_bag")
# Create a bag for the 3 files
new_bag = create_bag(dir_bag)
open_bag(dir_bag)
new_bag.save(manifests=True)
logger_bagit.info("exit finish_bag")
return | [
"def",
"finish_bag",
"(",
"dir_bag",
")",
":",
"logger_bagit",
".",
"info",
"(",
"\"enter finish_bag\"",
")",
"# Create a bag for the 3 files",
"new_bag",
"=",
"create_bag",
"(",
"dir_bag",
")",
"open_bag",
"(",
"dir_bag",
")",
"new_bag",
".",
"save",
"(",
"mani... | Closing steps for creating a bag
:param obj dir_bag:
:return None: | [
"Closing",
"steps",
"for",
"creating",
"a",
"bag",
":",
"param",
"obj",
"dir_bag",
":",
":",
"return",
"None",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/bag.py#L77-L89 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | _ask_how_many | def _ask_how_many():
"""
Ask user if they want to load in one file or do a batch process of a whole directory. Default to batch "m" mode.
:return str: Path or none
"""
batch = True
invalid = True
_option = ""
try:
while invalid:
print("\nChoose a loading option:\n1. Select specific file(s)\n2. Load entire folder")
_option = input("Option: ")
# these are the only 2 valid options. if this is true, then stop prompting
if _option in ["1", "2"]:
invalid = False
# indicate whether to leave batch on or turn off
if _option == "1":
batch = False
except Exception:
logger_directory.info("_askHowMany: Couldn't get a valid input from the user.")
return batch | python | def _ask_how_many():
"""
Ask user if they want to load in one file or do a batch process of a whole directory. Default to batch "m" mode.
:return str: Path or none
"""
batch = True
invalid = True
_option = ""
try:
while invalid:
print("\nChoose a loading option:\n1. Select specific file(s)\n2. Load entire folder")
_option = input("Option: ")
# these are the only 2 valid options. if this is true, then stop prompting
if _option in ["1", "2"]:
invalid = False
# indicate whether to leave batch on or turn off
if _option == "1":
batch = False
except Exception:
logger_directory.info("_askHowMany: Couldn't get a valid input from the user.")
return batch | [
"def",
"_ask_how_many",
"(",
")",
":",
"batch",
"=",
"True",
"invalid",
"=",
"True",
"_option",
"=",
"\"\"",
"try",
":",
"while",
"invalid",
":",
"print",
"(",
"\"\\nChoose a loading option:\\n1. Select specific file(s)\\n2. Load entire folder\"",
")",
"_option",
"=",... | Ask user if they want to load in one file or do a batch process of a whole directory. Default to batch "m" mode.
:return str: Path or none | [
"Ask",
"user",
"if",
"they",
"want",
"to",
"load",
"in",
"one",
"file",
"or",
"do",
"a",
"batch",
"process",
"of",
"a",
"whole",
"directory",
".",
"Default",
"to",
"batch",
"m",
"mode",
".",
":",
"return",
"str",
":",
"Path",
"or",
"none"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L15-L37 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | browse_dialog_dir | def browse_dialog_dir():
"""
Open up a GUI browse dialog window and let to user pick a target directory.
:return str: Target directory path
"""
_go_to_package()
logger_directory.info("enter browse_dialog")
_path_bytes = subprocess.check_output(['python', 'gui_dir_browse.py'], shell=False)
_path = _fix_path_bytes(_path_bytes, file=False)
if len(_path) >= 1:
_path = _path[0]
else:
_path = ""
logger_directory.info("chosen path: {}".format(_path))
logger_directory.info("exit browse_dialog")
return _path | python | def browse_dialog_dir():
"""
Open up a GUI browse dialog window and let to user pick a target directory.
:return str: Target directory path
"""
_go_to_package()
logger_directory.info("enter browse_dialog")
_path_bytes = subprocess.check_output(['python', 'gui_dir_browse.py'], shell=False)
_path = _fix_path_bytes(_path_bytes, file=False)
if len(_path) >= 1:
_path = _path[0]
else:
_path = ""
logger_directory.info("chosen path: {}".format(_path))
logger_directory.info("exit browse_dialog")
return _path | [
"def",
"browse_dialog_dir",
"(",
")",
":",
"_go_to_package",
"(",
")",
"logger_directory",
".",
"info",
"(",
"\"enter browse_dialog\"",
")",
"_path_bytes",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'python'",
",",
"'gui_dir_browse.py'",
"]",
",",
"shell",... | Open up a GUI browse dialog window and let to user pick a target directory.
:return str: Target directory path | [
"Open",
"up",
"a",
"GUI",
"browse",
"dialog",
"window",
"and",
"let",
"to",
"user",
"pick",
"a",
"target",
"directory",
".",
":",
"return",
"str",
":",
"Target",
"directory",
"path"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L54-L69 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | browse_dialog_file | def browse_dialog_file():
"""
Open up a GUI browse dialog window and let to user select one or more files
:return str _path: Target directory path
:return list _files: List of selected files
"""
logger_directory.info("enter browse_dialog")
# We make files a list, because the user can multi-select files.
_files = []
_path = ""
try:
_go_to_package()
_path_bytes = subprocess.check_output(['python', 'gui_file_browse.py'])
_path = _fix_path_bytes(_path_bytes)
_files = [i for i in _path]
_path = os.path.dirname(_path[0])
logger_directory.info("chosen path: {}, chosen file: {}".format(_path, _files))
except IndexError:
logger_directory.warn("directory: browse_dialog_file: IndexError: no file chosen")
except Exception as e:
logger_directory.error("directory: browse_dialog_file: UnknownError: {}".format(e))
logger_directory.info("exit browse_dialog_file")
return _path, _files | python | def browse_dialog_file():
"""
Open up a GUI browse dialog window and let to user select one or more files
:return str _path: Target directory path
:return list _files: List of selected files
"""
logger_directory.info("enter browse_dialog")
# We make files a list, because the user can multi-select files.
_files = []
_path = ""
try:
_go_to_package()
_path_bytes = subprocess.check_output(['python', 'gui_file_browse.py'])
_path = _fix_path_bytes(_path_bytes)
_files = [i for i in _path]
_path = os.path.dirname(_path[0])
logger_directory.info("chosen path: {}, chosen file: {}".format(_path, _files))
except IndexError:
logger_directory.warn("directory: browse_dialog_file: IndexError: no file chosen")
except Exception as e:
logger_directory.error("directory: browse_dialog_file: UnknownError: {}".format(e))
logger_directory.info("exit browse_dialog_file")
return _path, _files | [
"def",
"browse_dialog_file",
"(",
")",
":",
"logger_directory",
".",
"info",
"(",
"\"enter browse_dialog\"",
")",
"# We make files a list, because the user can multi-select files.",
"_files",
"=",
"[",
"]",
"_path",
"=",
"\"\"",
"try",
":",
"_go_to_package",
"(",
")",
... | Open up a GUI browse dialog window and let to user select one or more files
:return str _path: Target directory path
:return list _files: List of selected files | [
"Open",
"up",
"a",
"GUI",
"browse",
"dialog",
"window",
"and",
"let",
"to",
"user",
"select",
"one",
"or",
"more",
"files",
":",
"return",
"str",
"_path",
":",
"Target",
"directory",
"path",
":",
"return",
"list",
"_files",
":",
"List",
"of",
"selected",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L85-L112 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | check_file_age | def check_file_age(filename, days):
"""
Check if the target file has an older creation date than X amount of time.
i.e. One day: 60*60*24
:param str filename: Target filename
:param int days: Limit in number of days
:return bool: True - older than X time, False - not older than X time
"""
logger_directory.info("enter check_file_age")
# Multiply days given by time for one day.
t = days * 60 * 60 * 24
now = time.time()
specified_time = now - t
try:
if os.path.getctime(filename) < specified_time:
# File found and out of date
logger_directory.info("{} not up-to-date".format(filename))
logger_directory.info("exiting check_file_age()")
return True
# File found, and not out of date
logger_directory.info("{} and up-to-date".format(filename))
logger_directory.info("exiting check_file_age()")
return False
except FileNotFoundError:
# File not found. Need to download it.
logger_directory.info("{} not found in {}".format(filename, os.getcwd()))
logger_directory.info("exiting check_file_age()")
return True | python | def check_file_age(filename, days):
"""
Check if the target file has an older creation date than X amount of time.
i.e. One day: 60*60*24
:param str filename: Target filename
:param int days: Limit in number of days
:return bool: True - older than X time, False - not older than X time
"""
logger_directory.info("enter check_file_age")
# Multiply days given by time for one day.
t = days * 60 * 60 * 24
now = time.time()
specified_time = now - t
try:
if os.path.getctime(filename) < specified_time:
# File found and out of date
logger_directory.info("{} not up-to-date".format(filename))
logger_directory.info("exiting check_file_age()")
return True
# File found, and not out of date
logger_directory.info("{} and up-to-date".format(filename))
logger_directory.info("exiting check_file_age()")
return False
except FileNotFoundError:
# File not found. Need to download it.
logger_directory.info("{} not found in {}".format(filename, os.getcwd()))
logger_directory.info("exiting check_file_age()")
return True | [
"def",
"check_file_age",
"(",
"filename",
",",
"days",
")",
":",
"logger_directory",
".",
"info",
"(",
"\"enter check_file_age\"",
")",
"# Multiply days given by time for one day.",
"t",
"=",
"days",
"*",
"60",
"*",
"60",
"*",
"24",
"now",
"=",
"time",
".",
"t... | Check if the target file has an older creation date than X amount of time.
i.e. One day: 60*60*24
:param str filename: Target filename
:param int days: Limit in number of days
:return bool: True - older than X time, False - not older than X time | [
"Check",
"if",
"the",
"target",
"file",
"has",
"an",
"older",
"creation",
"date",
"than",
"X",
"amount",
"of",
"time",
".",
"i",
".",
"e",
".",
"One",
"day",
":",
"60",
"*",
"60",
"*",
"24",
":",
"param",
"str",
"filename",
":",
"Target",
"filename... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L115-L142 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | collect_metadata_files | def collect_metadata_files(cwd, new_files, existing_files):
"""
Collect all files from a given path. Separate by file type, and return one list for each type
If 'files' contains specific
:param str cwd: Directory w/ target files
:param list new_files: Specific new files to load
:param dict existing_files: Files currently loaded, separated by type
:return list: All files separated by type
"""
obj = {}
try:
os.chdir(cwd)
# Special case: User uses gui to mult-select 2+ files. You'll be given a list of file paths.
if new_files:
for full_path in new_files:
# Create the file metadata for one file, and append it to the existing files.
obj = collect_metadata_file(full_path)
# directory: get all files in the directory and sort by type
else:
for file_type in [".lpd", ".xls", ".txt"]:
# get all files in cwd of this file extension
files_found = list_files(file_type)
# if looking for excel files, also look for the alternate extension.
if file_type == ".xls":
files_found += list_files(".xlsx")
# for each file found, build it's metadata and append it to files_by_type
for file in files_found:
fn = os.path.splitext(file)[0]
existing_files[file_type].append({"full_path": os.path.join(cwd, file), "filename_ext": file, "filename_no_ext": fn, "dir": cwd})
except Exception:
logger_directory.info("directory: collect_files: there's a problem")
return obj | python | def collect_metadata_files(cwd, new_files, existing_files):
"""
Collect all files from a given path. Separate by file type, and return one list for each type
If 'files' contains specific
:param str cwd: Directory w/ target files
:param list new_files: Specific new files to load
:param dict existing_files: Files currently loaded, separated by type
:return list: All files separated by type
"""
obj = {}
try:
os.chdir(cwd)
# Special case: User uses gui to mult-select 2+ files. You'll be given a list of file paths.
if new_files:
for full_path in new_files:
# Create the file metadata for one file, and append it to the existing files.
obj = collect_metadata_file(full_path)
# directory: get all files in the directory and sort by type
else:
for file_type in [".lpd", ".xls", ".txt"]:
# get all files in cwd of this file extension
files_found = list_files(file_type)
# if looking for excel files, also look for the alternate extension.
if file_type == ".xls":
files_found += list_files(".xlsx")
# for each file found, build it's metadata and append it to files_by_type
for file in files_found:
fn = os.path.splitext(file)[0]
existing_files[file_type].append({"full_path": os.path.join(cwd, file), "filename_ext": file, "filename_no_ext": fn, "dir": cwd})
except Exception:
logger_directory.info("directory: collect_files: there's a problem")
return obj | [
"def",
"collect_metadata_files",
"(",
"cwd",
",",
"new_files",
",",
"existing_files",
")",
":",
"obj",
"=",
"{",
"}",
"try",
":",
"os",
".",
"chdir",
"(",
"cwd",
")",
"# Special case: User uses gui to mult-select 2+ files. You'll be given a list of file paths.",
"if",
... | Collect all files from a given path. Separate by file type, and return one list for each type
If 'files' contains specific
:param str cwd: Directory w/ target files
:param list new_files: Specific new files to load
:param dict existing_files: Files currently loaded, separated by type
:return list: All files separated by type | [
"Collect",
"all",
"files",
"from",
"a",
"given",
"path",
".",
"Separate",
"by",
"file",
"type",
"and",
"return",
"one",
"list",
"for",
"each",
"type",
"If",
"files",
"contains",
"specific",
":",
"param",
"str",
"cwd",
":",
"Directory",
"w",
"/",
"target"... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L155-L189 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | collect_metadata_file | def collect_metadata_file(full_path):
"""
Create the file metadata and add it to the appropriate section by file-type
:param str full_path:
:param dict existing_files:
:return dict existing files:
"""
fne = os.path.basename(full_path)
fn = os.path.splitext(fne)[0]
obj = {"full_path": full_path, "filename_ext": fne, "filename_no_ext": fn, "dir": os.path.dirname(full_path)}
return obj | python | def collect_metadata_file(full_path):
"""
Create the file metadata and add it to the appropriate section by file-type
:param str full_path:
:param dict existing_files:
:return dict existing files:
"""
fne = os.path.basename(full_path)
fn = os.path.splitext(fne)[0]
obj = {"full_path": full_path, "filename_ext": fne, "filename_no_ext": fn, "dir": os.path.dirname(full_path)}
return obj | [
"def",
"collect_metadata_file",
"(",
"full_path",
")",
":",
"fne",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"full_path",
")",
"fn",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fne",
")",
"[",
"0",
"]",
"obj",
"=",
"{",
"\"full_path\"",
":",
... | Create the file metadata and add it to the appropriate section by file-type
:param str full_path:
:param dict existing_files:
:return dict existing files: | [
"Create",
"the",
"file",
"metadata",
"and",
"add",
"it",
"to",
"the",
"appropriate",
"section",
"by",
"file",
"-",
"type",
":",
"param",
"str",
"full_path",
":",
":",
"param",
"dict",
"existing_files",
":",
":",
"return",
"dict",
"existing",
"files",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L192-L202 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | dir_cleanup | def dir_cleanup(dir_bag, dir_data):
"""
Moves JSON and csv files to bag root, then deletes all the metadata bag files. We'll be creating a new bag with
the data files, so we don't need the other text files and such.
:param str dir_bag: Path to root of Bag
:param str dir_data: Path to Bag /data subdirectory
:return None:
"""
logger_directory.info("enter dir_cleanup")
# dir : dir_data -> dir_bag
os.chdir(dir_bag)
# Delete files in dir_bag
for file in os.listdir(dir_bag):
if file.endswith('.txt'):
os.remove(os.path.join(dir_bag, file))
logger_directory.info("deleted files in dir_bag")
# Move dir_data files up to dir_bag
for file in os.listdir(dir_data):
shutil.move(os.path.join(dir_data, file), dir_bag)
logger_directory.info("moved dir_data contents to dir_bag")
# Delete empty dir_data folder
shutil.rmtree(dir_data)
logger_directory.info("exit dir_cleanup")
return | python | def dir_cleanup(dir_bag, dir_data):
"""
Moves JSON and csv files to bag root, then deletes all the metadata bag files. We'll be creating a new bag with
the data files, so we don't need the other text files and such.
:param str dir_bag: Path to root of Bag
:param str dir_data: Path to Bag /data subdirectory
:return None:
"""
logger_directory.info("enter dir_cleanup")
# dir : dir_data -> dir_bag
os.chdir(dir_bag)
# Delete files in dir_bag
for file in os.listdir(dir_bag):
if file.endswith('.txt'):
os.remove(os.path.join(dir_bag, file))
logger_directory.info("deleted files in dir_bag")
# Move dir_data files up to dir_bag
for file in os.listdir(dir_data):
shutil.move(os.path.join(dir_data, file), dir_bag)
logger_directory.info("moved dir_data contents to dir_bag")
# Delete empty dir_data folder
shutil.rmtree(dir_data)
logger_directory.info("exit dir_cleanup")
return | [
"def",
"dir_cleanup",
"(",
"dir_bag",
",",
"dir_data",
")",
":",
"logger_directory",
".",
"info",
"(",
"\"enter dir_cleanup\"",
")",
"# dir : dir_data -> dir_bag",
"os",
".",
"chdir",
"(",
"dir_bag",
")",
"# Delete files in dir_bag",
"for",
"file",
"in",
"os",
"."... | Moves JSON and csv files to bag root, then deletes all the metadata bag files. We'll be creating a new bag with
the data files, so we don't need the other text files and such.
:param str dir_bag: Path to root of Bag
:param str dir_data: Path to Bag /data subdirectory
:return None: | [
"Moves",
"JSON",
"and",
"csv",
"files",
"to",
"bag",
"root",
"then",
"deletes",
"all",
"the",
"metadata",
"bag",
"files",
".",
"We",
"ll",
"be",
"creating",
"a",
"new",
"bag",
"with",
"the",
"data",
"files",
"so",
"we",
"don",
"t",
"need",
"the",
"ot... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L205-L229 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | filename_from_path | def filename_from_path(path):
"""
Extract the file name from a given file path.
:param str path: File path
:return str: File name with extension
"""
head, tail = ntpath.split(path)
return head, tail or ntpath.basename(head) | python | def filename_from_path(path):
"""
Extract the file name from a given file path.
:param str path: File path
:return str: File name with extension
"""
head, tail = ntpath.split(path)
return head, tail or ntpath.basename(head) | [
"def",
"filename_from_path",
"(",
"path",
")",
":",
"head",
",",
"tail",
"=",
"ntpath",
".",
"split",
"(",
"path",
")",
"return",
"head",
",",
"tail",
"or",
"ntpath",
".",
"basename",
"(",
"head",
")"
] | Extract the file name from a given file path.
:param str path: File path
:return str: File name with extension | [
"Extract",
"the",
"file",
"name",
"from",
"a",
"given",
"file",
"path",
".",
":",
"param",
"str",
"path",
":",
"File",
"path",
":",
"return",
"str",
":",
"File",
"name",
"with",
"extension"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L232-L239 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | find_files | def find_files():
"""
Search for the directory containing jsonld and csv files. chdir and then quit.
:return none:
"""
_dir = os.getcwd()
_files = os.listdir()
# Look for a jsonld file
for _file in _files:
if _file.endswith(".jsonld"):
return os.getcwd()
# No jsonld file found, try to chdir into "bag" (LiPD v1.3)
if "bag" in _files:
os.chdir("bag")
_dir = find_files()
# No "bag" dir. Try chdir into whatever dataset name dir we find (< LiPD v1.2)
else:
for _file in _files:
if os.path.isdir(_file):
os.chdir(_file)
_dir = find_files()
return _dir | python | def find_files():
"""
Search for the directory containing jsonld and csv files. chdir and then quit.
:return none:
"""
_dir = os.getcwd()
_files = os.listdir()
# Look for a jsonld file
for _file in _files:
if _file.endswith(".jsonld"):
return os.getcwd()
# No jsonld file found, try to chdir into "bag" (LiPD v1.3)
if "bag" in _files:
os.chdir("bag")
_dir = find_files()
# No "bag" dir. Try chdir into whatever dataset name dir we find (< LiPD v1.2)
else:
for _file in _files:
if os.path.isdir(_file):
os.chdir(_file)
_dir = find_files()
return _dir | [
"def",
"find_files",
"(",
")",
":",
"_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"_files",
"=",
"os",
".",
"listdir",
"(",
")",
"# Look for a jsonld file",
"for",
"_file",
"in",
"_files",
":",
"if",
"_file",
".",
"endswith",
"(",
"\".jsonld\"",
")",
":"... | Search for the directory containing jsonld and csv files. chdir and then quit.
:return none: | [
"Search",
"for",
"the",
"directory",
"containing",
"jsonld",
"and",
"csv",
"files",
".",
"chdir",
"and",
"then",
"quit",
".",
":",
"return",
"none",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L242-L263 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | get_filenames_generated | def get_filenames_generated(d, name="", csvs=""):
"""
Get the filenames that the LiPD utilities has generated (per naming standard), as opposed to the filenames that
originated in the LiPD file (that possibly don't follow the naming standard)
:param dict d: Data
:param str name: LiPD dataset name to prefix
:param list csvs: Filenames list to merge with
:return list: Filenames
"""
filenames = []
try:
filenames = d.keys()
if name:
filenames = [os.path.join(name, "data", filename) for filename in filenames]
if csvs:
lst = [i for i in csvs if not i.endswith("csv")]
filenames = lst + filenames
except Exception as e:
logger_directory.debug("get_filenames_generated: Exception: {}".format(e))
return filenames | python | def get_filenames_generated(d, name="", csvs=""):
"""
Get the filenames that the LiPD utilities has generated (per naming standard), as opposed to the filenames that
originated in the LiPD file (that possibly don't follow the naming standard)
:param dict d: Data
:param str name: LiPD dataset name to prefix
:param list csvs: Filenames list to merge with
:return list: Filenames
"""
filenames = []
try:
filenames = d.keys()
if name:
filenames = [os.path.join(name, "data", filename) for filename in filenames]
if csvs:
lst = [i for i in csvs if not i.endswith("csv")]
filenames = lst + filenames
except Exception as e:
logger_directory.debug("get_filenames_generated: Exception: {}".format(e))
return filenames | [
"def",
"get_filenames_generated",
"(",
"d",
",",
"name",
"=",
"\"\"",
",",
"csvs",
"=",
"\"\"",
")",
":",
"filenames",
"=",
"[",
"]",
"try",
":",
"filenames",
"=",
"d",
".",
"keys",
"(",
")",
"if",
"name",
":",
"filenames",
"=",
"[",
"os",
".",
"... | Get the filenames that the LiPD utilities has generated (per naming standard), as opposed to the filenames that
originated in the LiPD file (that possibly don't follow the naming standard)
:param dict d: Data
:param str name: LiPD dataset name to prefix
:param list csvs: Filenames list to merge with
:return list: Filenames | [
"Get",
"the",
"filenames",
"that",
"the",
"LiPD",
"utilities",
"has",
"generated",
"(",
"per",
"naming",
"standard",
")",
"as",
"opposed",
"to",
"the",
"filenames",
"that",
"originated",
"in",
"the",
"LiPD",
"file",
"(",
"that",
"possibly",
"don",
"t",
"fo... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L266-L285 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | get_filenames_in_lipd | def get_filenames_in_lipd(path, name=""):
"""
List all the files contained in the LiPD archive. Bagit, JSON, and CSV
:param str path: Directory to be listed
:param str name: LiPD dataset name, if you want to prefix it to show file hierarchy
:return list: Filenames found
"""
_filenames = []
try:
# in the top level, list all files and skip the "data" directory
_top = [os.path.join(name, f) for f in os.listdir(path) if f != "data"]
# in the data directory, list all files
_dir_data = [os.path.join(name, "data", f) for f in os.listdir(os.path.join(path, "data"))]
# combine the two lists
_filenames = _top + _dir_data
except Exception:
pass
return _filenames | python | def get_filenames_in_lipd(path, name=""):
"""
List all the files contained in the LiPD archive. Bagit, JSON, and CSV
:param str path: Directory to be listed
:param str name: LiPD dataset name, if you want to prefix it to show file hierarchy
:return list: Filenames found
"""
_filenames = []
try:
# in the top level, list all files and skip the "data" directory
_top = [os.path.join(name, f) for f in os.listdir(path) if f != "data"]
# in the data directory, list all files
_dir_data = [os.path.join(name, "data", f) for f in os.listdir(os.path.join(path, "data"))]
# combine the two lists
_filenames = _top + _dir_data
except Exception:
pass
return _filenames | [
"def",
"get_filenames_in_lipd",
"(",
"path",
",",
"name",
"=",
"\"\"",
")",
":",
"_filenames",
"=",
"[",
"]",
"try",
":",
"# in the top level, list all files and skip the \"data\" directory",
"_top",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"name",
",",
... | List all the files contained in the LiPD archive. Bagit, JSON, and CSV
:param str path: Directory to be listed
:param str name: LiPD dataset name, if you want to prefix it to show file hierarchy
:return list: Filenames found | [
"List",
"all",
"the",
"files",
"contained",
"in",
"the",
"LiPD",
"archive",
".",
"Bagit",
"JSON",
"and",
"CSV",
":",
"param",
"str",
"path",
":",
"Directory",
"to",
"be",
"listed",
":",
"param",
"str",
"name",
":",
"LiPD",
"dataset",
"name",
"if",
"you... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L288-L305 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | get_src_or_dst | def get_src_or_dst(mode, path_type):
"""
User sets the path to a LiPD source location
:param str mode: "read" or "write" mode
:param str path_type: "directory" or "file"
:return str path: dir path to files
:return list files: files chosen
"""
logger_directory.info("enter set_src_or_dst")
_path = ""
_files = ""
invalid = True
count = 0
# Did you forget to enter a mode?
if not mode:
invalid = False
# Special case for gui reading a single or multi-select file(s).
elif mode == "read" and path_type == "file":
_path, _files = browse_dialog_file()
# Return early to skip prompts, since they're not needed
return _path, _files
# All other cases, prompt user to choose directory
else:
prompt = get_src_or_dst_prompt(mode)
# Loop max of 3 times, then default to Downloads folder if too many failed attempts
while invalid and prompt:
# Prompt user to choose target path
_path, count = get_src_or_dst_path(prompt, count)
if _path:
invalid = False
logger_directory.info("exit set_src_or_dst")
return _path, _files | python | def get_src_or_dst(mode, path_type):
"""
User sets the path to a LiPD source location
:param str mode: "read" or "write" mode
:param str path_type: "directory" or "file"
:return str path: dir path to files
:return list files: files chosen
"""
logger_directory.info("enter set_src_or_dst")
_path = ""
_files = ""
invalid = True
count = 0
# Did you forget to enter a mode?
if not mode:
invalid = False
# Special case for gui reading a single or multi-select file(s).
elif mode == "read" and path_type == "file":
_path, _files = browse_dialog_file()
# Return early to skip prompts, since they're not needed
return _path, _files
# All other cases, prompt user to choose directory
else:
prompt = get_src_or_dst_prompt(mode)
# Loop max of 3 times, then default to Downloads folder if too many failed attempts
while invalid and prompt:
# Prompt user to choose target path
_path, count = get_src_or_dst_path(prompt, count)
if _path:
invalid = False
logger_directory.info("exit set_src_or_dst")
return _path, _files | [
"def",
"get_src_or_dst",
"(",
"mode",
",",
"path_type",
")",
":",
"logger_directory",
".",
"info",
"(",
"\"enter set_src_or_dst\"",
")",
"_path",
"=",
"\"\"",
"_files",
"=",
"\"\"",
"invalid",
"=",
"True",
"count",
"=",
"0",
"# Did you forget to enter a mode?",
... | User sets the path to a LiPD source location
:param str mode: "read" or "write" mode
:param str path_type: "directory" or "file"
:return str path: dir path to files
:return list files: files chosen | [
"User",
"sets",
"the",
"path",
"to",
"a",
"LiPD",
"source",
"location",
":",
"param",
"str",
"mode",
":",
"read",
"or",
"write",
"mode",
":",
"param",
"str",
"path_type",
":",
"directory",
"or",
"file",
":",
"return",
"str",
"path",
":",
"dir",
"path",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L308-L344 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | get_src_or_dst_prompt | def get_src_or_dst_prompt(mode):
"""
String together the proper prompt based on the mode
:param str mode: "read" or "write"
:return str prompt: The prompt needed
"""
_words = {"read": "from", "write": "to"}
# print(os.getcwd())
prompt = "Where would you like to {} your file(s) {}?\n" \
"1. Desktop ({})\n" \
"2. Downloads ({})\n" \
"3. Current ({})\n" \
"4. Browse".format(mode, _words[mode],
os.path.expanduser('~/Desktop'),
os.path.expanduser('~/Downloads'),
os.getcwd())
return prompt | python | def get_src_or_dst_prompt(mode):
"""
String together the proper prompt based on the mode
:param str mode: "read" or "write"
:return str prompt: The prompt needed
"""
_words = {"read": "from", "write": "to"}
# print(os.getcwd())
prompt = "Where would you like to {} your file(s) {}?\n" \
"1. Desktop ({})\n" \
"2. Downloads ({})\n" \
"3. Current ({})\n" \
"4. Browse".format(mode, _words[mode],
os.path.expanduser('~/Desktop'),
os.path.expanduser('~/Downloads'),
os.getcwd())
return prompt | [
"def",
"get_src_or_dst_prompt",
"(",
"mode",
")",
":",
"_words",
"=",
"{",
"\"read\"",
":",
"\"from\"",
",",
"\"write\"",
":",
"\"to\"",
"}",
"# print(os.getcwd())",
"prompt",
"=",
"\"Where would you like to {} your file(s) {}?\\n\"",
"\"1. Desktop ({})\\n\"",
"\"2. Downl... | String together the proper prompt based on the mode
:param str mode: "read" or "write"
:return str prompt: The prompt needed | [
"String",
"together",
"the",
"proper",
"prompt",
"based",
"on",
"the",
"mode",
":",
"param",
"str",
"mode",
":",
"read",
"or",
"write",
":",
"return",
"str",
"prompt",
":",
"The",
"prompt",
"needed"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L347-L363 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | get_src_or_dst_path | def get_src_or_dst_path(prompt, count):
"""
Let the user choose a path, and store the value.
:return str _path: Target directory
:return str count: Counter for attempted prompts
"""
_path = ""
print(prompt)
option = input("Option: ")
print("\n")
if option == '1':
# Set the path to the system desktop folder.
logger_directory.info("1: desktop")
_path = os.path.expanduser('~/Desktop')
elif option == '2':
# Set the path to the system downloads folder.
logger_directory.info("2: downloads")
_path = os.path.expanduser('~/Downloads')
elif option == '3':
# Current directory
logger_directory.info("3: current")
_path = os.getcwd()
elif option == '4':
# Open up the GUI browse dialog
logger_directory.info("4: browse ")
_path = browse_dialog_dir()
else:
# Something went wrong. Prompt again. Give a couple tries before defaulting to downloads folder
if count == 2:
logger_directory.warn("too many attempts")
print("Too many failed attempts. Defaulting to current working directory.")
_path = os.getcwd()
else:
count += 1
logger_directory.warn("failed attempts: {}".format(count))
print("Invalid option. Try again.")
return _path, count | python | def get_src_or_dst_path(prompt, count):
"""
Let the user choose a path, and store the value.
:return str _path: Target directory
:return str count: Counter for attempted prompts
"""
_path = ""
print(prompt)
option = input("Option: ")
print("\n")
if option == '1':
# Set the path to the system desktop folder.
logger_directory.info("1: desktop")
_path = os.path.expanduser('~/Desktop')
elif option == '2':
# Set the path to the system downloads folder.
logger_directory.info("2: downloads")
_path = os.path.expanduser('~/Downloads')
elif option == '3':
# Current directory
logger_directory.info("3: current")
_path = os.getcwd()
elif option == '4':
# Open up the GUI browse dialog
logger_directory.info("4: browse ")
_path = browse_dialog_dir()
else:
# Something went wrong. Prompt again. Give a couple tries before defaulting to downloads folder
if count == 2:
logger_directory.warn("too many attempts")
print("Too many failed attempts. Defaulting to current working directory.")
_path = os.getcwd()
else:
count += 1
logger_directory.warn("failed attempts: {}".format(count))
print("Invalid option. Try again.")
return _path, count | [
"def",
"get_src_or_dst_path",
"(",
"prompt",
",",
"count",
")",
":",
"_path",
"=",
"\"\"",
"print",
"(",
"prompt",
")",
"option",
"=",
"input",
"(",
"\"Option: \"",
")",
"print",
"(",
"\"\\n\"",
")",
"if",
"option",
"==",
"'1'",
":",
"# Set the path to the... | Let the user choose a path, and store the value.
:return str _path: Target directory
:return str count: Counter for attempted prompts | [
"Let",
"the",
"user",
"choose",
"a",
"path",
"and",
"store",
"the",
"value",
".",
":",
"return",
"str",
"_path",
":",
"Target",
"directory",
":",
"return",
"str",
"count",
":",
"Counter",
"for",
"attempted",
"prompts"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L366-L404 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | list_files | def list_files(x, path=""):
"""
Lists file(s) in given path of the X type.
:param str x: File extension that we are interested in.
:param str path: Path, if user would like to check a specific directory outside of the CWD
:return list of str: File name(s) to be worked on
"""
logger_directory.info("enter list_files")
file_list = []
if path:
# list files from target directory
files = os.listdir(path)
for file in files:
if file.endswith(x) and not file.startswith(("$", "~", ".")):
# join the path and basename to create full path
file_list.append(os.path.join(path, file))
else:
# list files from current working directory
files = os.listdir()
for file in files:
if file.endswith(x) and not file.startswith(("$", "~", ".")):
# append basename. not full path
file_list.append(file)
logger_directory.info("exit list_files")
return file_list | python | def list_files(x, path=""):
"""
Lists file(s) in given path of the X type.
:param str x: File extension that we are interested in.
:param str path: Path, if user would like to check a specific directory outside of the CWD
:return list of str: File name(s) to be worked on
"""
logger_directory.info("enter list_files")
file_list = []
if path:
# list files from target directory
files = os.listdir(path)
for file in files:
if file.endswith(x) and not file.startswith(("$", "~", ".")):
# join the path and basename to create full path
file_list.append(os.path.join(path, file))
else:
# list files from current working directory
files = os.listdir()
for file in files:
if file.endswith(x) and not file.startswith(("$", "~", ".")):
# append basename. not full path
file_list.append(file)
logger_directory.info("exit list_files")
return file_list | [
"def",
"list_files",
"(",
"x",
",",
"path",
"=",
"\"\"",
")",
":",
"logger_directory",
".",
"info",
"(",
"\"enter list_files\"",
")",
"file_list",
"=",
"[",
"]",
"if",
"path",
":",
"# list files from target directory",
"files",
"=",
"os",
".",
"listdir",
"("... | Lists file(s) in given path of the X type.
:param str x: File extension that we are interested in.
:param str path: Path, if user would like to check a specific directory outside of the CWD
:return list of str: File name(s) to be worked on | [
"Lists",
"file",
"(",
"s",
")",
"in",
"given",
"path",
"of",
"the",
"X",
"type",
".",
":",
"param",
"str",
"x",
":",
"File",
"extension",
"that",
"we",
"are",
"interested",
"in",
".",
":",
"param",
"str",
"path",
":",
"Path",
"if",
"user",
"would",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L407-L431 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | rm_files_in_dir | def rm_files_in_dir(path):
"""
Removes all files within a directory, but does not delete the directory
:param str path: Target directory
:return none:
"""
for f in os.listdir(path):
try:
os.remove(f)
except PermissionError:
os.chmod(f, 0o777)
try:
os.remove(f)
except Exception:
pass
return | python | def rm_files_in_dir(path):
"""
Removes all files within a directory, but does not delete the directory
:param str path: Target directory
:return none:
"""
for f in os.listdir(path):
try:
os.remove(f)
except PermissionError:
os.chmod(f, 0o777)
try:
os.remove(f)
except Exception:
pass
return | [
"def",
"rm_files_in_dir",
"(",
"path",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"f",
")",
"except",
"PermissionError",
":",
"os",
".",
"chmod",
"(",
"f",
",",
"0o777",
")",
"tr... | Removes all files within a directory, but does not delete the directory
:param str path: Target directory
:return none: | [
"Removes",
"all",
"files",
"within",
"a",
"directory",
"but",
"does",
"not",
"delete",
"the",
"directory",
":",
"param",
"str",
"path",
":",
"Target",
"directory",
":",
"return",
"none",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L434-L449 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | rm_file_if_exists | def rm_file_if_exists(path, filename):
"""
Remove a file if it exists. Useful for when we want to write a file, but it already exists in that locaiton.
:param str filename: Filename
:param str path: Directory
:return none:
"""
_full_path = os.path.join(path, filename)
if os.path.exists(_full_path):
os.remove(_full_path)
return | python | def rm_file_if_exists(path, filename):
"""
Remove a file if it exists. Useful for when we want to write a file, but it already exists in that locaiton.
:param str filename: Filename
:param str path: Directory
:return none:
"""
_full_path = os.path.join(path, filename)
if os.path.exists(_full_path):
os.remove(_full_path)
return | [
"def",
"rm_file_if_exists",
"(",
"path",
",",
"filename",
")",
":",
"_full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"_full_path",
")",
":",
"os",
".",
"remove",
"(",
... | Remove a file if it exists. Useful for when we want to write a file, but it already exists in that locaiton.
:param str filename: Filename
:param str path: Directory
:return none: | [
"Remove",
"a",
"file",
"if",
"it",
"exists",
".",
"Useful",
"for",
"when",
"we",
"want",
"to",
"write",
"a",
"file",
"but",
"it",
"already",
"exists",
"in",
"that",
"locaiton",
".",
":",
"param",
"str",
"filename",
":",
"Filename",
":",
"param",
"str",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L452-L462 |
audiolion/django-language-field | languages/regenerate.py | regenerate | def regenerate(location='http://www.iana.org/assignments/language-subtag-registry',
filename=None, default_encoding='utf-8'):
"""
Generate the languages Python module.
"""
paren = re.compile('\([^)]*\)')
# Get the language list.
data = urllib2.urlopen(location)
if ('content-type' in data.headers and
'charset=' in data.headers['content-type']):
encoding = data.headers['content-type'].split('charset=')[-1]
else:
encoding = default_encoding
content = data.read().decode(encoding)
languages = []
info = {}
p = None
for line in content.splitlines():
if line == '%%':
if 'Type' in info and info['Type'] == 'language':
languages.append(info)
info = {}
elif ':' not in line and p:
info[p[0]] = paren.sub('', p[2]+line).strip()
else:
p = line.partition(':')
if not p[0] in info: # Keep the first description as it should be the most common
info[p[0]] = paren.sub('', p[2]).strip()
languages_lines = map(lambda x:'("%s", _(u"%s")),'%(x['Subtag'],x['Description']), languages)
# Generate and save the file.
if not filename:
filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'languages.py')
# TODO: first make a backup of the file if it exists already.
f = codecs.open(filename, 'w', 'utf-8')
f.write(TEMPLATE % {
'languages': '\n '.join(languages_lines),
})
f.close() | python | def regenerate(location='http://www.iana.org/assignments/language-subtag-registry',
filename=None, default_encoding='utf-8'):
"""
Generate the languages Python module.
"""
paren = re.compile('\([^)]*\)')
# Get the language list.
data = urllib2.urlopen(location)
if ('content-type' in data.headers and
'charset=' in data.headers['content-type']):
encoding = data.headers['content-type'].split('charset=')[-1]
else:
encoding = default_encoding
content = data.read().decode(encoding)
languages = []
info = {}
p = None
for line in content.splitlines():
if line == '%%':
if 'Type' in info and info['Type'] == 'language':
languages.append(info)
info = {}
elif ':' not in line and p:
info[p[0]] = paren.sub('', p[2]+line).strip()
else:
p = line.partition(':')
if not p[0] in info: # Keep the first description as it should be the most common
info[p[0]] = paren.sub('', p[2]).strip()
languages_lines = map(lambda x:'("%s", _(u"%s")),'%(x['Subtag'],x['Description']), languages)
# Generate and save the file.
if not filename:
filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'languages.py')
# TODO: first make a backup of the file if it exists already.
f = codecs.open(filename, 'w', 'utf-8')
f.write(TEMPLATE % {
'languages': '\n '.join(languages_lines),
})
f.close() | [
"def",
"regenerate",
"(",
"location",
"=",
"'http://www.iana.org/assignments/language-subtag-registry'",
",",
"filename",
"=",
"None",
",",
"default_encoding",
"=",
"'utf-8'",
")",
":",
"paren",
"=",
"re",
".",
"compile",
"(",
"'\\([^)]*\\)'",
")",
"# Get the language... | Generate the languages Python module. | [
"Generate",
"the",
"languages",
"Python",
"module",
"."
] | train | https://github.com/audiolion/django-language-field/blob/7847dab863794fd06d8b445c9dda6b45ce830f8d/languages/regenerate.py#L22-L62 |
mobiusklein/brainpy | brainpy/brainpy.py | give_repr | def give_repr(cls): # pragma: no cover
r"""Patch a class to give it a generic __repr__ method
that works by inspecting the instance dictionary.
Parameters
----------
cls: type
The class to add a generic __repr__ to.
Returns
-------
cls: type
The passed class is returned
"""
def reprer(self):
attribs = ', '.join(["%s=%r" % (k, v) for k, v in self.__dict__.items() if not k.startswith("_")])
wrap = "{self.__class__.__name__}({attribs})".format(self=self, attribs=attribs)
return wrap
cls.__repr__ = reprer
return cls | python | def give_repr(cls): # pragma: no cover
r"""Patch a class to give it a generic __repr__ method
that works by inspecting the instance dictionary.
Parameters
----------
cls: type
The class to add a generic __repr__ to.
Returns
-------
cls: type
The passed class is returned
"""
def reprer(self):
attribs = ', '.join(["%s=%r" % (k, v) for k, v in self.__dict__.items() if not k.startswith("_")])
wrap = "{self.__class__.__name__}({attribs})".format(self=self, attribs=attribs)
return wrap
cls.__repr__ = reprer
return cls | [
"def",
"give_repr",
"(",
"cls",
")",
":",
"# pragma: no cover",
"def",
"reprer",
"(",
"self",
")",
":",
"attribs",
"=",
"', '",
".",
"join",
"(",
"[",
"\"%s=%r\"",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
... | r"""Patch a class to give it a generic __repr__ method
that works by inspecting the instance dictionary.
Parameters
----------
cls: type
The class to add a generic __repr__ to.
Returns
-------
cls: type
The passed class is returned | [
"r",
"Patch",
"a",
"class",
"to",
"give",
"it",
"a",
"generic",
"__repr__",
"method",
"that",
"works",
"by",
"inspecting",
"the",
"instance",
"dictionary",
"."
] | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L33-L52 |
mobiusklein/brainpy | brainpy/brainpy.py | newton | def newton(power_sum, elementary_symmetric_polynomial, order):
r'''
Given two lists of values, the first list being the `power sum`s of a
polynomial, and the second being expressions of the roots of the
polynomial as found by Viete's Formula, use information from the longer list to
fill out the shorter list using Newton's Identities.
.. note::
Updates are done **in place**
Parameters
----------
power_sum: list of float
elementary_symmetric_polynomial: list of float
order: int
The number of terms to expand to when updating `elementary_symmetric_polynomial`
See Also
--------
https://en.wikipedia.org/wiki/Newton%27s_identities[https://en.wikipedia.org/wiki/Newton%27s_identities]
'''
if len(power_sum) > len(elementary_symmetric_polynomial):
_update_elementary_symmetric_polynomial(power_sum, elementary_symmetric_polynomial, order)
elif len(power_sum) < len(elementary_symmetric_polynomial):
_update_power_sum(power_sum, elementary_symmetric_polynomial, order) | python | def newton(power_sum, elementary_symmetric_polynomial, order):
r'''
Given two lists of values, the first list being the `power sum`s of a
polynomial, and the second being expressions of the roots of the
polynomial as found by Viete's Formula, use information from the longer list to
fill out the shorter list using Newton's Identities.
.. note::
Updates are done **in place**
Parameters
----------
power_sum: list of float
elementary_symmetric_polynomial: list of float
order: int
The number of terms to expand to when updating `elementary_symmetric_polynomial`
See Also
--------
https://en.wikipedia.org/wiki/Newton%27s_identities[https://en.wikipedia.org/wiki/Newton%27s_identities]
'''
if len(power_sum) > len(elementary_symmetric_polynomial):
_update_elementary_symmetric_polynomial(power_sum, elementary_symmetric_polynomial, order)
elif len(power_sum) < len(elementary_symmetric_polynomial):
_update_power_sum(power_sum, elementary_symmetric_polynomial, order) | [
"def",
"newton",
"(",
"power_sum",
",",
"elementary_symmetric_polynomial",
",",
"order",
")",
":",
"if",
"len",
"(",
"power_sum",
")",
">",
"len",
"(",
"elementary_symmetric_polynomial",
")",
":",
"_update_elementary_symmetric_polynomial",
"(",
"power_sum",
",",
"el... | r'''
Given two lists of values, the first list being the `power sum`s of a
polynomial, and the second being expressions of the roots of the
polynomial as found by Viete's Formula, use information from the longer list to
fill out the shorter list using Newton's Identities.
.. note::
Updates are done **in place**
Parameters
----------
power_sum: list of float
elementary_symmetric_polynomial: list of float
order: int
The number of terms to expand to when updating `elementary_symmetric_polynomial`
See Also
--------
https://en.wikipedia.org/wiki/Newton%27s_identities[https://en.wikipedia.org/wiki/Newton%27s_identities] | [
"r",
"Given",
"two",
"lists",
"of",
"values",
"the",
"first",
"list",
"being",
"the",
"power",
"sum",
"s",
"of",
"a",
"polynomial",
"and",
"the",
"second",
"being",
"expressions",
"of",
"the",
"roots",
"of",
"the",
"polynomial",
"as",
"found",
"by",
"Vie... | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L75-L99 |
mobiusklein/brainpy | brainpy/brainpy.py | vietes | def vietes(coefficients):
r'''
Given the coefficients of a polynomial of a single variable,
compute an elementary symmetric polynomial of the roots of the
input polynomial by Viete's Formula:
.. math::
\sum_{1\le i_1<i_2<...<i_k \le n} x_{i_1}x_{i_2}...x_{i_k} = (-1)^k\frac{a_{n-k}}{a_n}
Parameters
----------
coefficients: list of float
A list of coefficients of the input polynomial of arbitrary length (degree) `n`
Returns
-------
list of float:
A list containing the expression of the roots of the input polynomial of length `n`
See Also
--------
https://en.wikipedia.org/wiki/Vieta%27s_formulas
'''
elementary_symmetric_polynomial = []
tail = float(coefficients[-1])
size = len(coefficients)
for i in range(size):
sign = 1 if (i % 2) == 0 else -1
el = sign * coefficients[size - i - 1] / tail
elementary_symmetric_polynomial.append(el)
return elementary_symmetric_polynomial | python | def vietes(coefficients):
r'''
Given the coefficients of a polynomial of a single variable,
compute an elementary symmetric polynomial of the roots of the
input polynomial by Viete's Formula:
.. math::
\sum_{1\le i_1<i_2<...<i_k \le n} x_{i_1}x_{i_2}...x_{i_k} = (-1)^k\frac{a_{n-k}}{a_n}
Parameters
----------
coefficients: list of float
A list of coefficients of the input polynomial of arbitrary length (degree) `n`
Returns
-------
list of float:
A list containing the expression of the roots of the input polynomial of length `n`
See Also
--------
https://en.wikipedia.org/wiki/Vieta%27s_formulas
'''
elementary_symmetric_polynomial = []
tail = float(coefficients[-1])
size = len(coefficients)
for i in range(size):
sign = 1 if (i % 2) == 0 else -1
el = sign * coefficients[size - i - 1] / tail
elementary_symmetric_polynomial.append(el)
return elementary_symmetric_polynomial | [
"def",
"vietes",
"(",
"coefficients",
")",
":",
"elementary_symmetric_polynomial",
"=",
"[",
"]",
"tail",
"=",
"float",
"(",
"coefficients",
"[",
"-",
"1",
"]",
")",
"size",
"=",
"len",
"(",
"coefficients",
")",
"for",
"i",
"in",
"range",
"(",
"size",
... | r'''
Given the coefficients of a polynomial of a single variable,
compute an elementary symmetric polynomial of the roots of the
input polynomial by Viete's Formula:
.. math::
\sum_{1\le i_1<i_2<...<i_k \le n} x_{i_1}x_{i_2}...x_{i_k} = (-1)^k\frac{a_{n-k}}{a_n}
Parameters
----------
coefficients: list of float
A list of coefficients of the input polynomial of arbitrary length (degree) `n`
Returns
-------
list of float:
A list containing the expression of the roots of the input polynomial of length `n`
See Also
--------
https://en.wikipedia.org/wiki/Vieta%27s_formulas | [
"r",
"Given",
"the",
"coefficients",
"of",
"a",
"polynomial",
"of",
"a",
"single",
"variable",
"compute",
"an",
"elementary",
"symmetric",
"polynomial",
"of",
"the",
"roots",
"of",
"the",
"input",
"polynomial",
"by",
"Viete",
"s",
"Formula",
":"
] | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L136-L168 |
mobiusklein/brainpy | brainpy/brainpy.py | max_variants | def max_variants(composition):
"""Calculates the maximum number of isotopic variants that could be produced by a
composition.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
Returns
-------
max_n_variants : int
"""
max_n_variants = 0
for element, count in composition.items():
if element == "H+":
continue
try:
max_n_variants += count * periodic_table[element].max_neutron_shift()
except KeyError:
pass
return max_n_variants | python | def max_variants(composition):
"""Calculates the maximum number of isotopic variants that could be produced by a
composition.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
Returns
-------
max_n_variants : int
"""
max_n_variants = 0
for element, count in composition.items():
if element == "H+":
continue
try:
max_n_variants += count * periodic_table[element].max_neutron_shift()
except KeyError:
pass
return max_n_variants | [
"def",
"max_variants",
"(",
"composition",
")",
":",
"max_n_variants",
"=",
"0",
"for",
"element",
",",
"count",
"in",
"composition",
".",
"items",
"(",
")",
":",
"if",
"element",
"==",
"\"H+\"",
":",
"continue",
"try",
":",
"max_n_variants",
"+=",
"count"... | Calculates the maximum number of isotopic variants that could be produced by a
composition.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
Returns
-------
max_n_variants : int | [
"Calculates",
"the",
"maximum",
"number",
"of",
"isotopic",
"variants",
"that",
"could",
"be",
"produced",
"by",
"a",
"composition",
"."
] | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L339-L362 |
mobiusklein/brainpy | brainpy/brainpy.py | isotopic_variants | def isotopic_variants(composition, npeaks=None, charge=0, charge_carrier=PROTON):
'''
Compute a peak list representing the theoretical isotopic cluster for `composition`.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
npeaks: int
The number of peaks to include in the isotopic cluster, starting from the monoisotopic peak.
If given a number below 1 or above the maximum number of isotopic variants, the maximum will
be used. If `None`, a "reasonable" value is chosen by `int(sqrt(max_variants(composition)))`.
charge: int
The charge state of the isotopic cluster to produce. Defaults to 0, theoretical neutral mass.
Returns
-------
list of Peaks
See Also
--------
:class:`IsotopicDistribution`
'''
if npeaks is None:
max_n_variants = max_variants(composition)
npeaks = int(sqrt(max_n_variants) - 2)
npeaks = max(npeaks, 3)
else:
# Monoisotopic Peak is not included
npeaks -= 1
return IsotopicDistribution(composition, npeaks).aggregated_isotopic_variants(
charge, charge_carrier=charge_carrier) | python | def isotopic_variants(composition, npeaks=None, charge=0, charge_carrier=PROTON):
'''
Compute a peak list representing the theoretical isotopic cluster for `composition`.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
npeaks: int
The number of peaks to include in the isotopic cluster, starting from the monoisotopic peak.
If given a number below 1 or above the maximum number of isotopic variants, the maximum will
be used. If `None`, a "reasonable" value is chosen by `int(sqrt(max_variants(composition)))`.
charge: int
The charge state of the isotopic cluster to produce. Defaults to 0, theoretical neutral mass.
Returns
-------
list of Peaks
See Also
--------
:class:`IsotopicDistribution`
'''
if npeaks is None:
max_n_variants = max_variants(composition)
npeaks = int(sqrt(max_n_variants) - 2)
npeaks = max(npeaks, 3)
else:
# Monoisotopic Peak is not included
npeaks -= 1
return IsotopicDistribution(composition, npeaks).aggregated_isotopic_variants(
charge, charge_carrier=charge_carrier) | [
"def",
"isotopic_variants",
"(",
"composition",
",",
"npeaks",
"=",
"None",
",",
"charge",
"=",
"0",
",",
"charge_carrier",
"=",
"PROTON",
")",
":",
"if",
"npeaks",
"is",
"None",
":",
"max_n_variants",
"=",
"max_variants",
"(",
"composition",
")",
"npeaks",
... | Compute a peak list representing the theoretical isotopic cluster for `composition`.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
npeaks: int
The number of peaks to include in the isotopic cluster, starting from the monoisotopic peak.
If given a number below 1 or above the maximum number of isotopic variants, the maximum will
be used. If `None`, a "reasonable" value is chosen by `int(sqrt(max_variants(composition)))`.
charge: int
The charge state of the isotopic cluster to produce. Defaults to 0, theoretical neutral mass.
Returns
-------
list of Peaks
See Also
--------
:class:`IsotopicDistribution` | [
"Compute",
"a",
"peak",
"list",
"representing",
"the",
"theoretical",
"isotopic",
"cluster",
"for",
"composition",
"."
] | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L579-L611 |
MisterWil/skybellpy | skybellpy/__main__.py | call | def call():
"""Execute command line helper."""
args = get_arguments()
# Set up logging
if args.debug:
log_level = logging.DEBUG
elif args.quiet:
log_level = logging.WARN
else:
log_level = logging.INFO
setup_logging(log_level)
skybell = None
try:
# Create skybellpy instance.
skybell = skybellpy.Skybell(username=args.username,
password=args.password,
get_devices=True)
# # Set setting
# for setting in args.set or []:
# keyval = setting.split("=")
# if skybell.set_setting(keyval[0], keyval[1]):
# _LOGGER.info("Setting %s changed to %s", keyval[0], keyval[1])
# Output Json
for device_id in args.json or []:
device = skybell.get_device(device_id)
if device:
# pylint: disable=protected-access
_LOGGER.info(device_id + " JSON:\n" +
json.dumps(device._device_json, sort_keys=True,
indent=4, separators=(',', ': ')))
else:
_LOGGER.warning("Could not find device with id: %s", device_id)
# Print
def _device_print(dev, append=''):
_LOGGER.info("%s%s",
dev.desc, append)
# Print out all devices.
if args.devices:
for device in skybell.get_devices():
_device_print(device)
# Print out specific devices by device id.
if args.device:
for device_id in args.device:
device = skybell.get_device(device_id)
if device:
_device_print(device)
else:
_LOGGER.warning(
"Could not find device with id: %s", device_id)
# Print out last motion event
if args.activity_json:
for device_id in args.activity_json:
device = skybell.get_device(device_id)
if device:
_LOGGER.info(device.latest(CONST.EVENT_MOTION))
else:
_LOGGER.warning(
"Could not find device with id: %s", device_id)
# Print out avatar image
if args.avatar_image:
for device_id in args.avatar_image:
device = skybell.get_device(device_id)
if device:
_LOGGER.info(device.image)
else:
_LOGGER.warning(
"Could not find device with id: %s", device_id)
# Print out last motion event image
if args.activity_image:
for device_id in args.activity_image:
device = skybell.get_device(device_id)
if device:
_LOGGER.info(device.activity_image)
else:
_LOGGER.warning(
"Could not find device with id: %s", device_id)
except SkybellException as exc:
_LOGGER.error(exc) | python | def call():
"""Execute command line helper."""
args = get_arguments()
# Set up logging
if args.debug:
log_level = logging.DEBUG
elif args.quiet:
log_level = logging.WARN
else:
log_level = logging.INFO
setup_logging(log_level)
skybell = None
try:
# Create skybellpy instance.
skybell = skybellpy.Skybell(username=args.username,
password=args.password,
get_devices=True)
# # Set setting
# for setting in args.set or []:
# keyval = setting.split("=")
# if skybell.set_setting(keyval[0], keyval[1]):
# _LOGGER.info("Setting %s changed to %s", keyval[0], keyval[1])
# Output Json
for device_id in args.json or []:
device = skybell.get_device(device_id)
if device:
# pylint: disable=protected-access
_LOGGER.info(device_id + " JSON:\n" +
json.dumps(device._device_json, sort_keys=True,
indent=4, separators=(',', ': ')))
else:
_LOGGER.warning("Could not find device with id: %s", device_id)
# Print
def _device_print(dev, append=''):
_LOGGER.info("%s%s",
dev.desc, append)
# Print out all devices.
if args.devices:
for device in skybell.get_devices():
_device_print(device)
# Print out specific devices by device id.
if args.device:
for device_id in args.device:
device = skybell.get_device(device_id)
if device:
_device_print(device)
else:
_LOGGER.warning(
"Could not find device with id: %s", device_id)
# Print out last motion event
if args.activity_json:
for device_id in args.activity_json:
device = skybell.get_device(device_id)
if device:
_LOGGER.info(device.latest(CONST.EVENT_MOTION))
else:
_LOGGER.warning(
"Could not find device with id: %s", device_id)
# Print out avatar image
if args.avatar_image:
for device_id in args.avatar_image:
device = skybell.get_device(device_id)
if device:
_LOGGER.info(device.image)
else:
_LOGGER.warning(
"Could not find device with id: %s", device_id)
# Print out last motion event image
if args.activity_image:
for device_id in args.activity_image:
device = skybell.get_device(device_id)
if device:
_LOGGER.info(device.activity_image)
else:
_LOGGER.warning(
"Could not find device with id: %s", device_id)
except SkybellException as exc:
_LOGGER.error(exc) | [
"def",
"call",
"(",
")",
":",
"args",
"=",
"get_arguments",
"(",
")",
"# Set up logging",
"if",
"args",
".",
"debug",
":",
"log_level",
"=",
"logging",
".",
"DEBUG",
"elif",
"args",
".",
"quiet",
":",
"log_level",
"=",
"logging",
".",
"WARN",
"else",
"... | Execute command line helper. | [
"Execute",
"command",
"line",
"helper",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__main__.py#L140-L235 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | trimim | def trimim( fims,
affine=None,
scale=2,
divdim = 8**2,
int_order=0,
fmax = 0.05,
outpath='',
fname='',
fcomment='',
store_avg=False,
store_img_intrmd=False,
store_img=False,
imdtype=np.float32,
memlim=False,
verbose=False):
'''
Trim and upsample PET image(s), e.g., for GPU execution,
PVC correction, ROI sampling, etc.
The input images 'fims' can be passed in multiple ways:
1. as a string of the folder containing NIfTI files
2. as a string of a NIfTI file path (this way a 4D image can be loaded).
3. as a list of NIfTI file paths.
4. as a 3D or 4D image
Parameters:
-----------
affine: affine matrix, 4x4, for all the input images in case when images
passed as a matrix (all have to have the same shape and data type)
scale: the scaling factor for upsampling has to be greater than 1
divdim: image divisor, i.e., the dimensions are a multiple of this number (default 64)
int_order: interpolation order (0-nearest neighbour, 1-linear, as in scipy)
fmax: fraction of the max image value used for finding image borders for trimming
outpath: output folder path
fname: file name when image given as a numpy matrix
fcomment: part of the name of the output file, left for the user as a comment
store_img_intrmd: stores intermediate images with suffix '_i'
store_avg: stores the average image (if multiple images are given)
imdtype: data type for output images
memlim: Ture for cases when memory is limited and takes more processing time instead.
verbose: verbose mode [True/False]
'''
using_multiple_files = False
# case when input folder is given
if isinstance(fims, basestring) and os.path.isdir(fims):
# list of input images (e.g., PET)
fimlist = [os.path.join(fims,f) for f in os.listdir(fims) if f.endswith('.nii') or f.endswith('.nii.gz')]
imdic = imio.niisort(fimlist, memlim=memlim)
if not (imdic['N']>50 and memlim):
imin = imdic['im']
imshape = imdic['shape']
affine = imdic['affine']
fldrin = fims
fnms = [os.path.basename(f).split('.nii')[0] for f in imdic['files'] if f!=None]
# number of images/frames
Nim = imdic['N']
using_multiple_files = True
# case when input file is a 3D or 4D NIfTI image
elif isinstance(fims, basestring) and os.path.isfile(fims) and (fims.endswith('nii') or fims.endswith('nii.gz')):
imdic = imio.getnii(fims, output='all')
imin = imdic['im']
if imin.ndim==3:
imin.shape = (1, imin.shape[0], imin.shape[1], imin.shape[2])
imdtype = imdic['dtype']
imshape = imdic['shape'][-3:]
affine = imdic['affine']
fldrin = os.path.dirname(fims)
fnms = imin.shape[0] * [ os.path.basename(fims).split('.nii')[0] ]
# number of images/frames
Nim = imin.shape[0]
# case when a list of input files is given
elif isinstance(fims, list) and all([os.path.isfile(k) for k in fims]):
imdic = imio.niisort(fims, memlim=memlim)
if not (imdic['N']>50 and memlim):
imin = imdic['im']
imshape = imdic['shape']
affine = imdic['affine']
imdtype = imdic['dtype']
fldrin = os.path.dirname(fims[0])
fnms = [os.path.basename(f).split('.nii')[0] for f in imdic['files']]
# number of images/frames
Nim = imdic['N']
using_multiple_files = True
# case when an array [#frames, zdim, ydim, xdim]. Can be 3D or 4D
elif isinstance(fims, (np.ndarray, np.generic)) and (fims.ndim==4 or fims.ndim==3):
# check image affine
if affine.shape!=(4,4):
raise ValueError('Affine should be a 4x4 array.')
# create a copy to avoid mutation when only one image (3D)
imin = np.copy(fims)
if fims.ndim==3:
imin.shape = (1, imin.shape[0], imin.shape[1], imin.shape[2])
imshape = imin.shape[-3:]
fldrin = os.path.join(os.path.expanduser('~'), 'NIMPA_output')
if fname=='':
fnms = imin.shape[0] * [ 'NIMPA' ]
else:
fnms = imin.shape[0] * [ fname ]
# number of images/frames
Nim = imin.shape[0]
else:
raise TypeError('Wrong data type input.')
#-------------------------------------------------------
# store images in this folder
if outpath=='':
petudir = os.path.join(fldrin, 'trimmed')
else:
petudir = os.path.join(outpath, 'trimmed')
imio.create_dir( petudir )
#-------------------------------------------------------
#-------------------------------------------------------
# scale is preferred to be integer
try:
scale = int(scale)
except ValueError:
raise ValueError('e> scale has to be an integer.')
# scale factor as the inverse of scale
sf = 1/float(scale)
if verbose:
print 'i> upsampling scale {}, giving resolution scale factor {} for {} images.'.format(scale, sf, Nim)
#-------------------------------------------------------
#-------------------------------------------------------
# scaled input image and get a sum image as the base for trimming
if scale>1:
newshape = (scale*imshape[0], scale*imshape[1], scale*imshape[2])
imsum = np.zeros(newshape, dtype=imdtype)
if not memlim:
imscl = np.zeros((Nim,)+newshape, dtype=imdtype)
for i in range(Nim):
imscl[i,:,:,:] = ndi.interpolation.zoom(imin[i,:,:,:], (scale, scale, scale), order=int_order )
imsum += imscl[i,:,:,:]
else:
for i in range(Nim):
if Nim>50 and using_multiple_files:
imin_temp = imio.getnii(imdic['files'][i])
imsum += ndi.interpolation.zoom(imin_temp, (scale, scale, scale), order=0 )
if verbose:
print 'i> image sum: read', imdic['files'][i]
else:
imsum += ndi.interpolation.zoom(imin[i,:,:,:], (scale, scale, scale), order=0 )
else:
imscl = imin
imsum = np.sum(imin, axis=0)
# smooth the sum image for improving trimming (if any)
#imsum = ndi.filters.gaussian_filter(imsum, imio.fwhm2sig(4.0, voxsize=abs(affine[0,0])), mode='mirror')
#-------------------------------------------------------
# find the object bounding indexes in x, y and z axes, e.g., ix0-ix1 for the x axis
qx = np.sum(imsum, axis=(0,1))
ix0 = np.argmax( qx>(fmax*np.nanmax(qx)) )
ix1 = ix0+np.argmin( qx[ix0:]>(fmax*np.nanmax(qx)) )
qy = np.sum(imsum, axis=(0,2))
iy0 = np.argmax( qy>(fmax*np.nanmax(qy)) )
iy1 = iy0+np.argmin( qy[iy0:]>(fmax*np.nanmax(qy)) )
qz = np.sum(imsum, axis=(1,2))
iz0 = np.argmax( qz>(fmax*np.nanmax(qz)) )
# find the maximum voxel range for x and y axes
IX = ix1-ix0+1
IY = iy1-iy0+1
tmp = max(IX, IY)
#> get the range such that it is divisible by
#> divdim (64 by default) for GPU execution
IXY = divdim * ((tmp+divdim-1)/divdim)
div = (IXY-IX)/2
# x
ix0 -= div
ix1 += (IXY-IX)-div
# y
div = (IXY-IY)/2
iy0 -= div
iy1 += (IXY-IY)-div
# z
tmp = (len(qz)-iz0+1)
IZ = divdim * ((tmp+divdim-1)/divdim)
iz0 -= IZ-tmp+1
# save the trimming parameters in a dic
trimpar = {'x':(ix0, ix1), 'y':(iy0, iy1), 'z':(iz0), 'fmax':fmax}
# new dims (z,y,x)
newdims = (imsum.shape[0]-iz0, iy1-iy0+1, ix1-ix0+1)
imtrim = np.zeros((Nim,)+newdims, dtype=imdtype)
imsumt = np.zeros(newdims, dtype=imdtype)
# in case of needed padding (negative indx resulting above)
# the absolute values are supposed to work like padding in case the indx are negative
iz0s, iy0s, ix0s = iz0, iy0, ix0
iz0t, iy0t, ix0t = 0,0,0
if iz0<0:
iz0s=0;
iz0t = abs(iz0)
print '-----------------------------------------------------------------'
print 'w> Correcting for trimming outside the original image (z-axis)'
print '-----------------------------------------------------------------'
if iy0<0:
iy0s=0;
iy0t = abs(iy0)
print '-----------------------------------------------------------------'
print 'w> Correcting for trimming outside the original image (y-axis)'
print '-----------------------------------------------------------------'
if ix0<0:
ix0s=0;
ix0t = abs(ix0)
print '-----------------------------------------------------------------'
print 'w> Correcting for trimming outside the original image (x-axis)'
print '-----------------------------------------------------------------'
#> in case the upper index goes beyond the scaled but untrimmed image
iy1t = imsumt.shape[1]
if iy1>=imsum.shape[1]:
iy1t -= iy1+1
#> the same for x
ix1t = imsumt.shape[2]
if ix1>=imsum.shape[2]:
ix1t -= ix1+1
# first trim the sum image
imsumt[iz0t:, iy0t:iy1t, ix0t:ix1t] = imsum[iz0s:, iy0s:iy1+1, ix0s:ix1+1]
#> new affine matrix for the scaled and trimmed image
A = np.diag(sf*np.diag(affine))
#> note half of new voxel offset is used for the new centre of voxels
A[0,3] = affine[0,3] + A[0,0]*(ix0-0.5)
A[1,3] = affine[1,3] + (affine[1,1]*(imshape[1]-1) - A[1,1]*(iy1-0.5))
A[2,3] = affine[2,3] - A[1,1]*0.5
A[3,3] = 1
# output dictionary
dctout = {'affine': A, 'trimpar':trimpar, 'imsum':imsumt}
# NIfTI image description (to be stored in the header)
niidescr = 'trimm(x,y,z):' \
+ str(trimpar['x'])+',' \
+ str(trimpar['y'])+',' \
+ str((trimpar['z'],)) \
+ ';scale='+str(scale) \
+ ';fmx='+str(fmax)
# store the sum image
if store_avg:
fsum = os.path.join(petudir, 'avg_trimmed-upsampled-scale-'+str(scale)+fcomment+'.nii.gz')
imio.array2nii( imsumt[::-1,::-1,:], A, fsum, descrip=niidescr)
if verbose: print 'i> saved averaged image to:', fsum
dctout['fsum'] = fsum
# list of file names for the upsampled and trimmed images
fpetu = []
# perform the trimming and save the intermediate images if requested
for i in range(Nim):
# memory saving option, second time doing interpolation
if memlim:
if Nim>50 and using_multiple_files:
imin_temp = imio.getnii(imdic['files'][i])
im = ndi.interpolation.zoom(imin_temp, (scale, scale, scale), order=int_order )
if verbose:
print 'i> image scaling:', imdic['files'][i]
else:
im = ndi.interpolation.zoom(imin[i,:,:,:], (scale, scale, scale), order=int_order )
else:
im = imscl[i,:,:,:]
# trim the scaled image
imtrim[i, iz0t:, iy0t:iy1t, ix0t:ix1t] = im[iz0s:, iy0s:iy1+1, ix0s:ix1+1]
# save the up-sampled and trimmed PET images
if store_img_intrmd:
_frm = '_trmfrm'+str(i)
_fstr = '_trimmed-upsampled-scale-'+str(scale) + _frm*(Nim>1) +fcomment
fpetu.append( os.path.join(petudir, fnms[i]+_fstr+'_i.nii.gz') )
imio.array2nii( imtrim[i,::-1,::-1,:], A, fpetu[i], descrip=niidescr)
if verbose: print 'i> saved upsampled PET image to:', fpetu[i]
if store_img:
_nfrm = '_nfrm'+str(Nim)
fim = os.path.join(petudir, 'trimmed-upsampled-scale-'+str(scale))+_nfrm*(Nim>1)+fcomment+'.nii.gz'
imio.array2nii( np.squeeze(imtrim[:,::-1,::-1,:]), A, fim, descrip=niidescr)
dctout['fim'] = fim
# file names (with paths) for the intermediate PET images
dctout['fimi'] = fpetu
dctout['im'] = np.squeeze(imtrim)
dctout['N'] = Nim
dctout['affine'] = A
return dctout | python | def trimim( fims,
affine=None,
scale=2,
divdim = 8**2,
int_order=0,
fmax = 0.05,
outpath='',
fname='',
fcomment='',
store_avg=False,
store_img_intrmd=False,
store_img=False,
imdtype=np.float32,
memlim=False,
verbose=False):
'''
Trim and upsample PET image(s), e.g., for GPU execution,
PVC correction, ROI sampling, etc.
The input images 'fims' can be passed in multiple ways:
1. as a string of the folder containing NIfTI files
2. as a string of a NIfTI file path (this way a 4D image can be loaded).
3. as a list of NIfTI file paths.
4. as a 3D or 4D image
Parameters:
-----------
affine: affine matrix, 4x4, for all the input images in case when images
passed as a matrix (all have to have the same shape and data type)
scale: the scaling factor for upsampling has to be greater than 1
divdim: image divisor, i.e., the dimensions are a multiple of this number (default 64)
int_order: interpolation order (0-nearest neighbour, 1-linear, as in scipy)
fmax: fraction of the max image value used for finding image borders for trimming
outpath: output folder path
fname: file name when image given as a numpy matrix
fcomment: part of the name of the output file, left for the user as a comment
store_img_intrmd: stores intermediate images with suffix '_i'
store_avg: stores the average image (if multiple images are given)
imdtype: data type for output images
memlim: Ture for cases when memory is limited and takes more processing time instead.
verbose: verbose mode [True/False]
'''
using_multiple_files = False
# case when input folder is given
if isinstance(fims, basestring) and os.path.isdir(fims):
# list of input images (e.g., PET)
fimlist = [os.path.join(fims,f) for f in os.listdir(fims) if f.endswith('.nii') or f.endswith('.nii.gz')]
imdic = imio.niisort(fimlist, memlim=memlim)
if not (imdic['N']>50 and memlim):
imin = imdic['im']
imshape = imdic['shape']
affine = imdic['affine']
fldrin = fims
fnms = [os.path.basename(f).split('.nii')[0] for f in imdic['files'] if f!=None]
# number of images/frames
Nim = imdic['N']
using_multiple_files = True
# case when input file is a 3D or 4D NIfTI image
elif isinstance(fims, basestring) and os.path.isfile(fims) and (fims.endswith('nii') or fims.endswith('nii.gz')):
imdic = imio.getnii(fims, output='all')
imin = imdic['im']
if imin.ndim==3:
imin.shape = (1, imin.shape[0], imin.shape[1], imin.shape[2])
imdtype = imdic['dtype']
imshape = imdic['shape'][-3:]
affine = imdic['affine']
fldrin = os.path.dirname(fims)
fnms = imin.shape[0] * [ os.path.basename(fims).split('.nii')[0] ]
# number of images/frames
Nim = imin.shape[0]
# case when a list of input files is given
elif isinstance(fims, list) and all([os.path.isfile(k) for k in fims]):
imdic = imio.niisort(fims, memlim=memlim)
if not (imdic['N']>50 and memlim):
imin = imdic['im']
imshape = imdic['shape']
affine = imdic['affine']
imdtype = imdic['dtype']
fldrin = os.path.dirname(fims[0])
fnms = [os.path.basename(f).split('.nii')[0] for f in imdic['files']]
# number of images/frames
Nim = imdic['N']
using_multiple_files = True
# case when an array [#frames, zdim, ydim, xdim]. Can be 3D or 4D
elif isinstance(fims, (np.ndarray, np.generic)) and (fims.ndim==4 or fims.ndim==3):
# check image affine
if affine.shape!=(4,4):
raise ValueError('Affine should be a 4x4 array.')
# create a copy to avoid mutation when only one image (3D)
imin = np.copy(fims)
if fims.ndim==3:
imin.shape = (1, imin.shape[0], imin.shape[1], imin.shape[2])
imshape = imin.shape[-3:]
fldrin = os.path.join(os.path.expanduser('~'), 'NIMPA_output')
if fname=='':
fnms = imin.shape[0] * [ 'NIMPA' ]
else:
fnms = imin.shape[0] * [ fname ]
# number of images/frames
Nim = imin.shape[0]
else:
raise TypeError('Wrong data type input.')
#-------------------------------------------------------
# store images in this folder
if outpath=='':
petudir = os.path.join(fldrin, 'trimmed')
else:
petudir = os.path.join(outpath, 'trimmed')
imio.create_dir( petudir )
#-------------------------------------------------------
#-------------------------------------------------------
# scale is preferred to be integer
try:
scale = int(scale)
except ValueError:
raise ValueError('e> scale has to be an integer.')
# scale factor as the inverse of scale
sf = 1/float(scale)
if verbose:
print 'i> upsampling scale {}, giving resolution scale factor {} for {} images.'.format(scale, sf, Nim)
#-------------------------------------------------------
#-------------------------------------------------------
# scaled input image and get a sum image as the base for trimming
if scale>1:
newshape = (scale*imshape[0], scale*imshape[1], scale*imshape[2])
imsum = np.zeros(newshape, dtype=imdtype)
if not memlim:
imscl = np.zeros((Nim,)+newshape, dtype=imdtype)
for i in range(Nim):
imscl[i,:,:,:] = ndi.interpolation.zoom(imin[i,:,:,:], (scale, scale, scale), order=int_order )
imsum += imscl[i,:,:,:]
else:
for i in range(Nim):
if Nim>50 and using_multiple_files:
imin_temp = imio.getnii(imdic['files'][i])
imsum += ndi.interpolation.zoom(imin_temp, (scale, scale, scale), order=0 )
if verbose:
print 'i> image sum: read', imdic['files'][i]
else:
imsum += ndi.interpolation.zoom(imin[i,:,:,:], (scale, scale, scale), order=0 )
else:
imscl = imin
imsum = np.sum(imin, axis=0)
# smooth the sum image for improving trimming (if any)
#imsum = ndi.filters.gaussian_filter(imsum, imio.fwhm2sig(4.0, voxsize=abs(affine[0,0])), mode='mirror')
#-------------------------------------------------------
# find the object bounding indexes in x, y and z axes, e.g., ix0-ix1 for the x axis
qx = np.sum(imsum, axis=(0,1))
ix0 = np.argmax( qx>(fmax*np.nanmax(qx)) )
ix1 = ix0+np.argmin( qx[ix0:]>(fmax*np.nanmax(qx)) )
qy = np.sum(imsum, axis=(0,2))
iy0 = np.argmax( qy>(fmax*np.nanmax(qy)) )
iy1 = iy0+np.argmin( qy[iy0:]>(fmax*np.nanmax(qy)) )
qz = np.sum(imsum, axis=(1,2))
iz0 = np.argmax( qz>(fmax*np.nanmax(qz)) )
# find the maximum voxel range for x and y axes
IX = ix1-ix0+1
IY = iy1-iy0+1
tmp = max(IX, IY)
#> get the range such that it is divisible by
#> divdim (64 by default) for GPU execution
IXY = divdim * ((tmp+divdim-1)/divdim)
div = (IXY-IX)/2
# x
ix0 -= div
ix1 += (IXY-IX)-div
# y
div = (IXY-IY)/2
iy0 -= div
iy1 += (IXY-IY)-div
# z
tmp = (len(qz)-iz0+1)
IZ = divdim * ((tmp+divdim-1)/divdim)
iz0 -= IZ-tmp+1
# save the trimming parameters in a dic
trimpar = {'x':(ix0, ix1), 'y':(iy0, iy1), 'z':(iz0), 'fmax':fmax}
# new dims (z,y,x)
newdims = (imsum.shape[0]-iz0, iy1-iy0+1, ix1-ix0+1)
imtrim = np.zeros((Nim,)+newdims, dtype=imdtype)
imsumt = np.zeros(newdims, dtype=imdtype)
# in case of needed padding (negative indx resulting above)
# the absolute values are supposed to work like padding in case the indx are negative
iz0s, iy0s, ix0s = iz0, iy0, ix0
iz0t, iy0t, ix0t = 0,0,0
if iz0<0:
iz0s=0;
iz0t = abs(iz0)
print '-----------------------------------------------------------------'
print 'w> Correcting for trimming outside the original image (z-axis)'
print '-----------------------------------------------------------------'
if iy0<0:
iy0s=0;
iy0t = abs(iy0)
print '-----------------------------------------------------------------'
print 'w> Correcting for trimming outside the original image (y-axis)'
print '-----------------------------------------------------------------'
if ix0<0:
ix0s=0;
ix0t = abs(ix0)
print '-----------------------------------------------------------------'
print 'w> Correcting for trimming outside the original image (x-axis)'
print '-----------------------------------------------------------------'
#> in case the upper index goes beyond the scaled but untrimmed image
iy1t = imsumt.shape[1]
if iy1>=imsum.shape[1]:
iy1t -= iy1+1
#> the same for x
ix1t = imsumt.shape[2]
if ix1>=imsum.shape[2]:
ix1t -= ix1+1
# first trim the sum image
imsumt[iz0t:, iy0t:iy1t, ix0t:ix1t] = imsum[iz0s:, iy0s:iy1+1, ix0s:ix1+1]
#> new affine matrix for the scaled and trimmed image
A = np.diag(sf*np.diag(affine))
#> note half of new voxel offset is used for the new centre of voxels
A[0,3] = affine[0,3] + A[0,0]*(ix0-0.5)
A[1,3] = affine[1,3] + (affine[1,1]*(imshape[1]-1) - A[1,1]*(iy1-0.5))
A[2,3] = affine[2,3] - A[1,1]*0.5
A[3,3] = 1
# output dictionary
dctout = {'affine': A, 'trimpar':trimpar, 'imsum':imsumt}
# NIfTI image description (to be stored in the header)
niidescr = 'trimm(x,y,z):' \
+ str(trimpar['x'])+',' \
+ str(trimpar['y'])+',' \
+ str((trimpar['z'],)) \
+ ';scale='+str(scale) \
+ ';fmx='+str(fmax)
# store the sum image
if store_avg:
fsum = os.path.join(petudir, 'avg_trimmed-upsampled-scale-'+str(scale)+fcomment+'.nii.gz')
imio.array2nii( imsumt[::-1,::-1,:], A, fsum, descrip=niidescr)
if verbose: print 'i> saved averaged image to:', fsum
dctout['fsum'] = fsum
# list of file names for the upsampled and trimmed images
fpetu = []
# perform the trimming and save the intermediate images if requested
for i in range(Nim):
# memory saving option, second time doing interpolation
if memlim:
if Nim>50 and using_multiple_files:
imin_temp = imio.getnii(imdic['files'][i])
im = ndi.interpolation.zoom(imin_temp, (scale, scale, scale), order=int_order )
if verbose:
print 'i> image scaling:', imdic['files'][i]
else:
im = ndi.interpolation.zoom(imin[i,:,:,:], (scale, scale, scale), order=int_order )
else:
im = imscl[i,:,:,:]
# trim the scaled image
imtrim[i, iz0t:, iy0t:iy1t, ix0t:ix1t] = im[iz0s:, iy0s:iy1+1, ix0s:ix1+1]
# save the up-sampled and trimmed PET images
if store_img_intrmd:
_frm = '_trmfrm'+str(i)
_fstr = '_trimmed-upsampled-scale-'+str(scale) + _frm*(Nim>1) +fcomment
fpetu.append( os.path.join(petudir, fnms[i]+_fstr+'_i.nii.gz') )
imio.array2nii( imtrim[i,::-1,::-1,:], A, fpetu[i], descrip=niidescr)
if verbose: print 'i> saved upsampled PET image to:', fpetu[i]
if store_img:
_nfrm = '_nfrm'+str(Nim)
fim = os.path.join(petudir, 'trimmed-upsampled-scale-'+str(scale))+_nfrm*(Nim>1)+fcomment+'.nii.gz'
imio.array2nii( np.squeeze(imtrim[:,::-1,::-1,:]), A, fim, descrip=niidescr)
dctout['fim'] = fim
# file names (with paths) for the intermediate PET images
dctout['fimi'] = fpetu
dctout['im'] = np.squeeze(imtrim)
dctout['N'] = Nim
dctout['affine'] = A
return dctout | [
"def",
"trimim",
"(",
"fims",
",",
"affine",
"=",
"None",
",",
"scale",
"=",
"2",
",",
"divdim",
"=",
"8",
"**",
"2",
",",
"int_order",
"=",
"0",
",",
"fmax",
"=",
"0.05",
",",
"outpath",
"=",
"''",
",",
"fname",
"=",
"''",
",",
"fcomment",
"="... | Trim and upsample PET image(s), e.g., for GPU execution,
PVC correction, ROI sampling, etc.
The input images 'fims' can be passed in multiple ways:
1. as a string of the folder containing NIfTI files
2. as a string of a NIfTI file path (this way a 4D image can be loaded).
3. as a list of NIfTI file paths.
4. as a 3D or 4D image
Parameters:
-----------
affine: affine matrix, 4x4, for all the input images in case when images
passed as a matrix (all have to have the same shape and data type)
scale: the scaling factor for upsampling has to be greater than 1
divdim: image divisor, i.e., the dimensions are a multiple of this number (default 64)
int_order: interpolation order (0-nearest neighbour, 1-linear, as in scipy)
fmax: fraction of the max image value used for finding image borders for trimming
outpath: output folder path
fname: file name when image given as a numpy matrix
fcomment: part of the name of the output file, left for the user as a comment
store_img_intrmd: stores intermediate images with suffix '_i'
store_avg: stores the average image (if multiple images are given)
imdtype: data type for output images
memlim: Ture for cases when memory is limited and takes more processing time instead.
verbose: verbose mode [True/False] | [
"Trim",
"and",
"upsample",
"PET",
"image",
"(",
"s",
")",
"e",
".",
"g",
".",
"for",
"GPU",
"execution",
"PVC",
"correction",
"ROI",
"sampling",
"etc",
".",
"The",
"input",
"images",
"fims",
"can",
"be",
"passed",
"in",
"multiple",
"ways",
":",
"1",
... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L46-L347 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | psf_general | def psf_general(vx_size=(1,1,1), fwhm=(5, 5, 6), hradius=8, scale=2):
'''
Separable kernels for convolution executed on the GPU device
The outputted kernels are in this order: z, y, x
'''
xSig = (scale*fwhm[0]/vx_size[0]) / (2*(2*np.log(2))**.5)
ySig = (scale*fwhm[1]/vx_size[1]) / (2*(2*np.log(2))**.5)
zSig = (scale*fwhm[2]/vx_size[2]) / (2*(2*np.log(2))**.5)
# get the separated kernels
x = np.arange(-hradius,hradius+1)
xKrnl = np.exp(-(x**2/(2*xSig**2)))
yKrnl = np.exp(-(x**2/(2*ySig**2)))
zKrnl = np.exp(-(x**2/(2*zSig**2)))
# normalise kernels
xKrnl /= np.sum(xKrnl)
yKrnl /= np.sum(yKrnl)
zKrnl /= np.sum(zKrnl)
krnl = np.array([zKrnl, yKrnl, xKrnl], dtype=np.float32)
# for checking if the normalisation worked
# np.prod( np.sum(krnl,axis=1) )
# return all kernels together
return krnl | python | def psf_general(vx_size=(1,1,1), fwhm=(5, 5, 6), hradius=8, scale=2):
'''
Separable kernels for convolution executed on the GPU device
The outputted kernels are in this order: z, y, x
'''
xSig = (scale*fwhm[0]/vx_size[0]) / (2*(2*np.log(2))**.5)
ySig = (scale*fwhm[1]/vx_size[1]) / (2*(2*np.log(2))**.5)
zSig = (scale*fwhm[2]/vx_size[2]) / (2*(2*np.log(2))**.5)
# get the separated kernels
x = np.arange(-hradius,hradius+1)
xKrnl = np.exp(-(x**2/(2*xSig**2)))
yKrnl = np.exp(-(x**2/(2*ySig**2)))
zKrnl = np.exp(-(x**2/(2*zSig**2)))
# normalise kernels
xKrnl /= np.sum(xKrnl)
yKrnl /= np.sum(yKrnl)
zKrnl /= np.sum(zKrnl)
krnl = np.array([zKrnl, yKrnl, xKrnl], dtype=np.float32)
# for checking if the normalisation worked
# np.prod( np.sum(krnl,axis=1) )
# return all kernels together
return krnl | [
"def",
"psf_general",
"(",
"vx_size",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
",",
"fwhm",
"=",
"(",
"5",
",",
"5",
",",
"6",
")",
",",
"hradius",
"=",
"8",
",",
"scale",
"=",
"2",
")",
":",
"xSig",
"=",
"(",
"scale",
"*",
"fwhm",
"[",
"0... | Separable kernels for convolution executed on the GPU device
The outputted kernels are in this order: z, y, x | [
"Separable",
"kernels",
"for",
"convolution",
"executed",
"on",
"the",
"GPU",
"device",
"The",
"outputted",
"kernels",
"are",
"in",
"this",
"order",
":",
"z",
"y",
"x"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L356-L382 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | iyang | def iyang(imgIn, krnl, imgSeg, Cnt, itr=5):
'''partial volume correction using iterative Yang method
imgIn: input image which is blurred due to the PSF of the scanner
krnl: shift invariant kernel of the PSF
imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer numbers
itr: number of iteration (default 5)
'''
dim = imgIn.shape
m = np.int32(np.max(imgSeg))
m_a = np.zeros(( m+1, itr ), dtype=np.float32)
for jr in range(0,m+1):
m_a[jr, 0] = np.mean( imgIn[imgSeg==jr] )
# init output image
imgOut = np.copy(imgIn)
# iterative Yang algorithm:
for i in range(0, itr):
if Cnt['VERBOSE']: print 'i> PVC Yang iteration =', i
# piece-wise constant image
imgPWC = imgOut
imgPWC[imgPWC<0] = 0
for jr in range(0,m+1):
imgPWC[imgSeg==jr] = np.mean( imgPWC[imgSeg==jr] )
#> blur the piece-wise constant image using either:
#> (1) GPU convolution with a separable kernel (x,y,z), or
#> (2) CPU, Python-based convolution
if 'CCARCH' in Cnt and 'compute' in Cnt['CCARCH']:
#> convert to dimensions of GPU processing [y,x,z]
imin_d = np.transpose(imgPWC, (1, 2, 0))
imout_d = np.zeros(imin_d.shape, dtype=np.float32)
improc.convolve(imout_d, imin_d, krnl, Cnt)
imgSmo = np.transpose(imout_d, (2,0,1))
else:
hxy = np.outer(krnl[1,:], krnl[2,:])
hxyz = np.multiply.outer(krnl[0,:], hxy)
imgSmo = ndi.convolve(imgPWC, hxyz, mode='constant', cval=0.)
# correction factors
imgCrr = np.ones(dim, dtype=np.float32)
imgCrr[imgSmo>0] = imgPWC[imgSmo>0] / imgSmo[imgSmo>0]
imgOut = imgIn * imgCrr;
for jr in range(0,m+1):
m_a[jr, i] = np.mean( imgOut[imgSeg==jr] )
return imgOut, m_a | python | def iyang(imgIn, krnl, imgSeg, Cnt, itr=5):
'''partial volume correction using iterative Yang method
imgIn: input image which is blurred due to the PSF of the scanner
krnl: shift invariant kernel of the PSF
imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer numbers
itr: number of iteration (default 5)
'''
dim = imgIn.shape
m = np.int32(np.max(imgSeg))
m_a = np.zeros(( m+1, itr ), dtype=np.float32)
for jr in range(0,m+1):
m_a[jr, 0] = np.mean( imgIn[imgSeg==jr] )
# init output image
imgOut = np.copy(imgIn)
# iterative Yang algorithm:
for i in range(0, itr):
if Cnt['VERBOSE']: print 'i> PVC Yang iteration =', i
# piece-wise constant image
imgPWC = imgOut
imgPWC[imgPWC<0] = 0
for jr in range(0,m+1):
imgPWC[imgSeg==jr] = np.mean( imgPWC[imgSeg==jr] )
#> blur the piece-wise constant image using either:
#> (1) GPU convolution with a separable kernel (x,y,z), or
#> (2) CPU, Python-based convolution
if 'CCARCH' in Cnt and 'compute' in Cnt['CCARCH']:
#> convert to dimensions of GPU processing [y,x,z]
imin_d = np.transpose(imgPWC, (1, 2, 0))
imout_d = np.zeros(imin_d.shape, dtype=np.float32)
improc.convolve(imout_d, imin_d, krnl, Cnt)
imgSmo = np.transpose(imout_d, (2,0,1))
else:
hxy = np.outer(krnl[1,:], krnl[2,:])
hxyz = np.multiply.outer(krnl[0,:], hxy)
imgSmo = ndi.convolve(imgPWC, hxyz, mode='constant', cval=0.)
# correction factors
imgCrr = np.ones(dim, dtype=np.float32)
imgCrr[imgSmo>0] = imgPWC[imgSmo>0] / imgSmo[imgSmo>0]
imgOut = imgIn * imgCrr;
for jr in range(0,m+1):
m_a[jr, i] = np.mean( imgOut[imgSeg==jr] )
return imgOut, m_a | [
"def",
"iyang",
"(",
"imgIn",
",",
"krnl",
",",
"imgSeg",
",",
"Cnt",
",",
"itr",
"=",
"5",
")",
":",
"dim",
"=",
"imgIn",
".",
"shape",
"m",
"=",
"np",
".",
"int32",
"(",
"np",
".",
"max",
"(",
"imgSeg",
")",
")",
"m_a",
"=",
"np",
".",
"z... | partial volume correction using iterative Yang method
imgIn: input image which is blurred due to the PSF of the scanner
krnl: shift invariant kernel of the PSF
imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer numbers
itr: number of iteration (default 5) | [
"partial",
"volume",
"correction",
"using",
"iterative",
"Yang",
"method",
"imgIn",
":",
"input",
"image",
"which",
"is",
"blurred",
"due",
"to",
"the",
"PSF",
"of",
"the",
"scanner",
"krnl",
":",
"shift",
"invariant",
"kernel",
"of",
"the",
"PSF",
"imgSeg",... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L405-L453 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | pvc_iyang | def pvc_iyang(
petin,
mridct,
Cnt,
pvcroi,
krnl,
itr=5,
tool='niftyreg',
faff='',
outpath='',
fcomment='',
store_img=False,
store_rois=False,
):
''' Perform partial volume (PVC) correction of PET data (petin) using MRI data (mridct).
The PVC method uses iterative Yang method.
GPU based convolution is the key routine of the PVC.
Input:
-------
petin: either a dictionary containing image data, file name and affine transform,
or a string of the path to the NIfTI file of the PET data.
mridct: a dictionary of MRI data, including the T1w image, which can be given
in DICOM (field 'T1DCM') or NIfTI (field 'T1nii'). The T1w image data
is needed for co-registration to PET if affine is not given in the text
file with its path in faff.
Cnt: a dictionary of paths for third-party tools:
* dcm2niix: Cnt['DCM2NIIX']
* niftyreg, resample: Cnt['RESPATH']
* niftyreg, rigid-reg: Cnt['REGPATH']
* verbose mode on/off: Cnt['VERBOSE'] = True/False
pvcroi: list of regions (also a list) with number label to distinguish
the parcellations. The numbers correspond to the image values
of the parcellated T1w image. E.g.:
pvcroi = [
[36], # ROI 1 (single parcellation region)
[35], # ROI 2
[39, 40, 72, 73, 74], # ROI 3 (region consisting of multiple parcellation regions)
...
]
kernel: the point spread function (PSF) specific for the camera and the object.
It is given as a 3x17 matrix, a 17-element kernel for each dimension (x,y,z).
It is used in the GPU-based convolution using separable kernels.
outpath:path to the output of the resulting PVC images
faff: a text file of the affine transformations needed to get the MRI into PET space.
If not provided, it will be obtained from the performed rigid transformation.
For this the MR T1w image is required. If faff and T1w image are not provided,
it will results in exception/error.
fcomment:a string used in naming the produced files, helpful for distinguishing them.
tool: co-registration tool. By default it is NiftyReg, but SPM is also
possible (needs Matlab engine and more validation)
itr: number of iterations used by the PVC. 5-10 should be enough (5 default)
'''
# get all the input image properties
if isinstance(petin, dict):
im = imdic['im']
fpet = imdic['fpet']
B = imdic['affine']
elif isinstance(petin, basestring) and os.path.isfile(petin):
imdct = imio.getnii(petin, output='all')
im = imdct['im']
B = imdct['affine']
fpet = petin
if im.ndim!=3:
raise IndexError('Only 3D images are expected in this method of partial volume correction.')
# check if brain parcellations exist in NIfTI format
if not os.path.isfile(mridct['T1lbl']):
raise NameError('MissingLabels')
#> output dictionary
outdct = {}
# establish the output folder
if outpath=='':
prcl_dir = os.path.dirname(mridct['T1lbl'])
pvc_dir = os.path.join(os.path.dirname(fpet), 'PVC')
else:
prcl_dir = outpath
pvc_dir = os.path.join(os.path.dirname(fpet), 'PVC')
#> create folders
imio.create_dir(prcl_dir)
imio.create_dir(pvc_dir)
#==================================================================
#if affine transf. (faff) is given then take the T1 and resample it too.
if isinstance(faff, basestring) and not os.path.isfile(faff):
# faff is not given; get it by running the affine; get T1w to PET space
ft1w = imio.pick_t1w(mridct)
if tool=='spm':
regdct = regseg.coreg_spm(
fpet,
ft1w,
fcomment = fcomment,
outpath=os.path.join(outpath,'PET', 'positioning')
)
elif tool=='niftyreg':
regdct = regseg.affine_niftyreg(
fpet,
ft1w,
outpath=os.path.join(outpath,'PET', 'positioning'),
fcomment = fcomment,
executable = Cnt['REGPATH'],
omp = multiprocessing.cpu_count()/2,
rigOnly = True,
affDirect = False,
maxit=5,
speed=True,
pi=50, pv=50,
smof=0, smor=0,
rmsk=True,
fmsk=True,
rfwhm=15., #millilitres
rthrsh=0.05,
ffwhm = 15., #millilitres
fthrsh=0.05,
verbose=Cnt['VERBOSE']
)
faff = regdct['faff']
# resample the GIF T1/labels to upsampled PET
# file name of the parcellation (GIF-based) upsampled to PET
fgt1u = os.path.join(
prcl_dir,
os.path.basename(mridct['T1lbl']).split('.')[0]\
+'_registered_trimmed'+fcomment+'.nii.gz')
if tool=='niftyreg':
if os.path.isfile( Cnt['RESPATH'] ):
cmd = [Cnt['RESPATH'], '-ref', fpet, '-flo', mridct['T1lbl'],
'-trans', faff, '-res', fgt1u, '-inter', '0']
if not Cnt['VERBOSE']: cmd.append('-voff')
call(cmd)
else:
raise IOError('e> path to resampling executable is incorrect!')
elif tool=='spm':
fout = regseg.resample_spm(
fpet,
mridct['T1lbl'],
faff,
fimout = fgt1u,
matlab_eng = regdct['matlab_eng'],
intrp = 0.,
del_ref_uncmpr = True,
del_flo_uncmpr = True,
del_out_uncmpr = True,
)
#==================================================================
# Get the parcellation labels in the upsampled PET space
dprcl = imio.getnii(fgt1u, output='all')
prcl = dprcl['im']
#> path to parcellations in NIfTI format
prcl_pth = os.path.split(mridct['T1lbl'])
#---------------------------------------------------------------------------
#> get the parcellation specific for PVC based on the current parcellations
imgroi = prcl.copy(); imgroi[:] = 0
#> number of segments, without the background
nSeg = len(pvcroi)
#> create the image of numbered parcellations
for k in range(nSeg):
for m in pvcroi[k]:
imgroi[prcl==m] = k+1
#> save the PCV ROIs to a new NIfTI file
if store_rois:
froi = os.path.join(prcl_dir, prcl_pth[1].split('.nii')[0]+'_PVC-ROIs-inPET.nii.gz')
imio.array2nii(
imgroi,
dprcl['affine'],
froi,
trnsp = (dprcl['transpose'].index(0),
dprcl['transpose'].index(1),
dprcl['transpose'].index(2)),
flip = dprcl['flip'])
outdct['froi'] = froi
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
# run iterative Yang PVC
imgpvc, m_a = iyang(im, krnl, imgroi, Cnt, itr=itr)
#---------------------------------------------------------------------------
outdct['im'] = imgpvc
outdct['imroi'] = imgroi
outdct['faff'] = faff
if store_img:
fpvc = os.path.join( pvc_dir,
os.path.split(fpet)[1].split('.nii')[0]+'_PVC'+fcomment+'.nii.gz')
imio.array2nii( imgpvc[::-1,::-1,:], B, fpvc, descrip='pvc=iY')
outdct['fpet'] = fpvc
return outdct | python | def pvc_iyang(
petin,
mridct,
Cnt,
pvcroi,
krnl,
itr=5,
tool='niftyreg',
faff='',
outpath='',
fcomment='',
store_img=False,
store_rois=False,
):
''' Perform partial volume (PVC) correction of PET data (petin) using MRI data (mridct).
The PVC method uses iterative Yang method.
GPU based convolution is the key routine of the PVC.
Input:
-------
petin: either a dictionary containing image data, file name and affine transform,
or a string of the path to the NIfTI file of the PET data.
mridct: a dictionary of MRI data, including the T1w image, which can be given
in DICOM (field 'T1DCM') or NIfTI (field 'T1nii'). The T1w image data
is needed for co-registration to PET if affine is not given in the text
file with its path in faff.
Cnt: a dictionary of paths for third-party tools:
* dcm2niix: Cnt['DCM2NIIX']
* niftyreg, resample: Cnt['RESPATH']
* niftyreg, rigid-reg: Cnt['REGPATH']
* verbose mode on/off: Cnt['VERBOSE'] = True/False
pvcroi: list of regions (also a list) with number label to distinguish
the parcellations. The numbers correspond to the image values
of the parcellated T1w image. E.g.:
pvcroi = [
[36], # ROI 1 (single parcellation region)
[35], # ROI 2
[39, 40, 72, 73, 74], # ROI 3 (region consisting of multiple parcellation regions)
...
]
kernel: the point spread function (PSF) specific for the camera and the object.
It is given as a 3x17 matrix, a 17-element kernel for each dimension (x,y,z).
It is used in the GPU-based convolution using separable kernels.
outpath:path to the output of the resulting PVC images
faff: a text file of the affine transformations needed to get the MRI into PET space.
If not provided, it will be obtained from the performed rigid transformation.
For this the MR T1w image is required. If faff and T1w image are not provided,
it will results in exception/error.
fcomment:a string used in naming the produced files, helpful for distinguishing them.
tool: co-registration tool. By default it is NiftyReg, but SPM is also
possible (needs Matlab engine and more validation)
itr: number of iterations used by the PVC. 5-10 should be enough (5 default)
'''
# get all the input image properties
if isinstance(petin, dict):
im = imdic['im']
fpet = imdic['fpet']
B = imdic['affine']
elif isinstance(petin, basestring) and os.path.isfile(petin):
imdct = imio.getnii(petin, output='all')
im = imdct['im']
B = imdct['affine']
fpet = petin
if im.ndim!=3:
raise IndexError('Only 3D images are expected in this method of partial volume correction.')
# check if brain parcellations exist in NIfTI format
if not os.path.isfile(mridct['T1lbl']):
raise NameError('MissingLabels')
#> output dictionary
outdct = {}
# establish the output folder
if outpath=='':
prcl_dir = os.path.dirname(mridct['T1lbl'])
pvc_dir = os.path.join(os.path.dirname(fpet), 'PVC')
else:
prcl_dir = outpath
pvc_dir = os.path.join(os.path.dirname(fpet), 'PVC')
#> create folders
imio.create_dir(prcl_dir)
imio.create_dir(pvc_dir)
#==================================================================
#if affine transf. (faff) is given then take the T1 and resample it too.
if isinstance(faff, basestring) and not os.path.isfile(faff):
# faff is not given; get it by running the affine; get T1w to PET space
ft1w = imio.pick_t1w(mridct)
if tool=='spm':
regdct = regseg.coreg_spm(
fpet,
ft1w,
fcomment = fcomment,
outpath=os.path.join(outpath,'PET', 'positioning')
)
elif tool=='niftyreg':
regdct = regseg.affine_niftyreg(
fpet,
ft1w,
outpath=os.path.join(outpath,'PET', 'positioning'),
fcomment = fcomment,
executable = Cnt['REGPATH'],
omp = multiprocessing.cpu_count()/2,
rigOnly = True,
affDirect = False,
maxit=5,
speed=True,
pi=50, pv=50,
smof=0, smor=0,
rmsk=True,
fmsk=True,
rfwhm=15., #millilitres
rthrsh=0.05,
ffwhm = 15., #millilitres
fthrsh=0.05,
verbose=Cnt['VERBOSE']
)
faff = regdct['faff']
# resample the GIF T1/labels to upsampled PET
# file name of the parcellation (GIF-based) upsampled to PET
fgt1u = os.path.join(
prcl_dir,
os.path.basename(mridct['T1lbl']).split('.')[0]\
+'_registered_trimmed'+fcomment+'.nii.gz')
if tool=='niftyreg':
if os.path.isfile( Cnt['RESPATH'] ):
cmd = [Cnt['RESPATH'], '-ref', fpet, '-flo', mridct['T1lbl'],
'-trans', faff, '-res', fgt1u, '-inter', '0']
if not Cnt['VERBOSE']: cmd.append('-voff')
call(cmd)
else:
raise IOError('e> path to resampling executable is incorrect!')
elif tool=='spm':
fout = regseg.resample_spm(
fpet,
mridct['T1lbl'],
faff,
fimout = fgt1u,
matlab_eng = regdct['matlab_eng'],
intrp = 0.,
del_ref_uncmpr = True,
del_flo_uncmpr = True,
del_out_uncmpr = True,
)
#==================================================================
# Get the parcellation labels in the upsampled PET space
dprcl = imio.getnii(fgt1u, output='all')
prcl = dprcl['im']
#> path to parcellations in NIfTI format
prcl_pth = os.path.split(mridct['T1lbl'])
#---------------------------------------------------------------------------
#> get the parcellation specific for PVC based on the current parcellations
imgroi = prcl.copy(); imgroi[:] = 0
#> number of segments, without the background
nSeg = len(pvcroi)
#> create the image of numbered parcellations
for k in range(nSeg):
for m in pvcroi[k]:
imgroi[prcl==m] = k+1
#> save the PCV ROIs to a new NIfTI file
if store_rois:
froi = os.path.join(prcl_dir, prcl_pth[1].split('.nii')[0]+'_PVC-ROIs-inPET.nii.gz')
imio.array2nii(
imgroi,
dprcl['affine'],
froi,
trnsp = (dprcl['transpose'].index(0),
dprcl['transpose'].index(1),
dprcl['transpose'].index(2)),
flip = dprcl['flip'])
outdct['froi'] = froi
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
# run iterative Yang PVC
imgpvc, m_a = iyang(im, krnl, imgroi, Cnt, itr=itr)
#---------------------------------------------------------------------------
outdct['im'] = imgpvc
outdct['imroi'] = imgroi
outdct['faff'] = faff
if store_img:
fpvc = os.path.join( pvc_dir,
os.path.split(fpet)[1].split('.nii')[0]+'_PVC'+fcomment+'.nii.gz')
imio.array2nii( imgpvc[::-1,::-1,:], B, fpvc, descrip='pvc=iY')
outdct['fpet'] = fpvc
return outdct | [
"def",
"pvc_iyang",
"(",
"petin",
",",
"mridct",
",",
"Cnt",
",",
"pvcroi",
",",
"krnl",
",",
"itr",
"=",
"5",
",",
"tool",
"=",
"'niftyreg'",
",",
"faff",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"fcomment",
"=",
"''",
",",
"store_img",
"=",
"... | Perform partial volume (PVC) correction of PET data (petin) using MRI data (mridct).
The PVC method uses iterative Yang method.
GPU based convolution is the key routine of the PVC.
Input:
-------
petin: either a dictionary containing image data, file name and affine transform,
or a string of the path to the NIfTI file of the PET data.
mridct: a dictionary of MRI data, including the T1w image, which can be given
in DICOM (field 'T1DCM') or NIfTI (field 'T1nii'). The T1w image data
is needed for co-registration to PET if affine is not given in the text
file with its path in faff.
Cnt: a dictionary of paths for third-party tools:
* dcm2niix: Cnt['DCM2NIIX']
* niftyreg, resample: Cnt['RESPATH']
* niftyreg, rigid-reg: Cnt['REGPATH']
* verbose mode on/off: Cnt['VERBOSE'] = True/False
pvcroi: list of regions (also a list) with number label to distinguish
the parcellations. The numbers correspond to the image values
of the parcellated T1w image. E.g.:
pvcroi = [
[36], # ROI 1 (single parcellation region)
[35], # ROI 2
[39, 40, 72, 73, 74], # ROI 3 (region consisting of multiple parcellation regions)
...
]
kernel: the point spread function (PSF) specific for the camera and the object.
It is given as a 3x17 matrix, a 17-element kernel for each dimension (x,y,z).
It is used in the GPU-based convolution using separable kernels.
outpath:path to the output of the resulting PVC images
faff: a text file of the affine transformations needed to get the MRI into PET space.
If not provided, it will be obtained from the performed rigid transformation.
For this the MR T1w image is required. If faff and T1w image are not provided,
it will results in exception/error.
fcomment:a string used in naming the produced files, helpful for distinguishing them.
tool: co-registration tool. By default it is NiftyReg, but SPM is also
possible (needs Matlab engine and more validation)
itr: number of iterations used by the PVC. 5-10 should be enough (5 default) | [
"Perform",
"partial",
"volume",
"(",
"PVC",
")",
"correction",
"of",
"PET",
"data",
"(",
"petin",
")",
"using",
"MRI",
"data",
"(",
"mridct",
")",
".",
"The",
"PVC",
"method",
"uses",
"iterative",
"Yang",
"method",
".",
"GPU",
"based",
"convolution",
"is... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L460-L664 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | ct2mu | def ct2mu(im):
'''HU units to 511keV PET mu-values
https://link.springer.com/content/pdf/10.1007%2Fs00259-002-0796-3.pdf
C. Burger, et al., PET attenuation coefficients from CT images,
'''
# convert nans to -1024 for the HU values only
im[np.isnan(im)] = -1024
# constants
muwater = 0.096
mubone = 0.172
rhowater = 0.184
rhobone = 0.428
uim = np.zeros(im.shape, dtype=np.float32)
uim[im<=0] = muwater * ( 1+im[im<=0]*1e-3 )
uim[im> 0] = muwater+im[im>0]*(rhowater*(mubone-muwater)/(1e3*(rhobone-rhowater)))
# remove negative values
uim[uim<0] = 0
return uim | python | def ct2mu(im):
'''HU units to 511keV PET mu-values
https://link.springer.com/content/pdf/10.1007%2Fs00259-002-0796-3.pdf
C. Burger, et al., PET attenuation coefficients from CT images,
'''
# convert nans to -1024 for the HU values only
im[np.isnan(im)] = -1024
# constants
muwater = 0.096
mubone = 0.172
rhowater = 0.184
rhobone = 0.428
uim = np.zeros(im.shape, dtype=np.float32)
uim[im<=0] = muwater * ( 1+im[im<=0]*1e-3 )
uim[im> 0] = muwater+im[im>0]*(rhowater*(mubone-muwater)/(1e3*(rhobone-rhowater)))
# remove negative values
uim[uim<0] = 0
return uim | [
"def",
"ct2mu",
"(",
"im",
")",
":",
"# convert nans to -1024 for the HU values only",
"im",
"[",
"np",
".",
"isnan",
"(",
"im",
")",
"]",
"=",
"-",
"1024",
"# constants",
"muwater",
"=",
"0.096",
"mubone",
"=",
"0.172",
"rhowater",
"=",
"0.184",
"rhobone",
... | HU units to 511keV PET mu-values
https://link.springer.com/content/pdf/10.1007%2Fs00259-002-0796-3.pdf
C. Burger, et al., PET attenuation coefficients from CT images, | [
"HU",
"units",
"to",
"511keV",
"PET",
"mu",
"-",
"values",
"https",
":",
"//",
"link",
".",
"springer",
".",
"com",
"/",
"content",
"/",
"pdf",
"/",
"10",
".",
"1007%2Fs00259",
"-",
"002",
"-",
"0796",
"-",
"3",
".",
"pdf",
"C",
".",
"Burger",
"e... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L669-L687 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | centre_mass_img | def centre_mass_img(imdct):
''' Calculate the centre of mass of an image along each axes (x,y,z),
separately.
Arguments:
imdct - the image dictionary with the image and header data.
Output the list of the centre of mass for each axis.
'''
#> initialise centre of mass array
com = np.zeros(3, dtype=np.float32)
#> total image sum
imsum = np.sum(imdct['im'])
for ind_ax in [-1, -2, -3]:
#> list of axes
axs = range(imdct['im'].ndim)
del axs[ind_ax]
#> indexed centre of mass
icom = np.sum( np.sum(imdct['im'], axis=tuple(axs)) \
* np.arange(imdct['im'].shape[ind_ax]))/imsum
#> centre of mass in mm
com[abs(ind_ax)-1] = icom * imdct['hdr']['pixdim'][abs(ind_ax)]
return com | python | def centre_mass_img(imdct):
''' Calculate the centre of mass of an image along each axes (x,y,z),
separately.
Arguments:
imdct - the image dictionary with the image and header data.
Output the list of the centre of mass for each axis.
'''
#> initialise centre of mass array
com = np.zeros(3, dtype=np.float32)
#> total image sum
imsum = np.sum(imdct['im'])
for ind_ax in [-1, -2, -3]:
#> list of axes
axs = range(imdct['im'].ndim)
del axs[ind_ax]
#> indexed centre of mass
icom = np.sum( np.sum(imdct['im'], axis=tuple(axs)) \
* np.arange(imdct['im'].shape[ind_ax]))/imsum
#> centre of mass in mm
com[abs(ind_ax)-1] = icom * imdct['hdr']['pixdim'][abs(ind_ax)]
return com | [
"def",
"centre_mass_img",
"(",
"imdct",
")",
":",
"#> initialise centre of mass array",
"com",
"=",
"np",
".",
"zeros",
"(",
"3",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"#> total image sum",
"imsum",
"=",
"np",
".",
"sum",
"(",
"imdct",
"[",
"'im'",... | Calculate the centre of mass of an image along each axes (x,y,z),
separately.
Arguments:
imdct - the image dictionary with the image and header data.
Output the list of the centre of mass for each axis. | [
"Calculate",
"the",
"centre",
"of",
"mass",
"of",
"an",
"image",
"along",
"each",
"axes",
"(",
"x",
"y",
"z",
")",
"separately",
".",
"Arguments",
":",
"imdct",
"-",
"the",
"image",
"dictionary",
"with",
"the",
"image",
"and",
"header",
"data",
".",
"O... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L693-L716 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | nii_modify | def nii_modify(
nii,
fimout = '',
outpath = '',
fcomment = '',
voxel_range=[]):
''' Modify the NIfTI image given either as a file path or a dictionary,
obtained by nimpa.getnii(file_path).
'''
if isinstance(nii, basestring) and os.path.isfile(nii):
dctnii = imio.getnii(nii, output='all')
fnii = nii
if isinstance(nii, dict) and 'im' in nii:
dctnii = nii
if 'fim' in dctnii:
fnii = dctnii['fim']
#---------------------------------------------------------------------------
#> output path
if outpath=='' and fimout!='' and '/' in fimout:
opth = os.path.dirname(fimout)
if opth=='' and isinstance(fnii, basestring) and os.path.isfile(fnii):
opth = os.path.dirname(nii)
fimout = os.path.basename(fimout)
elif outpath=='' and isinstance(fnii, basestring) and os.path.isfile(fnii):
opth = os.path.dirname(fnii)
else:
opth = outpath
imio.create_dir(opth)
#> output floating and affine file names
if fimout=='':
if fcomment=='':
fcomment += '_nimpa-modified'
fout = os.path.join(
opth,
os.path.basename(fnii).split('.nii')[0]+fcomment+'.nii.gz')
else:
fout = os.path.join(
opth,
fimout.split('.')[0]+'.nii.gz')
#---------------------------------------------------------------------------
#> reduce the max value to 255
if voxel_range and len(voxel_range)==1:
im = voxel_range[0] * dctnii['im']/np.max(dctnii['im'])
elif voxel_range and len(voxel_range)==2:
#> normalise into range 0-1
im = (dctnii['im'] - np.min(dctnii['im'])) / np.ptp(dctnii['im'])
#> convert to voxel_range
im = voxel_range[0] + im*(voxel_range[1] - voxel_range[0])
else:
return None
#> output file name for the extra reference image
imio.array2nii(
im,
dctnii['affine'],
fout,
trnsp = (dctnii['transpose'].index(0),
dctnii['transpose'].index(1),
dctnii['transpose'].index(2)),
flip = dctnii['flip'])
return {'fim':fout, 'im':im, 'affine':dctnii['affine']} | python | def nii_modify(
nii,
fimout = '',
outpath = '',
fcomment = '',
voxel_range=[]):
''' Modify the NIfTI image given either as a file path or a dictionary,
obtained by nimpa.getnii(file_path).
'''
if isinstance(nii, basestring) and os.path.isfile(nii):
dctnii = imio.getnii(nii, output='all')
fnii = nii
if isinstance(nii, dict) and 'im' in nii:
dctnii = nii
if 'fim' in dctnii:
fnii = dctnii['fim']
#---------------------------------------------------------------------------
#> output path
if outpath=='' and fimout!='' and '/' in fimout:
opth = os.path.dirname(fimout)
if opth=='' and isinstance(fnii, basestring) and os.path.isfile(fnii):
opth = os.path.dirname(nii)
fimout = os.path.basename(fimout)
elif outpath=='' and isinstance(fnii, basestring) and os.path.isfile(fnii):
opth = os.path.dirname(fnii)
else:
opth = outpath
imio.create_dir(opth)
#> output floating and affine file names
if fimout=='':
if fcomment=='':
fcomment += '_nimpa-modified'
fout = os.path.join(
opth,
os.path.basename(fnii).split('.nii')[0]+fcomment+'.nii.gz')
else:
fout = os.path.join(
opth,
fimout.split('.')[0]+'.nii.gz')
#---------------------------------------------------------------------------
#> reduce the max value to 255
if voxel_range and len(voxel_range)==1:
im = voxel_range[0] * dctnii['im']/np.max(dctnii['im'])
elif voxel_range and len(voxel_range)==2:
#> normalise into range 0-1
im = (dctnii['im'] - np.min(dctnii['im'])) / np.ptp(dctnii['im'])
#> convert to voxel_range
im = voxel_range[0] + im*(voxel_range[1] - voxel_range[0])
else:
return None
#> output file name for the extra reference image
imio.array2nii(
im,
dctnii['affine'],
fout,
trnsp = (dctnii['transpose'].index(0),
dctnii['transpose'].index(1),
dctnii['transpose'].index(2)),
flip = dctnii['flip'])
return {'fim':fout, 'im':im, 'affine':dctnii['affine']} | [
"def",
"nii_modify",
"(",
"nii",
",",
"fimout",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"fcomment",
"=",
"''",
",",
"voxel_range",
"=",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"nii",
",",
"basestring",
")",
"and",
"os",
".",
"path",
".",
... | Modify the NIfTI image given either as a file path or a dictionary,
obtained by nimpa.getnii(file_path). | [
"Modify",
"the",
"NIfTI",
"image",
"given",
"either",
"as",
"a",
"file",
"path",
"or",
"a",
"dictionary",
"obtained",
"by",
"nimpa",
".",
"getnii",
"(",
"file_path",
")",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L721-L791 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | bias_field_correction | def bias_field_correction(
fmr,
fimout = '',
outpath = '',
fcomment = '_N4bias',
executable = '',
exe_options = [],
sitk_image_mask = True,
verbose = False,):
''' Correct for bias field in MR image(s) given in <fmr> as a string
(single file) or as a list of strings (multiple files).
Output dictionary with the bias corrected file names.
Options:
- fimout: The name (with path) of the output file. It's
ignored when multiple files are given as input. If
given for a single file name, the <outpath> and
<fcomment> options are ignored.
- outpath: Path to the output folder
- fcomment: A prefix comment to the file name
- executable: The path to the executable, overrides the above
choice of software; if 'sitk' is given instead
of the path, the Python module SimpleITK will be
used if it is available.
- exe_options: Options for the executable in the form of a list of
strings.
- sitk_image_mask: Image masking will be used if SimpleITK is
chosen.
'''
if executable=='sitk' and not 'SimpleITK' in sys.modules:
print 'e> if SimpleITK module is required for bias correction' \
+' it needs to be first installed.\n' \
+' Install the module by:\n' \
+' conda install -c https://conda.anaconda.org/simpleitk SimpleITK=1.2.0\n' \
+' or pip install SimpleITK'
return None
#---------------------------------------------------------------------------
# INPUT
#---------------------------------------------------------------------------
#> path to a single file
if isinstance(fmr, basestring) and os.path.isfile(fmr):
fins = [fmr]
#> list of file paths
elif isinstance(fmr, list) and all([os.path.isfile(f) for f in fmr]):
fins = fmr
print 'i> multiple input files => ignoring the single output file name.'
fimout = ''
#> path to a folder
elif isinstance(fmr, basestring) and os.path.isdir(fmr):
fins = [os.path.join(fmr, f) for f in os.listdir(fmr) if f.endswith(('.nii', '.nii.gz'))]
print 'i> multiple input files from input folder.'
fimout = ''
else:
raise ValueError('could not decode the input of floating images.')
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
# OUTPUT
#---------------------------------------------------------------------------
#> output path
if outpath=='' and fimout!='':
opth = os.path.dirname(fimout)
if opth=='':
opth = os.path.dirname(fmr)
fimout = os.path.join(opth, fimout)
n4opth = opth
fcomment = ''
elif outpath=='':
opth = os.path.dirname(fmr)
#> N4 bias correction specific folder
n4opth = os.path.join(opth, 'N4bias')
else:
opth = outpath
#> N4 bias correction specific folder
n4opth = os.path.join(opth, 'N4bias')
imio.create_dir(n4opth)
outdct = {}
#---------------------------------------------------------------------------
for fin in fins:
if verbose:
print 'i> input for bias correction:\n', fin
if fimout=='':
# split path
fspl = os.path.split(fin)
# N4 bias correction file output paths
fn4 = os.path.join( n4opth, fspl[1].split('.nii')[0]\
+ fcomment +'.nii.gz')
else:
fn4 = fimout
if not os.path.exists(fn4):
if executable=='sitk':
#==============================================
# SimpleITK Bias field correction for T1 and T2
#==============================================
#> initialise the corrector
corrector = sitk.N4BiasFieldCorrectionImageFilter()
# numberFilltingLevels = 4
# read input file
im = sitk.ReadImage(fin)
#> create a object specific mask
fmsk = os.path.join( n4opth, fspl[1].split('.nii')[0] +'_sitk_mask.nii.gz')
msk = sitk.OtsuThreshold(im, 0, 1, 200)
sitk.WriteImage(msk, fmsk)
#> cast to 32-bit float
im = sitk.Cast( im, sitk.sitkFloat32 )
#-------------------------------------------
print 'i> correcting bias field for', fin
n4out = corrector.Execute(im, msk)
sitk.WriteImage(n4out, fn4)
#-------------------------------------------
if sitk_image_mask:
if not 'fmsk' in outdct: outdct['fmsk'] = []
outdct['fmsk'].append(fmsk)
elif os.path.basename(executable)=='N4BiasFieldCorrection' \
and os.path.isfile(executable):
cmd = [executable, '-i', fin, '-o', fn4]
if verbose and os.path.basename(executable)=='N4BiasFieldCorrection':
cmd.extend(['-v', '1'])
cmd.extend(exe_options)
call(cmd)
if 'command' not in outdct:
outdct['command'] = []
outdct['command'].append(cmd)
elif os.path.isfile(executable):
cmd = [executable]
cmd.extend(exe_options)
call(cmd)
if 'command' not in outdct:
outdct['command'] = cmd
else:
print ' N4 bias corrected file seems already existing.'
#> output to dictionary
if not 'fim' in outdct: outdct['fim'] = []
outdct['fim'].append(fn4)
return outdct | python | def bias_field_correction(
fmr,
fimout = '',
outpath = '',
fcomment = '_N4bias',
executable = '',
exe_options = [],
sitk_image_mask = True,
verbose = False,):
''' Correct for bias field in MR image(s) given in <fmr> as a string
(single file) or as a list of strings (multiple files).
Output dictionary with the bias corrected file names.
Options:
- fimout: The name (with path) of the output file. It's
ignored when multiple files are given as input. If
given for a single file name, the <outpath> and
<fcomment> options are ignored.
- outpath: Path to the output folder
- fcomment: A prefix comment to the file name
- executable: The path to the executable, overrides the above
choice of software; if 'sitk' is given instead
of the path, the Python module SimpleITK will be
used if it is available.
- exe_options: Options for the executable in the form of a list of
strings.
- sitk_image_mask: Image masking will be used if SimpleITK is
chosen.
'''
if executable=='sitk' and not 'SimpleITK' in sys.modules:
print 'e> if SimpleITK module is required for bias correction' \
+' it needs to be first installed.\n' \
+' Install the module by:\n' \
+' conda install -c https://conda.anaconda.org/simpleitk SimpleITK=1.2.0\n' \
+' or pip install SimpleITK'
return None
#---------------------------------------------------------------------------
# INPUT
#---------------------------------------------------------------------------
#> path to a single file
if isinstance(fmr, basestring) and os.path.isfile(fmr):
fins = [fmr]
#> list of file paths
elif isinstance(fmr, list) and all([os.path.isfile(f) for f in fmr]):
fins = fmr
print 'i> multiple input files => ignoring the single output file name.'
fimout = ''
#> path to a folder
elif isinstance(fmr, basestring) and os.path.isdir(fmr):
fins = [os.path.join(fmr, f) for f in os.listdir(fmr) if f.endswith(('.nii', '.nii.gz'))]
print 'i> multiple input files from input folder.'
fimout = ''
else:
raise ValueError('could not decode the input of floating images.')
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
# OUTPUT
#---------------------------------------------------------------------------
#> output path
if outpath=='' and fimout!='':
opth = os.path.dirname(fimout)
if opth=='':
opth = os.path.dirname(fmr)
fimout = os.path.join(opth, fimout)
n4opth = opth
fcomment = ''
elif outpath=='':
opth = os.path.dirname(fmr)
#> N4 bias correction specific folder
n4opth = os.path.join(opth, 'N4bias')
else:
opth = outpath
#> N4 bias correction specific folder
n4opth = os.path.join(opth, 'N4bias')
imio.create_dir(n4opth)
outdct = {}
#---------------------------------------------------------------------------
for fin in fins:
if verbose:
print 'i> input for bias correction:\n', fin
if fimout=='':
# split path
fspl = os.path.split(fin)
# N4 bias correction file output paths
fn4 = os.path.join( n4opth, fspl[1].split('.nii')[0]\
+ fcomment +'.nii.gz')
else:
fn4 = fimout
if not os.path.exists(fn4):
if executable=='sitk':
#==============================================
# SimpleITK Bias field correction for T1 and T2
#==============================================
#> initialise the corrector
corrector = sitk.N4BiasFieldCorrectionImageFilter()
# numberFilltingLevels = 4
# read input file
im = sitk.ReadImage(fin)
#> create a object specific mask
fmsk = os.path.join( n4opth, fspl[1].split('.nii')[0] +'_sitk_mask.nii.gz')
msk = sitk.OtsuThreshold(im, 0, 1, 200)
sitk.WriteImage(msk, fmsk)
#> cast to 32-bit float
im = sitk.Cast( im, sitk.sitkFloat32 )
#-------------------------------------------
print 'i> correcting bias field for', fin
n4out = corrector.Execute(im, msk)
sitk.WriteImage(n4out, fn4)
#-------------------------------------------
if sitk_image_mask:
if not 'fmsk' in outdct: outdct['fmsk'] = []
outdct['fmsk'].append(fmsk)
elif os.path.basename(executable)=='N4BiasFieldCorrection' \
and os.path.isfile(executable):
cmd = [executable, '-i', fin, '-o', fn4]
if verbose and os.path.basename(executable)=='N4BiasFieldCorrection':
cmd.extend(['-v', '1'])
cmd.extend(exe_options)
call(cmd)
if 'command' not in outdct:
outdct['command'] = []
outdct['command'].append(cmd)
elif os.path.isfile(executable):
cmd = [executable]
cmd.extend(exe_options)
call(cmd)
if 'command' not in outdct:
outdct['command'] = cmd
else:
print ' N4 bias corrected file seems already existing.'
#> output to dictionary
if not 'fim' in outdct: outdct['fim'] = []
outdct['fim'].append(fn4)
return outdct | [
"def",
"bias_field_correction",
"(",
"fmr",
",",
"fimout",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"fcomment",
"=",
"'_N4bias'",
",",
"executable",
"=",
"''",
",",
"exe_options",
"=",
"[",
"]",
",",
"sitk_image_mask",
"=",
"True",
",",
"verbose",
"=",... | Correct for bias field in MR image(s) given in <fmr> as a string
(single file) or as a list of strings (multiple files).
Output dictionary with the bias corrected file names.
Options:
- fimout: The name (with path) of the output file. It's
ignored when multiple files are given as input. If
given for a single file name, the <outpath> and
<fcomment> options are ignored.
- outpath: Path to the output folder
- fcomment: A prefix comment to the file name
- executable: The path to the executable, overrides the above
choice of software; if 'sitk' is given instead
of the path, the Python module SimpleITK will be
used if it is available.
- exe_options: Options for the executable in the form of a list of
strings.
- sitk_image_mask: Image masking will be used if SimpleITK is
chosen. | [
"Correct",
"for",
"bias",
"field",
"in",
"MR",
"image",
"(",
"s",
")",
"given",
"in",
"<fmr",
">",
"as",
"a",
"string",
"(",
"single",
"file",
")",
"or",
"as",
"a",
"list",
"of",
"strings",
"(",
"multiple",
"files",
")",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L808-L983 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | roi_extraction | def roi_extraction(imdic, amyroi, datain, Cnt, use_stored=False):
'''
Extracting ROI values of upsampled PET. If not provided it will be upsampled.
imdic: dictionary of all image parts (image, path to file and affine transformation)
> fpet: file name for quantitative PET
> faff: file name and path to the affine (rigid) transformations, most likely for upscaled PET
amyroi: module with ROI definitions in numbers
datain: dictionary of all the input data
'''
fpet = imdic['fpet']
faff = imdic['faff']
im = imdic['im']
if Cnt['VERBOSE']: print 'i> extracting ROI values'
# split the labels path
lbpth = os.path.split(datain['T1lbl'])
# # MR T1w NIfTI
# if os.path.isfile(datain['T1nii']):
# ft1w = datain['T1nii']
# elif os.path.isfile(datain['T1bc']):
# ft1w = datain['T1nii']
# else:
# print 'e> no T1w NIfTI!'
# sys.exit()
prcl_dir = os.path.dirname(datain['T1lbl'])
dscrp = imio.getnii_descr(fpet)
impvc = False
if 'pvc' in dscrp.keys():
impvc = True
if Cnt['VERBOSE']: print 'i> the provided image is partial volume corrected.'
#------------------------------------------------------------------------------------------------------------
# next steps after having sorted out the upsampled input image and the rigid transformation for the T1w -> PET:
# Get the labels before resampling to PET space so that the regions can be separated (more difficult to separate after resampling)
if os.path.isfile(datain['T1lbl']):
nilb = nib.load(datain['T1lbl'])
A = nilb.get_sform()
imlb = nilb.get_data()
else:
print 'e> parcellation label image not present!'
sys.exit()
# ===============================================================
# get the segmentation/parcellation by creating an image for ROI extraction
# (still in the original T1 orientation)
roi_img = np.copy(imlb)
# sum of all voxel values in any given ROI
roisum = {}
# sum of the mask values <0,1> used for getting the mean value of any ROI
roimsk = {}
for k in amyroi.rois.keys():
roisum[k] = []
roimsk[k] = []
# extract the ROI values from PV corrected and uncorrected PET images
for k in amyroi.rois.keys():
roi_img[:] = 0
for i in amyroi.rois[k]:
roi_img[imlb==i] = 1.
# now save the image mask to nii file <froi1>
froi1 = os.path.join(prcl_dir, lbpth[1].split('.')[0][:8]+'_'+k+'.nii.gz')
nii_roi = nib.Nifti1Image(roi_img, A)
nii_roi.header['cal_max'] = 1.
nii_roi.header['cal_min'] = 0.
nib.save(nii_roi, froi1)
# file name for the resampled ROI to PET space
froi2 = os.path.join(prcl_dir, os.path.basename(datain['T1lbl']).split('.')[0]+ '_toPET_'+k+'.nii.gz')
if not use_stored and os.path.isfile( Cnt['RESPATH'] ):
cmd = [Cnt['RESPATH'],
'-ref', fpet,
'-flo', froi1,
'-trans', faff,
'-res', froi2]#,
#'-pad', '0']
if not Cnt['VERBOSE']: cmd.append('-voff')
call(cmd)
# get the resampled ROI mask image
rmsk = imio.getnii(froi2)
rmsk[rmsk>1.] = 1.
rmsk[rmsk<0.] = 0.
# erode the cerebral white matter region if no PVC image
if k=='wm' and not impvc:
if Cnt['VERBOSE']: print 'i> eroding white matter as PET image not partial volume corrected.'
nilb = nib.load(froi2)
B = nilb.get_sform()
tmp = ndi.filters.gaussian_filter(rmsk, imio.fwhm2sig(12,Cnt['VOXY']), mode='mirror')
rmsk = np.float32(tmp>0.85)
froi3 = os.path.join(prcl_dir, os.path.basename(datain['T1lbl']).split('.')[0]+ '_toPET_'+k+'_eroded.nii.gz')
savenii(rmsk, froi3, B, Cnt)
# ROI value and mask sums:
rvsum = np.sum(im*rmsk)
rmsum = np.sum(rmsk)
roisum[k].append( rvsum )
roimsk[k].append( rmsum )
if Cnt['VERBOSE']:
print ''
print '================================================================'
print 'i> ROI extracted:', k
print ' > value sum:', rvsum
print ' > # voxels :', rmsum
print '================================================================'
# --------------------------------------------------------------
return roisum, roimsk | python | def roi_extraction(imdic, amyroi, datain, Cnt, use_stored=False):
'''
Extracting ROI values of upsampled PET. If not provided it will be upsampled.
imdic: dictionary of all image parts (image, path to file and affine transformation)
> fpet: file name for quantitative PET
> faff: file name and path to the affine (rigid) transformations, most likely for upscaled PET
amyroi: module with ROI definitions in numbers
datain: dictionary of all the input data
'''
fpet = imdic['fpet']
faff = imdic['faff']
im = imdic['im']
if Cnt['VERBOSE']: print 'i> extracting ROI values'
# split the labels path
lbpth = os.path.split(datain['T1lbl'])
# # MR T1w NIfTI
# if os.path.isfile(datain['T1nii']):
# ft1w = datain['T1nii']
# elif os.path.isfile(datain['T1bc']):
# ft1w = datain['T1nii']
# else:
# print 'e> no T1w NIfTI!'
# sys.exit()
prcl_dir = os.path.dirname(datain['T1lbl'])
dscrp = imio.getnii_descr(fpet)
impvc = False
if 'pvc' in dscrp.keys():
impvc = True
if Cnt['VERBOSE']: print 'i> the provided image is partial volume corrected.'
#------------------------------------------------------------------------------------------------------------
# next steps after having sorted out the upsampled input image and the rigid transformation for the T1w -> PET:
# Get the labels before resampling to PET space so that the regions can be separated (more difficult to separate after resampling)
if os.path.isfile(datain['T1lbl']):
nilb = nib.load(datain['T1lbl'])
A = nilb.get_sform()
imlb = nilb.get_data()
else:
print 'e> parcellation label image not present!'
sys.exit()
# ===============================================================
# get the segmentation/parcellation by creating an image for ROI extraction
# (still in the original T1 orientation)
roi_img = np.copy(imlb)
# sum of all voxel values in any given ROI
roisum = {}
# sum of the mask values <0,1> used for getting the mean value of any ROI
roimsk = {}
for k in amyroi.rois.keys():
roisum[k] = []
roimsk[k] = []
# extract the ROI values from PV corrected and uncorrected PET images
for k in amyroi.rois.keys():
roi_img[:] = 0
for i in amyroi.rois[k]:
roi_img[imlb==i] = 1.
# now save the image mask to nii file <froi1>
froi1 = os.path.join(prcl_dir, lbpth[1].split('.')[0][:8]+'_'+k+'.nii.gz')
nii_roi = nib.Nifti1Image(roi_img, A)
nii_roi.header['cal_max'] = 1.
nii_roi.header['cal_min'] = 0.
nib.save(nii_roi, froi1)
# file name for the resampled ROI to PET space
froi2 = os.path.join(prcl_dir, os.path.basename(datain['T1lbl']).split('.')[0]+ '_toPET_'+k+'.nii.gz')
if not use_stored and os.path.isfile( Cnt['RESPATH'] ):
cmd = [Cnt['RESPATH'],
'-ref', fpet,
'-flo', froi1,
'-trans', faff,
'-res', froi2]#,
#'-pad', '0']
if not Cnt['VERBOSE']: cmd.append('-voff')
call(cmd)
# get the resampled ROI mask image
rmsk = imio.getnii(froi2)
rmsk[rmsk>1.] = 1.
rmsk[rmsk<0.] = 0.
# erode the cerebral white matter region if no PVC image
if k=='wm' and not impvc:
if Cnt['VERBOSE']: print 'i> eroding white matter as PET image not partial volume corrected.'
nilb = nib.load(froi2)
B = nilb.get_sform()
tmp = ndi.filters.gaussian_filter(rmsk, imio.fwhm2sig(12,Cnt['VOXY']), mode='mirror')
rmsk = np.float32(tmp>0.85)
froi3 = os.path.join(prcl_dir, os.path.basename(datain['T1lbl']).split('.')[0]+ '_toPET_'+k+'_eroded.nii.gz')
savenii(rmsk, froi3, B, Cnt)
# ROI value and mask sums:
rvsum = np.sum(im*rmsk)
rmsum = np.sum(rmsk)
roisum[k].append( rvsum )
roimsk[k].append( rmsum )
if Cnt['VERBOSE']:
print ''
print '================================================================'
print 'i> ROI extracted:', k
print ' > value sum:', rvsum
print ' > # voxels :', rmsum
print '================================================================'
# --------------------------------------------------------------
return roisum, roimsk | [
"def",
"roi_extraction",
"(",
"imdic",
",",
"amyroi",
",",
"datain",
",",
"Cnt",
",",
"use_stored",
"=",
"False",
")",
":",
"fpet",
"=",
"imdic",
"[",
"'fpet'",
"]",
"faff",
"=",
"imdic",
"[",
"'faff'",
"]",
"im",
"=",
"imdic",
"[",
"'im'",
"]",
"i... | Extracting ROI values of upsampled PET. If not provided it will be upsampled.
imdic: dictionary of all image parts (image, path to file and affine transformation)
> fpet: file name for quantitative PET
> faff: file name and path to the affine (rigid) transformations, most likely for upscaled PET
amyroi: module with ROI definitions in numbers
datain: dictionary of all the input data | [
"Extracting",
"ROI",
"values",
"of",
"upsampled",
"PET",
".",
"If",
"not",
"provided",
"it",
"will",
"be",
"upsampled",
".",
"imdic",
":",
"dictionary",
"of",
"all",
"image",
"parts",
"(",
"image",
"path",
"to",
"file",
"and",
"affine",
"transformation",
"... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L1143-L1254 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | getnii | def getnii(fim, nan_replace=None, output='image'):
'''Get PET image from NIfTI file.
fim: input file name for the nifty image
nan_replace: the value to be used for replacing the NaNs in the image.
by default no change (None).
output: option for choosing output: image, affine matrix or a dictionary with all info.
----------
Return:
'image': outputs just an image (4D or 3D)
'affine': outputs just the affine matrix
'all': outputs all as a dictionary
'''
import numbers
nim = nib.load(fim)
dim = nim.header.get('dim')
dimno = dim[0]
if output=='image' or output=='all':
imr = nim.get_data()
# replace NaNs if requested
if isinstance(nan_replace, numbers.Number): imr[np.isnan(imr)]
imr = np.squeeze(imr)
if dimno!=imr.ndim and dimno==4:
dimno = imr.ndim
#> get orientations from the affine
ornt = nib.orientations.axcodes2ornt(nib.aff2axcodes(nim.affine))
trnsp = tuple(np.int8(ornt[::-1,0]))
flip = tuple(np.int8(ornt[:,1]))
#> flip y-axis and z-axis and then transpose. Depends if dynamic (4 dimensions) or static (3 dimensions)
if dimno==4:
imr = np.transpose(imr[::-flip[0],::-flip[1],::-flip[2],:], (3,)+trnsp)
elif dimno==3:
imr = np.transpose(imr[::-flip[0],::-flip[1],::-flip[2]], trnsp)
if output=='affine' or output=='all':
# A = nim.get_sform()
# if not A[:3,:3].any():
# A = nim.get_qform()
A = nim.affine
if output=='all':
out = { 'im':imr,
'affine':A,
'fim':fim,
'dtype':nim.get_data_dtype(),
'shape':imr.shape,
'hdr':nim.header,
'transpose':trnsp,
'flip':flip}
elif output=='image':
out = imr
elif output=='affine':
out = A
else:
raise NameError('Unrecognised output request!')
return out | python | def getnii(fim, nan_replace=None, output='image'):
'''Get PET image from NIfTI file.
fim: input file name for the nifty image
nan_replace: the value to be used for replacing the NaNs in the image.
by default no change (None).
output: option for choosing output: image, affine matrix or a dictionary with all info.
----------
Return:
'image': outputs just an image (4D or 3D)
'affine': outputs just the affine matrix
'all': outputs all as a dictionary
'''
import numbers
nim = nib.load(fim)
dim = nim.header.get('dim')
dimno = dim[0]
if output=='image' or output=='all':
imr = nim.get_data()
# replace NaNs if requested
if isinstance(nan_replace, numbers.Number): imr[np.isnan(imr)]
imr = np.squeeze(imr)
if dimno!=imr.ndim and dimno==4:
dimno = imr.ndim
#> get orientations from the affine
ornt = nib.orientations.axcodes2ornt(nib.aff2axcodes(nim.affine))
trnsp = tuple(np.int8(ornt[::-1,0]))
flip = tuple(np.int8(ornt[:,1]))
#> flip y-axis and z-axis and then transpose. Depends if dynamic (4 dimensions) or static (3 dimensions)
if dimno==4:
imr = np.transpose(imr[::-flip[0],::-flip[1],::-flip[2],:], (3,)+trnsp)
elif dimno==3:
imr = np.transpose(imr[::-flip[0],::-flip[1],::-flip[2]], trnsp)
if output=='affine' or output=='all':
# A = nim.get_sform()
# if not A[:3,:3].any():
# A = nim.get_qform()
A = nim.affine
if output=='all':
out = { 'im':imr,
'affine':A,
'fim':fim,
'dtype':nim.get_data_dtype(),
'shape':imr.shape,
'hdr':nim.header,
'transpose':trnsp,
'flip':flip}
elif output=='image':
out = imr
elif output=='affine':
out = A
else:
raise NameError('Unrecognised output request!')
return out | [
"def",
"getnii",
"(",
"fim",
",",
"nan_replace",
"=",
"None",
",",
"output",
"=",
"'image'",
")",
":",
"import",
"numbers",
"nim",
"=",
"nib",
".",
"load",
"(",
"fim",
")",
"dim",
"=",
"nim",
".",
"header",
".",
"get",
"(",
"'dim'",
")",
"dimno",
... | Get PET image from NIfTI file.
fim: input file name for the nifty image
nan_replace: the value to be used for replacing the NaNs in the image.
by default no change (None).
output: option for choosing output: image, affine matrix or a dictionary with all info.
----------
Return:
'image': outputs just an image (4D or 3D)
'affine': outputs just the affine matrix
'all': outputs all as a dictionary | [
"Get",
"PET",
"image",
"from",
"NIfTI",
"file",
".",
"fim",
":",
"input",
"file",
"name",
"for",
"the",
"nifty",
"image",
"nan_replace",
":",
"the",
"value",
"to",
"be",
"used",
"for",
"replacing",
"the",
"NaNs",
"in",
"the",
"image",
".",
"by",
"defau... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L47-L109 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | getnii_descr | def getnii_descr(fim):
'''
Extracts the custom description header field to dictionary
'''
nim = nib.load(fim)
hdr = nim.header
rcnlst = hdr['descrip'].item().split(';')
rcndic = {}
if rcnlst[0]=='':
# print 'w> no description in the NIfTI header'
return rcndic
for ci in range(len(rcnlst)):
tmp = rcnlst[ci].split('=')
rcndic[tmp[0]] = tmp[1]
return rcndic | python | def getnii_descr(fim):
'''
Extracts the custom description header field to dictionary
'''
nim = nib.load(fim)
hdr = nim.header
rcnlst = hdr['descrip'].item().split(';')
rcndic = {}
if rcnlst[0]=='':
# print 'w> no description in the NIfTI header'
return rcndic
for ci in range(len(rcnlst)):
tmp = rcnlst[ci].split('=')
rcndic[tmp[0]] = tmp[1]
return rcndic | [
"def",
"getnii_descr",
"(",
"fim",
")",
":",
"nim",
"=",
"nib",
".",
"load",
"(",
"fim",
")",
"hdr",
"=",
"nim",
".",
"header",
"rcnlst",
"=",
"hdr",
"[",
"'descrip'",
"]",
".",
"item",
"(",
")",
".",
"split",
"(",
"';'",
")",
"rcndic",
"=",
"{... | Extracts the custom description header field to dictionary | [
"Extracts",
"the",
"custom",
"description",
"header",
"field",
"to",
"dictionary"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L111-L127 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | array2nii | def array2nii(im, A, fnii, descrip='', trnsp=(), flip=(), storage_as=[]):
'''Store the numpy array 'im' to a NIfTI file 'fnii'.
----
Arguments:
'im': image to be stored in NIfTI
'A': affine transformation
'fnii': output NIfTI file name.
'descrip': the description given to the file
'trsnp': transpose/permute the dimensions.
In NIfTI it has to be in this order: [x,y,z,t,...])
'flip': flip tupple for flipping the direction of x,y,z axes.
(1: no flip, -1: flip)
'storage_as': uses the flip and displacement as given by the following
NifTI dictionary, obtained using
nimpa.getnii(filepath, output='all').
'''
if not len(trnsp) in [0,3,4] and not len(flip) in [0,3]:
raise ValueError('e> number of flip and/or transpose elements is incorrect.')
#---------------------------------------------------------------------------
#> TRANSLATIONS and FLIPS
#> get the same geometry as the input NIfTI file in the form of dictionary,
#>>as obtained from getnii(..., output='all')
#> permute the axis order in the image array
if isinstance(storage_as, dict) and 'transpose' in storage_as \
and 'flip' in storage_as:
trnsp = (storage_as['transpose'].index(0),
storage_as['transpose'].index(1),
storage_as['transpose'].index(2))
flip = storage_as['flip']
if trnsp==():
im = im.transpose()
#> check if the image is 4D (dynamic) and modify as needed
elif len(trnsp)==3 and im.ndim==4:
trnsp = tuple([t+1 for t in trnsp] + [0])
im = im.transpose(trnsp)
else:
im = im.transpose(trnsp)
#> perform flip of x,y,z axes after transposition into proper NIfTI order
if flip!=() and len(flip)==3:
im = im[::-flip[0], ::-flip[1], ::-flip[2], ...]
#---------------------------------------------------------------------------
nii = nib.Nifti1Image(im, A)
hdr = nii.header
hdr.set_sform(None, code='scanner')
hdr['cal_max'] = np.max(im) #np.percentile(im, 90) #
hdr['cal_min'] = np.min(im)
hdr['descrip'] = descrip
nib.save(nii, fnii) | python | def array2nii(im, A, fnii, descrip='', trnsp=(), flip=(), storage_as=[]):
'''Store the numpy array 'im' to a NIfTI file 'fnii'.
----
Arguments:
'im': image to be stored in NIfTI
'A': affine transformation
'fnii': output NIfTI file name.
'descrip': the description given to the file
'trsnp': transpose/permute the dimensions.
In NIfTI it has to be in this order: [x,y,z,t,...])
'flip': flip tupple for flipping the direction of x,y,z axes.
(1: no flip, -1: flip)
'storage_as': uses the flip and displacement as given by the following
NifTI dictionary, obtained using
nimpa.getnii(filepath, output='all').
'''
if not len(trnsp) in [0,3,4] and not len(flip) in [0,3]:
raise ValueError('e> number of flip and/or transpose elements is incorrect.')
#---------------------------------------------------------------------------
#> TRANSLATIONS and FLIPS
#> get the same geometry as the input NIfTI file in the form of dictionary,
#>>as obtained from getnii(..., output='all')
#> permute the axis order in the image array
if isinstance(storage_as, dict) and 'transpose' in storage_as \
and 'flip' in storage_as:
trnsp = (storage_as['transpose'].index(0),
storage_as['transpose'].index(1),
storage_as['transpose'].index(2))
flip = storage_as['flip']
if trnsp==():
im = im.transpose()
#> check if the image is 4D (dynamic) and modify as needed
elif len(trnsp)==3 and im.ndim==4:
trnsp = tuple([t+1 for t in trnsp] + [0])
im = im.transpose(trnsp)
else:
im = im.transpose(trnsp)
#> perform flip of x,y,z axes after transposition into proper NIfTI order
if flip!=() and len(flip)==3:
im = im[::-flip[0], ::-flip[1], ::-flip[2], ...]
#---------------------------------------------------------------------------
nii = nib.Nifti1Image(im, A)
hdr = nii.header
hdr.set_sform(None, code='scanner')
hdr['cal_max'] = np.max(im) #np.percentile(im, 90) #
hdr['cal_min'] = np.min(im)
hdr['descrip'] = descrip
nib.save(nii, fnii) | [
"def",
"array2nii",
"(",
"im",
",",
"A",
",",
"fnii",
",",
"descrip",
"=",
"''",
",",
"trnsp",
"=",
"(",
")",
",",
"flip",
"=",
"(",
")",
",",
"storage_as",
"=",
"[",
"]",
")",
":",
"if",
"not",
"len",
"(",
"trnsp",
")",
"in",
"[",
"0",
","... | Store the numpy array 'im' to a NIfTI file 'fnii'.
----
Arguments:
'im': image to be stored in NIfTI
'A': affine transformation
'fnii': output NIfTI file name.
'descrip': the description given to the file
'trsnp': transpose/permute the dimensions.
In NIfTI it has to be in this order: [x,y,z,t,...])
'flip': flip tupple for flipping the direction of x,y,z axes.
(1: no flip, -1: flip)
'storage_as': uses the flip and displacement as given by the following
NifTI dictionary, obtained using
nimpa.getnii(filepath, output='all'). | [
"Store",
"the",
"numpy",
"array",
"im",
"to",
"a",
"NIfTI",
"file",
"fnii",
".",
"----",
"Arguments",
":",
"im",
":",
"image",
"to",
"be",
"stored",
"in",
"NIfTI",
"A",
":",
"affine",
"transformation",
"fnii",
":",
"output",
"NIfTI",
"file",
"name",
".... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L130-L187 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | orientnii | def orientnii(imfile):
'''Get the orientation from NIfTI sform. Not fully functional yet.'''
strorient = ['L-R', 'S-I', 'A-P']
niiorient = []
niixyz = np.zeros(3,dtype=np.int8)
if os.path.isfile(imfile):
nim = nib.load(imfile)
pct = nim.get_data()
A = nim.get_sform()
for i in range(3):
niixyz[i] = np.argmax(abs(A[i,:-1]))
niiorient.append( strorient[ niixyz[i] ] )
print niiorient | python | def orientnii(imfile):
'''Get the orientation from NIfTI sform. Not fully functional yet.'''
strorient = ['L-R', 'S-I', 'A-P']
niiorient = []
niixyz = np.zeros(3,dtype=np.int8)
if os.path.isfile(imfile):
nim = nib.load(imfile)
pct = nim.get_data()
A = nim.get_sform()
for i in range(3):
niixyz[i] = np.argmax(abs(A[i,:-1]))
niiorient.append( strorient[ niixyz[i] ] )
print niiorient | [
"def",
"orientnii",
"(",
"imfile",
")",
":",
"strorient",
"=",
"[",
"'L-R'",
",",
"'S-I'",
",",
"'A-P'",
"]",
"niiorient",
"=",
"[",
"]",
"niixyz",
"=",
"np",
".",
"zeros",
"(",
"3",
",",
"dtype",
"=",
"np",
".",
"int8",
")",
"if",
"os",
".",
"... | Get the orientation from NIfTI sform. Not fully functional yet. | [
"Get",
"the",
"orientation",
"from",
"NIfTI",
"sform",
".",
"Not",
"fully",
"functional",
"yet",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L191-L203 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | nii_ugzip | def nii_ugzip(imfile, outpath=''):
'''Uncompress *.gz file'''
import gzip
with gzip.open(imfile, 'rb') as f:
s = f.read()
# Now store the uncompressed data
if outpath=='':
fout = imfile[:-3]
else:
fout = os.path.join(outpath, os.path.basename(imfile)[:-3])
# store uncompressed file data from 's' variable
with open(fout, 'wb') as f:
f.write(s)
return fout | python | def nii_ugzip(imfile, outpath=''):
'''Uncompress *.gz file'''
import gzip
with gzip.open(imfile, 'rb') as f:
s = f.read()
# Now store the uncompressed data
if outpath=='':
fout = imfile[:-3]
else:
fout = os.path.join(outpath, os.path.basename(imfile)[:-3])
# store uncompressed file data from 's' variable
with open(fout, 'wb') as f:
f.write(s)
return fout | [
"def",
"nii_ugzip",
"(",
"imfile",
",",
"outpath",
"=",
"''",
")",
":",
"import",
"gzip",
"with",
"gzip",
".",
"open",
"(",
"imfile",
",",
"'rb'",
")",
"as",
"f",
":",
"s",
"=",
"f",
".",
"read",
"(",
")",
"# Now store the uncompressed data",
"if",
"... | Uncompress *.gz file | [
"Uncompress",
"*",
".",
"gz",
"file"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L205-L218 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | nii_gzip | def nii_gzip(imfile, outpath=''):
'''Compress *.gz file'''
import gzip
with open(imfile, 'rb') as f:
d = f.read()
# Now store the compressed data
if outpath=='':
fout = imfile+'.gz'
else:
fout = os.path.join(outpath, os.path.basename(imfile)+'.gz')
# store compressed file data from 'd' variable
with gzip.open(fout, 'wb') as f:
f.write(d)
return fout | python | def nii_gzip(imfile, outpath=''):
'''Compress *.gz file'''
import gzip
with open(imfile, 'rb') as f:
d = f.read()
# Now store the compressed data
if outpath=='':
fout = imfile+'.gz'
else:
fout = os.path.join(outpath, os.path.basename(imfile)+'.gz')
# store compressed file data from 'd' variable
with gzip.open(fout, 'wb') as f:
f.write(d)
return fout | [
"def",
"nii_gzip",
"(",
"imfile",
",",
"outpath",
"=",
"''",
")",
":",
"import",
"gzip",
"with",
"open",
"(",
"imfile",
",",
"'rb'",
")",
"as",
"f",
":",
"d",
"=",
"f",
".",
"read",
"(",
")",
"# Now store the compressed data",
"if",
"outpath",
"==",
... | Compress *.gz file | [
"Compress",
"*",
".",
"gz",
"file"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L220-L233 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | pick_t1w | def pick_t1w(mri):
''' Pick the MR T1w from the dictionary for MR->PET registration.
'''
if isinstance(mri, dict):
# check if NIfTI file is given
if 'T1N4' in mri and os.path.isfile(mri['T1N4']):
ft1w = mri['T1N4']
# or another bias corrected
elif 'T1bc' in mri and os.path.isfile(mri['T1bc']):
ft1w = mri['T1bc']
elif 'T1nii' in mri and os.path.isfile(mri['T1nii']):
ft1w = mri['T1nii']
elif 'T1DCM' in mri and os.path.exists(mri['MRT1W']):
# create file name for the converted NIfTI image
fnii = 'converted'
call( [rs.DCM2NIIX, '-f', fnii, mri['T1nii'] ] )
ft1nii = glob.glob( os.path.join(mri['T1nii'], '*converted*.nii*') )
ft1w = ft1nii[0]
else:
print 'e> disaster: could not find a T1w image!'
return None
else:
('e> no correct input found for the T1w image')
return None
return ft1w | python | def pick_t1w(mri):
''' Pick the MR T1w from the dictionary for MR->PET registration.
'''
if isinstance(mri, dict):
# check if NIfTI file is given
if 'T1N4' in mri and os.path.isfile(mri['T1N4']):
ft1w = mri['T1N4']
# or another bias corrected
elif 'T1bc' in mri and os.path.isfile(mri['T1bc']):
ft1w = mri['T1bc']
elif 'T1nii' in mri and os.path.isfile(mri['T1nii']):
ft1w = mri['T1nii']
elif 'T1DCM' in mri and os.path.exists(mri['MRT1W']):
# create file name for the converted NIfTI image
fnii = 'converted'
call( [rs.DCM2NIIX, '-f', fnii, mri['T1nii'] ] )
ft1nii = glob.glob( os.path.join(mri['T1nii'], '*converted*.nii*') )
ft1w = ft1nii[0]
else:
print 'e> disaster: could not find a T1w image!'
return None
else:
('e> no correct input found for the T1w image')
return None
return ft1w | [
"def",
"pick_t1w",
"(",
"mri",
")",
":",
"if",
"isinstance",
"(",
"mri",
",",
"dict",
")",
":",
"# check if NIfTI file is given",
"if",
"'T1N4'",
"in",
"mri",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"mri",
"[",
"'T1N4'",
"]",
")",
":",
"ft1w",
... | Pick the MR T1w from the dictionary for MR->PET registration. | [
"Pick",
"the",
"MR",
"T1w",
"from",
"the",
"dictionary",
"for",
"MR",
"-",
">",
"PET",
"registration",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L237-L264 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | dcminfo | def dcminfo(dcmvar, verbose=True):
''' Get basic info about the DICOM file/header.
'''
if isinstance(dcmvar, basestring):
if verbose:
print 'i> provided DICOM file:', dcmvar
dhdr = dcm.dcmread(dcmvar)
elif isinstance(dcmvar, dict):
dhdr = dcmvar
elif isinstance(dcmvar, dcm.dataset.FileDataset):
dhdr = dcmvar
dtype = dhdr[0x08, 0x08].value
if verbose:
print ' Image Type:', dtype
#-------------------------------------------
#> scanner ID
scanner_vendor = 'unknown'
if [0x008, 0x070] in dhdr:
scanner_vendor = dhdr[0x008, 0x070].value
scanner_model = 'unknown'
if [0x008, 0x1090] in dhdr:
scanner_model = dhdr[0x008, 0x1090].value
scanner_id = 'other'
if any(s in scanner_model for s in ['mMR', 'Biograph']) and 'siemens' in scanner_vendor.lower():
scanner_id = 'mmr'
#-------------------------------------------
#> CSA type (mMR)
csatype = ''
if [0x29, 0x1108] in dhdr:
csatype = dhdr[0x29, 0x1108].value
if verbose:
print ' CSA Data Type:', csatype
#> DICOM comment or on MR parameters
cmmnt = ''
if [0x20, 0x4000] in dhdr:
cmmnt = dhdr[0x0020, 0x4000].value
if verbose:
print ' Comments:', cmmnt
#> MR parameters (echo time, etc)
TR = 0
TE = 0
if [0x18, 0x80] in dhdr:
TR = float(dhdr[0x18, 0x80].value)
if verbose: print ' TR:', TR
if [0x18, 0x81] in dhdr:
TE = float(dhdr[0x18, 0x81].value)
if verbose: print ' TE:', TE
#> check if it is norm file
if any('PET_NORM' in s for s in dtype) or cmmnt=='PET Normalization data' or csatype=='MRPETNORM':
out = ['raw', 'norm', scanner_id]
elif any('PET_LISTMODE' in s for s in dtype) or cmmnt=='Listmode' or csatype=='MRPETLM_LARGE':
out = ['raw', 'list', scanner_id]
elif any('MRPET_UMAP3D' in s for s in dtype) or cmmnt=='MR based umap':
out = ['raw', 'mumap', 'ute', 'mr', scanner_id]
elif TR>400 and TR<2500 and TE<20:
out = ['mr', 't1', scanner_id]
elif TR>2500 and TE>50:
out = ['mr', 't2', scanner_id]
#> UTE's two sequences: UTE2
elif TR<50 and TE<20 and TE>1:
out = ['mr', 'ute', 'ute2', scanner_id]
#> UTE1
elif TR<50 and TE<20 and TE<0.1 and TR>0 and TE>0:
out = ['mr', 'ute', 'ute1', scanner_id]
#> physio data
elif 'PET_PHYSIO' in dtype or 'physio' in cmmnt.lower():
out = ['raw', 'physio', scanner_id]
else:
out = ['unknown', cmmnt]
return out | python | def dcminfo(dcmvar, verbose=True):
''' Get basic info about the DICOM file/header.
'''
if isinstance(dcmvar, basestring):
if verbose:
print 'i> provided DICOM file:', dcmvar
dhdr = dcm.dcmread(dcmvar)
elif isinstance(dcmvar, dict):
dhdr = dcmvar
elif isinstance(dcmvar, dcm.dataset.FileDataset):
dhdr = dcmvar
dtype = dhdr[0x08, 0x08].value
if verbose:
print ' Image Type:', dtype
#-------------------------------------------
#> scanner ID
scanner_vendor = 'unknown'
if [0x008, 0x070] in dhdr:
scanner_vendor = dhdr[0x008, 0x070].value
scanner_model = 'unknown'
if [0x008, 0x1090] in dhdr:
scanner_model = dhdr[0x008, 0x1090].value
scanner_id = 'other'
if any(s in scanner_model for s in ['mMR', 'Biograph']) and 'siemens' in scanner_vendor.lower():
scanner_id = 'mmr'
#-------------------------------------------
#> CSA type (mMR)
csatype = ''
if [0x29, 0x1108] in dhdr:
csatype = dhdr[0x29, 0x1108].value
if verbose:
print ' CSA Data Type:', csatype
#> DICOM comment or on MR parameters
cmmnt = ''
if [0x20, 0x4000] in dhdr:
cmmnt = dhdr[0x0020, 0x4000].value
if verbose:
print ' Comments:', cmmnt
#> MR parameters (echo time, etc)
TR = 0
TE = 0
if [0x18, 0x80] in dhdr:
TR = float(dhdr[0x18, 0x80].value)
if verbose: print ' TR:', TR
if [0x18, 0x81] in dhdr:
TE = float(dhdr[0x18, 0x81].value)
if verbose: print ' TE:', TE
#> check if it is norm file
if any('PET_NORM' in s for s in dtype) or cmmnt=='PET Normalization data' or csatype=='MRPETNORM':
out = ['raw', 'norm', scanner_id]
elif any('PET_LISTMODE' in s for s in dtype) or cmmnt=='Listmode' or csatype=='MRPETLM_LARGE':
out = ['raw', 'list', scanner_id]
elif any('MRPET_UMAP3D' in s for s in dtype) or cmmnt=='MR based umap':
out = ['raw', 'mumap', 'ute', 'mr', scanner_id]
elif TR>400 and TR<2500 and TE<20:
out = ['mr', 't1', scanner_id]
elif TR>2500 and TE>50:
out = ['mr', 't2', scanner_id]
#> UTE's two sequences: UTE2
elif TR<50 and TE<20 and TE>1:
out = ['mr', 'ute', 'ute2', scanner_id]
#> UTE1
elif TR<50 and TE<20 and TE<0.1 and TR>0 and TE>0:
out = ['mr', 'ute', 'ute1', scanner_id]
#> physio data
elif 'PET_PHYSIO' in dtype or 'physio' in cmmnt.lower():
out = ['raw', 'physio', scanner_id]
else:
out = ['unknown', cmmnt]
return out | [
"def",
"dcminfo",
"(",
"dcmvar",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"dcmvar",
",",
"basestring",
")",
":",
"if",
"verbose",
":",
"print",
"'i> provided DICOM file:'",
",",
"dcmvar",
"dhdr",
"=",
"dcm",
".",
"dcmread",
"(",
"d... | Get basic info about the DICOM file/header. | [
"Get",
"basic",
"info",
"about",
"the",
"DICOM",
"file",
"/",
"header",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L267-L355 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | list_dcm_datain | def list_dcm_datain(datain):
''' List all DICOM file paths in the datain dictionary of input data.
'''
if not isinstance(datain, dict):
raise ValueError('The input is not a dictionary!')
dcmlst = []
# list of mu-map DICOM files
if 'mumapDCM' in datain:
dcmump = os.listdir(datain['mumapDCM'])
# accept only *.dcm extensions
dcmump = [os.path.join(datain['mumapDCM'],d) for d in dcmump if d.endswith(dcmext)]
dcmlst += dcmump
if 'T1DCM' in datain:
dcmt1 = os.listdir(datain['T1DCM'])
# accept only *.dcm extensions
dcmt1 = [os.path.join(datain['T1DCM'],d) for d in dcmt1 if d.endswith(dcmext)]
dcmlst += dcmt1
if 'T2DCM' in datain:
dcmt2 = os.listdir(datain['T2DCM'])
# accept only *.dcm extensions
dcmt2 = [os.path.join(datain['T2DCM'],d) for d in dcmt2 if d.endswith(dcmext)]
dcmlst += dcmt2
if 'UTE1' in datain:
dcmute1 = os.listdir(datain['UTE1'])
# accept only *.dcm extensions
dcmute1 = [os.path.join(datain['UTE1'],d) for d in dcmute1 if d.endswith(dcmext)]
dcmlst += dcmute1
if 'UTE2' in datain:
dcmute2 = os.listdir(datain['UTE2'])
# accept only *.dcm extensions
dcmute2 = [os.path.join(datain['UTE2'],d) for d in dcmute2 if d.endswith(dcmext)]
dcmlst += dcmute2
#-list-mode data dcm
if 'lm_dcm' in datain:
dcmlst += [datain['lm_dcm']]
if 'lm_ima' in datain:
dcmlst += [datain['lm_ima']]
#-norm
if 'nrm_dcm' in datain:
dcmlst += [datain['nrm_dcm']]
if 'nrm_ima' in datain:
dcmlst += [datain['nrm_ima']]
return dcmlst | python | def list_dcm_datain(datain):
''' List all DICOM file paths in the datain dictionary of input data.
'''
if not isinstance(datain, dict):
raise ValueError('The input is not a dictionary!')
dcmlst = []
# list of mu-map DICOM files
if 'mumapDCM' in datain:
dcmump = os.listdir(datain['mumapDCM'])
# accept only *.dcm extensions
dcmump = [os.path.join(datain['mumapDCM'],d) for d in dcmump if d.endswith(dcmext)]
dcmlst += dcmump
if 'T1DCM' in datain:
dcmt1 = os.listdir(datain['T1DCM'])
# accept only *.dcm extensions
dcmt1 = [os.path.join(datain['T1DCM'],d) for d in dcmt1 if d.endswith(dcmext)]
dcmlst += dcmt1
if 'T2DCM' in datain:
dcmt2 = os.listdir(datain['T2DCM'])
# accept only *.dcm extensions
dcmt2 = [os.path.join(datain['T2DCM'],d) for d in dcmt2 if d.endswith(dcmext)]
dcmlst += dcmt2
if 'UTE1' in datain:
dcmute1 = os.listdir(datain['UTE1'])
# accept only *.dcm extensions
dcmute1 = [os.path.join(datain['UTE1'],d) for d in dcmute1 if d.endswith(dcmext)]
dcmlst += dcmute1
if 'UTE2' in datain:
dcmute2 = os.listdir(datain['UTE2'])
# accept only *.dcm extensions
dcmute2 = [os.path.join(datain['UTE2'],d) for d in dcmute2 if d.endswith(dcmext)]
dcmlst += dcmute2
#-list-mode data dcm
if 'lm_dcm' in datain:
dcmlst += [datain['lm_dcm']]
if 'lm_ima' in datain:
dcmlst += [datain['lm_ima']]
#-norm
if 'nrm_dcm' in datain:
dcmlst += [datain['nrm_dcm']]
if 'nrm_ima' in datain:
dcmlst += [datain['nrm_ima']]
return dcmlst | [
"def",
"list_dcm_datain",
"(",
"datain",
")",
":",
"if",
"not",
"isinstance",
"(",
"datain",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'The input is not a dictionary!'",
")",
"dcmlst",
"=",
"[",
"]",
"# list of mu-map DICOM files",
"if",
"'mumapDCM'",
... | List all DICOM file paths in the datain dictionary of input data. | [
"List",
"all",
"DICOM",
"file",
"paths",
"in",
"the",
"datain",
"dictionary",
"of",
"input",
"data",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L358-L411 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | dcmanonym | def dcmanonym(
dcmpth,
displayonly=False,
patient='anonymised',
physician='anonymised',
dob='19800101',
verbose=True):
''' Anonymise DICOM file(s)
Arguments:
> dcmpth: it can be passed as a single DICOM file, or
a folder containing DICOM files, or a list of DICOM file paths.
> patient: the name of the patient.
> physician:the name of the referring physician.
> dob: patient's date of birth.
> verbose: display processing output.
'''
#> check if a single DICOM file
if isinstance(dcmpth, basestring) and os.path.isfile(dcmpth):
dcmlst = [dcmpth]
if verbose:
print 'i> recognised the input argument as a single DICOM file.'
#> check if a folder containing DICOM files
elif isinstance(dcmpth, basestring) and os.path.isdir(dcmpth):
dircontent = os.listdir(dcmpth)
#> create a list of DICOM files inside the folder
dcmlst = [os.path.join(dcmpth,d) for d in dircontent if os.path.isfile(os.path.join(dcmpth,d)) and d.endswith(dcmext)]
if verbose:
print 'i> recognised the input argument as the folder containing DICOM files.'
#> check if a folder containing DICOM files
elif isinstance(dcmpth, list):
if not all([os.path.isfile(d) and d.endswith(dcmext) for d in dcmpth]):
raise IOError('Not all files in the list are DICOM files.')
dcmlst = dcmpth
if verbose:
print 'i> recognised the input argument as the list of DICOM file paths.'
#> check if dictionary of data input <datain>
elif isinstance(dcmpth, dict) and 'corepath' in dcmpth:
dcmlst = list_dcm_datain(dcmpth)
if verbose:
print 'i> recognised the input argument as the dictionary of scanner data.'
else:
raise IOError('Unrecognised input!')
for dcmf in dcmlst:
#> read the file
dhdr = dcm.dcmread(dcmf)
#> get the basic info about the DICOM file
dcmtype = dcminfo(dhdr, verbose=False)
if verbose:
print '-------------------------------'
print 'i> the DICOM file is for:', dcmtype
#> anonymise mMR data.
if 'mmr' in dcmtype:
if [0x029, 0x1120] in dhdr and dhdr[0x029, 0x1120].name=='[CSA Series Header Info]':
csafield = dhdr[0x029, 0x1120]
csa = csafield.value
elif [0x029, 0x1020] in dhdr and dhdr[0x029, 0x1020].name=='[CSA Series Header Info]':
csafield = dhdr[0x029, 0x1020]
csa = csafield.value
else:
csa = ''
# string length considered for replacement
strlen = 200
idx = [m.start() for m in re.finditer(r'([Pp]atients{0,1}[Nn]ame)', csa)]
if idx and verbose:
print ' > found sensitive information deep in DICOM headers:', dcmtype
#> run the anonymisation
iupdate = 0
for i in idx:
ci = i - iupdate
if displayonly:
print ' > sensitive info:'
print ' ', csa[ci:ci+strlen]
continue
rplcmnt = re.sub( r'(\{\s*\"{1,2}\W*\w+\W*\w+\W*\"{1,2}\s*\})',
'{ ""' +patient+ '"" }',
csa[ci:ci+strlen]
)
#> update string
csa = csa[:ci] + rplcmnt + csa[ci+strlen:]
print ' > removed sensitive information.'
#> correct for the number of removed letters
iupdate = strlen-len(rplcmnt)
#> update DICOM
if not displayonly and csa!='':
csafield.value = csa
#> Patient's name
if [0x010,0x010] in dhdr:
if displayonly:
print ' > sensitive info:', dhdr[0x010,0x010].name
print ' ', dhdr[0x010,0x010].value
else:
dhdr[0x010,0x010].value = patient
if verbose: print ' > anonymised patients name'
#> date of birth
if [0x010,0x030] in dhdr:
if displayonly:
print ' > sensitive info:', dhdr[0x010,0x030].name
print ' ', dhdr[0x010,0x030].value
else:
dhdr[0x010,0x030].value = dob
if verbose: print ' > anonymised date of birh'
#> physician's name
if [0x008, 0x090] in dhdr:
if displayonly:
print ' > sensitive info:', dhdr[0x008,0x090].name
print ' ', dhdr[0x008,0x090].value
else:
dhdr[0x008,0x090].value = physician
if verbose: print ' > anonymised physician name'
dhdr.save_as(dcmf) | python | def dcmanonym(
dcmpth,
displayonly=False,
patient='anonymised',
physician='anonymised',
dob='19800101',
verbose=True):
''' Anonymise DICOM file(s)
Arguments:
> dcmpth: it can be passed as a single DICOM file, or
a folder containing DICOM files, or a list of DICOM file paths.
> patient: the name of the patient.
> physician:the name of the referring physician.
> dob: patient's date of birth.
> verbose: display processing output.
'''
#> check if a single DICOM file
if isinstance(dcmpth, basestring) and os.path.isfile(dcmpth):
dcmlst = [dcmpth]
if verbose:
print 'i> recognised the input argument as a single DICOM file.'
#> check if a folder containing DICOM files
elif isinstance(dcmpth, basestring) and os.path.isdir(dcmpth):
dircontent = os.listdir(dcmpth)
#> create a list of DICOM files inside the folder
dcmlst = [os.path.join(dcmpth,d) for d in dircontent if os.path.isfile(os.path.join(dcmpth,d)) and d.endswith(dcmext)]
if verbose:
print 'i> recognised the input argument as the folder containing DICOM files.'
#> check if a folder containing DICOM files
elif isinstance(dcmpth, list):
if not all([os.path.isfile(d) and d.endswith(dcmext) for d in dcmpth]):
raise IOError('Not all files in the list are DICOM files.')
dcmlst = dcmpth
if verbose:
print 'i> recognised the input argument as the list of DICOM file paths.'
#> check if dictionary of data input <datain>
elif isinstance(dcmpth, dict) and 'corepath' in dcmpth:
dcmlst = list_dcm_datain(dcmpth)
if verbose:
print 'i> recognised the input argument as the dictionary of scanner data.'
else:
raise IOError('Unrecognised input!')
for dcmf in dcmlst:
#> read the file
dhdr = dcm.dcmread(dcmf)
#> get the basic info about the DICOM file
dcmtype = dcminfo(dhdr, verbose=False)
if verbose:
print '-------------------------------'
print 'i> the DICOM file is for:', dcmtype
#> anonymise mMR data.
if 'mmr' in dcmtype:
if [0x029, 0x1120] in dhdr and dhdr[0x029, 0x1120].name=='[CSA Series Header Info]':
csafield = dhdr[0x029, 0x1120]
csa = csafield.value
elif [0x029, 0x1020] in dhdr and dhdr[0x029, 0x1020].name=='[CSA Series Header Info]':
csafield = dhdr[0x029, 0x1020]
csa = csafield.value
else:
csa = ''
# string length considered for replacement
strlen = 200
idx = [m.start() for m in re.finditer(r'([Pp]atients{0,1}[Nn]ame)', csa)]
if idx and verbose:
print ' > found sensitive information deep in DICOM headers:', dcmtype
#> run the anonymisation
iupdate = 0
for i in idx:
ci = i - iupdate
if displayonly:
print ' > sensitive info:'
print ' ', csa[ci:ci+strlen]
continue
rplcmnt = re.sub( r'(\{\s*\"{1,2}\W*\w+\W*\w+\W*\"{1,2}\s*\})',
'{ ""' +patient+ '"" }',
csa[ci:ci+strlen]
)
#> update string
csa = csa[:ci] + rplcmnt + csa[ci+strlen:]
print ' > removed sensitive information.'
#> correct for the number of removed letters
iupdate = strlen-len(rplcmnt)
#> update DICOM
if not displayonly and csa!='':
csafield.value = csa
#> Patient's name
if [0x010,0x010] in dhdr:
if displayonly:
print ' > sensitive info:', dhdr[0x010,0x010].name
print ' ', dhdr[0x010,0x010].value
else:
dhdr[0x010,0x010].value = patient
if verbose: print ' > anonymised patients name'
#> date of birth
if [0x010,0x030] in dhdr:
if displayonly:
print ' > sensitive info:', dhdr[0x010,0x030].name
print ' ', dhdr[0x010,0x030].value
else:
dhdr[0x010,0x030].value = dob
if verbose: print ' > anonymised date of birh'
#> physician's name
if [0x008, 0x090] in dhdr:
if displayonly:
print ' > sensitive info:', dhdr[0x008,0x090].name
print ' ', dhdr[0x008,0x090].value
else:
dhdr[0x008,0x090].value = physician
if verbose: print ' > anonymised physician name'
dhdr.save_as(dcmf) | [
"def",
"dcmanonym",
"(",
"dcmpth",
",",
"displayonly",
"=",
"False",
",",
"patient",
"=",
"'anonymised'",
",",
"physician",
"=",
"'anonymised'",
",",
"dob",
"=",
"'19800101'",
",",
"verbose",
"=",
"True",
")",
":",
"#> check if a single DICOM file",
"if",
"isi... | Anonymise DICOM file(s)
Arguments:
> dcmpth: it can be passed as a single DICOM file, or
a folder containing DICOM files, or a list of DICOM file paths.
> patient: the name of the patient.
> physician:the name of the referring physician.
> dob: patient's date of birth.
> verbose: display processing output. | [
"Anonymise",
"DICOM",
"file",
"(",
"s",
")",
"Arguments",
":",
">",
"dcmpth",
":",
"it",
"can",
"be",
"passed",
"as",
"a",
"single",
"DICOM",
"file",
"or",
"a",
"folder",
"containing",
"DICOM",
"files",
"or",
"a",
"list",
"of",
"DICOM",
"file",
"paths"... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L415-L550 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | dcmsort | def dcmsort(folder, copy_series=False, verbose=False):
''' Sort out the DICOM files in the folder according to the recorded series.
'''
# list files in the input folder
files = os.listdir(folder)
srs = {}
for f in files:
if os.path.isfile(os.path.join(folder, f)) and f.endswith(dcmext):
dhdr = dcm.read_file(os.path.join(folder, f))
#---------------------------------
# image size
imsz = np.zeros(2, dtype=np.int64)
if [0x028,0x010] in dhdr:
imsz[0] = dhdr[0x028,0x010].value
if [0x028,0x011] in dhdr:
imsz[1] = dhdr[0x028,0x011].value
# voxel size
vxsz = np.zeros(3, dtype=np.float64)
if [0x028,0x030] in dhdr and [0x018,0x050] in dhdr:
pxsz = np.array([float(e) for e in dhdr[0x028,0x030].value])
vxsz[:2] = pxsz
vxsz[2] = float(dhdr[0x018,0x050].value)
# orientation
ornt = np.zeros(6, dtype=np.float64)
if [0x020,0x037] in dhdr:
ornt = np.array([float(e) for e in dhdr[0x20,0x37].value])
# seires description, time and study time
srs_dcrp = dhdr[0x0008, 0x103e].value
srs_time = dhdr[0x0008, 0x0031].value[:6]
std_time = dhdr[0x0008, 0x0030].value[:6]
if verbose:
print 'series desciption:', srs_dcrp
print 'series time:', srs_time
print 'study time:', std_time
print '---------------------------------------------------'
#----------
# series for any category (can be multiple scans within the same category)
recognised_series = False
srs_k = srs.keys()
for s in srs_k:
if np.array_equal(srs[s]['imorient'], ornt) and \
np.array_equal(srs[s]['imsize'], imsz) and \
np.array_equal(srs[s]['voxsize'], vxsz) and \
srs[s]['tseries'] == srs_time:
recognised_series = True
break
# if series was not found, create one
if not recognised_series:
s = srs_dcrp + '_' + srs_time
srs[s] = {}
srs[s]['imorient'] = ornt
srs[s]['imsize'] = imsz
srs[s]['voxsize'] = vxsz
srs[s]['tseries'] = srs_time
# append the file name
if 'files' not in srs[s]: srs[s]['files'] = []
if copy_series:
srsdir = os.path.join(folder, s)
create_dir( srsdir )
shutil.copy(os.path.join(folder, f), srsdir)
srs[s]['files'].append( os.path.join(srsdir, f) )
else:
srs[s]['files'].append( os.path.join(folder, f) )
return srs | python | def dcmsort(folder, copy_series=False, verbose=False):
''' Sort out the DICOM files in the folder according to the recorded series.
'''
# list files in the input folder
files = os.listdir(folder)
srs = {}
for f in files:
if os.path.isfile(os.path.join(folder, f)) and f.endswith(dcmext):
dhdr = dcm.read_file(os.path.join(folder, f))
#---------------------------------
# image size
imsz = np.zeros(2, dtype=np.int64)
if [0x028,0x010] in dhdr:
imsz[0] = dhdr[0x028,0x010].value
if [0x028,0x011] in dhdr:
imsz[1] = dhdr[0x028,0x011].value
# voxel size
vxsz = np.zeros(3, dtype=np.float64)
if [0x028,0x030] in dhdr and [0x018,0x050] in dhdr:
pxsz = np.array([float(e) for e in dhdr[0x028,0x030].value])
vxsz[:2] = pxsz
vxsz[2] = float(dhdr[0x018,0x050].value)
# orientation
ornt = np.zeros(6, dtype=np.float64)
if [0x020,0x037] in dhdr:
ornt = np.array([float(e) for e in dhdr[0x20,0x37].value])
# seires description, time and study time
srs_dcrp = dhdr[0x0008, 0x103e].value
srs_time = dhdr[0x0008, 0x0031].value[:6]
std_time = dhdr[0x0008, 0x0030].value[:6]
if verbose:
print 'series desciption:', srs_dcrp
print 'series time:', srs_time
print 'study time:', std_time
print '---------------------------------------------------'
#----------
# series for any category (can be multiple scans within the same category)
recognised_series = False
srs_k = srs.keys()
for s in srs_k:
if np.array_equal(srs[s]['imorient'], ornt) and \
np.array_equal(srs[s]['imsize'], imsz) and \
np.array_equal(srs[s]['voxsize'], vxsz) and \
srs[s]['tseries'] == srs_time:
recognised_series = True
break
# if series was not found, create one
if not recognised_series:
s = srs_dcrp + '_' + srs_time
srs[s] = {}
srs[s]['imorient'] = ornt
srs[s]['imsize'] = imsz
srs[s]['voxsize'] = vxsz
srs[s]['tseries'] = srs_time
# append the file name
if 'files' not in srs[s]: srs[s]['files'] = []
if copy_series:
srsdir = os.path.join(folder, s)
create_dir( srsdir )
shutil.copy(os.path.join(folder, f), srsdir)
srs[s]['files'].append( os.path.join(srsdir, f) )
else:
srs[s]['files'].append( os.path.join(folder, f) )
return srs | [
"def",
"dcmsort",
"(",
"folder",
",",
"copy_series",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"# list files in the input folder",
"files",
"=",
"os",
".",
"listdir",
"(",
"folder",
")",
"srs",
"=",
"{",
"}",
"for",
"f",
"in",
"files",
":",
... | Sort out the DICOM files in the folder according to the recorded series. | [
"Sort",
"out",
"the",
"DICOM",
"files",
"in",
"the",
"folder",
"according",
"to",
"the",
"recorded",
"series",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L557-L625 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | niisort | def niisort(
fims,
memlim=True
):
''' Sort all input NIfTI images and check their shape.
Output dictionary of image files and their properties.
Options:
memlim -- when processing large numbers of frames the memory may
not be large enough. memlim causes that the output does not contain
all the arrays corresponding to the images.
'''
# number of NIfTI images in folder
Nim = 0
# sorting list (if frame number is present in the form '_frm<dd>', where d is a digit)
sortlist = []
for f in fims:
if f.endswith('.nii') or f.endswith('.nii.gz'):
Nim += 1
_match = re.search('(?<=_frm)\d*', f)
if _match:
frm = int(_match.group(0))
freelists = [frm not in l for l in sortlist]
listidx = [i for i,f in enumerate(freelists) if f]
if listidx:
sortlist[listidx[0]].append(frm)
else:
sortlist.append([frm])
else:
sortlist.append([None])
if len(sortlist)>1:
# if more than one dynamic set is given, the dynamic mode is cancelled.
dyn_flg = False
sortlist = range(Nim)
elif len(sortlist)==1:
dyn_flg = True
sortlist = sortlist[0]
else:
raise ValueError('e> niisort input error.')
# number of frames (can be larger than the # images)
Nfrm = max(sortlist)+1
# sort the list according to the frame numbers
_fims = ['Blank']*Nfrm
# list of NIfTI image shapes and data types used
shape = []
dtype = []
_nii = []
for i in range(Nim):
if dyn_flg:
_fims[sortlist[i]] = fims[i]
_nii = nib.load(fims[i])
dtype.append(_nii.get_data_dtype())
shape.append(_nii.shape)
else:
_fims[i] = fims[i]
_nii = nib.load(fims[i])
dtype.append(_nii.get_data_dtype())
shape.append(_nii.shape)
# check if all images are of the same shape and data type
if _nii and not shape.count(_nii.shape)==len(shape):
raise ValueError('Input images are of different shapes.')
if _nii and not dtype.count(_nii.get_data_dtype())==len(dtype):
raise TypeError('Input images are of different data types.')
# image shape must be 3D
if _nii and not len(_nii.shape)==3:
raise ValueError('Input image(s) must be 3D.')
out = {'shape':_nii.shape[::-1],
'files':_fims,
'sortlist':sortlist,
'dtype':_nii.get_data_dtype(),
'N':Nim}
if memlim and Nfrm>50:
imdic = getnii(_fims[0], output='all')
affine = imdic['affine']
else:
# get the images into an array
_imin = np.zeros((Nfrm,)+_nii.shape[::-1], dtype=_nii.get_data_dtype())
for i in range(Nfrm):
if i in sortlist:
imdic = getnii(_fims[i], output='all')
_imin[i,:,:,:] = imdic['im']
affine = imdic['affine']
out['im'] = _imin[:Nfrm,:,:,:]
out['affine'] = affine
return out | python | def niisort(
fims,
memlim=True
):
''' Sort all input NIfTI images and check their shape.
Output dictionary of image files and their properties.
Options:
memlim -- when processing large numbers of frames the memory may
not be large enough. memlim causes that the output does not contain
all the arrays corresponding to the images.
'''
# number of NIfTI images in folder
Nim = 0
# sorting list (if frame number is present in the form '_frm<dd>', where d is a digit)
sortlist = []
for f in fims:
if f.endswith('.nii') or f.endswith('.nii.gz'):
Nim += 1
_match = re.search('(?<=_frm)\d*', f)
if _match:
frm = int(_match.group(0))
freelists = [frm not in l for l in sortlist]
listidx = [i for i,f in enumerate(freelists) if f]
if listidx:
sortlist[listidx[0]].append(frm)
else:
sortlist.append([frm])
else:
sortlist.append([None])
if len(sortlist)>1:
# if more than one dynamic set is given, the dynamic mode is cancelled.
dyn_flg = False
sortlist = range(Nim)
elif len(sortlist)==1:
dyn_flg = True
sortlist = sortlist[0]
else:
raise ValueError('e> niisort input error.')
# number of frames (can be larger than the # images)
Nfrm = max(sortlist)+1
# sort the list according to the frame numbers
_fims = ['Blank']*Nfrm
# list of NIfTI image shapes and data types used
shape = []
dtype = []
_nii = []
for i in range(Nim):
if dyn_flg:
_fims[sortlist[i]] = fims[i]
_nii = nib.load(fims[i])
dtype.append(_nii.get_data_dtype())
shape.append(_nii.shape)
else:
_fims[i] = fims[i]
_nii = nib.load(fims[i])
dtype.append(_nii.get_data_dtype())
shape.append(_nii.shape)
# check if all images are of the same shape and data type
if _nii and not shape.count(_nii.shape)==len(shape):
raise ValueError('Input images are of different shapes.')
if _nii and not dtype.count(_nii.get_data_dtype())==len(dtype):
raise TypeError('Input images are of different data types.')
# image shape must be 3D
if _nii and not len(_nii.shape)==3:
raise ValueError('Input image(s) must be 3D.')
out = {'shape':_nii.shape[::-1],
'files':_fims,
'sortlist':sortlist,
'dtype':_nii.get_data_dtype(),
'N':Nim}
if memlim and Nfrm>50:
imdic = getnii(_fims[0], output='all')
affine = imdic['affine']
else:
# get the images into an array
_imin = np.zeros((Nfrm,)+_nii.shape[::-1], dtype=_nii.get_data_dtype())
for i in range(Nfrm):
if i in sortlist:
imdic = getnii(_fims[i], output='all')
_imin[i,:,:,:] = imdic['im']
affine = imdic['affine']
out['im'] = _imin[:Nfrm,:,:,:]
out['affine'] = affine
return out | [
"def",
"niisort",
"(",
"fims",
",",
"memlim",
"=",
"True",
")",
":",
"# number of NIfTI images in folder",
"Nim",
"=",
"0",
"# sorting list (if frame number is present in the form '_frm<dd>', where d is a digit)",
"sortlist",
"=",
"[",
"]",
"for",
"f",
"in",
"fims",
":"... | Sort all input NIfTI images and check their shape.
Output dictionary of image files and their properties.
Options:
memlim -- when processing large numbers of frames the memory may
not be large enough. memlim causes that the output does not contain
all the arrays corresponding to the images. | [
"Sort",
"all",
"input",
"NIfTI",
"images",
"and",
"check",
"their",
"shape",
".",
"Output",
"dictionary",
"of",
"image",
"files",
"and",
"their",
"properties",
".",
"Options",
":",
"memlim",
"--",
"when",
"processing",
"large",
"numbers",
"of",
"frames",
"th... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L633-L726 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | dcm2nii | def dcm2nii(
dcmpth,
fimout = '',
fprefix = 'converted-from-DICOM_',
fcomment = '',
outpath = '',
timestamp = True,
executable = '',
force = False,
):
''' Convert DICOM files in folder (indicated by <dcmpth>) using DCM2NIIX
third-party software.
'''
# skip conversion if the output already exists and not force is selected
if os.path.isfile(fimout) and not force:
return fimout
if executable=='':
try:
import resources
executable = resources.DCM2NIIX
except:
raise NameError('e> could not import resources \
or find variable DCM2NIIX in resources.py')
elif not os.path.isfile(executable):
raise IOError('e> the executable is incorrect!')
if not os.path.isdir(dcmpth):
raise IOError('e> the provided DICOM path is not a folder!')
#> output path
if outpath=='' and fimout!='' and '/' in fimout:
opth = os.path.dirname(fimout)
if opth=='':
opth = dcmpth
fimout = os.path.basename(fimout)
elif outpath=='':
opth = dcmpth
else:
opth = outpath
create_dir(opth)
if fimout=='':
fimout = fprefix
if timestamp:
fimout += time_stamp(simple_ascii=True)
fimout = fimout.split('.nii')[0]
# convert the DICOM mu-map images to nii
call([executable, '-f', fimout, '-o', opth, dcmpth])
fniiout = glob.glob( os.path.join(opth, '*'+fimout+'*.nii*') )
if fniiout:
return fniiout[0]
else:
raise ValueError('e> could not get the output file!') | python | def dcm2nii(
dcmpth,
fimout = '',
fprefix = 'converted-from-DICOM_',
fcomment = '',
outpath = '',
timestamp = True,
executable = '',
force = False,
):
''' Convert DICOM files in folder (indicated by <dcmpth>) using DCM2NIIX
third-party software.
'''
# skip conversion if the output already exists and not force is selected
if os.path.isfile(fimout) and not force:
return fimout
if executable=='':
try:
import resources
executable = resources.DCM2NIIX
except:
raise NameError('e> could not import resources \
or find variable DCM2NIIX in resources.py')
elif not os.path.isfile(executable):
raise IOError('e> the executable is incorrect!')
if not os.path.isdir(dcmpth):
raise IOError('e> the provided DICOM path is not a folder!')
#> output path
if outpath=='' and fimout!='' and '/' in fimout:
opth = os.path.dirname(fimout)
if opth=='':
opth = dcmpth
fimout = os.path.basename(fimout)
elif outpath=='':
opth = dcmpth
else:
opth = outpath
create_dir(opth)
if fimout=='':
fimout = fprefix
if timestamp:
fimout += time_stamp(simple_ascii=True)
fimout = fimout.split('.nii')[0]
# convert the DICOM mu-map images to nii
call([executable, '-f', fimout, '-o', opth, dcmpth])
fniiout = glob.glob( os.path.join(opth, '*'+fimout+'*.nii*') )
if fniiout:
return fniiout[0]
else:
raise ValueError('e> could not get the output file!') | [
"def",
"dcm2nii",
"(",
"dcmpth",
",",
"fimout",
"=",
"''",
",",
"fprefix",
"=",
"'converted-from-DICOM_'",
",",
"fcomment",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"timestamp",
"=",
"True",
",",
"executable",
"=",
"''",
",",
"force",
"=",
"False",
"... | Convert DICOM files in folder (indicated by <dcmpth>) using DCM2NIIX
third-party software. | [
"Convert",
"DICOM",
"files",
"in",
"folder",
"(",
"indicated",
"by",
"<dcmpth",
">",
")",
"using",
"DCM2NIIX",
"third",
"-",
"party",
"software",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L730-L792 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | dcm2im | def dcm2im(fpth):
''' Get the DICOM files from 'fpth' into an image with the affine transformation.
fpth can be a list of DICOM files or a path (string) to the folder with DICOM files.
'''
# possible DICOM file extensions
ext = ('dcm', 'DCM', 'ima', 'IMA')
# case when given a folder path
if isinstance(fpth, basestring) and os.path.isdir(fpth):
SZ0 = len([d for d in os.listdir(fpth) if d.endswith(ext)])
# list of DICOM files
fdcms = os.listdir(fpth)
fdcms = [os.path.join(fpth,f) for f in fdcms if f.endswith(ext)]
# case when list of DICOM files is given
elif isinstance(fpth, list) and os.path.isfile(os.path.join(fpth[0])):
SZ0 = len(fpth)
# list of DICOM files
fdcms = fpth
fdcms = [f for f in fdcms if f.endswith(ext)]
else:
raise NameError('Unrecognised input for DICOM files.')
if SZ0<1:
print 'e> no DICOM images in the specified path.'
raise IOError('Input DICOM images not recognised')
# pick single DICOM header
dhdr = dcm.read_file(fdcms[0])
#------------------------------------
# some info, e.g.: patient position and series UID
if [0x018, 0x5100] in dhdr:
ornt = dhdr[0x18,0x5100].value
else:
ornt = 'unkonwn'
# Series UID
sruid = dhdr[0x0020, 0x000e].value
#------------------------------------
#------------------------------------
# INIT
# image position
P = np.zeros((SZ0,3), dtype=np.float64)
#image orientation
Orn = np.zeros((SZ0,6), dtype=np.float64)
#xy resolution
R = np.zeros((SZ0,2), dtype=np.float64)
#slice thickness
S = np.zeros((SZ0,1), dtype=np.float64)
#slope and intercept
SI = np.ones((SZ0,2), dtype=np.float64)
SI[:,1] = 0
#image data as an list of array for now
IM = []
#------------------------------------
c = 0
for d in fdcms:
dhdr = dcm.read_file(d)
if [0x20,0x32] in dhdr and [0x20,0x37] in dhdr and [0x28,0x30] in dhdr:
P[c,:] = np.array([float(f) for f in dhdr[0x20,0x32].value])
Orn[c,:] = np.array([float(f) for f in dhdr[0x20,0x37].value])
R[c,:] = np.array([float(f) for f in dhdr[0x28,0x30].value])
S[c,:] = float(dhdr[0x18,0x50].value)
else:
print 'e> could not read all the DICOM tags.'
return {'im':[], 'affine':[], 'shape':[], 'orient':ornt, 'sruid':sruid}
if [0x28,0x1053] in dhdr and [0x28,0x1052] in dhdr:
SI[c,0] = float(dhdr[0x28,0x1053].value)
SI[c,1] = float(dhdr[0x28,0x1052].value)
IM.append(dhdr.pixel_array)
c += 1
#check if orientation/resolution is the same for all slices
if np.sum(Orn-Orn[0,:]) > 1e-6:
print 'e> varying orientation for slices'
else:
Orn = Orn[0,:]
if np.sum(R-R[0,:]) > 1e-6:
print 'e> varying resolution for slices'
else:
R = R[0,:]
# Patient Position
#patpos = dhdr[0x18,0x5100].value
# Rows and Columns
if [0x28,0x10] in dhdr and [0x28,0x11] in dhdr:
SZ2 = dhdr[0x28,0x10].value
SZ1 = dhdr[0x28,0x11].value
# image resolution
SZ_VX2 = R[0]
SZ_VX1 = R[1]
#now sort the images along k-dimension
k = np.argmin(abs(Orn[:3]+Orn[3:]))
#sorted indeces
si = np.argsort(P[:,k])
Pos = np.zeros(P.shape, dtype=np.float64)
im = np.zeros((SZ0, SZ1, SZ2 ), dtype=np.float32)
#check if the detentions are in agreement (the pixel array could be transposed...)
if IM[0].shape[0]==SZ1:
for i in range(SZ0):
im[i,:,:] = IM[si[i]]*SI[si[i],0] + SI[si[i],1]
Pos[i,:] = P[si[i]]
else:
for i in range(SZ0):
im[i,:,:] = IM[si[i]].T * SI[si[i],0] + SI[si[i],1]
Pos[i,:] = P[si[i]]
# proper slice thickness
Zz = (P[si[-1],2] - P[si[0],2])/(SZ0-1)
Zy = (P[si[-1],1] - P[si[0],1])/(SZ0-1)
Zx = (P[si[-1],0] - P[si[0],0])/(SZ0-1)
# dictionary for affine and image size for the image
A = {
'AFFINE':np.array([[SZ_VX2*Orn[0], SZ_VX1*Orn[3], Zx, Pos[0,0]],
[SZ_VX2*Orn[1], SZ_VX1*Orn[4], Zy, Pos[0,1]],
[SZ_VX2*Orn[2], SZ_VX1*Orn[5], Zz, Pos[0,2]],
[0., 0., 0., 1.]]),
'SHAPE':(SZ0, SZ1, SZ2)
}
#the returned image is already scaled according to the dcm header
return {'im':im, 'affine':A['AFFINE'], 'shape':A['SHAPE'], 'orient':ornt, 'sruid':sruid} | python | def dcm2im(fpth):
''' Get the DICOM files from 'fpth' into an image with the affine transformation.
fpth can be a list of DICOM files or a path (string) to the folder with DICOM files.
'''
# possible DICOM file extensions
ext = ('dcm', 'DCM', 'ima', 'IMA')
# case when given a folder path
if isinstance(fpth, basestring) and os.path.isdir(fpth):
SZ0 = len([d for d in os.listdir(fpth) if d.endswith(ext)])
# list of DICOM files
fdcms = os.listdir(fpth)
fdcms = [os.path.join(fpth,f) for f in fdcms if f.endswith(ext)]
# case when list of DICOM files is given
elif isinstance(fpth, list) and os.path.isfile(os.path.join(fpth[0])):
SZ0 = len(fpth)
# list of DICOM files
fdcms = fpth
fdcms = [f for f in fdcms if f.endswith(ext)]
else:
raise NameError('Unrecognised input for DICOM files.')
if SZ0<1:
print 'e> no DICOM images in the specified path.'
raise IOError('Input DICOM images not recognised')
# pick single DICOM header
dhdr = dcm.read_file(fdcms[0])
#------------------------------------
# some info, e.g.: patient position and series UID
if [0x018, 0x5100] in dhdr:
ornt = dhdr[0x18,0x5100].value
else:
ornt = 'unkonwn'
# Series UID
sruid = dhdr[0x0020, 0x000e].value
#------------------------------------
#------------------------------------
# INIT
# image position
P = np.zeros((SZ0,3), dtype=np.float64)
#image orientation
Orn = np.zeros((SZ0,6), dtype=np.float64)
#xy resolution
R = np.zeros((SZ0,2), dtype=np.float64)
#slice thickness
S = np.zeros((SZ0,1), dtype=np.float64)
#slope and intercept
SI = np.ones((SZ0,2), dtype=np.float64)
SI[:,1] = 0
#image data as an list of array for now
IM = []
#------------------------------------
c = 0
for d in fdcms:
dhdr = dcm.read_file(d)
if [0x20,0x32] in dhdr and [0x20,0x37] in dhdr and [0x28,0x30] in dhdr:
P[c,:] = np.array([float(f) for f in dhdr[0x20,0x32].value])
Orn[c,:] = np.array([float(f) for f in dhdr[0x20,0x37].value])
R[c,:] = np.array([float(f) for f in dhdr[0x28,0x30].value])
S[c,:] = float(dhdr[0x18,0x50].value)
else:
print 'e> could not read all the DICOM tags.'
return {'im':[], 'affine':[], 'shape':[], 'orient':ornt, 'sruid':sruid}
if [0x28,0x1053] in dhdr and [0x28,0x1052] in dhdr:
SI[c,0] = float(dhdr[0x28,0x1053].value)
SI[c,1] = float(dhdr[0x28,0x1052].value)
IM.append(dhdr.pixel_array)
c += 1
#check if orientation/resolution is the same for all slices
if np.sum(Orn-Orn[0,:]) > 1e-6:
print 'e> varying orientation for slices'
else:
Orn = Orn[0,:]
if np.sum(R-R[0,:]) > 1e-6:
print 'e> varying resolution for slices'
else:
R = R[0,:]
# Patient Position
#patpos = dhdr[0x18,0x5100].value
# Rows and Columns
if [0x28,0x10] in dhdr and [0x28,0x11] in dhdr:
SZ2 = dhdr[0x28,0x10].value
SZ1 = dhdr[0x28,0x11].value
# image resolution
SZ_VX2 = R[0]
SZ_VX1 = R[1]
#now sort the images along k-dimension
k = np.argmin(abs(Orn[:3]+Orn[3:]))
#sorted indeces
si = np.argsort(P[:,k])
Pos = np.zeros(P.shape, dtype=np.float64)
im = np.zeros((SZ0, SZ1, SZ2 ), dtype=np.float32)
#check if the detentions are in agreement (the pixel array could be transposed...)
if IM[0].shape[0]==SZ1:
for i in range(SZ0):
im[i,:,:] = IM[si[i]]*SI[si[i],0] + SI[si[i],1]
Pos[i,:] = P[si[i]]
else:
for i in range(SZ0):
im[i,:,:] = IM[si[i]].T * SI[si[i],0] + SI[si[i],1]
Pos[i,:] = P[si[i]]
# proper slice thickness
Zz = (P[si[-1],2] - P[si[0],2])/(SZ0-1)
Zy = (P[si[-1],1] - P[si[0],1])/(SZ0-1)
Zx = (P[si[-1],0] - P[si[0],0])/(SZ0-1)
# dictionary for affine and image size for the image
A = {
'AFFINE':np.array([[SZ_VX2*Orn[0], SZ_VX1*Orn[3], Zx, Pos[0,0]],
[SZ_VX2*Orn[1], SZ_VX1*Orn[4], Zy, Pos[0,1]],
[SZ_VX2*Orn[2], SZ_VX1*Orn[5], Zz, Pos[0,2]],
[0., 0., 0., 1.]]),
'SHAPE':(SZ0, SZ1, SZ2)
}
#the returned image is already scaled according to the dcm header
return {'im':im, 'affine':A['AFFINE'], 'shape':A['SHAPE'], 'orient':ornt, 'sruid':sruid} | [
"def",
"dcm2im",
"(",
"fpth",
")",
":",
"# possible DICOM file extensions",
"ext",
"=",
"(",
"'dcm'",
",",
"'DCM'",
",",
"'ima'",
",",
"'IMA'",
")",
"# case when given a folder path",
"if",
"isinstance",
"(",
"fpth",
",",
"basestring",
")",
"and",
"os",
".",
... | Get the DICOM files from 'fpth' into an image with the affine transformation.
fpth can be a list of DICOM files or a path (string) to the folder with DICOM files. | [
"Get",
"the",
"DICOM",
"files",
"from",
"fpth",
"into",
"an",
"image",
"with",
"the",
"affine",
"transformation",
".",
"fpth",
"can",
"be",
"a",
"list",
"of",
"DICOM",
"files",
"or",
"a",
"path",
"(",
"string",
")",
"to",
"the",
"folder",
"with",
"DICO... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L798-L929 |
pjmark/NIMPA | cudasetup.py | path_niftypet_local | def path_niftypet_local():
'''Get the path to the local (home) folder for NiftyPET resources.'''
# if using conda put the resources in the folder with the environment name
if 'CONDA_DEFAULT_ENV' in os.environ:
env = os.environ['CONDA_DEFAULT_ENV']
print 'i> conda environment found:', env
else:
env = ''
# create the path for the resources files according to the OS platform
if platform.system() == 'Linux' :
path_resources = os.path.join( os.path.join(os.path.expanduser('~'), '.niftypet'), env )
elif platform.system() == 'Windows' :
path_resources = os.path.join( os.path.join(os.getenv('LOCALAPPDATA'), '.niftypet'), env )
elif platform.system() == 'Darwin':
path_resources = os.path.join( os.path.join(os.path.expanduser('~'), '.niftypet'), env )
else:
raise SystemError('e> the operating system is not recognised and therefore not supported!')
return path_resources | python | def path_niftypet_local():
'''Get the path to the local (home) folder for NiftyPET resources.'''
# if using conda put the resources in the folder with the environment name
if 'CONDA_DEFAULT_ENV' in os.environ:
env = os.environ['CONDA_DEFAULT_ENV']
print 'i> conda environment found:', env
else:
env = ''
# create the path for the resources files according to the OS platform
if platform.system() == 'Linux' :
path_resources = os.path.join( os.path.join(os.path.expanduser('~'), '.niftypet'), env )
elif platform.system() == 'Windows' :
path_resources = os.path.join( os.path.join(os.getenv('LOCALAPPDATA'), '.niftypet'), env )
elif platform.system() == 'Darwin':
path_resources = os.path.join( os.path.join(os.path.expanduser('~'), '.niftypet'), env )
else:
raise SystemError('e> the operating system is not recognised and therefore not supported!')
return path_resources | [
"def",
"path_niftypet_local",
"(",
")",
":",
"# if using conda put the resources in the folder with the environment name",
"if",
"'CONDA_DEFAULT_ENV'",
"in",
"os",
".",
"environ",
":",
"env",
"=",
"os",
".",
"environ",
"[",
"'CONDA_DEFAULT_ENV'",
"]",
"print",
"'i> conda ... | Get the path to the local (home) folder for NiftyPET resources. | [
"Get",
"the",
"path",
"to",
"the",
"local",
"(",
"home",
")",
"folder",
"for",
"NiftyPET",
"resources",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/cudasetup.py#L32-L50 |
pjmark/NIMPA | cudasetup.py | find_cuda | def find_cuda():
'''Locate the CUDA environment on the system.'''
# search the PATH for NVCC
for fldr in os.environ['PATH'].split(os.pathsep):
cuda_path = join(fldr, 'nvcc')
if os.path.exists(cuda_path):
cuda_path = os.path.dirname(os.path.dirname(cuda_path))
break
cuda_path = None
if cuda_path is None:
print 'w> nvcc compiler could not be found from the PATH!'
return None
# serach for the CUDA library path
lcuda_path = os.path.join(cuda_path, 'lib64')
if 'LD_LIBRARY_PATH' in os.environ.keys():
if lcuda_path in os.environ['LD_LIBRARY_PATH'].split(os.pathsep):
print 'i> found CUDA lib64 in LD_LIBRARY_PATH: ', lcuda_path
elif os.path.isdir(lcuda_path):
print 'i> found CUDA lib64 in : ', lcuda_path
else:
print 'w> folder for CUDA library (64-bit) could not be found!'
return cuda_path, lcuda_path | python | def find_cuda():
'''Locate the CUDA environment on the system.'''
# search the PATH for NVCC
for fldr in os.environ['PATH'].split(os.pathsep):
cuda_path = join(fldr, 'nvcc')
if os.path.exists(cuda_path):
cuda_path = os.path.dirname(os.path.dirname(cuda_path))
break
cuda_path = None
if cuda_path is None:
print 'w> nvcc compiler could not be found from the PATH!'
return None
# serach for the CUDA library path
lcuda_path = os.path.join(cuda_path, 'lib64')
if 'LD_LIBRARY_PATH' in os.environ.keys():
if lcuda_path in os.environ['LD_LIBRARY_PATH'].split(os.pathsep):
print 'i> found CUDA lib64 in LD_LIBRARY_PATH: ', lcuda_path
elif os.path.isdir(lcuda_path):
print 'i> found CUDA lib64 in : ', lcuda_path
else:
print 'w> folder for CUDA library (64-bit) could not be found!'
return cuda_path, lcuda_path | [
"def",
"find_cuda",
"(",
")",
":",
"# search the PATH for NVCC",
"for",
"fldr",
"in",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"cuda_path",
"=",
"join",
"(",
"fldr",
",",
"'nvcc'",
")",
"if",
"os",
... | Locate the CUDA environment on the system. | [
"Locate",
"the",
"CUDA",
"environment",
"on",
"the",
"system",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/cudasetup.py#L53-L78 |
pjmark/NIMPA | cudasetup.py | dev_setup | def dev_setup():
'''figure out what GPU devices are available and choose the supported ones.'''
# check first if NiftyPET was already installed and use the choice of GPU
path_resources = path_niftypet_local()
# if so, import the resources and get the constants
if os.path.isfile(os.path.join(path_resources,'resources.py')):
sys.path.append(path_resources)
try:
import resources
except ImportError as ie:
print '----------------------------'
print 'e> Import Error: NiftyPET''s resources file <resources.py> could not be imported. It should be in ''~/.niftypet/resources.py'' but likely it does not exists.'
print '----------------------------'
else:
print 'e> resources file not found/installed.'
return None
# get all constants and check if device is already chosen
Cnt = resources.get_setup()
if 'CCARCH' in Cnt and 'DEVID' in Cnt:
print 'i> using this CUDA architecture(s):', Cnt['CCARCH']
return Cnt['CCARCH']
# get the current locations
path_current = os.path.dirname( os.path.realpath(__file__) )
path_resins = os.path.join(path_current, 'resources')
path_dinf = os.path.join(path_current, 'niftypet')
path_dinf = os.path.join(path_dinf, 'nimpa')
path_dinf = os.path.join(path_dinf, 'dinf')
# temporary installation location for identifying the CUDA devices
path_tmp_dinf = os.path.join(path_resins,'dinf')
# if the folder 'path_tmp_dinf' exists, delete it
if os.path.isdir(path_tmp_dinf):
shutil.rmtree(path_tmp_dinf)
# copy the device_info module to the resources folder within the installation package
shutil.copytree( path_dinf, path_tmp_dinf)
# create a build using cmake
if platform.system()=='Windows':
path_tmp_build = os.path.join(path_tmp_dinf, 'build')
elif platform.system() in ['Linux', 'Darwin']:
path_tmp_build = os.path.join(path_tmp_dinf, 'build')
else:
print 'w> the operating system {} is not supported for GPU'.format(platform.system())
return ''
os.makedirs(path_tmp_build)
os.chdir(path_tmp_build)
if platform.system()=='Windows':
subprocess.call(
['cmake', '../', '-DPYTHON_INCLUDE_DIRS='+pyhdr,
'-DPYTHON_PREFIX_PATH='+prefix, '-G', Cnt['MSVC_VRSN']]
)
subprocess.call(['cmake', '--build', './', '--config', 'Release'])
path_tmp_build = os.path.join(path_tmp_build, 'Release')
elif platform.system() in ['Linux', 'Darwin']:
subprocess.call(
['cmake', '../', '-DPYTHON_INCLUDE_DIRS='+pyhdr,
'-DPYTHON_PREFIX_PATH='+prefix]
)
subprocess.call(['cmake', '--build', './'])
else:
print 'e> This operating systems {} is not supported!'.format(platform.system())
return ''
# imoprt the new module for device properties
sys.path.insert(0, path_tmp_build)
try:
import dinf
except ImportError:
print 'e> could not compile a CUDA C file--assuming no CUDA installation.'
return ''
# get the list of installed CUDA devices
Ldev = dinf.dev_info(0)
# extract the compute capability as a single number
cclist = [int(str(e[2])+str(e[3])) for e in Ldev]
# get the list of supported CUDA devices (with minimum compute capability)
spprtd = [str(cc) for cc in cclist if cc>=mincc]
ccstr = ''
if spprtd:
# best for the default CUDA device
i = [int(s) for s in spprtd]
devid = i.index(max(i))
#-----------------------------------------------------------------------------------
# form return list of compute capability numbers for which the software will be compiled
for cc in spprtd:
ccstr += '-gencode=arch=compute_'+cc+',code=compute_'+cc+';'
#-----------------------------------------------------------------------------------
else:
devid = None
# remove the temporary path
sys.path.remove(path_tmp_build)
# delete the build once the info about the GPUs has been obtained
os.chdir(path_current)
shutil.rmtree(path_tmp_dinf, ignore_errors=True)
# passing this setting to resources.py
fpth = os.path.join(path_resources,'resources.py') #resource_filename(__name__, 'resources/resources.py')
f = open(fpth, 'r')
rsrc = f.read()
f.close()
# get the region of keeping in synch with Python
i0 = rsrc.find('### start GPU properties ###')
i1 = rsrc.find('### end GPU properties ###')
# list of constants which will be kept in sych from Python
cnt_list = ['DEV_ID', 'CC_ARCH']
val_list = [str(devid), '\''+ccstr+'\'']
# update the resource.py file
strNew = '### start GPU properties ###\n'
for i in range(len(cnt_list)):
strNew += cnt_list[i]+' = '+val_list[i] + '\n'
rsrcNew = rsrc[:i0] + strNew + rsrc[i1:]
f = open(fpth, 'w')
f.write(rsrcNew)
f.close()
return ccstr | python | def dev_setup():
'''figure out what GPU devices are available and choose the supported ones.'''
# check first if NiftyPET was already installed and use the choice of GPU
path_resources = path_niftypet_local()
# if so, import the resources and get the constants
if os.path.isfile(os.path.join(path_resources,'resources.py')):
sys.path.append(path_resources)
try:
import resources
except ImportError as ie:
print '----------------------------'
print 'e> Import Error: NiftyPET''s resources file <resources.py> could not be imported. It should be in ''~/.niftypet/resources.py'' but likely it does not exists.'
print '----------------------------'
else:
print 'e> resources file not found/installed.'
return None
# get all constants and check if device is already chosen
Cnt = resources.get_setup()
if 'CCARCH' in Cnt and 'DEVID' in Cnt:
print 'i> using this CUDA architecture(s):', Cnt['CCARCH']
return Cnt['CCARCH']
# get the current locations
path_current = os.path.dirname( os.path.realpath(__file__) )
path_resins = os.path.join(path_current, 'resources')
path_dinf = os.path.join(path_current, 'niftypet')
path_dinf = os.path.join(path_dinf, 'nimpa')
path_dinf = os.path.join(path_dinf, 'dinf')
# temporary installation location for identifying the CUDA devices
path_tmp_dinf = os.path.join(path_resins,'dinf')
# if the folder 'path_tmp_dinf' exists, delete it
if os.path.isdir(path_tmp_dinf):
shutil.rmtree(path_tmp_dinf)
# copy the device_info module to the resources folder within the installation package
shutil.copytree( path_dinf, path_tmp_dinf)
# create a build using cmake
if platform.system()=='Windows':
path_tmp_build = os.path.join(path_tmp_dinf, 'build')
elif platform.system() in ['Linux', 'Darwin']:
path_tmp_build = os.path.join(path_tmp_dinf, 'build')
else:
print 'w> the operating system {} is not supported for GPU'.format(platform.system())
return ''
os.makedirs(path_tmp_build)
os.chdir(path_tmp_build)
if platform.system()=='Windows':
subprocess.call(
['cmake', '../', '-DPYTHON_INCLUDE_DIRS='+pyhdr,
'-DPYTHON_PREFIX_PATH='+prefix, '-G', Cnt['MSVC_VRSN']]
)
subprocess.call(['cmake', '--build', './', '--config', 'Release'])
path_tmp_build = os.path.join(path_tmp_build, 'Release')
elif platform.system() in ['Linux', 'Darwin']:
subprocess.call(
['cmake', '../', '-DPYTHON_INCLUDE_DIRS='+pyhdr,
'-DPYTHON_PREFIX_PATH='+prefix]
)
subprocess.call(['cmake', '--build', './'])
else:
print 'e> This operating systems {} is not supported!'.format(platform.system())
return ''
# imoprt the new module for device properties
sys.path.insert(0, path_tmp_build)
try:
import dinf
except ImportError:
print 'e> could not compile a CUDA C file--assuming no CUDA installation.'
return ''
# get the list of installed CUDA devices
Ldev = dinf.dev_info(0)
# extract the compute capability as a single number
cclist = [int(str(e[2])+str(e[3])) for e in Ldev]
# get the list of supported CUDA devices (with minimum compute capability)
spprtd = [str(cc) for cc in cclist if cc>=mincc]
ccstr = ''
if spprtd:
# best for the default CUDA device
i = [int(s) for s in spprtd]
devid = i.index(max(i))
#-----------------------------------------------------------------------------------
# form return list of compute capability numbers for which the software will be compiled
for cc in spprtd:
ccstr += '-gencode=arch=compute_'+cc+',code=compute_'+cc+';'
#-----------------------------------------------------------------------------------
else:
devid = None
# remove the temporary path
sys.path.remove(path_tmp_build)
# delete the build once the info about the GPUs has been obtained
os.chdir(path_current)
shutil.rmtree(path_tmp_dinf, ignore_errors=True)
# passing this setting to resources.py
fpth = os.path.join(path_resources,'resources.py') #resource_filename(__name__, 'resources/resources.py')
f = open(fpth, 'r')
rsrc = f.read()
f.close()
# get the region of keeping in synch with Python
i0 = rsrc.find('### start GPU properties ###')
i1 = rsrc.find('### end GPU properties ###')
# list of constants which will be kept in sych from Python
cnt_list = ['DEV_ID', 'CC_ARCH']
val_list = [str(devid), '\''+ccstr+'\'']
# update the resource.py file
strNew = '### start GPU properties ###\n'
for i in range(len(cnt_list)):
strNew += cnt_list[i]+' = '+val_list[i] + '\n'
rsrcNew = rsrc[:i0] + strNew + rsrc[i1:]
f = open(fpth, 'w')
f.write(rsrcNew)
f.close()
return ccstr | [
"def",
"dev_setup",
"(",
")",
":",
"# check first if NiftyPET was already installed and use the choice of GPU",
"path_resources",
"=",
"path_niftypet_local",
"(",
")",
"# if so, import the resources and get the constants",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".... | figure out what GPU devices are available and choose the supported ones. | [
"figure",
"out",
"what",
"GPU",
"devices",
"are",
"available",
"and",
"choose",
"the",
"supported",
"ones",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/cudasetup.py#L82-L202 |
pjmark/NIMPA | cudasetup.py | resources_setup | def resources_setup():
'''
This function checks CUDA devices, selects some and installs resources.py
'''
print 'i> installing file <resources.py> into home directory if it does not exist.'
path_current = os.path.dirname( os.path.realpath(__file__) )
# path to the install version of resources.py.
path_install = os.path.join(path_current, 'resources')
# get the path to the local resources.py (on Linux machines it is in ~/.niftypet)
path_resources = path_niftypet_local()
print path_current
# flag for the resources file if already installed (initially assumed not)
flg_resources = False
# does the local folder for niftypet exists? if not create one.
if not os.path.exists(path_resources):
os.makedirs(path_resources)
# is resources.py in the folder?
if not os.path.isfile(os.path.join(path_resources,'resources.py')):
if os.path.isfile(os.path.join(path_install,'resources.py')):
shutil.copyfile( os.path.join(path_install,'resources.py'), os.path.join(path_resources,'resources.py') )
else:
print 'e> could not fine file <resources.py> to be installed!'
raise IOError('could not find <resources.py')
else:
print 'i> <resources.py> should be already in the local NiftyPET folder.', path_resources
# set the flag that the resources file is already there
flg_resources = True
sys.path.append(path_resources)
try:
import resources
except ImportError as ie:
print '----------------------------'
print 'e> Import Error: NiftyPET''s resources file <resources.py> could not be imported. It should be in ''~/.niftypet/resources.py'' but likely it does not exists.'
print '----------------------------'
# find available GPU devices, select one or more and output the compilation flags
gpuarch = dev_setup()
# return gpuarch for cmake compilation
return gpuarch | python | def resources_setup():
'''
This function checks CUDA devices, selects some and installs resources.py
'''
print 'i> installing file <resources.py> into home directory if it does not exist.'
path_current = os.path.dirname( os.path.realpath(__file__) )
# path to the install version of resources.py.
path_install = os.path.join(path_current, 'resources')
# get the path to the local resources.py (on Linux machines it is in ~/.niftypet)
path_resources = path_niftypet_local()
print path_current
# flag for the resources file if already installed (initially assumed not)
flg_resources = False
# does the local folder for niftypet exists? if not create one.
if not os.path.exists(path_resources):
os.makedirs(path_resources)
# is resources.py in the folder?
if not os.path.isfile(os.path.join(path_resources,'resources.py')):
if os.path.isfile(os.path.join(path_install,'resources.py')):
shutil.copyfile( os.path.join(path_install,'resources.py'), os.path.join(path_resources,'resources.py') )
else:
print 'e> could not fine file <resources.py> to be installed!'
raise IOError('could not find <resources.py')
else:
print 'i> <resources.py> should be already in the local NiftyPET folder.', path_resources
# set the flag that the resources file is already there
flg_resources = True
sys.path.append(path_resources)
try:
import resources
except ImportError as ie:
print '----------------------------'
print 'e> Import Error: NiftyPET''s resources file <resources.py> could not be imported. It should be in ''~/.niftypet/resources.py'' but likely it does not exists.'
print '----------------------------'
# find available GPU devices, select one or more and output the compilation flags
gpuarch = dev_setup()
# return gpuarch for cmake compilation
return gpuarch | [
"def",
"resources_setup",
"(",
")",
":",
"print",
"'i> installing file <resources.py> into home directory if it does not exist.'",
"path_current",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"# path to th... | This function checks CUDA devices, selects some and installs resources.py | [
"This",
"function",
"checks",
"CUDA",
"devices",
"selects",
"some",
"and",
"installs",
"resources",
".",
"py"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/cudasetup.py#L205-L245 |
Syndace/python-omemo | omemo/promise.py | coroutine | def coroutine(f):
"""
Implementation of a coroutine.
Use as a decorator:
@coroutine
def foo():
result = yield somePromise
The function passed should be a generator yielding instances of the Promise class
(or compatible).
The coroutine waits for the Promise to resolve and sends the result (or the error)
back into the generator function.
This simulates sequential execution which in reality can be asynchonous.
"""
@functools.wraps(f)
def _coroutine(*args, **kwargs):
def _resolver(resolve, reject):
try:
generator = f(*args, **kwargs)
except BaseException as e:
# Special case for a function that throws immediately
reject(e)
else:
# Special case for a function that returns immediately
if not isinstance(generator, types.GeneratorType):
resolve(generator)
else:
def _step(previous, previous_type):
element = None
try:
if previous_type == None:
element = next(generator)
elif previous_type:
element = generator.send(previous)
else:
if not isinstance(previous, BaseException):
previous = RejectedException(previous)
element = generator.throw(previous)
except StopIteration as e:
resolve(getattr(e, "value", None))
except ReturnValueException as e:
resolve(e.value)
except BaseException as e:
reject(e)
else:
try:
element.then(
lambda value : _step(value, True),
lambda reason : _step(reason, False)
)
except AttributeError:
reject(InvalidCoroutineException(element))
_step(None, None)
return Promise(_resolver)
return _coroutine | python | def coroutine(f):
"""
Implementation of a coroutine.
Use as a decorator:
@coroutine
def foo():
result = yield somePromise
The function passed should be a generator yielding instances of the Promise class
(or compatible).
The coroutine waits for the Promise to resolve and sends the result (or the error)
back into the generator function.
This simulates sequential execution which in reality can be asynchonous.
"""
@functools.wraps(f)
def _coroutine(*args, **kwargs):
def _resolver(resolve, reject):
try:
generator = f(*args, **kwargs)
except BaseException as e:
# Special case for a function that throws immediately
reject(e)
else:
# Special case for a function that returns immediately
if not isinstance(generator, types.GeneratorType):
resolve(generator)
else:
def _step(previous, previous_type):
element = None
try:
if previous_type == None:
element = next(generator)
elif previous_type:
element = generator.send(previous)
else:
if not isinstance(previous, BaseException):
previous = RejectedException(previous)
element = generator.throw(previous)
except StopIteration as e:
resolve(getattr(e, "value", None))
except ReturnValueException as e:
resolve(e.value)
except BaseException as e:
reject(e)
else:
try:
element.then(
lambda value : _step(value, True),
lambda reason : _step(reason, False)
)
except AttributeError:
reject(InvalidCoroutineException(element))
_step(None, None)
return Promise(_resolver)
return _coroutine | [
"def",
"coroutine",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"_coroutine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_resolver",
"(",
"resolve",
",",
"reject",
")",
":",
"try",
":",
"generator",
... | Implementation of a coroutine.
Use as a decorator:
@coroutine
def foo():
result = yield somePromise
The function passed should be a generator yielding instances of the Promise class
(or compatible).
The coroutine waits for the Promise to resolve and sends the result (or the error)
back into the generator function.
This simulates sequential execution which in reality can be asynchonous. | [
"Implementation",
"of",
"a",
"coroutine",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/promise.py#L164-L225 |
Syndace/python-omemo | omemo/promise.py | no_coroutine | def no_coroutine(f):
"""
This is not a coroutine ;)
Use as a decorator:
@no_coroutine
def foo():
five = yield 5
print(yield "hello")
The function passed should be a generator yielding whatever you feel like.
The yielded values instantly get passed back into the generator.
It's basically the same as if you didn't use yield at all.
The example above is equivalent to:
def foo():
five = 5
print("hello")
Why?
This is the counterpart to coroutine used by maybe_coroutine below.
"""
@functools.wraps(f)
def _no_coroutine(*args, **kwargs):
generator = f(*args, **kwargs)
# Special case for a function that returns immediately
if not isinstance(generator, types.GeneratorType):
return generator
previous = None
first = True
while True:
element = None
try:
if first:
element = next(generator)
else:
element = generator.send(previous)
except StopIteration as e:
return getattr(e, "value", None)
except ReturnValueException as e:
return e.value
else:
previous = element
first = False
return _no_coroutine | python | def no_coroutine(f):
"""
This is not a coroutine ;)
Use as a decorator:
@no_coroutine
def foo():
five = yield 5
print(yield "hello")
The function passed should be a generator yielding whatever you feel like.
The yielded values instantly get passed back into the generator.
It's basically the same as if you didn't use yield at all.
The example above is equivalent to:
def foo():
five = 5
print("hello")
Why?
This is the counterpart to coroutine used by maybe_coroutine below.
"""
@functools.wraps(f)
def _no_coroutine(*args, **kwargs):
generator = f(*args, **kwargs)
# Special case for a function that returns immediately
if not isinstance(generator, types.GeneratorType):
return generator
previous = None
first = True
while True:
element = None
try:
if first:
element = next(generator)
else:
element = generator.send(previous)
except StopIteration as e:
return getattr(e, "value", None)
except ReturnValueException as e:
return e.value
else:
previous = element
first = False
return _no_coroutine | [
"def",
"no_coroutine",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"_no_coroutine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"generator",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Speci... | This is not a coroutine ;)
Use as a decorator:
@no_coroutine
def foo():
five = yield 5
print(yield "hello")
The function passed should be a generator yielding whatever you feel like.
The yielded values instantly get passed back into the generator.
It's basically the same as if you didn't use yield at all.
The example above is equivalent to:
def foo():
five = 5
print("hello")
Why?
This is the counterpart to coroutine used by maybe_coroutine below. | [
"This",
"is",
"not",
"a",
"coroutine",
";",
")"
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/promise.py#L227-L276 |
Syndace/python-omemo | omemo/promise.py | maybe_coroutine | def maybe_coroutine(decide):
"""
Either be a coroutine or not.
Use as a decorator:
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
result = yield maybeAPromise
print("hello")
return result
The function passed should be a generator yielding either only Promises or whatever
you feel like.
The decide parameter must be a function which gets called with the same parameters as
the function to decide whether this is a coroutine or not.
Using this it is possible to either make the function a coroutine or not based on a
parameter to the function call.
Let's explain the example above:
# If the maybeAPromise is an instance of Promise,
# we want the foo function to act as a coroutine.
# If the maybeAPromise is not an instance of Promise,
# we want the foo function to act like any other normal synchronous function.
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
# If isinstance(maybeAPromise, Promise), foo behaves like a coroutine,
# thus maybeAPromise will get resolved asynchronously and the result will be
# pushed back here.
# Otherwise, foo behaves like no_coroutine,
# just pushing the exact value of maybeAPromise back into the generator.
result = yield maybeAPromise
print("hello")
return result
"""
def _maybe_coroutine(f):
@functools.wraps(f)
def __maybe_coroutine(*args, **kwargs):
if decide(*args, **kwargs):
return coroutine(f)(*args, **kwargs)
else:
return no_coroutine(f)(*args, **kwargs)
return __maybe_coroutine
return _maybe_coroutine | python | def maybe_coroutine(decide):
"""
Either be a coroutine or not.
Use as a decorator:
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
result = yield maybeAPromise
print("hello")
return result
The function passed should be a generator yielding either only Promises or whatever
you feel like.
The decide parameter must be a function which gets called with the same parameters as
the function to decide whether this is a coroutine or not.
Using this it is possible to either make the function a coroutine or not based on a
parameter to the function call.
Let's explain the example above:
# If the maybeAPromise is an instance of Promise,
# we want the foo function to act as a coroutine.
# If the maybeAPromise is not an instance of Promise,
# we want the foo function to act like any other normal synchronous function.
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
# If isinstance(maybeAPromise, Promise), foo behaves like a coroutine,
# thus maybeAPromise will get resolved asynchronously and the result will be
# pushed back here.
# Otherwise, foo behaves like no_coroutine,
# just pushing the exact value of maybeAPromise back into the generator.
result = yield maybeAPromise
print("hello")
return result
"""
def _maybe_coroutine(f):
@functools.wraps(f)
def __maybe_coroutine(*args, **kwargs):
if decide(*args, **kwargs):
return coroutine(f)(*args, **kwargs)
else:
return no_coroutine(f)(*args, **kwargs)
return __maybe_coroutine
return _maybe_coroutine | [
"def",
"maybe_coroutine",
"(",
"decide",
")",
":",
"def",
"_maybe_coroutine",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"__maybe_coroutine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"decide",
"(",
"*"... | Either be a coroutine or not.
Use as a decorator:
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
result = yield maybeAPromise
print("hello")
return result
The function passed should be a generator yielding either only Promises or whatever
you feel like.
The decide parameter must be a function which gets called with the same parameters as
the function to decide whether this is a coroutine or not.
Using this it is possible to either make the function a coroutine or not based on a
parameter to the function call.
Let's explain the example above:
# If the maybeAPromise is an instance of Promise,
# we want the foo function to act as a coroutine.
# If the maybeAPromise is not an instance of Promise,
# we want the foo function to act like any other normal synchronous function.
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
# If isinstance(maybeAPromise, Promise), foo behaves like a coroutine,
# thus maybeAPromise will get resolved asynchronously and the result will be
# pushed back here.
# Otherwise, foo behaves like no_coroutine,
# just pushing the exact value of maybeAPromise back into the generator.
result = yield maybeAPromise
print("hello")
return result | [
"Either",
"be",
"a",
"coroutine",
"or",
"not",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/promise.py#L278-L321 |
Syndace/python-omemo | omemo/storagewrapper.py | makeCallbackPromise | def makeCallbackPromise(function, *args, **kwargs):
"""
Take a function that reports its result using a callback and return a Promise that
listenes for this callback.
The function must accept a callback as its first parameter.
The callback must take two arguments:
- success : True or False
- result : The result of the operation if success is True or the error otherwise.
"""
def _resolver(resolve, reject):
function(
lambda success, result: resolve(result) if success else reject(result),
*args,
**kwargs
)
return Promise(_resolver) | python | def makeCallbackPromise(function, *args, **kwargs):
"""
Take a function that reports its result using a callback and return a Promise that
listenes for this callback.
The function must accept a callback as its first parameter.
The callback must take two arguments:
- success : True or False
- result : The result of the operation if success is True or the error otherwise.
"""
def _resolver(resolve, reject):
function(
lambda success, result: resolve(result) if success else reject(result),
*args,
**kwargs
)
return Promise(_resolver) | [
"def",
"makeCallbackPromise",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_resolver",
"(",
"resolve",
",",
"reject",
")",
":",
"function",
"(",
"lambda",
"success",
",",
"result",
":",
"resolve",
"(",
"result",
")",
"i... | Take a function that reports its result using a callback and return a Promise that
listenes for this callback.
The function must accept a callback as its first parameter.
The callback must take two arguments:
- success : True or False
- result : The result of the operation if success is True or the error otherwise. | [
"Take",
"a",
"function",
"that",
"reports",
"its",
"result",
"using",
"a",
"callback",
"and",
"return",
"a",
"Promise",
"that",
"listenes",
"for",
"this",
"callback",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/storagewrapper.py#L6-L24 |
mobiusklein/brainpy | brainpy/composition.py | calculate_mass | def calculate_mass(composition, mass_data=None):
"""Calculates the monoisotopic mass of a composition
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
mass_data : dict, optional
A dict with the masses of the chemical elements (the default
value is :py:data:`nist_mass`).
Returns
-------
mass : float
"""
mass = 0.0
if mass_data is None:
mass_data = nist_mass
for element in composition:
try:
mass += (composition[element] * mass_data[element][0][0])
except KeyError:
match = re.search(r"(\S+)\[(\d+)\]", element)
if match:
element_ = match.group(1)
isotope = int(match.group(2))
mass += composition[element] * mass_data[element_][isotope][0]
else:
raise
return mass | python | def calculate_mass(composition, mass_data=None):
"""Calculates the monoisotopic mass of a composition
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
mass_data : dict, optional
A dict with the masses of the chemical elements (the default
value is :py:data:`nist_mass`).
Returns
-------
mass : float
"""
mass = 0.0
if mass_data is None:
mass_data = nist_mass
for element in composition:
try:
mass += (composition[element] * mass_data[element][0][0])
except KeyError:
match = re.search(r"(\S+)\[(\d+)\]", element)
if match:
element_ = match.group(1)
isotope = int(match.group(2))
mass += composition[element] * mass_data[element_][isotope][0]
else:
raise
return mass | [
"def",
"calculate_mass",
"(",
"composition",
",",
"mass_data",
"=",
"None",
")",
":",
"mass",
"=",
"0.0",
"if",
"mass_data",
"is",
"None",
":",
"mass_data",
"=",
"nist_mass",
"for",
"element",
"in",
"composition",
":",
"try",
":",
"mass",
"+=",
"(",
"com... | Calculates the monoisotopic mass of a composition
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
mass_data : dict, optional
A dict with the masses of the chemical elements (the default
value is :py:data:`nist_mass`).
Returns
-------
mass : float | [
"Calculates",
"the",
"monoisotopic",
"mass",
"of",
"a",
"composition"
] | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/composition.py#L14-L43 |
mobiusklein/brainpy | brainpy/composition.py | parse_formula | def parse_formula(formula):
"""Parse a chemical formula and construct a :class:`PyComposition` object
Parameters
----------
formula : :class:`str`
Returns
-------
:class:`PyComposition`
Raises
------
ValueError
If the formula doesn't match the expected pattern
"""
if not formula_pattern.match(formula):
raise ValueError("%r does not look like a formula" % (formula,))
composition = PyComposition()
for elem, isotope, number in atom_pattern.findall(formula):
composition[_make_isotope_string(elem, int(isotope) if isotope else 0)] += int(number)
return composition | python | def parse_formula(formula):
"""Parse a chemical formula and construct a :class:`PyComposition` object
Parameters
----------
formula : :class:`str`
Returns
-------
:class:`PyComposition`
Raises
------
ValueError
If the formula doesn't match the expected pattern
"""
if not formula_pattern.match(formula):
raise ValueError("%r does not look like a formula" % (formula,))
composition = PyComposition()
for elem, isotope, number in atom_pattern.findall(formula):
composition[_make_isotope_string(elem, int(isotope) if isotope else 0)] += int(number)
return composition | [
"def",
"parse_formula",
"(",
"formula",
")",
":",
"if",
"not",
"formula_pattern",
".",
"match",
"(",
"formula",
")",
":",
"raise",
"ValueError",
"(",
"\"%r does not look like a formula\"",
"%",
"(",
"formula",
",",
")",
")",
"composition",
"=",
"PyComposition",
... | Parse a chemical formula and construct a :class:`PyComposition` object
Parameters
----------
formula : :class:`str`
Returns
-------
:class:`PyComposition`
Raises
------
ValueError
If the formula doesn't match the expected pattern | [
"Parse",
"a",
"chemical",
"formula",
"and",
"construct",
"a",
":",
"class",
":",
"PyComposition",
"object"
] | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/composition.py#L103-L124 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.login | def login(self, username=None, password=None):
"""Execute Skybell login."""
if username is not None:
self._username = username
if password is not None:
self._password = password
if self._username is None or not isinstance(self._username, str):
raise SkybellAuthenticationException(ERROR.USERNAME)
if self._password is None or not isinstance(self._password, str):
raise SkybellAuthenticationException(ERROR.PASSWORD)
self.update_cache(
{
CONST.ACCESS_TOKEN: None
})
login_data = {
'username': self._username,
'password': self._password,
'appId': self.cache(CONST.APP_ID),
CONST.TOKEN: self.cache(CONST.TOKEN)
}
try:
response = self.send_request('post', CONST.LOGIN_URL,
json_data=login_data, retry=False)
except Exception as exc:
raise SkybellAuthenticationException(ERROR.LOGIN_FAILED, exc)
_LOGGER.debug("Login Response: %s", response.text)
response_object = json.loads(response.text)
self.update_cache({
CONST.ACCESS_TOKEN: response_object[CONST.ACCESS_TOKEN]})
_LOGGER.info("Login successful")
return True | python | def login(self, username=None, password=None):
"""Execute Skybell login."""
if username is not None:
self._username = username
if password is not None:
self._password = password
if self._username is None or not isinstance(self._username, str):
raise SkybellAuthenticationException(ERROR.USERNAME)
if self._password is None or not isinstance(self._password, str):
raise SkybellAuthenticationException(ERROR.PASSWORD)
self.update_cache(
{
CONST.ACCESS_TOKEN: None
})
login_data = {
'username': self._username,
'password': self._password,
'appId': self.cache(CONST.APP_ID),
CONST.TOKEN: self.cache(CONST.TOKEN)
}
try:
response = self.send_request('post', CONST.LOGIN_URL,
json_data=login_data, retry=False)
except Exception as exc:
raise SkybellAuthenticationException(ERROR.LOGIN_FAILED, exc)
_LOGGER.debug("Login Response: %s", response.text)
response_object = json.loads(response.text)
self.update_cache({
CONST.ACCESS_TOKEN: response_object[CONST.ACCESS_TOKEN]})
_LOGGER.info("Login successful")
return True | [
"def",
"login",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"username",
"is",
"not",
"None",
":",
"self",
".",
"_username",
"=",
"username",
"if",
"password",
"is",
"not",
"None",
":",
"self",
".",
"_passw... | Execute Skybell login. | [
"Execute",
"Skybell",
"login",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L68-L108 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.logout | def logout(self):
"""Explicit Skybell logout."""
if self.cache(CONST.ACCESS_TOKEN):
# No explicit logout call as it doesn't seem to matter
# if a logout happens without registering the app which
# we aren't currently doing.
self._session = requests.session()
self._devices = None
self.update_cache({CONST.ACCESS_TOKEN: None})
return True | python | def logout(self):
"""Explicit Skybell logout."""
if self.cache(CONST.ACCESS_TOKEN):
# No explicit logout call as it doesn't seem to matter
# if a logout happens without registering the app which
# we aren't currently doing.
self._session = requests.session()
self._devices = None
self.update_cache({CONST.ACCESS_TOKEN: None})
return True | [
"def",
"logout",
"(",
"self",
")",
":",
"if",
"self",
".",
"cache",
"(",
"CONST",
".",
"ACCESS_TOKEN",
")",
":",
"# No explicit logout call as it doesn't seem to matter",
"# if a logout happens without registering the app which",
"# we aren't currently doing.",
"self",
".",
... | Explicit Skybell logout. | [
"Explicit",
"Skybell",
"logout",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L110-L121 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.get_devices | def get_devices(self, refresh=False):
"""Get all devices from Abode."""
if refresh or self._devices is None:
if self._devices is None:
self._devices = {}
_LOGGER.info("Updating all devices...")
response = self.send_request("get", CONST.DEVICES_URL)
response_object = json.loads(response.text)
_LOGGER.debug("Get Devices Response: %s", response.text)
for device_json in response_object:
# Attempt to reuse an existing device
device = self._devices.get(device_json['id'])
# No existing device, create a new one
if device:
device.update(device_json)
else:
device = SkybellDevice(device_json, self)
self._devices[device.device_id] = device
return list(self._devices.values()) | python | def get_devices(self, refresh=False):
"""Get all devices from Abode."""
if refresh or self._devices is None:
if self._devices is None:
self._devices = {}
_LOGGER.info("Updating all devices...")
response = self.send_request("get", CONST.DEVICES_URL)
response_object = json.loads(response.text)
_LOGGER.debug("Get Devices Response: %s", response.text)
for device_json in response_object:
# Attempt to reuse an existing device
device = self._devices.get(device_json['id'])
# No existing device, create a new one
if device:
device.update(device_json)
else:
device = SkybellDevice(device_json, self)
self._devices[device.device_id] = device
return list(self._devices.values()) | [
"def",
"get_devices",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
"or",
"self",
".",
"_devices",
"is",
"None",
":",
"if",
"self",
".",
"_devices",
"is",
"None",
":",
"self",
".",
"_devices",
"=",
"{",
"}",
"_LOGGER",
".",
... | Get all devices from Abode. | [
"Get",
"all",
"devices",
"from",
"Abode",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L123-L146 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.send_request | def send_request(self, method, url, headers=None,
json_data=None, retry=True):
"""Send requests to Skybell."""
if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_URL:
self.login()
if not headers:
headers = {}
if self.cache(CONST.ACCESS_TOKEN):
headers['Authorization'] = 'Bearer ' + \
self.cache(CONST.ACCESS_TOKEN)
headers['user-agent'] = (
'SkyBell/3.4.1 (iPhone9,2; iOS 11.0; loc=en_US; lang=en-US) '
'com.skybell.doorbell/1')
headers['content-type'] = 'application/json'
headers['accepts'] = '*/*'
headers['x-skybell-app-id'] = self.cache(CONST.APP_ID)
headers['x-skybell-client-id'] = self.cache(CONST.CLIENT_ID)
_LOGGER.debug("HTTP %s %s Request with headers: %s",
method, url, headers)
try:
response = getattr(self._session, method)(
url, headers=headers, json=json_data)
_LOGGER.debug("%s %s", response, response.text)
if response and response.status_code < 400:
return response
except RequestException as exc:
_LOGGER.warning("Skybell request exception: %s", exc)
if retry:
self.login()
return self.send_request(method, url, headers, json_data, False)
raise SkybellException(ERROR.REQUEST, "Retry failed") | python | def send_request(self, method, url, headers=None,
json_data=None, retry=True):
"""Send requests to Skybell."""
if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_URL:
self.login()
if not headers:
headers = {}
if self.cache(CONST.ACCESS_TOKEN):
headers['Authorization'] = 'Bearer ' + \
self.cache(CONST.ACCESS_TOKEN)
headers['user-agent'] = (
'SkyBell/3.4.1 (iPhone9,2; iOS 11.0; loc=en_US; lang=en-US) '
'com.skybell.doorbell/1')
headers['content-type'] = 'application/json'
headers['accepts'] = '*/*'
headers['x-skybell-app-id'] = self.cache(CONST.APP_ID)
headers['x-skybell-client-id'] = self.cache(CONST.CLIENT_ID)
_LOGGER.debug("HTTP %s %s Request with headers: %s",
method, url, headers)
try:
response = getattr(self._session, method)(
url, headers=headers, json=json_data)
_LOGGER.debug("%s %s", response, response.text)
if response and response.status_code < 400:
return response
except RequestException as exc:
_LOGGER.warning("Skybell request exception: %s", exc)
if retry:
self.login()
return self.send_request(method, url, headers, json_data, False)
raise SkybellException(ERROR.REQUEST, "Retry failed") | [
"def",
"send_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"headers",
"=",
"None",
",",
"json_data",
"=",
"None",
",",
"retry",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"cache",
"(",
"CONST",
".",
"ACCESS_TOKEN",
")",
"and",
"url",
... | Send requests to Skybell. | [
"Send",
"requests",
"to",
"Skybell",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L161-L200 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.update_cache | def update_cache(self, data):
"""Update a cached value."""
UTILS.update(self._cache, data)
self._save_cache() | python | def update_cache(self, data):
"""Update a cached value."""
UTILS.update(self._cache, data)
self._save_cache() | [
"def",
"update_cache",
"(",
"self",
",",
"data",
")",
":",
"UTILS",
".",
"update",
"(",
"self",
".",
"_cache",
",",
"data",
")",
"self",
".",
"_save_cache",
"(",
")"
] | Update a cached value. | [
"Update",
"a",
"cached",
"value",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L206-L209 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.dev_cache | def dev_cache(self, device, key=None):
"""Get a cached value for a device."""
device_cache = self._cache.get(CONST.DEVICES, {}).get(device.device_id)
if device_cache and key:
return device_cache.get(key)
return device_cache | python | def dev_cache(self, device, key=None):
"""Get a cached value for a device."""
device_cache = self._cache.get(CONST.DEVICES, {}).get(device.device_id)
if device_cache and key:
return device_cache.get(key)
return device_cache | [
"def",
"dev_cache",
"(",
"self",
",",
"device",
",",
"key",
"=",
"None",
")",
":",
"device_cache",
"=",
"self",
".",
"_cache",
".",
"get",
"(",
"CONST",
".",
"DEVICES",
",",
"{",
"}",
")",
".",
"get",
"(",
"device",
".",
"device_id",
")",
"if",
"... | Get a cached value for a device. | [
"Get",
"a",
"cached",
"value",
"for",
"a",
"device",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L211-L218 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.update_dev_cache | def update_dev_cache(self, device, data):
"""Update cached values for a device."""
self.update_cache(
{
CONST.DEVICES: {
device.device_id: data
}
}) | python | def update_dev_cache(self, device, data):
"""Update cached values for a device."""
self.update_cache(
{
CONST.DEVICES: {
device.device_id: data
}
}) | [
"def",
"update_dev_cache",
"(",
"self",
",",
"device",
",",
"data",
")",
":",
"self",
".",
"update_cache",
"(",
"{",
"CONST",
".",
"DEVICES",
":",
"{",
"device",
".",
"device_id",
":",
"data",
"}",
"}",
")"
] | Update cached values for a device. | [
"Update",
"cached",
"values",
"for",
"a",
"device",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L220-L227 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell._load_cache | def _load_cache(self):
"""Load existing cache and merge for updating if required."""
if not self._disable_cache:
if os.path.exists(self._cache_path):
_LOGGER.debug("Cache found at: %s", self._cache_path)
if os.path.getsize(self._cache_path) > 0:
loaded_cache = UTILS.load_cache(self._cache_path)
UTILS.update(self._cache, loaded_cache)
else:
_LOGGER.debug("Cache file is empty. Removing it.")
os.remove(self._cache_path)
self._save_cache() | python | def _load_cache(self):
"""Load existing cache and merge for updating if required."""
if not self._disable_cache:
if os.path.exists(self._cache_path):
_LOGGER.debug("Cache found at: %s", self._cache_path)
if os.path.getsize(self._cache_path) > 0:
loaded_cache = UTILS.load_cache(self._cache_path)
UTILS.update(self._cache, loaded_cache)
else:
_LOGGER.debug("Cache file is empty. Removing it.")
os.remove(self._cache_path)
self._save_cache() | [
"def",
"_load_cache",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_disable_cache",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_cache_path",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Cache found at: %s\"",
",",
"self",
".",
"... | Load existing cache and merge for updating if required. | [
"Load",
"existing",
"cache",
"and",
"merge",
"for",
"updating",
"if",
"required",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L229-L241 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.__encryptKeyTransportMessage | def __encryptKeyTransportMessage(
self,
bare_jids,
encryption_callback,
bundles = None,
expect_problems = None,
ignore_trust = False
):
"""
bare_jids: iterable<string>
encryption_callback: A function which is called using an instance of cryptography.hazmat.primitives.ciphers.CipherContext, which you can use to encrypt any sort of data. You don't have to return anything.
bundles: { [bare_jid: string] => { [device_id: int] => ExtendedPublicBundle } }
expect_problems: { [bare_jid: string] => iterable<int> }
returns: {
iv: bytes,
sid: int,
keys: {
[bare_jid: string] => {
[device: int] => {
"data" : bytes,
"pre_key" : boolean
}
}
}
}
"""
yield self.runInactiveDeviceCleanup()
#########################
# parameter preparation #
#########################
if isinstance(bare_jids, string_type):
bare_jids = set([ bare_jids ])
else:
bare_jids = set(bare_jids)
if bundles == None:
bundles = {}
if expect_problems == None:
expect_problems = {}
else:
for bare_jid in expect_problems:
expect_problems[bare_jid] = set(expect_problems[bare_jid])
# Add the own bare jid to the set of jids
bare_jids.add(self.__my_bare_jid)
########################################################
# check all preconditions and prepare missing sessions #
########################################################
problems = []
# Prepare the lists of devices to encrypt for
encrypt_for = {}
for bare_jid in bare_jids:
devices = yield self.__loadActiveDevices(bare_jid)
if len(devices) == 0:
problems.append(NoDevicesException(bare_jid))
else:
encrypt_for[bare_jid] = devices
# Remove the sending devices from the list
encrypt_for[self.__my_bare_jid].remove(self.__my_device_id)
# Check whether all required bundles are available
for bare_jid, devices in encrypt_for.items():
missing_bundles = set()
# Load all sessions
sessions = yield self.__loadSessions(bare_jid, devices)
for device in devices:
session = sessions[device]
if session == None:
if not device in bundles.get(bare_jid, {}):
missing_bundles.add(device)
devices -= missing_bundles
for device in missing_bundles:
if not device in expect_problems.get(bare_jid, set()):
problems.append(MissingBundleException(bare_jid, device))
# Check for missing sessions and simulate the key exchange
for bare_jid, devices in encrypt_for.items():
key_exchange_problems = {}
# Load all sessions
sessions = yield self.__loadSessions(bare_jid, devices)
for device in devices:
session = sessions[device]
# If no session exists, create a new session
if session == None:
# Get the required bundle
bundle = bundles[bare_jid][device]
try:
# Build the session, discarding the result afterwards. This is
# just to check that the key exchange works.
self.__state.getSharedSecretActive(bundle)
except x3dh.exceptions.KeyExchangeException as e:
key_exchange_problems[device] = str(e)
encrypt_for[bare_jid] -= set(key_exchange_problems.keys())
for device, message in key_exchange_problems.items():
if not device in expect_problems.get(bare_jid, set()):
problems.append(KeyExchangeException(
bare_jid,
device,
message
))
if not ignore_trust:
# Check the trust for each device
for bare_jid, devices in encrypt_for.items():
# Load all trust
trusts = yield self.__loadTrusts(bare_jid, devices)
# Load all sessions
sessions = yield self.__loadSessions(bare_jid, devices)
trust_problems = []
for device in devices:
trust = trusts[device]
session = sessions[device]
# Get the identity key of the recipient
other_ik = (
bundles[bare_jid][device].ik
if session == None else
session.ik
)
if trust == None:
trust_problems.append((device, other_ik, "undecided"))
elif not (trust["key"] == other_ik and trust["trusted"]):
trust_problems.append((device, other_ik, "untrusted"))
devices -= set(map(lambda x: x[0], trust_problems))
for device, other_ik, problem_type in trust_problems:
if not device in expect_problems.get(bare_jid, set()):
problems.append(
TrustException(bare_jid, device, other_ik, problem_type)
)
# Check for jids with no eligible devices
for bare_jid, devices in list(encrypt_for.items()):
# Skip this check for my own bare jid
if bare_jid == self.__my_bare_jid:
continue
if len(devices) == 0:
problems.append(NoEligibleDevicesException(bare_jid))
del encrypt_for[bare_jid]
# If there were and problems, raise an Exception with a list of those.
if len(problems) > 0:
raise EncryptionProblemsException(problems)
##############
# encryption #
##############
# Prepare AES-GCM key and IV
aes_gcm_iv = os.urandom(16)
aes_gcm_key = os.urandom(16)
# Create the AES-GCM instance
aes_gcm = Cipher(
algorithms.AES(aes_gcm_key),
modes.GCM(aes_gcm_iv),
backend=default_backend()
).encryptor()
# Encrypt the plain data
encryption_callback(aes_gcm)
# Store the tag
aes_gcm_tag = aes_gcm.tag
# {
# [bare_jid: string] => {
# [device: int] => {
# "data" : bytes,
# "pre_key" : boolean
# }
# }
# }
encrypted_keys = {}
for bare_jid, devices in encrypt_for.items():
encrypted_keys[bare_jid] = {}
for device in devices:
# Note whether this is a response to a PreKeyMessage
if self.__state.hasBoundOTPK(bare_jid, device):
self.__state.respondedTo(bare_jid, device)
yield self._storage.storeState(self.__state.serialize())
# Load the session
session = yield self.__loadSession(bare_jid, device)
# If no session exists, this will be a PreKeyMessage
pre_key = session == None
# Create a new session
if pre_key:
# Get the required bundle
bundle = bundles[bare_jid][device]
# Build the session
session_and_init_data = self.__state.getSharedSecretActive(bundle)
session = session_and_init_data["dr"]
session_init_data = session_and_init_data["to_other"]
# Encrypt the AES GCM key and tag
encrypted_data = session.encryptMessage(aes_gcm_key + aes_gcm_tag)
# Store the new/changed session
yield self.__storeSession(bare_jid, device, session)
# Serialize the data into a simple message format
serialized = self.__backend.WireFormat.messageToWire(
encrypted_data["ciphertext"],
encrypted_data["header"],
{ "DoubleRatchet": encrypted_data["additional"] }
)
# If it is a PreKeyMessage, apply an additional step to the serialization.
if pre_key:
serialized = self.__backend.WireFormat.preKeyMessageToWire(
session_init_data,
serialized,
{ "DoubleRatchet": encrypted_data["additional"] }
)
# Add the final encrypted and serialized data.
encrypted_keys[bare_jid][device] = {
"data" : serialized,
"pre_key" : pre_key
}
promise.returnValue({
"iv" : aes_gcm_iv,
"sid" : self.__my_device_id,
"keys" : encrypted_keys
}) | python | def __encryptKeyTransportMessage(
self,
bare_jids,
encryption_callback,
bundles = None,
expect_problems = None,
ignore_trust = False
):
"""
bare_jids: iterable<string>
encryption_callback: A function which is called using an instance of cryptography.hazmat.primitives.ciphers.CipherContext, which you can use to encrypt any sort of data. You don't have to return anything.
bundles: { [bare_jid: string] => { [device_id: int] => ExtendedPublicBundle } }
expect_problems: { [bare_jid: string] => iterable<int> }
returns: {
iv: bytes,
sid: int,
keys: {
[bare_jid: string] => {
[device: int] => {
"data" : bytes,
"pre_key" : boolean
}
}
}
}
"""
yield self.runInactiveDeviceCleanup()
#########################
# parameter preparation #
#########################
if isinstance(bare_jids, string_type):
bare_jids = set([ bare_jids ])
else:
bare_jids = set(bare_jids)
if bundles == None:
bundles = {}
if expect_problems == None:
expect_problems = {}
else:
for bare_jid in expect_problems:
expect_problems[bare_jid] = set(expect_problems[bare_jid])
# Add the own bare jid to the set of jids
bare_jids.add(self.__my_bare_jid)
########################################################
# check all preconditions and prepare missing sessions #
########################################################
problems = []
# Prepare the lists of devices to encrypt for
encrypt_for = {}
for bare_jid in bare_jids:
devices = yield self.__loadActiveDevices(bare_jid)
if len(devices) == 0:
problems.append(NoDevicesException(bare_jid))
else:
encrypt_for[bare_jid] = devices
# Remove the sending devices from the list
encrypt_for[self.__my_bare_jid].remove(self.__my_device_id)
# Check whether all required bundles are available
for bare_jid, devices in encrypt_for.items():
missing_bundles = set()
# Load all sessions
sessions = yield self.__loadSessions(bare_jid, devices)
for device in devices:
session = sessions[device]
if session == None:
if not device in bundles.get(bare_jid, {}):
missing_bundles.add(device)
devices -= missing_bundles
for device in missing_bundles:
if not device in expect_problems.get(bare_jid, set()):
problems.append(MissingBundleException(bare_jid, device))
# Check for missing sessions and simulate the key exchange
for bare_jid, devices in encrypt_for.items():
key_exchange_problems = {}
# Load all sessions
sessions = yield self.__loadSessions(bare_jid, devices)
for device in devices:
session = sessions[device]
# If no session exists, create a new session
if session == None:
# Get the required bundle
bundle = bundles[bare_jid][device]
try:
# Build the session, discarding the result afterwards. This is
# just to check that the key exchange works.
self.__state.getSharedSecretActive(bundle)
except x3dh.exceptions.KeyExchangeException as e:
key_exchange_problems[device] = str(e)
encrypt_for[bare_jid] -= set(key_exchange_problems.keys())
for device, message in key_exchange_problems.items():
if not device in expect_problems.get(bare_jid, set()):
problems.append(KeyExchangeException(
bare_jid,
device,
message
))
if not ignore_trust:
# Check the trust for each device
for bare_jid, devices in encrypt_for.items():
# Load all trust
trusts = yield self.__loadTrusts(bare_jid, devices)
# Load all sessions
sessions = yield self.__loadSessions(bare_jid, devices)
trust_problems = []
for device in devices:
trust = trusts[device]
session = sessions[device]
# Get the identity key of the recipient
other_ik = (
bundles[bare_jid][device].ik
if session == None else
session.ik
)
if trust == None:
trust_problems.append((device, other_ik, "undecided"))
elif not (trust["key"] == other_ik and trust["trusted"]):
trust_problems.append((device, other_ik, "untrusted"))
devices -= set(map(lambda x: x[0], trust_problems))
for device, other_ik, problem_type in trust_problems:
if not device in expect_problems.get(bare_jid, set()):
problems.append(
TrustException(bare_jid, device, other_ik, problem_type)
)
# Check for jids with no eligible devices
for bare_jid, devices in list(encrypt_for.items()):
# Skip this check for my own bare jid
if bare_jid == self.__my_bare_jid:
continue
if len(devices) == 0:
problems.append(NoEligibleDevicesException(bare_jid))
del encrypt_for[bare_jid]
# If there were and problems, raise an Exception with a list of those.
if len(problems) > 0:
raise EncryptionProblemsException(problems)
##############
# encryption #
##############
# Prepare AES-GCM key and IV
aes_gcm_iv = os.urandom(16)
aes_gcm_key = os.urandom(16)
# Create the AES-GCM instance
aes_gcm = Cipher(
algorithms.AES(aes_gcm_key),
modes.GCM(aes_gcm_iv),
backend=default_backend()
).encryptor()
# Encrypt the plain data
encryption_callback(aes_gcm)
# Store the tag
aes_gcm_tag = aes_gcm.tag
# {
# [bare_jid: string] => {
# [device: int] => {
# "data" : bytes,
# "pre_key" : boolean
# }
# }
# }
encrypted_keys = {}
for bare_jid, devices in encrypt_for.items():
encrypted_keys[bare_jid] = {}
for device in devices:
# Note whether this is a response to a PreKeyMessage
if self.__state.hasBoundOTPK(bare_jid, device):
self.__state.respondedTo(bare_jid, device)
yield self._storage.storeState(self.__state.serialize())
# Load the session
session = yield self.__loadSession(bare_jid, device)
# If no session exists, this will be a PreKeyMessage
pre_key = session == None
# Create a new session
if pre_key:
# Get the required bundle
bundle = bundles[bare_jid][device]
# Build the session
session_and_init_data = self.__state.getSharedSecretActive(bundle)
session = session_and_init_data["dr"]
session_init_data = session_and_init_data["to_other"]
# Encrypt the AES GCM key and tag
encrypted_data = session.encryptMessage(aes_gcm_key + aes_gcm_tag)
# Store the new/changed session
yield self.__storeSession(bare_jid, device, session)
# Serialize the data into a simple message format
serialized = self.__backend.WireFormat.messageToWire(
encrypted_data["ciphertext"],
encrypted_data["header"],
{ "DoubleRatchet": encrypted_data["additional"] }
)
# If it is a PreKeyMessage, apply an additional step to the serialization.
if pre_key:
serialized = self.__backend.WireFormat.preKeyMessageToWire(
session_init_data,
serialized,
{ "DoubleRatchet": encrypted_data["additional"] }
)
# Add the final encrypted and serialized data.
encrypted_keys[bare_jid][device] = {
"data" : serialized,
"pre_key" : pre_key
}
promise.returnValue({
"iv" : aes_gcm_iv,
"sid" : self.__my_device_id,
"keys" : encrypted_keys
}) | [
"def",
"__encryptKeyTransportMessage",
"(",
"self",
",",
"bare_jids",
",",
"encryption_callback",
",",
"bundles",
"=",
"None",
",",
"expect_problems",
"=",
"None",
",",
"ignore_trust",
"=",
"False",
")",
":",
"yield",
"self",
".",
"runInactiveDeviceCleanup",
"(",
... | bare_jids: iterable<string>
encryption_callback: A function which is called using an instance of cryptography.hazmat.primitives.ciphers.CipherContext, which you can use to encrypt any sort of data. You don't have to return anything.
bundles: { [bare_jid: string] => { [device_id: int] => ExtendedPublicBundle } }
expect_problems: { [bare_jid: string] => iterable<int> }
returns: {
iv: bytes,
sid: int,
keys: {
[bare_jid: string] => {
[device: int] => {
"data" : bytes,
"pre_key" : boolean
}
}
}
} | [
"bare_jids",
":",
"iterable<string",
">",
"encryption_callback",
":",
"A",
"function",
"which",
"is",
"called",
"using",
"an",
"instance",
"of",
"cryptography",
".",
"hazmat",
".",
"primitives",
".",
"ciphers",
".",
"CipherContext",
"which",
"you",
"can",
"use",... | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L177-L437 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.deleteInactiveDevicesByQuota | def deleteInactiveDevicesByQuota(self, per_jid_max = 15, global_max = 0):
"""
Delete inactive devices by setting a quota. With per_jid_max you can define the
amount of inactive devices that are kept for each jid, with global_max you can
define a global maximum for inactive devices. If any of the quotas is reached,
inactive devices are deleted on an LRU basis. This also deletes the corresponding
sessions, so if a device comes active again and tries to send you an encrypted
message you will not be able to decrypt it.
The value "0" means no limitations/keep all inactive devices.
It is recommended to always restrict the amount of per-jid inactive devices. If
storage space limitations don't play a role, it is recommended to not restrict the
global amount of inactive devices. Otherwise, the global_max can be used to
control the amount of storage that can be used up by inactive sessions. The
default of 15 per-jid devices is very permissive, but it is not recommended to
decrease that number without a good reason.
This is the recommended way to handle inactive device deletion. For a time-based
alternative, look at the deleteInactiveDevicesByAge method.
"""
if per_jid_max < 1 and global_max < 1:
return
if per_jid_max < 1:
per_jid_max = None
if global_max < 1:
global_max = None
bare_jids = yield self._storage.listJIDs()
if not per_jid_max == None:
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
if len(devices) > per_jid_max:
# This sorts the devices from smaller to bigger timestamp, which means
# from old to young.
devices = sorted(devices.items(), key = lambda device: device[1])
# This gets the first (=oldest) n entries, so that only the
# per_jid_max youngest entries are left.
devices = devices[:-per_jid_max]
# Get the device ids and discard the timestamps.
devices = list(map(lambda device: device[0], devices))
yield self.__deleteInactiveDevices(bare_jid, devices)
if not global_max == None:
all_inactive_devices = []
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
all_inactive_devices.extend(map(
lambda device: (bare_jid, device[0], device[1]),
devices.items()
))
if len(all_inactive_devices) > global_max:
# This sorts the devices from smaller to bigger timestamp, which means
# from old to young.
devices = sorted(all_inactive_devices, key = lambda device: device[2])
# This gets the first (=oldest) n entries, so that only the global_max
# youngest entries are left.
devices = devices[:-global_max]
# Get the list of devices to delete for each jid
delete_devices = {}
for device in devices:
bare_jid = device[0]
device_id = device[1]
delete_devices[bare_jid] = delete_devices.get(bare_jid, [])
delete_devices[bare_jid].append(device_id)
# Now, delete the devices
for bare_jid, devices in delete_devices.items():
yield self.__deleteInactiveDevices(bare_jid, devices) | python | def deleteInactiveDevicesByQuota(self, per_jid_max = 15, global_max = 0):
"""
Delete inactive devices by setting a quota. With per_jid_max you can define the
amount of inactive devices that are kept for each jid, with global_max you can
define a global maximum for inactive devices. If any of the quotas is reached,
inactive devices are deleted on an LRU basis. This also deletes the corresponding
sessions, so if a device comes active again and tries to send you an encrypted
message you will not be able to decrypt it.
The value "0" means no limitations/keep all inactive devices.
It is recommended to always restrict the amount of per-jid inactive devices. If
storage space limitations don't play a role, it is recommended to not restrict the
global amount of inactive devices. Otherwise, the global_max can be used to
control the amount of storage that can be used up by inactive sessions. The
default of 15 per-jid devices is very permissive, but it is not recommended to
decrease that number without a good reason.
This is the recommended way to handle inactive device deletion. For a time-based
alternative, look at the deleteInactiveDevicesByAge method.
"""
if per_jid_max < 1 and global_max < 1:
return
if per_jid_max < 1:
per_jid_max = None
if global_max < 1:
global_max = None
bare_jids = yield self._storage.listJIDs()
if not per_jid_max == None:
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
if len(devices) > per_jid_max:
# This sorts the devices from smaller to bigger timestamp, which means
# from old to young.
devices = sorted(devices.items(), key = lambda device: device[1])
# This gets the first (=oldest) n entries, so that only the
# per_jid_max youngest entries are left.
devices = devices[:-per_jid_max]
# Get the device ids and discard the timestamps.
devices = list(map(lambda device: device[0], devices))
yield self.__deleteInactiveDevices(bare_jid, devices)
if not global_max == None:
all_inactive_devices = []
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
all_inactive_devices.extend(map(
lambda device: (bare_jid, device[0], device[1]),
devices.items()
))
if len(all_inactive_devices) > global_max:
# This sorts the devices from smaller to bigger timestamp, which means
# from old to young.
devices = sorted(all_inactive_devices, key = lambda device: device[2])
# This gets the first (=oldest) n entries, so that only the global_max
# youngest entries are left.
devices = devices[:-global_max]
# Get the list of devices to delete for each jid
delete_devices = {}
for device in devices:
bare_jid = device[0]
device_id = device[1]
delete_devices[bare_jid] = delete_devices.get(bare_jid, [])
delete_devices[bare_jid].append(device_id)
# Now, delete the devices
for bare_jid, devices in delete_devices.items():
yield self.__deleteInactiveDevices(bare_jid, devices) | [
"def",
"deleteInactiveDevicesByQuota",
"(",
"self",
",",
"per_jid_max",
"=",
"15",
",",
"global_max",
"=",
"0",
")",
":",
"if",
"per_jid_max",
"<",
"1",
"and",
"global_max",
"<",
"1",
":",
"return",
"if",
"per_jid_max",
"<",
"1",
":",
"per_jid_max",
"=",
... | Delete inactive devices by setting a quota. With per_jid_max you can define the
amount of inactive devices that are kept for each jid, with global_max you can
define a global maximum for inactive devices. If any of the quotas is reached,
inactive devices are deleted on an LRU basis. This also deletes the corresponding
sessions, so if a device comes active again and tries to send you an encrypted
message you will not be able to decrypt it.
The value "0" means no limitations/keep all inactive devices.
It is recommended to always restrict the amount of per-jid inactive devices. If
storage space limitations don't play a role, it is recommended to not restrict the
global amount of inactive devices. Otherwise, the global_max can be used to
control the amount of storage that can be used up by inactive sessions. The
default of 15 per-jid devices is very permissive, but it is not recommended to
decrease that number without a good reason.
This is the recommended way to handle inactive device deletion. For a time-based
alternative, look at the deleteInactiveDevicesByAge method. | [
"Delete",
"inactive",
"devices",
"by",
"setting",
"a",
"quota",
".",
"With",
"per_jid_max",
"you",
"can",
"define",
"the",
"amount",
"of",
"inactive",
"devices",
"that",
"are",
"kept",
"for",
"each",
"jid",
"with",
"global_max",
"you",
"can",
"define",
"a",
... | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L766-L849 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.deleteInactiveDevicesByAge | def deleteInactiveDevicesByAge(self, age_days):
"""
Delete all inactive devices from the device list storage and cache that are older
then a given number of days. This also deletes the corresponding sessions, so if
a device comes active again and tries to send you an encrypted message you will
not be able to decrypt it. You are not allowed to delete inactive devices that
were inactive for less than a day. Thus, the minimum value for age_days is 1.
It is recommended to keep inactive devices for a longer period of time (e.g.
multiple months), as it reduces the chance for message loss and doesn't require a
lot of storage.
The recommended alternative to deleting inactive devices by age is to delete them
by count/quota. Look at the deleteInactiveDevicesByQuota method for that variant.
"""
if age_days < 1:
return
now = time.time()
bare_jids = yield self._storage.listJIDs()
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
delete_devices = []
for device, timestamp in list(devices.items()):
elapsed_s = now - timestamp
elapsed_m = elapsed_s / 60
elapsed_h = elapsed_m / 60
elapsed_d = elapsed_h / 24
if elapsed_d >= age_days:
delete_devices.append(device)
if len(delete_devices) > 0:
yield self.__deleteInactiveDevices(bare_jid, delete_devices) | python | def deleteInactiveDevicesByAge(self, age_days):
"""
Delete all inactive devices from the device list storage and cache that are older
then a given number of days. This also deletes the corresponding sessions, so if
a device comes active again and tries to send you an encrypted message you will
not be able to decrypt it. You are not allowed to delete inactive devices that
were inactive for less than a day. Thus, the minimum value for age_days is 1.
It is recommended to keep inactive devices for a longer period of time (e.g.
multiple months), as it reduces the chance for message loss and doesn't require a
lot of storage.
The recommended alternative to deleting inactive devices by age is to delete them
by count/quota. Look at the deleteInactiveDevicesByQuota method for that variant.
"""
if age_days < 1:
return
now = time.time()
bare_jids = yield self._storage.listJIDs()
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
delete_devices = []
for device, timestamp in list(devices.items()):
elapsed_s = now - timestamp
elapsed_m = elapsed_s / 60
elapsed_h = elapsed_m / 60
elapsed_d = elapsed_h / 24
if elapsed_d >= age_days:
delete_devices.append(device)
if len(delete_devices) > 0:
yield self.__deleteInactiveDevices(bare_jid, delete_devices) | [
"def",
"deleteInactiveDevicesByAge",
"(",
"self",
",",
"age_days",
")",
":",
"if",
"age_days",
"<",
"1",
":",
"return",
"now",
"=",
"time",
".",
"time",
"(",
")",
"bare_jids",
"=",
"yield",
"self",
".",
"_storage",
".",
"listJIDs",
"(",
")",
"for",
"ba... | Delete all inactive devices from the device list storage and cache that are older
then a given number of days. This also deletes the corresponding sessions, so if
a device comes active again and tries to send you an encrypted message you will
not be able to decrypt it. You are not allowed to delete inactive devices that
were inactive for less than a day. Thus, the minimum value for age_days is 1.
It is recommended to keep inactive devices for a longer period of time (e.g.
multiple months), as it reduces the chance for message loss and doesn't require a
lot of storage.
The recommended alternative to deleting inactive devices by age is to delete them
by count/quota. Look at the deleteInactiveDevicesByQuota method for that variant. | [
"Delete",
"all",
"inactive",
"devices",
"from",
"the",
"device",
"list",
"storage",
"and",
"cache",
"that",
"are",
"older",
"then",
"a",
"given",
"number",
"of",
"days",
".",
"This",
"also",
"deletes",
"the",
"corresponding",
"sessions",
"so",
"if",
"a",
"... | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L852-L889 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.runInactiveDeviceCleanup | def runInactiveDeviceCleanup(self):
"""
Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota
methods with the configuration that was set when calling create.
"""
yield self.deleteInactiveDevicesByQuota(
self.__inactive_per_jid_max,
self.__inactive_global_max
)
yield self.deleteInactiveDevicesByAge(self.__inactive_max_age) | python | def runInactiveDeviceCleanup(self):
"""
Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota
methods with the configuration that was set when calling create.
"""
yield self.deleteInactiveDevicesByQuota(
self.__inactive_per_jid_max,
self.__inactive_global_max
)
yield self.deleteInactiveDevicesByAge(self.__inactive_max_age) | [
"def",
"runInactiveDeviceCleanup",
"(",
"self",
")",
":",
"yield",
"self",
".",
"deleteInactiveDevicesByQuota",
"(",
"self",
".",
"__inactive_per_jid_max",
",",
"self",
".",
"__inactive_global_max",
")",
"yield",
"self",
".",
"deleteInactiveDevicesByAge",
"(",
"self",... | Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota
methods with the configuration that was set when calling create. | [
"Runs",
"both",
"the",
"deleteInactiveDevicesByAge",
"and",
"the",
"deleteInactiveDevicesByQuota",
"methods",
"with",
"the",
"configuration",
"that",
"was",
"set",
"when",
"calling",
"create",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L892-L903 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.getTrustForJID | def getTrustForJID(self, bare_jid):
"""
All-in-one trust information for all devices of a bare jid.
The result is structured like this:
{
"active" : { device: int => trust_info }
"inactive" : { device: int => trust_info }
}
where trust_info is the structure returned by getTrustForDevice.
"""
result = {
"active" : {},
"inactive" : {}
}
devices = yield self.__loadActiveDevices(bare_jid)
for device in devices:
result["active"][device] = yield self.getTrustForDevice(bare_jid, device)
devices = yield self.__loadInactiveDevices(bare_jid)
for device in devices:
result["inactive"][device] = yield self.getTrustForDevice(bare_jid, device)
promise.returnValue(result) | python | def getTrustForJID(self, bare_jid):
"""
All-in-one trust information for all devices of a bare jid.
The result is structured like this:
{
"active" : { device: int => trust_info }
"inactive" : { device: int => trust_info }
}
where trust_info is the structure returned by getTrustForDevice.
"""
result = {
"active" : {},
"inactive" : {}
}
devices = yield self.__loadActiveDevices(bare_jid)
for device in devices:
result["active"][device] = yield self.getTrustForDevice(bare_jid, device)
devices = yield self.__loadInactiveDevices(bare_jid)
for device in devices:
result["inactive"][device] = yield self.getTrustForDevice(bare_jid, device)
promise.returnValue(result) | [
"def",
"getTrustForJID",
"(",
"self",
",",
"bare_jid",
")",
":",
"result",
"=",
"{",
"\"active\"",
":",
"{",
"}",
",",
"\"inactive\"",
":",
"{",
"}",
"}",
"devices",
"=",
"yield",
"self",
".",
"__loadActiveDevices",
"(",
"bare_jid",
")",
"for",
"device",... | All-in-one trust information for all devices of a bare jid.
The result is structured like this:
{
"active" : { device: int => trust_info }
"inactive" : { device: int => trust_info }
}
where trust_info is the structure returned by getTrustForDevice. | [
"All",
"-",
"in",
"-",
"one",
"trust",
"information",
"for",
"all",
"devices",
"of",
"a",
"bare",
"jid",
".",
"The",
"result",
"is",
"structured",
"like",
"this",
":"
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L998-L1026 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.deleteJID | def deleteJID(self, bare_jid):
"""
Delete all data associated with a JID. This includes the list of active/inactive
devices, all sessions with that JID and all information about trusted keys.
"""
yield self.runInactiveDeviceCleanup()
self.__sessions_cache.pop(bare_jid, None)
self.__devices_cache.pop(bare_jid, None)
self.__trust_cache.pop(bare_jid, None)
yield self._storage.deleteJID(bare_jid) | python | def deleteJID(self, bare_jid):
"""
Delete all data associated with a JID. This includes the list of active/inactive
devices, all sessions with that JID and all information about trusted keys.
"""
yield self.runInactiveDeviceCleanup()
self.__sessions_cache.pop(bare_jid, None)
self.__devices_cache.pop(bare_jid, None)
self.__trust_cache.pop(bare_jid, None)
yield self._storage.deleteJID(bare_jid) | [
"def",
"deleteJID",
"(",
"self",
",",
"bare_jid",
")",
":",
"yield",
"self",
".",
"runInactiveDeviceCleanup",
"(",
")",
"self",
".",
"__sessions_cache",
".",
"pop",
"(",
"bare_jid",
",",
"None",
")",
"self",
".",
"__devices_cache",
".",
"pop",
"(",
"bare_j... | Delete all data associated with a JID. This includes the list of active/inactive
devices, all sessions with that JID and all information about trusted keys. | [
"Delete",
"all",
"data",
"associated",
"with",
"a",
"JID",
".",
"This",
"includes",
"the",
"list",
"of",
"active",
"/",
"inactive",
"devices",
"all",
"sessions",
"with",
"that",
"JID",
"and",
"all",
"information",
"about",
"trusted",
"keys",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L1036-L1048 |
pjmark/NIMPA | resources/resources.py | get_setup | def get_setup(Cnt = {}):
'''Return a dictionary of GPU, mu-map hardware and third party set-up.'''
# the name of the folder for NiftyPET tools
Cnt['DIRTOOLS'] = DIRTOOLS
# additional paramteres for compiling tools with cmake
Cnt['CMAKE_TLS_PAR'] = CMAKE_TLS_PAR
# hardware mu-maps
Cnt['HMULIST'] = hrdwr_mu
# Microsoft Visual Studio Compiler version
Cnt['MSVC_VRSN'] = MSVC_VRSN
# GPU related setup
Cnt = get_gpu_constants(Cnt)
if 'PATHTOOLS' in globals() and PATHTOOLS!='': Cnt['PATHTOOLS'] = PATHTOOLS
# image processing setup
if 'RESPATH' in globals() and RESPATH!='': Cnt['RESPATH'] = RESPATH
if 'REGPATH' in globals() and REGPATH!='': Cnt['REGPATH'] = REGPATH
if 'DCM2NIIX' in globals() and DCM2NIIX!='': Cnt['DCM2NIIX'] = DCM2NIIX
# hardware mu-maps
if 'HMUDIR' in globals() and HMUDIR!='': Cnt['HMUDIR'] = HMUDIR
if 'VINCIPATH' in globals() and VINCIPATH!='': Cnt['VINCIPATH'] = VINCIPATH
Cnt['ENBLXNAT'] = ENBLXNAT
Cnt['ENBLAGG'] = ENBLAGG
Cnt['CMPL_DCM2NIIX'] = CMPL_DCM2NIIX
return Cnt | python | def get_setup(Cnt = {}):
'''Return a dictionary of GPU, mu-map hardware and third party set-up.'''
# the name of the folder for NiftyPET tools
Cnt['DIRTOOLS'] = DIRTOOLS
# additional paramteres for compiling tools with cmake
Cnt['CMAKE_TLS_PAR'] = CMAKE_TLS_PAR
# hardware mu-maps
Cnt['HMULIST'] = hrdwr_mu
# Microsoft Visual Studio Compiler version
Cnt['MSVC_VRSN'] = MSVC_VRSN
# GPU related setup
Cnt = get_gpu_constants(Cnt)
if 'PATHTOOLS' in globals() and PATHTOOLS!='': Cnt['PATHTOOLS'] = PATHTOOLS
# image processing setup
if 'RESPATH' in globals() and RESPATH!='': Cnt['RESPATH'] = RESPATH
if 'REGPATH' in globals() and REGPATH!='': Cnt['REGPATH'] = REGPATH
if 'DCM2NIIX' in globals() and DCM2NIIX!='': Cnt['DCM2NIIX'] = DCM2NIIX
# hardware mu-maps
if 'HMUDIR' in globals() and HMUDIR!='': Cnt['HMUDIR'] = HMUDIR
if 'VINCIPATH' in globals() and VINCIPATH!='': Cnt['VINCIPATH'] = VINCIPATH
Cnt['ENBLXNAT'] = ENBLXNAT
Cnt['ENBLAGG'] = ENBLAGG
Cnt['CMPL_DCM2NIIX'] = CMPL_DCM2NIIX
return Cnt | [
"def",
"get_setup",
"(",
"Cnt",
"=",
"{",
"}",
")",
":",
"# the name of the folder for NiftyPET tools",
"Cnt",
"[",
"'DIRTOOLS'",
"]",
"=",
"DIRTOOLS",
"# additional paramteres for compiling tools with cmake",
"Cnt",
"[",
"'CMAKE_TLS_PAR'",
"]",
"=",
"CMAKE_TLS_PAR",
"#... | Return a dictionary of GPU, mu-map hardware and third party set-up. | [
"Return",
"a",
"dictionary",
"of",
"GPU",
"mu",
"-",
"map",
"hardware",
"and",
"third",
"party",
"set",
"-",
"up",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/resources/resources.py#L247-L278 |
pjmark/NIMPA | resources/resources.py | get_mmr_constants | def get_mmr_constants():
'''
Put all the constants together in a dictionary
'''
Cnt = {
'ISOTOPE':'F18',
'DCYCRR':DCYCRR,
'ALPHA':ALPHA,
'NRNG':NRNG,
'NSRNG':NSRNG,
'NCRS':NCRS,
'NCRSR':NCRSR,
'NBCKT':224,
'NSANGLES':A,
'NSBINS':W,
'Naw':-1, # number of total active bins per 2D sino
'NSN11': NSN11, # number of sinos in span-11
'NSN1': NSN1, # number of sinos in span-1
'NSN64': NSN64, # number of sinos in span-1 with no MRD limit
'MRD': MRD, # maximum ring difference RD
'SPN':SPAN, # span-1 (1), span-11 (11), ssrb (0)
'TFOV2':TFOV2, # squared radius of TFOV
'RNG_STRT':RNG_STRT, # limit axial extension by defining start and end ring
'RNG_END' :RNG_END, # this feature only works with span-1 processing (Cnt['SPN']=1)
'SS_IMZ':SS_IMZ, #Scatter mu-map iamge size
'SS_IMY':SS_IMY,
'SS_IMX':SS_IMX,
'SS_VXZ':SS_VXZ,
'SS_VXY':SS_VXY,
'IS_VXZ':IS_VXZ,
'SSE_IMZ':SSE_IMZ, #Scatter emission image size
'SSE_IMY':SSE_IMY,
'SSE_IMX':SSE_IMX,
'SSE_VXZ':SSE_VXZ,
'SSE_VXY':SSE_VXY,
'SZ_IMZ':SZ_IMZ, #GPU optimised image size
'SZ_IMY':SZ_IMY,
'SZ_IMX':SZ_IMX,
'SZ_VOXZ':SZ_VOXZ,
'SZ_VOXY':SZ_VOXY,
'SZ_VOXZi':SZ_VOXZi,
'SO_IMZ':SO_IMZ, #Original image size (from Siemens)
'SO_IMY':SO_IMY,
'SO_IMX':SO_IMX,
'SO_VXZ':SO_VXZ,
'SO_VXY':SO_VXY,
'SO_VXX':SO_VXX,
'NSEG0':SEG0,
'RE':RE, #effective ring radius
'R':R,
'SEG':seg,
'MNRD':minrd,
'MXRD':maxrd,
'SCTRNG':sct_irng,
'TGAP':TGAP,
'OFFGAP':OFFGAP,
'AXR':AXR,
'R02':R02, #squared electron radius
'LLD':LLD, #lower energy threashold
'E511':E511,
'ER':ER, #energy resolution
'COSUPSMX':COSUPSMX, #cosine of max allowed scatter angle
'NCOS':NCOS, #number of cos samples for LUT
'COSSTP':COSSTP, #cosine step
'ICOSSTP':ICOSSTP, #inverse of cosine step
'ETHRLD':ETHRLD, #intensity emission image threshold (used in scatter modelling)
'CLGHT':CLGHT, #speed of light [cm/s]
'CWND':CWND, #coincidence time window [ps]
'TOFBINN':TOFBINN, #number of TOF bins
'TOFBINS':TOFBINS, #TOF bin width [ps]
'TOFBIND':TOFBIND,
'ITOFBIND':ITOFBIND,
# affine and image size for the reconstructed image, assuming the centre of voxels in mm
'AFFINE':np.array([ [-10*SO_VXX, 0., 0., 5.*SO_IMX*SO_VXX ], #+5.*SO_VXX
[0., 10*SO_VXY, 0., -5.*SO_IMY*SO_VXY ], #+5.*SO_VXY
[0., 0., 10*SO_VXZ, -5.*SO_IMZ*SO_VXZ ], #-5.*SO_VXZ
[0., 0., 0., 1.]]),
'IMSIZE':np.array([SO_IMZ, SO_IMY, SO_IMX]),
'BTP':0, #1:non parametric bootstrap, 2: parametric bootstrap (recommended)
'BTPRT':1.0, # Ratio of bootstrapped/original events (enables downsampling)
'VERBOSE':False,
'SCTSCLEM':SCTSCLEM,
'SCTSCLMU':SCTSCLMU,
}
# get the setup for GPU and third party apps
Cnt = get_setup(Cnt=Cnt)
return Cnt | python | def get_mmr_constants():
'''
Put all the constants together in a dictionary
'''
Cnt = {
'ISOTOPE':'F18',
'DCYCRR':DCYCRR,
'ALPHA':ALPHA,
'NRNG':NRNG,
'NSRNG':NSRNG,
'NCRS':NCRS,
'NCRSR':NCRSR,
'NBCKT':224,
'NSANGLES':A,
'NSBINS':W,
'Naw':-1, # number of total active bins per 2D sino
'NSN11': NSN11, # number of sinos in span-11
'NSN1': NSN1, # number of sinos in span-1
'NSN64': NSN64, # number of sinos in span-1 with no MRD limit
'MRD': MRD, # maximum ring difference RD
'SPN':SPAN, # span-1 (1), span-11 (11), ssrb (0)
'TFOV2':TFOV2, # squared radius of TFOV
'RNG_STRT':RNG_STRT, # limit axial extension by defining start and end ring
'RNG_END' :RNG_END, # this feature only works with span-1 processing (Cnt['SPN']=1)
'SS_IMZ':SS_IMZ, #Scatter mu-map iamge size
'SS_IMY':SS_IMY,
'SS_IMX':SS_IMX,
'SS_VXZ':SS_VXZ,
'SS_VXY':SS_VXY,
'IS_VXZ':IS_VXZ,
'SSE_IMZ':SSE_IMZ, #Scatter emission image size
'SSE_IMY':SSE_IMY,
'SSE_IMX':SSE_IMX,
'SSE_VXZ':SSE_VXZ,
'SSE_VXY':SSE_VXY,
'SZ_IMZ':SZ_IMZ, #GPU optimised image size
'SZ_IMY':SZ_IMY,
'SZ_IMX':SZ_IMX,
'SZ_VOXZ':SZ_VOXZ,
'SZ_VOXY':SZ_VOXY,
'SZ_VOXZi':SZ_VOXZi,
'SO_IMZ':SO_IMZ, #Original image size (from Siemens)
'SO_IMY':SO_IMY,
'SO_IMX':SO_IMX,
'SO_VXZ':SO_VXZ,
'SO_VXY':SO_VXY,
'SO_VXX':SO_VXX,
'NSEG0':SEG0,
'RE':RE, #effective ring radius
'R':R,
'SEG':seg,
'MNRD':minrd,
'MXRD':maxrd,
'SCTRNG':sct_irng,
'TGAP':TGAP,
'OFFGAP':OFFGAP,
'AXR':AXR,
'R02':R02, #squared electron radius
'LLD':LLD, #lower energy threashold
'E511':E511,
'ER':ER, #energy resolution
'COSUPSMX':COSUPSMX, #cosine of max allowed scatter angle
'NCOS':NCOS, #number of cos samples for LUT
'COSSTP':COSSTP, #cosine step
'ICOSSTP':ICOSSTP, #inverse of cosine step
'ETHRLD':ETHRLD, #intensity emission image threshold (used in scatter modelling)
'CLGHT':CLGHT, #speed of light [cm/s]
'CWND':CWND, #coincidence time window [ps]
'TOFBINN':TOFBINN, #number of TOF bins
'TOFBINS':TOFBINS, #TOF bin width [ps]
'TOFBIND':TOFBIND,
'ITOFBIND':ITOFBIND,
# affine and image size for the reconstructed image, assuming the centre of voxels in mm
'AFFINE':np.array([ [-10*SO_VXX, 0., 0., 5.*SO_IMX*SO_VXX ], #+5.*SO_VXX
[0., 10*SO_VXY, 0., -5.*SO_IMY*SO_VXY ], #+5.*SO_VXY
[0., 0., 10*SO_VXZ, -5.*SO_IMZ*SO_VXZ ], #-5.*SO_VXZ
[0., 0., 0., 1.]]),
'IMSIZE':np.array([SO_IMZ, SO_IMY, SO_IMX]),
'BTP':0, #1:non parametric bootstrap, 2: parametric bootstrap (recommended)
'BTPRT':1.0, # Ratio of bootstrapped/original events (enables downsampling)
'VERBOSE':False,
'SCTSCLEM':SCTSCLEM,
'SCTSCLMU':SCTSCLMU,
}
# get the setup for GPU and third party apps
Cnt = get_setup(Cnt=Cnt)
return Cnt | [
"def",
"get_mmr_constants",
"(",
")",
":",
"Cnt",
"=",
"{",
"'ISOTOPE'",
":",
"'F18'",
",",
"'DCYCRR'",
":",
"DCYCRR",
",",
"'ALPHA'",
":",
"ALPHA",
",",
"'NRNG'",
":",
"NRNG",
",",
"'NSRNG'",
":",
"NSRNG",
",",
"'NCRS'",
":",
"NCRS",
",",
"'NCRSR'",
... | Put all the constants together in a dictionary | [
"Put",
"all",
"the",
"constants",
"together",
"in",
"a",
"dictionary"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/resources/resources.py#L281-L376 |
pjmark/NIMPA | install_tools.py | check_version | def check_version(Cnt, chcklst=['RESPATH','REGPATH','DCM2NIIX','HMUDIR']):
''' Check version and existence of all third-party software and input data.
Output a dictionary with bool type of the requested bits in 'chcklst'
'''
# at start, assume that nothing is present yet
output = {}
for itm in chcklst:
output[itm] = False
# niftyreg reg_resample first
if 'RESPATH' in chcklst and 'RESPATH' in Cnt:
try:
proc = Popen([Cnt['RESPATH'], '--version'], stdout=PIPE)
out = proc.stdout.read()
if reg_ver in out:
output['RESPATH'] = True
except OSError:
print 'e> NiftyReg (reg_resample) either is NOT installed or is corrupt.'
# niftyreg reg_aladin
if 'REGPATH' in chcklst and 'REGPATH' in Cnt:
try:
proc = Popen([Cnt['REGPATH'], '--version'], stdout=PIPE)
out = proc.stdout.read()
if reg_ver in out:
output['REGPATH'] = True
except OSError:
print 'e> NiftyReg (reg_aladin) either is NOT installed or is corrupt.'
# dcm2niix
if 'DCM2NIIX' in chcklst and 'DCM2NIIX' in Cnt:
try:
proc = Popen([Cnt['DCM2NIIX'], '-h'], stdout=PIPE)
out = proc.stdout.read()
ver_str = re.search('(?<=dcm2niiX version v)\d{1,2}.\d{1,2}.\d*', out)
if ver_str and dcm_ver in ver_str.group(0):
output['DCM2NIIX'] = True
except OSError:
print 'e> dcm2niix either is NOT installed or is corrupt.'
# hdw mu-map list
if 'HMUDIR' in chcklst and 'HMUDIR' in Cnt:
for hi in Cnt['HMULIST']:
if os.path.isfile(os.path.join(Cnt['HMUDIR'],hi)):
output['HMUDIR'] = True
else:
output['HMUDIR'] = False
break
return output | python | def check_version(Cnt, chcklst=['RESPATH','REGPATH','DCM2NIIX','HMUDIR']):
''' Check version and existence of all third-party software and input data.
Output a dictionary with bool type of the requested bits in 'chcklst'
'''
# at start, assume that nothing is present yet
output = {}
for itm in chcklst:
output[itm] = False
# niftyreg reg_resample first
if 'RESPATH' in chcklst and 'RESPATH' in Cnt:
try:
proc = Popen([Cnt['RESPATH'], '--version'], stdout=PIPE)
out = proc.stdout.read()
if reg_ver in out:
output['RESPATH'] = True
except OSError:
print 'e> NiftyReg (reg_resample) either is NOT installed or is corrupt.'
# niftyreg reg_aladin
if 'REGPATH' in chcklst and 'REGPATH' in Cnt:
try:
proc = Popen([Cnt['REGPATH'], '--version'], stdout=PIPE)
out = proc.stdout.read()
if reg_ver in out:
output['REGPATH'] = True
except OSError:
print 'e> NiftyReg (reg_aladin) either is NOT installed or is corrupt.'
# dcm2niix
if 'DCM2NIIX' in chcklst and 'DCM2NIIX' in Cnt:
try:
proc = Popen([Cnt['DCM2NIIX'], '-h'], stdout=PIPE)
out = proc.stdout.read()
ver_str = re.search('(?<=dcm2niiX version v)\d{1,2}.\d{1,2}.\d*', out)
if ver_str and dcm_ver in ver_str.group(0):
output['DCM2NIIX'] = True
except OSError:
print 'e> dcm2niix either is NOT installed or is corrupt.'
# hdw mu-map list
if 'HMUDIR' in chcklst and 'HMUDIR' in Cnt:
for hi in Cnt['HMULIST']:
if os.path.isfile(os.path.join(Cnt['HMUDIR'],hi)):
output['HMUDIR'] = True
else:
output['HMUDIR'] = False
break
return output | [
"def",
"check_version",
"(",
"Cnt",
",",
"chcklst",
"=",
"[",
"'RESPATH'",
",",
"'REGPATH'",
",",
"'DCM2NIIX'",
",",
"'HMUDIR'",
"]",
")",
":",
"# at start, assume that nothing is present yet",
"output",
"=",
"{",
"}",
"for",
"itm",
"in",
"chcklst",
":",
"outp... | Check version and existence of all third-party software and input data.
Output a dictionary with bool type of the requested bits in 'chcklst' | [
"Check",
"version",
"and",
"existence",
"of",
"all",
"third",
"-",
"party",
"software",
"and",
"input",
"data",
".",
"Output",
"a",
"dictionary",
"with",
"bool",
"type",
"of",
"the",
"requested",
"bits",
"in",
"chcklst"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/install_tools.py#L120-L170 |
pjmark/NIMPA | install_tools.py | install_tool | def install_tool(app, Cnt):
''' Install the requested software from the git 'repo'
and check out the version given by 'sha1'.
'''
# get the current working directory
cwd = os.getcwd()
# pick the target installation folder for tools
if 'PATHTOOLS' in Cnt and Cnt['PATHTOOLS']!='':
path_tools = Cnt['PATHTOOLS']
elif ('PATHTOOLS' not in Cnt or Cnt['PATHTOOLS']!=''):
if 'DISPLAY' in os.environ and platform.system() in ['Linux', 'Windows']:
print '>>>>> DISPLAY', os.environ['DISPLAY']
Tk().withdraw()
dircore = askdirectory(title='choose a place for NiftyPET tools', initialdir=os.path.expanduser('~'))
Tk().destroy()
# get the full (combined path)
path_tools = os.path.join(dircore, Cnt['DIRTOOLS'])
else:
try:
path_tools = input_path('Enter path for NiftyPET tools (registration, etc):')
except:
print 'enter the intended PATHTOOLS in resources.py located in ~/.niftypet/'
raise ValueError('\n e> could not get the path for NiftyPET_tools \n')
Cnt['PATHTOOLS'] = path_tools
else:
if platform.system() == 'Linux' :
path_tools = os.path.join( os.path.expanduser('~'), Cnt['DIRTOOLS'] )
elif platform.system() == 'Windows' :
path_tools = os.path.join( os.getenv('LOCALAPPDATA'), Cnt['DIRTOOLS'] )
else:
print '\n=========================================================='
print 'e> only Linux and Windows operating systems are supported!'
print '==========================================================\n'
raise SystemError('OS not supported!')
Cnt['PATHTOOLS'] = path_tools
#create the main tools folder
if not os.path.isdir(path_tools):
os.mkdir(path_tools)
# identify the specific path for the requested app
if app=='niftyreg':
repo = repo_reg
sha1 = sha1_reg
path = os.path.join(path_tools, 'niftyreg')
elif app=='dcm2niix':
repo = repo_dcm
sha1 = sha1_dcm
path = os.path.join(path_tools, 'dcm2niix')
if not Cnt['CMPL_DCM2NIIX']:
# avoid installing from source, instead download the full version:
Cnt = download_dcm2niix(Cnt, path)
return Cnt
# Check if the source folder exists and delete it, if it does
if os.path.isdir(path): shutil.rmtree(path)
# Create an empty folder and enter it
os.mkdir(path)
os.chdir(path)
# clone the git repository
call(['git', 'clone', repo, dirsrc])
os.chdir(dirsrc)
print 'i> checking out the specific git version of the software...'
call(['git', 'checkout', sha1])
os.chdir('../')
# create the building folder
if not os.path.isdir(dirbld):
os.mkdir(dirbld)
# go inside the build folder
os.chdir(dirbld)
# run cmake with arguments
if platform.system()=='Windows':
cmd = ['cmake', '../'+dirsrc,
'-DBUILD_ALL_DEP=ON',
'-DCMAKE_INSTALL_PREFIX='+path,
'-G', Cnt['MSVC_VRSN']]
call(cmd)
call(['cmake', '--build', './', '--config', 'Release', '--target', 'install'])
elif platform.system() in ['Linux', 'Darwin']:
cmd = ['cmake', '../'+dirsrc,
'-DBUILD_ALL_DEP=ON',
'-DCMAKE_INSTALL_PREFIX='+path]
if Cnt['CMAKE_TLS_PAR']!='': cmd.append(Cnt['CMAKE_TLS_PAR'])
call(cmd)
call(
['cmake', '--build', './',
'--config', 'Release',
'--target', 'install',
'--','-j', str(ncpu)]
)
# restore the current working directory
os.chdir(cwd)
if app=='niftyreg':
try:
Cnt['RESPATH'] = glob.glob(os.path.join(os.path.join(path,'bin'), 'reg_resample*'))[0]
Cnt['REGPATH'] = glob.glob(os.path.join(os.path.join(path,'bin'), 'reg_aladin*'))[0]
except IndexError:
print 'e> NiftyReg has NOT been successfully installed.'
raise SystemError('Failed Installation (NiftyReg)')
# updated the file resources.py
Cnt = update_resources(Cnt)
# check the installation:
chck_niftyreg = check_version(Cnt, chcklst=['RESPATH','REGPATH'])
if not all([chck_niftyreg[k] for k in chck_niftyreg.keys()]):
print 'e> NiftyReg has NOT been successfully installed.'
raise SystemError('Failed Installation (NiftyReg)')
elif app=='dcm2niix':
try:
Cnt['DCM2NIIX'] = glob.glob(os.path.join(os.path.join(path,'bin'), 'dcm2niix*'))[0]
except IndexError:
print 'e> dcm2niix has NOT been successfully installed.'
Cnt = download_dcm2niix(Cnt, path)
# check the installation:
if not check_version(Cnt, chcklst=['DCM2NIIX']):
print 'e> dcm2niix has NOT been successfully compiled from github.'
Cnt = download_dcm2niix(Cnt, path)
return Cnt | python | def install_tool(app, Cnt):
''' Install the requested software from the git 'repo'
and check out the version given by 'sha1'.
'''
# get the current working directory
cwd = os.getcwd()
# pick the target installation folder for tools
if 'PATHTOOLS' in Cnt and Cnt['PATHTOOLS']!='':
path_tools = Cnt['PATHTOOLS']
elif ('PATHTOOLS' not in Cnt or Cnt['PATHTOOLS']!=''):
if 'DISPLAY' in os.environ and platform.system() in ['Linux', 'Windows']:
print '>>>>> DISPLAY', os.environ['DISPLAY']
Tk().withdraw()
dircore = askdirectory(title='choose a place for NiftyPET tools', initialdir=os.path.expanduser('~'))
Tk().destroy()
# get the full (combined path)
path_tools = os.path.join(dircore, Cnt['DIRTOOLS'])
else:
try:
path_tools = input_path('Enter path for NiftyPET tools (registration, etc):')
except:
print 'enter the intended PATHTOOLS in resources.py located in ~/.niftypet/'
raise ValueError('\n e> could not get the path for NiftyPET_tools \n')
Cnt['PATHTOOLS'] = path_tools
else:
if platform.system() == 'Linux' :
path_tools = os.path.join( os.path.expanduser('~'), Cnt['DIRTOOLS'] )
elif platform.system() == 'Windows' :
path_tools = os.path.join( os.getenv('LOCALAPPDATA'), Cnt['DIRTOOLS'] )
else:
print '\n=========================================================='
print 'e> only Linux and Windows operating systems are supported!'
print '==========================================================\n'
raise SystemError('OS not supported!')
Cnt['PATHTOOLS'] = path_tools
#create the main tools folder
if not os.path.isdir(path_tools):
os.mkdir(path_tools)
# identify the specific path for the requested app
if app=='niftyreg':
repo = repo_reg
sha1 = sha1_reg
path = os.path.join(path_tools, 'niftyreg')
elif app=='dcm2niix':
repo = repo_dcm
sha1 = sha1_dcm
path = os.path.join(path_tools, 'dcm2niix')
if not Cnt['CMPL_DCM2NIIX']:
# avoid installing from source, instead download the full version:
Cnt = download_dcm2niix(Cnt, path)
return Cnt
# Check if the source folder exists and delete it, if it does
if os.path.isdir(path): shutil.rmtree(path)
# Create an empty folder and enter it
os.mkdir(path)
os.chdir(path)
# clone the git repository
call(['git', 'clone', repo, dirsrc])
os.chdir(dirsrc)
print 'i> checking out the specific git version of the software...'
call(['git', 'checkout', sha1])
os.chdir('../')
# create the building folder
if not os.path.isdir(dirbld):
os.mkdir(dirbld)
# go inside the build folder
os.chdir(dirbld)
# run cmake with arguments
if platform.system()=='Windows':
cmd = ['cmake', '../'+dirsrc,
'-DBUILD_ALL_DEP=ON',
'-DCMAKE_INSTALL_PREFIX='+path,
'-G', Cnt['MSVC_VRSN']]
call(cmd)
call(['cmake', '--build', './', '--config', 'Release', '--target', 'install'])
elif platform.system() in ['Linux', 'Darwin']:
cmd = ['cmake', '../'+dirsrc,
'-DBUILD_ALL_DEP=ON',
'-DCMAKE_INSTALL_PREFIX='+path]
if Cnt['CMAKE_TLS_PAR']!='': cmd.append(Cnt['CMAKE_TLS_PAR'])
call(cmd)
call(
['cmake', '--build', './',
'--config', 'Release',
'--target', 'install',
'--','-j', str(ncpu)]
)
# restore the current working directory
os.chdir(cwd)
if app=='niftyreg':
try:
Cnt['RESPATH'] = glob.glob(os.path.join(os.path.join(path,'bin'), 'reg_resample*'))[0]
Cnt['REGPATH'] = glob.glob(os.path.join(os.path.join(path,'bin'), 'reg_aladin*'))[0]
except IndexError:
print 'e> NiftyReg has NOT been successfully installed.'
raise SystemError('Failed Installation (NiftyReg)')
# updated the file resources.py
Cnt = update_resources(Cnt)
# check the installation:
chck_niftyreg = check_version(Cnt, chcklst=['RESPATH','REGPATH'])
if not all([chck_niftyreg[k] for k in chck_niftyreg.keys()]):
print 'e> NiftyReg has NOT been successfully installed.'
raise SystemError('Failed Installation (NiftyReg)')
elif app=='dcm2niix':
try:
Cnt['DCM2NIIX'] = glob.glob(os.path.join(os.path.join(path,'bin'), 'dcm2niix*'))[0]
except IndexError:
print 'e> dcm2niix has NOT been successfully installed.'
Cnt = download_dcm2niix(Cnt, path)
# check the installation:
if not check_version(Cnt, chcklst=['DCM2NIIX']):
print 'e> dcm2niix has NOT been successfully compiled from github.'
Cnt = download_dcm2niix(Cnt, path)
return Cnt | [
"def",
"install_tool",
"(",
"app",
",",
"Cnt",
")",
":",
"# get the current working directory",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"# pick the target installation folder for tools",
"if",
"'PATHTOOLS'",
"in",
"Cnt",
"and",
"Cnt",
"[",
"'PATHTOOLS'",
"]",
"... | Install the requested software from the git 'repo'
and check out the version given by 'sha1'. | [
"Install",
"the",
"requested",
"software",
"from",
"the",
"git",
"repo",
"and",
"check",
"out",
"the",
"version",
"given",
"by",
"sha1",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/install_tools.py#L215-L340 |
pjmark/NIMPA | install_tools.py | update_resources | def update_resources(Cnt):
'''Update resources.py with the paths to the new installed apps.
'''
# list of path names which will be saved
key_list = ['PATHTOOLS', 'RESPATH', 'REGPATH', 'DCM2NIIX', 'HMUDIR']
# get the local path to NiftyPET resources.py
path_resources = cs.path_niftypet_local()
resources_file = os.path.join(path_resources,'resources.py')
# update resources.py
if os.path.isfile(resources_file):
f = open(resources_file, 'r')
rsrc = f.read()
f.close()
# get the region of keeping in synch with Python
i0 = rsrc.find('### start NiftyPET tools ###')
i1 = rsrc.find('### end NiftyPET tools ###')
pth_list = []
for k in key_list:
if k in Cnt:
pth_list.append('\'' + Cnt[k].replace("\\","/") + '\'')
else:
pth_list.append('\'\'')
# modify resources.py with the new paths
strNew = '### start NiftyPET tools ###\n'
for i in range(len(key_list)):
if pth_list[i] != '\'\'':
strNew += key_list[i]+' = '+pth_list[i] + '\n'
rsrcNew = rsrc[:i0] + strNew + rsrc[i1:]
f = open(resources_file, 'w')
f.write(rsrcNew)
f.close()
return Cnt | python | def update_resources(Cnt):
'''Update resources.py with the paths to the new installed apps.
'''
# list of path names which will be saved
key_list = ['PATHTOOLS', 'RESPATH', 'REGPATH', 'DCM2NIIX', 'HMUDIR']
# get the local path to NiftyPET resources.py
path_resources = cs.path_niftypet_local()
resources_file = os.path.join(path_resources,'resources.py')
# update resources.py
if os.path.isfile(resources_file):
f = open(resources_file, 'r')
rsrc = f.read()
f.close()
# get the region of keeping in synch with Python
i0 = rsrc.find('### start NiftyPET tools ###')
i1 = rsrc.find('### end NiftyPET tools ###')
pth_list = []
for k in key_list:
if k in Cnt:
pth_list.append('\'' + Cnt[k].replace("\\","/") + '\'')
else:
pth_list.append('\'\'')
# modify resources.py with the new paths
strNew = '### start NiftyPET tools ###\n'
for i in range(len(key_list)):
if pth_list[i] != '\'\'':
strNew += key_list[i]+' = '+pth_list[i] + '\n'
rsrcNew = rsrc[:i0] + strNew + rsrc[i1:]
f = open(resources_file, 'w')
f.write(rsrcNew)
f.close()
return Cnt | [
"def",
"update_resources",
"(",
"Cnt",
")",
":",
"# list of path names which will be saved",
"key_list",
"=",
"[",
"'PATHTOOLS'",
",",
"'RESPATH'",
",",
"'REGPATH'",
",",
"'DCM2NIIX'",
",",
"'HMUDIR'",
"]",
"# get the local path to NiftyPET resources.py",
"path_resources",
... | Update resources.py with the paths to the new installed apps. | [
"Update",
"resources",
".",
"py",
"with",
"the",
"paths",
"to",
"the",
"new",
"installed",
"apps",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/install_tools.py#L343-L379 |
Syndace/python-omemo | omemo/storage.py | Storage.loadSessions | def loadSessions(self, callback, bare_jid, device_ids):
"""
Return a dict containing the session for each device id. By default, this method
calls loadSession for each device id.
"""
if self.is_async:
self.__loadSessionsAsync(callback, bare_jid, device_ids, {})
else:
return self.__loadSessionsSync(bare_jid, device_ids) | python | def loadSessions(self, callback, bare_jid, device_ids):
"""
Return a dict containing the session for each device id. By default, this method
calls loadSession for each device id.
"""
if self.is_async:
self.__loadSessionsAsync(callback, bare_jid, device_ids, {})
else:
return self.__loadSessionsSync(bare_jid, device_ids) | [
"def",
"loadSessions",
"(",
"self",
",",
"callback",
",",
"bare_jid",
",",
"device_ids",
")",
":",
"if",
"self",
".",
"is_async",
":",
"self",
".",
"__loadSessionsAsync",
"(",
"callback",
",",
"bare_jid",
",",
"device_ids",
",",
"{",
"}",
")",
"else",
":... | Return a dict containing the session for each device id. By default, this method
calls loadSession for each device id. | [
"Return",
"a",
"dict",
"containing",
"the",
"session",
"for",
"each",
"device",
"id",
".",
"By",
"default",
"this",
"method",
"calls",
"loadSession",
"for",
"each",
"device",
"id",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/storage.py#L88-L97 |
Syndace/python-omemo | omemo/storage.py | Storage.loadTrusts | def loadTrusts(self, callback, bare_jid, device_ids):
"""
Return a dict containing the trust status for each device id. By default, this
method calls loadTrust for each device id.
"""
if self.is_async:
self.__loadTrustsAsync(callback, bare_jid, device_ids, {})
else:
return self.__loadTrustsSync(bare_jid, device_ids) | python | def loadTrusts(self, callback, bare_jid, device_ids):
"""
Return a dict containing the trust status for each device id. By default, this
method calls loadTrust for each device id.
"""
if self.is_async:
self.__loadTrustsAsync(callback, bare_jid, device_ids, {})
else:
return self.__loadTrustsSync(bare_jid, device_ids) | [
"def",
"loadTrusts",
"(",
"self",
",",
"callback",
",",
"bare_jid",
",",
"device_ids",
")",
":",
"if",
"self",
".",
"is_async",
":",
"self",
".",
"__loadTrustsAsync",
"(",
"callback",
",",
"bare_jid",
",",
"device_ids",
",",
"{",
"}",
")",
"else",
":",
... | Return a dict containing the trust status for each device id. By default, this
method calls loadTrust for each device id. | [
"Return",
"a",
"dict",
"containing",
"the",
"trust",
"status",
"for",
"each",
"device",
"id",
".",
"By",
"default",
"this",
"method",
"calls",
"loadTrust",
"for",
"each",
"device",
"id",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/storage.py#L205-L214 |
Syndace/python-omemo | omemo/extendedpublicbundle.py | ExtendedPublicBundle.parse | def parse(cls, backend, ik, spk, spk_signature, otpks):
"""
Use this method when creating a bundle from data you retrieved directly from some
PEP node. This method applies an additional decoding step to the public keys in
the bundle. Pass the same structure as the constructor expects.
"""
ik = backend.decodePublicKey(ik)[0]
spk["key"] = backend.decodePublicKey(spk["key"])[0]
otpks = list(map(lambda otpk: {
"key" : backend.decodePublicKey(otpk["key"])[0],
"id" : otpk["id"]
}, otpks))
return cls(ik, spk, spk_signature, otpks) | python | def parse(cls, backend, ik, spk, spk_signature, otpks):
"""
Use this method when creating a bundle from data you retrieved directly from some
PEP node. This method applies an additional decoding step to the public keys in
the bundle. Pass the same structure as the constructor expects.
"""
ik = backend.decodePublicKey(ik)[0]
spk["key"] = backend.decodePublicKey(spk["key"])[0]
otpks = list(map(lambda otpk: {
"key" : backend.decodePublicKey(otpk["key"])[0],
"id" : otpk["id"]
}, otpks))
return cls(ik, spk, spk_signature, otpks) | [
"def",
"parse",
"(",
"cls",
",",
"backend",
",",
"ik",
",",
"spk",
",",
"spk_signature",
",",
"otpks",
")",
":",
"ik",
"=",
"backend",
".",
"decodePublicKey",
"(",
"ik",
")",
"[",
"0",
"]",
"spk",
"[",
"\"key\"",
"]",
"=",
"backend",
".",
"decodePu... | Use this method when creating a bundle from data you retrieved directly from some
PEP node. This method applies an additional decoding step to the public keys in
the bundle. Pass the same structure as the constructor expects. | [
"Use",
"this",
"method",
"when",
"creating",
"a",
"bundle",
"from",
"data",
"you",
"retrieved",
"directly",
"from",
"some",
"PEP",
"node",
".",
"This",
"method",
"applies",
"an",
"additional",
"decoding",
"step",
"to",
"the",
"public",
"keys",
"in",
"the",
... | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/extendedpublicbundle.py#L38-L54 |
Syndace/python-omemo | omemo/extendedpublicbundle.py | ExtendedPublicBundle.serialize | def serialize(self, backend):
"""
Use this method to prepare the data to be uploaded directly to some PEP node. This
method applies an additional encoding step to the public keys in the bundle. The
result is a dictionary with the keys ik, spk, spk_signature and otpks. The values
are structured the same way as the inputs of the constructor.
"""
return {
"ik": backend.encodePublicKey(self.ik, "25519"),
"spk": {
"id" : self.spk["id"],
"key" : backend.encodePublicKey(self.spk["key"], "25519"),
},
"spk_signature": self.spk_signature,
"otpks": list(map(lambda otpk: {
"id" : otpk["id"],
"key" : backend.encodePublicKey(otpk["key"], "25519")
}, self.otpks))
} | python | def serialize(self, backend):
"""
Use this method to prepare the data to be uploaded directly to some PEP node. This
method applies an additional encoding step to the public keys in the bundle. The
result is a dictionary with the keys ik, spk, spk_signature and otpks. The values
are structured the same way as the inputs of the constructor.
"""
return {
"ik": backend.encodePublicKey(self.ik, "25519"),
"spk": {
"id" : self.spk["id"],
"key" : backend.encodePublicKey(self.spk["key"], "25519"),
},
"spk_signature": self.spk_signature,
"otpks": list(map(lambda otpk: {
"id" : otpk["id"],
"key" : backend.encodePublicKey(otpk["key"], "25519")
}, self.otpks))
} | [
"def",
"serialize",
"(",
"self",
",",
"backend",
")",
":",
"return",
"{",
"\"ik\"",
":",
"backend",
".",
"encodePublicKey",
"(",
"self",
".",
"ik",
",",
"\"25519\"",
")",
",",
"\"spk\"",
":",
"{",
"\"id\"",
":",
"self",
".",
"spk",
"[",
"\"id\"",
"]"... | Use this method to prepare the data to be uploaded directly to some PEP node. This
method applies an additional encoding step to the public keys in the bundle. The
result is a dictionary with the keys ik, spk, spk_signature and otpks. The values
are structured the same way as the inputs of the constructor. | [
"Use",
"this",
"method",
"to",
"prepare",
"the",
"data",
"to",
"be",
"uploaded",
"directly",
"to",
"some",
"PEP",
"node",
".",
"This",
"method",
"applies",
"an",
"additional",
"encoding",
"step",
"to",
"the",
"public",
"keys",
"in",
"the",
"bundle",
".",
... | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/extendedpublicbundle.py#L56-L75 |
pjmark/NIMPA | niftypet/nimpa/prc/regseg.py | imfill | def imfill(immsk):
'''fill the empty patches of image mask 'immsk' '''
for iz in range(immsk.shape[0]):
for iy in range(immsk.shape[1]):
ix0 = np.argmax(immsk[iz,iy,:]>0)
ix1 = immsk.shape[2] - np.argmax(immsk[iz,iy,::-1]>0)
if (ix1-ix0) > immsk.shape[2]-10: continue
immsk[iz,iy,ix0:ix1] = 1
return immsk | python | def imfill(immsk):
'''fill the empty patches of image mask 'immsk' '''
for iz in range(immsk.shape[0]):
for iy in range(immsk.shape[1]):
ix0 = np.argmax(immsk[iz,iy,:]>0)
ix1 = immsk.shape[2] - np.argmax(immsk[iz,iy,::-1]>0)
if (ix1-ix0) > immsk.shape[2]-10: continue
immsk[iz,iy,ix0:ix1] = 1
return immsk | [
"def",
"imfill",
"(",
"immsk",
")",
":",
"for",
"iz",
"in",
"range",
"(",
"immsk",
".",
"shape",
"[",
"0",
"]",
")",
":",
"for",
"iy",
"in",
"range",
"(",
"immsk",
".",
"shape",
"[",
"1",
"]",
")",
":",
"ix0",
"=",
"np",
".",
"argmax",
"(",
... | fill the empty patches of image mask 'immsk' | [
"fill",
"the",
"empty",
"patches",
"of",
"image",
"mask",
"immsk"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/regseg.py#L22-L31 |
pjmark/NIMPA | niftypet/nimpa/prc/regseg.py | create_mask | def create_mask(
fnii,
fimout = '',
outpath = '',
fill = 1,
dtype_fill = np.uint8,
thrsh = 0.,
fwhm = 0.,):
''' create mask over the whole image or over the threshold area'''
#> output path
if outpath=='' and fimout!='':
opth = os.path.dirname(fimout)
if opth=='':
opth = os.path.dirname(fnii)
fimout = os.path.join(opth, fimout)
elif outpath=='':
opth = os.path.dirname(fnii)
else:
opth = outpath
#> output file name if not given
if fimout=='':
fniis = os.path.split(fnii)
fimout = os.path.join(opth, fniis[1].split('.nii')[0]+'_mask.nii.gz')
niidct = imio.getnii(fnii, output='all')
im = niidct['im']
hdr = niidct['hdr']
if im.ndim>3:
raise ValueError('The masking function only accepts 3-D images.')
#> generate output image
if thrsh>0.:
smoim = ndi.filters.gaussian_filter(
im,
imio.fwhm2sig(fwhm, voxsize=abs(hdr['pixdim'][1])),
mode='mirror')
thrsh = thrsh*smoim.max()
immsk = np.int8(smoim>thrsh)
immsk = imfill(immsk)
#> output image
imo = fill * immsk.astype(dtype_fill)
else:
imo = fill * np.ones(im.shape, dtype = dtype_fill)
#> save output image
imio.array2nii(
imo,
niidct['affine'],
fimout,
trnsp = (niidct['transpose'].index(0),
niidct['transpose'].index(1),
niidct['transpose'].index(2)),
flip = niidct['flip'])
return {'fim':fimout, 'im':imo} | python | def create_mask(
fnii,
fimout = '',
outpath = '',
fill = 1,
dtype_fill = np.uint8,
thrsh = 0.,
fwhm = 0.,):
''' create mask over the whole image or over the threshold area'''
#> output path
if outpath=='' and fimout!='':
opth = os.path.dirname(fimout)
if opth=='':
opth = os.path.dirname(fnii)
fimout = os.path.join(opth, fimout)
elif outpath=='':
opth = os.path.dirname(fnii)
else:
opth = outpath
#> output file name if not given
if fimout=='':
fniis = os.path.split(fnii)
fimout = os.path.join(opth, fniis[1].split('.nii')[0]+'_mask.nii.gz')
niidct = imio.getnii(fnii, output='all')
im = niidct['im']
hdr = niidct['hdr']
if im.ndim>3:
raise ValueError('The masking function only accepts 3-D images.')
#> generate output image
if thrsh>0.:
smoim = ndi.filters.gaussian_filter(
im,
imio.fwhm2sig(fwhm, voxsize=abs(hdr['pixdim'][1])),
mode='mirror')
thrsh = thrsh*smoim.max()
immsk = np.int8(smoim>thrsh)
immsk = imfill(immsk)
#> output image
imo = fill * immsk.astype(dtype_fill)
else:
imo = fill * np.ones(im.shape, dtype = dtype_fill)
#> save output image
imio.array2nii(
imo,
niidct['affine'],
fimout,
trnsp = (niidct['transpose'].index(0),
niidct['transpose'].index(1),
niidct['transpose'].index(2)),
flip = niidct['flip'])
return {'fim':fimout, 'im':imo} | [
"def",
"create_mask",
"(",
"fnii",
",",
"fimout",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"fill",
"=",
"1",
",",
"dtype_fill",
"=",
"np",
".",
"uint8",
",",
"thrsh",
"=",
"0.",
",",
"fwhm",
"=",
"0.",
",",
")",
":",
"#> output path",
"if",
"ou... | create mask over the whole image or over the threshold area | [
"create",
"mask",
"over",
"the",
"whole",
"image",
"or",
"over",
"the",
"threshold",
"area"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/regseg.py#L38-L103 |
pjmark/NIMPA | niftypet/nimpa/prc/regseg.py | resample_vinci | def resample_vinci(
fref,
fflo,
faff,
intrp = 0,
fimout = '',
fcomment = '',
outpath = '',
pickname = 'ref',
vc = '',
con = '',
vincipy_path = '',
atlas_resample = False,
atlas_ref_make = False,
atlas_ref_del = False,
close_vinci = False,
close_buff = True,
):
''' Resample the floating image <fflo> into the geometry of <fref>,
using the Vinci transformation output <faff> (an *.xml file).
Output the NIfTI file path of the resampled/resliced image.
'''
#---------------------------------------------------------------------------
#> output path
if outpath=='' and fimout!='' and '/' in fimout:
opth = os.path.dirname(fimout)
if opth=='':
opth = os.path.dirname(fflo)
fimout = os.path.basename(fimout)
elif outpath=='':
opth = os.path.dirname(fflo)
else:
opth = outpath
imio.create_dir(opth)
#> output floating and affine file names
if fimout=='':
if pickname=='ref':
fout = os.path.join(
opth,
'affine-ref-' \
+os.path.basename(fref).split('.nii')[0]+fcomment+'.nii.gz')
else:
fout = os.path.join(
opth,
'affine-flo-' \
+os.path.basename(fflo).split('.nii')[0]+fcomment+'.nii.gz')
else:
fout = os.path.join(
opth,
fimout.split('.')[0]+'.nii.gz')
#---------------------------------------------------------------------------
if vincipy_path=='':
try:
import resources
vincipy_path = resources.VINCIPATH
except:
raise NameError('e> could not import resources \
or find variable VINCIPATH in resources.py')
sys.path.append(vincipy_path)
try:
from VinciPy import Vinci_Bin, Vinci_Connect, Vinci_Core, Vinci_XML, Vinci_ImageT
except ImportError:
raise ImportError('e> could not import Vinci:\n \
check the variable VINCIPATH (path to Vinci) in resources.py')
#---------------------------------------------------------------------------
#> start Vinci core engine if it is not running/given
if vc=='' or con=='':
#> adopted from the Vinci's example RunMMMJob.py
bin = Vinci_Bin.Vinci_Bin()
con = Vinci_Connect.Vinci_Connect(bin)
vinci_binpath = con.StartMyVinci()
vc = Vinci_Core.Vinci_CoreCalc(con)
vc.StdProject()
#---------------------------------------------------------------------------
if int(intrp)==0:
interp_nn = True
else:
interp_nn = False
#---------------------------------------------------------------------------
#> change the reference image to be loaded as atlas
if atlas_resample and atlas_ref_make:
#> output file name for the extra reference image
fextref = os.path.join(opth, 'reference-as-atlas.nii.gz')
prc.nii_modify(fref, fimout=fextref, voxel_range=[0., 255.])
ref = Vinci_ImageT.newTemporary(
vc,
szFileName = fextref,
bLoadAsAtlas = atlas_resample)
if atlas_ref_del:
os.remove(fextref)
else:
ref = Vinci_ImageT.newTemporary(
vc,
szFileName = fref,
bLoadAsAtlas = atlas_resample)
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
#> reapply rigid transformation to new image
flo = Vinci_ImageT.newTemporary(
vc,
szFileName = fflo,
bLoadAsAtlas = atlas_resample)
rsl = flo.reapplyMMMTransform(
faff,
refImage = ref,
IsComputed=True)
rsl.saveYourselfAs(
bUseOffsetRotation = True,
bUseNextNeighbourInterp = interp_nn,
szFullFileName = fout)
#---------------------------------------------------------------------------
#> close image buffers for reference and floating
if close_buff:
ref.killYourself()
flo.killYourself()
rsl.killYourself()
if close_vinci: con.CloseVinci(True)
return fout | python | def resample_vinci(
fref,
fflo,
faff,
intrp = 0,
fimout = '',
fcomment = '',
outpath = '',
pickname = 'ref',
vc = '',
con = '',
vincipy_path = '',
atlas_resample = False,
atlas_ref_make = False,
atlas_ref_del = False,
close_vinci = False,
close_buff = True,
):
''' Resample the floating image <fflo> into the geometry of <fref>,
using the Vinci transformation output <faff> (an *.xml file).
Output the NIfTI file path of the resampled/resliced image.
'''
#---------------------------------------------------------------------------
#> output path
if outpath=='' and fimout!='' and '/' in fimout:
opth = os.path.dirname(fimout)
if opth=='':
opth = os.path.dirname(fflo)
fimout = os.path.basename(fimout)
elif outpath=='':
opth = os.path.dirname(fflo)
else:
opth = outpath
imio.create_dir(opth)
#> output floating and affine file names
if fimout=='':
if pickname=='ref':
fout = os.path.join(
opth,
'affine-ref-' \
+os.path.basename(fref).split('.nii')[0]+fcomment+'.nii.gz')
else:
fout = os.path.join(
opth,
'affine-flo-' \
+os.path.basename(fflo).split('.nii')[0]+fcomment+'.nii.gz')
else:
fout = os.path.join(
opth,
fimout.split('.')[0]+'.nii.gz')
#---------------------------------------------------------------------------
if vincipy_path=='':
try:
import resources
vincipy_path = resources.VINCIPATH
except:
raise NameError('e> could not import resources \
or find variable VINCIPATH in resources.py')
sys.path.append(vincipy_path)
try:
from VinciPy import Vinci_Bin, Vinci_Connect, Vinci_Core, Vinci_XML, Vinci_ImageT
except ImportError:
raise ImportError('e> could not import Vinci:\n \
check the variable VINCIPATH (path to Vinci) in resources.py')
#---------------------------------------------------------------------------
#> start Vinci core engine if it is not running/given
if vc=='' or con=='':
#> adopted from the Vinci's example RunMMMJob.py
bin = Vinci_Bin.Vinci_Bin()
con = Vinci_Connect.Vinci_Connect(bin)
vinci_binpath = con.StartMyVinci()
vc = Vinci_Core.Vinci_CoreCalc(con)
vc.StdProject()
#---------------------------------------------------------------------------
if int(intrp)==0:
interp_nn = True
else:
interp_nn = False
#---------------------------------------------------------------------------
#> change the reference image to be loaded as atlas
if atlas_resample and atlas_ref_make:
#> output file name for the extra reference image
fextref = os.path.join(opth, 'reference-as-atlas.nii.gz')
prc.nii_modify(fref, fimout=fextref, voxel_range=[0., 255.])
ref = Vinci_ImageT.newTemporary(
vc,
szFileName = fextref,
bLoadAsAtlas = atlas_resample)
if atlas_ref_del:
os.remove(fextref)
else:
ref = Vinci_ImageT.newTemporary(
vc,
szFileName = fref,
bLoadAsAtlas = atlas_resample)
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
#> reapply rigid transformation to new image
flo = Vinci_ImageT.newTemporary(
vc,
szFileName = fflo,
bLoadAsAtlas = atlas_resample)
rsl = flo.reapplyMMMTransform(
faff,
refImage = ref,
IsComputed=True)
rsl.saveYourselfAs(
bUseOffsetRotation = True,
bUseNextNeighbourInterp = interp_nn,
szFullFileName = fout)
#---------------------------------------------------------------------------
#> close image buffers for reference and floating
if close_buff:
ref.killYourself()
flo.killYourself()
rsl.killYourself()
if close_vinci: con.CloseVinci(True)
return fout | [
"def",
"resample_vinci",
"(",
"fref",
",",
"fflo",
",",
"faff",
",",
"intrp",
"=",
"0",
",",
"fimout",
"=",
"''",
",",
"fcomment",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"pickname",
"=",
"'ref'",
",",
"vc",
"=",
"''",
",",
"con",
"=",
"''",
... | Resample the floating image <fflo> into the geometry of <fref>,
using the Vinci transformation output <faff> (an *.xml file).
Output the NIfTI file path of the resampled/resliced image. | [
"Resample",
"the",
"floating",
"image",
"<fflo",
">",
"into",
"the",
"geometry",
"of",
"<fref",
">",
"using",
"the",
"Vinci",
"transformation",
"output",
"<faff",
">",
"(",
"an",
"*",
".",
"xml",
"file",
")",
".",
"Output",
"the",
"NIfTI",
"file",
"path"... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/regseg.py#L703-L848 |
pjmark/NIMPA | niftypet/nimpa/prc/regseg.py | dice_coeff | def dice_coeff(im1, im2, val=1):
''' Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>.
Input images can be given as:
1. paths to NIfTI image files or as
2. Numpy arrays.
The ROI value can be given as:
1. a single integer representing one ROI out of many in the parcellation
images (<im1> and <im2>) or as
2. a list of integers to form a composite ROI used for the association test.
Outputs a float number representing the Dice score.
'''
if isinstance(im1, basestring) and isinstance(im2, basestring) \
and os.path.isfile(im1) and os.path.basename(im1).endswith(('nii', 'nii.gz')) \
and os.path.isfile(im2) and os.path.basename(im2).endswith(('nii', 'nii.gz')):
imn1 = imio.getnii(im1, output='image')
imn2 = imio.getnii(im2, output='image')
elif isinstance(im1, (np.ndarray, np.generic)) and isinstance(im1, (np.ndarray, np.generic)):
imn1 = im1
imn2 = im2
else:
raise TypeError('Unrecognised or Mismatched Images.')
# a single value corresponding to one ROI
if isinstance(val, (int, long)):
imv1 = (imn1 == val)
imv2 = (imn2 == val)
# multiple values in list corresponding to a composite ROI
elif isinstance(val, list) and all([isinstance(v, (int, long)) for v in val]):
imv1 = (imn1==val[0])
imv2 = (imn2==val[0])
for v in val[1:]:
# boolean addition to form a composite ROI
imv1 += (imn1==v)
imv2 += (imn2==v)
else:
raise TypeError('ROI Values have to be integer (single or in a list).')
if imv1.shape != imv2.shape:
raise ValueError('Shape Mismatch: Input images must have the same shape.')
#-compute Dice coefficient
intrsctn = np.logical_and(imv1, imv2)
return 2. * intrsctn.sum() / (imv1.sum() + imv2.sum()) | python | def dice_coeff(im1, im2, val=1):
''' Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>.
Input images can be given as:
1. paths to NIfTI image files or as
2. Numpy arrays.
The ROI value can be given as:
1. a single integer representing one ROI out of many in the parcellation
images (<im1> and <im2>) or as
2. a list of integers to form a composite ROI used for the association test.
Outputs a float number representing the Dice score.
'''
if isinstance(im1, basestring) and isinstance(im2, basestring) \
and os.path.isfile(im1) and os.path.basename(im1).endswith(('nii', 'nii.gz')) \
and os.path.isfile(im2) and os.path.basename(im2).endswith(('nii', 'nii.gz')):
imn1 = imio.getnii(im1, output='image')
imn2 = imio.getnii(im2, output='image')
elif isinstance(im1, (np.ndarray, np.generic)) and isinstance(im1, (np.ndarray, np.generic)):
imn1 = im1
imn2 = im2
else:
raise TypeError('Unrecognised or Mismatched Images.')
# a single value corresponding to one ROI
if isinstance(val, (int, long)):
imv1 = (imn1 == val)
imv2 = (imn2 == val)
# multiple values in list corresponding to a composite ROI
elif isinstance(val, list) and all([isinstance(v, (int, long)) for v in val]):
imv1 = (imn1==val[0])
imv2 = (imn2==val[0])
for v in val[1:]:
# boolean addition to form a composite ROI
imv1 += (imn1==v)
imv2 += (imn2==v)
else:
raise TypeError('ROI Values have to be integer (single or in a list).')
if imv1.shape != imv2.shape:
raise ValueError('Shape Mismatch: Input images must have the same shape.')
#-compute Dice coefficient
intrsctn = np.logical_and(imv1, imv2)
return 2. * intrsctn.sum() / (imv1.sum() + imv2.sum()) | [
"def",
"dice_coeff",
"(",
"im1",
",",
"im2",
",",
"val",
"=",
"1",
")",
":",
"if",
"isinstance",
"(",
"im1",
",",
"basestring",
")",
"and",
"isinstance",
"(",
"im2",
",",
"basestring",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"im1",
")",
... | Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>.
Input images can be given as:
1. paths to NIfTI image files or as
2. Numpy arrays.
The ROI value can be given as:
1. a single integer representing one ROI out of many in the parcellation
images (<im1> and <im2>) or as
2. a list of integers to form a composite ROI used for the association test.
Outputs a float number representing the Dice score. | [
"Calculate",
"Dice",
"score",
"for",
"parcellation",
"images",
"<im1",
">",
"and",
"<im2",
">",
"and",
"ROI",
"value",
"<val",
">",
".",
"Input",
"images",
"can",
"be",
"given",
"as",
":",
"1",
".",
"paths",
"to",
"NIfTI",
"image",
"files",
"or",
"as",... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/regseg.py#L1115-L1160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.