INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns the root resource.
def get_root_resource(config): """Returns the root resource.""" app_package_name = get_app_package_name(config) return config.registry._root_resources.setdefault( app_package_name, Resource(config))
view is a dotted name of ( or direct reference to ) a Python view class e. g. my. package. views. MyView.
def add_resource_routes(config, view, member_name, collection_name, **kwargs): """ ``view`` is a dotted name of (or direct reference to) a Python view class, e.g. ``'my.package.views.MyView'``. ``member_name`` should be the appropriate singular version of the resource given your locale and used...
Returns the dotted path to the default view class.
def get_default_view_path(resource): "Returns the dotted path to the default view class." parts = [a.member_name for a in resource.ancestors] +\ [resource.collection_name or resource.member_name] if resource.prefix: parts.insert(-1, resource.prefix) view_file = '%s' % '_'.join(par...
Returns the list of ancestor resources.
def get_ancestors(self): "Returns the list of ancestor resources." if self._ancestors: return self._ancestors if not self.parent: return [] obj = self.resource_map.get(self.parent.uid) while obj and obj.member_name: self._ancestors.append(o...
: param member_name: singular name of the resource. It should be the appropriate singular version of the resource given your locale and used with members of the collection.
def add(self, member_name, collection_name='', parent=None, uid='', **kwargs): """ :param member_name: singular name of the resource. It should be the appropriate singular version of the resource given your locale and used with members of the collection. :par...
Add a resource with its all children resources to the current resource.
def add_from_child(self, resource, **kwargs): """ Add a resource with its all children resources to the current resource. """ new_resource = self.add( resource.member_name, resource.collection_name, **kwargs) for child in resource.children: new_resource.a...
Add the path of a data set to the list of available sets
def add(self, path): """ Add the path of a data set to the list of available sets NOTE: a data set is assumed to be a pickled and gzip compressed Pandas DataFrame Parameters ---------- path : str """ name_with_ext = os.path.split(path)[1] # spli...
Unpacks a data set to a Pandas DataFrame
def unpack(self, name): """ Unpacks a data set to a Pandas DataFrame Parameters ---------- name : str call `.list` to see all availble datasets Returns ------- pd.DataFrame """ path = self.list[name] df = pd.read_pickl...
translate each sequence into six reading frames
def six_frame(genome, table, minimum = 10): """ translate each sequence into six reading frames """ for seq in parse_fasta(genome): dna = Seq(seq[1].upper().replace('U', 'T'), IUPAC.ambiguous_dna) counter = 0 for sequence in ['f', dna], ['rc', dna.reverse_complement()]: ...
# Redis/ RabbitMQ/ SQS messaging endpoints for pub - sub routing_key = ev ( PUBLISH_EXCHANGE reporting. accounts ) queue_name = ev ( PUBLISH_QUEUE reporting. accounts ) auth_url = ev ( PUB_BROKER_URL redis:// localhost: 6379/ 15 ) serializer = json
def publish_processed_network_packets( name="not-set", task_queue=None, result_queue=None, need_response=False, shutdown_msg="SHUTDOWN"): """ # Redis/RabbitMQ/SQS messaging endpoints for pub-sub routing_key = ev("PUBLISH_EXCHANGE", "reporting.acc...
run_main
def run_main( need_response=False, callback=None): """run_main start the packet consumers and the packet processors :param need_response: should send response back to publisher :param callback: handler method """ stop_file = ev("STOP_FILE", "/opt/stop_record...
determine the best model: archaea bacteria eukarya ( best score )
def best_model(seq2hmm): """ determine the best model: archaea, bacteria, eukarya (best score) """ for seq in seq2hmm: best = [] for model in seq2hmm[seq]: best.append([model, sorted([i[-1] for i in seq2hmm[seq][model]], reverse = True)[0]]) best_model = sorted(best, ...
check for large gaps between alignment windows
def check_gaps(matches, gap_threshold = 0): """ check for large gaps between alignment windows """ gaps = [] prev = None for match in sorted(matches, key = itemgetter(0)): if prev is None: prev = match continue if match[0] - prev[1] >= gap_threshold: ...
determine if sequence has already hit the same part of the model indicating that this hit is for another 16S rRNA gene
def check_overlap(current, hit, overlap = 200): """ determine if sequence has already hit the same part of the model, indicating that this hit is for another 16S rRNA gene """ for prev in current: p_coords = prev[2:4] coords = hit[2:4] if get_overlap(coords, p_coords) >= over...
determine if hits are sequential on model and on the same strand * if not they should be split into different groups
def check_order(current, hit, overlap = 200): """ determine if hits are sequential on model and on the same strand * if not, they should be split into different groups """ prev_model = current[-1][2:4] prev_strand = current[-1][-2] hit_model = hit[2:4] hit_strand = hit[-2] # ...
* each sequence may have more than one 16S rRNA gene * group hits for each gene
def hit_groups(hits): """ * each sequence may have more than one 16S rRNA gene * group hits for each gene """ groups = [] current = False for hit in sorted(hits, key = itemgetter(0)): if current is False: current = [hit] elif check_overlap(current, hit) is True or...
find 16S rRNA gene sequence coordinates
def find_coordinates(hmms, bit_thresh): """ find 16S rRNA gene sequence coordinates """ # get coordinates from cmsearch output seq2hmm = parse_hmm(hmms, bit_thresh) seq2hmm = best_model(seq2hmm) group2hmm = {} # group2hmm[seq][group] = [model, strand, coordinates, matches, gaps] for seq,...
get info from either ssu - cmsearch or cmsearch output
def get_info(line, bit_thresh): """ get info from either ssu-cmsearch or cmsearch output """ if len(line) >= 18: # output is from cmsearch id, model, bit, inc = line[0].split()[0], line[2], float(line[14]), line[16] sstart, send, strand = int(line[7]), int(line[8]), line[9] mstar...
check to see how much of the buffer is being used
def check_buffer(coords, length, buffer): """ check to see how much of the buffer is being used """ s = min(coords[0], buffer) e = min(length - coords[1], buffer) return [s, e]
: return: a parser of type parser_or_type initialized with the properties of parser. If parser_or_type is a type an instance of it must contain a update method. The update method must also process the set of properties supported by MetadataParser for the conversion to have any affect.: param parser: the parser ( or con...
def convert_parser_to(parser, parser_or_type, metadata_props=None): """ :return: a parser of type parser_or_type, initialized with the properties of parser. If parser_or_type is a type, an instance of it must contain a update method. The update method must also process the set of properties supported by...
Takes a metadata_container which may be a type or instance of a parser a dict string or file.: return: a new instance of a parser corresponding to the standard represented by metadata_container: see: get_parsed_content ( metdata_content ) for more on types of content that can be parsed
def get_metadata_parser(metadata_container, **metadata_defaults): """ Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file. :return: a new instance of a parser corresponding to the standard represented by metadata_container :see: get_parsed_content(metdata_con...
Parses any of the following types of content: 1. XML string or file object: parses XML content 2. MetadataParser instance: deep copies xml_tree 3. Dictionary with nested objects containing: - name ( required ): the name of the element tag - text: the text contained by element - tail: text immediately following the elem...
def get_parsed_content(metadata_content): """ Parses any of the following types of content: 1. XML string or file object: parses XML content 2. MetadataParser instance: deep copies xml_tree 3. Dictionary with nested objects containing: - name (required): the name of the element tag -...
Lazy imports to prevent circular dependencies between this module and utils
def _import_parsers(): """ Lazy imports to prevent circular dependencies between this module and utils """ global ARCGIS_NODES global ARCGIS_ROOTS global ArcGISParser global FGDC_ROOT global FgdcParser global ISO_ROOTS global IsoParser global VALID_ROOTS if ARCGIS_NODES is N...
Dynamically sets attributes from a Dictionary passed in by children. The Dictionary will contain the name of each attribute as keys and either an XPATH mapping to a text value in _xml_tree or a function that takes no parameters and returns the intended value.
def _init_metadata(self): """ Dynamically sets attributes from a Dictionary passed in by children. The Dictionary will contain the name of each attribute as keys, and either an XPATH mapping to a text value in _xml_tree, or a function that takes no parameters and returns the inte...
Default data map initialization: MUST be overridden in children
def _init_data_map(self): """ Default data map initialization: MUST be overridden in children """ if self._data_map is None: self._data_map = {'_root': None} self._data_map.update({}.fromkeys(self._metadata_props))
Iterate over items metadata_defaults { prop: val... } to populate template
def _get_template(self, root=None, **metadata_defaults): """ Iterate over items metadata_defaults {prop: val, ...} to populate template """ if root is None: if self._data_map is None: self._init_data_map() root = self._xml_root = self._data_map['_root'] ...
: return: the configured xpath for a given property
def _get_xpath_for(self, prop): """ :return: the configured xpath for a given property """ xpath = self._data_map.get(prop) return getattr(xpath, 'xpath', xpath)
Default parsing operation for a complex struct
def _parse_complex(self, prop): """ Default parsing operation for a complex struct """ xpath_root = None xpath_map = self._data_structures[prop] return parse_complex(self._xml_tree, xpath_root, xpath_map, prop)
Default parsing operation for lists of complex structs
def _parse_complex_list(self, prop): """ Default parsing operation for lists of complex structs """ xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return parse_complex_list(self._xml_tree, xpath_root, xpath_map, prop)
Creates and returns a Date Types data structure parsed from the metadata
def _parse_dates(self, prop=DATES): """ Creates and returns a Date Types data structure parsed from the metadata """ return parse_dates(self._xml_tree, self._data_structures[prop])
Default update operation for a complex struct
def _update_complex(self, **update_props): """ Default update operation for a complex struct """ prop = update_props['prop'] xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return update_complex(xpath_root=xpath_root, xpath_map=xpath_map, **update...
Default update operation for lists of complex structs
def _update_complex_list(self, **update_props): """ Default update operation for lists of complex structs """ prop = update_props['prop'] xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return update_complex_list(xpath_root=xpath_root, xpath_map=x...
Default update operation for Dates metadata: see: gis_metadata. utils. _complex_definitions [ DATES ]
def _update_dates(self, xpath_root=None, **update_props): """ Default update operation for Dates metadata :see: gis_metadata.utils._complex_definitions[DATES] """ tree_to_update = update_props['tree_to_update'] prop = update_props['prop'] values = (update_props['...
Validates instance properties updates an XML tree with them and writes the content to a file.: param use_template: if True updates a new template XML tree ; otherwise the original XML tree: param out_file_or_path: optionally override self. out_file_or_path with a custom file path: param encoding: optionally use another...
def write(self, use_template=False, out_file_or_path=None, encoding=DEFAULT_ENCODING): """ Validates instance properties, updates an XML tree with them, and writes the content to a file. :param use_template: if True, updates a new template XML tree; otherwise the original XML tree :param...
Default validation for updated properties: MAY be overridden in children
def validate(self): """ Default validation for updated properties: MAY be overridden in children """ validate_properties(self._data_map, self._metadata_props) for prop in self._data_map: validate_any(prop, getattr(self, prop), self._data_structures.get(prop)) return self
Search order: * specified regexps * operators sorted from longer to shorter
def _search_regex(ops: dict, regex_pat: str): """ Search order: * specified regexps * operators sorted from longer to shorter """ custom_regexps = list(filter(None, [dic['regex'] for op, dic in ops.items() if 'regex' in dic])) op_names = [op for op, dic in ops.items() if 'regex' not in d...
Return prefix unary operators list
def spec(self, postf_un_ops: str) -> list: """Return prefix unary operators list""" spec = [(l + op, {'pat': self.pat(pat), 'postf': self.postf(r, postf_un_ops), 'regex': None}) for op, pat in self.styles.items() for l, ...
Returns prefix unary operators list. Sets only one regex for all items in the dict.
def spec(self) -> list: """Returns prefix unary operators list. Sets only one regex for all items in the dict.""" spec = [item for op, pat in self.ops.items() for item in [('{' + op, {'pat': pat, 'postf': self.postf, 'regex': None}), (...
Insert: * math styles * other styles * unary prefix operators without brackets * defaults
def fill(self, postf_un_ops: str): """ Insert: * math styles * other styles * unary prefix operators without brackets * defaults """ for op, dic in self.ops.items(): if 'postf' not in dic: dic['postf'] = self.postf ...
Regex - escaped string with all one - symbol operators
def one_symbol_ops_str(self) -> str: """Regex-escaped string with all one-symbol operators""" return re.escape(''.join((key for key in self.ops.keys() if len(key) == 1)))
: return: [ compiled regex function ]
def _su_scripts_regex(self): """ :return: [compiled regex, function] """ sups = re.escape(''.join([k for k in self.superscripts.keys()])) subs = re.escape(''.join([k for k in self.subscripts.keys()])) # language=PythonRegExp su_regex = (r'\\([{su_}])|([{sub}]...
: param match:: param loc: str l or r or lr turns on/ off left/ right local area calculation: return: list list of the same size as the string + 2 it s the local map that counted { and } list can contain: None or int > = 0 from the left of the operator match: in b } a if a: 0 then }: 0 and b: 1 in b { a if a: 0 then {:...
def _local_map(match, loc: str = 'lr') -> list: """ :param match: :param loc: str "l" or "r" or "lr" turns on/off left/right local area calculation :return: list list of the same size as the string + 2 it's the local map that counted { and ...
Searches for first unary or binary operator ( via self. op_regex that has only one group that contain operator ) then replaces it ( or escapes it if brackets do not match ). Everything until: * space * begin/ end of the string * bracket from outer scope ( like { a/ b }: term1 = a term2 = b ) is considered a term ( cont...
def _operators_replace(self, string: str) -> str: """ Searches for first unary or binary operator (via self.op_regex that has only one group that contain operator) then replaces it (or escapes it if brackets do not match). Everything until: * space ' ' * begin...
Extends LaTeX syntax via regex preprocess: param src: str LaTeX string: return: str New LaTeX string
def replace(self, src: str) -> str: """ Extends LaTeX syntax via regex preprocess :param src: str LaTeX string :return: str New LaTeX string """ if not self.readied: self.ready() # Brackets + simple pre replacements: sr...
plot % of gaps at each position
def plot_gaps(plot, columns): """ plot % of gaps at each position """ from plot_window import window_plot_convolve as plot_window # plot_window([columns], len(columns)*.01, plot) plot_window([[100 - i for i in columns]], len(columns)*.01, plot)
strip out columns of a MSA that represent gaps for X percent ( threshold ) of sequences
def strip_msa_100(msa, threshold, plot = False): """ strip out columns of a MSA that represent gaps for X percent (threshold) of sequences """ msa = [seq for seq in parse_fasta(msa)] columns = [[0, 0] for pos in msa[0][1]] # [[#bases, #gaps], [#bases, #gaps], ...] for seq in msa: for position, base in enumerate...
Iterate through all categories in an OrderedDict and return category name if SampleID present in that category.
def sample_group(sid, groups): """ Iterate through all categories in an OrderedDict and return category name if SampleID present in that category. :type sid: str :param sid: SampleID from dataset. :type groups: OrderedDict :param groups: Returned dict from phylotoast.util.gather_categories...
Combine multiple sets to create a single larger set.
def combine_sets(*sets): """ Combine multiple sets to create a single larger set. """ combined = set() for s in sets: combined.update(s) return combined
Get unique OTUIDs of each category.
def unique_otuids(groups): """ Get unique OTUIDs of each category. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on category name and unique OTUIDs as values. """ uniques = {key: set() for key in groups} for i, group in...
Get shared OTUIDs between all unique combinations of groups.
def shared_otuids(groups): """ Get shared OTUIDs between all unique combinations of groups. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on group combination and their shared OTUIDs as values. """ for g in sorted(groups): ...
Given a path the method writes out one file for each group name in the uniques dictionary with the file name in the pattern
def write_uniques(path, prefix, uniques): """ Given a path, the method writes out one file for each group name in the uniques dictionary with the file name in the pattern PATH/prefix_group.txt with each file containing the unique OTUIDs found when comparing that group to all the other grou...
Parse the records in a FASTA - format file by first reading the entire file into memory.
def storeFASTA(fastaFNH): """ Parse the records in a FASTA-format file by first reading the entire file into memory. :type source: path to FAST file or open file handle :param source: The data source from which to parse the FASTA records. Expects the input to resolve to a collection ...
Parse the records in a FASTA - format file keeping the file open and reading through one line at a time.
def parseFASTA(fastaFNH): """ Parse the records in a FASTA-format file keeping the file open, and reading through one line at a time. :type source: path to FAST file or open file handle :param source: The data source from which to parse the FASTA records. Expects the input to res...
Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID ( default ) or a user - supplied one. The only required fields are SampleID BarcodeSequence LinkerPrimerSequence ( in that order ) and Description ( which must be the final field ).
def parse_map_file(mapFNH): """ Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID (default) or a user-supplied one. The only required fields are SampleID, BarcodeSequence, LinkerPrimerSequence (in that order), and Description (which must be the final field). :...
Train a deepq model.
def learn(env, network, seed=None, lr=5e-4, total_timesteps=100000, buffer_size=50000, exploration_fraction=0.1, exploration_final_eps=0.02, train_freq=1, batch_size=32, print_freq=100, checkpoint_freq=10000, ...
Save model to a pickle located at path
def save_act(self, path=None): """Save model to a pickle located at `path`""" if path is None: path = os.path.join(logger.get_dir(), "model.pkl") with tempfile.TemporaryDirectory() as td: save_variables(os.path.join(td, "model")) arc_name = os.path.join(td, "...
CNN from Nature paper.
def nature_cnn(unscaled_images, **conv_kwargs): """ CNN from Nature paper. """ scaled_images = tf.cast(unscaled_images, tf.float32) / 255. activ = tf.nn.relu h = activ(conv(scaled_images, 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2), **conv_kwargs)) h2 = activ(conv(h...
Stack of fully - connected layers to be used in a policy/ q - function approximator
def mlp(num_layers=2, num_hidden=64, activation=tf.tanh, layer_norm=False): """ Stack of fully-connected layers to be used in a policy / q-function approximator Parameters: ---------- num_layers: int number of fully-connected layers (default: 2) num_hidden: int ...
Builds LSTM ( Long - Short Term Memory ) network to be used in a policy. Note that the resulting function returns not only the output of the LSTM ( i. e. hidden state of lstm for each step in the sequence ) but also a dictionary with auxiliary tensors to be set as policy attributes.
def lstm(nlstm=128, layer_norm=False): """ Builds LSTM (Long-Short Term Memory) network to be used in a policy. Note that the resulting function returns not only the output of the LSTM (i.e. hidden state of lstm for each step in the sequence), but also a dictionary with auxiliary tensors to be set a...
convolutions - only net
def conv_only(convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)], **conv_kwargs): ''' convolutions-only net Parameters: ---------- conv: list of triples (filter_number, filter_size, stride) specifying parameters for each layer. Returns: function that takes tensorflow tensor as input and re...
If you want to register your own network outside models. py you just need:
def get_network_builder(name): """ If you want to register your own network outside models.py, you just need: Usage Example: ------------- from baselines.common.models import register @register("your_network_name") def your_network_define(**net_kwargs): ... return network_fn...
This model takes as input an observation and returns values of all actions.
def mlp(hiddens=[], layer_norm=False): """This model takes as input an observation and returns values of all actions. Parameters ---------- hiddens: [int] list of sizes of hidden layers layer_norm: bool if true applies layer normalization for every layer as described in http...
This model takes as input an observation and returns values of all actions.
def cnn_to_mlp(convs, hiddens, dueling=False, layer_norm=False): """This model takes as input an observation and returns values of all actions. Parameters ---------- convs: [(int, int, int)] list of convolutional layers in form of (num_outputs, kernel_size, stride) hiddens: [int] ...
Create a wrapped monitored SubprocVecEnv for Atari and MuJoCo.
def make_vec_env(env_id, env_type, num_env, seed, wrapper_kwargs=None, start_index=0, reward_scale=1.0, flatten_dict_observations=True, gamestate=None): """ Create a wrapped, monitored SubprocVecEnv for Atari and MuJoCo. ""...
Create a wrapped monitored gym. Env for MuJoCo.
def make_mujoco_env(env_id, seed, reward_scale=1.0): """ Create a wrapped, monitored gym.Env for MuJoCo. """ rank = MPI.COMM_WORLD.Get_rank() myseed = seed + 1000 * rank if seed is not None else None set_global_seeds(myseed) env = gym.make(env_id) logger_path = None if logger.get_dir() ...
Create a wrapped monitored gym. Env for MuJoCo.
def make_robotics_env(env_id, seed, rank=0): """ Create a wrapped, monitored gym.Env for MuJoCo. """ set_global_seeds(seed) env = gym.make(env_id) env = FlattenDictWrapper(env, ['observation', 'desired_goal']) env = Monitor( env, logger.get_dir() and os.path.join(logger.get_dir(), st...
Create an argparse. ArgumentParser for run_mujoco. py.
def common_arg_parser(): """ Create an argparse.ArgumentParser for run_mujoco.py. """ parser = arg_parser() parser.add_argument('--env', help='environment ID', type=str, default='Reacher-v2') parser.add_argument('--env_type', help='type of environment, used when the environment type cannot be au...
Create an argparse. ArgumentParser for run_mujoco. py.
def robotics_arg_parser(): """ Create an argparse.ArgumentParser for run_mujoco.py. """ parser = arg_parser() parser.add_argument('--env', help='environment ID', type=str, default='FetchReach-v0') parser.add_argument('--seed', help='RNG seed', type=int, default=None) parser.add_argument('--n...
Parse arguments not consumed by arg parser into a dicitonary
def parse_unknown_args(args): """ Parse arguments not consumed by arg parser into a dicitonary """ retval = {} preceded_by_key = False for arg in args: if arg.startswith('--'): if '=' in arg: key = arg.split('=')[0][2:] value = arg.split('=')[1...
from mpi4py import MPI will call MPI_Init by default. If the child process has MPI environment variables MPI will think that the child process is an MPI process just like the parent and do bad things such as hang. This context manager is a hacky way to clear those environment variables temporarily such as when we are s...
def clear_mpi_env_vars(): """ from mpi4py import MPI will call MPI_Init by default. If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang. This context manager is a hacky way to clear those environment...
Learn policy using PPO algorithm ( https:// arxiv. org/ abs/ 1707. 06347 )
def learn(*, network, env, total_timesteps, eval_env = None, seed=None, nsteps=2048, ent_coef=0.0, lr=3e-4, vf_coef=0.5, max_grad_norm=0.5, gamma=0.99, lam=0.95, log_interval=10, nminibatches=4, noptepochs=4, cliprange=0.2, save_interval=0, load_path=None, model_fn=None, **network_k...
Demmel p 312
def cg(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10): """ Demmel p 312 """ p = b.copy() r = b.copy() x = np.zeros_like(b) rdotr = r.dot(r) fmtstr = "%10i %10.3g %10.3g" titlestr = "%10s %10s %10s" if verbose: print(titlestr % ("iter", "residual norm",...
Create placeholder to feed observations into of the size appropriate to the observation space
def observation_placeholder(ob_space, batch_size=None, name='Ob'): ''' Create placeholder to feed observations into of the size appropriate to the observation space Parameters: ---------- ob_space: gym.Space observation space batch_size: int size of the batch to be fed into input....
Create placeholder to feed observations into of the size appropriate to the observation space and add input encoder of the appropriate type.
def observation_input(ob_space, batch_size=None, name='Ob'): ''' Create placeholder to feed observations into of the size appropriate to the observation space, and add input encoder of the appropriate type. ''' placeholder = observation_placeholder(ob_space, batch_size, name) return placeholder...
Encode input in the way that is appropriate to the observation space
def encode_observation(ob_space, placeholder): ''' Encode input in the way that is appropriate to the observation space Parameters: ---------- ob_space: gym.Space observation space placeholder: tf.placeholder observation input placeholder ''' if isinstance(ob_space, Di...
Performs rollout_batch_size rollouts in parallel for time horizon T with the current policy acting on it accordingly.
def generate_rollouts(self): """Performs `rollout_batch_size` rollouts in parallel for time horizon `T` with the current policy acting on it accordingly. """ self.reset_all_rollouts() # compute observations o = np.empty((self.rollout_batch_size, self.dims['o']), np.float...
Pickles the current policy for later inspection.
def save_policy(self, path): """Pickles the current policy for later inspection. """ with open(path, 'wb') as f: pickle.dump(self.policy, f)
Generates a dictionary that contains all collected statistics.
def logs(self, prefix='worker'): """Generates a dictionary that contains all collected statistics. """ logs = [] logs += [('success_rate', np.mean(self.success_history))] if self.compute_Q: logs += [('mean_Q', np.mean(self.Q_history))] logs += [('episode', sel...
Smooth signal y where radius is determines the size of the window
def smooth(y, radius, mode='two_sided', valid_only=False): ''' Smooth signal y, where radius is determines the size of the window mode='twosided': average over the window [max(index - radius, 0), min(index + radius, len(y)-1)] mode='causal': average over the window [max(index - radius, ...
perform one - sided ( causal ) EMA ( exponential moving average ) smoothing and resampling to an even grid with n points. Does not do extrapolation so we assume xolds [ 0 ] < = low && high < = xolds [ - 1 ]
def one_sided_ema(xolds, yolds, low=None, high=None, n=512, decay_steps=1., low_counts_threshold=1e-8): ''' perform one-sided (causal) EMA (exponential moving average) smoothing and resampling to an even grid with n points. Does not do extrapolation, so we assume xolds[0] <= low && high <= xolds[-1]...
perform symmetric EMA ( exponential moving average ) smoothing and resampling to an even grid with n points. Does not do extrapolation so we assume xolds [ 0 ] < = low && high < = xolds [ - 1 ]
def symmetric_ema(xolds, yolds, low=None, high=None, n=512, decay_steps=1., low_counts_threshold=1e-8): ''' perform symmetric EMA (exponential moving average) smoothing and resampling to an even grid with n points. Does not do extrapolation, so we assume xolds[0] <= low && high <= xolds[-1] Arg...
load summaries of runs from a list of directories ( including subdirectories ) Arguments:
def load_results(root_dir_or_dirs, enable_progress=True, enable_monitor=True, verbose=False): ''' load summaries of runs from a list of directories (including subdirectories) Arguments: enable_progress: bool - if True, will attempt to load data from progress.csv files (data saved by logger). Default: T...
Plot multiple Results objects
def plot_results( allresults, *, xy_fn=default_xy_fn, split_fn=default_split_fn, group_fn=default_split_fn, average_group=False, shaded_std=True, shaded_err=True, figsize=None, legend_outside=False, resample=0, smooth_step=1.0 ): ''' Plot multiple Results objects ...
It s common to forget to initialize your variables to the same values or ( less commonly ) if you update them in some other way than adam to get them out of sync. This function checks that variables on all MPI workers are the same and raises an AssertionError otherwise
def check_synced(localval, comm=None): """ It's common to forget to initialize your variables to the same values, or (less commonly) if you update them in some other way than adam, to get them out of sync. This function checks that variables on all MPI workers are the same, and raises an AssertionEr...
Deep - copy an observation dict.
def copy_obs_dict(obs): """ Deep-copy an observation dict. """ return {k: np.copy(v) for k, v in obs.items()}
Get dict - structured information about a gym. Space.
def obs_space_info(obs_space): """ Get dict-structured information about a gym.Space. Returns: A tuple (keys, shapes, dtypes): keys: a list of dict keys. shapes: a dict mapping keys to shapes. dtypes: a dict mapping keys to dtypes. """ if isinstance(obs_space, gym.spac...
Calculates q_retrace targets
def q_retrace(R, D, q_i, v, rho_i, nenvs, nsteps, gamma): """ Calculates q_retrace targets :param R: Rewards :param D: Dones :param q_i: Q values for actions taken :param v: V values :param rho_i: Importance weight for each action :return: Q_retrace values """ rho_bar = batch_to...
Main entrypoint for ACER ( Actor - Critic with Experience Replay ) algorithm ( https:// arxiv. org/ pdf/ 1611. 01224. pdf ) Train an agent with given network architecture on a given environment using ACER.
def learn(network, env, seed=None, nsteps=20, total_timesteps=int(80e6), q_coef=0.5, ent_coef=0.01, max_grad_norm=10, lr=7e-4, lrschedule='linear', rprop_epsilon=1e-5, rprop_alpha=0.99, gamma=0.99, log_interval=100, buffer_size=50000, replay_ratio=4, replay_start=10000, c=10.0, trust_regio...
compute stats and update/ apply the new stats to the running average
def apply_stats(self, statsUpdates): """ compute stats and update/apply the new stats to the running average """ def updateAccumStats(): if self._full_stats_init: return tf.cond(tf.greater(self.sgd_step, self._cold_iter), lambda: tf.group(*self._apply_stats(statsUpda...
Tile N images into one big PxQ image ( P Q ) are chosen to be as close as possible and if N is square then P = Q.
def tile_images(img_nhwc): """ Tile N images into one big PxQ image (P,Q) are chosen to be as close as possible, and if N is square, then P=Q. input: img_nhwc, list or array of images, ndim=4 once turned into array n = batch index, h = height, w = width, c = channel returns: big...
Returns arr [ start ] +... + arr [ end ]
def sum(self, start=0, end=None): """Returns arr[start] + ... + arr[end]""" return super(SumSegmentTree, self).reduce(start, end)
Find the highest index i in the array such that sum ( arr [ 0 ] + arr [ 1 ] +... + arr [ i - i ] ) < = prefixsum
def find_prefixsum_idx(self, prefixsum): """Find the highest index `i` in the array such that sum(arr[0] + arr[1] + ... + arr[i - i]) <= prefixsum if array values are probabilities, this function allows to sample indexes according to the discrete probability efficiently. ...
Returns min ( arr [ start ]... arr [ end ] )
def min(self, start=0, end=None): """Returns min(arr[start], ..., arr[end])""" return super(MinSegmentTree, self).reduce(start, end)
See Schedule. value
def value(self, t): """See Schedule.value""" for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]): if l_t <= t and t < r_t: alpha = float(t - l_t) / (r_t - l_t) return self._interpolation(l, r, alpha) # t does not belong to any of ...
Control a single environment instance using IPC and shared memory.
def _subproc_worker(pipe, parent_pipe, env_fn_wrapper, obs_bufs, obs_shapes, obs_dtypes, keys): """ Control a single environment instance using IPC and shared memory. """ def _write_obs(maybe_dict_obs): flatdict = obs_to_dict(maybe_dict_obs) for k in keys: dst = obs_bufs[...
Main entrypoint for A2C algorithm. Train a policy with given network architecture on a given environment using a2c algorithm.
def learn( network, env, seed=None, nsteps=5, total_timesteps=int(80e6), vf_coef=0.5, ent_coef=0.01, max_grad_norm=0.5, lr=7e-4, lrschedule='linear', epsilon=1e-5, alpha=0.99, gamma=0.99, log_interval=100, load_path=None, **network_kwargs): ''' Ma...
swap and then flatten axes 0 and 1
def sf01(arr): """ swap and then flatten axes 0 and 1 """ s = arr.shape return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])
Compute next action ( s ) given the observation ( s )
def step(self, observation, **extra_feed): """ Compute next action(s) given the observation(s) Parameters: ---------- observation observation data (either single or a batch) **extra_feed additional data such as state or mask (names of the arguments should match ...
Compute value estimate ( s ) given the observation ( s )
def value(self, ob, *args, **kwargs): """ Compute value estimate(s) given the observation(s) Parameters: ---------- observation observation data (either single or a batch) **extra_feed additional data such as state or mask (names of the arguments should match th...
Print the number of seconds in human readable format.
def pretty_eta(seconds_left): """Print the number of seconds in human readable format. Examples: 2 days 2 hours and 37 minutes less than a minute Paramters --------- seconds_left: int Number of seconds to be converted to the ETA Returns ------- eta: str Stri...