repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
django-parler/django-parler | parler/admin.py | TranslatableAdmin.get_object | def get_object(self, request, object_id, *args, **kwargs):
"""
Make sure the object is fetched in the correct language.
"""
obj = super(TranslatableAdmin, self).get_object(request, object_id, *args, **kwargs)
if obj is not None and self._has_translatable_model(): # Allow fallback to regular models.
obj.set_current_language(self._language(request, obj), initialize=True)
return obj | python | def get_object(self, request, object_id, *args, **kwargs):
"""
Make sure the object is fetched in the correct language.
"""
obj = super(TranslatableAdmin, self).get_object(request, object_id, *args, **kwargs)
if obj is not None and self._has_translatable_model(): # Allow fallback to regular models.
obj.set_current_language(self._language(request, obj), initialize=True)
return obj | [
"def",
"get_object",
"(",
"self",
",",
"request",
",",
"object_id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"super",
"(",
"TranslatableAdmin",
",",
"self",
")",
".",
"get_object",
"(",
"request",
",",
"object_id",
",",
"*",
"... | Make sure the object is fetched in the correct language. | [
"Make",
"sure",
"the",
"object",
"is",
"fetched",
"in",
"the",
"correct",
"language",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L284-L293 | train | 211,700 |
django-parler/django-parler | parler/admin.py | TranslatableAdmin.get_urls | def get_urls(self):
"""
Add a delete-translation view.
"""
urlpatterns = super(TranslatableAdmin, self).get_urls()
if not self._has_translatable_model():
return urlpatterns
else:
opts = self.model._meta
info = opts.app_label, opts.model_name
return [url(
r'^(.+)/change/delete-translation/(.+)/$',
self.admin_site.admin_view(self.delete_translation),
name='{0}_{1}_delete_translation'.format(*info)
)] + urlpatterns | python | def get_urls(self):
"""
Add a delete-translation view.
"""
urlpatterns = super(TranslatableAdmin, self).get_urls()
if not self._has_translatable_model():
return urlpatterns
else:
opts = self.model._meta
info = opts.app_label, opts.model_name
return [url(
r'^(.+)/change/delete-translation/(.+)/$',
self.admin_site.admin_view(self.delete_translation),
name='{0}_{1}_delete_translation'.format(*info)
)] + urlpatterns | [
"def",
"get_urls",
"(",
"self",
")",
":",
"urlpatterns",
"=",
"super",
"(",
"TranslatableAdmin",
",",
"self",
")",
".",
"get_urls",
"(",
")",
"if",
"not",
"self",
".",
"_has_translatable_model",
"(",
")",
":",
"return",
"urlpatterns",
"else",
":",
"opts",
... | Add a delete-translation view. | [
"Add",
"a",
"delete",
"-",
"translation",
"view",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L305-L319 | train | 211,701 |
django-parler/django-parler | parler/admin.py | TranslatableAdmin.render_change_form | def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
"""
Insert the language tabs.
"""
if self._has_translatable_model():
lang_code = self.get_form_language(request, obj)
lang = get_language_title(lang_code)
available_languages = self.get_available_languages(obj)
language_tabs = self.get_language_tabs(request, obj, available_languages)
context['language_tabs'] = language_tabs
if language_tabs:
context['title'] = '%s (%s)' % (context['title'], lang)
if not language_tabs.current_is_translated:
add = True # lets prepopulated_fields_js work.
# Patch form_url to contain the "language" GET parameter.
# Otherwise AdminModel.render_change_form will clean the URL
# and remove the "language" when coming from a filtered object
# list causing the wrong translation to be changed.
params = request.GET.dict()
params['language'] = lang_code
form_url = add_preserved_filters({
'preserved_filters': urlencode(params),
'opts': self.model._meta
}, form_url)
# django-fluent-pages uses the same technique
if 'default_change_form_template' not in context:
context['default_change_form_template'] = self.default_change_form_template
#context['base_template'] = self.get_change_form_base_template()
return super(TranslatableAdmin, self).render_change_form(request, context, add, change, form_url, obj) | python | def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
"""
Insert the language tabs.
"""
if self._has_translatable_model():
lang_code = self.get_form_language(request, obj)
lang = get_language_title(lang_code)
available_languages = self.get_available_languages(obj)
language_tabs = self.get_language_tabs(request, obj, available_languages)
context['language_tabs'] = language_tabs
if language_tabs:
context['title'] = '%s (%s)' % (context['title'], lang)
if not language_tabs.current_is_translated:
add = True # lets prepopulated_fields_js work.
# Patch form_url to contain the "language" GET parameter.
# Otherwise AdminModel.render_change_form will clean the URL
# and remove the "language" when coming from a filtered object
# list causing the wrong translation to be changed.
params = request.GET.dict()
params['language'] = lang_code
form_url = add_preserved_filters({
'preserved_filters': urlencode(params),
'opts': self.model._meta
}, form_url)
# django-fluent-pages uses the same technique
if 'default_change_form_template' not in context:
context['default_change_form_template'] = self.default_change_form_template
#context['base_template'] = self.get_change_form_base_template()
return super(TranslatableAdmin, self).render_change_form(request, context, add, change, form_url, obj) | [
"def",
"render_change_form",
"(",
"self",
",",
"request",
",",
"context",
",",
"add",
"=",
"False",
",",
"change",
"=",
"False",
",",
"form_url",
"=",
"''",
",",
"obj",
"=",
"None",
")",
":",
"if",
"self",
".",
"_has_translatable_model",
"(",
")",
":",... | Insert the language tabs. | [
"Insert",
"the",
"language",
"tabs",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L321-L354 | train | 211,702 |
django-parler/django-parler | parler/admin.py | TranslatableAdmin.deletion_not_allowed | def deletion_not_allowed(self, request, obj, language_code):
"""
Deletion-not-allowed view.
"""
opts = self.model._meta
context = {
'object': obj.master,
'language_code': language_code,
'opts': opts,
'app_label': opts.app_label,
'language_name': get_language_title(language_code),
'object_name': force_text(opts.verbose_name)
}
return render(request, self.deletion_not_allowed_template, context) | python | def deletion_not_allowed(self, request, obj, language_code):
"""
Deletion-not-allowed view.
"""
opts = self.model._meta
context = {
'object': obj.master,
'language_code': language_code,
'opts': opts,
'app_label': opts.app_label,
'language_name': get_language_title(language_code),
'object_name': force_text(opts.verbose_name)
}
return render(request, self.deletion_not_allowed_template, context) | [
"def",
"deletion_not_allowed",
"(",
"self",
",",
"request",
",",
"obj",
",",
"language_code",
")",
":",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"context",
"=",
"{",
"'object'",
":",
"obj",
".",
"master",
",",
"'language_code'",
":",
"language_code... | Deletion-not-allowed view. | [
"Deletion",
"-",
"not",
"-",
"allowed",
"view",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L493-L506 | train | 211,703 |
django-parler/django-parler | parler/admin.py | TranslatableAdmin.get_translation_objects | def get_translation_objects(self, request, language_code, obj=None, inlines=True):
"""
Return all objects that should be deleted when a translation is deleted.
This method can yield all QuerySet objects or lists for the objects.
"""
if obj is not None:
# A single model can hold multiple TranslatedFieldsModel objects.
# Return them all.
for translations_model in obj._parler_meta.get_all_models():
try:
translation = translations_model.objects.get(master=obj, language_code=language_code)
except translations_model.DoesNotExist:
continue
yield [translation]
if inlines:
for inline, qs in self._get_inline_translations(request, language_code, obj=obj):
yield qs | python | def get_translation_objects(self, request, language_code, obj=None, inlines=True):
"""
Return all objects that should be deleted when a translation is deleted.
This method can yield all QuerySet objects or lists for the objects.
"""
if obj is not None:
# A single model can hold multiple TranslatedFieldsModel objects.
# Return them all.
for translations_model in obj._parler_meta.get_all_models():
try:
translation = translations_model.objects.get(master=obj, language_code=language_code)
except translations_model.DoesNotExist:
continue
yield [translation]
if inlines:
for inline, qs in self._get_inline_translations(request, language_code, obj=obj):
yield qs | [
"def",
"get_translation_objects",
"(",
"self",
",",
"request",
",",
"language_code",
",",
"obj",
"=",
"None",
",",
"inlines",
"=",
"True",
")",
":",
"if",
"obj",
"is",
"not",
"None",
":",
"# A single model can hold multiple TranslatedFieldsModel objects.",
"# Return... | Return all objects that should be deleted when a translation is deleted.
This method can yield all QuerySet objects or lists for the objects. | [
"Return",
"all",
"objects",
"that",
"should",
"be",
"deleted",
"when",
"a",
"translation",
"is",
"deleted",
".",
"This",
"method",
"can",
"yield",
"all",
"QuerySet",
"objects",
"or",
"lists",
"for",
"the",
"objects",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L526-L543 | train | 211,704 |
django-parler/django-parler | parler/admin.py | TranslatableAdmin._get_inline_translations | def _get_inline_translations(self, request, language_code, obj=None):
"""
Fetch the inline translations
"""
inline_instances = self.get_inline_instances(request, obj=obj)
for inline in inline_instances:
if issubclass(inline.model, TranslatableModelMixin):
# leverage inlineformset_factory() to find the ForeignKey.
# This also resolves the fk_name if it's set.
fk = inline.get_formset(request, obj).fk
rel_name = 'master__{0}'.format(fk.name)
filters = {
'language_code': language_code,
rel_name: obj
}
for translations_model in inline.model._parler_meta.get_all_models():
qs = translations_model.objects.filter(**filters)
if obj is not None:
qs = qs.using(obj._state.db)
yield inline, qs | python | def _get_inline_translations(self, request, language_code, obj=None):
"""
Fetch the inline translations
"""
inline_instances = self.get_inline_instances(request, obj=obj)
for inline in inline_instances:
if issubclass(inline.model, TranslatableModelMixin):
# leverage inlineformset_factory() to find the ForeignKey.
# This also resolves the fk_name if it's set.
fk = inline.get_formset(request, obj).fk
rel_name = 'master__{0}'.format(fk.name)
filters = {
'language_code': language_code,
rel_name: obj
}
for translations_model in inline.model._parler_meta.get_all_models():
qs = translations_model.objects.filter(**filters)
if obj is not None:
qs = qs.using(obj._state.db)
yield inline, qs | [
"def",
"_get_inline_translations",
"(",
"self",
",",
"request",
",",
"language_code",
",",
"obj",
"=",
"None",
")",
":",
"inline_instances",
"=",
"self",
".",
"get_inline_instances",
"(",
"request",
",",
"obj",
"=",
"obj",
")",
"for",
"inline",
"in",
"inline... | Fetch the inline translations | [
"Fetch",
"the",
"inline",
"translations"
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L545-L567 | train | 211,705 |
django-parler/django-parler | parler/admin.py | TranslatableAdmin.default_change_form_template | def default_change_form_template(self):
"""
Determine what the actual `change_form_template` should be.
"""
opts = self.model._meta
app_label = opts.app_label
return select_template_name((
"admin/{0}/{1}/change_form.html".format(app_label, opts.object_name.lower()),
"admin/{0}/change_form.html".format(app_label),
"admin/change_form.html"
)) | python | def default_change_form_template(self):
"""
Determine what the actual `change_form_template` should be.
"""
opts = self.model._meta
app_label = opts.app_label
return select_template_name((
"admin/{0}/{1}/change_form.html".format(app_label, opts.object_name.lower()),
"admin/{0}/change_form.html".format(app_label),
"admin/change_form.html"
)) | [
"def",
"default_change_form_template",
"(",
"self",
")",
":",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"app_label",
"=",
"opts",
".",
"app_label",
"return",
"select_template_name",
"(",
"(",
"\"admin/{0}/{1}/change_form.html\"",
".",
"format",
"(",
"app_la... | Determine what the actual `change_form_template` should be. | [
"Determine",
"what",
"the",
"actual",
"change_form_template",
"should",
"be",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L570-L580 | train | 211,706 |
django-parler/django-parler | parler/admin.py | TranslatableInlineModelAdmin.get_formset | def get_formset(self, request, obj=None, **kwargs):
"""
Return the formset, and provide the language information to the formset.
"""
FormSet = super(TranslatableInlineModelAdmin, self).get_formset(request, obj, **kwargs)
# Existing objects already got the language code from the queryset().language() method.
# For new objects, the language code should be set here.
FormSet.language_code = self.get_form_language(request, obj)
if self.inline_tabs:
# Need to pass information to the template, this can only happen via the FormSet object.
available_languages = self.get_available_languages(obj, FormSet)
FormSet.language_tabs = self.get_language_tabs(request, obj, available_languages, css_class='parler-inline-language-tabs')
FormSet.language_tabs.allow_deletion = self._has_translatable_parent_model() # Views not available otherwise.
return FormSet | python | def get_formset(self, request, obj=None, **kwargs):
"""
Return the formset, and provide the language information to the formset.
"""
FormSet = super(TranslatableInlineModelAdmin, self).get_formset(request, obj, **kwargs)
# Existing objects already got the language code from the queryset().language() method.
# For new objects, the language code should be set here.
FormSet.language_code = self.get_form_language(request, obj)
if self.inline_tabs:
# Need to pass information to the template, this can only happen via the FormSet object.
available_languages = self.get_available_languages(obj, FormSet)
FormSet.language_tabs = self.get_language_tabs(request, obj, available_languages, css_class='parler-inline-language-tabs')
FormSet.language_tabs.allow_deletion = self._has_translatable_parent_model() # Views not available otherwise.
return FormSet | [
"def",
"get_formset",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"FormSet",
"=",
"super",
"(",
"TranslatableInlineModelAdmin",
",",
"self",
")",
".",
"get_formset",
"(",
"request",
",",
"obj",
",",
"*",
"*"... | Return the formset, and provide the language information to the formset. | [
"Return",
"the",
"formset",
"and",
"provide",
"the",
"language",
"information",
"to",
"the",
"formset",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L612-L627 | train | 211,707 |
django-parler/django-parler | parler/admin.py | TranslatableInlineModelAdmin.get_available_languages | def get_available_languages(self, obj, formset):
"""
Fetching the available inline languages as queryset.
"""
if obj:
# Inlines dictate language code, not the parent model.
# Hence, not looking at obj.get_available_languages(), but see what languages
# are used by the inline objects that point to it.
filter = {
'master__{0}'.format(formset.fk.name): obj
}
return self.model._parler_meta.root_model.objects.using(obj._state.db).filter(**filter) \
.values_list('language_code', flat=True).distinct().order_by('language_code')
else:
return self.model._parler_meta.root_model.objects.none() | python | def get_available_languages(self, obj, formset):
"""
Fetching the available inline languages as queryset.
"""
if obj:
# Inlines dictate language code, not the parent model.
# Hence, not looking at obj.get_available_languages(), but see what languages
# are used by the inline objects that point to it.
filter = {
'master__{0}'.format(formset.fk.name): obj
}
return self.model._parler_meta.root_model.objects.using(obj._state.db).filter(**filter) \
.values_list('language_code', flat=True).distinct().order_by('language_code')
else:
return self.model._parler_meta.root_model.objects.none() | [
"def",
"get_available_languages",
"(",
"self",
",",
"obj",
",",
"formset",
")",
":",
"if",
"obj",
":",
"# Inlines dictate language code, not the parent model.",
"# Hence, not looking at obj.get_available_languages(), but see what languages",
"# are used by the inline objects that point... | Fetching the available inline languages as queryset. | [
"Fetching",
"the",
"available",
"inline",
"languages",
"as",
"queryset",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L639-L653 | train | 211,708 |
django-parler/django-parler | parler/managers.py | TranslatableQuerySet.language | def language(self, language_code=None):
"""
Set the language code to assign to objects retrieved using this QuerySet.
"""
if language_code is None:
language_code = appsettings.PARLER_LANGUAGES.get_default_language()
self._language = language_code
return self | python | def language(self, language_code=None):
"""
Set the language code to assign to objects retrieved using this QuerySet.
"""
if language_code is None:
language_code = appsettings.PARLER_LANGUAGES.get_default_language()
self._language = language_code
return self | [
"def",
"language",
"(",
"self",
",",
"language_code",
"=",
"None",
")",
":",
"if",
"language_code",
"is",
"None",
":",
"language_code",
"=",
"appsettings",
".",
"PARLER_LANGUAGES",
".",
"get_default_language",
"(",
")",
"self",
".",
"_language",
"=",
"language... | Set the language code to assign to objects retrieved using this QuerySet. | [
"Set",
"the",
"language",
"code",
"to",
"assign",
"to",
"objects",
"retrieved",
"using",
"this",
"QuerySet",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/managers.py#L61-L69 | train | 211,709 |
django-parler/django-parler | parler/managers.py | TranslatableQuerySet.translated | def translated(self, *language_codes, **translated_fields):
"""
Only return translated objects which of the given languages.
When no language codes are given, only the currently active language is returned.
.. note::
Due to Django `ORM limitations <https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships>`_,
this method can't be combined with other filters that access the translated fields. As such, query the fields in one filter:
.. code-block:: python
qs.translated('en', name="Cheese Omelette")
This will query the translated model for the ``name`` field.
"""
relname = self.model._parler_meta.root_rel_name
if not language_codes:
language_codes = (get_language(),)
filters = {}
for field_name, val in six.iteritems(translated_fields):
if field_name.startswith('master__'):
filters[field_name[8:]] = val # avoid translations__master__ back and forth
else:
filters["{0}__{1}".format(relname, field_name)] = val
if len(language_codes) == 1:
filters[relname + '__language_code'] = language_codes[0]
return self.filter(**filters)
else:
filters[relname + '__language_code__in'] = language_codes
return self.filter(**filters).distinct() | python | def translated(self, *language_codes, **translated_fields):
"""
Only return translated objects which of the given languages.
When no language codes are given, only the currently active language is returned.
.. note::
Due to Django `ORM limitations <https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships>`_,
this method can't be combined with other filters that access the translated fields. As such, query the fields in one filter:
.. code-block:: python
qs.translated('en', name="Cheese Omelette")
This will query the translated model for the ``name`` field.
"""
relname = self.model._parler_meta.root_rel_name
if not language_codes:
language_codes = (get_language(),)
filters = {}
for field_name, val in six.iteritems(translated_fields):
if field_name.startswith('master__'):
filters[field_name[8:]] = val # avoid translations__master__ back and forth
else:
filters["{0}__{1}".format(relname, field_name)] = val
if len(language_codes) == 1:
filters[relname + '__language_code'] = language_codes[0]
return self.filter(**filters)
else:
filters[relname + '__language_code__in'] = language_codes
return self.filter(**filters).distinct() | [
"def",
"translated",
"(",
"self",
",",
"*",
"language_codes",
",",
"*",
"*",
"translated_fields",
")",
":",
"relname",
"=",
"self",
".",
"model",
".",
"_parler_meta",
".",
"root_rel_name",
"if",
"not",
"language_codes",
":",
"language_codes",
"=",
"(",
"get_... | Only return translated objects which of the given languages.
When no language codes are given, only the currently active language is returned.
.. note::
Due to Django `ORM limitations <https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships>`_,
this method can't be combined with other filters that access the translated fields. As such, query the fields in one filter:
.. code-block:: python
qs.translated('en', name="Cheese Omelette")
This will query the translated model for the ``name`` field. | [
"Only",
"return",
"translated",
"objects",
"which",
"of",
"the",
"given",
"languages",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/managers.py#L71-L105 | train | 211,710 |
django-parler/django-parler | parler/managers.py | TranslatableQuerySet.active_translations | def active_translations(self, language_code=None, **translated_fields):
"""
Only return objects which are translated, or have a fallback that should be displayed.
Typically that's the currently active language and fallback language.
This should be combined with ``.distinct()``.
When ``hide_untranslated = True``, only the currently active language will be returned.
"""
# Default: (language, fallback) when hide_translated == False
# Alternative: (language,) when hide_untranslated == True
language_codes = get_active_language_choices(language_code)
return self.translated(*language_codes, **translated_fields) | python | def active_translations(self, language_code=None, **translated_fields):
"""
Only return objects which are translated, or have a fallback that should be displayed.
Typically that's the currently active language and fallback language.
This should be combined with ``.distinct()``.
When ``hide_untranslated = True``, only the currently active language will be returned.
"""
# Default: (language, fallback) when hide_translated == False
# Alternative: (language,) when hide_untranslated == True
language_codes = get_active_language_choices(language_code)
return self.translated(*language_codes, **translated_fields) | [
"def",
"active_translations",
"(",
"self",
",",
"language_code",
"=",
"None",
",",
"*",
"*",
"translated_fields",
")",
":",
"# Default: (language, fallback) when hide_translated == False",
"# Alternative: (language,) when hide_untranslated == True",
"language_codes",
"... | Only return objects which are translated, or have a fallback that should be displayed.
Typically that's the currently active language and fallback language.
This should be combined with ``.distinct()``.
When ``hide_untranslated = True``, only the currently active language will be returned. | [
"Only",
"return",
"objects",
"which",
"are",
"translated",
"or",
"have",
"a",
"fallback",
"that",
"should",
"be",
"displayed",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/managers.py#L107-L119 | train | 211,711 |
django-parler/django-parler | parler/utils/i18n.py | get_language_title | def get_language_title(language_code):
"""
Return the verbose_name for a language code.
Fallback to language_code if language is not found in settings.
"""
from parler import appsettings
# Avoid weird lookup errors.
if not language_code:
raise ValueError("Missing language_code in get_language_title()")
if appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS:
# this allows to edit languages that are not enabled in current project but are already
# in database
languages = ALL_LANGUAGES_DICT
else:
languages = LANGUAGES_DICT
try:
return _(languages[language_code])
except KeyError:
language_code = language_code.split('-')[0] # e.g. if fr-ca is not supported fallback to fr
language_title = languages.get(language_code, None)
if language_title is not None:
return _(language_title)
else:
return language_code | python | def get_language_title(language_code):
"""
Return the verbose_name for a language code.
Fallback to language_code if language is not found in settings.
"""
from parler import appsettings
# Avoid weird lookup errors.
if not language_code:
raise ValueError("Missing language_code in get_language_title()")
if appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS:
# this allows to edit languages that are not enabled in current project but are already
# in database
languages = ALL_LANGUAGES_DICT
else:
languages = LANGUAGES_DICT
try:
return _(languages[language_code])
except KeyError:
language_code = language_code.split('-')[0] # e.g. if fr-ca is not supported fallback to fr
language_title = languages.get(language_code, None)
if language_title is not None:
return _(language_title)
else:
return language_code | [
"def",
"get_language_title",
"(",
"language_code",
")",
":",
"from",
"parler",
"import",
"appsettings",
"# Avoid weird lookup errors.",
"if",
"not",
"language_code",
":",
"raise",
"ValueError",
"(",
"\"Missing language_code in get_language_title()\"",
")",
"if",
"appsetting... | Return the verbose_name for a language code.
Fallback to language_code if language is not found in settings. | [
"Return",
"the",
"verbose_name",
"for",
"a",
"language",
"code",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/utils/i18n.py#L44-L70 | train | 211,712 |
django-parler/django-parler | parler/utils/i18n.py | is_multilingual_project | def is_multilingual_project(site_id=None):
"""
Whether the current Django project is configured for multilingual support.
"""
from parler import appsettings
if site_id is None:
site_id = getattr(settings, 'SITE_ID', None)
return appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS or site_id in appsettings.PARLER_LANGUAGES | python | def is_multilingual_project(site_id=None):
"""
Whether the current Django project is configured for multilingual support.
"""
from parler import appsettings
if site_id is None:
site_id = getattr(settings, 'SITE_ID', None)
return appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS or site_id in appsettings.PARLER_LANGUAGES | [
"def",
"is_multilingual_project",
"(",
"site_id",
"=",
"None",
")",
":",
"from",
"parler",
"import",
"appsettings",
"if",
"site_id",
"is",
"None",
":",
"site_id",
"=",
"getattr",
"(",
"settings",
",",
"'SITE_ID'",
",",
"None",
")",
"return",
"appsettings",
"... | Whether the current Django project is configured for multilingual support. | [
"Whether",
"the",
"current",
"Django",
"project",
"is",
"configured",
"for",
"multilingual",
"support",
"."
] | 11ae4af5e8faddb74c69c848870122df4006a54e | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/utils/i18n.py#L94-L101 | train | 211,713 |
matiasb/unpy2exe | unpy2exe.py | __timestamp | def __timestamp():
"""Generate timestamp data for pyc header."""
today = time.time()
ret = struct.pack(b'=L', int(today))
return ret | python | def __timestamp():
"""Generate timestamp data for pyc header."""
today = time.time()
ret = struct.pack(b'=L', int(today))
return ret | [
"def",
"__timestamp",
"(",
")",
":",
"today",
"=",
"time",
".",
"time",
"(",
")",
"ret",
"=",
"struct",
".",
"pack",
"(",
"b'=L'",
",",
"int",
"(",
"today",
")",
")",
"return",
"ret"
] | Generate timestamp data for pyc header. | [
"Generate",
"timestamp",
"data",
"for",
"pyc",
"header",
"."
] | 7a579f323e2b46ec925281ede9d913b81aa7b781 | https://github.com/matiasb/unpy2exe/blob/7a579f323e2b46ec925281ede9d913b81aa7b781/unpy2exe.py#L49-L53 | train | 211,714 |
matiasb/unpy2exe | unpy2exe.py | _get_scripts_resource | def _get_scripts_resource(pe):
"""Return the PYTHONSCRIPT resource entry."""
res = None
for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries:
if entry.name and entry.name.string == b"PYTHONSCRIPT":
res = entry.directory.entries[0].directory.entries[0]
break
return res | python | def _get_scripts_resource(pe):
"""Return the PYTHONSCRIPT resource entry."""
res = None
for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries:
if entry.name and entry.name.string == b"PYTHONSCRIPT":
res = entry.directory.entries[0].directory.entries[0]
break
return res | [
"def",
"_get_scripts_resource",
"(",
"pe",
")",
":",
"res",
"=",
"None",
"for",
"entry",
"in",
"pe",
".",
"DIRECTORY_ENTRY_RESOURCE",
".",
"entries",
":",
"if",
"entry",
".",
"name",
"and",
"entry",
".",
"name",
".",
"string",
"==",
"b\"PYTHONSCRIPT\"",
":... | Return the PYTHONSCRIPT resource entry. | [
"Return",
"the",
"PYTHONSCRIPT",
"resource",
"entry",
"."
] | 7a579f323e2b46ec925281ede9d913b81aa7b781 | https://github.com/matiasb/unpy2exe/blob/7a579f323e2b46ec925281ede9d913b81aa7b781/unpy2exe.py#L67-L74 | train | 211,715 |
matiasb/unpy2exe | unpy2exe.py | _resource_dump | def _resource_dump(pe, res):
"""Return the dump of the given resource."""
rva = res.data.struct.OffsetToData
size = res.data.struct.Size
dump = pe.get_data(rva, size)
return dump | python | def _resource_dump(pe, res):
"""Return the dump of the given resource."""
rva = res.data.struct.OffsetToData
size = res.data.struct.Size
dump = pe.get_data(rva, size)
return dump | [
"def",
"_resource_dump",
"(",
"pe",
",",
"res",
")",
":",
"rva",
"=",
"res",
".",
"data",
".",
"struct",
".",
"OffsetToData",
"size",
"=",
"res",
".",
"data",
".",
"struct",
".",
"Size",
"dump",
"=",
"pe",
".",
"get_data",
"(",
"rva",
",",
"size",
... | Return the dump of the given resource. | [
"Return",
"the",
"dump",
"of",
"the",
"given",
"resource",
"."
] | 7a579f323e2b46ec925281ede9d913b81aa7b781 | https://github.com/matiasb/unpy2exe/blob/7a579f323e2b46ec925281ede9d913b81aa7b781/unpy2exe.py#L77-L83 | train | 211,716 |
matiasb/unpy2exe | unpy2exe.py | _get_co_from_dump | def _get_co_from_dump(data):
"""Return the code objects from the dump."""
# Read py2exe header
current = struct.calcsize(b'iiii')
metadata = struct.unpack(b'iiii', data[:current])
# check py2exe magic number
# assert(metadata[0] == 0x78563412)
logging.info("Magic value: %x", metadata[0])
logging.info("Code bytes length: %d", metadata[3])
arcname = ''
while six.indexbytes(data, current) != 0:
arcname += chr(six.indexbytes(data, current))
current += 1
logging.info("Archive name: %s", arcname or '-')
code_bytes = data[current + 1:]
# verify code bytes count and metadata info
# assert(len(code_bytes) == metadata[3])
code_objects = marshal.loads(code_bytes)
return code_objects | python | def _get_co_from_dump(data):
"""Return the code objects from the dump."""
# Read py2exe header
current = struct.calcsize(b'iiii')
metadata = struct.unpack(b'iiii', data[:current])
# check py2exe magic number
# assert(metadata[0] == 0x78563412)
logging.info("Magic value: %x", metadata[0])
logging.info("Code bytes length: %d", metadata[3])
arcname = ''
while six.indexbytes(data, current) != 0:
arcname += chr(six.indexbytes(data, current))
current += 1
logging.info("Archive name: %s", arcname or '-')
code_bytes = data[current + 1:]
# verify code bytes count and metadata info
# assert(len(code_bytes) == metadata[3])
code_objects = marshal.loads(code_bytes)
return code_objects | [
"def",
"_get_co_from_dump",
"(",
"data",
")",
":",
"# Read py2exe header",
"current",
"=",
"struct",
".",
"calcsize",
"(",
"b'iiii'",
")",
"metadata",
"=",
"struct",
".",
"unpack",
"(",
"b'iiii'",
",",
"data",
"[",
":",
"current",
"]",
")",
"# check py2exe m... | Return the code objects from the dump. | [
"Return",
"the",
"code",
"objects",
"from",
"the",
"dump",
"."
] | 7a579f323e2b46ec925281ede9d913b81aa7b781 | https://github.com/matiasb/unpy2exe/blob/7a579f323e2b46ec925281ede9d913b81aa7b781/unpy2exe.py#L86-L108 | train | 211,717 |
matiasb/unpy2exe | unpy2exe.py | check_py2exe_file | def check_py2exe_file(pe):
"""Check file is a py2exe executable."""
py2exe_resource = _get_scripts_resource(pe)
if py2exe_resource is None:
logging.info('This is not a py2exe executable.')
if pe.__data__.find(b'pyi-windows-manifest-filename'):
logging.info('This seems a pyinstaller executable (unsupported).')
return bool(py2exe_resource) | python | def check_py2exe_file(pe):
"""Check file is a py2exe executable."""
py2exe_resource = _get_scripts_resource(pe)
if py2exe_resource is None:
logging.info('This is not a py2exe executable.')
if pe.__data__.find(b'pyi-windows-manifest-filename'):
logging.info('This seems a pyinstaller executable (unsupported).')
return bool(py2exe_resource) | [
"def",
"check_py2exe_file",
"(",
"pe",
")",
":",
"py2exe_resource",
"=",
"_get_scripts_resource",
"(",
"pe",
")",
"if",
"py2exe_resource",
"is",
"None",
":",
"logging",
".",
"info",
"(",
"'This is not a py2exe executable.'",
")",
"if",
"pe",
".",
"__data__",
"."... | Check file is a py2exe executable. | [
"Check",
"file",
"is",
"a",
"py2exe",
"executable",
"."
] | 7a579f323e2b46ec925281ede9d913b81aa7b781 | https://github.com/matiasb/unpy2exe/blob/7a579f323e2b46ec925281ede9d913b81aa7b781/unpy2exe.py#L111-L120 | train | 211,718 |
matiasb/unpy2exe | unpy2exe.py | extract_code_objects | def extract_code_objects(pe):
"""Extract Python code objects from a py2exe executable."""
script_res = _get_scripts_resource(pe)
dump = _resource_dump(pe, script_res)
return _get_co_from_dump(dump) | python | def extract_code_objects(pe):
"""Extract Python code objects from a py2exe executable."""
script_res = _get_scripts_resource(pe)
dump = _resource_dump(pe, script_res)
return _get_co_from_dump(dump) | [
"def",
"extract_code_objects",
"(",
"pe",
")",
":",
"script_res",
"=",
"_get_scripts_resource",
"(",
"pe",
")",
"dump",
"=",
"_resource_dump",
"(",
"pe",
",",
"script_res",
")",
"return",
"_get_co_from_dump",
"(",
"dump",
")"
] | Extract Python code objects from a py2exe executable. | [
"Extract",
"Python",
"code",
"objects",
"from",
"a",
"py2exe",
"executable",
"."
] | 7a579f323e2b46ec925281ede9d913b81aa7b781 | https://github.com/matiasb/unpy2exe/blob/7a579f323e2b46ec925281ede9d913b81aa7b781/unpy2exe.py#L123-L127 | train | 211,719 |
matiasb/unpy2exe | unpy2exe.py | dump_to_pyc | def dump_to_pyc(co, python_version, output_dir):
"""Save given code_object as a .pyc file."""
# assume Windows path information from the .exe
pyc_basename = ntpath.basename(co.co_filename)
pyc_name = pyc_basename + '.pyc'
if pyc_name not in IGNORE:
logging.info("Extracting %s", pyc_name)
pyc_header = _generate_pyc_header(python_version, len(co.co_code))
destination = os.path.join(output_dir, pyc_name)
pyc = open(destination, 'wb')
pyc.write(pyc_header)
marshaled_code = marshal.dumps(co)
pyc.write(marshaled_code)
pyc.close()
else:
logging.info("Skipping %s", pyc_name) | python | def dump_to_pyc(co, python_version, output_dir):
"""Save given code_object as a .pyc file."""
# assume Windows path information from the .exe
pyc_basename = ntpath.basename(co.co_filename)
pyc_name = pyc_basename + '.pyc'
if pyc_name not in IGNORE:
logging.info("Extracting %s", pyc_name)
pyc_header = _generate_pyc_header(python_version, len(co.co_code))
destination = os.path.join(output_dir, pyc_name)
pyc = open(destination, 'wb')
pyc.write(pyc_header)
marshaled_code = marshal.dumps(co)
pyc.write(marshaled_code)
pyc.close()
else:
logging.info("Skipping %s", pyc_name) | [
"def",
"dump_to_pyc",
"(",
"co",
",",
"python_version",
",",
"output_dir",
")",
":",
"# assume Windows path information from the .exe",
"pyc_basename",
"=",
"ntpath",
".",
"basename",
"(",
"co",
".",
"co_filename",
")",
"pyc_name",
"=",
"pyc_basename",
"+",
"'.pyc'"... | Save given code_object as a .pyc file. | [
"Save",
"given",
"code_object",
"as",
"a",
".",
"pyc",
"file",
"."
] | 7a579f323e2b46ec925281ede9d913b81aa7b781 | https://github.com/matiasb/unpy2exe/blob/7a579f323e2b46ec925281ede9d913b81aa7b781/unpy2exe.py#L145-L161 | train | 211,720 |
matiasb/unpy2exe | unpy2exe.py | unpy2exe | def unpy2exe(filename, python_version=None, output_dir=None):
"""Process input params and produce output pyc files."""
if output_dir is None:
output_dir = '.'
elif not os.path.exists(output_dir):
os.makedirs(output_dir)
pe = pefile.PE(filename)
is_py2exe = check_py2exe_file(pe)
if not is_py2exe:
raise ValueError('Not a py2exe executable.')
code_objects = extract_code_objects(pe)
for co in code_objects:
dump_to_pyc(co, python_version, output_dir) | python | def unpy2exe(filename, python_version=None, output_dir=None):
"""Process input params and produce output pyc files."""
if output_dir is None:
output_dir = '.'
elif not os.path.exists(output_dir):
os.makedirs(output_dir)
pe = pefile.PE(filename)
is_py2exe = check_py2exe_file(pe)
if not is_py2exe:
raise ValueError('Not a py2exe executable.')
code_objects = extract_code_objects(pe)
for co in code_objects:
dump_to_pyc(co, python_version, output_dir) | [
"def",
"unpy2exe",
"(",
"filename",
",",
"python_version",
"=",
"None",
",",
"output_dir",
"=",
"None",
")",
":",
"if",
"output_dir",
"is",
"None",
":",
"output_dir",
"=",
"'.'",
"elif",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"output_dir",
")",
... | Process input params and produce output pyc files. | [
"Process",
"input",
"params",
"and",
"produce",
"output",
"pyc",
"files",
"."
] | 7a579f323e2b46ec925281ede9d913b81aa7b781 | https://github.com/matiasb/unpy2exe/blob/7a579f323e2b46ec925281ede9d913b81aa7b781/unpy2exe.py#L164-L179 | train | 211,721 |
UAVCAN/pyuavcan | uavcan/app/node_monitor.py | NodeMonitor.are_all_nodes_discovered | def are_all_nodes_discovered(self):
"""Reports whether there are nodes whose node info is still unknown."""
undiscovered = self.find_all(lambda e: not e.discovered)
return len(list(undiscovered)) == 0 | python | def are_all_nodes_discovered(self):
"""Reports whether there are nodes whose node info is still unknown."""
undiscovered = self.find_all(lambda e: not e.discovered)
return len(list(undiscovered)) == 0 | [
"def",
"are_all_nodes_discovered",
"(",
"self",
")",
":",
"undiscovered",
"=",
"self",
".",
"find_all",
"(",
"lambda",
"e",
":",
"not",
"e",
".",
"discovered",
")",
"return",
"len",
"(",
"list",
"(",
"undiscovered",
")",
")",
"==",
"0"
] | Reports whether there are nodes whose node info is still unknown. | [
"Reports",
"whether",
"there",
"are",
"nodes",
"whose",
"node",
"info",
"is",
"still",
"unknown",
"."
] | a06a9975c1c0de4f1d469f05b29b374332968e2b | https://github.com/UAVCAN/pyuavcan/blob/a06a9975c1c0de4f1d469f05b29b374332968e2b/uavcan/app/node_monitor.py#L144-L147 | train | 211,722 |
UAVCAN/pyuavcan | uavcan/__init__.py | Namespace._path | def _path(self, attrpath):
"""Returns the namespace object at the given .-separated path,
creating any namespaces in the path that don't already exist."""
attr, _, subpath = attrpath.partition(".")
if attr not in self.__dict__:
self.__dict__[attr] = Namespace()
self.__namespaces.add(attr)
if subpath:
return self.__dict__[attr]._path(subpath)
else:
return self.__dict__[attr] | python | def _path(self, attrpath):
"""Returns the namespace object at the given .-separated path,
creating any namespaces in the path that don't already exist."""
attr, _, subpath = attrpath.partition(".")
if attr not in self.__dict__:
self.__dict__[attr] = Namespace()
self.__namespaces.add(attr)
if subpath:
return self.__dict__[attr]._path(subpath)
else:
return self.__dict__[attr] | [
"def",
"_path",
"(",
"self",
",",
"attrpath",
")",
":",
"attr",
",",
"_",
",",
"subpath",
"=",
"attrpath",
".",
"partition",
"(",
"\".\"",
")",
"if",
"attr",
"not",
"in",
"self",
".",
"__dict__",
":",
"self",
".",
"__dict__",
"[",
"attr",
"]",
"=",... | Returns the namespace object at the given .-separated path,
creating any namespaces in the path that don't already exist. | [
"Returns",
"the",
"namespace",
"object",
"at",
"the",
"given",
".",
"-",
"separated",
"path",
"creating",
"any",
"namespaces",
"in",
"the",
"path",
"that",
"don",
"t",
"already",
"exist",
"."
] | a06a9975c1c0de4f1d469f05b29b374332968e2b | https://github.com/UAVCAN/pyuavcan/blob/a06a9975c1c0de4f1d469f05b29b374332968e2b/uavcan/__init__.py#L80-L92 | train | 211,723 |
UAVCAN/pyuavcan | uavcan/dsdl/signature.py | Signature.add | def add(self, data_bytes):
'''Feed ASCII string or bytes to the signature function'''
try:
if isinstance(data_bytes, basestring): # Python 2.7 compatibility
data_bytes = map(ord, data_bytes)
except NameError:
if isinstance(data_bytes, str): # This branch will be taken on Python 3
data_bytes = map(ord, data_bytes)
for b in data_bytes:
self._crc ^= (b << 56) & Signature.MASK64
for _ in range(8):
if self._crc & (1 << 63):
self._crc = ((self._crc << 1) & Signature.MASK64) ^ Signature.POLY
else:
self._crc <<= 1 | python | def add(self, data_bytes):
'''Feed ASCII string or bytes to the signature function'''
try:
if isinstance(data_bytes, basestring): # Python 2.7 compatibility
data_bytes = map(ord, data_bytes)
except NameError:
if isinstance(data_bytes, str): # This branch will be taken on Python 3
data_bytes = map(ord, data_bytes)
for b in data_bytes:
self._crc ^= (b << 56) & Signature.MASK64
for _ in range(8):
if self._crc & (1 << 63):
self._crc = ((self._crc << 1) & Signature.MASK64) ^ Signature.POLY
else:
self._crc <<= 1 | [
"def",
"add",
"(",
"self",
",",
"data_bytes",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"data_bytes",
",",
"basestring",
")",
":",
"# Python 2.7 compatibility",
"data_bytes",
"=",
"map",
"(",
"ord",
",",
"data_bytes",
")",
"except",
"NameError",
":",
... | Feed ASCII string or bytes to the signature function | [
"Feed",
"ASCII",
"string",
"or",
"bytes",
"to",
"the",
"signature",
"function"
] | a06a9975c1c0de4f1d469f05b29b374332968e2b | https://github.com/UAVCAN/pyuavcan/blob/a06a9975c1c0de4f1d469f05b29b374332968e2b/uavcan/dsdl/signature.py#L39-L54 | train | 211,724 |
UAVCAN/pyuavcan | uavcan/dsdl/parser.py | ArrayType.get_max_bitlen | def get_max_bitlen(self):
"""Returns total maximum bit length of the array, including length field if applicable."""
payload_max_bitlen = self.max_size * self.value_type.get_max_bitlen()
return {
self.MODE_DYNAMIC: payload_max_bitlen + self.max_size.bit_length(),
self.MODE_STATIC: payload_max_bitlen
}[self.mode] | python | def get_max_bitlen(self):
"""Returns total maximum bit length of the array, including length field if applicable."""
payload_max_bitlen = self.max_size * self.value_type.get_max_bitlen()
return {
self.MODE_DYNAMIC: payload_max_bitlen + self.max_size.bit_length(),
self.MODE_STATIC: payload_max_bitlen
}[self.mode] | [
"def",
"get_max_bitlen",
"(",
"self",
")",
":",
"payload_max_bitlen",
"=",
"self",
".",
"max_size",
"*",
"self",
".",
"value_type",
".",
"get_max_bitlen",
"(",
")",
"return",
"{",
"self",
".",
"MODE_DYNAMIC",
":",
"payload_max_bitlen",
"+",
"self",
".",
"max... | Returns total maximum bit length of the array, including length field if applicable. | [
"Returns",
"total",
"maximum",
"bit",
"length",
"of",
"the",
"array",
"including",
"length",
"field",
"if",
"applicable",
"."
] | a06a9975c1c0de4f1d469f05b29b374332968e2b | https://github.com/UAVCAN/pyuavcan/blob/a06a9975c1c0de4f1d469f05b29b374332968e2b/uavcan/dsdl/parser.py#L154-L160 | train | 211,725 |
UAVCAN/pyuavcan | uavcan/dsdl/parser.py | CompoundType.get_dsdl_signature_source_definition | def get_dsdl_signature_source_definition(self):
"""
Returns normalized DSDL definition text.
Please refer to the specification for details about normalized DSDL definitions.
"""
txt = StringIO()
txt.write(self.full_name + '\n')
def adjoin(attrs):
return txt.write('\n'.join(x.get_normalized_definition() for x in attrs) + '\n')
if self.kind == CompoundType.KIND_SERVICE:
if self.request_union:
txt.write('\n@union\n')
adjoin(self.request_fields)
txt.write('\n---\n')
if self.response_union:
txt.write('\n@union\n')
adjoin(self.response_fields)
elif self.kind == CompoundType.KIND_MESSAGE:
if self.union:
txt.write('\n@union\n')
adjoin(self.fields)
else:
error('Compound type of unknown kind [%s]', self.kind)
return txt.getvalue().strip().replace('\n\n\n', '\n').replace('\n\n', '\n') | python | def get_dsdl_signature_source_definition(self):
"""
Returns normalized DSDL definition text.
Please refer to the specification for details about normalized DSDL definitions.
"""
txt = StringIO()
txt.write(self.full_name + '\n')
def adjoin(attrs):
return txt.write('\n'.join(x.get_normalized_definition() for x in attrs) + '\n')
if self.kind == CompoundType.KIND_SERVICE:
if self.request_union:
txt.write('\n@union\n')
adjoin(self.request_fields)
txt.write('\n---\n')
if self.response_union:
txt.write('\n@union\n')
adjoin(self.response_fields)
elif self.kind == CompoundType.KIND_MESSAGE:
if self.union:
txt.write('\n@union\n')
adjoin(self.fields)
else:
error('Compound type of unknown kind [%s]', self.kind)
return txt.getvalue().strip().replace('\n\n\n', '\n').replace('\n\n', '\n') | [
"def",
"get_dsdl_signature_source_definition",
"(",
"self",
")",
":",
"txt",
"=",
"StringIO",
"(",
")",
"txt",
".",
"write",
"(",
"self",
".",
"full_name",
"+",
"'\\n'",
")",
"def",
"adjoin",
"(",
"attrs",
")",
":",
"return",
"txt",
".",
"write",
"(",
... | Returns normalized DSDL definition text.
Please refer to the specification for details about normalized DSDL definitions. | [
"Returns",
"normalized",
"DSDL",
"definition",
"text",
".",
"Please",
"refer",
"to",
"the",
"specification",
"for",
"details",
"about",
"normalized",
"DSDL",
"definitions",
"."
] | a06a9975c1c0de4f1d469f05b29b374332968e2b | https://github.com/UAVCAN/pyuavcan/blob/a06a9975c1c0de4f1d469f05b29b374332968e2b/uavcan/dsdl/parser.py#L269-L294 | train | 211,726 |
UAVCAN/pyuavcan | uavcan/dsdl/parser.py | CompoundType.get_data_type_signature | def get_data_type_signature(self):
"""
Computes data type signature of this type. The data type signature is
guaranteed to match only if all nested data structures are compatible.
Please refer to the specification for details about signatures.
"""
if self._data_type_signature is None:
sig = Signature(self.get_dsdl_signature())
fields = self.request_fields + self.response_fields if self.kind == CompoundType.KIND_SERVICE else self.fields
for field in fields:
field_sig = field.type.get_data_type_signature()
if field_sig is not None:
sig_value = sig.get_value()
sig.add(bytes_from_crc64(field_sig))
sig.add(bytes_from_crc64(sig_value))
self._data_type_signature = sig.get_value()
return self._data_type_signature | python | def get_data_type_signature(self):
"""
Computes data type signature of this type. The data type signature is
guaranteed to match only if all nested data structures are compatible.
Please refer to the specification for details about signatures.
"""
if self._data_type_signature is None:
sig = Signature(self.get_dsdl_signature())
fields = self.request_fields + self.response_fields if self.kind == CompoundType.KIND_SERVICE else self.fields
for field in fields:
field_sig = field.type.get_data_type_signature()
if field_sig is not None:
sig_value = sig.get_value()
sig.add(bytes_from_crc64(field_sig))
sig.add(bytes_from_crc64(sig_value))
self._data_type_signature = sig.get_value()
return self._data_type_signature | [
"def",
"get_data_type_signature",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_type_signature",
"is",
"None",
":",
"sig",
"=",
"Signature",
"(",
"self",
".",
"get_dsdl_signature",
"(",
")",
")",
"fields",
"=",
"self",
".",
"request_fields",
"+",
"self",
... | Computes data type signature of this type. The data type signature is
guaranteed to match only if all nested data structures are compatible.
Please refer to the specification for details about signatures. | [
"Computes",
"data",
"type",
"signature",
"of",
"this",
"type",
".",
"The",
"data",
"type",
"signature",
"is",
"guaranteed",
"to",
"match",
"only",
"if",
"all",
"nested",
"data",
"structures",
"are",
"compatible",
".",
"Please",
"refer",
"to",
"the",
"specifi... | a06a9975c1c0de4f1d469f05b29b374332968e2b | https://github.com/UAVCAN/pyuavcan/blob/a06a9975c1c0de4f1d469f05b29b374332968e2b/uavcan/dsdl/parser.py#L307-L323 | train | 211,727 |
UAVCAN/pyuavcan | uavcan/app/dynamic_node_id.py | CentralizedServer.close | def close(self):
"""Stops the instance and closes the allocation table storage.
"""
self._handle.remove()
self._node_monitor_event_handle.remove()
self._allocation_table.close() | python | def close(self):
"""Stops the instance and closes the allocation table storage.
"""
self._handle.remove()
self._node_monitor_event_handle.remove()
self._allocation_table.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_handle",
".",
"remove",
"(",
")",
"self",
".",
"_node_monitor_event_handle",
".",
"remove",
"(",
")",
"self",
".",
"_allocation_table",
".",
"close",
"(",
")"
] | Stops the instance and closes the allocation table storage. | [
"Stops",
"the",
"instance",
"and",
"closes",
"the",
"allocation",
"table",
"storage",
"."
] | a06a9975c1c0de4f1d469f05b29b374332968e2b | https://github.com/UAVCAN/pyuavcan/blob/a06a9975c1c0de4f1d469f05b29b374332968e2b/uavcan/app/dynamic_node_id.py#L123-L128 | train | 211,728 |
UAVCAN/pyuavcan | uavcan/dsdl/common.py | pretty_filename | def pretty_filename(filename):
'''Returns a nice human readable path to 'filename'.'''
try:
a = os.path.abspath(filename)
r = os.path.relpath(filename)
except ValueError:
# Catch relpath exception. Happens, because it can not produce relative path
# if wroking directory is on different drive.
a = r = filename
return a if '..' in r else r | python | def pretty_filename(filename):
'''Returns a nice human readable path to 'filename'.'''
try:
a = os.path.abspath(filename)
r = os.path.relpath(filename)
except ValueError:
# Catch relpath exception. Happens, because it can not produce relative path
# if wroking directory is on different drive.
a = r = filename
return a if '..' in r else r | [
"def",
"pretty_filename",
"(",
"filename",
")",
":",
"try",
":",
"a",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"r",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"filename",
")",
"except",
"ValueError",
":",
"# Catch relpath exception... | Returns a nice human readable path to 'filename'. | [
"Returns",
"a",
"nice",
"human",
"readable",
"path",
"to",
"filename",
"."
] | a06a9975c1c0de4f1d469f05b29b374332968e2b | https://github.com/UAVCAN/pyuavcan/blob/a06a9975c1c0de4f1d469f05b29b374332968e2b/uavcan/dsdl/common.py#L38-L47 | train | 211,729 |
awslabs/mxboard | python/mxboard/event_file_writer.py | EventsWriter.write_event | def write_event(self, event):
"""Appends event to the file."""
# Check if event is of type event_pb2.Event proto.
if not isinstance(event, event_pb2.Event):
raise TypeError("expected an event_pb2.Event proto, "
" but got %s" % type(event))
return self._write_serialized_event(event.SerializeToString()) | python | def write_event(self, event):
"""Appends event to the file."""
# Check if event is of type event_pb2.Event proto.
if not isinstance(event, event_pb2.Event):
raise TypeError("expected an event_pb2.Event proto, "
" but got %s" % type(event))
return self._write_serialized_event(event.SerializeToString()) | [
"def",
"write_event",
"(",
"self",
",",
"event",
")",
":",
"# Check if event is of type event_pb2.Event proto.",
"if",
"not",
"isinstance",
"(",
"event",
",",
"event_pb2",
".",
"Event",
")",
":",
"raise",
"TypeError",
"(",
"\"expected an event_pb2.Event proto, \"",
"\... | Appends event to the file. | [
"Appends",
"event",
"to",
"the",
"file",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/event_file_writer.py#L78-L84 | train | 211,730 |
awslabs/mxboard | python/mxboard/event_file_writer.py | EventsWriter.flush | def flush(self):
"""Flushes the event file to disk."""
if self._num_outstanding_events == 0 or self._recordio_writer is None:
return
self._recordio_writer.flush()
if self._logger is not None:
self._logger.info('wrote %d %s to disk', self._num_outstanding_events,
'event' if self._num_outstanding_events == 1 else 'events')
self._num_outstanding_events = 0 | python | def flush(self):
"""Flushes the event file to disk."""
if self._num_outstanding_events == 0 or self._recordio_writer is None:
return
self._recordio_writer.flush()
if self._logger is not None:
self._logger.info('wrote %d %s to disk', self._num_outstanding_events,
'event' if self._num_outstanding_events == 1 else 'events')
self._num_outstanding_events = 0 | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"_num_outstanding_events",
"==",
"0",
"or",
"self",
".",
"_recordio_writer",
"is",
"None",
":",
"return",
"self",
".",
"_recordio_writer",
".",
"flush",
"(",
")",
"if",
"self",
".",
"_logger",
"is... | Flushes the event file to disk. | [
"Flushes",
"the",
"event",
"file",
"to",
"disk",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/event_file_writer.py#L92-L100 | train | 211,731 |
awslabs/mxboard | python/mxboard/event_file_writer.py | EventsWriter.close | def close(self):
"""Flushes the pending events and closes the writer after it is done."""
self.flush()
if self._recordio_writer is not None:
self._recordio_writer.close()
self._recordio_writer = None | python | def close(self):
"""Flushes the pending events and closes the writer after it is done."""
self.flush()
if self._recordio_writer is not None:
self._recordio_writer.close()
self._recordio_writer = None | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"flush",
"(",
")",
"if",
"self",
".",
"_recordio_writer",
"is",
"not",
"None",
":",
"self",
".",
"_recordio_writer",
".",
"close",
"(",
")",
"self",
".",
"_recordio_writer",
"=",
"None"
] | Flushes the pending events and closes the writer after it is done. | [
"Flushes",
"the",
"pending",
"events",
"and",
"closes",
"the",
"writer",
"after",
"it",
"is",
"done",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/event_file_writer.py#L102-L107 | train | 211,732 |
awslabs/mxboard | python/mxboard/event_file_writer.py | EventFileWriter.close | def close(self):
"""Flushes the event file to disk and close the file.
Call this method when you do not need the summary writer anymore.
"""
if not self._closed:
self.add_event(self._sentinel_event)
self.flush()
self._worker.join()
self._ev_writer.close()
self._closed = True | python | def close(self):
"""Flushes the event file to disk and close the file.
Call this method when you do not need the summary writer anymore.
"""
if not self._closed:
self.add_event(self._sentinel_event)
self.flush()
self._worker.join()
self._ev_writer.close()
self._closed = True | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_closed",
":",
"self",
".",
"add_event",
"(",
"self",
".",
"_sentinel_event",
")",
"self",
".",
"flush",
"(",
")",
"self",
".",
"_worker",
".",
"join",
"(",
")",
"self",
".",
"_ev_wr... | Flushes the event file to disk and close the file.
Call this method when you do not need the summary writer anymore. | [
"Flushes",
"the",
"event",
"file",
"to",
"disk",
"and",
"close",
"the",
"file",
".",
"Call",
"this",
"method",
"when",
"you",
"do",
"not",
"need",
"the",
"summary",
"writer",
"anymore",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/event_file_writer.py#L175-L184 | train | 211,733 |
awslabs/mxboard | python/mxboard/record_writer.py | RecordWriter.write_record | def write_record(self, event_str):
"""Writes a serialized event to file."""
header = struct.pack('Q', len(event_str))
header += struct.pack('I', masked_crc32c(header))
footer = struct.pack('I', masked_crc32c(event_str))
self._writer.write(header + event_str + footer) | python | def write_record(self, event_str):
"""Writes a serialized event to file."""
header = struct.pack('Q', len(event_str))
header += struct.pack('I', masked_crc32c(header))
footer = struct.pack('I', masked_crc32c(event_str))
self._writer.write(header + event_str + footer) | [
"def",
"write_record",
"(",
"self",
",",
"event_str",
")",
":",
"header",
"=",
"struct",
".",
"pack",
"(",
"'Q'",
",",
"len",
"(",
"event_str",
")",
")",
"header",
"+=",
"struct",
".",
"pack",
"(",
"'I'",
",",
"masked_crc32c",
"(",
"header",
")",
")"... | Writes a serialized event to file. | [
"Writes",
"a",
"serialized",
"event",
"to",
"file",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/record_writer.py#L47-L52 | train | 211,734 |
awslabs/mxboard | python/mxboard/record_writer.py | RecordWriter.close | def close(self):
"""Closes the record writer."""
if self._writer is not None:
self.flush()
self._writer.close()
self._writer = None | python | def close(self):
"""Closes the record writer."""
if self._writer is not None:
self.flush()
self._writer.close()
self._writer = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_writer",
"is",
"not",
"None",
":",
"self",
".",
"flush",
"(",
")",
"self",
".",
"_writer",
".",
"close",
"(",
")",
"self",
".",
"_writer",
"=",
"None"
] | Closes the record writer. | [
"Closes",
"the",
"record",
"writer",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/record_writer.py#L59-L64 | train | 211,735 |
awslabs/mxboard | python/mxboard/writer.py | SummaryToEventTransformer.add_summary | def add_summary(self, summary, global_step=None):
"""Adds a `Summary` protocol buffer to the event file.
This method wraps the provided summary in an `Event` protocol buffer and adds it
to the event file.
Parameters
----------
summary : A `Summary` protocol buffer
Optionally serialized as a string.
global_step: Number
Optional global step value to record with the summary.
"""
if isinstance(summary, bytes):
summ = summary_pb2.Summary()
summ.ParseFromString(summary)
summary = summ
# We strip metadata from values with tags that we have seen before in order
# to save space - we just store the metadata on the first value with a
# specific tag.
for value in summary.value:
if not value.metadata:
continue
if value.tag in self._seen_summary_tags:
# This tag has been encountered before. Strip the metadata.
value.ClearField("metadata")
continue
# We encounter a value with a tag we have not encountered previously. And
# it has metadata. Remember to strip metadata from future values with this
# tag string.
self._seen_summary_tags.add(value.tag)
event = event_pb2.Event(summary=summary)
self._add_event(event, global_step) | python | def add_summary(self, summary, global_step=None):
"""Adds a `Summary` protocol buffer to the event file.
This method wraps the provided summary in an `Event` protocol buffer and adds it
to the event file.
Parameters
----------
summary : A `Summary` protocol buffer
Optionally serialized as a string.
global_step: Number
Optional global step value to record with the summary.
"""
if isinstance(summary, bytes):
summ = summary_pb2.Summary()
summ.ParseFromString(summary)
summary = summ
# We strip metadata from values with tags that we have seen before in order
# to save space - we just store the metadata on the first value with a
# specific tag.
for value in summary.value:
if not value.metadata:
continue
if value.tag in self._seen_summary_tags:
# This tag has been encountered before. Strip the metadata.
value.ClearField("metadata")
continue
# We encounter a value with a tag we have not encountered previously. And
# it has metadata. Remember to strip metadata from future values with this
# tag string.
self._seen_summary_tags.add(value.tag)
event = event_pb2.Event(summary=summary)
self._add_event(event, global_step) | [
"def",
"add_summary",
"(",
"self",
",",
"summary",
",",
"global_step",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"summary",
",",
"bytes",
")",
":",
"summ",
"=",
"summary_pb2",
".",
"Summary",
"(",
")",
"summ",
".",
"ParseFromString",
"(",
"summary"... | Adds a `Summary` protocol buffer to the event file.
This method wraps the provided summary in an `Event` protocol buffer and adds it
to the event file.
Parameters
----------
summary : A `Summary` protocol buffer
Optionally serialized as a string.
global_step: Number
Optional global step value to record with the summary. | [
"Adds",
"a",
"Summary",
"protocol",
"buffer",
"to",
"the",
"event",
"file",
".",
"This",
"method",
"wraps",
"the",
"provided",
"summary",
"in",
"an",
"Event",
"protocol",
"buffer",
"and",
"adds",
"it",
"to",
"the",
"event",
"file",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/writer.py#L64-L99 | train | 211,736 |
awslabs/mxboard | python/mxboard/writer.py | SummaryToEventTransformer.add_graph | def add_graph(self, graph):
"""Adds a `Graph` protocol buffer to the event file."""
event = event_pb2.Event(graph_def=graph.SerializeToString())
self._add_event(event, None) | python | def add_graph(self, graph):
"""Adds a `Graph` protocol buffer to the event file."""
event = event_pb2.Event(graph_def=graph.SerializeToString())
self._add_event(event, None) | [
"def",
"add_graph",
"(",
"self",
",",
"graph",
")",
":",
"event",
"=",
"event_pb2",
".",
"Event",
"(",
"graph_def",
"=",
"graph",
".",
"SerializeToString",
"(",
")",
")",
"self",
".",
"_add_event",
"(",
"event",
",",
"None",
")"
] | Adds a `Graph` protocol buffer to the event file. | [
"Adds",
"a",
"Graph",
"protocol",
"buffer",
"to",
"the",
"event",
"file",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/writer.py#L101-L104 | train | 211,737 |
awslabs/mxboard | python/mxboard/writer.py | SummaryWriter.add_scalar | def add_scalar(self, tag, value, global_step=None):
"""Adds scalar data to the event file.
Parameters
----------
tag : str
Name for the scalar plot.
value : float, tuple, list, or dict
If value is a float, the corresponding curve would have no name attached in the
plot.
If value is a tuple or list, it must have two elements with the first one
representing the name of the value and the second one as the float value. The
name of the value will be attached to the corresponding curve in the plot. This
is useful when users want to draw multiple curves in the same plot. It internally
calls `_add_scalars`.
If value is a dict, it's a mapping from strs to float values, with strs
representing the names of the float values. This is convenient when users want
to log a collection of float values with different names for visualizing them in
the same plot without repeatedly calling `add_scalar` for each value. It internally
calls `_add_scalars`.
global_step : int
Global step value to record.
Examples
--------
>>> import numpy as np
>>> from mxboard import SummaryWriter
>>> xs = np.arange(start=0, stop=2 * np.pi, step=0.01)
>>> y_sin = np.sin(xs)
>>> y_cos = np.cos(xs)
>>> y_exp_sin = np.exp(y_sin)
>>> y_exp_cos = np.exp(y_cos)
>>> y_sin2 = y_sin * y_sin
>>> with SummaryWriter(logdir='./logs') as sw:
>>> for x, y1, y2, y3, y4, y5 in zip(xs, y_sin, y_cos, y_exp_sin, y_exp_cos, y_sin2):
>>> sw.add_scalar('curves', {'sin': y1, 'cos': y2}, x * 100)
>>> sw.add_scalar('curves', ('exp(sin)', y3), x * 100)
>>> sw.add_scalar('curves', ['exp(cos)', y4], x * 100)
>>> sw.add_scalar('curves', y5, x * 100)
"""
if isinstance(value, (tuple, list, dict)):
if isinstance(value, (tuple, list)):
if len(value) != 2:
raise ValueError('expected two elements in value, while received %d'
% len(value))
value = {value[0]: value[1]}
self._add_scalars(tag, value, global_step)
else:
self._file_writer.add_summary(scalar_summary(tag, value), global_step)
self._append_to_scalar_dict(self.get_logdir() + '/' + tag,
value, global_step, time.time()) | python | def add_scalar(self, tag, value, global_step=None):
"""Adds scalar data to the event file.
Parameters
----------
tag : str
Name for the scalar plot.
value : float, tuple, list, or dict
If value is a float, the corresponding curve would have no name attached in the
plot.
If value is a tuple or list, it must have two elements with the first one
representing the name of the value and the second one as the float value. The
name of the value will be attached to the corresponding curve in the plot. This
is useful when users want to draw multiple curves in the same plot. It internally
calls `_add_scalars`.
If value is a dict, it's a mapping from strs to float values, with strs
representing the names of the float values. This is convenient when users want
to log a collection of float values with different names for visualizing them in
the same plot without repeatedly calling `add_scalar` for each value. It internally
calls `_add_scalars`.
global_step : int
Global step value to record.
Examples
--------
>>> import numpy as np
>>> from mxboard import SummaryWriter
>>> xs = np.arange(start=0, stop=2 * np.pi, step=0.01)
>>> y_sin = np.sin(xs)
>>> y_cos = np.cos(xs)
>>> y_exp_sin = np.exp(y_sin)
>>> y_exp_cos = np.exp(y_cos)
>>> y_sin2 = y_sin * y_sin
>>> with SummaryWriter(logdir='./logs') as sw:
>>> for x, y1, y2, y3, y4, y5 in zip(xs, y_sin, y_cos, y_exp_sin, y_exp_cos, y_sin2):
>>> sw.add_scalar('curves', {'sin': y1, 'cos': y2}, x * 100)
>>> sw.add_scalar('curves', ('exp(sin)', y3), x * 100)
>>> sw.add_scalar('curves', ['exp(cos)', y4], x * 100)
>>> sw.add_scalar('curves', y5, x * 100)
"""
if isinstance(value, (tuple, list, dict)):
if isinstance(value, (tuple, list)):
if len(value) != 2:
raise ValueError('expected two elements in value, while received %d'
% len(value))
value = {value[0]: value[1]}
self._add_scalars(tag, value, global_step)
else:
self._file_writer.add_summary(scalar_summary(tag, value), global_step)
self._append_to_scalar_dict(self.get_logdir() + '/' + tag,
value, global_step, time.time()) | [
"def",
"add_scalar",
"(",
"self",
",",
"tag",
",",
"value",
",",
"global_step",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"tuple",
",",
"list",
",",
"dict",
")",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"tuple"... | Adds scalar data to the event file.
Parameters
----------
tag : str
Name for the scalar plot.
value : float, tuple, list, or dict
If value is a float, the corresponding curve would have no name attached in the
plot.
If value is a tuple or list, it must have two elements with the first one
representing the name of the value and the second one as the float value. The
name of the value will be attached to the corresponding curve in the plot. This
is useful when users want to draw multiple curves in the same plot. It internally
calls `_add_scalars`.
If value is a dict, it's a mapping from strs to float values, with strs
representing the names of the float values. This is convenient when users want
to log a collection of float values with different names for visualizing them in
the same plot without repeatedly calling `add_scalar` for each value. It internally
calls `_add_scalars`.
global_step : int
Global step value to record.
Examples
--------
>>> import numpy as np
>>> from mxboard import SummaryWriter
>>> xs = np.arange(start=0, stop=2 * np.pi, step=0.01)
>>> y_sin = np.sin(xs)
>>> y_cos = np.cos(xs)
>>> y_exp_sin = np.exp(y_sin)
>>> y_exp_cos = np.exp(y_cos)
>>> y_sin2 = y_sin * y_sin
>>> with SummaryWriter(logdir='./logs') as sw:
>>> for x, y1, y2, y3, y4, y5 in zip(xs, y_sin, y_cos, y_exp_sin, y_exp_cos, y_sin2):
>>> sw.add_scalar('curves', {'sin': y1, 'cos': y2}, x * 100)
>>> sw.add_scalar('curves', ('exp(sin)', y3), x * 100)
>>> sw.add_scalar('curves', ['exp(cos)', y4], x * 100)
>>> sw.add_scalar('curves', y5, x * 100) | [
"Adds",
"scalar",
"data",
"to",
"the",
"event",
"file",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/writer.py#L279-L330 | train | 211,738 |
awslabs/mxboard | python/mxboard/writer.py | SummaryWriter._add_scalars | def _add_scalars(self, tag, scalar_dict, global_step=None):
"""Adds multiple scalars to summary. This enables drawing multiple curves in one plot.
Parameters
----------
tag : str
Name for the plot.
scalar_dict : dict
Values to be saved.
global_step : int
Global step value to record.
"""
timestamp = time.time()
fw_logdir = self._file_writer.get_logdir()
for scalar_name, scalar_value in scalar_dict.items():
fw_tag = fw_logdir + '/' + tag + '/' + scalar_name
if fw_tag in self._all_writers.keys():
fw = self._all_writers[fw_tag]
else:
fw = FileWriter(logdir=fw_tag, max_queue=self._max_queue,
flush_secs=self._flush_secs, filename_suffix=self._filename_suffix,
verbose=self._verbose)
self._all_writers[fw_tag] = fw
fw.add_summary(scalar_summary(tag, scalar_value), global_step)
self._append_to_scalar_dict(fw_tag, scalar_value, global_step, timestamp) | python | def _add_scalars(self, tag, scalar_dict, global_step=None):
"""Adds multiple scalars to summary. This enables drawing multiple curves in one plot.
Parameters
----------
tag : str
Name for the plot.
scalar_dict : dict
Values to be saved.
global_step : int
Global step value to record.
"""
timestamp = time.time()
fw_logdir = self._file_writer.get_logdir()
for scalar_name, scalar_value in scalar_dict.items():
fw_tag = fw_logdir + '/' + tag + '/' + scalar_name
if fw_tag in self._all_writers.keys():
fw = self._all_writers[fw_tag]
else:
fw = FileWriter(logdir=fw_tag, max_queue=self._max_queue,
flush_secs=self._flush_secs, filename_suffix=self._filename_suffix,
verbose=self._verbose)
self._all_writers[fw_tag] = fw
fw.add_summary(scalar_summary(tag, scalar_value), global_step)
self._append_to_scalar_dict(fw_tag, scalar_value, global_step, timestamp) | [
"def",
"_add_scalars",
"(",
"self",
",",
"tag",
",",
"scalar_dict",
",",
"global_step",
"=",
"None",
")",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"fw_logdir",
"=",
"self",
".",
"_file_writer",
".",
"get_logdir",
"(",
")",
"for",
"scalar_nam... | Adds multiple scalars to summary. This enables drawing multiple curves in one plot.
Parameters
----------
tag : str
Name for the plot.
scalar_dict : dict
Values to be saved.
global_step : int
Global step value to record. | [
"Adds",
"multiple",
"scalars",
"to",
"summary",
".",
"This",
"enables",
"drawing",
"multiple",
"curves",
"in",
"one",
"plot",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/writer.py#L332-L356 | train | 211,739 |
awslabs/mxboard | python/mxboard/writer.py | SummaryWriter.add_histogram | def add_histogram(self, tag, values, global_step=None, bins='default'):
"""Add histogram data to the event file.
Note: This function internally calls `asnumpy()` if `values` is an MXNet NDArray.
Since `asnumpy()` is a blocking function call, this function would block the main
thread till it returns. It may consequently affect the performance of async execution
of the MXNet engine.
Parameters
----------
tag : str
Name for the `values`.
values : MXNet `NDArray` or `numpy.ndarray`
Values for building histogram.
global_step : int
Global step value to record.
bins : int or sequence of scalars or str
If `bins` is an int, it defines the number equal-width bins in the range
`(values.min(), values.max())`.
If `bins` is a sequence, it defines the bin edges, including the rightmost edge,
allowing for non-uniform bin width.
If `bins` is a str equal to 'default', it will use the bin distribution
defined in TensorFlow for building histogram.
Ref: https://www.tensorflow.org/programmers_guide/tensorboard_histograms
The rest of supported strings for `bins` are 'auto', 'fd', 'doane', 'scott',
'rice', 'sturges', and 'sqrt'. etc. See the documentation of `numpy.histogram`
for detailed definitions of those strings.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
"""
if bins == 'default':
bins = self._get_default_bins()
self._file_writer.add_summary(histogram_summary(tag, values, bins), global_step) | python | def add_histogram(self, tag, values, global_step=None, bins='default'):
"""Add histogram data to the event file.
Note: This function internally calls `asnumpy()` if `values` is an MXNet NDArray.
Since `asnumpy()` is a blocking function call, this function would block the main
thread till it returns. It may consequently affect the performance of async execution
of the MXNet engine.
Parameters
----------
tag : str
Name for the `values`.
values : MXNet `NDArray` or `numpy.ndarray`
Values for building histogram.
global_step : int
Global step value to record.
bins : int or sequence of scalars or str
If `bins` is an int, it defines the number equal-width bins in the range
`(values.min(), values.max())`.
If `bins` is a sequence, it defines the bin edges, including the rightmost edge,
allowing for non-uniform bin width.
If `bins` is a str equal to 'default', it will use the bin distribution
defined in TensorFlow for building histogram.
Ref: https://www.tensorflow.org/programmers_guide/tensorboard_histograms
The rest of supported strings for `bins` are 'auto', 'fd', 'doane', 'scott',
'rice', 'sturges', and 'sqrt'. etc. See the documentation of `numpy.histogram`
for detailed definitions of those strings.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
"""
if bins == 'default':
bins = self._get_default_bins()
self._file_writer.add_summary(histogram_summary(tag, values, bins), global_step) | [
"def",
"add_histogram",
"(",
"self",
",",
"tag",
",",
"values",
",",
"global_step",
"=",
"None",
",",
"bins",
"=",
"'default'",
")",
":",
"if",
"bins",
"==",
"'default'",
":",
"bins",
"=",
"self",
".",
"_get_default_bins",
"(",
")",
"self",
".",
"_file... | Add histogram data to the event file.
Note: This function internally calls `asnumpy()` if `values` is an MXNet NDArray.
Since `asnumpy()` is a blocking function call, this function would block the main
thread till it returns. It may consequently affect the performance of async execution
of the MXNet engine.
Parameters
----------
tag : str
Name for the `values`.
values : MXNet `NDArray` or `numpy.ndarray`
Values for building histogram.
global_step : int
Global step value to record.
bins : int or sequence of scalars or str
If `bins` is an int, it defines the number equal-width bins in the range
`(values.min(), values.max())`.
If `bins` is a sequence, it defines the bin edges, including the rightmost edge,
allowing for non-uniform bin width.
If `bins` is a str equal to 'default', it will use the bin distribution
defined in TensorFlow for building histogram.
Ref: https://www.tensorflow.org/programmers_guide/tensorboard_histograms
The rest of supported strings for `bins` are 'auto', 'fd', 'doane', 'scott',
'rice', 'sturges', and 'sqrt'. etc. See the documentation of `numpy.histogram`
for detailed definitions of those strings.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html | [
"Add",
"histogram",
"data",
"to",
"the",
"event",
"file",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/writer.py#L372-L403 | train | 211,740 |
awslabs/mxboard | python/mxboard/writer.py | SummaryWriter.add_image | def add_image(self, tag, image, global_step=None):
"""Add image data to the event file.
This function supports input as a 2D, 3D, or 4D image.
If the input image is 2D, a channel axis is prepended as the first dimension
and image will be replicated three times and concatenated along the channel axis.
If the input image is 3D, it will be replicated three times and concatenated along
the channel axis. If the input image is 4D, which is a batch images, all the
images will be spliced as a sprite image for display.
Note: This function requires the ``pillow`` package.
Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs.
Since `asnumpy()` is a blocking function call, this function would block the main
thread till it returns. It may consequently affect the performance of async execution
of the MXNet engine.
Parameters
----------
tag : str
Name for the `image`.
image : MXNet `NDArray` or `numpy.ndarray`
Image is one of the following formats: (H, W), (C, H, W), (N, C, H, W).
If the input is a batch of images, a grid of images is made by stitching them
together.
If data type is float, values must be in range [0, 1], and then they are
rescaled to range [0, 255]. Note that this does not change the values of the
input `image`. A copy of the input `image` is created instead.
If data type is 'uint8`, values are unchanged.
global_step : int
Global step value to record.
"""
self._file_writer.add_summary(image_summary(tag, image), global_step) | python | def add_image(self, tag, image, global_step=None):
"""Add image data to the event file.
This function supports input as a 2D, 3D, or 4D image.
If the input image is 2D, a channel axis is prepended as the first dimension
and image will be replicated three times and concatenated along the channel axis.
If the input image is 3D, it will be replicated three times and concatenated along
the channel axis. If the input image is 4D, which is a batch images, all the
images will be spliced as a sprite image for display.
Note: This function requires the ``pillow`` package.
Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs.
Since `asnumpy()` is a blocking function call, this function would block the main
thread till it returns. It may consequently affect the performance of async execution
of the MXNet engine.
Parameters
----------
tag : str
Name for the `image`.
image : MXNet `NDArray` or `numpy.ndarray`
Image is one of the following formats: (H, W), (C, H, W), (N, C, H, W).
If the input is a batch of images, a grid of images is made by stitching them
together.
If data type is float, values must be in range [0, 1], and then they are
rescaled to range [0, 255]. Note that this does not change the values of the
input `image`. A copy of the input `image` is created instead.
If data type is 'uint8`, values are unchanged.
global_step : int
Global step value to record.
"""
self._file_writer.add_summary(image_summary(tag, image), global_step) | [
"def",
"add_image",
"(",
"self",
",",
"tag",
",",
"image",
",",
"global_step",
"=",
"None",
")",
":",
"self",
".",
"_file_writer",
".",
"add_summary",
"(",
"image_summary",
"(",
"tag",
",",
"image",
")",
",",
"global_step",
")"
] | Add image data to the event file.
This function supports input as a 2D, 3D, or 4D image.
If the input image is 2D, a channel axis is prepended as the first dimension
and image will be replicated three times and concatenated along the channel axis.
If the input image is 3D, it will be replicated three times and concatenated along
the channel axis. If the input image is 4D, which is a batch images, all the
images will be spliced as a sprite image for display.
Note: This function requires the ``pillow`` package.
Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs.
Since `asnumpy()` is a blocking function call, this function would block the main
thread till it returns. It may consequently affect the performance of async execution
of the MXNet engine.
Parameters
----------
tag : str
Name for the `image`.
image : MXNet `NDArray` or `numpy.ndarray`
Image is one of the following formats: (H, W), (C, H, W), (N, C, H, W).
If the input is a batch of images, a grid of images is made by stitching them
together.
If data type is float, values must be in range [0, 1], and then they are
rescaled to range [0, 255]. Note that this does not change the values of the
input `image`. A copy of the input `image` is created instead.
If data type is 'uint8`, values are unchanged.
global_step : int
Global step value to record. | [
"Add",
"image",
"data",
"to",
"the",
"event",
"file",
".",
"This",
"function",
"supports",
"input",
"as",
"a",
"2D",
"3D",
"or",
"4D",
"image",
".",
"If",
"the",
"input",
"image",
"is",
"2D",
"a",
"channel",
"axis",
"is",
"prepended",
"as",
"the",
"f... | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/writer.py#L405-L436 | train | 211,741 |
awslabs/mxboard | python/mxboard/writer.py | SummaryWriter.add_audio | def add_audio(self, tag, audio, sample_rate=44100, global_step=None):
"""Add audio data to the event file.
Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs.
Since `asnumpy()` is a blocking function call, this function would block the main
thread till it returns. It may consequently affect the performance of async execution
of the MXNet engine.
Parameters
----------
tag : str
Name for the `audio`.
audio : MXNet `NDArray` or `numpy.ndarray`
Audio data squeezable to a 1D tensor. The values of the tensor are in the range
`[-1, 1]`.
sample_rate : int
Sample rate in Hz.
global_step : int
Global step value to record.
"""
self._file_writer.add_summary(audio_summary(tag, audio, sample_rate=sample_rate),
global_step) | python | def add_audio(self, tag, audio, sample_rate=44100, global_step=None):
"""Add audio data to the event file.
Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs.
Since `asnumpy()` is a blocking function call, this function would block the main
thread till it returns. It may consequently affect the performance of async execution
of the MXNet engine.
Parameters
----------
tag : str
Name for the `audio`.
audio : MXNet `NDArray` or `numpy.ndarray`
Audio data squeezable to a 1D tensor. The values of the tensor are in the range
`[-1, 1]`.
sample_rate : int
Sample rate in Hz.
global_step : int
Global step value to record.
"""
self._file_writer.add_summary(audio_summary(tag, audio, sample_rate=sample_rate),
global_step) | [
"def",
"add_audio",
"(",
"self",
",",
"tag",
",",
"audio",
",",
"sample_rate",
"=",
"44100",
",",
"global_step",
"=",
"None",
")",
":",
"self",
".",
"_file_writer",
".",
"add_summary",
"(",
"audio_summary",
"(",
"tag",
",",
"audio",
",",
"sample_rate",
"... | Add audio data to the event file.
Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs.
Since `asnumpy()` is a blocking function call, this function would block the main
thread till it returns. It may consequently affect the performance of async execution
of the MXNet engine.
Parameters
----------
tag : str
Name for the `audio`.
audio : MXNet `NDArray` or `numpy.ndarray`
Audio data squeezable to a 1D tensor. The values of the tensor are in the range
`[-1, 1]`.
sample_rate : int
Sample rate in Hz.
global_step : int
Global step value to record. | [
"Add",
"audio",
"data",
"to",
"the",
"event",
"file",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/writer.py#L438-L459 | train | 211,742 |
awslabs/mxboard | python/mxboard/writer.py | SummaryWriter.add_text | def add_text(self, tag, text, global_step=None):
"""Add text data to the event file.
Parameters
----------
tag : str
Name for the `text`.
text : str
Text to be saved to the event file.
global_step : int
Global step value to record.
"""
self._file_writer.add_summary(text_summary(tag, text), global_step)
if tag not in self._text_tags:
self._text_tags.append(tag)
extension_dir = self.get_logdir() + '/plugins/tensorboard_text/'
if not os.path.exists(extension_dir):
os.makedirs(extension_dir)
with open(extension_dir + 'tensors.json', 'w') as fp:
json.dump(self._text_tags, fp) | python | def add_text(self, tag, text, global_step=None):
"""Add text data to the event file.
Parameters
----------
tag : str
Name for the `text`.
text : str
Text to be saved to the event file.
global_step : int
Global step value to record.
"""
self._file_writer.add_summary(text_summary(tag, text), global_step)
if tag not in self._text_tags:
self._text_tags.append(tag)
extension_dir = self.get_logdir() + '/plugins/tensorboard_text/'
if not os.path.exists(extension_dir):
os.makedirs(extension_dir)
with open(extension_dir + 'tensors.json', 'w') as fp:
json.dump(self._text_tags, fp) | [
"def",
"add_text",
"(",
"self",
",",
"tag",
",",
"text",
",",
"global_step",
"=",
"None",
")",
":",
"self",
".",
"_file_writer",
".",
"add_summary",
"(",
"text_summary",
"(",
"tag",
",",
"text",
")",
",",
"global_step",
")",
"if",
"tag",
"not",
"in",
... | Add text data to the event file.
Parameters
----------
tag : str
Name for the `text`.
text : str
Text to be saved to the event file.
global_step : int
Global step value to record. | [
"Add",
"text",
"data",
"to",
"the",
"event",
"file",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/writer.py#L461-L480 | train | 211,743 |
awslabs/mxboard | python/mxboard/writer.py | SummaryWriter.add_pr_curve | def add_pr_curve(self, tag, labels, predictions, num_thresholds,
global_step=None, weights=None):
"""Adds precision-recall curve.
Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs.
Since `asnumpy()` is a blocking function call, this function would block the main
thread till it returns. It may consequently affect the performance of async execution
of the MXNet engine.
Parameters
----------
tag : str
A tag attached to the summary. Used by TensorBoard for organization.
labels : MXNet `NDArray` or `numpy.ndarray`.
The ground truth values. A tensor of 0/1 values with arbitrary shape.
predictions : MXNet `NDArray` or `numpy.ndarray`.
A float32 tensor whose values are in the range `[0, 1]`. Dimensions must match
those of `labels`.
num_thresholds : int
Number of thresholds, evenly distributed in `[0, 1]`, to compute PR metrics for.
Should be `>= 2`. This value should be a constant integer value, not a tensor
that stores an integer.
The thresholds for computing the pr curves are calculated in the following way:
`width = 1.0 / (num_thresholds - 1),
thresholds = [0.0, 1*width, 2*width, 3*width, ..., 1.0]`.
global_step : int
Global step value to record.
weights : MXNet `NDArray` or `numpy.ndarray`.
Optional float32 tensor. Individual counts are multiplied by this value.
This tensor must be either the same shape as or broadcastable to the `labels`
tensor.
"""
if num_thresholds < 2:
raise ValueError('num_thresholds must be >= 2')
labels = _make_numpy_array(labels)
predictions = _make_numpy_array(predictions)
self._file_writer.add_summary(pr_curve_summary(tag, labels, predictions,
num_thresholds, weights), global_step) | python | def add_pr_curve(self, tag, labels, predictions, num_thresholds,
global_step=None, weights=None):
"""Adds precision-recall curve.
Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs.
Since `asnumpy()` is a blocking function call, this function would block the main
thread till it returns. It may consequently affect the performance of async execution
of the MXNet engine.
Parameters
----------
tag : str
A tag attached to the summary. Used by TensorBoard for organization.
labels : MXNet `NDArray` or `numpy.ndarray`.
The ground truth values. A tensor of 0/1 values with arbitrary shape.
predictions : MXNet `NDArray` or `numpy.ndarray`.
A float32 tensor whose values are in the range `[0, 1]`. Dimensions must match
those of `labels`.
num_thresholds : int
Number of thresholds, evenly distributed in `[0, 1]`, to compute PR metrics for.
Should be `>= 2`. This value should be a constant integer value, not a tensor
that stores an integer.
The thresholds for computing the pr curves are calculated in the following way:
`width = 1.0 / (num_thresholds - 1),
thresholds = [0.0, 1*width, 2*width, 3*width, ..., 1.0]`.
global_step : int
Global step value to record.
weights : MXNet `NDArray` or `numpy.ndarray`.
Optional float32 tensor. Individual counts are multiplied by this value.
This tensor must be either the same shape as or broadcastable to the `labels`
tensor.
"""
if num_thresholds < 2:
raise ValueError('num_thresholds must be >= 2')
labels = _make_numpy_array(labels)
predictions = _make_numpy_array(predictions)
self._file_writer.add_summary(pr_curve_summary(tag, labels, predictions,
num_thresholds, weights), global_step) | [
"def",
"add_pr_curve",
"(",
"self",
",",
"tag",
",",
"labels",
",",
"predictions",
",",
"num_thresholds",
",",
"global_step",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"if",
"num_thresholds",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"'num_thres... | Adds precision-recall curve.
Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs.
Since `asnumpy()` is a blocking function call, this function would block the main
thread till it returns. It may consequently affect the performance of async execution
of the MXNet engine.
Parameters
----------
tag : str
A tag attached to the summary. Used by TensorBoard for organization.
labels : MXNet `NDArray` or `numpy.ndarray`.
The ground truth values. A tensor of 0/1 values with arbitrary shape.
predictions : MXNet `NDArray` or `numpy.ndarray`.
A float32 tensor whose values are in the range `[0, 1]`. Dimensions must match
those of `labels`.
num_thresholds : int
Number of thresholds, evenly distributed in `[0, 1]`, to compute PR metrics for.
Should be `>= 2`. This value should be a constant integer value, not a tensor
that stores an integer.
The thresholds for computing the pr curves are calculated in the following way:
`width = 1.0 / (num_thresholds - 1),
thresholds = [0.0, 1*width, 2*width, 3*width, ..., 1.0]`.
global_step : int
Global step value to record.
weights : MXNet `NDArray` or `numpy.ndarray`.
Optional float32 tensor. Individual counts are multiplied by this value.
This tensor must be either the same shape as or broadcastable to the `labels`
tensor. | [
"Adds",
"precision",
"-",
"recall",
"curve",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/writer.py#L548-L585 | train | 211,744 |
awslabs/mxboard | python/mxboard/utils.py | _rectangular | def _rectangular(n):
"""Checks to see if a 2D list is a valid 2D matrix"""
for i in n:
if len(i) != len(n[0]):
return False
return True | python | def _rectangular(n):
"""Checks to see if a 2D list is a valid 2D matrix"""
for i in n:
if len(i) != len(n[0]):
return False
return True | [
"def",
"_rectangular",
"(",
"n",
")",
":",
"for",
"i",
"in",
"n",
":",
"if",
"len",
"(",
"i",
")",
"!=",
"len",
"(",
"n",
"[",
"0",
"]",
")",
":",
"return",
"False",
"return",
"True"
] | Checks to see if a 2D list is a valid 2D matrix | [
"Checks",
"to",
"see",
"if",
"a",
"2D",
"list",
"is",
"a",
"valid",
"2D",
"matrix"
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/utils.py#L46-L51 | train | 211,745 |
awslabs/mxboard | python/mxboard/utils.py | _is_2D_matrix | def _is_2D_matrix(matrix):
"""Checks to see if a ndarray is 2D or a list of lists is 2D"""
return ((isinstance(matrix[0], list) and _rectangular(matrix) and
not isinstance(matrix[0][0], list)) or
(not isinstance(matrix, list) and matrix.shape == 2)) | python | def _is_2D_matrix(matrix):
"""Checks to see if a ndarray is 2D or a list of lists is 2D"""
return ((isinstance(matrix[0], list) and _rectangular(matrix) and
not isinstance(matrix[0][0], list)) or
(not isinstance(matrix, list) and matrix.shape == 2)) | [
"def",
"_is_2D_matrix",
"(",
"matrix",
")",
":",
"return",
"(",
"(",
"isinstance",
"(",
"matrix",
"[",
"0",
"]",
",",
"list",
")",
"and",
"_rectangular",
"(",
"matrix",
")",
"and",
"not",
"isinstance",
"(",
"matrix",
"[",
"0",
"]",
"[",
"0",
"]",
"... | Checks to see if a ndarray is 2D or a list of lists is 2D | [
"Checks",
"to",
"see",
"if",
"a",
"ndarray",
"is",
"2D",
"or",
"a",
"list",
"of",
"lists",
"is",
"2D"
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/utils.py#L54-L58 | train | 211,746 |
awslabs/mxboard | python/mxboard/utils.py | _save_image | def _save_image(image, filename, nrow=8, padding=2, square_image=True):
"""Saves a given Tensor into an image file. If the input tensor contains multiple images,
a grid of images will be saved.
Parameters
----------
image : `NDArray`
Input image(s) in the format of HW, CHW, or NCHW.
filename : str
Filename of the saved image(s).
nrow : int
Number of images displayed in each row of the grid. The Final grid size is
(batch_size / `nrow`, `nrow`) when square_image is False; otherwise, (`nrow`, `nrow`).
padding : int
Padding value for each image in the grid.
square_image : bool
If True, force the image grid to be strictly square.
"""
if not isinstance(image, NDArray):
raise TypeError('MXNet NDArray expected, received {}'.format(str(type(image))))
image = _prepare_image(image, nrow=nrow, padding=padding, square_image=square_image)
if Image is None:
raise ImportError('saving image failed because PIL is not found')
im = Image.fromarray(image.asnumpy())
im.save(filename) | python | def _save_image(image, filename, nrow=8, padding=2, square_image=True):
"""Saves a given Tensor into an image file. If the input tensor contains multiple images,
a grid of images will be saved.
Parameters
----------
image : `NDArray`
Input image(s) in the format of HW, CHW, or NCHW.
filename : str
Filename of the saved image(s).
nrow : int
Number of images displayed in each row of the grid. The Final grid size is
(batch_size / `nrow`, `nrow`) when square_image is False; otherwise, (`nrow`, `nrow`).
padding : int
Padding value for each image in the grid.
square_image : bool
If True, force the image grid to be strictly square.
"""
if not isinstance(image, NDArray):
raise TypeError('MXNet NDArray expected, received {}'.format(str(type(image))))
image = _prepare_image(image, nrow=nrow, padding=padding, square_image=square_image)
if Image is None:
raise ImportError('saving image failed because PIL is not found')
im = Image.fromarray(image.asnumpy())
im.save(filename) | [
"def",
"_save_image",
"(",
"image",
",",
"filename",
",",
"nrow",
"=",
"8",
",",
"padding",
"=",
"2",
",",
"square_image",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"image",
",",
"NDArray",
")",
":",
"raise",
"TypeError",
"(",
"'MXNet NDAr... | Saves a given Tensor into an image file. If the input tensor contains multiple images,
a grid of images will be saved.
Parameters
----------
image : `NDArray`
Input image(s) in the format of HW, CHW, or NCHW.
filename : str
Filename of the saved image(s).
nrow : int
Number of images displayed in each row of the grid. The Final grid size is
(batch_size / `nrow`, `nrow`) when square_image is False; otherwise, (`nrow`, `nrow`).
padding : int
Padding value for each image in the grid.
square_image : bool
If True, force the image grid to be strictly square. | [
"Saves",
"a",
"given",
"Tensor",
"into",
"an",
"image",
"file",
".",
"If",
"the",
"input",
"tensor",
"contains",
"multiple",
"images",
"a",
"grid",
"of",
"images",
"will",
"be",
"saved",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/utils.py#L178-L202 | train | 211,747 |
awslabs/mxboard | python/mxboard/utils.py | _save_embedding_tsv | def _save_embedding_tsv(data, file_path):
"""Given a 2D `NDarray` or a `numpy.ndarray` as embeding,
save it in tensors.tsv under the path provided by the user."""
if isinstance(data, np.ndarray):
data_list = data.tolist()
elif isinstance(data, NDArray):
data_list = data.asnumpy().tolist()
else:
raise TypeError('expected NDArray of np.ndarray, while received type {}'.format(
str(type(data))))
with open(os.path.join(file_path, 'tensors.tsv'), 'w') as f:
for x in data_list:
x = [str(i) for i in x]
f.write('\t'.join(x) + '\n') | python | def _save_embedding_tsv(data, file_path):
"""Given a 2D `NDarray` or a `numpy.ndarray` as embeding,
save it in tensors.tsv under the path provided by the user."""
if isinstance(data, np.ndarray):
data_list = data.tolist()
elif isinstance(data, NDArray):
data_list = data.asnumpy().tolist()
else:
raise TypeError('expected NDArray of np.ndarray, while received type {}'.format(
str(type(data))))
with open(os.path.join(file_path, 'tensors.tsv'), 'w') as f:
for x in data_list:
x = [str(i) for i in x]
f.write('\t'.join(x) + '\n') | [
"def",
"_save_embedding_tsv",
"(",
"data",
",",
"file_path",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
":",
"data_list",
"=",
"data",
".",
"tolist",
"(",
")",
"elif",
"isinstance",
"(",
"data",
",",
"NDArray",
")",
":",... | Given a 2D `NDarray` or a `numpy.ndarray` as embeding,
save it in tensors.tsv under the path provided by the user. | [
"Given",
"a",
"2D",
"NDarray",
"or",
"a",
"numpy",
".",
"ndarray",
"as",
"embeding",
"save",
"it",
"in",
"tensors",
".",
"tsv",
"under",
"the",
"path",
"provided",
"by",
"the",
"user",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/utils.py#L312-L325 | train | 211,748 |
awslabs/mxboard | python/mxboard/summary.py | _make_image | def _make_image(tensor):
"""Converts an NDArray type image to Image protobuf"""
assert isinstance(tensor, NDArray)
if Image is None:
raise ImportError('need to install PIL for visualizing images')
height, width, channel = tensor.shape
tensor = _make_numpy_array(tensor)
image = Image.fromarray(tensor)
output = io.BytesIO()
image.save(output, format='PNG')
image_string = output.getvalue()
output.close()
return Summary.Image(height=height, width=width, colorspace=channel,
encoded_image_string=image_string) | python | def _make_image(tensor):
"""Converts an NDArray type image to Image protobuf"""
assert isinstance(tensor, NDArray)
if Image is None:
raise ImportError('need to install PIL for visualizing images')
height, width, channel = tensor.shape
tensor = _make_numpy_array(tensor)
image = Image.fromarray(tensor)
output = io.BytesIO()
image.save(output, format='PNG')
image_string = output.getvalue()
output.close()
return Summary.Image(height=height, width=width, colorspace=channel,
encoded_image_string=image_string) | [
"def",
"_make_image",
"(",
"tensor",
")",
":",
"assert",
"isinstance",
"(",
"tensor",
",",
"NDArray",
")",
"if",
"Image",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"'need to install PIL for visualizing images'",
")",
"height",
",",
"width",
",",
"channel",... | Converts an NDArray type image to Image protobuf | [
"Converts",
"an",
"NDArray",
"type",
"image",
"to",
"Image",
"protobuf"
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/summary.py#L192-L205 | train | 211,749 |
awslabs/mxboard | python/mxboard/summary.py | pr_curve_summary | def pr_curve_summary(tag, labels, predictions, num_thresholds, weights=None):
"""Outputs a precision-recall curve `Summary` protocol buffer.
Parameters
----------
tag : str
A tag attached to the summary. Used by TensorBoard for organization.
labels : MXNet `NDArray` or `numpy.ndarray`.
The ground truth values. A tensor of 0/1 values with arbitrary shape.
predictions : MXNet `NDArray` or `numpy.ndarray`.
A float32 tensor whose values are in the range `[0, 1]`. Dimensions must
match those of `labels`.
num_thresholds : int
Number of thresholds, evenly distributed in `[0, 1]`, to compute PR metrics for.
Should be `>= 2`. This value should be a constant integer value, not a tensor
that stores an integer.
The thresholds for computing the pr curves are calculated in the following way:
`width = 1.0 / (num_thresholds - 1),
thresholds = [0.0, 1*width, 2*width, 3*width, ..., 1.0]`.
weights : MXNet `NDArray` or `numpy.ndarray`.
Optional float32 tensor. Individual counts are multiplied by this value.
This tensor must be either the same shape as or broadcastable to the `labels` tensor.
Returns
-------
A `Summary` protobuf of the pr_curve.
"""
# num_thresholds > 127 results in failure of creating protobuf,
# probably a bug of protobuf
if num_thresholds > 127:
logging.warning('num_thresholds>127 would result in failure of creating pr_curve protobuf,'
' clipping it at 127')
num_thresholds = 127
labels = _make_numpy_array(labels)
predictions = _make_numpy_array(predictions)
if weights is not None:
weights = _make_numpy_array(weights)
data = _compute_curve(labels, predictions, num_thresholds=num_thresholds, weights=weights)
pr_curve_plugin_data = PrCurvePluginData(version=0,
num_thresholds=num_thresholds).SerializeToString()
plugin_data = [SummaryMetadata.PluginData(plugin_name='pr_curves',
content=pr_curve_plugin_data)]
smd = SummaryMetadata(plugin_data=plugin_data)
tensor = TensorProto(dtype='DT_FLOAT',
float_val=data.reshape(-1).tolist(),
tensor_shape=TensorShapeProto(
dim=[TensorShapeProto.Dim(size=data.shape[0]),
TensorShapeProto.Dim(size=data.shape[1])]))
return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor)]) | python | def pr_curve_summary(tag, labels, predictions, num_thresholds, weights=None):
"""Outputs a precision-recall curve `Summary` protocol buffer.
Parameters
----------
tag : str
A tag attached to the summary. Used by TensorBoard for organization.
labels : MXNet `NDArray` or `numpy.ndarray`.
The ground truth values. A tensor of 0/1 values with arbitrary shape.
predictions : MXNet `NDArray` or `numpy.ndarray`.
A float32 tensor whose values are in the range `[0, 1]`. Dimensions must
match those of `labels`.
num_thresholds : int
Number of thresholds, evenly distributed in `[0, 1]`, to compute PR metrics for.
Should be `>= 2`. This value should be a constant integer value, not a tensor
that stores an integer.
The thresholds for computing the pr curves are calculated in the following way:
`width = 1.0 / (num_thresholds - 1),
thresholds = [0.0, 1*width, 2*width, 3*width, ..., 1.0]`.
weights : MXNet `NDArray` or `numpy.ndarray`.
Optional float32 tensor. Individual counts are multiplied by this value.
This tensor must be either the same shape as or broadcastable to the `labels` tensor.
Returns
-------
A `Summary` protobuf of the pr_curve.
"""
# num_thresholds > 127 results in failure of creating protobuf,
# probably a bug of protobuf
if num_thresholds > 127:
logging.warning('num_thresholds>127 would result in failure of creating pr_curve protobuf,'
' clipping it at 127')
num_thresholds = 127
labels = _make_numpy_array(labels)
predictions = _make_numpy_array(predictions)
if weights is not None:
weights = _make_numpy_array(weights)
data = _compute_curve(labels, predictions, num_thresholds=num_thresholds, weights=weights)
pr_curve_plugin_data = PrCurvePluginData(version=0,
num_thresholds=num_thresholds).SerializeToString()
plugin_data = [SummaryMetadata.PluginData(plugin_name='pr_curves',
content=pr_curve_plugin_data)]
smd = SummaryMetadata(plugin_data=plugin_data)
tensor = TensorProto(dtype='DT_FLOAT',
float_val=data.reshape(-1).tolist(),
tensor_shape=TensorShapeProto(
dim=[TensorShapeProto.Dim(size=data.shape[0]),
TensorShapeProto.Dim(size=data.shape[1])]))
return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor)]) | [
"def",
"pr_curve_summary",
"(",
"tag",
",",
"labels",
",",
"predictions",
",",
"num_thresholds",
",",
"weights",
"=",
"None",
")",
":",
"# num_thresholds > 127 results in failure of creating protobuf,",
"# probably a bug of protobuf",
"if",
"num_thresholds",
">",
"127",
"... | Outputs a precision-recall curve `Summary` protocol buffer.
Parameters
----------
tag : str
A tag attached to the summary. Used by TensorBoard for organization.
labels : MXNet `NDArray` or `numpy.ndarray`.
The ground truth values. A tensor of 0/1 values with arbitrary shape.
predictions : MXNet `NDArray` or `numpy.ndarray`.
A float32 tensor whose values are in the range `[0, 1]`. Dimensions must
match those of `labels`.
num_thresholds : int
Number of thresholds, evenly distributed in `[0, 1]`, to compute PR metrics for.
Should be `>= 2`. This value should be a constant integer value, not a tensor
that stores an integer.
The thresholds for computing the pr curves are calculated in the following way:
`width = 1.0 / (num_thresholds - 1),
thresholds = [0.0, 1*width, 2*width, 3*width, ..., 1.0]`.
weights : MXNet `NDArray` or `numpy.ndarray`.
Optional float32 tensor. Individual counts are multiplied by this value.
This tensor must be either the same shape as or broadcastable to the `labels` tensor.
Returns
-------
A `Summary` protobuf of the pr_curve. | [
"Outputs",
"a",
"precision",
"-",
"recall",
"curve",
"Summary",
"protocol",
"buffer",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/summary.py#L272-L320 | train | 211,750 |
awslabs/mxboard | python/mxboard/summary.py | _get_nodes_from_symbol | def _get_nodes_from_symbol(sym):
"""Given a symbol and shapes, return a list of `NodeDef`s for visualizing the
the graph in TensorBoard."""
if not isinstance(sym, Symbol):
raise TypeError('sym must be an `mxnet.symbol.Symbol`,'
' received type {}'.format(str(type(sym))))
conf = json.loads(sym.tojson())
nodes = conf['nodes']
data2op = {} # key: data id, value: list of ops to whom data is an input
for i, node in enumerate(nodes):
if node['op'] != 'null': # node is an operator
input_list = node['inputs']
for idx in input_list:
if idx[0] == 0: # do not include 'data' node in the op scope
continue
if idx[0] in data2op:
# nodes[idx[0]] is a data as an input to op nodes[i]
data2op[idx[0]].append(i)
else:
data2op[idx[0]] = [i]
# In the following, we group data with operators they belong to
# by attaching them with operator names as scope names.
# The parameters with the operator name as the prefix will be
# assigned with the scope name of that operator. For example,
# a convolution op has name 'conv', while its weight and bias
# have name 'conv_weight' and 'conv_bias'. In the end, the operator
# has scope name 'conv' prepended to its name, i.e. 'conv/conv'.
# The parameters are named 'conv/conv_weight' and 'conv/conv_bias'.
node_defs = []
for i, node in enumerate(nodes):
node_name = node['name']
op_name = node['op']
kwargs = {'op': op_name, 'name': node_name}
if op_name != 'null': # node is an operator
inputs = []
input_list = node['inputs']
for idx in input_list:
input_node = nodes[idx[0]]
input_node_name = input_node['name']
if input_node['op'] != 'null':
inputs.append(_scoped_name(input_node_name, input_node_name))
elif idx[0] in data2op and len(data2op[idx[0]]) == 1 and data2op[idx[0]][0] == i:
# the data is only as an input to nodes[i], no else
inputs.append(_scoped_name(node_name, input_node_name))
else: # the data node has no scope name, e.g. 'data' as the input node
inputs.append(input_node_name)
kwargs['input'] = inputs
kwargs['name'] = _scoped_name(node_name, node_name)
elif i in data2op and len(data2op[i]) == 1:
# node is a data node belonging to one op, find out which operator this node belongs to
op_node_name = nodes[data2op[i][0]]['name']
kwargs['name'] = _scoped_name(op_node_name, node_name)
if 'attrs' in node:
# TensorBoard would escape quotation marks, replace it with space
attr = json.dumps(node['attrs'], sort_keys=True).replace("\"", ' ')
attr = {'param': AttrValue(s=attr.encode(encoding='utf-8'))}
kwargs['attr'] = attr
node_def = NodeDef(**kwargs)
node_defs.append(node_def)
return node_defs | python | def _get_nodes_from_symbol(sym):
"""Given a symbol and shapes, return a list of `NodeDef`s for visualizing the
the graph in TensorBoard."""
if not isinstance(sym, Symbol):
raise TypeError('sym must be an `mxnet.symbol.Symbol`,'
' received type {}'.format(str(type(sym))))
conf = json.loads(sym.tojson())
nodes = conf['nodes']
data2op = {} # key: data id, value: list of ops to whom data is an input
for i, node in enumerate(nodes):
if node['op'] != 'null': # node is an operator
input_list = node['inputs']
for idx in input_list:
if idx[0] == 0: # do not include 'data' node in the op scope
continue
if idx[0] in data2op:
# nodes[idx[0]] is a data as an input to op nodes[i]
data2op[idx[0]].append(i)
else:
data2op[idx[0]] = [i]
# In the following, we group data with operators they belong to
# by attaching them with operator names as scope names.
# The parameters with the operator name as the prefix will be
# assigned with the scope name of that operator. For example,
# a convolution op has name 'conv', while its weight and bias
# have name 'conv_weight' and 'conv_bias'. In the end, the operator
# has scope name 'conv' prepended to its name, i.e. 'conv/conv'.
# The parameters are named 'conv/conv_weight' and 'conv/conv_bias'.
node_defs = []
for i, node in enumerate(nodes):
node_name = node['name']
op_name = node['op']
kwargs = {'op': op_name, 'name': node_name}
if op_name != 'null': # node is an operator
inputs = []
input_list = node['inputs']
for idx in input_list:
input_node = nodes[idx[0]]
input_node_name = input_node['name']
if input_node['op'] != 'null':
inputs.append(_scoped_name(input_node_name, input_node_name))
elif idx[0] in data2op and len(data2op[idx[0]]) == 1 and data2op[idx[0]][0] == i:
# the data is only as an input to nodes[i], no else
inputs.append(_scoped_name(node_name, input_node_name))
else: # the data node has no scope name, e.g. 'data' as the input node
inputs.append(input_node_name)
kwargs['input'] = inputs
kwargs['name'] = _scoped_name(node_name, node_name)
elif i in data2op and len(data2op[i]) == 1:
# node is a data node belonging to one op, find out which operator this node belongs to
op_node_name = nodes[data2op[i][0]]['name']
kwargs['name'] = _scoped_name(op_node_name, node_name)
if 'attrs' in node:
# TensorBoard would escape quotation marks, replace it with space
attr = json.dumps(node['attrs'], sort_keys=True).replace("\"", ' ')
attr = {'param': AttrValue(s=attr.encode(encoding='utf-8'))}
kwargs['attr'] = attr
node_def = NodeDef(**kwargs)
node_defs.append(node_def)
return node_defs | [
"def",
"_get_nodes_from_symbol",
"(",
"sym",
")",
":",
"if",
"not",
"isinstance",
"(",
"sym",
",",
"Symbol",
")",
":",
"raise",
"TypeError",
"(",
"'sym must be an `mxnet.symbol.Symbol`,'",
"' received type {}'",
".",
"format",
"(",
"str",
"(",
"type",
"(",
"sym"... | Given a symbol and shapes, return a list of `NodeDef`s for visualizing the
the graph in TensorBoard. | [
"Given",
"a",
"symbol",
"and",
"shapes",
"return",
"a",
"list",
"of",
"NodeDef",
"s",
"for",
"visualizing",
"the",
"the",
"graph",
"in",
"TensorBoard",
"."
] | 36057ff0f05325c9dc2fe046521325bf9d563a88 | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/summary.py#L364-L425 | train | 211,751 |
poldracklab/niworkflows | niworkflows/interfaces/confounds.py | temporal_derivatives | def temporal_derivatives(order, variables, data):
"""
Compute temporal derivative terms by the method of backwards differences.
Parameters
----------
order: range or list(int)
A list of temporal derivative terms to include. For instance, [1, 2]
indicates that the first and second derivative terms should be added.
To retain the original terms, 0 *must* be included in the list.
variables: list(str)
List of variables for which temporal derivative terms should be
computed.
data: pandas DataFrame object
Table of values of all observations of all variables.
Returns
-------
variables_deriv: list
A list of variables to include in the final data frame after adding
the specified derivative terms.
data_deriv: pandas DataFrame object
Table of values of all observations of all variables, including any
specified derivative terms.
"""
variables_deriv = OrderedDict()
data_deriv = OrderedDict()
if 0 in order:
data_deriv[0] = data[variables]
variables_deriv[0] = variables
order = set(order) - set([0])
for o in order:
variables_deriv[o] = ['{}_derivative{}'.format(v, o)
for v in variables]
data_deriv[o] = np.tile(np.nan, data[variables].shape)
data_deriv[o][o:, :] = np.diff(data[variables], n=o, axis=0)
variables_deriv = reduce((lambda x, y: x + y), variables_deriv.values())
data_deriv = pd.DataFrame(columns=variables_deriv,
data=np.concatenate([*data_deriv.values()],
axis=1))
return (variables_deriv, data_deriv) | python | def temporal_derivatives(order, variables, data):
"""
Compute temporal derivative terms by the method of backwards differences.
Parameters
----------
order: range or list(int)
A list of temporal derivative terms to include. For instance, [1, 2]
indicates that the first and second derivative terms should be added.
To retain the original terms, 0 *must* be included in the list.
variables: list(str)
List of variables for which temporal derivative terms should be
computed.
data: pandas DataFrame object
Table of values of all observations of all variables.
Returns
-------
variables_deriv: list
A list of variables to include in the final data frame after adding
the specified derivative terms.
data_deriv: pandas DataFrame object
Table of values of all observations of all variables, including any
specified derivative terms.
"""
variables_deriv = OrderedDict()
data_deriv = OrderedDict()
if 0 in order:
data_deriv[0] = data[variables]
variables_deriv[0] = variables
order = set(order) - set([0])
for o in order:
variables_deriv[o] = ['{}_derivative{}'.format(v, o)
for v in variables]
data_deriv[o] = np.tile(np.nan, data[variables].shape)
data_deriv[o][o:, :] = np.diff(data[variables], n=o, axis=0)
variables_deriv = reduce((lambda x, y: x + y), variables_deriv.values())
data_deriv = pd.DataFrame(columns=variables_deriv,
data=np.concatenate([*data_deriv.values()],
axis=1))
return (variables_deriv, data_deriv) | [
"def",
"temporal_derivatives",
"(",
"order",
",",
"variables",
",",
"data",
")",
":",
"variables_deriv",
"=",
"OrderedDict",
"(",
")",
"data_deriv",
"=",
"OrderedDict",
"(",
")",
"if",
"0",
"in",
"order",
":",
"data_deriv",
"[",
"0",
"]",
"=",
"data",
"[... | Compute temporal derivative terms by the method of backwards differences.
Parameters
----------
order: range or list(int)
A list of temporal derivative terms to include. For instance, [1, 2]
indicates that the first and second derivative terms should be added.
To retain the original terms, 0 *must* be included in the list.
variables: list(str)
List of variables for which temporal derivative terms should be
computed.
data: pandas DataFrame object
Table of values of all observations of all variables.
Returns
-------
variables_deriv: list
A list of variables to include in the final data frame after adding
the specified derivative terms.
data_deriv: pandas DataFrame object
Table of values of all observations of all variables, including any
specified derivative terms. | [
"Compute",
"temporal",
"derivative",
"terms",
"by",
"the",
"method",
"of",
"backwards",
"differences",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/confounds.py#L247-L288 | train | 211,752 |
poldracklab/niworkflows | niworkflows/interfaces/confounds.py | exponential_terms | def exponential_terms(order, variables, data):
"""
Compute exponential expansions.
Parameters
----------
order: range or list(int)
A list of exponential terms to include. For instance, [1, 2]
indicates that the first and second exponential terms should be added.
To retain the original terms, 1 *must* be included in the list.
variables: list(str)
List of variables for which exponential terms should be computed.
data: pandas DataFrame object
Table of values of all observations of all variables.
Returns
-------
variables_exp: list
A list of variables to include in the final data frame after adding
the specified exponential terms.
data_exp: pandas DataFrame object
Table of values of all observations of all variables, including any
specified exponential terms.
"""
variables_exp = OrderedDict()
data_exp = OrderedDict()
if 1 in order:
data_exp[1] = data[variables]
variables_exp[1] = variables
order = set(order) - set([1])
for o in order:
variables_exp[o] = ['{}_power{}'.format(v, o) for v in variables]
data_exp[o] = data[variables]**o
variables_exp = reduce((lambda x, y: x + y), variables_exp.values())
data_exp = pd.DataFrame(columns=variables_exp,
data=np.concatenate([*data_exp.values()], axis=1))
return (variables_exp, data_exp) | python | def exponential_terms(order, variables, data):
"""
Compute exponential expansions.
Parameters
----------
order: range or list(int)
A list of exponential terms to include. For instance, [1, 2]
indicates that the first and second exponential terms should be added.
To retain the original terms, 1 *must* be included in the list.
variables: list(str)
List of variables for which exponential terms should be computed.
data: pandas DataFrame object
Table of values of all observations of all variables.
Returns
-------
variables_exp: list
A list of variables to include in the final data frame after adding
the specified exponential terms.
data_exp: pandas DataFrame object
Table of values of all observations of all variables, including any
specified exponential terms.
"""
variables_exp = OrderedDict()
data_exp = OrderedDict()
if 1 in order:
data_exp[1] = data[variables]
variables_exp[1] = variables
order = set(order) - set([1])
for o in order:
variables_exp[o] = ['{}_power{}'.format(v, o) for v in variables]
data_exp[o] = data[variables]**o
variables_exp = reduce((lambda x, y: x + y), variables_exp.values())
data_exp = pd.DataFrame(columns=variables_exp,
data=np.concatenate([*data_exp.values()], axis=1))
return (variables_exp, data_exp) | [
"def",
"exponential_terms",
"(",
"order",
",",
"variables",
",",
"data",
")",
":",
"variables_exp",
"=",
"OrderedDict",
"(",
")",
"data_exp",
"=",
"OrderedDict",
"(",
")",
"if",
"1",
"in",
"order",
":",
"data_exp",
"[",
"1",
"]",
"=",
"data",
"[",
"var... | Compute exponential expansions.
Parameters
----------
order: range or list(int)
A list of exponential terms to include. For instance, [1, 2]
indicates that the first and second exponential terms should be added.
To retain the original terms, 1 *must* be included in the list.
variables: list(str)
List of variables for which exponential terms should be computed.
data: pandas DataFrame object
Table of values of all observations of all variables.
Returns
-------
variables_exp: list
A list of variables to include in the final data frame after adding
the specified exponential terms.
data_exp: pandas DataFrame object
Table of values of all observations of all variables, including any
specified exponential terms. | [
"Compute",
"exponential",
"expansions",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/confounds.py#L291-L327 | train | 211,753 |
poldracklab/niworkflows | niworkflows/interfaces/confounds.py | _order_as_range | def _order_as_range(order):
"""Convert a hyphenated string representing order for derivative or
exponential terms into a range object that can be passed as input to the
appropriate expansion function."""
order = order.split('-')
order = [int(o) for o in order]
if len(order) > 1:
order = range(order[0], (order[-1] + 1))
return order | python | def _order_as_range(order):
"""Convert a hyphenated string representing order for derivative or
exponential terms into a range object that can be passed as input to the
appropriate expansion function."""
order = order.split('-')
order = [int(o) for o in order]
if len(order) > 1:
order = range(order[0], (order[-1] + 1))
return order | [
"def",
"_order_as_range",
"(",
"order",
")",
":",
"order",
"=",
"order",
".",
"split",
"(",
"'-'",
")",
"order",
"=",
"[",
"int",
"(",
"o",
")",
"for",
"o",
"in",
"order",
"]",
"if",
"len",
"(",
"order",
")",
">",
"1",
":",
"order",
"=",
"range... | Convert a hyphenated string representing order for derivative or
exponential terms into a range object that can be passed as input to the
appropriate expansion function. | [
"Convert",
"a",
"hyphenated",
"string",
"representing",
"order",
"for",
"derivative",
"or",
"exponential",
"terms",
"into",
"a",
"range",
"object",
"that",
"can",
"be",
"passed",
"as",
"input",
"to",
"the",
"appropriate",
"expansion",
"function",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/confounds.py#L330-L338 | train | 211,754 |
poldracklab/niworkflows | niworkflows/interfaces/confounds.py | _check_and_expand_exponential | def _check_and_expand_exponential(expr, variables, data):
"""Check if the current operation specifies exponential expansion. ^^6
specifies all powers up to the 6th, ^5-6 the 5th and 6th powers, ^6 the
6th only."""
if re.search(r'\^\^[0-9]+$', expr):
order = re.compile(r'\^\^([0-9]+)$').findall(expr)
order = range(1, int(*order) + 1)
variables, data = exponential_terms(order, variables, data)
elif re.search(r'\^[0-9]+[\-]?[0-9]*$', expr):
order = re.compile(r'\^([0-9]+[\-]?[0-9]*)').findall(expr)
order = _order_as_range(*order)
variables, data = exponential_terms(order, variables, data)
return variables, data | python | def _check_and_expand_exponential(expr, variables, data):
"""Check if the current operation specifies exponential expansion. ^^6
specifies all powers up to the 6th, ^5-6 the 5th and 6th powers, ^6 the
6th only."""
if re.search(r'\^\^[0-9]+$', expr):
order = re.compile(r'\^\^([0-9]+)$').findall(expr)
order = range(1, int(*order) + 1)
variables, data = exponential_terms(order, variables, data)
elif re.search(r'\^[0-9]+[\-]?[0-9]*$', expr):
order = re.compile(r'\^([0-9]+[\-]?[0-9]*)').findall(expr)
order = _order_as_range(*order)
variables, data = exponential_terms(order, variables, data)
return variables, data | [
"def",
"_check_and_expand_exponential",
"(",
"expr",
",",
"variables",
",",
"data",
")",
":",
"if",
"re",
".",
"search",
"(",
"r'\\^\\^[0-9]+$'",
",",
"expr",
")",
":",
"order",
"=",
"re",
".",
"compile",
"(",
"r'\\^\\^([0-9]+)$'",
")",
".",
"findall",
"("... | Check if the current operation specifies exponential expansion. ^^6
specifies all powers up to the 6th, ^5-6 the 5th and 6th powers, ^6 the
6th only. | [
"Check",
"if",
"the",
"current",
"operation",
"specifies",
"exponential",
"expansion",
".",
"^^6",
"specifies",
"all",
"powers",
"up",
"to",
"the",
"6th",
"^5",
"-",
"6",
"the",
"5th",
"and",
"6th",
"powers",
"^6",
"the",
"6th",
"only",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/confounds.py#L341-L353 | train | 211,755 |
poldracklab/niworkflows | niworkflows/interfaces/confounds.py | _check_and_expand_derivative | def _check_and_expand_derivative(expr, variables, data):
"""Check if the current operation specifies a temporal derivative. dd6x
specifies all derivatives up to the 6th, d5-6x the 5th and 6th, d6x the
6th only."""
if re.search(r'^dd[0-9]+', expr):
order = re.compile(r'^dd([0-9]+)').findall(expr)
order = range(0, int(*order) + 1)
(variables, data) = temporal_derivatives(order, variables, data)
elif re.search(r'^d[0-9]+[\-]?[0-9]*', expr):
order = re.compile(r'^d([0-9]+[\-]?[0-9]*)').findall(expr)
order = _order_as_range(*order)
(variables, data) = temporal_derivatives(order, variables, data)
return variables, data | python | def _check_and_expand_derivative(expr, variables, data):
"""Check if the current operation specifies a temporal derivative. dd6x
specifies all derivatives up to the 6th, d5-6x the 5th and 6th, d6x the
6th only."""
if re.search(r'^dd[0-9]+', expr):
order = re.compile(r'^dd([0-9]+)').findall(expr)
order = range(0, int(*order) + 1)
(variables, data) = temporal_derivatives(order, variables, data)
elif re.search(r'^d[0-9]+[\-]?[0-9]*', expr):
order = re.compile(r'^d([0-9]+[\-]?[0-9]*)').findall(expr)
order = _order_as_range(*order)
(variables, data) = temporal_derivatives(order, variables, data)
return variables, data | [
"def",
"_check_and_expand_derivative",
"(",
"expr",
",",
"variables",
",",
"data",
")",
":",
"if",
"re",
".",
"search",
"(",
"r'^dd[0-9]+'",
",",
"expr",
")",
":",
"order",
"=",
"re",
".",
"compile",
"(",
"r'^dd([0-9]+)'",
")",
".",
"findall",
"(",
"expr... | Check if the current operation specifies a temporal derivative. dd6x
specifies all derivatives up to the 6th, d5-6x the 5th and 6th, d6x the
6th only. | [
"Check",
"if",
"the",
"current",
"operation",
"specifies",
"a",
"temporal",
"derivative",
".",
"dd6x",
"specifies",
"all",
"derivatives",
"up",
"to",
"the",
"6th",
"d5",
"-",
"6x",
"the",
"5th",
"and",
"6th",
"d6x",
"the",
"6th",
"only",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/confounds.py#L356-L368 | train | 211,756 |
poldracklab/niworkflows | niworkflows/interfaces/confounds.py | _check_and_expand_subformula | def _check_and_expand_subformula(expression, parent_data, variables, data):
"""Check if the current operation contains a suboperation, and parse it
where appropriate."""
grouping_depth = 0
for i, char in enumerate(expression):
if char == '(':
if grouping_depth == 0:
formula_delimiter = i + 1
grouping_depth += 1
elif char == ')':
grouping_depth -= 1
if grouping_depth == 0:
expr = expression[formula_delimiter:i].strip()
return parse_formula(expr, parent_data)
return variables, data | python | def _check_and_expand_subformula(expression, parent_data, variables, data):
"""Check if the current operation contains a suboperation, and parse it
where appropriate."""
grouping_depth = 0
for i, char in enumerate(expression):
if char == '(':
if grouping_depth == 0:
formula_delimiter = i + 1
grouping_depth += 1
elif char == ')':
grouping_depth -= 1
if grouping_depth == 0:
expr = expression[formula_delimiter:i].strip()
return parse_formula(expr, parent_data)
return variables, data | [
"def",
"_check_and_expand_subformula",
"(",
"expression",
",",
"parent_data",
",",
"variables",
",",
"data",
")",
":",
"grouping_depth",
"=",
"0",
"for",
"i",
",",
"char",
"in",
"enumerate",
"(",
"expression",
")",
":",
"if",
"char",
"==",
"'('",
":",
"if"... | Check if the current operation contains a suboperation, and parse it
where appropriate. | [
"Check",
"if",
"the",
"current",
"operation",
"contains",
"a",
"suboperation",
"and",
"parse",
"it",
"where",
"appropriate",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/confounds.py#L371-L385 | train | 211,757 |
poldracklab/niworkflows | niworkflows/interfaces/confounds.py | parse_expression | def parse_expression(expression, parent_data):
"""
Parse an expression in a model formula.
Parameters
----------
expression: str
Formula expression: either a single variable or a variable group
paired with an operation (exponentiation or differentiation).
parent_data: pandas DataFrame
The source data for the model expansion.
Returns
-------
variables: list
A list of variables in the provided formula expression.
data: pandas DataFrame
A tabulation of all terms in the provided formula expression.
"""
variables = None
data = None
variables, data = _check_and_expand_subformula(expression,
parent_data,
variables,
data)
variables, data = _check_and_expand_exponential(expression,
variables,
data)
variables, data = _check_and_expand_derivative(expression,
variables,
data)
if variables is None:
expr = expression.strip()
variables = [expr]
data = parent_data[expr]
return variables, data | python | def parse_expression(expression, parent_data):
"""
Parse an expression in a model formula.
Parameters
----------
expression: str
Formula expression: either a single variable or a variable group
paired with an operation (exponentiation or differentiation).
parent_data: pandas DataFrame
The source data for the model expansion.
Returns
-------
variables: list
A list of variables in the provided formula expression.
data: pandas DataFrame
A tabulation of all terms in the provided formula expression.
"""
variables = None
data = None
variables, data = _check_and_expand_subformula(expression,
parent_data,
variables,
data)
variables, data = _check_and_expand_exponential(expression,
variables,
data)
variables, data = _check_and_expand_derivative(expression,
variables,
data)
if variables is None:
expr = expression.strip()
variables = [expr]
data = parent_data[expr]
return variables, data | [
"def",
"parse_expression",
"(",
"expression",
",",
"parent_data",
")",
":",
"variables",
"=",
"None",
"data",
"=",
"None",
"variables",
",",
"data",
"=",
"_check_and_expand_subformula",
"(",
"expression",
",",
"parent_data",
",",
"variables",
",",
"data",
")",
... | Parse an expression in a model formula.
Parameters
----------
expression: str
Formula expression: either a single variable or a variable group
paired with an operation (exponentiation or differentiation).
parent_data: pandas DataFrame
The source data for the model expansion.
Returns
-------
variables: list
A list of variables in the provided formula expression.
data: pandas DataFrame
A tabulation of all terms in the provided formula expression. | [
"Parse",
"an",
"expression",
"in",
"a",
"model",
"formula",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/confounds.py#L388-L423 | train | 211,758 |
poldracklab/niworkflows | niworkflows/interfaces/confounds.py | _expand_shorthand | def _expand_shorthand(model_formula, variables):
"""Expand shorthand terms in the model formula.
"""
wm = 'white_matter'
gsr = 'global_signal'
rps = 'trans_x + trans_y + trans_z + rot_x + rot_y + rot_z'
fd = 'framewise_displacement'
acc = _get_matches_from_data('a_comp_cor_[0-9]+', variables)
tcc = _get_matches_from_data('t_comp_cor_[0-9]+', variables)
dv = _get_matches_from_data('^std_dvars$', variables)
dvall = _get_matches_from_data('.*dvars', variables)
nss = _get_matches_from_data('non_steady_state_outlier[0-9]+',
variables)
spikes = _get_matches_from_data('motion_outlier[0-9]+', variables)
model_formula = re.sub('wm', wm, model_formula)
model_formula = re.sub('gsr', gsr, model_formula)
model_formula = re.sub('rps', rps, model_formula)
model_formula = re.sub('fd', fd, model_formula)
model_formula = re.sub('acc', acc, model_formula)
model_formula = re.sub('tcc', tcc, model_formula)
model_formula = re.sub('dv', dv, model_formula)
model_formula = re.sub('dvall', dvall, model_formula)
model_formula = re.sub('nss', nss, model_formula)
model_formula = re.sub('spikes', spikes, model_formula)
formula_variables = _get_variables_from_formula(model_formula)
others = ' + '.join(set(variables) - set(formula_variables))
model_formula = re.sub('others', others, model_formula)
return model_formula | python | def _expand_shorthand(model_formula, variables):
"""Expand shorthand terms in the model formula.
"""
wm = 'white_matter'
gsr = 'global_signal'
rps = 'trans_x + trans_y + trans_z + rot_x + rot_y + rot_z'
fd = 'framewise_displacement'
acc = _get_matches_from_data('a_comp_cor_[0-9]+', variables)
tcc = _get_matches_from_data('t_comp_cor_[0-9]+', variables)
dv = _get_matches_from_data('^std_dvars$', variables)
dvall = _get_matches_from_data('.*dvars', variables)
nss = _get_matches_from_data('non_steady_state_outlier[0-9]+',
variables)
spikes = _get_matches_from_data('motion_outlier[0-9]+', variables)
model_formula = re.sub('wm', wm, model_formula)
model_formula = re.sub('gsr', gsr, model_formula)
model_formula = re.sub('rps', rps, model_formula)
model_formula = re.sub('fd', fd, model_formula)
model_formula = re.sub('acc', acc, model_formula)
model_formula = re.sub('tcc', tcc, model_formula)
model_formula = re.sub('dv', dv, model_formula)
model_formula = re.sub('dvall', dvall, model_formula)
model_formula = re.sub('nss', nss, model_formula)
model_formula = re.sub('spikes', spikes, model_formula)
formula_variables = _get_variables_from_formula(model_formula)
others = ' + '.join(set(variables) - set(formula_variables))
model_formula = re.sub('others', others, model_formula)
return model_formula | [
"def",
"_expand_shorthand",
"(",
"model_formula",
",",
"variables",
")",
":",
"wm",
"=",
"'white_matter'",
"gsr",
"=",
"'global_signal'",
"rps",
"=",
"'trans_x + trans_y + trans_z + rot_x + rot_y + rot_z'",
"fd",
"=",
"'framewise_displacement'",
"acc",
"=",
"_get_matches_... | Expand shorthand terms in the model formula. | [
"Expand",
"shorthand",
"terms",
"in",
"the",
"model",
"formula",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/confounds.py#L441-L470 | train | 211,759 |
poldracklab/niworkflows | niworkflows/interfaces/confounds.py | _unscramble_regressor_columns | def _unscramble_regressor_columns(parent_data, data):
"""Reorder the columns of a confound matrix such that the columns are in
the same order as the input data with any expansion columns inserted
immediately after the originals.
"""
matches = ['_power[0-9]+', '_derivative[0-9]+']
var = OrderedDict((c, deque()) for c in parent_data.columns)
for c in data.columns:
col = c
for m in matches:
col = re.sub(m, '', col)
if col == c:
var[col].appendleft(c)
else:
var[col].append(c)
unscrambled = reduce((lambda x, y: x + y), var.values())
return data[[*unscrambled]] | python | def _unscramble_regressor_columns(parent_data, data):
"""Reorder the columns of a confound matrix such that the columns are in
the same order as the input data with any expansion columns inserted
immediately after the originals.
"""
matches = ['_power[0-9]+', '_derivative[0-9]+']
var = OrderedDict((c, deque()) for c in parent_data.columns)
for c in data.columns:
col = c
for m in matches:
col = re.sub(m, '', col)
if col == c:
var[col].appendleft(c)
else:
var[col].append(c)
unscrambled = reduce((lambda x, y: x + y), var.values())
return data[[*unscrambled]] | [
"def",
"_unscramble_regressor_columns",
"(",
"parent_data",
",",
"data",
")",
":",
"matches",
"=",
"[",
"'_power[0-9]+'",
",",
"'_derivative[0-9]+'",
"]",
"var",
"=",
"OrderedDict",
"(",
"(",
"c",
",",
"deque",
"(",
")",
")",
"for",
"c",
"in",
"parent_data",... | Reorder the columns of a confound matrix such that the columns are in
the same order as the input data with any expansion columns inserted
immediately after the originals. | [
"Reorder",
"the",
"columns",
"of",
"a",
"confound",
"matrix",
"such",
"that",
"the",
"columns",
"are",
"in",
"the",
"same",
"order",
"as",
"the",
"input",
"data",
"with",
"any",
"expansion",
"columns",
"inserted",
"immediately",
"after",
"the",
"originals",
... | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/confounds.py#L473-L489 | train | 211,760 |
poldracklab/niworkflows | niworkflows/interfaces/confounds.py | parse_formula | def parse_formula(model_formula, parent_data, unscramble=False):
"""
Recursively parse a model formula by breaking it into additive atoms
and tracking grouping symbol depth.
Parameters
----------
model_formula: str
Expression for the model formula, e.g.
'(a + b)^^2 + dd1(c + (d + e)^3) + f'
Note that any expressions to be expanded *must* be in parentheses,
even if they include only a single variable (e.g., (x)^2, not x^2).
parent_data: pandas DataFrame
A tabulation of all values usable in the model formula. Each additive
term in `model_formula` should correspond either to a variable in this
data frame or to instructions for operating on a variable (for
instance, computing temporal derivatives or exponential terms).
Temporal derivative options:
* d6(variable) for the 6th temporal derivative
* dd6(variable) for all temporal derivatives up to the 6th
* d4-6(variable) for the 4th through 6th temporal derivatives
* 0 must be included in the temporal derivative range for the original
term to be returned when temporal derivatives are computed.
Exponential options:
* (variable)^6 for the 6th power
* (variable)^^6 for all powers up to the 6th
* (variable)^4-6 for the 4th through 6th powers
* 1 must be included in the powers range for the original term to be
returned when exponential terms are computed.
Temporal derivatives and exponential terms are computed for all terms
in the grouping symbols that they adjoin.
Returns
-------
variables: list(str)
A list of variables included in the model parsed from the provided
formula.
data: pandas DataFrame
All values in the complete model.
"""
variables = {}
data = {}
expr_delimiter = 0
grouping_depth = 0
model_formula = _expand_shorthand(model_formula, parent_data.columns)
for i, char in enumerate(model_formula):
if char == '(':
grouping_depth += 1
elif char == ')':
grouping_depth -= 1
elif grouping_depth == 0 and char == '+':
expression = model_formula[expr_delimiter:i].strip()
variables[expression] = None
data[expression] = None
expr_delimiter = i + 1
expression = model_formula[expr_delimiter:].strip()
variables[expression] = None
data[expression] = None
for expression in list(variables):
if expression[0] == '(' and expression[-1] == ')':
(variables[expression],
data[expression]) = parse_formula(expression[1:-1],
parent_data)
else:
(variables[expression],
data[expression]) = parse_expression(expression,
parent_data)
variables = list(set(reduce((lambda x, y: x + y), variables.values())))
data = pd.concat((data.values()), axis=1)
if unscramble:
data = _unscramble_regressor_columns(parent_data, data)
return variables, data | python | def parse_formula(model_formula, parent_data, unscramble=False):
"""
Recursively parse a model formula by breaking it into additive atoms
and tracking grouping symbol depth.
Parameters
----------
model_formula: str
Expression for the model formula, e.g.
'(a + b)^^2 + dd1(c + (d + e)^3) + f'
Note that any expressions to be expanded *must* be in parentheses,
even if they include only a single variable (e.g., (x)^2, not x^2).
parent_data: pandas DataFrame
A tabulation of all values usable in the model formula. Each additive
term in `model_formula` should correspond either to a variable in this
data frame or to instructions for operating on a variable (for
instance, computing temporal derivatives or exponential terms).
Temporal derivative options:
* d6(variable) for the 6th temporal derivative
* dd6(variable) for all temporal derivatives up to the 6th
* d4-6(variable) for the 4th through 6th temporal derivatives
* 0 must be included in the temporal derivative range for the original
term to be returned when temporal derivatives are computed.
Exponential options:
* (variable)^6 for the 6th power
* (variable)^^6 for all powers up to the 6th
* (variable)^4-6 for the 4th through 6th powers
* 1 must be included in the powers range for the original term to be
returned when exponential terms are computed.
Temporal derivatives and exponential terms are computed for all terms
in the grouping symbols that they adjoin.
Returns
-------
variables: list(str)
A list of variables included in the model parsed from the provided
formula.
data: pandas DataFrame
All values in the complete model.
"""
variables = {}
data = {}
expr_delimiter = 0
grouping_depth = 0
model_formula = _expand_shorthand(model_formula, parent_data.columns)
for i, char in enumerate(model_formula):
if char == '(':
grouping_depth += 1
elif char == ')':
grouping_depth -= 1
elif grouping_depth == 0 and char == '+':
expression = model_formula[expr_delimiter:i].strip()
variables[expression] = None
data[expression] = None
expr_delimiter = i + 1
expression = model_formula[expr_delimiter:].strip()
variables[expression] = None
data[expression] = None
for expression in list(variables):
if expression[0] == '(' and expression[-1] == ')':
(variables[expression],
data[expression]) = parse_formula(expression[1:-1],
parent_data)
else:
(variables[expression],
data[expression]) = parse_expression(expression,
parent_data)
variables = list(set(reduce((lambda x, y: x + y), variables.values())))
data = pd.concat((data.values()), axis=1)
if unscramble:
data = _unscramble_regressor_columns(parent_data, data)
return variables, data | [
"def",
"parse_formula",
"(",
"model_formula",
",",
"parent_data",
",",
"unscramble",
"=",
"False",
")",
":",
"variables",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"expr_delimiter",
"=",
"0",
"grouping_depth",
"=",
"0",
"model_formula",
"=",
"_expand_shorthand",
... | Recursively parse a model formula by breaking it into additive atoms
and tracking grouping symbol depth.
Parameters
----------
model_formula: str
Expression for the model formula, e.g.
'(a + b)^^2 + dd1(c + (d + e)^3) + f'
Note that any expressions to be expanded *must* be in parentheses,
even if they include only a single variable (e.g., (x)^2, not x^2).
parent_data: pandas DataFrame
A tabulation of all values usable in the model formula. Each additive
term in `model_formula` should correspond either to a variable in this
data frame or to instructions for operating on a variable (for
instance, computing temporal derivatives or exponential terms).
Temporal derivative options:
* d6(variable) for the 6th temporal derivative
* dd6(variable) for all temporal derivatives up to the 6th
* d4-6(variable) for the 4th through 6th temporal derivatives
* 0 must be included in the temporal derivative range for the original
term to be returned when temporal derivatives are computed.
Exponential options:
* (variable)^6 for the 6th power
* (variable)^^6 for all powers up to the 6th
* (variable)^4-6 for the 4th through 6th powers
* 1 must be included in the powers range for the original term to be
returned when exponential terms are computed.
Temporal derivatives and exponential terms are computed for all terms
in the grouping symbols that they adjoin.
Returns
-------
variables: list(str)
A list of variables included in the model parsed from the provided
formula.
data: pandas DataFrame
All values in the complete model. | [
"Recursively",
"parse",
"a",
"model",
"formula",
"by",
"breaking",
"it",
"into",
"additive",
"atoms",
"and",
"tracking",
"grouping",
"symbol",
"depth",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/confounds.py#L492-L568 | train | 211,761 |
poldracklab/niworkflows | niworkflows/interfaces/mni.py | mask | def mask(in_file, mask_file, new_name):
"""
Apply a binary mask to an image.
Parameters
----------
in_file : str
Path to a NIfTI file to mask
mask_file : str
Path to a binary mask
new_name : str
Path/filename for the masked output image.
Returns
-------
str
Absolute path of the masked output image.
Notes
-----
in_file and mask_file must be in the same
image space and have the same dimensions.
"""
import nibabel as nb
import os
# Load the input image
in_nii = nb.load(in_file)
# Load the mask image
mask_nii = nb.load(mask_file)
# Set all non-mask voxels in the input file to zero.
data = in_nii.get_data()
data[mask_nii.get_data() == 0] = 0
# Save the new masked image.
new_nii = nb.Nifti1Image(data, in_nii.affine, in_nii.header)
new_nii.to_filename(new_name)
return os.path.abspath(new_name) | python | def mask(in_file, mask_file, new_name):
"""
Apply a binary mask to an image.
Parameters
----------
in_file : str
Path to a NIfTI file to mask
mask_file : str
Path to a binary mask
new_name : str
Path/filename for the masked output image.
Returns
-------
str
Absolute path of the masked output image.
Notes
-----
in_file and mask_file must be in the same
image space and have the same dimensions.
"""
import nibabel as nb
import os
# Load the input image
in_nii = nb.load(in_file)
# Load the mask image
mask_nii = nb.load(mask_file)
# Set all non-mask voxels in the input file to zero.
data = in_nii.get_data()
data[mask_nii.get_data() == 0] = 0
# Save the new masked image.
new_nii = nb.Nifti1Image(data, in_nii.affine, in_nii.header)
new_nii.to_filename(new_name)
return os.path.abspath(new_name) | [
"def",
"mask",
"(",
"in_file",
",",
"mask_file",
",",
"new_name",
")",
":",
"import",
"nibabel",
"as",
"nb",
"import",
"os",
"# Load the input image",
"in_nii",
"=",
"nb",
".",
"load",
"(",
"in_file",
")",
"# Load the mask image",
"mask_nii",
"=",
"nb",
".",... | Apply a binary mask to an image.
Parameters
----------
in_file : str
Path to a NIfTI file to mask
mask_file : str
Path to a binary mask
new_name : str
Path/filename for the masked output image.
Returns
-------
str
Absolute path of the masked output image.
Notes
-----
in_file and mask_file must be in the same
image space and have the same dimensions. | [
"Apply",
"a",
"binary",
"mask",
"to",
"an",
"image",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/mni.py#L398-L433 | train | 211,762 |
poldracklab/niworkflows | niworkflows/interfaces/mni.py | create_cfm | def create_cfm(in_file, lesion_mask=None, global_mask=True, out_path=None):
"""
Create a mask to constrain registration.
Parameters
----------
in_file : str
Path to an existing image (usually a mask).
If global_mask = True, this is used as a size/dimension reference.
out_path : str
Path/filename for the new cost function mask.
lesion_mask : str, optional
Path to an existing binary lesion mask.
global_mask : bool
Create a whole-image mask (True) or limit to reference mask (False)
A whole image-mask is 1 everywhere
Returns
-------
str
Absolute path of the new cost function mask.
Notes
-----
in_file and lesion_mask must be in the same
image space and have the same dimensions
"""
import os
import numpy as np
import nibabel as nb
from nipype.utils.filemanip import fname_presuffix
if out_path is None:
out_path = fname_presuffix(in_file, suffix='_cfm', newpath=os.getcwd())
else:
out_path = os.path.abspath(out_path)
if not global_mask and not lesion_mask:
NIWORKFLOWS_LOG.warning(
'No lesion mask was provided and global_mask not requested, '
'therefore the original mask will not be modified.')
# Load the input image
in_img = nb.load(in_file)
# If we want a global mask, create one based on the input image.
data = np.ones(in_img.shape, dtype=np.uint8) if global_mask else in_img.get_data()
if set(np.unique(data)) - {0, 1}:
raise ValueError("`global_mask` must be true if `in_file` is not a binary mask")
# If a lesion mask was provided, combine it with the secondary mask.
if lesion_mask is not None:
# Reorient the lesion mask and get the data.
lm_img = nb.as_closest_canonical(nb.load(lesion_mask))
# Subtract lesion mask from secondary mask, set negatives to 0
data = np.fmax(data - lm_img.get_data(), 0)
# Cost function mask will be created from subtraction
# Otherwise, CFM will be created from global mask
cfm_img = nb.Nifti1Image(data, in_img.affine, in_img.header)
# Save the cost function mask.
cfm_img.set_data_dtype(np.uint8)
cfm_img.to_filename(out_path)
return out_path | python | def create_cfm(in_file, lesion_mask=None, global_mask=True, out_path=None):
"""
Create a mask to constrain registration.
Parameters
----------
in_file : str
Path to an existing image (usually a mask).
If global_mask = True, this is used as a size/dimension reference.
out_path : str
Path/filename for the new cost function mask.
lesion_mask : str, optional
Path to an existing binary lesion mask.
global_mask : bool
Create a whole-image mask (True) or limit to reference mask (False)
A whole image-mask is 1 everywhere
Returns
-------
str
Absolute path of the new cost function mask.
Notes
-----
in_file and lesion_mask must be in the same
image space and have the same dimensions
"""
import os
import numpy as np
import nibabel as nb
from nipype.utils.filemanip import fname_presuffix
if out_path is None:
out_path = fname_presuffix(in_file, suffix='_cfm', newpath=os.getcwd())
else:
out_path = os.path.abspath(out_path)
if not global_mask and not lesion_mask:
NIWORKFLOWS_LOG.warning(
'No lesion mask was provided and global_mask not requested, '
'therefore the original mask will not be modified.')
# Load the input image
in_img = nb.load(in_file)
# If we want a global mask, create one based on the input image.
data = np.ones(in_img.shape, dtype=np.uint8) if global_mask else in_img.get_data()
if set(np.unique(data)) - {0, 1}:
raise ValueError("`global_mask` must be true if `in_file` is not a binary mask")
# If a lesion mask was provided, combine it with the secondary mask.
if lesion_mask is not None:
# Reorient the lesion mask and get the data.
lm_img = nb.as_closest_canonical(nb.load(lesion_mask))
# Subtract lesion mask from secondary mask, set negatives to 0
data = np.fmax(data - lm_img.get_data(), 0)
# Cost function mask will be created from subtraction
# Otherwise, CFM will be created from global mask
cfm_img = nb.Nifti1Image(data, in_img.affine, in_img.header)
# Save the cost function mask.
cfm_img.set_data_dtype(np.uint8)
cfm_img.to_filename(out_path)
return out_path | [
"def",
"create_cfm",
"(",
"in_file",
",",
"lesion_mask",
"=",
"None",
",",
"global_mask",
"=",
"True",
",",
"out_path",
"=",
"None",
")",
":",
"import",
"os",
"import",
"numpy",
"as",
"np",
"import",
"nibabel",
"as",
"nb",
"from",
"nipype",
".",
"utils",... | Create a mask to constrain registration.
Parameters
----------
in_file : str
Path to an existing image (usually a mask).
If global_mask = True, this is used as a size/dimension reference.
out_path : str
Path/filename for the new cost function mask.
lesion_mask : str, optional
Path to an existing binary lesion mask.
global_mask : bool
Create a whole-image mask (True) or limit to reference mask (False)
A whole image-mask is 1 everywhere
Returns
-------
str
Absolute path of the new cost function mask.
Notes
-----
in_file and lesion_mask must be in the same
image space and have the same dimensions | [
"Create",
"a",
"mask",
"to",
"constrain",
"registration",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/mni.py#L436-L502 | train | 211,763 |
poldracklab/niworkflows | niworkflows/interfaces/mni.py | RobustMNINormalization._get_settings | def _get_settings(self):
"""
Return any settings defined by the user, as well as any pre-defined
settings files that exist for the image modalities to be registered.
"""
# If user-defined settings exist...
if isdefined(self.inputs.settings):
# Note this in the log and return those settings.
NIWORKFLOWS_LOG.info('User-defined settings, overriding defaults')
return self.inputs.settings
# Define a prefix for output files based on the modality of the moving image.
filestart = '{}-mni_registration_{}_'.format(
self.inputs.moving.lower(), self.inputs.flavor)
# Get a list of settings files that match the flavor.
filenames = [i for i in pkgr.resource_listdir('niworkflows', 'data')
if i.startswith(filestart) and i.endswith('.json')]
# Return the settings files.
return [pkgr.resource_filename('niworkflows.data', f)
for f in sorted(filenames)] | python | def _get_settings(self):
"""
Return any settings defined by the user, as well as any pre-defined
settings files that exist for the image modalities to be registered.
"""
# If user-defined settings exist...
if isdefined(self.inputs.settings):
# Note this in the log and return those settings.
NIWORKFLOWS_LOG.info('User-defined settings, overriding defaults')
return self.inputs.settings
# Define a prefix for output files based on the modality of the moving image.
filestart = '{}-mni_registration_{}_'.format(
self.inputs.moving.lower(), self.inputs.flavor)
# Get a list of settings files that match the flavor.
filenames = [i for i in pkgr.resource_listdir('niworkflows', 'data')
if i.startswith(filestart) and i.endswith('.json')]
# Return the settings files.
return [pkgr.resource_filename('niworkflows.data', f)
for f in sorted(filenames)] | [
"def",
"_get_settings",
"(",
"self",
")",
":",
"# If user-defined settings exist...",
"if",
"isdefined",
"(",
"self",
".",
"inputs",
".",
"settings",
")",
":",
"# Note this in the log and return those settings.",
"NIWORKFLOWS_LOG",
".",
"info",
"(",
"'User-defined setting... | Return any settings defined by the user, as well as any pre-defined
settings files that exist for the image modalities to be registered. | [
"Return",
"any",
"settings",
"defined",
"by",
"the",
"user",
"as",
"well",
"as",
"any",
"pre",
"-",
"defined",
"settings",
"files",
"that",
"exist",
"for",
"the",
"image",
"modalities",
"to",
"be",
"registered",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/mni.py#L100-L120 | train | 211,764 |
poldracklab/niworkflows | niworkflows/interfaces/mni.py | RobustMNINormalization._get_ants_args | def _get_ants_args(self):
args = {'moving_image': self.inputs.moving_image,
'num_threads': self.inputs.num_threads,
'float': self.inputs.float,
'terminal_output': 'file',
'write_composite_transform': True,
'initial_moving_transform': self.inputs.initial_moving_transform}
"""
Moving image handling - The following truth table maps out the intended action
sequence. Future refactoring may more directly encode this.
moving_mask and lesion_mask are files
True = file
False = None
| moving_mask | explicit_masking | lesion_mask | action
|-------------|------------------|-------------|-------------------------------------------
| True | True | True | Update `moving_image` after applying
| | | | mask.
| | | | Set `moving_image_masks` applying
| | | | `create_cfm` with `global_mask=True`.
|-------------|------------------|-------------|-------------------------------------------
| True | True | False | Update `moving_image` after applying
| | | | mask.
|-------------|------------------|-------------|-------------------------------------------
| True | False | True | Set `moving_image_masks` applying
| | | | `create_cfm` with `global_mask=False`
|-------------|------------------|-------------|-------------------------------------------
| True | False | False | args['moving_image_masks'] = moving_mask
|-------------|------------------|-------------|-------------------------------------------
| False | * | True | Set `moving_image_masks` applying
| | | | `create_cfm` with `global_mask=True`
|-------------|------------------|-------------|-------------------------------------------
| False | * | False | No action
"""
# If a moving mask is provided...
if isdefined(self.inputs.moving_mask):
# If explicit masking is enabled...
if self.inputs.explicit_masking:
# Mask the moving image.
# Do not use a moving mask during registration.
args['moving_image'] = mask(
self.inputs.moving_image,
self.inputs.moving_mask,
"moving_masked.nii.gz")
# If explicit masking is disabled...
else:
# Use the moving mask during registration.
# Do not mask the moving image.
args['moving_image_masks'] = self.inputs.moving_mask
# If a lesion mask is also provided...
if isdefined(self.inputs.lesion_mask):
# Create a cost function mask with the form:
# [global mask - lesion mask] (if explicit masking is enabled)
# [moving mask - lesion mask] (if explicit masking is disabled)
# Use this as the moving mask.
args['moving_image_masks'] = create_cfm(
self.inputs.moving_mask,
lesion_mask=self.inputs.lesion_mask,
global_mask=self.inputs.explicit_masking)
# If no moving mask is provided...
# But a lesion mask *IS* provided...
elif isdefined(self.inputs.lesion_mask):
# Create a cost function mask with the form: [global mask - lesion mask]
# Use this as the moving mask.
args['moving_image_masks'] = create_cfm(
self.inputs.moving_image,
lesion_mask=self.inputs.lesion_mask,
global_mask=True)
"""
Reference image handling - The following truth table maps out the intended action
sequence. Future refactoring may more directly encode this.
reference_mask and lesion_mask are files
True = file
False = None
| reference_mask | explicit_masking | lesion_mask | action
|----------------|------------------|-------------|----------------------------------------
| True | True | True | Update `fixed_image` after applying
| | | | mask.
| | | | Set `fixed_image_masks` applying
| | | | `create_cfm` with `global_mask=True`.
|----------------|------------------|-------------|----------------------------------------
| True | True | False | Update `fixed_image` after applying
| | | | mask.
|----------------|------------------|-------------|----------------------------------------
| True | False | True | Set `fixed_image_masks` applying
| | | | `create_cfm` with `global_mask=False`
|----------------|------------------|-------------|----------------------------------------
| True | False | False | args['fixed_image_masks'] = fixed_mask
|----------------|------------------|-------------|----------------------------------------
| False | * | True | Set `fixed_image_masks` applying
| | | | `create_cfm` with `global_mask=True`
|----------------|------------------|-------------|----------------------------------------
| False | * | False | No action
"""
# If a reference image is provided...
if isdefined(self.inputs.reference_image):
# Use the reference image as the fixed image.
args['fixed_image'] = self.inputs.reference_image
# If a reference mask is provided...
if isdefined(self.inputs.reference_mask):
# If explicit masking is enabled...
if self.inputs.explicit_masking:
# Mask the reference image.
# Do not use a fixed mask during registration.
args['fixed_image'] = mask(
self.inputs.reference_image,
self.inputs.reference_mask,
"fixed_masked.nii.gz")
# If a lesion mask is also provided...
if isdefined(self.inputs.lesion_mask):
# Create a cost function mask with the form: [global mask]
# Use this as the fixed mask.
args['fixed_image_masks'] = create_cfm(
self.inputs.reference_mask,
lesion_mask=None,
global_mask=True)
# If a reference mask is provided...
# But explicit masking is disabled...
else:
# Use the reference mask as the fixed mask during registration.
# Do not mask the fixed image.
args['fixed_image_masks'] = self.inputs.reference_mask
# If no reference mask is provided...
# But a lesion mask *IS* provided ...
elif isdefined(self.inputs.lesion_mask):
# Create a cost function mask with the form: [global mask]
# Use this as the fixed mask
args['fixed_image_masks'] = create_cfm(
self.inputs.reference_image,
lesion_mask=None,
global_mask=True)
# If no reference image is provided, fall back to the default template.
else:
# Raise an error if the user specifies an unsupported image orientation.
if self.inputs.orientation == 'LAS':
raise NotImplementedError
# Set the template resolution.
resolution = self.inputs.template_resolution
# Get the template specified by the user.
ref_template = get_template(self.inputs.template, resolution=resolution,
desc=None, suffix=self.inputs.reference)
ref_mask = get_template(self.inputs.template, resolution=resolution,
desc='brain', suffix='mask')
# Default is explicit masking disabled
args['fixed_image'] = str(ref_template)
# Use the template mask as the fixed mask.
args['fixed_image_masks'] = str(ref_mask)
# Overwrite defaults if explicit masking
if self.inputs.explicit_masking:
# Mask the template image with the template mask.
args['fixed_image'] = mask(str(ref_template), str(ref_mask),
"fixed_masked.nii.gz")
# Do not use a fixed mask during registration.
args.pop('fixed_image_masks', None)
# If a lesion mask is provided...
if isdefined(self.inputs.lesion_mask):
# Create a cost function mask with the form: [global mask]
# Use this as the fixed mask.
args['fixed_image_masks'] = create_cfm(
str(ref_mask), lesion_mask=None, global_mask=True)
return args | python | def _get_ants_args(self):
args = {'moving_image': self.inputs.moving_image,
'num_threads': self.inputs.num_threads,
'float': self.inputs.float,
'terminal_output': 'file',
'write_composite_transform': True,
'initial_moving_transform': self.inputs.initial_moving_transform}
"""
Moving image handling - The following truth table maps out the intended action
sequence. Future refactoring may more directly encode this.
moving_mask and lesion_mask are files
True = file
False = None
| moving_mask | explicit_masking | lesion_mask | action
|-------------|------------------|-------------|-------------------------------------------
| True | True | True | Update `moving_image` after applying
| | | | mask.
| | | | Set `moving_image_masks` applying
| | | | `create_cfm` with `global_mask=True`.
|-------------|------------------|-------------|-------------------------------------------
| True | True | False | Update `moving_image` after applying
| | | | mask.
|-------------|------------------|-------------|-------------------------------------------
| True | False | True | Set `moving_image_masks` applying
| | | | `create_cfm` with `global_mask=False`
|-------------|------------------|-------------|-------------------------------------------
| True | False | False | args['moving_image_masks'] = moving_mask
|-------------|------------------|-------------|-------------------------------------------
| False | * | True | Set `moving_image_masks` applying
| | | | `create_cfm` with `global_mask=True`
|-------------|------------------|-------------|-------------------------------------------
| False | * | False | No action
"""
# If a moving mask is provided...
if isdefined(self.inputs.moving_mask):
# If explicit masking is enabled...
if self.inputs.explicit_masking:
# Mask the moving image.
# Do not use a moving mask during registration.
args['moving_image'] = mask(
self.inputs.moving_image,
self.inputs.moving_mask,
"moving_masked.nii.gz")
# If explicit masking is disabled...
else:
# Use the moving mask during registration.
# Do not mask the moving image.
args['moving_image_masks'] = self.inputs.moving_mask
# If a lesion mask is also provided...
if isdefined(self.inputs.lesion_mask):
# Create a cost function mask with the form:
# [global mask - lesion mask] (if explicit masking is enabled)
# [moving mask - lesion mask] (if explicit masking is disabled)
# Use this as the moving mask.
args['moving_image_masks'] = create_cfm(
self.inputs.moving_mask,
lesion_mask=self.inputs.lesion_mask,
global_mask=self.inputs.explicit_masking)
# If no moving mask is provided...
# But a lesion mask *IS* provided...
elif isdefined(self.inputs.lesion_mask):
# Create a cost function mask with the form: [global mask - lesion mask]
# Use this as the moving mask.
args['moving_image_masks'] = create_cfm(
self.inputs.moving_image,
lesion_mask=self.inputs.lesion_mask,
global_mask=True)
"""
Reference image handling - The following truth table maps out the intended action
sequence. Future refactoring may more directly encode this.
reference_mask and lesion_mask are files
True = file
False = None
| reference_mask | explicit_masking | lesion_mask | action
|----------------|------------------|-------------|----------------------------------------
| True | True | True | Update `fixed_image` after applying
| | | | mask.
| | | | Set `fixed_image_masks` applying
| | | | `create_cfm` with `global_mask=True`.
|----------------|------------------|-------------|----------------------------------------
| True | True | False | Update `fixed_image` after applying
| | | | mask.
|----------------|------------------|-------------|----------------------------------------
| True | False | True | Set `fixed_image_masks` applying
| | | | `create_cfm` with `global_mask=False`
|----------------|------------------|-------------|----------------------------------------
| True | False | False | args['fixed_image_masks'] = fixed_mask
|----------------|------------------|-------------|----------------------------------------
| False | * | True | Set `fixed_image_masks` applying
| | | | `create_cfm` with `global_mask=True`
|----------------|------------------|-------------|----------------------------------------
| False | * | False | No action
"""
# If a reference image is provided...
if isdefined(self.inputs.reference_image):
# Use the reference image as the fixed image.
args['fixed_image'] = self.inputs.reference_image
# If a reference mask is provided...
if isdefined(self.inputs.reference_mask):
# If explicit masking is enabled...
if self.inputs.explicit_masking:
# Mask the reference image.
# Do not use a fixed mask during registration.
args['fixed_image'] = mask(
self.inputs.reference_image,
self.inputs.reference_mask,
"fixed_masked.nii.gz")
# If a lesion mask is also provided...
if isdefined(self.inputs.lesion_mask):
# Create a cost function mask with the form: [global mask]
# Use this as the fixed mask.
args['fixed_image_masks'] = create_cfm(
self.inputs.reference_mask,
lesion_mask=None,
global_mask=True)
# If a reference mask is provided...
# But explicit masking is disabled...
else:
# Use the reference mask as the fixed mask during registration.
# Do not mask the fixed image.
args['fixed_image_masks'] = self.inputs.reference_mask
# If no reference mask is provided...
# But a lesion mask *IS* provided ...
elif isdefined(self.inputs.lesion_mask):
# Create a cost function mask with the form: [global mask]
# Use this as the fixed mask
args['fixed_image_masks'] = create_cfm(
self.inputs.reference_image,
lesion_mask=None,
global_mask=True)
# If no reference image is provided, fall back to the default template.
else:
# Raise an error if the user specifies an unsupported image orientation.
if self.inputs.orientation == 'LAS':
raise NotImplementedError
# Set the template resolution.
resolution = self.inputs.template_resolution
# Get the template specified by the user.
ref_template = get_template(self.inputs.template, resolution=resolution,
desc=None, suffix=self.inputs.reference)
ref_mask = get_template(self.inputs.template, resolution=resolution,
desc='brain', suffix='mask')
# Default is explicit masking disabled
args['fixed_image'] = str(ref_template)
# Use the template mask as the fixed mask.
args['fixed_image_masks'] = str(ref_mask)
# Overwrite defaults if explicit masking
if self.inputs.explicit_masking:
# Mask the template image with the template mask.
args['fixed_image'] = mask(str(ref_template), str(ref_mask),
"fixed_masked.nii.gz")
# Do not use a fixed mask during registration.
args.pop('fixed_image_masks', None)
# If a lesion mask is provided...
if isdefined(self.inputs.lesion_mask):
# Create a cost function mask with the form: [global mask]
# Use this as the fixed mask.
args['fixed_image_masks'] = create_cfm(
str(ref_mask), lesion_mask=None, global_mask=True)
return args | [
"def",
"_get_ants_args",
"(",
"self",
")",
":",
"args",
"=",
"{",
"'moving_image'",
":",
"self",
".",
"inputs",
".",
"moving_image",
",",
"'num_threads'",
":",
"self",
".",
"inputs",
".",
"num_threads",
",",
"'float'",
":",
"self",
".",
"inputs",
".",
"f... | Moving image handling - The following truth table maps out the intended action
sequence. Future refactoring may more directly encode this.
moving_mask and lesion_mask are files
True = file
False = None
| moving_mask | explicit_masking | lesion_mask | action
|-------------|------------------|-------------|-------------------------------------------
| True | True | True | Update `moving_image` after applying
| | | | mask.
| | | | Set `moving_image_masks` applying
| | | | `create_cfm` with `global_mask=True`.
|-------------|------------------|-------------|-------------------------------------------
| True | True | False | Update `moving_image` after applying
| | | | mask.
|-------------|------------------|-------------|-------------------------------------------
| True | False | True | Set `moving_image_masks` applying
| | | | `create_cfm` with `global_mask=False`
|-------------|------------------|-------------|-------------------------------------------
| True | False | False | args['moving_image_masks'] = moving_mask
|-------------|------------------|-------------|-------------------------------------------
| False | * | True | Set `moving_image_masks` applying
| | | | `create_cfm` with `global_mask=True`
|-------------|------------------|-------------|-------------------------------------------
| False | * | False | No action | [
"Moving",
"image",
"handling",
"-",
"The",
"following",
"truth",
"table",
"maps",
"out",
"the",
"intended",
"action",
"sequence",
".",
"Future",
"refactoring",
"may",
"more",
"directly",
"encode",
"this",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/mni.py#L190-L368 | train | 211,765 |
poldracklab/niworkflows | docs/sphinxext/math_dollar.py | dollars_to_math | def dollars_to_math(source):
r"""
Replace dollar signs with backticks.
More precisely, do a regular expression search. Replace a plain
dollar sign ($) by a backtick (`). Replace an escaped dollar sign
(\$) by a dollar sign ($). Don't change a dollar sign preceded or
followed by a backtick (`$ or $`), because of strings like
"``$HOME``". Don't make any changes on lines starting with
spaces, because those are indented and hence part of a block of
code or examples.
This also doesn't replaces dollar signs enclosed in curly braces,
to avoid nested math environments, such as ::
$f(n) = 0 \text{ if $n$ is prime}$
Thus the above line would get changed to
`f(n) = 0 \text{ if $n$ is prime}`
"""
s = "\n".join(source)
if s.find("$") == -1:
return
# This searches for "$blah$" inside a pair of curly braces --
# don't change these, since they're probably coming from a nested
# math environment. So for each match, we replace it with a temporary
# string, and later on we substitute the original back.
global _data
_data = {}
def repl(matchobj):
global _data
s = matchobj.group(0)
t = "___XXX_REPL_%d___" % len(_data)
_data[t] = s
return t
s = re.sub(r"({[^{}$]*\$[^{}$]*\$[^{}]*})", repl, s)
# matches $...$
dollars = re.compile(r"(?<!\$)(?<!\\)\$([^\$]+?)\$")
# regular expression for \$
slashdollar = re.compile(r"\\\$")
s = dollars.sub(r":math:`\1`", s)
s = slashdollar.sub(r"$", s)
# change the original {...} things in:
for r in _data:
s = s.replace(r, _data[r])
# now save results in "source"
source[:] = [s] | python | def dollars_to_math(source):
r"""
Replace dollar signs with backticks.
More precisely, do a regular expression search. Replace a plain
dollar sign ($) by a backtick (`). Replace an escaped dollar sign
(\$) by a dollar sign ($). Don't change a dollar sign preceded or
followed by a backtick (`$ or $`), because of strings like
"``$HOME``". Don't make any changes on lines starting with
spaces, because those are indented and hence part of a block of
code or examples.
This also doesn't replaces dollar signs enclosed in curly braces,
to avoid nested math environments, such as ::
$f(n) = 0 \text{ if $n$ is prime}$
Thus the above line would get changed to
`f(n) = 0 \text{ if $n$ is prime}`
"""
s = "\n".join(source)
if s.find("$") == -1:
return
# This searches for "$blah$" inside a pair of curly braces --
# don't change these, since they're probably coming from a nested
# math environment. So for each match, we replace it with a temporary
# string, and later on we substitute the original back.
global _data
_data = {}
def repl(matchobj):
global _data
s = matchobj.group(0)
t = "___XXX_REPL_%d___" % len(_data)
_data[t] = s
return t
s = re.sub(r"({[^{}$]*\$[^{}$]*\$[^{}]*})", repl, s)
# matches $...$
dollars = re.compile(r"(?<!\$)(?<!\\)\$([^\$]+?)\$")
# regular expression for \$
slashdollar = re.compile(r"\\\$")
s = dollars.sub(r":math:`\1`", s)
s = slashdollar.sub(r"$", s)
# change the original {...} things in:
for r in _data:
s = s.replace(r, _data[r])
# now save results in "source"
source[:] = [s] | [
"def",
"dollars_to_math",
"(",
"source",
")",
":",
"s",
"=",
"\"\\n\"",
".",
"join",
"(",
"source",
")",
"if",
"s",
".",
"find",
"(",
"\"$\"",
")",
"==",
"-",
"1",
":",
"return",
"# This searches for \"$blah$\" inside a pair of curly braces --",
"# don't change ... | r"""
Replace dollar signs with backticks.
More precisely, do a regular expression search. Replace a plain
dollar sign ($) by a backtick (`). Replace an escaped dollar sign
(\$) by a dollar sign ($). Don't change a dollar sign preceded or
followed by a backtick (`$ or $`), because of strings like
"``$HOME``". Don't make any changes on lines starting with
spaces, because those are indented and hence part of a block of
code or examples.
This also doesn't replaces dollar signs enclosed in curly braces,
to avoid nested math environments, such as ::
$f(n) = 0 \text{ if $n$ is prime}$
Thus the above line would get changed to
`f(n) = 0 \text{ if $n$ is prime}` | [
"r",
"Replace",
"dollar",
"signs",
"with",
"backticks",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/docs/sphinxext/math_dollar.py#L3-L50 | train | 211,766 |
poldracklab/niworkflows | niworkflows/interfaces/registration.py | SimpleBeforeAfterRPT._post_run_hook | def _post_run_hook(self, runtime):
""" there is not inner interface to run """
self._fixed_image = self.inputs.after
self._moving_image = self.inputs.before
self._contour = self.inputs.wm_seg if isdefined(self.inputs.wm_seg) else None
NIWORKFLOWS_LOG.info(
'Report - setting before (%s) and after (%s) images',
self._fixed_image, self._moving_image)
return super(SimpleBeforeAfterRPT, self)._post_run_hook(runtime) | python | def _post_run_hook(self, runtime):
""" there is not inner interface to run """
self._fixed_image = self.inputs.after
self._moving_image = self.inputs.before
self._contour = self.inputs.wm_seg if isdefined(self.inputs.wm_seg) else None
NIWORKFLOWS_LOG.info(
'Report - setting before (%s) and after (%s) images',
self._fixed_image, self._moving_image)
return super(SimpleBeforeAfterRPT, self)._post_run_hook(runtime) | [
"def",
"_post_run_hook",
"(",
"self",
",",
"runtime",
")",
":",
"self",
".",
"_fixed_image",
"=",
"self",
".",
"inputs",
".",
"after",
"self",
".",
"_moving_image",
"=",
"self",
".",
"inputs",
".",
"before",
"self",
".",
"_contour",
"=",
"self",
".",
"... | there is not inner interface to run | [
"there",
"is",
"not",
"inner",
"interface",
"to",
"run"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/registration.py#L303-L312 | train | 211,767 |
poldracklab/niworkflows | niworkflows/data/utils.py | _get_data_path | def _get_data_path(data_dir=None):
""" Get data storage directory
data_dir: str
Path of the data directory. Used to force data storage in
a specified location.
:returns:
a list of paths where the dataset could be stored,
ordered by priority
"""
data_dir = data_dir or ''
default_dirs = [Path(d).expanduser().resolve()
for d in os.getenv('CRN_SHARED_DATA', '').split(os.pathsep)
if d.strip()]
default_dirs += [Path(d).expanduser().resolve()
for d in os.getenv('CRN_DATA', '').split(os.pathsep)
if d.strip()]
default_dirs += [NIWORKFLOWS_CACHE_DIR]
return [Path(d).expanduser()
for d in data_dir.split(os.pathsep) if d.strip()] or default_dirs | python | def _get_data_path(data_dir=None):
""" Get data storage directory
data_dir: str
Path of the data directory. Used to force data storage in
a specified location.
:returns:
a list of paths where the dataset could be stored,
ordered by priority
"""
data_dir = data_dir or ''
default_dirs = [Path(d).expanduser().resolve()
for d in os.getenv('CRN_SHARED_DATA', '').split(os.pathsep)
if d.strip()]
default_dirs += [Path(d).expanduser().resolve()
for d in os.getenv('CRN_DATA', '').split(os.pathsep)
if d.strip()]
default_dirs += [NIWORKFLOWS_CACHE_DIR]
return [Path(d).expanduser()
for d in data_dir.split(os.pathsep) if d.strip()] or default_dirs | [
"def",
"_get_data_path",
"(",
"data_dir",
"=",
"None",
")",
":",
"data_dir",
"=",
"data_dir",
"or",
"''",
"default_dirs",
"=",
"[",
"Path",
"(",
"d",
")",
".",
"expanduser",
"(",
")",
".",
"resolve",
"(",
")",
"for",
"d",
"in",
"os",
".",
"getenv",
... | Get data storage directory
data_dir: str
Path of the data directory. Used to force data storage in
a specified location.
:returns:
a list of paths where the dataset could be stored,
ordered by priority | [
"Get",
"data",
"storage",
"directory"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/data/utils.py#L200-L223 | train | 211,768 |
poldracklab/niworkflows | niworkflows/data/utils.py | _get_dataset | def _get_dataset(dataset_name, dataset_prefix=None,
data_dir=None, default_paths=None,
verbose=1):
""" Create if necessary and returns data directory of given dataset.
data_dir: str
Path of the data directory. Used to force data storage in
a specified location.
default_paths: list(str)
Default system paths in which the dataset may already have been installed
by a third party software. They will be checked first.
verbose: int
verbosity level (0 means no message).
:returns: the path of the given dataset directory.
:rtype: str
.. note::
This function retrieves the datasets directory (or data directory) using
the following priority :
1. defaults system paths
2. the keyword argument data_dir
3. the global environment variable CRN_SHARED_DATA
4. the user environment variable CRN_DATA
5. ~/.cache/stanford-crn in the user home folder
"""
dataset_folder = dataset_name if not dataset_prefix \
else '%s%s' % (dataset_prefix, dataset_name)
default_paths = default_paths or ''
paths = [p / dataset_folder for p in _get_data_path(data_dir)]
all_paths = [Path(p) / dataset_folder
for p in default_paths.split(os.pathsep)] + paths
# Check if the dataset folder exists somewhere and is not empty
for path in all_paths:
if path.is_dir() and list(path.iterdir()):
if verbose > 1:
NIWORKFLOWS_LOG.info(
'Dataset "%s" already cached in %s', dataset_name, path)
return path, True
for path in paths:
if verbose > 0:
NIWORKFLOWS_LOG.info(
'Dataset "%s" not cached, downloading to %s', dataset_name, path)
path.mkdir(parents=True, exist_ok=True)
return path, False | python | def _get_dataset(dataset_name, dataset_prefix=None,
data_dir=None, default_paths=None,
verbose=1):
""" Create if necessary and returns data directory of given dataset.
data_dir: str
Path of the data directory. Used to force data storage in
a specified location.
default_paths: list(str)
Default system paths in which the dataset may already have been installed
by a third party software. They will be checked first.
verbose: int
verbosity level (0 means no message).
:returns: the path of the given dataset directory.
:rtype: str
.. note::
This function retrieves the datasets directory (or data directory) using
the following priority :
1. defaults system paths
2. the keyword argument data_dir
3. the global environment variable CRN_SHARED_DATA
4. the user environment variable CRN_DATA
5. ~/.cache/stanford-crn in the user home folder
"""
dataset_folder = dataset_name if not dataset_prefix \
else '%s%s' % (dataset_prefix, dataset_name)
default_paths = default_paths or ''
paths = [p / dataset_folder for p in _get_data_path(data_dir)]
all_paths = [Path(p) / dataset_folder
for p in default_paths.split(os.pathsep)] + paths
# Check if the dataset folder exists somewhere and is not empty
for path in all_paths:
if path.is_dir() and list(path.iterdir()):
if verbose > 1:
NIWORKFLOWS_LOG.info(
'Dataset "%s" already cached in %s', dataset_name, path)
return path, True
for path in paths:
if verbose > 0:
NIWORKFLOWS_LOG.info(
'Dataset "%s" not cached, downloading to %s', dataset_name, path)
path.mkdir(parents=True, exist_ok=True)
return path, False | [
"def",
"_get_dataset",
"(",
"dataset_name",
",",
"dataset_prefix",
"=",
"None",
",",
"data_dir",
"=",
"None",
",",
"default_paths",
"=",
"None",
",",
"verbose",
"=",
"1",
")",
":",
"dataset_folder",
"=",
"dataset_name",
"if",
"not",
"dataset_prefix",
"else",
... | Create if necessary and returns data directory of given dataset.
data_dir: str
Path of the data directory. Used to force data storage in
a specified location.
default_paths: list(str)
Default system paths in which the dataset may already have been installed
by a third party software. They will be checked first.
verbose: int
verbosity level (0 means no message).
:returns: the path of the given dataset directory.
:rtype: str
.. note::
This function retrieves the datasets directory (or data directory) using
the following priority :
1. defaults system paths
2. the keyword argument data_dir
3. the global environment variable CRN_SHARED_DATA
4. the user environment variable CRN_DATA
5. ~/.cache/stanford-crn in the user home folder | [
"Create",
"if",
"necessary",
"and",
"returns",
"data",
"directory",
"of",
"given",
"dataset",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/data/utils.py#L226-L277 | train | 211,769 |
poldracklab/niworkflows | niworkflows/data/utils.py | _md5_sum_file | def _md5_sum_file(path):
""" Calculates the MD5 sum of a file.
"""
with Path(path).open('rb') as fhandle:
md5sum = hashlib.md5()
while True:
data = fhandle.read(8192)
if not data:
break
md5sum.update(data)
return md5sum.hexdigest() | python | def _md5_sum_file(path):
""" Calculates the MD5 sum of a file.
"""
with Path(path).open('rb') as fhandle:
md5sum = hashlib.md5()
while True:
data = fhandle.read(8192)
if not data:
break
md5sum.update(data)
return md5sum.hexdigest() | [
"def",
"_md5_sum_file",
"(",
"path",
")",
":",
"with",
"Path",
"(",
"path",
")",
".",
"open",
"(",
"'rb'",
")",
"as",
"fhandle",
":",
"md5sum",
"=",
"hashlib",
".",
"md5",
"(",
")",
"while",
"True",
":",
"data",
"=",
"fhandle",
".",
"read",
"(",
... | Calculates the MD5 sum of a file. | [
"Calculates",
"the",
"MD5",
"sum",
"of",
"a",
"file",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/data/utils.py#L291-L301 | train | 211,770 |
poldracklab/niworkflows | niworkflows/data/utils.py | _chunk_report_ | def _chunk_report_(bytes_so_far, total_size, initial_size, t_0):
"""Show downloading percentage.
:param int bytes_so_far: number of downloaded bytes
:param int total_size: total size of the file (may be 0/None, depending
on download method).
:param int t_0: the time in seconds (as returned by time.time()) at which
the download was resumed / started.
:param int initial_size: if resuming, indicate the initial size of the
file. If not resuming, set to zero.
"""
if not total_size:
sys.stderr.write("\rDownloaded {0:d} of ? bytes.".format(bytes_so_far))
else:
# Estimate remaining download time
total_percent = float(bytes_so_far) / total_size
current_download_size = bytes_so_far - initial_size
bytes_remaining = total_size - bytes_so_far
delta_t = time.time() - t_0
download_rate = current_download_size / max(1e-8, float(delta_t))
# Minimum rate of 0.01 bytes/s, to avoid dividing by zero.
time_remaining = bytes_remaining / max(0.01, download_rate)
# Trailing whitespace is to erase extra char when message length
# varies
sys.stderr.write(
"\rDownloaded {0:d} of {1:d} bytes ({2:.1f}%, {3!s} remaining)".format(
bytes_so_far, total_size, total_percent * 100, _format_time(time_remaining))) | python | def _chunk_report_(bytes_so_far, total_size, initial_size, t_0):
"""Show downloading percentage.
:param int bytes_so_far: number of downloaded bytes
:param int total_size: total size of the file (may be 0/None, depending
on download method).
:param int t_0: the time in seconds (as returned by time.time()) at which
the download was resumed / started.
:param int initial_size: if resuming, indicate the initial size of the
file. If not resuming, set to zero.
"""
if not total_size:
sys.stderr.write("\rDownloaded {0:d} of ? bytes.".format(bytes_so_far))
else:
# Estimate remaining download time
total_percent = float(bytes_so_far) / total_size
current_download_size = bytes_so_far - initial_size
bytes_remaining = total_size - bytes_so_far
delta_t = time.time() - t_0
download_rate = current_download_size / max(1e-8, float(delta_t))
# Minimum rate of 0.01 bytes/s, to avoid dividing by zero.
time_remaining = bytes_remaining / max(0.01, download_rate)
# Trailing whitespace is to erase extra char when message length
# varies
sys.stderr.write(
"\rDownloaded {0:d} of {1:d} bytes ({2:.1f}%, {3!s} remaining)".format(
bytes_so_far, total_size, total_percent * 100, _format_time(time_remaining))) | [
"def",
"_chunk_report_",
"(",
"bytes_so_far",
",",
"total_size",
",",
"initial_size",
",",
"t_0",
")",
":",
"if",
"not",
"total_size",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\rDownloaded {0:d} of ? bytes.\"",
".",
"format",
"(",
"bytes_so_far",
")",
... | Show downloading percentage.
:param int bytes_so_far: number of downloaded bytes
:param int total_size: total size of the file (may be 0/None, depending
on download method).
:param int t_0: the time in seconds (as returned by time.time()) at which
the download was resumed / started.
:param int initial_size: if resuming, indicate the initial size of the
file. If not resuming, set to zero. | [
"Show",
"downloading",
"percentage",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/data/utils.py#L353-L383 | train | 211,771 |
poldracklab/niworkflows | niworkflows/interfaces/freesurfer.py | refine_aseg | def refine_aseg(aseg, ball_size=4):
"""
First step to reconcile ANTs' and FreeSurfer's brain masks.
Here, the ``aseg.mgz`` mask from FreeSurfer is refined in two
steps, using binary morphological operations:
1. With a binary closing operation the sulci are included
into the mask. This results in a smoother brain mask
that does not exclude deep, wide sulci.
2. Fill any holes (typically, there could be a hole next to
the pineal gland and the corpora quadrigemina if the great
cerebral brain is segmented out).
"""
# Read aseg data
bmask = aseg.copy()
bmask[bmask > 0] = 1
bmask = bmask.astype(np.uint8)
# Morphological operations
selem = sim.ball(ball_size)
newmask = sim.binary_closing(bmask, selem)
newmask = binary_fill_holes(newmask.astype(np.uint8), selem).astype(np.uint8)
return newmask.astype(np.uint8) | python | def refine_aseg(aseg, ball_size=4):
"""
First step to reconcile ANTs' and FreeSurfer's brain masks.
Here, the ``aseg.mgz`` mask from FreeSurfer is refined in two
steps, using binary morphological operations:
1. With a binary closing operation the sulci are included
into the mask. This results in a smoother brain mask
that does not exclude deep, wide sulci.
2. Fill any holes (typically, there could be a hole next to
the pineal gland and the corpora quadrigemina if the great
cerebral brain is segmented out).
"""
# Read aseg data
bmask = aseg.copy()
bmask[bmask > 0] = 1
bmask = bmask.astype(np.uint8)
# Morphological operations
selem = sim.ball(ball_size)
newmask = sim.binary_closing(bmask, selem)
newmask = binary_fill_holes(newmask.astype(np.uint8), selem).astype(np.uint8)
return newmask.astype(np.uint8) | [
"def",
"refine_aseg",
"(",
"aseg",
",",
"ball_size",
"=",
"4",
")",
":",
"# Read aseg data",
"bmask",
"=",
"aseg",
".",
"copy",
"(",
")",
"bmask",
"[",
"bmask",
">",
"0",
"]",
"=",
"1",
"bmask",
"=",
"bmask",
".",
"astype",
"(",
"np",
".",
"uint8",... | First step to reconcile ANTs' and FreeSurfer's brain masks.
Here, the ``aseg.mgz`` mask from FreeSurfer is refined in two
steps, using binary morphological operations:
1. With a binary closing operation the sulci are included
into the mask. This results in a smoother brain mask
that does not exclude deep, wide sulci.
2. Fill any holes (typically, there could be a hole next to
the pineal gland and the corpora quadrigemina if the great
cerebral brain is segmented out). | [
"First",
"step",
"to",
"reconcile",
"ANTs",
"and",
"FreeSurfer",
"s",
"brain",
"masks",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/freesurfer.py#L372-L399 | train | 211,772 |
poldracklab/niworkflows | niworkflows/interfaces/freesurfer.py | grow_mask | def grow_mask(anat, aseg, ants_segs=None, ww=7, zval=2.0, bw=4):
"""
Grow mask including pixels that have a high likelihood.
GM tissue parameters are sampled in image patches of ``ww`` size.
This is inspired on mindboggle's solution to the problem:
https://github.com/nipy/mindboggle/blob/master/mindboggle/guts/segment.py#L1660
"""
selem = sim.ball(bw)
if ants_segs is None:
ants_segs = np.zeros_like(aseg, dtype=np.uint8)
aseg[aseg == 42] = 3 # Collapse both hemispheres
gm = anat.copy()
gm[aseg != 3] = 0
refined = refine_aseg(aseg)
newrefmask = sim.binary_dilation(refined, selem) - refined
indices = np.argwhere(newrefmask > 0)
for pixel in indices:
# When ATROPOS identified the pixel as GM, set and carry on
if ants_segs[tuple(pixel)] == 2:
refined[tuple(pixel)] = 1
continue
window = gm[
pixel[0] - ww:pixel[0] + ww,
pixel[1] - ww:pixel[1] + ww,
pixel[2] - ww:pixel[2] + ww
]
if np.any(window > 0):
mu = window[window > 0].mean()
sigma = max(window[window > 0].std(), 1.e-5)
zstat = abs(anat[tuple(pixel)] - mu) / sigma
refined[tuple(pixel)] = int(zstat < zval)
refined = sim.binary_opening(refined, selem)
return refined | python | def grow_mask(anat, aseg, ants_segs=None, ww=7, zval=2.0, bw=4):
"""
Grow mask including pixels that have a high likelihood.
GM tissue parameters are sampled in image patches of ``ww`` size.
This is inspired on mindboggle's solution to the problem:
https://github.com/nipy/mindboggle/blob/master/mindboggle/guts/segment.py#L1660
"""
selem = sim.ball(bw)
if ants_segs is None:
ants_segs = np.zeros_like(aseg, dtype=np.uint8)
aseg[aseg == 42] = 3 # Collapse both hemispheres
gm = anat.copy()
gm[aseg != 3] = 0
refined = refine_aseg(aseg)
newrefmask = sim.binary_dilation(refined, selem) - refined
indices = np.argwhere(newrefmask > 0)
for pixel in indices:
# When ATROPOS identified the pixel as GM, set and carry on
if ants_segs[tuple(pixel)] == 2:
refined[tuple(pixel)] = 1
continue
window = gm[
pixel[0] - ww:pixel[0] + ww,
pixel[1] - ww:pixel[1] + ww,
pixel[2] - ww:pixel[2] + ww
]
if np.any(window > 0):
mu = window[window > 0].mean()
sigma = max(window[window > 0].std(), 1.e-5)
zstat = abs(anat[tuple(pixel)] - mu) / sigma
refined[tuple(pixel)] = int(zstat < zval)
refined = sim.binary_opening(refined, selem)
return refined | [
"def",
"grow_mask",
"(",
"anat",
",",
"aseg",
",",
"ants_segs",
"=",
"None",
",",
"ww",
"=",
"7",
",",
"zval",
"=",
"2.0",
",",
"bw",
"=",
"4",
")",
":",
"selem",
"=",
"sim",
".",
"ball",
"(",
"bw",
")",
"if",
"ants_segs",
"is",
"None",
":",
... | Grow mask including pixels that have a high likelihood.
GM tissue parameters are sampled in image patches of ``ww`` size.
This is inspired on mindboggle's solution to the problem:
https://github.com/nipy/mindboggle/blob/master/mindboggle/guts/segment.py#L1660 | [
"Grow",
"mask",
"including",
"pixels",
"that",
"have",
"a",
"high",
"likelihood",
".",
"GM",
"tissue",
"parameters",
"are",
"sampled",
"in",
"image",
"patches",
"of",
"ww",
"size",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/freesurfer.py#L402-L441 | train | 211,773 |
poldracklab/niworkflows | niworkflows/interfaces/freesurfer.py | medial_wall_to_nan | def medial_wall_to_nan(in_file, subjects_dir, target_subject, newpath=None):
""" Convert values on medial wall to NaNs
"""
import nibabel as nb
import numpy as np
import os
fn = os.path.basename(in_file)
if not target_subject.startswith('fs'):
return in_file
cortex = nb.freesurfer.read_label(os.path.join(
subjects_dir, target_subject, 'label', '{}.cortex.label'.format(fn[:2])))
func = nb.load(in_file)
medial = np.delete(np.arange(len(func.darrays[0].data)), cortex)
for darray in func.darrays:
darray.data[medial] = np.nan
out_file = os.path.join(newpath or os.getcwd(), fn)
func.to_filename(out_file)
return out_file | python | def medial_wall_to_nan(in_file, subjects_dir, target_subject, newpath=None):
""" Convert values on medial wall to NaNs
"""
import nibabel as nb
import numpy as np
import os
fn = os.path.basename(in_file)
if not target_subject.startswith('fs'):
return in_file
cortex = nb.freesurfer.read_label(os.path.join(
subjects_dir, target_subject, 'label', '{}.cortex.label'.format(fn[:2])))
func = nb.load(in_file)
medial = np.delete(np.arange(len(func.darrays[0].data)), cortex)
for darray in func.darrays:
darray.data[medial] = np.nan
out_file = os.path.join(newpath or os.getcwd(), fn)
func.to_filename(out_file)
return out_file | [
"def",
"medial_wall_to_nan",
"(",
"in_file",
",",
"subjects_dir",
",",
"target_subject",
",",
"newpath",
"=",
"None",
")",
":",
"import",
"nibabel",
"as",
"nb",
"import",
"numpy",
"as",
"np",
"import",
"os",
"fn",
"=",
"os",
".",
"path",
".",
"basename",
... | Convert values on medial wall to NaNs | [
"Convert",
"values",
"on",
"medial",
"wall",
"to",
"NaNs"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/freesurfer.py#L444-L464 | train | 211,774 |
poldracklab/niworkflows | docs/sphinxext/github.py | make_link_node | def make_link_node(rawtext, app, type, slug, options):
"""Create a link to a github resource.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param type: Link type (issues, changeset, etc.)
:param slug: ID of the thing to link to
:param options: Options dictionary passed to role func.
"""
try:
base = app.config.github_project_url
if not base:
raise AttributeError
if not base.endswith('/'):
base += '/'
except AttributeError as err:
raise ValueError('github_project_url configuration value is not set (%s)' % str(err))
ref = base + type + '/' + slug + '/'
set_classes(options)
prefix = "#"
if type == 'pull':
prefix = "PR " + prefix
node = nodes.reference(rawtext, prefix + utils.unescape(slug), refuri=ref,
**options)
return node | python | def make_link_node(rawtext, app, type, slug, options):
"""Create a link to a github resource.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param type: Link type (issues, changeset, etc.)
:param slug: ID of the thing to link to
:param options: Options dictionary passed to role func.
"""
try:
base = app.config.github_project_url
if not base:
raise AttributeError
if not base.endswith('/'):
base += '/'
except AttributeError as err:
raise ValueError('github_project_url configuration value is not set (%s)' % str(err))
ref = base + type + '/' + slug + '/'
set_classes(options)
prefix = "#"
if type == 'pull':
prefix = "PR " + prefix
node = nodes.reference(rawtext, prefix + utils.unescape(slug), refuri=ref,
**options)
return node | [
"def",
"make_link_node",
"(",
"rawtext",
",",
"app",
",",
"type",
",",
"slug",
",",
"options",
")",
":",
"try",
":",
"base",
"=",
"app",
".",
"config",
".",
"github_project_url",
"if",
"not",
"base",
":",
"raise",
"AttributeError",
"if",
"not",
"base",
... | Create a link to a github resource.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param type: Link type (issues, changeset, etc.)
:param slug: ID of the thing to link to
:param options: Options dictionary passed to role func. | [
"Create",
"a",
"link",
"to",
"a",
"github",
"resource",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/docs/sphinxext/github.py#L23-L49 | train | 211,775 |
poldracklab/niworkflows | docs/sphinxext/github.py | ghissue_role | def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub issue.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
try:
issue_num = int(text)
if issue_num <= 0:
raise ValueError
except ValueError:
msg = inliner.reporter.error(
'GitHub issue number must be a number greater than or equal to 1; '
'"%s" is invalid.' % text, line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
app = inliner.document.settings.env.app
#app.info('issue %r' % text)
if 'pull' in name.lower():
category = 'pull'
elif 'issue' in name.lower():
category = 'issues'
else:
msg = inliner.reporter.error(
'GitHub roles include "ghpull" and "ghissue", '
'"%s" is invalid.' % name, line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
node = make_link_node(rawtext, app, category, str(issue_num), options)
return [node], [] | python | def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub issue.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
try:
issue_num = int(text)
if issue_num <= 0:
raise ValueError
except ValueError:
msg = inliner.reporter.error(
'GitHub issue number must be a number greater than or equal to 1; '
'"%s" is invalid.' % text, line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
app = inliner.document.settings.env.app
#app.info('issue %r' % text)
if 'pull' in name.lower():
category = 'pull'
elif 'issue' in name.lower():
category = 'issues'
else:
msg = inliner.reporter.error(
'GitHub roles include "ghpull" and "ghissue", '
'"%s" is invalid.' % name, line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
node = make_link_node(rawtext, app, category, str(issue_num), options)
return [node], [] | [
"def",
"ghissue_role",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"{",
"}",
",",
"content",
"=",
"[",
"]",
")",
":",
"try",
":",
"issue_num",
"=",
"int",
"(",
"text",
")",
"if",
"issue_num",
"<=",
... | Link to a GitHub issue.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization. | [
"Link",
"to",
"a",
"GitHub",
"issue",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/docs/sphinxext/github.py#L51-L90 | train | 211,776 |
poldracklab/niworkflows | docs/sphinxext/github.py | ghuser_role | def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub user.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
app = inliner.document.settings.env.app
#app.info('user link %r' % text)
ref = 'https://www.github.com/' + text
node = nodes.reference(rawtext, text, refuri=ref, **options)
return [node], [] | python | def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub user.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
app = inliner.document.settings.env.app
#app.info('user link %r' % text)
ref = 'https://www.github.com/' + text
node = nodes.reference(rawtext, text, refuri=ref, **options)
return [node], [] | [
"def",
"ghuser_role",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"{",
"}",
",",
"content",
"=",
"[",
"]",
")",
":",
"app",
"=",
"inliner",
".",
"document",
".",
"settings",
".",
"env",
".",
"app",
... | Link to a GitHub user.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization. | [
"Link",
"to",
"a",
"GitHub",
"user",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/docs/sphinxext/github.py#L92-L111 | train | 211,777 |
poldracklab/niworkflows | docs/sphinxext/github.py | ghcommit_role | def ghcommit_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub commit.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
app = inliner.document.settings.env.app
#app.info('user link %r' % text)
try:
base = app.config.github_project_url
if not base:
raise AttributeError
if not base.endswith('/'):
base += '/'
except AttributeError as err:
raise ValueError('github_project_url configuration value is not set (%s)' % str(err))
ref = base + text
node = nodes.reference(rawtext, text[:6], refuri=ref, **options)
return [node], [] | python | def ghcommit_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub commit.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
app = inliner.document.settings.env.app
#app.info('user link %r' % text)
try:
base = app.config.github_project_url
if not base:
raise AttributeError
if not base.endswith('/'):
base += '/'
except AttributeError as err:
raise ValueError('github_project_url configuration value is not set (%s)' % str(err))
ref = base + text
node = nodes.reference(rawtext, text[:6], refuri=ref, **options)
return [node], [] | [
"def",
"ghcommit_role",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"{",
"}",
",",
"content",
"=",
"[",
"]",
")",
":",
"app",
"=",
"inliner",
".",
"document",
".",
"settings",
".",
"env",
".",
"app"... | Link to a GitHub commit.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization. | [
"Link",
"to",
"a",
"GitHub",
"commit",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/docs/sphinxext/github.py#L113-L141 | train | 211,778 |
poldracklab/niworkflows | docs/tools/apigen.py | ApiDocWriter._import | def _import(self, name):
''' Import namespace package '''
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod | python | def _import(self, name):
''' Import namespace package '''
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod | [
"def",
"_import",
"(",
"self",
",",
"name",
")",
":",
"mod",
"=",
"__import__",
"(",
"name",
")",
"components",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"for",
"comp",
"in",
"components",
"[",
"1",
":",
"]",
":",
"mod",
"=",
"getattr",
"(",
"m... | Import namespace package | [
"Import",
"namespace",
"package"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/docs/tools/apigen.py#L107-L113 | train | 211,779 |
poldracklab/niworkflows | docs/tools/apigen.py | ApiDocWriter.discover_modules | def discover_modules(self):
''' Return module sequence discovered from ``self.package_name``
Parameters
----------
None
Returns
-------
mods : sequence
Sequence of module names within ``self.package_name``
Examples
--------
>>> dw = ApiDocWriter('sphinx')
>>> mods = dw.discover_modules()
>>> 'sphinx.util' in mods
True
>>> dw.package_skip_patterns.append('\.util$')
>>> 'sphinx.util' in dw.discover_modules()
False
>>>
'''
modules = [self.package_name]
# raw directory parsing
for dirpath, dirnames, filenames in os.walk(self.root_path):
# Check directory names for packages
root_uri = self._path2uri(os.path.join(self.root_path,
dirpath))
# Normally, we'd only iterate over dirnames, but since
# dipy does not import a whole bunch of modules we'll
# include those here as well (the *.py filenames).
filenames = [f[:-3] for f in filenames if
f.endswith('.py') and not f.startswith('__init__')]
for filename in filenames:
package_uri = '/'.join((dirpath, filename))
for subpkg_name in dirnames + filenames:
package_uri = '.'.join((root_uri, subpkg_name))
package_path = self._uri2path(package_uri)
if (package_path and
self._survives_exclude(package_uri, 'package')):
modules.append(package_uri)
return sorted(modules) | python | def discover_modules(self):
''' Return module sequence discovered from ``self.package_name``
Parameters
----------
None
Returns
-------
mods : sequence
Sequence of module names within ``self.package_name``
Examples
--------
>>> dw = ApiDocWriter('sphinx')
>>> mods = dw.discover_modules()
>>> 'sphinx.util' in mods
True
>>> dw.package_skip_patterns.append('\.util$')
>>> 'sphinx.util' in dw.discover_modules()
False
>>>
'''
modules = [self.package_name]
# raw directory parsing
for dirpath, dirnames, filenames in os.walk(self.root_path):
# Check directory names for packages
root_uri = self._path2uri(os.path.join(self.root_path,
dirpath))
# Normally, we'd only iterate over dirnames, but since
# dipy does not import a whole bunch of modules we'll
# include those here as well (the *.py filenames).
filenames = [f[:-3] for f in filenames if
f.endswith('.py') and not f.startswith('__init__')]
for filename in filenames:
package_uri = '/'.join((dirpath, filename))
for subpkg_name in dirnames + filenames:
package_uri = '.'.join((root_uri, subpkg_name))
package_path = self._uri2path(package_uri)
if (package_path and
self._survives_exclude(package_uri, 'package')):
modules.append(package_uri)
return sorted(modules) | [
"def",
"discover_modules",
"(",
"self",
")",
":",
"modules",
"=",
"[",
"self",
".",
"package_name",
"]",
"# raw directory parsing",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"self",
".",
"root_path",
")",
":",
"# Ch... | Return module sequence discovered from ``self.package_name``
Parameters
----------
None
Returns
-------
mods : sequence
Sequence of module names within ``self.package_name``
Examples
--------
>>> dw = ApiDocWriter('sphinx')
>>> mods = dw.discover_modules()
>>> 'sphinx.util' in mods
True
>>> dw.package_skip_patterns.append('\.util$')
>>> 'sphinx.util' in dw.discover_modules()
False
>>> | [
"Return",
"module",
"sequence",
"discovered",
"from",
"self",
".",
"package_name"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/docs/tools/apigen.py#L362-L408 | train | 211,780 |
poldracklab/niworkflows | niworkflows/utils/bids.py | get_metadata_for_nifti | def get_metadata_for_nifti(in_file, bids_dir=None, validate=True):
"""Fetch metadata for a given nifti file
>>> metadata = get_metadata_for_nifti(
... datadir / 'ds054' / 'sub-100185' / 'fmap' / 'sub-100185_phasediff.nii.gz',
... validate=False)
>>> metadata['Manufacturer']
'SIEMENS'
>>>
"""
return _init_layout(in_file, bids_dir, validate).get_metadata(
str(in_file)) | python | def get_metadata_for_nifti(in_file, bids_dir=None, validate=True):
"""Fetch metadata for a given nifti file
>>> metadata = get_metadata_for_nifti(
... datadir / 'ds054' / 'sub-100185' / 'fmap' / 'sub-100185_phasediff.nii.gz',
... validate=False)
>>> metadata['Manufacturer']
'SIEMENS'
>>>
"""
return _init_layout(in_file, bids_dir, validate).get_metadata(
str(in_file)) | [
"def",
"get_metadata_for_nifti",
"(",
"in_file",
",",
"bids_dir",
"=",
"None",
",",
"validate",
"=",
"True",
")",
":",
"return",
"_init_layout",
"(",
"in_file",
",",
"bids_dir",
",",
"validate",
")",
".",
"get_metadata",
"(",
"str",
"(",
"in_file",
")",
")... | Fetch metadata for a given nifti file
>>> metadata = get_metadata_for_nifti(
... datadir / 'ds054' / 'sub-100185' / 'fmap' / 'sub-100185_phasediff.nii.gz',
... validate=False)
>>> metadata['Manufacturer']
'SIEMENS'
>>> | [
"Fetch",
"metadata",
"for",
"a",
"given",
"nifti",
"file"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/utils/bids.py#L183-L196 | train | 211,781 |
poldracklab/niworkflows | niworkflows/utils/bids.py | group_multiecho | def group_multiecho(bold_sess):
"""
Multiplexes multi-echo EPIs into arrays. Dual-echo is a special
case of multi-echo, which is treated as single-echo data.
>>> bold_sess = ["sub-01_task-rest_echo-1_run-01_bold.nii.gz",
... "sub-01_task-rest_echo-2_run-01_bold.nii.gz",
... "sub-01_task-rest_echo-1_run-02_bold.nii.gz",
... "sub-01_task-rest_echo-2_run-02_bold.nii.gz",
... "sub-01_task-rest_echo-3_run-02_bold.nii.gz",
... "sub-01_task-rest_run-03_bold.nii.gz"]
>>> group_multiecho(bold_sess)
['sub-01_task-rest_echo-1_run-01_bold.nii.gz',
'sub-01_task-rest_echo-2_run-01_bold.nii.gz',
['sub-01_task-rest_echo-1_run-02_bold.nii.gz',
'sub-01_task-rest_echo-2_run-02_bold.nii.gz',
'sub-01_task-rest_echo-3_run-02_bold.nii.gz'],
'sub-01_task-rest_run-03_bold.nii.gz']
>>> bold_sess.insert(2, "sub-01_task-rest_echo-3_run-01_bold.nii.gz")
>>> group_multiecho(bold_sess)
[['sub-01_task-rest_echo-1_run-01_bold.nii.gz',
'sub-01_task-rest_echo-2_run-01_bold.nii.gz',
'sub-01_task-rest_echo-3_run-01_bold.nii.gz'],
['sub-01_task-rest_echo-1_run-02_bold.nii.gz',
'sub-01_task-rest_echo-2_run-02_bold.nii.gz',
'sub-01_task-rest_echo-3_run-02_bold.nii.gz'],
'sub-01_task-rest_run-03_bold.nii.gz']
>>> bold_sess += ["sub-01_task-beh_echo-1_run-01_bold.nii.gz",
... "sub-01_task-beh_echo-2_run-01_bold.nii.gz",
... "sub-01_task-beh_echo-1_run-02_bold.nii.gz",
... "sub-01_task-beh_echo-2_run-02_bold.nii.gz",
... "sub-01_task-beh_echo-3_run-02_bold.nii.gz",
... "sub-01_task-beh_run-03_bold.nii.gz"]
>>> group_multiecho(bold_sess)
[['sub-01_task-rest_echo-1_run-01_bold.nii.gz',
'sub-01_task-rest_echo-2_run-01_bold.nii.gz',
'sub-01_task-rest_echo-3_run-01_bold.nii.gz'],
['sub-01_task-rest_echo-1_run-02_bold.nii.gz',
'sub-01_task-rest_echo-2_run-02_bold.nii.gz',
'sub-01_task-rest_echo-3_run-02_bold.nii.gz'],
'sub-01_task-rest_run-03_bold.nii.gz',
'sub-01_task-beh_echo-1_run-01_bold.nii.gz',
'sub-01_task-beh_echo-2_run-01_bold.nii.gz',
['sub-01_task-beh_echo-1_run-02_bold.nii.gz',
'sub-01_task-beh_echo-2_run-02_bold.nii.gz',
'sub-01_task-beh_echo-3_run-02_bold.nii.gz'],
'sub-01_task-beh_run-03_bold.nii.gz']
Some tests from https://neurostars.org/t/fmriprep-from\
-singularity-unboundlocalerror/3299/7
>>> bold_sess = ['sub-01_task-AudLoc_echo-1_bold.nii',
... 'sub-01_task-AudLoc_echo-2_bold.nii',
... 'sub-01_task-FJT_echo-1_bold.nii',
... 'sub-01_task-FJT_echo-2_bold.nii',
... 'sub-01_task-LDT_echo-1_bold.nii',
... 'sub-01_task-LDT_echo-2_bold.nii',
... 'sub-01_task-MotLoc_echo-1_bold.nii',
... 'sub-01_task-MotLoc_echo-2_bold.nii']
>>> group_multiecho(bold_sess) == bold_sess
True
>>> bold_sess += ['sub-01_task-MotLoc_echo-3_bold.nii']
>>> groups = group_multiecho(bold_sess)
>>> len(groups[:-1])
6
>>> [isinstance(g, list) for g in groups]
[False, False, False, False, False, False, True]
>>> len(groups[-1])
3
"""
from itertools import groupby
def _grp_echos(x):
if '_echo-' not in x:
return x
echo = re.search("_echo-\\d*", x).group(0)
return x.replace(echo, "_echo-?")
ses_uids = []
for _, bold in groupby(bold_sess, key=_grp_echos):
bold = list(bold)
# If single- or dual-echo, flatten list; keep list otherwise.
action = getattr(ses_uids, 'append' if len(bold) > 2 else 'extend')
action(bold)
return ses_uids | python | def group_multiecho(bold_sess):
"""
Multiplexes multi-echo EPIs into arrays. Dual-echo is a special
case of multi-echo, which is treated as single-echo data.
>>> bold_sess = ["sub-01_task-rest_echo-1_run-01_bold.nii.gz",
... "sub-01_task-rest_echo-2_run-01_bold.nii.gz",
... "sub-01_task-rest_echo-1_run-02_bold.nii.gz",
... "sub-01_task-rest_echo-2_run-02_bold.nii.gz",
... "sub-01_task-rest_echo-3_run-02_bold.nii.gz",
... "sub-01_task-rest_run-03_bold.nii.gz"]
>>> group_multiecho(bold_sess)
['sub-01_task-rest_echo-1_run-01_bold.nii.gz',
'sub-01_task-rest_echo-2_run-01_bold.nii.gz',
['sub-01_task-rest_echo-1_run-02_bold.nii.gz',
'sub-01_task-rest_echo-2_run-02_bold.nii.gz',
'sub-01_task-rest_echo-3_run-02_bold.nii.gz'],
'sub-01_task-rest_run-03_bold.nii.gz']
>>> bold_sess.insert(2, "sub-01_task-rest_echo-3_run-01_bold.nii.gz")
>>> group_multiecho(bold_sess)
[['sub-01_task-rest_echo-1_run-01_bold.nii.gz',
'sub-01_task-rest_echo-2_run-01_bold.nii.gz',
'sub-01_task-rest_echo-3_run-01_bold.nii.gz'],
['sub-01_task-rest_echo-1_run-02_bold.nii.gz',
'sub-01_task-rest_echo-2_run-02_bold.nii.gz',
'sub-01_task-rest_echo-3_run-02_bold.nii.gz'],
'sub-01_task-rest_run-03_bold.nii.gz']
>>> bold_sess += ["sub-01_task-beh_echo-1_run-01_bold.nii.gz",
... "sub-01_task-beh_echo-2_run-01_bold.nii.gz",
... "sub-01_task-beh_echo-1_run-02_bold.nii.gz",
... "sub-01_task-beh_echo-2_run-02_bold.nii.gz",
... "sub-01_task-beh_echo-3_run-02_bold.nii.gz",
... "sub-01_task-beh_run-03_bold.nii.gz"]
>>> group_multiecho(bold_sess)
[['sub-01_task-rest_echo-1_run-01_bold.nii.gz',
'sub-01_task-rest_echo-2_run-01_bold.nii.gz',
'sub-01_task-rest_echo-3_run-01_bold.nii.gz'],
['sub-01_task-rest_echo-1_run-02_bold.nii.gz',
'sub-01_task-rest_echo-2_run-02_bold.nii.gz',
'sub-01_task-rest_echo-3_run-02_bold.nii.gz'],
'sub-01_task-rest_run-03_bold.nii.gz',
'sub-01_task-beh_echo-1_run-01_bold.nii.gz',
'sub-01_task-beh_echo-2_run-01_bold.nii.gz',
['sub-01_task-beh_echo-1_run-02_bold.nii.gz',
'sub-01_task-beh_echo-2_run-02_bold.nii.gz',
'sub-01_task-beh_echo-3_run-02_bold.nii.gz'],
'sub-01_task-beh_run-03_bold.nii.gz']
Some tests from https://neurostars.org/t/fmriprep-from\
-singularity-unboundlocalerror/3299/7
>>> bold_sess = ['sub-01_task-AudLoc_echo-1_bold.nii',
... 'sub-01_task-AudLoc_echo-2_bold.nii',
... 'sub-01_task-FJT_echo-1_bold.nii',
... 'sub-01_task-FJT_echo-2_bold.nii',
... 'sub-01_task-LDT_echo-1_bold.nii',
... 'sub-01_task-LDT_echo-2_bold.nii',
... 'sub-01_task-MotLoc_echo-1_bold.nii',
... 'sub-01_task-MotLoc_echo-2_bold.nii']
>>> group_multiecho(bold_sess) == bold_sess
True
>>> bold_sess += ['sub-01_task-MotLoc_echo-3_bold.nii']
>>> groups = group_multiecho(bold_sess)
>>> len(groups[:-1])
6
>>> [isinstance(g, list) for g in groups]
[False, False, False, False, False, False, True]
>>> len(groups[-1])
3
"""
from itertools import groupby
def _grp_echos(x):
if '_echo-' not in x:
return x
echo = re.search("_echo-\\d*", x).group(0)
return x.replace(echo, "_echo-?")
ses_uids = []
for _, bold in groupby(bold_sess, key=_grp_echos):
bold = list(bold)
# If single- or dual-echo, flatten list; keep list otherwise.
action = getattr(ses_uids, 'append' if len(bold) > 2 else 'extend')
action(bold)
return ses_uids | [
"def",
"group_multiecho",
"(",
"bold_sess",
")",
":",
"from",
"itertools",
"import",
"groupby",
"def",
"_grp_echos",
"(",
"x",
")",
":",
"if",
"'_echo-'",
"not",
"in",
"x",
":",
"return",
"x",
"echo",
"=",
"re",
".",
"search",
"(",
"\"_echo-\\\\d*\"",
",... | Multiplexes multi-echo EPIs into arrays. Dual-echo is a special
case of multi-echo, which is treated as single-echo data.
>>> bold_sess = ["sub-01_task-rest_echo-1_run-01_bold.nii.gz",
... "sub-01_task-rest_echo-2_run-01_bold.nii.gz",
... "sub-01_task-rest_echo-1_run-02_bold.nii.gz",
... "sub-01_task-rest_echo-2_run-02_bold.nii.gz",
... "sub-01_task-rest_echo-3_run-02_bold.nii.gz",
... "sub-01_task-rest_run-03_bold.nii.gz"]
>>> group_multiecho(bold_sess)
['sub-01_task-rest_echo-1_run-01_bold.nii.gz',
'sub-01_task-rest_echo-2_run-01_bold.nii.gz',
['sub-01_task-rest_echo-1_run-02_bold.nii.gz',
'sub-01_task-rest_echo-2_run-02_bold.nii.gz',
'sub-01_task-rest_echo-3_run-02_bold.nii.gz'],
'sub-01_task-rest_run-03_bold.nii.gz']
>>> bold_sess.insert(2, "sub-01_task-rest_echo-3_run-01_bold.nii.gz")
>>> group_multiecho(bold_sess)
[['sub-01_task-rest_echo-1_run-01_bold.nii.gz',
'sub-01_task-rest_echo-2_run-01_bold.nii.gz',
'sub-01_task-rest_echo-3_run-01_bold.nii.gz'],
['sub-01_task-rest_echo-1_run-02_bold.nii.gz',
'sub-01_task-rest_echo-2_run-02_bold.nii.gz',
'sub-01_task-rest_echo-3_run-02_bold.nii.gz'],
'sub-01_task-rest_run-03_bold.nii.gz']
>>> bold_sess += ["sub-01_task-beh_echo-1_run-01_bold.nii.gz",
... "sub-01_task-beh_echo-2_run-01_bold.nii.gz",
... "sub-01_task-beh_echo-1_run-02_bold.nii.gz",
... "sub-01_task-beh_echo-2_run-02_bold.nii.gz",
... "sub-01_task-beh_echo-3_run-02_bold.nii.gz",
... "sub-01_task-beh_run-03_bold.nii.gz"]
>>> group_multiecho(bold_sess)
[['sub-01_task-rest_echo-1_run-01_bold.nii.gz',
'sub-01_task-rest_echo-2_run-01_bold.nii.gz',
'sub-01_task-rest_echo-3_run-01_bold.nii.gz'],
['sub-01_task-rest_echo-1_run-02_bold.nii.gz',
'sub-01_task-rest_echo-2_run-02_bold.nii.gz',
'sub-01_task-rest_echo-3_run-02_bold.nii.gz'],
'sub-01_task-rest_run-03_bold.nii.gz',
'sub-01_task-beh_echo-1_run-01_bold.nii.gz',
'sub-01_task-beh_echo-2_run-01_bold.nii.gz',
['sub-01_task-beh_echo-1_run-02_bold.nii.gz',
'sub-01_task-beh_echo-2_run-02_bold.nii.gz',
'sub-01_task-beh_echo-3_run-02_bold.nii.gz'],
'sub-01_task-beh_run-03_bold.nii.gz']
Some tests from https://neurostars.org/t/fmriprep-from\
-singularity-unboundlocalerror/3299/7
>>> bold_sess = ['sub-01_task-AudLoc_echo-1_bold.nii',
... 'sub-01_task-AudLoc_echo-2_bold.nii',
... 'sub-01_task-FJT_echo-1_bold.nii',
... 'sub-01_task-FJT_echo-2_bold.nii',
... 'sub-01_task-LDT_echo-1_bold.nii',
... 'sub-01_task-LDT_echo-2_bold.nii',
... 'sub-01_task-MotLoc_echo-1_bold.nii',
... 'sub-01_task-MotLoc_echo-2_bold.nii']
>>> group_multiecho(bold_sess) == bold_sess
True
>>> bold_sess += ['sub-01_task-MotLoc_echo-3_bold.nii']
>>> groups = group_multiecho(bold_sess)
>>> len(groups[:-1])
6
>>> [isinstance(g, list) for g in groups]
[False, False, False, False, False, False, True]
>>> len(groups[-1])
3 | [
"Multiplexes",
"multi",
"-",
"echo",
"EPIs",
"into",
"arrays",
".",
"Dual",
"-",
"echo",
"is",
"a",
"special",
"case",
"of",
"multi",
"-",
"echo",
"which",
"is",
"treated",
"as",
"single",
"-",
"echo",
"data",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/utils/bids.py#L217-L306 | train | 211,782 |
poldracklab/niworkflows | niworkflows/interfaces/cifti.py | GenerateCifti._define_variant | def _define_variant(self):
"""Assign arbitrary label to combination of CIFTI spaces"""
space = None
variants = {
# to be expanded once addtional spaces are supported
'space1': ['fsaverage5', 'MNI152NLin2009cAsym'],
'space2': ['fsaverage6', 'MNI152NLin2009cAsym'],
}
for sp, targets in variants.items():
if all(target in targets for target in
[self.inputs.surface_target, self.inputs.volume_target]):
space = sp
if space is None:
raise NotImplementedError
variant_key = os.path.abspath('dtseries_variant.json')
with open(variant_key, 'w') as fp:
json.dump({space: variants[space]}, fp)
return variant_key, space | python | def _define_variant(self):
"""Assign arbitrary label to combination of CIFTI spaces"""
space = None
variants = {
# to be expanded once addtional spaces are supported
'space1': ['fsaverage5', 'MNI152NLin2009cAsym'],
'space2': ['fsaverage6', 'MNI152NLin2009cAsym'],
}
for sp, targets in variants.items():
if all(target in targets for target in
[self.inputs.surface_target, self.inputs.volume_target]):
space = sp
if space is None:
raise NotImplementedError
variant_key = os.path.abspath('dtseries_variant.json')
with open(variant_key, 'w') as fp:
json.dump({space: variants[space]}, fp)
return variant_key, space | [
"def",
"_define_variant",
"(",
"self",
")",
":",
"space",
"=",
"None",
"variants",
"=",
"{",
"# to be expanded once addtional spaces are supported",
"'space1'",
":",
"[",
"'fsaverage5'",
",",
"'MNI152NLin2009cAsym'",
"]",
",",
"'space2'",
":",
"[",
"'fsaverage6'",
"... | Assign arbitrary label to combination of CIFTI spaces | [
"Assign",
"arbitrary",
"label",
"to",
"combination",
"of",
"CIFTI",
"spaces"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/cifti.py#L97-L115 | train | 211,783 |
poldracklab/niworkflows | niworkflows/interfaces/cifti.py | GenerateCifti._fetch_data | def _fetch_data(self):
"""Converts inputspec to files"""
if (self.inputs.surface_target == "fsnative" or
self.inputs.volume_target != "MNI152NLin2009cAsym"):
# subject space is not support yet
raise NotImplementedError
annotation_files = sorted(glob(os.path.join(self.inputs.subjects_dir,
self.inputs.surface_target,
'label',
'*h.aparc.annot')))
if not annotation_files:
raise IOError("Freesurfer annotations for %s not found in %s" % (
self.inputs.surface_target, self.inputs.subjects_dir))
label_file = str(get_template(
'MNI152NLin2009cAsym', resolution=2, desc='DKT31', suffix='dseg'))
return annotation_files, label_file | python | def _fetch_data(self):
"""Converts inputspec to files"""
if (self.inputs.surface_target == "fsnative" or
self.inputs.volume_target != "MNI152NLin2009cAsym"):
# subject space is not support yet
raise NotImplementedError
annotation_files = sorted(glob(os.path.join(self.inputs.subjects_dir,
self.inputs.surface_target,
'label',
'*h.aparc.annot')))
if not annotation_files:
raise IOError("Freesurfer annotations for %s not found in %s" % (
self.inputs.surface_target, self.inputs.subjects_dir))
label_file = str(get_template(
'MNI152NLin2009cAsym', resolution=2, desc='DKT31', suffix='dseg'))
return annotation_files, label_file | [
"def",
"_fetch_data",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"inputs",
".",
"surface_target",
"==",
"\"fsnative\"",
"or",
"self",
".",
"inputs",
".",
"volume_target",
"!=",
"\"MNI152NLin2009cAsym\"",
")",
":",
"# subject space is not support yet",
"raise",... | Converts inputspec to files | [
"Converts",
"inputspec",
"to",
"files"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/cifti.py#L117-L134 | train | 211,784 |
poldracklab/niworkflows | niworkflows/interfaces/images.py | reorient | def reorient(in_file, newpath=None):
"""Reorient Nifti files to RAS"""
out_file = fname_presuffix(in_file, suffix='_ras', newpath=newpath)
nb.as_closest_canonical(nb.load(in_file)).to_filename(out_file)
return out_file | python | def reorient(in_file, newpath=None):
"""Reorient Nifti files to RAS"""
out_file = fname_presuffix(in_file, suffix='_ras', newpath=newpath)
nb.as_closest_canonical(nb.load(in_file)).to_filename(out_file)
return out_file | [
"def",
"reorient",
"(",
"in_file",
",",
"newpath",
"=",
"None",
")",
":",
"out_file",
"=",
"fname_presuffix",
"(",
"in_file",
",",
"suffix",
"=",
"'_ras'",
",",
"newpath",
"=",
"newpath",
")",
"nb",
".",
"as_closest_canonical",
"(",
"nb",
".",
"load",
"(... | Reorient Nifti files to RAS | [
"Reorient",
"Nifti",
"files",
"to",
"RAS"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/images.py#L532-L536 | train | 211,785 |
poldracklab/niworkflows | niworkflows/interfaces/images.py | normalize_xform | def normalize_xform(img):
""" Set identical, valid qform and sform matrices in an image
Selects the best available affine (sform > qform > shape-based), and
coerces it to be qform-compatible (no shears).
The resulting image represents this same affine as both qform and sform,
and is marked as NIFTI_XFORM_ALIGNED_ANAT, indicating that it is valid,
not aligned to template, and not necessarily preserving the original
coordinates.
If header would be unchanged, returns input image.
"""
# Let nibabel convert from affine to quaternions, and recover xform
tmp_header = img.header.copy()
tmp_header.set_qform(img.affine)
xform = tmp_header.get_qform()
xform_code = 2
# Check desired codes
qform, qform_code = img.get_qform(coded=True)
sform, sform_code = img.get_sform(coded=True)
if all((qform is not None and np.allclose(qform, xform),
sform is not None and np.allclose(sform, xform),
int(qform_code) == xform_code, int(sform_code) == xform_code)):
return img
new_img = img.__class__(img.get_data(), xform, img.header)
# Unconditionally set sform/qform
new_img.set_sform(xform, xform_code)
new_img.set_qform(xform, xform_code)
return new_img | python | def normalize_xform(img):
""" Set identical, valid qform and sform matrices in an image
Selects the best available affine (sform > qform > shape-based), and
coerces it to be qform-compatible (no shears).
The resulting image represents this same affine as both qform and sform,
and is marked as NIFTI_XFORM_ALIGNED_ANAT, indicating that it is valid,
not aligned to template, and not necessarily preserving the original
coordinates.
If header would be unchanged, returns input image.
"""
# Let nibabel convert from affine to quaternions, and recover xform
tmp_header = img.header.copy()
tmp_header.set_qform(img.affine)
xform = tmp_header.get_qform()
xform_code = 2
# Check desired codes
qform, qform_code = img.get_qform(coded=True)
sform, sform_code = img.get_sform(coded=True)
if all((qform is not None and np.allclose(qform, xform),
sform is not None and np.allclose(sform, xform),
int(qform_code) == xform_code, int(sform_code) == xform_code)):
return img
new_img = img.__class__(img.get_data(), xform, img.header)
# Unconditionally set sform/qform
new_img.set_sform(xform, xform_code)
new_img.set_qform(xform, xform_code)
return new_img | [
"def",
"normalize_xform",
"(",
"img",
")",
":",
"# Let nibabel convert from affine to quaternions, and recover xform",
"tmp_header",
"=",
"img",
".",
"header",
".",
"copy",
"(",
")",
"tmp_header",
".",
"set_qform",
"(",
"img",
".",
"affine",
")",
"xform",
"=",
"tm... | Set identical, valid qform and sform matrices in an image
Selects the best available affine (sform > qform > shape-based), and
coerces it to be qform-compatible (no shears).
The resulting image represents this same affine as both qform and sform,
and is marked as NIFTI_XFORM_ALIGNED_ANAT, indicating that it is valid,
not aligned to template, and not necessarily preserving the original
coordinates.
If header would be unchanged, returns input image. | [
"Set",
"identical",
"valid",
"qform",
"and",
"sform",
"matrices",
"in",
"an",
"image"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/images.py#L555-L586 | train | 211,786 |
poldracklab/niworkflows | niworkflows/interfaces/images.py | demean | def demean(in_file, in_mask, only_mask=False, newpath=None):
"""Demean ``in_file`` within the mask defined by ``in_mask``"""
import os
import numpy as np
import nibabel as nb
from nipype.utils.filemanip import fname_presuffix
out_file = fname_presuffix(in_file, suffix='_demeaned',
newpath=os.getcwd())
nii = nb.load(in_file)
msk = nb.load(in_mask).get_data()
data = nii.get_data()
if only_mask:
data[msk > 0] -= np.median(data[msk > 0])
else:
data -= np.median(data[msk > 0])
nb.Nifti1Image(data, nii.affine, nii.header).to_filename(
out_file)
return out_file | python | def demean(in_file, in_mask, only_mask=False, newpath=None):
"""Demean ``in_file`` within the mask defined by ``in_mask``"""
import os
import numpy as np
import nibabel as nb
from nipype.utils.filemanip import fname_presuffix
out_file = fname_presuffix(in_file, suffix='_demeaned',
newpath=os.getcwd())
nii = nb.load(in_file)
msk = nb.load(in_mask).get_data()
data = nii.get_data()
if only_mask:
data[msk > 0] -= np.median(data[msk > 0])
else:
data -= np.median(data[msk > 0])
nb.Nifti1Image(data, nii.affine, nii.header).to_filename(
out_file)
return out_file | [
"def",
"demean",
"(",
"in_file",
",",
"in_mask",
",",
"only_mask",
"=",
"False",
",",
"newpath",
"=",
"None",
")",
":",
"import",
"os",
"import",
"numpy",
"as",
"np",
"import",
"nibabel",
"as",
"nb",
"from",
"nipype",
".",
"utils",
".",
"filemanip",
"i... | Demean ``in_file`` within the mask defined by ``in_mask`` | [
"Demean",
"in_file",
"within",
"the",
"mask",
"defined",
"by",
"in_mask"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/images.py#L589-L607 | train | 211,787 |
poldracklab/niworkflows | niworkflows/interfaces/images.py | nii_ones_like | def nii_ones_like(in_file, value, dtype, newpath=None):
"""Create a NIfTI file filled with ``value``, matching properties of ``in_file``"""
import os
import numpy as np
import nibabel as nb
nii = nb.load(in_file)
data = np.ones(nii.shape, dtype=float) * value
out_file = os.path.join(newpath or os.getcwd(), "filled.nii.gz")
nii = nb.Nifti1Image(data, nii.affine, nii.header)
nii.set_data_dtype(dtype)
nii.to_filename(out_file)
return out_file | python | def nii_ones_like(in_file, value, dtype, newpath=None):
"""Create a NIfTI file filled with ``value``, matching properties of ``in_file``"""
import os
import numpy as np
import nibabel as nb
nii = nb.load(in_file)
data = np.ones(nii.shape, dtype=float) * value
out_file = os.path.join(newpath or os.getcwd(), "filled.nii.gz")
nii = nb.Nifti1Image(data, nii.affine, nii.header)
nii.set_data_dtype(dtype)
nii.to_filename(out_file)
return out_file | [
"def",
"nii_ones_like",
"(",
"in_file",
",",
"value",
",",
"dtype",
",",
"newpath",
"=",
"None",
")",
":",
"import",
"os",
"import",
"numpy",
"as",
"np",
"import",
"nibabel",
"as",
"nb",
"nii",
"=",
"nb",
".",
"load",
"(",
"in_file",
")",
"data",
"="... | Create a NIfTI file filled with ``value``, matching properties of ``in_file`` | [
"Create",
"a",
"NIfTI",
"file",
"filled",
"with",
"value",
"matching",
"properties",
"of",
"in_file"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/images.py#L610-L624 | train | 211,788 |
poldracklab/niworkflows | niworkflows/common/orient.py | reorient_wf | def reorient_wf(name='ReorientWorkflow'):
"""A workflow to reorient images to 'RPI' orientation"""
workflow = pe.Workflow(name=name)
inputnode = pe.Node(niu.IdentityInterface(fields=['in_file']),
name='inputnode')
outputnode = pe.Node(niu.IdentityInterface(
fields=['out_file']), name='outputnode')
deoblique = pe.Node(afni.Refit(deoblique=True), name='deoblique')
reorient = pe.Node(afni.Resample(
orientation='RPI', outputtype='NIFTI_GZ'), name='reorient')
workflow.connect([
(inputnode, deoblique, [('in_file', 'in_file')]),
(deoblique, reorient, [('out_file', 'in_file')]),
(reorient, outputnode, [('out_file', 'out_file')])
])
return workflow | python | def reorient_wf(name='ReorientWorkflow'):
"""A workflow to reorient images to 'RPI' orientation"""
workflow = pe.Workflow(name=name)
inputnode = pe.Node(niu.IdentityInterface(fields=['in_file']),
name='inputnode')
outputnode = pe.Node(niu.IdentityInterface(
fields=['out_file']), name='outputnode')
deoblique = pe.Node(afni.Refit(deoblique=True), name='deoblique')
reorient = pe.Node(afni.Resample(
orientation='RPI', outputtype='NIFTI_GZ'), name='reorient')
workflow.connect([
(inputnode, deoblique, [('in_file', 'in_file')]),
(deoblique, reorient, [('out_file', 'in_file')]),
(reorient, outputnode, [('out_file', 'out_file')])
])
return workflow | [
"def",
"reorient_wf",
"(",
"name",
"=",
"'ReorientWorkflow'",
")",
":",
"workflow",
"=",
"pe",
".",
"Workflow",
"(",
"name",
"=",
"name",
")",
"inputnode",
"=",
"pe",
".",
"Node",
"(",
"niu",
".",
"IdentityInterface",
"(",
"fields",
"=",
"[",
"'in_file'"... | A workflow to reorient images to 'RPI' orientation | [
"A",
"workflow",
"to",
"reorient",
"images",
"to",
"RPI",
"orientation"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/common/orient.py#L10-L27 | train | 211,789 |
poldracklab/niworkflows | niworkflows/interfaces/utils.py | _tsv2json | def _tsv2json(in_tsv, out_json, index_column, additional_metadata=None,
drop_columns=None, enforce_case=True):
"""
Convert metadata from TSV format to JSON format.
Parameters
----------
in_tsv: str
Path to the metadata in TSV format.
out_json: str
Path where the metadata should be saved in JSON format after
conversion. If this is None, then a dictionary is returned instead.
index_column: str
Name of the column in the TSV to be used as an index (top-level key in
the JSON).
additional_metadata: dict
Any additional metadata that should be applied to all entries in the
JSON.
drop_columns: list
List of columns from the input TSV to be dropped from the JSON.
enforce_case: bool
Indicates whether BIDS case conventions should be followed. Currently,
this means that index fields (column names in the associated data TSV)
use snake case and other fields use camel case.
Returns
-------
str
Path to the metadata saved in JSON format.
"""
import pandas as pd
# Adapted from https://dev.to/rrampage/snake-case-to-camel-case-and- ...
# back-using-regular-expressions-and-python-m9j
re_to_camel = r'(.*?)_([a-zA-Z0-9])'
re_to_snake = r'(^.+?|.*?)((?<![_A-Z])[A-Z]|(?<![_0-9])[0-9]+)'
def snake(match):
return '{}_{}'.format(match.group(1).lower(), match.group(2).lower())
def camel(match):
return '{}{}'.format(match.group(1), match.group(2).upper())
# from fmriprep
def less_breakable(a_string):
""" hardens the string to different envs (i.e. case insensitive, no
whitespace, '#' """
return ''.join(a_string.split()).strip('#')
drop_columns = drop_columns or []
additional_metadata = additional_metadata or {}
tsv_data = pd.read_csv(in_tsv, '\t')
for k, v in additional_metadata.items():
tsv_data[k] = v
for col in drop_columns:
tsv_data.drop(labels=col, axis='columns', inplace=True)
tsv_data.set_index(index_column, drop=True, inplace=True)
if enforce_case:
tsv_data.index = [re.sub(re_to_snake, snake,
less_breakable(i), 0).lower()
for i in tsv_data.index]
tsv_data.columns = [re.sub(re_to_camel, camel,
less_breakable(i).title(), 0)
for i in tsv_data.columns]
json_data = tsv_data.to_json(orient='index')
json_data = json.JSONDecoder(
object_pairs_hook=OrderedDict).decode(json_data)
if out_json is None:
return json_data
with open(out_json, 'w') as f:
json.dump(json_data, f, indent=4)
return out_json | python | def _tsv2json(in_tsv, out_json, index_column, additional_metadata=None,
drop_columns=None, enforce_case=True):
"""
Convert metadata from TSV format to JSON format.
Parameters
----------
in_tsv: str
Path to the metadata in TSV format.
out_json: str
Path where the metadata should be saved in JSON format after
conversion. If this is None, then a dictionary is returned instead.
index_column: str
Name of the column in the TSV to be used as an index (top-level key in
the JSON).
additional_metadata: dict
Any additional metadata that should be applied to all entries in the
JSON.
drop_columns: list
List of columns from the input TSV to be dropped from the JSON.
enforce_case: bool
Indicates whether BIDS case conventions should be followed. Currently,
this means that index fields (column names in the associated data TSV)
use snake case and other fields use camel case.
Returns
-------
str
Path to the metadata saved in JSON format.
"""
import pandas as pd
# Adapted from https://dev.to/rrampage/snake-case-to-camel-case-and- ...
# back-using-regular-expressions-and-python-m9j
re_to_camel = r'(.*?)_([a-zA-Z0-9])'
re_to_snake = r'(^.+?|.*?)((?<![_A-Z])[A-Z]|(?<![_0-9])[0-9]+)'
def snake(match):
return '{}_{}'.format(match.group(1).lower(), match.group(2).lower())
def camel(match):
return '{}{}'.format(match.group(1), match.group(2).upper())
# from fmriprep
def less_breakable(a_string):
""" hardens the string to different envs (i.e. case insensitive, no
whitespace, '#' """
return ''.join(a_string.split()).strip('#')
drop_columns = drop_columns or []
additional_metadata = additional_metadata or {}
tsv_data = pd.read_csv(in_tsv, '\t')
for k, v in additional_metadata.items():
tsv_data[k] = v
for col in drop_columns:
tsv_data.drop(labels=col, axis='columns', inplace=True)
tsv_data.set_index(index_column, drop=True, inplace=True)
if enforce_case:
tsv_data.index = [re.sub(re_to_snake, snake,
less_breakable(i), 0).lower()
for i in tsv_data.index]
tsv_data.columns = [re.sub(re_to_camel, camel,
less_breakable(i).title(), 0)
for i in tsv_data.columns]
json_data = tsv_data.to_json(orient='index')
json_data = json.JSONDecoder(
object_pairs_hook=OrderedDict).decode(json_data)
if out_json is None:
return json_data
with open(out_json, 'w') as f:
json.dump(json_data, f, indent=4)
return out_json | [
"def",
"_tsv2json",
"(",
"in_tsv",
",",
"out_json",
",",
"index_column",
",",
"additional_metadata",
"=",
"None",
",",
"drop_columns",
"=",
"None",
",",
"enforce_case",
"=",
"True",
")",
":",
"import",
"pandas",
"as",
"pd",
"# Adapted from https://dev.to/rrampage/... | Convert metadata from TSV format to JSON format.
Parameters
----------
in_tsv: str
Path to the metadata in TSV format.
out_json: str
Path where the metadata should be saved in JSON format after
conversion. If this is None, then a dictionary is returned instead.
index_column: str
Name of the column in the TSV to be used as an index (top-level key in
the JSON).
additional_metadata: dict
Any additional metadata that should be applied to all entries in the
JSON.
drop_columns: list
List of columns from the input TSV to be dropped from the JSON.
enforce_case: bool
Indicates whether BIDS case conventions should be followed. Currently,
this means that index fields (column names in the associated data TSV)
use snake case and other fields use camel case.
Returns
-------
str
Path to the metadata saved in JSON format. | [
"Convert",
"metadata",
"from",
"TSV",
"format",
"to",
"JSON",
"format",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/utils.py#L793-L864 | train | 211,790 |
poldracklab/niworkflows | niworkflows/interfaces/utils.py | _tpm2roi | def _tpm2roi(in_tpm, in_mask, mask_erosion_mm=None, erosion_mm=None,
mask_erosion_prop=None, erosion_prop=None, pthres=0.95,
newpath=None):
"""
Generate a mask from a tissue probability map
"""
tpm_img = nb.load(in_tpm)
roi_mask = (tpm_img.get_data() >= pthres).astype(np.uint8)
eroded_mask_file = None
erode_in = (mask_erosion_mm is not None and mask_erosion_mm > 0 or
mask_erosion_prop is not None and mask_erosion_prop < 1)
if erode_in:
eroded_mask_file = fname_presuffix(in_mask, suffix='_eroded',
newpath=newpath)
mask_img = nb.load(in_mask)
mask_data = mask_img.get_data().astype(np.uint8)
if mask_erosion_mm:
iter_n = max(int(mask_erosion_mm / max(mask_img.header.get_zooms())), 1)
mask_data = nd.binary_erosion(mask_data, iterations=iter_n)
else:
orig_vol = np.sum(mask_data > 0)
while np.sum(mask_data > 0) / orig_vol > mask_erosion_prop:
mask_data = nd.binary_erosion(mask_data, iterations=1)
# Store mask
eroded = nb.Nifti1Image(mask_data, mask_img.affine, mask_img.header)
eroded.set_data_dtype(np.uint8)
eroded.to_filename(eroded_mask_file)
# Mask TPM data (no effect if not eroded)
roi_mask[~mask_data] = 0
# shrinking
erode_out = (erosion_mm is not None and erosion_mm > 0 or
erosion_prop is not None and erosion_prop < 1)
if erode_out:
if erosion_mm:
iter_n = max(int(erosion_mm / max(tpm_img.header.get_zooms())), 1)
iter_n = int(erosion_mm / max(tpm_img.header.get_zooms()))
roi_mask = nd.binary_erosion(roi_mask, iterations=iter_n)
else:
orig_vol = np.sum(roi_mask > 0)
while np.sum(roi_mask > 0) / orig_vol > erosion_prop:
roi_mask = nd.binary_erosion(roi_mask, iterations=1)
# Create image to resample
roi_fname = fname_presuffix(in_tpm, suffix='_roi', newpath=newpath)
roi_img = nb.Nifti1Image(roi_mask, tpm_img.affine, tpm_img.header)
roi_img.set_data_dtype(np.uint8)
roi_img.to_filename(roi_fname)
return roi_fname, eroded_mask_file or in_mask | python | def _tpm2roi(in_tpm, in_mask, mask_erosion_mm=None, erosion_mm=None,
mask_erosion_prop=None, erosion_prop=None, pthres=0.95,
newpath=None):
"""
Generate a mask from a tissue probability map
"""
tpm_img = nb.load(in_tpm)
roi_mask = (tpm_img.get_data() >= pthres).astype(np.uint8)
eroded_mask_file = None
erode_in = (mask_erosion_mm is not None and mask_erosion_mm > 0 or
mask_erosion_prop is not None and mask_erosion_prop < 1)
if erode_in:
eroded_mask_file = fname_presuffix(in_mask, suffix='_eroded',
newpath=newpath)
mask_img = nb.load(in_mask)
mask_data = mask_img.get_data().astype(np.uint8)
if mask_erosion_mm:
iter_n = max(int(mask_erosion_mm / max(mask_img.header.get_zooms())), 1)
mask_data = nd.binary_erosion(mask_data, iterations=iter_n)
else:
orig_vol = np.sum(mask_data > 0)
while np.sum(mask_data > 0) / orig_vol > mask_erosion_prop:
mask_data = nd.binary_erosion(mask_data, iterations=1)
# Store mask
eroded = nb.Nifti1Image(mask_data, mask_img.affine, mask_img.header)
eroded.set_data_dtype(np.uint8)
eroded.to_filename(eroded_mask_file)
# Mask TPM data (no effect if not eroded)
roi_mask[~mask_data] = 0
# shrinking
erode_out = (erosion_mm is not None and erosion_mm > 0 or
erosion_prop is not None and erosion_prop < 1)
if erode_out:
if erosion_mm:
iter_n = max(int(erosion_mm / max(tpm_img.header.get_zooms())), 1)
iter_n = int(erosion_mm / max(tpm_img.header.get_zooms()))
roi_mask = nd.binary_erosion(roi_mask, iterations=iter_n)
else:
orig_vol = np.sum(roi_mask > 0)
while np.sum(roi_mask > 0) / orig_vol > erosion_prop:
roi_mask = nd.binary_erosion(roi_mask, iterations=1)
# Create image to resample
roi_fname = fname_presuffix(in_tpm, suffix='_roi', newpath=newpath)
roi_img = nb.Nifti1Image(roi_mask, tpm_img.affine, tpm_img.header)
roi_img.set_data_dtype(np.uint8)
roi_img.to_filename(roi_fname)
return roi_fname, eroded_mask_file or in_mask | [
"def",
"_tpm2roi",
"(",
"in_tpm",
",",
"in_mask",
",",
"mask_erosion_mm",
"=",
"None",
",",
"erosion_mm",
"=",
"None",
",",
"mask_erosion_prop",
"=",
"None",
",",
"erosion_prop",
"=",
"None",
",",
"pthres",
"=",
"0.95",
",",
"newpath",
"=",
"None",
")",
... | Generate a mask from a tissue probability map | [
"Generate",
"a",
"mask",
"from",
"a",
"tissue",
"probability",
"map"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/utils.py#L867-L918 | train | 211,791 |
poldracklab/niworkflows | niworkflows/reports/core.py | run_reports | def run_reports(reportlets_dir, out_dir, subject_label, run_uuid, config=None,
packagename=None):
"""
Runs the reports
.. testsetup::
>>> from shutil import copytree
>>> from tempfile import TemporaryDirectory
>>> new_path = Path(__file__).resolve().parent.parent
>>> test_data_path = new_path / 'data' / 'tests' / 'work'
>>> tmpdir = TemporaryDirectory()
>>> os.chdir(tmpdir.name) #noqa
>>> testdir = Path().resolve()
>>> data_dir = copytree(test_data_path, testdir / 'work')
>>> (testdir / 'fmriprep').mkdir(parents=True, exist_ok=True)
.. doctest::
>>> run_reports(str(testdir / 'work' / 'reportlets'),
... str(testdir / 'out'), '01', 'madeoutuuid')
0
.. testcleanup::
>>> tmpdir.cleanup()
"""
report = Report(Path(reportlets_dir), out_dir, run_uuid, config=config,
subject_id=subject_label, packagename=packagename)
return report.generate_report() | python | def run_reports(reportlets_dir, out_dir, subject_label, run_uuid, config=None,
packagename=None):
"""
Runs the reports
.. testsetup::
>>> from shutil import copytree
>>> from tempfile import TemporaryDirectory
>>> new_path = Path(__file__).resolve().parent.parent
>>> test_data_path = new_path / 'data' / 'tests' / 'work'
>>> tmpdir = TemporaryDirectory()
>>> os.chdir(tmpdir.name) #noqa
>>> testdir = Path().resolve()
>>> data_dir = copytree(test_data_path, testdir / 'work')
>>> (testdir / 'fmriprep').mkdir(parents=True, exist_ok=True)
.. doctest::
>>> run_reports(str(testdir / 'work' / 'reportlets'),
... str(testdir / 'out'), '01', 'madeoutuuid')
0
.. testcleanup::
>>> tmpdir.cleanup()
"""
report = Report(Path(reportlets_dir), out_dir, run_uuid, config=config,
subject_id=subject_label, packagename=packagename)
return report.generate_report() | [
"def",
"run_reports",
"(",
"reportlets_dir",
",",
"out_dir",
",",
"subject_label",
",",
"run_uuid",
",",
"config",
"=",
"None",
",",
"packagename",
"=",
"None",
")",
":",
"report",
"=",
"Report",
"(",
"Path",
"(",
"reportlets_dir",
")",
",",
"out_dir",
","... | Runs the reports
.. testsetup::
>>> from shutil import copytree
>>> from tempfile import TemporaryDirectory
>>> new_path = Path(__file__).resolve().parent.parent
>>> test_data_path = new_path / 'data' / 'tests' / 'work'
>>> tmpdir = TemporaryDirectory()
>>> os.chdir(tmpdir.name) #noqa
>>> testdir = Path().resolve()
>>> data_dir = copytree(test_data_path, testdir / 'work')
>>> (testdir / 'fmriprep').mkdir(parents=True, exist_ok=True)
.. doctest::
>>> run_reports(str(testdir / 'work' / 'reportlets'),
... str(testdir / 'out'), '01', 'madeoutuuid')
0
.. testcleanup::
>>> tmpdir.cleanup() | [
"Runs",
"the",
"reports"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/reports/core.py#L352-L382 | train | 211,792 |
poldracklab/niworkflows | niworkflows/reports/core.py | generate_reports | def generate_reports(subject_list, output_dir, work_dir, run_uuid, config=None,
packagename=None):
"""
A wrapper to run_reports on a given ``subject_list``
"""
reports_dir = str(Path(work_dir) / 'reportlets')
report_errors = [
run_reports(reports_dir, output_dir, subject_label, run_uuid,
config, packagename=packagename)
for subject_label in subject_list
]
errno = sum(report_errors)
if errno:
import logging
logger = logging.getLogger('cli')
error_list = ', '.join('%s (%d)' % (subid, err)
for subid, err in zip(subject_list, report_errors) if err)
logger.error(
'Preprocessing did not finish successfully. Errors occurred while processing '
'data from participants: %s. Check the HTML reports for details.', error_list)
return errno | python | def generate_reports(subject_list, output_dir, work_dir, run_uuid, config=None,
packagename=None):
"""
A wrapper to run_reports on a given ``subject_list``
"""
reports_dir = str(Path(work_dir) / 'reportlets')
report_errors = [
run_reports(reports_dir, output_dir, subject_label, run_uuid,
config, packagename=packagename)
for subject_label in subject_list
]
errno = sum(report_errors)
if errno:
import logging
logger = logging.getLogger('cli')
error_list = ', '.join('%s (%d)' % (subid, err)
for subid, err in zip(subject_list, report_errors) if err)
logger.error(
'Preprocessing did not finish successfully. Errors occurred while processing '
'data from participants: %s. Check the HTML reports for details.', error_list)
return errno | [
"def",
"generate_reports",
"(",
"subject_list",
",",
"output_dir",
",",
"work_dir",
",",
"run_uuid",
",",
"config",
"=",
"None",
",",
"packagename",
"=",
"None",
")",
":",
"reports_dir",
"=",
"str",
"(",
"Path",
"(",
"work_dir",
")",
"/",
"'reportlets'",
"... | A wrapper to run_reports on a given ``subject_list`` | [
"A",
"wrapper",
"to",
"run_reports",
"on",
"a",
"given",
"subject_list"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/reports/core.py#L385-L406 | train | 211,793 |
poldracklab/niworkflows | niworkflows/reports/core.py | Report.index | def index(self, config):
"""
Traverse the reports config definition and instantiate reportlets.
This method also places figures in their final location.
"""
for subrep_cfg in config:
# First determine whether we need to split by some ordering
# (ie. sessions / tasks / runs), which are separated by commas.
orderings = [s for s in subrep_cfg.get('ordering', '').strip().split(',') if s]
queries = []
for key in orderings:
values = getattr(self.layout, 'get_%s%s' % (key, PLURAL_SUFFIX[key]))()
if values:
queries.append((key, values))
if not queries: # E.g. this is an anatomical reportlet
reportlets = [Reportlet(self.layout, self.out_dir, config=cfg)
for cfg in subrep_cfg['reportlets']]
else:
# Do not use dictionary for queries, as we need to preserve ordering
# of ordering columns.
reportlets = []
entities, values = zip(*queries)
combinations = list(product(*values)) # e.g.: [('rest', 1), ('rest', 2)]
for c in combinations:
# Set a common title for this particular combination c
title = 'Reports for: %s.' % ', '.join(
['%s <span class="bids-entity">%s</span>' % (entities[i], c[i])
for i in range(len(c))])
for cfg in subrep_cfg['reportlets']:
cfg['bids'].update({entities[i]: c[i] for i in range(len(c))})
rlet = Reportlet(self.layout, self.out_dir, config=cfg)
if not rlet.is_empty():
rlet.title = title
title = None
reportlets.append(rlet)
# Filter out empty reportlets
reportlets = [r for r in reportlets if not r.is_empty()]
if reportlets:
sub_report = SubReport(
subrep_cfg['name'],
isnested=len(queries) > 0,
reportlets=reportlets,
title=subrep_cfg.get('title'))
self.sections.append(sub_report)
# Populate errors sections
error_dir = self.out_dir / self.packagename / 'sub-{}'.format(self.subject_id) / \
'log' / self.run_uuid
if error_dir.is_dir():
from ..utils.misc import read_crashfile
self.errors = [read_crashfile(str(f)) for f in error_dir.glob('crash*.*')] | python | def index(self, config):
"""
Traverse the reports config definition and instantiate reportlets.
This method also places figures in their final location.
"""
for subrep_cfg in config:
# First determine whether we need to split by some ordering
# (ie. sessions / tasks / runs), which are separated by commas.
orderings = [s for s in subrep_cfg.get('ordering', '').strip().split(',') if s]
queries = []
for key in orderings:
values = getattr(self.layout, 'get_%s%s' % (key, PLURAL_SUFFIX[key]))()
if values:
queries.append((key, values))
if not queries: # E.g. this is an anatomical reportlet
reportlets = [Reportlet(self.layout, self.out_dir, config=cfg)
for cfg in subrep_cfg['reportlets']]
else:
# Do not use dictionary for queries, as we need to preserve ordering
# of ordering columns.
reportlets = []
entities, values = zip(*queries)
combinations = list(product(*values)) # e.g.: [('rest', 1), ('rest', 2)]
for c in combinations:
# Set a common title for this particular combination c
title = 'Reports for: %s.' % ', '.join(
['%s <span class="bids-entity">%s</span>' % (entities[i], c[i])
for i in range(len(c))])
for cfg in subrep_cfg['reportlets']:
cfg['bids'].update({entities[i]: c[i] for i in range(len(c))})
rlet = Reportlet(self.layout, self.out_dir, config=cfg)
if not rlet.is_empty():
rlet.title = title
title = None
reportlets.append(rlet)
# Filter out empty reportlets
reportlets = [r for r in reportlets if not r.is_empty()]
if reportlets:
sub_report = SubReport(
subrep_cfg['name'],
isnested=len(queries) > 0,
reportlets=reportlets,
title=subrep_cfg.get('title'))
self.sections.append(sub_report)
# Populate errors sections
error_dir = self.out_dir / self.packagename / 'sub-{}'.format(self.subject_id) / \
'log' / self.run_uuid
if error_dir.is_dir():
from ..utils.misc import read_crashfile
self.errors = [read_crashfile(str(f)) for f in error_dir.glob('crash*.*')] | [
"def",
"index",
"(",
"self",
",",
"config",
")",
":",
"for",
"subrep_cfg",
"in",
"config",
":",
"# First determine whether we need to split by some ordering",
"# (ie. sessions / tasks / runs), which are separated by commas.",
"orderings",
"=",
"[",
"s",
"for",
"s",
"in",
... | Traverse the reports config definition and instantiate reportlets.
This method also places figures in their final location. | [
"Traverse",
"the",
"reports",
"config",
"definition",
"and",
"instantiate",
"reportlets",
".",
"This",
"method",
"also",
"places",
"figures",
"in",
"their",
"final",
"location",
"."
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/reports/core.py#L252-L305 | train | 211,794 |
poldracklab/niworkflows | niworkflows/reports/core.py | Report.generate_report | def generate_report(self):
"""Once the Report has been indexed, the final HTML can be generated"""
logs_path = self.out_dir / 'logs'
boilerplate = []
boiler_idx = 0
if (logs_path / 'CITATION.html').exists():
text = (logs_path / 'CITATION.html').read_text(encoding='UTF-8')
text = '<div class="boiler-html">%s</div>' % re.compile(
'<body>(.*?)</body>',
re.DOTALL | re.IGNORECASE).findall(text)[0].strip()
boilerplate.append((boiler_idx, 'HTML', text))
boiler_idx += 1
if (logs_path / 'CITATION.md').exists():
text = '<pre>%s</pre>\n' % (logs_path / 'CITATION.md').read_text(encoding='UTF-8')
boilerplate.append((boiler_idx, 'Markdown', text))
boiler_idx += 1
if (logs_path / 'CITATION.tex').exists():
text = (logs_path / 'CITATION.tex').read_text(encoding='UTF-8')
text = re.compile(
r'\\begin{document}(.*?)\\end{document}',
re.DOTALL | re.IGNORECASE).findall(text)[0].strip()
text = '<pre>%s</pre>\n' % text
text += '<h3>Bibliography</h3>\n'
text += '<pre>%s</pre>\n' % Path(
pkgrf(self.packagename, 'data/boilerplate.bib')).read_text(encoding='UTF-8')
boilerplate.append((boiler_idx, 'LaTeX', text))
boiler_idx += 1
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(searchpath=str(self.template_path.parent)),
trim_blocks=True, lstrip_blocks=True
)
report_tpl = env.get_template(self.template_path.name)
report_render = report_tpl.render(sections=self.sections, errors=self.errors,
boilerplate=boilerplate)
# Write out report
(self.out_dir / self.out_filename).write_text(report_render, encoding='UTF-8')
return len(self.errors) | python | def generate_report(self):
"""Once the Report has been indexed, the final HTML can be generated"""
logs_path = self.out_dir / 'logs'
boilerplate = []
boiler_idx = 0
if (logs_path / 'CITATION.html').exists():
text = (logs_path / 'CITATION.html').read_text(encoding='UTF-8')
text = '<div class="boiler-html">%s</div>' % re.compile(
'<body>(.*?)</body>',
re.DOTALL | re.IGNORECASE).findall(text)[0].strip()
boilerplate.append((boiler_idx, 'HTML', text))
boiler_idx += 1
if (logs_path / 'CITATION.md').exists():
text = '<pre>%s</pre>\n' % (logs_path / 'CITATION.md').read_text(encoding='UTF-8')
boilerplate.append((boiler_idx, 'Markdown', text))
boiler_idx += 1
if (logs_path / 'CITATION.tex').exists():
text = (logs_path / 'CITATION.tex').read_text(encoding='UTF-8')
text = re.compile(
r'\\begin{document}(.*?)\\end{document}',
re.DOTALL | re.IGNORECASE).findall(text)[0].strip()
text = '<pre>%s</pre>\n' % text
text += '<h3>Bibliography</h3>\n'
text += '<pre>%s</pre>\n' % Path(
pkgrf(self.packagename, 'data/boilerplate.bib')).read_text(encoding='UTF-8')
boilerplate.append((boiler_idx, 'LaTeX', text))
boiler_idx += 1
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(searchpath=str(self.template_path.parent)),
trim_blocks=True, lstrip_blocks=True
)
report_tpl = env.get_template(self.template_path.name)
report_render = report_tpl.render(sections=self.sections, errors=self.errors,
boilerplate=boilerplate)
# Write out report
(self.out_dir / self.out_filename).write_text(report_render, encoding='UTF-8')
return len(self.errors) | [
"def",
"generate_report",
"(",
"self",
")",
":",
"logs_path",
"=",
"self",
".",
"out_dir",
"/",
"'logs'",
"boilerplate",
"=",
"[",
"]",
"boiler_idx",
"=",
"0",
"if",
"(",
"logs_path",
"/",
"'CITATION.html'",
")",
".",
"exists",
"(",
")",
":",
"text",
"... | Once the Report has been indexed, the final HTML can be generated | [
"Once",
"the",
"Report",
"has",
"been",
"indexed",
"the",
"final",
"HTML",
"can",
"be",
"generated"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/reports/core.py#L307-L349 | train | 211,795 |
poldracklab/niworkflows | niworkflows/interfaces/itk.py | _applytfms | def _applytfms(args):
"""
Applies ANTs' antsApplyTransforms to the input image.
All inputs are zipped in one tuple to make it digestible by
multiprocessing's map
"""
import nibabel as nb
from nipype.utils.filemanip import fname_presuffix
from niworkflows.interfaces.fixes import FixHeaderApplyTransforms as ApplyTransforms
in_file, in_xform, ifargs, index, newpath = args
out_file = fname_presuffix(in_file, suffix='_xform-%05d' % index,
newpath=newpath, use_ext=True)
copy_dtype = ifargs.pop('copy_dtype', False)
xfm = ApplyTransforms(
input_image=in_file, transforms=in_xform, output_image=out_file, **ifargs)
xfm.terminal_output = 'allatonce'
xfm.resource_monitor = False
runtime = xfm.run().runtime
if copy_dtype:
nii = nb.load(out_file)
in_dtype = nb.load(in_file).get_data_dtype()
# Overwrite only iff dtypes don't match
if in_dtype != nii.get_data_dtype():
nii.set_data_dtype(in_dtype)
nii.to_filename(out_file)
return (out_file, runtime.cmdline) | python | def _applytfms(args):
"""
Applies ANTs' antsApplyTransforms to the input image.
All inputs are zipped in one tuple to make it digestible by
multiprocessing's map
"""
import nibabel as nb
from nipype.utils.filemanip import fname_presuffix
from niworkflows.interfaces.fixes import FixHeaderApplyTransforms as ApplyTransforms
in_file, in_xform, ifargs, index, newpath = args
out_file = fname_presuffix(in_file, suffix='_xform-%05d' % index,
newpath=newpath, use_ext=True)
copy_dtype = ifargs.pop('copy_dtype', False)
xfm = ApplyTransforms(
input_image=in_file, transforms=in_xform, output_image=out_file, **ifargs)
xfm.terminal_output = 'allatonce'
xfm.resource_monitor = False
runtime = xfm.run().runtime
if copy_dtype:
nii = nb.load(out_file)
in_dtype = nb.load(in_file).get_data_dtype()
# Overwrite only iff dtypes don't match
if in_dtype != nii.get_data_dtype():
nii.set_data_dtype(in_dtype)
nii.to_filename(out_file)
return (out_file, runtime.cmdline) | [
"def",
"_applytfms",
"(",
"args",
")",
":",
"import",
"nibabel",
"as",
"nb",
"from",
"nipype",
".",
"utils",
".",
"filemanip",
"import",
"fname_presuffix",
"from",
"niworkflows",
".",
"interfaces",
".",
"fixes",
"import",
"FixHeaderApplyTransforms",
"as",
"Apply... | Applies ANTs' antsApplyTransforms to the input image.
All inputs are zipped in one tuple to make it digestible by
multiprocessing's map | [
"Applies",
"ANTs",
"antsApplyTransforms",
"to",
"the",
"input",
"image",
".",
"All",
"inputs",
"are",
"zipped",
"in",
"one",
"tuple",
"to",
"make",
"it",
"digestible",
"by",
"multiprocessing",
"s",
"map"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/itk.py#L243-L273 | train | 211,796 |
poldracklab/niworkflows | niworkflows/interfaces/itk.py | _arrange_xfms | def _arrange_xfms(transforms, num_files, tmp_folder):
"""
Convenience method to arrange the list of transforms that should be applied
to each input file
"""
base_xform = ['#Insight Transform File V1.0', '#Transform 0']
# Initialize the transforms matrix
xfms_T = []
for i, tf_file in enumerate(transforms):
# If it is a deformation field, copy to the tfs_matrix directly
if guess_type(tf_file)[0] != 'text/plain':
xfms_T.append([tf_file] * num_files)
continue
with open(tf_file) as tf_fh:
tfdata = tf_fh.read().strip()
# If it is not an ITK transform file, copy to the tfs_matrix directly
if not tfdata.startswith('#Insight Transform File'):
xfms_T.append([tf_file] * num_files)
continue
# Count number of transforms in ITK transform file
nxforms = tfdata.count('#Transform')
# Remove first line
tfdata = tfdata.split('\n')[1:]
# If it is a ITK transform file with only 1 xform, copy to the tfs_matrix directly
if nxforms == 1:
xfms_T.append([tf_file] * num_files)
continue
if nxforms != num_files:
raise RuntimeError('Number of transforms (%d) found in the ITK file does not match'
' the number of input image files (%d).' % (nxforms, num_files))
# At this point splitting transforms will be necessary, generate a base name
out_base = fname_presuffix(tf_file, suffix='_pos-%03d_xfm-{:05d}' % i,
newpath=tmp_folder.name).format
# Split combined ITK transforms file
split_xfms = []
for xform_i in range(nxforms):
# Find start token to extract
startidx = tfdata.index('#Transform %d' % xform_i)
next_xform = base_xform + tfdata[startidx + 1:startidx + 4] + ['']
xfm_file = out_base(xform_i)
with open(xfm_file, 'w') as out_xfm:
out_xfm.write('\n'.join(next_xform))
split_xfms.append(xfm_file)
xfms_T.append(split_xfms)
# Transpose back (only Python 3)
return list(map(list, zip(*xfms_T))) | python | def _arrange_xfms(transforms, num_files, tmp_folder):
"""
Convenience method to arrange the list of transforms that should be applied
to each input file
"""
base_xform = ['#Insight Transform File V1.0', '#Transform 0']
# Initialize the transforms matrix
xfms_T = []
for i, tf_file in enumerate(transforms):
# If it is a deformation field, copy to the tfs_matrix directly
if guess_type(tf_file)[0] != 'text/plain':
xfms_T.append([tf_file] * num_files)
continue
with open(tf_file) as tf_fh:
tfdata = tf_fh.read().strip()
# If it is not an ITK transform file, copy to the tfs_matrix directly
if not tfdata.startswith('#Insight Transform File'):
xfms_T.append([tf_file] * num_files)
continue
# Count number of transforms in ITK transform file
nxforms = tfdata.count('#Transform')
# Remove first line
tfdata = tfdata.split('\n')[1:]
# If it is a ITK transform file with only 1 xform, copy to the tfs_matrix directly
if nxforms == 1:
xfms_T.append([tf_file] * num_files)
continue
if nxforms != num_files:
raise RuntimeError('Number of transforms (%d) found in the ITK file does not match'
' the number of input image files (%d).' % (nxforms, num_files))
# At this point splitting transforms will be necessary, generate a base name
out_base = fname_presuffix(tf_file, suffix='_pos-%03d_xfm-{:05d}' % i,
newpath=tmp_folder.name).format
# Split combined ITK transforms file
split_xfms = []
for xform_i in range(nxforms):
# Find start token to extract
startidx = tfdata.index('#Transform %d' % xform_i)
next_xform = base_xform + tfdata[startidx + 1:startidx + 4] + ['']
xfm_file = out_base(xform_i)
with open(xfm_file, 'w') as out_xfm:
out_xfm.write('\n'.join(next_xform))
split_xfms.append(xfm_file)
xfms_T.append(split_xfms)
# Transpose back (only Python 3)
return list(map(list, zip(*xfms_T))) | [
"def",
"_arrange_xfms",
"(",
"transforms",
",",
"num_files",
",",
"tmp_folder",
")",
":",
"base_xform",
"=",
"[",
"'#Insight Transform File V1.0'",
",",
"'#Transform 0'",
"]",
"# Initialize the transforms matrix",
"xfms_T",
"=",
"[",
"]",
"for",
"i",
",",
"tf_file",... | Convenience method to arrange the list of transforms that should be applied
to each input file | [
"Convenience",
"method",
"to",
"arrange",
"the",
"list",
"of",
"transforms",
"that",
"should",
"be",
"applied",
"to",
"each",
"input",
"file"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/itk.py#L276-L329 | train | 211,797 |
poldracklab/niworkflows | niworkflows/interfaces/surf.py | normalize_surfs | def normalize_surfs(in_file, transform_file, newpath=None):
""" Re-center GIFTI coordinates to fit align to native T1 space
For midthickness surfaces, add MidThickness metadata
Coordinate update based on:
https://github.com/Washington-University/workbench/blob/1b79e56/src/Algorithms/AlgorithmSurfaceApplyAffine.cxx#L73-L91
and
https://github.com/Washington-University/Pipelines/blob/ae69b9a/PostFreeSurfer/scripts/FreeSurfer2CaretConvertAndRegisterNonlinear.sh#L147
"""
img = nb.load(in_file)
transform = load_transform(transform_file)
pointset = img.get_arrays_from_intent('NIFTI_INTENT_POINTSET')[0]
coords = pointset.data.T
c_ras_keys = ('VolGeomC_R', 'VolGeomC_A', 'VolGeomC_S')
ras = np.array([[float(pointset.metadata[key])]
for key in c_ras_keys])
ones = np.ones((1, coords.shape[1]), dtype=coords.dtype)
# Apply C_RAS translation to coordinates, then transform
pointset.data = transform.dot(np.vstack((coords + ras, ones)))[:3].T.astype(coords.dtype)
secondary = nb.gifti.GiftiNVPairs('AnatomicalStructureSecondary', 'MidThickness')
geom_type = nb.gifti.GiftiNVPairs('GeometricType', 'Anatomical')
has_ass = has_geo = False
for nvpair in pointset.meta.data:
# Remove C_RAS translation from metadata to avoid double-dipping in FreeSurfer
if nvpair.name in c_ras_keys:
nvpair.value = '0.000000'
# Check for missing metadata
elif nvpair.name == secondary.name:
has_ass = True
elif nvpair.name == geom_type.name:
has_geo = True
fname = os.path.basename(in_file)
# Update metadata for MidThickness/graymid surfaces
if 'midthickness' in fname.lower() or 'graymid' in fname.lower():
if not has_ass:
pointset.meta.data.insert(1, secondary)
if not has_geo:
pointset.meta.data.insert(2, geom_type)
if newpath is not None:
newpath = os.getcwd()
out_file = os.path.join(newpath, fname)
img.to_filename(out_file)
return out_file | python | def normalize_surfs(in_file, transform_file, newpath=None):
""" Re-center GIFTI coordinates to fit align to native T1 space
For midthickness surfaces, add MidThickness metadata
Coordinate update based on:
https://github.com/Washington-University/workbench/blob/1b79e56/src/Algorithms/AlgorithmSurfaceApplyAffine.cxx#L73-L91
and
https://github.com/Washington-University/Pipelines/blob/ae69b9a/PostFreeSurfer/scripts/FreeSurfer2CaretConvertAndRegisterNonlinear.sh#L147
"""
img = nb.load(in_file)
transform = load_transform(transform_file)
pointset = img.get_arrays_from_intent('NIFTI_INTENT_POINTSET')[0]
coords = pointset.data.T
c_ras_keys = ('VolGeomC_R', 'VolGeomC_A', 'VolGeomC_S')
ras = np.array([[float(pointset.metadata[key])]
for key in c_ras_keys])
ones = np.ones((1, coords.shape[1]), dtype=coords.dtype)
# Apply C_RAS translation to coordinates, then transform
pointset.data = transform.dot(np.vstack((coords + ras, ones)))[:3].T.astype(coords.dtype)
secondary = nb.gifti.GiftiNVPairs('AnatomicalStructureSecondary', 'MidThickness')
geom_type = nb.gifti.GiftiNVPairs('GeometricType', 'Anatomical')
has_ass = has_geo = False
for nvpair in pointset.meta.data:
# Remove C_RAS translation from metadata to avoid double-dipping in FreeSurfer
if nvpair.name in c_ras_keys:
nvpair.value = '0.000000'
# Check for missing metadata
elif nvpair.name == secondary.name:
has_ass = True
elif nvpair.name == geom_type.name:
has_geo = True
fname = os.path.basename(in_file)
# Update metadata for MidThickness/graymid surfaces
if 'midthickness' in fname.lower() or 'graymid' in fname.lower():
if not has_ass:
pointset.meta.data.insert(1, secondary)
if not has_geo:
pointset.meta.data.insert(2, geom_type)
if newpath is not None:
newpath = os.getcwd()
out_file = os.path.join(newpath, fname)
img.to_filename(out_file)
return out_file | [
"def",
"normalize_surfs",
"(",
"in_file",
",",
"transform_file",
",",
"newpath",
"=",
"None",
")",
":",
"img",
"=",
"nb",
".",
"load",
"(",
"in_file",
")",
"transform",
"=",
"load_transform",
"(",
"transform_file",
")",
"pointset",
"=",
"img",
".",
"get_ar... | Re-center GIFTI coordinates to fit align to native T1 space
For midthickness surfaces, add MidThickness metadata
Coordinate update based on:
https://github.com/Washington-University/workbench/blob/1b79e56/src/Algorithms/AlgorithmSurfaceApplyAffine.cxx#L73-L91
and
https://github.com/Washington-University/Pipelines/blob/ae69b9a/PostFreeSurfer/scripts/FreeSurfer2CaretConvertAndRegisterNonlinear.sh#L147 | [
"Re",
"-",
"center",
"GIFTI",
"coordinates",
"to",
"fit",
"align",
"to",
"native",
"T1",
"space"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/surf.py#L409-L455 | train | 211,798 |
poldracklab/niworkflows | niworkflows/interfaces/surf.py | load_transform | def load_transform(fname):
"""Load affine transform from file
Parameters
----------
fname : str or None
Filename of an LTA or FSL-style MAT transform file.
If ``None``, return an identity transform
Returns
-------
affine : (4, 4) numpy.ndarray
"""
if fname is None:
return np.eye(4)
if fname.endswith('.mat'):
return np.loadtxt(fname)
elif fname.endswith('.lta'):
with open(fname, 'rb') as fobj:
for line in fobj:
if line.startswith(b'1 4 4'):
break
lines = fobj.readlines()[:4]
return np.genfromtxt(lines)
raise ValueError("Unknown transform type; pass FSL (.mat) or LTA (.lta)") | python | def load_transform(fname):
"""Load affine transform from file
Parameters
----------
fname : str or None
Filename of an LTA or FSL-style MAT transform file.
If ``None``, return an identity transform
Returns
-------
affine : (4, 4) numpy.ndarray
"""
if fname is None:
return np.eye(4)
if fname.endswith('.mat'):
return np.loadtxt(fname)
elif fname.endswith('.lta'):
with open(fname, 'rb') as fobj:
for line in fobj:
if line.startswith(b'1 4 4'):
break
lines = fobj.readlines()[:4]
return np.genfromtxt(lines)
raise ValueError("Unknown transform type; pass FSL (.mat) or LTA (.lta)") | [
"def",
"load_transform",
"(",
"fname",
")",
":",
"if",
"fname",
"is",
"None",
":",
"return",
"np",
".",
"eye",
"(",
"4",
")",
"if",
"fname",
".",
"endswith",
"(",
"'.mat'",
")",
":",
"return",
"np",
".",
"loadtxt",
"(",
"fname",
")",
"elif",
"fname... | Load affine transform from file
Parameters
----------
fname : str or None
Filename of an LTA or FSL-style MAT transform file.
If ``None``, return an identity transform
Returns
-------
affine : (4, 4) numpy.ndarray | [
"Load",
"affine",
"transform",
"from",
"file"
] | 254f4b4fcc5e6ecb29d2f4602a30786b913ecce5 | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/surf.py#L458-L484 | train | 211,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.