code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
max_bytes = self._config['fetch_message_max_bytes']
max_wait_time = self._config['fetch_wait_max_ms']
min_bytes = self._config['fetch_min_bytes']
if not self._topics:
raise KafkaConfigurationError('No topics or partitions configured')
if not self._offsets.... | def fetch_messages(self) | Sends FetchRequests for all topic/partitions set for consumption
Returns:
Generator that yields KafkaMessage structs
after deserializing with the configured `deserializer_class`
Note:
Refreshes metadata on errors, and resets fetch offset on
OffsetOutOfRa... | 4.006621 | 3.640417 | 1.100594 |
reqs = [OffsetRequest(topic, partition, request_time_ms, max_num_offsets)]
(resp,) = self._client.send_offset_request(reqs)
check_error(resp)
# Just for sanity..
# probably unnecessary
assert resp.topic == topic
assert resp.partition == partition
... | def get_partition_offsets(self, topic, partition, request_time_ms, max_num_offsets) | Request available fetch offsets for a single topic/partition
Keyword Arguments:
topic (str): topic for offset request
partition (int): partition for offset request
request_time_ms (int): Used to ask for all messages before a
certain time (ms). There are two s... | 5.548207 | 6.314246 | 0.878681 |
if not group:
return {
'fetch': self.offsets('fetch'),
'commit': self.offsets('commit'),
'task_done': self.offsets('task_done'),
'highwater': self.offsets('highwater')
}
else:
return dict(deepcop... | def offsets(self, group=None) | Get internal consumer offset values
Keyword Arguments:
group: Either "fetch", "commit", "task_done", or "highwater".
If no group specified, returns all groups.
Returns:
A copy of internal offsets struct | 4.45305 | 2.509142 | 1.77473 |
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
offset = message.offset
... | def task_done(self, message) | 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... | 3.726372 | 3.562328 | 1.04605 |
if not self._config['group_id']:
logger.warning('Cannot commit without a group_id!')
raise KafkaConfigurationError(
'Attempted to commit offsets '
'without a configured consumer group (group_id)'
)
# API supports storing metad... | def commit(self) | Store consumed message offsets (marked via task_done())
to kafka cluster for this consumer_group.
Returns:
True on success, or False if no offsets were found for commit
Note:
this functionality requires server version >=0.8.1.1
https://cwiki.apache.org/confl... | 4.444726 | 4.108271 | 1.081897 |
if 'sort_keys' not in kwargs:
kwargs['sort_keys'] = False
if 'ensure_ascii' not in kwargs:
kwargs['ensure_ascii'] = False
data = json.dumps(data, **kwargs)
return data | def as_json(data, **kwargs) | Writes data as json.
:param dict data: data to convert to json
:param kwargs kwargs: kwargs for json dumps
:return: json string
:rtype: str | 2.449169 | 2.232282 | 1.097159 |
if content_type not in _READABLE_CONTENT_TYPES:
msg = ('Cannot read %s, not in %s' %
(content_type, _READABLE_CONTENT_TYPES))
raise exceptions.UnsupportedContentTypeException(msg)
try:
content = payload.read()
if not content:
return None
excep... | def read_body(payload, content_type=JSON_CONTENT_TYPE) | Reads HTTP payload according to given content_type.
Function is capable of reading from payload stream.
Read data is then processed according to content_type.
Note:
Content-Type is validated. It means that if read_body
body is not capable of reading data in requested type,
it will ... | 3.013437 | 3.323291 | 0.906763 |
while True:
try:
callable, args = self.queue.get(block=False)
except queue.Empty:
break
callable(*args) | def __process_idle_events(self) | This should never be called directly, it is called via an
event, and should always be on the GUI thread | 4.228233 | 4.172029 | 1.013472 |
self.__process_idle_events()
# grab the simulation lock, gather all of the
# wpilib objects, and display them on the screen
self.update_widgets()
# call next timer_fired (or we'll never call timer_fired again!)
delay = 100 # milliseconds
self.root.afte... | def timer_fired(self) | Polling loop for events from other threads | 11.561333 | 10.890318 | 1.061616 |
if not has_snappy():
raise NotImplementedError("Snappy codec is not available")
if xerial_compatible:
def _chunker():
for i in xrange(0, len(payload), xerial_blocksize):
yield payload[i:i + xerial_blocksize]
out = BytesIO()
header = b''.join([... | def snappy_encode(payload, xerial_compatible=False, xerial_blocksize=32 * 1024) | Encodes the given data with snappy if xerial_compatible is set then the
stream is encoded in a fashion compatible with the xerial snappy library
The block size (xerial_blocksize) controls how frequent the blocking
occurs 32k is the default in the xerial library.
The format winds up being
... | 2.626812 | 2.807534 | 0.93563 |
return os.path.normpath(
os.path.join(os.path.abspath(os.path.dirname(__file__)), path)
) | def relpath(path) | Path helper, gives you a path relative to this file | 2.064948 | 2.325752 | 0.887863 |
# pathfinder x/y coordinates are switched
pts = [(pt.x, -pt.y) for pt in trajectory]
robot_coordinates = offset if offset else True
self.draw_line(
pts,
color=color,
robot_coordinates=robot_coordinates,
relative_to_first=True,
... | def draw_pathfinder_trajectory(
self,
trajectory,
color="#ff0000",
offset=None,
scale=(1, 1),
show_dt=False,
dt_offset=0.0,
**kwargs
) | Special helper function for drawing trajectories generated by
robotpy-pathfinder
:param trajectory: A list of pathfinder segment objects
:param offset: If specified, should be x/y tuple to add to the path
relative to the robot coordinates
... | 5.857968 | 5.794673 | 1.010923 |
def _defer(): # called later because the field might not exist yet
px_per_ft = UserRenderer._global_ui.field.px_per_ft
if arrow:
kwargs["arrow"] = "last"
sx, sy = scale
line = DrawableLine(
[(x * px_per_ft * sx, y * px_pe... | def draw_line(
self,
line_pts,
color="#ff0000",
robot_coordinates=False,
relative_to_first=False,
arrow=True,
scale=(1, 1),
**kwargs
) | :param line_pts: A list of (x,y) pairs to draw. (x,y) are in field units
which are measured in feet
:param color: The color of the line, expressed as a 6-digit hex color
:param robot_coordinates: If True, the pts will be adjusted such that
... | 5.331195 | 5.028022 | 1.060297 |
x, y = pt
def _defer(): # called later because the field might not exist yet
px_per_ft = UserRenderer._global_ui.field.px_per_ft
sx, sy = scale
pt = ((x * px_per_ft * sx), (y * px_per_ft * sy))
el = TextElement(text, pt, 0, color, fontSize, **k... | def draw_text(
self,
text,
pt,
color="#000000",
fontSize=10,
robot_coordinates=False,
scale=(1, 1),
**kwargs
) | :param text: Text to render
:param pt: A tuple of (x,y) in field units (which are measured in feet)
:param color: The color of the text, expressed as a 6-digit hex color
:param robot_coordinates: If True, the pt will be adjusted such that
the poi... | 5.830004 | 5.953983 | 0.979177 |
# 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.
# They're not real... | def murmur2(key) | 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 | 1.607863 | 1.584867 | 1.01451 |
global _ENFORCER
global saved_file_rules
if not _ENFORCER:
_ENFORCER = policy.Enforcer(CONF,
policy_file=policy_file,
rules=rules,
default_rule=default_rule,
... | def init(policy_file=None, rules=None, default_rule=None, use_conf=True) | Init an Enforcer class.
:param policy_file: Custom policy file to use, if none is specified,
`CONF.policy_file` will be used.
:param rules: Default dictionary / Rules to use. It will be
considered just in the first instantiation.
:param default_rule:... | 3.407258 | 3.590666 | 0.948921 |
result = [(rule_name, str(rule)) for rule_name, rule in rules.items()]
return sorted(result, key=lambda rule: rule[0]) | def _serialize_rules(rules) | Serialize all the Rule object as string.
New string is used to compare the rules list. | 3.512098 | 3.145812 | 1.116436 |
for rule in rules:
# We will skip the warning for the resources which support user based
# policy enforcement.
if [resource for resource in USER_BASED_RESOURCES
if resource in rule[0]]:
continue
if 'user_id' in KEY_EXPR.findall(rule[1]):
L... | def _warning_for_deprecated_user_based_rules(rules) | Warning user based policy enforcement used in the rule but the rule
doesn't support it. | 5.988068 | 5.661042 | 1.057768 |
init()
credentials = context.to_policy_values()
try:
result = _ENFORCER.authorize(action, target, credentials,
do_raise=do_raise, action=action)
return result
except policy.PolicyNotRegistered:
LOG.exception('Policy not registered')
... | def authorize(context, action, target, do_raise=True) | Verify that the action is valid on the target in this context.
:param context: monasca project context
:param action: String representing the action to be checked. This
should be colon separated for clarity.
:param target: Dictionary representing the object of the action for
... | 4.127424 | 4.13114 | 0.9991 |
init()
credentials = context.to_policy_values()
target = credentials
return _ENFORCER.authorize('admin_required', target, credentials) | def check_is_admin(context) | Check if roles contains 'admin' role according to policy settings. | 16.066345 | 14.985613 | 1.072118 |
def set_rules(rules, overwrite=True, use_conf=False): # pragma: no cover
init(use_conf=False)
_ENFORCER.set_rules(rules, overwrite, use_conf) | Set rules based on the provided dict of rules.
Note:
Used in tests only.
:param rules: New rules to use. It should be an instance of dict
:param overwrite: Whether to overwrite current rules or update them
with the new rules.
:param use_conf: Whether to reload rules from ... | null | null | null | |
if _ENFORCER:
current_rule = str(_ENFORCER.rules[old_policy])
else:
current_rule = None
if current_rule != default_rule:
LOG.warning("Start using the new action '{0}'. The existing "
"action '{1}' is being deprecated and will be "
"remov... | def verify_deprecated_policy(old_policy, new_policy, default_rule, context) | Check the rule of the deprecated policy action
If the current rule of the deprecated policy action is set to a non-default
value, then a warning message is logged stating that the new policy
action should be used to dictate permissions as the old policy action is
being deprecated.
:param old_polic... | 4.066021 | 3.84633 | 1.057117 |
x = [numpy.random.uniform(-1, 1, size=N)
for _i in range(0, 5)]
noise = numpy.random.standard_normal(N)
y = numpy.log(4.0 + numpy.sin(4 * x[0]) + numpy.abs(x[1]) + x[2] ** 2 +
x[3] ** 3 + x[4] + 0.1 * noise)
return x, y | def build_sample_ace_problem_wang04(N=100) | Build sample problem from Wang 2004. | 3.308003 | 3.195009 | 1.035366 |
x, y = build_sample_ace_problem_wang04(N=200)
ace_solver = ace.ACESolver()
ace_solver.specify_data_set(x, y)
ace_solver.solve()
try:
ace.plot_transforms(ace_solver, 'ace_transforms_wang04.png')
ace.plot_input(ace_solver, 'ace_input_wang04.png')
except ImportError:
pa... | def run_wang04() | Run sample problem. | 5.166042 | 4.729093 | 1.092396 |
# connect to the controller
# -> this is to support module robots
controller.on_mode_change(self._on_robot_mode_change)
self.robots.append(controller) | def add_robot(self, controller) | Add a robot controller | 9.816233 | 9.334184 | 1.051643 |
self.robots[n].set_joystick(x, y) | def set_joystick(self, x, y, n) | Receives joystick values from the SnakeBoard
x,y Coordinates
n Robot number to give it to | 5.914251 | 5.056702 | 1.169587 |
async with self._disconnect_lock:
if self._state == ConnectionState.DISCONNECTED:
return
self._set_state(ConnectionState.DISCONNECTING)
logger.info('%s Disconnecting...', self.fingerprint)
if self._reconnect_task:
self._... | async def disconnect(self) | Disconnect coroutine | 2.487905 | 2.373328 | 1.048277 |
if self._state == ConnectionState.DISCONNECTED:
return
self._set_state(ConnectionState.DISCONNECTING)
logger.info('%s Disconnecting...', self.fingerprint)
if self._reconnect_task and not self._reconnect_task.done():
self._reconnect_task.cancel()
... | def close(self) | Same as disconnect, but not a coroutine, i.e. it does not wait
for disconnect to finish. | 2.668985 | 2.421991 | 1.10198 |
return self._db.call(func_name, args,
timeout=timeout, push_subscribe=push_subscribe) | def call(self, func_name, args=None, *,
timeout=-1.0, push_subscribe=False) -> _MethodRet | Call request coroutine. It is a call with a new behaviour
(return result of a Tarantool procedure is not wrapped into
an extra tuple). If you're connecting to Tarantool with
version < 1.7, then this call method acts like a call16 method
Examples:
.. code-blo... | 3.586115 | 5.447583 | 0.658295 |
return self._db.eval(expression, args,
timeout=timeout, push_subscribe=push_subscribe) | def eval(self, expression, args=None, *,
timeout=-1.0, push_subscribe=False) -> _MethodRet | Eval request coroutine.
Examples:
.. code-block:: pycon
>>> await conn.eval('return 42')
<Response sync=3 rowcount=1 data=[42]>
>>> await conn.eval('return box.info.version')
<Response sync=3 rowcount=1 data=['2.1.1-7-gd381a45b... | 4.027774 | 6.328042 | 0.636496 |
return self._db.select(space, key, **kwargs) | def select(self, space, key=None, **kwargs) -> _MethodRet | Select request coroutine.
Examples:
.. code-block:: pycon
>>> await conn.select('tester')
<Response sync=3 rowcount=2 data=[
<TarantoolTuple id=1 name='one'>,
<TarantoolTuple id=2 name='two'>
]>
... | 6.362523 | 18.582117 | 0.3424 |
return self._db.insert(space, t,
replace=replace,
timeout=timeout) | def insert(self, space, t, *, replace=False, timeout=-1) -> _MethodRet | Insert request coroutine.
Examples:
.. code-block:: pycon
# Basic usage
>>> await conn.insert('tester', [0, 'hello'])
<Response sync=3 rowcount=1 data=[
<TarantoolTuple id=0 name='hello'>
]>
#... | 4.871678 | 8.898727 | 0.547458 |
return self._db.replace(space, t, timeout=timeout) | def replace(self, space, t, *, timeout=-1.0) -> _MethodRet | Replace request coroutine. Same as insert, but replace.
:param space: space id or space name.
:param t: tuple to insert (list object)
:param timeout: Request timeout
:returns: :class:`asynctnt.Response` instance | 6.373857 | 11.380357 | 0.560075 |
return self._db.delete(space, key, **kwargs) | def delete(self, space, key, **kwargs) -> _MethodRet | Delete request coroutine.
Examples:
.. code-block:: pycon
# Assuming tuple [0, 'hello'] is in space tester
>>> await conn.delete('tester', [0])
<Response sync=3 rowcount=1 data=[
<TarantoolTuple id=0 name='hello'>
... | 6.985124 | 18.143541 | 0.384992 |
return self._db.update(space, key, operations, **kwargs) | def update(self, space, key, operations, **kwargs) -> _MethodRet | Update request coroutine.
Examples:
.. code-block:: pycon
# Assuming tuple [0, 'hello'] is in space tester
>>> await conn.update('tester', [0], [ ['=', 1, 'hi!'] ])
<Response sync=3 rowcount=1 data=[
<TarantoolTuple id=0 nam... | 5.600248 | 13.95293 | 0.401367 |
return self._db.upsert(space, t, operations, **kwargs) | def upsert(self, space, t, operations, **kwargs) -> _MethodRet | Update request coroutine. Performs either insert or update
(depending of either tuple exists or not)
Examples:
.. code-block:: pycon
# upsert does not return anything
>>> await conn.upsert('tester', [0, 'hello'],
... ... | 4.834594 | 10.766586 | 0.449037 |
return self._db.sql(query, args,
parse_metadata=parse_metadata,
timeout=timeout) | def sql(self, query, args=None, *,
parse_metadata=True, timeout=-1.0) -> _MethodRet | Executes an SQL statement (only for Tarantool > 2)
Examples:
.. code-block:: pycon
>>> await conn.sql("select 1 as a, 2 as b")
<Response sync=3 rowcount=1 data=[<TarantoolTuple A=1 B=2>]>
>>> await conn.sql("select * from sql_space")
... | 3.460607 | 6.009326 | 0.575873 |
self._compute_primary_smooths()
self._smooth_the_residuals()
self._select_best_smooth_at_each_point()
self._enhance_bass()
self._smooth_best_span_estimates()
self._apply_best_spans_to_primaries()
self._smooth_interpolated_smooth()
self._store_unso... | def compute(self) | Run the SuperSmoother. | 8.744872 | 7.945412 | 1.100619 |
for span in DEFAULT_SPANS:
smooth = smoother.perform_smooth(self.x, self.y, span)
self._primary_smooths.append(smooth) | def _compute_primary_smooths(self) | Compute fixed-span smooths with all of the default spans. | 6.39384 | 4.305172 | 1.485153 |
for primary_smooth in self._primary_smooths:
smooth = smoother.perform_smooth(self.x,
primary_smooth.cross_validated_residual,
MID_SPAN)
self._residual_smooths.append(smooth.smooth_result) | def _smooth_the_residuals(self) | Apply the MID_SPAN to the residuals of the primary smooths.
"For stability reasons, it turns out to be a little better to smooth
|r_{i}(J)| against xi" - [1] | 10.691808 | 6.677977 | 1.601055 |
for residuals_i in zip(*self._residual_smooths):
index_of_best_span = residuals_i.index(min(residuals_i))
self._best_span_at_each_point.append(DEFAULT_SPANS[index_of_best_span]) | def _select_best_smooth_at_each_point(self) | Solve Eq (10) to find the best span for each observation.
Stores index so we can easily grab the best residual smooth, primary smooth, etc. | 4.63066 | 3.648595 | 1.269163 |
if not self._bass_enhancement:
# like in supsmu, skip if alpha=0
return
bass_span = DEFAULT_SPANS[BASS_INDEX]
enhanced_spans = []
for i, best_span_here in enumerate(self._best_span_at_each_point):
best_smooth_index = DEFAULT_SPANS.index(best_s... | def _enhance_bass(self) | Update best span choices with bass enhancement as requested by user (Eq. 11). | 3.50431 | 3.210247 | 1.091601 |
self._smoothed_best_spans = smoother.perform_smooth(self.x,
self._best_span_at_each_point,
MID_SPAN) | def _smooth_best_span_estimates(self) | Apply a MID_SPAN smooth to the best span estimates at each observation. | 10.592485 | 5.92929 | 1.786468 |
self.smooth_result = []
for xi, best_span in enumerate(self._smoothed_best_spans.smooth_result):
primary_values = [s.smooth_result[xi] for s in self._primary_smooths]
# pylint: disable=no-member
best_value = numpy.interp(best_span, DEFAULT_SPANS, primary_valu... | def _apply_best_spans_to_primaries(self) | Apply best spans.
Given the best span, interpolate to compute the best smoothed value
at each observation. | 5.496458 | 4.303645 | 1.277163 |
smoothed_results = smoother.perform_smooth(self.x,
self.smooth_result,
TWEETER_SPAN)
self.smooth_result = smoothed_results.smooth_result | def _smooth_interpolated_smooth(self) | Smooth interpolated results with tweeter span.
A final step of the supersmoother is to smooth the interpolated values with
the tweeter span. This is done in Breiman's supsmu.f but is not explicitly
discussed in the publication. This step is necessary to match
the FORTRAN version perfect... | 8.087816 | 5.042947 | 1.603788 |
# Initial interval for retries in seconds.
interval = 1
while not events.exit.is_set():
try:
# Make the child processes open separate socket connections
client.reinit()
# We will start consumers without auto-commit. Auto-commit will be
# done by... | def _mp_consume(client, group, topic, queue, size, events, **consumer_options) | A child process worker which consumes messages based on the
notifications given by the controller process
NOTE: Ideally, this should have been a method inside the Consumer
class. However, multiprocessing module has issues in windows. The
functionality breaks unless this function is kept outside of a cl... | 5.225473 | 5.077811 | 1.02908 |
# rotate movement vector according to the angle of the object
vx, vy = v
vx, vy = (
vx * math.cos(self.angle) - vy * math.sin(self.angle),
vx * math.sin(self.angle) + vy * math.cos(self.angle),
)
def _move(xy):
x, y = xy
... | def move(self, v) | v is a tuple of x/y coordinates to move object | 3.873967 | 3.752808 | 1.032285 |
self.angle = (self.angle + angle) % (math.pi * 2.0)
# precalculate these parameters
c = math.cos(angle)
s = math.sin(angle)
px, py = self.center
def _rotate_point(xy):
x, y = xy
x = x - px
y = y - py
return (x... | def rotate(self, angle) | This works. Rotates the object about its center.
Angle is specified in radians | 3.165363 | 3.219133 | 0.983297 |
if err is not None:
log.exception(u'Message delivery failed: {}'.format(err))
raise confluent_kafka.KafkaException(err)
else:
log.debug(u'Message delivered to {} [{}]: {}'.format(
msg.topic(), msg.partition(), msg.value())) | def delivery_report(err, msg) | Callback called once for each produced message to indicate the final
delivery result. Triggered by poll() or flush().
:param confluent_kafka.KafkaError err: Information about any error
that occurred whilst producing the message.
:param confluent_kafka.Message msg: Information about the ... | 2.986547 | 2.770409 | 1.078017 |
if not isinstance(messages, list):
messages = [messages]
try:
for m in messages:
m = encodeutils.safe_encode(m, incoming='utf-8')
self._producer.produce(topic, m, key,
callback=KafkaProducer.deliver... | def publish(self, topic, messages, key=None, timeout=2) | Publish messages to the topic.
:param str topic: Topic to produce messages to.
:param list(str) messages: List of message payloads.
:param str key: Message key.
:param float timeout: Maximum time to block in seconds.
:returns: Number of messages still in queue.
:rtype i... | 4.29529 | 4.370065 | 0.982889 |
self.slept = [True] * 3
was_paused = False
with self.lock:
self._increment_tm(secs)
while self.paused and secs > 0:
if self.pause_secs is not None:
# if pause_secs is set, this means it was a step operation,
... | def increment_time_by(self, secs) | This is called when wpilib.Timer.delay() occurs | 5.382697 | 5.435986 | 0.990197 |
try:
site_id = page.node.site_id
except AttributeError:
site_id = page.site_id
return _get_cache_key('page_sitemap', page, 'default', site_id) | def get_cache_key(page) | Create the cache key for the current page and language | 3.809994 | 3.688907 | 1.032825 |
if timestep is not None:
stem = (stem + INT_FMT).format(timestep)
return conf.core.outname + '_' + stem | def out_name(stem, timestep=None) | 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'``. | 9.449075 | 7.782781 | 1.2141 |
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) | def saveplot(fig, *name_args, close=True, **name_kwargs) | 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_... | 3.300898 | 3.658266 | 0.902312 |
doc = getdoc(obj)
if not doc:
return ''
doc = doc.splitlines()[0]
return doc.rstrip(' .').lstrip() | def baredoc(obj) | 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. | 3.967187 | 4.177042 | 0.94976 |
aaa, bbb = '{:.2e}'.format(tin).split('e')
bbb = int(bbb)
return r'$t={} \times 10^{{{}}}$'.format(aaa, bbb) | def fmttime(tin) | Return LaTeX expression with time in scientific notation.
Args:
tin (float): the time.
Returns:
str: the LaTeX expression. | 3.829172 | 3.721443 | 1.028948 |
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] | def list_of_vars(arg_plot) | 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;
... | 3.658411 | 4.380571 | 0.835145 |
return set(var for pvars in lovs for svars in pvars for var in svars) | def set_of_vars(lovs) | 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. | 5.908273 | 9.642273 | 0.612747 |
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 | def get_rbounds(step) | 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. | 5.373741 | 5.125003 | 1.048534 |
names = list(names[:len(self._fnames)])
self._fnames = names + self._fnames[len(names):] | def fnames(self, names) | Ensure constant size of fnames | 4.756955 | 3.921416 | 1.213071 |
if times is None:
times = {}
for vfig in lovs:
fig, axes = plt.subplots(nrows=len(vfig), sharex=True,
figsize=(12, 2 * len(vfig)))
axes = [axes] if len(vfig) == 1 else axes
fname = ['time']
for iplt, vplt in enumerate(vfig):
... | def _plot_time_list(sdat, lovs, tseries, metas, times=None) | Plot requested profiles | 2.990381 | 3.006763 | 0.994551 |
tseries = sdat.tseries_between(tstart, tend)
if var in tseries.columns:
series = tseries[var]
time = None
if var in phyvars.TIME:
meta = phyvars.TIME[var]
else:
meta = phyvars.Vart(var, None, '1')
elif var in phyvars.TIME_EXTRA:
meta = phy... | def get_time_series(sdat, var, tstart, tend) | Extract or compute and rescale a time series.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
var (str): time series name, a key of :data:`stagpy.phyvars.TIME`
or :data:`stagpy.phyvars.TIME_EXTRA`.
tstart (float): starting time of desired series. Set ... | 4.750032 | 3.647016 | 1.302444 |
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 is not None:
times[tva... | def plot_time_series(sdat, lovs) | 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... | 3.353279 | 3.162939 | 1.060178 |
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)**2, x=time, axis=0) / delta_time)
with o... | def compstat(sdat, tstart=None, tend=None) | 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... | 2.815747 | 2.804467 | 1.004022 |
sdat = StagyyData(conf.core.path)
if sdat.tseries is None:
return
if conf.time.fraction is not None:
if not 0 < conf.time.fraction <= 1:
raise InvalidTimeFractionError(conf.time.fraction)
conf.time.tend = None
t_0 = sdat.tseries.iloc[0].loc['t']
t_f ... | def cmd() | Implementation of time subcommand.
Other Parameters:
conf.time
conf.core | 4.296087 | 3.993761 | 1.075699 |
sdat = stagyydata.StagyyData(conf.core.path)
lsnap = sdat.snaps.last
lstep = sdat.steps.last
print('StagYY run in {}'.format(sdat.path))
if lsnap.geom.threed:
dimension = '{} x {} x {}'.format(lsnap.geom.nxtot,
lsnap.geom.nytot,
... | def info_cmd() | Print basic information about StagYY run. | 3.290987 | 3.005816 | 1.094873 |
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
ncols = min(ncols, len(key_val))
wrapper = TextWrapper(width=colw)
... | def _pretty_print(key_val, sep=': ', min_col_width=39, text_width=None) | 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
... | 2.416807 | 2.471755 | 0.97777 |
desc = [(v, m.description) for v, m in dict_vars.items()]
desc.extend((v, baredoc(m.description))
for v, m in dict_vars_extra.items())
_pretty_print(desc, min_col_width=26) | def _layout(dict_vars, dict_vars_extra) | Print nicely [(var, description)] from phyvars | 6.378685 | 5.415277 | 1.177905 |
print_all = not any(val for _, val in conf.var.opt_vals_())
if print_all or conf.var.field:
print('field:')
_layout(phyvars.FIELD, phyvars.FIELD_EXTRA)
print()
if print_all or conf.var.sfield:
print('surface field:')
_layout(phyvars.SFIELD, {})
print()
... | def var_cmd() | Print a list of available variables.
See :mod:`stagpy.phyvars` where the lists of variables organized by command
are defined. | 3.464264 | 3.245527 | 1.067397 |
_, empty, faulty = parsing_out
if CONFIG_FILE in empty or CONFIG_FILE in faulty:
print('Unable to read global config file', CONFIG_FILE,
file=sys.stderr)
print('Please run stagpy config --create',
sep='\n', end='\n\n', file=sys.stderr)
if CONFIG_LOCAL in faul... | def report_parsing_problems(parsing_out) | Output message about potential parsing problems. | 3.572454 | 3.677536 | 0.971426 |
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)'
hlp_lst.append((op... | def config_pp(subs) | Pretty print of configuration options.
Args:
subs (iterable of str): iterable with the list of conf sections to
print. | 7.485115 | 7.105906 | 1.053365 |
if not (conf.common.config or conf.config.create or
conf.config.create_local or conf.config.update or
conf.config.edit):
config_pp(conf.sections_())
loam.tools.config_cmd_handler(conf) | def config_cmd() | Configuration handling.
Other Parameters:
conf.config | 12.549479 | 13.243952 | 0.947563 |
if rads is None:
rads = {}
for vfig in lovs:
fig, axes = plt.subplots(ncols=len(vfig), sharey=True)
axes = [axes] if len(vfig) == 1 else axes
fname = 'rprof_'
for iplt, vplt in enumerate(vfig):
xlabel = None
for ivar, rvar in enumerate(vplt):
... | def _plot_rprof_list(sdat, lovs, rprofs, metas, stepstr, rads=None) | Plot requested profiles | 3.016373 | 3.018266 | 0.999373 |
if var in step.rprof.columns:
rprof = step.rprof[var]
rad = None
if var in phyvars.RPROF:
meta = phyvars.RPROF[var]
else:
meta = phyvars.Varr(var, None, '1')
elif var in phyvars.RPROF_EXTRA:
meta = phyvars.RPROF_EXTRA[var]
rprof, rad =... | def get_rprof(step, var) | Extract or compute and rescale requested radial profile.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): radial profile name, a key of :data:`stagpy.phyvars.RPROF`
or :data:`stagpy.phyvars.RPROF_EXTRA`.
Returns:
tuple o... | 4.864733 | 3.72223 | 1.30694 |
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')
ax2.set_ylabel('$dr... | def plot_grid(step) | 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. | 3.591226 | 3.691571 | 0.972818 |
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 z spacing for the moment
f... | def plot_average(sdat, lovs) | 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... | 4.189383 | 4.162008 | 1.006577 |
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
if rad is not None:
... | def plot_every_step(sdat, lovs) | 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... | 4.317855 | 4.678998 | 0.922816 |
sdat = StagyyData(conf.core.path)
if sdat.rprof is None:
return
if conf.rprof.grid:
for step in sdat.walk.filter(rprof=True):
plot_grid(step)
lovs = misc.list_of_vars(conf.rprof.plot)
if not lovs:
return
if conf.rprof.average:
plot_average(sdat... | def cmd() | Implementation of rprof subcommand.
Other Parameters:
conf.rprof
conf.core | 7.108173 | 6.160105 | 1.153905 |
if not DEBUG:
signal.signal(signal.SIGINT, sigint_handler)
warnings.simplefilter('ignore')
args = importlib.import_module('stagpy.args')
error = importlib.import_module('stagpy.error')
try:
args.parse_args()()
except error.StagpyError as err:
if DEBUG:
... | def main() | StagPy entry point | 4.610353 | 4.195447 | 1.098894 |
par_new = f90nml.read(str(par_file))
for section, content in par_new.items():
if section not in par_nml:
par_nml[section] = {}
for par, value in content.items():
try:
content[par] = value.strip()
except AttributeError:
pass... | def _enrich_with_par(par_nml, par_file) | Enrich a par namelist with the content of a file. | 2.531721 | 2.529798 | 1.00076 |
par_nml = deepcopy(PAR_DEFAULT)
if PAR_DFLT_FILE.is_file():
_enrich_with_par(par_nml, PAR_DFLT_FILE)
else:
PAR_DFLT_FILE.parent.mkdir(exist_ok=True)
f90nml.write(par_nml, str(PAR_DFLT_FILE))
if not par_file.is_file():
raise NoParFileError(par_file)
par_main = ... | def readpar(par_file, root) | Read StagYY par file.
The namelist is populated in chronological order with:
- :data:`PAR_DEFAULT`, an internal dictionary defining defaults;
- :data:`PAR_DFLT_FILE`, the global configuration par file;
- ``par_name_defaultparameters`` if it is defined in ``par_file``;
- ``par_file`` itself;
- ... | 2.472283 | 2.186873 | 1.130511 |
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, :, :]
fld = fld[0, :, :, 0... | def get_meshes_fld(step, var) | 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... | 2.409537 | 2.237751 | 1.076767 |
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.geom.y_mesh[0, :, :], step.geom.z... | def get_meshes_vec(step, var) | 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... | 1.993778 | 1.930704 | 1.032668 |
sovs = set(tuple((var + '+').split('+')[:2])
for var in arg_plot.split(','))
sovs.discard(('', ''))
return sovs | def set_of_vars(arg_plot) | 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... | 8.173365 | 8.124283 | 1.006041 |
if var in phyvars.FIELD:
meta = phyvars.FIELD[var]
else:
meta = phyvars.FIELD_EXTRA[var]
meta = phyvars.Varf(misc.baredoc(meta.description), meta.dim)
if step.geom.threed:
raise NotAvailableError('plot_scalar only implemented for 2D fields')
xmesh, ymesh, fld = get_... | def plot_scalar(step, var, field=None, axis=None, set_cbar=True, **extra) | Plot scalar field.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): the scalar field name.
field (:class:`numpy.array`): if not None, it is plotted instead of
step.fields[var]. This is useful to plot a masked or rescaled
... | 3.648657 | 3.470671 | 1.051283 |
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) | def plot_iso(axis, step, var) | 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): ... | 4.937286 | 5.650699 | 0.873748 |
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:
dipx = dipz
else:
... | def plot_vec(axis, step, var) | 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... | 3.782022 | 3.952196 | 0.956942 |
sdat = StagyyData(conf.core.path)
sovs = set_of_vars(conf.field.plot)
minmax = {}
if conf.plot.cminmax:
conf.plot.vmin = None
conf.plot.vmax = None
for step in sdat.walk.filter(snap=True):
for var, _ in sovs:
if var in step.fields:
... | def cmd() | Implementation of field subcommand.
Other Parameters:
conf.field
conf.core | 3.750988 | 3.65306 | 1.026807 |
cmd_func = cmd if isfunction(cmd) else cmd.cmd
return Subcmd(baredoc(cmd), *sections, func=cmd_func) | def _sub(cmd, *sections) | Build Subcmd instance. | 12.940388 | 8.802541 | 1.470074 |
if not (conf.core.timesteps or conf.core.snapshots):
# default to the last snap
conf.core.timesteps = None
conf.core.snapshots = slice(-1, None, None)
return
elif conf.core.snapshots:
# snapshots take precedence over timesteps
# if both are defined
co... | def _steps_to_slices() | parse timesteps and snapshots arguments and return slices | 2.548724 | 2.384811 | 1.068732 |
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:
return cmd_args.func
if sub... | def parse_args(arglist=None) | 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. | 11.854525 | 11.271756 | 1.051702 |
for trench in trenches:
axis.axvline(
x=trench, ymin=ymin, ymax=ymax,
color='red', ls='dashed', alpha=0.4)
for ridge in ridges:
axis.axvline(
x=ridge, ymin=ymin, ymax=ymax,
color='green', ls='dashed', alpha=0.4)
axis.set_xlim(0, 2 * np.pi)... | def plot_plate_limits(axis, ridges, trenches, ymin, ymax) | plot lines designating ridges and trenches | 1.839769 | 1.851834 | 0.993485 |
for trench in trenches:
xxd = (rcmb + 1.02) * np.cos(trench) # arrow begin
yyd = (rcmb + 1.02) * np.sin(trench) # arrow begin
xxt = (rcmb + 1.35) * np.cos(trench) # arrow end
yyt = (rcmb + 1.35) * np.sin(trench) # arrow end
axis.annotate('', xy=(xxd, yyd), xytext=(xx... | def plot_plate_limits_field(axis, rcmb, ridges, trenches) | plot arrows designating ridges and trenches in 2D field plots | 1.574125 | 1.537669 | 1.023709 |
fid.write("{} {}".format(timestep, time))
fid.writelines(["%10.2e" % item for item in fld[:]])
fid.writelines(["\n"]) | def io_surface(timestep, time, fid, fld) | Output for surface files | 4.678402 | 4.759942 | 0.98287 |
return set(var for var in arg_plot.split(',') if var in phyvars.PLATES) | def set_of_vars(arg_plot) | Build set of needed variables.
Args:
arg_plot (str): string with variable names separated with ``,``.
Returns:
set of str: set of variables. | 18.729271 | 18.172081 | 1.030662 |
sdat = StagyyData(conf.core.path)
conf.plates.plot = set_of_vars(conf.plates.plot)
if not conf.plates.vzcheck:
conf.scaling.dimensional = True
conf.scaling.factors['Pa'] = 'M'
main_plates(sdat)
else:
seuil_memz = 0
nb_plates = []
time = []
ch2... | def cmd() | Implementation of plates subcommand.
Other Parameters:
conf.plates
conf.scaling
conf.plot
conf.core | 3.906756 | 3.713918 | 1.051923 |
config.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
verfile = config.CONFIG_DIR / '.version'
uptodate = verfile.is_file() and verfile.read_text() == __version__
if not uptodate:
verfile.write_text(__version__)
if not (uptodate and config.CONFIG_FILE.is_file()):
conf.create_conf... | def _check_config() | Create config files as necessary. | 3.299578 | 3.235554 | 1.019788 |
plt = importlib.import_module('matplotlib.pyplot')
if conf.plot.mplstyle:
for style in conf.plot.mplstyle.split():
stfile = config.CONFIG_DIR / (style + '.mplstyle')
if stfile.is_file():
style = str(stfile)
try:
plt.style.use(style... | def load_mplstyle() | Try to load conf.plot.mplstyle matplotlib style. | 3.260286 | 2.891504 | 1.12754 |
tseries = sdat.tseries_between(tstart, tend)
time = tseries['t'].values
return time[1:] - time[:-1], time[:-1] | def dtime(sdat, tstart=None, tend=None) | 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... | 6.154161 | 7.549828 | 0.815139 |
tseries = sdat.tseries_between(tstart, tend)
time = tseries['t'].values
temp = tseries['Tmean'].values
dtdt = (temp[1:] - temp[:-1]) / (time[1:] - time[:-1])
return dtdt, time[:-1] | def dt_dt(sdat, tstart=None, tend=None) | Derivative of temperature.
Compute dT/dt as a function of time using an explicit Euler scheme.
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... | 3.524496 | 3.965729 | 0.888739 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.