text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_order(self, order_id): """Lookup an order based on the order id returned from one of the order functions. Parameters order_id : str The unique identifier...
if order_id in self.blotter.orders: return self.blotter.orders[order_id].to_api_obj()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cancel_order(self, order_param): """Cancel an open order. Parameters order_param : str or Order The order_id or order object to cancel. """
order_id = order_param if isinstance(order_param, zipline.protocol.Order): order_id = order_param.id self.blotter.cancel(order_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_account_control(self, control): """ Register a new AccountControl to be checked on each bar. """
if self.initialized: raise RegisterAccountControlPostInit() self.account_controls.append(control)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_min_leverage(self, min_leverage, grace_period): """Set a limit on the minimum leverage of the algorithm. Parameters min_leverage : float The minimum leve...
deadline = self.sim_params.start_session + grace_period control = MinLeverage(min_leverage, deadline) self.register_account_control(control)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_trading_control(self, control): """ Register a new TradingControl to be checked prior to order calls. """
if self.initialized: raise RegisterTradingControlPostInit() self.trading_controls.append(control)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_max_order_count(self, max_count, on_error='fail'): """Set a limit on the number of orders that can be placed in a single day. Parameters max_count : int ...
control = MaxOrderCount(on_error, max_count) self.register_trading_control(control)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach_pipeline(self, pipeline, name, chunks=None, eager=True): """Register a pipeline to be computed at the start of each day. Parameters pipeline : Pipelin...
if chunks is None: # Make the first chunk smaller to get more immediate results: # (one week, then every half year) chunks = chain([5], repeat(126)) elif isinstance(chunks, int): chunks = repeat(chunks) if name in self._pipelines: rai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pipeline_output(self, pipeline, chunks, name): """ Internal implementation of `pipeline_output`. """
today = normalize_date(self.get_datetime()) try: data = self._pipeline_cache.get(name, today) except KeyError: # Calculate the next block. data, valid_until = self.run_pipeline( pipeline, today, next(chunks), ) self._pi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_pipeline(self, pipeline, start_session, chunksize): """ Compute `pipeline`, providing values for at least `start_date`. Produces a DataFrame containing d...
sessions = self.trading_calendar.all_sessions # Load data starting from the previous trading day... start_date_loc = sessions.get_loc(start_session) # ...continuing until either the day before the simulation end, or # until chunksize days of data have been loaded. sim_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all_api_methods(cls): """ Return a list of all the TradingAlgorithm API methods. """
return [ fn for fn in itervalues(vars(cls)) if getattr(fn, 'is_api_method', False) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _expect_extra(expected, present, exc_unexpected, exc_missing, exc_args): """ Checks for the presence of an extra to the argument list. Raises expections if t...
if present: if not expected: raise exc_unexpected(*exc_args) elif expected and expected is not Argument.ignore: raise exc_missing(*exc_args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_restricted(self, assets, dt): """ An asset is restricted for all dts if it is in the static list. """
if isinstance(assets, Asset): return assets in self._restricted_set return pd.Series( index=pd.Index(assets), data=vectorized_is_element(assets, self._restricted_set) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_restricted(self, assets, dt): """ Returns whether or not an asset or iterable of assets is restricted on a dt. """
if isinstance(assets, Asset): return self._is_restricted_for_asset(assets, dt) is_restricted = partial(self._is_restricted_for_asset, dt=dt) return pd.Series( index=pd.Index(assets), data=vectorize(is_restricted, otypes=[bool])(assets) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pay_dividends(self, next_trading_day): """ Returns a cash payment based on the dividends that should be paid out according to the accumulated bookkeeping of ...
net_cash_payment = 0.0 try: payments = self._unpaid_dividends[next_trading_day] # Mark these dividends as paid by dropping them from our unpaid del self._unpaid_dividends[next_trading_day] except KeyError: payments = [] # representing th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stats(self): """The current status of the positions. Returns ------- stats : PositionStats The current stats position stats. Notes ----- This is cached, repe...
if self._dirty_stats: calculate_position_tracker_stats(self.positions, self._stats) self._dirty_stats = False return self._stats
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_transaction(self, transaction): """Add a transaction to ledger, updating the current state as needed. Parameters transaction : zp.Transaction The tra...
asset = transaction.asset if isinstance(asset, Future): try: old_price = self._payout_last_sale_prices[asset] except KeyError: self._payout_last_sale_prices[asset] = transaction.price else: position = self.position_trac...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_order(self, order): """Keep track of an order that was placed. Parameters order : zp.Order The order to record. """
try: dt_orders = self._orders_by_modified[order.dt] except KeyError: self._orders_by_modified[order.dt] = OrderedDict([ (order.id, order), ]) self._orders_by_id[order.id] = order else: self._orders_by_id[order.id] = dt_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_commission(self, commission): """Process the commission. Parameters commission : zp.Event The commission being paid. """
asset = commission['asset'] cost = commission['cost'] self.position_tracker.handle_commission(asset, cost) self._cash_flow(-cost)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_dividends(self, next_session, asset_finder, adjustment_reader): """Process dividends for the next session. This will earn us any dividends whose ex-d...
position_tracker = self.position_tracker # Earn dividends whose ex_date is the next trading day. We need to # check if we own any of these stocks so we know to pay them out when # the pay date comes. held_sids = set(position_tracker.positions) if held_sids: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transactions(self, dt=None): """Retrieve the dict-form of all of the transactions in a given bar or for the whole simulation. Parameters dt : pd.Timestamp or...
if dt is None: # flatten the by-day transactions return [ txn for by_day in itervalues(self._processed_transactions) for txn in by_day ] return self._processed_transactions.get(dt, [])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def orders(self, dt=None): """Retrieve the dict-form of all of the orders in a given bar or for the whole simulation. Parameters dt : pd.Timestamp or None, optio...
if dt is None: # orders by id is already flattened return [o.to_dict() for o in itervalues(self._orders_by_id)] return [ o.to_dict() for o in itervalues(self._orders_by_modified.get(dt, {})) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_portfolio(self): """Force a computation of the current portfolio state. """
if not self._dirty_portfolio: return portfolio = self._portfolio pt = self.position_tracker portfolio.positions = pt.get_positions() position_stats = pt.stats portfolio.positions_value = position_value = ( position_stats.net_value ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def override_account_fields(self, settled_cash=not_overridden, accrued_interest=not_overridden, buying_power=not_overridden, equity_with_loan=not_overridden, tota...
# mark that the portfolio is dirty to override the fields again self._dirty_account = True self._account_overrides = kwargs = { k: v for k, v in locals().items() if v is not not_overridden } del kwargs['self']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_dataset(expr, missing_values, domain): """ Creates or returns a dataset from a blaze expression. Parameters expr : Expr The blaze expression representing...
missing_values = dict(missing_values) class_dict = {'ndim': 2 if SID_FIELD_NAME in expr.fields else 1} for name, type_ in expr.dshape.measure.fields: # Don't generate a column for sid or timestamp, since they're # implicitly the labels if the arrays that will be passed to pipeline #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_resources(name, expr, resources): """Validate that the expression and resources passed match up. Parameters name : str The name of the argument we are...
if expr is None: return bound = expr._resources() if not bound and resources is None: raise ValueError('no resources provided to compute %s' % name) if bound and resources: raise ValueError( 'explicit and implicit resources provided to compute %s' % name, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_datetime_field(name, measure): """Check that a field is a datetime inside some measure. Parameters name : str The name of the field to check. measure ...
if not isinstance(measure[name], (Date, DateTime)): raise TypeError( "'{name}' field must be a '{dt}', not: '{dshape}'".format( name=name, dt=DateTime(), dshape=measure[name], ), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_metadata(field, expr, metadata_expr, no_metadata_rule): """Find the correct metadata expression for the expression. Parameters field : {'deltas', 'check...
if isinstance(metadata_expr, bz.Expr) or metadata_expr is None: return metadata_expr try: return expr._child['_'.join(((expr._name or ''), field))] except (ValueError, AttributeError): if no_metadata_rule == 'raise': raise ValueError( "no %s table could ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ensure_timestamp_field(dataset_expr, deltas, checkpoints): """Verify that the baseline and deltas expressions have a timestamp field. If there is not a ``TS...
measure = dataset_expr.dshape.measure if TS_FIELD_NAME not in measure.names: dataset_expr = bz.transform( dataset_expr, **{TS_FIELD_NAME: dataset_expr[AD_FIELD_NAME]} ) deltas = _ad_as_ts(deltas) checkpoints = _ad_as_ts(checkpoints) else: _che...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind_expression_to_resources(expr, resources): """ Bind a Blaze expression to resources. Parameters expr : bz.Expr The expression to which we want to bind re...
# bind the resources into the expression if resources is None: resources = {} # _subs stands for substitute. It's not actually private, blaze just # prefixes symbol-manipulation methods with underscores to prevent # collisions with data column names. return expr._subs({ k: bz....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_materialized_checkpoints(checkpoints, colnames, lower_dt, odo_kwargs): """ Computes a lower bound and a DataFrame checkpoints. Parameters checkpoints : E...
if checkpoints is not None: ts = checkpoints[TS_FIELD_NAME] checkpoints_ts = odo( ts[ts < lower_dt].max(), pd.Timestamp, **odo_kwargs ) if pd.isnull(checkpoints_ts): # We don't have a checkpoint for before our start date so just ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ffill_query_in_range(expr, lower, upper, checkpoints=None, odo_kwargs=None, ts_field=TS_FIELD_NAME): """Query a blaze expression in a given time range proper...
odo_kwargs = odo_kwargs or {} computed_lower, materialized_checkpoints = get_materialized_checkpoints( checkpoints, expr.fields, lower, odo_kwargs, ) pred = expr[ts_field] <= upper if computed_lower is not None: # only constrain the lower date if we compute...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_dataset(self, dataset, expr, deltas=None, checkpoints=None, odo_kwargs=None): """Explicitly map a datset to a collection of blaze expressions. Param...
expr_data = ExprData( expr, deltas, checkpoints, odo_kwargs, ) for column in dataset.columns: self._table_expressions[column] = expr_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_column(self, column, expr, deltas=None, checkpoints=None, odo_kwargs=None): """Explicitly map a single bound column to a collection of blaze express...
self._table_expressions[column] = ExprData( expr, deltas, checkpoints, odo_kwargs, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_ownership_periods(mappings): """ Given a dict of mappings where the values are lists of OwnershipPeriod objects, returns a dict with the same structure...
return valmap( lambda v: tuple( OwnershipPeriod( a.start, b.start, a.sid, a.value, ) for a, b in sliding_window( 2, concatv( sorted(v), # concat wi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_ownership_map(table, key_from_row, value_from_row): """ Builds a dict mapping to lists of OwnershipPeriods, from a db table. """
return _build_ownership_map_from_rows( sa.select(table.c).execute().fetchall(), key_from_row, value_from_row, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_grouped_ownership_map(table, key_from_row, value_from_row, group_key): """ Builds a dict mapping group keys to maps of keys to to lists of OwnershipPer...
grouped_rows = groupby( group_key, sa.select(table.c).execute().fetchall(), ) return { key: _build_ownership_map_from_rows( rows, key_from_row, value_from_row, ) for key, rows in grouped_rows.items() }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _filter_kwargs(names, dict_): """Filter out kwargs from a dictionary. Parameters names : set[str] The names to select from ``dict_``. dict_ : dict[str, any] ...
return {k: v for k, v in dict_.items() if k in names and v is not None}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_asset_timestamp_fields(dict_): """ Takes in a dict of Asset init args and converts dates to pd.Timestamps """
for key in _asset_timestamp_fields & viewkeys(dict_): value = pd.Timestamp(dict_[key], tz='UTC') dict_[key] = None if isnull(value) else value return dict_
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def was_active(reference_date_value, asset): """ Whether or not `asset` was active at the time corresponding to `reference_date_value`. Parameters reference_date...
return ( asset.start_date.value <= reference_date_value <= asset.end_date.value )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_asset_types(self, sids): """ Retrieve asset types for a list of sids. Parameters sids : list[int] Returns ------- types : dict[sid -> str or None] Ass...
found = {} missing = set() for sid in sids: try: found[sid] = self._asset_type_cache[sid] except KeyError: missing.add(sid) if not missing: return found router_cols = self.asset_router.c for assets i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _select_most_recent_symbols_chunk(self, sid_group): """Retrieve the most recent symbol for a set of sids. Parameters sid_group : iterable[int] The sids to lo...
cols = self.equity_symbol_mappings.c # These are the columns we actually want. data_cols = (cols.sid,) + tuple(cols[name] for name in symbol_columns) # Also select the max of end_date so that all non-grouped fields take # on the value associated with the max end_date. The SQLi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _retrieve_assets(self, sids, asset_tbl, asset_type): """ Internal function for loading assets from a table. This should be the only method of `AssetFinder` t...
# Fastpath for empty request. if not sids: return {} cache = self._asset_cache hits = {} querying_equities = issubclass(asset_type, Equity) filter_kwargs = ( _filter_equity_kwargs if querying_equities else _filter_future_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _lookup_symbol_strict(self, ownership_map, multi_country, symbol, as_of_date): """ Resolve a symbol to an asset object without fuzzy matching. Parameters own...
# split the symbol into the components, if there are no # company/share class parts then share_class_symbol will be empty company_symbol, share_class_symbol = split_delimited_symbol(symbol) try: owners = ownership_map[company_symbol, share_class_symbol] assert ow...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_symbol(self, symbol, as_of_date, fuzzy=False, country_code=None): """Lookup an equity by symbol. Parameters symbol : str The ticker symbol to resolve....
if symbol is None: raise TypeError("Cannot lookup asset for symbol of None for " "as of date %s." % as_of_date) if fuzzy: f = self._lookup_symbol_fuzzy mapping = self._choose_fuzzy_symbol_ownership_map(country_code) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_symbols(self, symbols, as_of_date, fuzzy=False, country_code=None): """ Lookup a list of equities by symbol. Equivalent to:: [finder.lookup_symbol(s, ...
if not symbols: return [] multi_country = country_code is None if fuzzy: f = self._lookup_symbol_fuzzy mapping = self._choose_fuzzy_symbol_ownership_map(country_code) else: f = self._lookup_symbol_strict mapping = self._choose...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_future_symbol(self, symbol): """Lookup a future contract by symbol. Parameters symbol : str The symbol of the desired contract. Returns ------- future...
data = self._select_asset_by_symbol(self.futures_contracts, symbol)\ .execute().fetchone() # If no data found, raise an exception if not data: raise SymbolNotFound(symbol=symbol) return self.retrieve_asset(data['sid'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_supplementary_field(self, sid, field_name, as_of_date): """Get the value of a supplementary field for an asset. Parameters sid : int The sid of the asset...
try: periods = self.equity_supplementary_map_by_sid[ field_name, sid, ] assert periods, 'empty periods list for %r' % (field_name, sid) except KeyError: raise NoValueForSid(field=field_name, sid=sid) if not as_of_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _lookup_generic_scalar(self, obj, as_of_date, country_code, matches, missing): """ Convert asset_convertible to an asset. On success, append to matches. On f...
result = self._lookup_generic_scalar_helper( obj, as_of_date, country_code, ) if result is not None: matches.append(result) else: missing.append(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_generic(self, obj, as_of_date, country_code): """ Convert an object into an Asset or sequence of Assets. This method exists primarily as a convenience...
matches = [] missing = [] # Interpret input as scalar. if isinstance(obj, (AssetConvertible, ContinuousFuture)): self._lookup_generic_scalar( obj=obj, as_of_date=as_of_date, country_code=country_code, matches=m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_asset_lifetimes(self, country_codes): """ Compute and cache a recarray of asset lifetimes. """
equities_cols = self.equities.c if country_codes: buf = np.array( tuple( sa.select(( equities_cols.sid, equities_cols.start_date, equities_cols.end_date, )).where(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lifetimes(self, dates, include_start_date, country_codes): """ Compute a DataFrame representing asset lifetimes for the specified date range. Parameters date...
if isinstance(country_codes, string_types): raise TypeError( "Got string {!r} instead of an iterable of strings in " "AssetFinder.lifetimes.".format(country_codes), ) # normalize to a cache-key so that we can memoize results. country_code...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def equities_sids_for_country_code(self, country_code): """Return all of the sids for a given country. Parameters country_code : str An ISO 3166 alpha-2 country ...
sids = self._compute_asset_lifetimes([country_code]).sid return tuple(sids.tolist())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_last_traded_dt(self, asset, dt): """ Get the latest minute on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, ret...
rf = self._roll_finders[asset.roll_style] sid = (rf.get_contract_center(asset.root_symbol, dt, asset.offset)) if sid is None: return pd.NaT contract = rf.asset_finder.retrieve_asset(sid) retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current_portfolio_weights(self): """ Compute each asset's weight in the portfolio by calculating its held value divided by the total value of all positions. ...
position_values = pd.Series({ asset: ( position.last_sale_price * position.amount * asset.price_multiplier ) for asset, position in self.positions.items() }) return position_values / self.portfolio_v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decode_image(fobj, session, filename): """Reads and decodes an image from a file object as a Numpy array. The SUN dataset contains images in several formats...
buf = fobj.read() image = tfds.core.lazy_imports.cv2.imdecode( np.fromstring(buf, dtype=np.uint8), flags=3) # Note: Converts to RGB. if image is None: logging.warning( "Image %s could not be decoded by OpenCV, falling back to TF", filename) try: image = tf.image.decode_image(buf, ch...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_image_file(fobj, session, filename): """Process image files from the dataset."""
# We need to read the image files and convert them to JPEG, since some files # actually contain GIF, PNG or BMP data (despite having a .jpg extension) and # some encoding options that will make TF crash in general. image = _decode_image(fobj, session, filename=filename) return _encode_jpeg(image)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_parallel_sentences(f1, f2): """Returns examples from parallel SGML or text files, which may be gzipped."""
def _parse_text(path): """Returns the sentences from a single text file, which may be gzipped.""" split_path = path.split(".") if split_path[-1] == "gz": lang = split_path[-2] with tf.io.gfile.GFile(path) as f, gzip.GzipFile(fileobj=f) as g: return g.read().split("\n"), lang if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_tmx(path): """Generates examples from TMX file."""
def _get_tuv_lang(tuv): for k, v in tuv.items(): if k.endswith("}lang"): return v raise AssertionError("Language not found in `tuv` attributes.") def _get_tuv_seg(tuv): segs = tuv.findall("seg") assert len(segs) == 1, "Invalid number of segments: %d" % len(segs) return segs[0].te...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_tsv(path, language_pair=None): """Generates examples from TSV file."""
if language_pair is None: lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])\.tsv", path) assert lang_match is not None, "Invalid TSV filename: %s" % path l1, l2 = lang_match.groups() else: l1, l2 = language_pair with tf.io.gfile.GFile(path) as f: for j, line in enumerate(f): cols = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_wikiheadlines(path): """Generates examples from Wikiheadlines dataset file."""
lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])$", path) assert lang_match is not None, "Invalid Wikiheadlines filename: %s" % path l1, l2 = lang_match.groups() with tf.io.gfile.GFile(path) as f: for line in f: s1, s2 = line.split("|||") yield { l1: s1.strip(), l2: s2....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_czeng(*paths, **kwargs): """Generates examples from CzEng v1.6, with optional filtering for v1.7."""
filter_path = kwargs.get("filter_path", None) if filter_path: re_block = re.compile(r"^[^-]+-b(\d+)-\d\d[tde]") with tf.io.gfile.GFile(filter_path) as f: bad_blocks = { blk for blk in re.search( r"qw{([\s\d]*)}", f.read()).groups()[0].split() } logging.info( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subsets(self): """Subsets that make up each split of the dataset for the language pair."""
source, target = self.builder_config.language_pair filtered_subsets = {} for split, ss_names in self._subsets.items(): filtered_subsets[split] = [] for ss_name in ss_names: ds = DATASET_MAP[ss_name] if ds.target != target or source not in ds.sources: logging.info( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def builder(name, **builder_init_kwargs): """Fetches a `tfds.core.DatasetBuilder` by string name. Args: name: `str`, the registered name of the `DatasetBuilder` ...
name, builder_kwargs = _dataset_name_and_kwargs_from_name_str(name) builder_kwargs.update(builder_init_kwargs) if name in _ABSTRACT_DATASET_REGISTRY: raise DatasetNotFoundError(name, is_abstract=True) if name in _IN_DEVELOPMENT_REGISTRY: raise DatasetNotFoundError(name, in_development=True) if name n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(name, split=None, data_dir=None, batch_size=1, download=True, as_supervised=False, with_info=False, builder_kwargs=None, download_and_prepare_kwargs=None...
name, name_builder_kwargs = _dataset_name_and_kwargs_from_name_str(name) name_builder_kwargs.update(builder_kwargs or {}) builder_kwargs = name_builder_kwargs # Set data_dir if try_gcs and gcs_utils.is_dataset_on_gcs(name): data_dir = constants.GCS_DATA_DIR elif data_dir is None: data_dir = consta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dataset_name_and_kwargs_from_name_str(name_str): """Extract kwargs from name str."""
res = _NAME_REG.match(name_str) if not res: raise ValueError(_NAME_STR_ERR.format(name_str)) name = res.group("dataset_name") kwargs = _kwargs_str_to_kwargs(res.group("kwargs")) try: for attr in ["config", "version"]: val = res.group(attr) if val is None: continue if attr in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cast_to_pod(val): """Try cast to int, float, bool, str, in that order."""
bools = {"True": True, "False": False} if val in bools: return bools[val] try: return int(val) except ValueError: try: return float(val) except ValueError: return tf.compat.as_text(val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _try_import(module_name): """Try importing a module, with an informative error message on failure."""
try: mod = importlib.import_module(module_name) return mod except ImportError: err_msg = ("Tried importing %s but failed. See setup.py extras_require. " "The dataset you are trying to use may have additional " "dependencies.") utils.reraise(err_msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def np_to_list(elem): """Returns list from list, tuple or ndarray."""
if isinstance(elem, list): return elem elif isinstance(elem, tuple): return list(elem) elif isinstance(elem, np.ndarray): return list(elem) else: raise ValueError( 'Input elements of a sequence should be either a numpy array, a ' 'python list or tuple. Got {}'.format(type(elem))...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_examples(self, num_examples, data_path, label_path): """Generate MNIST examples as dicts. Args: num_examples (int): The number of example. data_pa...
images = _extract_mnist_images(data_path, num_examples) labels = _extract_mnist_labels(label_path, num_examples) data = list(zip(images, labels)) # Data is shuffled automatically to distribute classes uniformly. for image, label in data: yield { "image": image, "label": l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dataset_feature_statistics(builder, split): """Calculate statistics for the specified split."""
statistics = statistics_pb2.DatasetFeatureStatistics() # Make this to the best of our abilities. schema = schema_pb2.Schema() dataset = builder.as_dataset(split=split) # Just computing the number of examples for now. statistics.num_examples = 0 # Feature dictionaries. feature_to_num_examples = coll...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_from_json(json_filename): """Read JSON-formatted proto into DatasetInfo proto."""
with tf.io.gfile.GFile(json_filename) as f: dataset_info_json_str = f.read() # Parse it back into a proto. parsed_proto = json_format.Parse(dataset_info_json_str, dataset_info_pb2.DatasetInfo()) return parsed_proto
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_splits_if_different(self, split_dict): """Overwrite the splits if they are different from the current ones. * If splits aren't already defined or diff...
assert isinstance(split_dict, splits_lib.SplitDict) # If splits are already defined and identical, then we do not update if self._splits and splits_lib.check_splits_equals( self._splits, split_dict): return self._set_splits(split_dict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_dynamic_properties(self, builder): """Update from the DatasetBuilder."""
# Fill other things by going over the dataset. splits = self.splits for split_info in utils.tqdm( splits.values(), desc="Computing statistics...", unit=" split"): try: split_name = split_info.name # Fill DatasetFeatureStatistics. dataset_feature_statistics, schema = ge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_to_directory(self, dataset_info_dir): """Write `DatasetInfo` as JSON to `dataset_info_dir`."""
# Save the metadata from the features (vocabulary, labels,...) if self.features: self.features.save_metadata(dataset_info_dir) if self.redistribution_info.license: with tf.io.gfile.GFile(self._license_filename(dataset_info_dir), "w") as f: f.write(self.redi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_from_directory(self, dataset_info_dir): """Update DatasetInfo from the JSON file in `dataset_info_dir`. This function updates all the dynamically genera...
if not dataset_info_dir: raise ValueError( "Calling read_from_directory with undefined dataset_info_dir.") json_filename = self._dataset_info_filename(dataset_info_dir) # Load the metadata from disk parsed_proto = read_from_json(json_filename) # Update splits self._set_splits...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_from_bucket(self): """Initialize DatasetInfo from GCS bucket info files."""
# In order to support Colab, we use the HTTP GCS API to access the metadata # files. They are copied locally and then loaded. tmp_dir = tempfile.mkdtemp("tfds") data_files = gcs_utils.gcs_dataset_info_files(self.full_name) if not data_files: return logging.info("Loading info from GCS for ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _map_promise(map_fn, all_inputs): """Map the function into each element and resolve the promise."""
all_promises = utils.map_nested(map_fn, all_inputs) # Apply the function res = utils.map_nested(_wait_on_promise, all_promises) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_download_result(self, resource, tmp_dir_path, sha256, dl_size): """Store dled file to definitive place, write INFO file, return path."""
fnames = tf.io.gfile.listdir(tmp_dir_path) if len(fnames) > 1: raise AssertionError('More than one file in %s.' % tmp_dir_path) original_fname = fnames[0] tmp_path = os.path.join(tmp_dir_path, original_fname) self._recorded_sizes_checksums[resource.url] = (dl_size, sha256) if self._regist...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _download(self, resource): """Download resource, returns Promise->path to downloaded file."""
if isinstance(resource, six.string_types): resource = resource_lib.Resource(url=resource) url = resource.url if url in self._sizes_checksums: expected_sha256 = self._sizes_checksums[url][1] download_path = self._get_final_dl_path(url, expected_sha256) if not self._force_download and...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract(self, resource): """Extract a single archive, returns Promise->path to extraction result."""
if isinstance(resource, six.string_types): resource = resource_lib.Resource(path=resource) path = resource.path extract_method = resource.extract_method if extract_method == resource_lib.ExtractMethod.NO_EXTRACT: logging.info('Skipping extraction for %s (method=NO_EXTRACT).', path) re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _download_extract(self, resource): """Download-extract `Resource` or url, returns Promise->path."""
if isinstance(resource, six.string_types): resource = resource_lib.Resource(url=resource) def callback(path): resource.path = path return self._extract(resource) return self._download(resource).then(callback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_kaggle_data(self, competition_name): """Download data for a given Kaggle competition."""
with self._downloader.tqdm(): kaggle_downloader = self._downloader.kaggle_downloader(competition_name) urls = kaggle_downloader.competition_urls files = kaggle_downloader.competition_files return _map_promise(self._download, dict((f, u) for (f, u) in zip(files, url...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_archive(self, resource): """Returns iterator over files within archive. **Important Note**: caller should read files as they are yielded. Reading out of...
if isinstance(resource, six.string_types): resource = resource_lib.Resource(path=resource) return extractor.iter_archive(resource.path, resource.extract_method)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_and_extract(self, url_or_urls): """Download and extract given url_or_urls. Is roughly equivalent to: ``` extracted_paths = dl_manager.extract(dl_man...
# Add progress bar to follow the download state with self._downloader.tqdm(): with self._extractor.tqdm(): return _map_promise(self._download_extract, url_or_urls)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def manual_dir(self): """Returns the directory containing the manually extracted data."""
if not tf.io.gfile.exists(self._manual_dir): raise AssertionError( 'Manual directory {} does not exist. Create it and download/extract ' 'dataset artifacts in there.'.format(self._manual_dir)) return self._manual_dir
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _split_generators(self, dl_manager): """Return the test split of Cifar10. Args: dl_manager: download manager object. Returns: test split. """
path = dl_manager.download_and_extract(_DOWNLOAD_URL) return [ tfds.core.SplitGenerator( name=tfds.Split.TEST, num_shards=1, gen_kwargs={'data_dir': os.path.join(path, _DIRNAME)}) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_examples(self, data_dir): """Generate corrupted Cifar10 test data. Apply corruptions to the raw images according to self.corruption_type. Args: dat...
corruption = self.builder_config.corruption severity = self.builder_config.severity images_file = os.path.join(data_dir, _CORRUPTIONS_TO_FILENAMES[corruption]) labels_file = os.path.join(data_dir, _LABELS_FILENAME) with tf.io.gfile.GFile(labels_file, mode='rb') as f: labels = np.load(f) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def document_single_builder(builder): """Doc string for a single builder, with or without configs."""
mod_name = builder.__class__.__module__ cls_name = builder.__class__.__name__ mod_file = sys.modules[mod_name].__file__ if mod_file.endswith("pyc"): mod_file = mod_file[:-1] description_prefix = "" if builder.builder_configs: # Dataset with configs; document each one config_docs = [] for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_module_to_builder_dict(datasets=None): """Get all builders organized by module in nested dicts."""
# pylint: disable=g-long-lambda # dict to hold tfds->image->mnist->[builders] module_to_builder = collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(list))) # pylint: enable=g-long-lambda if datasets: builders = [tfds.builder(name) for name in datas...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pprint_features_dict(features_dict, indent=0, add_prefix=True): """Pretty-print tfds.features.FeaturesDict."""
first_last_indent_str = " " * indent indent_str = " " * (indent + 4) first_line = "%s%s({" % ( first_last_indent_str if add_prefix else "", type(features_dict).__name__, ) lines = [first_line] for k in sorted(list(features_dict.keys())): v = features_dict[k] if isinstance(v, tfds.featur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_statistics_information(info): """Make statistics information table."""
if not info.splits.total_num_examples: # That means that we have yet to calculate the statistics for this. return "None computed" stats = [(info.splits.total_num_examples, "ALL")] for split_name, split_info in info.splits.items(): stats.append((split_info.num_examples, split_name.upper())) # Sort ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataset_docs_str(datasets=None): """Create dataset documentation string for given datasets. Args: datasets: list of datasets for which to create documentatio...
module_to_builder = make_module_to_builder_dict(datasets) sections = sorted(list(module_to_builder.keys())) section_tocs = [] section_docs = [] for section in sections: builders = tf.nest.flatten(module_to_builder[section]) builders = sorted(builders, key=lambda b: b.name) builder_docs = [docume...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def schema_org(builder): # pylint: disable=line-too-long """Builds schema.org microdata for DatasetSearch from DatasetBuilder. Markup spec: https://developers.go...
# pylint: enable=line-too-long properties = [ (lambda x: x.name, SCHEMA_ORG_NAME), (lambda x: x.description, SCHEMA_ORG_DESC), (lambda x: x.name, SCHEMA_ORG_URL), (lambda x: (x.urls and x.urls[0]) or "", SCHEMA_ORG_SAMEAS) ] info = builder.info out_str = SCHEMA_ORG_PRE for extract...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disk(radius, alias_blur=0.1, dtype=np.float32): """Generating a Gaussian blurring kernel with disk shape. Generating a Gaussian blurring kernel with disk sha...
if radius <= 8: length = np.arange(-8, 8 + 1) ksize = (3, 3) else: length = np.arange(-radius, radius + 1) ksize = (5, 5) x_axis, y_axis = np.meshgrid(length, length) aliased_disk = np.array((x_axis**2 + y_axis**2) <= radius**2, dtype=dtype) aliased_disk /= np.sum(aliased_disk) # supersampl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clipped_zoom(img, zoom_factor): """Zoom image with clipping. Zoom the central part of the image and clip extra pixels. Args: img: numpy array, uncorrupted im...
h = img.shape[0] ch = int(np.ceil(h / float(zoom_factor))) top_h = (h - ch) // 2 w = img.shape[1] cw = int(np.ceil(w / float(zoom_factor))) top_w = (w - cw) // 2 img = tfds.core.lazy_imports.scipy.ndimage.zoom( img[top_h:top_h + ch, top_w:top_w + cw], (zoom_factor, zoom_factor, 1), order=1)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plasma_fractal(mapsize=512, wibbledecay=3): """Generate a heightmap using diamond-square algorithm. Modification of the algorithm in https://github.com/FLHer...
if mapsize & (mapsize - 1) != 0: raise ValueError('mapsize must be a power of two.') maparray = np.empty((mapsize, mapsize), dtype=np.float_) maparray[0, 0] = 0 stepsize = mapsize wibble = 100 def wibbledmean(array): return array / 4 + wibble * np.random.uniform(-wibble, wibble, array.shape) de...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gaussian_noise(x, severity=1): """Gaussian noise corruption to images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. sever...
c = [.08, .12, 0.18, 0.26, 0.38][severity - 1] x = np.array(x) / 255. x_clip = np.clip(x + np.random.normal(size=x.shape, scale=c), 0, 1) * 255 return around_and_astype(x_clip)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shot_noise(x, severity=1): """Shot noise corruption to images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: int...
c = [60, 25, 12, 5, 3][severity - 1] x = np.array(x) / 255. x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255 return around_and_astype(x_clip)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def impulse_noise(x, severity=1): """Impulse noise corruption to images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severit...
c = [.03, .06, .09, 0.17, 0.27][severity - 1] x = tfds.core.lazy_imports.skimage.util.random_noise( np.array(x) / 255., mode='s&p', amount=c) x_clip = np.clip(x, 0, 1) * 255 return around_and_astype(x_clip)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def defocus_blur(x, severity=1): """Defocus blurring to images. Apply defocus blurring to images using Gaussian kernel. Args: x: numpy array, uncorrupted image, ...
c = [(3, 0.1), (4, 0.5), (6, 0.5), (8, 0.5), (10, 0.5)][severity - 1] x = np.array(x) / 255. kernel = disk(radius=c[0], alias_blur=c[1]) channels = [] for d in range(3): channels.append(tfds.core.lazy_imports.cv2.filter2D(x[:, :, d], -1, kernel)) channels = np.array(channels).transpose((1, 2, 0)) # 3x...