docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
The console tab for bethebot
Args:
parent: tk or ttk element | def __init__(self, parent):
super(ModuleUIFrame, self).__init__(parent, padding=8)
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
chat = ChatFrame(self)
chat.grid(column=0, row=0, sticky="W E N S") | 677,391 |
Send messages from the bot
Args:
parent: | def __init__(self, parent):
super(ChatFrame, self).__init__(parent, padding=8, text="Chat")
self.channel = tk.StringVar()
self.message = tk.StringVar()
self.channel_frame = ttk.Frame(self)
self.channel_frame.grid(column=0, row=0, sticky="W E")
self.channel_lab... | 677,392 |
The on_message event handler for this module
Args:
message (discord.Message): Input message | async def on_message(message):
# Simplify message info
server = message.server
author = message.author
channel = message.channel
content = message.content
data = datatools.get_data()
if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
return
# On... | 677,393 |
Changes a modules activated/deactivated state for a server
Args:
channel: The channel to send the message to
module_name: The name of the module to change state for
activate: The activated/deactivated state of the module | async def activate_module(channel, module_name, activate):
data = datatools.get_data()
server_id = channel.server.id
_dir = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
_dir_modules = "{}/../".format(_dir)
if not os.path.isfile("{}/{}/_data.py".format(_dir_modules, m... | 677,397 |
Gives a user a warning, and bans them if they are over the maximum warnings
Args:
channel: The channel to send the warning message in
user: The user to give the warning to | async def warn_user(channel, user):
data = datatools.get_data()
server_id = channel.server.id
if "warnings_max" not in data["discord"]["servers"][server_id][_data.modulename]:
data["discord"]["servers"][server_id][_data.modulename]["warnings_max"] = 3
if "warnings" not in data["discord"][... | 677,398 |
Bans a user from a server
Args:
channel: The channel to send the warning message in
user: The user to give the warning to | async def ban_user(channel, user):
data = datatools.get_data()
server_id = channel.server.id
try:
await client.ban(user)
except discord.errors.Forbidden:
await client.send_typing(channel)
embed = ui_embed.error(channel, "Ban Error", "I do not have the permissions to ban th... | 677,399 |
Get the help datapacks for a module
Args:
module_name (str): The module to get help data for
server_prefix (str): The command prefix for this server
Returns:
datapacks (list): The help datapacks for the module | def get_help_datapacks(module_name, server_prefix):
_dir = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
module_dir = "{}/../{}".format(_dir, module_name, "_help.json")
if os.path.isdir(module_dir):
module_help_path = "{}/{}".format(module_dir, "_help.json")
... | 677,400 |
Get the help commands for all modules
Args:
server_prefix: The server command prefix
Returns:
datapacks (list): A list of datapacks for the help commands for all the modules | def get_help_commands(server_prefix):
datapacks = []
_dir = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
for module_name in os.listdir("{}/../".format(_dir)):
if not module_name.startswith("_") and not module_name.startswith("!"):
help_command = ... | 677,401 |
The on_message event handler for this module
Args:
message (discord.Message): Input message | async def on_message(message):
# Simplify message info
server = message.server
author = message.author
channel = message.channel
content = message.content
data = datatools.get_data()
# Only reply to server messages and don't reply to myself
if server is not None and author != cha... | 677,402 |
The on_message event handler for this module
Args:
message (discord.Message): Input message | async def on_message(message):
# Simplify message info
server = message.server
author = message.author
channel = message.channel
content = message.content
data = datatools.get_data()
# Only reply to server messages and don't reply to myself
if server is not None and author != cha... | 677,403 |
Creates an embed UI for the topic update
Args:
channel (discord.Channel): The Discord channel to bind the embed to
topic_channel: The new topic channel
Returns:
embed: The created embed | def topic_update(channel, topic_channel):
if topic_channel is not None:
try:
channel_message = "Topic channel is now `{}`.".format(topic_channel.name)
except Exception as e:
logger.exception(e)
channel_message = "Topic channel has been updated."
else:
... | 677,404 |
Creates an embed UI for the topic update
Args:
channel (discord.Channel): The Discord channel to bind the embed to
err_title: The title for the error
err_message: The message for the error
Returns:
embed: The created embed | def error_message(channel, err_title, err_message):
# Create embed UI object
gui = ui_embed.UI(
channel,
err_title,
err_message,
modulename=modulename,
colour=modulecolor_error
)
return gui | 677,405 |
Locks onto a server for easy management of various UIs
Args:
server_id (str): The Discord ID of the server to lock on to | def __init__(self, server_id):
data = datatools.get_data()
# Player variables
self.server_id = server_id
self.logger = logging.getLogger("{}.{}".format(__name__, self.server_id))
# File variables
self.songcache_dir = "{}/{}".format(_root_songcache_dir, self.serv... | 677,408 |
The play command
Args:
author (discord.Member): The member that called the command
text_channel (discord.Channel): The channel where the command was called
query (str): The argument that was passed with the command
index (str): Whether to play next or at the end ... | async def play(self, author, text_channel, query, index=None, stop_current=False, shuffle=False):
if self.state == 'off':
self.state = 'starting'
self.prev_queue = []
await self.set_topic("")
# Init the music player
await self.msetup(text_cha... | 677,409 |
The skip command
Args:
query (str): The number of items to skip | async def skip(self, query="1"):
if not self.state == 'ready':
logger.debug("Trying to skip from wrong state '{}'".format(self.state))
return
if query == "":
query = "1"
elif query == "all":
query = str(len(self.queue) + 1)
try:... | 677,414 |
The remove command
Args:
index (str): The index to remove, can be either a number, or a range in the for '##-##' | async def remove(self, index=""):
if not self.state == 'ready':
logger.debug("Trying to remove from wrong state '{}'".format(self.state))
return
if index == "":
self.statuslog.error("Must provide index to remove")
return
elif index == "a... | 677,415 |
The rewind command
Args:
query (str): The number of items to skip | async def rewind(self, query="1"):
if not self.state == 'ready':
logger.debug("Trying to rewind from wrong state '{}'".format(self.state))
return
if query == "":
query = "1"
try:
num = int(query)
except TypeError:
se... | 677,416 |
The volume command
Args:
value (str): The value to set the volume to | async def setvolume(self, value):
self.logger.debug("volume command")
if self.state != 'ready':
return
logger.debug("Volume command received")
if value == '+':
if self.volume < 100:
self.statuslog.debug("Volume up")
sel... | 677,419 |
Moves the embed message to a new channel; can also be used to move the musicplayer to the front
Args:
channel (discord.Channel): The channel to move to | async def movehere(self, channel):
self.logger.debug("movehere command")
# Delete the old message
await self.embed.delete()
# Set the channel to this channel
self.embed.channel = channel
# Send a new embed to the channel
await self.embed.send()
... | 677,421 |
Creates the voice client
Args:
author (discord.Member): The user that the voice ui will seek | async def vsetup(self, author):
if self.vready:
logger.warning("Attempt to init voice when already initialised")
return
if self.state != 'starting':
logger.error("Attempt to init from wrong state ('{}'), must be 'starting'.".format(self.state))
... | 677,424 |
Creates the gui
Args:
text_channel (discord.Channel): The channel for the embed ui to run in | async def msetup(self, text_channel):
if self.mready:
logger.warning("Attempt to init music when already initialised")
return
if self.state != 'starting':
logger.error("Attempt to init from wrong state ('{}'), must be 'starting'.".format(self.state))
... | 677,425 |
Queues songs based on either a YouTube search or a link
Args:
query (str): Either a search term or a link
queue_index (str): The queue index to enqueue at (None for end)
stop_current (bool): Whether to stop the current song after the songs are queued
shuffle (boo... | async def enqueue(self, query, queue_index=None, stop_current=False, shuffle=False):
if query is None or query == "":
return
self.statuslog.info("Parsing {}".format(query))
self.logger.debug("Enqueueing from query")
indexnum = None
if queue_index is not No... | 677,428 |
Parses a query and adds it to the queue
Args:
query (str): Either a search term or a link
index (int): The index to enqueue at (None for end)
stop_current (bool): Whether to stop the current song after the songs are queued
shuffle (bool): Whether to shuffle the a... | def parse_query(self, query, index, stop_current, shuffle):
if index is not None and len(self.queue) > 0:
if index < 0 or index >= len(self.queue):
if len(self.queue) == 1:
self.statuslog.error("Play index must be 1 (1 song in queue)")
... | 677,429 |
The on_message event handler for this module
Args:
message (discord.Message): Input message | async def on_message(message):
# Simplify message info
server = message.server
author = message.author
channel = message.channel
content = message.content
data = datatools.get_data()
if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
return
# On... | 677,448 |
Gets either a list of videos from a query, parsing links and search queries
and playlists
Args:
query (str): The YouTube search query
ilogger (logging.logger): The logger to log API calls to
Returns:
queue (list): The items obtained from the YouTube search | def parse_query(query, ilogger):
# Try parsing this as a link
p = urlparse(query)
if p and p.scheme and p.netloc:
if "youtube" in p.netloc and p.query and ytdiscoveryapi is not None:
query_parts = p.query.split('&')
yturl_parts = {}
for q in query_parts:
... | 677,453 |
Gets either a list of videos from a playlist or a single video, using the
first result of a YouTube search
Args:
query (str): The YouTube search query
ilogger (logging.logger): The logger to log API calls to
Returns:
queue (list): The items obtained from the YouTube search | def get_ytvideos(query, ilogger):
queue = []
# Search YouTube
search_result = ytdiscoveryapi.search().list(
q=query,
part="id,snippet",
maxResults=1,
type="video,playlist"
).execute()
if not search_result["items"]:
return []
# Get ... | 677,454 |
Converts a duration to a string
Args:
duration (int): The duration in seconds to convert
Returns s (str): The duration as a string | def duration_to_string(duration):
m, s = divmod(duration, 60)
h, m = divmod(m, 60)
return "%d:%02d:%02d" % (h, m, s) | 677,461 |
Parses the source info from an info dict generated by youtube-dl
Args:
info (dict): The info dict to parse
Returns:
source (str): The source of this song | def parse_source(info):
if "extractor_key" in info:
source = info["extractor_key"]
lower_source = source.lower()
for key in SOURCE_TO_NAME:
lower_key = key.lower()
if lower_source == lower_key:
source = SOURCE_TO_NAME[lower_key]
if sour... | 677,462 |
Checks a string for anger and soothes said anger
Args:
content (str): The message to be flipchecked
Returns:
putitback (str): The righted table or text | def flipcheck(content):
# Prevent tampering with flip
punct =
tamperdict = str.maketrans('', '', punct)
tamperproof = content.translate(tamperdict)
# Unflip
if "(╯°□°)╯︵" in tamperproof:
# For tables
if "┻┻" in tamperproof:
# Calculate table length
... | 677,463 |
Sends a message to Mitsuku and retrieves the reply
Args:
botcust2 (str): The botcust2 identifier
message (str): The message to send to Mitsuku
Returns:
reply (str): The message Mitsuku sent back | def query(botcust2, message):
logger.debug("Getting Mitsuku reply")
# Set up http request packages
params = {
'botid': 'f6a012073e345a08',
'amp;skin': 'chat'
}
headers = {
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.8',
'Cach... | 677,465 |
The on_message event handler for this module
Args:
message (discord.Message): Input message | async def on_message(message):
# Simplify message info
server = message.server
author = message.author
channel = message.channel
content = message.content
data = datatools.get_data()
if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
return
# On... | 677,466 |
Adds a key to the bot's data
Args:
key: The name of the key to add
value: The value for the key | def add_api_key(key, value):
if key is None or key == "":
logger.error("Key cannot be empty")
if value is None or value == "":
logger.error("Value cannot be empty")
from .. import datatools
data = datatools.get_data()
if "keys" not in data["discord"]:
data["discord"]... | 677,469 |
Creates an embed UI containing the help message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
title (str): The title of the embed
datapacks (list): The hex value
Returns:
ui (ui_embed.UI): The embed UI object | def success(channel, title, datapacks):
# Create embed UI object
gui = ui_embed.UI(
channel,
title,
"",
modulename=modulename,
datapacks=datapacks
)
return gui | 677,470 |
Creates an embed UI containing the 'too long' error message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
title (str): The title of the embed
Returns:
ui (ui_embed.UI): The embed UI object | def http_exception(channel, title):
# Create embed UI object
gui = ui_embed.UI(
channel,
"Too much help",
"{} is too helpful! Try trimming some of the help messages.".format(title),
modulename=modulename
)
return gui | 677,471 |
Write the refractive index profile to file.
Args:
filename (str): The nominal filename the refractive
index data should be saved to.
plot (bool): `True` if plots should be generates,
otherwise `False`. Default is `True`. | def write_to_file(self, filename='material_index.dat', plot=True):
path = os.path.dirname(sys.modules[__name__].__file__) + '/'
with open(filename, 'w') as fs:
for n_row in np.abs(self.n[::-1]):
n_str = ','.join([str(v) for v in n_row])
fs.write(n_st... | 677,946 |
Creates and adds a :class:`Slab` object.
Args:
height (float): Height of the slab.
n_background (float): The nominal refractive
index of the slab. Default is 1 (air).
Returns:
str: The name of the slab. | def add_slab(self, height, n_background=1., position='top'):
assert position in ('top', 'bottom')
name = str(self.slab_count)
if not callable(n_background):
n_back = lambda wl: n_background
else:
n_back = n_background
height_discretised = self.... | 677,949 |
Changes the wavelength of the structure.
This will affect the mode solver and potentially
the refractive indices used (provided functions
were provided as refractive indices).
Args:
wavelength (float): The new wavelength. | def change_wavelength(self, wavelength):
for name, slab in self.slabs.items():
const_args = slab._const_args
mat_args = slab._mat_params
const_args[8] = wavelength
s = Slab(*const_args)
for mat_arg in mat_args:
s.add_material... | 677,950 |
Write the refractive index profile to file.
Args:
filename (str): The nominal filename the refractive
index data should be saved to.
plot (bool): `True` if plots should be generates,
otherwise `False`. Default is `True`. | def write_to_file(self, filename='material_index.dat', plot=True):
path = os.path.dirname(sys.modules[__name__].__file__) + '/'
dir_plot = 'material_index/'
if not os.path.exists(dir_plot):
os.makedirs(dir_plot)
for axis, name in zip(self.axes, self.axes_str):
... | 677,959 |
Changes the wavelength of the structure.
This will affect the mode solver and potentially
the refractive indices used (provided functions
were provided as refractive indices).
Args:
wavelength (float): The new wavelength. | def change_wavelength(self, wavelength):
for axis in self.axes:
if issubclass(type(axis), Slabs):
axis.change_wavelength(wavelength)
self.xx, self.xy, self.yx, self.yy, self.zz = self.axes
self._wl = wavelength | 677,960 |
Calculate the power reflection at the interface
of two refractive index materials.
Args:
n1 (float): Refractive index of material 1.
n2 (float): Refractive index of material 2.
Returns:
float: The percentage of reflected power. | def reflection(n1, n2):
r = abs((n1-n2) / (n1+n2))**2
return r | 678,064 |
Construct a Gzipped Message containing multiple Messages
The given payloads will be encoded, compressed, and sent as a single atomic
message to Kafka.
Arguments:
payloads: list(bytes), a list of payload to send be sent to Kafka
key: bytes, a key used for partition routing (optional) | def create_gzip_message(payloads, key=None, compresslevel=None):
message_set = KafkaProtocol._encode_message_set(
[create_message(payload, pl_key) for payload, pl_key in payloads])
gzipped = gzip_encode(message_set, compresslevel=compresslevel)
codec = ATTRIBUTE_CODEC_MASK & CODEC_GZIP
re... | 679,810 |
Decode bytes to a ProduceResponse
Arguments:
data: bytes to decode | def decode_produce_response(cls, data):
((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0)
for _ in range(num_topics):
((strlen,), cur) = relative_unpack('>h', data, cur)
topic = data[cur:cur + strlen]
cur += strlen
((num_parti... | 679,815 |
Encodes some FetchRequest structs
Arguments:
client_id: string
correlation_id: int
payloads: list of FetchRequest
max_wait_time: int, how long to block waiting on min_bytes of data
min_bytes: int, the minimum number of bytes to accumulate before
... | def encode_fetch_request(cls, client_id, correlation_id, payloads=None,
max_wait_time=100, min_bytes=4096):
payloads = [] if payloads is None else payloads
grouped_payloads = group_by_topic_and_partition(payloads)
message = []
message.append(cls._e... | 679,816 |
Decode bytes to a FetchResponse
Arguments:
data: bytes to decode | def decode_fetch_response(cls, data):
((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0)
for _ in range(num_topics):
(topic, cur) = read_short_string(data, cur)
((num_partitions,), cur) = relative_unpack('>i', data, cur)
for j in range(nu... | 679,817 |
Decode bytes to an OffsetResponse
Arguments:
data: bytes to decode | def decode_offset_response(cls, data):
((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0)
for _ in range(num_topics):
(topic, cur) = read_short_string(data, cur)
((num_partitions,), cur) = relative_unpack('>i', data, cur)
for _ in range(n... | 679,819 |
Encode a MetadataRequest
Arguments:
client_id: string
correlation_id: int
topics: list of strings | def encode_metadata_request(cls, client_id, correlation_id, topics=None,
payloads=None):
if payloads is None:
topics = [] if topics is None else topics
else:
topics = payloads
message = []
message.append(cls._encode_messag... | 679,820 |
Decode bytes to a MetadataResponse
Arguments:
data: bytes to decode | def decode_metadata_response(cls, data):
((correlation_id, numbrokers), cur) = relative_unpack('>ii', data, 0)
# Broker info
brokers = []
for _ in range(numbrokers):
((nodeId, ), cur) = relative_unpack('>i', data, cur)
(host, cur) = read_short_string(dat... | 679,821 |
Encode some OffsetCommitRequest structs
Arguments:
client_id: string
correlation_id: int
group: string, the consumer group you are committing offsets for
payloads: list of OffsetCommitRequest | def encode_offset_commit_request(cls, client_id, correlation_id,
group, payloads):
grouped_payloads = group_by_topic_and_partition(payloads)
message = []
message.append(cls._encode_message_header(client_id, correlation_id,
... | 679,822 |
Decode bytes to an OffsetCommitResponse
Arguments:
data: bytes to decode | def decode_offset_commit_response(cls, data):
((correlation_id,), cur) = relative_unpack('>i', data, 0)
((num_topics,), cur) = relative_unpack('>i', data, cur)
for _ in xrange(num_topics):
(topic, cur) = read_short_string(data, cur)
((num_partitions,), cur) = re... | 679,823 |
Decode bytes to an OffsetFetchResponse
Arguments:
data: bytes to decode | def decode_offset_fetch_response(cls, data):
((correlation_id,), cur) = relative_unpack('>i', data, 0)
((num_topics,), cur) = relative_unpack('>i', data, cur)
for _ in range(num_topics):
(topic, cur) = read_short_string(data, cur)
((num_partitions,), cur) = rel... | 679,825 |
Get a response packet from Kafka
Arguments:
request_id: can be any int (only used for debug logging...)
Returns:
str: Encoded kafka packet response from server | def recv(self, request_id):
log.debug("Reading response %d from Kafka" % request_id)
# Make sure we have a connection
if not self._sock:
self.reinit()
# Read the size off of the header
resp = self._read_bytes(4)
(size,) = struct.unpack('>i', resp)
... | 679,881 |
Mark a fetched message as consumed.
Offsets for messages marked as "task_done" will be stored back
to the kafka cluster for this consumer group on commit()
Arguments:
message (KafkaMessage): the message to mark as complete
Returns:
True, unless the topic-partit... | def task_done(self, message):
topic_partition = (message.topic, message.partition)
if topic_partition not in self._topics:
logger.warning('Unrecognized topic/partition in task_done message: '
'{0}:{1}'.format(*topic_partition))
return False
... | 679,892 |
Pure-python Murmur2 implementation.
Based on java client, see org.apache.kafka.common.utils.Utils.murmur2
Args:
key: if not a bytes type, encoded using default encoding
Returns: MurmurHash2 of key bytearray | def murmur2(key):
# Convert key to bytes or bytearray
if isinstance(key, bytearray) or (six.PY3 and isinstance(key, bytes)):
data = key
else:
data = bytearray(str(key).encode())
length = len(data)
seed = 0x9747b28c
# 'm' and 'r' are mixing constants generated offline.
... | 679,987 |
Return StagPy out file name.
Args:
stem (str): short description of file content.
timestep (int): timestep if relevant.
Returns:
str: the output file name.
Other Parameters:
conf.core.outname (str): the generic name stem, defaults to
``'stagpy'``. | def out_name(stem, timestep=None):
if timestep is not None:
stem = (stem + INT_FMT).format(timestep)
return conf.core.outname + '_' + stem | 680,112 |
Save matplotlib figure.
You need to provide :data:`stem` as a positional or keyword argument (see
:func:`out_name`).
Args:
fig (:class:`matplotlib.figure.Figure`): matplotlib figure.
close (bool): whether to close the figure.
name_args: positional arguments passed on to :func:`out_... | def saveplot(fig, *name_args, close=True, **name_kwargs):
oname = out_name(*name_args, **name_kwargs)
fig.savefig('{}.{}'.format(oname, conf.plot.format),
format=conf.plot.format, bbox_inches='tight')
if close:
plt.close(fig) | 680,113 |
Return the first line of the docstring of an object.
Trailing periods and spaces as well as leading spaces are removed from the
output.
Args:
obj: any Python object.
Returns:
str: the first line of the docstring of obj. | def baredoc(obj):
doc = getdoc(obj)
if not doc:
return ''
doc = doc.splitlines()[0]
return doc.rstrip(' .').lstrip() | 680,114 |
Return LaTeX expression with time in scientific notation.
Args:
tin (float): the time.
Returns:
str: the LaTeX expression. | def fmttime(tin):
aaa, bbb = '{:.2e}'.format(tin).split('e')
bbb = int(bbb)
return r'$t={} \times 10^{{{}}}$'.format(aaa, bbb) | 680,115 |
Construct list of variables per plot.
Args:
arg_plot (str): string with variable names separated with
``_`` (figures), ``.`` (subplots) and ``,`` (same subplot).
Returns:
three nested lists of str
- variables on the same subplot;
- subplots on the same figure;
... | def list_of_vars(arg_plot):
lovs = [[[var for var in svars.split(',') if var]
for svars in pvars.split('.') if svars]
for pvars in arg_plot.split('-') if pvars]
lovs = [[slov for slov in lov if slov] for lov in lovs if lov]
return [lov for lov in lovs if lov] | 680,116 |
Build set of variables from list.
Args:
lovs: nested lists of variables such as the one produced by
:func:`list_of_vars`.
Returns:
set of str: flattened set of all the variables present in the
nested lists. | def set_of_vars(lovs):
return set(var for pvars in lovs for svars in pvars for var in svars) | 680,117 |
Radial or vertical position of boundaries.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of floats: radial or vertical positions of boundaries of the
domain. | def get_rbounds(step):
if step.geom is not None:
rcmb = step.geom.rcmb
else:
rcmb = step.sdat.par['geometry']['r_cmb']
if step.sdat.par['geometry']['shape'].lower() == 'cartesian':
rcmb = 0
rcmb = max(rcmb, 0)
return rcmb, rcmb + 1 | 680,118 |
Initialization of instances:
Args:
nfiles (int): number of files. Defaults to 1.
tmp_prefix (str): prefix name of temporary files. Use this
parameter if you want to easily track down the temporary files
created by the manager. | def __init__(self, nfiles=1, tmp_prefix=None):
self._fnames = ['inchoate{}'.format(i) for i in range(nfiles)]
self._tmpprefix = tmp_prefix
self._fids = [] | 680,119 |
Plot requested time series.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
lovs (nested list of str): nested list of series names such as
the one produced by :func:`stagpy.misc.list_of_vars`.
Other Parameters:
conf.time.tstart: the starting time... | def plot_time_series(sdat, lovs):
sovs = misc.set_of_vars(lovs)
tseries = {}
times = {}
metas = {}
for tvar in sovs:
series, time, meta = get_time_series(
sdat, tvar, conf.time.tstart, conf.time.tend)
tseries[tvar] = series
metas[tvar] = meta
if time ... | 680,125 |
Compute statistics from series output by StagYY.
Create a file 'statistics.dat' containing the mean and standard deviation
of each series on the requested time span.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): starting time. Set to None to st... | def compstat(sdat, tstart=None, tend=None):
data = sdat.tseries_between(tstart, tend)
time = data['t'].values
delta_time = time[-1] - time[0]
data = data.iloc[:, 1:].values # assume t is first column
mean = np.trapz(data, x=time, axis=0) / delta_time
rms = np.sqrt(np.trapz((data - mean)**... | 680,126 |
Print a iterable of key/values
Args:
key_val (list of (str, str)): the pairs of section names and text.
sep (str): separator between section names and text.
min_col_width (int): minimal acceptable column width
text_width (int): text width to use. If set to None, will try to infer
... | def _pretty_print(key_val, sep=': ', min_col_width=39, text_width=None):
if text_width is None:
text_width = get_terminal_size().columns
if text_width < min_col_width:
min_col_width = text_width
ncols = (text_width + 1) // (min_col_width + 1)
colw = (text_width + 1) // ncols - 1
... | 680,129 |
Pretty print of configuration options.
Args:
subs (iterable of str): iterable with the list of conf sections to
print. | def config_pp(subs):
print('(c|f): available only as CLI argument/in the config file',
end='\n\n')
for sub in subs:
hlp_lst = []
for opt, meta in conf[sub].defaults_():
if meta.cmd_arg ^ meta.conf_arg:
opt += ' (c)' if meta.cmd_arg else ' (f)'
... | 680,133 |
Plot cell position and thickness.
The figure is call grid_N.pdf where N is replace by the step index.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance. | def plot_grid(step):
rad = get_rprof(step, 'r')[0]
drad = get_rprof(step, 'dr')[0]
_, unit = step.sdat.scale(1, 'm')
if unit:
unit = ' ({})'.format(unit)
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
ax1.plot(rad, '-ko')
ax1.set_ylabel('$r$' + unit)
ax2.plot(drad, '-ko')
... | 680,137 |
Plot time averaged profiles.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
lovs (nested list of str): nested list of profile names such as
the one produced by :func:`stagpy.misc.list_of_vars`.
Other Parameters:
conf.core.snapshots: the slice of... | def plot_average(sdat, lovs):
steps_iter = iter(sdat.walk.filter(rprof=True))
try:
step = next(steps_iter)
except StopIteration:
return
sovs = misc.set_of_vars(lovs)
istart = step.istep
nprofs = 1
rprof_averaged = {}
rads = {}
metas = {}
# assume constant ... | 680,138 |
Plot profiles at each time step.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
lovs (nested list of str): nested list of profile names such as
the one produced by :func:`stagpy.misc.list_of_vars`.
Other Parameters:
conf.core.snapshots: the slic... | def plot_every_step(sdat, lovs):
sovs = misc.set_of_vars(lovs)
for step in sdat.walk.filter(rprof=True):
rprofs = {}
rads = {}
metas = {}
for rvar in sovs:
rprof, rad, meta = get_rprof(step, rvar)
rprofs[rvar] = rprof
metas[rvar] = meta
... | 680,139 |
Return scalar field along with coordinates meshes.
Only works properly in 2D geometry.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): scalar field name.
Returns:
tuple of :class:`numpy.array`: xmesh, ymesh, fld
2D... | def get_meshes_fld(step, var):
fld = step.fields[var]
if step.geom.twod_xz:
xmesh, ymesh = step.geom.x_mesh[:, 0, :], step.geom.z_mesh[:, 0, :]
fld = fld[:, 0, :, 0]
elif step.geom.cartesian and step.geom.twod_yz:
xmesh, ymesh = step.geom.y_mesh[0, :, :], step.geom.z_mesh[0, :, ... | 680,144 |
Return vector field components along with coordinates meshes.
Only works properly in 2D geometry.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): vector field name.
Returns:
tuple of :class:`numpy.array`: xmesh, ymesh, fldx, f... | def get_meshes_vec(step, var):
if step.geom.twod_xz:
xmesh, ymesh = step.geom.x_mesh[:, 0, :], step.geom.z_mesh[:, 0, :]
vec1 = step.fields[var + '1'][:, 0, :, 0]
vec2 = step.fields[var + '3'][:, 0, :, 0]
elif step.geom.cartesian and step.geom.twod_yz:
xmesh, ymesh = step.ge... | 680,145 |
Build set of needed field variables.
Each var is a tuple, first component is a scalar field, second component is
either:
- a scalar field, isocontours are added to the plot.
- a vector field (e.g. 'v' for the (v1,v2,v3) vector), arrows are added to
the plot.
Args:
arg_plot (str): st... | def set_of_vars(arg_plot):
sovs = set(tuple((var + '+').split('+')[:2])
for var in arg_plot.split(','))
sovs.discard(('', ''))
return sovs | 680,146 |
Plot isocontours of scalar field.
Args:
axis (:class:`matplotlib.axes.Axes`): the axis handler of an
existing matplotlib figure where the isocontours should
be plotted.
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): ... | def plot_iso(axis, step, var):
xmesh, ymesh, fld = get_meshes_fld(step, var)
if conf.field.shift:
fld = np.roll(fld, conf.field.shift, axis=0)
axis.contour(xmesh, ymesh, fld, linewidths=1) | 680,148 |
Plot vector field.
Args:
axis (:class:`matplotlib.axes.Axes`): the axis handler of an
existing matplotlib figure where the vector field should
be plotted.
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): the vector fie... | def plot_vec(axis, step, var):
xmesh, ymesh, vec1, vec2 = get_meshes_vec(step, var)
dipz = step.geom.nztot // 10
if conf.field.shift:
vec1 = np.roll(vec1, conf.field.shift, axis=0)
vec2 = np.roll(vec2, conf.field.shift, axis=0)
if step.geom.spherical or conf.plot.ratio is None:
... | 680,149 |
Parse cmd line arguments.
Update :attr:`stagpy.conf` accordingly.
Args:
arglist (list of str): the list of cmd line arguments. If set to
None, the arguments are taken from :attr:`sys.argv`.
Returns:
function: the function implementing the sub command to be executed. | def parse_args(arglist=None):
climan = CLIManager(conf, **SUB_CMDS)
create_complete_files(climan, CONFIG_DIR, 'stagpy', 'stagpy-git',
zsh_sourceable=True)
cmd_args, all_subs = climan.parse_args(arglist)
sub_cmd = cmd_args.loam_sub_name
if sub_cmd is None:
re... | 680,153 |
Initialization of instances:
Args:
parfile (pathlike): the expected path of
the par file.
Attributes:
parfile (pathlike): the expected path of the par file. | def __init__(self, parfile):
self.parfile = parfile
super().__init__('{} file not found'.format(parfile)) | 680,154 |
Initialization of instances:
Args:
faulty_file (pathlike): path of the file where a parsing problem
was encountered.
msg (str): error message.
Attributes:
file (pathlike): path of the file where a parsing problem was
encountered.
... | def __init__(self, faulty_file, msg):
self.file = faulty_file
self.msg = msg
super().__init__(faulty_file, msg) | 680,155 |
Initialization of instances:
Args:
fraction (float): the invalid fraction.
Attributes:
fraction (float): the invalid fraction. | def __init__(self, fraction):
self.fraction = fraction
super().__init__('Fraction should be in (0,1] (received {})'
.format(fraction)) | 680,157 |
Initialization of instances:
Args:
zoom (int): the invalid zoom level.
Attributes:
zoom (int): the invalid zoom level. | def __init__(self, zoom):
self.zoom = zoom
super().__init__('Zoom angle should be in [0,360] (received {})'
.format(zoom)) | 680,158 |
Initialization of instances:
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): the StagyyData
instance for which a stagnant lid regime was found.
Attributes:
sdat (:class:`~stagpy.stagyydata.StagyyData`): the StagyyData
instance for which a st... | def __init__(self, sdat):
self.sdat = sdat
super().__init__('Stagnant lid regime for {}'.format(sdat)) | 680,159 |
Initialization of instances:
Args:
filters (list): the invalid filter names.
Attributes:
filters (list): the invalid filter names. | def __init__(self, filters):
self.filters = filters
super().__init__(', '.join(repr(f) for f in filters)) | 680,160 |
Build set of needed variables.
Args:
arg_plot (str): string with variable names separated with ``,``.
Returns:
set of str: set of variables. | def set_of_vars(arg_plot):
return set(var for var in arg_plot.split(',') if var in phyvars.PLATES) | 680,168 |
Time increment dt.
Compute dt as a function of time.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which... | def dtime(sdat, tstart=None, tend=None):
tseries = sdat.tseries_between(tstart, tend)
time = tseries['t'].values
return time[1:] - time[:-1], time[:-1] | 680,173 |
Plates mobility.
Compute the ratio vsurf / vrms.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the... | def mobility(sdat, tstart=None, tend=None):
tseries = sdat.tseries_between(tstart, tend)
steps = sdat.steps[tseries.index[0]:tseries.index[-1]]
time = []
mob = []
for step in steps.filter(rprof=True):
time.append(step.timeinfo['t'])
mob.append(step.rprof.iloc[-1].loc['vrms'] / s... | 680,176 |
Cell border.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the position of the bottom and top walls
of the cells. The two elements of the tuple are identical. | def r_edges(step):
rbot, rtop = misc.get_rbounds(step)
centers = step.rprof.loc[:, 'r'].values + rbot
# assume walls are mid-way between T-nodes
# could be T-nodes at center between walls
edges = (centers[:-1] + centers[1:]) / 2
edges = np.insert(edges, 0, rbot)
edges = np.append(edges,... | 680,177 |
Diffusion.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the diffusion and the radial position
at which it is evaluated. | def diff_prof(step):
rbot, rtop = misc.get_rbounds(step)
rad = step.rprof['r'].values + rbot
tprof = step.rprof['Tmean'].values
diff = (tprof[:-1] - tprof[1:]) / (rad[1:] - rad[:-1])
# assume tbot = 1
diff = np.insert(diff, 0, (1 - tprof[0]) / (rad[0] - rbot))
# assume ttop = 0
diff... | 680,179 |
Scaled diffusion.
This computation takes sphericity into account if necessary.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the diffusion and the radial position
at which it is evaluated. | def diffs_prof(step):
diff, rad = diff_prof(step)
return _scale_prof(step, diff, rad), rad | 680,180 |
Energy flux.
This computation takes sphericity into account if necessary.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the energy flux and the radial position
at which it is evaluated. | def energy_prof(step):
diff, rad = diffs_prof(step)
adv, _ = advts_prof(step)
return (diff + np.append(adv, 0)), rad | 680,181 |
Theoretical advection.
This compute the theoretical profile of total advection as function of
radius.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array` and None: the theoretical advection.
The sec... | def advth(step):
rbot, rtop = misc.get_rbounds(step)
rmean = 0.5 * (rbot + rtop)
rad = step.rprof['r'].values + rbot
radio = step.timeinfo['H_int']
if rbot != 0: # spherical
th_adv = -(rtop**3 - rad**3) / rmean**2 / 3
else:
th_adv = rad - rtop
th_adv *= radio
th_adv... | 680,182 |
Initial concentration.
This compute the resulting composition profile if fractional
crystallization of a SMO is assumed.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the composition and the radial p... | def init_c_overturn(step):
rbot, rtop = misc.get_rbounds(step)
xieut = step.sdat.par['tracersin']['fe_eut']
k_fe = step.sdat.par['tracersin']['k_fe']
xi0l = step.sdat.par['tracersin']['fe_cont']
xi0s = k_fe * xi0l
xired = xi0l / xieut
rsup = (rtop**3 - xired**(1 / (1 - k_fe)) *
... | 680,183 |
Theoretical overturned concentration.
This compute the resulting composition profile if fractional
crystallization of a SMO is assumed and then a purely radial
overturn happens.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tu... | def c_overturned(step):
rbot, rtop = misc.get_rbounds(step)
cinit, rad = init_c_overturn(step)
radf = (rtop**3 + rbot**3 - rad**3)**(1 / 3)
return cinit, radf | 680,184 |
Stream function.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
:class:`numpy.array`: the stream function field, with four dimensions:
x-direction, y-direction, z-direction and block. | def stream_function(step):
if step.geom.twod_yz:
x_coord = step.geom.y_coord
v_x = step.fields['v2'][0, :, :, 0]
v_z = step.fields['v3'][0, :, :, 0]
shape = (1, v_x.shape[0], v_x.shape[1], 1)
elif step.geom.twod_xz and step.geom.cartesian:
x_coord = step.geom.x_coord... | 680,185 |
Initialization of instances:
Args:
sdat (:class:`StagyyData`): the StagyyData instance owning the
:class:`_Steps` instance.
Attributes:
sdat (:class:`StagyyData`): the StagyyData instance owning the
:class:`_Steps` instance. | def __init__(self, sdat):
self.sdat = sdat
self._last = UNDETERMINED
self._data = {None: _step.EmptyStep()} | 680,186 |
Initialization of instances:
Args:
sdat (:class:`StagyyData`): the StagyyData instance owning the
:class:`_Snaps` instance.
Attributes:
sdat (:class:`StagyyData`): the StagyyData instance owning the
:class:`_Snaps` instance. | def __init__(self, sdat):
self._isteps = {}
self._all_isteps_known = False
super().__init__(sdat) | 680,189 |
Register the isnap / istep correspondence.
Users of :class:`StagyyData` should not use this method.
Args:
isnap (int): snapshot index.
istep (int): time step index. | def bind(self, isnap, istep):
self._isteps[isnap] = istep
self.sdat.steps[istep].isnap = isnap | 680,192 |
Initialization of instances:
Args:
steps_col (:class:`_Steps` or :class:`_Snaps`): steps collection,
i.e. :attr:`StagyyData.steps` or :attr:`StagyyData.snaps`
attributes.
slc (slice): slice of desired isteps or isnap. | def __init__(self, steps_col, slc):
self._col = steps_col
self._idx = slc.indices(len(self._col))
self._flt = {
'snap': False,
'rprof': False,
'fields': [],
'func': lambda _: True,
}
self._dflt_func = self._flt['func'] | 680,193 |
Scales quantity to obtain dimensionful quantity.
Args:
data (numpy.array): the quantity that should be scaled.
dim (str): the dimension of data as defined in phyvars.
Return:
(float, str): scaling factor and unit string.
Other Parameters:
conf.sca... | def scale(self, data, unit):
if self.par['switches']['dimensional_units'] or \
not conf.scaling.dimensional or \
unit == '1':
return data, ''
scaling = phyvars.SCALES[unit](self.scales)
factor = conf.scaling.factors.get(unit, ' ')
if conf.scalin... | 680,205 |
Return time series data between requested times.
Args:
tstart (float): starting time. Set to None to start at the
beginning of available data.
tend (float): ending time. Set to None to stop at the end of
available data.
Returns:
:class... | def tseries_between(self, tstart=None, tend=None):
if self.tseries is None:
return None
ndat = self.tseries.shape[0]
if tstart is None:
istart = 0
else:
igm = 0
igp = ndat - 1
while igp - igm > 1:
ista... | 680,206 |
Return name of StagYY output file.
Args:
fname (str): name stem.
timestep (int): snapshot number, set to None if this is not
relevant.
suffix (str): optional suffix of file name.
force_legacy (bool): force returning the legacy output path.
... | def filename(self, fname, timestep=None, suffix='', force_legacy=False):
if timestep is not None:
fname += '{:05d}'.format(timestep)
fname += suffix
if not force_legacy and self.hdf5:
fpath = self.hdf5 / fname
else:
fpath = self.par['ioin']['o... | 680,207 |
Set of existing binary files at a given snap.
Args:
isnap (int): snapshot index.
Returns:
set of pathlib.Path: the set of output files available for this
snapshot number. | def binfiles_set(self, isnap):
possible_files = set(self.filename(fstem, isnap, force_legacy=True)
for fstem in phyvars.FIELD_FILES)
return possible_files & self.files | 680,208 |
Truncate or extend names so that its len is nnames.
The list is modified, this function returns nothing.
Args:
names (list): list of names.
nnames (int): desired number of names.
extra_names (list of str): list of names to be used to extend the list
if needed. If this list ... | def _tidy_names(names, nnames, extra_names=None):
if len(names) < nnames and extra_names is not None:
names.extend(extra_names)
names.extend(range(nnames - len(names)))
del names[nnames:] | 680,209 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.