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 |
|---|---|---|---|---|---|---|---|---|---|---|
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.load_distant | def load_distant(self):
"""Load the distant Zotero data."""
print("Loading distant Zotero data...")
self._references = self.get_references()
self.reference_types = self.get_reference_types()
self.reference_templates = self.get_reference_templates(self.reference_types)
print("Distant Zotero data loaded.")
self.cache() | python | def load_distant(self):
"""Load the distant Zotero data."""
print("Loading distant Zotero data...")
self._references = self.get_references()
self.reference_types = self.get_reference_types()
self.reference_templates = self.get_reference_templates(self.reference_types)
print("Distant Zotero data loaded.")
self.cache() | [
"def",
"load_distant",
"(",
"self",
")",
":",
"print",
"(",
"\"Loading distant Zotero data...\"",
")",
"self",
".",
"_references",
"=",
"self",
".",
"get_references",
"(",
")",
"self",
".",
"reference_types",
"=",
"self",
".",
"get_reference_types",
"(",
")",
"self",
".",
"reference_templates",
"=",
"self",
".",
"get_reference_templates",
"(",
"self",
".",
"reference_types",
")",
"print",
"(",
"\"Distant Zotero data loaded.\"",
")",
"self",
".",
"cache",
"(",
")"
] | Load the distant Zotero data. | [
"Load",
"the",
"distant",
"Zotero",
"data",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L48-L55 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.cache | def cache(self):
"""Cache the Zotero data."""
with open(self.cache_path, "wb") as f:
cache = {self.CACHE_REFERENCE_LIST: self._references,
self.CACHE_REFERENCE_TYPES: self.reference_types,
self.CACHE_REFERENCE_TEMPLATES: self.reference_templates}
pickle.dump(cache, f) | python | def cache(self):
"""Cache the Zotero data."""
with open(self.cache_path, "wb") as f:
cache = {self.CACHE_REFERENCE_LIST: self._references,
self.CACHE_REFERENCE_TYPES: self.reference_types,
self.CACHE_REFERENCE_TEMPLATES: self.reference_templates}
pickle.dump(cache, f) | [
"def",
"cache",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"cache_path",
",",
"\"wb\"",
")",
"as",
"f",
":",
"cache",
"=",
"{",
"self",
".",
"CACHE_REFERENCE_LIST",
":",
"self",
".",
"_references",
",",
"self",
".",
"CACHE_REFERENCE_TYPES",
":",
"self",
".",
"reference_types",
",",
"self",
".",
"CACHE_REFERENCE_TEMPLATES",
":",
"self",
".",
"reference_templates",
"}",
"pickle",
".",
"dump",
"(",
"cache",
",",
"f",
")"
] | Cache the Zotero data. | [
"Cache",
"the",
"Zotero",
"data",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L57-L63 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.create_distant_reference | def create_distant_reference(self, ref_data):
"""Validate and create the reference in Zotero and return the created item."""
self.validate_reference_data(ref_data)
creation_status = self._zotero_lib.create_items([ref_data])
try:
created_item = creation_status["successful"]["0"]
return created_item
except KeyError as e:
print(creation_status)
raise CreateZoteroItemError from e | python | def create_distant_reference(self, ref_data):
"""Validate and create the reference in Zotero and return the created item."""
self.validate_reference_data(ref_data)
creation_status = self._zotero_lib.create_items([ref_data])
try:
created_item = creation_status["successful"]["0"]
return created_item
except KeyError as e:
print(creation_status)
raise CreateZoteroItemError from e | [
"def",
"create_distant_reference",
"(",
"self",
",",
"ref_data",
")",
":",
"self",
".",
"validate_reference_data",
"(",
"ref_data",
")",
"creation_status",
"=",
"self",
".",
"_zotero_lib",
".",
"create_items",
"(",
"[",
"ref_data",
"]",
")",
"try",
":",
"created_item",
"=",
"creation_status",
"[",
"\"successful\"",
"]",
"[",
"\"0\"",
"]",
"return",
"created_item",
"except",
"KeyError",
"as",
"e",
":",
"print",
"(",
"creation_status",
")",
"raise",
"CreateZoteroItemError",
"from",
"e"
] | Validate and create the reference in Zotero and return the created item. | [
"Validate",
"and",
"create",
"the",
"reference",
"in",
"Zotero",
"and",
"return",
"the",
"created",
"item",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L70-L79 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.update_local_reference | def update_local_reference(self, index, ref):
"""Replace the reference in the reference list and cache it."""
self._references[index] = ref
self.cache() | python | def update_local_reference(self, index, ref):
"""Replace the reference in the reference list and cache it."""
self._references[index] = ref
self.cache() | [
"def",
"update_local_reference",
"(",
"self",
",",
"index",
",",
"ref",
")",
":",
"self",
".",
"_references",
"[",
"index",
"]",
"=",
"ref",
"self",
".",
"cache",
"(",
")"
] | Replace the reference in the reference list and cache it. | [
"Replace",
"the",
"reference",
"in",
"the",
"reference",
"list",
"and",
"cache",
"it",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L81-L84 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.update_distant_reference | def update_distant_reference(self, ref):
"""Validate and update the reference in Zotero.
Existing fields not present will be left unmodified.
"""
self.validate_reference_data(ref["data"])
self._zotero_lib.update_item(ref) | python | def update_distant_reference(self, ref):
"""Validate and update the reference in Zotero.
Existing fields not present will be left unmodified.
"""
self.validate_reference_data(ref["data"])
self._zotero_lib.update_item(ref) | [
"def",
"update_distant_reference",
"(",
"self",
",",
"ref",
")",
":",
"self",
".",
"validate_reference_data",
"(",
"ref",
"[",
"\"data\"",
"]",
")",
"self",
".",
"_zotero_lib",
".",
"update_item",
"(",
"ref",
")"
] | Validate and update the reference in Zotero.
Existing fields not present will be left unmodified. | [
"Validate",
"and",
"update",
"the",
"reference",
"in",
"Zotero",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L86-L92 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.validate_reference_data | def validate_reference_data(self, ref_data):
"""Validate the reference data.
Zotero.check_items() caches data after the first API call.
"""
try:
self._zotero_lib.check_items([ref_data])
except InvalidItemFields as e:
raise InvalidZoteroItemError from e | python | def validate_reference_data(self, ref_data):
"""Validate the reference data.
Zotero.check_items() caches data after the first API call.
"""
try:
self._zotero_lib.check_items([ref_data])
except InvalidItemFields as e:
raise InvalidZoteroItemError from e | [
"def",
"validate_reference_data",
"(",
"self",
",",
"ref_data",
")",
":",
"try",
":",
"self",
".",
"_zotero_lib",
".",
"check_items",
"(",
"[",
"ref_data",
"]",
")",
"except",
"InvalidItemFields",
"as",
"e",
":",
"raise",
"InvalidZoteroItemError",
"from",
"e"
] | Validate the reference data.
Zotero.check_items() caches data after the first API call. | [
"Validate",
"the",
"reference",
"data",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L94-L102 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.get_reference_types | def get_reference_types(self):
"""Return the reference types.
Zotero.item_types() caches data after the first API call.
"""
item_types = self._zotero_lib.item_types()
return sorted([x["itemType"] for x in item_types]) | python | def get_reference_types(self):
"""Return the reference types.
Zotero.item_types() caches data after the first API call.
"""
item_types = self._zotero_lib.item_types()
return sorted([x["itemType"] for x in item_types]) | [
"def",
"get_reference_types",
"(",
"self",
")",
":",
"item_types",
"=",
"self",
".",
"_zotero_lib",
".",
"item_types",
"(",
")",
"return",
"sorted",
"(",
"[",
"x",
"[",
"\"itemType\"",
"]",
"for",
"x",
"in",
"item_types",
"]",
")"
] | Return the reference types.
Zotero.item_types() caches data after the first API call. | [
"Return",
"the",
"reference",
"types",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L108-L114 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.get_reference_templates | def get_reference_templates(self, ref_types):
"""Return the reference templates for the types as an ordered dictionary."""
return OrderedDict([(x, self.get_reference_template(x)) for x in ref_types]) | python | def get_reference_templates(self, ref_types):
"""Return the reference templates for the types as an ordered dictionary."""
return OrderedDict([(x, self.get_reference_template(x)) for x in ref_types]) | [
"def",
"get_reference_templates",
"(",
"self",
",",
"ref_types",
")",
":",
"return",
"OrderedDict",
"(",
"[",
"(",
"x",
",",
"self",
".",
"get_reference_template",
"(",
"x",
")",
")",
"for",
"x",
"in",
"ref_types",
"]",
")"
] | Return the reference templates for the types as an ordered dictionary. | [
"Return",
"the",
"reference",
"templates",
"for",
"the",
"types",
"as",
"an",
"ordered",
"dictionary",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L116-L118 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.get_reference_template | def get_reference_template(self, ref_type):
"""Return the reference template for the type as an ordered dictionary.
Zotero.item_template() caches data after the first API call.
"""
template = self._zotero_lib.item_template(ref_type)
return OrderedDict(sorted(template.items(), key=lambda x: x[0])) | python | def get_reference_template(self, ref_type):
"""Return the reference template for the type as an ordered dictionary.
Zotero.item_template() caches data after the first API call.
"""
template = self._zotero_lib.item_template(ref_type)
return OrderedDict(sorted(template.items(), key=lambda x: x[0])) | [
"def",
"get_reference_template",
"(",
"self",
",",
"ref_type",
")",
":",
"template",
"=",
"self",
".",
"_zotero_lib",
".",
"item_template",
"(",
"ref_type",
")",
"return",
"OrderedDict",
"(",
"sorted",
"(",
"template",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
")"
] | Return the reference template for the type as an ordered dictionary.
Zotero.item_template() caches data after the first API call. | [
"Return",
"the",
"reference",
"template",
"for",
"the",
"type",
"as",
"an",
"ordered",
"dictionary",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L120-L126 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.reference_extra_field | def reference_extra_field(self, field, index):
"""Return the value of the field in 'extra', otherwise ''."""
ref_data = self.reference_data(index)
extra_fields = ref_data["extra"].split("\n")
field_id = field + ":"
matched = next((x for x in extra_fields if x.startswith(field_id)), None)
if matched:
return matched.replace(field_id, "", 1).strip()
else:
return "" | python | def reference_extra_field(self, field, index):
"""Return the value of the field in 'extra', otherwise ''."""
ref_data = self.reference_data(index)
extra_fields = ref_data["extra"].split("\n")
field_id = field + ":"
matched = next((x for x in extra_fields if x.startswith(field_id)), None)
if matched:
return matched.replace(field_id, "", 1).strip()
else:
return "" | [
"def",
"reference_extra_field",
"(",
"self",
",",
"field",
",",
"index",
")",
":",
"ref_data",
"=",
"self",
".",
"reference_data",
"(",
"index",
")",
"extra_fields",
"=",
"ref_data",
"[",
"\"extra\"",
"]",
".",
"split",
"(",
"\"\\n\"",
")",
"field_id",
"=",
"field",
"+",
"\":\"",
"matched",
"=",
"next",
"(",
"(",
"x",
"for",
"x",
"in",
"extra_fields",
"if",
"x",
".",
"startswith",
"(",
"field_id",
")",
")",
",",
"None",
")",
"if",
"matched",
":",
"return",
"matched",
".",
"replace",
"(",
"field_id",
",",
"\"\"",
",",
"1",
")",
".",
"strip",
"(",
")",
"else",
":",
"return",
"\"\""
] | Return the value of the field in 'extra', otherwise ''. | [
"Return",
"the",
"value",
"of",
"the",
"field",
"in",
"extra",
"otherwise",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L142-L151 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.reference_id | def reference_id(self, index):
"""Return the reference ID (locally defined)."""
# TODO Include ISBN and ISSN?
doi = self.reference_doi(index)
if doi:
return doi
else:
pmid = self.reference_pmid(index)
if pmid:
return "PMID_" + pmid
else:
unpublished_id = self.reference_unpublished_id(index)
if unpublished_id:
return "UNPUBLISHED_" + unpublished_id
return "" | python | def reference_id(self, index):
"""Return the reference ID (locally defined)."""
# TODO Include ISBN and ISSN?
doi = self.reference_doi(index)
if doi:
return doi
else:
pmid = self.reference_pmid(index)
if pmid:
return "PMID_" + pmid
else:
unpublished_id = self.reference_unpublished_id(index)
if unpublished_id:
return "UNPUBLISHED_" + unpublished_id
return "" | [
"def",
"reference_id",
"(",
"self",
",",
"index",
")",
":",
"# TODO Include ISBN and ISSN?",
"doi",
"=",
"self",
".",
"reference_doi",
"(",
"index",
")",
"if",
"doi",
":",
"return",
"doi",
"else",
":",
"pmid",
"=",
"self",
".",
"reference_pmid",
"(",
"index",
")",
"if",
"pmid",
":",
"return",
"\"PMID_\"",
"+",
"pmid",
"else",
":",
"unpublished_id",
"=",
"self",
".",
"reference_unpublished_id",
"(",
"index",
")",
"if",
"unpublished_id",
":",
"return",
"\"UNPUBLISHED_\"",
"+",
"unpublished_id",
"return",
"\"\""
] | Return the reference ID (locally defined). | [
"Return",
"the",
"reference",
"ID",
"(",
"locally",
"defined",
")",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L161-L175 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.reference_doi | def reference_doi(self, index):
"""Return the reference DOI."""
return self.reference_data(index).get("DOI", self.reference_extra_field("DOI", index)) | python | def reference_doi(self, index):
"""Return the reference DOI."""
return self.reference_data(index).get("DOI", self.reference_extra_field("DOI", index)) | [
"def",
"reference_doi",
"(",
"self",
",",
"index",
")",
":",
"return",
"self",
".",
"reference_data",
"(",
"index",
")",
".",
"get",
"(",
"\"DOI\"",
",",
"self",
".",
"reference_extra_field",
"(",
"\"DOI\"",
",",
"index",
")",
")"
] | Return the reference DOI. | [
"Return",
"the",
"reference",
"DOI",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L177-L179 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.reference_creator_surnames | def reference_creator_surnames(self, index):
"""Return as a list the surnames of the reference creators (locally defined)."""
# TODO Not true, ex: ISBN 978-1-4398-3778-8. Return all creator types?
# Academic books published as a collection of chapters contributed by
# different authors have editors but not authors at the level of the
# book (as opposed to the level of a chapter).
creators = self.reference_data(index)["creators"]
creator_types = [x["creatorType"] for x in creators]
# 'name' (not split) might be used instead of 'firstName' and 'lastName'.
try:
if "author" in creator_types:
return [x["lastName"] for x in creators if x["creatorType"] == "author"]
else:
return [x["lastName"] for x in creators]
except KeyError:
return [] | python | def reference_creator_surnames(self, index):
"""Return as a list the surnames of the reference creators (locally defined)."""
# TODO Not true, ex: ISBN 978-1-4398-3778-8. Return all creator types?
# Academic books published as a collection of chapters contributed by
# different authors have editors but not authors at the level of the
# book (as opposed to the level of a chapter).
creators = self.reference_data(index)["creators"]
creator_types = [x["creatorType"] for x in creators]
# 'name' (not split) might be used instead of 'firstName' and 'lastName'.
try:
if "author" in creator_types:
return [x["lastName"] for x in creators if x["creatorType"] == "author"]
else:
return [x["lastName"] for x in creators]
except KeyError:
return [] | [
"def",
"reference_creator_surnames",
"(",
"self",
",",
"index",
")",
":",
"# TODO Not true, ex: ISBN 978-1-4398-3778-8. Return all creator types?",
"# Academic books published as a collection of chapters contributed by",
"# different authors have editors but not authors at the level of the",
"# book (as opposed to the level of a chapter).",
"creators",
"=",
"self",
".",
"reference_data",
"(",
"index",
")",
"[",
"\"creators\"",
"]",
"creator_types",
"=",
"[",
"x",
"[",
"\"creatorType\"",
"]",
"for",
"x",
"in",
"creators",
"]",
"# 'name' (not split) might be used instead of 'firstName' and 'lastName'.",
"try",
":",
"if",
"\"author\"",
"in",
"creator_types",
":",
"return",
"[",
"x",
"[",
"\"lastName\"",
"]",
"for",
"x",
"in",
"creators",
"if",
"x",
"[",
"\"creatorType\"",
"]",
"==",
"\"author\"",
"]",
"else",
":",
"return",
"[",
"x",
"[",
"\"lastName\"",
"]",
"for",
"x",
"in",
"creators",
"]",
"except",
"KeyError",
":",
"return",
"[",
"]"
] | Return as a list the surnames of the reference creators (locally defined). | [
"Return",
"as",
"a",
"list",
"the",
"surnames",
"of",
"the",
"reference",
"creators",
"(",
"locally",
"defined",
")",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L193-L208 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.reference_year | def reference_year(self, index):
"""Return the reference publication year."""
# TODO Use meta:parsedDate field instead?
ref_date = self.reference_date(index)
try:
# NB: datetime.year returns an int.
return parse(ref_date).year
except ValueError:
matched = re.search(r"\d{4}", ref_date)
if matched:
return int(matched.group())
else:
return "" | python | def reference_year(self, index):
"""Return the reference publication year."""
# TODO Use meta:parsedDate field instead?
ref_date = self.reference_date(index)
try:
# NB: datetime.year returns an int.
return parse(ref_date).year
except ValueError:
matched = re.search(r"\d{4}", ref_date)
if matched:
return int(matched.group())
else:
return "" | [
"def",
"reference_year",
"(",
"self",
",",
"index",
")",
":",
"# TODO Use meta:parsedDate field instead?",
"ref_date",
"=",
"self",
".",
"reference_date",
"(",
"index",
")",
"try",
":",
"# NB: datetime.year returns an int.",
"return",
"parse",
"(",
"ref_date",
")",
".",
"year",
"except",
"ValueError",
":",
"matched",
"=",
"re",
".",
"search",
"(",
"r\"\\d{4}\"",
",",
"ref_date",
")",
"if",
"matched",
":",
"return",
"int",
"(",
"matched",
".",
"group",
"(",
")",
")",
"else",
":",
"return",
"\"\""
] | Return the reference publication year. | [
"Return",
"the",
"reference",
"publication",
"year",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L219-L231 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.reference_journal | def reference_journal(self, index):
"""Return the reference journal name."""
# TODO Change the column name 'Journal' to an other?
ref_type = self.reference_type(index)
if ref_type == "journalArticle":
return self.reference_data(index)["publicationTitle"]
else:
return "({})".format(ref_type) | python | def reference_journal(self, index):
"""Return the reference journal name."""
# TODO Change the column name 'Journal' to an other?
ref_type = self.reference_type(index)
if ref_type == "journalArticle":
return self.reference_data(index)["publicationTitle"]
else:
return "({})".format(ref_type) | [
"def",
"reference_journal",
"(",
"self",
",",
"index",
")",
":",
"# TODO Change the column name 'Journal' to an other?",
"ref_type",
"=",
"self",
".",
"reference_type",
"(",
"index",
")",
"if",
"ref_type",
"==",
"\"journalArticle\"",
":",
"return",
"self",
".",
"reference_data",
"(",
"index",
")",
"[",
"\"publicationTitle\"",
"]",
"else",
":",
"return",
"\"({})\"",
".",
"format",
"(",
"ref_type",
")"
] | Return the reference journal name. | [
"Return",
"the",
"reference",
"journal",
"name",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L233-L240 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.reference_index | def reference_index(self, ref_id):
"""Return the first reference with this ID."""
try:
indexes = range(self.reference_count())
return next(i for i in indexes if self.reference_id(i) == ref_id)
except StopIteration as e:
raise ReferenceNotFoundError("ID: " + ref_id) from e | python | def reference_index(self, ref_id):
"""Return the first reference with this ID."""
try:
indexes = range(self.reference_count())
return next(i for i in indexes if self.reference_id(i) == ref_id)
except StopIteration as e:
raise ReferenceNotFoundError("ID: " + ref_id) from e | [
"def",
"reference_index",
"(",
"self",
",",
"ref_id",
")",
":",
"try",
":",
"indexes",
"=",
"range",
"(",
"self",
".",
"reference_count",
"(",
")",
")",
"return",
"next",
"(",
"i",
"for",
"i",
"in",
"indexes",
"if",
"self",
".",
"reference_id",
"(",
"i",
")",
"==",
"ref_id",
")",
"except",
"StopIteration",
"as",
"e",
":",
"raise",
"ReferenceNotFoundError",
"(",
"\"ID: \"",
"+",
"ref_id",
")",
"from",
"e"
] | Return the first reference with this ID. | [
"Return",
"the",
"first",
"reference",
"with",
"this",
"ID",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L244-L250 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.reference_creators_citation | def reference_creators_citation(self, ref_id):
"""Return for citation the creator surnames (locally defined) and the publication year."""
# FIXME Delayed refactoring. Use an index instead of an ID.
index = self.reference_index(ref_id)
creators = self.reference_creator_surnames(index)
creator_count = len(creators)
if creator_count == 0:
return ""
year = self.reference_year(index)
if creator_count == 1:
return "{} ({})".format(creators[0], year)
elif creator_count == 2:
return "{} and {} ({})".format(creators[0], creators[1], year)
else:
return "{} et al. ({})".format(creators[0], year) | python | def reference_creators_citation(self, ref_id):
"""Return for citation the creator surnames (locally defined) and the publication year."""
# FIXME Delayed refactoring. Use an index instead of an ID.
index = self.reference_index(ref_id)
creators = self.reference_creator_surnames(index)
creator_count = len(creators)
if creator_count == 0:
return ""
year = self.reference_year(index)
if creator_count == 1:
return "{} ({})".format(creators[0], year)
elif creator_count == 2:
return "{} and {} ({})".format(creators[0], creators[1], year)
else:
return "{} et al. ({})".format(creators[0], year) | [
"def",
"reference_creators_citation",
"(",
"self",
",",
"ref_id",
")",
":",
"# FIXME Delayed refactoring. Use an index instead of an ID.",
"index",
"=",
"self",
".",
"reference_index",
"(",
"ref_id",
")",
"creators",
"=",
"self",
".",
"reference_creator_surnames",
"(",
"index",
")",
"creator_count",
"=",
"len",
"(",
"creators",
")",
"if",
"creator_count",
"==",
"0",
":",
"return",
"\"\"",
"year",
"=",
"self",
".",
"reference_year",
"(",
"index",
")",
"if",
"creator_count",
"==",
"1",
":",
"return",
"\"{} ({})\"",
".",
"format",
"(",
"creators",
"[",
"0",
"]",
",",
"year",
")",
"elif",
"creator_count",
"==",
"2",
":",
"return",
"\"{} and {} ({})\"",
".",
"format",
"(",
"creators",
"[",
"0",
"]",
",",
"creators",
"[",
"1",
"]",
",",
"year",
")",
"else",
":",
"return",
"\"{} et al. ({})\"",
".",
"format",
"(",
"creators",
"[",
"0",
"]",
",",
"year",
")"
] | Return for citation the creator surnames (locally defined) and the publication year. | [
"Return",
"for",
"citation",
"the",
"creator",
"surnames",
"(",
"locally",
"defined",
")",
"and",
"the",
"publication",
"year",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L252-L266 |
BlueBrain/nat | nat/restServer.py | computePDFSimilarity | def computePDFSimilarity(paperId, userPDF):
if not isPDFInDb(paperId):
return None
userPDF.save("temp.pdf")
# check_call is blocking
check_call(['pdftotext', '-enc', 'UTF-8', "temp.pdf", "temp.txt"])
os.remove("temp.pdf")
a = open("temp.txt", 'r').read()
b = open(join(dbPath, paperId) + ".txt", 'r').read()
import nltk, string
from sklearn.feature_extraction.text import TfidfVectorizer
stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
def stem_tokens(tokens):
return [stemmer.stem(item) for item in tokens]
'''remove punctuation, lowercase, stem'''
def normalize(text):
return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))
vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')
def cosine_sim(text1, text2):
tfidf = vectorizer.fit_transform([text1, text2])
return ((tfidf * tfidf.T).A)[0,1]
similarity = cosine_sim(a, b)
os.remove("temp.txt")
return similarity | python | def computePDFSimilarity(paperId, userPDF):
if not isPDFInDb(paperId):
return None
userPDF.save("temp.pdf")
# check_call is blocking
check_call(['pdftotext', '-enc', 'UTF-8', "temp.pdf", "temp.txt"])
os.remove("temp.pdf")
a = open("temp.txt", 'r').read()
b = open(join(dbPath, paperId) + ".txt", 'r').read()
import nltk, string
from sklearn.feature_extraction.text import TfidfVectorizer
stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
def stem_tokens(tokens):
return [stemmer.stem(item) for item in tokens]
'''remove punctuation, lowercase, stem'''
def normalize(text):
return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))
vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')
def cosine_sim(text1, text2):
tfidf = vectorizer.fit_transform([text1, text2])
return ((tfidf * tfidf.T).A)[0,1]
similarity = cosine_sim(a, b)
os.remove("temp.txt")
return similarity | [
"def",
"computePDFSimilarity",
"(",
"paperId",
",",
"userPDF",
")",
":",
"if",
"not",
"isPDFInDb",
"(",
"paperId",
")",
":",
"return",
"None",
"userPDF",
".",
"save",
"(",
"\"temp.pdf\"",
")",
"# check_call is blocking",
"check_call",
"(",
"[",
"'pdftotext'",
",",
"'-enc'",
",",
"'UTF-8'",
",",
"\"temp.pdf\"",
",",
"\"temp.txt\"",
"]",
")",
"os",
".",
"remove",
"(",
"\"temp.pdf\"",
")",
"a",
"=",
"open",
"(",
"\"temp.txt\"",
",",
"'r'",
")",
".",
"read",
"(",
")",
"b",
"=",
"open",
"(",
"join",
"(",
"dbPath",
",",
"paperId",
")",
"+",
"\".txt\"",
",",
"'r'",
")",
".",
"read",
"(",
")",
"import",
"nltk",
",",
"string",
"from",
"sklearn",
".",
"feature_extraction",
".",
"text",
"import",
"TfidfVectorizer",
"stemmer",
"=",
"nltk",
".",
"stem",
".",
"porter",
".",
"PorterStemmer",
"(",
")",
"remove_punctuation_map",
"=",
"dict",
"(",
"(",
"ord",
"(",
"char",
")",
",",
"None",
")",
"for",
"char",
"in",
"string",
".",
"punctuation",
")",
"def",
"stem_tokens",
"(",
"tokens",
")",
":",
"return",
"[",
"stemmer",
".",
"stem",
"(",
"item",
")",
"for",
"item",
"in",
"tokens",
"]",
"def",
"normalize",
"(",
"text",
")",
":",
"return",
"stem_tokens",
"(",
"nltk",
".",
"word_tokenize",
"(",
"text",
".",
"lower",
"(",
")",
".",
"translate",
"(",
"remove_punctuation_map",
")",
")",
")",
"vectorizer",
"=",
"TfidfVectorizer",
"(",
"tokenizer",
"=",
"normalize",
",",
"stop_words",
"=",
"'english'",
")",
"def",
"cosine_sim",
"(",
"text1",
",",
"text2",
")",
":",
"tfidf",
"=",
"vectorizer",
".",
"fit_transform",
"(",
"[",
"text1",
",",
"text2",
"]",
")",
"return",
"(",
"(",
"tfidf",
"*",
"tfidf",
".",
"T",
")",
".",
"A",
")",
"[",
"0",
",",
"1",
"]",
"similarity",
"=",
"cosine_sim",
"(",
"a",
",",
"b",
")",
"os",
".",
"remove",
"(",
"\"temp.txt\"",
")",
"return",
"similarity"
] | remove punctuation, lowercase, stem | [
"remove",
"punctuation",
"lowercase",
"stem"
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/restServer.py#L339-L374 |
BlueBrain/nat | nat/treeData.py | getChildren | def getChildren(root_id, maxDepth=100, relationshipType="subClassOf",
alwaysFetch=False):
"""
Accessing web-based ontology service is too long, so we cache the
information in a pickle file and query the services only if the info
has not already been cached.
"""
childrenDic = {}
fileName = os.path.join(os.path.dirname(__file__), "children.bin")
#### CHECK FOR CASE OF BBP TAGS
if root_id[:4] == "BBP_":
if not alwaysFetch:
try:
with open(fileName, "rb") as childrenFile:
childrenDic = pickle.load(childrenFile)
if root_id in childrenDic:
return childrenDic[root_id]
except:
pass
childrenDic[root_id] = getBBPChildren(root_id)
if not alwaysFetch:
try:
with open(fileName, "wb") as childrenFile:
pickle.dump(childrenDic, childrenFile)
except:
pass
return childrenDic[root_id]
## TODO: should also check for BBP children of online onto terms
if root_id in nlx2ks:
root_id = nlx2ks[root_id]
if not alwaysFetch:
try:
with open(fileName, "rb") as childrenFile:
childrenDic = pickle.load(childrenFile)
if root_id in childrenDic:
return childrenDic[root_id]
except:
pass
direction="INCOMING"
#neighbors = graph.getNeighbors(root_id, depth=maxDepth,
# relationshipType=relationshipType,
# direction=direction)
baseKS = "http://matrix.neuinfo.org:9000"
response = requests.get(baseKS + "/scigraph/graph/neighbors/" +
root_id + "?direction=" + direction +
"&depth=" + str(maxDepth) +
"&project=%2A&blankNodes=false&relationshipType="
+ relationshipType)
if not response.ok:
return {}
neighbors = response.json()
if neighbors is None:
return {}
nodes = neighbors["nodes"]
#for node in np.array(nodes):
# node["lbl"] = node["lbl"].encode('utf-8').decode('utf-8')
#try:
# assert(np.all([not node["lbl"] is None for node in np.array(nodes)]))
#except AssertionError:
# for node in np.array(nodes):
# if node["lbl"] is None:
# print(node["id"])
# raise
# TODO: replace by the commented line below. This patch is only to
# accomodate for a current issue with the knowledge-space endpoint.
#childrenDic[root_id] = OntoDic({node["id"]:node["lbl"] for node in np.array(nodes)})
childrenDic[root_id] = OntoDic({node["id"]:node["lbl"] for node in np.array(nodes) if not node["lbl"] is None})
if not alwaysFetch:
try:
with open(fileName, "wb") as childrenFile:
pickle.dump(childrenDic, childrenFile)
except:
pass
return childrenDic[root_id] | python | def getChildren(root_id, maxDepth=100, relationshipType="subClassOf",
alwaysFetch=False):
"""
Accessing web-based ontology service is too long, so we cache the
information in a pickle file and query the services only if the info
has not already been cached.
"""
childrenDic = {}
fileName = os.path.join(os.path.dirname(__file__), "children.bin")
#### CHECK FOR CASE OF BBP TAGS
if root_id[:4] == "BBP_":
if not alwaysFetch:
try:
with open(fileName, "rb") as childrenFile:
childrenDic = pickle.load(childrenFile)
if root_id in childrenDic:
return childrenDic[root_id]
except:
pass
childrenDic[root_id] = getBBPChildren(root_id)
if not alwaysFetch:
try:
with open(fileName, "wb") as childrenFile:
pickle.dump(childrenDic, childrenFile)
except:
pass
return childrenDic[root_id]
## TODO: should also check for BBP children of online onto terms
if root_id in nlx2ks:
root_id = nlx2ks[root_id]
if not alwaysFetch:
try:
with open(fileName, "rb") as childrenFile:
childrenDic = pickle.load(childrenFile)
if root_id in childrenDic:
return childrenDic[root_id]
except:
pass
direction="INCOMING"
#neighbors = graph.getNeighbors(root_id, depth=maxDepth,
# relationshipType=relationshipType,
# direction=direction)
baseKS = "http://matrix.neuinfo.org:9000"
response = requests.get(baseKS + "/scigraph/graph/neighbors/" +
root_id + "?direction=" + direction +
"&depth=" + str(maxDepth) +
"&project=%2A&blankNodes=false&relationshipType="
+ relationshipType)
if not response.ok:
return {}
neighbors = response.json()
if neighbors is None:
return {}
nodes = neighbors["nodes"]
#for node in np.array(nodes):
# node["lbl"] = node["lbl"].encode('utf-8').decode('utf-8')
#try:
# assert(np.all([not node["lbl"] is None for node in np.array(nodes)]))
#except AssertionError:
# for node in np.array(nodes):
# if node["lbl"] is None:
# print(node["id"])
# raise
# TODO: replace by the commented line below. This patch is only to
# accomodate for a current issue with the knowledge-space endpoint.
#childrenDic[root_id] = OntoDic({node["id"]:node["lbl"] for node in np.array(nodes)})
childrenDic[root_id] = OntoDic({node["id"]:node["lbl"] for node in np.array(nodes) if not node["lbl"] is None})
if not alwaysFetch:
try:
with open(fileName, "wb") as childrenFile:
pickle.dump(childrenDic, childrenFile)
except:
pass
return childrenDic[root_id] | [
"def",
"getChildren",
"(",
"root_id",
",",
"maxDepth",
"=",
"100",
",",
"relationshipType",
"=",
"\"subClassOf\"",
",",
"alwaysFetch",
"=",
"False",
")",
":",
"childrenDic",
"=",
"{",
"}",
"fileName",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"children.bin\"",
")",
"#### CHECK FOR CASE OF BBP TAGS",
"if",
"root_id",
"[",
":",
"4",
"]",
"==",
"\"BBP_\"",
":",
"if",
"not",
"alwaysFetch",
":",
"try",
":",
"with",
"open",
"(",
"fileName",
",",
"\"rb\"",
")",
"as",
"childrenFile",
":",
"childrenDic",
"=",
"pickle",
".",
"load",
"(",
"childrenFile",
")",
"if",
"root_id",
"in",
"childrenDic",
":",
"return",
"childrenDic",
"[",
"root_id",
"]",
"except",
":",
"pass",
"childrenDic",
"[",
"root_id",
"]",
"=",
"getBBPChildren",
"(",
"root_id",
")",
"if",
"not",
"alwaysFetch",
":",
"try",
":",
"with",
"open",
"(",
"fileName",
",",
"\"wb\"",
")",
"as",
"childrenFile",
":",
"pickle",
".",
"dump",
"(",
"childrenDic",
",",
"childrenFile",
")",
"except",
":",
"pass",
"return",
"childrenDic",
"[",
"root_id",
"]",
"## TODO: should also check for BBP children of online onto terms",
"if",
"root_id",
"in",
"nlx2ks",
":",
"root_id",
"=",
"nlx2ks",
"[",
"root_id",
"]",
"if",
"not",
"alwaysFetch",
":",
"try",
":",
"with",
"open",
"(",
"fileName",
",",
"\"rb\"",
")",
"as",
"childrenFile",
":",
"childrenDic",
"=",
"pickle",
".",
"load",
"(",
"childrenFile",
")",
"if",
"root_id",
"in",
"childrenDic",
":",
"return",
"childrenDic",
"[",
"root_id",
"]",
"except",
":",
"pass",
"direction",
"=",
"\"INCOMING\"",
"#neighbors = graph.getNeighbors(root_id, depth=maxDepth, ",
"# relationshipType=relationshipType, ",
"# direction=direction)",
"baseKS",
"=",
"\"http://matrix.neuinfo.org:9000\"",
"response",
"=",
"requests",
".",
"get",
"(",
"baseKS",
"+",
"\"/scigraph/graph/neighbors/\"",
"+",
"root_id",
"+",
"\"?direction=\"",
"+",
"direction",
"+",
"\"&depth=\"",
"+",
"str",
"(",
"maxDepth",
")",
"+",
"\"&project=%2A&blankNodes=false&relationshipType=\"",
"+",
"relationshipType",
")",
"if",
"not",
"response",
".",
"ok",
":",
"return",
"{",
"}",
"neighbors",
"=",
"response",
".",
"json",
"(",
")",
"if",
"neighbors",
"is",
"None",
":",
"return",
"{",
"}",
"nodes",
"=",
"neighbors",
"[",
"\"nodes\"",
"]",
"#for node in np.array(nodes):",
"# node[\"lbl\"] = node[\"lbl\"].encode('utf-8').decode('utf-8')",
"#try:",
"# assert(np.all([not node[\"lbl\"] is None for node in np.array(nodes)]))",
"#except AssertionError: ",
"# for node in np.array(nodes):",
"# if node[\"lbl\"] is None:",
"# print(node[\"id\"])",
"# raise ",
"# TODO: replace by the commented line below. This patch is only to ",
"# accomodate for a current issue with the knowledge-space endpoint. ",
"#childrenDic[root_id] = OntoDic({node[\"id\"]:node[\"lbl\"] for node in np.array(nodes)}) ",
"childrenDic",
"[",
"root_id",
"]",
"=",
"OntoDic",
"(",
"{",
"node",
"[",
"\"id\"",
"]",
":",
"node",
"[",
"\"lbl\"",
"]",
"for",
"node",
"in",
"np",
".",
"array",
"(",
"nodes",
")",
"if",
"not",
"node",
"[",
"\"lbl\"",
"]",
"is",
"None",
"}",
")",
"if",
"not",
"alwaysFetch",
":",
"try",
":",
"with",
"open",
"(",
"fileName",
",",
"\"wb\"",
")",
"as",
"childrenFile",
":",
"pickle",
".",
"dump",
"(",
"childrenDic",
",",
"childrenFile",
")",
"except",
":",
"pass",
"return",
"childrenDic",
"[",
"root_id",
"]"
] | Accessing web-based ontology service is too long, so we cache the
information in a pickle file and query the services only if the info
has not already been cached. | [
"Accessing",
"web",
"-",
"based",
"ontology",
"service",
"is",
"too",
"long",
"so",
"we",
"cache",
"the",
"information",
"in",
"a",
"pickle",
"file",
"and",
"query",
"the",
"services",
"only",
"if",
"the",
"info",
"has",
"not",
"already",
"been",
"cached",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/treeData.py#L53-L146 |
lablup/backend.ai-common | src/ai/backend/common/plugin.py | install_plugins | def install_plugins(plugins, app, install_type, config):
"""
Automatically install plugins to the app.
:param plugins: List of plugin names to discover and install plugins
:param app: Any type of app to install plugins
:param install_type: The way to install plugins to app
:param config: Config object to initialize plugins
:return:
You should note that app can be any type of object. For instance,
when used in manager, app param is the instance of aiohttp.web.Application,
but it is the instance of subclass of aiozmq.rpc.AttrHandler in agents.
Therefore, you should specify :install_type: to install plugins into different
types of apps correctly. Currently we support two types of :install_type:,
which are 'attr' and 'dict'. For 'attr', plugins will be installed to app
as its attributes. For 'dict', plugins will be installed as following:
app[plugin_name] = plugin.
"""
try:
disable_plugins = config.disable_plugins
if not disable_plugins:
disable_plugins = []
except AttributeError:
disable_plugins = []
for plugin_name in plugins:
plugin_group = f'backendai_{plugin_name}_v10'
registry = PluginRegistry(plugin_name)
for entrypoint in pkg_resources.iter_entry_points(plugin_group):
if entrypoint.name in disable_plugins:
continue
log.info('Installing plugin: {}.{}', plugin_group, entrypoint.name)
plugin_module = entrypoint.load()
plugin = getattr(plugin_module, 'get_plugin')(config)
registry.register(plugin)
if install_type == 'attr':
setattr(app, plugin_name, registry)
elif install_type == 'dict':
assert isinstance(app, typing.MutableMapping), \
(f"app must be an instance of MutableMapping "
f"for 'dict' install_type.")
app[plugin_name] = registry
else:
raise ValueError(f'Invalid install type: {install_type}') | python | def install_plugins(plugins, app, install_type, config):
"""
Automatically install plugins to the app.
:param plugins: List of plugin names to discover and install plugins
:param app: Any type of app to install plugins
:param install_type: The way to install plugins to app
:param config: Config object to initialize plugins
:return:
You should note that app can be any type of object. For instance,
when used in manager, app param is the instance of aiohttp.web.Application,
but it is the instance of subclass of aiozmq.rpc.AttrHandler in agents.
Therefore, you should specify :install_type: to install plugins into different
types of apps correctly. Currently we support two types of :install_type:,
which are 'attr' and 'dict'. For 'attr', plugins will be installed to app
as its attributes. For 'dict', plugins will be installed as following:
app[plugin_name] = plugin.
"""
try:
disable_plugins = config.disable_plugins
if not disable_plugins:
disable_plugins = []
except AttributeError:
disable_plugins = []
for plugin_name in plugins:
plugin_group = f'backendai_{plugin_name}_v10'
registry = PluginRegistry(plugin_name)
for entrypoint in pkg_resources.iter_entry_points(plugin_group):
if entrypoint.name in disable_plugins:
continue
log.info('Installing plugin: {}.{}', plugin_group, entrypoint.name)
plugin_module = entrypoint.load()
plugin = getattr(plugin_module, 'get_plugin')(config)
registry.register(plugin)
if install_type == 'attr':
setattr(app, plugin_name, registry)
elif install_type == 'dict':
assert isinstance(app, typing.MutableMapping), \
(f"app must be an instance of MutableMapping "
f"for 'dict' install_type.")
app[plugin_name] = registry
else:
raise ValueError(f'Invalid install type: {install_type}') | [
"def",
"install_plugins",
"(",
"plugins",
",",
"app",
",",
"install_type",
",",
"config",
")",
":",
"try",
":",
"disable_plugins",
"=",
"config",
".",
"disable_plugins",
"if",
"not",
"disable_plugins",
":",
"disable_plugins",
"=",
"[",
"]",
"except",
"AttributeError",
":",
"disable_plugins",
"=",
"[",
"]",
"for",
"plugin_name",
"in",
"plugins",
":",
"plugin_group",
"=",
"f'backendai_{plugin_name}_v10'",
"registry",
"=",
"PluginRegistry",
"(",
"plugin_name",
")",
"for",
"entrypoint",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"plugin_group",
")",
":",
"if",
"entrypoint",
".",
"name",
"in",
"disable_plugins",
":",
"continue",
"log",
".",
"info",
"(",
"'Installing plugin: {}.{}'",
",",
"plugin_group",
",",
"entrypoint",
".",
"name",
")",
"plugin_module",
"=",
"entrypoint",
".",
"load",
"(",
")",
"plugin",
"=",
"getattr",
"(",
"plugin_module",
",",
"'get_plugin'",
")",
"(",
"config",
")",
"registry",
".",
"register",
"(",
"plugin",
")",
"if",
"install_type",
"==",
"'attr'",
":",
"setattr",
"(",
"app",
",",
"plugin_name",
",",
"registry",
")",
"elif",
"install_type",
"==",
"'dict'",
":",
"assert",
"isinstance",
"(",
"app",
",",
"typing",
".",
"MutableMapping",
")",
",",
"(",
"f\"app must be an instance of MutableMapping \"",
"f\"for 'dict' install_type.\"",
")",
"app",
"[",
"plugin_name",
"]",
"=",
"registry",
"else",
":",
"raise",
"ValueError",
"(",
"f'Invalid install type: {install_type}'",
")"
] | Automatically install plugins to the app.
:param plugins: List of plugin names to discover and install plugins
:param app: Any type of app to install plugins
:param install_type: The way to install plugins to app
:param config: Config object to initialize plugins
:return:
You should note that app can be any type of object. For instance,
when used in manager, app param is the instance of aiohttp.web.Application,
but it is the instance of subclass of aiozmq.rpc.AttrHandler in agents.
Therefore, you should specify :install_type: to install plugins into different
types of apps correctly. Currently we support two types of :install_type:,
which are 'attr' and 'dict'. For 'attr', plugins will be installed to app
as its attributes. For 'dict', plugins will be installed as following:
app[plugin_name] = plugin. | [
"Automatically",
"install",
"plugins",
"to",
"the",
"app",
"."
] | train | https://github.com/lablup/backend.ai-common/blob/20b3a2551ee5bb3b88e7836471bc244a70ad0ae6/src/ai/backend/common/plugin.py#L70-L114 |
siboles/pyFEBio | febio/MeshDef.py | MeshDef.addElement | def addElement(self,etype='hex8',corners=[-1.0,-1.0,-1.0,1.,-1.0,-1.0,1.0,1.0,-1.0,-1.0,1.0,-1.0,-1.0,-1.0,1.0,1.0,-1.0,1.0,1.0,1.0,1.0,-1.0,1.0,1.0],name='new_elem'):
'''
corners - list of nodal coordinates properly ordered for element type (counter clockwise)
'''
lastelm = self.elements[-1][1]
lastnode = self.nodes[-1][0]
elm = [etype,lastelm+1]
for i in range(old_div(len(corners),3)):
elm.append(lastnode+1+i)
self.elements.append(elm)
self.elsets['e'+name] = {}
self.elsets['e'+name][int(elm[1])] = True
cnt = 1
self.nsets['n'+name] = []
for i in range(0,len(corners),3):
self.nodes.append([lastnode+cnt, corners[i], corners[i+1], corners[i+2]])
self.nsets['n'+name].append(lastnode+cnt)
cnt += 1
# if this is a quad4 or tri3 element make a surface set
if etype == 'quad4' or etype == 'tri3':
self.fsets['f'+name] = [[etype, MeshDef.facetID, lastnode+1, lastnode+2, lastnode+3, lastnode+4]]
MeshDef.facetID += 1 | python | def addElement(self,etype='hex8',corners=[-1.0,-1.0,-1.0,1.,-1.0,-1.0,1.0,1.0,-1.0,-1.0,1.0,-1.0,-1.0,-1.0,1.0,1.0,-1.0,1.0,1.0,1.0,1.0,-1.0,1.0,1.0],name='new_elem'):
'''
corners - list of nodal coordinates properly ordered for element type (counter clockwise)
'''
lastelm = self.elements[-1][1]
lastnode = self.nodes[-1][0]
elm = [etype,lastelm+1]
for i in range(old_div(len(corners),3)):
elm.append(lastnode+1+i)
self.elements.append(elm)
self.elsets['e'+name] = {}
self.elsets['e'+name][int(elm[1])] = True
cnt = 1
self.nsets['n'+name] = []
for i in range(0,len(corners),3):
self.nodes.append([lastnode+cnt, corners[i], corners[i+1], corners[i+2]])
self.nsets['n'+name].append(lastnode+cnt)
cnt += 1
# if this is a quad4 or tri3 element make a surface set
if etype == 'quad4' or etype == 'tri3':
self.fsets['f'+name] = [[etype, MeshDef.facetID, lastnode+1, lastnode+2, lastnode+3, lastnode+4]]
MeshDef.facetID += 1 | [
"def",
"addElement",
"(",
"self",
",",
"etype",
"=",
"'hex8'",
",",
"corners",
"=",
"[",
"-",
"1.0",
",",
"-",
"1.0",
",",
"-",
"1.0",
",",
"1.",
",",
"-",
"1.0",
",",
"-",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"-",
"1.0",
",",
"-",
"1.0",
",",
"1.0",
",",
"-",
"1.0",
",",
"-",
"1.0",
",",
"-",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"-",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"-",
"1.0",
",",
"1.0",
",",
"1.0",
"]",
",",
"name",
"=",
"'new_elem'",
")",
":",
"lastelm",
"=",
"self",
".",
"elements",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"lastnode",
"=",
"self",
".",
"nodes",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"elm",
"=",
"[",
"etype",
",",
"lastelm",
"+",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"old_div",
"(",
"len",
"(",
"corners",
")",
",",
"3",
")",
")",
":",
"elm",
".",
"append",
"(",
"lastnode",
"+",
"1",
"+",
"i",
")",
"self",
".",
"elements",
".",
"append",
"(",
"elm",
")",
"self",
".",
"elsets",
"[",
"'e'",
"+",
"name",
"]",
"=",
"{",
"}",
"self",
".",
"elsets",
"[",
"'e'",
"+",
"name",
"]",
"[",
"int",
"(",
"elm",
"[",
"1",
"]",
")",
"]",
"=",
"True",
"cnt",
"=",
"1",
"self",
".",
"nsets",
"[",
"'n'",
"+",
"name",
"]",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"corners",
")",
",",
"3",
")",
":",
"self",
".",
"nodes",
".",
"append",
"(",
"[",
"lastnode",
"+",
"cnt",
",",
"corners",
"[",
"i",
"]",
",",
"corners",
"[",
"i",
"+",
"1",
"]",
",",
"corners",
"[",
"i",
"+",
"2",
"]",
"]",
")",
"self",
".",
"nsets",
"[",
"'n'",
"+",
"name",
"]",
".",
"append",
"(",
"lastnode",
"+",
"cnt",
")",
"cnt",
"+=",
"1",
"# if this is a quad4 or tri3 element make a surface set",
"if",
"etype",
"==",
"'quad4'",
"or",
"etype",
"==",
"'tri3'",
":",
"self",
".",
"fsets",
"[",
"'f'",
"+",
"name",
"]",
"=",
"[",
"[",
"etype",
",",
"MeshDef",
".",
"facetID",
",",
"lastnode",
"+",
"1",
",",
"lastnode",
"+",
"2",
",",
"lastnode",
"+",
"3",
",",
"lastnode",
"+",
"4",
"]",
"]",
"MeshDef",
".",
"facetID",
"+=",
"1"
] | corners - list of nodal coordinates properly ordered for element type (counter clockwise) | [
"corners",
"-",
"list",
"of",
"nodal",
"coordinates",
"properly",
"ordered",
"for",
"element",
"type",
"(",
"counter",
"clockwise",
")"
] | train | https://github.com/siboles/pyFEBio/blob/95083a558c34b236ad4e197b558099dc15f9e319/febio/MeshDef.py#L145-L169 |
BlueBrain/nat | nat/scigraph_client.py | Graph.getEdges | def getEdges(self, type, entail='true', limit=100, skip=0, callback=None, output='application/json'):
""" Get nodes connected by an edge type from: /graph/edges/{type}
Arguments:
type: The type of the edge
entail: Should subproperties and equivalent properties be included
limit: The number of edges to be returned
skip: The number of edges to skip
callback: Name of the JSONP callback ('fn' by default). Supplying this parameter or
requesting a javascript media type will cause a JSONP response to be
rendered.
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
kwargs = {'type':type, 'entail':entail, 'limit':limit, 'skip':skip, 'callback':callback}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('type', **kwargs)
url = self._basePath + ('/graph/edges/{type}').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'type'}
return self._get('GET', url, requests_params, output) | python | def getEdges(self, type, entail='true', limit=100, skip=0, callback=None, output='application/json'):
""" Get nodes connected by an edge type from: /graph/edges/{type}
Arguments:
type: The type of the edge
entail: Should subproperties and equivalent properties be included
limit: The number of edges to be returned
skip: The number of edges to skip
callback: Name of the JSONP callback ('fn' by default). Supplying this parameter or
requesting a javascript media type will cause a JSONP response to be
rendered.
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
kwargs = {'type':type, 'entail':entail, 'limit':limit, 'skip':skip, 'callback':callback}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('type', **kwargs)
url = self._basePath + ('/graph/edges/{type}').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'type'}
return self._get('GET', url, requests_params, output) | [
"def",
"getEdges",
"(",
"self",
",",
"type",
",",
"entail",
"=",
"'true'",
",",
"limit",
"=",
"100",
",",
"skip",
"=",
"0",
",",
"callback",
"=",
"None",
",",
"output",
"=",
"'application/json'",
")",
":",
"kwargs",
"=",
"{",
"'type'",
":",
"type",
",",
"'entail'",
":",
"entail",
",",
"'limit'",
":",
"limit",
",",
"'skip'",
":",
"skip",
",",
"'callback'",
":",
"callback",
"}",
"kwargs",
"=",
"{",
"k",
":",
"dumps",
"(",
"v",
")",
"if",
"type",
"(",
"v",
")",
"is",
"dict",
"else",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"}",
"param_rest",
"=",
"self",
".",
"_make_rest",
"(",
"'type'",
",",
"*",
"*",
"kwargs",
")",
"url",
"=",
"self",
".",
"_basePath",
"+",
"(",
"'/graph/edges/{type}'",
")",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
"requests_params",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"k",
"!=",
"'type'",
"}",
"return",
"self",
".",
"_get",
"(",
"'GET'",
",",
"url",
",",
"requests_params",
",",
"output",
")"
] | Get nodes connected by an edge type from: /graph/edges/{type}
Arguments:
type: The type of the edge
entail: Should subproperties and equivalent properties be included
limit: The number of edges to be returned
skip: The number of edges to skip
callback: Name of the JSONP callback ('fn' by default). Supplying this parameter or
requesting a javascript media type will cause a JSONP response to be
rendered.
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png | [
"Get",
"nodes",
"connected",
"by",
"an",
"edge",
"type",
"from",
":",
"/",
"graph",
"/",
"edges",
"/",
"{",
"type",
"}",
"Arguments",
":",
"type",
":",
"The",
"type",
"of",
"the",
"edge",
"entail",
":",
"Should",
"subproperties",
"and",
"equivalent",
"properties",
"be",
"included",
"limit",
":",
"The",
"number",
"of",
"edges",
"to",
"be",
"returned",
"skip",
":",
"The",
"number",
"of",
"edges",
"to",
"skip",
"callback",
":",
"Name",
"of",
"the",
"JSONP",
"callback",
"(",
"fn",
"by",
"default",
")",
".",
"Supplying",
"this",
"parameter",
"or",
"requesting",
"a",
"javascript",
"media",
"type",
"will",
"cause",
"a",
"JSONP",
"response",
"to",
"be",
"rendered",
".",
"outputs",
":",
"application",
"/",
"json",
"application",
"/",
"graphson",
"application",
"/",
"xml",
"application",
"/",
"graphml",
"+",
"xml",
"application",
"/",
"xgmml",
"text",
"/",
"gml",
"text",
"/",
"csv",
"text",
"/",
"tab",
"-",
"separated",
"-",
"values",
"image",
"/",
"jpeg",
"image",
"/",
"png"
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/scigraph_client.py#L96-L124 |
BlueBrain/nat | nat/scigraph_client.py | Graph.getNeighbors | def getNeighbors(self, id, depth=1, blankNodes='false', relationshipType=None, direction='BOTH', project='*', callback=None, output='application/json'):
""" Get neighbors from: /graph/neighbors/{id}
Arguments:
id: This ID should be either a CURIE or an IRI
depth: How far to traverse neighbors
blankNodes: Traverse blank nodes
relationshipType: Which relationship to traverse
direction: Which direction to traverse: INCOMING, OUTGOING, BOTH (default). Only used if relationshipType is specified.
project: Which properties to project. Defaults to '*'.
callback: Name of the JSONP callback ('fn' by default). Supplying this parameter or
requesting a javascript media type will cause a JSONP response to be
rendered.
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
kwargs = {'id':id, 'depth':depth, 'blankNodes':blankNodes, 'relationshipType':relationshipType, 'direction':direction, 'project':project, 'callback':callback}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('id', **kwargs)
url = self._basePath + ('/graph/neighbors/{id}').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'id'}
return self._get('GET', url, requests_params, output) | python | def getNeighbors(self, id, depth=1, blankNodes='false', relationshipType=None, direction='BOTH', project='*', callback=None, output='application/json'):
""" Get neighbors from: /graph/neighbors/{id}
Arguments:
id: This ID should be either a CURIE or an IRI
depth: How far to traverse neighbors
blankNodes: Traverse blank nodes
relationshipType: Which relationship to traverse
direction: Which direction to traverse: INCOMING, OUTGOING, BOTH (default). Only used if relationshipType is specified.
project: Which properties to project. Defaults to '*'.
callback: Name of the JSONP callback ('fn' by default). Supplying this parameter or
requesting a javascript media type will cause a JSONP response to be
rendered.
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
kwargs = {'id':id, 'depth':depth, 'blankNodes':blankNodes, 'relationshipType':relationshipType, 'direction':direction, 'project':project, 'callback':callback}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('id', **kwargs)
url = self._basePath + ('/graph/neighbors/{id}').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'id'}
return self._get('GET', url, requests_params, output) | [
"def",
"getNeighbors",
"(",
"self",
",",
"id",
",",
"depth",
"=",
"1",
",",
"blankNodes",
"=",
"'false'",
",",
"relationshipType",
"=",
"None",
",",
"direction",
"=",
"'BOTH'",
",",
"project",
"=",
"'*'",
",",
"callback",
"=",
"None",
",",
"output",
"=",
"'application/json'",
")",
":",
"kwargs",
"=",
"{",
"'id'",
":",
"id",
",",
"'depth'",
":",
"depth",
",",
"'blankNodes'",
":",
"blankNodes",
",",
"'relationshipType'",
":",
"relationshipType",
",",
"'direction'",
":",
"direction",
",",
"'project'",
":",
"project",
",",
"'callback'",
":",
"callback",
"}",
"kwargs",
"=",
"{",
"k",
":",
"dumps",
"(",
"v",
")",
"if",
"type",
"(",
"v",
")",
"is",
"dict",
"else",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"}",
"param_rest",
"=",
"self",
".",
"_make_rest",
"(",
"'id'",
",",
"*",
"*",
"kwargs",
")",
"url",
"=",
"self",
".",
"_basePath",
"+",
"(",
"'/graph/neighbors/{id}'",
")",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
"requests_params",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"k",
"!=",
"'id'",
"}",
"return",
"self",
".",
"_get",
"(",
"'GET'",
",",
"url",
",",
"requests_params",
",",
"output",
")"
] | Get neighbors from: /graph/neighbors/{id}
Arguments:
id: This ID should be either a CURIE or an IRI
depth: How far to traverse neighbors
blankNodes: Traverse blank nodes
relationshipType: Which relationship to traverse
direction: Which direction to traverse: INCOMING, OUTGOING, BOTH (default). Only used if relationshipType is specified.
project: Which properties to project. Defaults to '*'.
callback: Name of the JSONP callback ('fn' by default). Supplying this parameter or
requesting a javascript media type will cause a JSONP response to be
rendered.
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png | [
"Get",
"neighbors",
"from",
":",
"/",
"graph",
"/",
"neighbors",
"/",
"{",
"id",
"}",
"Arguments",
":",
"id",
":",
"This",
"ID",
"should",
"be",
"either",
"a",
"CURIE",
"or",
"an",
"IRI",
"depth",
":",
"How",
"far",
"to",
"traverse",
"neighbors",
"blankNodes",
":",
"Traverse",
"blank",
"nodes",
"relationshipType",
":",
"Which",
"relationship",
"to",
"traverse",
"direction",
":",
"Which",
"direction",
"to",
"traverse",
":",
"INCOMING",
"OUTGOING",
"BOTH",
"(",
"default",
")",
".",
"Only",
"used",
"if",
"relationshipType",
"is",
"specified",
".",
"project",
":",
"Which",
"properties",
"to",
"project",
".",
"Defaults",
"to",
"*",
".",
"callback",
":",
"Name",
"of",
"the",
"JSONP",
"callback",
"(",
"fn",
"by",
"default",
")",
".",
"Supplying",
"this",
"parameter",
"or",
"requesting",
"a",
"javascript",
"media",
"type",
"will",
"cause",
"a",
"JSONP",
"response",
"to",
"be",
"rendered",
".",
"outputs",
":",
"application",
"/",
"json",
"application",
"/",
"graphson",
"application",
"/",
"xml",
"application",
"/",
"graphml",
"+",
"xml",
"application",
"/",
"xgmml",
"text",
"/",
"gml",
"text",
"/",
"csv",
"text",
"/",
"tab",
"-",
"separated",
"-",
"values",
"image",
"/",
"jpeg",
"image",
"/",
"png"
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/scigraph_client.py#L143-L173 |
BlueBrain/nat | nat/scigraph_client.py | Analyzer.enrich | def enrich(self, sample, ontologyClass, path, callback=None, output='application/json'):
""" Class Enrichment Service from: /analyzer/enrichment
Arguments:
sample: A list of CURIEs for nodes whose attributes are to be tested for enrichment. For example, a list of genes.
ontologyClass: CURIE for parent ontology class for the attribute to be tested. For example, GO biological process
path: A path expression that connects sample nodes to attribute class nodes
callback: Name of the JSONP callback ('fn' by default). Supplying this parameter or
requesting a javascript media type will cause a JSONP response to be
rendered.
outputs:
application/json
"""
kwargs = {'sample':sample, 'ontologyClass':ontologyClass, 'path':path, 'callback':callback}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('path', **kwargs)
url = self._basePath + ('/analyzer/enrichment').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'path'}
return self._get('GET', url, requests_params, output) | python | def enrich(self, sample, ontologyClass, path, callback=None, output='application/json'):
""" Class Enrichment Service from: /analyzer/enrichment
Arguments:
sample: A list of CURIEs for nodes whose attributes are to be tested for enrichment. For example, a list of genes.
ontologyClass: CURIE for parent ontology class for the attribute to be tested. For example, GO biological process
path: A path expression that connects sample nodes to attribute class nodes
callback: Name of the JSONP callback ('fn' by default). Supplying this parameter or
requesting a javascript media type will cause a JSONP response to be
rendered.
outputs:
application/json
"""
kwargs = {'sample':sample, 'ontologyClass':ontologyClass, 'path':path, 'callback':callback}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('path', **kwargs)
url = self._basePath + ('/analyzer/enrichment').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'path'}
return self._get('GET', url, requests_params, output) | [
"def",
"enrich",
"(",
"self",
",",
"sample",
",",
"ontologyClass",
",",
"path",
",",
"callback",
"=",
"None",
",",
"output",
"=",
"'application/json'",
")",
":",
"kwargs",
"=",
"{",
"'sample'",
":",
"sample",
",",
"'ontologyClass'",
":",
"ontologyClass",
",",
"'path'",
":",
"path",
",",
"'callback'",
":",
"callback",
"}",
"kwargs",
"=",
"{",
"k",
":",
"dumps",
"(",
"v",
")",
"if",
"type",
"(",
"v",
")",
"is",
"dict",
"else",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"}",
"param_rest",
"=",
"self",
".",
"_make_rest",
"(",
"'path'",
",",
"*",
"*",
"kwargs",
")",
"url",
"=",
"self",
".",
"_basePath",
"+",
"(",
"'/analyzer/enrichment'",
")",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
"requests_params",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"k",
"!=",
"'path'",
"}",
"return",
"self",
".",
"_get",
"(",
"'GET'",
",",
"url",
",",
"requests_params",
",",
"output",
")"
] | Class Enrichment Service from: /analyzer/enrichment
Arguments:
sample: A list of CURIEs for nodes whose attributes are to be tested for enrichment. For example, a list of genes.
ontologyClass: CURIE for parent ontology class for the attribute to be tested. For example, GO biological process
path: A path expression that connects sample nodes to attribute class nodes
callback: Name of the JSONP callback ('fn' by default). Supplying this parameter or
requesting a javascript media type will cause a JSONP response to be
rendered.
outputs:
application/json | [
"Class",
"Enrichment",
"Service",
"from",
":",
"/",
"analyzer",
"/",
"enrichment",
"Arguments",
":",
"sample",
":",
"A",
"list",
"of",
"CURIEs",
"for",
"nodes",
"whose",
"attributes",
"are",
"to",
"be",
"tested",
"for",
"enrichment",
".",
"For",
"example",
"a",
"list",
"of",
"genes",
".",
"ontologyClass",
":",
"CURIE",
"for",
"parent",
"ontology",
"class",
"for",
"the",
"attribute",
"to",
"be",
"tested",
".",
"For",
"example",
"GO",
"biological",
"process",
"path",
":",
"A",
"path",
"expression",
"that",
"connects",
"sample",
"nodes",
"to",
"attribute",
"class",
"nodes",
"callback",
":",
"Name",
"of",
"the",
"JSONP",
"callback",
"(",
"fn",
"by",
"default",
")",
".",
"Supplying",
"this",
"parameter",
"or",
"requesting",
"a",
"javascript",
"media",
"type",
"will",
"cause",
"a",
"JSONP",
"response",
"to",
"be",
"rendered",
".",
"outputs",
":",
"application",
"/",
"json"
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/scigraph_client.py#L286-L304 |
BlueBrain/nat | nat/scigraph_client.py | Annotations.annotatePost | def annotatePost(self, content, includeCat=None, excludeCat=None, minLength=4, longestOnly='false', includeAbbrev='false', includeAcronym='false', includeNumbers='false', ignoreTag=None, stylesheet=None, scripts=None, targetId=None, targetClass=None):
""" Annotate text from: /annotations
Arguments:
content: The content to annotate
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Should only the longest entity be returned for an overlapping group
includeAbbrev: Should abbreviations be included
includeAcronym: Should acronyms be included
includeNumbers: Should numbers be included
ignoreTag: HTML tags that should not be annotated
stylesheet: CSS stylesheets to add to the HEAD
scripts: JavaScripts that should to add to the HEAD
targetId: A set of element IDs to annotate
targetClass: A set of CSS class names to annotate
"""
kwargs = {'content':content, 'includeCat':includeCat, 'excludeCat':excludeCat, 'minLength':minLength, 'longestOnly':longestOnly, 'includeAbbrev':includeAbbrev, 'includeAcronym':includeAcronym, 'includeNumbers':includeNumbers, 'ignoreTag':ignoreTag, 'stylesheet':stylesheet, 'scripts':scripts, 'targetId':targetId, 'targetClass':targetClass}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('content', **kwargs)
url = self._basePath + ('/annotations').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'content'}
return self._get('POST', url, requests_params) | python | def annotatePost(self, content, includeCat=None, excludeCat=None, minLength=4, longestOnly='false', includeAbbrev='false', includeAcronym='false', includeNumbers='false', ignoreTag=None, stylesheet=None, scripts=None, targetId=None, targetClass=None):
""" Annotate text from: /annotations
Arguments:
content: The content to annotate
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Should only the longest entity be returned for an overlapping group
includeAbbrev: Should abbreviations be included
includeAcronym: Should acronyms be included
includeNumbers: Should numbers be included
ignoreTag: HTML tags that should not be annotated
stylesheet: CSS stylesheets to add to the HEAD
scripts: JavaScripts that should to add to the HEAD
targetId: A set of element IDs to annotate
targetClass: A set of CSS class names to annotate
"""
kwargs = {'content':content, 'includeCat':includeCat, 'excludeCat':excludeCat, 'minLength':minLength, 'longestOnly':longestOnly, 'includeAbbrev':includeAbbrev, 'includeAcronym':includeAcronym, 'includeNumbers':includeNumbers, 'ignoreTag':ignoreTag, 'stylesheet':stylesheet, 'scripts':scripts, 'targetId':targetId, 'targetClass':targetClass}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('content', **kwargs)
url = self._basePath + ('/annotations').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'content'}
return self._get('POST', url, requests_params) | [
"def",
"annotatePost",
"(",
"self",
",",
"content",
",",
"includeCat",
"=",
"None",
",",
"excludeCat",
"=",
"None",
",",
"minLength",
"=",
"4",
",",
"longestOnly",
"=",
"'false'",
",",
"includeAbbrev",
"=",
"'false'",
",",
"includeAcronym",
"=",
"'false'",
",",
"includeNumbers",
"=",
"'false'",
",",
"ignoreTag",
"=",
"None",
",",
"stylesheet",
"=",
"None",
",",
"scripts",
"=",
"None",
",",
"targetId",
"=",
"None",
",",
"targetClass",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"'content'",
":",
"content",
",",
"'includeCat'",
":",
"includeCat",
",",
"'excludeCat'",
":",
"excludeCat",
",",
"'minLength'",
":",
"minLength",
",",
"'longestOnly'",
":",
"longestOnly",
",",
"'includeAbbrev'",
":",
"includeAbbrev",
",",
"'includeAcronym'",
":",
"includeAcronym",
",",
"'includeNumbers'",
":",
"includeNumbers",
",",
"'ignoreTag'",
":",
"ignoreTag",
",",
"'stylesheet'",
":",
"stylesheet",
",",
"'scripts'",
":",
"scripts",
",",
"'targetId'",
":",
"targetId",
",",
"'targetClass'",
":",
"targetClass",
"}",
"kwargs",
"=",
"{",
"k",
":",
"dumps",
"(",
"v",
")",
"if",
"type",
"(",
"v",
")",
"is",
"dict",
"else",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"}",
"param_rest",
"=",
"self",
".",
"_make_rest",
"(",
"'content'",
",",
"*",
"*",
"kwargs",
")",
"url",
"=",
"self",
".",
"_basePath",
"+",
"(",
"'/annotations'",
")",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
"requests_params",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"k",
"!=",
"'content'",
"}",
"return",
"self",
".",
"_get",
"(",
"'POST'",
",",
"url",
",",
"requests_params",
")"
] | Annotate text from: /annotations
Arguments:
content: The content to annotate
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Should only the longest entity be returned for an overlapping group
includeAbbrev: Should abbreviations be included
includeAcronym: Should acronyms be included
includeNumbers: Should numbers be included
ignoreTag: HTML tags that should not be annotated
stylesheet: CSS stylesheets to add to the HEAD
scripts: JavaScripts that should to add to the HEAD
targetId: A set of element IDs to annotate
targetClass: A set of CSS class names to annotate | [
"Annotate",
"text",
"from",
":",
"/",
"annotations",
"Arguments",
":",
"content",
":",
"The",
"content",
"to",
"annotate",
"includeCat",
":",
"A",
"set",
"of",
"categories",
"to",
"include",
"excludeCat",
":",
"A",
"set",
"of",
"categories",
"to",
"exclude",
"minLength",
":",
"The",
"minimum",
"number",
"of",
"characters",
"in",
"annotated",
"entities",
"longestOnly",
":",
"Should",
"only",
"the",
"longest",
"entity",
"be",
"returned",
"for",
"an",
"overlapping",
"group",
"includeAbbrev",
":",
"Should",
"abbreviations",
"be",
"included",
"includeAcronym",
":",
"Should",
"acronyms",
"be",
"included",
"includeNumbers",
":",
"Should",
"numbers",
"be",
"included",
"ignoreTag",
":",
"HTML",
"tags",
"that",
"should",
"not",
"be",
"annotated",
"stylesheet",
":",
"CSS",
"stylesheets",
"to",
"add",
"to",
"the",
"HEAD",
"scripts",
":",
"JavaScripts",
"that",
"should",
"to",
"add",
"to",
"the",
"HEAD",
"targetId",
":",
"A",
"set",
"of",
"element",
"IDs",
"to",
"annotate",
"targetClass",
":",
"A",
"set",
"of",
"CSS",
"class",
"names",
"to",
"annotate"
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/scigraph_client.py#L399-L422 |
BlueBrain/nat | nat/scigraph_client.py | Lexical.getPos | def getPos(self, text):
""" Tag parts of speech. from: /lexical/pos
Arguments:
text: The text to tag
"""
kwargs = {'text':text}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('text', **kwargs)
url = self._basePath + ('/lexical/pos').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'text'}
return self._get('GET', url, requests_params) | python | def getPos(self, text):
""" Tag parts of speech. from: /lexical/pos
Arguments:
text: The text to tag
"""
kwargs = {'text':text}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('text', **kwargs)
url = self._basePath + ('/lexical/pos').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'text'}
return self._get('GET', url, requests_params) | [
"def",
"getPos",
"(",
"self",
",",
"text",
")",
":",
"kwargs",
"=",
"{",
"'text'",
":",
"text",
"}",
"kwargs",
"=",
"{",
"k",
":",
"dumps",
"(",
"v",
")",
"if",
"type",
"(",
"v",
")",
"is",
"dict",
"else",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"}",
"param_rest",
"=",
"self",
".",
"_make_rest",
"(",
"'text'",
",",
"*",
"*",
"kwargs",
")",
"url",
"=",
"self",
".",
"_basePath",
"+",
"(",
"'/lexical/pos'",
")",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
"requests_params",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"k",
"!=",
"'text'",
"}",
"return",
"self",
".",
"_get",
"(",
"'GET'",
",",
"url",
",",
"requests_params",
")"
] | Tag parts of speech. from: /lexical/pos
Arguments:
text: The text to tag | [
"Tag",
"parts",
"of",
"speech",
".",
"from",
":",
"/",
"lexical",
"/",
"pos",
"Arguments",
":",
"text",
":",
"The",
"text",
"to",
"tag"
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/scigraph_client.py#L538-L549 |
BlueBrain/nat | nat/scigraph_client.py | Vocabulary.findByPrefix | def findByPrefix(self, term, limit=20, searchSynonyms='true', searchAbbreviations='false', searchAcronyms='false', includeDeprecated='false', category=None, prefix=None):
""" Find a concept by its prefix from: /vocabulary/autocomplete/{term}
Arguments:
term: Term prefix to find
limit: Maximum result count
searchSynonyms: Should synonyms be matched
searchAbbreviations: Should abbreviations be matched
searchAcronyms: Should acronyms be matched
includeDeprecated: Should deprecated classes be included
category: Categories to search (defaults to all)
prefix: CURIE prefixes to search (defaults to all)
"""
kwargs = {'term':term, 'limit':limit, 'searchSynonyms':searchSynonyms, 'searchAbbreviations':searchAbbreviations, 'searchAcronyms':searchAcronyms, 'includeDeprecated':includeDeprecated, 'category':category, 'prefix':prefix}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('term', **kwargs)
url = self._basePath + ('/vocabulary/autocomplete/{term}').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'term'}
return self._get('GET', url, requests_params) | python | def findByPrefix(self, term, limit=20, searchSynonyms='true', searchAbbreviations='false', searchAcronyms='false', includeDeprecated='false', category=None, prefix=None):
""" Find a concept by its prefix from: /vocabulary/autocomplete/{term}
Arguments:
term: Term prefix to find
limit: Maximum result count
searchSynonyms: Should synonyms be matched
searchAbbreviations: Should abbreviations be matched
searchAcronyms: Should acronyms be matched
includeDeprecated: Should deprecated classes be included
category: Categories to search (defaults to all)
prefix: CURIE prefixes to search (defaults to all)
"""
kwargs = {'term':term, 'limit':limit, 'searchSynonyms':searchSynonyms, 'searchAbbreviations':searchAbbreviations, 'searchAcronyms':searchAcronyms, 'includeDeprecated':includeDeprecated, 'category':category, 'prefix':prefix}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('term', **kwargs)
url = self._basePath + ('/vocabulary/autocomplete/{term}').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'term'}
return self._get('GET', url, requests_params) | [
"def",
"findByPrefix",
"(",
"self",
",",
"term",
",",
"limit",
"=",
"20",
",",
"searchSynonyms",
"=",
"'true'",
",",
"searchAbbreviations",
"=",
"'false'",
",",
"searchAcronyms",
"=",
"'false'",
",",
"includeDeprecated",
"=",
"'false'",
",",
"category",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"'term'",
":",
"term",
",",
"'limit'",
":",
"limit",
",",
"'searchSynonyms'",
":",
"searchSynonyms",
",",
"'searchAbbreviations'",
":",
"searchAbbreviations",
",",
"'searchAcronyms'",
":",
"searchAcronyms",
",",
"'includeDeprecated'",
":",
"includeDeprecated",
",",
"'category'",
":",
"category",
",",
"'prefix'",
":",
"prefix",
"}",
"kwargs",
"=",
"{",
"k",
":",
"dumps",
"(",
"v",
")",
"if",
"type",
"(",
"v",
")",
"is",
"dict",
"else",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"}",
"param_rest",
"=",
"self",
".",
"_make_rest",
"(",
"'term'",
",",
"*",
"*",
"kwargs",
")",
"url",
"=",
"self",
".",
"_basePath",
"+",
"(",
"'/vocabulary/autocomplete/{term}'",
")",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
"requests_params",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"k",
"!=",
"'term'",
"}",
"return",
"self",
".",
"_get",
"(",
"'GET'",
",",
"url",
",",
"requests_params",
")"
] | Find a concept by its prefix from: /vocabulary/autocomplete/{term}
Arguments:
term: Term prefix to find
limit: Maximum result count
searchSynonyms: Should synonyms be matched
searchAbbreviations: Should abbreviations be matched
searchAcronyms: Should acronyms be matched
includeDeprecated: Should deprecated classes be included
category: Categories to search (defaults to all)
prefix: CURIE prefixes to search (defaults to all) | [
"Find",
"a",
"concept",
"by",
"its",
"prefix",
"from",
":",
"/",
"vocabulary",
"/",
"autocomplete",
"/",
"{",
"term",
"}",
"Arguments",
":",
"term",
":",
"Term",
"prefix",
"to",
"find",
"limit",
":",
"Maximum",
"result",
"count",
"searchSynonyms",
":",
"Should",
"synonyms",
"be",
"matched",
"searchAbbreviations",
":",
"Should",
"abbreviations",
"be",
"matched",
"searchAcronyms",
":",
"Should",
"acronyms",
"be",
"matched",
"includeDeprecated",
":",
"Should",
"deprecated",
"classes",
"be",
"included",
"category",
":",
"Categories",
"to",
"search",
"(",
"defaults",
"to",
"all",
")",
"prefix",
":",
"CURIE",
"prefixes",
"to",
"search",
"(",
"defaults",
"to",
"all",
")"
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/scigraph_client.py#L585-L603 |
RI-imaging/nrefocus | examples/example_helper.py | load_cell | def load_cell(fname="HL60_field.zip"):
"Load zip file and return complex field"
here = op.dirname(op.abspath(__file__))
data = op.join(here, "data")
arc = zipfile.ZipFile(op.join(data, fname))
for f in arc.filelist:
with arc.open(f) as fd:
if f.filename.count("imag"):
imag = np.loadtxt(fd)
elif f.filename.count("real"):
real = np.loadtxt(fd)
field = real + 1j * imag
return field | python | def load_cell(fname="HL60_field.zip"):
"Load zip file and return complex field"
here = op.dirname(op.abspath(__file__))
data = op.join(here, "data")
arc = zipfile.ZipFile(op.join(data, fname))
for f in arc.filelist:
with arc.open(f) as fd:
if f.filename.count("imag"):
imag = np.loadtxt(fd)
elif f.filename.count("real"):
real = np.loadtxt(fd)
field = real + 1j * imag
return field | [
"def",
"load_cell",
"(",
"fname",
"=",
"\"HL60_field.zip\"",
")",
":",
"here",
"=",
"op",
".",
"dirname",
"(",
"op",
".",
"abspath",
"(",
"__file__",
")",
")",
"data",
"=",
"op",
".",
"join",
"(",
"here",
",",
"\"data\"",
")",
"arc",
"=",
"zipfile",
".",
"ZipFile",
"(",
"op",
".",
"join",
"(",
"data",
",",
"fname",
")",
")",
"for",
"f",
"in",
"arc",
".",
"filelist",
":",
"with",
"arc",
".",
"open",
"(",
"f",
")",
"as",
"fd",
":",
"if",
"f",
".",
"filename",
".",
"count",
"(",
"\"imag\"",
")",
":",
"imag",
"=",
"np",
".",
"loadtxt",
"(",
"fd",
")",
"elif",
"f",
".",
"filename",
".",
"count",
"(",
"\"real\"",
")",
":",
"real",
"=",
"np",
".",
"loadtxt",
"(",
"fd",
")",
"field",
"=",
"real",
"+",
"1j",
"*",
"imag",
"return",
"field"
] | Load zip file and return complex field | [
"Load",
"zip",
"file",
"and",
"return",
"complex",
"field"
] | train | https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/examples/example_helper.py#L7-L21 |
rainwoodman/kdcount | kdcount/sphere.py | bootstrap | def bootstrap(nside, rand, nbar, *data):
""" This function will bootstrap data based on the sky coverage of rand.
It is different from bootstrap in the traditional sense, but for correlation
functions it gives the correct answer with less computation.
nbar : number density of rand, used to estimate the effective area of a pixel
nside : number of healpix pixels per side to use
*data : a list of data -- will be binned on the same regions.
small regions (incomplete pixels) are combined such that the total
area is about the same (a healpix pixel) in each returned boot strap sample
Yields: area, random, *data
rand and *data are in (RA, DEC)
Example:
>>> for area, ran, data1, data2 in bootstrap(4, ran, 100., data1, data2):
>>> # Do stuff
>>> pass
"""
def split(data, indices, axis):
""" This function splits array. It fixes the bug
in numpy that zero length array are improperly handled.
In the future this will be fixed.
"""
s = []
s.append(slice(0, indices[0]))
for i in range(len(indices) - 1):
s.append(slice(indices[i], indices[i+1]))
s.append(slice(indices[-1], None))
rt = []
for ss in s:
ind = [slice(None, None, None) for i in range(len(data.shape))]
ind[axis] = ss
ind = tuple(ind)
rt.append(data[ind])
return rt
def hpsplit(nside, data):
# data is (RA, DEC)
RA, DEC = data
pix = radec2pix(nside, RA, DEC)
n = numpy.bincount(pix)
a = numpy.argsort(pix)
data = numpy.array(data)[:, a]
rt = split(data, n.cumsum(), axis=-1)
return rt
# mean area of sky.
Abar = 41252.96 / nside2npix(nside)
rand = hpsplit(nside, rand)
if len(data) > 0:
data = [list(i) for i in zip(*[hpsplit(nside, d1) for d1 in data])]
else:
data = [[] for i in range(len(rand))]
heap = []
j = 0
for r, d in zip(rand, data):
if len(r[0]) == 0: continue
a = 1.0 * len(r[0]) / nbar
j = j + 1
if len(heap) == 0:
heapq.heappush(heap, (a, j, r, d))
else:
a0, j0, r0, d0 = heapq.heappop(heap)
if a0 + a < Abar:
a0 += a
d0 = [
numpy.concatenate((d0[i], d[i]), axis=-1)
for i in range(len(d))
]
r0 = numpy.concatenate((r0, r), axis=-1)
else:
heapq.heappush(heap, (a, j, r, d))
heapq.heappush(heap, (a0, j0, r0, d0))
for i in range(len(heap)):
area, j, r, d = heapq.heappop(heap)
rt = [area, r] + d
yield rt | python | def bootstrap(nside, rand, nbar, *data):
""" This function will bootstrap data based on the sky coverage of rand.
It is different from bootstrap in the traditional sense, but for correlation
functions it gives the correct answer with less computation.
nbar : number density of rand, used to estimate the effective area of a pixel
nside : number of healpix pixels per side to use
*data : a list of data -- will be binned on the same regions.
small regions (incomplete pixels) are combined such that the total
area is about the same (a healpix pixel) in each returned boot strap sample
Yields: area, random, *data
rand and *data are in (RA, DEC)
Example:
>>> for area, ran, data1, data2 in bootstrap(4, ran, 100., data1, data2):
>>> # Do stuff
>>> pass
"""
def split(data, indices, axis):
""" This function splits array. It fixes the bug
in numpy that zero length array are improperly handled.
In the future this will be fixed.
"""
s = []
s.append(slice(0, indices[0]))
for i in range(len(indices) - 1):
s.append(slice(indices[i], indices[i+1]))
s.append(slice(indices[-1], None))
rt = []
for ss in s:
ind = [slice(None, None, None) for i in range(len(data.shape))]
ind[axis] = ss
ind = tuple(ind)
rt.append(data[ind])
return rt
def hpsplit(nside, data):
# data is (RA, DEC)
RA, DEC = data
pix = radec2pix(nside, RA, DEC)
n = numpy.bincount(pix)
a = numpy.argsort(pix)
data = numpy.array(data)[:, a]
rt = split(data, n.cumsum(), axis=-1)
return rt
# mean area of sky.
Abar = 41252.96 / nside2npix(nside)
rand = hpsplit(nside, rand)
if len(data) > 0:
data = [list(i) for i in zip(*[hpsplit(nside, d1) for d1 in data])]
else:
data = [[] for i in range(len(rand))]
heap = []
j = 0
for r, d in zip(rand, data):
if len(r[0]) == 0: continue
a = 1.0 * len(r[0]) / nbar
j = j + 1
if len(heap) == 0:
heapq.heappush(heap, (a, j, r, d))
else:
a0, j0, r0, d0 = heapq.heappop(heap)
if a0 + a < Abar:
a0 += a
d0 = [
numpy.concatenate((d0[i], d[i]), axis=-1)
for i in range(len(d))
]
r0 = numpy.concatenate((r0, r), axis=-1)
else:
heapq.heappush(heap, (a, j, r, d))
heapq.heappush(heap, (a0, j0, r0, d0))
for i in range(len(heap)):
area, j, r, d = heapq.heappop(heap)
rt = [area, r] + d
yield rt | [
"def",
"bootstrap",
"(",
"nside",
",",
"rand",
",",
"nbar",
",",
"*",
"data",
")",
":",
"def",
"split",
"(",
"data",
",",
"indices",
",",
"axis",
")",
":",
"\"\"\" This function splits array. It fixes the bug\n in numpy that zero length array are improperly handled.\n\n In the future this will be fixed.\n \"\"\"",
"s",
"=",
"[",
"]",
"s",
".",
"append",
"(",
"slice",
"(",
"0",
",",
"indices",
"[",
"0",
"]",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"indices",
")",
"-",
"1",
")",
":",
"s",
".",
"append",
"(",
"slice",
"(",
"indices",
"[",
"i",
"]",
",",
"indices",
"[",
"i",
"+",
"1",
"]",
")",
")",
"s",
".",
"append",
"(",
"slice",
"(",
"indices",
"[",
"-",
"1",
"]",
",",
"None",
")",
")",
"rt",
"=",
"[",
"]",
"for",
"ss",
"in",
"s",
":",
"ind",
"=",
"[",
"slice",
"(",
"None",
",",
"None",
",",
"None",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"data",
".",
"shape",
")",
")",
"]",
"ind",
"[",
"axis",
"]",
"=",
"ss",
"ind",
"=",
"tuple",
"(",
"ind",
")",
"rt",
".",
"append",
"(",
"data",
"[",
"ind",
"]",
")",
"return",
"rt",
"def",
"hpsplit",
"(",
"nside",
",",
"data",
")",
":",
"# data is (RA, DEC)",
"RA",
",",
"DEC",
"=",
"data",
"pix",
"=",
"radec2pix",
"(",
"nside",
",",
"RA",
",",
"DEC",
")",
"n",
"=",
"numpy",
".",
"bincount",
"(",
"pix",
")",
"a",
"=",
"numpy",
".",
"argsort",
"(",
"pix",
")",
"data",
"=",
"numpy",
".",
"array",
"(",
"data",
")",
"[",
":",
",",
"a",
"]",
"rt",
"=",
"split",
"(",
"data",
",",
"n",
".",
"cumsum",
"(",
")",
",",
"axis",
"=",
"-",
"1",
")",
"return",
"rt",
"# mean area of sky.",
"Abar",
"=",
"41252.96",
"/",
"nside2npix",
"(",
"nside",
")",
"rand",
"=",
"hpsplit",
"(",
"nside",
",",
"rand",
")",
"if",
"len",
"(",
"data",
")",
">",
"0",
":",
"data",
"=",
"[",
"list",
"(",
"i",
")",
"for",
"i",
"in",
"zip",
"(",
"*",
"[",
"hpsplit",
"(",
"nside",
",",
"d1",
")",
"for",
"d1",
"in",
"data",
"]",
")",
"]",
"else",
":",
"data",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"rand",
")",
")",
"]",
"heap",
"=",
"[",
"]",
"j",
"=",
"0",
"for",
"r",
",",
"d",
"in",
"zip",
"(",
"rand",
",",
"data",
")",
":",
"if",
"len",
"(",
"r",
"[",
"0",
"]",
")",
"==",
"0",
":",
"continue",
"a",
"=",
"1.0",
"*",
"len",
"(",
"r",
"[",
"0",
"]",
")",
"/",
"nbar",
"j",
"=",
"j",
"+",
"1",
"if",
"len",
"(",
"heap",
")",
"==",
"0",
":",
"heapq",
".",
"heappush",
"(",
"heap",
",",
"(",
"a",
",",
"j",
",",
"r",
",",
"d",
")",
")",
"else",
":",
"a0",
",",
"j0",
",",
"r0",
",",
"d0",
"=",
"heapq",
".",
"heappop",
"(",
"heap",
")",
"if",
"a0",
"+",
"a",
"<",
"Abar",
":",
"a0",
"+=",
"a",
"d0",
"=",
"[",
"numpy",
".",
"concatenate",
"(",
"(",
"d0",
"[",
"i",
"]",
",",
"d",
"[",
"i",
"]",
")",
",",
"axis",
"=",
"-",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"d",
")",
")",
"]",
"r0",
"=",
"numpy",
".",
"concatenate",
"(",
"(",
"r0",
",",
"r",
")",
",",
"axis",
"=",
"-",
"1",
")",
"else",
":",
"heapq",
".",
"heappush",
"(",
"heap",
",",
"(",
"a",
",",
"j",
",",
"r",
",",
"d",
")",
")",
"heapq",
".",
"heappush",
"(",
"heap",
",",
"(",
"a0",
",",
"j0",
",",
"r0",
",",
"d0",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"heap",
")",
")",
":",
"area",
",",
"j",
",",
"r",
",",
"d",
"=",
"heapq",
".",
"heappop",
"(",
"heap",
")",
"rt",
"=",
"[",
"area",
",",
"r",
"]",
"+",
"d",
"yield",
"rt"
] | This function will bootstrap data based on the sky coverage of rand.
It is different from bootstrap in the traditional sense, but for correlation
functions it gives the correct answer with less computation.
nbar : number density of rand, used to estimate the effective area of a pixel
nside : number of healpix pixels per side to use
*data : a list of data -- will be binned on the same regions.
small regions (incomplete pixels) are combined such that the total
area is about the same (a healpix pixel) in each returned boot strap sample
Yields: area, random, *data
rand and *data are in (RA, DEC)
Example:
>>> for area, ran, data1, data2 in bootstrap(4, ran, 100., data1, data2):
>>> # Do stuff
>>> pass | [
"This",
"function",
"will",
"bootstrap",
"data",
"based",
"on",
"the",
"sky",
"coverage",
"of",
"rand",
".",
"It",
"is",
"different",
"from",
"bootstrap",
"in",
"the",
"traditional",
"sense",
"but",
"for",
"correlation",
"functions",
"it",
"gives",
"the",
"correct",
"answer",
"with",
"less",
"computation",
"."
] | train | https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/sphere.py#L65-L153 |
rainwoodman/kdcount | kdcount/sphere.py | ang2pix | def ang2pix(nside, theta, phi):
r"""Convert angle :math:`\theta` :math:`\phi` to pixel.
This is translated from chealpix.c; but refer to Section 4.1 of
http://adsabs.harvard.edu/abs/2005ApJ...622..759G
"""
nside, theta, phi = numpy.lib.stride_tricks.broadcast_arrays(nside, theta, phi)
def equatorial(nside, tt, z):
t1 = nside * (0.5 + tt)
t2 = nside * z * 0.75
jp = (t1 - t2).astype('i8')
jm = (t1 + t2).astype('i8')
ir = nside + 1 + jp - jm # in {1, 2n + 1}
kshift = 1 - (ir & 1) # kshift=1 if ir even, 0 odd
ip = (jp + jm - nside + kshift + 1) // 2 # in {0, 4n - 1}
ip = ip % (4 * nside)
return nside * (nside - 1) * 2 + (ir - 1) * 4 * nside + ip
def polecaps(nside, tt, z, s):
tp = tt - numpy.floor(tt)
za = numpy.abs(z)
tmp = nside * s / ((1 + za) / 3) ** 0.5
mp = za > 0.99
tmp[mp] = nside[mp] * (3 *(1-za[mp])) ** 0.5
jp = (tp * tmp).astype('i8')
jm = ((1 - tp) * tmp).astype('i8')
ir = jp + jm + 1
ip = (tt * ir).astype('i8')
ip = ip % (4 * ir)
r1 = 2 * ir * (ir - 1)
r2 = 2 * ir * (ir + 1)
r = numpy.empty_like(r1)
r[z > 0] = r1[z > 0] + ip[z > 0]
r[z < 0] = 12 * nside[z < 0] * nside[z < 0] - r2[z < 0] + ip[z < 0]
return r
z = numpy.cos(theta)
s = numpy.sin(theta)
tt = (phi / (0.5 * numpy.pi) ) % 4 # in [0, 4]
result = numpy.zeros(z.shape, dtype='i8')
mask = (z < 2. / 3) & (z > -2. / 3)
result[mask] = equatorial(nside[mask], tt[mask], z[mask])
result[~mask] = polecaps(nside[~mask], tt[~mask], z[~mask], s[~mask])
return result | python | def ang2pix(nside, theta, phi):
r"""Convert angle :math:`\theta` :math:`\phi` to pixel.
This is translated from chealpix.c; but refer to Section 4.1 of
http://adsabs.harvard.edu/abs/2005ApJ...622..759G
"""
nside, theta, phi = numpy.lib.stride_tricks.broadcast_arrays(nside, theta, phi)
def equatorial(nside, tt, z):
t1 = nside * (0.5 + tt)
t2 = nside * z * 0.75
jp = (t1 - t2).astype('i8')
jm = (t1 + t2).astype('i8')
ir = nside + 1 + jp - jm # in {1, 2n + 1}
kshift = 1 - (ir & 1) # kshift=1 if ir even, 0 odd
ip = (jp + jm - nside + kshift + 1) // 2 # in {0, 4n - 1}
ip = ip % (4 * nside)
return nside * (nside - 1) * 2 + (ir - 1) * 4 * nside + ip
def polecaps(nside, tt, z, s):
tp = tt - numpy.floor(tt)
za = numpy.abs(z)
tmp = nside * s / ((1 + za) / 3) ** 0.5
mp = za > 0.99
tmp[mp] = nside[mp] * (3 *(1-za[mp])) ** 0.5
jp = (tp * tmp).astype('i8')
jm = ((1 - tp) * tmp).astype('i8')
ir = jp + jm + 1
ip = (tt * ir).astype('i8')
ip = ip % (4 * ir)
r1 = 2 * ir * (ir - 1)
r2 = 2 * ir * (ir + 1)
r = numpy.empty_like(r1)
r[z > 0] = r1[z > 0] + ip[z > 0]
r[z < 0] = 12 * nside[z < 0] * nside[z < 0] - r2[z < 0] + ip[z < 0]
return r
z = numpy.cos(theta)
s = numpy.sin(theta)
tt = (phi / (0.5 * numpy.pi) ) % 4 # in [0, 4]
result = numpy.zeros(z.shape, dtype='i8')
mask = (z < 2. / 3) & (z > -2. / 3)
result[mask] = equatorial(nside[mask], tt[mask], z[mask])
result[~mask] = polecaps(nside[~mask], tt[~mask], z[~mask], s[~mask])
return result | [
"def",
"ang2pix",
"(",
"nside",
",",
"theta",
",",
"phi",
")",
":",
"nside",
",",
"theta",
",",
"phi",
"=",
"numpy",
".",
"lib",
".",
"stride_tricks",
".",
"broadcast_arrays",
"(",
"nside",
",",
"theta",
",",
"phi",
")",
"def",
"equatorial",
"(",
"nside",
",",
"tt",
",",
"z",
")",
":",
"t1",
"=",
"nside",
"*",
"(",
"0.5",
"+",
"tt",
")",
"t2",
"=",
"nside",
"*",
"z",
"*",
"0.75",
"jp",
"=",
"(",
"t1",
"-",
"t2",
")",
".",
"astype",
"(",
"'i8'",
")",
"jm",
"=",
"(",
"t1",
"+",
"t2",
")",
".",
"astype",
"(",
"'i8'",
")",
"ir",
"=",
"nside",
"+",
"1",
"+",
"jp",
"-",
"jm",
"# in {1, 2n + 1}",
"kshift",
"=",
"1",
"-",
"(",
"ir",
"&",
"1",
")",
"# kshift=1 if ir even, 0 odd",
"ip",
"=",
"(",
"jp",
"+",
"jm",
"-",
"nside",
"+",
"kshift",
"+",
"1",
")",
"//",
"2",
"# in {0, 4n - 1}",
"ip",
"=",
"ip",
"%",
"(",
"4",
"*",
"nside",
")",
"return",
"nside",
"*",
"(",
"nside",
"-",
"1",
")",
"*",
"2",
"+",
"(",
"ir",
"-",
"1",
")",
"*",
"4",
"*",
"nside",
"+",
"ip",
"def",
"polecaps",
"(",
"nside",
",",
"tt",
",",
"z",
",",
"s",
")",
":",
"tp",
"=",
"tt",
"-",
"numpy",
".",
"floor",
"(",
"tt",
")",
"za",
"=",
"numpy",
".",
"abs",
"(",
"z",
")",
"tmp",
"=",
"nside",
"*",
"s",
"/",
"(",
"(",
"1",
"+",
"za",
")",
"/",
"3",
")",
"**",
"0.5",
"mp",
"=",
"za",
">",
"0.99",
"tmp",
"[",
"mp",
"]",
"=",
"nside",
"[",
"mp",
"]",
"*",
"(",
"3",
"*",
"(",
"1",
"-",
"za",
"[",
"mp",
"]",
")",
")",
"**",
"0.5",
"jp",
"=",
"(",
"tp",
"*",
"tmp",
")",
".",
"astype",
"(",
"'i8'",
")",
"jm",
"=",
"(",
"(",
"1",
"-",
"tp",
")",
"*",
"tmp",
")",
".",
"astype",
"(",
"'i8'",
")",
"ir",
"=",
"jp",
"+",
"jm",
"+",
"1",
"ip",
"=",
"(",
"tt",
"*",
"ir",
")",
".",
"astype",
"(",
"'i8'",
")",
"ip",
"=",
"ip",
"%",
"(",
"4",
"*",
"ir",
")",
"r1",
"=",
"2",
"*",
"ir",
"*",
"(",
"ir",
"-",
"1",
")",
"r2",
"=",
"2",
"*",
"ir",
"*",
"(",
"ir",
"+",
"1",
")",
"r",
"=",
"numpy",
".",
"empty_like",
"(",
"r1",
")",
"r",
"[",
"z",
">",
"0",
"]",
"=",
"r1",
"[",
"z",
">",
"0",
"]",
"+",
"ip",
"[",
"z",
">",
"0",
"]",
"r",
"[",
"z",
"<",
"0",
"]",
"=",
"12",
"*",
"nside",
"[",
"z",
"<",
"0",
"]",
"*",
"nside",
"[",
"z",
"<",
"0",
"]",
"-",
"r2",
"[",
"z",
"<",
"0",
"]",
"+",
"ip",
"[",
"z",
"<",
"0",
"]",
"return",
"r",
"z",
"=",
"numpy",
".",
"cos",
"(",
"theta",
")",
"s",
"=",
"numpy",
".",
"sin",
"(",
"theta",
")",
"tt",
"=",
"(",
"phi",
"/",
"(",
"0.5",
"*",
"numpy",
".",
"pi",
")",
")",
"%",
"4",
"# in [0, 4]",
"result",
"=",
"numpy",
".",
"zeros",
"(",
"z",
".",
"shape",
",",
"dtype",
"=",
"'i8'",
")",
"mask",
"=",
"(",
"z",
"<",
"2.",
"/",
"3",
")",
"&",
"(",
"z",
">",
"-",
"2.",
"/",
"3",
")",
"result",
"[",
"mask",
"]",
"=",
"equatorial",
"(",
"nside",
"[",
"mask",
"]",
",",
"tt",
"[",
"mask",
"]",
",",
"z",
"[",
"mask",
"]",
")",
"result",
"[",
"~",
"mask",
"]",
"=",
"polecaps",
"(",
"nside",
"[",
"~",
"mask",
"]",
",",
"tt",
"[",
"~",
"mask",
"]",
",",
"z",
"[",
"~",
"mask",
"]",
",",
"s",
"[",
"~",
"mask",
"]",
")",
"return",
"result"
] | r"""Convert angle :math:`\theta` :math:`\phi` to pixel.
This is translated from chealpix.c; but refer to Section 4.1 of
http://adsabs.harvard.edu/abs/2005ApJ...622..759G | [
"r",
"Convert",
"angle",
":",
"math",
":",
"\\",
"theta",
":",
"math",
":",
"\\",
"phi",
"to",
"pixel",
"."
] | train | https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/sphere.py#L167-L219 |
rainwoodman/kdcount | kdcount/sphere.py | pix2ang | def pix2ang(nside, pix):
r"""Convert pixel to angle :math:`\theta` :math:`\phi`.
nside and pix are broadcast with numpy rules.
Returns: theta, phi
This is translated from chealpix.c; but refer to Section 4.1 of
http://adsabs.harvard.edu/abs/2005ApJ...622..759G
"""
nside, pix = numpy.lib.stride_tricks.broadcast_arrays(nside, pix)
ncap = nside * (nside - 1) * 2
npix = 12 * nside * nside
def northpole(pix, npix):
iring = (1 + ((1 + 2 * pix) ** 0.5)).astype('i8') // 2
iphi = (pix + 1) - 2 * iring * (iring - 1)
z = 1.0 - (iring*iring) * 4. / npix
phi = (iphi - 0.5) * 0.5 * numpy.pi / iring
return z, phi
def equatorial(pix, nside, npix, ncap):
ip = pix - ncap
iring = ip // (4 * nside) + nside
iphi = ip % (4 * nside) + 1
fodd = (((iring + nside) &1) + 1.) * 0.5
z = (2 * nside - iring) * nside * 8.0 / npix
phi = (iphi - fodd) * (0.5 * numpy.pi) / nside
return z, phi
def southpole(pix, npix):
ip = npix - pix
iring = (1 + ((2 * ip - 1)**0.5).astype('i8')) // 2
iphi = 4 * iring + 1 - (ip - 2 * iring * (iring - 1))
z = -1 + (iring * iring) * 4. / npix
phi = (iphi - 0.5 ) * 0.5 * numpy.pi / iring
return z, phi
mask1 = pix < ncap
mask2 = (~mask1) & (pix < npix - ncap)
mask3 = pix >= npix - ncap
z = numpy.zeros(pix.shape, dtype='f8')
phi = numpy.zeros(pix.shape, dtype='f8')
z[mask1], phi[mask1] = northpole(pix[mask1], npix[mask1])
z[mask2], phi[mask2] = equatorial(pix[mask2], nside[mask2], npix[mask2], ncap[mask2])
z[mask3], phi[mask3] = southpole(pix[mask3], npix[mask3])
return numpy.arccos(z), phi | python | def pix2ang(nside, pix):
r"""Convert pixel to angle :math:`\theta` :math:`\phi`.
nside and pix are broadcast with numpy rules.
Returns: theta, phi
This is translated from chealpix.c; but refer to Section 4.1 of
http://adsabs.harvard.edu/abs/2005ApJ...622..759G
"""
nside, pix = numpy.lib.stride_tricks.broadcast_arrays(nside, pix)
ncap = nside * (nside - 1) * 2
npix = 12 * nside * nside
def northpole(pix, npix):
iring = (1 + ((1 + 2 * pix) ** 0.5)).astype('i8') // 2
iphi = (pix + 1) - 2 * iring * (iring - 1)
z = 1.0 - (iring*iring) * 4. / npix
phi = (iphi - 0.5) * 0.5 * numpy.pi / iring
return z, phi
def equatorial(pix, nside, npix, ncap):
ip = pix - ncap
iring = ip // (4 * nside) + nside
iphi = ip % (4 * nside) + 1
fodd = (((iring + nside) &1) + 1.) * 0.5
z = (2 * nside - iring) * nside * 8.0 / npix
phi = (iphi - fodd) * (0.5 * numpy.pi) / nside
return z, phi
def southpole(pix, npix):
ip = npix - pix
iring = (1 + ((2 * ip - 1)**0.5).astype('i8')) // 2
iphi = 4 * iring + 1 - (ip - 2 * iring * (iring - 1))
z = -1 + (iring * iring) * 4. / npix
phi = (iphi - 0.5 ) * 0.5 * numpy.pi / iring
return z, phi
mask1 = pix < ncap
mask2 = (~mask1) & (pix < npix - ncap)
mask3 = pix >= npix - ncap
z = numpy.zeros(pix.shape, dtype='f8')
phi = numpy.zeros(pix.shape, dtype='f8')
z[mask1], phi[mask1] = northpole(pix[mask1], npix[mask1])
z[mask2], phi[mask2] = equatorial(pix[mask2], nside[mask2], npix[mask2], ncap[mask2])
z[mask3], phi[mask3] = southpole(pix[mask3], npix[mask3])
return numpy.arccos(z), phi | [
"def",
"pix2ang",
"(",
"nside",
",",
"pix",
")",
":",
"nside",
",",
"pix",
"=",
"numpy",
".",
"lib",
".",
"stride_tricks",
".",
"broadcast_arrays",
"(",
"nside",
",",
"pix",
")",
"ncap",
"=",
"nside",
"*",
"(",
"nside",
"-",
"1",
")",
"*",
"2",
"npix",
"=",
"12",
"*",
"nside",
"*",
"nside",
"def",
"northpole",
"(",
"pix",
",",
"npix",
")",
":",
"iring",
"=",
"(",
"1",
"+",
"(",
"(",
"1",
"+",
"2",
"*",
"pix",
")",
"**",
"0.5",
")",
")",
".",
"astype",
"(",
"'i8'",
")",
"//",
"2",
"iphi",
"=",
"(",
"pix",
"+",
"1",
")",
"-",
"2",
"*",
"iring",
"*",
"(",
"iring",
"-",
"1",
")",
"z",
"=",
"1.0",
"-",
"(",
"iring",
"*",
"iring",
")",
"*",
"4.",
"/",
"npix",
"phi",
"=",
"(",
"iphi",
"-",
"0.5",
")",
"*",
"0.5",
"*",
"numpy",
".",
"pi",
"/",
"iring",
"return",
"z",
",",
"phi",
"def",
"equatorial",
"(",
"pix",
",",
"nside",
",",
"npix",
",",
"ncap",
")",
":",
"ip",
"=",
"pix",
"-",
"ncap",
"iring",
"=",
"ip",
"//",
"(",
"4",
"*",
"nside",
")",
"+",
"nside",
"iphi",
"=",
"ip",
"%",
"(",
"4",
"*",
"nside",
")",
"+",
"1",
"fodd",
"=",
"(",
"(",
"(",
"iring",
"+",
"nside",
")",
"&",
"1",
")",
"+",
"1.",
")",
"*",
"0.5",
"z",
"=",
"(",
"2",
"*",
"nside",
"-",
"iring",
")",
"*",
"nside",
"*",
"8.0",
"/",
"npix",
"phi",
"=",
"(",
"iphi",
"-",
"fodd",
")",
"*",
"(",
"0.5",
"*",
"numpy",
".",
"pi",
")",
"/",
"nside",
"return",
"z",
",",
"phi",
"def",
"southpole",
"(",
"pix",
",",
"npix",
")",
":",
"ip",
"=",
"npix",
"-",
"pix",
"iring",
"=",
"(",
"1",
"+",
"(",
"(",
"2",
"*",
"ip",
"-",
"1",
")",
"**",
"0.5",
")",
".",
"astype",
"(",
"'i8'",
")",
")",
"//",
"2",
"iphi",
"=",
"4",
"*",
"iring",
"+",
"1",
"-",
"(",
"ip",
"-",
"2",
"*",
"iring",
"*",
"(",
"iring",
"-",
"1",
")",
")",
"z",
"=",
"-",
"1",
"+",
"(",
"iring",
"*",
"iring",
")",
"*",
"4.",
"/",
"npix",
"phi",
"=",
"(",
"iphi",
"-",
"0.5",
")",
"*",
"0.5",
"*",
"numpy",
".",
"pi",
"/",
"iring",
"return",
"z",
",",
"phi",
"mask1",
"=",
"pix",
"<",
"ncap",
"mask2",
"=",
"(",
"~",
"mask1",
")",
"&",
"(",
"pix",
"<",
"npix",
"-",
"ncap",
")",
"mask3",
"=",
"pix",
">=",
"npix",
"-",
"ncap",
"z",
"=",
"numpy",
".",
"zeros",
"(",
"pix",
".",
"shape",
",",
"dtype",
"=",
"'f8'",
")",
"phi",
"=",
"numpy",
".",
"zeros",
"(",
"pix",
".",
"shape",
",",
"dtype",
"=",
"'f8'",
")",
"z",
"[",
"mask1",
"]",
",",
"phi",
"[",
"mask1",
"]",
"=",
"northpole",
"(",
"pix",
"[",
"mask1",
"]",
",",
"npix",
"[",
"mask1",
"]",
")",
"z",
"[",
"mask2",
"]",
",",
"phi",
"[",
"mask2",
"]",
"=",
"equatorial",
"(",
"pix",
"[",
"mask2",
"]",
",",
"nside",
"[",
"mask2",
"]",
",",
"npix",
"[",
"mask2",
"]",
",",
"ncap",
"[",
"mask2",
"]",
")",
"z",
"[",
"mask3",
"]",
",",
"phi",
"[",
"mask3",
"]",
"=",
"southpole",
"(",
"pix",
"[",
"mask3",
"]",
",",
"npix",
"[",
"mask3",
"]",
")",
"return",
"numpy",
".",
"arccos",
"(",
"z",
")",
",",
"phi"
] | r"""Convert pixel to angle :math:`\theta` :math:`\phi`.
nside and pix are broadcast with numpy rules.
Returns: theta, phi
This is translated from chealpix.c; but refer to Section 4.1 of
http://adsabs.harvard.edu/abs/2005ApJ...622..759G | [
"r",
"Convert",
"pixel",
"to",
"angle",
":",
"math",
":",
"\\",
"theta",
":",
"math",
":",
"\\",
"phi",
"."
] | train | https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/sphere.py#L221-L270 |
anteater/anteater | anteater/src/get_lists.py | GetLists.load_project_flag_list_file | def load_project_flag_list_file(self, project_exceptions, project):
""" Loads project specific lists """
if self.loaded:
return
exception_file = None
for item in project_exceptions:
if project in item:
exception_file = item.get(project)
if exception_file is not None:
try:
with open(exception_file, 'r') as f:
ex = yaml.safe_load(f)
except IOError:
logger.error('File not found: %s', exception_file)
sys.exit(0)
for key in ex:
if key in fl:
fl[key][project] = _merge(fl[key][project], ex.get(key, None)) \
if project in fl[key] else ex.get(key, None)
self.loaded = True
else:
logger.info('%s not found in %s', project, ignore_list)
logger.info('No project specific exceptions will be applied') | python | def load_project_flag_list_file(self, project_exceptions, project):
""" Loads project specific lists """
if self.loaded:
return
exception_file = None
for item in project_exceptions:
if project in item:
exception_file = item.get(project)
if exception_file is not None:
try:
with open(exception_file, 'r') as f:
ex = yaml.safe_load(f)
except IOError:
logger.error('File not found: %s', exception_file)
sys.exit(0)
for key in ex:
if key in fl:
fl[key][project] = _merge(fl[key][project], ex.get(key, None)) \
if project in fl[key] else ex.get(key, None)
self.loaded = True
else:
logger.info('%s not found in %s', project, ignore_list)
logger.info('No project specific exceptions will be applied') | [
"def",
"load_project_flag_list_file",
"(",
"self",
",",
"project_exceptions",
",",
"project",
")",
":",
"if",
"self",
".",
"loaded",
":",
"return",
"exception_file",
"=",
"None",
"for",
"item",
"in",
"project_exceptions",
":",
"if",
"project",
"in",
"item",
":",
"exception_file",
"=",
"item",
".",
"get",
"(",
"project",
")",
"if",
"exception_file",
"is",
"not",
"None",
":",
"try",
":",
"with",
"open",
"(",
"exception_file",
",",
"'r'",
")",
"as",
"f",
":",
"ex",
"=",
"yaml",
".",
"safe_load",
"(",
"f",
")",
"except",
"IOError",
":",
"logger",
".",
"error",
"(",
"'File not found: %s'",
",",
"exception_file",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"for",
"key",
"in",
"ex",
":",
"if",
"key",
"in",
"fl",
":",
"fl",
"[",
"key",
"]",
"[",
"project",
"]",
"=",
"_merge",
"(",
"fl",
"[",
"key",
"]",
"[",
"project",
"]",
",",
"ex",
".",
"get",
"(",
"key",
",",
"None",
")",
")",
"if",
"project",
"in",
"fl",
"[",
"key",
"]",
"else",
"ex",
".",
"get",
"(",
"key",
",",
"None",
")",
"self",
".",
"loaded",
"=",
"True",
"else",
":",
"logger",
".",
"info",
"(",
"'%s not found in %s'",
",",
"project",
",",
"ignore_list",
")",
"logger",
".",
"info",
"(",
"'No project specific exceptions will be applied'",
")"
] | Loads project specific lists | [
"Loads",
"project",
"specific",
"lists"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/get_lists.py#L63-L85 |
anteater/anteater | anteater/src/get_lists.py | GetLists.binary_hash | def binary_hash(self, project, patch_file):
""" Gathers sha256 hashes from binary lists """
global il
exception_file = None
try:
project_exceptions = il.get('project_exceptions')
except KeyError:
logger.info('project_exceptions missing in %s for %s', ignore_list, project)
for project_files in project_exceptions:
if project in project_files:
exception_file = project_files.get(project)
with open(exception_file, 'r') as f:
bl = yaml.safe_load(f)
for key, value in bl.items():
if key == 'binaries':
if patch_file in value:
hashvalue = value[patch_file]
return hashvalue
else:
for key, value in il.items():
if key == 'binaries':
if patch_file in value:
hashvalue = value[patch_file]
return hashvalue
else:
hashvalue = ""
return hashvalue
else:
logger.info('%s not found in %s', project, ignore_list)
logger.info('No project specific exceptions will be applied')
hashvalue = ""
return hashvalue | python | def binary_hash(self, project, patch_file):
""" Gathers sha256 hashes from binary lists """
global il
exception_file = None
try:
project_exceptions = il.get('project_exceptions')
except KeyError:
logger.info('project_exceptions missing in %s for %s', ignore_list, project)
for project_files in project_exceptions:
if project in project_files:
exception_file = project_files.get(project)
with open(exception_file, 'r') as f:
bl = yaml.safe_load(f)
for key, value in bl.items():
if key == 'binaries':
if patch_file in value:
hashvalue = value[patch_file]
return hashvalue
else:
for key, value in il.items():
if key == 'binaries':
if patch_file in value:
hashvalue = value[patch_file]
return hashvalue
else:
hashvalue = ""
return hashvalue
else:
logger.info('%s not found in %s', project, ignore_list)
logger.info('No project specific exceptions will be applied')
hashvalue = ""
return hashvalue | [
"def",
"binary_hash",
"(",
"self",
",",
"project",
",",
"patch_file",
")",
":",
"global",
"il",
"exception_file",
"=",
"None",
"try",
":",
"project_exceptions",
"=",
"il",
".",
"get",
"(",
"'project_exceptions'",
")",
"except",
"KeyError",
":",
"logger",
".",
"info",
"(",
"'project_exceptions missing in %s for %s'",
",",
"ignore_list",
",",
"project",
")",
"for",
"project_files",
"in",
"project_exceptions",
":",
"if",
"project",
"in",
"project_files",
":",
"exception_file",
"=",
"project_files",
".",
"get",
"(",
"project",
")",
"with",
"open",
"(",
"exception_file",
",",
"'r'",
")",
"as",
"f",
":",
"bl",
"=",
"yaml",
".",
"safe_load",
"(",
"f",
")",
"for",
"key",
",",
"value",
"in",
"bl",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"'binaries'",
":",
"if",
"patch_file",
"in",
"value",
":",
"hashvalue",
"=",
"value",
"[",
"patch_file",
"]",
"return",
"hashvalue",
"else",
":",
"for",
"key",
",",
"value",
"in",
"il",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"'binaries'",
":",
"if",
"patch_file",
"in",
"value",
":",
"hashvalue",
"=",
"value",
"[",
"patch_file",
"]",
"return",
"hashvalue",
"else",
":",
"hashvalue",
"=",
"\"\"",
"return",
"hashvalue",
"else",
":",
"logger",
".",
"info",
"(",
"'%s not found in %s'",
",",
"project",
",",
"ignore_list",
")",
"logger",
".",
"info",
"(",
"'No project specific exceptions will be applied'",
")",
"hashvalue",
"=",
"\"\"",
"return",
"hashvalue"
] | Gathers sha256 hashes from binary lists | [
"Gathers",
"sha256",
"hashes",
"from",
"binary",
"lists"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/get_lists.py#L117-L150 |
anteater/anteater | anteater/src/get_lists.py | GetLists.file_audit_list | def file_audit_list(self, project):
""" Gathers file name lists """
project_list = False
self.load_project_flag_list_file(il.get('project_exceptions'), project)
try:
default_list = set((fl['file_audits']['file_names']))
except KeyError:
logger.error('Key Error processing file_names list values')
try:
project_list = set((fl['file_audits'][project]['file_names']))
logger.info('Loaded %s specific file_audits entries', project)
except KeyError:
logger.info('No project specific file_names section for project %s', project)
file_names_re = re.compile("|".join(default_list),
flags=re.IGNORECASE)
if project_list:
file_names_proj_re = re.compile("|".join(project_list),
flags=re.IGNORECASE)
return file_names_re, file_names_proj_re
else:
file_names_proj_re = re.compile("")
return file_names_re, file_names_proj_re | python | def file_audit_list(self, project):
""" Gathers file name lists """
project_list = False
self.load_project_flag_list_file(il.get('project_exceptions'), project)
try:
default_list = set((fl['file_audits']['file_names']))
except KeyError:
logger.error('Key Error processing file_names list values')
try:
project_list = set((fl['file_audits'][project]['file_names']))
logger.info('Loaded %s specific file_audits entries', project)
except KeyError:
logger.info('No project specific file_names section for project %s', project)
file_names_re = re.compile("|".join(default_list),
flags=re.IGNORECASE)
if project_list:
file_names_proj_re = re.compile("|".join(project_list),
flags=re.IGNORECASE)
return file_names_re, file_names_proj_re
else:
file_names_proj_re = re.compile("")
return file_names_re, file_names_proj_re | [
"def",
"file_audit_list",
"(",
"self",
",",
"project",
")",
":",
"project_list",
"=",
"False",
"self",
".",
"load_project_flag_list_file",
"(",
"il",
".",
"get",
"(",
"'project_exceptions'",
")",
",",
"project",
")",
"try",
":",
"default_list",
"=",
"set",
"(",
"(",
"fl",
"[",
"'file_audits'",
"]",
"[",
"'file_names'",
"]",
")",
")",
"except",
"KeyError",
":",
"logger",
".",
"error",
"(",
"'Key Error processing file_names list values'",
")",
"try",
":",
"project_list",
"=",
"set",
"(",
"(",
"fl",
"[",
"'file_audits'",
"]",
"[",
"project",
"]",
"[",
"'file_names'",
"]",
")",
")",
"logger",
".",
"info",
"(",
"'Loaded %s specific file_audits entries'",
",",
"project",
")",
"except",
"KeyError",
":",
"logger",
".",
"info",
"(",
"'No project specific file_names section for project %s'",
",",
"project",
")",
"file_names_re",
"=",
"re",
".",
"compile",
"(",
"\"|\"",
".",
"join",
"(",
"default_list",
")",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"if",
"project_list",
":",
"file_names_proj_re",
"=",
"re",
".",
"compile",
"(",
"\"|\"",
".",
"join",
"(",
"project_list",
")",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"return",
"file_names_re",
",",
"file_names_proj_re",
"else",
":",
"file_names_proj_re",
"=",
"re",
".",
"compile",
"(",
"\"\"",
")",
"return",
"file_names_re",
",",
"file_names_proj_re"
] | Gathers file name lists | [
"Gathers",
"file",
"name",
"lists"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/get_lists.py#L152-L175 |
anteater/anteater | anteater/src/get_lists.py | GetLists.file_content_list | def file_content_list(self, project):
""" gathers content strings """
project_list = False
self.load_project_flag_list_file(il.get('project_exceptions'), project)
try:
flag_list = (fl['file_audits']['file_contents'])
except KeyError:
logger.error('Key Error processing file_contents list values')
try:
ignore_list = il['file_audits']['file_contents']
except KeyError:
logger.error('Key Error processing file_contents list values')
try:
project_list = fl['file_audits'][project]['file_contents']
logger.info('Loaded %s specific file_contents entries', project)
except KeyError:
logger.info('No project specific file_contents section for project %s', project)
if project_list:
ignore_list_merge = project_list + ignore_list
ignore_list_re = re.compile("|".join(ignore_list_merge), flags=re.IGNORECASE)
return flag_list, ignore_list_re
else:
ignore_list_re = re.compile("|".join(ignore_list),
flags=re.IGNORECASE)
return flag_list, ignore_list_re | python | def file_content_list(self, project):
""" gathers content strings """
project_list = False
self.load_project_flag_list_file(il.get('project_exceptions'), project)
try:
flag_list = (fl['file_audits']['file_contents'])
except KeyError:
logger.error('Key Error processing file_contents list values')
try:
ignore_list = il['file_audits']['file_contents']
except KeyError:
logger.error('Key Error processing file_contents list values')
try:
project_list = fl['file_audits'][project]['file_contents']
logger.info('Loaded %s specific file_contents entries', project)
except KeyError:
logger.info('No project specific file_contents section for project %s', project)
if project_list:
ignore_list_merge = project_list + ignore_list
ignore_list_re = re.compile("|".join(ignore_list_merge), flags=re.IGNORECASE)
return flag_list, ignore_list_re
else:
ignore_list_re = re.compile("|".join(ignore_list),
flags=re.IGNORECASE)
return flag_list, ignore_list_re | [
"def",
"file_content_list",
"(",
"self",
",",
"project",
")",
":",
"project_list",
"=",
"False",
"self",
".",
"load_project_flag_list_file",
"(",
"il",
".",
"get",
"(",
"'project_exceptions'",
")",
",",
"project",
")",
"try",
":",
"flag_list",
"=",
"(",
"fl",
"[",
"'file_audits'",
"]",
"[",
"'file_contents'",
"]",
")",
"except",
"KeyError",
":",
"logger",
".",
"error",
"(",
"'Key Error processing file_contents list values'",
")",
"try",
":",
"ignore_list",
"=",
"il",
"[",
"'file_audits'",
"]",
"[",
"'file_contents'",
"]",
"except",
"KeyError",
":",
"logger",
".",
"error",
"(",
"'Key Error processing file_contents list values'",
")",
"try",
":",
"project_list",
"=",
"fl",
"[",
"'file_audits'",
"]",
"[",
"project",
"]",
"[",
"'file_contents'",
"]",
"logger",
".",
"info",
"(",
"'Loaded %s specific file_contents entries'",
",",
"project",
")",
"except",
"KeyError",
":",
"logger",
".",
"info",
"(",
"'No project specific file_contents section for project %s'",
",",
"project",
")",
"if",
"project_list",
":",
"ignore_list_merge",
"=",
"project_list",
"+",
"ignore_list",
"ignore_list_re",
"=",
"re",
".",
"compile",
"(",
"\"|\"",
".",
"join",
"(",
"ignore_list_merge",
")",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"return",
"flag_list",
",",
"ignore_list_re",
"else",
":",
"ignore_list_re",
"=",
"re",
".",
"compile",
"(",
"\"|\"",
".",
"join",
"(",
"ignore_list",
")",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"return",
"flag_list",
",",
"ignore_list_re"
] | gathers content strings | [
"gathers",
"content",
"strings"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/get_lists.py#L177-L207 |
anteater/anteater | anteater/src/get_lists.py | GetLists.ignore_directories | def ignore_directories(self, project):
""" Gathers a list of directories to ignore """
project_list = False
try:
ignore_directories = il['ignore_directories']
except KeyError:
logger.error('Key Error processing ignore_directories list values')
try:
project_exceptions = il.get('project_exceptions')
for item in project_exceptions:
if project in item:
exception_file = item.get(project)
with open(exception_file, 'r') as f:
test_list = yaml.safe_load(f)
project_list = test_list['ignore_directories']
except KeyError:
logger.info('No ignore_directories for %s', project)
if project_list:
ignore_directories = ignore_directories + project_list
return ignore_directories
else:
return ignore_directories | python | def ignore_directories(self, project):
""" Gathers a list of directories to ignore """
project_list = False
try:
ignore_directories = il['ignore_directories']
except KeyError:
logger.error('Key Error processing ignore_directories list values')
try:
project_exceptions = il.get('project_exceptions')
for item in project_exceptions:
if project in item:
exception_file = item.get(project)
with open(exception_file, 'r') as f:
test_list = yaml.safe_load(f)
project_list = test_list['ignore_directories']
except KeyError:
logger.info('No ignore_directories for %s', project)
if project_list:
ignore_directories = ignore_directories + project_list
return ignore_directories
else:
return ignore_directories | [
"def",
"ignore_directories",
"(",
"self",
",",
"project",
")",
":",
"project_list",
"=",
"False",
"try",
":",
"ignore_directories",
"=",
"il",
"[",
"'ignore_directories'",
"]",
"except",
"KeyError",
":",
"logger",
".",
"error",
"(",
"'Key Error processing ignore_directories list values'",
")",
"try",
":",
"project_exceptions",
"=",
"il",
".",
"get",
"(",
"'project_exceptions'",
")",
"for",
"item",
"in",
"project_exceptions",
":",
"if",
"project",
"in",
"item",
":",
"exception_file",
"=",
"item",
".",
"get",
"(",
"project",
")",
"with",
"open",
"(",
"exception_file",
",",
"'r'",
")",
"as",
"f",
":",
"test_list",
"=",
"yaml",
".",
"safe_load",
"(",
"f",
")",
"project_list",
"=",
"test_list",
"[",
"'ignore_directories'",
"]",
"except",
"KeyError",
":",
"logger",
".",
"info",
"(",
"'No ignore_directories for %s'",
",",
"project",
")",
"if",
"project_list",
":",
"ignore_directories",
"=",
"ignore_directories",
"+",
"project_list",
"return",
"ignore_directories",
"else",
":",
"return",
"ignore_directories"
] | Gathers a list of directories to ignore | [
"Gathers",
"a",
"list",
"of",
"directories",
"to",
"ignore"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/get_lists.py#L209-L232 |
anteater/anteater | anteater/src/get_lists.py | GetLists.url_ignore | def url_ignore(self, project):
""" Gathers a list of URLs to ignore """
project_list = False
try:
url_ignore = il['url_ignore']
except KeyError:
logger.error('Key Error processing url_ignore list values')
try:
project_exceptions = il.get('project_exceptions')
for item in project_exceptions:
if project in item:
exception_file = item.get(project)
with open(exception_file, 'r') as f:
url_list = yaml.safe_load(f)
project_list = url_list['url_ignore']
except KeyError:
logger.info('No url_ignore for %s', project)
if project_list:
url_ignore = url_ignore + project_list
url_ignore_re = re.compile("|".join(url_ignore), flags=re.IGNORECASE)
return url_ignore_re
else:
url_ignore_re = re.compile("|".join(url_ignore), flags=re.IGNORECASE)
return url_ignore_re | python | def url_ignore(self, project):
""" Gathers a list of URLs to ignore """
project_list = False
try:
url_ignore = il['url_ignore']
except KeyError:
logger.error('Key Error processing url_ignore list values')
try:
project_exceptions = il.get('project_exceptions')
for item in project_exceptions:
if project in item:
exception_file = item.get(project)
with open(exception_file, 'r') as f:
url_list = yaml.safe_load(f)
project_list = url_list['url_ignore']
except KeyError:
logger.info('No url_ignore for %s', project)
if project_list:
url_ignore = url_ignore + project_list
url_ignore_re = re.compile("|".join(url_ignore), flags=re.IGNORECASE)
return url_ignore_re
else:
url_ignore_re = re.compile("|".join(url_ignore), flags=re.IGNORECASE)
return url_ignore_re | [
"def",
"url_ignore",
"(",
"self",
",",
"project",
")",
":",
"project_list",
"=",
"False",
"try",
":",
"url_ignore",
"=",
"il",
"[",
"'url_ignore'",
"]",
"except",
"KeyError",
":",
"logger",
".",
"error",
"(",
"'Key Error processing url_ignore list values'",
")",
"try",
":",
"project_exceptions",
"=",
"il",
".",
"get",
"(",
"'project_exceptions'",
")",
"for",
"item",
"in",
"project_exceptions",
":",
"if",
"project",
"in",
"item",
":",
"exception_file",
"=",
"item",
".",
"get",
"(",
"project",
")",
"with",
"open",
"(",
"exception_file",
",",
"'r'",
")",
"as",
"f",
":",
"url_list",
"=",
"yaml",
".",
"safe_load",
"(",
"f",
")",
"project_list",
"=",
"url_list",
"[",
"'url_ignore'",
"]",
"except",
"KeyError",
":",
"logger",
".",
"info",
"(",
"'No url_ignore for %s'",
",",
"project",
")",
"if",
"project_list",
":",
"url_ignore",
"=",
"url_ignore",
"+",
"project_list",
"url_ignore_re",
"=",
"re",
".",
"compile",
"(",
"\"|\"",
".",
"join",
"(",
"url_ignore",
")",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"return",
"url_ignore_re",
"else",
":",
"url_ignore_re",
"=",
"re",
".",
"compile",
"(",
"\"|\"",
".",
"join",
"(",
"url_ignore",
")",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"return",
"url_ignore_re"
] | Gathers a list of URLs to ignore | [
"Gathers",
"a",
"list",
"of",
"URLs",
"to",
"ignore"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/get_lists.py#L234-L259 |
anteater/anteater | anteater/src/get_lists.py | GetLists.ip_ignore | def ip_ignore(self, project):
""" Gathers a list of URLs to ignore """
project_list = False
try:
ip_ignore = il['ip_ignore']
except KeyError:
logger.error('Key Error processing ip_ignore list values')
try:
project_exceptions = il.get('project_exceptions')
for item in project_exceptions:
if project in item:
exception_file = item.get(project)
with open(exception_file, 'r') as f:
ip_list = yaml.safe_load(f)
project_list = ip_list['ip_ignore']
except KeyError:
logger.info('No ip_ignore for %s', project)
if project_list:
ip_ignore = ip_ignore + project_list
ip_ignore_re = re.compile("|".join(ip_ignore), flags=re.IGNORECASE)
return ip_ignore_re
else:
ip_ignore_re = re.compile("|".join(ip_ignore), flags=re.IGNORECASE)
return ip_ignore_re | python | def ip_ignore(self, project):
""" Gathers a list of URLs to ignore """
project_list = False
try:
ip_ignore = il['ip_ignore']
except KeyError:
logger.error('Key Error processing ip_ignore list values')
try:
project_exceptions = il.get('project_exceptions')
for item in project_exceptions:
if project in item:
exception_file = item.get(project)
with open(exception_file, 'r') as f:
ip_list = yaml.safe_load(f)
project_list = ip_list['ip_ignore']
except KeyError:
logger.info('No ip_ignore for %s', project)
if project_list:
ip_ignore = ip_ignore + project_list
ip_ignore_re = re.compile("|".join(ip_ignore), flags=re.IGNORECASE)
return ip_ignore_re
else:
ip_ignore_re = re.compile("|".join(ip_ignore), flags=re.IGNORECASE)
return ip_ignore_re | [
"def",
"ip_ignore",
"(",
"self",
",",
"project",
")",
":",
"project_list",
"=",
"False",
"try",
":",
"ip_ignore",
"=",
"il",
"[",
"'ip_ignore'",
"]",
"except",
"KeyError",
":",
"logger",
".",
"error",
"(",
"'Key Error processing ip_ignore list values'",
")",
"try",
":",
"project_exceptions",
"=",
"il",
".",
"get",
"(",
"'project_exceptions'",
")",
"for",
"item",
"in",
"project_exceptions",
":",
"if",
"project",
"in",
"item",
":",
"exception_file",
"=",
"item",
".",
"get",
"(",
"project",
")",
"with",
"open",
"(",
"exception_file",
",",
"'r'",
")",
"as",
"f",
":",
"ip_list",
"=",
"yaml",
".",
"safe_load",
"(",
"f",
")",
"project_list",
"=",
"ip_list",
"[",
"'ip_ignore'",
"]",
"except",
"KeyError",
":",
"logger",
".",
"info",
"(",
"'No ip_ignore for %s'",
",",
"project",
")",
"if",
"project_list",
":",
"ip_ignore",
"=",
"ip_ignore",
"+",
"project_list",
"ip_ignore_re",
"=",
"re",
".",
"compile",
"(",
"\"|\"",
".",
"join",
"(",
"ip_ignore",
")",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"return",
"ip_ignore_re",
"else",
":",
"ip_ignore_re",
"=",
"re",
".",
"compile",
"(",
"\"|\"",
".",
"join",
"(",
"ip_ignore",
")",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"return",
"ip_ignore_re"
] | Gathers a list of URLs to ignore | [
"Gathers",
"a",
"list",
"of",
"URLs",
"to",
"ignore"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/get_lists.py#L261-L286 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | download_from_github | def download_from_github(fname, path):
"""
Download database from GitHub
:param fname: file name with extension ('.zip') of the target item
:type fname: str
:param path: path to save unzipped files
:type path: str
:return: database folder
:rtype: folder
"""
base_url = 'https://github.com/ornlneutronimaging/ImagingReso/blob/master/ImagingReso/reference_data/'
# Add GitHub junk to the file name for downloading.
f = fname + '?raw=true'
url = base_url + f
block_size = 16384
req = urlopen(url)
# Get file size from header
if sys.version_info[0] < 3:
file_size = int(req.info().getheaders('Content-Length')[0])
else:
file_size = req.length
# downloaded = 0
# Check if file already downloaded
if os.path.exists(fname):
if os.path.getsize(fname) == file_size:
print("Skipping downloading '{}'".format(fname))
else:
overwrite = input("File size changed, overwrite '{}'? ([y]/n) ".format(fname))
if overwrite.lower().startswith('n'):
print("Local file '{}' kept without overwriting.".format(fname))
# Copy file to disk
print("Downloading '{}'... ".format(fname))
with open(fname, 'wb') as fh:
while True:
chunk = req.read(block_size)
if not chunk:
break
fh.write(chunk)
# downloaded += len(chunk)
print('')
print('Download completed.')
print("Unzipping '{}'... ".format(fname))
_database_zip = zipfile.ZipFile(fname)
_database_zip.extractall(path=path)
print("'{}' has been unzipped and database '{}' is ready to use.".format(fname, fname.replace('.zip', '')))
os.remove(fname)
print("'{}' has been deleted".format(fname)) | python | def download_from_github(fname, path):
"""
Download database from GitHub
:param fname: file name with extension ('.zip') of the target item
:type fname: str
:param path: path to save unzipped files
:type path: str
:return: database folder
:rtype: folder
"""
base_url = 'https://github.com/ornlneutronimaging/ImagingReso/blob/master/ImagingReso/reference_data/'
# Add GitHub junk to the file name for downloading.
f = fname + '?raw=true'
url = base_url + f
block_size = 16384
req = urlopen(url)
# Get file size from header
if sys.version_info[0] < 3:
file_size = int(req.info().getheaders('Content-Length')[0])
else:
file_size = req.length
# downloaded = 0
# Check if file already downloaded
if os.path.exists(fname):
if os.path.getsize(fname) == file_size:
print("Skipping downloading '{}'".format(fname))
else:
overwrite = input("File size changed, overwrite '{}'? ([y]/n) ".format(fname))
if overwrite.lower().startswith('n'):
print("Local file '{}' kept without overwriting.".format(fname))
# Copy file to disk
print("Downloading '{}'... ".format(fname))
with open(fname, 'wb') as fh:
while True:
chunk = req.read(block_size)
if not chunk:
break
fh.write(chunk)
# downloaded += len(chunk)
print('')
print('Download completed.')
print("Unzipping '{}'... ".format(fname))
_database_zip = zipfile.ZipFile(fname)
_database_zip.extractall(path=path)
print("'{}' has been unzipped and database '{}' is ready to use.".format(fname, fname.replace('.zip', '')))
os.remove(fname)
print("'{}' has been deleted".format(fname)) | [
"def",
"download_from_github",
"(",
"fname",
",",
"path",
")",
":",
"base_url",
"=",
"'https://github.com/ornlneutronimaging/ImagingReso/blob/master/ImagingReso/reference_data/'",
"# Add GitHub junk to the file name for downloading.",
"f",
"=",
"fname",
"+",
"'?raw=true'",
"url",
"=",
"base_url",
"+",
"f",
"block_size",
"=",
"16384",
"req",
"=",
"urlopen",
"(",
"url",
")",
"# Get file size from header",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"file_size",
"=",
"int",
"(",
"req",
".",
"info",
"(",
")",
".",
"getheaders",
"(",
"'Content-Length'",
")",
"[",
"0",
"]",
")",
"else",
":",
"file_size",
"=",
"req",
".",
"length",
"# downloaded = 0",
"# Check if file already downloaded",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"if",
"os",
".",
"path",
".",
"getsize",
"(",
"fname",
")",
"==",
"file_size",
":",
"print",
"(",
"\"Skipping downloading '{}'\"",
".",
"format",
"(",
"fname",
")",
")",
"else",
":",
"overwrite",
"=",
"input",
"(",
"\"File size changed, overwrite '{}'? ([y]/n) \"",
".",
"format",
"(",
"fname",
")",
")",
"if",
"overwrite",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'n'",
")",
":",
"print",
"(",
"\"Local file '{}' kept without overwriting.\"",
".",
"format",
"(",
"fname",
")",
")",
"# Copy file to disk",
"print",
"(",
"\"Downloading '{}'... \"",
".",
"format",
"(",
"fname",
")",
")",
"with",
"open",
"(",
"fname",
",",
"'wb'",
")",
"as",
"fh",
":",
"while",
"True",
":",
"chunk",
"=",
"req",
".",
"read",
"(",
"block_size",
")",
"if",
"not",
"chunk",
":",
"break",
"fh",
".",
"write",
"(",
"chunk",
")",
"# downloaded += len(chunk)",
"print",
"(",
"''",
")",
"print",
"(",
"'Download completed.'",
")",
"print",
"(",
"\"Unzipping '{}'... \"",
".",
"format",
"(",
"fname",
")",
")",
"_database_zip",
"=",
"zipfile",
".",
"ZipFile",
"(",
"fname",
")",
"_database_zip",
".",
"extractall",
"(",
"path",
"=",
"path",
")",
"print",
"(",
"\"'{}' has been unzipped and database '{}' is ready to use.\"",
".",
"format",
"(",
"fname",
",",
"fname",
".",
"replace",
"(",
"'.zip'",
",",
"''",
")",
")",
")",
"os",
".",
"remove",
"(",
"fname",
")",
"print",
"(",
"\"'{}' has been deleted\"",
".",
"format",
"(",
"fname",
")",
")"
] | Download database from GitHub
:param fname: file name with extension ('.zip') of the target item
:type fname: str
:param path: path to save unzipped files
:type path: str
:return: database folder
:rtype: folder | [
"Download",
"database",
"from",
"GitHub"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L18-L71 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | get_list_element_from_database | def get_list_element_from_database(database='ENDF_VII'):
"""return a string array of all the element from the database
Parameters:
==========
database: string. Name of database
Raises:
======
ValueError if database can not be found
"""
_file_path = os.path.abspath(os.path.dirname(__file__))
_ref_data_folder = os.path.join(_file_path, 'reference_data')
_database_folder = os.path.join(_ref_data_folder, database)
if not os.path.exists(_ref_data_folder):
os.makedirs(_ref_data_folder)
print("Folder to store database files has been created: '{}'".format(_ref_data_folder))
if not os.path.exists(_database_folder):
print("First time using database '{}'? ".format(database))
print("I will retrieve and store a local copy of database'{}': ".format(database))
download_from_github(fname=database + '.zip', path=_ref_data_folder)
# if '/_elements_list.csv' NOT exist
if not os.path.exists(_database_folder + '/_elements_list.csv'):
# glob all .csv files
_list_files = glob.glob(_database_folder + '/*.csv')
# glob all .h5 files if NO .csv file exist
if not _list_files:
_list_files = glob.glob(_database_folder + '/*.h5')
# test if files globed
_empty_list_boo = not _list_files
if _empty_list_boo is True:
raise ValueError("'{}' does not contain any '*.csv' or '*.h5' file.".format(_database_folder))
# convert path/to/file to filename only
_list_short_filename_without_extension = [os.path.splitext(os.path.basename(_file))[0] for _file in _list_files]
# isolate element names and output as list
if '-' in _list_short_filename_without_extension[0]:
_list_element = list(set([_name.split('-')[0] for _name in _list_short_filename_without_extension]))
else:
_list_letter_part = list(
set([re.split(r'(\d+)', _name)[0] for _name in _list_short_filename_without_extension]))
_list_element = []
for each_letter_part in _list_letter_part:
if len(each_letter_part) <= 2:
_list_element.append(each_letter_part)
# save to current dir
_list_element.sort()
df_to_save = pd.DataFrame()
df_to_save['elements'] = _list_element
df_to_save.to_csv(_database_folder + '/_elements_list.csv')
# print("NOT FOUND '{}'".format(_database_folder + '/_elements_list.csv'))
# print("SAVED '{}'".format(_database_folder + '/_elements_list.csv'))
# '/_elements_list.csv' exist
else:
df_to_read = pd.read_csv(_database_folder + '/_elements_list.csv')
_list_element = list(df_to_read['elements'])
# print("FOUND '{}'".format(_database_folder + '/_elements_list.csv'))
# print("READ '{}'".format(_database_folder + '/_elements_list.csv'))
return _list_element | python | def get_list_element_from_database(database='ENDF_VII'):
"""return a string array of all the element from the database
Parameters:
==========
database: string. Name of database
Raises:
======
ValueError if database can not be found
"""
_file_path = os.path.abspath(os.path.dirname(__file__))
_ref_data_folder = os.path.join(_file_path, 'reference_data')
_database_folder = os.path.join(_ref_data_folder, database)
if not os.path.exists(_ref_data_folder):
os.makedirs(_ref_data_folder)
print("Folder to store database files has been created: '{}'".format(_ref_data_folder))
if not os.path.exists(_database_folder):
print("First time using database '{}'? ".format(database))
print("I will retrieve and store a local copy of database'{}': ".format(database))
download_from_github(fname=database + '.zip', path=_ref_data_folder)
# if '/_elements_list.csv' NOT exist
if not os.path.exists(_database_folder + '/_elements_list.csv'):
# glob all .csv files
_list_files = glob.glob(_database_folder + '/*.csv')
# glob all .h5 files if NO .csv file exist
if not _list_files:
_list_files = glob.glob(_database_folder + '/*.h5')
# test if files globed
_empty_list_boo = not _list_files
if _empty_list_boo is True:
raise ValueError("'{}' does not contain any '*.csv' or '*.h5' file.".format(_database_folder))
# convert path/to/file to filename only
_list_short_filename_without_extension = [os.path.splitext(os.path.basename(_file))[0] for _file in _list_files]
# isolate element names and output as list
if '-' in _list_short_filename_without_extension[0]:
_list_element = list(set([_name.split('-')[0] for _name in _list_short_filename_without_extension]))
else:
_list_letter_part = list(
set([re.split(r'(\d+)', _name)[0] for _name in _list_short_filename_without_extension]))
_list_element = []
for each_letter_part in _list_letter_part:
if len(each_letter_part) <= 2:
_list_element.append(each_letter_part)
# save to current dir
_list_element.sort()
df_to_save = pd.DataFrame()
df_to_save['elements'] = _list_element
df_to_save.to_csv(_database_folder + '/_elements_list.csv')
# print("NOT FOUND '{}'".format(_database_folder + '/_elements_list.csv'))
# print("SAVED '{}'".format(_database_folder + '/_elements_list.csv'))
# '/_elements_list.csv' exist
else:
df_to_read = pd.read_csv(_database_folder + '/_elements_list.csv')
_list_element = list(df_to_read['elements'])
# print("FOUND '{}'".format(_database_folder + '/_elements_list.csv'))
# print("READ '{}'".format(_database_folder + '/_elements_list.csv'))
return _list_element | [
"def",
"get_list_element_from_database",
"(",
"database",
"=",
"'ENDF_VII'",
")",
":",
"_file_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"_ref_data_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_file_path",
",",
"'reference_data'",
")",
"_database_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_ref_data_folder",
",",
"database",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"_ref_data_folder",
")",
":",
"os",
".",
"makedirs",
"(",
"_ref_data_folder",
")",
"print",
"(",
"\"Folder to store database files has been created: '{}'\"",
".",
"format",
"(",
"_ref_data_folder",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"_database_folder",
")",
":",
"print",
"(",
"\"First time using database '{}'? \"",
".",
"format",
"(",
"database",
")",
")",
"print",
"(",
"\"I will retrieve and store a local copy of database'{}': \"",
".",
"format",
"(",
"database",
")",
")",
"download_from_github",
"(",
"fname",
"=",
"database",
"+",
"'.zip'",
",",
"path",
"=",
"_ref_data_folder",
")",
"# if '/_elements_list.csv' NOT exist",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"_database_folder",
"+",
"'/_elements_list.csv'",
")",
":",
"# glob all .csv files",
"_list_files",
"=",
"glob",
".",
"glob",
"(",
"_database_folder",
"+",
"'/*.csv'",
")",
"# glob all .h5 files if NO .csv file exist",
"if",
"not",
"_list_files",
":",
"_list_files",
"=",
"glob",
".",
"glob",
"(",
"_database_folder",
"+",
"'/*.h5'",
")",
"# test if files globed",
"_empty_list_boo",
"=",
"not",
"_list_files",
"if",
"_empty_list_boo",
"is",
"True",
":",
"raise",
"ValueError",
"(",
"\"'{}' does not contain any '*.csv' or '*.h5' file.\"",
".",
"format",
"(",
"_database_folder",
")",
")",
"# convert path/to/file to filename only",
"_list_short_filename_without_extension",
"=",
"[",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"_file",
")",
")",
"[",
"0",
"]",
"for",
"_file",
"in",
"_list_files",
"]",
"# isolate element names and output as list",
"if",
"'-'",
"in",
"_list_short_filename_without_extension",
"[",
"0",
"]",
":",
"_list_element",
"=",
"list",
"(",
"set",
"(",
"[",
"_name",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]",
"for",
"_name",
"in",
"_list_short_filename_without_extension",
"]",
")",
")",
"else",
":",
"_list_letter_part",
"=",
"list",
"(",
"set",
"(",
"[",
"re",
".",
"split",
"(",
"r'(\\d+)'",
",",
"_name",
")",
"[",
"0",
"]",
"for",
"_name",
"in",
"_list_short_filename_without_extension",
"]",
")",
")",
"_list_element",
"=",
"[",
"]",
"for",
"each_letter_part",
"in",
"_list_letter_part",
":",
"if",
"len",
"(",
"each_letter_part",
")",
"<=",
"2",
":",
"_list_element",
".",
"append",
"(",
"each_letter_part",
")",
"# save to current dir",
"_list_element",
".",
"sort",
"(",
")",
"df_to_save",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"df_to_save",
"[",
"'elements'",
"]",
"=",
"_list_element",
"df_to_save",
".",
"to_csv",
"(",
"_database_folder",
"+",
"'/_elements_list.csv'",
")",
"# print(\"NOT FOUND '{}'\".format(_database_folder + '/_elements_list.csv'))",
"# print(\"SAVED '{}'\".format(_database_folder + '/_elements_list.csv'))",
"# '/_elements_list.csv' exist",
"else",
":",
"df_to_read",
"=",
"pd",
".",
"read_csv",
"(",
"_database_folder",
"+",
"'/_elements_list.csv'",
")",
"_list_element",
"=",
"list",
"(",
"df_to_read",
"[",
"'elements'",
"]",
")",
"# print(\"FOUND '{}'\".format(_database_folder + '/_elements_list.csv'))",
"# print(\"READ '{}'\".format(_database_folder + '/_elements_list.csv'))",
"return",
"_list_element"
] | return a string array of all the element from the database
Parameters:
==========
database: string. Name of database
Raises:
======
ValueError if database can not be found | [
"return",
"a",
"string",
"array",
"of",
"all",
"the",
"element",
"from",
"the",
"database"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L74-L141 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | is_element_in_database | def is_element_in_database(element='', database='ENDF_VII'):
"""will try to find the element in the folder (database) specified
Parameters:
==========
element: string. Name of the element. Not case sensitive
database: string (default is 'ENDF_VII'). Name of folder that has the list of elements
Returns:
=======
bool: True if element was found in the database
False if element could not be found
"""
if element == '':
return False
list_entry_from_database = get_list_element_from_database(database=database)
if element in list_entry_from_database:
return True
return False | python | def is_element_in_database(element='', database='ENDF_VII'):
"""will try to find the element in the folder (database) specified
Parameters:
==========
element: string. Name of the element. Not case sensitive
database: string (default is 'ENDF_VII'). Name of folder that has the list of elements
Returns:
=======
bool: True if element was found in the database
False if element could not be found
"""
if element == '':
return False
list_entry_from_database = get_list_element_from_database(database=database)
if element in list_entry_from_database:
return True
return False | [
"def",
"is_element_in_database",
"(",
"element",
"=",
"''",
",",
"database",
"=",
"'ENDF_VII'",
")",
":",
"if",
"element",
"==",
"''",
":",
"return",
"False",
"list_entry_from_database",
"=",
"get_list_element_from_database",
"(",
"database",
"=",
"database",
")",
"if",
"element",
"in",
"list_entry_from_database",
":",
"return",
"True",
"return",
"False"
] | will try to find the element in the folder (database) specified
Parameters:
==========
element: string. Name of the element. Not case sensitive
database: string (default is 'ENDF_VII'). Name of folder that has the list of elements
Returns:
=======
bool: True if element was found in the database
False if element could not be found | [
"will",
"try",
"to",
"find",
"the",
"element",
"in",
"the",
"folder",
"(",
"database",
")",
"specified"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L144-L163 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | checking_stack | def checking_stack(stack, database='ENDF_VII'):
"""This method makes sure that all the elements from the various stacks are
in the database and that the thickness has the correct format (float)
Parameters:
==========
stack: dictionary that defines the various stacks
database: string (default is 'ENDF_VII') name of database
Raises:
======
ValueError if one of the element in one of the stack can not be found
ValueError if thickness is not a float
ValueError if elements and stoichiometric ratio arrays do not have the same size
Return:
======
True: for testing purpose only
"""
for _keys in stack:
_elements = stack[_keys]['elements']
for _element in _elements:
if not is_element_in_database(element=_element, database=database):
raise ValueError("Element {} can not be found in the database".format(_element))
_thickness = stack[_keys]['thickness']['value']
if not isinstance(_thickness, numbers.Number):
raise ValueError("Thickness {} should be a number!".format(_thickness))
_stoichiometric_ratio = stack[_keys]['stoichiometric_ratio']
if len(_stoichiometric_ratio) != len(_elements):
raise ValueError("stoichiometric Ratio and Elements should have the same size!")
return True | python | def checking_stack(stack, database='ENDF_VII'):
"""This method makes sure that all the elements from the various stacks are
in the database and that the thickness has the correct format (float)
Parameters:
==========
stack: dictionary that defines the various stacks
database: string (default is 'ENDF_VII') name of database
Raises:
======
ValueError if one of the element in one of the stack can not be found
ValueError if thickness is not a float
ValueError if elements and stoichiometric ratio arrays do not have the same size
Return:
======
True: for testing purpose only
"""
for _keys in stack:
_elements = stack[_keys]['elements']
for _element in _elements:
if not is_element_in_database(element=_element, database=database):
raise ValueError("Element {} can not be found in the database".format(_element))
_thickness = stack[_keys]['thickness']['value']
if not isinstance(_thickness, numbers.Number):
raise ValueError("Thickness {} should be a number!".format(_thickness))
_stoichiometric_ratio = stack[_keys]['stoichiometric_ratio']
if len(_stoichiometric_ratio) != len(_elements):
raise ValueError("stoichiometric Ratio and Elements should have the same size!")
return True | [
"def",
"checking_stack",
"(",
"stack",
",",
"database",
"=",
"'ENDF_VII'",
")",
":",
"for",
"_keys",
"in",
"stack",
":",
"_elements",
"=",
"stack",
"[",
"_keys",
"]",
"[",
"'elements'",
"]",
"for",
"_element",
"in",
"_elements",
":",
"if",
"not",
"is_element_in_database",
"(",
"element",
"=",
"_element",
",",
"database",
"=",
"database",
")",
":",
"raise",
"ValueError",
"(",
"\"Element {} can not be found in the database\"",
".",
"format",
"(",
"_element",
")",
")",
"_thickness",
"=",
"stack",
"[",
"_keys",
"]",
"[",
"'thickness'",
"]",
"[",
"'value'",
"]",
"if",
"not",
"isinstance",
"(",
"_thickness",
",",
"numbers",
".",
"Number",
")",
":",
"raise",
"ValueError",
"(",
"\"Thickness {} should be a number!\"",
".",
"format",
"(",
"_thickness",
")",
")",
"_stoichiometric_ratio",
"=",
"stack",
"[",
"_keys",
"]",
"[",
"'stoichiometric_ratio'",
"]",
"if",
"len",
"(",
"_stoichiometric_ratio",
")",
"!=",
"len",
"(",
"_elements",
")",
":",
"raise",
"ValueError",
"(",
"\"stoichiometric Ratio and Elements should have the same size!\"",
")",
"return",
"True"
] | This method makes sure that all the elements from the various stacks are
in the database and that the thickness has the correct format (float)
Parameters:
==========
stack: dictionary that defines the various stacks
database: string (default is 'ENDF_VII') name of database
Raises:
======
ValueError if one of the element in one of the stack can not be found
ValueError if thickness is not a float
ValueError if elements and stoichiometric ratio arrays do not have the same size
Return:
======
True: for testing purpose only | [
"This",
"method",
"makes",
"sure",
"that",
"all",
"the",
"elements",
"from",
"the",
"various",
"stacks",
"are",
"in",
"the",
"database",
"and",
"that",
"the",
"thickness",
"has",
"the",
"correct",
"format",
"(",
"float",
")"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L166-L199 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | formula_to_dictionary | def formula_to_dictionary(formula='', thickness=np.NaN, density=np.NaN, database='ENDF_VII'):
"""create dictionary based on formula given
Parameters:
===========
formula: string
ex: 'AgCo2'
ex: 'Ag'
thickness: float (in mm) default is np.NaN
density: float (in g/cm3) default is np.NaN
database: string (default is ENDV_VIII). Database where to look for elements
Raises:
=======
ValueError if one of the element is missing from the database
Return:
=======
the dictionary of the elements passed
ex: {'AgCo2': {'elements': ['Ag','Co'],
'stoichiometric_ratio': [1,2],
'thickness': {'value': thickness,
'units': 'mm'},
'density': {'value': density,
'units': 'g/cm3'},
'molar_mass': {'value': np.nan,
'units': 'g/mol'},
}
"""
if '.' in formula:
raise ValueError("formula '{}' is invalid, containing symbol '{}' !".format(formula, '.'))
_formula_parsed = re.findall(r'([A-Z][a-z]*)(\d*)', formula)
if len(_formula_parsed) == 0:
raise ValueError("formula '{}' is invalid !".format(formula))
# _dictionary = {}
_elements_array = []
_atomic_ratio_array = []
for _element in _formula_parsed:
[_single_element, _atomic_ratio] = list(_element)
if not is_element_in_database(element=_single_element, database=database):
raise ValueError("element '{}' not found in the database '{}'!".format(_single_element, database))
if _atomic_ratio == '':
_atomic_ratio = 1
_atomic_ratio_array.append(int(_atomic_ratio))
_elements_array.append(_single_element)
_dict = {formula: {'elements': _elements_array,
'stoichiometric_ratio': _atomic_ratio_array,
'thickness': {'value': thickness,
'units': 'mm'},
'density': {'value': density,
'units': 'g/cm3'},
'molar_mass': {'value': np.nan,
'units': 'g/mol'}
}
}
return _dict | python | def formula_to_dictionary(formula='', thickness=np.NaN, density=np.NaN, database='ENDF_VII'):
"""create dictionary based on formula given
Parameters:
===========
formula: string
ex: 'AgCo2'
ex: 'Ag'
thickness: float (in mm) default is np.NaN
density: float (in g/cm3) default is np.NaN
database: string (default is ENDV_VIII). Database where to look for elements
Raises:
=======
ValueError if one of the element is missing from the database
Return:
=======
the dictionary of the elements passed
ex: {'AgCo2': {'elements': ['Ag','Co'],
'stoichiometric_ratio': [1,2],
'thickness': {'value': thickness,
'units': 'mm'},
'density': {'value': density,
'units': 'g/cm3'},
'molar_mass': {'value': np.nan,
'units': 'g/mol'},
}
"""
if '.' in formula:
raise ValueError("formula '{}' is invalid, containing symbol '{}' !".format(formula, '.'))
_formula_parsed = re.findall(r'([A-Z][a-z]*)(\d*)', formula)
if len(_formula_parsed) == 0:
raise ValueError("formula '{}' is invalid !".format(formula))
# _dictionary = {}
_elements_array = []
_atomic_ratio_array = []
for _element in _formula_parsed:
[_single_element, _atomic_ratio] = list(_element)
if not is_element_in_database(element=_single_element, database=database):
raise ValueError("element '{}' not found in the database '{}'!".format(_single_element, database))
if _atomic_ratio == '':
_atomic_ratio = 1
_atomic_ratio_array.append(int(_atomic_ratio))
_elements_array.append(_single_element)
_dict = {formula: {'elements': _elements_array,
'stoichiometric_ratio': _atomic_ratio_array,
'thickness': {'value': thickness,
'units': 'mm'},
'density': {'value': density,
'units': 'g/cm3'},
'molar_mass': {'value': np.nan,
'units': 'g/mol'}
}
}
return _dict | [
"def",
"formula_to_dictionary",
"(",
"formula",
"=",
"''",
",",
"thickness",
"=",
"np",
".",
"NaN",
",",
"density",
"=",
"np",
".",
"NaN",
",",
"database",
"=",
"'ENDF_VII'",
")",
":",
"if",
"'.'",
"in",
"formula",
":",
"raise",
"ValueError",
"(",
"\"formula '{}' is invalid, containing symbol '{}' !\"",
".",
"format",
"(",
"formula",
",",
"'.'",
")",
")",
"_formula_parsed",
"=",
"re",
".",
"findall",
"(",
"r'([A-Z][a-z]*)(\\d*)'",
",",
"formula",
")",
"if",
"len",
"(",
"_formula_parsed",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"formula '{}' is invalid !\"",
".",
"format",
"(",
"formula",
")",
")",
"# _dictionary = {}",
"_elements_array",
"=",
"[",
"]",
"_atomic_ratio_array",
"=",
"[",
"]",
"for",
"_element",
"in",
"_formula_parsed",
":",
"[",
"_single_element",
",",
"_atomic_ratio",
"]",
"=",
"list",
"(",
"_element",
")",
"if",
"not",
"is_element_in_database",
"(",
"element",
"=",
"_single_element",
",",
"database",
"=",
"database",
")",
":",
"raise",
"ValueError",
"(",
"\"element '{}' not found in the database '{}'!\"",
".",
"format",
"(",
"_single_element",
",",
"database",
")",
")",
"if",
"_atomic_ratio",
"==",
"''",
":",
"_atomic_ratio",
"=",
"1",
"_atomic_ratio_array",
".",
"append",
"(",
"int",
"(",
"_atomic_ratio",
")",
")",
"_elements_array",
".",
"append",
"(",
"_single_element",
")",
"_dict",
"=",
"{",
"formula",
":",
"{",
"'elements'",
":",
"_elements_array",
",",
"'stoichiometric_ratio'",
":",
"_atomic_ratio_array",
",",
"'thickness'",
":",
"{",
"'value'",
":",
"thickness",
",",
"'units'",
":",
"'mm'",
"}",
",",
"'density'",
":",
"{",
"'value'",
":",
"density",
",",
"'units'",
":",
"'g/cm3'",
"}",
",",
"'molar_mass'",
":",
"{",
"'value'",
":",
"np",
".",
"nan",
",",
"'units'",
":",
"'g/mol'",
"}",
"}",
"}",
"return",
"_dict"
] | create dictionary based on formula given
Parameters:
===========
formula: string
ex: 'AgCo2'
ex: 'Ag'
thickness: float (in mm) default is np.NaN
density: float (in g/cm3) default is np.NaN
database: string (default is ENDV_VIII). Database where to look for elements
Raises:
=======
ValueError if one of the element is missing from the database
Return:
=======
the dictionary of the elements passed
ex: {'AgCo2': {'elements': ['Ag','Co'],
'stoichiometric_ratio': [1,2],
'thickness': {'value': thickness,
'units': 'mm'},
'density': {'value': density,
'units': 'g/cm3'},
'molar_mass': {'value': np.nan,
'units': 'g/mol'},
} | [
"create",
"dictionary",
"based",
"on",
"formula",
"given",
"Parameters",
":",
"===========",
"formula",
":",
"string",
"ex",
":",
"AgCo2",
"ex",
":",
"Ag",
"thickness",
":",
"float",
"(",
"in",
"mm",
")",
"default",
"is",
"np",
".",
"NaN",
"density",
":",
"float",
"(",
"in",
"g",
"/",
"cm3",
")",
"default",
"is",
"np",
".",
"NaN",
"database",
":",
"string",
"(",
"default",
"is",
"ENDV_VIII",
")",
".",
"Database",
"where",
"to",
"look",
"for",
"elements",
"Raises",
":",
"=======",
"ValueError",
"if",
"one",
"of",
"the",
"element",
"is",
"missing",
"from",
"the",
"database",
"Return",
":",
"=======",
"the",
"dictionary",
"of",
"the",
"elements",
"passed",
"ex",
":",
"{",
"AgCo2",
":",
"{",
"elements",
":",
"[",
"Ag",
"Co",
"]",
"stoichiometric_ratio",
":",
"[",
"1",
"2",
"]",
"thickness",
":",
"{",
"value",
":",
"thickness",
"units",
":",
"mm",
"}",
"density",
":",
"{",
"value",
":",
"density",
"units",
":",
"g",
"/",
"cm3",
"}",
"molar_mass",
":",
"{",
"value",
":",
"np",
".",
"nan",
"units",
":",
"g",
"/",
"mol",
"}",
"}"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L202-L261 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | get_isotope_dicts | def get_isotope_dicts(element='', database='ENDF_VII'):
"""return a dictionary with list of isotopes found in database and name of database files
Parameters:
===========
element: string. Name of the element
ex: 'Ag'
database: string (default is ENDF_VII)
Returns:
========
dictionary with isotopes and files
ex: {'Ag': {'isotopes': ['107-Ag','109-Ag'],
'file_names': ['Ag-107.csv','Ag-109.csv']}}
"""
_file_path = os.path.abspath(os.path.dirname(__file__))
_database_folder = os.path.join(_file_path, 'reference_data', database)
_element_search_path = os.path.join(_database_folder, element + '-*.csv')
list_files = glob.glob(_element_search_path)
if not list_files:
raise ValueError("File names contains NO '-', the name should in the format of 'Cd-115_m1' or 'Cd-114'")
list_files.sort()
isotope_dict = {'isotopes': {'list': [],
'file_names': [],
'density': {'value': np.NaN,
'units': 'g/cm3'},
'mass': {'value': [],
'units': 'g/mol',
},
'isotopic_ratio': [], },
'density': {'value': np.NaN,
'units': 'g/cm3'},
'molar_mass': {'value': np.NaN,
'units': 'g/mol'},
}
# isotope_dict_mirror = {}
_isotopes_list = []
_isotopes_list_files = []
_isotopes_mass = []
_isotopes_density = []
_isotopes_atomic_ratio = []
_density = np.NaN
_molar_mass = np.NaN
for file in list_files:
# Obtain element, z number from the basename
_basename = os.path.basename(file)
filename = os.path.splitext(_basename)[0]
if '-' in filename:
[_name, _number] = filename.split('-')
if '_' in _number:
[aaa, meta] = _number.split('_')
_number = aaa[:]
else:
_split_list = re.split(r'(\d+)', filename)
if len(_split_list) == 2:
[_name, _number] = _split_list
else:
_name = _split_list[0]
_number = _split_list[1]
if _number == '0':
_number = '12'
_symbol = _number + '-' + _name
isotope = str(_symbol)
_isotopes_list.append(isotope)
_isotopes_list_files.append(_basename)
_isotopes_mass.append(get_mass(isotope))
_isotopes_atomic_ratio.append(get_abundance(isotope))
_isotopes_density.append(get_density(isotope))
_density = get_density(element)
_molar_mass = get_mass(element)
isotope_dict['isotopes']['list'] = _isotopes_list
isotope_dict['isotopes']['file_names'] = _isotopes_list_files
isotope_dict['isotopes']['mass']['value'] = _isotopes_mass
isotope_dict['isotopes']['isotopic_ratio'] = _isotopes_atomic_ratio
isotope_dict['isotopes']['density']['value'] = _isotopes_density
isotope_dict['density']['value'] = _density
isotope_dict['molar_mass']['value'] = _molar_mass
return isotope_dict | python | def get_isotope_dicts(element='', database='ENDF_VII'):
"""return a dictionary with list of isotopes found in database and name of database files
Parameters:
===========
element: string. Name of the element
ex: 'Ag'
database: string (default is ENDF_VII)
Returns:
========
dictionary with isotopes and files
ex: {'Ag': {'isotopes': ['107-Ag','109-Ag'],
'file_names': ['Ag-107.csv','Ag-109.csv']}}
"""
_file_path = os.path.abspath(os.path.dirname(__file__))
_database_folder = os.path.join(_file_path, 'reference_data', database)
_element_search_path = os.path.join(_database_folder, element + '-*.csv')
list_files = glob.glob(_element_search_path)
if not list_files:
raise ValueError("File names contains NO '-', the name should in the format of 'Cd-115_m1' or 'Cd-114'")
list_files.sort()
isotope_dict = {'isotopes': {'list': [],
'file_names': [],
'density': {'value': np.NaN,
'units': 'g/cm3'},
'mass': {'value': [],
'units': 'g/mol',
},
'isotopic_ratio': [], },
'density': {'value': np.NaN,
'units': 'g/cm3'},
'molar_mass': {'value': np.NaN,
'units': 'g/mol'},
}
# isotope_dict_mirror = {}
_isotopes_list = []
_isotopes_list_files = []
_isotopes_mass = []
_isotopes_density = []
_isotopes_atomic_ratio = []
_density = np.NaN
_molar_mass = np.NaN
for file in list_files:
# Obtain element, z number from the basename
_basename = os.path.basename(file)
filename = os.path.splitext(_basename)[0]
if '-' in filename:
[_name, _number] = filename.split('-')
if '_' in _number:
[aaa, meta] = _number.split('_')
_number = aaa[:]
else:
_split_list = re.split(r'(\d+)', filename)
if len(_split_list) == 2:
[_name, _number] = _split_list
else:
_name = _split_list[0]
_number = _split_list[1]
if _number == '0':
_number = '12'
_symbol = _number + '-' + _name
isotope = str(_symbol)
_isotopes_list.append(isotope)
_isotopes_list_files.append(_basename)
_isotopes_mass.append(get_mass(isotope))
_isotopes_atomic_ratio.append(get_abundance(isotope))
_isotopes_density.append(get_density(isotope))
_density = get_density(element)
_molar_mass = get_mass(element)
isotope_dict['isotopes']['list'] = _isotopes_list
isotope_dict['isotopes']['file_names'] = _isotopes_list_files
isotope_dict['isotopes']['mass']['value'] = _isotopes_mass
isotope_dict['isotopes']['isotopic_ratio'] = _isotopes_atomic_ratio
isotope_dict['isotopes']['density']['value'] = _isotopes_density
isotope_dict['density']['value'] = _density
isotope_dict['molar_mass']['value'] = _molar_mass
return isotope_dict | [
"def",
"get_isotope_dicts",
"(",
"element",
"=",
"''",
",",
"database",
"=",
"'ENDF_VII'",
")",
":",
"_file_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"_database_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_file_path",
",",
"'reference_data'",
",",
"database",
")",
"_element_search_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_database_folder",
",",
"element",
"+",
"'-*.csv'",
")",
"list_files",
"=",
"glob",
".",
"glob",
"(",
"_element_search_path",
")",
"if",
"not",
"list_files",
":",
"raise",
"ValueError",
"(",
"\"File names contains NO '-', the name should in the format of 'Cd-115_m1' or 'Cd-114'\"",
")",
"list_files",
".",
"sort",
"(",
")",
"isotope_dict",
"=",
"{",
"'isotopes'",
":",
"{",
"'list'",
":",
"[",
"]",
",",
"'file_names'",
":",
"[",
"]",
",",
"'density'",
":",
"{",
"'value'",
":",
"np",
".",
"NaN",
",",
"'units'",
":",
"'g/cm3'",
"}",
",",
"'mass'",
":",
"{",
"'value'",
":",
"[",
"]",
",",
"'units'",
":",
"'g/mol'",
",",
"}",
",",
"'isotopic_ratio'",
":",
"[",
"]",
",",
"}",
",",
"'density'",
":",
"{",
"'value'",
":",
"np",
".",
"NaN",
",",
"'units'",
":",
"'g/cm3'",
"}",
",",
"'molar_mass'",
":",
"{",
"'value'",
":",
"np",
".",
"NaN",
",",
"'units'",
":",
"'g/mol'",
"}",
",",
"}",
"# isotope_dict_mirror = {}",
"_isotopes_list",
"=",
"[",
"]",
"_isotopes_list_files",
"=",
"[",
"]",
"_isotopes_mass",
"=",
"[",
"]",
"_isotopes_density",
"=",
"[",
"]",
"_isotopes_atomic_ratio",
"=",
"[",
"]",
"_density",
"=",
"np",
".",
"NaN",
"_molar_mass",
"=",
"np",
".",
"NaN",
"for",
"file",
"in",
"list_files",
":",
"# Obtain element, z number from the basename",
"_basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file",
")",
"filename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"_basename",
")",
"[",
"0",
"]",
"if",
"'-'",
"in",
"filename",
":",
"[",
"_name",
",",
"_number",
"]",
"=",
"filename",
".",
"split",
"(",
"'-'",
")",
"if",
"'_'",
"in",
"_number",
":",
"[",
"aaa",
",",
"meta",
"]",
"=",
"_number",
".",
"split",
"(",
"'_'",
")",
"_number",
"=",
"aaa",
"[",
":",
"]",
"else",
":",
"_split_list",
"=",
"re",
".",
"split",
"(",
"r'(\\d+)'",
",",
"filename",
")",
"if",
"len",
"(",
"_split_list",
")",
"==",
"2",
":",
"[",
"_name",
",",
"_number",
"]",
"=",
"_split_list",
"else",
":",
"_name",
"=",
"_split_list",
"[",
"0",
"]",
"_number",
"=",
"_split_list",
"[",
"1",
"]",
"if",
"_number",
"==",
"'0'",
":",
"_number",
"=",
"'12'",
"_symbol",
"=",
"_number",
"+",
"'-'",
"+",
"_name",
"isotope",
"=",
"str",
"(",
"_symbol",
")",
"_isotopes_list",
".",
"append",
"(",
"isotope",
")",
"_isotopes_list_files",
".",
"append",
"(",
"_basename",
")",
"_isotopes_mass",
".",
"append",
"(",
"get_mass",
"(",
"isotope",
")",
")",
"_isotopes_atomic_ratio",
".",
"append",
"(",
"get_abundance",
"(",
"isotope",
")",
")",
"_isotopes_density",
".",
"append",
"(",
"get_density",
"(",
"isotope",
")",
")",
"_density",
"=",
"get_density",
"(",
"element",
")",
"_molar_mass",
"=",
"get_mass",
"(",
"element",
")",
"isotope_dict",
"[",
"'isotopes'",
"]",
"[",
"'list'",
"]",
"=",
"_isotopes_list",
"isotope_dict",
"[",
"'isotopes'",
"]",
"[",
"'file_names'",
"]",
"=",
"_isotopes_list_files",
"isotope_dict",
"[",
"'isotopes'",
"]",
"[",
"'mass'",
"]",
"[",
"'value'",
"]",
"=",
"_isotopes_mass",
"isotope_dict",
"[",
"'isotopes'",
"]",
"[",
"'isotopic_ratio'",
"]",
"=",
"_isotopes_atomic_ratio",
"isotope_dict",
"[",
"'isotopes'",
"]",
"[",
"'density'",
"]",
"[",
"'value'",
"]",
"=",
"_isotopes_density",
"isotope_dict",
"[",
"'density'",
"]",
"[",
"'value'",
"]",
"=",
"_density",
"isotope_dict",
"[",
"'molar_mass'",
"]",
"[",
"'value'",
"]",
"=",
"_molar_mass",
"return",
"isotope_dict"
] | return a dictionary with list of isotopes found in database and name of database files
Parameters:
===========
element: string. Name of the element
ex: 'Ag'
database: string (default is ENDF_VII)
Returns:
========
dictionary with isotopes and files
ex: {'Ag': {'isotopes': ['107-Ag','109-Ag'],
'file_names': ['Ag-107.csv','Ag-109.csv']}} | [
"return",
"a",
"dictionary",
"with",
"list",
"of",
"isotopes",
"found",
"in",
"database",
"and",
"name",
"of",
"database",
"files",
"Parameters",
":",
"===========",
"element",
":",
"string",
".",
"Name",
"of",
"the",
"element",
"ex",
":",
"Ag",
"database",
":",
"string",
"(",
"default",
"is",
"ENDF_VII",
")",
"Returns",
":",
"========",
"dictionary",
"with",
"isotopes",
"and",
"files",
"ex",
":",
"{",
"Ag",
":",
"{",
"isotopes",
":",
"[",
"107",
"-",
"Ag",
"109",
"-",
"Ag",
"]",
"file_names",
":",
"[",
"Ag",
"-",
"107",
".",
"csv",
"Ag",
"-",
"109",
".",
"csv",
"]",
"}}"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L264-L347 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | get_database_data | def get_database_data(file_name=''):
"""return the energy (eV) and Sigma (barn) from the file_name
Parameters:
===========
file_name: string ('' by default) name of csv file
Returns:
========
pandas dataframe
Raises:
=======
IOError if file does not exist
"""
if not os.path.exists(file_name):
raise IOError("File {} does not exist!".format(file_name))
df = pd.read_csv(file_name, header=1)
return df | python | def get_database_data(file_name=''):
"""return the energy (eV) and Sigma (barn) from the file_name
Parameters:
===========
file_name: string ('' by default) name of csv file
Returns:
========
pandas dataframe
Raises:
=======
IOError if file does not exist
"""
if not os.path.exists(file_name):
raise IOError("File {} does not exist!".format(file_name))
df = pd.read_csv(file_name, header=1)
return df | [
"def",
"get_database_data",
"(",
"file_name",
"=",
"''",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file_name",
")",
":",
"raise",
"IOError",
"(",
"\"File {} does not exist!\"",
".",
"format",
"(",
"file_name",
")",
")",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"file_name",
",",
"header",
"=",
"1",
")",
"return",
"df"
] | return the energy (eV) and Sigma (barn) from the file_name
Parameters:
===========
file_name: string ('' by default) name of csv file
Returns:
========
pandas dataframe
Raises:
=======
IOError if file does not exist | [
"return",
"the",
"energy",
"(",
"eV",
")",
"and",
"Sigma",
"(",
"barn",
")",
"from",
"the",
"file_name",
"Parameters",
":",
"===========",
"file_name",
":",
"string",
"(",
"by",
"default",
")",
"name",
"of",
"csv",
"file",
"Returns",
":",
"========",
"pandas",
"dataframe",
"Raises",
":",
"=======",
"IOError",
"if",
"file",
"does",
"not",
"exist"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L413-L431 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | get_interpolated_data | def get_interpolated_data(df: pd.DataFrame, e_min=np.nan, e_max=np.nan, e_step=np.nan):
"""return the interpolated x and y axis for the given x range [e_min, e_max] with step defined
:param df: input data frame
:type df: pandas.DataFrame
:param e_min: left energy range in eV of new interpolated data
:type e_min: float
:param e_max: right energy range in eV of new interpolated data
:type e_max: float
:param e_step: energy step in eV for interpolation
:type e_step: float
:return: x_axis and y_axis of interpolated data over specified range
:rtype: dict
"""
nbr_point = int((e_max - e_min) / e_step + 1)
x_axis = np.linspace(e_min, e_max, nbr_point).round(6)
y_axis_function = interp1d(x=df['E_eV'], y=df['Sig_b'], kind='linear')
y_axis = y_axis_function(x_axis)
return {'x_axis': x_axis, 'y_axis': y_axis} | python | def get_interpolated_data(df: pd.DataFrame, e_min=np.nan, e_max=np.nan, e_step=np.nan):
"""return the interpolated x and y axis for the given x range [e_min, e_max] with step defined
:param df: input data frame
:type df: pandas.DataFrame
:param e_min: left energy range in eV of new interpolated data
:type e_min: float
:param e_max: right energy range in eV of new interpolated data
:type e_max: float
:param e_step: energy step in eV for interpolation
:type e_step: float
:return: x_axis and y_axis of interpolated data over specified range
:rtype: dict
"""
nbr_point = int((e_max - e_min) / e_step + 1)
x_axis = np.linspace(e_min, e_max, nbr_point).round(6)
y_axis_function = interp1d(x=df['E_eV'], y=df['Sig_b'], kind='linear')
y_axis = y_axis_function(x_axis)
return {'x_axis': x_axis, 'y_axis': y_axis} | [
"def",
"get_interpolated_data",
"(",
"df",
":",
"pd",
".",
"DataFrame",
",",
"e_min",
"=",
"np",
".",
"nan",
",",
"e_max",
"=",
"np",
".",
"nan",
",",
"e_step",
"=",
"np",
".",
"nan",
")",
":",
"nbr_point",
"=",
"int",
"(",
"(",
"e_max",
"-",
"e_min",
")",
"/",
"e_step",
"+",
"1",
")",
"x_axis",
"=",
"np",
".",
"linspace",
"(",
"e_min",
",",
"e_max",
",",
"nbr_point",
")",
".",
"round",
"(",
"6",
")",
"y_axis_function",
"=",
"interp1d",
"(",
"x",
"=",
"df",
"[",
"'E_eV'",
"]",
",",
"y",
"=",
"df",
"[",
"'Sig_b'",
"]",
",",
"kind",
"=",
"'linear'",
")",
"y_axis",
"=",
"y_axis_function",
"(",
"x_axis",
")",
"return",
"{",
"'x_axis'",
":",
"x_axis",
",",
"'y_axis'",
":",
"y_axis",
"}"
] | return the interpolated x and y axis for the given x range [e_min, e_max] with step defined
:param df: input data frame
:type df: pandas.DataFrame
:param e_min: left energy range in eV of new interpolated data
:type e_min: float
:param e_max: right energy range in eV of new interpolated data
:type e_max: float
:param e_step: energy step in eV for interpolation
:type e_step: float
:return: x_axis and y_axis of interpolated data over specified range
:rtype: dict | [
"return",
"the",
"interpolated",
"x",
"and",
"y",
"axis",
"for",
"the",
"given",
"x",
"range",
"[",
"e_min",
"e_max",
"]",
"with",
"step",
"defined"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L434-L454 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | get_sigma | def get_sigma(database_file_name='', e_min=np.NaN, e_max=np.NaN, e_step=np.NaN, t_kelvin=None):
"""retrieve the Energy and sigma axis for the given isotope
:param database_file_name: path/to/file with extension
:type database_file_name: string
:param e_min: left energy range in eV of new interpolated data
:type e_min: float
:param e_max: right energy range in eV of new interpolated data
:type e_max: float
:param e_step: energy step in eV for interpolation
:type e_step: float
:param t_kelvin: temperature in Kelvin
:type t_kelvin: float
:return: {'energy': np.array, 'sigma': np.array}
:rtype: dict
"""
file_extension = os.path.splitext(database_file_name)[1]
if t_kelvin is None:
# '.csv' files
if file_extension != '.csv':
raise IOError("Cross-section File type must be '.csv'")
else:
_df = get_database_data(file_name=database_file_name)
_dict = get_interpolated_data(df=_df, e_min=e_min, e_max=e_max,
e_step=e_step)
return {'energy_eV': _dict['x_axis'],
'sigma_b': _dict['y_axis']}
else:
raise ValueError("Doppler broadened cross-section in not yet supported in current version.") | python | def get_sigma(database_file_name='', e_min=np.NaN, e_max=np.NaN, e_step=np.NaN, t_kelvin=None):
"""retrieve the Energy and sigma axis for the given isotope
:param database_file_name: path/to/file with extension
:type database_file_name: string
:param e_min: left energy range in eV of new interpolated data
:type e_min: float
:param e_max: right energy range in eV of new interpolated data
:type e_max: float
:param e_step: energy step in eV for interpolation
:type e_step: float
:param t_kelvin: temperature in Kelvin
:type t_kelvin: float
:return: {'energy': np.array, 'sigma': np.array}
:rtype: dict
"""
file_extension = os.path.splitext(database_file_name)[1]
if t_kelvin is None:
# '.csv' files
if file_extension != '.csv':
raise IOError("Cross-section File type must be '.csv'")
else:
_df = get_database_data(file_name=database_file_name)
_dict = get_interpolated_data(df=_df, e_min=e_min, e_max=e_max,
e_step=e_step)
return {'energy_eV': _dict['x_axis'],
'sigma_b': _dict['y_axis']}
else:
raise ValueError("Doppler broadened cross-section in not yet supported in current version.") | [
"def",
"get_sigma",
"(",
"database_file_name",
"=",
"''",
",",
"e_min",
"=",
"np",
".",
"NaN",
",",
"e_max",
"=",
"np",
".",
"NaN",
",",
"e_step",
"=",
"np",
".",
"NaN",
",",
"t_kelvin",
"=",
"None",
")",
":",
"file_extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"database_file_name",
")",
"[",
"1",
"]",
"if",
"t_kelvin",
"is",
"None",
":",
"# '.csv' files",
"if",
"file_extension",
"!=",
"'.csv'",
":",
"raise",
"IOError",
"(",
"\"Cross-section File type must be '.csv'\"",
")",
"else",
":",
"_df",
"=",
"get_database_data",
"(",
"file_name",
"=",
"database_file_name",
")",
"_dict",
"=",
"get_interpolated_data",
"(",
"df",
"=",
"_df",
",",
"e_min",
"=",
"e_min",
",",
"e_max",
"=",
"e_max",
",",
"e_step",
"=",
"e_step",
")",
"return",
"{",
"'energy_eV'",
":",
"_dict",
"[",
"'x_axis'",
"]",
",",
"'sigma_b'",
":",
"_dict",
"[",
"'y_axis'",
"]",
"}",
"else",
":",
"raise",
"ValueError",
"(",
"\"Doppler broadened cross-section in not yet supported in current version.\"",
")"
] | retrieve the Energy and sigma axis for the given isotope
:param database_file_name: path/to/file with extension
:type database_file_name: string
:param e_min: left energy range in eV of new interpolated data
:type e_min: float
:param e_max: right energy range in eV of new interpolated data
:type e_max: float
:param e_step: energy step in eV for interpolation
:type e_step: float
:param t_kelvin: temperature in Kelvin
:type t_kelvin: float
:return: {'energy': np.array, 'sigma': np.array}
:rtype: dict | [
"retrieve",
"the",
"Energy",
"and",
"sigma",
"axis",
"for",
"the",
"given",
"isotope"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L457-L488 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | get_atoms_per_cm3_of_layer | def get_atoms_per_cm3_of_layer(compound_dict: dict):
"""
calculate the atoms per cm3 of the given compound (layer)
:param compound_dict: compound infomation to pass
:type compound_dict: dict
:return: molar mass and atom density for layer
:rtype: float
"""
# atoms_per_cm3 = {}
_list_of_elements = compound_dict['elements']
_stoichiometric_list = compound_dict['stoichiometric_ratio']
_element_stoichio = zip(_list_of_elements, _stoichiometric_list)
_molar_mass_sum = 0
for _element, _stoichio in _element_stoichio:
_molar_mass_sum += _stoichio * compound_dict[_element]['molar_mass']['value']
atoms_per_cm3 = Avogadro * compound_dict['density']['value'] / _molar_mass_sum
# _element_stoichio = zip(_list_of_elements, _stoichiometric_list)
# for _element, _stoichio in _element_stoichio:
# _step1 = (compound_dict['density']['value'] * _stoichio) / _molar_mass_sum
# atoms_per_cm3[_element] = Avogadro * _step1
return _molar_mass_sum, atoms_per_cm3 | python | def get_atoms_per_cm3_of_layer(compound_dict: dict):
"""
calculate the atoms per cm3 of the given compound (layer)
:param compound_dict: compound infomation to pass
:type compound_dict: dict
:return: molar mass and atom density for layer
:rtype: float
"""
# atoms_per_cm3 = {}
_list_of_elements = compound_dict['elements']
_stoichiometric_list = compound_dict['stoichiometric_ratio']
_element_stoichio = zip(_list_of_elements, _stoichiometric_list)
_molar_mass_sum = 0
for _element, _stoichio in _element_stoichio:
_molar_mass_sum += _stoichio * compound_dict[_element]['molar_mass']['value']
atoms_per_cm3 = Avogadro * compound_dict['density']['value'] / _molar_mass_sum
# _element_stoichio = zip(_list_of_elements, _stoichiometric_list)
# for _element, _stoichio in _element_stoichio:
# _step1 = (compound_dict['density']['value'] * _stoichio) / _molar_mass_sum
# atoms_per_cm3[_element] = Avogadro * _step1
return _molar_mass_sum, atoms_per_cm3 | [
"def",
"get_atoms_per_cm3_of_layer",
"(",
"compound_dict",
":",
"dict",
")",
":",
"# atoms_per_cm3 = {}",
"_list_of_elements",
"=",
"compound_dict",
"[",
"'elements'",
"]",
"_stoichiometric_list",
"=",
"compound_dict",
"[",
"'stoichiometric_ratio'",
"]",
"_element_stoichio",
"=",
"zip",
"(",
"_list_of_elements",
",",
"_stoichiometric_list",
")",
"_molar_mass_sum",
"=",
"0",
"for",
"_element",
",",
"_stoichio",
"in",
"_element_stoichio",
":",
"_molar_mass_sum",
"+=",
"_stoichio",
"*",
"compound_dict",
"[",
"_element",
"]",
"[",
"'molar_mass'",
"]",
"[",
"'value'",
"]",
"atoms_per_cm3",
"=",
"Avogadro",
"*",
"compound_dict",
"[",
"'density'",
"]",
"[",
"'value'",
"]",
"/",
"_molar_mass_sum",
"# _element_stoichio = zip(_list_of_elements, _stoichiometric_list)",
"# for _element, _stoichio in _element_stoichio:",
"# _step1 = (compound_dict['density']['value'] * _stoichio) / _molar_mass_sum",
"# atoms_per_cm3[_element] = Avogadro * _step1",
"return",
"_molar_mass_sum",
",",
"atoms_per_cm3"
] | calculate the atoms per cm3 of the given compound (layer)
:param compound_dict: compound infomation to pass
:type compound_dict: dict
:return: molar mass and atom density for layer
:rtype: float | [
"calculate",
"the",
"atoms",
"per",
"cm3",
"of",
"the",
"given",
"compound",
"(",
"layer",
")",
":",
"param",
"compound_dict",
":",
"compound",
"infomation",
"to",
"pass",
":",
"type",
"compound_dict",
":",
"dict",
":",
"return",
":",
"molar",
"mass",
"and",
"atom",
"density",
"for",
"layer",
":",
"rtype",
":",
"float"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L538-L562 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | calculate_linear_attenuation_coefficient | def calculate_linear_attenuation_coefficient(atoms_per_cm3: np.float, sigma_b: np.array):
"""calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of element/isotope)
sigma_b: np.array of sigma retrieved from database
Returns:
========
transmission array
"""
miu_per_cm = 1e-24 * sigma_b * atoms_per_cm3
return np.array(miu_per_cm) | python | def calculate_linear_attenuation_coefficient(atoms_per_cm3: np.float, sigma_b: np.array):
"""calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of element/isotope)
sigma_b: np.array of sigma retrieved from database
Returns:
========
transmission array
"""
miu_per_cm = 1e-24 * sigma_b * atoms_per_cm3
return np.array(miu_per_cm) | [
"def",
"calculate_linear_attenuation_coefficient",
"(",
"atoms_per_cm3",
":",
"np",
".",
"float",
",",
"sigma_b",
":",
"np",
".",
"array",
")",
":",
"miu_per_cm",
"=",
"1e-24",
"*",
"sigma_b",
"*",
"atoms_per_cm3",
"return",
"np",
".",
"array",
"(",
"miu_per_cm",
")"
] | calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of element/isotope)
sigma_b: np.array of sigma retrieved from database
Returns:
========
transmission array | [
"calculate",
"the",
"transmission",
"signal",
"using",
"the",
"formula"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L565-L581 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | calculate_trans | def calculate_trans(thickness_cm: np.float, miu_per_cm: np.array):
"""calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of element/isotope)
sigma_b: np.array of sigma retrieved from database
Returns:
========
transmission array
"""
transmission = np.exp(-thickness_cm * miu_per_cm)
return np.array(transmission) | python | def calculate_trans(thickness_cm: np.float, miu_per_cm: np.array):
"""calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of element/isotope)
sigma_b: np.array of sigma retrieved from database
Returns:
========
transmission array
"""
transmission = np.exp(-thickness_cm * miu_per_cm)
return np.array(transmission) | [
"def",
"calculate_trans",
"(",
"thickness_cm",
":",
"np",
".",
"float",
",",
"miu_per_cm",
":",
"np",
".",
"array",
")",
":",
"transmission",
"=",
"np",
".",
"exp",
"(",
"-",
"thickness_cm",
"*",
"miu_per_cm",
")",
"return",
"np",
".",
"array",
"(",
"transmission",
")"
] | calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of element/isotope)
sigma_b: np.array of sigma retrieved from database
Returns:
========
transmission array | [
"calculate",
"the",
"transmission",
"signal",
"using",
"the",
"formula"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L584-L600 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | calculate_transmission | def calculate_transmission(thickness_cm: np.float, atoms_per_cm3: np.float, sigma_b: np.array):
"""calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of element/isotope)
sigma_b: np.array of sigma retrieved from database
Returns:
========
transmission array
"""
miu_per_cm = calculate_linear_attenuation_coefficient(atoms_per_cm3=atoms_per_cm3, sigma_b=sigma_b)
transmission = calculate_trans(thickness_cm=thickness_cm, miu_per_cm=miu_per_cm)
return miu_per_cm, transmission | python | def calculate_transmission(thickness_cm: np.float, atoms_per_cm3: np.float, sigma_b: np.array):
"""calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of element/isotope)
sigma_b: np.array of sigma retrieved from database
Returns:
========
transmission array
"""
miu_per_cm = calculate_linear_attenuation_coefficient(atoms_per_cm3=atoms_per_cm3, sigma_b=sigma_b)
transmission = calculate_trans(thickness_cm=thickness_cm, miu_per_cm=miu_per_cm)
return miu_per_cm, transmission | [
"def",
"calculate_transmission",
"(",
"thickness_cm",
":",
"np",
".",
"float",
",",
"atoms_per_cm3",
":",
"np",
".",
"float",
",",
"sigma_b",
":",
"np",
".",
"array",
")",
":",
"miu_per_cm",
"=",
"calculate_linear_attenuation_coefficient",
"(",
"atoms_per_cm3",
"=",
"atoms_per_cm3",
",",
"sigma_b",
"=",
"sigma_b",
")",
"transmission",
"=",
"calculate_trans",
"(",
"thickness_cm",
"=",
"thickness_cm",
",",
"miu_per_cm",
"=",
"miu_per_cm",
")",
"return",
"miu_per_cm",
",",
"transmission"
] | calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of element/isotope)
sigma_b: np.array of sigma retrieved from database
Returns:
========
transmission array | [
"calculate",
"the",
"transmission",
"signal",
"using",
"the",
"formula",
"transmission",
"=",
"exp",
"(",
"-",
"thickness_cm",
"*",
"atoms_per_cm3",
"*",
"1e",
"-",
"24",
"*",
"sigma_b",
")",
"Parameters",
":",
"===========",
"thickness",
":",
"float",
"(",
"in",
"cm",
")",
"atoms_per_cm3",
":",
"float",
"(",
"number",
"of",
"atoms",
"per",
"cm3",
"of",
"element",
"/",
"isotope",
")",
"sigma_b",
":",
"np",
".",
"array",
"of",
"sigma",
"retrieved",
"from",
"database",
"Returns",
":",
"========",
"transmission",
"array"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L603-L620 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | set_distance_units | def set_distance_units(value=np.NaN, from_units='mm', to_units='cm'):
"""convert distance into new units
Parameters:
===========
value: float. value to convert
from_units: string. Must be 'mm', 'cm' or 'm'
to_units: string. must be 'mm','cm' or 'm'
Returns:
========
converted value
Raises:
=======
ValueError if from_units is not a valid unit (see above)
ValueError if to_units is not a valid unit
"""
if from_units == to_units:
return value
if from_units == 'cm':
if to_units == 'mm':
coeff = 10
elif to_units == 'm':
coeff = 0.01
else:
raise ValueError("to_units not supported ['cm','m','mm']!")
elif from_units == 'mm':
if to_units == 'cm':
coeff = 0.1
elif to_units == 'm':
coeff = 0.001
else:
raise ValueError("to_units not supported ['cm','m','mm']!")
elif from_units == 'm':
if to_units == 'mm':
coeff = 1000
elif to_units == 'cm':
coeff = 100
else:
raise ValueError("to_units not supported ['cm','m','mm']!")
else:
raise ValueError("to_units not supported ['cm','m','mm']!")
return coeff * value | python | def set_distance_units(value=np.NaN, from_units='mm', to_units='cm'):
"""convert distance into new units
Parameters:
===========
value: float. value to convert
from_units: string. Must be 'mm', 'cm' or 'm'
to_units: string. must be 'mm','cm' or 'm'
Returns:
========
converted value
Raises:
=======
ValueError if from_units is not a valid unit (see above)
ValueError if to_units is not a valid unit
"""
if from_units == to_units:
return value
if from_units == 'cm':
if to_units == 'mm':
coeff = 10
elif to_units == 'm':
coeff = 0.01
else:
raise ValueError("to_units not supported ['cm','m','mm']!")
elif from_units == 'mm':
if to_units == 'cm':
coeff = 0.1
elif to_units == 'm':
coeff = 0.001
else:
raise ValueError("to_units not supported ['cm','m','mm']!")
elif from_units == 'm':
if to_units == 'mm':
coeff = 1000
elif to_units == 'cm':
coeff = 100
else:
raise ValueError("to_units not supported ['cm','m','mm']!")
else:
raise ValueError("to_units not supported ['cm','m','mm']!")
return coeff * value | [
"def",
"set_distance_units",
"(",
"value",
"=",
"np",
".",
"NaN",
",",
"from_units",
"=",
"'mm'",
",",
"to_units",
"=",
"'cm'",
")",
":",
"if",
"from_units",
"==",
"to_units",
":",
"return",
"value",
"if",
"from_units",
"==",
"'cm'",
":",
"if",
"to_units",
"==",
"'mm'",
":",
"coeff",
"=",
"10",
"elif",
"to_units",
"==",
"'m'",
":",
"coeff",
"=",
"0.01",
"else",
":",
"raise",
"ValueError",
"(",
"\"to_units not supported ['cm','m','mm']!\"",
")",
"elif",
"from_units",
"==",
"'mm'",
":",
"if",
"to_units",
"==",
"'cm'",
":",
"coeff",
"=",
"0.1",
"elif",
"to_units",
"==",
"'m'",
":",
"coeff",
"=",
"0.001",
"else",
":",
"raise",
"ValueError",
"(",
"\"to_units not supported ['cm','m','mm']!\"",
")",
"elif",
"from_units",
"==",
"'m'",
":",
"if",
"to_units",
"==",
"'mm'",
":",
"coeff",
"=",
"1000",
"elif",
"to_units",
"==",
"'cm'",
":",
"coeff",
"=",
"100",
"else",
":",
"raise",
"ValueError",
"(",
"\"to_units not supported ['cm','m','mm']!\"",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"to_units not supported ['cm','m','mm']!\"",
")",
"return",
"coeff",
"*",
"value"
] | convert distance into new units
Parameters:
===========
value: float. value to convert
from_units: string. Must be 'mm', 'cm' or 'm'
to_units: string. must be 'mm','cm' or 'm'
Returns:
========
converted value
Raises:
=======
ValueError if from_units is not a valid unit (see above)
ValueError if to_units is not a valid unit | [
"convert",
"distance",
"into",
"new",
"units",
"Parameters",
":",
"===========",
"value",
":",
"float",
".",
"value",
"to",
"convert",
"from_units",
":",
"string",
".",
"Must",
"be",
"mm",
"cm",
"or",
"m",
"to_units",
":",
"string",
".",
"must",
"be",
"mm",
"cm",
"or",
"m",
"Returns",
":",
"========",
"converted",
"value",
"Raises",
":",
"=======",
"ValueError",
"if",
"from_units",
"is",
"not",
"a",
"valid",
"unit",
"(",
"see",
"above",
")",
"ValueError",
"if",
"to_units",
"is",
"not",
"a",
"valid",
"unit"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L623-L668 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | ev_to_s | def ev_to_s(offset_us, source_to_detector_m, array):
# delay values is normal 2.99 us with NONE actual MCP delay settings
"""convert energy (eV) to time (us)
Parameters:
===========
array: array (in eV)
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
time: array in s
"""
# 1000 is used to convert eV to meV
time_s = np.sqrt(81.787 / (array * 1000.)) * source_to_detector_m / 3956.
time_record_s = time_s - offset_us * 1e-6
return time_record_s | python | def ev_to_s(offset_us, source_to_detector_m, array):
# delay values is normal 2.99 us with NONE actual MCP delay settings
"""convert energy (eV) to time (us)
Parameters:
===========
array: array (in eV)
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
time: array in s
"""
# 1000 is used to convert eV to meV
time_s = np.sqrt(81.787 / (array * 1000.)) * source_to_detector_m / 3956.
time_record_s = time_s - offset_us * 1e-6
return time_record_s | [
"def",
"ev_to_s",
"(",
"offset_us",
",",
"source_to_detector_m",
",",
"array",
")",
":",
"# delay values is normal 2.99 us with NONE actual MCP delay settings",
"# 1000 is used to convert eV to meV",
"time_s",
"=",
"np",
".",
"sqrt",
"(",
"81.787",
"/",
"(",
"array",
"*",
"1000.",
")",
")",
"*",
"source_to_detector_m",
"/",
"3956.",
"time_record_s",
"=",
"time_s",
"-",
"offset_us",
"*",
"1e-6",
"return",
"time_record_s"
] | convert energy (eV) to time (us)
Parameters:
===========
array: array (in eV)
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
time: array in s | [
"convert",
"energy",
"(",
"eV",
")",
"to",
"time",
"(",
"us",
")"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L699-L716 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | s_to_ev | def s_to_ev(offset_us, source_to_detector_m, array):
"""convert time (s) to energy (eV)
Parameters:
===========
numpy array of time in s
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
numpy array of energy in eV
"""
lambda_a = 3956. * (array + offset_us * 1e-6) / source_to_detector_m
return (81.787 / pow(lambda_a, 2)) / 1000. | python | def s_to_ev(offset_us, source_to_detector_m, array):
"""convert time (s) to energy (eV)
Parameters:
===========
numpy array of time in s
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
numpy array of energy in eV
"""
lambda_a = 3956. * (array + offset_us * 1e-6) / source_to_detector_m
return (81.787 / pow(lambda_a, 2)) / 1000. | [
"def",
"s_to_ev",
"(",
"offset_us",
",",
"source_to_detector_m",
",",
"array",
")",
":",
"lambda_a",
"=",
"3956.",
"*",
"(",
"array",
"+",
"offset_us",
"*",
"1e-6",
")",
"/",
"source_to_detector_m",
"return",
"(",
"81.787",
"/",
"pow",
"(",
"lambda_a",
",",
"2",
")",
")",
"/",
"1000."
] | convert time (s) to energy (eV)
Parameters:
===========
numpy array of time in s
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
numpy array of energy in eV | [
"convert",
"time",
"(",
"s",
")",
"to",
"energy",
"(",
"eV",
")",
"Parameters",
":",
"===========",
"numpy",
"array",
"of",
"time",
"in",
"s",
"offset_us",
":",
"float",
".",
"Delay",
"of",
"detector",
"in",
"us",
"source_to_detector_m",
":",
"float",
".",
"Distance",
"source",
"to",
"detector",
"in",
"m"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L719-L732 |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | ev_to_image_number | def ev_to_image_number(offset_us, source_to_detector_m, time_resolution_us, t_start_us, array):
# delay values is normal 2.99 us with NONE actual MCP delay settings
"""convert energy (eV) to image numbers (#)
Parameters:
===========
numpy array of energy in eV
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
image numbers: array of image number
"""
time_tot_us = np.sqrt(81.787 / (array * 1000)) * source_to_detector_m * 100 / 0.3956
time_record_us = (time_tot_us + offset_us)
image_number = (time_record_us - t_start_us) / time_resolution_us
return image_number | python | def ev_to_image_number(offset_us, source_to_detector_m, time_resolution_us, t_start_us, array):
# delay values is normal 2.99 us with NONE actual MCP delay settings
"""convert energy (eV) to image numbers (#)
Parameters:
===========
numpy array of energy in eV
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
image numbers: array of image number
"""
time_tot_us = np.sqrt(81.787 / (array * 1000)) * source_to_detector_m * 100 / 0.3956
time_record_us = (time_tot_us + offset_us)
image_number = (time_record_us - t_start_us) / time_resolution_us
return image_number | [
"def",
"ev_to_image_number",
"(",
"offset_us",
",",
"source_to_detector_m",
",",
"time_resolution_us",
",",
"t_start_us",
",",
"array",
")",
":",
"# delay values is normal 2.99 us with NONE actual MCP delay settings",
"time_tot_us",
"=",
"np",
".",
"sqrt",
"(",
"81.787",
"/",
"(",
"array",
"*",
"1000",
")",
")",
"*",
"source_to_detector_m",
"*",
"100",
"/",
"0.3956",
"time_record_us",
"=",
"(",
"time_tot_us",
"+",
"offset_us",
")",
"image_number",
"=",
"(",
"time_record_us",
"-",
"t_start_us",
")",
"/",
"time_resolution_us",
"return",
"image_number"
] | convert energy (eV) to image numbers (#)
Parameters:
===========
numpy array of energy in eV
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
image numbers: array of image number | [
"convert",
"energy",
"(",
"eV",
")",
"to",
"image",
"numbers",
"(",
"#",
")"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L767-L784 |
Numigi/gitoo | src/core.py | temp_repo | def temp_repo(url, branch, commit=''):
""" Clone a git repository inside a temporary folder, yield the folder then delete the folder.
:param string url: url of the repo to clone.
:param string branch: name of the branch to checkout to.
:param string commit: Optional commit rev to checkout to. If mentioned, that take over the branch
:return: yield the path to the temporary folder
:rtype: string
"""
tmp_folder = tempfile.mkdtemp()
git.Repo.clone_from(
url, tmp_folder, branch=branch
)
if commit:
git_cmd = git.Git(tmp_folder)
git_cmd.checkout(commit)
yield tmp_folder
shutil.rmtree(tmp_folder) | python | def temp_repo(url, branch, commit=''):
""" Clone a git repository inside a temporary folder, yield the folder then delete the folder.
:param string url: url of the repo to clone.
:param string branch: name of the branch to checkout to.
:param string commit: Optional commit rev to checkout to. If mentioned, that take over the branch
:return: yield the path to the temporary folder
:rtype: string
"""
tmp_folder = tempfile.mkdtemp()
git.Repo.clone_from(
url, tmp_folder, branch=branch
)
if commit:
git_cmd = git.Git(tmp_folder)
git_cmd.checkout(commit)
yield tmp_folder
shutil.rmtree(tmp_folder) | [
"def",
"temp_repo",
"(",
"url",
",",
"branch",
",",
"commit",
"=",
"''",
")",
":",
"tmp_folder",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"git",
".",
"Repo",
".",
"clone_from",
"(",
"url",
",",
"tmp_folder",
",",
"branch",
"=",
"branch",
")",
"if",
"commit",
":",
"git_cmd",
"=",
"git",
".",
"Git",
"(",
"tmp_folder",
")",
"git_cmd",
".",
"checkout",
"(",
"commit",
")",
"yield",
"tmp_folder",
"shutil",
".",
"rmtree",
"(",
"tmp_folder",
")"
] | Clone a git repository inside a temporary folder, yield the folder then delete the folder.
:param string url: url of the repo to clone.
:param string branch: name of the branch to checkout to.
:param string commit: Optional commit rev to checkout to. If mentioned, that take over the branch
:return: yield the path to the temporary folder
:rtype: string | [
"Clone",
"a",
"git",
"repository",
"inside",
"a",
"temporary",
"folder",
"yield",
"the",
"folder",
"then",
"delete",
"the",
"folder",
"."
] | train | https://github.com/Numigi/gitoo/blob/0921f5fb8a948021760bb0373a40f9fbe8a4a2e5/src/core.py#L18-L35 |
Numigi/gitoo | src/core.py | force_move | def force_move(source, destination):
""" Force the move of the source inside the destination even if the destination has already a folder with the
name inside. In the case, the folder will be replaced.
:param string source: path of the source to move.
:param string destination: path of the folder to move the source to.
"""
if not os.path.exists(destination):
raise RuntimeError(
'The code could not be moved to {destination} '
'because the folder does not exist'.format(destination=destination))
destination_folder = os.path.join(destination, os.path.split(source)[-1])
if os.path.exists(destination_folder):
shutil.rmtree(destination_folder)
shutil.move(source, destination) | python | def force_move(source, destination):
""" Force the move of the source inside the destination even if the destination has already a folder with the
name inside. In the case, the folder will be replaced.
:param string source: path of the source to move.
:param string destination: path of the folder to move the source to.
"""
if not os.path.exists(destination):
raise RuntimeError(
'The code could not be moved to {destination} '
'because the folder does not exist'.format(destination=destination))
destination_folder = os.path.join(destination, os.path.split(source)[-1])
if os.path.exists(destination_folder):
shutil.rmtree(destination_folder)
shutil.move(source, destination) | [
"def",
"force_move",
"(",
"source",
",",
"destination",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"destination",
")",
":",
"raise",
"RuntimeError",
"(",
"'The code could not be moved to {destination} '",
"'because the folder does not exist'",
".",
"format",
"(",
"destination",
"=",
"destination",
")",
")",
"destination_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination",
",",
"os",
".",
"path",
".",
"split",
"(",
"source",
")",
"[",
"-",
"1",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"destination_folder",
")",
":",
"shutil",
".",
"rmtree",
"(",
"destination_folder",
")",
"shutil",
".",
"move",
"(",
"source",
",",
"destination",
")"
] | Force the move of the source inside the destination even if the destination has already a folder with the
name inside. In the case, the folder will be replaced.
:param string source: path of the source to move.
:param string destination: path of the folder to move the source to. | [
"Force",
"the",
"move",
"of",
"the",
"source",
"inside",
"the",
"destination",
"even",
"if",
"the",
"destination",
"has",
"already",
"a",
"folder",
"with",
"the",
"name",
"inside",
".",
"In",
"the",
"case",
"the",
"folder",
"will",
"be",
"replaced",
"."
] | train | https://github.com/Numigi/gitoo/blob/0921f5fb8a948021760bb0373a40f9fbe8a4a2e5/src/core.py#L38-L54 |
Numigi/gitoo | src/core.py | _run_command_inside_folder | def _run_command_inside_folder(command, folder):
"""Run a command inside the given folder.
:param string command: the command to execute.
:param string folder: the folder where to execute the command.
:return: the return code of the process.
:rtype: Tuple[int, str]
"""
logger.debug("command: %s", command)
# avoid usage of shell = True
# see https://docs.openstack.org/bandit/latest/plugins/subprocess_popen_with_shell_equals_true.html
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, cwd=folder)
stream_data = process.communicate()[0]
logger.debug("%s stdout: %s (RC %s)", command, stream_data, process.returncode)
return process.returncode, stream_data | python | def _run_command_inside_folder(command, folder):
"""Run a command inside the given folder.
:param string command: the command to execute.
:param string folder: the folder where to execute the command.
:return: the return code of the process.
:rtype: Tuple[int, str]
"""
logger.debug("command: %s", command)
# avoid usage of shell = True
# see https://docs.openstack.org/bandit/latest/plugins/subprocess_popen_with_shell_equals_true.html
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, cwd=folder)
stream_data = process.communicate()[0]
logger.debug("%s stdout: %s (RC %s)", command, stream_data, process.returncode)
return process.returncode, stream_data | [
"def",
"_run_command_inside_folder",
"(",
"command",
",",
"folder",
")",
":",
"logger",
".",
"debug",
"(",
"\"command: %s\"",
",",
"command",
")",
"# avoid usage of shell = True",
"# see https://docs.openstack.org/bandit/latest/plugins/subprocess_popen_with_shell_equals_true.html",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
".",
"split",
"(",
")",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"cwd",
"=",
"folder",
")",
"stream_data",
"=",
"process",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
"logger",
".",
"debug",
"(",
"\"%s stdout: %s (RC %s)\"",
",",
"command",
",",
"stream_data",
",",
"process",
".",
"returncode",
")",
"return",
"process",
".",
"returncode",
",",
"stream_data"
] | Run a command inside the given folder.
:param string command: the command to execute.
:param string folder: the folder where to execute the command.
:return: the return code of the process.
:rtype: Tuple[int, str] | [
"Run",
"a",
"command",
"inside",
"the",
"given",
"folder",
"."
] | train | https://github.com/Numigi/gitoo/blob/0921f5fb8a948021760bb0373a40f9fbe8a4a2e5/src/core.py#L163-L177 |
Numigi/gitoo | src/core.py | parse_url | def parse_url(url):
""" Parse the given url and update it with environment value if required.
:param basestring url:
:rtype: basestring
:raise: KeyError if environment variable is needed but not found.
"""
# the url has to be a unicode by pystache's design, but the unicode concept has been rewamped in py3
# we use a try except to make the code compatible with py2 and py3
try:
url = unicode(url)
except NameError:
url = url
parsed = pystache.parse(url)
# pylint: disable=protected-access
variables = (element.key for element in parsed._parse_tree if isinstance(element, _EscapeNode))
return pystache.render(url, {variable: os.environ[variable] for variable in variables}) | python | def parse_url(url):
""" Parse the given url and update it with environment value if required.
:param basestring url:
:rtype: basestring
:raise: KeyError if environment variable is needed but not found.
"""
# the url has to be a unicode by pystache's design, but the unicode concept has been rewamped in py3
# we use a try except to make the code compatible with py2 and py3
try:
url = unicode(url)
except NameError:
url = url
parsed = pystache.parse(url)
# pylint: disable=protected-access
variables = (element.key for element in parsed._parse_tree if isinstance(element, _EscapeNode))
return pystache.render(url, {variable: os.environ[variable] for variable in variables}) | [
"def",
"parse_url",
"(",
"url",
")",
":",
"# the url has to be a unicode by pystache's design, but the unicode concept has been rewamped in py3",
"# we use a try except to make the code compatible with py2 and py3",
"try",
":",
"url",
"=",
"unicode",
"(",
"url",
")",
"except",
"NameError",
":",
"url",
"=",
"url",
"parsed",
"=",
"pystache",
".",
"parse",
"(",
"url",
")",
"# pylint: disable=protected-access",
"variables",
"=",
"(",
"element",
".",
"key",
"for",
"element",
"in",
"parsed",
".",
"_parse_tree",
"if",
"isinstance",
"(",
"element",
",",
"_EscapeNode",
")",
")",
"return",
"pystache",
".",
"render",
"(",
"url",
",",
"{",
"variable",
":",
"os",
".",
"environ",
"[",
"variable",
"]",
"for",
"variable",
"in",
"variables",
"}",
")"
] | Parse the given url and update it with environment value if required.
:param basestring url:
:rtype: basestring
:raise: KeyError if environment variable is needed but not found. | [
"Parse",
"the",
"given",
"url",
"and",
"update",
"it",
"with",
"environment",
"value",
"if",
"required",
"."
] | train | https://github.com/Numigi/gitoo/blob/0921f5fb8a948021760bb0373a40f9fbe8a4a2e5/src/core.py#L242-L259 |
Numigi/gitoo | src/core.py | Addon.install | def install(self, destination):
""" Install a third party odoo add-on
:param string destination: the folder where the add-on should end up at.
"""
logger.info(
"Installing %s@%s to %s",
self.repo, self.commit if self.commit else self.branch, destination
)
with temp_repo(self.repo, self.branch, self.commit) as tmp:
self._apply_patches(tmp)
self._move_modules(tmp, destination) | python | def install(self, destination):
""" Install a third party odoo add-on
:param string destination: the folder where the add-on should end up at.
"""
logger.info(
"Installing %s@%s to %s",
self.repo, self.commit if self.commit else self.branch, destination
)
with temp_repo(self.repo, self.branch, self.commit) as tmp:
self._apply_patches(tmp)
self._move_modules(tmp, destination) | [
"def",
"install",
"(",
"self",
",",
"destination",
")",
":",
"logger",
".",
"info",
"(",
"\"Installing %s@%s to %s\"",
",",
"self",
".",
"repo",
",",
"self",
".",
"commit",
"if",
"self",
".",
"commit",
"else",
"self",
".",
"branch",
",",
"destination",
")",
"with",
"temp_repo",
"(",
"self",
".",
"repo",
",",
"self",
".",
"branch",
",",
"self",
".",
"commit",
")",
"as",
"tmp",
":",
"self",
".",
"_apply_patches",
"(",
"tmp",
")",
"self",
".",
"_move_modules",
"(",
"tmp",
",",
"destination",
")"
] | Install a third party odoo add-on
:param string destination: the folder where the add-on should end up at. | [
"Install",
"a",
"third",
"party",
"odoo",
"add",
"-",
"on"
] | train | https://github.com/Numigi/gitoo/blob/0921f5fb8a948021760bb0373a40f9fbe8a4a2e5/src/core.py#L82-L93 |
Numigi/gitoo | src/core.py | Addon._move_modules | def _move_modules(self, temp_repo, destination):
"""Move modules froom the temp directory to the destination.
:param string temp_repo: the folder containing the code.
:param string destination: the folder where the add-on should end up at.
"""
folders = self._get_module_folders(temp_repo)
for folder in folders:
force_move(folder, destination) | python | def _move_modules(self, temp_repo, destination):
"""Move modules froom the temp directory to the destination.
:param string temp_repo: the folder containing the code.
:param string destination: the folder where the add-on should end up at.
"""
folders = self._get_module_folders(temp_repo)
for folder in folders:
force_move(folder, destination) | [
"def",
"_move_modules",
"(",
"self",
",",
"temp_repo",
",",
"destination",
")",
":",
"folders",
"=",
"self",
".",
"_get_module_folders",
"(",
"temp_repo",
")",
"for",
"folder",
"in",
"folders",
":",
"force_move",
"(",
"folder",
",",
"destination",
")"
] | Move modules froom the temp directory to the destination.
:param string temp_repo: the folder containing the code.
:param string destination: the folder where the add-on should end up at. | [
"Move",
"modules",
"froom",
"the",
"temp",
"directory",
"to",
"the",
"destination",
"."
] | train | https://github.com/Numigi/gitoo/blob/0921f5fb8a948021760bb0373a40f9fbe8a4a2e5/src/core.py#L103-L111 |
Numigi/gitoo | src/core.py | Addon._get_module_folders | def _get_module_folders(self, temp_repo):
"""Get a list of module paths contained in a temp directory.
:param string temp_repo: the folder containing the modules.
"""
paths = (
os.path.join(temp_repo, path) for path in os.listdir(temp_repo)
if self._is_module_included(path)
)
return (path for path in paths if os.path.isdir(path)) | python | def _get_module_folders(self, temp_repo):
"""Get a list of module paths contained in a temp directory.
:param string temp_repo: the folder containing the modules.
"""
paths = (
os.path.join(temp_repo, path) for path in os.listdir(temp_repo)
if self._is_module_included(path)
)
return (path for path in paths if os.path.isdir(path)) | [
"def",
"_get_module_folders",
"(",
"self",
",",
"temp_repo",
")",
":",
"paths",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"temp_repo",
",",
"path",
")",
"for",
"path",
"in",
"os",
".",
"listdir",
"(",
"temp_repo",
")",
"if",
"self",
".",
"_is_module_included",
"(",
"path",
")",
")",
"return",
"(",
"path",
"for",
"path",
"in",
"paths",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
")"
] | Get a list of module paths contained in a temp directory.
:param string temp_repo: the folder containing the modules. | [
"Get",
"a",
"list",
"of",
"module",
"paths",
"contained",
"in",
"a",
"temp",
"directory",
"."
] | train | https://github.com/Numigi/gitoo/blob/0921f5fb8a948021760bb0373a40f9fbe8a4a2e5/src/core.py#L113-L122 |
Numigi/gitoo | src/core.py | Addon._is_module_included | def _is_module_included(self, module):
"""Evaluate if the module must be included in the Odoo addons.
:param string module: the name of the module
:rtype: bool
"""
if module in self.exclude_modules:
return False
if self.include_modules is None:
return True
return module in self.include_modules | python | def _is_module_included(self, module):
"""Evaluate if the module must be included in the Odoo addons.
:param string module: the name of the module
:rtype: bool
"""
if module in self.exclude_modules:
return False
if self.include_modules is None:
return True
return module in self.include_modules | [
"def",
"_is_module_included",
"(",
"self",
",",
"module",
")",
":",
"if",
"module",
"in",
"self",
".",
"exclude_modules",
":",
"return",
"False",
"if",
"self",
".",
"include_modules",
"is",
"None",
":",
"return",
"True",
"return",
"module",
"in",
"self",
".",
"include_modules"
] | Evaluate if the module must be included in the Odoo addons.
:param string module: the name of the module
:rtype: bool | [
"Evaluate",
"if",
"the",
"module",
"must",
"be",
"included",
"in",
"the",
"Odoo",
"addons",
"."
] | train | https://github.com/Numigi/gitoo/blob/0921f5fb8a948021760bb0373a40f9fbe8a4a2e5/src/core.py#L124-L136 |
Numigi/gitoo | src/core.py | Base._move_modules | def _move_modules(self, temp_repo, destination):
"""Move odoo modules from the temp directory to the destination.
This step is different from a standard repository. In the base code
of Odoo, the modules are contained in a addons folder at the root
of the git repository. However, when deploying the application,
those modules are placed inside the folder odoo/addons.
1- Move modules from addons/ to odoo/addons/ (with the base module).
2- Move the whole odoo folder to the destination location.
"""
tmp_addons = os.path.join(temp_repo, 'addons')
tmp_odoo_addons = os.path.join(temp_repo, 'odoo/addons')
folders = self._get_module_folders(tmp_addons)
for folder in folders:
force_move(folder, tmp_odoo_addons)
tmp_odoo = os.path.join(temp_repo, 'odoo')
force_move(tmp_odoo, destination) | python | def _move_modules(self, temp_repo, destination):
"""Move odoo modules from the temp directory to the destination.
This step is different from a standard repository. In the base code
of Odoo, the modules are contained in a addons folder at the root
of the git repository. However, when deploying the application,
those modules are placed inside the folder odoo/addons.
1- Move modules from addons/ to odoo/addons/ (with the base module).
2- Move the whole odoo folder to the destination location.
"""
tmp_addons = os.path.join(temp_repo, 'addons')
tmp_odoo_addons = os.path.join(temp_repo, 'odoo/addons')
folders = self._get_module_folders(tmp_addons)
for folder in folders:
force_move(folder, tmp_odoo_addons)
tmp_odoo = os.path.join(temp_repo, 'odoo')
force_move(tmp_odoo, destination) | [
"def",
"_move_modules",
"(",
"self",
",",
"temp_repo",
",",
"destination",
")",
":",
"tmp_addons",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_repo",
",",
"'addons'",
")",
"tmp_odoo_addons",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_repo",
",",
"'odoo/addons'",
")",
"folders",
"=",
"self",
".",
"_get_module_folders",
"(",
"tmp_addons",
")",
"for",
"folder",
"in",
"folders",
":",
"force_move",
"(",
"folder",
",",
"tmp_odoo_addons",
")",
"tmp_odoo",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_repo",
",",
"'odoo'",
")",
"force_move",
"(",
"tmp_odoo",
",",
"destination",
")"
] | Move odoo modules from the temp directory to the destination.
This step is different from a standard repository. In the base code
of Odoo, the modules are contained in a addons folder at the root
of the git repository. However, when deploying the application,
those modules are placed inside the folder odoo/addons.
1- Move modules from addons/ to odoo/addons/ (with the base module).
2- Move the whole odoo folder to the destination location. | [
"Move",
"odoo",
"modules",
"from",
"the",
"temp",
"directory",
"to",
"the",
"destination",
"."
] | train | https://github.com/Numigi/gitoo/blob/0921f5fb8a948021760bb0373a40f9fbe8a4a2e5/src/core.py#L142-L160 |
Numigi/gitoo | src/core.py | Patch.apply | def apply(self, folder):
""" Merge code from the given repo url to the git repo contained in the given folder.
:param string folder: path of the folder where is the git repo cloned at.
:raise: RuntimeError if the patch could not be applied.
"""
logger.info("Apply Patch %s@%s (commit %s)", self.url, self.branch, self.commit)
remote_name = 'patch'
commands = [
"git remote add {} {}".format(remote_name, self.url),
"git fetch {} {}".format(remote_name, self.branch),
'git merge {} -m "patch"'.format(self.commit),
"git remote remove {}".format(remote_name),
]
for command in commands:
return_code, stream_data = _run_command_inside_folder(command, folder)
if return_code:
msg = "Could not apply patch from {}@{}: {}. Error: {}".format(
self.url, self.branch, command, stream_data)
logger.error(msg)
raise RuntimeError(msg) | python | def apply(self, folder):
""" Merge code from the given repo url to the git repo contained in the given folder.
:param string folder: path of the folder where is the git repo cloned at.
:raise: RuntimeError if the patch could not be applied.
"""
logger.info("Apply Patch %s@%s (commit %s)", self.url, self.branch, self.commit)
remote_name = 'patch'
commands = [
"git remote add {} {}".format(remote_name, self.url),
"git fetch {} {}".format(remote_name, self.branch),
'git merge {} -m "patch"'.format(self.commit),
"git remote remove {}".format(remote_name),
]
for command in commands:
return_code, stream_data = _run_command_inside_folder(command, folder)
if return_code:
msg = "Could not apply patch from {}@{}: {}. Error: {}".format(
self.url, self.branch, command, stream_data)
logger.error(msg)
raise RuntimeError(msg) | [
"def",
"apply",
"(",
"self",
",",
"folder",
")",
":",
"logger",
".",
"info",
"(",
"\"Apply Patch %s@%s (commit %s)\"",
",",
"self",
".",
"url",
",",
"self",
".",
"branch",
",",
"self",
".",
"commit",
")",
"remote_name",
"=",
"'patch'",
"commands",
"=",
"[",
"\"git remote add {} {}\"",
".",
"format",
"(",
"remote_name",
",",
"self",
".",
"url",
")",
",",
"\"git fetch {} {}\"",
".",
"format",
"(",
"remote_name",
",",
"self",
".",
"branch",
")",
",",
"'git merge {} -m \"patch\"'",
".",
"format",
"(",
"self",
".",
"commit",
")",
",",
"\"git remote remove {}\"",
".",
"format",
"(",
"remote_name",
")",
",",
"]",
"for",
"command",
"in",
"commands",
":",
"return_code",
",",
"stream_data",
"=",
"_run_command_inside_folder",
"(",
"command",
",",
"folder",
")",
"if",
"return_code",
":",
"msg",
"=",
"\"Could not apply patch from {}@{}: {}. Error: {}\"",
".",
"format",
"(",
"self",
".",
"url",
",",
"self",
".",
"branch",
",",
"command",
",",
"stream_data",
")",
"logger",
".",
"error",
"(",
"msg",
")",
"raise",
"RuntimeError",
"(",
"msg",
")"
] | Merge code from the given repo url to the git repo contained in the given folder.
:param string folder: path of the folder where is the git repo cloned at.
:raise: RuntimeError if the patch could not be applied. | [
"Merge",
"code",
"from",
"the",
"given",
"repo",
"url",
"to",
"the",
"git",
"repo",
"contained",
"in",
"the",
"given",
"folder",
"."
] | train | https://github.com/Numigi/gitoo/blob/0921f5fb8a948021760bb0373a40f9fbe8a4a2e5/src/core.py#L193-L213 |
Numigi/gitoo | src/core.py | FilePatch.apply | def apply(self, folder):
"""Apply a patch from a git patch file.
:param string folder: path of the folder where is the git repo cloned at.
:raise: RuntimeError if the patch could not be applied.
"""
logger.info("Apply Patch File %s", self.file_path)
command = "git apply {}".format(self.file_path)
return_code, stream_data = _run_command_inside_folder(command, folder)
if return_code:
msg = "Could not apply patch file at {}. Error: {}".format(self.file_path, stream_data)
logger.error(msg)
raise RuntimeError(msg) | python | def apply(self, folder):
"""Apply a patch from a git patch file.
:param string folder: path of the folder where is the git repo cloned at.
:raise: RuntimeError if the patch could not be applied.
"""
logger.info("Apply Patch File %s", self.file_path)
command = "git apply {}".format(self.file_path)
return_code, stream_data = _run_command_inside_folder(command, folder)
if return_code:
msg = "Could not apply patch file at {}. Error: {}".format(self.file_path, stream_data)
logger.error(msg)
raise RuntimeError(msg) | [
"def",
"apply",
"(",
"self",
",",
"folder",
")",
":",
"logger",
".",
"info",
"(",
"\"Apply Patch File %s\"",
",",
"self",
".",
"file_path",
")",
"command",
"=",
"\"git apply {}\"",
".",
"format",
"(",
"self",
".",
"file_path",
")",
"return_code",
",",
"stream_data",
"=",
"_run_command_inside_folder",
"(",
"command",
",",
"folder",
")",
"if",
"return_code",
":",
"msg",
"=",
"\"Could not apply patch file at {}. Error: {}\"",
".",
"format",
"(",
"self",
".",
"file_path",
",",
"stream_data",
")",
"logger",
".",
"error",
"(",
"msg",
")",
"raise",
"RuntimeError",
"(",
"msg",
")"
] | Apply a patch from a git patch file.
:param string folder: path of the folder where is the git repo cloned at.
:raise: RuntimeError if the patch could not be applied. | [
"Apply",
"a",
"patch",
"from",
"a",
"git",
"patch",
"file",
"."
] | train | https://github.com/Numigi/gitoo/blob/0921f5fb8a948021760bb0373a40f9fbe8a4a2e5/src/core.py#L226-L239 |
beregond/super_state_machine | super_state_machine/machines.py | StateMachineMetaclass._set_up_context | def _set_up_context(cls):
"""Create context to keep all needed variables in."""
cls.context = AttributeDict()
cls.context.new_meta = {}
cls.context.new_transitions = {}
cls.context.new_methods = {} | python | def _set_up_context(cls):
"""Create context to keep all needed variables in."""
cls.context = AttributeDict()
cls.context.new_meta = {}
cls.context.new_transitions = {}
cls.context.new_methods = {} | [
"def",
"_set_up_context",
"(",
"cls",
")",
":",
"cls",
".",
"context",
"=",
"AttributeDict",
"(",
")",
"cls",
".",
"context",
".",
"new_meta",
"=",
"{",
"}",
"cls",
".",
"context",
".",
"new_transitions",
"=",
"{",
"}",
"cls",
".",
"context",
".",
"new_methods",
"=",
"{",
"}"
] | Create context to keep all needed variables in. | [
"Create",
"context",
"to",
"keep",
"all",
"needed",
"variables",
"in",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L64-L69 |
beregond/super_state_machine | super_state_machine/machines.py | StateMachineMetaclass._check_states_enum | def _check_states_enum(cls):
"""Check if states enum exists and is proper one."""
states_enum_name = cls.context.get_config('states_enum_name')
try:
cls.context['states_enum'] = getattr(
cls.context.new_class, states_enum_name)
except AttributeError:
raise ValueError('No states enum given!')
proper = True
try:
if not issubclass(cls.context.states_enum, Enum):
proper = False
except TypeError:
proper = False
if not proper:
raise ValueError(
'Please provide enum instance to define available states.') | python | def _check_states_enum(cls):
"""Check if states enum exists and is proper one."""
states_enum_name = cls.context.get_config('states_enum_name')
try:
cls.context['states_enum'] = getattr(
cls.context.new_class, states_enum_name)
except AttributeError:
raise ValueError('No states enum given!')
proper = True
try:
if not issubclass(cls.context.states_enum, Enum):
proper = False
except TypeError:
proper = False
if not proper:
raise ValueError(
'Please provide enum instance to define available states.') | [
"def",
"_check_states_enum",
"(",
"cls",
")",
":",
"states_enum_name",
"=",
"cls",
".",
"context",
".",
"get_config",
"(",
"'states_enum_name'",
")",
"try",
":",
"cls",
".",
"context",
"[",
"'states_enum'",
"]",
"=",
"getattr",
"(",
"cls",
".",
"context",
".",
"new_class",
",",
"states_enum_name",
")",
"except",
"AttributeError",
":",
"raise",
"ValueError",
"(",
"'No states enum given!'",
")",
"proper",
"=",
"True",
"try",
":",
"if",
"not",
"issubclass",
"(",
"cls",
".",
"context",
".",
"states_enum",
",",
"Enum",
")",
":",
"proper",
"=",
"False",
"except",
"TypeError",
":",
"proper",
"=",
"False",
"if",
"not",
"proper",
":",
"raise",
"ValueError",
"(",
"'Please provide enum instance to define available states.'",
")"
] | Check if states enum exists and is proper one. | [
"Check",
"if",
"states",
"enum",
"exists",
"and",
"is",
"proper",
"one",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L72-L90 |
beregond/super_state_machine | super_state_machine/machines.py | StateMachineMetaclass._check_if_states_are_strings | def _check_if_states_are_strings(cls):
"""Check if all states are strings."""
for item in list(cls.context.states_enum):
if not isinstance(item.value, six.string_types):
raise ValueError(
'Item {name} is not string. Only strings are allowed.'
.format(name=item.name)
) | python | def _check_if_states_are_strings(cls):
"""Check if all states are strings."""
for item in list(cls.context.states_enum):
if not isinstance(item.value, six.string_types):
raise ValueError(
'Item {name} is not string. Only strings are allowed.'
.format(name=item.name)
) | [
"def",
"_check_if_states_are_strings",
"(",
"cls",
")",
":",
"for",
"item",
"in",
"list",
"(",
"cls",
".",
"context",
".",
"states_enum",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
".",
"value",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"'Item {name} is not string. Only strings are allowed.'",
".",
"format",
"(",
"name",
"=",
"item",
".",
"name",
")",
")"
] | Check if all states are strings. | [
"Check",
"if",
"all",
"states",
"are",
"strings",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L93-L100 |
beregond/super_state_machine | super_state_machine/machines.py | StateMachineMetaclass._check_state_value | def _check_state_value(cls):
"""Check initial state value - if is proper and translate it.
Initial state is required.
"""
state_value = cls.context.get_config('initial_state', None)
state_value = state_value or getattr(
cls.context.new_class, cls.context.state_name, None
)
if not state_value:
raise ValueError(
"Empty state is disallowed, yet no initial state is given!"
)
state_value = (
cls.context
.new_meta['translator']
.translate(state_value)
)
cls.context.state_value = state_value | python | def _check_state_value(cls):
"""Check initial state value - if is proper and translate it.
Initial state is required.
"""
state_value = cls.context.get_config('initial_state', None)
state_value = state_value or getattr(
cls.context.new_class, cls.context.state_name, None
)
if not state_value:
raise ValueError(
"Empty state is disallowed, yet no initial state is given!"
)
state_value = (
cls.context
.new_meta['translator']
.translate(state_value)
)
cls.context.state_value = state_value | [
"def",
"_check_state_value",
"(",
"cls",
")",
":",
"state_value",
"=",
"cls",
".",
"context",
".",
"get_config",
"(",
"'initial_state'",
",",
"None",
")",
"state_value",
"=",
"state_value",
"or",
"getattr",
"(",
"cls",
".",
"context",
".",
"new_class",
",",
"cls",
".",
"context",
".",
"state_name",
",",
"None",
")",
"if",
"not",
"state_value",
":",
"raise",
"ValueError",
"(",
"\"Empty state is disallowed, yet no initial state is given!\"",
")",
"state_value",
"=",
"(",
"cls",
".",
"context",
".",
"new_meta",
"[",
"'translator'",
"]",
".",
"translate",
"(",
"state_value",
")",
")",
"cls",
".",
"context",
".",
"state_value",
"=",
"state_value"
] | Check initial state value - if is proper and translate it.
Initial state is required. | [
"Check",
"initial",
"state",
"value",
"-",
"if",
"is",
"proper",
"and",
"translate",
"it",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L103-L122 |
beregond/super_state_machine | super_state_machine/machines.py | StateMachineMetaclass._add_standard_attributes | def _add_standard_attributes(cls):
"""Add attributes common to all state machines.
These are methods for setting and checking state etc.
"""
setattr(
cls.context.new_class,
cls.context.new_meta['state_attribute_name'],
cls.context.state_value)
setattr(
cls.context.new_class,
cls.context.state_name,
utils.state_property)
setattr(cls.context.new_class, 'is_', utils.is_)
setattr(cls.context.new_class, 'can_be_', utils.can_be_)
setattr(cls.context.new_class, 'set_', utils.set_) | python | def _add_standard_attributes(cls):
"""Add attributes common to all state machines.
These are methods for setting and checking state etc.
"""
setattr(
cls.context.new_class,
cls.context.new_meta['state_attribute_name'],
cls.context.state_value)
setattr(
cls.context.new_class,
cls.context.state_name,
utils.state_property)
setattr(cls.context.new_class, 'is_', utils.is_)
setattr(cls.context.new_class, 'can_be_', utils.can_be_)
setattr(cls.context.new_class, 'set_', utils.set_) | [
"def",
"_add_standard_attributes",
"(",
"cls",
")",
":",
"setattr",
"(",
"cls",
".",
"context",
".",
"new_class",
",",
"cls",
".",
"context",
".",
"new_meta",
"[",
"'state_attribute_name'",
"]",
",",
"cls",
".",
"context",
".",
"state_value",
")",
"setattr",
"(",
"cls",
".",
"context",
".",
"new_class",
",",
"cls",
".",
"context",
".",
"state_name",
",",
"utils",
".",
"state_property",
")",
"setattr",
"(",
"cls",
".",
"context",
".",
"new_class",
",",
"'is_'",
",",
"utils",
".",
"is_",
")",
"setattr",
"(",
"cls",
".",
"context",
".",
"new_class",
",",
"'can_be_'",
",",
"utils",
".",
"can_be_",
")",
"setattr",
"(",
"cls",
".",
"context",
".",
"new_class",
",",
"'set_'",
",",
"utils",
".",
"set_",
")"
] | Add attributes common to all state machines.
These are methods for setting and checking state etc. | [
"Add",
"attributes",
"common",
"to",
"all",
"state",
"machines",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L125-L142 |
beregond/super_state_machine | super_state_machine/machines.py | StateMachineMetaclass._generate_standard_transitions | def _generate_standard_transitions(cls):
"""Generate methods used for transitions."""
allowed_transitions = cls.context.get_config('transitions', {})
for key, transitions in allowed_transitions.items():
key = cls.context.new_meta['translator'].translate(key)
new_transitions = set()
for trans in transitions:
if not isinstance(trans, Enum):
trans = cls.context.new_meta['translator'].translate(trans)
new_transitions.add(trans)
cls.context.new_transitions[key] = new_transitions
for state in cls.context.states_enum:
if state not in cls.context.new_transitions:
cls.context.new_transitions[state] = set() | python | def _generate_standard_transitions(cls):
"""Generate methods used for transitions."""
allowed_transitions = cls.context.get_config('transitions', {})
for key, transitions in allowed_transitions.items():
key = cls.context.new_meta['translator'].translate(key)
new_transitions = set()
for trans in transitions:
if not isinstance(trans, Enum):
trans = cls.context.new_meta['translator'].translate(trans)
new_transitions.add(trans)
cls.context.new_transitions[key] = new_transitions
for state in cls.context.states_enum:
if state not in cls.context.new_transitions:
cls.context.new_transitions[state] = set() | [
"def",
"_generate_standard_transitions",
"(",
"cls",
")",
":",
"allowed_transitions",
"=",
"cls",
".",
"context",
".",
"get_config",
"(",
"'transitions'",
",",
"{",
"}",
")",
"for",
"key",
",",
"transitions",
"in",
"allowed_transitions",
".",
"items",
"(",
")",
":",
"key",
"=",
"cls",
".",
"context",
".",
"new_meta",
"[",
"'translator'",
"]",
".",
"translate",
"(",
"key",
")",
"new_transitions",
"=",
"set",
"(",
")",
"for",
"trans",
"in",
"transitions",
":",
"if",
"not",
"isinstance",
"(",
"trans",
",",
"Enum",
")",
":",
"trans",
"=",
"cls",
".",
"context",
".",
"new_meta",
"[",
"'translator'",
"]",
".",
"translate",
"(",
"trans",
")",
"new_transitions",
".",
"add",
"(",
"trans",
")",
"cls",
".",
"context",
".",
"new_transitions",
"[",
"key",
"]",
"=",
"new_transitions",
"for",
"state",
"in",
"cls",
".",
"context",
".",
"states_enum",
":",
"if",
"state",
"not",
"in",
"cls",
".",
"context",
".",
"new_transitions",
":",
"cls",
".",
"context",
".",
"new_transitions",
"[",
"state",
"]",
"=",
"set",
"(",
")"
] | Generate methods used for transitions. | [
"Generate",
"methods",
"used",
"for",
"transitions",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L145-L161 |
beregond/super_state_machine | super_state_machine/machines.py | StateMachineMetaclass._generate_standard_methods | def _generate_standard_methods(cls):
"""Generate standard setters, getters and checkers."""
for state in cls.context.states_enum:
getter_name = 'is_{name}'.format(name=state.value)
cls.context.new_methods[getter_name] = utils.generate_getter(state)
setter_name = 'set_{name}'.format(name=state.value)
cls.context.new_methods[setter_name] = utils.generate_setter(state)
checker_name = 'can_be_{name}'.format(name=state.value)
checker = utils.generate_checker(state)
cls.context.new_methods[checker_name] = checker
cls.context.new_methods['actual_state'] = utils.actual_state
cls.context.new_methods['as_enum'] = utils.as_enum
cls.context.new_methods['force_set'] = utils.force_set | python | def _generate_standard_methods(cls):
"""Generate standard setters, getters and checkers."""
for state in cls.context.states_enum:
getter_name = 'is_{name}'.format(name=state.value)
cls.context.new_methods[getter_name] = utils.generate_getter(state)
setter_name = 'set_{name}'.format(name=state.value)
cls.context.new_methods[setter_name] = utils.generate_setter(state)
checker_name = 'can_be_{name}'.format(name=state.value)
checker = utils.generate_checker(state)
cls.context.new_methods[checker_name] = checker
cls.context.new_methods['actual_state'] = utils.actual_state
cls.context.new_methods['as_enum'] = utils.as_enum
cls.context.new_methods['force_set'] = utils.force_set | [
"def",
"_generate_standard_methods",
"(",
"cls",
")",
":",
"for",
"state",
"in",
"cls",
".",
"context",
".",
"states_enum",
":",
"getter_name",
"=",
"'is_{name}'",
".",
"format",
"(",
"name",
"=",
"state",
".",
"value",
")",
"cls",
".",
"context",
".",
"new_methods",
"[",
"getter_name",
"]",
"=",
"utils",
".",
"generate_getter",
"(",
"state",
")",
"setter_name",
"=",
"'set_{name}'",
".",
"format",
"(",
"name",
"=",
"state",
".",
"value",
")",
"cls",
".",
"context",
".",
"new_methods",
"[",
"setter_name",
"]",
"=",
"utils",
".",
"generate_setter",
"(",
"state",
")",
"checker_name",
"=",
"'can_be_{name}'",
".",
"format",
"(",
"name",
"=",
"state",
".",
"value",
")",
"checker",
"=",
"utils",
".",
"generate_checker",
"(",
"state",
")",
"cls",
".",
"context",
".",
"new_methods",
"[",
"checker_name",
"]",
"=",
"checker",
"cls",
".",
"context",
".",
"new_methods",
"[",
"'actual_state'",
"]",
"=",
"utils",
".",
"actual_state",
"cls",
".",
"context",
".",
"new_methods",
"[",
"'as_enum'",
"]",
"=",
"utils",
".",
"as_enum",
"cls",
".",
"context",
".",
"new_methods",
"[",
"'force_set'",
"]",
"=",
"utils",
".",
"force_set"
] | Generate standard setters, getters and checkers. | [
"Generate",
"standard",
"setters",
"getters",
"and",
"checkers",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L164-L179 |
beregond/super_state_machine | super_state_machine/machines.py | StateMachineMetaclass._add_new_methods | def _add_new_methods(cls):
"""Add all generated methods to result class."""
for name, method in cls.context.new_methods.items():
if hasattr(cls.context.new_class, name):
raise ValueError(
"Name collision in state machine class - '{name}'."
.format(name)
)
setattr(cls.context.new_class, name, method) | python | def _add_new_methods(cls):
"""Add all generated methods to result class."""
for name, method in cls.context.new_methods.items():
if hasattr(cls.context.new_class, name):
raise ValueError(
"Name collision in state machine class - '{name}'."
.format(name)
)
setattr(cls.context.new_class, name, method) | [
"def",
"_add_new_methods",
"(",
"cls",
")",
":",
"for",
"name",
",",
"method",
"in",
"cls",
".",
"context",
".",
"new_methods",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"cls",
".",
"context",
".",
"new_class",
",",
"name",
")",
":",
"raise",
"ValueError",
"(",
"\"Name collision in state machine class - '{name}'.\"",
".",
"format",
"(",
"name",
")",
")",
"setattr",
"(",
"cls",
".",
"context",
".",
"new_class",
",",
"name",
",",
"method",
")"
] | Add all generated methods to result class. | [
"Add",
"all",
"generated",
"methods",
"to",
"result",
"class",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L235-L244 |
beregond/super_state_machine | super_state_machine/machines.py | StateMachineMetaclass._set_complete_option | def _set_complete_option(cls):
"""Check and set complete option."""
get_config = cls.context.get_config
complete = get_config('complete', None)
if complete is None:
conditions = [
get_config('transitions', False),
get_config('named_transitions', False),
]
complete = not any(conditions)
cls.context.new_meta['complete'] = complete | python | def _set_complete_option(cls):
"""Check and set complete option."""
get_config = cls.context.get_config
complete = get_config('complete', None)
if complete is None:
conditions = [
get_config('transitions', False),
get_config('named_transitions', False),
]
complete = not any(conditions)
cls.context.new_meta['complete'] = complete | [
"def",
"_set_complete_option",
"(",
"cls",
")",
":",
"get_config",
"=",
"cls",
".",
"context",
".",
"get_config",
"complete",
"=",
"get_config",
"(",
"'complete'",
",",
"None",
")",
"if",
"complete",
"is",
"None",
":",
"conditions",
"=",
"[",
"get_config",
"(",
"'transitions'",
",",
"False",
")",
",",
"get_config",
"(",
"'named_transitions'",
",",
"False",
")",
",",
"]",
"complete",
"=",
"not",
"any",
"(",
"conditions",
")",
"cls",
".",
"context",
".",
"new_meta",
"[",
"'complete'",
"]",
"=",
"complete"
] | Check and set complete option. | [
"Check",
"and",
"set",
"complete",
"option",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L247-L258 |
BlueBrain/nat | nat/utils.py | data_directory | def data_directory():
"""Return the absolute path to the directory containing the package data."""
package_directory = os.path.abspath(os.path.dirname(__file__))
return os.path.join(package_directory, "data") | python | def data_directory():
"""Return the absolute path to the directory containing the package data."""
package_directory = os.path.abspath(os.path.dirname(__file__))
return os.path.join(package_directory, "data") | [
"def",
"data_directory",
"(",
")",
":",
"package_directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"package_directory",
",",
"\"data\"",
")"
] | Return the absolute path to the directory containing the package data. | [
"Return",
"the",
"absolute",
"path",
"to",
"the",
"directory",
"containing",
"the",
"package",
"data",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/utils.py#L16-L19 |
ttinies/sc2gameMapRepo | sc2maptool/functions.py | selectMap | def selectMap(name=None, excludeName=False, closestMatch=True, **tags):
"""select a map by name and/or critiera"""
matches = filterMapAttrs(**tags)
if not matches: raise c.InvalidMapSelection("could not find any matching maps given criteria: %s"%tags)
if name: # if name is specified, consider only the best-matching names only
matches = filterMapNames(name, excludeRegex=excludeName, closestMatch=closestMatch, records=matches)
try:
if closestMatch: return random.choice(matches) # pick any map at random that matches all criteria
elif matches: return matches
except IndexError: pass # matches is empty still
raise c.InvalidMapSelection("requested map '%s', but could not locate "\
"it within %s or its subdirectories. Submit the map to https://"\
"github.com/ttinies/sc2gameMapRepo/tree/master/sc2maptool/maps"%(
name, c.PATH_MAP_INSTALL)) | python | def selectMap(name=None, excludeName=False, closestMatch=True, **tags):
"""select a map by name and/or critiera"""
matches = filterMapAttrs(**tags)
if not matches: raise c.InvalidMapSelection("could not find any matching maps given criteria: %s"%tags)
if name: # if name is specified, consider only the best-matching names only
matches = filterMapNames(name, excludeRegex=excludeName, closestMatch=closestMatch, records=matches)
try:
if closestMatch: return random.choice(matches) # pick any map at random that matches all criteria
elif matches: return matches
except IndexError: pass # matches is empty still
raise c.InvalidMapSelection("requested map '%s', but could not locate "\
"it within %s or its subdirectories. Submit the map to https://"\
"github.com/ttinies/sc2gameMapRepo/tree/master/sc2maptool/maps"%(
name, c.PATH_MAP_INSTALL)) | [
"def",
"selectMap",
"(",
"name",
"=",
"None",
",",
"excludeName",
"=",
"False",
",",
"closestMatch",
"=",
"True",
",",
"*",
"*",
"tags",
")",
":",
"matches",
"=",
"filterMapAttrs",
"(",
"*",
"*",
"tags",
")",
"if",
"not",
"matches",
":",
"raise",
"c",
".",
"InvalidMapSelection",
"(",
"\"could not find any matching maps given criteria: %s\"",
"%",
"tags",
")",
"if",
"name",
":",
"# if name is specified, consider only the best-matching names only",
"matches",
"=",
"filterMapNames",
"(",
"name",
",",
"excludeRegex",
"=",
"excludeName",
",",
"closestMatch",
"=",
"closestMatch",
",",
"records",
"=",
"matches",
")",
"try",
":",
"if",
"closestMatch",
":",
"return",
"random",
".",
"choice",
"(",
"matches",
")",
"# pick any map at random that matches all criteria",
"elif",
"matches",
":",
"return",
"matches",
"except",
"IndexError",
":",
"pass",
"# matches is empty still",
"raise",
"c",
".",
"InvalidMapSelection",
"(",
"\"requested map '%s', but could not locate \"",
"\"it within %s or its subdirectories. Submit the map to https://\"",
"\"github.com/ttinies/sc2gameMapRepo/tree/master/sc2maptool/maps\"",
"%",
"(",
"name",
",",
"c",
".",
"PATH_MAP_INSTALL",
")",
")"
] | select a map by name and/or critiera | [
"select",
"a",
"map",
"by",
"name",
"and",
"/",
"or",
"critiera"
] | train | https://github.com/ttinies/sc2gameMapRepo/blob/3a215067fae8f86f6a3ffe37272fbd7a5461cfab/sc2maptool/functions.py#L12-L25 |
ttinies/sc2gameMapRepo | sc2maptool/functions.py | filterMapAttrs | def filterMapAttrs(records=getIndex(), **tags):
"""matches available maps if their attributes match as specified"""
if len(tags) == 0: return records # otherwise if unspecified, all given records match
ret = []
for record in records: # attempt to match attributes
if matchRecordAttrs(record, tags):
ret.append(record)
return ret | python | def filterMapAttrs(records=getIndex(), **tags):
"""matches available maps if their attributes match as specified"""
if len(tags) == 0: return records # otherwise if unspecified, all given records match
ret = []
for record in records: # attempt to match attributes
if matchRecordAttrs(record, tags):
ret.append(record)
return ret | [
"def",
"filterMapAttrs",
"(",
"records",
"=",
"getIndex",
"(",
")",
",",
"*",
"*",
"tags",
")",
":",
"if",
"len",
"(",
"tags",
")",
"==",
"0",
":",
"return",
"records",
"# otherwise if unspecified, all given records match",
"ret",
"=",
"[",
"]",
"for",
"record",
"in",
"records",
":",
"# attempt to match attributes",
"if",
"matchRecordAttrs",
"(",
"record",
",",
"tags",
")",
":",
"ret",
".",
"append",
"(",
"record",
")",
"return",
"ret"
] | matches available maps if their attributes match as specified | [
"matches",
"available",
"maps",
"if",
"their",
"attributes",
"match",
"as",
"specified"
] | train | https://github.com/ttinies/sc2gameMapRepo/blob/3a215067fae8f86f6a3ffe37272fbd7a5461cfab/sc2maptool/functions.py#L29-L36 |
ttinies/sc2gameMapRepo | sc2maptool/functions.py | matchRecordAttrs | def matchRecordAttrs(mapobj, attrs):
"""attempt to match given attributes against a single map object's attributes"""
for k,v in iteritems(attrs):
try: val = getattr(mapobj, k)
except AttributeError: # k isn't an attr of record
if bool(v): return False # if k doesn't exist in mapobj but was required, no match
else: continue # otherwise ignore attributes that aren't defined for the given map record
if val != v: return False # if any criteria matches, it's considered a match
return True | python | def matchRecordAttrs(mapobj, attrs):
"""attempt to match given attributes against a single map object's attributes"""
for k,v in iteritems(attrs):
try: val = getattr(mapobj, k)
except AttributeError: # k isn't an attr of record
if bool(v): return False # if k doesn't exist in mapobj but was required, no match
else: continue # otherwise ignore attributes that aren't defined for the given map record
if val != v: return False # if any criteria matches, it's considered a match
return True | [
"def",
"matchRecordAttrs",
"(",
"mapobj",
",",
"attrs",
")",
":",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"attrs",
")",
":",
"try",
":",
"val",
"=",
"getattr",
"(",
"mapobj",
",",
"k",
")",
"except",
"AttributeError",
":",
"# k isn't an attr of record",
"if",
"bool",
"(",
"v",
")",
":",
"return",
"False",
"# if k doesn't exist in mapobj but was required, no match",
"else",
":",
"continue",
"# otherwise ignore attributes that aren't defined for the given map record",
"if",
"val",
"!=",
"v",
":",
"return",
"False",
"# if any criteria matches, it's considered a match",
"return",
"True"
] | attempt to match given attributes against a single map object's attributes | [
"attempt",
"to",
"match",
"given",
"attributes",
"against",
"a",
"single",
"map",
"object",
"s",
"attributes"
] | train | https://github.com/ttinies/sc2gameMapRepo/blob/3a215067fae8f86f6a3ffe37272fbd7a5461cfab/sc2maptool/functions.py#L40-L48 |
ttinies/sc2gameMapRepo | sc2maptool/functions.py | filterMapNames | def filterMapNames(regexText, records=getIndex(), excludeRegex=False, closestMatch=True):
"""matches each record against regexText according to parameters
NOTE: the code could be written more simply, but this is loop-optimized to
scale better with a large number of map records"""
bestScr = 99999 # a big enough number to not be a valid file system path
regex = re.compile(regexText, flags=re.IGNORECASE)
ret = []
if excludeRegex: # match only records that do NOT contain regex
if regexText and closestMatch: # then maps with fewer characters are better matches
for m in list(records):
if re.search(regex, m.name): continue # map must NOT contain specified phrase
score = len(m.name) # the map with the smallest map name means it has the largets matching character percentage
if score == bestScr:
bestScr = score
ret.append(m)
elif score < bestScr: # new set of best maps
bestScr = score
ret = [m]
else: # all maps that match regex are included
for m in list(records):
if re.search(regex, m.name): continue # map must NOT contain specified phrase
ret.append(m) # any mapname containing regex matches
else: # only match records that contain regex
if regexText and closestMatch: # then maps with fewer characters are better matches
for m in records:
if not re.search(regex, m.name): continue # map must contain specified phrase if excludeRegex==True
score = len(m.name) # the map with the smallest map name means it has the largets matching character percentage
if score == bestScr:
bestScr = score
ret.append(m)
elif score < bestScr: # new group of best maps
bestScr = score
ret = [m]
else: # all maps that match regex are included
for m in records:
if not re.search(regex, m.name): continue # map must contain specified phrase if excludeRegex==True
ret.append(m) # any mapname containing regex matches
return ret | python | def filterMapNames(regexText, records=getIndex(), excludeRegex=False, closestMatch=True):
"""matches each record against regexText according to parameters
NOTE: the code could be written more simply, but this is loop-optimized to
scale better with a large number of map records"""
bestScr = 99999 # a big enough number to not be a valid file system path
regex = re.compile(regexText, flags=re.IGNORECASE)
ret = []
if excludeRegex: # match only records that do NOT contain regex
if regexText and closestMatch: # then maps with fewer characters are better matches
for m in list(records):
if re.search(regex, m.name): continue # map must NOT contain specified phrase
score = len(m.name) # the map with the smallest map name means it has the largets matching character percentage
if score == bestScr:
bestScr = score
ret.append(m)
elif score < bestScr: # new set of best maps
bestScr = score
ret = [m]
else: # all maps that match regex are included
for m in list(records):
if re.search(regex, m.name): continue # map must NOT contain specified phrase
ret.append(m) # any mapname containing regex matches
else: # only match records that contain regex
if regexText and closestMatch: # then maps with fewer characters are better matches
for m in records:
if not re.search(regex, m.name): continue # map must contain specified phrase if excludeRegex==True
score = len(m.name) # the map with the smallest map name means it has the largets matching character percentage
if score == bestScr:
bestScr = score
ret.append(m)
elif score < bestScr: # new group of best maps
bestScr = score
ret = [m]
else: # all maps that match regex are included
for m in records:
if not re.search(regex, m.name): continue # map must contain specified phrase if excludeRegex==True
ret.append(m) # any mapname containing regex matches
return ret | [
"def",
"filterMapNames",
"(",
"regexText",
",",
"records",
"=",
"getIndex",
"(",
")",
",",
"excludeRegex",
"=",
"False",
",",
"closestMatch",
"=",
"True",
")",
":",
"bestScr",
"=",
"99999",
"# a big enough number to not be a valid file system path",
"regex",
"=",
"re",
".",
"compile",
"(",
"regexText",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"ret",
"=",
"[",
"]",
"if",
"excludeRegex",
":",
"# match only records that do NOT contain regex",
"if",
"regexText",
"and",
"closestMatch",
":",
"# then maps with fewer characters are better matches",
"for",
"m",
"in",
"list",
"(",
"records",
")",
":",
"if",
"re",
".",
"search",
"(",
"regex",
",",
"m",
".",
"name",
")",
":",
"continue",
"# map must NOT contain specified phrase",
"score",
"=",
"len",
"(",
"m",
".",
"name",
")",
"# the map with the smallest map name means it has the largets matching character percentage",
"if",
"score",
"==",
"bestScr",
":",
"bestScr",
"=",
"score",
"ret",
".",
"append",
"(",
"m",
")",
"elif",
"score",
"<",
"bestScr",
":",
"# new set of best maps",
"bestScr",
"=",
"score",
"ret",
"=",
"[",
"m",
"]",
"else",
":",
"# all maps that match regex are included",
"for",
"m",
"in",
"list",
"(",
"records",
")",
":",
"if",
"re",
".",
"search",
"(",
"regex",
",",
"m",
".",
"name",
")",
":",
"continue",
"# map must NOT contain specified phrase",
"ret",
".",
"append",
"(",
"m",
")",
"# any mapname containing regex matches",
"else",
":",
"# only match records that contain regex",
"if",
"regexText",
"and",
"closestMatch",
":",
"# then maps with fewer characters are better matches",
"for",
"m",
"in",
"records",
":",
"if",
"not",
"re",
".",
"search",
"(",
"regex",
",",
"m",
".",
"name",
")",
":",
"continue",
"# map must contain specified phrase if excludeRegex==True",
"score",
"=",
"len",
"(",
"m",
".",
"name",
")",
"# the map with the smallest map name means it has the largets matching character percentage",
"if",
"score",
"==",
"bestScr",
":",
"bestScr",
"=",
"score",
"ret",
".",
"append",
"(",
"m",
")",
"elif",
"score",
"<",
"bestScr",
":",
"# new group of best maps",
"bestScr",
"=",
"score",
"ret",
"=",
"[",
"m",
"]",
"else",
":",
"# all maps that match regex are included",
"for",
"m",
"in",
"records",
":",
"if",
"not",
"re",
".",
"search",
"(",
"regex",
",",
"m",
".",
"name",
")",
":",
"continue",
"# map must contain specified phrase if excludeRegex==True",
"ret",
".",
"append",
"(",
"m",
")",
"# any mapname containing regex matches",
"return",
"ret"
] | matches each record against regexText according to parameters
NOTE: the code could be written more simply, but this is loop-optimized to
scale better with a large number of map records | [
"matches",
"each",
"record",
"against",
"regexText",
"according",
"to",
"parameters",
"NOTE",
":",
"the",
"code",
"could",
"be",
"written",
"more",
"simply",
"but",
"this",
"is",
"loop",
"-",
"optimized",
"to",
"scale",
"better",
"with",
"a",
"large",
"number",
"of",
"map",
"records"
] | train | https://github.com/ttinies/sc2gameMapRepo/blob/3a215067fae8f86f6a3ffe37272fbd7a5461cfab/sc2maptool/functions.py#L52-L89 |
rapidpro/expressions | python/temba_expressions/conversions.py | to_boolean | def to_boolean(value, ctx):
"""
Tries conversion of any value to a boolean
"""
if isinstance(value, bool):
return value
elif isinstance(value, int):
return value != 0
elif isinstance(value, Decimal):
return value != Decimal(0)
elif isinstance(value, str):
value = value.lower()
if value == 'true':
return True
elif value == 'false':
return False
elif isinstance(value, datetime.date) or isinstance(value, datetime.time):
return True
raise EvaluationError("Can't convert '%s' to a boolean" % str(value)) | python | def to_boolean(value, ctx):
"""
Tries conversion of any value to a boolean
"""
if isinstance(value, bool):
return value
elif isinstance(value, int):
return value != 0
elif isinstance(value, Decimal):
return value != Decimal(0)
elif isinstance(value, str):
value = value.lower()
if value == 'true':
return True
elif value == 'false':
return False
elif isinstance(value, datetime.date) or isinstance(value, datetime.time):
return True
raise EvaluationError("Can't convert '%s' to a boolean" % str(value)) | [
"def",
"to_boolean",
"(",
"value",
",",
"ctx",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"return",
"value",
"!=",
"0",
"elif",
"isinstance",
"(",
"value",
",",
"Decimal",
")",
":",
"return",
"value",
"!=",
"Decimal",
"(",
"0",
")",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"if",
"value",
"==",
"'true'",
":",
"return",
"True",
"elif",
"value",
"==",
"'false'",
":",
"return",
"False",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"date",
")",
"or",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"time",
")",
":",
"return",
"True",
"raise",
"EvaluationError",
"(",
"\"Can't convert '%s' to a boolean\"",
"%",
"str",
"(",
"value",
")",
")"
] | Tries conversion of any value to a boolean | [
"Tries",
"conversion",
"of",
"any",
"value",
"to",
"a",
"boolean"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L7-L26 |
rapidpro/expressions | python/temba_expressions/conversions.py | to_integer | def to_integer(value, ctx):
"""
Tries conversion of any value to an integer
"""
if isinstance(value, bool):
return 1 if value else 0
elif isinstance(value, int):
return value
elif isinstance(value, Decimal):
try:
val = int(value.to_integral_exact(ROUND_HALF_UP))
if isinstance(val, int):
return val
except ArithmeticError:
pass
elif isinstance(value, str):
try:
return int(value)
except ValueError:
pass
raise EvaluationError("Can't convert '%s' to an integer" % str(value)) | python | def to_integer(value, ctx):
"""
Tries conversion of any value to an integer
"""
if isinstance(value, bool):
return 1 if value else 0
elif isinstance(value, int):
return value
elif isinstance(value, Decimal):
try:
val = int(value.to_integral_exact(ROUND_HALF_UP))
if isinstance(val, int):
return val
except ArithmeticError:
pass
elif isinstance(value, str):
try:
return int(value)
except ValueError:
pass
raise EvaluationError("Can't convert '%s' to an integer" % str(value)) | [
"def",
"to_integer",
"(",
"value",
",",
"ctx",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"1",
"if",
"value",
"else",
"0",
"elif",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"Decimal",
")",
":",
"try",
":",
"val",
"=",
"int",
"(",
"value",
".",
"to_integral_exact",
"(",
"ROUND_HALF_UP",
")",
")",
"if",
"isinstance",
"(",
"val",
",",
"int",
")",
":",
"return",
"val",
"except",
"ArithmeticError",
":",
"pass",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"try",
":",
"return",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"pass",
"raise",
"EvaluationError",
"(",
"\"Can't convert '%s' to an integer\"",
"%",
"str",
"(",
"value",
")",
")"
] | Tries conversion of any value to an integer | [
"Tries",
"conversion",
"of",
"any",
"value",
"to",
"an",
"integer"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L29-L50 |
rapidpro/expressions | python/temba_expressions/conversions.py | to_decimal | def to_decimal(value, ctx):
"""
Tries conversion of any value to a decimal
"""
if isinstance(value, bool):
return Decimal(1) if value else Decimal(0)
elif isinstance(value, int):
return Decimal(value)
elif isinstance(value, Decimal):
return value
elif isinstance(value, str):
try:
return Decimal(value)
except Exception:
pass
raise EvaluationError("Can't convert '%s' to a decimal" % str(value)) | python | def to_decimal(value, ctx):
"""
Tries conversion of any value to a decimal
"""
if isinstance(value, bool):
return Decimal(1) if value else Decimal(0)
elif isinstance(value, int):
return Decimal(value)
elif isinstance(value, Decimal):
return value
elif isinstance(value, str):
try:
return Decimal(value)
except Exception:
pass
raise EvaluationError("Can't convert '%s' to a decimal" % str(value)) | [
"def",
"to_decimal",
"(",
"value",
",",
"ctx",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"Decimal",
"(",
"1",
")",
"if",
"value",
"else",
"Decimal",
"(",
"0",
")",
"elif",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"return",
"Decimal",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"Decimal",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"try",
":",
"return",
"Decimal",
"(",
"value",
")",
"except",
"Exception",
":",
"pass",
"raise",
"EvaluationError",
"(",
"\"Can't convert '%s' to a decimal\"",
"%",
"str",
"(",
"value",
")",
")"
] | Tries conversion of any value to a decimal | [
"Tries",
"conversion",
"of",
"any",
"value",
"to",
"a",
"decimal"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L53-L69 |
rapidpro/expressions | python/temba_expressions/conversions.py | to_string | def to_string(value, ctx):
"""
Tries conversion of any value to a string
"""
if isinstance(value, bool):
return "TRUE" if value else "FALSE"
elif isinstance(value, int):
return str(value)
elif isinstance(value, Decimal):
return format_decimal(value)
elif isinstance(value, str):
return value
elif type(value) == datetime.date:
return value.strftime(ctx.get_date_format(False))
elif isinstance(value, datetime.time):
return value.strftime('%H:%M')
elif isinstance(value, datetime.datetime):
return value.astimezone(ctx.timezone).isoformat()
raise EvaluationError("Can't convert '%s' to a string" % str(value)) | python | def to_string(value, ctx):
"""
Tries conversion of any value to a string
"""
if isinstance(value, bool):
return "TRUE" if value else "FALSE"
elif isinstance(value, int):
return str(value)
elif isinstance(value, Decimal):
return format_decimal(value)
elif isinstance(value, str):
return value
elif type(value) == datetime.date:
return value.strftime(ctx.get_date_format(False))
elif isinstance(value, datetime.time):
return value.strftime('%H:%M')
elif isinstance(value, datetime.datetime):
return value.astimezone(ctx.timezone).isoformat()
raise EvaluationError("Can't convert '%s' to a string" % str(value)) | [
"def",
"to_string",
"(",
"value",
",",
"ctx",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"\"TRUE\"",
"if",
"value",
"else",
"\"FALSE\"",
"elif",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"Decimal",
")",
":",
"return",
"format_decimal",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"value",
"elif",
"type",
"(",
"value",
")",
"==",
"datetime",
".",
"date",
":",
"return",
"value",
".",
"strftime",
"(",
"ctx",
".",
"get_date_format",
"(",
"False",
")",
")",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"time",
")",
":",
"return",
"value",
".",
"strftime",
"(",
"'%H:%M'",
")",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"value",
".",
"astimezone",
"(",
"ctx",
".",
"timezone",
")",
".",
"isoformat",
"(",
")",
"raise",
"EvaluationError",
"(",
"\"Can't convert '%s' to a string\"",
"%",
"str",
"(",
"value",
")",
")"
] | Tries conversion of any value to a string | [
"Tries",
"conversion",
"of",
"any",
"value",
"to",
"a",
"string"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L72-L91 |
rapidpro/expressions | python/temba_expressions/conversions.py | to_date | def to_date(value, ctx):
"""
Tries conversion of any value to a date
"""
if isinstance(value, str):
temporal = ctx.get_date_parser().auto(value)
if temporal is not None:
return to_date(temporal, ctx)
elif type(value) == datetime.date:
return value
elif isinstance(value, datetime.datetime):
return value.date() # discard time
raise EvaluationError("Can't convert '%s' to a date" % str(value)) | python | def to_date(value, ctx):
"""
Tries conversion of any value to a date
"""
if isinstance(value, str):
temporal = ctx.get_date_parser().auto(value)
if temporal is not None:
return to_date(temporal, ctx)
elif type(value) == datetime.date:
return value
elif isinstance(value, datetime.datetime):
return value.date() # discard time
raise EvaluationError("Can't convert '%s' to a date" % str(value)) | [
"def",
"to_date",
"(",
"value",
",",
"ctx",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"temporal",
"=",
"ctx",
".",
"get_date_parser",
"(",
")",
".",
"auto",
"(",
"value",
")",
"if",
"temporal",
"is",
"not",
"None",
":",
"return",
"to_date",
"(",
"temporal",
",",
"ctx",
")",
"elif",
"type",
"(",
"value",
")",
"==",
"datetime",
".",
"date",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"value",
".",
"date",
"(",
")",
"# discard time",
"raise",
"EvaluationError",
"(",
"\"Can't convert '%s' to a date\"",
"%",
"str",
"(",
"value",
")",
")"
] | Tries conversion of any value to a date | [
"Tries",
"conversion",
"of",
"any",
"value",
"to",
"a",
"date"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L94-L107 |
rapidpro/expressions | python/temba_expressions/conversions.py | to_datetime | def to_datetime(value, ctx):
"""
Tries conversion of any value to a datetime
"""
if isinstance(value, str):
temporal = ctx.get_date_parser().auto(value)
if temporal is not None:
return to_datetime(temporal, ctx)
elif type(value) == datetime.date:
return ctx.timezone.localize(datetime.datetime.combine(value, datetime.time(0, 0)))
elif isinstance(value, datetime.datetime):
return value.astimezone(ctx.timezone)
raise EvaluationError("Can't convert '%s' to a datetime" % str(value)) | python | def to_datetime(value, ctx):
"""
Tries conversion of any value to a datetime
"""
if isinstance(value, str):
temporal = ctx.get_date_parser().auto(value)
if temporal is not None:
return to_datetime(temporal, ctx)
elif type(value) == datetime.date:
return ctx.timezone.localize(datetime.datetime.combine(value, datetime.time(0, 0)))
elif isinstance(value, datetime.datetime):
return value.astimezone(ctx.timezone)
raise EvaluationError("Can't convert '%s' to a datetime" % str(value)) | [
"def",
"to_datetime",
"(",
"value",
",",
"ctx",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"temporal",
"=",
"ctx",
".",
"get_date_parser",
"(",
")",
".",
"auto",
"(",
"value",
")",
"if",
"temporal",
"is",
"not",
"None",
":",
"return",
"to_datetime",
"(",
"temporal",
",",
"ctx",
")",
"elif",
"type",
"(",
"value",
")",
"==",
"datetime",
".",
"date",
":",
"return",
"ctx",
".",
"timezone",
".",
"localize",
"(",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"value",
",",
"datetime",
".",
"time",
"(",
"0",
",",
"0",
")",
")",
")",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"value",
".",
"astimezone",
"(",
"ctx",
".",
"timezone",
")",
"raise",
"EvaluationError",
"(",
"\"Can't convert '%s' to a datetime\"",
"%",
"str",
"(",
"value",
")",
")"
] | Tries conversion of any value to a datetime | [
"Tries",
"conversion",
"of",
"any",
"value",
"to",
"a",
"datetime"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L110-L123 |
rapidpro/expressions | python/temba_expressions/conversions.py | to_date_or_datetime | def to_date_or_datetime(value, ctx):
"""
Tries conversion of any value to a date or datetime
"""
if isinstance(value, str):
temporal = ctx.get_date_parser().auto(value)
if temporal is not None:
return temporal
elif type(value) == datetime.date:
return value
elif isinstance(value, datetime.datetime):
return value.astimezone(ctx.timezone)
raise EvaluationError("Can't convert '%s' to a date or datetime" % str(value)) | python | def to_date_or_datetime(value, ctx):
"""
Tries conversion of any value to a date or datetime
"""
if isinstance(value, str):
temporal = ctx.get_date_parser().auto(value)
if temporal is not None:
return temporal
elif type(value) == datetime.date:
return value
elif isinstance(value, datetime.datetime):
return value.astimezone(ctx.timezone)
raise EvaluationError("Can't convert '%s' to a date or datetime" % str(value)) | [
"def",
"to_date_or_datetime",
"(",
"value",
",",
"ctx",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"temporal",
"=",
"ctx",
".",
"get_date_parser",
"(",
")",
".",
"auto",
"(",
"value",
")",
"if",
"temporal",
"is",
"not",
"None",
":",
"return",
"temporal",
"elif",
"type",
"(",
"value",
")",
"==",
"datetime",
".",
"date",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"value",
".",
"astimezone",
"(",
"ctx",
".",
"timezone",
")",
"raise",
"EvaluationError",
"(",
"\"Can't convert '%s' to a date or datetime\"",
"%",
"str",
"(",
"value",
")",
")"
] | Tries conversion of any value to a date or datetime | [
"Tries",
"conversion",
"of",
"any",
"value",
"to",
"a",
"date",
"or",
"datetime"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L126-L139 |
rapidpro/expressions | python/temba_expressions/conversions.py | to_time | def to_time(value, ctx):
"""
Tries conversion of any value to a time
"""
if isinstance(value, str):
time = ctx.get_date_parser().time(value)
if time is not None:
return time
elif isinstance(value, datetime.time):
return value
elif isinstance(value, datetime.datetime):
return value.astimezone(ctx.timezone).time()
raise EvaluationError("Can't convert '%s' to a time" % str(value)) | python | def to_time(value, ctx):
"""
Tries conversion of any value to a time
"""
if isinstance(value, str):
time = ctx.get_date_parser().time(value)
if time is not None:
return time
elif isinstance(value, datetime.time):
return value
elif isinstance(value, datetime.datetime):
return value.astimezone(ctx.timezone).time()
raise EvaluationError("Can't convert '%s' to a time" % str(value)) | [
"def",
"to_time",
"(",
"value",
",",
"ctx",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"time",
"=",
"ctx",
".",
"get_date_parser",
"(",
")",
".",
"time",
"(",
"value",
")",
"if",
"time",
"is",
"not",
"None",
":",
"return",
"time",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"time",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"value",
".",
"astimezone",
"(",
"ctx",
".",
"timezone",
")",
".",
"time",
"(",
")",
"raise",
"EvaluationError",
"(",
"\"Can't convert '%s' to a time\"",
"%",
"str",
"(",
"value",
")",
")"
] | Tries conversion of any value to a time | [
"Tries",
"conversion",
"of",
"any",
"value",
"to",
"a",
"time"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L142-L155 |
rapidpro/expressions | python/temba_expressions/conversions.py | to_same | def to_same(value1, value2, ctx):
"""
Converts a pair of arguments to their most-likely types. This deviates from Excel which doesn't auto convert values
but is necessary for us to intuitively handle contact fields which don't use the correct value type
"""
if type(value1) == type(value2):
return value1, value2
try:
# try converting to two decimals
return to_decimal(value1, ctx), to_decimal(value2, ctx)
except EvaluationError:
pass
try:
# try converting to two dates
d1, d2 = to_date_or_datetime(value1, ctx), to_date_or_datetime(value2, ctx)
# if either one is a datetime, then the other needs to become a datetime
if type(value1) != type(value2):
d1, d2 = to_datetime(d1, ctx), to_datetime(d2, ctx)
return d1, d2
except EvaluationError:
pass
# try converting to two strings
return to_string(value1, ctx), to_string(value2, ctx) | python | def to_same(value1, value2, ctx):
"""
Converts a pair of arguments to their most-likely types. This deviates from Excel which doesn't auto convert values
but is necessary for us to intuitively handle contact fields which don't use the correct value type
"""
if type(value1) == type(value2):
return value1, value2
try:
# try converting to two decimals
return to_decimal(value1, ctx), to_decimal(value2, ctx)
except EvaluationError:
pass
try:
# try converting to two dates
d1, d2 = to_date_or_datetime(value1, ctx), to_date_or_datetime(value2, ctx)
# if either one is a datetime, then the other needs to become a datetime
if type(value1) != type(value2):
d1, d2 = to_datetime(d1, ctx), to_datetime(d2, ctx)
return d1, d2
except EvaluationError:
pass
# try converting to two strings
return to_string(value1, ctx), to_string(value2, ctx) | [
"def",
"to_same",
"(",
"value1",
",",
"value2",
",",
"ctx",
")",
":",
"if",
"type",
"(",
"value1",
")",
"==",
"type",
"(",
"value2",
")",
":",
"return",
"value1",
",",
"value2",
"try",
":",
"# try converting to two decimals",
"return",
"to_decimal",
"(",
"value1",
",",
"ctx",
")",
",",
"to_decimal",
"(",
"value2",
",",
"ctx",
")",
"except",
"EvaluationError",
":",
"pass",
"try",
":",
"# try converting to two dates",
"d1",
",",
"d2",
"=",
"to_date_or_datetime",
"(",
"value1",
",",
"ctx",
")",
",",
"to_date_or_datetime",
"(",
"value2",
",",
"ctx",
")",
"# if either one is a datetime, then the other needs to become a datetime",
"if",
"type",
"(",
"value1",
")",
"!=",
"type",
"(",
"value2",
")",
":",
"d1",
",",
"d2",
"=",
"to_datetime",
"(",
"d1",
",",
"ctx",
")",
",",
"to_datetime",
"(",
"d2",
",",
"ctx",
")",
"return",
"d1",
",",
"d2",
"except",
"EvaluationError",
":",
"pass",
"# try converting to two strings",
"return",
"to_string",
"(",
"value1",
",",
"ctx",
")",
",",
"to_string",
"(",
"value2",
",",
"ctx",
")"
] | Converts a pair of arguments to their most-likely types. This deviates from Excel which doesn't auto convert values
but is necessary for us to intuitively handle contact fields which don't use the correct value type | [
"Converts",
"a",
"pair",
"of",
"arguments",
"to",
"their",
"most",
"-",
"likely",
"types",
".",
"This",
"deviates",
"from",
"Excel",
"which",
"doesn",
"t",
"auto",
"convert",
"values",
"but",
"is",
"necessary",
"for",
"us",
"to",
"intuitively",
"handle",
"contact",
"fields",
"which",
"don",
"t",
"use",
"the",
"correct",
"value",
"type"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L158-L184 |
rapidpro/expressions | python/temba_expressions/conversions.py | to_repr | def to_repr(value, ctx):
"""
Converts a value back to its representation form, e.g. x -> "x"
"""
as_string = to_string(value, ctx)
if isinstance(value, str) or isinstance(value, datetime.date) or isinstance(value, datetime.time):
as_string = as_string.replace('"', '""') # escape quotes by doubling
as_string = '"%s"' % as_string
return as_string | python | def to_repr(value, ctx):
"""
Converts a value back to its representation form, e.g. x -> "x"
"""
as_string = to_string(value, ctx)
if isinstance(value, str) or isinstance(value, datetime.date) or isinstance(value, datetime.time):
as_string = as_string.replace('"', '""') # escape quotes by doubling
as_string = '"%s"' % as_string
return as_string | [
"def",
"to_repr",
"(",
"value",
",",
"ctx",
")",
":",
"as_string",
"=",
"to_string",
"(",
"value",
",",
"ctx",
")",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
"or",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"date",
")",
"or",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"time",
")",
":",
"as_string",
"=",
"as_string",
".",
"replace",
"(",
"'\"'",
",",
"'\"\"'",
")",
"# escape quotes by doubling",
"as_string",
"=",
"'\"%s\"'",
"%",
"as_string",
"return",
"as_string"
] | Converts a value back to its representation form, e.g. x -> "x" | [
"Converts",
"a",
"value",
"back",
"to",
"its",
"representation",
"form",
"e",
".",
"g",
".",
"x",
"-",
">",
"x"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L187-L197 |
rapidpro/expressions | python/temba_expressions/conversions.py | format_decimal | def format_decimal(decimal):
"""
Formats a decimal number
:param decimal: the decimal value
:return: the formatted string value
"""
# strip trailing fractional zeros
normalized = decimal.normalize()
sign, digits, exponent = normalized.as_tuple()
if exponent >= 1:
normalized = normalized.quantize(1)
return str(normalized) | python | def format_decimal(decimal):
"""
Formats a decimal number
:param decimal: the decimal value
:return: the formatted string value
"""
# strip trailing fractional zeros
normalized = decimal.normalize()
sign, digits, exponent = normalized.as_tuple()
if exponent >= 1:
normalized = normalized.quantize(1)
return str(normalized) | [
"def",
"format_decimal",
"(",
"decimal",
")",
":",
"# strip trailing fractional zeros",
"normalized",
"=",
"decimal",
".",
"normalize",
"(",
")",
"sign",
",",
"digits",
",",
"exponent",
"=",
"normalized",
".",
"as_tuple",
"(",
")",
"if",
"exponent",
">=",
"1",
":",
"normalized",
"=",
"normalized",
".",
"quantize",
"(",
"1",
")",
"return",
"str",
"(",
"normalized",
")"
] | Formats a decimal number
:param decimal: the decimal value
:return: the formatted string value | [
"Formats",
"a",
"decimal",
"number",
":",
"param",
"decimal",
":",
"the",
"decimal",
"value",
":",
"return",
":",
"the",
"formatted",
"string",
"value"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L200-L212 |
lablup/backend.ai-common | src/ai/backend/common/identity.py | is_containerized | def is_containerized() -> bool:
'''
Check if I am running inside a Linux container.
'''
try:
cginfo = Path('/proc/self/cgroup').read_text()
if '/docker/' in cginfo or '/lxc/' in cginfo:
return True
except IOError:
return False | python | def is_containerized() -> bool:
'''
Check if I am running inside a Linux container.
'''
try:
cginfo = Path('/proc/self/cgroup').read_text()
if '/docker/' in cginfo or '/lxc/' in cginfo:
return True
except IOError:
return False | [
"def",
"is_containerized",
"(",
")",
"->",
"bool",
":",
"try",
":",
"cginfo",
"=",
"Path",
"(",
"'/proc/self/cgroup'",
")",
".",
"read_text",
"(",
")",
"if",
"'/docker/'",
"in",
"cginfo",
"or",
"'/lxc/'",
"in",
"cginfo",
":",
"return",
"True",
"except",
"IOError",
":",
"return",
"False"
] | Check if I am running inside a Linux container. | [
"Check",
"if",
"I",
"am",
"running",
"inside",
"a",
"Linux",
"container",
"."
] | train | https://github.com/lablup/backend.ai-common/blob/20b3a2551ee5bb3b88e7836471bc244a70ad0ae6/src/ai/backend/common/identity.py#L24-L33 |
lablup/backend.ai-common | src/ai/backend/common/identity.py | detect_cloud | def detect_cloud() -> str:
'''
Detect the cloud provider where I am running on.
'''
# NOTE: Contributions are welcome!
# Please add other cloud providers such as Rackspace, IBM BlueMix, etc.
if sys.platform.startswith('linux'):
# Google Cloud Platform or Amazon AWS (hvm)
try:
# AWS Nitro-based instances
mb = Path('/sys/devices/virtual/dmi/id/board_vendor').read_text().lower()
if 'amazon' in mb:
return 'amazon'
except IOError:
pass
try:
bios = Path('/sys/devices/virtual/dmi/id/bios_version').read_text().lower()
if 'google' in bios:
return 'google'
if 'amazon' in bios:
return 'amazon'
except IOError:
pass
# Microsoft Azure
# https://gallery.technet.microsoft.com/scriptcenter/Detect-Windows-Azure-aed06d51
# TODO: this only works with Debian/Ubuntu instances.
# TODO: this does not work inside containers.
try:
dhcp = Path('/var/lib/dhcp/dhclient.eth0.leases').read_text()
if 'unknown-245' in dhcp:
return 'azure'
# alternative method is to read /var/lib/waagent/GoalState.1.xml
# but it requires sudo privilege.
except IOError:
pass
else:
log.warning('Cloud detection is implemented for Linux only yet.')
return None | python | def detect_cloud() -> str:
'''
Detect the cloud provider where I am running on.
'''
# NOTE: Contributions are welcome!
# Please add other cloud providers such as Rackspace, IBM BlueMix, etc.
if sys.platform.startswith('linux'):
# Google Cloud Platform or Amazon AWS (hvm)
try:
# AWS Nitro-based instances
mb = Path('/sys/devices/virtual/dmi/id/board_vendor').read_text().lower()
if 'amazon' in mb:
return 'amazon'
except IOError:
pass
try:
bios = Path('/sys/devices/virtual/dmi/id/bios_version').read_text().lower()
if 'google' in bios:
return 'google'
if 'amazon' in bios:
return 'amazon'
except IOError:
pass
# Microsoft Azure
# https://gallery.technet.microsoft.com/scriptcenter/Detect-Windows-Azure-aed06d51
# TODO: this only works with Debian/Ubuntu instances.
# TODO: this does not work inside containers.
try:
dhcp = Path('/var/lib/dhcp/dhclient.eth0.leases').read_text()
if 'unknown-245' in dhcp:
return 'azure'
# alternative method is to read /var/lib/waagent/GoalState.1.xml
# but it requires sudo privilege.
except IOError:
pass
else:
log.warning('Cloud detection is implemented for Linux only yet.')
return None | [
"def",
"detect_cloud",
"(",
")",
"->",
"str",
":",
"# NOTE: Contributions are welcome!",
"# Please add other cloud providers such as Rackspace, IBM BlueMix, etc.",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'linux'",
")",
":",
"# Google Cloud Platform or Amazon AWS (hvm)",
"try",
":",
"# AWS Nitro-based instances",
"mb",
"=",
"Path",
"(",
"'/sys/devices/virtual/dmi/id/board_vendor'",
")",
".",
"read_text",
"(",
")",
".",
"lower",
"(",
")",
"if",
"'amazon'",
"in",
"mb",
":",
"return",
"'amazon'",
"except",
"IOError",
":",
"pass",
"try",
":",
"bios",
"=",
"Path",
"(",
"'/sys/devices/virtual/dmi/id/bios_version'",
")",
".",
"read_text",
"(",
")",
".",
"lower",
"(",
")",
"if",
"'google'",
"in",
"bios",
":",
"return",
"'google'",
"if",
"'amazon'",
"in",
"bios",
":",
"return",
"'amazon'",
"except",
"IOError",
":",
"pass",
"# Microsoft Azure",
"# https://gallery.technet.microsoft.com/scriptcenter/Detect-Windows-Azure-aed06d51",
"# TODO: this only works with Debian/Ubuntu instances.",
"# TODO: this does not work inside containers.",
"try",
":",
"dhcp",
"=",
"Path",
"(",
"'/var/lib/dhcp/dhclient.eth0.leases'",
")",
".",
"read_text",
"(",
")",
"if",
"'unknown-245'",
"in",
"dhcp",
":",
"return",
"'azure'",
"# alternative method is to read /var/lib/waagent/GoalState.1.xml",
"# but it requires sudo privilege.",
"except",
"IOError",
":",
"pass",
"else",
":",
"log",
".",
"warning",
"(",
"'Cloud detection is implemented for Linux only yet.'",
")",
"return",
"None"
] | Detect the cloud provider where I am running on. | [
"Detect",
"the",
"cloud",
"provider",
"where",
"I",
"am",
"running",
"on",
"."
] | train | https://github.com/lablup/backend.ai-common/blob/20b3a2551ee5bb3b88e7836471bc244a70ad0ae6/src/ai/backend/common/identity.py#L36-L73 |
siboles/pyFEBio | febio/MatDef.py | MatDef.addBlock | def addBlock(self,branch=None,btype=None,mtype=None,attributes=None):
'''
Add block definition to list of blocks in material
Order for list entry: branch level (0=root), block type (material,solid,fluid,etc.), matid (integer if root, False otherwise),
material name (string if root, False otherwise), material type, dictionary of attributes or False if none
'''
if branch == 0:
attributes = self.attributes
blk = {'branch': branch,
'btype': btype,
'mtype': mtype,
'attributes': attributes}
self.blocks.append(blk) | python | def addBlock(self,branch=None,btype=None,mtype=None,attributes=None):
'''
Add block definition to list of blocks in material
Order for list entry: branch level (0=root), block type (material,solid,fluid,etc.), matid (integer if root, False otherwise),
material name (string if root, False otherwise), material type, dictionary of attributes or False if none
'''
if branch == 0:
attributes = self.attributes
blk = {'branch': branch,
'btype': btype,
'mtype': mtype,
'attributes': attributes}
self.blocks.append(blk) | [
"def",
"addBlock",
"(",
"self",
",",
"branch",
"=",
"None",
",",
"btype",
"=",
"None",
",",
"mtype",
"=",
"None",
",",
"attributes",
"=",
"None",
")",
":",
"if",
"branch",
"==",
"0",
":",
"attributes",
"=",
"self",
".",
"attributes",
"blk",
"=",
"{",
"'branch'",
":",
"branch",
",",
"'btype'",
":",
"btype",
",",
"'mtype'",
":",
"mtype",
",",
"'attributes'",
":",
"attributes",
"}",
"self",
".",
"blocks",
".",
"append",
"(",
"blk",
")"
] | Add block definition to list of blocks in material
Order for list entry: branch level (0=root), block type (material,solid,fluid,etc.), matid (integer if root, False otherwise),
material name (string if root, False otherwise), material type, dictionary of attributes or False if none | [
"Add",
"block",
"definition",
"to",
"list",
"of",
"blocks",
"in",
"material",
"Order",
"for",
"list",
"entry",
":",
"branch",
"level",
"(",
"0",
"=",
"root",
")",
"block",
"type",
"(",
"material",
"solid",
"fluid",
"etc",
".",
")",
"matid",
"(",
"integer",
"if",
"root",
"False",
"otherwise",
")",
"material",
"name",
"(",
"string",
"if",
"root",
"False",
"otherwise",
")",
"material",
"type",
"dictionary",
"of",
"attributes",
"or",
"False",
"if",
"none"
] | train | https://github.com/siboles/pyFEBio/blob/95083a558c34b236ad4e197b558099dc15f9e319/febio/MatDef.py#L38-L51 |
RI-imaging/nrefocus | nrefocus/_propagate.py | refocus | def refocus(field, d, nm, res, method="helmholtz", num_cpus=1, padding=True):
"""Refocus a 1D or 2D field
Parameters
----------
field : 1d or 2d array
1D or 2D background corrected electric field (Ex/BEx)
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelenth in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
num_cpus : int
Not implemented. Only one CPU is used.
padding : bool
perform padding with linear ramp from edge to average
to reduce ringing artifacts.
.. versionadded:: 0.1.4
Returns
-------
Electric field at `d`.
"""
# FFT of field
fshape = len(field.shape)
assert fshape in [1, 2], "Dimension of `field` must be 1 or 2."
func = fft_propagate
names = func.__code__.co_varnames[:func.__code__.co_argcount]
loc = locals()
vardict = dict()
for name in names:
if name in loc:
vardict[name] = loc[name]
if padding:
field = pad.pad_add(field)
vardict["fftfield"] = np.fft.fftn(field)
refoc = func(**vardict)
if padding:
refoc = pad.pad_rem(refoc)
return refoc | python | def refocus(field, d, nm, res, method="helmholtz", num_cpus=1, padding=True):
"""Refocus a 1D or 2D field
Parameters
----------
field : 1d or 2d array
1D or 2D background corrected electric field (Ex/BEx)
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelenth in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
num_cpus : int
Not implemented. Only one CPU is used.
padding : bool
perform padding with linear ramp from edge to average
to reduce ringing artifacts.
.. versionadded:: 0.1.4
Returns
-------
Electric field at `d`.
"""
# FFT of field
fshape = len(field.shape)
assert fshape in [1, 2], "Dimension of `field` must be 1 or 2."
func = fft_propagate
names = func.__code__.co_varnames[:func.__code__.co_argcount]
loc = locals()
vardict = dict()
for name in names:
if name in loc:
vardict[name] = loc[name]
if padding:
field = pad.pad_add(field)
vardict["fftfield"] = np.fft.fftn(field)
refoc = func(**vardict)
if padding:
refoc = pad.pad_rem(refoc)
return refoc | [
"def",
"refocus",
"(",
"field",
",",
"d",
",",
"nm",
",",
"res",
",",
"method",
"=",
"\"helmholtz\"",
",",
"num_cpus",
"=",
"1",
",",
"padding",
"=",
"True",
")",
":",
"# FFT of field",
"fshape",
"=",
"len",
"(",
"field",
".",
"shape",
")",
"assert",
"fshape",
"in",
"[",
"1",
",",
"2",
"]",
",",
"\"Dimension of `field` must be 1 or 2.\"",
"func",
"=",
"fft_propagate",
"names",
"=",
"func",
".",
"__code__",
".",
"co_varnames",
"[",
":",
"func",
".",
"__code__",
".",
"co_argcount",
"]",
"loc",
"=",
"locals",
"(",
")",
"vardict",
"=",
"dict",
"(",
")",
"for",
"name",
"in",
"names",
":",
"if",
"name",
"in",
"loc",
":",
"vardict",
"[",
"name",
"]",
"=",
"loc",
"[",
"name",
"]",
"if",
"padding",
":",
"field",
"=",
"pad",
".",
"pad_add",
"(",
"field",
")",
"vardict",
"[",
"\"fftfield\"",
"]",
"=",
"np",
".",
"fft",
".",
"fftn",
"(",
"field",
")",
"refoc",
"=",
"func",
"(",
"*",
"*",
"vardict",
")",
"if",
"padding",
":",
"refoc",
"=",
"pad",
".",
"pad_rem",
"(",
"refoc",
")",
"return",
"refoc"
] | Refocus a 1D or 2D field
Parameters
----------
field : 1d or 2d array
1D or 2D background corrected electric field (Ex/BEx)
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelenth in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
num_cpus : int
Not implemented. Only one CPU is used.
padding : bool
perform padding with linear ramp from edge to average
to reduce ringing artifacts.
.. versionadded:: 0.1.4
Returns
-------
Electric field at `d`. | [
"Refocus",
"a",
"1D",
"or",
"2D",
"field"
] | train | https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/_propagate.py#L12-L69 |
RI-imaging/nrefocus | nrefocus/_propagate.py | refocus_stack | def refocus_stack(fieldstack, d, nm, res, method="helmholtz",
num_cpus=_cpu_count, copy=True, padding=True):
"""Refocus a stack of 1D or 2D fields
Parameters
----------
fieldstack : 2d or 3d array
Stack of 1D or 2D background corrected electric fields (Ex/BEx).
The first axis iterates through the individual fields.
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelenth in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
num_cpus : str
Defines the number of CPUs to be used for refocusing.
copy : bool
If False, overwrites input stack.
padding : bool
Perform padding with linear ramp from edge to average
to reduce ringing artifacts.
.. versionadded:: 0.1.4
Returns
-------
Electric field stack at `d`.
"""
func = refocus
names = func.__code__.co_varnames[:func.__code__.co_argcount]
loc = locals()
vardict = dict()
for name in names:
if name in loc.keys():
vardict[name] = loc[name]
# default keyword arguments
func_def = func.__defaults__[::-1]
# child processes should only use one cpu
vardict["num_cpus"] = 1
vardict["padding"] = padding
M = fieldstack.shape[0]
stackargs = list()
# Create individual arglists for all fields
for m in range(M):
kwarg = vardict.copy()
kwarg["field"] = fieldstack[m]
# now we turn the kwarg into an arglist
args = list()
for i, a in enumerate(names[::-1]):
# first set default
if i < len(func_def):
val = func_def[i]
if a in kwarg:
val = kwarg[a]
args.append(val)
stackargs.append(args[::-1])
p = mp.Pool(num_cpus)
result = p.map_async(_refocus_wrapper, stackargs).get()
p.close()
p.terminate()
p.join()
if copy:
data = np.zeros(fieldstack.shape, dtype=result[0].dtype)
else:
data = fieldstack
for m in range(M):
data[m] = result[m]
return data | python | def refocus_stack(fieldstack, d, nm, res, method="helmholtz",
num_cpus=_cpu_count, copy=True, padding=True):
"""Refocus a stack of 1D or 2D fields
Parameters
----------
fieldstack : 2d or 3d array
Stack of 1D or 2D background corrected electric fields (Ex/BEx).
The first axis iterates through the individual fields.
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelenth in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
num_cpus : str
Defines the number of CPUs to be used for refocusing.
copy : bool
If False, overwrites input stack.
padding : bool
Perform padding with linear ramp from edge to average
to reduce ringing artifacts.
.. versionadded:: 0.1.4
Returns
-------
Electric field stack at `d`.
"""
func = refocus
names = func.__code__.co_varnames[:func.__code__.co_argcount]
loc = locals()
vardict = dict()
for name in names:
if name in loc.keys():
vardict[name] = loc[name]
# default keyword arguments
func_def = func.__defaults__[::-1]
# child processes should only use one cpu
vardict["num_cpus"] = 1
vardict["padding"] = padding
M = fieldstack.shape[0]
stackargs = list()
# Create individual arglists for all fields
for m in range(M):
kwarg = vardict.copy()
kwarg["field"] = fieldstack[m]
# now we turn the kwarg into an arglist
args = list()
for i, a in enumerate(names[::-1]):
# first set default
if i < len(func_def):
val = func_def[i]
if a in kwarg:
val = kwarg[a]
args.append(val)
stackargs.append(args[::-1])
p = mp.Pool(num_cpus)
result = p.map_async(_refocus_wrapper, stackargs).get()
p.close()
p.terminate()
p.join()
if copy:
data = np.zeros(fieldstack.shape, dtype=result[0].dtype)
else:
data = fieldstack
for m in range(M):
data[m] = result[m]
return data | [
"def",
"refocus_stack",
"(",
"fieldstack",
",",
"d",
",",
"nm",
",",
"res",
",",
"method",
"=",
"\"helmholtz\"",
",",
"num_cpus",
"=",
"_cpu_count",
",",
"copy",
"=",
"True",
",",
"padding",
"=",
"True",
")",
":",
"func",
"=",
"refocus",
"names",
"=",
"func",
".",
"__code__",
".",
"co_varnames",
"[",
":",
"func",
".",
"__code__",
".",
"co_argcount",
"]",
"loc",
"=",
"locals",
"(",
")",
"vardict",
"=",
"dict",
"(",
")",
"for",
"name",
"in",
"names",
":",
"if",
"name",
"in",
"loc",
".",
"keys",
"(",
")",
":",
"vardict",
"[",
"name",
"]",
"=",
"loc",
"[",
"name",
"]",
"# default keyword arguments",
"func_def",
"=",
"func",
".",
"__defaults__",
"[",
":",
":",
"-",
"1",
"]",
"# child processes should only use one cpu",
"vardict",
"[",
"\"num_cpus\"",
"]",
"=",
"1",
"vardict",
"[",
"\"padding\"",
"]",
"=",
"padding",
"M",
"=",
"fieldstack",
".",
"shape",
"[",
"0",
"]",
"stackargs",
"=",
"list",
"(",
")",
"# Create individual arglists for all fields",
"for",
"m",
"in",
"range",
"(",
"M",
")",
":",
"kwarg",
"=",
"vardict",
".",
"copy",
"(",
")",
"kwarg",
"[",
"\"field\"",
"]",
"=",
"fieldstack",
"[",
"m",
"]",
"# now we turn the kwarg into an arglist",
"args",
"=",
"list",
"(",
")",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"names",
"[",
":",
":",
"-",
"1",
"]",
")",
":",
"# first set default",
"if",
"i",
"<",
"len",
"(",
"func_def",
")",
":",
"val",
"=",
"func_def",
"[",
"i",
"]",
"if",
"a",
"in",
"kwarg",
":",
"val",
"=",
"kwarg",
"[",
"a",
"]",
"args",
".",
"append",
"(",
"val",
")",
"stackargs",
".",
"append",
"(",
"args",
"[",
":",
":",
"-",
"1",
"]",
")",
"p",
"=",
"mp",
".",
"Pool",
"(",
"num_cpus",
")",
"result",
"=",
"p",
".",
"map_async",
"(",
"_refocus_wrapper",
",",
"stackargs",
")",
".",
"get",
"(",
")",
"p",
".",
"close",
"(",
")",
"p",
".",
"terminate",
"(",
")",
"p",
".",
"join",
"(",
")",
"if",
"copy",
":",
"data",
"=",
"np",
".",
"zeros",
"(",
"fieldstack",
".",
"shape",
",",
"dtype",
"=",
"result",
"[",
"0",
"]",
".",
"dtype",
")",
"else",
":",
"data",
"=",
"fieldstack",
"for",
"m",
"in",
"range",
"(",
"M",
")",
":",
"data",
"[",
"m",
"]",
"=",
"result",
"[",
"m",
"]",
"return",
"data"
] | Refocus a stack of 1D or 2D fields
Parameters
----------
fieldstack : 2d or 3d array
Stack of 1D or 2D background corrected electric fields (Ex/BEx).
The first axis iterates through the individual fields.
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelenth in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
num_cpus : str
Defines the number of CPUs to be used for refocusing.
copy : bool
If False, overwrites input stack.
padding : bool
Perform padding with linear ramp from edge to average
to reduce ringing artifacts.
.. versionadded:: 0.1.4
Returns
-------
Electric field stack at `d`. | [
"Refocus",
"a",
"stack",
"of",
"1D",
"or",
"2D",
"fields"
] | train | https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/_propagate.py#L72-L157 |
RI-imaging/nrefocus | nrefocus/_propagate.py | fft_propagate | def fft_propagate(fftfield, d, nm, res, method="helmholtz",
ret_fft=False):
"""Propagates a 1D or 2D Fourier transformed field
Parameters
----------
fftfield : 1-dimensional or 2-dimensional ndarray
Fourier transform of 1D Electric field component
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelength in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
ret_fft : bool
Do not perform an inverse Fourier transform and return the field
in Fourier space.
Returns
-------
Electric field at `d`. If `ret_fft` is True, then the
Fourier transform of the electric field will be returned (faster).
"""
fshape = len(fftfield.shape)
assert fshape in [1, 2], "Dimension of `fftfield` must be 1 or 2."
if fshape == 1:
func = fft_propagate_2d
else:
func = fft_propagate_3d
names = func.__code__.co_varnames[:func.__code__.co_argcount]
loc = locals()
vardict = dict()
for name in names:
vardict[name] = loc[name]
return func(**vardict) | python | def fft_propagate(fftfield, d, nm, res, method="helmholtz",
ret_fft=False):
"""Propagates a 1D or 2D Fourier transformed field
Parameters
----------
fftfield : 1-dimensional or 2-dimensional ndarray
Fourier transform of 1D Electric field component
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelength in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
ret_fft : bool
Do not perform an inverse Fourier transform and return the field
in Fourier space.
Returns
-------
Electric field at `d`. If `ret_fft` is True, then the
Fourier transform of the electric field will be returned (faster).
"""
fshape = len(fftfield.shape)
assert fshape in [1, 2], "Dimension of `fftfield` must be 1 or 2."
if fshape == 1:
func = fft_propagate_2d
else:
func = fft_propagate_3d
names = func.__code__.co_varnames[:func.__code__.co_argcount]
loc = locals()
vardict = dict()
for name in names:
vardict[name] = loc[name]
return func(**vardict) | [
"def",
"fft_propagate",
"(",
"fftfield",
",",
"d",
",",
"nm",
",",
"res",
",",
"method",
"=",
"\"helmholtz\"",
",",
"ret_fft",
"=",
"False",
")",
":",
"fshape",
"=",
"len",
"(",
"fftfield",
".",
"shape",
")",
"assert",
"fshape",
"in",
"[",
"1",
",",
"2",
"]",
",",
"\"Dimension of `fftfield` must be 1 or 2.\"",
"if",
"fshape",
"==",
"1",
":",
"func",
"=",
"fft_propagate_2d",
"else",
":",
"func",
"=",
"fft_propagate_3d",
"names",
"=",
"func",
".",
"__code__",
".",
"co_varnames",
"[",
":",
"func",
".",
"__code__",
".",
"co_argcount",
"]",
"loc",
"=",
"locals",
"(",
")",
"vardict",
"=",
"dict",
"(",
")",
"for",
"name",
"in",
"names",
":",
"vardict",
"[",
"name",
"]",
"=",
"loc",
"[",
"name",
"]",
"return",
"func",
"(",
"*",
"*",
"vardict",
")"
] | Propagates a 1D or 2D Fourier transformed field
Parameters
----------
fftfield : 1-dimensional or 2-dimensional ndarray
Fourier transform of 1D Electric field component
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelength in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
ret_fft : bool
Do not perform an inverse Fourier transform and return the field
in Fourier space.
Returns
-------
Electric field at `d`. If `ret_fft` is True, then the
Fourier transform of the electric field will be returned (faster). | [
"Propagates",
"a",
"1D",
"or",
"2D",
"Fourier",
"transformed",
"field"
] | train | https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/_propagate.py#L160-L207 |
RI-imaging/nrefocus | nrefocus/_propagate.py | fft_propagate_2d | def fft_propagate_2d(fftfield, d, nm, res, method="helmholtz",
ret_fft=False):
"""Propagate a 1D Fourier transformed field in 2D
Parameters
----------
fftfield : 1d array
Fourier transform of 1D Electric field component
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelength in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
ret_fft : bool
Do not perform an inverse Fourier transform and return the field
in Fourier space.
Returns
-------
Electric field at `d`. If `ret_fft` is True, then the
Fourier transform of the electric field will be returned (faster).
"""
assert len(fftfield.shape) == 1, "Dimension of `fftfield` must be 1."
km = (2 * np.pi * nm) / res
kx = np.fft.fftfreq(len(fftfield)) * 2 * np.pi
# free space propagator is
if method == "helmholtz":
# exp(i*sqrt(km²-kx²)*d)
# Also subtract incoming plane wave. We are only considering
# the scattered field here.
root_km = km**2 - kx**2
rt0 = (root_km > 0)
# multiply by rt0 (filter in Fourier space)
fstemp = np.exp(1j * (np.sqrt(root_km * rt0) - km) * d) * rt0
elif method == "fresnel":
# exp(i*d*(km-kx²/(2*km))
# fstemp = np.exp(-1j * d * (kx**2/(2*km)))
fstemp = np.exp(-1j * d * (kx**2/(2*km)))
else:
raise ValueError("Unknown method: {}".format(method))
if ret_fft:
return fftfield * fstemp
else:
return np.fft.ifft(fftfield * fstemp) | python | def fft_propagate_2d(fftfield, d, nm, res, method="helmholtz",
ret_fft=False):
"""Propagate a 1D Fourier transformed field in 2D
Parameters
----------
fftfield : 1d array
Fourier transform of 1D Electric field component
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelength in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
ret_fft : bool
Do not perform an inverse Fourier transform and return the field
in Fourier space.
Returns
-------
Electric field at `d`. If `ret_fft` is True, then the
Fourier transform of the electric field will be returned (faster).
"""
assert len(fftfield.shape) == 1, "Dimension of `fftfield` must be 1."
km = (2 * np.pi * nm) / res
kx = np.fft.fftfreq(len(fftfield)) * 2 * np.pi
# free space propagator is
if method == "helmholtz":
# exp(i*sqrt(km²-kx²)*d)
# Also subtract incoming plane wave. We are only considering
# the scattered field here.
root_km = km**2 - kx**2
rt0 = (root_km > 0)
# multiply by rt0 (filter in Fourier space)
fstemp = np.exp(1j * (np.sqrt(root_km * rt0) - km) * d) * rt0
elif method == "fresnel":
# exp(i*d*(km-kx²/(2*km))
# fstemp = np.exp(-1j * d * (kx**2/(2*km)))
fstemp = np.exp(-1j * d * (kx**2/(2*km)))
else:
raise ValueError("Unknown method: {}".format(method))
if ret_fft:
return fftfield * fstemp
else:
return np.fft.ifft(fftfield * fstemp) | [
"def",
"fft_propagate_2d",
"(",
"fftfield",
",",
"d",
",",
"nm",
",",
"res",
",",
"method",
"=",
"\"helmholtz\"",
",",
"ret_fft",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"fftfield",
".",
"shape",
")",
"==",
"1",
",",
"\"Dimension of `fftfield` must be 1.\"",
"km",
"=",
"(",
"2",
"*",
"np",
".",
"pi",
"*",
"nm",
")",
"/",
"res",
"kx",
"=",
"np",
".",
"fft",
".",
"fftfreq",
"(",
"len",
"(",
"fftfield",
")",
")",
"*",
"2",
"*",
"np",
".",
"pi",
"# free space propagator is",
"if",
"method",
"==",
"\"helmholtz\"",
":",
"# exp(i*sqrt(km²-kx²)*d)",
"# Also subtract incoming plane wave. We are only considering",
"# the scattered field here.",
"root_km",
"=",
"km",
"**",
"2",
"-",
"kx",
"**",
"2",
"rt0",
"=",
"(",
"root_km",
">",
"0",
")",
"# multiply by rt0 (filter in Fourier space)",
"fstemp",
"=",
"np",
".",
"exp",
"(",
"1j",
"*",
"(",
"np",
".",
"sqrt",
"(",
"root_km",
"*",
"rt0",
")",
"-",
"km",
")",
"*",
"d",
")",
"*",
"rt0",
"elif",
"method",
"==",
"\"fresnel\"",
":",
"# exp(i*d*(km-kx²/(2*km))",
"# fstemp = np.exp(-1j * d * (kx**2/(2*km)))",
"fstemp",
"=",
"np",
".",
"exp",
"(",
"-",
"1j",
"*",
"d",
"*",
"(",
"kx",
"**",
"2",
"/",
"(",
"2",
"*",
"km",
")",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown method: {}\"",
".",
"format",
"(",
"method",
")",
")",
"if",
"ret_fft",
":",
"return",
"fftfield",
"*",
"fstemp",
"else",
":",
"return",
"np",
".",
"fft",
".",
"ifft",
"(",
"fftfield",
"*",
"fstemp",
")"
] | Propagate a 1D Fourier transformed field in 2D
Parameters
----------
fftfield : 1d array
Fourier transform of 1D Electric field component
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelength in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
ret_fft : bool
Do not perform an inverse Fourier transform and return the field
in Fourier space.
Returns
-------
Electric field at `d`. If `ret_fft` is True, then the
Fourier transform of the electric field will be returned (faster). | [
"Propagate",
"a",
"1D",
"Fourier",
"transformed",
"field",
"in",
"2D"
] | train | https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/_propagate.py#L210-L265 |
RI-imaging/nrefocus | nrefocus/_propagate.py | fft_propagate_3d | def fft_propagate_3d(fftfield, d, nm, res, method="helmholtz",
ret_fft=False):
"""Propagate a 2D Fourier transformed field in 3D
Parameters
----------
fftfield : 2d array
Fourier transform of 2D Electric field component
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelength in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
ret_fft : bool
Do not perform an inverse Fourier transform and return the field
in Fourier space.
Returns
-------
Electric field at `d`. If `ret_fft` is True, then the
Fourier transform of the electric field will be returned (faster).
"""
assert len(fftfield.shape) == 2, "Dimension of `fftfield` must be 2."
# if fftfield.shape[0] != fftfield.shape[1]:
# raise NotImplementedError("Field must be square shaped.")
# free space propagator is
# exp(i*sqrt(km**2-kx**2-ky**2)*d)
km = (2 * np.pi * nm) / res
kx = (np.fft.fftfreq(fftfield.shape[0]) * 2 * np.pi).reshape(-1, 1)
ky = (np.fft.fftfreq(fftfield.shape[1]) * 2 * np.pi).reshape(1, -1)
if method == "helmholtz":
# exp(i*sqrt(km²-kx²-ky²)*d)
root_km = km**2 - kx**2 - ky**2
rt0 = (root_km > 0)
# multiply by rt0 (filter in Fourier space)
fstemp = np.exp(1j * (np.sqrt(root_km * rt0) - km) * d) * rt0
elif method == "fresnel":
# exp(i*d*(km-(kx²+ky²)/(2*km))
# fstemp = np.exp(-1j * d * (kx**2+ky**2)/(2*km))
fstemp = np.exp(-1j * d * (kx**2 + ky**2)/(2*km))
else:
raise ValueError("Unknown method: {}".format(method))
# fstemp[np.where(np.isnan(fstemp))] = 0
# Also subtract incoming plane wave. We are only considering
# the scattered field here.
if ret_fft:
return fftfield * fstemp
else:
return np.fft.ifft2(fftfield * fstemp) | python | def fft_propagate_3d(fftfield, d, nm, res, method="helmholtz",
ret_fft=False):
"""Propagate a 2D Fourier transformed field in 3D
Parameters
----------
fftfield : 2d array
Fourier transform of 2D Electric field component
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelength in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
ret_fft : bool
Do not perform an inverse Fourier transform and return the field
in Fourier space.
Returns
-------
Electric field at `d`. If `ret_fft` is True, then the
Fourier transform of the electric field will be returned (faster).
"""
assert len(fftfield.shape) == 2, "Dimension of `fftfield` must be 2."
# if fftfield.shape[0] != fftfield.shape[1]:
# raise NotImplementedError("Field must be square shaped.")
# free space propagator is
# exp(i*sqrt(km**2-kx**2-ky**2)*d)
km = (2 * np.pi * nm) / res
kx = (np.fft.fftfreq(fftfield.shape[0]) * 2 * np.pi).reshape(-1, 1)
ky = (np.fft.fftfreq(fftfield.shape[1]) * 2 * np.pi).reshape(1, -1)
if method == "helmholtz":
# exp(i*sqrt(km²-kx²-ky²)*d)
root_km = km**2 - kx**2 - ky**2
rt0 = (root_km > 0)
# multiply by rt0 (filter in Fourier space)
fstemp = np.exp(1j * (np.sqrt(root_km * rt0) - km) * d) * rt0
elif method == "fresnel":
# exp(i*d*(km-(kx²+ky²)/(2*km))
# fstemp = np.exp(-1j * d * (kx**2+ky**2)/(2*km))
fstemp = np.exp(-1j * d * (kx**2 + ky**2)/(2*km))
else:
raise ValueError("Unknown method: {}".format(method))
# fstemp[np.where(np.isnan(fstemp))] = 0
# Also subtract incoming plane wave. We are only considering
# the scattered field here.
if ret_fft:
return fftfield * fstemp
else:
return np.fft.ifft2(fftfield * fstemp) | [
"def",
"fft_propagate_3d",
"(",
"fftfield",
",",
"d",
",",
"nm",
",",
"res",
",",
"method",
"=",
"\"helmholtz\"",
",",
"ret_fft",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"fftfield",
".",
"shape",
")",
"==",
"2",
",",
"\"Dimension of `fftfield` must be 2.\"",
"# if fftfield.shape[0] != fftfield.shape[1]:",
"# raise NotImplementedError(\"Field must be square shaped.\")",
"# free space propagator is",
"# exp(i*sqrt(km**2-kx**2-ky**2)*d)",
"km",
"=",
"(",
"2",
"*",
"np",
".",
"pi",
"*",
"nm",
")",
"/",
"res",
"kx",
"=",
"(",
"np",
".",
"fft",
".",
"fftfreq",
"(",
"fftfield",
".",
"shape",
"[",
"0",
"]",
")",
"*",
"2",
"*",
"np",
".",
"pi",
")",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
"ky",
"=",
"(",
"np",
".",
"fft",
".",
"fftfreq",
"(",
"fftfield",
".",
"shape",
"[",
"1",
"]",
")",
"*",
"2",
"*",
"np",
".",
"pi",
")",
".",
"reshape",
"(",
"1",
",",
"-",
"1",
")",
"if",
"method",
"==",
"\"helmholtz\"",
":",
"# exp(i*sqrt(km²-kx²-ky²)*d)",
"root_km",
"=",
"km",
"**",
"2",
"-",
"kx",
"**",
"2",
"-",
"ky",
"**",
"2",
"rt0",
"=",
"(",
"root_km",
">",
"0",
")",
"# multiply by rt0 (filter in Fourier space)",
"fstemp",
"=",
"np",
".",
"exp",
"(",
"1j",
"*",
"(",
"np",
".",
"sqrt",
"(",
"root_km",
"*",
"rt0",
")",
"-",
"km",
")",
"*",
"d",
")",
"*",
"rt0",
"elif",
"method",
"==",
"\"fresnel\"",
":",
"# exp(i*d*(km-(kx²+ky²)/(2*km))",
"# fstemp = np.exp(-1j * d * (kx**2+ky**2)/(2*km))",
"fstemp",
"=",
"np",
".",
"exp",
"(",
"-",
"1j",
"*",
"d",
"*",
"(",
"kx",
"**",
"2",
"+",
"ky",
"**",
"2",
")",
"/",
"(",
"2",
"*",
"km",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown method: {}\"",
".",
"format",
"(",
"method",
")",
")",
"# fstemp[np.where(np.isnan(fstemp))] = 0",
"# Also subtract incoming plane wave. We are only considering",
"# the scattered field here.",
"if",
"ret_fft",
":",
"return",
"fftfield",
"*",
"fstemp",
"else",
":",
"return",
"np",
".",
"fft",
".",
"ifft2",
"(",
"fftfield",
"*",
"fstemp",
")"
] | Propagate a 2D Fourier transformed field in 3D
Parameters
----------
fftfield : 2d array
Fourier transform of 2D Electric field component
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of medium
res : float
Wavelength in pixels
method : str
Defines the method of propagation;
one of
- "helmholtz" : the optical transfer function `exp(idkₘ(M-1))`
- "fresnel" : paraxial approximation `exp(idk²/kₘ)`
ret_fft : bool
Do not perform an inverse Fourier transform and return the field
in Fourier space.
Returns
-------
Electric field at `d`. If `ret_fft` is True, then the
Fourier transform of the electric field will be returned (faster). | [
"Propagate",
"a",
"2D",
"Fourier",
"transformed",
"field",
"in",
"3D"
] | train | https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/_propagate.py#L268-L326 |
BlueBrain/nat | nat/gitManager.py | GitManager.push | def push(self):
"""
Adding the no_thin argument to the GIT push because we had some issues pushing previously.
According to http://stackoverflow.com/questions/16586642/git-unpack-error-on-push-to-gerrit#comment42953435_23610917,
"a new optimization which causes git to send as little data as possible over the network caused this bug to manifest,
so my guess is --no-thin just turns these optimizations off. From git push --help: "A thin transfer significantly
reduces the amount of sent data when the sender and receiver share many of the same objects in common." (--thin is the default)."
"""
if not self.canRunRemoteCmd():
return None
try:
fetchInfo = self.repo.remotes.origin.push(no_thin=True)[0]
except exc.GitCommandError as e:
print(dir(e))
print(e)
raise
if fetchInfo.flags & fetchInfo.ERROR:
try:
raise IOError("An error occured while trying to push the GIT repository from the server. Error flag: '" +
str(fetchInfo.flags) + "', message: '" + str(fetchInfo.note) + "'.")
except:
IOError("An error occured while trying to push the GIT repository from the server.")
return fetchInfo | python | def push(self):
"""
Adding the no_thin argument to the GIT push because we had some issues pushing previously.
According to http://stackoverflow.com/questions/16586642/git-unpack-error-on-push-to-gerrit#comment42953435_23610917,
"a new optimization which causes git to send as little data as possible over the network caused this bug to manifest,
so my guess is --no-thin just turns these optimizations off. From git push --help: "A thin transfer significantly
reduces the amount of sent data when the sender and receiver share many of the same objects in common." (--thin is the default)."
"""
if not self.canRunRemoteCmd():
return None
try:
fetchInfo = self.repo.remotes.origin.push(no_thin=True)[0]
except exc.GitCommandError as e:
print(dir(e))
print(e)
raise
if fetchInfo.flags & fetchInfo.ERROR:
try:
raise IOError("An error occured while trying to push the GIT repository from the server. Error flag: '" +
str(fetchInfo.flags) + "', message: '" + str(fetchInfo.note) + "'.")
except:
IOError("An error occured while trying to push the GIT repository from the server.")
return fetchInfo | [
"def",
"push",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"canRunRemoteCmd",
"(",
")",
":",
"return",
"None",
"try",
":",
"fetchInfo",
"=",
"self",
".",
"repo",
".",
"remotes",
".",
"origin",
".",
"push",
"(",
"no_thin",
"=",
"True",
")",
"[",
"0",
"]",
"except",
"exc",
".",
"GitCommandError",
"as",
"e",
":",
"print",
"(",
"dir",
"(",
"e",
")",
")",
"print",
"(",
"e",
")",
"raise",
"if",
"fetchInfo",
".",
"flags",
"&",
"fetchInfo",
".",
"ERROR",
":",
"try",
":",
"raise",
"IOError",
"(",
"\"An error occured while trying to push the GIT repository from the server. Error flag: '\"",
"+",
"str",
"(",
"fetchInfo",
".",
"flags",
")",
"+",
"\"', message: '\"",
"+",
"str",
"(",
"fetchInfo",
".",
"note",
")",
"+",
"\"'.\"",
")",
"except",
":",
"IOError",
"(",
"\"An error occured while trying to push the GIT repository from the server.\"",
")",
"return",
"fetchInfo"
] | Adding the no_thin argument to the GIT push because we had some issues pushing previously.
According to http://stackoverflow.com/questions/16586642/git-unpack-error-on-push-to-gerrit#comment42953435_23610917,
"a new optimization which causes git to send as little data as possible over the network caused this bug to manifest,
so my guess is --no-thin just turns these optimizations off. From git push --help: "A thin transfer significantly
reduces the amount of sent data when the sender and receiver share many of the same objects in common." (--thin is the default)." | [
"Adding",
"the",
"no_thin",
"argument",
"to",
"the",
"GIT",
"push",
"because",
"we",
"had",
"some",
"issues",
"pushing",
"previously",
".",
"According",
"to",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"16586642",
"/",
"git",
"-",
"unpack",
"-",
"error",
"-",
"on",
"-",
"push",
"-",
"to",
"-",
"gerrit#comment42953435_23610917",
"a",
"new",
"optimization",
"which",
"causes",
"git",
"to",
"send",
"as",
"little",
"data",
"as",
"possible",
"over",
"the",
"network",
"caused",
"this",
"bug",
"to",
"manifest",
"so",
"my",
"guess",
"is",
"--",
"no",
"-",
"thin",
"just",
"turns",
"these",
"optimizations",
"off",
".",
"From",
"git",
"push",
"--",
"help",
":",
"A",
"thin",
"transfer",
"significantly",
"reduces",
"the",
"amount",
"of",
"sent",
"data",
"when",
"the",
"sender",
"and",
"receiver",
"share",
"many",
"of",
"the",
"same",
"objects",
"in",
"common",
".",
"(",
"--",
"thin",
"is",
"the",
"default",
")",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/gitManager.py#L141-L167 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.