body
stringlengths 26
98.2k
| body_hash
int64 -9,222,864,604,528,158,000
9,221,803,474B
| docstring
stringlengths 1
16.8k
| path
stringlengths 5
230
| name
stringlengths 1
96
| repository_name
stringlengths 7
89
| lang
stringclasses 1
value | body_without_docstring
stringlengths 20
98.2k
|
---|---|---|---|---|---|---|---|
def get(iterable: Iterable[T], **attrs: Any) -> Optional[T]:
"A helper that returns the first element in the iterable that meets\n all the traits passed in ``attrs``. This is an alternative for\n :func:`~discord.utils.find`.\n\n When multiple attributes are specified, they are checked using\n logical AND, not logical OR. Meaning they have to meet every\n attribute passed in and not one of them.\n\n To have a nested attribute search (i.e. search by ``x.y``) then\n pass in ``x__y`` as the keyword argument.\n\n If nothing is found that matches the attributes passed, then\n ``None`` is returned.\n\n Examples\n ---------\n\n Basic usage:\n\n .. code-block:: python3\n\n member = discord.utils.get(message.guild.members, name='Foo')\n\n Multiple attribute matching:\n\n .. code-block:: python3\n\n channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)\n\n Nested attribute matching:\n\n .. code-block:: python3\n\n channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')\n\n Parameters\n -----------\n iterable\n An iterable to search through.\n \\*\\*attrs\n Keyword arguments that denote attributes to search with.\n "
_all = all
attrget = attrgetter
if (len(attrs) == 1):
(k, v) = attrs.popitem()
pred = attrget(k.replace('__', '.'))
for elem in iterable:
if (pred(elem) == v):
return elem
return None
converted = [(attrget(attr.replace('__', '.')), value) for (attr, value) in attrs.items()]
for elem in iterable:
if _all(((pred(elem) == value) for (pred, value) in converted)):
return elem
return None | 277,057,969,456,913,730 | A helper that returns the first element in the iterable that meets
all the traits passed in ``attrs``. This is an alternative for
:func:`~discord.utils.find`.
When multiple attributes are specified, they are checked using
logical AND, not logical OR. Meaning they have to meet every
attribute passed in and not one of them.
To have a nested attribute search (i.e. search by ``x.y``) then
pass in ``x__y`` as the keyword argument.
If nothing is found that matches the attributes passed, then
``None`` is returned.
Examples
---------
Basic usage:
.. code-block:: python3
member = discord.utils.get(message.guild.members, name='Foo')
Multiple attribute matching:
.. code-block:: python3
channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)
Nested attribute matching:
.. code-block:: python3
channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
Parameters
-----------
iterable
An iterable to search through.
\*\*attrs
Keyword arguments that denote attributes to search with. | discord/utils.py | get | Astrea49/enhanced-discord.py | python | def get(iterable: Iterable[T], **attrs: Any) -> Optional[T]:
"A helper that returns the first element in the iterable that meets\n all the traits passed in ``attrs``. This is an alternative for\n :func:`~discord.utils.find`.\n\n When multiple attributes are specified, they are checked using\n logical AND, not logical OR. Meaning they have to meet every\n attribute passed in and not one of them.\n\n To have a nested attribute search (i.e. search by ``x.y``) then\n pass in ``x__y`` as the keyword argument.\n\n If nothing is found that matches the attributes passed, then\n ``None`` is returned.\n\n Examples\n ---------\n\n Basic usage:\n\n .. code-block:: python3\n\n member = discord.utils.get(message.guild.members, name='Foo')\n\n Multiple attribute matching:\n\n .. code-block:: python3\n\n channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)\n\n Nested attribute matching:\n\n .. code-block:: python3\n\n channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')\n\n Parameters\n -----------\n iterable\n An iterable to search through.\n \\*\\*attrs\n Keyword arguments that denote attributes to search with.\n "
_all = all
attrget = attrgetter
if (len(attrs) == 1):
(k, v) = attrs.popitem()
pred = attrget(k.replace('__', '.'))
for elem in iterable:
if (pred(elem) == v):
return elem
return None
converted = [(attrget(attr.replace('__', '.')), value) for (attr, value) in attrs.items()]
for elem in iterable:
if _all(((pred(elem) == value) for (pred, value) in converted)):
return elem
return None |
async def sleep_until(when: datetime.datetime, result: Optional[T]=None) -> Optional[T]:
'|coro|\n\n Sleep until a specified time.\n\n If the time supplied is in the past this function will yield instantly.\n\n .. versionadded:: 1.3\n\n Parameters\n -----------\n when: :class:`datetime.datetime`\n The timestamp in which to sleep until. If the datetime is naive then\n it is assumed to be local time.\n result: Any\n If provided is returned to the caller when the coroutine completes.\n '
delta = compute_timedelta(when)
return (await asyncio.sleep(delta, result)) | 4,609,430,239,901,095,400 | |coro|
Sleep until a specified time.
If the time supplied is in the past this function will yield instantly.
.. versionadded:: 1.3
Parameters
-----------
when: :class:`datetime.datetime`
The timestamp in which to sleep until. If the datetime is naive then
it is assumed to be local time.
result: Any
If provided is returned to the caller when the coroutine completes. | discord/utils.py | sleep_until | Astrea49/enhanced-discord.py | python | async def sleep_until(when: datetime.datetime, result: Optional[T]=None) -> Optional[T]:
'|coro|\n\n Sleep until a specified time.\n\n If the time supplied is in the past this function will yield instantly.\n\n .. versionadded:: 1.3\n\n Parameters\n -----------\n when: :class:`datetime.datetime`\n The timestamp in which to sleep until. If the datetime is naive then\n it is assumed to be local time.\n result: Any\n If provided is returned to the caller when the coroutine completes.\n '
delta = compute_timedelta(when)
return (await asyncio.sleep(delta, result)) |
def utcnow() -> datetime.datetime:
'A helper function to return an aware UTC datetime representing the current time.\n\n This should be preferred to :meth:`datetime.datetime.utcnow` since it is an aware\n datetime, compared to the naive datetime in the standard library.\n\n .. versionadded:: 2.0\n\n Returns\n --------\n :class:`datetime.datetime`\n The current aware datetime in UTC.\n '
return datetime.datetime.now(datetime.timezone.utc) | -7,392,825,032,410,449,000 | A helper function to return an aware UTC datetime representing the current time.
This should be preferred to :meth:`datetime.datetime.utcnow` since it is an aware
datetime, compared to the naive datetime in the standard library.
.. versionadded:: 2.0
Returns
--------
:class:`datetime.datetime`
The current aware datetime in UTC. | discord/utils.py | utcnow | Astrea49/enhanced-discord.py | python | def utcnow() -> datetime.datetime:
'A helper function to return an aware UTC datetime representing the current time.\n\n This should be preferred to :meth:`datetime.datetime.utcnow` since it is an aware\n datetime, compared to the naive datetime in the standard library.\n\n .. versionadded:: 2.0\n\n Returns\n --------\n :class:`datetime.datetime`\n The current aware datetime in UTC.\n '
return datetime.datetime.now(datetime.timezone.utc) |
def valid_icon_size(size: int) -> bool:
'Icons must be power of 2 within [16, 4096].'
return ((not (size & (size - 1))) and (4096 >= size >= 16)) | 8,354,134,979,157,664,000 | Icons must be power of 2 within [16, 4096]. | discord/utils.py | valid_icon_size | Astrea49/enhanced-discord.py | python | def valid_icon_size(size: int) -> bool:
return ((not (size & (size - 1))) and (4096 >= size >= 16)) |
def _string_width(string: str, *, _IS_ASCII=_IS_ASCII) -> int:
"Returns string's width."
match = _IS_ASCII.match(string)
if match:
return match.endpos
UNICODE_WIDE_CHAR_TYPE = 'WFA'
func = unicodedata.east_asian_width
return sum(((2 if (func(char) in UNICODE_WIDE_CHAR_TYPE) else 1) for char in string)) | 8,570,024,438,440,873,000 | Returns string's width. | discord/utils.py | _string_width | Astrea49/enhanced-discord.py | python | def _string_width(string: str, *, _IS_ASCII=_IS_ASCII) -> int:
match = _IS_ASCII.match(string)
if match:
return match.endpos
UNICODE_WIDE_CHAR_TYPE = 'WFA'
func = unicodedata.east_asian_width
return sum(((2 if (func(char) in UNICODE_WIDE_CHAR_TYPE) else 1) for char in string)) |
def resolve_invite(invite: Union[(Invite, str)]) -> str:
'\n Resolves an invite from a :class:`~discord.Invite`, URL or code.\n\n Parameters\n -----------\n invite: Union[:class:`~discord.Invite`, :class:`str`]\n The invite.\n\n Returns\n --------\n :class:`str`\n The invite code.\n '
from .invite import Invite
if isinstance(invite, Invite):
return invite.code
else:
rx = '(?:https?\\:\\/\\/)?discord(?:\\.gg|(?:app)?\\.com\\/invite)\\/(.+)'
m = re.match(rx, invite)
if m:
return m.group(1)
return invite | -6,593,978,646,863,497,000 | Resolves an invite from a :class:`~discord.Invite`, URL or code.
Parameters
-----------
invite: Union[:class:`~discord.Invite`, :class:`str`]
The invite.
Returns
--------
:class:`str`
The invite code. | discord/utils.py | resolve_invite | Astrea49/enhanced-discord.py | python | def resolve_invite(invite: Union[(Invite, str)]) -> str:
'\n Resolves an invite from a :class:`~discord.Invite`, URL or code.\n\n Parameters\n -----------\n invite: Union[:class:`~discord.Invite`, :class:`str`]\n The invite.\n\n Returns\n --------\n :class:`str`\n The invite code.\n '
from .invite import Invite
if isinstance(invite, Invite):
return invite.code
else:
rx = '(?:https?\\:\\/\\/)?discord(?:\\.gg|(?:app)?\\.com\\/invite)\\/(.+)'
m = re.match(rx, invite)
if m:
return m.group(1)
return invite |
def resolve_template(code: Union[(Template, str)]) -> str:
'\n Resolves a template code from a :class:`~discord.Template`, URL or code.\n\n .. versionadded:: 1.4\n\n Parameters\n -----------\n code: Union[:class:`~discord.Template`, :class:`str`]\n The code.\n\n Returns\n --------\n :class:`str`\n The template code.\n '
from .template import Template
if isinstance(code, Template):
return code.code
else:
rx = '(?:https?\\:\\/\\/)?discord(?:\\.new|(?:app)?\\.com\\/template)\\/(.+)'
m = re.match(rx, code)
if m:
return m.group(1)
return code | 7,340,644,970,982,626,000 | Resolves a template code from a :class:`~discord.Template`, URL or code.
.. versionadded:: 1.4
Parameters
-----------
code: Union[:class:`~discord.Template`, :class:`str`]
The code.
Returns
--------
:class:`str`
The template code. | discord/utils.py | resolve_template | Astrea49/enhanced-discord.py | python | def resolve_template(code: Union[(Template, str)]) -> str:
'\n Resolves a template code from a :class:`~discord.Template`, URL or code.\n\n .. versionadded:: 1.4\n\n Parameters\n -----------\n code: Union[:class:`~discord.Template`, :class:`str`]\n The code.\n\n Returns\n --------\n :class:`str`\n The template code.\n '
from .template import Template
if isinstance(code, Template):
return code.code
else:
rx = '(?:https?\\:\\/\\/)?discord(?:\\.new|(?:app)?\\.com\\/template)\\/(.+)'
m = re.match(rx, code)
if m:
return m.group(1)
return code |
def remove_markdown(text: str, *, ignore_links: bool=True) -> str:
'A helper function that removes markdown characters.\n\n .. versionadded:: 1.7\n\n .. note::\n This function is not markdown aware and may remove meaning from the original text. For example,\n if the input contains ``10 * 5`` then it will be converted into ``10 5``.\n\n Parameters\n -----------\n text: :class:`str`\n The text to remove markdown from.\n ignore_links: :class:`bool`\n Whether to leave links alone when removing markdown. For example,\n if a URL in the text contains characters such as ``_`` then it will\n be left alone. Defaults to ``True``.\n\n Returns\n --------\n :class:`str`\n The text with the markdown special characters removed.\n '
def replacement(match):
groupdict = match.groupdict()
return groupdict.get('url', '')
regex = _MARKDOWN_STOCK_REGEX
if ignore_links:
regex = f'(?:{_URL_REGEX}|{regex})'
return re.sub(regex, replacement, text, 0, re.MULTILINE) | -8,926,758,432,552,786,000 | A helper function that removes markdown characters.
.. versionadded:: 1.7
.. note::
This function is not markdown aware and may remove meaning from the original text. For example,
if the input contains ``10 * 5`` then it will be converted into ``10 5``.
Parameters
-----------
text: :class:`str`
The text to remove markdown from.
ignore_links: :class:`bool`
Whether to leave links alone when removing markdown. For example,
if a URL in the text contains characters such as ``_`` then it will
be left alone. Defaults to ``True``.
Returns
--------
:class:`str`
The text with the markdown special characters removed. | discord/utils.py | remove_markdown | Astrea49/enhanced-discord.py | python | def remove_markdown(text: str, *, ignore_links: bool=True) -> str:
'A helper function that removes markdown characters.\n\n .. versionadded:: 1.7\n\n .. note::\n This function is not markdown aware and may remove meaning from the original text. For example,\n if the input contains ``10 * 5`` then it will be converted into ``10 5``.\n\n Parameters\n -----------\n text: :class:`str`\n The text to remove markdown from.\n ignore_links: :class:`bool`\n Whether to leave links alone when removing markdown. For example,\n if a URL in the text contains characters such as ``_`` then it will\n be left alone. Defaults to ``True``.\n\n Returns\n --------\n :class:`str`\n The text with the markdown special characters removed.\n '
def replacement(match):
groupdict = match.groupdict()
return groupdict.get('url', )
regex = _MARKDOWN_STOCK_REGEX
if ignore_links:
regex = f'(?:{_URL_REGEX}|{regex})'
return re.sub(regex, replacement, text, 0, re.MULTILINE) |
def escape_markdown(text: str, *, as_needed: bool=False, ignore_links: bool=True) -> str:
"A helper function that escapes Discord's markdown.\n\n Parameters\n -----------\n text: :class:`str`\n The text to escape markdown from.\n as_needed: :class:`bool`\n Whether to escape the markdown characters as needed. This\n means that it does not escape extraneous characters if it's\n not necessary, e.g. ``**hello**`` is escaped into ``\\*\\*hello**``\n instead of ``\\*\\*hello\\*\\*``. Note however that this can open\n you up to some clever syntax abuse. Defaults to ``False``.\n ignore_links: :class:`bool`\n Whether to leave links alone when escaping markdown. For example,\n if a URL in the text contains characters such as ``_`` then it will\n be left alone. This option is not supported with ``as_needed``.\n Defaults to ``True``.\n\n Returns\n --------\n :class:`str`\n The text with the markdown special characters escaped with a slash.\n "
if (not as_needed):
def replacement(match):
groupdict = match.groupdict()
is_url = groupdict.get('url')
if is_url:
return is_url
return ('\\' + groupdict['markdown'])
regex = _MARKDOWN_STOCK_REGEX
if ignore_links:
regex = f'(?:{_URL_REGEX}|{regex})'
return re.sub(regex, replacement, text, 0, re.MULTILINE)
else:
text = re.sub('\\\\', '\\\\\\\\', text)
return _MARKDOWN_ESCAPE_REGEX.sub('\\\\\\1', text) | 7,610,843,465,327,333,000 | A helper function that escapes Discord's markdown.
Parameters
-----------
text: :class:`str`
The text to escape markdown from.
as_needed: :class:`bool`
Whether to escape the markdown characters as needed. This
means that it does not escape extraneous characters if it's
not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**``
instead of ``\*\*hello\*\*``. Note however that this can open
you up to some clever syntax abuse. Defaults to ``False``.
ignore_links: :class:`bool`
Whether to leave links alone when escaping markdown. For example,
if a URL in the text contains characters such as ``_`` then it will
be left alone. This option is not supported with ``as_needed``.
Defaults to ``True``.
Returns
--------
:class:`str`
The text with the markdown special characters escaped with a slash. | discord/utils.py | escape_markdown | Astrea49/enhanced-discord.py | python | def escape_markdown(text: str, *, as_needed: bool=False, ignore_links: bool=True) -> str:
"A helper function that escapes Discord's markdown.\n\n Parameters\n -----------\n text: :class:`str`\n The text to escape markdown from.\n as_needed: :class:`bool`\n Whether to escape the markdown characters as needed. This\n means that it does not escape extraneous characters if it's\n not necessary, e.g. ``**hello**`` is escaped into ``\\*\\*hello**``\n instead of ``\\*\\*hello\\*\\*``. Note however that this can open\n you up to some clever syntax abuse. Defaults to ``False``.\n ignore_links: :class:`bool`\n Whether to leave links alone when escaping markdown. For example,\n if a URL in the text contains characters such as ``_`` then it will\n be left alone. This option is not supported with ``as_needed``.\n Defaults to ``True``.\n\n Returns\n --------\n :class:`str`\n The text with the markdown special characters escaped with a slash.\n "
if (not as_needed):
def replacement(match):
groupdict = match.groupdict()
is_url = groupdict.get('url')
if is_url:
return is_url
return ('\\' + groupdict['markdown'])
regex = _MARKDOWN_STOCK_REGEX
if ignore_links:
regex = f'(?:{_URL_REGEX}|{regex})'
return re.sub(regex, replacement, text, 0, re.MULTILINE)
else:
text = re.sub('\\\\', '\\\\\\\\', text)
return _MARKDOWN_ESCAPE_REGEX.sub('\\\\\\1', text) |
def escape_mentions(text: str) -> str:
'A helper function that escapes everyone, here, role, and user mentions.\n\n .. note::\n\n This does not include channel mentions.\n\n .. note::\n\n For more granular control over what mentions should be escaped\n within messages, refer to the :class:`~discord.AllowedMentions`\n class.\n\n Parameters\n -----------\n text: :class:`str`\n The text to escape mentions from.\n\n Returns\n --------\n :class:`str`\n The text with the mentions removed.\n '
return re.sub('@(everyone|here|[!&]?[0-9]{17,20})', '@\u200b\\1', text) | 7,038,716,603,072,212,000 | A helper function that escapes everyone, here, role, and user mentions.
.. note::
This does not include channel mentions.
.. note::
For more granular control over what mentions should be escaped
within messages, refer to the :class:`~discord.AllowedMentions`
class.
Parameters
-----------
text: :class:`str`
The text to escape mentions from.
Returns
--------
:class:`str`
The text with the mentions removed. | discord/utils.py | escape_mentions | Astrea49/enhanced-discord.py | python | def escape_mentions(text: str) -> str:
'A helper function that escapes everyone, here, role, and user mentions.\n\n .. note::\n\n This does not include channel mentions.\n\n .. note::\n\n For more granular control over what mentions should be escaped\n within messages, refer to the :class:`~discord.AllowedMentions`\n class.\n\n Parameters\n -----------\n text: :class:`str`\n The text to escape mentions from.\n\n Returns\n --------\n :class:`str`\n The text with the mentions removed.\n '
return re.sub('@(everyone|here|[!&]?[0-9]{17,20})', '@\u200b\\1', text) |
def as_chunks(iterator: _Iter[T], max_size: int) -> _Iter[List[T]]:
'A helper function that collects an iterator into chunks of a given size.\n\n .. versionadded:: 2.0\n\n Parameters\n ----------\n iterator: Union[:class:`collections.abc.Iterator`, :class:`collections.abc.AsyncIterator`]\n The iterator to chunk, can be sync or async.\n max_size: :class:`int`\n The maximum chunk size.\n\n\n .. warning::\n\n The last chunk collected may not be as large as ``max_size``.\n\n Returns\n --------\n Union[:class:`Iterator`, :class:`AsyncIterator`]\n A new iterator which yields chunks of a given size.\n '
if (max_size <= 0):
raise ValueError('Chunk sizes must be greater than 0.')
if isinstance(iterator, AsyncIterator):
return _achunk(iterator, max_size)
return _chunk(iterator, max_size) | 6,781,882,996,010,155,000 | A helper function that collects an iterator into chunks of a given size.
.. versionadded:: 2.0
Parameters
----------
iterator: Union[:class:`collections.abc.Iterator`, :class:`collections.abc.AsyncIterator`]
The iterator to chunk, can be sync or async.
max_size: :class:`int`
The maximum chunk size.
.. warning::
The last chunk collected may not be as large as ``max_size``.
Returns
--------
Union[:class:`Iterator`, :class:`AsyncIterator`]
A new iterator which yields chunks of a given size. | discord/utils.py | as_chunks | Astrea49/enhanced-discord.py | python | def as_chunks(iterator: _Iter[T], max_size: int) -> _Iter[List[T]]:
'A helper function that collects an iterator into chunks of a given size.\n\n .. versionadded:: 2.0\n\n Parameters\n ----------\n iterator: Union[:class:`collections.abc.Iterator`, :class:`collections.abc.AsyncIterator`]\n The iterator to chunk, can be sync or async.\n max_size: :class:`int`\n The maximum chunk size.\n\n\n .. warning::\n\n The last chunk collected may not be as large as ``max_size``.\n\n Returns\n --------\n Union[:class:`Iterator`, :class:`AsyncIterator`]\n A new iterator which yields chunks of a given size.\n '
if (max_size <= 0):
raise ValueError('Chunk sizes must be greater than 0.')
if isinstance(iterator, AsyncIterator):
return _achunk(iterator, max_size)
return _chunk(iterator, max_size) |
def format_dt(dt: datetime.datetime, /, style: Optional[TimestampStyle]=None) -> str:
"A helper function to format a :class:`datetime.datetime` for presentation within Discord.\n\n This allows for a locale-independent way of presenting data using Discord specific Markdown.\n\n +-------------+----------------------------+-----------------+\n | Style | Example Output | Description |\n +=============+============================+=================+\n | t | 22:57 | Short Time |\n +-------------+----------------------------+-----------------+\n | T | 22:57:58 | Long Time |\n +-------------+----------------------------+-----------------+\n | d | 17/05/2016 | Short Date |\n +-------------+----------------------------+-----------------+\n | D | 17 May 2016 | Long Date |\n +-------------+----------------------------+-----------------+\n | f (default) | 17 May 2016 22:57 | Short Date Time |\n +-------------+----------------------------+-----------------+\n | F | Tuesday, 17 May 2016 22:57 | Long Date Time |\n +-------------+----------------------------+-----------------+\n | R | 5 years ago | Relative Time |\n +-------------+----------------------------+-----------------+\n\n Note that the exact output depends on the user's locale setting in the client. The example output\n presented is using the ``en-GB`` locale.\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n dt: :class:`datetime.datetime`\n The datetime to format.\n style: :class:`str`\n The style to format the datetime with.\n\n Returns\n --------\n :class:`str`\n The formatted string.\n "
if (style is None):
return f'<t:{int(dt.timestamp())}>'
return f'<t:{int(dt.timestamp())}:{style}>' | 4,399,302,417,089,593,300 | A helper function to format a :class:`datetime.datetime` for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown.
+-------------+----------------------------+-----------------+
| Style | Example Output | Description |
+=============+============================+=================+
| t | 22:57 | Short Time |
+-------------+----------------------------+-----------------+
| T | 22:57:58 | Long Time |
+-------------+----------------------------+-----------------+
| d | 17/05/2016 | Short Date |
+-------------+----------------------------+-----------------+
| D | 17 May 2016 | Long Date |
+-------------+----------------------------+-----------------+
| f (default) | 17 May 2016 22:57 | Short Date Time |
+-------------+----------------------------+-----------------+
| F | Tuesday, 17 May 2016 22:57 | Long Date Time |
+-------------+----------------------------+-----------------+
| R | 5 years ago | Relative Time |
+-------------+----------------------------+-----------------+
Note that the exact output depends on the user's locale setting in the client. The example output
presented is using the ``en-GB`` locale.
.. versionadded:: 2.0
Parameters
-----------
dt: :class:`datetime.datetime`
The datetime to format.
style: :class:`str`
The style to format the datetime with.
Returns
--------
:class:`str`
The formatted string. | discord/utils.py | format_dt | Astrea49/enhanced-discord.py | python | def format_dt(dt: datetime.datetime, /, style: Optional[TimestampStyle]=None) -> str:
"A helper function to format a :class:`datetime.datetime` for presentation within Discord.\n\n This allows for a locale-independent way of presenting data using Discord specific Markdown.\n\n +-------------+----------------------------+-----------------+\n | Style | Example Output | Description |\n +=============+============================+=================+\n | t | 22:57 | Short Time |\n +-------------+----------------------------+-----------------+\n | T | 22:57:58 | Long Time |\n +-------------+----------------------------+-----------------+\n | d | 17/05/2016 | Short Date |\n +-------------+----------------------------+-----------------+\n | D | 17 May 2016 | Long Date |\n +-------------+----------------------------+-----------------+\n | f (default) | 17 May 2016 22:57 | Short Date Time |\n +-------------+----------------------------+-----------------+\n | F | Tuesday, 17 May 2016 22:57 | Long Date Time |\n +-------------+----------------------------+-----------------+\n | R | 5 years ago | Relative Time |\n +-------------+----------------------------+-----------------+\n\n Note that the exact output depends on the user's locale setting in the client. The example output\n presented is using the ``en-GB`` locale.\n\n .. versionadded:: 2.0\n\n Parameters\n -----------\n dt: :class:`datetime.datetime`\n The datetime to format.\n style: :class:`str`\n The style to format the datetime with.\n\n Returns\n --------\n :class:`str`\n The formatted string.\n "
if (style is None):
return f'<t:{int(dt.timestamp())}>'
return f'<t:{int(dt.timestamp())}:{style}>' |
def __init__(self, rule_file_path=None, rule_ref=None, trigger_instance_file_path=None, trigger_instance_id=None):
'\n :param rule_file_path: Path to the file containing rule definition.\n :type rule_file_path: ``str``\n\n :param trigger_instance_file_path: Path to the file containg trigger instance definition.\n :type trigger_instance_file_path: ``str``\n '
self._rule_file_path = rule_file_path
self._rule_ref = rule_ref
self._trigger_instance_file_path = trigger_instance_file_path
self._trigger_instance_id = trigger_instance_id
self._meta_loader = MetaLoader() | 5,441,461,311,905,855,000 | :param rule_file_path: Path to the file containing rule definition.
:type rule_file_path: ``str``
:param trigger_instance_file_path: Path to the file containg trigger instance definition.
:type trigger_instance_file_path: ``str`` | st2reactor/st2reactor/rules/tester.py | __init__ | Horizon-95/st2 | python | def __init__(self, rule_file_path=None, rule_ref=None, trigger_instance_file_path=None, trigger_instance_id=None):
'\n :param rule_file_path: Path to the file containing rule definition.\n :type rule_file_path: ``str``\n\n :param trigger_instance_file_path: Path to the file containg trigger instance definition.\n :type trigger_instance_file_path: ``str``\n '
self._rule_file_path = rule_file_path
self._rule_ref = rule_ref
self._trigger_instance_file_path = trigger_instance_file_path
self._trigger_instance_id = trigger_instance_id
self._meta_loader = MetaLoader() |
def evaluate(self):
'\n Evaluate trigger instance against the rule.\n\n :return: ``True`` if the rule matches, ``False`` otherwise.\n :rtype: ``boolean``\n '
rule_db = self._get_rule_db()
(trigger_instance_db, trigger_db) = self._get_trigger_instance_db()
if (rule_db.trigger != trigger_db.ref):
LOG.info('rule.trigger "%s" and trigger.ref "%s" do not match.', rule_db.trigger, trigger_db.ref)
return False
matcher = RulesMatcher(trigger_instance=trigger_instance_db, trigger=trigger_db, rules=[rule_db], extra_info=True)
matching_rules = matcher.get_matching_rules()
if (len(matching_rules) < 1):
return False
enforcer = RuleEnforcer(trigger_instance=trigger_instance_db, rule=rule_db)
runner_type_db = mock.Mock()
runner_type_db.runner_parameters = {}
action_db = mock.Mock()
action_db.parameters = {}
params = rule_db.action.parameters
(context, additional_contexts) = enforcer.get_action_execution_context(action_db=action_db, trace_context=None)
try:
params = enforcer.get_resolved_parameters(action_db=action_db, runnertype_db=runner_type_db, params=params, context=context, additional_contexts=additional_contexts)
LOG.info('Action parameters resolved to:')
for param in six.iteritems(params):
LOG.info('\t%s: %s', param[0], param[1])
return True
except (UndefinedError, ValueError) as e:
LOG.error('Failed to resolve parameters\n\tOriginal error : %s', six.text_type(e))
return False
except:
LOG.exception('Failed to resolve parameters.')
return False | 6,243,851,178,808,306,000 | Evaluate trigger instance against the rule.
:return: ``True`` if the rule matches, ``False`` otherwise.
:rtype: ``boolean`` | st2reactor/st2reactor/rules/tester.py | evaluate | Horizon-95/st2 | python | def evaluate(self):
'\n Evaluate trigger instance against the rule.\n\n :return: ``True`` if the rule matches, ``False`` otherwise.\n :rtype: ``boolean``\n '
rule_db = self._get_rule_db()
(trigger_instance_db, trigger_db) = self._get_trigger_instance_db()
if (rule_db.trigger != trigger_db.ref):
LOG.info('rule.trigger "%s" and trigger.ref "%s" do not match.', rule_db.trigger, trigger_db.ref)
return False
matcher = RulesMatcher(trigger_instance=trigger_instance_db, trigger=trigger_db, rules=[rule_db], extra_info=True)
matching_rules = matcher.get_matching_rules()
if (len(matching_rules) < 1):
return False
enforcer = RuleEnforcer(trigger_instance=trigger_instance_db, rule=rule_db)
runner_type_db = mock.Mock()
runner_type_db.runner_parameters = {}
action_db = mock.Mock()
action_db.parameters = {}
params = rule_db.action.parameters
(context, additional_contexts) = enforcer.get_action_execution_context(action_db=action_db, trace_context=None)
try:
params = enforcer.get_resolved_parameters(action_db=action_db, runnertype_db=runner_type_db, params=params, context=context, additional_contexts=additional_contexts)
LOG.info('Action parameters resolved to:')
for param in six.iteritems(params):
LOG.info('\t%s: %s', param[0], param[1])
return True
except (UndefinedError, ValueError) as e:
LOG.error('Failed to resolve parameters\n\tOriginal error : %s', six.text_type(e))
return False
except:
LOG.exception('Failed to resolve parameters.')
return False |
def setup_platform(hass, config, add_entities, discovery_info=None):
'Set up the Dyson 360 Eye robot vacuum platform.'
from libpurecoollink.dyson_360_eye import Dyson360Eye
_LOGGER.debug('Creating new Dyson 360 Eye robot vacuum')
if (DYSON_360_EYE_DEVICES not in hass.data):
hass.data[DYSON_360_EYE_DEVICES] = []
for device in [d for d in hass.data[DYSON_DEVICES] if isinstance(d, Dyson360Eye)]:
dyson_entity = Dyson360EyeDevice(device)
hass.data[DYSON_360_EYE_DEVICES].append(dyson_entity)
add_entities(hass.data[DYSON_360_EYE_DEVICES])
return True | 1,680,145,101,689,338,000 | Set up the Dyson 360 Eye robot vacuum platform. | homeassistant/components/dyson/vacuum.py | setup_platform | FlorianLudwig/home-assistant | python | def setup_platform(hass, config, add_entities, discovery_info=None):
from libpurecoollink.dyson_360_eye import Dyson360Eye
_LOGGER.debug('Creating new Dyson 360 Eye robot vacuum')
if (DYSON_360_EYE_DEVICES not in hass.data):
hass.data[DYSON_360_EYE_DEVICES] = []
for device in [d for d in hass.data[DYSON_DEVICES] if isinstance(d, Dyson360Eye)]:
dyson_entity = Dyson360EyeDevice(device)
hass.data[DYSON_360_EYE_DEVICES].append(dyson_entity)
add_entities(hass.data[DYSON_360_EYE_DEVICES])
return True |
def __init__(self, device):
'Dyson 360 Eye robot vacuum device.'
_LOGGER.debug('Creating device %s', device.name)
self._device = device | -7,126,531,234,313,695,000 | Dyson 360 Eye robot vacuum device. | homeassistant/components/dyson/vacuum.py | __init__ | FlorianLudwig/home-assistant | python | def __init__(self, device):
_LOGGER.debug('Creating device %s', device.name)
self._device = device |
async def async_added_to_hass(self):
'Call when entity is added to hass.'
self.hass.async_add_job(self._device.add_message_listener, self.on_message) | -7,591,945,232,566,411,000 | Call when entity is added to hass. | homeassistant/components/dyson/vacuum.py | async_added_to_hass | FlorianLudwig/home-assistant | python | async def async_added_to_hass(self):
self.hass.async_add_job(self._device.add_message_listener, self.on_message) |
def on_message(self, message):
'Handle a new messages that was received from the vacuum.'
_LOGGER.debug('Message received for %s device: %s', self.name, message)
self.schedule_update_ha_state() | -953,463,388,233,144,800 | Handle a new messages that was received from the vacuum. | homeassistant/components/dyson/vacuum.py | on_message | FlorianLudwig/home-assistant | python | def on_message(self, message):
_LOGGER.debug('Message received for %s device: %s', self.name, message)
self.schedule_update_ha_state() |
@property
def should_poll(self) -> bool:
'Return True if entity has to be polled for state.\n\n False if entity pushes its state to HA.\n '
return False | 9,137,668,176,441,036,000 | Return True if entity has to be polled for state.
False if entity pushes its state to HA. | homeassistant/components/dyson/vacuum.py | should_poll | FlorianLudwig/home-assistant | python | @property
def should_poll(self) -> bool:
'Return True if entity has to be polled for state.\n\n False if entity pushes its state to HA.\n '
return False |
@property
def name(self):
'Return the name of the device.'
return self._device.name | 2,513,907,752,780,827,000 | Return the name of the device. | homeassistant/components/dyson/vacuum.py | name | FlorianLudwig/home-assistant | python | @property
def name(self):
return self._device.name |
@property
def status(self):
'Return the status of the vacuum cleaner.'
from libpurecoollink.const import Dyson360EyeMode
dyson_labels = {Dyson360EyeMode.INACTIVE_CHARGING: 'Stopped - Charging', Dyson360EyeMode.INACTIVE_CHARGED: 'Stopped - Charged', Dyson360EyeMode.FULL_CLEAN_PAUSED: 'Paused', Dyson360EyeMode.FULL_CLEAN_RUNNING: 'Cleaning', Dyson360EyeMode.FULL_CLEAN_ABORTED: 'Returning home', Dyson360EyeMode.FULL_CLEAN_INITIATED: 'Start cleaning', Dyson360EyeMode.FAULT_USER_RECOVERABLE: 'Error - device blocked', Dyson360EyeMode.FAULT_REPLACE_ON_DOCK: 'Error - Replace device on dock', Dyson360EyeMode.FULL_CLEAN_FINISHED: 'Finished', Dyson360EyeMode.FULL_CLEAN_NEEDS_CHARGE: 'Need charging'}
return dyson_labels.get(self._device.state.state, self._device.state.state) | -6,246,395,718,633,716,000 | Return the status of the vacuum cleaner. | homeassistant/components/dyson/vacuum.py | status | FlorianLudwig/home-assistant | python | @property
def status(self):
from libpurecoollink.const import Dyson360EyeMode
dyson_labels = {Dyson360EyeMode.INACTIVE_CHARGING: 'Stopped - Charging', Dyson360EyeMode.INACTIVE_CHARGED: 'Stopped - Charged', Dyson360EyeMode.FULL_CLEAN_PAUSED: 'Paused', Dyson360EyeMode.FULL_CLEAN_RUNNING: 'Cleaning', Dyson360EyeMode.FULL_CLEAN_ABORTED: 'Returning home', Dyson360EyeMode.FULL_CLEAN_INITIATED: 'Start cleaning', Dyson360EyeMode.FAULT_USER_RECOVERABLE: 'Error - device blocked', Dyson360EyeMode.FAULT_REPLACE_ON_DOCK: 'Error - Replace device on dock', Dyson360EyeMode.FULL_CLEAN_FINISHED: 'Finished', Dyson360EyeMode.FULL_CLEAN_NEEDS_CHARGE: 'Need charging'}
return dyson_labels.get(self._device.state.state, self._device.state.state) |
@property
def battery_level(self):
'Return the battery level of the vacuum cleaner.'
return self._device.state.battery_level | -1,717,471,583,728,855,800 | Return the battery level of the vacuum cleaner. | homeassistant/components/dyson/vacuum.py | battery_level | FlorianLudwig/home-assistant | python | @property
def battery_level(self):
return self._device.state.battery_level |
@property
def fan_speed(self):
'Return the fan speed of the vacuum cleaner.'
from libpurecoollink.const import PowerMode
speed_labels = {PowerMode.MAX: 'Max', PowerMode.QUIET: 'Quiet'}
return speed_labels[self._device.state.power_mode] | 258,221,379,467,744,350 | Return the fan speed of the vacuum cleaner. | homeassistant/components/dyson/vacuum.py | fan_speed | FlorianLudwig/home-assistant | python | @property
def fan_speed(self):
from libpurecoollink.const import PowerMode
speed_labels = {PowerMode.MAX: 'Max', PowerMode.QUIET: 'Quiet'}
return speed_labels[self._device.state.power_mode] |
@property
def fan_speed_list(self):
'Get the list of available fan speed steps of the vacuum cleaner.'
return ['Quiet', 'Max'] | 1,026,950,633,880,453,800 | Get the list of available fan speed steps of the vacuum cleaner. | homeassistant/components/dyson/vacuum.py | fan_speed_list | FlorianLudwig/home-assistant | python | @property
def fan_speed_list(self):
return ['Quiet', 'Max'] |
@property
def device_state_attributes(self):
'Return the specific state attributes of this vacuum cleaner.'
return {ATTR_POSITION: str(self._device.state.position)} | 3,477,451,807,515,275,000 | Return the specific state attributes of this vacuum cleaner. | homeassistant/components/dyson/vacuum.py | device_state_attributes | FlorianLudwig/home-assistant | python | @property
def device_state_attributes(self):
return {ATTR_POSITION: str(self._device.state.position)} |
@property
def is_on(self) -> bool:
'Return True if entity is on.'
from libpurecoollink.const import Dyson360EyeMode
return (self._device.state.state in [Dyson360EyeMode.FULL_CLEAN_INITIATED, Dyson360EyeMode.FULL_CLEAN_ABORTED, Dyson360EyeMode.FULL_CLEAN_RUNNING]) | -8,088,883,491,669,138,000 | Return True if entity is on. | homeassistant/components/dyson/vacuum.py | is_on | FlorianLudwig/home-assistant | python | @property
def is_on(self) -> bool:
from libpurecoollink.const import Dyson360EyeMode
return (self._device.state.state in [Dyson360EyeMode.FULL_CLEAN_INITIATED, Dyson360EyeMode.FULL_CLEAN_ABORTED, Dyson360EyeMode.FULL_CLEAN_RUNNING]) |
@property
def available(self) -> bool:
'Return True if entity is available.'
return True | -3,548,180,598,612,628,500 | Return True if entity is available. | homeassistant/components/dyson/vacuum.py | available | FlorianLudwig/home-assistant | python | @property
def available(self) -> bool:
return True |
@property
def supported_features(self):
'Flag vacuum cleaner robot features that are supported.'
return SUPPORT_DYSON | 8,696,468,197,100,955,000 | Flag vacuum cleaner robot features that are supported. | homeassistant/components/dyson/vacuum.py | supported_features | FlorianLudwig/home-assistant | python | @property
def supported_features(self):
return SUPPORT_DYSON |
@property
def battery_icon(self):
'Return the battery icon for the vacuum cleaner.'
from libpurecoollink.const import Dyson360EyeMode
charging = (self._device.state.state in [Dyson360EyeMode.INACTIVE_CHARGING])
return icon_for_battery_level(battery_level=self.battery_level, charging=charging) | 7,973,860,692,923,932,000 | Return the battery icon for the vacuum cleaner. | homeassistant/components/dyson/vacuum.py | battery_icon | FlorianLudwig/home-assistant | python | @property
def battery_icon(self):
from libpurecoollink.const import Dyson360EyeMode
charging = (self._device.state.state in [Dyson360EyeMode.INACTIVE_CHARGING])
return icon_for_battery_level(battery_level=self.battery_level, charging=charging) |
def turn_on(self, **kwargs):
'Turn the vacuum on.'
from libpurecoollink.const import Dyson360EyeMode
_LOGGER.debug('Turn on device %s', self.name)
if (self._device.state.state in [Dyson360EyeMode.FULL_CLEAN_PAUSED]):
self._device.resume()
else:
self._device.start() | -4,007,245,549,949,464,000 | Turn the vacuum on. | homeassistant/components/dyson/vacuum.py | turn_on | FlorianLudwig/home-assistant | python | def turn_on(self, **kwargs):
from libpurecoollink.const import Dyson360EyeMode
_LOGGER.debug('Turn on device %s', self.name)
if (self._device.state.state in [Dyson360EyeMode.FULL_CLEAN_PAUSED]):
self._device.resume()
else:
self._device.start() |
def turn_off(self, **kwargs):
'Turn the vacuum off and return to home.'
_LOGGER.debug('Turn off device %s', self.name)
self._device.pause() | -9,075,945,135,207,410,000 | Turn the vacuum off and return to home. | homeassistant/components/dyson/vacuum.py | turn_off | FlorianLudwig/home-assistant | python | def turn_off(self, **kwargs):
_LOGGER.debug('Turn off device %s', self.name)
self._device.pause() |
def stop(self, **kwargs):
'Stop the vacuum cleaner.'
_LOGGER.debug('Stop device %s', self.name)
self._device.pause() | -1,359,305,905,265,330,200 | Stop the vacuum cleaner. | homeassistant/components/dyson/vacuum.py | stop | FlorianLudwig/home-assistant | python | def stop(self, **kwargs):
_LOGGER.debug('Stop device %s', self.name)
self._device.pause() |
def set_fan_speed(self, fan_speed, **kwargs):
'Set fan speed.'
from libpurecoollink.const import PowerMode
_LOGGER.debug('Set fan speed %s on device %s', fan_speed, self.name)
power_modes = {'Quiet': PowerMode.QUIET, 'Max': PowerMode.MAX}
self._device.set_power_mode(power_modes[fan_speed]) | -9,020,456,243,668,777,000 | Set fan speed. | homeassistant/components/dyson/vacuum.py | set_fan_speed | FlorianLudwig/home-assistant | python | def set_fan_speed(self, fan_speed, **kwargs):
from libpurecoollink.const import PowerMode
_LOGGER.debug('Set fan speed %s on device %s', fan_speed, self.name)
power_modes = {'Quiet': PowerMode.QUIET, 'Max': PowerMode.MAX}
self._device.set_power_mode(power_modes[fan_speed]) |
def start_pause(self, **kwargs):
'Start, pause or resume the cleaning task.'
from libpurecoollink.const import Dyson360EyeMode
if (self._device.state.state in [Dyson360EyeMode.FULL_CLEAN_PAUSED]):
_LOGGER.debug('Resume device %s', self.name)
self._device.resume()
elif (self._device.state.state in [Dyson360EyeMode.INACTIVE_CHARGED, Dyson360EyeMode.INACTIVE_CHARGING]):
_LOGGER.debug('Start device %s', self.name)
self._device.start()
else:
_LOGGER.debug('Pause device %s', self.name)
self._device.pause() | -1,182,193,037,062,809,300 | Start, pause or resume the cleaning task. | homeassistant/components/dyson/vacuum.py | start_pause | FlorianLudwig/home-assistant | python | def start_pause(self, **kwargs):
from libpurecoollink.const import Dyson360EyeMode
if (self._device.state.state in [Dyson360EyeMode.FULL_CLEAN_PAUSED]):
_LOGGER.debug('Resume device %s', self.name)
self._device.resume()
elif (self._device.state.state in [Dyson360EyeMode.INACTIVE_CHARGED, Dyson360EyeMode.INACTIVE_CHARGING]):
_LOGGER.debug('Start device %s', self.name)
self._device.start()
else:
_LOGGER.debug('Pause device %s', self.name)
self._device.pause() |
def return_to_base(self, **kwargs):
'Set the vacuum cleaner to return to the dock.'
_LOGGER.debug('Return to base device %s', self.name)
self._device.abort() | -7,344,116,717,420,590,000 | Set the vacuum cleaner to return to the dock. | homeassistant/components/dyson/vacuum.py | return_to_base | FlorianLudwig/home-assistant | python | def return_to_base(self, **kwargs):
_LOGGER.debug('Return to base device %s', self.name)
self._device.abort() |
def _get_trigger(trigger, filename=None, lines=None, return_lines=True):
'\n Find the lines where a specific trigger appears.\n\n Args:\n trigger (str): string pattern to search for\n lines (list/None): list of lines\n filename (str/None): file to read lines from\n\n Returns:\n list: indicies of the lines where the trigger string was found and list of lines\n '
lines = _get_lines_from_file(filename=filename, lines=lines)
trigger_indicies = [i for (i, line) in enumerate(lines) if (trigger in line.strip())]
if return_lines:
return (trigger_indicies, lines)
else:
return trigger_indicies | 2,337,207,938,337,832,000 | Find the lines where a specific trigger appears.
Args:
trigger (str): string pattern to search for
lines (list/None): list of lines
filename (str/None): file to read lines from
Returns:
list: indicies of the lines where the trigger string was found and list of lines | pyiron_atomistics/vasp/outcar.py | _get_trigger | pyiron/pyiron_atomistic | python | def _get_trigger(trigger, filename=None, lines=None, return_lines=True):
'\n Find the lines where a specific trigger appears.\n\n Args:\n trigger (str): string pattern to search for\n lines (list/None): list of lines\n filename (str/None): file to read lines from\n\n Returns:\n list: indicies of the lines where the trigger string was found and list of lines\n '
lines = _get_lines_from_file(filename=filename, lines=lines)
trigger_indicies = [i for (i, line) in enumerate(lines) if (trigger in line.strip())]
if return_lines:
return (trigger_indicies, lines)
else:
return trigger_indicies |
def _get_lines_from_file(filename, lines=None):
'\n If lines is None read the lines from the file with the filename filename.\n\n Args:\n filename (str): file to read lines from\n lines (list/ None): list of lines\n\n Returns:\n list: list of lines\n '
if (lines is None):
with open(filename, 'r') as f:
lines = f.readlines()
return lines | 1,785,496,538,491,603,200 | If lines is None read the lines from the file with the filename filename.
Args:
filename (str): file to read lines from
lines (list/ None): list of lines
Returns:
list: list of lines | pyiron_atomistics/vasp/outcar.py | _get_lines_from_file | pyiron/pyiron_atomistic | python | def _get_lines_from_file(filename, lines=None):
'\n If lines is None read the lines from the file with the filename filename.\n\n Args:\n filename (str): file to read lines from\n lines (list/ None): list of lines\n\n Returns:\n list: list of lines\n '
if (lines is None):
with open(filename, 'r') as f:
lines = f.readlines()
return lines |
def from_file(self, filename='OUTCAR'):
'\n Parse and store relevant quantities from the OUTCAR file into parse_dict.\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n\n '
with open(filename, 'r') as f:
lines = f.readlines()
energies = self.get_total_energies(filename=filename, lines=lines)
energies_int = self.get_energy_without_entropy(filename=filename, lines=lines)
energies_zero = self.get_energy_sigma_0(filename=filename, lines=lines)
scf_energies = self.get_all_total_energies(filename=filename, lines=lines)
n_atoms = self.get_number_of_atoms(filename=filename, lines=lines)
forces = self.get_forces(filename=filename, lines=lines, n_atoms=n_atoms)
positions = self.get_positions(filename=filename, lines=lines, n_atoms=n_atoms)
cells = self.get_cells(filename=filename, lines=lines)
steps = self.get_steps(filename=filename, lines=lines)
temperatures = self.get_temperatures(filename=filename, lines=lines)
time = self.get_time(filename=filename, lines=lines)
fermi_level = self.get_fermi_level(filename=filename, lines=lines)
scf_moments = self.get_dipole_moments(filename=filename, lines=lines)
kin_energy_error = self.get_kinetic_energy_error(filename=filename, lines=lines)
stresses = self.get_stresses(filename=filename, si_unit=False, lines=lines)
n_elect = self.get_nelect(filename=filename, lines=lines)
(e_fermi_list, vbm_list, cbm_list) = self.get_band_properties(filename=filename, lines=lines)
elastic_constants = self.get_elastic_constants(filename=filename, lines=lines)
try:
irreducible_kpoints = self.get_irreducible_kpoints(filename=filename, lines=lines)
except ValueError:
print('irreducible kpoints not parsed !')
irreducible_kpoints = None
(magnetization, final_magmom_lst) = self.get_magnetization(filename=filename, lines=lines)
broyden_mixing = self.get_broyden_mixing_mesh(filename=filename, lines=lines)
self.parse_dict['energies'] = energies
self.parse_dict['energies_int'] = energies_int
self.parse_dict['energies_zero'] = energies_zero
self.parse_dict['scf_energies'] = scf_energies
self.parse_dict['forces'] = forces
self.parse_dict['positions'] = positions
self.parse_dict['cells'] = cells
self.parse_dict['steps'] = steps
self.parse_dict['temperatures'] = temperatures
self.parse_dict['time'] = time
self.parse_dict['fermi_level'] = fermi_level
self.parse_dict['scf_dipole_moments'] = scf_moments
self.parse_dict['kin_energy_error'] = kin_energy_error
self.parse_dict['stresses'] = stresses
self.parse_dict['irreducible_kpoints'] = irreducible_kpoints
self.parse_dict['magnetization'] = magnetization
self.parse_dict['final_magmoms'] = final_magmom_lst
self.parse_dict['broyden_mixing'] = broyden_mixing
self.parse_dict['n_elect'] = n_elect
self.parse_dict['e_fermi_list'] = e_fermi_list
self.parse_dict['vbm_list'] = vbm_list
self.parse_dict['cbm_list'] = cbm_list
self.parse_dict['elastic_constants'] = elastic_constants
try:
self.parse_dict['pressures'] = (np.average(stresses[:, 0:3], axis=1) * KBAR_TO_EVA)
except IndexError:
self.parse_dict['pressures'] = np.zeros(len(steps)) | 2,331,835,258,319,286,300 | Parse and store relevant quantities from the OUTCAR file into parse_dict.
Args:
filename (str): Filename of the OUTCAR file to parse | pyiron_atomistics/vasp/outcar.py | from_file | pyiron/pyiron_atomistic | python | def from_file(self, filename='OUTCAR'):
'\n Parse and store relevant quantities from the OUTCAR file into parse_dict.\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n\n '
with open(filename, 'r') as f:
lines = f.readlines()
energies = self.get_total_energies(filename=filename, lines=lines)
energies_int = self.get_energy_without_entropy(filename=filename, lines=lines)
energies_zero = self.get_energy_sigma_0(filename=filename, lines=lines)
scf_energies = self.get_all_total_energies(filename=filename, lines=lines)
n_atoms = self.get_number_of_atoms(filename=filename, lines=lines)
forces = self.get_forces(filename=filename, lines=lines, n_atoms=n_atoms)
positions = self.get_positions(filename=filename, lines=lines, n_atoms=n_atoms)
cells = self.get_cells(filename=filename, lines=lines)
steps = self.get_steps(filename=filename, lines=lines)
temperatures = self.get_temperatures(filename=filename, lines=lines)
time = self.get_time(filename=filename, lines=lines)
fermi_level = self.get_fermi_level(filename=filename, lines=lines)
scf_moments = self.get_dipole_moments(filename=filename, lines=lines)
kin_energy_error = self.get_kinetic_energy_error(filename=filename, lines=lines)
stresses = self.get_stresses(filename=filename, si_unit=False, lines=lines)
n_elect = self.get_nelect(filename=filename, lines=lines)
(e_fermi_list, vbm_list, cbm_list) = self.get_band_properties(filename=filename, lines=lines)
elastic_constants = self.get_elastic_constants(filename=filename, lines=lines)
try:
irreducible_kpoints = self.get_irreducible_kpoints(filename=filename, lines=lines)
except ValueError:
print('irreducible kpoints not parsed !')
irreducible_kpoints = None
(magnetization, final_magmom_lst) = self.get_magnetization(filename=filename, lines=lines)
broyden_mixing = self.get_broyden_mixing_mesh(filename=filename, lines=lines)
self.parse_dict['energies'] = energies
self.parse_dict['energies_int'] = energies_int
self.parse_dict['energies_zero'] = energies_zero
self.parse_dict['scf_energies'] = scf_energies
self.parse_dict['forces'] = forces
self.parse_dict['positions'] = positions
self.parse_dict['cells'] = cells
self.parse_dict['steps'] = steps
self.parse_dict['temperatures'] = temperatures
self.parse_dict['time'] = time
self.parse_dict['fermi_level'] = fermi_level
self.parse_dict['scf_dipole_moments'] = scf_moments
self.parse_dict['kin_energy_error'] = kin_energy_error
self.parse_dict['stresses'] = stresses
self.parse_dict['irreducible_kpoints'] = irreducible_kpoints
self.parse_dict['magnetization'] = magnetization
self.parse_dict['final_magmoms'] = final_magmom_lst
self.parse_dict['broyden_mixing'] = broyden_mixing
self.parse_dict['n_elect'] = n_elect
self.parse_dict['e_fermi_list'] = e_fermi_list
self.parse_dict['vbm_list'] = vbm_list
self.parse_dict['cbm_list'] = cbm_list
self.parse_dict['elastic_constants'] = elastic_constants
try:
self.parse_dict['pressures'] = (np.average(stresses[:, 0:3], axis=1) * KBAR_TO_EVA)
except IndexError:
self.parse_dict['pressures'] = np.zeros(len(steps)) |
def to_hdf(self, hdf, group_name='outcar'):
'\n Store output in an HDF5 file\n\n Args:\n hdf (pyiron_base.generic.hdfio.FileHDFio): HDF5 group or file\n group_name (str): Name of the HDF5 group\n '
with hdf.open(group_name) as hdf5_output:
for key in self.parse_dict.keys():
hdf5_output[key] = self.parse_dict[key] | 2,061,548,751,776,756,500 | Store output in an HDF5 file
Args:
hdf (pyiron_base.generic.hdfio.FileHDFio): HDF5 group or file
group_name (str): Name of the HDF5 group | pyiron_atomistics/vasp/outcar.py | to_hdf | pyiron/pyiron_atomistic | python | def to_hdf(self, hdf, group_name='outcar'):
'\n Store output in an HDF5 file\n\n Args:\n hdf (pyiron_base.generic.hdfio.FileHDFio): HDF5 group or file\n group_name (str): Name of the HDF5 group\n '
with hdf.open(group_name) as hdf5_output:
for key in self.parse_dict.keys():
hdf5_output[key] = self.parse_dict[key] |
def to_hdf_minimal(self, hdf, group_name='outcar'):
'\n Store minimal output in an HDF5 file (output unique to OUTCAR)\n\n Args:\n hdf (pyiron_base.generic.hdfio.FileHDFio): HDF5 group or file\n group_name (str): Name of the HDF5 group\n '
unique_quantities = ['kin_energy_error', 'broyden_mixing', 'stresses', 'irreducible_kpoints']
with hdf.open(group_name) as hdf5_output:
for key in self.parse_dict.keys():
if (key in unique_quantities):
hdf5_output[key] = self.parse_dict[key] | -1,055,857,124,896,554,000 | Store minimal output in an HDF5 file (output unique to OUTCAR)
Args:
hdf (pyiron_base.generic.hdfio.FileHDFio): HDF5 group or file
group_name (str): Name of the HDF5 group | pyiron_atomistics/vasp/outcar.py | to_hdf_minimal | pyiron/pyiron_atomistic | python | def to_hdf_minimal(self, hdf, group_name='outcar'):
'\n Store minimal output in an HDF5 file (output unique to OUTCAR)\n\n Args:\n hdf (pyiron_base.generic.hdfio.FileHDFio): HDF5 group or file\n group_name (str): Name of the HDF5 group\n '
unique_quantities = ['kin_energy_error', 'broyden_mixing', 'stresses', 'irreducible_kpoints']
with hdf.open(group_name) as hdf5_output:
for key in self.parse_dict.keys():
if (key in unique_quantities):
hdf5_output[key] = self.parse_dict[key] |
def from_hdf(self, hdf, group_name='outcar'):
'\n Load output from an HDF5 file\n\n Args:\n hdf (pyiron_base.generic.hdfio.FileHDFio): HDF5 group or file\n group_name (str): Name of the HDF5 group\n '
with hdf.open(group_name) as hdf5_output:
for key in hdf5_output.list_nodes():
self.parse_dict[key] = hdf5_output[key] | 1,578,328,730,927,588,600 | Load output from an HDF5 file
Args:
hdf (pyiron_base.generic.hdfio.FileHDFio): HDF5 group or file
group_name (str): Name of the HDF5 group | pyiron_atomistics/vasp/outcar.py | from_hdf | pyiron/pyiron_atomistic | python | def from_hdf(self, hdf, group_name='outcar'):
'\n Load output from an HDF5 file\n\n Args:\n hdf (pyiron_base.generic.hdfio.FileHDFio): HDF5 group or file\n group_name (str): Name of the HDF5 group\n '
with hdf.open(group_name) as hdf5_output:
for key in hdf5_output.list_nodes():
self.parse_dict[key] = hdf5_output[key] |
def get_positions_and_forces(self, filename='OUTCAR', lines=None, n_atoms=None):
'\n Gets the forces and positions for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n n_atoms (int/None): number of ions in OUTCAR\n\n Returns:\n [positions, forces] (sequence)\n numpy.ndarray: A Nx3xM array of positions in $\\AA$\n numpy.ndarray: A Nx3xM array of forces in $eV / \\AA$\n\n where N is the number of atoms and M is the number of time steps\n '
if (n_atoms is None):
n_atoms = self.get_number_of_atoms(filename=filename, lines=lines)
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='TOTAL-FORCE (eV/Angst)')
return self._get_positions_and_forces_parser(lines=lines, trigger_indices=trigger_indices, n_atoms=n_atoms, pos_flag=True, force_flag=True) | -3,221,029,323,817,749,000 | Gets the forces and positions for every ionic step from the OUTCAR file
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
n_atoms (int/None): number of ions in OUTCAR
Returns:
[positions, forces] (sequence)
numpy.ndarray: A Nx3xM array of positions in $\AA$
numpy.ndarray: A Nx3xM array of forces in $eV / \AA$
where N is the number of atoms and M is the number of time steps | pyiron_atomistics/vasp/outcar.py | get_positions_and_forces | pyiron/pyiron_atomistic | python | def get_positions_and_forces(self, filename='OUTCAR', lines=None, n_atoms=None):
'\n Gets the forces and positions for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n n_atoms (int/None): number of ions in OUTCAR\n\n Returns:\n [positions, forces] (sequence)\n numpy.ndarray: A Nx3xM array of positions in $\\AA$\n numpy.ndarray: A Nx3xM array of forces in $eV / \\AA$\n\n where N is the number of atoms and M is the number of time steps\n '
if (n_atoms is None):
n_atoms = self.get_number_of_atoms(filename=filename, lines=lines)
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='TOTAL-FORCE (eV/Angst)')
return self._get_positions_and_forces_parser(lines=lines, trigger_indices=trigger_indices, n_atoms=n_atoms, pos_flag=True, force_flag=True) |
def get_positions(self, filename='OUTCAR', lines=None, n_atoms=None):
'\n Gets the positions for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n n_atoms (int/None): number of ions in OUTCAR\n\n Returns:\n numpy.ndarray: A Nx3xM array of positions in $\\AA$\n\n where N is the number of atoms and M is the number of time steps\n '
if (n_atoms is None):
n_atoms = self.get_number_of_atoms(filename=filename, lines=lines)
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='TOTAL-FORCE (eV/Angst)')
return self._get_positions_and_forces_parser(lines=lines, trigger_indices=trigger_indices, n_atoms=n_atoms, pos_flag=True, force_flag=False) | 4,963,498,154,091,084,000 | Gets the positions for every ionic step from the OUTCAR file
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
n_atoms (int/None): number of ions in OUTCAR
Returns:
numpy.ndarray: A Nx3xM array of positions in $\AA$
where N is the number of atoms and M is the number of time steps | pyiron_atomistics/vasp/outcar.py | get_positions | pyiron/pyiron_atomistic | python | def get_positions(self, filename='OUTCAR', lines=None, n_atoms=None):
'\n Gets the positions for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n n_atoms (int/None): number of ions in OUTCAR\n\n Returns:\n numpy.ndarray: A Nx3xM array of positions in $\\AA$\n\n where N is the number of atoms and M is the number of time steps\n '
if (n_atoms is None):
n_atoms = self.get_number_of_atoms(filename=filename, lines=lines)
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='TOTAL-FORCE (eV/Angst)')
return self._get_positions_and_forces_parser(lines=lines, trigger_indices=trigger_indices, n_atoms=n_atoms, pos_flag=True, force_flag=False) |
def get_forces(self, filename='OUTCAR', lines=None, n_atoms=None):
'\n Gets the forces for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n n_atoms (int/None): number of ions in OUTCAR\n\n Returns:\n\n numpy.ndarray: A Nx3xM array of forces in $eV / \\AA$\n\n where N is the number of atoms and M is the number of time steps\n '
if (n_atoms is None):
n_atoms = self.get_number_of_atoms(filename=filename, lines=lines)
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='TOTAL-FORCE (eV/Angst)')
return self._get_positions_and_forces_parser(lines=lines, trigger_indices=trigger_indices, n_atoms=n_atoms, pos_flag=False, force_flag=True) | -8,477,871,776,164,714,000 | Gets the forces for every ionic step from the OUTCAR file
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
n_atoms (int/None): number of ions in OUTCAR
Returns:
numpy.ndarray: A Nx3xM array of forces in $eV / \AA$
where N is the number of atoms and M is the number of time steps | pyiron_atomistics/vasp/outcar.py | get_forces | pyiron/pyiron_atomistic | python | def get_forces(self, filename='OUTCAR', lines=None, n_atoms=None):
'\n Gets the forces for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n n_atoms (int/None): number of ions in OUTCAR\n\n Returns:\n\n numpy.ndarray: A Nx3xM array of forces in $eV / \\AA$\n\n where N is the number of atoms and M is the number of time steps\n '
if (n_atoms is None):
n_atoms = self.get_number_of_atoms(filename=filename, lines=lines)
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='TOTAL-FORCE (eV/Angst)')
return self._get_positions_and_forces_parser(lines=lines, trigger_indices=trigger_indices, n_atoms=n_atoms, pos_flag=False, force_flag=True) |
def get_cells(self, filename='OUTCAR', lines=None):
'\n Gets the cell size and shape for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: A 3x3xM array of the cell shape in $\\AA$\n\n where M is the number of time steps\n '
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='VOLUME and BASIS-vectors are now :')
return self._get_cells_praser(lines=lines, trigger_indices=trigger_indices) | 9,096,097,438,204,182,000 | Gets the cell size and shape for every ionic step from the OUTCAR file
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
numpy.ndarray: A 3x3xM array of the cell shape in $\AA$
where M is the number of time steps | pyiron_atomistics/vasp/outcar.py | get_cells | pyiron/pyiron_atomistic | python | def get_cells(self, filename='OUTCAR', lines=None):
'\n Gets the cell size and shape for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: A 3x3xM array of the cell shape in $\\AA$\n\n where M is the number of time steps\n '
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='VOLUME and BASIS-vectors are now :')
return self._get_cells_praser(lines=lines, trigger_indices=trigger_indices) |
@staticmethod
def get_stresses(filename='OUTCAR', lines=None, si_unit=True):
'\n\n Args:\n filename (str): Input filename\n lines (list/None): lines read from the file\n si_unit (bool): True SI units are used\n\n Returns:\n numpy.ndarray: An array of stress values\n\n '
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='FORCE on cell =-STRESS in cart. coord. units (eV):')
pullay_stress_lst = []
for j in trigger_indices:
try:
if si_unit:
pullay_stress_lst.append([float(l) for l in lines[(j + 13)].split()[1:7]])
else:
pullay_stress_lst.append([float(l) for l in lines[(j + 14)].split()[2:8]])
except ValueError:
if si_unit:
pullay_stress_lst.append(([float('NaN')] * 6))
else:
pullay_stress_lst.append(([float('NaN')] * 6))
return np.array(pullay_stress_lst) | 3,243,403,515,257,189,000 | Args:
filename (str): Input filename
lines (list/None): lines read from the file
si_unit (bool): True SI units are used
Returns:
numpy.ndarray: An array of stress values | pyiron_atomistics/vasp/outcar.py | get_stresses | pyiron/pyiron_atomistic | python | @staticmethod
def get_stresses(filename='OUTCAR', lines=None, si_unit=True):
'\n\n Args:\n filename (str): Input filename\n lines (list/None): lines read from the file\n si_unit (bool): True SI units are used\n\n Returns:\n numpy.ndarray: An array of stress values\n\n '
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='FORCE on cell =-STRESS in cart. coord. units (eV):')
pullay_stress_lst = []
for j in trigger_indices:
try:
if si_unit:
pullay_stress_lst.append([float(l) for l in lines[(j + 13)].split()[1:7]])
else:
pullay_stress_lst.append([float(l) for l in lines[(j + 14)].split()[2:8]])
except ValueError:
if si_unit:
pullay_stress_lst.append(([float('NaN')] * 6))
else:
pullay_stress_lst.append(([float('NaN')] * 6))
return np.array(pullay_stress_lst) |
@staticmethod
def get_irreducible_kpoints(filename='OUTCAR', reciprocal=True, weight=True, planewaves=True, lines=None):
'\n Function to extract the irreducible kpoints from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n reciprocal (bool): Get either the reciprocal or the cartesian coordinates\n weight (bool): Get the weight assigned to the irreducible kpoints\n planewaves (bool): Get the planewaves assigned to the irreducible kpoints\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: An array of k-points\n '
kpoint_lst = []
weight_lst = []
planewaves_lst = []
trigger_number_str = 'Subroutine IBZKPT returns following result:'
trigger_plane_waves_str = 'k-point 1 :'
trigger_number = 0
trigger_plane_waves = 0
lines = _get_lines_from_file(filename=filename, lines=lines)
for (i, line) in enumerate(lines):
line = line.strip()
if (trigger_number_str in line):
trigger_number = int(i)
elif planewaves:
if (trigger_plane_waves_str in line):
trigger_plane_waves = int(i)
number_irr_kpoints = int(lines[(trigger_number + 3)].split()[1])
if reciprocal:
trigger_start = (trigger_number + 7)
else:
trigger_start = ((trigger_number + 10) + number_irr_kpoints)
for line in lines[trigger_start:(trigger_start + number_irr_kpoints)]:
line = line.strip()
line = _clean_line(line)
kpoint_lst.append([float(l) for l in line.split()[0:3]])
if weight:
weight_lst.append(float(line.split()[3]))
if (planewaves and (trigger_plane_waves != 0)):
for line in lines[trigger_plane_waves:(trigger_plane_waves + number_irr_kpoints)]:
line = line.strip()
line = _clean_line(line)
planewaves_lst.append(float(line.split()[(- 1)]))
if (weight and planewaves):
return (np.array(kpoint_lst), np.array(weight_lst), np.array(planewaves_lst))
elif weight:
return (np.array(kpoint_lst), np.array(weight_lst))
elif planewaves:
return (np.array(kpoint_lst), np.array(planewaves_lst))
else:
return np.array(kpoint_lst) | 8,054,148,439,433,988,000 | Function to extract the irreducible kpoints from the OUTCAR file
Args:
filename (str): Filename of the OUTCAR file to parse
reciprocal (bool): Get either the reciprocal or the cartesian coordinates
weight (bool): Get the weight assigned to the irreducible kpoints
planewaves (bool): Get the planewaves assigned to the irreducible kpoints
lines (list/None): lines read from the file
Returns:
numpy.ndarray: An array of k-points | pyiron_atomistics/vasp/outcar.py | get_irreducible_kpoints | pyiron/pyiron_atomistic | python | @staticmethod
def get_irreducible_kpoints(filename='OUTCAR', reciprocal=True, weight=True, planewaves=True, lines=None):
'\n Function to extract the irreducible kpoints from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n reciprocal (bool): Get either the reciprocal or the cartesian coordinates\n weight (bool): Get the weight assigned to the irreducible kpoints\n planewaves (bool): Get the planewaves assigned to the irreducible kpoints\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: An array of k-points\n '
kpoint_lst = []
weight_lst = []
planewaves_lst = []
trigger_number_str = 'Subroutine IBZKPT returns following result:'
trigger_plane_waves_str = 'k-point 1 :'
trigger_number = 0
trigger_plane_waves = 0
lines = _get_lines_from_file(filename=filename, lines=lines)
for (i, line) in enumerate(lines):
line = line.strip()
if (trigger_number_str in line):
trigger_number = int(i)
elif planewaves:
if (trigger_plane_waves_str in line):
trigger_plane_waves = int(i)
number_irr_kpoints = int(lines[(trigger_number + 3)].split()[1])
if reciprocal:
trigger_start = (trigger_number + 7)
else:
trigger_start = ((trigger_number + 10) + number_irr_kpoints)
for line in lines[trigger_start:(trigger_start + number_irr_kpoints)]:
line = line.strip()
line = _clean_line(line)
kpoint_lst.append([float(l) for l in line.split()[0:3]])
if weight:
weight_lst.append(float(line.split()[3]))
if (planewaves and (trigger_plane_waves != 0)):
for line in lines[trigger_plane_waves:(trigger_plane_waves + number_irr_kpoints)]:
line = line.strip()
line = _clean_line(line)
planewaves_lst.append(float(line.split()[(- 1)]))
if (weight and planewaves):
return (np.array(kpoint_lst), np.array(weight_lst), np.array(planewaves_lst))
elif weight:
return (np.array(kpoint_lst), np.array(weight_lst))
elif planewaves:
return (np.array(kpoint_lst), np.array(planewaves_lst))
else:
return np.array(kpoint_lst) |
@staticmethod
def get_total_energies(filename='OUTCAR', lines=None):
'\n Gets the total energy for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: A 1xM array of the total energies in $eV$\n\n where M is the number of time steps\n '
def get_total_energies_from_line(line):
return float(_clean_line(line.strip()).split()[(- 2)])
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)')
return np.array([get_total_energies_from_line(lines[(j + 2)]) for j in trigger_indices]) | -2,156,645,816,712,065,000 | Gets the total energy for every ionic step from the OUTCAR file
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
numpy.ndarray: A 1xM array of the total energies in $eV$
where M is the number of time steps | pyiron_atomistics/vasp/outcar.py | get_total_energies | pyiron/pyiron_atomistic | python | @staticmethod
def get_total_energies(filename='OUTCAR', lines=None):
'\n Gets the total energy for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: A 1xM array of the total energies in $eV$\n\n where M is the number of time steps\n '
def get_total_energies_from_line(line):
return float(_clean_line(line.strip()).split()[(- 2)])
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)')
return np.array([get_total_energies_from_line(lines[(j + 2)]) for j in trigger_indices]) |
@staticmethod
def get_energy_without_entropy(filename='OUTCAR', lines=None):
'\n Gets the total energy for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: A 1xM array of the total energies in $eV$\n\n where M is the number of time steps\n '
def get_energy_without_entropy_from_line(line):
return float(_clean_line(line.strip()).split()[3])
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)')
return np.array([get_energy_without_entropy_from_line(lines[(j + 4)]) for j in trigger_indices]) | 6,844,802,103,660,939,000 | Gets the total energy for every ionic step from the OUTCAR file
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
numpy.ndarray: A 1xM array of the total energies in $eV$
where M is the number of time steps | pyiron_atomistics/vasp/outcar.py | get_energy_without_entropy | pyiron/pyiron_atomistic | python | @staticmethod
def get_energy_without_entropy(filename='OUTCAR', lines=None):
'\n Gets the total energy for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: A 1xM array of the total energies in $eV$\n\n where M is the number of time steps\n '
def get_energy_without_entropy_from_line(line):
return float(_clean_line(line.strip()).split()[3])
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)')
return np.array([get_energy_without_entropy_from_line(lines[(j + 4)]) for j in trigger_indices]) |
@staticmethod
def get_energy_sigma_0(filename='OUTCAR', lines=None):
'\n Gets the total energy for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: A 1xM array of the total energies in $eV$\n\n where M is the number of time steps\n '
def get_energy_sigma_0_from_line(line):
return float(_clean_line(line.strip()).split()[(- 1)])
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)')
return np.array([get_energy_sigma_0_from_line(lines[(j + 4)]) for j in trigger_indices]) | 7,513,835,992,246,647,000 | Gets the total energy for every ionic step from the OUTCAR file
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
numpy.ndarray: A 1xM array of the total energies in $eV$
where M is the number of time steps | pyiron_atomistics/vasp/outcar.py | get_energy_sigma_0 | pyiron/pyiron_atomistic | python | @staticmethod
def get_energy_sigma_0(filename='OUTCAR', lines=None):
'\n Gets the total energy for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: A 1xM array of the total energies in $eV$\n\n where M is the number of time steps\n '
def get_energy_sigma_0_from_line(line):
return float(_clean_line(line.strip()).split()[(- 1)])
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)')
return np.array([get_energy_sigma_0_from_line(lines[(j + 4)]) for j in trigger_indices]) |
@staticmethod
def get_all_total_energies(filename='OUTCAR', lines=None):
'\n Gets the energy at every electronic step\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n list: A list of energie for every electronic step at every ionic step\n '
ionic_trigger = 'FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)'
electronic_trigger = 'free energy TOTEN ='
scf_energies = list()
lines = _get_lines_from_file(filename=filename, lines=lines)
istep_energies = list()
for (i, line) in enumerate(lines):
line = line.strip()
if (ionic_trigger in line):
scf_energies.append(np.array(istep_energies))
istep_energies = list()
if (electronic_trigger in line):
line = _clean_line(line)
ene = float(line.split()[(- 2)])
istep_energies.append(ene)
return scf_energies | 938,323,484,795,355,100 | Gets the energy at every electronic step
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
list: A list of energie for every electronic step at every ionic step | pyiron_atomistics/vasp/outcar.py | get_all_total_energies | pyiron/pyiron_atomistic | python | @staticmethod
def get_all_total_energies(filename='OUTCAR', lines=None):
'\n Gets the energy at every electronic step\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n list: A list of energie for every electronic step at every ionic step\n '
ionic_trigger = 'FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)'
electronic_trigger = 'free energy TOTEN ='
scf_energies = list()
lines = _get_lines_from_file(filename=filename, lines=lines)
istep_energies = list()
for (i, line) in enumerate(lines):
line = line.strip()
if (ionic_trigger in line):
scf_energies.append(np.array(istep_energies))
istep_energies = list()
if (electronic_trigger in line):
line = _clean_line(line)
ene = float(line.split()[(- 2)])
istep_energies.append(ene)
return scf_energies |
@staticmethod
def get_magnetization(filename='OUTCAR', lines=None):
'\n Gets the magnetization\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n list: A list with the mgnetization values\n '
ionic_trigger = 'FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)'
electronic_trigger = 'eigenvalue-minimisations'
nion_trigger = 'NIONS ='
mag_lst = list()
local_spin_trigger = False
n_atoms = None
mag_dict = dict()
mag_dict['x'] = list()
mag_dict['y'] = list()
mag_dict['z'] = list()
lines = _get_lines_from_file(filename=filename, lines=lines)
istep_energies = list()
final_magmom_lst = list()
for (i, line) in enumerate(lines):
line = line.strip()
if (ionic_trigger in line):
mag_lst.append(np.array(istep_energies))
istep_energies = list()
if ('Atomic Wigner-Seitz radii' in line):
local_spin_trigger = True
if (electronic_trigger in line):
try:
line = lines[(i + 2)].split('magnetization')[(- 1)]
if (line != ' \n'):
spin_str_lst = line.split()
spin_str_len = len(spin_str_lst)
if (spin_str_len == 1):
ene = float(line)
elif (spin_str_len == 3):
ene = [float(spin_str_lst[0]), float(spin_str_lst[1]), float(spin_str_lst[2])]
else:
warnings.warn('Unrecognized spin configuration.')
return (mag_lst, final_magmom_lst)
istep_energies.append(ene)
except ValueError:
warnings.warn('Something went wrong in parsing the magnetization')
if (n_atoms is None):
if (nion_trigger in line):
n_atoms = int(line.split(nion_trigger)[(- 1)])
if local_spin_trigger:
try:
for (ind_dir, direc) in enumerate(['x', 'y', 'z']):
if ('magnetization ({})'.format(direc) in line):
mag_dict[direc].append([float(lines[((i + 4) + atom_index)].split()[(- 1)]) for atom_index in range(n_atoms)])
except ValueError:
warnings.warn('Something went wrong in parsing the magnetic moments')
if (len(mag_dict['x']) > 0):
if (len(mag_dict['y']) == 0):
final_mag = np.array(mag_dict['x'])
else:
n_ionic_steps = np.array(mag_dict['x']).shape[0]
final_mag = np.abs(np.zeros((n_ionic_steps, n_atoms, 3)))
final_mag[:, :, 0] = np.array(mag_dict['x'])
final_mag[:, :, 1] = np.array(mag_dict['y'])
final_mag[:, :, 2] = np.array(mag_dict['z'])
final_magmom_lst = final_mag.tolist()
return (mag_lst, final_magmom_lst) | 2,437,539,680,318,981,000 | Gets the magnetization
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
list: A list with the mgnetization values | pyiron_atomistics/vasp/outcar.py | get_magnetization | pyiron/pyiron_atomistic | python | @staticmethod
def get_magnetization(filename='OUTCAR', lines=None):
'\n Gets the magnetization\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n list: A list with the mgnetization values\n '
ionic_trigger = 'FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)'
electronic_trigger = 'eigenvalue-minimisations'
nion_trigger = 'NIONS ='
mag_lst = list()
local_spin_trigger = False
n_atoms = None
mag_dict = dict()
mag_dict['x'] = list()
mag_dict['y'] = list()
mag_dict['z'] = list()
lines = _get_lines_from_file(filename=filename, lines=lines)
istep_energies = list()
final_magmom_lst = list()
for (i, line) in enumerate(lines):
line = line.strip()
if (ionic_trigger in line):
mag_lst.append(np.array(istep_energies))
istep_energies = list()
if ('Atomic Wigner-Seitz radii' in line):
local_spin_trigger = True
if (electronic_trigger in line):
try:
line = lines[(i + 2)].split('magnetization')[(- 1)]
if (line != ' \n'):
spin_str_lst = line.split()
spin_str_len = len(spin_str_lst)
if (spin_str_len == 1):
ene = float(line)
elif (spin_str_len == 3):
ene = [float(spin_str_lst[0]), float(spin_str_lst[1]), float(spin_str_lst[2])]
else:
warnings.warn('Unrecognized spin configuration.')
return (mag_lst, final_magmom_lst)
istep_energies.append(ene)
except ValueError:
warnings.warn('Something went wrong in parsing the magnetization')
if (n_atoms is None):
if (nion_trigger in line):
n_atoms = int(line.split(nion_trigger)[(- 1)])
if local_spin_trigger:
try:
for (ind_dir, direc) in enumerate(['x', 'y', 'z']):
if ('magnetization ({})'.format(direc) in line):
mag_dict[direc].append([float(lines[((i + 4) + atom_index)].split()[(- 1)]) for atom_index in range(n_atoms)])
except ValueError:
warnings.warn('Something went wrong in parsing the magnetic moments')
if (len(mag_dict['x']) > 0):
if (len(mag_dict['y']) == 0):
final_mag = np.array(mag_dict['x'])
else:
n_ionic_steps = np.array(mag_dict['x']).shape[0]
final_mag = np.abs(np.zeros((n_ionic_steps, n_atoms, 3)))
final_mag[:, :, 0] = np.array(mag_dict['x'])
final_mag[:, :, 1] = np.array(mag_dict['y'])
final_mag[:, :, 2] = np.array(mag_dict['z'])
final_magmom_lst = final_mag.tolist()
return (mag_lst, final_magmom_lst) |
@staticmethod
def get_broyden_mixing_mesh(filename='OUTCAR', lines=None):
'\n Gets the Broyden mixing mesh size\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n int: Mesh size\n '
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='gives a total of ')
if (len(trigger_indices) > 0):
line_ngx = lines[(trigger_indices[0] - 2)]
else:
warnings.warn('Unable to parse the Broyden mixing mesh. Returning 0 instead')
return 0
str_list = re.sub('[a-zA-Z]', '', line_ngx.replace(' ', '').replace('\n', '')).split('=')
return np.prod([int(val) for val in str_list[1:]]) | -5,583,057,983,312,634,000 | Gets the Broyden mixing mesh size
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
int: Mesh size | pyiron_atomistics/vasp/outcar.py | get_broyden_mixing_mesh | pyiron/pyiron_atomistic | python | @staticmethod
def get_broyden_mixing_mesh(filename='OUTCAR', lines=None):
'\n Gets the Broyden mixing mesh size\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n int: Mesh size\n '
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='gives a total of ')
if (len(trigger_indices) > 0):
line_ngx = lines[(trigger_indices[0] - 2)]
else:
warnings.warn('Unable to parse the Broyden mixing mesh. Returning 0 instead')
return 0
str_list = re.sub('[a-zA-Z]', , line_ngx.replace(' ', ).replace('\n', )).split('=')
return np.prod([int(val) for val in str_list[1:]]) |
@staticmethod
def get_temperatures(filename='OUTCAR', lines=None):
'\n Gets the temperature at each ionic step (applicable for MD)\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: An array of temperatures in Kelvin\n '
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='kin. lattice EKIN_LAT= ')
temperatures = []
if (len(trigger_indices) > 0):
for j in trigger_indices:
line = lines[j].strip()
line = _clean_line(line)
temperatures.append(float(line.split()[(- 2)]))
else:
temperatures = np.zeros(len(_get_trigger(lines=lines, trigger='FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)', return_lines=False)))
return np.array(temperatures) | 7,192,756,473,802,071,000 | Gets the temperature at each ionic step (applicable for MD)
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
numpy.ndarray: An array of temperatures in Kelvin | pyiron_atomistics/vasp/outcar.py | get_temperatures | pyiron/pyiron_atomistic | python | @staticmethod
def get_temperatures(filename='OUTCAR', lines=None):
'\n Gets the temperature at each ionic step (applicable for MD)\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: An array of temperatures in Kelvin\n '
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger='kin. lattice EKIN_LAT= ')
temperatures = []
if (len(trigger_indices) > 0):
for j in trigger_indices:
line = lines[j].strip()
line = _clean_line(line)
temperatures.append(float(line.split()[(- 2)]))
else:
temperatures = np.zeros(len(_get_trigger(lines=lines, trigger='FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)', return_lines=False)))
return np.array(temperatures) |
@staticmethod
def get_steps(filename='OUTCAR', lines=None):
'\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: Steps during the simulation\n '
nblock_trigger = 'NBLOCK ='
trigger = 'FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)'
trigger_indices = list()
read_nblock = True
n_block = 1
lines = _get_lines_from_file(filename=filename, lines=lines)
for (i, line) in enumerate(lines):
line = line.strip()
if (trigger in line):
trigger_indices.append(i)
if (read_nblock is None):
if (nblock_trigger in line):
line = _clean_line(line)
n_block = int(line.split(nblock_trigger)[(- 1)])
return (n_block * np.linspace(0, len(trigger_indices))) | 5,047,558,663,425,873,000 | Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
numpy.ndarray: Steps during the simulation | pyiron_atomistics/vasp/outcar.py | get_steps | pyiron/pyiron_atomistic | python | @staticmethod
def get_steps(filename='OUTCAR', lines=None):
'\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: Steps during the simulation\n '
nblock_trigger = 'NBLOCK ='
trigger = 'FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)'
trigger_indices = list()
read_nblock = True
n_block = 1
lines = _get_lines_from_file(filename=filename, lines=lines)
for (i, line) in enumerate(lines):
line = line.strip()
if (trigger in line):
trigger_indices.append(i)
if (read_nblock is None):
if (nblock_trigger in line):
line = _clean_line(line)
n_block = int(line.split(nblock_trigger)[(- 1)])
return (n_block * np.linspace(0, len(trigger_indices))) |
def get_time(self, filename='OUTCAR', lines=None):
'\n Time after each simulation step (for MD)\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: An array of time values in fs\n\n '
potim_trigger = 'POTIM ='
read_potim = True
potim = 1.0
lines = _get_lines_from_file(filename=filename, lines=lines)
for (i, line) in enumerate(lines):
line = line.strip()
if (read_potim is None):
if (potim_trigger in line):
line = _clean_line(line)
potim = float(line.split(potim_trigger)[0])
return (potim * self.get_steps(filename)) | 7,670,659,648,015,844,000 | Time after each simulation step (for MD)
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
numpy.ndarray: An array of time values in fs | pyiron_atomistics/vasp/outcar.py | get_time | pyiron/pyiron_atomistic | python | def get_time(self, filename='OUTCAR', lines=None):
'\n Time after each simulation step (for MD)\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: An array of time values in fs\n\n '
potim_trigger = 'POTIM ='
read_potim = True
potim = 1.0
lines = _get_lines_from_file(filename=filename, lines=lines)
for (i, line) in enumerate(lines):
line = line.strip()
if (read_potim is None):
if (potim_trigger in line):
line = _clean_line(line)
potim = float(line.split(potim_trigger)[0])
return (potim * self.get_steps(filename)) |
@staticmethod
def get_kinetic_energy_error(filename='OUTCAR', lines=None):
'\n Get the kinetic energy error\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n float: The kinetic energy error in eV\n '
trigger = 'kinetic energy error for atom='
e_kin_err = list()
n_species_list = list()
nion_trigger = 'ions per type ='
tot_kin_error = 0.0
lines = _get_lines_from_file(filename=filename, lines=lines)
for (i, line) in enumerate(lines):
line = line.strip()
if (trigger in line):
e_kin_err.append(float(line.split()[5]))
if (nion_trigger in line):
n_species_list = [float(val) for val in line.split(nion_trigger)[(- 1)].strip().split()]
if ((len(n_species_list) > 0) and (len(n_species_list) == len(e_kin_err))):
tot_kin_error = np.sum((np.array(n_species_list) * np.array(e_kin_err)))
return tot_kin_error | 8,818,304,231,474,694,000 | Get the kinetic energy error
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
float: The kinetic energy error in eV | pyiron_atomistics/vasp/outcar.py | get_kinetic_energy_error | pyiron/pyiron_atomistic | python | @staticmethod
def get_kinetic_energy_error(filename='OUTCAR', lines=None):
'\n Get the kinetic energy error\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n float: The kinetic energy error in eV\n '
trigger = 'kinetic energy error for atom='
e_kin_err = list()
n_species_list = list()
nion_trigger = 'ions per type ='
tot_kin_error = 0.0
lines = _get_lines_from_file(filename=filename, lines=lines)
for (i, line) in enumerate(lines):
line = line.strip()
if (trigger in line):
e_kin_err.append(float(line.split()[5]))
if (nion_trigger in line):
n_species_list = [float(val) for val in line.split(nion_trigger)[(- 1)].strip().split()]
if ((len(n_species_list) > 0) and (len(n_species_list) == len(e_kin_err))):
tot_kin_error = np.sum((np.array(n_species_list) * np.array(e_kin_err)))
return tot_kin_error |
@staticmethod
def get_fermi_level(filename='OUTCAR', lines=None):
'\n Getting the Fermi-level (Kohn_Sham) from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n float: The Kohn-Sham Fermi level in eV\n '
trigger = 'E-fermi :'
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger=trigger)
if (len(trigger_indices) != 0):
try:
return float(lines[trigger_indices[(- 1)]].split(trigger)[(- 1)].split()[0])
except ValueError:
return
else:
return | -2,384,256,268,820,492,000 | Getting the Fermi-level (Kohn_Sham) from the OUTCAR file
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
float: The Kohn-Sham Fermi level in eV | pyiron_atomistics/vasp/outcar.py | get_fermi_level | pyiron/pyiron_atomistic | python | @staticmethod
def get_fermi_level(filename='OUTCAR', lines=None):
'\n Getting the Fermi-level (Kohn_Sham) from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n float: The Kohn-Sham Fermi level in eV\n '
trigger = 'E-fermi :'
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger=trigger)
if (len(trigger_indices) != 0):
try:
return float(lines[trigger_indices[(- 1)]].split(trigger)[(- 1)].split()[0])
except ValueError:
return
else:
return |
@staticmethod
def get_dipole_moments(filename='OUTCAR', lines=None):
'\n Get the electric dipole moment at every electronic step\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n list: A list of dipole moments in (eA) for each electronic step\n\n '
moment_trigger = 'dipolmoment'
istep_trigger = 'FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)'
dip_moms = list()
lines = _get_lines_from_file(filename=filename, lines=lines)
istep_mom = list()
for (i, line) in enumerate(lines):
line = line.strip()
if (istep_trigger in line):
dip_moms.append(np.array(istep_mom))
istep_mom = list()
if (moment_trigger in line):
line = _clean_line(line)
mom = np.array([float(val) for val in line.split()[1:4]])
istep_mom.append(mom)
return dip_moms | 4,424,285,629,045,084,700 | Get the electric dipole moment at every electronic step
Args:
filename (str): Filename of the OUTCAR file to parse
lines (list/None): lines read from the file
Returns:
list: A list of dipole moments in (eA) for each electronic step | pyiron_atomistics/vasp/outcar.py | get_dipole_moments | pyiron/pyiron_atomistic | python | @staticmethod
def get_dipole_moments(filename='OUTCAR', lines=None):
'\n Get the electric dipole moment at every electronic step\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n list: A list of dipole moments in (eA) for each electronic step\n\n '
moment_trigger = 'dipolmoment'
istep_trigger = 'FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)'
dip_moms = list()
lines = _get_lines_from_file(filename=filename, lines=lines)
istep_mom = list()
for (i, line) in enumerate(lines):
line = line.strip()
if (istep_trigger in line):
dip_moms.append(np.array(istep_mom))
istep_mom = list()
if (moment_trigger in line):
line = _clean_line(line)
mom = np.array([float(val) for val in line.split()[1:4]])
istep_mom.append(mom)
return dip_moms |
@staticmethod
def get_nelect(filename='OUTCAR', lines=None):
'\n Returns the number of electrons in the simulation\n\n Args:\n filename (str): OUTCAR filename\n lines (list/None): lines read from the file\n\n Returns:\n float: The number of electrons in the simulation\n\n '
nelect_trigger = 'NELECT'
lines = _get_lines_from_file(filename=filename, lines=lines)
for (i, line) in enumerate(lines):
line = line.strip()
if (nelect_trigger in line):
return float(line.split()[2]) | -6,875,787,904,357,671,000 | Returns the number of electrons in the simulation
Args:
filename (str): OUTCAR filename
lines (list/None): lines read from the file
Returns:
float: The number of electrons in the simulation | pyiron_atomistics/vasp/outcar.py | get_nelect | pyiron/pyiron_atomistic | python | @staticmethod
def get_nelect(filename='OUTCAR', lines=None):
'\n Returns the number of electrons in the simulation\n\n Args:\n filename (str): OUTCAR filename\n lines (list/None): lines read from the file\n\n Returns:\n float: The number of electrons in the simulation\n\n '
nelect_trigger = 'NELECT'
lines = _get_lines_from_file(filename=filename, lines=lines)
for (i, line) in enumerate(lines):
line = line.strip()
if (nelect_trigger in line):
return float(line.split()[2]) |
@staticmethod
def get_number_of_atoms(filename='OUTCAR', lines=None):
'\n Returns the number of ions in the simulation\n\n Args:\n filename (str): OUTCAR filename\n lines (list/None): lines read from the file\n\n Returns:\n int: The number of ions in the simulation\n\n '
ions_trigger = 'NIONS ='
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger=ions_trigger)
if (len(trigger_indices) != 0):
return int(lines[trigger_indices[0]].split(ions_trigger)[(- 1)])
else:
raise ValueError() | 922,051,548,595,736,700 | Returns the number of ions in the simulation
Args:
filename (str): OUTCAR filename
lines (list/None): lines read from the file
Returns:
int: The number of ions in the simulation | pyiron_atomistics/vasp/outcar.py | get_number_of_atoms | pyiron/pyiron_atomistic | python | @staticmethod
def get_number_of_atoms(filename='OUTCAR', lines=None):
'\n Returns the number of ions in the simulation\n\n Args:\n filename (str): OUTCAR filename\n lines (list/None): lines read from the file\n\n Returns:\n int: The number of ions in the simulation\n\n '
ions_trigger = 'NIONS ='
(trigger_indices, lines) = _get_trigger(lines=lines, filename=filename, trigger=ions_trigger)
if (len(trigger_indices) != 0):
return int(lines[trigger_indices[0]].split(ions_trigger)[(- 1)])
else:
raise ValueError() |
@staticmethod
def _get_positions_and_forces_parser(lines, trigger_indices, n_atoms, pos_flag=True, force_flag=True):
'\n Parser to get the forces and or positions for every ionic step from the OUTCAR file\n\n Args:\n lines (list): lines read from the file\n trigger_indices (list): list of line indices where the trigger was found.\n n_atoms (int): number of atoms\n pos_flag (bool): parse position\n force_flag (bool): parse forces\n\n Returns:\n [positions, forces] (sequence)\n numpy.ndarray: A Nx3xM array of positions in $\\AA$\n numpy.ndarray: A Nx3xM array of forces in $eV / \\AA$\n\n where N is the number of atoms and M is the number of time steps\n\n '
positions = []
forces = []
for j in trigger_indices:
pos = []
force = []
for line in lines[(j + 2):((j + n_atoms) + 2)]:
line = line.strip()
line = _clean_line(line)
if pos_flag:
pos.append([float(l) for l in line.split()[0:3]])
if force_flag:
force.append([float(l) for l in line.split()[3:]])
forces.append(force)
positions.append(pos)
if (pos_flag and force_flag):
return (np.array(positions), np.array(forces))
elif pos_flag:
return np.array(positions)
elif force_flag:
return np.array(forces) | -2,625,770,188,972,833,300 | Parser to get the forces and or positions for every ionic step from the OUTCAR file
Args:
lines (list): lines read from the file
trigger_indices (list): list of line indices where the trigger was found.
n_atoms (int): number of atoms
pos_flag (bool): parse position
force_flag (bool): parse forces
Returns:
[positions, forces] (sequence)
numpy.ndarray: A Nx3xM array of positions in $\AA$
numpy.ndarray: A Nx3xM array of forces in $eV / \AA$
where N is the number of atoms and M is the number of time steps | pyiron_atomistics/vasp/outcar.py | _get_positions_and_forces_parser | pyiron/pyiron_atomistic | python | @staticmethod
def _get_positions_and_forces_parser(lines, trigger_indices, n_atoms, pos_flag=True, force_flag=True):
'\n Parser to get the forces and or positions for every ionic step from the OUTCAR file\n\n Args:\n lines (list): lines read from the file\n trigger_indices (list): list of line indices where the trigger was found.\n n_atoms (int): number of atoms\n pos_flag (bool): parse position\n force_flag (bool): parse forces\n\n Returns:\n [positions, forces] (sequence)\n numpy.ndarray: A Nx3xM array of positions in $\\AA$\n numpy.ndarray: A Nx3xM array of forces in $eV / \\AA$\n\n where N is the number of atoms and M is the number of time steps\n\n '
positions = []
forces = []
for j in trigger_indices:
pos = []
force = []
for line in lines[(j + 2):((j + n_atoms) + 2)]:
line = line.strip()
line = _clean_line(line)
if pos_flag:
pos.append([float(l) for l in line.split()[0:3]])
if force_flag:
force.append([float(l) for l in line.split()[3:]])
forces.append(force)
positions.append(pos)
if (pos_flag and force_flag):
return (np.array(positions), np.array(forces))
elif pos_flag:
return np.array(positions)
elif force_flag:
return np.array(forces) |
@staticmethod
def _get_cells_praser(lines, trigger_indices):
'\n Parser to get the cell size and shape for every ionic step from the OUTCAR file\n\n Args:\n lines (list): lines read from the file\n trigger_indices (list): list of line indices where the trigger was found.\n n_atoms (int): number of atoms\n\n Returns:\n numpy.ndarray: A 3x3xM array of the cell shape in $\\AA$\n\n where M is the number of time steps\n\n '
cells = []
try:
for j in trigger_indices:
cell = []
for line in lines[(j + 5):(j + 8)]:
line = line.strip()
line = _clean_line(line)
cell.append([float(l) for l in line.split()[0:3]])
cells.append(cell)
return np.array(cells)
except ValueError:
warnings.warn('Unable to parse the cells from the OUTCAR file')
return | -4,564,041,709,904,208,000 | Parser to get the cell size and shape for every ionic step from the OUTCAR file
Args:
lines (list): lines read from the file
trigger_indices (list): list of line indices where the trigger was found.
n_atoms (int): number of atoms
Returns:
numpy.ndarray: A 3x3xM array of the cell shape in $\AA$
where M is the number of time steps | pyiron_atomistics/vasp/outcar.py | _get_cells_praser | pyiron/pyiron_atomistic | python | @staticmethod
def _get_cells_praser(lines, trigger_indices):
'\n Parser to get the cell size and shape for every ionic step from the OUTCAR file\n\n Args:\n lines (list): lines read from the file\n trigger_indices (list): list of line indices where the trigger was found.\n n_atoms (int): number of atoms\n\n Returns:\n numpy.ndarray: A 3x3xM array of the cell shape in $\\AA$\n\n where M is the number of time steps\n\n '
cells = []
try:
for j in trigger_indices:
cell = []
for line in lines[(j + 5):(j + 8)]:
line = line.strip()
line = _clean_line(line)
cell.append([float(l) for l in line.split()[0:3]])
cells.append(cell)
return np.array(cells)
except ValueError:
warnings.warn('Unable to parse the cells from the OUTCAR file')
return |
@property
def content(self):
'Return a string or a Troposphere CFN Function object'
if self.content_file:
return self.content_file
elif self.content_cfn_file:
return self.content_cfn_file
return self._content | -5,168,335,891,709,782,000 | Return a string or a Troposphere CFN Function object | src/paco/models/cfn_init.py | content | waterbear-cloud/aim.models | python | @property
def content(self):
if self.content_file:
return self.content_file
elif self.content_cfn_file:
return self.content_cfn_file
return self._content |
def data_collector(item_list=None, data_processing_chain=None, meta_processing_chain=None, target_format='single_target_per_sequence', channel_dimension='channels_last', verbose=True, print_indent=2):
"Data collector\n\n Collects data and meta into matrices while processing them through processing chains.\n\n Parameters\n ----------\n item_list : list or dict\n Items in the data sequence. List containing multi-level dictionary with first level key\n 'data' and 'meta'. Second level should contain parameters for process method in the processing chain.\n Default value None\n\n data_processing_chain : ProcessingChain\n Data processing chain.\n Default value None\n\n meta_processing_chain : ProcessingChain\n Meta processing chain.\n Default value None\n\n channel_dimension : str\n Controls where channel dimension should be added. Similar to Keras data format parameter.\n If None given, no channel dimension is added.\n Possible values [None, 'channels_first', 'channels_last']\n Default value None\n\n target_format : str\n Meta data interpretation in the relation to the data items.\n Default value 'single_target_per_segment'\n\n verbose : bool\n Print information about the data\n Default value True\n\n print_indent : int\n Default value 2\n\n Returns\n -------\n numpy.ndarray\n data\n\n numpy.ndarray\n meta\n\n dict\n data size information\n\n "
if item_list:
X = []
Y = []
for item in item_list:
data = data_processing_chain.process(**item['data'])
meta = meta_processing_chain.process(**item['meta'])
X.append(data.data)
if (target_format == 'single_target_per_sequence'):
for i in range(0, data.shape[data.sequence_axis]):
Y.append(meta.data[:, 0])
elif (target_format == 'same'):
Y.append(numpy.repeat(a=meta.data, repeats=data.length, axis=1).T)
data_size = {}
if (len(data.shape) == 2):
if (data.time_axis == 0):
X = numpy.vstack(X)
Y = numpy.vstack(Y)
else:
X = numpy.hstack(X)
Y = numpy.hstack(Y)
data_size = {'data': X.shape[data.data_axis], 'time': X.shape[data.time_axis]}
elif (len(data.shape) == 3):
if (data.sequence_axis == 0):
X = numpy.vstack(X)
Y = numpy.vstack(Y)
elif (data.sequence_axis == 1):
X = numpy.hstack(X)
Y = numpy.hstack(Y)
elif (data.sequence_axis == 2):
X = numpy.dstack(X)
Y = numpy.dstack(Y)
if channel_dimension:
if (channel_dimension == 'channels_first'):
X = numpy.expand_dims(X, axis=1)
elif (channel_dimension == 'channels_last'):
X = numpy.expand_dims(X, axis=3)
data_size = {'data': X.shape[data.data_axis], 'time': X.shape[data.time_axis], 'sequence': X.shape[data.sequence_axis]}
if verbose:
data_shape = data.shape
data_axis = {'time_axis': data.time_axis, 'data_axis': data.data_axis}
if hasattr(data, 'sequence_axis'):
data_axis['sequence_axis'] = data.sequence_axis
meta_shape = meta.shape
meta_axis = {'time_axis': meta.time_axis, 'data_axis': meta.data_axis}
if hasattr(meta, 'sequence_axis'):
meta_axis['sequence_axis'] = meta.sequence_axis
logger = FancyLogger()
logger.line('Data', indent=print_indent)
logger.data(field='Matrix shape', value=X.shape, indent=(print_indent + 2))
logger.data(field='Item shape', value=data_shape, indent=(print_indent + 2))
logger.data(field='Time', value=data_shape[data_axis['time_axis']], indent=(print_indent + 4))
logger.data(field='Data', value=data_shape[data_axis['data_axis']], indent=(print_indent + 4))
if ('sequence_axis' in data_axis):
logger.data(field='Sequence', value=data_shape[data_axis['sequence_axis']], indent=(print_indent + 4))
logger.line('Meta', indent=print_indent)
logger.data(field='Matrix shape', value=Y.shape, indent=(print_indent + 2))
logger.data(field='Item shape', value=meta_shape, indent=(print_indent + 2))
logger.data(field='Time', value=meta_shape[meta_axis['time_axis']], indent=(print_indent + 4))
logger.data(field='Data', value=meta_shape[meta_axis['data_axis']], indent=(print_indent + 4))
if ('sequence_axis' in meta_axis):
logger.data(field='Sequence', value=meta_shape[meta_axis['sequence_axis']], indent=(print_indent + 4))
return (X, Y, data_size) | 8,201,264,136,872,432,000 | Data collector
Collects data and meta into matrices while processing them through processing chains.
Parameters
----------
item_list : list or dict
Items in the data sequence. List containing multi-level dictionary with first level key
'data' and 'meta'. Second level should contain parameters for process method in the processing chain.
Default value None
data_processing_chain : ProcessingChain
Data processing chain.
Default value None
meta_processing_chain : ProcessingChain
Meta processing chain.
Default value None
channel_dimension : str
Controls where channel dimension should be added. Similar to Keras data format parameter.
If None given, no channel dimension is added.
Possible values [None, 'channels_first', 'channels_last']
Default value None
target_format : str
Meta data interpretation in the relation to the data items.
Default value 'single_target_per_segment'
verbose : bool
Print information about the data
Default value True
print_indent : int
Default value 2
Returns
-------
numpy.ndarray
data
numpy.ndarray
meta
dict
data size information | venv/Lib/site-packages/dcase_util/keras/data.py | data_collector | AlexBruBuxo/TFG--ASC-Deep-Learning | python | def data_collector(item_list=None, data_processing_chain=None, meta_processing_chain=None, target_format='single_target_per_sequence', channel_dimension='channels_last', verbose=True, print_indent=2):
"Data collector\n\n Collects data and meta into matrices while processing them through processing chains.\n\n Parameters\n ----------\n item_list : list or dict\n Items in the data sequence. List containing multi-level dictionary with first level key\n 'data' and 'meta'. Second level should contain parameters for process method in the processing chain.\n Default value None\n\n data_processing_chain : ProcessingChain\n Data processing chain.\n Default value None\n\n meta_processing_chain : ProcessingChain\n Meta processing chain.\n Default value None\n\n channel_dimension : str\n Controls where channel dimension should be added. Similar to Keras data format parameter.\n If None given, no channel dimension is added.\n Possible values [None, 'channels_first', 'channels_last']\n Default value None\n\n target_format : str\n Meta data interpretation in the relation to the data items.\n Default value 'single_target_per_segment'\n\n verbose : bool\n Print information about the data\n Default value True\n\n print_indent : int\n Default value 2\n\n Returns\n -------\n numpy.ndarray\n data\n\n numpy.ndarray\n meta\n\n dict\n data size information\n\n "
if item_list:
X = []
Y = []
for item in item_list:
data = data_processing_chain.process(**item['data'])
meta = meta_processing_chain.process(**item['meta'])
X.append(data.data)
if (target_format == 'single_target_per_sequence'):
for i in range(0, data.shape[data.sequence_axis]):
Y.append(meta.data[:, 0])
elif (target_format == 'same'):
Y.append(numpy.repeat(a=meta.data, repeats=data.length, axis=1).T)
data_size = {}
if (len(data.shape) == 2):
if (data.time_axis == 0):
X = numpy.vstack(X)
Y = numpy.vstack(Y)
else:
X = numpy.hstack(X)
Y = numpy.hstack(Y)
data_size = {'data': X.shape[data.data_axis], 'time': X.shape[data.time_axis]}
elif (len(data.shape) == 3):
if (data.sequence_axis == 0):
X = numpy.vstack(X)
Y = numpy.vstack(Y)
elif (data.sequence_axis == 1):
X = numpy.hstack(X)
Y = numpy.hstack(Y)
elif (data.sequence_axis == 2):
X = numpy.dstack(X)
Y = numpy.dstack(Y)
if channel_dimension:
if (channel_dimension == 'channels_first'):
X = numpy.expand_dims(X, axis=1)
elif (channel_dimension == 'channels_last'):
X = numpy.expand_dims(X, axis=3)
data_size = {'data': X.shape[data.data_axis], 'time': X.shape[data.time_axis], 'sequence': X.shape[data.sequence_axis]}
if verbose:
data_shape = data.shape
data_axis = {'time_axis': data.time_axis, 'data_axis': data.data_axis}
if hasattr(data, 'sequence_axis'):
data_axis['sequence_axis'] = data.sequence_axis
meta_shape = meta.shape
meta_axis = {'time_axis': meta.time_axis, 'data_axis': meta.data_axis}
if hasattr(meta, 'sequence_axis'):
meta_axis['sequence_axis'] = meta.sequence_axis
logger = FancyLogger()
logger.line('Data', indent=print_indent)
logger.data(field='Matrix shape', value=X.shape, indent=(print_indent + 2))
logger.data(field='Item shape', value=data_shape, indent=(print_indent + 2))
logger.data(field='Time', value=data_shape[data_axis['time_axis']], indent=(print_indent + 4))
logger.data(field='Data', value=data_shape[data_axis['data_axis']], indent=(print_indent + 4))
if ('sequence_axis' in data_axis):
logger.data(field='Sequence', value=data_shape[data_axis['sequence_axis']], indent=(print_indent + 4))
logger.line('Meta', indent=print_indent)
logger.data(field='Matrix shape', value=Y.shape, indent=(print_indent + 2))
logger.data(field='Item shape', value=meta_shape, indent=(print_indent + 2))
logger.data(field='Time', value=meta_shape[meta_axis['time_axis']], indent=(print_indent + 4))
logger.data(field='Data', value=meta_shape[meta_axis['data_axis']], indent=(print_indent + 4))
if ('sequence_axis' in meta_axis):
logger.data(field='Sequence', value=meta_shape[meta_axis['sequence_axis']], indent=(print_indent + 4))
return (X, Y, data_size) |
def __init__(self, item_list=None, batch_size=64, buffer_size=None, data_processing_chain=None, meta_processing_chain=None, data_processing_chain_callback_on_epoch_end=None, meta_processing_chain_callback_on_epoch_end=None, transformer_callbacks=None, refresh_buffer_on_epoch=False, data_format='channels_last', target_format='single_target_per_sequence', **kwargs):
"Constructor\n\n Parameters\n ----------\n item_list : list or dict\n Items in the data sequence. List containing multi-level dictionary with first level key\n 'data' and 'meta'. Second level should contain parameters for process method in the processing chain.\n Default value None\n\n batch_size : int\n Batch size (item count).\n Default value 64\n\n buffer_size : int\n Internal buffer size (item count). By setting this sufficiently high, data sequence generator can\n possibly fit all sequence items into internal buffer and can fetch without loading from disk.\n Set to None, if no internal buffer used.\n Default value None\n\n data_processing_chain : ProcessingChain\n Data processing chain.\n Default value None\n\n meta_processing_chain : ProcessingChain\n Meta processing chain.\n Default value None\n\n data_processing_chain_callback_on_epoch_end : list of dict\n Can be used to call methods with parameters for processing chain at the end of epoch. This can be\n used to control processing chain's internal status (e.g. roll the data).\n Default value None\n\n meta_processing_chain_callback_on_epoch_end : list of dict\n Can be used to call methods with parameters for processing chain at the end of epoch. This can be\n used to control processing chain's internal status (e.g. roll the data).\n Default value None\n\n transformer_callbacks : list of func\n Transformer callbacks to jointly process data and meta. This can be used for local data modification and\n data augmentation.\n Default value None\n\n refresh_buffer_on_epoch : bool\n In case internal data buffer is used, force data and meta refresh at the end of each epoch. Use this if\n data is modified/augmented differently for each epoch.\n In case data_processing_chain_callback_on_epoch_end or meta_processing_chain_callback_on_epoch_end is\n used, this parameter is automatically set to True.\n Default value False\n\n data_format : str\n Keras like data format, controls where channel should be added.\n Possible values ['channels_first', 'channels_last']\n Default value 'channels_last'\n\n target_format : str\n Meta data interpretation in the relation to the data items.\n Default value 'single_target_per_segment'\n\n "
ContainerMixin.__init__(self, **kwargs)
self._data_shape = None
self._data_axis = None
self.item_list = copy.copy(item_list)
self.batch_size = batch_size
self.buffer_size = buffer_size
self.data_refresh_on_epoch = refresh_buffer_on_epoch
if (data_format is None):
data_format = 'channels_last'
self.data_format = data_format
if (self.data_format not in ['channels_first', 'channels_last']):
message = '{name}: Unknown data_format [{data_format}].'.format(name=self.__class__.__name__, data_format=self.data_format)
self.logger.exception(message)
raise NotImplementedError(message)
if (target_format is None):
target_format = 'single_target_per_sequence'
self.target_format = target_format
if (self.target_format not in ['same', 'single_target_per_sequence']):
message = '{name}: Unknown target_format [{target_format}].'.format(name=self.__class__.__name__, target_format=self.target_format)
self.logger.exception(message)
raise NotImplementedError(message)
if (data_processing_chain_callback_on_epoch_end is None):
data_processing_chain_callback_on_epoch_end = []
self.data_processing_chain_callback_on_epoch_end = data_processing_chain_callback_on_epoch_end
if self.data_processing_chain_callback_on_epoch_end:
self.data_refresh_on_epoch = True
if (meta_processing_chain_callback_on_epoch_end is None):
meta_processing_chain_callback_on_epoch_end = []
self.meta_processing_chain_callback_on_epoch_end = meta_processing_chain_callback_on_epoch_end
if (transformer_callbacks is None):
transformer_callbacks = []
self.transformer_callbacks = transformer_callbacks
self.data_processing_chain = data_processing_chain
self.meta_processing_chain = meta_processing_chain
if (self.buffer_size is not None):
self.data_buffer = DataBuffer(size=self.buffer_size)
else:
self.data_buffer = None | -436,798,435,833,156,350 | Constructor
Parameters
----------
item_list : list or dict
Items in the data sequence. List containing multi-level dictionary with first level key
'data' and 'meta'. Second level should contain parameters for process method in the processing chain.
Default value None
batch_size : int
Batch size (item count).
Default value 64
buffer_size : int
Internal buffer size (item count). By setting this sufficiently high, data sequence generator can
possibly fit all sequence items into internal buffer and can fetch without loading from disk.
Set to None, if no internal buffer used.
Default value None
data_processing_chain : ProcessingChain
Data processing chain.
Default value None
meta_processing_chain : ProcessingChain
Meta processing chain.
Default value None
data_processing_chain_callback_on_epoch_end : list of dict
Can be used to call methods with parameters for processing chain at the end of epoch. This can be
used to control processing chain's internal status (e.g. roll the data).
Default value None
meta_processing_chain_callback_on_epoch_end : list of dict
Can be used to call methods with parameters for processing chain at the end of epoch. This can be
used to control processing chain's internal status (e.g. roll the data).
Default value None
transformer_callbacks : list of func
Transformer callbacks to jointly process data and meta. This can be used for local data modification and
data augmentation.
Default value None
refresh_buffer_on_epoch : bool
In case internal data buffer is used, force data and meta refresh at the end of each epoch. Use this if
data is modified/augmented differently for each epoch.
In case data_processing_chain_callback_on_epoch_end or meta_processing_chain_callback_on_epoch_end is
used, this parameter is automatically set to True.
Default value False
data_format : str
Keras like data format, controls where channel should be added.
Possible values ['channels_first', 'channels_last']
Default value 'channels_last'
target_format : str
Meta data interpretation in the relation to the data items.
Default value 'single_target_per_segment' | venv/Lib/site-packages/dcase_util/keras/data.py | __init__ | AlexBruBuxo/TFG--ASC-Deep-Learning | python | def __init__(self, item_list=None, batch_size=64, buffer_size=None, data_processing_chain=None, meta_processing_chain=None, data_processing_chain_callback_on_epoch_end=None, meta_processing_chain_callback_on_epoch_end=None, transformer_callbacks=None, refresh_buffer_on_epoch=False, data_format='channels_last', target_format='single_target_per_sequence', **kwargs):
"Constructor\n\n Parameters\n ----------\n item_list : list or dict\n Items in the data sequence. List containing multi-level dictionary with first level key\n 'data' and 'meta'. Second level should contain parameters for process method in the processing chain.\n Default value None\n\n batch_size : int\n Batch size (item count).\n Default value 64\n\n buffer_size : int\n Internal buffer size (item count). By setting this sufficiently high, data sequence generator can\n possibly fit all sequence items into internal buffer and can fetch without loading from disk.\n Set to None, if no internal buffer used.\n Default value None\n\n data_processing_chain : ProcessingChain\n Data processing chain.\n Default value None\n\n meta_processing_chain : ProcessingChain\n Meta processing chain.\n Default value None\n\n data_processing_chain_callback_on_epoch_end : list of dict\n Can be used to call methods with parameters for processing chain at the end of epoch. This can be\n used to control processing chain's internal status (e.g. roll the data).\n Default value None\n\n meta_processing_chain_callback_on_epoch_end : list of dict\n Can be used to call methods with parameters for processing chain at the end of epoch. This can be\n used to control processing chain's internal status (e.g. roll the data).\n Default value None\n\n transformer_callbacks : list of func\n Transformer callbacks to jointly process data and meta. This can be used for local data modification and\n data augmentation.\n Default value None\n\n refresh_buffer_on_epoch : bool\n In case internal data buffer is used, force data and meta refresh at the end of each epoch. Use this if\n data is modified/augmented differently for each epoch.\n In case data_processing_chain_callback_on_epoch_end or meta_processing_chain_callback_on_epoch_end is\n used, this parameter is automatically set to True.\n Default value False\n\n data_format : str\n Keras like data format, controls where channel should be added.\n Possible values ['channels_first', 'channels_last']\n Default value 'channels_last'\n\n target_format : str\n Meta data interpretation in the relation to the data items.\n Default value 'single_target_per_segment'\n\n "
ContainerMixin.__init__(self, **kwargs)
self._data_shape = None
self._data_axis = None
self.item_list = copy.copy(item_list)
self.batch_size = batch_size
self.buffer_size = buffer_size
self.data_refresh_on_epoch = refresh_buffer_on_epoch
if (data_format is None):
data_format = 'channels_last'
self.data_format = data_format
if (self.data_format not in ['channels_first', 'channels_last']):
message = '{name}: Unknown data_format [{data_format}].'.format(name=self.__class__.__name__, data_format=self.data_format)
self.logger.exception(message)
raise NotImplementedError(message)
if (target_format is None):
target_format = 'single_target_per_sequence'
self.target_format = target_format
if (self.target_format not in ['same', 'single_target_per_sequence']):
message = '{name}: Unknown target_format [{target_format}].'.format(name=self.__class__.__name__, target_format=self.target_format)
self.logger.exception(message)
raise NotImplementedError(message)
if (data_processing_chain_callback_on_epoch_end is None):
data_processing_chain_callback_on_epoch_end = []
self.data_processing_chain_callback_on_epoch_end = data_processing_chain_callback_on_epoch_end
if self.data_processing_chain_callback_on_epoch_end:
self.data_refresh_on_epoch = True
if (meta_processing_chain_callback_on_epoch_end is None):
meta_processing_chain_callback_on_epoch_end = []
self.meta_processing_chain_callback_on_epoch_end = meta_processing_chain_callback_on_epoch_end
if (transformer_callbacks is None):
transformer_callbacks = []
self.transformer_callbacks = transformer_callbacks
self.data_processing_chain = data_processing_chain
self.meta_processing_chain = meta_processing_chain
if (self.buffer_size is not None):
self.data_buffer = DataBuffer(size=self.buffer_size)
else:
self.data_buffer = None |
def main(json_dir, out_dir):
' Script to convert all .json files in json_dir into corresponding .mat\n files in out_dir\n\n .mat files have the same basename as the .json files\n\n This script is meant for data files that contain data from\n OpenSauce / VoiceSauce variables.\n '
json_files = glob.glob(os.path.join(json_dir, '*.json'))
for json_file in json_files:
with open(json_file) as f:
json_dict = json.load(f)
if (not os.path.isdir(out_dir)):
os.makedirs(out_dir)
fn = (os.path.join(out_dir, os.path.splitext(os.path.basename(json_file))[0]) + '.mat')
savemat(fn, json_dict)
print('Wrote data in {} to {}'.format(json_file, fn)) | 6,966,082,690,874,818,000 | Script to convert all .json files in json_dir into corresponding .mat
files in out_dir
.mat files have the same basename as the .json files
This script is meant for data files that contain data from
OpenSauce / VoiceSauce variables. | tools/convert_json_to_mat.py | main | CobiELF/opensauce-python | python | def main(json_dir, out_dir):
' Script to convert all .json files in json_dir into corresponding .mat\n files in out_dir\n\n .mat files have the same basename as the .json files\n\n This script is meant for data files that contain data from\n OpenSauce / VoiceSauce variables.\n '
json_files = glob.glob(os.path.join(json_dir, '*.json'))
for json_file in json_files:
with open(json_file) as f:
json_dict = json.load(f)
if (not os.path.isdir(out_dir)):
os.makedirs(out_dir)
fn = (os.path.join(out_dir, os.path.splitext(os.path.basename(json_file))[0]) + '.mat')
savemat(fn, json_dict)
print('Wrote data in {} to {}'.format(json_file, fn)) |
def __str__(self):
'Print function displays username.'
return self.title | -8,196,650,801,646,137,000 | Print function displays username. | imagersite/imager_images/models.py | __str__ | Loaye/django-imager-group | python | def __str__(self):
return self.title |
def __str__(self):
'Print function displays username.'
return self.title | -8,196,650,801,646,137,000 | Print function displays username. | imagersite/imager_images/models.py | __str__ | Loaye/django-imager-group | python | def __str__(self):
return self.title |
async def fetch_time(self, params={}):
'\n fetches the current integer timestamp in milliseconds from the exchange server\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns int: the current integer timestamp in milliseconds from the exchange server\n '
response = (await self.publicGetTime(params))
return self.safe_integer(response, 'time') | 4,727,720,431,297,713,000 | fetches the current integer timestamp in milliseconds from the exchange server
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns int: the current integer timestamp in milliseconds from the exchange server | python/ccxt/async_support/bitvavo.py | fetch_time | DoctorSlimm/ccxt | python | async def fetch_time(self, params={}):
'\n fetches the current integer timestamp in milliseconds from the exchange server\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns int: the current integer timestamp in milliseconds from the exchange server\n '
response = (await self.publicGetTime(params))
return self.safe_integer(response, 'time') |
async def fetch_markets(self, params={}):
'\n retrieves data on all markets for bitvavo\n :param dict params: extra parameters specific to the exchange api endpoint\n :returns [dict]: an array of objects representing market data\n '
response = (await self.publicGetMarkets(params))
currencies = (await self.fetch_currencies_from_cache(params))
currenciesById = self.index_by(currencies, 'symbol')
result = []
for i in range(0, len(response)):
market = response[i]
id = self.safe_string(market, 'market')
baseId = self.safe_string(market, 'base')
quoteId = self.safe_string(market, 'quote')
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
status = self.safe_string(market, 'status')
baseCurrency = self.safe_value(currenciesById, baseId)
amountPrecision = None
if (baseCurrency is not None):
amountPrecision = self.safe_integer(baseCurrency, 'decimals', 8)
result.append({'id': id, 'symbol': ((base + '/') + quote), 'base': base, 'quote': quote, 'settle': None, 'baseId': baseId, 'quoteId': quoteId, 'settleId': None, 'type': 'spot', 'spot': True, 'margin': False, 'swap': False, 'future': False, 'option': False, 'active': (status == 'trading'), 'contract': False, 'linear': None, 'inverse': None, 'contractSize': None, 'expiry': None, 'expiryDatetime': None, 'strike': None, 'optionType': None, 'precision': {'amount': amountPrecision, 'price': self.safe_integer(market, 'pricePrecision')}, 'limits': {'leverage': {'min': None, 'max': None}, 'amount': {'min': self.safe_number(market, 'minOrderInBaseAsset'), 'max': None}, 'price': {'min': None, 'max': None}, 'cost': {'min': self.safe_number(market, 'minOrderInQuoteAsset'), 'max': None}}, 'info': market})
return result | -8,583,666,571,276,738,000 | retrieves data on all markets for bitvavo
:param dict params: extra parameters specific to the exchange api endpoint
:returns [dict]: an array of objects representing market data | python/ccxt/async_support/bitvavo.py | fetch_markets | DoctorSlimm/ccxt | python | async def fetch_markets(self, params={}):
'\n retrieves data on all markets for bitvavo\n :param dict params: extra parameters specific to the exchange api endpoint\n :returns [dict]: an array of objects representing market data\n '
response = (await self.publicGetMarkets(params))
currencies = (await self.fetch_currencies_from_cache(params))
currenciesById = self.index_by(currencies, 'symbol')
result = []
for i in range(0, len(response)):
market = response[i]
id = self.safe_string(market, 'market')
baseId = self.safe_string(market, 'base')
quoteId = self.safe_string(market, 'quote')
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
status = self.safe_string(market, 'status')
baseCurrency = self.safe_value(currenciesById, baseId)
amountPrecision = None
if (baseCurrency is not None):
amountPrecision = self.safe_integer(baseCurrency, 'decimals', 8)
result.append({'id': id, 'symbol': ((base + '/') + quote), 'base': base, 'quote': quote, 'settle': None, 'baseId': baseId, 'quoteId': quoteId, 'settleId': None, 'type': 'spot', 'spot': True, 'margin': False, 'swap': False, 'future': False, 'option': False, 'active': (status == 'trading'), 'contract': False, 'linear': None, 'inverse': None, 'contractSize': None, 'expiry': None, 'expiryDatetime': None, 'strike': None, 'optionType': None, 'precision': {'amount': amountPrecision, 'price': self.safe_integer(market, 'pricePrecision')}, 'limits': {'leverage': {'min': None, 'max': None}, 'amount': {'min': self.safe_number(market, 'minOrderInBaseAsset'), 'max': None}, 'price': {'min': None, 'max': None}, 'cost': {'min': self.safe_number(market, 'minOrderInQuoteAsset'), 'max': None}}, 'info': market})
return result |
async def fetch_currencies(self, params={}):
'\n fetches all available currencies on an exchange\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: an associative dictionary of currencies\n '
response = (await self.fetch_currencies_from_cache(params))
result = {}
for i in range(0, len(response)):
currency = response[i]
id = self.safe_string(currency, 'symbol')
code = self.safe_currency_code(id)
depositStatus = self.safe_value(currency, 'depositStatus')
deposit = (depositStatus == 'OK')
withdrawalStatus = self.safe_value(currency, 'withdrawalStatus')
withdrawal = (withdrawalStatus == 'OK')
active = (deposit and withdrawal)
name = self.safe_string(currency, 'name')
precision = self.safe_integer(currency, 'decimals', 8)
result[code] = {'id': id, 'info': currency, 'code': code, 'name': name, 'active': active, 'deposit': deposit, 'withdraw': withdrawal, 'fee': self.safe_number(currency, 'withdrawalFee'), 'precision': precision, 'limits': {'amount': {'min': None, 'max': None}, 'withdraw': {'min': self.safe_number(currency, 'withdrawalMinAmount'), 'max': None}}}
return result | 3,034,382,448,980,844,000 | fetches all available currencies on an exchange
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns dict: an associative dictionary of currencies | python/ccxt/async_support/bitvavo.py | fetch_currencies | DoctorSlimm/ccxt | python | async def fetch_currencies(self, params={}):
'\n fetches all available currencies on an exchange\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: an associative dictionary of currencies\n '
response = (await self.fetch_currencies_from_cache(params))
result = {}
for i in range(0, len(response)):
currency = response[i]
id = self.safe_string(currency, 'symbol')
code = self.safe_currency_code(id)
depositStatus = self.safe_value(currency, 'depositStatus')
deposit = (depositStatus == 'OK')
withdrawalStatus = self.safe_value(currency, 'withdrawalStatus')
withdrawal = (withdrawalStatus == 'OK')
active = (deposit and withdrawal)
name = self.safe_string(currency, 'name')
precision = self.safe_integer(currency, 'decimals', 8)
result[code] = {'id': id, 'info': currency, 'code': code, 'name': name, 'active': active, 'deposit': deposit, 'withdraw': withdrawal, 'fee': self.safe_number(currency, 'withdrawalFee'), 'precision': precision, 'limits': {'amount': {'min': None, 'max': None}, 'withdraw': {'min': self.safe_number(currency, 'withdrawalMinAmount'), 'max': None}}}
return result |
async def fetch_ticker(self, symbol, params={}):
'\n fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market\n :param str symbol: unified symbol of the market to fetch the ticker for\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`\n '
(await self.load_markets())
market = self.market(symbol)
request = {'market': market['id']}
response = (await self.publicGetTicker24h(self.extend(request, params)))
return self.parse_ticker(response, market) | -6,137,170,768,951,819,000 | fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
:param str symbol: unified symbol of the market to fetch the ticker for
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>` | python/ccxt/async_support/bitvavo.py | fetch_ticker | DoctorSlimm/ccxt | python | async def fetch_ticker(self, symbol, params={}):
'\n fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market\n :param str symbol: unified symbol of the market to fetch the ticker for\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`\n '
(await self.load_markets())
market = self.market(symbol)
request = {'market': market['id']}
response = (await self.publicGetTicker24h(self.extend(request, params)))
return self.parse_ticker(response, market) |
async def fetch_tickers(self, symbols=None, params={}):
'\n fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market\n :param [str]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: an array of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`\n '
(await self.load_markets())
response = (await self.publicGetTicker24h(params))
return self.parse_tickers(response, symbols) | -7,503,686,667,502,880,000 | fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market
:param [str]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns dict: an array of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>` | python/ccxt/async_support/bitvavo.py | fetch_tickers | DoctorSlimm/ccxt | python | async def fetch_tickers(self, symbols=None, params={}):
'\n fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market\n :param [str]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: an array of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`\n '
(await self.load_markets())
response = (await self.publicGetTicker24h(params))
return self.parse_tickers(response, symbols) |
async def fetch_trades(self, symbol, since=None, limit=None, params={}):
'\n get the list of most recent trades for a particular symbol\n :param str symbol: unified symbol of the market to fetch trades for\n :param int|None since: timestamp in ms of the earliest trade to fetch\n :param int|None limit: the maximum amount of trades to fetch\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>`\n '
(await self.load_markets())
market = self.market(symbol)
request = {'market': market['id']}
if (limit is not None):
request['limit'] = limit
if (since is not None):
request['start'] = since
response = (await self.publicGetMarketTrades(self.extend(request, params)))
return self.parse_trades(response, market, since, limit) | -6,750,279,957,478,437,000 | get the list of most recent trades for a particular symbol
:param str symbol: unified symbol of the market to fetch trades for
:param int|None since: timestamp in ms of the earliest trade to fetch
:param int|None limit: the maximum amount of trades to fetch
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>` | python/ccxt/async_support/bitvavo.py | fetch_trades | DoctorSlimm/ccxt | python | async def fetch_trades(self, symbol, since=None, limit=None, params={}):
'\n get the list of most recent trades for a particular symbol\n :param str symbol: unified symbol of the market to fetch trades for\n :param int|None since: timestamp in ms of the earliest trade to fetch\n :param int|None limit: the maximum amount of trades to fetch\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>`\n '
(await self.load_markets())
market = self.market(symbol)
request = {'market': market['id']}
if (limit is not None):
request['limit'] = limit
if (since is not None):
request['start'] = since
response = (await self.publicGetMarketTrades(self.extend(request, params)))
return self.parse_trades(response, market, since, limit) |
async def fetch_trading_fees(self, params={}):
'\n fetch the trading fees for multiple markets\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/en/latest/manual.html#fee-structure>` indexed by market symbols\n '
(await self.load_markets())
response = (await self.privateGetAccount(params))
fees = self.safe_value(response, 'fees')
maker = self.safe_number(fees, 'maker')
taker = self.safe_number(fees, 'taker')
result = {}
for i in range(0, len(self.symbols)):
symbol = self.symbols[i]
result[symbol] = {'info': response, 'symbol': symbol, 'maker': maker, 'taker': taker, 'percentage': True, 'tierBased': True}
return result | -2,611,278,846,379,126,000 | fetch the trading fees for multiple markets
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns dict: a dictionary of `fee structures <https://docs.ccxt.com/en/latest/manual.html#fee-structure>` indexed by market symbols | python/ccxt/async_support/bitvavo.py | fetch_trading_fees | DoctorSlimm/ccxt | python | async def fetch_trading_fees(self, params={}):
'\n fetch the trading fees for multiple markets\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/en/latest/manual.html#fee-structure>` indexed by market symbols\n '
(await self.load_markets())
response = (await self.privateGetAccount(params))
fees = self.safe_value(response, 'fees')
maker = self.safe_number(fees, 'maker')
taker = self.safe_number(fees, 'taker')
result = {}
for i in range(0, len(self.symbols)):
symbol = self.symbols[i]
result[symbol] = {'info': response, 'symbol': symbol, 'maker': maker, 'taker': taker, 'percentage': True, 'tierBased': True}
return result |
async def fetch_order_book(self, symbol, limit=None, params={}):
'\n fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data\n :param str symbol: unified symbol of the market to fetch the order book for\n :param int|None limit: the maximum amount of order book entries to return\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols\n '
(await self.load_markets())
request = {'market': self.market_id(symbol)}
if (limit is not None):
request['depth'] = limit
response = (await self.publicGetMarketBook(self.extend(request, params)))
orderbook = self.parse_order_book(response, symbol)
orderbook['nonce'] = self.safe_integer(response, 'nonce')
return orderbook | -6,137,599,076,384,609,000 | fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
:param str symbol: unified symbol of the market to fetch the order book for
:param int|None limit: the maximum amount of order book entries to return
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols | python/ccxt/async_support/bitvavo.py | fetch_order_book | DoctorSlimm/ccxt | python | async def fetch_order_book(self, symbol, limit=None, params={}):
'\n fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data\n :param str symbol: unified symbol of the market to fetch the order book for\n :param int|None limit: the maximum amount of order book entries to return\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols\n '
(await self.load_markets())
request = {'market': self.market_id(symbol)}
if (limit is not None):
request['depth'] = limit
response = (await self.publicGetMarketBook(self.extend(request, params)))
orderbook = self.parse_order_book(response, symbol)
orderbook['nonce'] = self.safe_integer(response, 'nonce')
return orderbook |
async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
'\n fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market\n :param str symbol: unified symbol of the market to fetch OHLCV data for\n :param str timeframe: the length of time each candle represents\n :param int|None since: timestamp in ms of the earliest candle to fetch\n :param int|None limit: the maximum amount of candles to fetch\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume\n '
(await self.load_markets())
market = self.market(symbol)
request = {'market': market['id'], 'interval': self.timeframes[timeframe]}
if (since is not None):
duration = self.parse_timeframe(timeframe)
request['start'] = since
if (limit is None):
limit = 1440
request['end'] = self.sum(since, ((limit * duration) * 1000))
if (limit is not None):
request['limit'] = limit
response = (await self.publicGetMarketCandles(self.extend(request, params)))
return self.parse_ohlcvs(response, market, timeframe, since, limit) | -4,359,227,001,451,613,700 | fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
:param str symbol: unified symbol of the market to fetch OHLCV data for
:param str timeframe: the length of time each candle represents
:param int|None since: timestamp in ms of the earliest candle to fetch
:param int|None limit: the maximum amount of candles to fetch
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume | python/ccxt/async_support/bitvavo.py | fetch_ohlcv | DoctorSlimm/ccxt | python | async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
'\n fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market\n :param str symbol: unified symbol of the market to fetch OHLCV data for\n :param str timeframe: the length of time each candle represents\n :param int|None since: timestamp in ms of the earliest candle to fetch\n :param int|None limit: the maximum amount of candles to fetch\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume\n '
(await self.load_markets())
market = self.market(symbol)
request = {'market': market['id'], 'interval': self.timeframes[timeframe]}
if (since is not None):
duration = self.parse_timeframe(timeframe)
request['start'] = since
if (limit is None):
limit = 1440
request['end'] = self.sum(since, ((limit * duration) * 1000))
if (limit is not None):
request['limit'] = limit
response = (await self.publicGetMarketCandles(self.extend(request, params)))
return self.parse_ohlcvs(response, market, timeframe, since, limit) |
async def fetch_balance(self, params={}):
'\n query for balance and get the amount of funds available for trading or funds locked in orders\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`\n '
(await self.load_markets())
response = (await self.privateGetBalance(params))
return self.parse_balance(response) | -4,888,217,278,312,201,000 | query for balance and get the amount of funds available for trading or funds locked in orders
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>` | python/ccxt/async_support/bitvavo.py | fetch_balance | DoctorSlimm/ccxt | python | async def fetch_balance(self, params={}):
'\n query for balance and get the amount of funds available for trading or funds locked in orders\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`\n '
(await self.load_markets())
response = (await self.privateGetBalance(params))
return self.parse_balance(response) |
async def fetch_deposit_address(self, code, params={}):
'\n fetch the deposit address for a currency associated with self account\n :param str code: unified currency code\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`\n '
(await self.load_markets())
currency = self.currency(code)
request = {'symbol': currency['id']}
response = (await self.privateGetDeposit(self.extend(request, params)))
address = self.safe_string(response, 'address')
tag = self.safe_string(response, 'paymentId')
self.check_address(address)
return {'currency': code, 'address': address, 'tag': tag, 'network': None, 'info': response} | -7,805,161,392,912,422,000 | fetch the deposit address for a currency associated with self account
:param str code: unified currency code
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>` | python/ccxt/async_support/bitvavo.py | fetch_deposit_address | DoctorSlimm/ccxt | python | async def fetch_deposit_address(self, code, params={}):
'\n fetch the deposit address for a currency associated with self account\n :param str code: unified currency code\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`\n '
(await self.load_markets())
currency = self.currency(code)
request = {'symbol': currency['id']}
response = (await self.privateGetDeposit(self.extend(request, params)))
address = self.safe_string(response, 'address')
tag = self.safe_string(response, 'paymentId')
self.check_address(address)
return {'currency': code, 'address': address, 'tag': tag, 'network': None, 'info': response} |
async def create_order(self, symbol, type, side, amount, price=None, params={}):
"\n create a trade order\n :param str symbol: unified symbol of the market to create an order in\n :param str type: 'market' or 'limit'\n :param str side: 'buy' or 'sell'\n :param float amount: how much of currency you want to trade in units of base currency\n :param float price: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`\n "
(await self.load_markets())
market = self.market(symbol)
request = {'market': market['id'], 'side': side, 'orderType': type}
isStopLimit = ((type == 'stopLossLimit') or (type == 'takeProfitLimit'))
isStopMarket = ((type == 'stopLoss') or (type == 'takeProfit'))
if (type == 'market'):
cost = None
if (price is not None):
cost = (amount * price)
else:
cost = self.safe_number_2(params, 'cost', 'amountQuote')
if (cost is not None):
precision = market['precision']['price']
request['amountQuote'] = self.decimal_to_precision(cost, TRUNCATE, precision, self.precisionMode)
else:
request['amount'] = self.amount_to_precision(symbol, amount)
params = self.omit(params, ['cost', 'amountQuote'])
elif (type == 'limit'):
request['price'] = self.price_to_precision(symbol, price)
request['amount'] = self.amount_to_precision(symbol, amount)
elif (isStopMarket or isStopLimit):
stopPrice = self.safe_number_2(params, 'stopPrice', 'triggerAmount')
if (stopPrice is None):
if isStopLimit:
raise ArgumentsRequired((((self.id + ' createOrder() requires a stopPrice parameter for a ') + type) + ' order'))
elif isStopMarket:
if (price is None):
raise ArgumentsRequired((((self.id + ' createOrder() requires a price argument or a stopPrice parameter for a ') + type) + ' order'))
else:
stopPrice = price
if isStopLimit:
request['price'] = self.price_to_precision(symbol, price)
params = self.omit(params, ['stopPrice', 'triggerAmount'])
request['triggerAmount'] = self.price_to_precision(symbol, stopPrice)
request['triggerType'] = 'price'
request['amount'] = self.amount_to_precision(symbol, amount)
response = (await self.privatePostOrder(self.extend(request, params)))
return self.parse_order(response, market) | -3,071,188,071,810,781,700 | create a trade order
:param str symbol: unified symbol of the market to create an order in
:param str type: 'market' or 'limit'
:param str side: 'buy' or 'sell'
:param float amount: how much of currency you want to trade in units of base currency
:param float price: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>` | python/ccxt/async_support/bitvavo.py | create_order | DoctorSlimm/ccxt | python | async def create_order(self, symbol, type, side, amount, price=None, params={}):
"\n create a trade order\n :param str symbol: unified symbol of the market to create an order in\n :param str type: 'market' or 'limit'\n :param str side: 'buy' or 'sell'\n :param float amount: how much of currency you want to trade in units of base currency\n :param float price: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`\n "
(await self.load_markets())
market = self.market(symbol)
request = {'market': market['id'], 'side': side, 'orderType': type}
isStopLimit = ((type == 'stopLossLimit') or (type == 'takeProfitLimit'))
isStopMarket = ((type == 'stopLoss') or (type == 'takeProfit'))
if (type == 'market'):
cost = None
if (price is not None):
cost = (amount * price)
else:
cost = self.safe_number_2(params, 'cost', 'amountQuote')
if (cost is not None):
precision = market['precision']['price']
request['amountQuote'] = self.decimal_to_precision(cost, TRUNCATE, precision, self.precisionMode)
else:
request['amount'] = self.amount_to_precision(symbol, amount)
params = self.omit(params, ['cost', 'amountQuote'])
elif (type == 'limit'):
request['price'] = self.price_to_precision(symbol, price)
request['amount'] = self.amount_to_precision(symbol, amount)
elif (isStopMarket or isStopLimit):
stopPrice = self.safe_number_2(params, 'stopPrice', 'triggerAmount')
if (stopPrice is None):
if isStopLimit:
raise ArgumentsRequired((((self.id + ' createOrder() requires a stopPrice parameter for a ') + type) + ' order'))
elif isStopMarket:
if (price is None):
raise ArgumentsRequired((((self.id + ' createOrder() requires a price argument or a stopPrice parameter for a ') + type) + ' order'))
else:
stopPrice = price
if isStopLimit:
request['price'] = self.price_to_precision(symbol, price)
params = self.omit(params, ['stopPrice', 'triggerAmount'])
request['triggerAmount'] = self.price_to_precision(symbol, stopPrice)
request['triggerType'] = 'price'
request['amount'] = self.amount_to_precision(symbol, amount)
response = (await self.privatePostOrder(self.extend(request, params)))
return self.parse_order(response, market) |
async def cancel_order(self, id, symbol=None, params={}):
'\n cancels an open order\n :param str id: order id\n :param str symbol: unified symbol of the market the order was made in\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`\n '
if (symbol is None):
raise ArgumentsRequired((self.id + ' cancelOrder() requires a symbol argument'))
(await self.load_markets())
market = self.market(symbol)
request = {'orderId': id, 'market': market['id']}
response = (await self.privateDeleteOrder(self.extend(request, params)))
return self.parse_order(response, market) | -4,035,625,816,908,149,000 | cancels an open order
:param str id: order id
:param str symbol: unified symbol of the market the order was made in
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>` | python/ccxt/async_support/bitvavo.py | cancel_order | DoctorSlimm/ccxt | python | async def cancel_order(self, id, symbol=None, params={}):
'\n cancels an open order\n :param str id: order id\n :param str symbol: unified symbol of the market the order was made in\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`\n '
if (symbol is None):
raise ArgumentsRequired((self.id + ' cancelOrder() requires a symbol argument'))
(await self.load_markets())
market = self.market(symbol)
request = {'orderId': id, 'market': market['id']}
response = (await self.privateDeleteOrder(self.extend(request, params)))
return self.parse_order(response, market) |
async def cancel_all_orders(self, symbol=None, params={}):
'\n cancel all open orders\n :param str|None symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`\n '
(await self.load_markets())
request = {}
market = None
if (symbol is not None):
market = self.market(symbol)
request['market'] = market['id']
response = (await self.privateDeleteOrders(self.extend(request, params)))
return self.parse_orders(response, market) | -1,090,313,933,898,150,700 | cancel all open orders
:param str|None symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>` | python/ccxt/async_support/bitvavo.py | cancel_all_orders | DoctorSlimm/ccxt | python | async def cancel_all_orders(self, symbol=None, params={}):
'\n cancel all open orders\n :param str|None symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`\n '
(await self.load_markets())
request = {}
market = None
if (symbol is not None):
market = self.market(symbol)
request['market'] = market['id']
response = (await self.privateDeleteOrders(self.extend(request, params)))
return self.parse_orders(response, market) |
async def fetch_order(self, id, symbol=None, params={}):
'\n fetches information on an order made by the user\n :param str symbol: unified symbol of the market the order was made in\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`\n '
if (symbol is None):
raise ArgumentsRequired((self.id + ' fetchOrder() requires a symbol argument'))
(await self.load_markets())
market = self.market(symbol)
request = {'orderId': id, 'market': market['id']}
response = (await self.privateGetOrder(self.extend(request, params)))
return self.parse_order(response, market) | 6,079,850,510,680,083,000 | fetches information on an order made by the user
:param str symbol: unified symbol of the market the order was made in
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>` | python/ccxt/async_support/bitvavo.py | fetch_order | DoctorSlimm/ccxt | python | async def fetch_order(self, id, symbol=None, params={}):
'\n fetches information on an order made by the user\n :param str symbol: unified symbol of the market the order was made in\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`\n '
if (symbol is None):
raise ArgumentsRequired((self.id + ' fetchOrder() requires a symbol argument'))
(await self.load_markets())
market = self.market(symbol)
request = {'orderId': id, 'market': market['id']}
response = (await self.privateGetOrder(self.extend(request, params)))
return self.parse_order(response, market) |
async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
'\n fetch all unfilled currently open orders\n :param str|None symbol: unified market symbol\n :param int|None since: the earliest time in ms to fetch open orders for\n :param int|None limit: the maximum number of open orders structures to retrieve\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`\n '
(await self.load_markets())
request = {}
market = None
if (symbol is not None):
market = self.market(symbol)
request['market'] = market['id']
response = (await self.privateGetOrdersOpen(self.extend(request, params)))
return self.parse_orders(response, market, since, limit) | -8,882,759,450,574,307,000 | fetch all unfilled currently open orders
:param str|None symbol: unified market symbol
:param int|None since: the earliest time in ms to fetch open orders for
:param int|None limit: the maximum number of open orders structures to retrieve
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>` | python/ccxt/async_support/bitvavo.py | fetch_open_orders | DoctorSlimm/ccxt | python | async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
'\n fetch all unfilled currently open orders\n :param str|None symbol: unified market symbol\n :param int|None since: the earliest time in ms to fetch open orders for\n :param int|None limit: the maximum number of open orders structures to retrieve\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`\n '
(await self.load_markets())
request = {}
market = None
if (symbol is not None):
market = self.market(symbol)
request['market'] = market['id']
response = (await self.privateGetOrdersOpen(self.extend(request, params)))
return self.parse_orders(response, market, since, limit) |
async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
'\n fetch all trades made by the user\n :param str|None symbol: unified market symbol\n :param int|None since: the earliest time in ms to fetch trades for\n :param int|None limit: the maximum number of trades structures to retrieve\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`\n '
if (symbol is None):
raise ArgumentsRequired((self.id + ' fetchMyTrades() requires a symbol argument'))
(await self.load_markets())
market = self.market(symbol)
request = {'market': market['id']}
if (since is not None):
request['start'] = since
if (limit is not None):
request['limit'] = limit
response = (await self.privateGetTrades(self.extend(request, params)))
return self.parse_trades(response, market, since, limit) | 5,100,821,919,391,181,000 | fetch all trades made by the user
:param str|None symbol: unified market symbol
:param int|None since: the earliest time in ms to fetch trades for
:param int|None limit: the maximum number of trades structures to retrieve
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>` | python/ccxt/async_support/bitvavo.py | fetch_my_trades | DoctorSlimm/ccxt | python | async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
'\n fetch all trades made by the user\n :param str|None symbol: unified market symbol\n :param int|None since: the earliest time in ms to fetch trades for\n :param int|None limit: the maximum number of trades structures to retrieve\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`\n '
if (symbol is None):
raise ArgumentsRequired((self.id + ' fetchMyTrades() requires a symbol argument'))
(await self.load_markets())
market = self.market(symbol)
request = {'market': market['id']}
if (since is not None):
request['start'] = since
if (limit is not None):
request['limit'] = limit
response = (await self.privateGetTrades(self.extend(request, params)))
return self.parse_trades(response, market, since, limit) |
async def withdraw(self, code, amount, address, tag=None, params={}):
'\n make a withdrawal\n :param str code: unified currency code\n :param float amount: the amount to withdraw\n :param str address: the address to withdraw to\n :param str|None tag:\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: a `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`\n '
(tag, params) = self.handle_withdraw_tag_and_params(tag, params)
self.check_address(address)
(await self.load_markets())
currency = self.currency(code)
request = {'symbol': currency['id'], 'amount': self.currency_to_precision(code, amount), 'address': address}
if (tag is not None):
request['paymentId'] = tag
response = (await self.privatePostWithdrawal(self.extend(request, params)))
return self.parse_transaction(response, currency) | 4,381,774,155,091,937,300 | make a withdrawal
:param str code: unified currency code
:param float amount: the amount to withdraw
:param str address: the address to withdraw to
:param str|None tag:
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns dict: a `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>` | python/ccxt/async_support/bitvavo.py | withdraw | DoctorSlimm/ccxt | python | async def withdraw(self, code, amount, address, tag=None, params={}):
'\n make a withdrawal\n :param str code: unified currency code\n :param float amount: the amount to withdraw\n :param str address: the address to withdraw to\n :param str|None tag:\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns dict: a `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`\n '
(tag, params) = self.handle_withdraw_tag_and_params(tag, params)
self.check_address(address)
(await self.load_markets())
currency = self.currency(code)
request = {'symbol': currency['id'], 'amount': self.currency_to_precision(code, amount), 'address': address}
if (tag is not None):
request['paymentId'] = tag
response = (await self.privatePostWithdrawal(self.extend(request, params)))
return self.parse_transaction(response, currency) |
async def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
'\n fetch all withdrawals made from an account\n :param str|None code: unified currency code\n :param int|None since: the earliest time in ms to fetch withdrawals for\n :param int|None limit: the maximum number of withdrawals structures to retrieve\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`\n '
(await self.load_markets())
request = {}
currency = None
if (code is not None):
currency = self.currency(code)
request['symbol'] = currency['id']
if (since is not None):
request['start'] = since
if (limit is not None):
request['limit'] = limit
response = (await self.privateGetWithdrawalHistory(self.extend(request, params)))
return self.parse_transactions(response, currency, since, limit, {'type': 'withdrawal'}) | 2,784,951,726,627,947,500 | fetch all withdrawals made from an account
:param str|None code: unified currency code
:param int|None since: the earliest time in ms to fetch withdrawals for
:param int|None limit: the maximum number of withdrawals structures to retrieve
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>` | python/ccxt/async_support/bitvavo.py | fetch_withdrawals | DoctorSlimm/ccxt | python | async def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
'\n fetch all withdrawals made from an account\n :param str|None code: unified currency code\n :param int|None since: the earliest time in ms to fetch withdrawals for\n :param int|None limit: the maximum number of withdrawals structures to retrieve\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`\n '
(await self.load_markets())
request = {}
currency = None
if (code is not None):
currency = self.currency(code)
request['symbol'] = currency['id']
if (since is not None):
request['start'] = since
if (limit is not None):
request['limit'] = limit
response = (await self.privateGetWithdrawalHistory(self.extend(request, params)))
return self.parse_transactions(response, currency, since, limit, {'type': 'withdrawal'}) |
async def fetch_deposits(self, code=None, since=None, limit=None, params={}):
'\n fetch all deposits made to an account\n :param str|None code: unified currency code\n :param int|None since: the earliest time in ms to fetch deposits for\n :param int|None limit: the maximum number of deposits structures to retrieve\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`\n '
(await self.load_markets())
request = {}
currency = None
if (code is not None):
currency = self.currency(code)
request['symbol'] = currency['id']
if (since is not None):
request['start'] = since
if (limit is not None):
request['limit'] = limit
response = (await self.privateGetDepositHistory(self.extend(request, params)))
return self.parse_transactions(response, currency, since, limit, {'type': 'deposit'}) | 6,673,181,452,946,335,000 | fetch all deposits made to an account
:param str|None code: unified currency code
:param int|None since: the earliest time in ms to fetch deposits for
:param int|None limit: the maximum number of deposits structures to retrieve
:param dict params: extra parameters specific to the bitvavo api endpoint
:returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>` | python/ccxt/async_support/bitvavo.py | fetch_deposits | DoctorSlimm/ccxt | python | async def fetch_deposits(self, code=None, since=None, limit=None, params={}):
'\n fetch all deposits made to an account\n :param str|None code: unified currency code\n :param int|None since: the earliest time in ms to fetch deposits for\n :param int|None limit: the maximum number of deposits structures to retrieve\n :param dict params: extra parameters specific to the bitvavo api endpoint\n :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`\n '
(await self.load_markets())
request = {}
currency = None
if (code is not None):
currency = self.currency(code)
request['symbol'] = currency['id']
if (since is not None):
request['start'] = since
if (limit is not None):
request['limit'] = limit
response = (await self.privateGetDepositHistory(self.extend(request, params)))
return self.parse_transactions(response, currency, since, limit, {'type': 'deposit'}) |
def _IsInstallationCorruption(err):
'Determines if the error may be from installation corruption.\n\n Args:\n err: Exception err.\n\n Returns:\n bool, True if installation error, False otherwise\n '
return (isinstance(err, backend.CommandLoadFailure) and isinstance(err.root_exception, ImportError)) | 3,970,820,307,311,172,000 | Determines if the error may be from installation corruption.
Args:
err: Exception err.
Returns:
bool, True if installation error, False otherwise | google-cloud-sdk/lib/googlecloudsdk/command_lib/crash_handling.py | _IsInstallationCorruption | bopopescu/searchparty | python | def _IsInstallationCorruption(err):
'Determines if the error may be from installation corruption.\n\n Args:\n err: Exception err.\n\n Returns:\n bool, True if installation error, False otherwise\n '
return (isinstance(err, backend.CommandLoadFailure) and isinstance(err.root_exception, ImportError)) |
def _PrintInstallationAction(err, err_string):
'Prompts installation error action.\n\n Args:\n err: Exception err.\n err_string: Exception err string.\n '
log.error('gcloud failed to load ({0}): {1}\n\nThis usually indicates corruption in your gcloud installation or problems with your Python interpreter.\n\nPlease verify that the following is the path to a working Python 2.7 executable:\n {2}\nIf it is not, please set the CLOUDSDK_PYTHON environment variable to point to a working Python 2.7 executable.\n\nIf you are still experiencing problems, please run the following command to reinstall:\n $ gcloud components reinstall\n\nIf that command fails, please reinstall the Cloud SDK using the instructions here:\n https://cloud.google.com/sdk/'.format(err.command, err_string, sys.executable)) | 8,228,267,783,591,513,000 | Prompts installation error action.
Args:
err: Exception err.
err_string: Exception err string. | google-cloud-sdk/lib/googlecloudsdk/command_lib/crash_handling.py | _PrintInstallationAction | bopopescu/searchparty | python | def _PrintInstallationAction(err, err_string):
'Prompts installation error action.\n\n Args:\n err: Exception err.\n err_string: Exception err string.\n '
log.error('gcloud failed to load ({0}): {1}\n\nThis usually indicates corruption in your gcloud installation or problems with your Python interpreter.\n\nPlease verify that the following is the path to a working Python 2.7 executable:\n {2}\nIf it is not, please set the CLOUDSDK_PYTHON environment variable to point to a working Python 2.7 executable.\n\nIf you are still experiencing problems, please run the following command to reinstall:\n $ gcloud components reinstall\n\nIf that command fails, please reinstall the Cloud SDK using the instructions here:\n https://cloud.google.com/sdk/'.format(err.command, err_string, sys.executable)) |
def _GetReportingClient():
'Returns a client that uses an API key for Cloud SDK crash reports.\n\n Returns:\n An error reporting client that uses an API key for Cloud SDK crash reports.\n '
client_class = core_apis.GetClientClass(util.API_NAME, util.API_VERSION)
client_instance = client_class(get_credentials=False, http=http.Http())
client_instance.AddGlobalParam('key', CRASH_API_KEY)
return client_instance | -8,993,715,344,848,936,000 | Returns a client that uses an API key for Cloud SDK crash reports.
Returns:
An error reporting client that uses an API key for Cloud SDK crash reports. | google-cloud-sdk/lib/googlecloudsdk/command_lib/crash_handling.py | _GetReportingClient | bopopescu/searchparty | python | def _GetReportingClient():
'Returns a client that uses an API key for Cloud SDK crash reports.\n\n Returns:\n An error reporting client that uses an API key for Cloud SDK crash reports.\n '
client_class = core_apis.GetClientClass(util.API_NAME, util.API_VERSION)
client_instance = client_class(get_credentials=False, http=http.Http())
client_instance.AddGlobalParam('key', CRASH_API_KEY)
return client_instance |
def ReportError(err, is_crash):
'Report the anonymous crash information to the Error Reporting service.\n\n Args:\n err: Exception, the error that caused the crash.\n is_crash: bool, True if this is a crash, False if it is a user error.\n '
if properties.VALUES.core.disable_usage_reporting.GetBool():
return
stacktrace = traceback.format_exc(err)
stacktrace = error_reporting_util.RemovePrivateInformationFromTraceback(stacktrace)
command = properties.VALUES.metrics.command_name.Get()
cid = metrics.GetCIDIfMetricsEnabled()
client = _GetReportingClient()
reporter = util.ErrorReporting(client)
try:
method_config = client.projects_events.GetMethodConfig('Report')
request = reporter.GenerateReportRequest(error_message=stacktrace, service=(CRASH_SERVICE if is_crash else ERROR_SERVICE), version=config.CLOUD_SDK_VERSION, project=CRASH_PROJECT, request_url=command, user=cid)
http_request = client.projects_events.PrepareHttpRequest(method_config, request)
metrics.CustomBeacon(http_request.url, http_request.http_method, http_request.body, http_request.headers)
except apitools_exceptions.Error as e:
log.file_only_logger.error('Unable to report crash stacktrace:\n{0}'.format(console_attr.EncodeForConsole(e))) | 2,386,250,183,612,762,000 | Report the anonymous crash information to the Error Reporting service.
Args:
err: Exception, the error that caused the crash.
is_crash: bool, True if this is a crash, False if it is a user error. | google-cloud-sdk/lib/googlecloudsdk/command_lib/crash_handling.py | ReportError | bopopescu/searchparty | python | def ReportError(err, is_crash):
'Report the anonymous crash information to the Error Reporting service.\n\n Args:\n err: Exception, the error that caused the crash.\n is_crash: bool, True if this is a crash, False if it is a user error.\n '
if properties.VALUES.core.disable_usage_reporting.GetBool():
return
stacktrace = traceback.format_exc(err)
stacktrace = error_reporting_util.RemovePrivateInformationFromTraceback(stacktrace)
command = properties.VALUES.metrics.command_name.Get()
cid = metrics.GetCIDIfMetricsEnabled()
client = _GetReportingClient()
reporter = util.ErrorReporting(client)
try:
method_config = client.projects_events.GetMethodConfig('Report')
request = reporter.GenerateReportRequest(error_message=stacktrace, service=(CRASH_SERVICE if is_crash else ERROR_SERVICE), version=config.CLOUD_SDK_VERSION, project=CRASH_PROJECT, request_url=command, user=cid)
http_request = client.projects_events.PrepareHttpRequest(method_config, request)
metrics.CustomBeacon(http_request.url, http_request.http_method, http_request.body, http_request.headers)
except apitools_exceptions.Error as e:
log.file_only_logger.error('Unable to report crash stacktrace:\n{0}'.format(console_attr.EncodeForConsole(e))) |
def HandleGcloudCrash(err):
'Checks if installation error occurred, then proceeds with Error Reporting.\n\n Args:\n err: Exception err.\n '
err_string = console_attr.EncodeForConsole(err)
log.file_only_logger.exception('BEGIN CRASH STACKTRACE')
if _IsInstallationCorruption(err):
_PrintInstallationAction(err, err_string)
else:
log.error(u'gcloud crashed ({0}): {1}'.format(getattr(err, 'error_name', type(err).__name__), err_string))
ReportError(err, is_crash=True)
log.err.Print('\nIf you would like to report this issue, please run the following command:')
log.err.Print(' gcloud feedback')
log.err.Print('\nTo check gcloud for common problems, please run the following command:')
log.err.Print(' gcloud info --run-diagnostics') | -6,910,200,027,604,990,000 | Checks if installation error occurred, then proceeds with Error Reporting.
Args:
err: Exception err. | google-cloud-sdk/lib/googlecloudsdk/command_lib/crash_handling.py | HandleGcloudCrash | bopopescu/searchparty | python | def HandleGcloudCrash(err):
'Checks if installation error occurred, then proceeds with Error Reporting.\n\n Args:\n err: Exception err.\n '
err_string = console_attr.EncodeForConsole(err)
log.file_only_logger.exception('BEGIN CRASH STACKTRACE')
if _IsInstallationCorruption(err):
_PrintInstallationAction(err, err_string)
else:
log.error(u'gcloud crashed ({0}): {1}'.format(getattr(err, 'error_name', type(err).__name__), err_string))
ReportError(err, is_crash=True)
log.err.Print('\nIf you would like to report this issue, please run the following command:')
log.err.Print(' gcloud feedback')
log.err.Print('\nTo check gcloud for common problems, please run the following command:')
log.err.Print(' gcloud info --run-diagnostics') |
def test_multiple_patterns(self, testdir):
'Test support for multiple --doctest-glob arguments (#1255).\n '
testdir.maketxtfile(xdoc='\n >>> 1\n 1\n ')
testdir.makefile('.foo', test='\n >>> 1\n 1\n ')
testdir.maketxtfile(test_normal='\n >>> 1\n 1\n ')
expected = {'xdoc.txt', 'test.foo', 'test_normal.txt'}
assert ({x.basename for x in testdir.tmpdir.listdir()} == expected)
args = ['--doctest-glob=xdoc*.txt', '--doctest-glob=*.foo']
result = testdir.runpytest(*args)
result.stdout.fnmatch_lines(['*test.foo *', '*xdoc.txt *', '*2 passed*'])
result = testdir.runpytest()
result.stdout.fnmatch_lines(['*test_normal.txt *', '*1 passed*']) | 938,271,015,983,329,000 | Test support for multiple --doctest-glob arguments (#1255). | testing/test_doctest.py | test_multiple_patterns | NNRepos/pytest | python | def test_multiple_patterns(self, testdir):
'\n '
testdir.maketxtfile(xdoc='\n >>> 1\n 1\n ')
testdir.makefile('.foo', test='\n >>> 1\n 1\n ')
testdir.maketxtfile(test_normal='\n >>> 1\n 1\n ')
expected = {'xdoc.txt', 'test.foo', 'test_normal.txt'}
assert ({x.basename for x in testdir.tmpdir.listdir()} == expected)
args = ['--doctest-glob=xdoc*.txt', '--doctest-glob=*.foo']
result = testdir.runpytest(*args)
result.stdout.fnmatch_lines(['*test.foo *', '*xdoc.txt *', '*2 passed*'])
result = testdir.runpytest()
result.stdout.fnmatch_lines(['*test_normal.txt *', '*1 passed*']) |
@pytest.mark.parametrize(' test_string, encoding', [('foo', 'ascii'), ('öäü', 'latin1'), ('öäü', 'utf-8')])
def test_encoding(self, testdir, test_string, encoding):
'Test support for doctest_encoding ini option.\n '
testdir.makeini('\n [pytest]\n doctest_encoding={}\n '.format(encoding))
doctest = '\n >>> "{}"\n {}\n '.format(test_string, repr(test_string))
testdir._makefile('.txt', [doctest], {}, encoding=encoding)
result = testdir.runpytest()
result.stdout.fnmatch_lines(['*1 passed*']) | 1,949,234,291,330,208,500 | Test support for doctest_encoding ini option. | testing/test_doctest.py | test_encoding | NNRepos/pytest | python | @pytest.mark.parametrize(' test_string, encoding', [('foo', 'ascii'), ('öäü', 'latin1'), ('öäü', 'utf-8')])
def test_encoding(self, testdir, test_string, encoding):
'\n '
testdir.makeini('\n [pytest]\n doctest_encoding={}\n '.format(encoding))
doctest = '\n >>> "{}"\n {}\n '.format(test_string, repr(test_string))
testdir._makefile('.txt', [doctest], {}, encoding=encoding)
result = testdir.runpytest()
result.stdout.fnmatch_lines(['*1 passed*']) |
def test_docstring_partial_context_around_error(self, testdir):
'Test that we show some context before the actual line of a failing\n doctest.\n '
testdir.makepyfile('\n def foo():\n """\n text-line-1\n text-line-2\n text-line-3\n text-line-4\n text-line-5\n text-line-6\n text-line-7\n text-line-8\n text-line-9\n text-line-10\n text-line-11\n >>> 1 + 1\n 3\n\n text-line-after\n """\n ')
result = testdir.runpytest('--doctest-modules')
result.stdout.fnmatch_lines(['*docstring_partial_context_around_error*', '005*text-line-3', '006*text-line-4', '013*text-line-11', '014*>>> 1 + 1', 'Expected:', ' 3', 'Got:', ' 2'])
result.stdout.no_fnmatch_line('*text-line-2*')
result.stdout.no_fnmatch_line('*text-line-after*') | -3,960,056,223,615,673,300 | Test that we show some context before the actual line of a failing
doctest. | testing/test_doctest.py | test_docstring_partial_context_around_error | NNRepos/pytest | python | def test_docstring_partial_context_around_error(self, testdir):
'Test that we show some context before the actual line of a failing\n doctest.\n '
testdir.makepyfile('\n def foo():\n "\n text-line-1\n text-line-2\n text-line-3\n text-line-4\n text-line-5\n text-line-6\n text-line-7\n text-line-8\n text-line-9\n text-line-10\n text-line-11\n >>> 1 + 1\n 3\n\n text-line-after\n "\n ')
result = testdir.runpytest('--doctest-modules')
result.stdout.fnmatch_lines(['*docstring_partial_context_around_error*', '005*text-line-3', '006*text-line-4', '013*text-line-11', '014*>>> 1 + 1', 'Expected:', ' 3', 'Got:', ' 2'])
result.stdout.no_fnmatch_line('*text-line-2*')
result.stdout.no_fnmatch_line('*text-line-after*') |
def test_docstring_full_context_around_error(self, testdir):
'Test that we show the whole context before the actual line of a failing\n doctest, provided that the context is up to 10 lines long.\n '
testdir.makepyfile('\n def foo():\n """\n text-line-1\n text-line-2\n\n >>> 1 + 1\n 3\n """\n ')
result = testdir.runpytest('--doctest-modules')
result.stdout.fnmatch_lines(['*docstring_full_context_around_error*', '003*text-line-1', '004*text-line-2', '006*>>> 1 + 1', 'Expected:', ' 3', 'Got:', ' 2']) | -7,155,863,544,981,086,000 | Test that we show the whole context before the actual line of a failing
doctest, provided that the context is up to 10 lines long. | testing/test_doctest.py | test_docstring_full_context_around_error | NNRepos/pytest | python | def test_docstring_full_context_around_error(self, testdir):
'Test that we show the whole context before the actual line of a failing\n doctest, provided that the context is up to 10 lines long.\n '
testdir.makepyfile('\n def foo():\n "\n text-line-1\n text-line-2\n\n >>> 1 + 1\n 3\n "\n ')
result = testdir.runpytest('--doctest-modules')
result.stdout.fnmatch_lines(['*docstring_full_context_around_error*', '003*text-line-1', '004*text-line-2', '006*>>> 1 + 1', 'Expected:', ' 3', 'Got:', ' 2']) |
def test_contains_unicode(self, testdir):
'Fix internal error with docstrings containing non-ascii characters.\n '
testdir.makepyfile(' def foo():\n """\n >>> name = \'с\' # not letter \'c\' but instead Cyrillic \'s\'.\n \'anything\'\n """\n ')
result = testdir.runpytest('--doctest-modules')
result.stdout.fnmatch_lines(['Got nothing', '* 1 failed in*']) | -3,770,004,817,608,001,500 | Fix internal error with docstrings containing non-ascii characters. | testing/test_doctest.py | test_contains_unicode | NNRepos/pytest | python | def test_contains_unicode(self, testdir):
'\n '
testdir.makepyfile(' def foo():\n "\n >>> name = \'с\' # not letter \'c\' but instead Cyrillic \'s\'.\n \'anything\'\n "\n ')
result = testdir.runpytest('--doctest-modules')
result.stdout.fnmatch_lines(['Got nothing', '* 1 failed in*']) |
def test_junit_report_for_doctest(self, testdir):
'\n #713: Fix --junit-xml option when used with --doctest-modules.\n '
p = testdir.makepyfile("\n def foo():\n '''\n >>> 1 + 1\n 3\n '''\n pass\n ")
reprec = testdir.inline_run(p, '--doctest-modules', '--junit-xml=junit.xml')
reprec.assertoutcome(failed=1) | 1,620,717,561,939,104,800 | #713: Fix --junit-xml option when used with --doctest-modules. | testing/test_doctest.py | test_junit_report_for_doctest | NNRepos/pytest | python | def test_junit_report_for_doctest(self, testdir):
'\n \n '
p = testdir.makepyfile("\n def foo():\n '\n >>> 1 + 1\n 3\n '\n pass\n ")
reprec = testdir.inline_run(p, '--doctest-modules', '--junit-xml=junit.xml')
reprec.assertoutcome(failed=1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.