INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Query encoder/ decoder with a request value
def query(request): """Query encoder/decoder with a request value""" def inner(func, obj): result_code = func(obj, request) if result_code is not constants.OK: raise OpusError(result_code) return result_code return inner
Get CTL value from a encoder/ decoder
def get(request, result_type): """Get CTL value from a encoder/decoder""" def inner(func, obj): result = result_type() result_code = func(obj, request, ctypes.byref(result)) if result_code is not constants.OK: raise OpusError(result_code) return result.value r...
Set new CTL value to a encoder/ decoder
def set(request): """Set new CTL value to a encoder/decoder""" def inner(func, obj, value): result_code = func(obj, request, value) if result_code is not constants.OK: raise OpusError(result_code) return inner
Sort a list of SQL schemas in order
def sort_schemas(schemas): """Sort a list of SQL schemas in order""" def keyfun(v): x = SQL_SCHEMA_REGEXP.match(v).groups() # x3: 'DEV' should come before '' return (int(x[0]), x[1], int(x[2]) if x[2] else None, x[3] if x[3] else 'zzz', int(x[4])) return sorted(schem...
Parse a list of SQL files and return a dictionary of valid schema files where each key is a valid schema file and the corresponding value is a tuple containing the source and the target schema.
def parse_schema_files(files): """ Parse a list of SQL files and return a dictionary of valid schema files where each key is a valid schema file and the corresponding value is a tuple containing the source and the target schema. """ f_dict = {} for f in files: root, ext = os.path.spl...
Dump the database using the postgres custom format
def dump(self): """ Dump the database using the postgres custom format """ dumpfile = self.args.dumpfile if not dumpfile: db, env = self.get_db_args_env() dumpfile = fileutils.timestamp_filename( 'omero-database-%s' % db['name'], 'pgdump') ...
Get a dictionary of database connection parameters and create an environment for running postgres commands. Falls back to omego defaults.
def get_db_args_env(self): """ Get a dictionary of database connection parameters, and create an environment for running postgres commands. Falls back to omego defaults. """ db = { 'name': self.args.dbname, 'host': self.args.dbhost, 'us...
Run a psql command
def psql(self, *psqlargs): """ Run a psql command """ db, env = self.get_db_args_env() args = [ '-v', 'ON_ERROR_STOP=on', '-d', db['name'], '-h', db['host'], '-U', db['user'], '-w', '-A', '-t' ] + list(psqla...
Run a pg_dump command
def pgdump(self, *pgdumpargs): """ Run a pg_dump command """ db, env = self.get_db_args_env() args = ['-d', db['name'], '-h', db['host'], '-U', db['user'], '-w' ] + list(pgdumpargs) stdout, stderr = External.run( 'pg_dump', args, capturestd=Tr...
Set the directory of the server to be controlled
def set_server_dir(self, dir): """ Set the directory of the server to be controlled """ self.dir = os.path.abspath(dir) config = os.path.join(self.dir, 'etc', 'grid', 'config.xml') self.configured = os.path.exists(config)
Returns a dictionary of all config. xml properties
def get_config(self, force=False): """ Returns a dictionary of all config.xml properties If `force = True` then ignore any cached state and read config.xml if possible setup_omero_cli() must be called before this method to import the correct omero module to minimise the...
Imports the omero CLI module so that commands can be run directly. Note Python does not allow a module to be imported multiple times so this will only work with a single omero instance.
def setup_omero_cli(self): """ Imports the omero CLI module so that commands can be run directly. Note Python does not allow a module to be imported multiple times, so this will only work with a single omero instance. This can have several surprising effects, so setup_omero_cli(...
Create a copy of the current environment for interacting with the current OMERO server installation
def setup_previous_omero_env(self, olddir, savevarsfile): """ Create a copy of the current environment for interacting with the current OMERO server installation """ env = self.get_environment(savevarsfile) def addpath(varname, p): if not os.path.exists(p): ...
Runs a command as if from the OMERO command - line without the need for using popen or subprocess.
def omero_cli(self, command): """ Runs a command as if from the OMERO command-line without the need for using popen or subprocess. """ assert isinstance(command, list) if not self.cli: raise Exception('omero.cli not initialised') log.info("Invoking CLI...
Runs the omero command - line client with an array of arguments using the old environment
def omero_bin(self, command): """ Runs the omero command-line client with an array of arguments using the old environment """ assert isinstance(command, list) if not self.old_env: raise Exception('Old environment not initialised') log.info("Running [ol...
Runs an executable with an array of arguments optionally in the specified environment. Returns stdout and stderr
def run(exe, args, capturestd=False, env=None): """ Runs an executable with an array of arguments, optionally in the specified environment. Returns stdout and stderr """ command = [exe] + args if env: log.info("Executing [custom environment]: %s", " "....
Create byte - to - string and string - to - byte conversion functions for internal use.
def string_support(py3enc): '''Create byte-to-string and string-to-byte conversion functions for internal use. :param py3enc: Encoding used by Python 3 environment. :type py3enc: str ''' if sys.version < '3': def bytes2str(b): '''Identity, returns the argument string (bytes)...
Create tokenizer for use in boundary constraint parsing.
def splitter_support(py2enc): '''Create tokenizer for use in boundary constraint parsing. :param py2enc: Encoding used by Python 2 environment. :type py2enc: str ''' if sys.version < '3': def _fn_sentence(pattern, sentence): if REGEXTYPE == type(pattern): if patt...
Apply updates given in update_spec to the document whose id matches that of doc.
def update(self, document_id, update_spec, namespace, timestamp): """Apply updates given in update_spec to the document whose id matches that of doc. """ index, doc_type = self._index_and_mapping(namespace) with self.lock: # Check if document source is stored in loca...
Insert a document into Elasticsearch.
def upsert(self, doc, namespace, timestamp, update_spec=None): """Insert a document into Elasticsearch.""" index, doc_type = self._index_and_mapping(namespace) # No need to duplicate '_id' in source document doc_id = u(doc.pop("_id")) metadata = { 'ns': namespace, ...
Insert multiple documents into Elasticsearch.
def bulk_upsert(self, docs, namespace, timestamp): """Insert multiple documents into Elasticsearch.""" def docs_to_upsert(): doc = None for doc in docs: # Remove metadata and redundant _id index, doc_type = self._index_and_mapping(namespace) ...
Remove a document from Elasticsearch.
def remove(self, document_id, namespace, timestamp): """Remove a document from Elasticsearch.""" index, doc_type = self._index_and_mapping(namespace) action = { '_op_type': 'delete', '_index': index, '_type': doc_type, '_id': u(document_id) ...
Send buffered operations to Elasticsearch.
def send_buffered_operations(self): """Send buffered operations to Elasticsearch. This method is periodically called by the AutoCommitThread. """ with self.lock: try: action_buffer = self.BulkBuffer.get_buffer() if action_buffer: ...
Get the most recently modified document from Elasticsearch.
def get_last_doc(self): """Get the most recently modified document from Elasticsearch. This method is used to help define a time window within which documents may be in conflict after a MongoDB rollback. """ try: result = self.elastic.search( index=se...
Split a list of parameters/ types by commas whilst respecting brackets.
def split_sig(params): """ Split a list of parameters/types by commas, whilst respecting brackets. For example: String arg0, int arg2 = 1, List<int> arg3 = [1, 2, 3] => ['String arg0', 'int arg2 = 1', 'List<int> arg3 = [1, 2, 3]'] """ result = [] current = '' level = 0 f...
Parse a method signature of the form: modifier * type name ( params )
def parse_method_signature(sig): """ Parse a method signature of the form: modifier* type name (params) """ match = METH_SIG_RE.match(sig.strip()) if not match: raise RuntimeError('Method signature invalid: ' + sig) modifiers, return_type, name, generic_types, params = match.groups() if para...
Parse a property signature of the form: modifier * type name { ( get ; ) ? ( set ; ) ? }
def parse_property_signature(sig): """ Parse a property signature of the form: modifier* type name { (get;)? (set;)? } """ match = PROP_SIG_RE.match(sig.strip()) if not match: raise RuntimeError('Property signature invalid: ' + sig) groups = match.groups() if groups[0] is not None: ...
Parse a indexer signature of the form: modifier * type this [ params ] { ( get ; ) ? ( set ; ) ? }
def parse_indexer_signature(sig): """ Parse a indexer signature of the form: modifier* type this[params] { (get;)? (set;)? } """ match = IDXR_SIG_RE.match(sig.strip()) if not match: raise RuntimeError('Indexer signature invalid: ' + sig) modifiers, return_type, params, getter, setter = m...
Parse a parameter signature of the form: type name ( = default ) ?
def parse_param_signature(sig): """ Parse a parameter signature of the form: type name (= default)? """ match = PARAM_SIG_RE.match(sig.strip()) if not match: raise RuntimeError('Parameter signature invalid, got ' + sig) groups = match.groups() modifiers = groups[0].split() typ, name, _, ...
Parse a type signature
def parse_type_signature(sig): """ Parse a type signature """ match = TYPE_SIG_RE.match(sig.strip()) if not match: raise RuntimeError('Type signature invalid, got ' + sig) groups = match.groups() typ = groups[0] generic_types = groups[1] if not generic_types: generic_types = ...
Parse an attribute signature
def parse_attr_signature(sig): """ Parse an attribute signature """ match = ATTR_SIG_RE.match(sig.strip()) if not match: raise RuntimeError('Attribute signature invalid, got ' + sig) name, _, params = match.groups() if params is not None and params.strip() != '': params = split_sig(p...
Try and create a reference to a type on MSDN
def get_msdn_ref(name): """ Try and create a reference to a type on MSDN """ in_msdn = False if name in MSDN_VALUE_TYPES: name = MSDN_VALUE_TYPES[name] in_msdn = True if name.startswith('System.'): in_msdn = True if in_msdn: link = name.split('<')[0] if link i...
Shorten a type. E. g. drops System.
def shorten_type(typ): """ Shorten a type. E.g. drops 'System.' """ offset = 0 for prefix in SHORTEN_TYPE_PREFIXES: if typ.startswith(prefix): if len(prefix) > offset: offset = len(prefix) return typ[offset:]
Parses the MeCab options returning them in a dictionary. Lattice - level option has been deprecated ; please use marginal or nbest instead.: options string or dictionary of options to use when instantiating the MeCab instance. May be in short - or long - form or in a Python dictionary. Returns: A dictionary of the spec...
def parse_mecab_options(self, options): '''Parses the MeCab options, returning them in a dictionary. Lattice-level option has been deprecated; please use marginal or nbest instead. :options string or dictionary of options to use when instantiating the MeCab insta...
Returns a string concatenation of the MeCab options. Args: options: dictionary of options to use when instantiating the MeCab instance. Returns: A string concatenation of the options used when instantiating the MeCab instance in long - form.
def build_options_str(self, options): '''Returns a string concatenation of the MeCab options. Args: options: dictionary of options to use when instantiating the MeCab instance. Returns: A string concatenation of the options used when instantiatin...
Allocates and initializes a decoder state
def create(fs, channels): """Allocates and initializes a decoder state""" result_code = ctypes.c_int() result = _create(fs, channels, ctypes.byref(result_code)) if result_code.value is not 0: raise OpusError(result_code.value) return result
Gets the bandwidth of an Opus packet.
def packet_get_bandwidth(data): """Gets the bandwidth of an Opus packet.""" data_pointer = ctypes.c_char_p(data) result = _packet_get_bandwidth(data_pointer) if result < 0: raise OpusError(result) return result
Gets the number of channels from an Opus packet
def packet_get_nb_channels(data): """Gets the number of channels from an Opus packet""" data_pointer = ctypes.c_char_p(data) result = _packet_get_nb_channels(data_pointer) if result < 0: raise OpusError(result) return result
Gets the number of frames in an Opus packet
def packet_get_nb_frames(data, length=None): """Gets the number of frames in an Opus packet""" data_pointer = ctypes.c_char_p(data) if length is None: length = len(data) result = _packet_get_nb_frames(data_pointer, ctypes.c_int(length)) if result < 0: raise OpusError(result) r...
Gets the number of samples per frame from an Opus packet
def packet_get_samples_per_frame(data, fs): """Gets the number of samples per frame from an Opus packet""" data_pointer = ctypes.c_char_p(data) result = _packet_get_nb_frames(data_pointer, ctypes.c_int(fs)) if result < 0: raise OpusError(result) return result
Decode an Opus frame
def decode(decoder, data, length, frame_size, decode_fec, channels=2): """Decode an Opus frame Unlike the `opus_decode` function , this function takes an additional parameter `channels`, which indicates the number of channels in the frame """ pcm_size = frame_size * channels * ctypes.sizeof(ctypes...
Extracts comma separate tag = value pairs from a string Assumes all characters other than/ and are valid
def label_list_parser(self, url): """ Extracts comma separate tag=value pairs from a string Assumes all characters other than / and , are valid """ labels = re.findall('([^/,]+=[^/,]+)', url) slabels = set(labels) if '' in slabels: slabels.remove('') ...
: param app: The Flask app: param register_blueprint: Override to False to stop the blueprint from automatically being registered to the app: param url_prefix: The URL prefix for the blueprint defaults to/ fm: param access_control_function: Pass in a function here to implement access control. The function will be calle...
def init(app, register_blueprint=True, url_prefix='/fm', access_control_function=None, custom_config_json_path=None, custom_init_js_path=None): """ :param app: The Flask app :param register_blueprint: Override to False to stop the blueprint from automatically being registered to the ...
: param path: relative path or None to get from request: param content: file content output in data. Used for editfile
def get_file(path=None, content=None): """ :param path: relative path, or None to get from request :param content: file content, output in data. Used for editfile """ if path is None: path = request.args.get('path') if path is None: return error('No path in request') fi...
Return the character encoding ( charset ) used internally by MeCab. Charset is that of the system dictionary used by MeCab. Will defer to the user - specified MECAB_CHARSET environment variable if set. Defaults to shift - jis on Windows. Defaults to utf - 8 on Mac OS. Defaults to euc - jp as per MeCab documentation whe...
def __get_charset(self): '''Return the character encoding (charset) used internally by MeCab. Charset is that of the system dictionary used by MeCab. Will defer to the user-specified MECAB_CHARSET environment variable, if set. Defaults to shift-jis on Windows. Defaults t...
Return the absolute path to the MeCab library. On Windows the path to the system dictionary is used to deduce the path to libmecab. dll. Otherwise mecab - config is used find the libmecab shared object or dynamic library ( * NIX or Mac OS respectively ). Will defer to the user - specified MECAB_PATH environment variabl...
def __get_libpath(self): '''Return the absolute path to the MeCab library. On Windows, the path to the system dictionary is used to deduce the path to libmecab.dll. Otherwise, mecab-config is used find the libmecab shared object or dynamic library (*NIX or Mac OS, respec...
r Return the data of value mecabrc at MeCab HKEY node. On Windows the path to the mecabrc as set in the Windows Registry is used to deduce the path to libmecab. dll. Returns: The full path to the mecabrc on Windows. Raises: WindowsError: A problem was encountered in trying to locate the value mecabrc at HKEY_CURRENT_US...
def __regkey_value(self, path, name='', start_key=None): r'''Return the data of value mecabrc at MeCab HKEY node. On Windows, the path to the mecabrc as set in the Windows Registry is used to deduce the path to libmecab.dll. Returns: The full path to the mecabrc on W...
Show the differences between the old and new html document as html.
def diff(old_html, new_html, cutoff=0.0, plaintext=False, pretty=False): """Show the differences between the old and new html document, as html. Return the document html with extra tags added to show changes. Add <ins> tags around newly added sections, and <del> tags to show sections that have been del...
Iterate through opcodes turning them into a series of insert and delete operations adjusting indices to account for the size of insertions and deletions.
def adjusted_ops(opcodes): """ Iterate through opcodes, turning them into a series of insert and delete operations, adjusting indices to account for the size of insertions and deletions. >>> def sequence_opcodes(old, new): return difflib.SequenceMatcher(a=old, b=new).get_opcodes() >>> list(adju...
Yield index tuples ( old_index new_index ) for each place in the match.
def match_indices(match): """Yield index tuples (old_index, new_index) for each place in the match.""" a, b, size = match for i in range(size): yield a + i, b + i
Use difflib to get the opcodes for a set of matching blocks.
def get_opcodes(matching_blocks): """Use difflib to get the opcodes for a set of matching blocks.""" sm = difflib.SequenceMatcher(a=[], b=[]) sm.matching_blocks = matching_blocks return sm.get_opcodes()
Use difflib to find matching blocks.
def match_blocks(hash_func, old_children, new_children): """Use difflib to find matching blocks.""" sm = difflib.SequenceMatcher( _is_junk, a=[hash_func(c) for c in old_children], b=[hash_func(c) for c in new_children], ) return sm
Given a list of matching blocks output the gaps between them.
def get_nonmatching_blocks(matching_blocks): """Given a list of matching blocks, output the gaps between them. Non-matches have the format (alo, ahi, blo, bhi). This specifies two index ranges, one in the A sequence, and one in the B sequence. """ i = j = 0 for match in matching_blocks: ...
Given two lists of blocks combine them in the proper order.
def merge_blocks(a_blocks, b_blocks): """Given two lists of blocks, combine them, in the proper order. Ensure that there are no overlaps, and that they are for sequences of the same length. """ # Check sentinels for sequence length. assert a_blocks[-1][2] == b_blocks[-1][2] == 0 # sentinel size...
Remove comments as they can break the xml parser.
def remove_comments(xml): """ Remove comments, as they can break the xml parser. See html5lib issue #122 ( http://code.google.com/p/html5lib/issues/detail?id=122 ). >>> remove_comments('<!-- -->') '' >>> remove_comments('<!--\\n-->') '' >>> remove_comments('<p>stuff<!-- \\n -->stuff</p...
r Remove newlines in the xml.
def remove_newlines(xml): r"""Remove newlines in the xml. If the newline separates words in text, then replace with a space instead. >>> remove_newlines('<p>para one</p>\n<p>para two</p>') '<p>para one</p><p>para two</p>' >>> remove_newlines('<p>line one\nline two</p>') '<p>line one line two</...
For html elements that should not have text nodes inside them remove all whitespace. For elements that may have text collapse multiple spaces to a single space.
def remove_insignificant_text_nodes(dom): """ For html elements that should not have text nodes inside them, remove all whitespace. For elements that may have text, collapse multiple spaces to a single space. """ nodes_to_remove = [] for node in walk_dom(dom): if is_text(node): ...
Get the child at the given index or return None if it doesn t exist.
def get_child(parent, child_index): """ Get the child at the given index, or return None if it doesn't exist. """ if child_index < 0 or child_index >= len(parent.childNodes): return None return parent.childNodes[child_index]
Get the node at the specified location in the dom. Location is a sequence of child indices starting at the children of the root element. If there is no node at this location raise a ValueError.
def get_location(dom, location): """ Get the node at the specified location in the dom. Location is a sequence of child indices, starting at the children of the root element. If there is no node at this location, raise a ValueError. """ node = dom.documentElement for i in location: n...
Check whether two dom trees have similar text or not.
def check_text_similarity(a_dom, b_dom, cutoff): """Check whether two dom trees have similar text or not.""" a_words = list(tree_words(a_dom)) b_words = list(tree_words(b_dom)) sm = WordMatcher(a=a_words, b=b_words) if sm.text_ratio() >= cutoff: return True return False
Return all the significant text below the given node as a list of words. >>> list ( tree_words ( parse_minidom ( <h1 > one</ h1 > two <div > three<em > four</ em > </ div > ))) [ one two three four ]
def tree_words(node): """Return all the significant text below the given node as a list of words. >>> list(tree_words(parse_minidom('<h1>one</h1> two <div>three<em>four</em></div>'))) ['one', 'two', 'three', 'four'] """ for word in split_text(tree_text(node)): word = word.strip() if ...
>>> tree_text ( parse_minidom ( <h1 > one</ h1 > two<div > three<em > four</ em > </ div > )) one two three four
def tree_text(node): """ >>> tree_text(parse_minidom('<h1>one</h1>two<div>three<em>four</em></div>')) 'one two three four' """ text = [] for descendant in walk_dom(node): if is_text(descendant): text.append(descendant.nodeValue) return ' '.join(text)
Insert the node before next_sibling. If next_sibling is None append the node last instead.
def insert_or_append(parent, node, next_sibling): """ Insert the node before next_sibling. If next_sibling is None, append the node last instead. """ # simple insert if next_sibling: parent.insertBefore(node, next_sibling) else: parent.appendChild(node)
Wrap the given tag around a node.
def wrap(node, tag): """Wrap the given tag around a node.""" wrap_node = node.ownerDocument.createElement(tag) parent = node.parentNode if parent: parent.replaceChild(wrap_node, node) wrap_node.appendChild(node) return wrap_node
Wrap the given tag around the contents of a node.
def wrap_inner(node, tag): """Wrap the given tag around the contents of a node.""" children = list(node.childNodes) wrap_node = node.ownerDocument.createElement(tag) for c in children: wrap_node.appendChild(c) node.appendChild(wrap_node)
Remove a node replacing it with its children.
def unwrap(node): """Remove a node, replacing it with its children.""" for child in list(node.childNodes): node.parentNode.insertBefore(child, node) remove_node(node)
Split the text by the regex keeping all parts. The parts should re - join back into the original text.
def full_split(text, regex): """ Split the text by the regex, keeping all parts. The parts should re-join back into the original text. >>> list(full_split('word', re.compile('&.*?'))) ['word'] """ while text: m = regex.search(text) if not m: yield text ...
Split the text by the given regexes in priority order.
def multi_split(text, regexes): """ Split the text by the given regexes, in priority order. Make sure that the regex is parenthesized so that matches are returned in re.split(). Splitting on a single regex works like normal split. >>> '|'.join(multi_split('one two three', [r'\w+'])) 'one| ...
Return a measure of the sequences word similarity ( float in [ 0 1 ] ).
def text_ratio(self): """Return a measure of the sequences' word similarity (float in [0,1]). Each word has weight equal to its length for this measure >>> m = WordMatcher(a=['abcdef', '12'], b=['abcdef', '34']) # 3/4 of the text is the same >>> '%.3f' % m.ratio() # normal ratio fails ...
Find the total length of all words that match between the two sequences.
def match_length(self): """ Find the total length of all words that match between the two sequences.""" length = 0 for match in self.get_matching_blocks(): a, b, size = match length += self._text_length(self.a[a:a+size]) return length
Run an xml edit script and return the new html produced.
def run_edit_script(self): """ Run an xml edit script, and return the new html produced. """ for action, location, properties in self.edit_script: if action == 'delete': node = get_location(self.dom, location) self.action_delete(node) ...
Add <ins > and <del > tags to the dom to show changes.
def add_changes_markup(dom, ins_nodes, del_nodes): """ Add <ins> and <del> tags to the dom to show changes. """ # add markup for inserted and deleted sections for node in reversed(del_nodes): # diff algorithm deletes nodes in reverse order, so un-reverse the # order for this iteratio...
Unwrap items in the node list that have ancestors with the same tag.
def remove_nesting(dom, tag_name): """ Unwrap items in the node list that have ancestors with the same tag. """ for node in dom.getElementsByTagName(tag_name): for ancestor in ancestors(node): if ancestor is node: continue if ancestor is dom.documentElemen...
Sort the nodes of the dom in - place based on a comparison function.
def sort_nodes(dom, cmp_func): """ Sort the nodes of the dom in-place, based on a comparison function. """ dom.normalize() for node in list(walk_dom(dom, elements_only=True)): prev_sib = node.previousSibling while prev_sib and cmp_func(prev_sib, node) == 1: node.parentNod...
Merge all adjacent tags with the specified tag name. Return the number of merges performed.
def merge_adjacent(dom, tag_name): """ Merge all adjacent tags with the specified tag name. Return the number of merges performed. """ for node in dom.getElementsByTagName(tag_name): prev_sib = node.previousSibling if prev_sib and prev_sib.nodeName == node.tagName: for ch...
Wrap a copy of the given element around the contents of each of its children removing the node in the process.
def distribute(node): """ Wrap a copy of the given element around the contents of each of its children, removing the node in the process. """ children = list(c for c in node.childNodes if is_element(c)) unwrap(node) tag_name = node.tagName for c in children: wrap_inner(c, tag_nam...
Save object to the database. Removes all other entries if there are any.
def save(self, *args, **kwargs): """ Save object to the database. Removes all other entries if there are any. """ self.__class__.objects.exclude(id=self.id).delete() super(SingletonModel, self).save(*args, **kwargs)
Get the mappings from MAGICC to OpenSCM regions.
def get_magicc_region_to_openscm_region_mapping(inverse=False): """Get the mappings from MAGICC to OpenSCM regions. This is not a pure inverse of the other way around. For example, we never provide "GLOBAL" as a MAGICC return value because it's unnecesarily confusing when we also have "World". Fortunat...
Convert MAGICC regions to OpenSCM regions
def convert_magicc_to_openscm_regions(regions, inverse=False): """ Convert MAGICC regions to OpenSCM regions Parameters ---------- regions : list_like, str Regions to convert inverse : bool If True, convert the other way i.e. convert OpenSCM regions to MAGICC7 regions ...
Get the mappings from MAGICC7 to OpenSCM variables.
def get_magicc7_to_openscm_variable_mapping(inverse=False): """Get the mappings from MAGICC7 to OpenSCM variables. Parameters ---------- inverse : bool If True, return the inverse mappings i.e. OpenSCM to MAGICC7 mappings Returns ------- dict Dictionary of mappings """ ...
Convert MAGICC7 variables to OpenSCM variables
def convert_magicc7_to_openscm_variables(variables, inverse=False): """ Convert MAGICC7 variables to OpenSCM variables Parameters ---------- variables : list_like, str Variables to convert inverse : bool If True, convert the other way i.e. convert OpenSCM variables to MAGICC7 ...
Get the mappings from MAGICC6 to MAGICC7 variables.
def get_magicc6_to_magicc7_variable_mapping(inverse=False): """Get the mappings from MAGICC6 to MAGICC7 variables. Note that this mapping is not one to one. For example, "HFC4310", "HFC43-10" and "HFC-43-10" in MAGICC6 both map to "HFC4310" in MAGICC7 but "HFC4310" in MAGICC7 maps back to "HFC4310". ...
Convert MAGICC6 variables to MAGICC7 variables
def convert_magicc6_to_magicc7_variables(variables, inverse=False): """ Convert MAGICC6 variables to MAGICC7 variables Parameters ---------- variables : list_like, str Variables to convert inverse : bool If True, convert the other way i.e. convert MAGICC7 variables to MAGICC6 ...
Get the mappings from Pint to Fortran safe units.
def get_pint_to_fortran_safe_units_mapping(inverse=False): """Get the mappings from Pint to Fortran safe units. Fortran can't handle special characters like "^" or "/" in names, but we need these in Pint. Conversely, Pint stores variables with spaces by default e.g. "Mt CO2 / yr" but we don't want thes...
Convert Pint units to Fortran safe units
def convert_pint_to_fortran_safe_units(units, inverse=False): """ Convert Pint units to Fortran safe units Parameters ---------- units : list_like, str Units to convert inverse : bool If True, convert the other way i.e. convert Fortran safe units to Pint units Returns ...
Overrides the base evaluation to set the value to the evaluation result of the value expression in the schema
def run_evaluate(self) -> None: """ Overrides the base evaluation to set the value to the evaluation result of the value expression in the schema """ result = None self.eval_error = False if self._needs_evaluation: result = self._schema.value.evaluate(...
Sets the value of a key to a supplied value
def set(self, key: Any, value: Any) -> None: """ Sets the value of a key to a supplied value """ if key is not None: self[key] = value
Increments the value set against a key. If the key is not present 0 is assumed as the initial state
def increment(self, key: Any, by: int = 1) -> None: """ Increments the value set against a key. If the key is not present, 0 is assumed as the initial state """ if key is not None: self[key] = self.get(key, 0) + by
Inserts an item to the list as long as it is not None
def insert(self, index: int, obj: Any) -> None: """ Inserts an item to the list as long as it is not None """ if obj is not None: super().insert(index, obj)
Get the THISFILE_DATTYPE and THISFILE_REGIONMODE flags for a given region set.
def get_dattype_regionmode(regions, scen7=False): """ Get the THISFILE_DATTYPE and THISFILE_REGIONMODE flags for a given region set. In all MAGICC input files, there are two flags: THISFILE_DATTYPE and THISFILE_REGIONMODE. These tell MAGICC how to read in a given input file. This function maps the ...
Get the region order expected by MAGICC.
def get_region_order(regions, scen7=False): """ Get the region order expected by MAGICC. Parameters ---------- regions : list_like The regions to get THISFILE_DATTYPE and THISFILE_REGIONMODE flags for. scen7 : bool, optional Whether the file we are getting the flags for is a SC...
Get special code for MAGICC6 SCEN files.
def get_special_scen_code(regions, emissions): """ Get special code for MAGICC6 SCEN files. At the top of every MAGICC6 and MAGICC5 SCEN file there is a two digit number. The first digit, the 'scenfile_region_code' tells MAGICC how many regions data is being provided for. The second digit, the 'sce...
Determine the tool to use for reading/ writing.
def determine_tool(filepath, tool_to_get): """ Determine the tool to use for reading/writing. The function uses an internally defined set of mappings between filepaths, regular expresions and readers/writers to work out which tool to use for a given task, given the filepath. It is intended for...
Pull out a single config set from a parameters_out namelist.
def pull_cfg_from_parameters_out(parameters_out, namelist_to_read="nml_allcfgs"): """Pull out a single config set from a parameters_out namelist. This function returns a single file with the config that needs to be passed to MAGICC in order to do the same run as is represented by the values in ``parame...
Pull out a single config set from a MAGICC PARAMETERS. OUT file.
def pull_cfg_from_parameters_out_file( parameters_out_file, namelist_to_read="nml_allcfgs" ): """Pull out a single config set from a MAGICC ``PARAMETERS.OUT`` file. This function reads in the ``PARAMETERS.OUT`` file and returns a single file with the config that needs to be passed to MAGICC in order to...
Convert an RCP name into the generic Pymagicc RCP name
def get_generic_rcp_name(inname): """Convert an RCP name into the generic Pymagicc RCP name The conversion is case insensitive. Parameters ---------- inname : str The name for which to get the generic Pymagicc RCP name Returns ------- str The generic Pymagicc RCP name ...
Join two sets of timeseries
def join_timeseries(base, overwrite, join_linear=None): """Join two sets of timeseries Parameters ---------- base : :obj:`MAGICCData`, :obj:`pd.DataFrame`, filepath Base timeseries to use. If a filepath, the data will first be loaded from disk. overwrite : :obj:`MAGICCData`, :obj:`pd.DataF...
Read a MAGICC. SCEN file.
def read_scen_file( filepath, columns={ "model": ["unspecified"], "scenario": ["unspecified"], "climate_model": ["unspecified"], }, **kwargs ): """ Read a MAGICC .SCEN file. Parameters ---------- filepath : str Filepath of the .SCEN file to read ...
Determine the OpenSCM variable from a filepath.
def _get_openscm_var_from_filepath(filepath): """ Determine the OpenSCM variable from a filepath. Uses MAGICC's internal, implicit, filenaming conventions. Parameters ---------- filepath : str Filepath from which to determine the OpenSCM variable. Returns ------- str ...
Find the start and end of the embedded namelist.
def _find_nml(self): """ Find the start and end of the embedded namelist. Returns ------- (int, int) start and end index for the namelist """ nml_start = None nml_end = None for i in range(len(self.lines)): if self.lines[i]...