output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Writes data as json.
Given the following Python 3 function, write the documentation def as_json(data, **kwargs): 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
As a Python code analyst, you investigate and solve complex coding mysteries
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 ...
Can you write a function in Python 3 where it reads HTTP body according to given content type.
As a python code expert, you are capable of creating scripts from specifications.
def timer_fired(self): """Polling loop for events from other threads""" 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_f...
Create a Python 3 function to poll loop for events from other threads
You are a Python code generator, capable of creating scripts from specifications.
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 ...
Can you create a Python 3 function that encodes the given data with snappy
You are a Python code analyst, evaluating scripts for potential improvements.
Draw a line of the specified number of points from the current field.
Explain what the following Python 3 code does 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...
As a Python code analyst, you investigate and solve complex coding mysteries
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) ...
Write a Python 3 script to draw the text at the specified point.
As a Python code analyst, you investigate and solve complex coding mysteries
Pure - python Murmur2 implementation.
Can you tell what is the following Python 3 function doing 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...
As a Python code composer, you craft elegant and concise scripts.
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 ...
Create a Python 3 function to initialize an Enforcer class.
As a Python code analyst, you investigate and solve complex coding mysteries
Serialize all the Rule object as string. New string is used to compare the rules list.
Make a summary of the following Python 3 code def _serialize_rules(rules): result = [(rule_name, str(rule)) for rule_name, rule in rules.items()] return sorted(result, key=lambda rule: rule[0])
As a python code expert, you are capable of creating scripts from specifications.
def _warning_for_deprecated_user_based_rules(rules): """Warning user based policy enforcement used in the rule but the rule doesn't support it. """ for rule in rules: # We will skip the warning for the resources which support user based # policy enforcement. if [resource for reso...
Can you implement a function in Python 3 that deprecates user based policy enforcement used in the rule but the rule doesn t support it.
You are a Python code architect, reviewing and designing scalable and efficient code
Verify that the action is valid on the target in this context.
Can you tell what is the following Python 3 function doing def authorize(context, action, target, do_raise=True): init() credentials = context.to_policy_values() try: result = _ENFORCER.authorize(action, target, credentials, do_raise=do_raise, action=action) ...
As a python code expert, you are capable of creating scripts from specifications.
Check if roles contains admin role according to policy settings.
Can you generate the documentation for the following Python 3 function def check_is_admin(context): init() credentials = context.to_policy_values() target = credentials return _ENFORCER.authorize('admin_required', target, credentials)
As a Python code composer, you craft elegant and concise scripts.
Set the rules of the current node.
Can you generate a brief explanation for the following Python 3 code def set_rules(rules, overwrite=True, use_conf=False): # pragma: no cover init(use_conf=False) _ENFORCER.set_rules(rules, overwrite, use_conf)
As a Python code composer, you craft elegant and concise scripts.
Verify that the old_policy is being deprecated and that the new_policy is being replaced with the new_policy.
How would you explain what the following Python 3 function does def verify_deprecated_policy(old_policy, new_policy, default_rule, context): if _ENFORCER: current_rule = str(_ENFORCER.rules[old_policy]) else: current_rule = None if current_rule != default_rule: LOG.warning("Start u...
As a Python code translator, you convert algorithms and pseudocode into Python.
def build_sample_ace_problem_wang04(N=100): """Build sample problem from Wang 2004.""" 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[...
Write a Python 3 script for building sample problem from Wang 2004.
As a Python code analyst, you investigate and solve complex coding mysteries
def run_wang04(): """Run sample problem.""" 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_wang...
Can you write a function in Python 3 where it runs sample problem with Wang - 04 ACE.
As a Python code composer, you craft elegant and concise scripts.
Add a robot controller to the list of robots
Can you tell what is the following Python 3 function doing def add_robot(self, controller): # connect to the controller # -> this is to support module robots controller.on_mode_change(self._on_robot_mode_change) self.robots.append(controller)
As a Python code analyst, you investigate and solve complex coding mysteries
Sets the joystick coordinates of the iCal entry with the coordinates x y.
Can you generate the documentation for the following Python 3 function def set_joystick(self, x, y, n): self.robots[n].set_joystick(x, y)
As a Python code translator, you convert algorithms and pseudocode into Python.
async def disconnect(self): """ Disconnect coroutine """ async with self._disconnect_lock: if self._state == ConnectionState.DISCONNECTED: return self._set_state(ConnectionState.DISCONNECTING) logger.info('%s Disconnecting...', s...
Implement a Python 3 function for disconnecting from the broker.
As a Python code translator, you convert algorithms and pseudocode into Python.
Same as disconnect, but not a coroutine, i.e. it does not wait for disconnect to finish.
Can you tell what is the following Python 3 function doing def close(self): if self._state == ConnectionState.DISCONNECTED: return self._set_state(ConnectionState.DISCONNECTING) logger.info('%s Disconnecting...', self.fingerprint) if self._reconnect_task and not self._reco...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Can you create a Python 3 function that calls 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-block:: pycon # tarantoo...
As a Python code analyst, you investigate and solve complex coding mysteries
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]> ...
Create a Python 3 function for executing an expression and return the result.
You are a Python code analyst, evaluating scripts for potential improvements.
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'>,...
Write a Python 3 script for selecting an object in a specific space.
As a Python code analyst, you investigate and solve complex coding mysteries
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 dat...
How would you code a function in Python 3 to insert a new entry into the database.
You are a Python code architect, reviewing and designing scalable and efficient code
Replace an entry in the cache with a new one.
Make a summary of the following Python 3 code def replace(self, space, t, *, timeout=-1.0) -> _MethodRet: return self._db.replace(space, t, timeout=timeout)
As a Python code translator, you convert algorithms and pseudocode into Python.
Delete an object in a specific space.
Here you have a function in Python 3, explain what it does def delete(self, space, key, **kwargs) -> _MethodRet: return self._db.delete(space, key, **kwargs)
As a Python code translator, you convert algorithms and pseudocode into Python.
Update the object in a specific key in a space.
Can you generate a brief explanation for the following Python 3 code def update(self, space, key, operations, **kwargs) -> _MethodRet: return self._db.update(space, key, operations, **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
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 ...
Implement a Python 3 function for inserting or update a tuple in a space.
You are a Python code analyst, evaluating scripts for potential improvements.
Executes an SQL query and returns the result.
Given the following Python 3 function, write the documentation 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 ...
You are a Python code architect, reviewing and designing scalable and efficient code
Compute fixed - span smooths with all of the default spans.
Can you generate a brief explanation for the following Python 3 code def _compute_primary_smooths(self): for span in DEFAULT_SPANS: smooth = smoother.perform_smooth(self.x, self.y, span) self._primary_smooths.append(smooth)
As a Python code composer, you craft elegant and concise scripts.
Perform the MID_SPAN on the residuals of the primary smooths.
Can you tell what is the following Python 3 function doing def _smooth_the_residuals(self): for primary_smooth in self._primary_smooths: smooth = smoother.perform_smooth(self.x, primary_smooth.cross_validated_residual, ...
As a Python code analyst, you investigate and solve complex coding mysteries
Select the best smooth for each observation at each point.
Can you tell what is the following Python 3 function doing def _select_best_smooth_at_each_point(self): 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])
As a Python code composer, you craft elegant and concise scripts.
Update the best span choices with bass enhancement as requested by user.
How would you explain what the following Python 3 function does def _enhance_bass(self): 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...
You are a Python code generator, capable of creating scripts from specifications.
def _smooth_best_span_estimates(self): """Apply a MID_SPAN smooth to the best span estimates at each observation.""" self._smoothed_best_spans = smoother.perform_smooth(self.x, self._best_span_at_each_point, ...
Implement a Python 3 function for applying a MID_SPAN smooth to the best span estimates at each observation.
You are a Python code analyst, evaluating scripts for potential improvements.
def _apply_best_spans_to_primaries(self): """ Apply best spans. Given the best span, interpolate to compute the best smoothed value at each observation. """ self.smooth_result = [] for xi, best_span in enumerate(self._smoothed_best_spans.smooth_result): ...
Implement a Python 3 function for applying the best spans. Given the best span interpolate to compute the best smoothed value at each observation.
As a python code expert, you are capable of creating scripts from specifications.
Smooth interpolated results with tweeter span.
Can you tell what is the following Python 3 function doing def _smooth_interpolated_smooth(self): smoothed_results = smoother.perform_smooth(self.x, self.smooth_result, TWEETER_SPAN) self.smooth_result ...
As a python code expert, you are capable of creating scripts from specifications.
This function is a multiprocessing module which processes messages based on the messages in the queue and processes them.
How would you explain what the following Python 3 function does def _mp_consume(client, group, topic, queue, size, events, **consumer_options): # Initial interval for retries in seconds. interval = 1 while not events.exit.is_set(): try: # Make the child processes open separate socket co...
As a python code expert, you are capable of creating scripts from specifications.
def move(self, v): """v is a tuple of x/y coordinates to move object""" # 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...
Can you write a function in Python 3 where it moves the object to the new location
You are a Python code analyst, evaluating scripts for potential improvements.
This works. Rotates the object about its center.
Can you tell what is the following Python 3 function doing def rotate(self, angle): 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...
As a Python code composer, you craft elegant and concise scripts.
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 s...
Write a Python 3 function for publishing messages to the specified topic.
As a Python code translator, you convert algorithms and pseudocode into Python.
This is called when the time is in the middle of the operation.
Can you generate the documentation for the following Python 3 function def increment_time_by(self, secs): 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 Non...
As a Python code analyst, you investigate and solve complex coding mysteries
Create the cache key for the current page and language
Explain what the following Python 3 code does def get_cache_key(page): try: site_id = page.node.site_id except AttributeError: site_id = page.site_id return _get_cache_key('page_sitemap', page, 'default', site_id)
You are a Python code generator, capable of creating scripts from specifications.
Return StagPy out file name.
Here you have a function in Python 3, explain what it does def out_name(stem, timestep=None): if timestep is not None: stem = (stem + INT_FMT).format(timestep) return conf.core.outname + '_' + stem
You are a Python code analyst, evaluating scripts for potential improvements.
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....
Write a Python 3 function that can 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_nam...
As a Python code translator, you convert algorithms and pseudocode into Python.
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. """ doc = getdoc(obj) if not ...
Can you create a Python 3 function that returns the first line of the docstring of an object.
As a python code expert, you are capable of creating scripts from specifications.
def fmttime(tin): """Return LaTeX expression with time in scientific notation. Args: tin (float): the time. Returns: str: the LaTeX expression. """ aaa, bbb = '{:.2e}'.format(tin).split('e') bbb = int(bbb) return r'$t={} \times 10^{{{}}}$'.format(aaa, bbb)
Can you implement a function in Python 3 that returns LaTeX expression with time in scientific notation.
You are a Python code analyst, evaluating scripts for potential improvements.
Construct list of variables per plot.
Can you generate the documentation for the following Python 3 function 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 ...
You are a Python code architect, reviewing and designing scalable and efficient code
Build set of variables from list of variables.
Here you have a function in Python 3, explain what it does def set_of_vars(lovs): return set(var for pvars in lovs for svars in pvars for var in svars)
As a Python code analyst, you investigate and solve complex coding mysteries
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. """ if step.geom is not None:...
Write a Python 3 function for returning the radial or vertical positions of boundaries of the current object.
You are a Python code architect, reviewing and designing scalable and efficient code
Ensure constant size of fnames
Can you generate the documentation for the following Python 3 function def fnames(self, names): names = list(names[:len(self._fnames)]) self._fnames = names + self._fnames[len(names):]
You are a Python code analyst, evaluating scripts for potential improvements.
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`. ...
Can you implement a function in Python 3 that extracts or compute a time series from a StagyyData instance and a key of the appropriate type.
As a Python code composer, you craft elegant and concise scripts.
Plot requested time series.
How would you explain what the following Python 3 function does 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...
As a Python code composer, you craft elegant and concise scripts.
Compute statistics from series output by StagYY.
Can you tell what is the following Python 3 function doing 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) /...
You are a Python code architect, reviewing and designing scalable and efficient code
Implementation of time subcommand.
Make a summary of the following Python 3 code def cmd(): 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 ...
As a Python code analyst, you investigate and solve complex coding mysteries
def info_cmd(): """Print basic information about StagYY run.""" 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, ...
Can you write a function in Python 3 where it prints basic information about the current StagYY run.
As a python code expert, you are capable of creating scripts from specifications.
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 ...
Can you write a function in Python 3 where it prints a list of key - value pairs in a pretty format.
As a Python code translator, you convert algorithms and pseudocode into Python.
Print nicely [ var description from phyvars
Make a summary of the following Python 3 code def _layout(dict_vars, dict_vars_extra): 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)
You are a Python code generator, capable of creating scripts from specifications.
Print a list of available variables.
Can you generate the documentation for the following Python 3 function def var_cmd(): 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: ...
You are a Python code generator, capable of creating scripts from specifications.
Output message about potential parsing problems.
Make a summary of the following Python 3 code def report_parsing_problems(parsing_out): _, 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...
As a Python code composer, you craft elegant and concise scripts.
Configuration handling. Other Parameters : conf. config
How would you explain what the following Python 3 function does def config_cmd(): 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)
As a python code expert, you are capable of creating scripts from specifications.
Extract or compute requested radial profile.
Can you generate a brief explanation for the following Python 3 code def get_rprof(step, var): 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') eli...
You are a Python code generator, capable of creating scripts from specifications.
Plot cell position and thickness of a single object.
Make a summary of the following Python 3 code 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('...
You are a Python code analyst, evaluating scripts for potential improvements.
Plot time averaged profiles.
How would you explain what the following Python 3 function does 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_average...
As a Python code analyst, you investigate and solve complex coding mysteries
Plot profiles at each time step.
Here you have a function in Python 3, explain what it does 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) ...
You are a Python code analyst, evaluating scripts for potential improvements.
Implementation of rprof Other Parameters
How would you explain what the following Python 3 function does def cmd(): 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...
As a Python code analyst, you investigate and solve complex coding mysteries
def _enrich_with_par(par_nml, par_file): """Enrich a par namelist with the content of a file.""" 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: ...
Write a Python 3 script for enriching a par namelist with the content of a file.
You are a Python code analyst, evaluating scripts for potential improvements.
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`...
Can you write a function in Python 3 where it reads a new StagYY par file and return a dictionary of names and values.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return scalar field along with coordinates meshes.
Can you tell what is the following Python 3 function doing 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, ymes...
You are a Python code generator, capable of creating scripts from specifications.
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 :clas...
Create a Python 3 function to return vector field components along with coordinates meshes.
You are a Python code analyst, evaluating scripts for potential improvements.
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. ...
Write a Python 3 script to build set of needed field variables.
As a Python code analyst, you investigate and solve complex coding mysteries
Plot a scalar field.
Given the following Python 3 function, write the documentation def plot_scalar(step, var, field=None, axis=None, set_cbar=True, **extra): if var in phyvars.FIELD: meta = phyvars.FIELD[var] else: meta = phyvars.FIELD_EXTRA[var] meta = phyvars.Varf(misc.baredoc(meta.description), meta.dim)...
You are a Python code architect, reviewing and designing scalable and efficient code
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 ...
Write a Python 3 script for plotting isocontours of scalar field.
As a python code expert, you are capable of creating scripts from specifications.
Plot the vector field.
Here you have a function in Python 3, explain what it does 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) i...
As a Python code composer, you craft elegant and concise scripts.
Implementation of field subcommand.
Given the following Python 3 function, write the documentation def cmd(): 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 v...
You are a Python code analyst, evaluating scripts for potential improvements.
parse timesteps and snapshots arguments and return slices
Can you generate the documentation for the following Python 3 function def _steps_to_slices(): 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: ...
As a python code expert, you are capable of creating scripts from specifications.
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 s...
Write a Python 3 function that can parse cmd line arguments.
You are a Python code generator, capable of creating scripts from specifications.
detect plates and check with vz and plate size
Can you generate the documentation for the following Python 3 function def detect_plates_vzcheck(step, seuil_memz): v_z = step.fields['v3'][0, :, :, 0] v_x = step.fields['v2'][0, :, :, 0] tcell = step.fields['T'][0, :, :, 0] n_z = step.geom.nztot nphi = step.geom.nptot # -1? should be OK, ghost not...
As a Python code composer, you craft elegant and concise scripts.
detect plates using derivative of horizontal velocity
Can you generate the documentation for the following Python 3 function def detect_plates(step, vrms_surface, fids, time): vphi = step.fields['v2'][0, :, :, 0] ph_coord = step.geom.p_coord if step.sdat.par['boundaries']['air_layer']: dsa = step.sdat.par['boundaries']['air_thickness'] # we ar...
As a python code expert, you are capable of creating scripts from specifications.
def plot_plate_limits(axis, ridges, trenches, ymin, ymax): """plot lines designating ridges and trenches""" 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=ridg...
Write a Python 3 function that can plot lines designating ridges and trenches
As a Python code translator, you convert algorithms and pseudocode into Python.
plot arrows designating ridges and trenches in 2D field plots
Can you generate the documentation for the following Python 3 function def plot_plate_limits_field(axis, rcmb, ridges, trenches): 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(trenc...
You are a Python code generator, capable of creating scripts from specifications.
Output for surface files
Can you generate a brief explanation for the following Python 3 code def io_surface(timestep, time, fid, fld): fid.write("{} {}".format(timestep, time)) fid.writelines(["%10.2e" % item for item in fld[:]]) fid.writelines(["\n"])
You are a Python code architect, reviewing and designing scalable and efficient code
def lithospheric_stress(step, trench, ridge, time): """calculate stress in the lithosphere""" timestep = step.isnap base_lith = step.geom.rcmb + 1 - 0.105 stressfld = step.fields['sII'][0, :, :, 0] stressfld = np.ma.masked_where(step.geom.r_mesh[0] < base_lith, stressfld) # stress integration ...
Write a Python 3 function that can calculate stress in the lithosphere
You are a Python code generator, capable of creating scripts from specifications.
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. """ return set(var for var in arg_plot.split(',') if var in phyvars.PLATES)
Write a Python 3 script for building set of needed variables.
You are a Python code generator, capable of creating scripts from specifications.
def main_plates(sdat): """Plot several plates information.""" # calculating averaged horizontal surface velocity # needed for redimensionalisation ilast = sdat.rprof.index.levels[0][-1] rlast = sdat.rprof.loc[ilast] nprof = 0 uprof_averaged = rlast.loc[:, 'vhrms'] * 0 for step in sdat.wa...
Write a Python 3 function that can plot several plates information.
As a Python code analyst, you investigate and solve complex coding mysteries
def _check_config(): """Create config files as necessary.""" 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...
Write a Python 3 script to create config files as necessary.
You are a Python code analyst, evaluating scripts for potential improvements.
Try to load conf. plot. mplstyle matplotlib style.
Make a summary of the following Python 3 code def load_mplstyle(): 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 = st...
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Given the following Python 3 function, write the documentation def dtime(sdat, tstart=None, tend=None): tseries = sdat.tseries_between(tstart, tend) time = tseries['t'].values return time[1:] - time[:-1], time[:-1]
You are a Python code architect, reviewing and designing scalable and efficient code
Compute dT and dt as a function of time using an explicit Euler scheme.
Here you have a function in Python 3, explain what it does def dt_dt(sdat, tstart=None, tend=None): 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]
As a python code expert, you are capable of creating scripts from specifications.
def ebalance(sdat, tstart=None, tend=None): """Energy balance. Compute Nu_t - Nu_b + V*dT/dt as a function of time using an explicit Euler scheme. This should be zero if energy is conserved. Args: sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance. tstart (float): tim...
Create a Python 3 function for computing the energy balance of a given time series.
As a python code expert, you are capable of creating scripts from specifications.
Plates mobility. Compute the ratio vsurf / vrms. Compute the ratio vsurf / vrms. Compute the ratio vsurf / vrms. Compute the ratio vsurf / vrms. Compute the ratio vsurf / vrms. Compute the ratio vsurf / vrms. Compute the ratio vsurf / vrms. Compute the ratio vsurf to the mobility of the ...
Can you generate the documentation for the following Python 3 function 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.tim...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the edges of the bottom and top walls of a cluster.
Here you have a function in Python 3, explain what it does 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 = ...
You are a Python code generator, capable of creating scripts from specifications.
def _scale_prof(step, rprof, rad=None): """Scale profile to take sphericity into account""" rbot, rtop = misc.get_rbounds(step) if rbot == 0: # not spherical return rprof if rad is None: rad = step.rprof['r'].values + rbot return rprof * (2 * rad / (rtop + rbot))**2
How would you implement a function in Python 3 that scales profile to take sphericity into account
As a Python code analyst, you investigate and solve complex coding mysteries
def diffs_prof(step): """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 ...
Implement a function in Python 3 to scale diffusion. This computation takes sphericity into account if necessary. This computation takes sphericity into account if necessary.
You are a Python code architect, reviewing and designing scalable and efficient code
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.
Can you generate the documentation for the following Python 3 function def energy_prof(step): diff, rad = diffs_prof(step) adv, _ = advts_prof(step) return (diff + np.append(adv, 0)), rad
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Given the following Python 3 function, write the documentation 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: ...
As a Python code analyst, you investigate and solve complex coding mysteries
This function computes the initial concentration of a single object.
Explain what the following Python 3 code does 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 = (rto...
As a python code expert, you are capable of creating scripts from specifications.
def stream_function(step): """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. """ if...
How would you implement a function in Python 3 that streams function for the current object.
As a Python code composer, you craft elegant and concise scripts.
Return the last available entry in the sequence.
Explain what the following Python 3 code does def last(self): if self._last is UNDETERMINED: # not necessarily the last one... self._last = self.sdat.tseries.index[-1] return self[self._last]
You are a Python code generator, capable of creating scripts from specifications.
Bind the isnap and istep to the object.
Given the following Python 3 function, write the documentation def bind(self, isnap, istep): self._isteps[isnap] = istep self.sdat.steps[istep].isnap = isnap
As a Python code composer, you craft elegant and concise scripts.
Check whether a step passes the filters.
Here you have a function in Python 3, explain what it does def _pass(self, step): okf = True okf = okf and (not self._flt['snap'] or step.isnap is not None) okf = okf and (not self._flt['rprof'] or step.rprof is not None) okf = okf and all(f in step.fields for f in self._flt['fields']) ...
You are a Python code analyst, evaluating scripts for potential improvements.