id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
7,600
mmp2/megaman
megaman/datasets/datasets.py
generate_megaman_data
def generate_megaman_data(sampling=2): """Generate 2D point data of the megaman image""" data = get_megaman_image() x = np.arange(sampling * data.shape[1]) / float(sampling) y = np.arange(sampling * data.shape[0]) / float(sampling) X, Y = map(np.ravel, np.meshgrid(x, y)) C = data[np.floor(Y.max() - Y).astype(int), np.floor(X).astype(int)] return np.vstack([X, Y]).T, C
python
def generate_megaman_data(sampling=2): """Generate 2D point data of the megaman image""" data = get_megaman_image() x = np.arange(sampling * data.shape[1]) / float(sampling) y = np.arange(sampling * data.shape[0]) / float(sampling) X, Y = map(np.ravel, np.meshgrid(x, y)) C = data[np.floor(Y.max() - Y).astype(int), np.floor(X).astype(int)] return np.vstack([X, Y]).T, C
[ "def", "generate_megaman_data", "(", "sampling", "=", "2", ")", ":", "data", "=", "get_megaman_image", "(", ")", "x", "=", "np", ".", "arange", "(", "sampling", "*", "data", ".", "shape", "[", "1", "]", ")", "/", "float", "(", "sampling", ")", "y", "=", "np", ".", "arange", "(", "sampling", "*", "data", ".", "shape", "[", "0", "]", ")", "/", "float", "(", "sampling", ")", "X", ",", "Y", "=", "map", "(", "np", ".", "ravel", ",", "np", ".", "meshgrid", "(", "x", ",", "y", ")", ")", "C", "=", "data", "[", "np", ".", "floor", "(", "Y", ".", "max", "(", ")", "-", "Y", ")", ".", "astype", "(", "int", ")", ",", "np", ".", "floor", "(", "X", ")", ".", "astype", "(", "int", ")", "]", "return", "np", ".", "vstack", "(", "[", "X", ",", "Y", "]", ")", ".", "T", ",", "C" ]
Generate 2D point data of the megaman image
[ "Generate", "2D", "point", "data", "of", "the", "megaman", "image" ]
faccaf267aad0a8b18ec8a705735fd9dd838ca1e
https://github.com/mmp2/megaman/blob/faccaf267aad0a8b18ec8a705735fd9dd838ca1e/megaman/datasets/datasets.py#L21-L29
7,601
mmp2/megaman
megaman/datasets/datasets.py
_make_S_curve
def _make_S_curve(x, range=(-0.75, 0.75)): """Make a 2D S-curve from a 1D vector""" assert x.ndim == 1 x = x - x.min() theta = 2 * np.pi * (range[0] + (range[1] - range[0]) * x / x.max()) X = np.empty((x.shape[0], 2), dtype=float) X[:, 0] = np.sign(theta) * (1 - np.cos(theta)) X[:, 1] = np.sin(theta) X *= x.max() / (2 * np.pi * (range[1] - range[0])) return X
python
def _make_S_curve(x, range=(-0.75, 0.75)): """Make a 2D S-curve from a 1D vector""" assert x.ndim == 1 x = x - x.min() theta = 2 * np.pi * (range[0] + (range[1] - range[0]) * x / x.max()) X = np.empty((x.shape[0], 2), dtype=float) X[:, 0] = np.sign(theta) * (1 - np.cos(theta)) X[:, 1] = np.sin(theta) X *= x.max() / (2 * np.pi * (range[1] - range[0])) return X
[ "def", "_make_S_curve", "(", "x", ",", "range", "=", "(", "-", "0.75", ",", "0.75", ")", ")", ":", "assert", "x", ".", "ndim", "==", "1", "x", "=", "x", "-", "x", ".", "min", "(", ")", "theta", "=", "2", "*", "np", ".", "pi", "*", "(", "range", "[", "0", "]", "+", "(", "range", "[", "1", "]", "-", "range", "[", "0", "]", ")", "*", "x", "/", "x", ".", "max", "(", ")", ")", "X", "=", "np", ".", "empty", "(", "(", "x", ".", "shape", "[", "0", "]", ",", "2", ")", ",", "dtype", "=", "float", ")", "X", "[", ":", ",", "0", "]", "=", "np", ".", "sign", "(", "theta", ")", "*", "(", "1", "-", "np", ".", "cos", "(", "theta", ")", ")", "X", "[", ":", ",", "1", "]", "=", "np", ".", "sin", "(", "theta", ")", "X", "*=", "x", ".", "max", "(", ")", "/", "(", "2", "*", "np", ".", "pi", "*", "(", "range", "[", "1", "]", "-", "range", "[", "0", "]", ")", ")", "return", "X" ]
Make a 2D S-curve from a 1D vector
[ "Make", "a", "2D", "S", "-", "curve", "from", "a", "1D", "vector" ]
faccaf267aad0a8b18ec8a705735fd9dd838ca1e
https://github.com/mmp2/megaman/blob/faccaf267aad0a8b18ec8a705735fd9dd838ca1e/megaman/datasets/datasets.py#L32-L41
7,602
mmp2/megaman
megaman/datasets/datasets.py
generate_megaman_manifold
def generate_megaman_manifold(sampling=2, nfolds=2, rotate=True, random_state=None): """Generate a manifold of the megaman data""" X, c = generate_megaman_data(sampling) for i in range(nfolds): X = np.hstack([_make_S_curve(x) for x in X.T]) if rotate: rand = check_random_state(random_state) R = rand.randn(X.shape[1], X.shape[1]) U, s, VT = np.linalg.svd(R) X = np.dot(X, U) return X, c
python
def generate_megaman_manifold(sampling=2, nfolds=2, rotate=True, random_state=None): """Generate a manifold of the megaman data""" X, c = generate_megaman_data(sampling) for i in range(nfolds): X = np.hstack([_make_S_curve(x) for x in X.T]) if rotate: rand = check_random_state(random_state) R = rand.randn(X.shape[1], X.shape[1]) U, s, VT = np.linalg.svd(R) X = np.dot(X, U) return X, c
[ "def", "generate_megaman_manifold", "(", "sampling", "=", "2", ",", "nfolds", "=", "2", ",", "rotate", "=", "True", ",", "random_state", "=", "None", ")", ":", "X", ",", "c", "=", "generate_megaman_data", "(", "sampling", ")", "for", "i", "in", "range", "(", "nfolds", ")", ":", "X", "=", "np", ".", "hstack", "(", "[", "_make_S_curve", "(", "x", ")", "for", "x", "in", "X", ".", "T", "]", ")", "if", "rotate", ":", "rand", "=", "check_random_state", "(", "random_state", ")", "R", "=", "rand", ".", "randn", "(", "X", ".", "shape", "[", "1", "]", ",", "X", ".", "shape", "[", "1", "]", ")", "U", ",", "s", ",", "VT", "=", "np", ".", "linalg", ".", "svd", "(", "R", ")", "X", "=", "np", ".", "dot", "(", "X", ",", "U", ")", "return", "X", ",", "c" ]
Generate a manifold of the megaman data
[ "Generate", "a", "manifold", "of", "the", "megaman", "data" ]
faccaf267aad0a8b18ec8a705735fd9dd838ca1e
https://github.com/mmp2/megaman/blob/faccaf267aad0a8b18ec8a705735fd9dd838ca1e/megaman/datasets/datasets.py#L44-L57
7,603
presslabs/z3
z3/ssh_sync.py
snapshots_to_send
def snapshots_to_send(source_snaps, dest_snaps): """return pair of snapshots""" if len(source_snaps) == 0: raise AssertionError("No snapshots exist locally!") if len(dest_snaps) == 0: # nothing on the remote side, send everything return None, source_snaps[-1] last_remote = dest_snaps[-1] for snap in reversed(source_snaps): if snap == last_remote: # found a common snapshot return last_remote, source_snaps[-1] # sys.stderr.write("source:'{}', dest:'{}'".format(source_snaps, dest_snaps)) raise AssertionError("Latest snapshot on destination doesn't exist on source!")
python
def snapshots_to_send(source_snaps, dest_snaps): """return pair of snapshots""" if len(source_snaps) == 0: raise AssertionError("No snapshots exist locally!") if len(dest_snaps) == 0: # nothing on the remote side, send everything return None, source_snaps[-1] last_remote = dest_snaps[-1] for snap in reversed(source_snaps): if snap == last_remote: # found a common snapshot return last_remote, source_snaps[-1] # sys.stderr.write("source:'{}', dest:'{}'".format(source_snaps, dest_snaps)) raise AssertionError("Latest snapshot on destination doesn't exist on source!")
[ "def", "snapshots_to_send", "(", "source_snaps", ",", "dest_snaps", ")", ":", "if", "len", "(", "source_snaps", ")", "==", "0", ":", "raise", "AssertionError", "(", "\"No snapshots exist locally!\"", ")", "if", "len", "(", "dest_snaps", ")", "==", "0", ":", "# nothing on the remote side, send everything", "return", "None", ",", "source_snaps", "[", "-", "1", "]", "last_remote", "=", "dest_snaps", "[", "-", "1", "]", "for", "snap", "in", "reversed", "(", "source_snaps", ")", ":", "if", "snap", "==", "last_remote", ":", "# found a common snapshot", "return", "last_remote", ",", "source_snaps", "[", "-", "1", "]", "# sys.stderr.write(\"source:'{}', dest:'{}'\".format(source_snaps, dest_snaps))", "raise", "AssertionError", "(", "\"Latest snapshot on destination doesn't exist on source!\"", ")" ]
return pair of snapshots
[ "return", "pair", "of", "snapshots" ]
965898cccddd351ce4c56402a215c3bda9f37b5e
https://github.com/presslabs/z3/blob/965898cccddd351ce4c56402a215c3bda9f37b5e/z3/ssh_sync.py#L25-L38
7,604
presslabs/z3
z3/pput.py
StreamHandler.get_chunk
def get_chunk(self): """Return complete chunks or None if EOF reached""" while not self._eof_reached: read = self.input_stream.read(self.chunk_size - len(self._partial_chunk)) if len(read) == 0: self._eof_reached = True self._partial_chunk += read if len(self._partial_chunk) == self.chunk_size or self._eof_reached: chunk = self._partial_chunk self._partial_chunk = "" return chunk
python
def get_chunk(self): """Return complete chunks or None if EOF reached""" while not self._eof_reached: read = self.input_stream.read(self.chunk_size - len(self._partial_chunk)) if len(read) == 0: self._eof_reached = True self._partial_chunk += read if len(self._partial_chunk) == self.chunk_size or self._eof_reached: chunk = self._partial_chunk self._partial_chunk = "" return chunk
[ "def", "get_chunk", "(", "self", ")", ":", "while", "not", "self", ".", "_eof_reached", ":", "read", "=", "self", ".", "input_stream", ".", "read", "(", "self", ".", "chunk_size", "-", "len", "(", "self", ".", "_partial_chunk", ")", ")", "if", "len", "(", "read", ")", "==", "0", ":", "self", ".", "_eof_reached", "=", "True", "self", ".", "_partial_chunk", "+=", "read", "if", "len", "(", "self", ".", "_partial_chunk", ")", "==", "self", ".", "chunk_size", "or", "self", ".", "_eof_reached", ":", "chunk", "=", "self", ".", "_partial_chunk", "self", ".", "_partial_chunk", "=", "\"\"", "return", "chunk" ]
Return complete chunks or None if EOF reached
[ "Return", "complete", "chunks", "or", "None", "if", "EOF", "reached" ]
965898cccddd351ce4c56402a215c3bda9f37b5e
https://github.com/presslabs/z3/blob/965898cccddd351ce4c56402a215c3bda9f37b5e/z3/pput.py#L76-L86
7,605
presslabs/z3
z3/pput.py
UploadSupervisor._handle_result
def _handle_result(self): """Process one result. Block untill one is available """ result = self.inbox.get() if result.success: if self._verbosity >= VERB_PROGRESS: sys.stderr.write("\nuploaded chunk {} \n".format(result.index)) self.results.append((result.index, result.md5)) self._pending_chunks -= 1 else: raise result.traceback
python
def _handle_result(self): """Process one result. Block untill one is available """ result = self.inbox.get() if result.success: if self._verbosity >= VERB_PROGRESS: sys.stderr.write("\nuploaded chunk {} \n".format(result.index)) self.results.append((result.index, result.md5)) self._pending_chunks -= 1 else: raise result.traceback
[ "def", "_handle_result", "(", "self", ")", ":", "result", "=", "self", ".", "inbox", ".", "get", "(", ")", "if", "result", ".", "success", ":", "if", "self", ".", "_verbosity", ">=", "VERB_PROGRESS", ":", "sys", ".", "stderr", ".", "write", "(", "\"\\nuploaded chunk {} \\n\"", ".", "format", "(", "result", ".", "index", ")", ")", "self", ".", "results", ".", "append", "(", "(", "result", ".", "index", ",", "result", ".", "md5", ")", ")", "self", ".", "_pending_chunks", "-=", "1", "else", ":", "raise", "result", ".", "traceback" ]
Process one result. Block untill one is available
[ "Process", "one", "result", ".", "Block", "untill", "one", "is", "available" ]
965898cccddd351ce4c56402a215c3bda9f37b5e
https://github.com/presslabs/z3/blob/965898cccddd351ce4c56402a215c3bda9f37b5e/z3/pput.py#L201-L211
7,606
presslabs/z3
z3/pput.py
UploadSupervisor._send_chunk
def _send_chunk(self, index, chunk): """Send the current chunk to the workers for processing. Called when the _partial_chunk is complete. Blocks when the outbox is full. """ self._pending_chunks += 1 self.outbox.put((index, chunk))
python
def _send_chunk(self, index, chunk): """Send the current chunk to the workers for processing. Called when the _partial_chunk is complete. Blocks when the outbox is full. """ self._pending_chunks += 1 self.outbox.put((index, chunk))
[ "def", "_send_chunk", "(", "self", ",", "index", ",", "chunk", ")", ":", "self", ".", "_pending_chunks", "+=", "1", "self", ".", "outbox", ".", "put", "(", "(", "index", ",", "chunk", ")", ")" ]
Send the current chunk to the workers for processing. Called when the _partial_chunk is complete. Blocks when the outbox is full.
[ "Send", "the", "current", "chunk", "to", "the", "workers", "for", "processing", ".", "Called", "when", "the", "_partial_chunk", "is", "complete", "." ]
965898cccddd351ce4c56402a215c3bda9f37b5e
https://github.com/presslabs/z3/blob/965898cccddd351ce4c56402a215c3bda9f37b5e/z3/pput.py#L220-L227
7,607
presslabs/z3
z3/config.py
OnionDict._get
def _get(self, key, section=None, default=_onion_dict_guard): """Try to get the key from each dict in turn. If you specify the optional section it looks there first. """ if section is not None: section_dict = self.__sections.get(section, {}) if key in section_dict: return section_dict[key] for d in self.__dictionaries: if key in d: return d[key] if default is _onion_dict_guard: raise KeyError(key) else: return default
python
def _get(self, key, section=None, default=_onion_dict_guard): """Try to get the key from each dict in turn. If you specify the optional section it looks there first. """ if section is not None: section_dict = self.__sections.get(section, {}) if key in section_dict: return section_dict[key] for d in self.__dictionaries: if key in d: return d[key] if default is _onion_dict_guard: raise KeyError(key) else: return default
[ "def", "_get", "(", "self", ",", "key", ",", "section", "=", "None", ",", "default", "=", "_onion_dict_guard", ")", ":", "if", "section", "is", "not", "None", ":", "section_dict", "=", "self", ".", "__sections", ".", "get", "(", "section", ",", "{", "}", ")", "if", "key", "in", "section_dict", ":", "return", "section_dict", "[", "key", "]", "for", "d", "in", "self", ".", "__dictionaries", ":", "if", "key", "in", "d", ":", "return", "d", "[", "key", "]", "if", "default", "is", "_onion_dict_guard", ":", "raise", "KeyError", "(", "key", ")", "else", ":", "return", "default" ]
Try to get the key from each dict in turn. If you specify the optional section it looks there first.
[ "Try", "to", "get", "the", "key", "from", "each", "dict", "in", "turn", ".", "If", "you", "specify", "the", "optional", "section", "it", "looks", "there", "first", "." ]
965898cccddd351ce4c56402a215c3bda9f37b5e
https://github.com/presslabs/z3/blob/965898cccddd351ce4c56402a215c3bda9f37b5e/z3/config.py#L21-L35
7,608
presslabs/z3
z3/snap.py
ZFSSnapshotManager._parse_snapshots
def _parse_snapshots(self): """Returns all snapshots grouped by filesystem, a dict of OrderedDict's The order of snapshots matters when determining parents for incremental send, so it's preserved. Data is indexed by filesystem then for each filesystem we have an OrderedDict of snapshots. """ try: snap = self._list_snapshots() except OSError as err: logging.error("unable to list local snapshots!") return {} vols = {} for line in snap.splitlines(): if len(line) == 0: continue name, used, refer, mountpoint, written = line.split('\t') vol_name, snap_name = name.split('@', 1) snapshots = vols.setdefault(vol_name, OrderedDict()) snapshots[snap_name] = { 'name': name, 'used': used, 'refer': refer, 'mountpoint': mountpoint, 'written': written, } return vols
python
def _parse_snapshots(self): """Returns all snapshots grouped by filesystem, a dict of OrderedDict's The order of snapshots matters when determining parents for incremental send, so it's preserved. Data is indexed by filesystem then for each filesystem we have an OrderedDict of snapshots. """ try: snap = self._list_snapshots() except OSError as err: logging.error("unable to list local snapshots!") return {} vols = {} for line in snap.splitlines(): if len(line) == 0: continue name, used, refer, mountpoint, written = line.split('\t') vol_name, snap_name = name.split('@', 1) snapshots = vols.setdefault(vol_name, OrderedDict()) snapshots[snap_name] = { 'name': name, 'used': used, 'refer': refer, 'mountpoint': mountpoint, 'written': written, } return vols
[ "def", "_parse_snapshots", "(", "self", ")", ":", "try", ":", "snap", "=", "self", ".", "_list_snapshots", "(", ")", "except", "OSError", "as", "err", ":", "logging", ".", "error", "(", "\"unable to list local snapshots!\"", ")", "return", "{", "}", "vols", "=", "{", "}", "for", "line", "in", "snap", ".", "splitlines", "(", ")", ":", "if", "len", "(", "line", ")", "==", "0", ":", "continue", "name", ",", "used", ",", "refer", ",", "mountpoint", ",", "written", "=", "line", ".", "split", "(", "'\\t'", ")", "vol_name", ",", "snap_name", "=", "name", ".", "split", "(", "'@'", ",", "1", ")", "snapshots", "=", "vols", ".", "setdefault", "(", "vol_name", ",", "OrderedDict", "(", ")", ")", "snapshots", "[", "snap_name", "]", "=", "{", "'name'", ":", "name", ",", "'used'", ":", "used", ",", "'refer'", ":", "refer", ",", "'mountpoint'", ":", "mountpoint", ",", "'written'", ":", "written", ",", "}", "return", "vols" ]
Returns all snapshots grouped by filesystem, a dict of OrderedDict's The order of snapshots matters when determining parents for incremental send, so it's preserved. Data is indexed by filesystem then for each filesystem we have an OrderedDict of snapshots.
[ "Returns", "all", "snapshots", "grouped", "by", "filesystem", "a", "dict", "of", "OrderedDict", "s", "The", "order", "of", "snapshots", "matters", "when", "determining", "parents", "for", "incremental", "send", "so", "it", "s", "preserved", ".", "Data", "is", "indexed", "by", "filesystem", "then", "for", "each", "filesystem", "we", "have", "an", "OrderedDict", "of", "snapshots", "." ]
965898cccddd351ce4c56402a215c3bda9f37b5e
https://github.com/presslabs/z3/blob/965898cccddd351ce4c56402a215c3bda9f37b5e/z3/snap.py#L176-L202
7,609
presslabs/z3
z3/snap.py
PairManager._compress
def _compress(self, cmd): """Adds the appropriate command to compress the zfs stream""" compressor = COMPRESSORS.get(self.compressor) if compressor is None: return cmd compress_cmd = compressor['compress'] return "{} | {}".format(compress_cmd, cmd)
python
def _compress(self, cmd): """Adds the appropriate command to compress the zfs stream""" compressor = COMPRESSORS.get(self.compressor) if compressor is None: return cmd compress_cmd = compressor['compress'] return "{} | {}".format(compress_cmd, cmd)
[ "def", "_compress", "(", "self", ",", "cmd", ")", ":", "compressor", "=", "COMPRESSORS", ".", "get", "(", "self", ".", "compressor", ")", "if", "compressor", "is", "None", ":", "return", "cmd", "compress_cmd", "=", "compressor", "[", "'compress'", "]", "return", "\"{} | {}\"", ".", "format", "(", "compress_cmd", ",", "cmd", ")" ]
Adds the appropriate command to compress the zfs stream
[ "Adds", "the", "appropriate", "command", "to", "compress", "the", "zfs", "stream" ]
965898cccddd351ce4c56402a215c3bda9f37b5e
https://github.com/presslabs/z3/blob/965898cccddd351ce4c56402a215c3bda9f37b5e/z3/snap.py#L311-L317
7,610
presslabs/z3
z3/snap.py
PairManager._decompress
def _decompress(self, cmd, s3_snap): """Adds the appropriate command to decompress the zfs stream This is determined from the metadata of the s3_snap. """ compressor = COMPRESSORS.get(s3_snap.compressor) if compressor is None: return cmd decompress_cmd = compressor['decompress'] return "{} | {}".format(decompress_cmd, cmd)
python
def _decompress(self, cmd, s3_snap): """Adds the appropriate command to decompress the zfs stream This is determined from the metadata of the s3_snap. """ compressor = COMPRESSORS.get(s3_snap.compressor) if compressor is None: return cmd decompress_cmd = compressor['decompress'] return "{} | {}".format(decompress_cmd, cmd)
[ "def", "_decompress", "(", "self", ",", "cmd", ",", "s3_snap", ")", ":", "compressor", "=", "COMPRESSORS", ".", "get", "(", "s3_snap", ".", "compressor", ")", "if", "compressor", "is", "None", ":", "return", "cmd", "decompress_cmd", "=", "compressor", "[", "'decompress'", "]", "return", "\"{} | {}\"", ".", "format", "(", "decompress_cmd", ",", "cmd", ")" ]
Adds the appropriate command to decompress the zfs stream This is determined from the metadata of the s3_snap.
[ "Adds", "the", "appropriate", "command", "to", "decompress", "the", "zfs", "stream", "This", "is", "determined", "from", "the", "metadata", "of", "the", "s3_snap", "." ]
965898cccddd351ce4c56402a215c3bda9f37b5e
https://github.com/presslabs/z3/blob/965898cccddd351ce4c56402a215c3bda9f37b5e/z3/snap.py#L319-L327
7,611
presslabs/z3
z3/snap.py
PairManager.backup_full
def backup_full(self, snap_name=None, dry_run=False): """Do a full backup of a snapshot. By default latest local snapshot""" z_snap = self._snapshot_to_backup(snap_name) estimated_size = self._parse_estimated_size( self._cmd.shell( "zfs send -nvP '{}'".format(z_snap.name), capture=True)) self._cmd.pipe( "zfs send '{}'".format(z_snap.name), self._compress( self._pput_cmd( estimated=estimated_size, s3_prefix=self.s3_manager.s3_prefix, snap_name=z_snap.name) ), dry_run=dry_run, estimated_size=estimated_size, ) return [{'snap_name': z_snap.name, 'size': estimated_size}]
python
def backup_full(self, snap_name=None, dry_run=False): """Do a full backup of a snapshot. By default latest local snapshot""" z_snap = self._snapshot_to_backup(snap_name) estimated_size = self._parse_estimated_size( self._cmd.shell( "zfs send -nvP '{}'".format(z_snap.name), capture=True)) self._cmd.pipe( "zfs send '{}'".format(z_snap.name), self._compress( self._pput_cmd( estimated=estimated_size, s3_prefix=self.s3_manager.s3_prefix, snap_name=z_snap.name) ), dry_run=dry_run, estimated_size=estimated_size, ) return [{'snap_name': z_snap.name, 'size': estimated_size}]
[ "def", "backup_full", "(", "self", ",", "snap_name", "=", "None", ",", "dry_run", "=", "False", ")", ":", "z_snap", "=", "self", ".", "_snapshot_to_backup", "(", "snap_name", ")", "estimated_size", "=", "self", ".", "_parse_estimated_size", "(", "self", ".", "_cmd", ".", "shell", "(", "\"zfs send -nvP '{}'\"", ".", "format", "(", "z_snap", ".", "name", ")", ",", "capture", "=", "True", ")", ")", "self", ".", "_cmd", ".", "pipe", "(", "\"zfs send '{}'\"", ".", "format", "(", "z_snap", ".", "name", ")", ",", "self", ".", "_compress", "(", "self", ".", "_pput_cmd", "(", "estimated", "=", "estimated_size", ",", "s3_prefix", "=", "self", ".", "s3_manager", ".", "s3_prefix", ",", "snap_name", "=", "z_snap", ".", "name", ")", ")", ",", "dry_run", "=", "dry_run", ",", "estimated_size", "=", "estimated_size", ",", ")", "return", "[", "{", "'snap_name'", ":", "z_snap", ".", "name", ",", "'size'", ":", "estimated_size", "}", "]" ]
Do a full backup of a snapshot. By default latest local snapshot
[ "Do", "a", "full", "backup", "of", "a", "snapshot", ".", "By", "default", "latest", "local", "snapshot" ]
965898cccddd351ce4c56402a215c3bda9f37b5e
https://github.com/presslabs/z3/blob/965898cccddd351ce4c56402a215c3bda9f37b5e/z3/snap.py#L341-L359
7,612
presslabs/z3
z3/snap.py
PairManager.backup_incremental
def backup_incremental(self, snap_name=None, dry_run=False): """Uploads named snapshot or latest, along with any other snapshots required for an incremental backup. """ z_snap = self._snapshot_to_backup(snap_name) to_upload = [] current = z_snap uploaded_meta = [] while True: s3_snap = self.s3_manager.get(current.name) if s3_snap is not None: if not s3_snap.is_healthy: # abort everything if we run in to unhealthy snapshots raise IntegrityError( "Broken snapshot detected {}, reason: '{}'".format( s3_snap.name, s3_snap.reason_broken )) break to_upload.append(current) if current.parent is None: break current = current.parent for z_snap in reversed(to_upload): estimated_size = self._parse_estimated_size( self._cmd.shell( "zfs send -nvP -i '{}' '{}'".format( z_snap.parent.name, z_snap.name), capture=True)) self._cmd.pipe( "zfs send -i '{}' '{}'".format( z_snap.parent.name, z_snap.name), self._compress( self._pput_cmd( estimated=estimated_size, parent=z_snap.parent.name, s3_prefix=self.s3_manager.s3_prefix, snap_name=z_snap.name) ), dry_run=dry_run, estimated_size=estimated_size, ) uploaded_meta.append({'snap_name': z_snap.name, 'size': estimated_size}) return uploaded_meta
python
def backup_incremental(self, snap_name=None, dry_run=False): """Uploads named snapshot or latest, along with any other snapshots required for an incremental backup. """ z_snap = self._snapshot_to_backup(snap_name) to_upload = [] current = z_snap uploaded_meta = [] while True: s3_snap = self.s3_manager.get(current.name) if s3_snap is not None: if not s3_snap.is_healthy: # abort everything if we run in to unhealthy snapshots raise IntegrityError( "Broken snapshot detected {}, reason: '{}'".format( s3_snap.name, s3_snap.reason_broken )) break to_upload.append(current) if current.parent is None: break current = current.parent for z_snap in reversed(to_upload): estimated_size = self._parse_estimated_size( self._cmd.shell( "zfs send -nvP -i '{}' '{}'".format( z_snap.parent.name, z_snap.name), capture=True)) self._cmd.pipe( "zfs send -i '{}' '{}'".format( z_snap.parent.name, z_snap.name), self._compress( self._pput_cmd( estimated=estimated_size, parent=z_snap.parent.name, s3_prefix=self.s3_manager.s3_prefix, snap_name=z_snap.name) ), dry_run=dry_run, estimated_size=estimated_size, ) uploaded_meta.append({'snap_name': z_snap.name, 'size': estimated_size}) return uploaded_meta
[ "def", "backup_incremental", "(", "self", ",", "snap_name", "=", "None", ",", "dry_run", "=", "False", ")", ":", "z_snap", "=", "self", ".", "_snapshot_to_backup", "(", "snap_name", ")", "to_upload", "=", "[", "]", "current", "=", "z_snap", "uploaded_meta", "=", "[", "]", "while", "True", ":", "s3_snap", "=", "self", ".", "s3_manager", ".", "get", "(", "current", ".", "name", ")", "if", "s3_snap", "is", "not", "None", ":", "if", "not", "s3_snap", ".", "is_healthy", ":", "# abort everything if we run in to unhealthy snapshots", "raise", "IntegrityError", "(", "\"Broken snapshot detected {}, reason: '{}'\"", ".", "format", "(", "s3_snap", ".", "name", ",", "s3_snap", ".", "reason_broken", ")", ")", "break", "to_upload", ".", "append", "(", "current", ")", "if", "current", ".", "parent", "is", "None", ":", "break", "current", "=", "current", ".", "parent", "for", "z_snap", "in", "reversed", "(", "to_upload", ")", ":", "estimated_size", "=", "self", ".", "_parse_estimated_size", "(", "self", ".", "_cmd", ".", "shell", "(", "\"zfs send -nvP -i '{}' '{}'\"", ".", "format", "(", "z_snap", ".", "parent", ".", "name", ",", "z_snap", ".", "name", ")", ",", "capture", "=", "True", ")", ")", "self", ".", "_cmd", ".", "pipe", "(", "\"zfs send -i '{}' '{}'\"", ".", "format", "(", "z_snap", ".", "parent", ".", "name", ",", "z_snap", ".", "name", ")", ",", "self", ".", "_compress", "(", "self", ".", "_pput_cmd", "(", "estimated", "=", "estimated_size", ",", "parent", "=", "z_snap", ".", "parent", ".", "name", ",", "s3_prefix", "=", "self", ".", "s3_manager", ".", "s3_prefix", ",", "snap_name", "=", "z_snap", ".", "name", ")", ")", ",", "dry_run", "=", "dry_run", ",", "estimated_size", "=", "estimated_size", ",", ")", "uploaded_meta", ".", "append", "(", "{", "'snap_name'", ":", "z_snap", ".", "name", ",", "'size'", ":", "estimated_size", "}", ")", "return", "uploaded_meta" ]
Uploads named snapshot or latest, along with any other snapshots required for an incremental backup.
[ "Uploads", "named", "snapshot", "or", "latest", "along", "with", "any", "other", "snapshots", "required", "for", "an", "incremental", "backup", "." ]
965898cccddd351ce4c56402a215c3bda9f37b5e
https://github.com/presslabs/z3/blob/965898cccddd351ce4c56402a215c3bda9f37b5e/z3/snap.py#L361-L403
7,613
pyannote/pyannote-metrics
pyannote/metrics/utils.py
UEMSupportMixin.extrude
def extrude(self, uem, reference, collar=0.0, skip_overlap=False): """Extrude reference boundary collars from uem reference |----| |--------------| |-------------| uem |---------------------| |-------------------------------| extruded |--| |--| |---| |-----| |-| |-----| |-----------| |-----| Parameters ---------- uem : Timeline Evaluation map. reference : Annotation Reference annotation. collar : float, optional When provided, set the duration of collars centered around reference segment boundaries that are extruded from both reference and hypothesis. Defaults to 0. (i.e. no collar). skip_overlap : bool, optional Set to True to not evaluate overlap regions. Defaults to False (i.e. keep overlap regions). Returns ------- extruded_uem : Timeline """ if collar == 0. and not skip_overlap: return uem collars, overlap_regions = [], [] # build list of collars if needed if collar > 0.: # iterate over all segments in reference for segment in reference.itersegments(): # add collar centered on start time t = segment.start collars.append(Segment(t - .5 * collar, t + .5 * collar)) # add collar centered on end time t = segment.end collars.append(Segment(t - .5 * collar, t + .5 * collar)) # build list of overlap regions if needed if skip_overlap: # iterate over pair of intersecting segments for (segment1, track1), (segment2, track2) in reference.co_iter(reference): if segment1 == segment2 and track1 == track2: continue # add their intersection overlap_regions.append(segment1 & segment2) segments = collars + overlap_regions return Timeline(segments=segments).support().gaps(support=uem)
python
def extrude(self, uem, reference, collar=0.0, skip_overlap=False): """Extrude reference boundary collars from uem reference |----| |--------------| |-------------| uem |---------------------| |-------------------------------| extruded |--| |--| |---| |-----| |-| |-----| |-----------| |-----| Parameters ---------- uem : Timeline Evaluation map. reference : Annotation Reference annotation. collar : float, optional When provided, set the duration of collars centered around reference segment boundaries that are extruded from both reference and hypothesis. Defaults to 0. (i.e. no collar). skip_overlap : bool, optional Set to True to not evaluate overlap regions. Defaults to False (i.e. keep overlap regions). Returns ------- extruded_uem : Timeline """ if collar == 0. and not skip_overlap: return uem collars, overlap_regions = [], [] # build list of collars if needed if collar > 0.: # iterate over all segments in reference for segment in reference.itersegments(): # add collar centered on start time t = segment.start collars.append(Segment(t - .5 * collar, t + .5 * collar)) # add collar centered on end time t = segment.end collars.append(Segment(t - .5 * collar, t + .5 * collar)) # build list of overlap regions if needed if skip_overlap: # iterate over pair of intersecting segments for (segment1, track1), (segment2, track2) in reference.co_iter(reference): if segment1 == segment2 and track1 == track2: continue # add their intersection overlap_regions.append(segment1 & segment2) segments = collars + overlap_regions return Timeline(segments=segments).support().gaps(support=uem)
[ "def", "extrude", "(", "self", ",", "uem", ",", "reference", ",", "collar", "=", "0.0", ",", "skip_overlap", "=", "False", ")", ":", "if", "collar", "==", "0.", "and", "not", "skip_overlap", ":", "return", "uem", "collars", ",", "overlap_regions", "=", "[", "]", ",", "[", "]", "# build list of collars if needed", "if", "collar", ">", "0.", ":", "# iterate over all segments in reference", "for", "segment", "in", "reference", ".", "itersegments", "(", ")", ":", "# add collar centered on start time", "t", "=", "segment", ".", "start", "collars", ".", "append", "(", "Segment", "(", "t", "-", ".5", "*", "collar", ",", "t", "+", ".5", "*", "collar", ")", ")", "# add collar centered on end time", "t", "=", "segment", ".", "end", "collars", ".", "append", "(", "Segment", "(", "t", "-", ".5", "*", "collar", ",", "t", "+", ".5", "*", "collar", ")", ")", "# build list of overlap regions if needed", "if", "skip_overlap", ":", "# iterate over pair of intersecting segments", "for", "(", "segment1", ",", "track1", ")", ",", "(", "segment2", ",", "track2", ")", "in", "reference", ".", "co_iter", "(", "reference", ")", ":", "if", "segment1", "==", "segment2", "and", "track1", "==", "track2", ":", "continue", "# add their intersection", "overlap_regions", ".", "append", "(", "segment1", "&", "segment2", ")", "segments", "=", "collars", "+", "overlap_regions", "return", "Timeline", "(", "segments", "=", "segments", ")", ".", "support", "(", ")", ".", "gaps", "(", "support", "=", "uem", ")" ]
Extrude reference boundary collars from uem reference |----| |--------------| |-------------| uem |---------------------| |-------------------------------| extruded |--| |--| |---| |-----| |-| |-----| |-----------| |-----| Parameters ---------- uem : Timeline Evaluation map. reference : Annotation Reference annotation. collar : float, optional When provided, set the duration of collars centered around reference segment boundaries that are extruded from both reference and hypothesis. Defaults to 0. (i.e. no collar). skip_overlap : bool, optional Set to True to not evaluate overlap regions. Defaults to False (i.e. keep overlap regions). Returns ------- extruded_uem : Timeline
[ "Extrude", "reference", "boundary", "collars", "from", "uem" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/utils.py#L38-L93
7,614
pyannote/pyannote-metrics
pyannote/metrics/utils.py
UEMSupportMixin.common_timeline
def common_timeline(self, reference, hypothesis): """Return timeline common to both reference and hypothesis reference |--------| |------------| |---------| |----| hypothesis |--------------| |------| |----------------| timeline |--|-----|----|---|-|------| |-|---------|----| |----| Parameters ---------- reference : Annotation hypothesis : Annotation Returns ------- timeline : Timeline """ timeline = reference.get_timeline(copy=True) timeline.update(hypothesis.get_timeline(copy=False)) return timeline.segmentation()
python
def common_timeline(self, reference, hypothesis): """Return timeline common to both reference and hypothesis reference |--------| |------------| |---------| |----| hypothesis |--------------| |------| |----------------| timeline |--|-----|----|---|-|------| |-|---------|----| |----| Parameters ---------- reference : Annotation hypothesis : Annotation Returns ------- timeline : Timeline """ timeline = reference.get_timeline(copy=True) timeline.update(hypothesis.get_timeline(copy=False)) return timeline.segmentation()
[ "def", "common_timeline", "(", "self", ",", "reference", ",", "hypothesis", ")", ":", "timeline", "=", "reference", ".", "get_timeline", "(", "copy", "=", "True", ")", "timeline", ".", "update", "(", "hypothesis", ".", "get_timeline", "(", "copy", "=", "False", ")", ")", "return", "timeline", ".", "segmentation", "(", ")" ]
Return timeline common to both reference and hypothesis reference |--------| |------------| |---------| |----| hypothesis |--------------| |------| |----------------| timeline |--|-----|----|---|-|------| |-|---------|----| |----| Parameters ---------- reference : Annotation hypothesis : Annotation Returns ------- timeline : Timeline
[ "Return", "timeline", "common", "to", "both", "reference", "and", "hypothesis" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/utils.py#L95-L113
7,615
pyannote/pyannote-metrics
pyannote/metrics/utils.py
UEMSupportMixin.project
def project(self, annotation, timeline): """Project annotation onto timeline segments reference |__A__| |__B__| |____C____| timeline |---|---|---| |---| projection |_A_|_A_|_C_| |_B_| |_C_| Parameters ---------- annotation : Annotation timeline : Timeline Returns ------- projection : Annotation """ projection = annotation.empty() timeline_ = annotation.get_timeline(copy=False) for segment_, segment in timeline_.co_iter(timeline): for track_ in annotation.get_tracks(segment_): track = projection.new_track(segment, candidate=track_) projection[segment, track] = annotation[segment_, track_] return projection
python
def project(self, annotation, timeline): """Project annotation onto timeline segments reference |__A__| |__B__| |____C____| timeline |---|---|---| |---| projection |_A_|_A_|_C_| |_B_| |_C_| Parameters ---------- annotation : Annotation timeline : Timeline Returns ------- projection : Annotation """ projection = annotation.empty() timeline_ = annotation.get_timeline(copy=False) for segment_, segment in timeline_.co_iter(timeline): for track_ in annotation.get_tracks(segment_): track = projection.new_track(segment, candidate=track_) projection[segment, track] = annotation[segment_, track_] return projection
[ "def", "project", "(", "self", ",", "annotation", ",", "timeline", ")", ":", "projection", "=", "annotation", ".", "empty", "(", ")", "timeline_", "=", "annotation", ".", "get_timeline", "(", "copy", "=", "False", ")", "for", "segment_", ",", "segment", "in", "timeline_", ".", "co_iter", "(", "timeline", ")", ":", "for", "track_", "in", "annotation", ".", "get_tracks", "(", "segment_", ")", ":", "track", "=", "projection", ".", "new_track", "(", "segment", ",", "candidate", "=", "track_", ")", "projection", "[", "segment", ",", "track", "]", "=", "annotation", "[", "segment_", ",", "track_", "]", "return", "projection" ]
Project annotation onto timeline segments reference |__A__| |__B__| |____C____| timeline |---|---|---| |---| projection |_A_|_A_|_C_| |_B_| |_C_| Parameters ---------- annotation : Annotation timeline : Timeline Returns ------- projection : Annotation
[ "Project", "annotation", "onto", "timeline", "segments" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/utils.py#L115-L141
7,616
pyannote/pyannote-metrics
pyannote/metrics/utils.py
UEMSupportMixin.uemify
def uemify(self, reference, hypothesis, uem=None, collar=0., skip_overlap=False, returns_uem=False, returns_timeline=False): """Crop 'reference' and 'hypothesis' to 'uem' support Parameters ---------- reference, hypothesis : Annotation Reference and hypothesis annotations. uem : Timeline, optional Evaluation map. collar : float, optional When provided, set the duration of collars centered around reference segment boundaries that are extruded from both reference and hypothesis. Defaults to 0. (i.e. no collar). skip_overlap : bool, optional Set to True to not evaluate overlap regions. Defaults to False (i.e. keep overlap regions). returns_uem : bool, optional Set to True to return extruded uem as well. Defaults to False (i.e. only return reference and hypothesis) returns_timeline : bool, optional Set to True to oversegment reference and hypothesis so that they share the same internal timeline. Returns ------- reference, hypothesis : Annotation Extruded reference and hypothesis annotations uem : Timeline Extruded uem (returned only when 'returns_uem' is True) timeline : Timeline: Common timeline (returned only when 'returns_timeline' is True) """ # when uem is not provided, use the union of reference and hypothesis # extents -- and warn the user about that. if uem is None: r_extent = reference.get_timeline().extent() h_extent = hypothesis.get_timeline().extent() extent = r_extent | h_extent uem = Timeline(segments=[extent] if extent else [], uri=reference.uri) warnings.warn( "'uem' was approximated by the union of 'reference' " "and 'hypothesis' extents.") # extrude collars (and overlap regions) from uem uem = self.extrude(uem, reference, collar=collar, skip_overlap=skip_overlap) # extrude regions outside of uem reference = reference.crop(uem, mode='intersection') hypothesis = hypothesis.crop(uem, mode='intersection') # project reference and hypothesis on common timeline if returns_timeline: timeline = self.common_timeline(reference, hypothesis) reference = self.project(reference, timeline) hypothesis = self.project(hypothesis, timeline) result = (reference, hypothesis) if returns_uem: result += (uem, ) if returns_timeline: result += (timeline, ) return result
python
def uemify(self, reference, hypothesis, uem=None, collar=0., skip_overlap=False, returns_uem=False, returns_timeline=False): """Crop 'reference' and 'hypothesis' to 'uem' support Parameters ---------- reference, hypothesis : Annotation Reference and hypothesis annotations. uem : Timeline, optional Evaluation map. collar : float, optional When provided, set the duration of collars centered around reference segment boundaries that are extruded from both reference and hypothesis. Defaults to 0. (i.e. no collar). skip_overlap : bool, optional Set to True to not evaluate overlap regions. Defaults to False (i.e. keep overlap regions). returns_uem : bool, optional Set to True to return extruded uem as well. Defaults to False (i.e. only return reference and hypothesis) returns_timeline : bool, optional Set to True to oversegment reference and hypothesis so that they share the same internal timeline. Returns ------- reference, hypothesis : Annotation Extruded reference and hypothesis annotations uem : Timeline Extruded uem (returned only when 'returns_uem' is True) timeline : Timeline: Common timeline (returned only when 'returns_timeline' is True) """ # when uem is not provided, use the union of reference and hypothesis # extents -- and warn the user about that. if uem is None: r_extent = reference.get_timeline().extent() h_extent = hypothesis.get_timeline().extent() extent = r_extent | h_extent uem = Timeline(segments=[extent] if extent else [], uri=reference.uri) warnings.warn( "'uem' was approximated by the union of 'reference' " "and 'hypothesis' extents.") # extrude collars (and overlap regions) from uem uem = self.extrude(uem, reference, collar=collar, skip_overlap=skip_overlap) # extrude regions outside of uem reference = reference.crop(uem, mode='intersection') hypothesis = hypothesis.crop(uem, mode='intersection') # project reference and hypothesis on common timeline if returns_timeline: timeline = self.common_timeline(reference, hypothesis) reference = self.project(reference, timeline) hypothesis = self.project(hypothesis, timeline) result = (reference, hypothesis) if returns_uem: result += (uem, ) if returns_timeline: result += (timeline, ) return result
[ "def", "uemify", "(", "self", ",", "reference", ",", "hypothesis", ",", "uem", "=", "None", ",", "collar", "=", "0.", ",", "skip_overlap", "=", "False", ",", "returns_uem", "=", "False", ",", "returns_timeline", "=", "False", ")", ":", "# when uem is not provided, use the union of reference and hypothesis", "# extents -- and warn the user about that.", "if", "uem", "is", "None", ":", "r_extent", "=", "reference", ".", "get_timeline", "(", ")", ".", "extent", "(", ")", "h_extent", "=", "hypothesis", ".", "get_timeline", "(", ")", ".", "extent", "(", ")", "extent", "=", "r_extent", "|", "h_extent", "uem", "=", "Timeline", "(", "segments", "=", "[", "extent", "]", "if", "extent", "else", "[", "]", ",", "uri", "=", "reference", ".", "uri", ")", "warnings", ".", "warn", "(", "\"'uem' was approximated by the union of 'reference' \"", "\"and 'hypothesis' extents.\"", ")", "# extrude collars (and overlap regions) from uem", "uem", "=", "self", ".", "extrude", "(", "uem", ",", "reference", ",", "collar", "=", "collar", ",", "skip_overlap", "=", "skip_overlap", ")", "# extrude regions outside of uem", "reference", "=", "reference", ".", "crop", "(", "uem", ",", "mode", "=", "'intersection'", ")", "hypothesis", "=", "hypothesis", ".", "crop", "(", "uem", ",", "mode", "=", "'intersection'", ")", "# project reference and hypothesis on common timeline", "if", "returns_timeline", ":", "timeline", "=", "self", ".", "common_timeline", "(", "reference", ",", "hypothesis", ")", "reference", "=", "self", ".", "project", "(", "reference", ",", "timeline", ")", "hypothesis", "=", "self", ".", "project", "(", "hypothesis", ",", "timeline", ")", "result", "=", "(", "reference", ",", "hypothesis", ")", "if", "returns_uem", ":", "result", "+=", "(", "uem", ",", ")", "if", "returns_timeline", ":", "result", "+=", "(", "timeline", ",", ")", "return", "result" ]
Crop 'reference' and 'hypothesis' to 'uem' support Parameters ---------- reference, hypothesis : Annotation Reference and hypothesis annotations. uem : Timeline, optional Evaluation map. collar : float, optional When provided, set the duration of collars centered around reference segment boundaries that are extruded from both reference and hypothesis. Defaults to 0. (i.e. no collar). skip_overlap : bool, optional Set to True to not evaluate overlap regions. Defaults to False (i.e. keep overlap regions). returns_uem : bool, optional Set to True to return extruded uem as well. Defaults to False (i.e. only return reference and hypothesis) returns_timeline : bool, optional Set to True to oversegment reference and hypothesis so that they share the same internal timeline. Returns ------- reference, hypothesis : Annotation Extruded reference and hypothesis annotations uem : Timeline Extruded uem (returned only when 'returns_uem' is True) timeline : Timeline: Common timeline (returned only when 'returns_timeline' is True)
[ "Crop", "reference", "and", "hypothesis", "to", "uem", "support" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/utils.py#L143-L210
7,617
pyannote/pyannote-metrics
scripts/pyannote-metrics.py
get_hypothesis
def get_hypothesis(hypotheses, current_file): """Get hypothesis for given file Parameters ---------- hypotheses : `dict` Speaker diarization hypothesis provided by `load_rttm`. current_file : `dict` File description as given by pyannote.database protocols. Returns ------- hypothesis : `pyannote.core.Annotation` Hypothesis corresponding to `current_file`. """ uri = current_file['uri'] if uri in hypotheses: return hypotheses[uri] # if the exact 'uri' is not available in hypothesis, # look for matching substring tmp_uri = [u for u in hypotheses if u in uri] # no matching speech turns. return empty annotation if len(tmp_uri) == 0: msg = f'Could not find hypothesis for file "{uri}"; assuming empty file.' warnings.warn(msg) return Annotation(uri=uri, modality='speaker') # exactly one matching file. return it if len(tmp_uri) == 1: hypothesis = hypotheses[tmp_uri[0]] hypothesis.uri = uri return hypothesis # more that one matching file. error. msg = f'Found too many hypotheses matching file "{uri}" ({uris}).' raise ValueError(msg.format(uri=uri, uris=tmp_uri))
python
def get_hypothesis(hypotheses, current_file): """Get hypothesis for given file Parameters ---------- hypotheses : `dict` Speaker diarization hypothesis provided by `load_rttm`. current_file : `dict` File description as given by pyannote.database protocols. Returns ------- hypothesis : `pyannote.core.Annotation` Hypothesis corresponding to `current_file`. """ uri = current_file['uri'] if uri in hypotheses: return hypotheses[uri] # if the exact 'uri' is not available in hypothesis, # look for matching substring tmp_uri = [u for u in hypotheses if u in uri] # no matching speech turns. return empty annotation if len(tmp_uri) == 0: msg = f'Could not find hypothesis for file "{uri}"; assuming empty file.' warnings.warn(msg) return Annotation(uri=uri, modality='speaker') # exactly one matching file. return it if len(tmp_uri) == 1: hypothesis = hypotheses[tmp_uri[0]] hypothesis.uri = uri return hypothesis # more that one matching file. error. msg = f'Found too many hypotheses matching file "{uri}" ({uris}).' raise ValueError(msg.format(uri=uri, uris=tmp_uri))
[ "def", "get_hypothesis", "(", "hypotheses", ",", "current_file", ")", ":", "uri", "=", "current_file", "[", "'uri'", "]", "if", "uri", "in", "hypotheses", ":", "return", "hypotheses", "[", "uri", "]", "# if the exact 'uri' is not available in hypothesis,", "# look for matching substring", "tmp_uri", "=", "[", "u", "for", "u", "in", "hypotheses", "if", "u", "in", "uri", "]", "# no matching speech turns. return empty annotation", "if", "len", "(", "tmp_uri", ")", "==", "0", ":", "msg", "=", "f'Could not find hypothesis for file \"{uri}\"; assuming empty file.'", "warnings", ".", "warn", "(", "msg", ")", "return", "Annotation", "(", "uri", "=", "uri", ",", "modality", "=", "'speaker'", ")", "# exactly one matching file. return it", "if", "len", "(", "tmp_uri", ")", "==", "1", ":", "hypothesis", "=", "hypotheses", "[", "tmp_uri", "[", "0", "]", "]", "hypothesis", ".", "uri", "=", "uri", "return", "hypothesis", "# more that one matching file. error.", "msg", "=", "f'Found too many hypotheses matching file \"{uri}\" ({uris}).'", "raise", "ValueError", "(", "msg", ".", "format", "(", "uri", "=", "uri", ",", "uris", "=", "tmp_uri", ")", ")" ]
Get hypothesis for given file Parameters ---------- hypotheses : `dict` Speaker diarization hypothesis provided by `load_rttm`. current_file : `dict` File description as given by pyannote.database protocols. Returns ------- hypothesis : `pyannote.core.Annotation` Hypothesis corresponding to `current_file`.
[ "Get", "hypothesis", "for", "given", "file" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/scripts/pyannote-metrics.py#L142-L181
7,618
pyannote/pyannote-metrics
scripts/pyannote-metrics.py
reindex
def reindex(report): """Reindex report so that 'TOTAL' is the last row""" index = list(report.index) i = index.index('TOTAL') return report.reindex(index[:i] + index[i+1:] + ['TOTAL'])
python
def reindex(report): """Reindex report so that 'TOTAL' is the last row""" index = list(report.index) i = index.index('TOTAL') return report.reindex(index[:i] + index[i+1:] + ['TOTAL'])
[ "def", "reindex", "(", "report", ")", ":", "index", "=", "list", "(", "report", ".", "index", ")", "i", "=", "index", ".", "index", "(", "'TOTAL'", ")", "return", "report", ".", "reindex", "(", "index", "[", ":", "i", "]", "+", "index", "[", "i", "+", "1", ":", "]", "+", "[", "'TOTAL'", "]", ")" ]
Reindex report so that 'TOTAL' is the last row
[ "Reindex", "report", "so", "that", "TOTAL", "is", "the", "last", "row" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/scripts/pyannote-metrics.py#L219-L223
7,619
pyannote/pyannote-metrics
pyannote/metrics/binary_classification.py
precision_recall_curve
def precision_recall_curve(y_true, scores, distances=False): """Precision-recall curve Parameters ---------- y_true : (n_samples, ) array-like Boolean reference. scores : (n_samples, ) array-like Predicted score. distances : boolean, optional When True, indicate that `scores` are actually `distances` Returns ------- precision : numpy array Precision recall : numpy array Recall thresholds : numpy array Corresponding thresholds auc : float Area under curve """ if distances: scores = -scores precision, recall, thresholds = sklearn.metrics.precision_recall_curve( y_true, scores, pos_label=True) if distances: thresholds = -thresholds auc = sklearn.metrics.auc(precision, recall, reorder=True) return precision, recall, thresholds, auc
python
def precision_recall_curve(y_true, scores, distances=False): """Precision-recall curve Parameters ---------- y_true : (n_samples, ) array-like Boolean reference. scores : (n_samples, ) array-like Predicted score. distances : boolean, optional When True, indicate that `scores` are actually `distances` Returns ------- precision : numpy array Precision recall : numpy array Recall thresholds : numpy array Corresponding thresholds auc : float Area under curve """ if distances: scores = -scores precision, recall, thresholds = sklearn.metrics.precision_recall_curve( y_true, scores, pos_label=True) if distances: thresholds = -thresholds auc = sklearn.metrics.auc(precision, recall, reorder=True) return precision, recall, thresholds, auc
[ "def", "precision_recall_curve", "(", "y_true", ",", "scores", ",", "distances", "=", "False", ")", ":", "if", "distances", ":", "scores", "=", "-", "scores", "precision", ",", "recall", ",", "thresholds", "=", "sklearn", ".", "metrics", ".", "precision_recall_curve", "(", "y_true", ",", "scores", ",", "pos_label", "=", "True", ")", "if", "distances", ":", "thresholds", "=", "-", "thresholds", "auc", "=", "sklearn", ".", "metrics", ".", "auc", "(", "precision", ",", "recall", ",", "reorder", "=", "True", ")", "return", "precision", ",", "recall", ",", "thresholds", ",", "auc" ]
Precision-recall curve Parameters ---------- y_true : (n_samples, ) array-like Boolean reference. scores : (n_samples, ) array-like Predicted score. distances : boolean, optional When True, indicate that `scores` are actually `distances` Returns ------- precision : numpy array Precision recall : numpy array Recall thresholds : numpy array Corresponding thresholds auc : float Area under curve
[ "Precision", "-", "recall", "curve" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/binary_classification.py#L81-L117
7,620
pyannote/pyannote-metrics
pyannote/metrics/errors/identification.py
IdentificationErrorAnalysis.difference
def difference(self, reference, hypothesis, uem=None, uemified=False): """Get error analysis as `Annotation` Labels are (status, reference_label, hypothesis_label) tuples. `status` is either 'correct', 'confusion', 'missed detection' or 'false alarm'. `reference_label` is None in case of 'false alarm'. `hypothesis_label` is None in case of 'missed detection'. Parameters ---------- uemified : bool, optional Returns "uemified" version of reference and hypothesis. Defaults to False. Returns ------- errors : `Annotation` """ R, H, common_timeline = self.uemify( reference, hypothesis, uem=uem, collar=self.collar, skip_overlap=self.skip_overlap, returns_timeline=True) errors = Annotation(uri=reference.uri, modality=reference.modality) # loop on all segments for segment in common_timeline: # list of labels in reference segment rlabels = R.get_labels(segment, unique=False) # list of labels in hypothesis segment hlabels = H.get_labels(segment, unique=False) _, details = self.matcher(rlabels, hlabels) for r, h in details[MATCH_CORRECT]: track = errors.new_track(segment, prefix=MATCH_CORRECT) errors[segment, track] = (MATCH_CORRECT, r, h) for r, h in details[MATCH_CONFUSION]: track = errors.new_track(segment, prefix=MATCH_CONFUSION) errors[segment, track] = (MATCH_CONFUSION, r, h) for r in details[MATCH_MISSED_DETECTION]: track = errors.new_track(segment, prefix=MATCH_MISSED_DETECTION) errors[segment, track] = (MATCH_MISSED_DETECTION, r, None) for h in details[MATCH_FALSE_ALARM]: track = errors.new_track(segment, prefix=MATCH_FALSE_ALARM) errors[segment, track] = (MATCH_FALSE_ALARM, None, h) if uemified: return reference, hypothesis, errors else: return errors
python
def difference(self, reference, hypothesis, uem=None, uemified=False): """Get error analysis as `Annotation` Labels are (status, reference_label, hypothesis_label) tuples. `status` is either 'correct', 'confusion', 'missed detection' or 'false alarm'. `reference_label` is None in case of 'false alarm'. `hypothesis_label` is None in case of 'missed detection'. Parameters ---------- uemified : bool, optional Returns "uemified" version of reference and hypothesis. Defaults to False. Returns ------- errors : `Annotation` """ R, H, common_timeline = self.uemify( reference, hypothesis, uem=uem, collar=self.collar, skip_overlap=self.skip_overlap, returns_timeline=True) errors = Annotation(uri=reference.uri, modality=reference.modality) # loop on all segments for segment in common_timeline: # list of labels in reference segment rlabels = R.get_labels(segment, unique=False) # list of labels in hypothesis segment hlabels = H.get_labels(segment, unique=False) _, details = self.matcher(rlabels, hlabels) for r, h in details[MATCH_CORRECT]: track = errors.new_track(segment, prefix=MATCH_CORRECT) errors[segment, track] = (MATCH_CORRECT, r, h) for r, h in details[MATCH_CONFUSION]: track = errors.new_track(segment, prefix=MATCH_CONFUSION) errors[segment, track] = (MATCH_CONFUSION, r, h) for r in details[MATCH_MISSED_DETECTION]: track = errors.new_track(segment, prefix=MATCH_MISSED_DETECTION) errors[segment, track] = (MATCH_MISSED_DETECTION, r, None) for h in details[MATCH_FALSE_ALARM]: track = errors.new_track(segment, prefix=MATCH_FALSE_ALARM) errors[segment, track] = (MATCH_FALSE_ALARM, None, h) if uemified: return reference, hypothesis, errors else: return errors
[ "def", "difference", "(", "self", ",", "reference", ",", "hypothesis", ",", "uem", "=", "None", ",", "uemified", "=", "False", ")", ":", "R", ",", "H", ",", "common_timeline", "=", "self", ".", "uemify", "(", "reference", ",", "hypothesis", ",", "uem", "=", "uem", ",", "collar", "=", "self", ".", "collar", ",", "skip_overlap", "=", "self", ".", "skip_overlap", ",", "returns_timeline", "=", "True", ")", "errors", "=", "Annotation", "(", "uri", "=", "reference", ".", "uri", ",", "modality", "=", "reference", ".", "modality", ")", "# loop on all segments", "for", "segment", "in", "common_timeline", ":", "# list of labels in reference segment", "rlabels", "=", "R", ".", "get_labels", "(", "segment", ",", "unique", "=", "False", ")", "# list of labels in hypothesis segment", "hlabels", "=", "H", ".", "get_labels", "(", "segment", ",", "unique", "=", "False", ")", "_", ",", "details", "=", "self", ".", "matcher", "(", "rlabels", ",", "hlabels", ")", "for", "r", ",", "h", "in", "details", "[", "MATCH_CORRECT", "]", ":", "track", "=", "errors", ".", "new_track", "(", "segment", ",", "prefix", "=", "MATCH_CORRECT", ")", "errors", "[", "segment", ",", "track", "]", "=", "(", "MATCH_CORRECT", ",", "r", ",", "h", ")", "for", "r", ",", "h", "in", "details", "[", "MATCH_CONFUSION", "]", ":", "track", "=", "errors", ".", "new_track", "(", "segment", ",", "prefix", "=", "MATCH_CONFUSION", ")", "errors", "[", "segment", ",", "track", "]", "=", "(", "MATCH_CONFUSION", ",", "r", ",", "h", ")", "for", "r", "in", "details", "[", "MATCH_MISSED_DETECTION", "]", ":", "track", "=", "errors", ".", "new_track", "(", "segment", ",", "prefix", "=", "MATCH_MISSED_DETECTION", ")", "errors", "[", "segment", ",", "track", "]", "=", "(", "MATCH_MISSED_DETECTION", ",", "r", ",", "None", ")", "for", "h", "in", "details", "[", "MATCH_FALSE_ALARM", "]", ":", "track", "=", "errors", ".", "new_track", "(", "segment", ",", "prefix", "=", "MATCH_FALSE_ALARM", ")", "errors", "[", "segment", ",", "track", "]", "=", "(", "MATCH_FALSE_ALARM", ",", "None", ",", "h", ")", "if", "uemified", ":", "return", "reference", ",", "hypothesis", ",", "errors", "else", ":", "return", "errors" ]
Get error analysis as `Annotation` Labels are (status, reference_label, hypothesis_label) tuples. `status` is either 'correct', 'confusion', 'missed detection' or 'false alarm'. `reference_label` is None in case of 'false alarm'. `hypothesis_label` is None in case of 'missed detection'. Parameters ---------- uemified : bool, optional Returns "uemified" version of reference and hypothesis. Defaults to False. Returns ------- errors : `Annotation`
[ "Get", "error", "analysis", "as", "Annotation" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/errors/identification.py#L75-L134
7,621
pyannote/pyannote-metrics
pyannote/metrics/base.py
BaseMetric.reset
def reset(self): """Reset accumulated components and metric values""" if self.parallel: from pyannote.metrics import manager_ self.accumulated_ = manager_.dict() self.results_ = manager_.list() self.uris_ = manager_.dict() else: self.accumulated_ = dict() self.results_ = list() self.uris_ = dict() for value in self.components_: self.accumulated_[value] = 0.
python
def reset(self): """Reset accumulated components and metric values""" if self.parallel: from pyannote.metrics import manager_ self.accumulated_ = manager_.dict() self.results_ = manager_.list() self.uris_ = manager_.dict() else: self.accumulated_ = dict() self.results_ = list() self.uris_ = dict() for value in self.components_: self.accumulated_[value] = 0.
[ "def", "reset", "(", "self", ")", ":", "if", "self", ".", "parallel", ":", "from", "pyannote", ".", "metrics", "import", "manager_", "self", ".", "accumulated_", "=", "manager_", ".", "dict", "(", ")", "self", ".", "results_", "=", "manager_", ".", "list", "(", ")", "self", ".", "uris_", "=", "manager_", ".", "dict", "(", ")", "else", ":", "self", ".", "accumulated_", "=", "dict", "(", ")", "self", ".", "results_", "=", "list", "(", ")", "self", ".", "uris_", "=", "dict", "(", ")", "for", "value", "in", "self", ".", "components_", ":", "self", ".", "accumulated_", "[", "value", "]", "=", "0." ]
Reset accumulated components and metric values
[ "Reset", "accumulated", "components", "and", "metric", "values" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/base.py#L76-L88
7,622
pyannote/pyannote-metrics
pyannote/metrics/base.py
BaseMetric.confidence_interval
def confidence_interval(self, alpha=0.9): """Compute confidence interval on accumulated metric values Parameters ---------- alpha : float, optional Probability that the returned confidence interval contains the true metric value. Returns ------- (center, (lower, upper)) with center the mean of the conditional pdf of the metric value and (lower, upper) is a confidence interval centered on the median, containing the estimate to a probability alpha. See Also: --------- scipy.stats.bayes_mvs """ m, _, _ = scipy.stats.bayes_mvs( [r[self.metric_name_] for _, r in self.results_], alpha=alpha) return m
python
def confidence_interval(self, alpha=0.9): """Compute confidence interval on accumulated metric values Parameters ---------- alpha : float, optional Probability that the returned confidence interval contains the true metric value. Returns ------- (center, (lower, upper)) with center the mean of the conditional pdf of the metric value and (lower, upper) is a confidence interval centered on the median, containing the estimate to a probability alpha. See Also: --------- scipy.stats.bayes_mvs """ m, _, _ = scipy.stats.bayes_mvs( [r[self.metric_name_] for _, r in self.results_], alpha=alpha) return m
[ "def", "confidence_interval", "(", "self", ",", "alpha", "=", "0.9", ")", ":", "m", ",", "_", ",", "_", "=", "scipy", ".", "stats", ".", "bayes_mvs", "(", "[", "r", "[", "self", ".", "metric_name_", "]", "for", "_", ",", "r", "in", "self", ".", "results_", "]", ",", "alpha", "=", "alpha", ")", "return", "m" ]
Compute confidence interval on accumulated metric values Parameters ---------- alpha : float, optional Probability that the returned confidence interval contains the true metric value. Returns ------- (center, (lower, upper)) with center the mean of the conditional pdf of the metric value and (lower, upper) is a confidence interval centered on the median, containing the estimate to a probability alpha. See Also: --------- scipy.stats.bayes_mvs
[ "Compute", "confidence", "interval", "on", "accumulated", "metric", "values" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/base.py#L296-L319
7,623
pyannote/pyannote-metrics
pyannote/metrics/base.py
Precision.compute_metric
def compute_metric(self, components): """Compute precision from `components`""" numerator = components[PRECISION_RELEVANT_RETRIEVED] denominator = components[PRECISION_RETRIEVED] if denominator == 0.: if numerator == 0: return 1. else: raise ValueError('') else: return numerator/denominator
python
def compute_metric(self, components): """Compute precision from `components`""" numerator = components[PRECISION_RELEVANT_RETRIEVED] denominator = components[PRECISION_RETRIEVED] if denominator == 0.: if numerator == 0: return 1. else: raise ValueError('') else: return numerator/denominator
[ "def", "compute_metric", "(", "self", ",", "components", ")", ":", "numerator", "=", "components", "[", "PRECISION_RELEVANT_RETRIEVED", "]", "denominator", "=", "components", "[", "PRECISION_RETRIEVED", "]", "if", "denominator", "==", "0.", ":", "if", "numerator", "==", "0", ":", "return", "1.", "else", ":", "raise", "ValueError", "(", "''", ")", "else", ":", "return", "numerator", "/", "denominator" ]
Compute precision from `components`
[ "Compute", "precision", "from", "components" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/base.py#L347-L357
7,624
pyannote/pyannote-metrics
pyannote/metrics/base.py
Recall.compute_metric
def compute_metric(self, components): """Compute recall from `components`""" numerator = components[RECALL_RELEVANT_RETRIEVED] denominator = components[RECALL_RELEVANT] if denominator == 0.: if numerator == 0: return 1. else: raise ValueError('') else: return numerator/denominator
python
def compute_metric(self, components): """Compute recall from `components`""" numerator = components[RECALL_RELEVANT_RETRIEVED] denominator = components[RECALL_RELEVANT] if denominator == 0.: if numerator == 0: return 1. else: raise ValueError('') else: return numerator/denominator
[ "def", "compute_metric", "(", "self", ",", "components", ")", ":", "numerator", "=", "components", "[", "RECALL_RELEVANT_RETRIEVED", "]", "denominator", "=", "components", "[", "RECALL_RELEVANT", "]", "if", "denominator", "==", "0.", ":", "if", "numerator", "==", "0", ":", "return", "1.", "else", ":", "raise", "ValueError", "(", "''", ")", "else", ":", "return", "numerator", "/", "denominator" ]
Compute recall from `components`
[ "Compute", "recall", "from", "components" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/base.py#L384-L394
7,625
pyannote/pyannote-metrics
pyannote/metrics/diarization.py
DiarizationErrorRate.optimal_mapping
def optimal_mapping(self, reference, hypothesis, uem=None): """Optimal label mapping Parameters ---------- reference : Annotation hypothesis : Annotation Reference and hypothesis diarization uem : Timeline Evaluation map Returns ------- mapping : dict Mapping between hypothesis (key) and reference (value) labels """ # NOTE that this 'uemification' will not be called when # 'optimal_mapping' is called from 'compute_components' as it # has already been done in 'compute_components' if uem: reference, hypothesis = self.uemify(reference, hypothesis, uem=uem) # call hungarian mapper mapping = self.mapper_(hypothesis, reference) return mapping
python
def optimal_mapping(self, reference, hypothesis, uem=None): """Optimal label mapping Parameters ---------- reference : Annotation hypothesis : Annotation Reference and hypothesis diarization uem : Timeline Evaluation map Returns ------- mapping : dict Mapping between hypothesis (key) and reference (value) labels """ # NOTE that this 'uemification' will not be called when # 'optimal_mapping' is called from 'compute_components' as it # has already been done in 'compute_components' if uem: reference, hypothesis = self.uemify(reference, hypothesis, uem=uem) # call hungarian mapper mapping = self.mapper_(hypothesis, reference) return mapping
[ "def", "optimal_mapping", "(", "self", ",", "reference", ",", "hypothesis", ",", "uem", "=", "None", ")", ":", "# NOTE that this 'uemification' will not be called when", "# 'optimal_mapping' is called from 'compute_components' as it", "# has already been done in 'compute_components'", "if", "uem", ":", "reference", ",", "hypothesis", "=", "self", ".", "uemify", "(", "reference", ",", "hypothesis", ",", "uem", "=", "uem", ")", "# call hungarian mapper", "mapping", "=", "self", ".", "mapper_", "(", "hypothesis", ",", "reference", ")", "return", "mapping" ]
Optimal label mapping Parameters ---------- reference : Annotation hypothesis : Annotation Reference and hypothesis diarization uem : Timeline Evaluation map Returns ------- mapping : dict Mapping between hypothesis (key) and reference (value) labels
[ "Optimal", "label", "mapping" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/diarization.py#L106-L131
7,626
pyannote/pyannote-metrics
pyannote/metrics/diarization.py
GreedyDiarizationErrorRate.greedy_mapping
def greedy_mapping(self, reference, hypothesis, uem=None): """Greedy label mapping Parameters ---------- reference : Annotation hypothesis : Annotation Reference and hypothesis diarization uem : Timeline Evaluation map Returns ------- mapping : dict Mapping between hypothesis (key) and reference (value) labels """ if uem: reference, hypothesis = self.uemify(reference, hypothesis, uem=uem) return self.mapper_(hypothesis, reference)
python
def greedy_mapping(self, reference, hypothesis, uem=None): """Greedy label mapping Parameters ---------- reference : Annotation hypothesis : Annotation Reference and hypothesis diarization uem : Timeline Evaluation map Returns ------- mapping : dict Mapping between hypothesis (key) and reference (value) labels """ if uem: reference, hypothesis = self.uemify(reference, hypothesis, uem=uem) return self.mapper_(hypothesis, reference)
[ "def", "greedy_mapping", "(", "self", ",", "reference", ",", "hypothesis", ",", "uem", "=", "None", ")", ":", "if", "uem", ":", "reference", ",", "hypothesis", "=", "self", ".", "uemify", "(", "reference", ",", "hypothesis", ",", "uem", "=", "uem", ")", "return", "self", ".", "mapper_", "(", "hypothesis", ",", "reference", ")" ]
Greedy label mapping Parameters ---------- reference : Annotation hypothesis : Annotation Reference and hypothesis diarization uem : Timeline Evaluation map Returns ------- mapping : dict Mapping between hypothesis (key) and reference (value) labels
[ "Greedy", "label", "mapping" ]
b433fec3bd37ca36fe026a428cd72483d646871a
https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/diarization.py#L223-L241
7,627
brian-rose/climlab
climlab/radiation/radiation.py
default_absorbers
def default_absorbers(Tatm, ozone_file = 'apeozone_cam3_5_54.nc', verbose = True,): '''Initialize a dictionary of well-mixed radiatively active gases All values are volumetric mixing ratios. Ozone is set to a climatology. All other gases are assumed well-mixed: - CO2 - CH4 - N2O - O2 - CFC11 - CFC12 - CFC22 - CCL4 Specific values are based on the AquaPlanet Experiment protocols, except for O2 which is set the realistic value 0.21 (affects the RRTMG scheme). ''' absorber_vmr = {} absorber_vmr['CO2'] = 348. / 1E6 absorber_vmr['CH4'] = 1650. / 1E9 absorber_vmr['N2O'] = 306. / 1E9 absorber_vmr['O2'] = 0.21 absorber_vmr['CFC11'] = 0. absorber_vmr['CFC12'] = 0. absorber_vmr['CFC22'] = 0. absorber_vmr['CCL4'] = 0. # Ozone: start with all zeros, interpolate to data if we can xTatm = Tatm.to_xarray() O3 = 0. * xTatm if ozone_file is not None: ozonefilepath = os.path.join(os.path.dirname(__file__), 'data', 'ozone', ozone_file) remotepath_http = 'http://thredds.atmos.albany.edu:8080/thredds/fileServer/CLIMLAB/ozone/' + ozone_file remotepath_opendap = 'http://thredds.atmos.albany.edu:8080/thredds/dodsC/CLIMLAB/ozone/' + ozone_file ozonedata, path = load_data_source(local_path=ozonefilepath, remote_source_list=[remotepath_http, remotepath_opendap], open_method=xr.open_dataset, remote_kwargs={'engine':'pydap'}, verbose=verbose,) ## zonal and time average ozone_zon = ozonedata.OZONE.mean(dim=('time','lon')).transpose('lat','lev') if ('lat' in xTatm.dims): O3source = ozone_zon else: weight = np.cos(np.deg2rad(ozonedata.lat)) ozone_global = (ozone_zon * weight).mean(dim='lat') / weight.mean(dim='lat') O3source = ozone_global try: O3 = O3source.interp_like(xTatm) # There will be NaNs for gridpoints outside the ozone file domain assert not np.any(np.isnan(O3)) except: warnings.warn('Some grid points are beyond the bounds of the ozone file. Ozone values will be extrapolated.') try: # passing fill_value=None to the underlying scipy interpolator # will result in extrapolation instead of NaNs O3 = O3source.interp_like(xTatm, kwargs={'fill_value':None}) assert not np.any(np.isnan(O3)) except: warnings.warn('Interpolation of ozone data failed. Setting O3 to zero instead.') O3 = 0. * xTatm absorber_vmr['O3'] = O3.values return absorber_vmr
python
def default_absorbers(Tatm, ozone_file = 'apeozone_cam3_5_54.nc', verbose = True,): '''Initialize a dictionary of well-mixed radiatively active gases All values are volumetric mixing ratios. Ozone is set to a climatology. All other gases are assumed well-mixed: - CO2 - CH4 - N2O - O2 - CFC11 - CFC12 - CFC22 - CCL4 Specific values are based on the AquaPlanet Experiment protocols, except for O2 which is set the realistic value 0.21 (affects the RRTMG scheme). ''' absorber_vmr = {} absorber_vmr['CO2'] = 348. / 1E6 absorber_vmr['CH4'] = 1650. / 1E9 absorber_vmr['N2O'] = 306. / 1E9 absorber_vmr['O2'] = 0.21 absorber_vmr['CFC11'] = 0. absorber_vmr['CFC12'] = 0. absorber_vmr['CFC22'] = 0. absorber_vmr['CCL4'] = 0. # Ozone: start with all zeros, interpolate to data if we can xTatm = Tatm.to_xarray() O3 = 0. * xTatm if ozone_file is not None: ozonefilepath = os.path.join(os.path.dirname(__file__), 'data', 'ozone', ozone_file) remotepath_http = 'http://thredds.atmos.albany.edu:8080/thredds/fileServer/CLIMLAB/ozone/' + ozone_file remotepath_opendap = 'http://thredds.atmos.albany.edu:8080/thredds/dodsC/CLIMLAB/ozone/' + ozone_file ozonedata, path = load_data_source(local_path=ozonefilepath, remote_source_list=[remotepath_http, remotepath_opendap], open_method=xr.open_dataset, remote_kwargs={'engine':'pydap'}, verbose=verbose,) ## zonal and time average ozone_zon = ozonedata.OZONE.mean(dim=('time','lon')).transpose('lat','lev') if ('lat' in xTatm.dims): O3source = ozone_zon else: weight = np.cos(np.deg2rad(ozonedata.lat)) ozone_global = (ozone_zon * weight).mean(dim='lat') / weight.mean(dim='lat') O3source = ozone_global try: O3 = O3source.interp_like(xTatm) # There will be NaNs for gridpoints outside the ozone file domain assert not np.any(np.isnan(O3)) except: warnings.warn('Some grid points are beyond the bounds of the ozone file. Ozone values will be extrapolated.') try: # passing fill_value=None to the underlying scipy interpolator # will result in extrapolation instead of NaNs O3 = O3source.interp_like(xTatm, kwargs={'fill_value':None}) assert not np.any(np.isnan(O3)) except: warnings.warn('Interpolation of ozone data failed. Setting O3 to zero instead.') O3 = 0. * xTatm absorber_vmr['O3'] = O3.values return absorber_vmr
[ "def", "default_absorbers", "(", "Tatm", ",", "ozone_file", "=", "'apeozone_cam3_5_54.nc'", ",", "verbose", "=", "True", ",", ")", ":", "absorber_vmr", "=", "{", "}", "absorber_vmr", "[", "'CO2'", "]", "=", "348.", "/", "1E6", "absorber_vmr", "[", "'CH4'", "]", "=", "1650.", "/", "1E9", "absorber_vmr", "[", "'N2O'", "]", "=", "306.", "/", "1E9", "absorber_vmr", "[", "'O2'", "]", "=", "0.21", "absorber_vmr", "[", "'CFC11'", "]", "=", "0.", "absorber_vmr", "[", "'CFC12'", "]", "=", "0.", "absorber_vmr", "[", "'CFC22'", "]", "=", "0.", "absorber_vmr", "[", "'CCL4'", "]", "=", "0.", "# Ozone: start with all zeros, interpolate to data if we can", "xTatm", "=", "Tatm", ".", "to_xarray", "(", ")", "O3", "=", "0.", "*", "xTatm", "if", "ozone_file", "is", "not", "None", ":", "ozonefilepath", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'data'", ",", "'ozone'", ",", "ozone_file", ")", "remotepath_http", "=", "'http://thredds.atmos.albany.edu:8080/thredds/fileServer/CLIMLAB/ozone/'", "+", "ozone_file", "remotepath_opendap", "=", "'http://thredds.atmos.albany.edu:8080/thredds/dodsC/CLIMLAB/ozone/'", "+", "ozone_file", "ozonedata", ",", "path", "=", "load_data_source", "(", "local_path", "=", "ozonefilepath", ",", "remote_source_list", "=", "[", "remotepath_http", ",", "remotepath_opendap", "]", ",", "open_method", "=", "xr", ".", "open_dataset", ",", "remote_kwargs", "=", "{", "'engine'", ":", "'pydap'", "}", ",", "verbose", "=", "verbose", ",", ")", "## zonal and time average", "ozone_zon", "=", "ozonedata", ".", "OZONE", ".", "mean", "(", "dim", "=", "(", "'time'", ",", "'lon'", ")", ")", ".", "transpose", "(", "'lat'", ",", "'lev'", ")", "if", "(", "'lat'", "in", "xTatm", ".", "dims", ")", ":", "O3source", "=", "ozone_zon", "else", ":", "weight", "=", "np", ".", "cos", "(", "np", ".", "deg2rad", "(", "ozonedata", ".", "lat", ")", ")", "ozone_global", "=", "(", "ozone_zon", "*", "weight", ")", ".", "mean", "(", "dim", "=", "'lat'", ")", "/", "weight", ".", "mean", "(", "dim", "=", "'lat'", ")", "O3source", "=", "ozone_global", "try", ":", "O3", "=", "O3source", ".", "interp_like", "(", "xTatm", ")", "# There will be NaNs for gridpoints outside the ozone file domain", "assert", "not", "np", ".", "any", "(", "np", ".", "isnan", "(", "O3", ")", ")", "except", ":", "warnings", ".", "warn", "(", "'Some grid points are beyond the bounds of the ozone file. Ozone values will be extrapolated.'", ")", "try", ":", "# passing fill_value=None to the underlying scipy interpolator", "# will result in extrapolation instead of NaNs", "O3", "=", "O3source", ".", "interp_like", "(", "xTatm", ",", "kwargs", "=", "{", "'fill_value'", ":", "None", "}", ")", "assert", "not", "np", ".", "any", "(", "np", ".", "isnan", "(", "O3", ")", ")", "except", ":", "warnings", ".", "warn", "(", "'Interpolation of ozone data failed. Setting O3 to zero instead.'", ")", "O3", "=", "0.", "*", "xTatm", "absorber_vmr", "[", "'O3'", "]", "=", "O3", ".", "values", "return", "absorber_vmr" ]
Initialize a dictionary of well-mixed radiatively active gases All values are volumetric mixing ratios. Ozone is set to a climatology. All other gases are assumed well-mixed: - CO2 - CH4 - N2O - O2 - CFC11 - CFC12 - CFC22 - CCL4 Specific values are based on the AquaPlanet Experiment protocols, except for O2 which is set the realistic value 0.21 (affects the RRTMG scheme).
[ "Initialize", "a", "dictionary", "of", "well", "-", "mixed", "radiatively", "active", "gases", "All", "values", "are", "volumetric", "mixing", "ratios", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/radiation.py#L98-L166
7,628
brian-rose/climlab
climlab/radiation/radiation.py
init_interface
def init_interface(field): '''Return a Field object defined at the vertical interfaces of the input Field object.''' interface_shape = np.array(field.shape); interface_shape[-1] += 1 interfaces = np.tile(False,len(interface_shape)); interfaces[-1] = True interface_zero = Field(np.zeros(interface_shape), domain=field.domain, interfaces=interfaces) return interface_zero
python
def init_interface(field): '''Return a Field object defined at the vertical interfaces of the input Field object.''' interface_shape = np.array(field.shape); interface_shape[-1] += 1 interfaces = np.tile(False,len(interface_shape)); interfaces[-1] = True interface_zero = Field(np.zeros(interface_shape), domain=field.domain, interfaces=interfaces) return interface_zero
[ "def", "init_interface", "(", "field", ")", ":", "interface_shape", "=", "np", ".", "array", "(", "field", ".", "shape", ")", "interface_shape", "[", "-", "1", "]", "+=", "1", "interfaces", "=", "np", ".", "tile", "(", "False", ",", "len", "(", "interface_shape", ")", ")", "interfaces", "[", "-", "1", "]", "=", "True", "interface_zero", "=", "Field", "(", "np", ".", "zeros", "(", "interface_shape", ")", ",", "domain", "=", "field", ".", "domain", ",", "interfaces", "=", "interfaces", ")", "return", "interface_zero" ]
Return a Field object defined at the vertical interfaces of the input Field object.
[ "Return", "a", "Field", "object", "defined", "at", "the", "vertical", "interfaces", "of", "the", "input", "Field", "object", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/radiation.py#L168-L173
7,629
brian-rose/climlab
climlab/convection/akmaev_adjustment.py
convective_adjustment_direct
def convective_adjustment_direct(p, T, c, lapserate=6.5): """Convective Adjustment to a specified lapse rate. Input argument lapserate gives the lapse rate expressed in degrees K per km (positive means temperature increasing downward). Default lapse rate is 6.5 K / km. Returns the adjusted Column temperature. inputs: p is pressure in hPa T is temperature in K c is heat capacity in in J / m**2 / K Implements the conservative adjustment algorithm from Akmaev (1991) MWR """ # largely follows notation and algorithm in Akmaev (1991) MWR alpha = const.Rd / const.g * lapserate / 1.E3 # same dimensions as lapserate L = p.size ### now handles variable lapse rate pextended = np.insert(p,0,const.ps) # prepend const.ps = 1000 hPa as ref pressure to compute potential temperature Pi = np.cumprod((p / pextended[:-1])**alpha) # Akmaev's equation 14 recurrence formula beta = 1./Pi theta = T * beta q = Pi * c n_k = np.zeros(L, dtype=np.int8) theta_k = np.zeros_like(p) s_k = np.zeros_like(p) t_k = np.zeros_like(p) thetaadj = Akmaev_adjustment_multidim(theta, q, beta, n_k, theta_k, s_k, t_k) T = thetaadj * Pi return T
python
def convective_adjustment_direct(p, T, c, lapserate=6.5): """Convective Adjustment to a specified lapse rate. Input argument lapserate gives the lapse rate expressed in degrees K per km (positive means temperature increasing downward). Default lapse rate is 6.5 K / km. Returns the adjusted Column temperature. inputs: p is pressure in hPa T is temperature in K c is heat capacity in in J / m**2 / K Implements the conservative adjustment algorithm from Akmaev (1991) MWR """ # largely follows notation and algorithm in Akmaev (1991) MWR alpha = const.Rd / const.g * lapserate / 1.E3 # same dimensions as lapserate L = p.size ### now handles variable lapse rate pextended = np.insert(p,0,const.ps) # prepend const.ps = 1000 hPa as ref pressure to compute potential temperature Pi = np.cumprod((p / pextended[:-1])**alpha) # Akmaev's equation 14 recurrence formula beta = 1./Pi theta = T * beta q = Pi * c n_k = np.zeros(L, dtype=np.int8) theta_k = np.zeros_like(p) s_k = np.zeros_like(p) t_k = np.zeros_like(p) thetaadj = Akmaev_adjustment_multidim(theta, q, beta, n_k, theta_k, s_k, t_k) T = thetaadj * Pi return T
[ "def", "convective_adjustment_direct", "(", "p", ",", "T", ",", "c", ",", "lapserate", "=", "6.5", ")", ":", "# largely follows notation and algorithm in Akmaev (1991) MWR", "alpha", "=", "const", ".", "Rd", "/", "const", ".", "g", "*", "lapserate", "/", "1.E3", "# same dimensions as lapserate", "L", "=", "p", ".", "size", "### now handles variable lapse rate", "pextended", "=", "np", ".", "insert", "(", "p", ",", "0", ",", "const", ".", "ps", ")", "# prepend const.ps = 1000 hPa as ref pressure to compute potential temperature", "Pi", "=", "np", ".", "cumprod", "(", "(", "p", "/", "pextended", "[", ":", "-", "1", "]", ")", "**", "alpha", ")", "# Akmaev's equation 14 recurrence formula", "beta", "=", "1.", "/", "Pi", "theta", "=", "T", "*", "beta", "q", "=", "Pi", "*", "c", "n_k", "=", "np", ".", "zeros", "(", "L", ",", "dtype", "=", "np", ".", "int8", ")", "theta_k", "=", "np", ".", "zeros_like", "(", "p", ")", "s_k", "=", "np", ".", "zeros_like", "(", "p", ")", "t_k", "=", "np", ".", "zeros_like", "(", "p", ")", "thetaadj", "=", "Akmaev_adjustment_multidim", "(", "theta", ",", "q", ",", "beta", ",", "n_k", ",", "theta_k", ",", "s_k", ",", "t_k", ")", "T", "=", "thetaadj", "*", "Pi", "return", "T" ]
Convective Adjustment to a specified lapse rate. Input argument lapserate gives the lapse rate expressed in degrees K per km (positive means temperature increasing downward). Default lapse rate is 6.5 K / km. Returns the adjusted Column temperature. inputs: p is pressure in hPa T is temperature in K c is heat capacity in in J / m**2 / K Implements the conservative adjustment algorithm from Akmaev (1991) MWR
[ "Convective", "Adjustment", "to", "a", "specified", "lapse", "rate", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/convection/akmaev_adjustment.py#L7-L39
7,630
brian-rose/climlab
climlab/convection/akmaev_adjustment.py
Akmaev_adjustment
def Akmaev_adjustment(theta, q, beta, n_k, theta_k, s_k, t_k): '''Single column only.''' L = q.size # number of vertical levels # Akmaev step 1 k = 1 n_k[k-1] = 1 theta_k[k-1] = theta[k-1] l = 2 while True: # Akmaev step 2 n = 1 thistheta = theta[l-1] while True: # Akmaev step 3 if theta_k[k-1] <= thistheta: # Akmaev step 6 k += 1 break # to step 7 else: if n <= 1: s = q[l-1] t = s*thistheta # Akmaev step 4 if n_k[k-1] <= 1: # lower adjacent level is not an earlier-formed neutral layer s_k[k-1] = q[l-n-1] t_k[k-1] = s_k[k-1] * theta_k[k-1] # Akmaev step 5 # join current and underlying layers n += n_k[k-1] s += s_k[k-1] t += t_k[k-1] s_k[k-1] = s t_k[k-1] = t thistheta = t/s if k==1: # joint neutral layer is the first one break # to step 7 k -= 1 # back to step 3 # Akmaev step 7 if l == L: # the scan is over break # to step 8 l += 1 n_k[k-1] = n theta_k[k-1] = thistheta # back to step 2 # update the potential temperatures while True: while True: # Akmaev step 8 if n==1: # current model level was not included in any neutral layer break # to step 11 while True: # Akmaev step 9 theta[l-1] = thistheta if n==1: break # Akmaev step 10 l -= 1 n -= 1 # back to step 9 # Akmaev step 11 if k==1: break k -= 1 l -= 1 n = n_k[k-1] thistheta = theta_k[k-1] # back to step 8 return theta
python
def Akmaev_adjustment(theta, q, beta, n_k, theta_k, s_k, t_k): '''Single column only.''' L = q.size # number of vertical levels # Akmaev step 1 k = 1 n_k[k-1] = 1 theta_k[k-1] = theta[k-1] l = 2 while True: # Akmaev step 2 n = 1 thistheta = theta[l-1] while True: # Akmaev step 3 if theta_k[k-1] <= thistheta: # Akmaev step 6 k += 1 break # to step 7 else: if n <= 1: s = q[l-1] t = s*thistheta # Akmaev step 4 if n_k[k-1] <= 1: # lower adjacent level is not an earlier-formed neutral layer s_k[k-1] = q[l-n-1] t_k[k-1] = s_k[k-1] * theta_k[k-1] # Akmaev step 5 # join current and underlying layers n += n_k[k-1] s += s_k[k-1] t += t_k[k-1] s_k[k-1] = s t_k[k-1] = t thistheta = t/s if k==1: # joint neutral layer is the first one break # to step 7 k -= 1 # back to step 3 # Akmaev step 7 if l == L: # the scan is over break # to step 8 l += 1 n_k[k-1] = n theta_k[k-1] = thistheta # back to step 2 # update the potential temperatures while True: while True: # Akmaev step 8 if n==1: # current model level was not included in any neutral layer break # to step 11 while True: # Akmaev step 9 theta[l-1] = thistheta if n==1: break # Akmaev step 10 l -= 1 n -= 1 # back to step 9 # Akmaev step 11 if k==1: break k -= 1 l -= 1 n = n_k[k-1] thistheta = theta_k[k-1] # back to step 8 return theta
[ "def", "Akmaev_adjustment", "(", "theta", ",", "q", ",", "beta", ",", "n_k", ",", "theta_k", ",", "s_k", ",", "t_k", ")", ":", "L", "=", "q", ".", "size", "# number of vertical levels", "# Akmaev step 1", "k", "=", "1", "n_k", "[", "k", "-", "1", "]", "=", "1", "theta_k", "[", "k", "-", "1", "]", "=", "theta", "[", "k", "-", "1", "]", "l", "=", "2", "while", "True", ":", "# Akmaev step 2", "n", "=", "1", "thistheta", "=", "theta", "[", "l", "-", "1", "]", "while", "True", ":", "# Akmaev step 3", "if", "theta_k", "[", "k", "-", "1", "]", "<=", "thistheta", ":", "# Akmaev step 6", "k", "+=", "1", "break", "# to step 7", "else", ":", "if", "n", "<=", "1", ":", "s", "=", "q", "[", "l", "-", "1", "]", "t", "=", "s", "*", "thistheta", "# Akmaev step 4", "if", "n_k", "[", "k", "-", "1", "]", "<=", "1", ":", "# lower adjacent level is not an earlier-formed neutral layer", "s_k", "[", "k", "-", "1", "]", "=", "q", "[", "l", "-", "n", "-", "1", "]", "t_k", "[", "k", "-", "1", "]", "=", "s_k", "[", "k", "-", "1", "]", "*", "theta_k", "[", "k", "-", "1", "]", "# Akmaev step 5", "# join current and underlying layers", "n", "+=", "n_k", "[", "k", "-", "1", "]", "s", "+=", "s_k", "[", "k", "-", "1", "]", "t", "+=", "t_k", "[", "k", "-", "1", "]", "s_k", "[", "k", "-", "1", "]", "=", "s", "t_k", "[", "k", "-", "1", "]", "=", "t", "thistheta", "=", "t", "/", "s", "if", "k", "==", "1", ":", "# joint neutral layer is the first one", "break", "# to step 7", "k", "-=", "1", "# back to step 3", "# Akmaev step 7", "if", "l", "==", "L", ":", "# the scan is over", "break", "# to step 8", "l", "+=", "1", "n_k", "[", "k", "-", "1", "]", "=", "n", "theta_k", "[", "k", "-", "1", "]", "=", "thistheta", "# back to step 2", "# update the potential temperatures", "while", "True", ":", "while", "True", ":", "# Akmaev step 8", "if", "n", "==", "1", ":", "# current model level was not included in any neutral layer", "break", "# to step 11", "while", "True", ":", "# Akmaev step 9", "theta", "[", "l", "-", "1", "]", "=", "thistheta", "if", "n", "==", "1", ":", "break", "# Akmaev step 10", "l", "-=", "1", "n", "-=", "1", "# back to step 9", "# Akmaev step 11", "if", "k", "==", "1", ":", "break", "k", "-=", "1", "l", "-=", "1", "n", "=", "n_k", "[", "k", "-", "1", "]", "thistheta", "=", "theta_k", "[", "k", "-", "1", "]", "# back to step 8", "return", "theta" ]
Single column only.
[ "Single", "column", "only", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/convection/akmaev_adjustment.py#L58-L129
7,631
brian-rose/climlab
climlab/model/column.py
GreyRadiationModel.do_diagnostics
def do_diagnostics(self): '''Set all the diagnostics from long and shortwave radiation.''' self.OLR = self.subprocess['LW'].flux_to_space self.LW_down_sfc = self.subprocess['LW'].flux_to_sfc self.LW_up_sfc = self.subprocess['LW'].flux_from_sfc self.LW_absorbed_sfc = self.LW_down_sfc - self.LW_up_sfc self.LW_absorbed_atm = self.subprocess['LW'].absorbed self.LW_emission = self.subprocess['LW'].emission # contributions to OLR from surface and atm. levels #self.diagnostics['OLR_sfc'] = self.flux['sfc2space'] #self.diagnostics['OLR_atm'] = self.flux['atm2space'] self.ASR = (self.subprocess['SW'].flux_from_space - self.subprocess['SW'].flux_to_space) #self.SW_absorbed_sfc = (self.subprocess['surface'].SW_from_atm - # self.subprocess['surface'].SW_to_atm) self.SW_absorbed_atm = self.subprocess['SW'].absorbed self.SW_down_sfc = self.subprocess['SW'].flux_to_sfc self.SW_up_sfc = self.subprocess['SW'].flux_from_sfc self.SW_absorbed_sfc = self.SW_down_sfc - self.SW_up_sfc self.SW_up_TOA = self.subprocess['SW'].flux_to_space self.SW_down_TOA = self.subprocess['SW'].flux_from_space self.planetary_albedo = (self.subprocess['SW'].flux_to_space / self.subprocess['SW'].flux_from_space)
python
def do_diagnostics(self): '''Set all the diagnostics from long and shortwave radiation.''' self.OLR = self.subprocess['LW'].flux_to_space self.LW_down_sfc = self.subprocess['LW'].flux_to_sfc self.LW_up_sfc = self.subprocess['LW'].flux_from_sfc self.LW_absorbed_sfc = self.LW_down_sfc - self.LW_up_sfc self.LW_absorbed_atm = self.subprocess['LW'].absorbed self.LW_emission = self.subprocess['LW'].emission # contributions to OLR from surface and atm. levels #self.diagnostics['OLR_sfc'] = self.flux['sfc2space'] #self.diagnostics['OLR_atm'] = self.flux['atm2space'] self.ASR = (self.subprocess['SW'].flux_from_space - self.subprocess['SW'].flux_to_space) #self.SW_absorbed_sfc = (self.subprocess['surface'].SW_from_atm - # self.subprocess['surface'].SW_to_atm) self.SW_absorbed_atm = self.subprocess['SW'].absorbed self.SW_down_sfc = self.subprocess['SW'].flux_to_sfc self.SW_up_sfc = self.subprocess['SW'].flux_from_sfc self.SW_absorbed_sfc = self.SW_down_sfc - self.SW_up_sfc self.SW_up_TOA = self.subprocess['SW'].flux_to_space self.SW_down_TOA = self.subprocess['SW'].flux_from_space self.planetary_albedo = (self.subprocess['SW'].flux_to_space / self.subprocess['SW'].flux_from_space)
[ "def", "do_diagnostics", "(", "self", ")", ":", "self", ".", "OLR", "=", "self", ".", "subprocess", "[", "'LW'", "]", ".", "flux_to_space", "self", ".", "LW_down_sfc", "=", "self", ".", "subprocess", "[", "'LW'", "]", ".", "flux_to_sfc", "self", ".", "LW_up_sfc", "=", "self", ".", "subprocess", "[", "'LW'", "]", ".", "flux_from_sfc", "self", ".", "LW_absorbed_sfc", "=", "self", ".", "LW_down_sfc", "-", "self", ".", "LW_up_sfc", "self", ".", "LW_absorbed_atm", "=", "self", ".", "subprocess", "[", "'LW'", "]", ".", "absorbed", "self", ".", "LW_emission", "=", "self", ".", "subprocess", "[", "'LW'", "]", ".", "emission", "# contributions to OLR from surface and atm. levels", "#self.diagnostics['OLR_sfc'] = self.flux['sfc2space']", "#self.diagnostics['OLR_atm'] = self.flux['atm2space']", "self", ".", "ASR", "=", "(", "self", ".", "subprocess", "[", "'SW'", "]", ".", "flux_from_space", "-", "self", ".", "subprocess", "[", "'SW'", "]", ".", "flux_to_space", ")", "#self.SW_absorbed_sfc = (self.subprocess['surface'].SW_from_atm -", "# self.subprocess['surface'].SW_to_atm)", "self", ".", "SW_absorbed_atm", "=", "self", ".", "subprocess", "[", "'SW'", "]", ".", "absorbed", "self", ".", "SW_down_sfc", "=", "self", ".", "subprocess", "[", "'SW'", "]", ".", "flux_to_sfc", "self", ".", "SW_up_sfc", "=", "self", ".", "subprocess", "[", "'SW'", "]", ".", "flux_from_sfc", "self", ".", "SW_absorbed_sfc", "=", "self", ".", "SW_down_sfc", "-", "self", ".", "SW_up_sfc", "self", ".", "SW_up_TOA", "=", "self", ".", "subprocess", "[", "'SW'", "]", ".", "flux_to_space", "self", ".", "SW_down_TOA", "=", "self", ".", "subprocess", "[", "'SW'", "]", ".", "flux_from_space", "self", ".", "planetary_albedo", "=", "(", "self", ".", "subprocess", "[", "'SW'", "]", ".", "flux_to_space", "/", "self", ".", "subprocess", "[", "'SW'", "]", ".", "flux_from_space", ")" ]
Set all the diagnostics from long and shortwave radiation.
[ "Set", "all", "the", "diagnostics", "from", "long", "and", "shortwave", "radiation", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/model/column.py#L119-L141
7,632
brian-rose/climlab
climlab/utils/thermo.py
clausius_clapeyron
def clausius_clapeyron(T): """Compute saturation vapor pressure as function of temperature T. Input: T is temperature in Kelvin Output: saturation vapor pressure in mb or hPa Formula from Rogers and Yau "A Short Course in Cloud Physics" (Pergammon Press), p. 16 claimed to be accurate to within 0.1% between -30degC and 35 degC Based on the paper by Bolton (1980, Monthly Weather Review). """ Tcel = T - tempCtoK es = 6.112 * exp(17.67*Tcel/(Tcel+243.5)) return es
python
def clausius_clapeyron(T): """Compute saturation vapor pressure as function of temperature T. Input: T is temperature in Kelvin Output: saturation vapor pressure in mb or hPa Formula from Rogers and Yau "A Short Course in Cloud Physics" (Pergammon Press), p. 16 claimed to be accurate to within 0.1% between -30degC and 35 degC Based on the paper by Bolton (1980, Monthly Weather Review). """ Tcel = T - tempCtoK es = 6.112 * exp(17.67*Tcel/(Tcel+243.5)) return es
[ "def", "clausius_clapeyron", "(", "T", ")", ":", "Tcel", "=", "T", "-", "tempCtoK", "es", "=", "6.112", "*", "exp", "(", "17.67", "*", "Tcel", "/", "(", "Tcel", "+", "243.5", ")", ")", "return", "es" ]
Compute saturation vapor pressure as function of temperature T. Input: T is temperature in Kelvin Output: saturation vapor pressure in mb or hPa Formula from Rogers and Yau "A Short Course in Cloud Physics" (Pergammon Press), p. 16 claimed to be accurate to within 0.1% between -30degC and 35 degC Based on the paper by Bolton (1980, Monthly Weather Review).
[ "Compute", "saturation", "vapor", "pressure", "as", "function", "of", "temperature", "T", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/utils/thermo.py#L41-L54
7,633
brian-rose/climlab
climlab/utils/thermo.py
qsat
def qsat(T,p): """Compute saturation specific humidity as function of temperature and pressure. Input: T is temperature in Kelvin p is pressure in hPa or mb Output: saturation specific humidity (dimensionless). """ es = clausius_clapeyron(T) q = eps * es / (p - (1 - eps) * es ) return q
python
def qsat(T,p): """Compute saturation specific humidity as function of temperature and pressure. Input: T is temperature in Kelvin p is pressure in hPa or mb Output: saturation specific humidity (dimensionless). """ es = clausius_clapeyron(T) q = eps * es / (p - (1 - eps) * es ) return q
[ "def", "qsat", "(", "T", ",", "p", ")", ":", "es", "=", "clausius_clapeyron", "(", "T", ")", "q", "=", "eps", "*", "es", "/", "(", "p", "-", "(", "1", "-", "eps", ")", "*", "es", ")", "return", "q" ]
Compute saturation specific humidity as function of temperature and pressure. Input: T is temperature in Kelvin p is pressure in hPa or mb Output: saturation specific humidity (dimensionless).
[ "Compute", "saturation", "specific", "humidity", "as", "function", "of", "temperature", "and", "pressure", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/utils/thermo.py#L56-L66
7,634
brian-rose/climlab
climlab/utils/thermo.py
pseudoadiabat
def pseudoadiabat(T,p): """Compute the local slope of the pseudoadiabat at given temperature and pressure Inputs: p is pressure in hPa or mb T is local temperature in Kelvin Output: dT/dp, the rate of temperature change for pseudoadiabatic ascent in units of K / hPa The pseudoadiabat describes changes in temperature and pressure for an air parcel at saturation assuming instantaneous rain-out of the super-saturated water Formula consistent with eq. (2.33) from Raymond Pierrehumbert, "Principles of Planetary Climate" which nominally accounts for non-dilute effects, but computes the derivative dT/dpa, where pa is the partial pressure of the non-condensible gas. Integrating the result dT/dp treating p as total pressure effectively makes the dilute assumption. """ esoverp = clausius_clapeyron(T) / p Tcel = T - tempCtoK L = (2.501 - 0.00237 * Tcel) * 1.E6 # Accurate form of latent heat of vaporization in J/kg ratio = L / T / Rv dTdp = (T / p * kappa * (1 + esoverp * ratio) / (1 + kappa * (cpv / Rv + (ratio-1) * ratio) * esoverp)) return dTdp
python
def pseudoadiabat(T,p): """Compute the local slope of the pseudoadiabat at given temperature and pressure Inputs: p is pressure in hPa or mb T is local temperature in Kelvin Output: dT/dp, the rate of temperature change for pseudoadiabatic ascent in units of K / hPa The pseudoadiabat describes changes in temperature and pressure for an air parcel at saturation assuming instantaneous rain-out of the super-saturated water Formula consistent with eq. (2.33) from Raymond Pierrehumbert, "Principles of Planetary Climate" which nominally accounts for non-dilute effects, but computes the derivative dT/dpa, where pa is the partial pressure of the non-condensible gas. Integrating the result dT/dp treating p as total pressure effectively makes the dilute assumption. """ esoverp = clausius_clapeyron(T) / p Tcel = T - tempCtoK L = (2.501 - 0.00237 * Tcel) * 1.E6 # Accurate form of latent heat of vaporization in J/kg ratio = L / T / Rv dTdp = (T / p * kappa * (1 + esoverp * ratio) / (1 + kappa * (cpv / Rv + (ratio-1) * ratio) * esoverp)) return dTdp
[ "def", "pseudoadiabat", "(", "T", ",", "p", ")", ":", "esoverp", "=", "clausius_clapeyron", "(", "T", ")", "/", "p", "Tcel", "=", "T", "-", "tempCtoK", "L", "=", "(", "2.501", "-", "0.00237", "*", "Tcel", ")", "*", "1.E6", "# Accurate form of latent heat of vaporization in J/kg", "ratio", "=", "L", "/", "T", "/", "Rv", "dTdp", "=", "(", "T", "/", "p", "*", "kappa", "*", "(", "1", "+", "esoverp", "*", "ratio", ")", "/", "(", "1", "+", "kappa", "*", "(", "cpv", "/", "Rv", "+", "(", "ratio", "-", "1", ")", "*", "ratio", ")", "*", "esoverp", ")", ")", "return", "dTdp" ]
Compute the local slope of the pseudoadiabat at given temperature and pressure Inputs: p is pressure in hPa or mb T is local temperature in Kelvin Output: dT/dp, the rate of temperature change for pseudoadiabatic ascent in units of K / hPa The pseudoadiabat describes changes in temperature and pressure for an air parcel at saturation assuming instantaneous rain-out of the super-saturated water Formula consistent with eq. (2.33) from Raymond Pierrehumbert, "Principles of Planetary Climate" which nominally accounts for non-dilute effects, but computes the derivative dT/dpa, where pa is the partial pressure of the non-condensible gas. Integrating the result dT/dp treating p as total pressure effectively makes the dilute assumption.
[ "Compute", "the", "local", "slope", "of", "the", "pseudoadiabat", "at", "given", "temperature", "and", "pressure" ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/utils/thermo.py#L101-L124
7,635
brian-rose/climlab
climlab/dynamics/diffusion.py
_solve_implicit_banded
def _solve_implicit_banded(current, banded_matrix): """Uses a banded solver for matrix inversion of a tridiagonal matrix. Converts the complete listed tridiagonal matrix *(nxn)* into a three row matrix *(3xn)* and calls :py:func:`scipy.linalg.solve_banded()`. :param array current: the current state of the variable for which matrix inversion should be computed :param array banded_matrix: complete diffusion matrix (*dimension: nxn*) :returns: output of :py:func:`scipy.linalg.solve_banded()` :rtype: array """ # can improve performance by storing the banded form once and not # recalculating it... # but whatever J = banded_matrix.shape[0] diag = np.zeros((3, J)) diag[1, :] = np.diag(banded_matrix, k=0) diag[0, 1:] = np.diag(banded_matrix, k=1) diag[2, :-1] = np.diag(banded_matrix, k=-1) return solve_banded((1, 1), diag, current)
python
def _solve_implicit_banded(current, banded_matrix): """Uses a banded solver for matrix inversion of a tridiagonal matrix. Converts the complete listed tridiagonal matrix *(nxn)* into a three row matrix *(3xn)* and calls :py:func:`scipy.linalg.solve_banded()`. :param array current: the current state of the variable for which matrix inversion should be computed :param array banded_matrix: complete diffusion matrix (*dimension: nxn*) :returns: output of :py:func:`scipy.linalg.solve_banded()` :rtype: array """ # can improve performance by storing the banded form once and not # recalculating it... # but whatever J = banded_matrix.shape[0] diag = np.zeros((3, J)) diag[1, :] = np.diag(banded_matrix, k=0) diag[0, 1:] = np.diag(banded_matrix, k=1) diag[2, :-1] = np.diag(banded_matrix, k=-1) return solve_banded((1, 1), diag, current)
[ "def", "_solve_implicit_banded", "(", "current", ",", "banded_matrix", ")", ":", "# can improve performance by storing the banded form once and not", "# recalculating it...", "# but whatever", "J", "=", "banded_matrix", ".", "shape", "[", "0", "]", "diag", "=", "np", ".", "zeros", "(", "(", "3", ",", "J", ")", ")", "diag", "[", "1", ",", ":", "]", "=", "np", ".", "diag", "(", "banded_matrix", ",", "k", "=", "0", ")", "diag", "[", "0", ",", "1", ":", "]", "=", "np", ".", "diag", "(", "banded_matrix", ",", "k", "=", "1", ")", "diag", "[", "2", ",", ":", "-", "1", "]", "=", "np", ".", "diag", "(", "banded_matrix", ",", "k", "=", "-", "1", ")", "return", "solve_banded", "(", "(", "1", ",", "1", ")", ",", "diag", ",", "current", ")" ]
Uses a banded solver for matrix inversion of a tridiagonal matrix. Converts the complete listed tridiagonal matrix *(nxn)* into a three row matrix *(3xn)* and calls :py:func:`scipy.linalg.solve_banded()`. :param array current: the current state of the variable for which matrix inversion should be computed :param array banded_matrix: complete diffusion matrix (*dimension: nxn*) :returns: output of :py:func:`scipy.linalg.solve_banded()` :rtype: array
[ "Uses", "a", "banded", "solver", "for", "matrix", "inversion", "of", "a", "tridiagonal", "matrix", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/dynamics/diffusion.py#L360-L381
7,636
brian-rose/climlab
climlab/dynamics/diffusion.py
_guess_diffusion_axis
def _guess_diffusion_axis(process_or_domain): """Scans given process, domain or dictionary of domains for a diffusion axis and returns appropriate name. In case only one axis with length > 1 in the process or set of domains exists, the name of that axis is returned. Otherwise an error is raised. :param process_or_domain: input from where diffusion axis should be guessed :type process_or_domain: :class:`~climlab.process.process.Process`, :class:`~climlab.domain.domain._Domain` or :py:class:`dict` of domains :raises: :exc:`ValueError` if more than one diffusion axis is possible. :returns: name of the diffusion axis :rtype: str """ axes = get_axes(process_or_domain) diff_ax = {} for axname, ax in axes.items(): if ax.num_points > 1: diff_ax.update({axname: ax}) if len(list(diff_ax.keys())) == 1: return list(diff_ax.keys())[0] else: raise ValueError('More than one possible diffusion axis.')
python
def _guess_diffusion_axis(process_or_domain): """Scans given process, domain or dictionary of domains for a diffusion axis and returns appropriate name. In case only one axis with length > 1 in the process or set of domains exists, the name of that axis is returned. Otherwise an error is raised. :param process_or_domain: input from where diffusion axis should be guessed :type process_or_domain: :class:`~climlab.process.process.Process`, :class:`~climlab.domain.domain._Domain` or :py:class:`dict` of domains :raises: :exc:`ValueError` if more than one diffusion axis is possible. :returns: name of the diffusion axis :rtype: str """ axes = get_axes(process_or_domain) diff_ax = {} for axname, ax in axes.items(): if ax.num_points > 1: diff_ax.update({axname: ax}) if len(list(diff_ax.keys())) == 1: return list(diff_ax.keys())[0] else: raise ValueError('More than one possible diffusion axis.')
[ "def", "_guess_diffusion_axis", "(", "process_or_domain", ")", ":", "axes", "=", "get_axes", "(", "process_or_domain", ")", "diff_ax", "=", "{", "}", "for", "axname", ",", "ax", "in", "axes", ".", "items", "(", ")", ":", "if", "ax", ".", "num_points", ">", "1", ":", "diff_ax", ".", "update", "(", "{", "axname", ":", "ax", "}", ")", "if", "len", "(", "list", "(", "diff_ax", ".", "keys", "(", ")", ")", ")", "==", "1", ":", "return", "list", "(", "diff_ax", ".", "keys", "(", ")", ")", "[", "0", "]", "else", ":", "raise", "ValueError", "(", "'More than one possible diffusion axis.'", ")" ]
Scans given process, domain or dictionary of domains for a diffusion axis and returns appropriate name. In case only one axis with length > 1 in the process or set of domains exists, the name of that axis is returned. Otherwise an error is raised. :param process_or_domain: input from where diffusion axis should be guessed :type process_or_domain: :class:`~climlab.process.process.Process`, :class:`~climlab.domain.domain._Domain` or :py:class:`dict` of domains :raises: :exc:`ValueError` if more than one diffusion axis is possible. :returns: name of the diffusion axis :rtype: str
[ "Scans", "given", "process", "domain", "or", "dictionary", "of", "domains", "for", "a", "diffusion", "axis", "and", "returns", "appropriate", "name", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/dynamics/diffusion.py#L384-L408
7,637
brian-rose/climlab
climlab/dynamics/diffusion.py
Diffusion._implicit_solver
def _implicit_solver(self): """Invertes and solves the matrix problem for diffusion matrix and temperature T. The method is called by the :func:`~climlab.process.implicit.ImplicitProcess._compute()` function of the :class:`~climlab.process.implicit.ImplicitProcess` class and solves the matrix problem .. math:: A \\cdot T_{\\textrm{new}} = T_{\\textrm{old}} for diffusion matrix A and corresponding temperatures. :math:`T_{\\textrm{old}}` is in this case the current state variable which already has been adjusted by the explicit processes. :math:`T_{\\textrm{new}}` is the new state of the variable. To derive the temperature tendency of the diffusion process the adjustment has to be calculated and muliplied with the timestep which is done by the :func:`~climlab.process.implicit.ImplicitProcess._compute()` function of the :class:`~climlab.process.implicit.ImplicitProcess` class. This method calculates the matrix inversion for every state variable and calling either :func:`solve_implicit_banded()` or :py:func:`numpy.linalg.solve()` dependent on the flag ``self.use_banded_solver``. :ivar dict state: method uses current state variables but does not modify them :ivar bool use_banded_solver: input flag whether to use :func:`_solve_implicit_banded()` or :py:func:`numpy.linalg.solve()` to do the matrix inversion :ivar array _diffTriDiag: the diffusion matrix which is given with the current state variable to the method solving the matrix problem """ #if self.update_diffusivity: # Time-stepping the diffusion is just inverting this matrix problem: newstate = {} for varname, value in self.state.items(): if self.use_banded_solver: newvar = _solve_implicit_banded(value, self._diffTriDiag) else: newvar = np.linalg.solve(self._diffTriDiag, value) newstate[varname] = newvar return newstate
python
def _implicit_solver(self): """Invertes and solves the matrix problem for diffusion matrix and temperature T. The method is called by the :func:`~climlab.process.implicit.ImplicitProcess._compute()` function of the :class:`~climlab.process.implicit.ImplicitProcess` class and solves the matrix problem .. math:: A \\cdot T_{\\textrm{new}} = T_{\\textrm{old}} for diffusion matrix A and corresponding temperatures. :math:`T_{\\textrm{old}}` is in this case the current state variable which already has been adjusted by the explicit processes. :math:`T_{\\textrm{new}}` is the new state of the variable. To derive the temperature tendency of the diffusion process the adjustment has to be calculated and muliplied with the timestep which is done by the :func:`~climlab.process.implicit.ImplicitProcess._compute()` function of the :class:`~climlab.process.implicit.ImplicitProcess` class. This method calculates the matrix inversion for every state variable and calling either :func:`solve_implicit_banded()` or :py:func:`numpy.linalg.solve()` dependent on the flag ``self.use_banded_solver``. :ivar dict state: method uses current state variables but does not modify them :ivar bool use_banded_solver: input flag whether to use :func:`_solve_implicit_banded()` or :py:func:`numpy.linalg.solve()` to do the matrix inversion :ivar array _diffTriDiag: the diffusion matrix which is given with the current state variable to the method solving the matrix problem """ #if self.update_diffusivity: # Time-stepping the diffusion is just inverting this matrix problem: newstate = {} for varname, value in self.state.items(): if self.use_banded_solver: newvar = _solve_implicit_banded(value, self._diffTriDiag) else: newvar = np.linalg.solve(self._diffTriDiag, value) newstate[varname] = newvar return newstate
[ "def", "_implicit_solver", "(", "self", ")", ":", "#if self.update_diffusivity:", "# Time-stepping the diffusion is just inverting this matrix problem:", "newstate", "=", "{", "}", "for", "varname", ",", "value", "in", "self", ".", "state", ".", "items", "(", ")", ":", "if", "self", ".", "use_banded_solver", ":", "newvar", "=", "_solve_implicit_banded", "(", "value", ",", "self", ".", "_diffTriDiag", ")", "else", ":", "newvar", "=", "np", ".", "linalg", ".", "solve", "(", "self", ".", "_diffTriDiag", ",", "value", ")", "newstate", "[", "varname", "]", "=", "newvar", "return", "newstate" ]
Invertes and solves the matrix problem for diffusion matrix and temperature T. The method is called by the :func:`~climlab.process.implicit.ImplicitProcess._compute()` function of the :class:`~climlab.process.implicit.ImplicitProcess` class and solves the matrix problem .. math:: A \\cdot T_{\\textrm{new}} = T_{\\textrm{old}} for diffusion matrix A and corresponding temperatures. :math:`T_{\\textrm{old}}` is in this case the current state variable which already has been adjusted by the explicit processes. :math:`T_{\\textrm{new}}` is the new state of the variable. To derive the temperature tendency of the diffusion process the adjustment has to be calculated and muliplied with the timestep which is done by the :func:`~climlab.process.implicit.ImplicitProcess._compute()` function of the :class:`~climlab.process.implicit.ImplicitProcess` class. This method calculates the matrix inversion for every state variable and calling either :func:`solve_implicit_banded()` or :py:func:`numpy.linalg.solve()` dependent on the flag ``self.use_banded_solver``. :ivar dict state: method uses current state variables but does not modify them :ivar bool use_banded_solver: input flag whether to use :func:`_solve_implicit_banded()` or :py:func:`numpy.linalg.solve()` to do the matrix inversion :ivar array _diffTriDiag: the diffusion matrix which is given with the current state variable to the method solving the matrix problem
[ "Invertes", "and", "solves", "the", "matrix", "problem", "for", "diffusion", "matrix", "and", "temperature", "T", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/dynamics/diffusion.py#L143-L192
7,638
brian-rose/climlab
climlab/surface/albedo.py
P2Albedo._compute_fixed
def _compute_fixed(self): '''Recompute any fixed quantities after a change in parameters''' try: lon, lat = np.meshgrid(self.lon, self.lat) except: lat = self.lat phi = np.deg2rad(lat) try: albedo = self.a0 + self.a2 * P2(np.sin(phi)) except: albedo = np.zeros_like(phi) # make sure that the diagnostic has the correct field dimensions. #dom = self.domains['default'] # this is a more robust way to get the single value from dictionary: dom = next(iter(self.domains.values())) self.albedo = Field(albedo, domain=dom)
python
def _compute_fixed(self): '''Recompute any fixed quantities after a change in parameters''' try: lon, lat = np.meshgrid(self.lon, self.lat) except: lat = self.lat phi = np.deg2rad(lat) try: albedo = self.a0 + self.a2 * P2(np.sin(phi)) except: albedo = np.zeros_like(phi) # make sure that the diagnostic has the correct field dimensions. #dom = self.domains['default'] # this is a more robust way to get the single value from dictionary: dom = next(iter(self.domains.values())) self.albedo = Field(albedo, domain=dom)
[ "def", "_compute_fixed", "(", "self", ")", ":", "try", ":", "lon", ",", "lat", "=", "np", ".", "meshgrid", "(", "self", ".", "lon", ",", "self", ".", "lat", ")", "except", ":", "lat", "=", "self", ".", "lat", "phi", "=", "np", ".", "deg2rad", "(", "lat", ")", "try", ":", "albedo", "=", "self", ".", "a0", "+", "self", ".", "a2", "*", "P2", "(", "np", ".", "sin", "(", "phi", ")", ")", "except", ":", "albedo", "=", "np", ".", "zeros_like", "(", "phi", ")", "# make sure that the diagnostic has the correct field dimensions.", "#dom = self.domains['default']", "# this is a more robust way to get the single value from dictionary:", "dom", "=", "next", "(", "iter", "(", "self", ".", "domains", ".", "values", "(", ")", ")", ")", "self", ".", "albedo", "=", "Field", "(", "albedo", ",", "domain", "=", "dom", ")" ]
Recompute any fixed quantities after a change in parameters
[ "Recompute", "any", "fixed", "quantities", "after", "a", "change", "in", "parameters" ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/surface/albedo.py#L179-L194
7,639
brian-rose/climlab
climlab/surface/albedo.py
Iceline.find_icelines
def find_icelines(self): """Finds iceline according to the surface temperature. This method is called by the private function :func:`~climlab.surface.albedo.Iceline._compute` and updates following attributes according to the freezing temperature ``self.param['Tf']`` and the surface temperature ``self.param['Ts']``: **Object attributes** \n :ivar Field noice: a Field of booleans which are ``True`` where :math:`T_s \\ge T_f` :ivar Field ice: a Field of booleans which are ``True`` where :math:`T_s < T_f` :ivar array icelat: an array with two elements indicating the ice-edge latitudes :ivar float ice_area: fractional area covered by ice (0 - 1) :ivar dict diagnostics: keys ``'icelat'`` and ``'ice_area'`` are updated """ Tf = self.param['Tf'] Ts = self.state['Ts'] lat_bounds = self.domains['Ts'].axes['lat'].bounds self.noice = np.where(Ts >= Tf, True, False) self.ice = np.where(Ts < Tf, True, False) # Ice cover in fractional area self.ice_area = global_mean(self.ice * np.ones_like(self.Ts)) # Express ice cover in terms of ice edge latitudes if self.ice.all(): # 100% ice cover self.icelat = np.array([-0., 0.]) elif self.noice.all(): # zero ice cover self.icelat = np.array([-90., 90.]) else: # there is some ice edge # Taking np.diff of a boolean array gives True at the boundaries between True and False boundary_indices = np.where(np.diff(self.ice.squeeze()))[0]+1 # check for asymmetry case: [-90,x] or [x,90] # -> boundary_indices hold only one value for icelat if boundary_indices.size == 1: if self.ice[0] == True: # case: [x,90] # extend indice array by missing value for northpole boundary_indices = np.append(boundary_indices, self.ice.size) elif self.ice[-1] == True: # case: [-90,x] # extend indice array by missing value for northpole boundary_indices = np.insert(boundary_indices,0 ,0) # check for asymmetry case: [-90,x] or [x,90] # -> boundary_indices hold only one value for icelat if boundary_indices.size == 1: if self.ice[0] == True: # case: [x,90] # extend indice array by missing value for northpole boundary_indices = np.append(boundary_indices, self.ice.size) elif self.ice[-1] == True: # case: [-90,x] # extend indice array by missing value for northpole boundary_indices = np.insert(boundary_indices,0 ,0) self.icelat = lat_bounds[boundary_indices]
python
def find_icelines(self): """Finds iceline according to the surface temperature. This method is called by the private function :func:`~climlab.surface.albedo.Iceline._compute` and updates following attributes according to the freezing temperature ``self.param['Tf']`` and the surface temperature ``self.param['Ts']``: **Object attributes** \n :ivar Field noice: a Field of booleans which are ``True`` where :math:`T_s \\ge T_f` :ivar Field ice: a Field of booleans which are ``True`` where :math:`T_s < T_f` :ivar array icelat: an array with two elements indicating the ice-edge latitudes :ivar float ice_area: fractional area covered by ice (0 - 1) :ivar dict diagnostics: keys ``'icelat'`` and ``'ice_area'`` are updated """ Tf = self.param['Tf'] Ts = self.state['Ts'] lat_bounds = self.domains['Ts'].axes['lat'].bounds self.noice = np.where(Ts >= Tf, True, False) self.ice = np.where(Ts < Tf, True, False) # Ice cover in fractional area self.ice_area = global_mean(self.ice * np.ones_like(self.Ts)) # Express ice cover in terms of ice edge latitudes if self.ice.all(): # 100% ice cover self.icelat = np.array([-0., 0.]) elif self.noice.all(): # zero ice cover self.icelat = np.array([-90., 90.]) else: # there is some ice edge # Taking np.diff of a boolean array gives True at the boundaries between True and False boundary_indices = np.where(np.diff(self.ice.squeeze()))[0]+1 # check for asymmetry case: [-90,x] or [x,90] # -> boundary_indices hold only one value for icelat if boundary_indices.size == 1: if self.ice[0] == True: # case: [x,90] # extend indice array by missing value for northpole boundary_indices = np.append(boundary_indices, self.ice.size) elif self.ice[-1] == True: # case: [-90,x] # extend indice array by missing value for northpole boundary_indices = np.insert(boundary_indices,0 ,0) # check for asymmetry case: [-90,x] or [x,90] # -> boundary_indices hold only one value for icelat if boundary_indices.size == 1: if self.ice[0] == True: # case: [x,90] # extend indice array by missing value for northpole boundary_indices = np.append(boundary_indices, self.ice.size) elif self.ice[-1] == True: # case: [-90,x] # extend indice array by missing value for northpole boundary_indices = np.insert(boundary_indices,0 ,0) self.icelat = lat_bounds[boundary_indices]
[ "def", "find_icelines", "(", "self", ")", ":", "Tf", "=", "self", ".", "param", "[", "'Tf'", "]", "Ts", "=", "self", ".", "state", "[", "'Ts'", "]", "lat_bounds", "=", "self", ".", "domains", "[", "'Ts'", "]", ".", "axes", "[", "'lat'", "]", ".", "bounds", "self", ".", "noice", "=", "np", ".", "where", "(", "Ts", ">=", "Tf", ",", "True", ",", "False", ")", "self", ".", "ice", "=", "np", ".", "where", "(", "Ts", "<", "Tf", ",", "True", ",", "False", ")", "# Ice cover in fractional area", "self", ".", "ice_area", "=", "global_mean", "(", "self", ".", "ice", "*", "np", ".", "ones_like", "(", "self", ".", "Ts", ")", ")", "# Express ice cover in terms of ice edge latitudes", "if", "self", ".", "ice", ".", "all", "(", ")", ":", "# 100% ice cover", "self", ".", "icelat", "=", "np", ".", "array", "(", "[", "-", "0.", ",", "0.", "]", ")", "elif", "self", ".", "noice", ".", "all", "(", ")", ":", "# zero ice cover", "self", ".", "icelat", "=", "np", ".", "array", "(", "[", "-", "90.", ",", "90.", "]", ")", "else", ":", "# there is some ice edge", "# Taking np.diff of a boolean array gives True at the boundaries between True and False", "boundary_indices", "=", "np", ".", "where", "(", "np", ".", "diff", "(", "self", ".", "ice", ".", "squeeze", "(", ")", ")", ")", "[", "0", "]", "+", "1", "# check for asymmetry case: [-90,x] or [x,90]", "# -> boundary_indices hold only one value for icelat", "if", "boundary_indices", ".", "size", "==", "1", ":", "if", "self", ".", "ice", "[", "0", "]", "==", "True", ":", "# case: [x,90]", "# extend indice array by missing value for northpole", "boundary_indices", "=", "np", ".", "append", "(", "boundary_indices", ",", "self", ".", "ice", ".", "size", ")", "elif", "self", ".", "ice", "[", "-", "1", "]", "==", "True", ":", "# case: [-90,x]", "# extend indice array by missing value for northpole", "boundary_indices", "=", "np", ".", "insert", "(", "boundary_indices", ",", "0", ",", "0", ")", "# check for asymmetry case: [-90,x] or [x,90]", "# -> boundary_indices hold only one value for icelat", "if", "boundary_indices", ".", "size", "==", "1", ":", "if", "self", ".", "ice", "[", "0", "]", "==", "True", ":", "# case: [x,90]", "# extend indice array by missing value for northpole", "boundary_indices", "=", "np", ".", "append", "(", "boundary_indices", ",", "self", ".", "ice", ".", "size", ")", "elif", "self", ".", "ice", "[", "-", "1", "]", "==", "True", ":", "# case: [-90,x]", "# extend indice array by missing value for northpole", "boundary_indices", "=", "np", ".", "insert", "(", "boundary_indices", ",", "0", ",", "0", ")", "self", ".", "icelat", "=", "lat_bounds", "[", "boundary_indices", "]" ]
Finds iceline according to the surface temperature. This method is called by the private function :func:`~climlab.surface.albedo.Iceline._compute` and updates following attributes according to the freezing temperature ``self.param['Tf']`` and the surface temperature ``self.param['Ts']``: **Object attributes** \n :ivar Field noice: a Field of booleans which are ``True`` where :math:`T_s \\ge T_f` :ivar Field ice: a Field of booleans which are ``True`` where :math:`T_s < T_f` :ivar array icelat: an array with two elements indicating the ice-edge latitudes :ivar float ice_area: fractional area covered by ice (0 - 1) :ivar dict diagnostics: keys ``'icelat'`` and ``'ice_area'`` are updated
[ "Finds", "iceline", "according", "to", "the", "surface", "temperature", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/surface/albedo.py#L236-L291
7,640
brian-rose/climlab
climlab/surface/albedo.py
StepFunctionAlbedo._get_current_albedo
def _get_current_albedo(self): '''Simple step-function albedo based on ice line at temperature Tf.''' ice = self.subprocess['iceline'].ice # noice = self.subprocess['iceline'].diagnostics['noice'] cold_albedo = self.subprocess['cold_albedo'].albedo warm_albedo = self.subprocess['warm_albedo'].albedo albedo = Field(np.where(ice, cold_albedo, warm_albedo), domain=self.domains['Ts']) return albedo
python
def _get_current_albedo(self): '''Simple step-function albedo based on ice line at temperature Tf.''' ice = self.subprocess['iceline'].ice # noice = self.subprocess['iceline'].diagnostics['noice'] cold_albedo = self.subprocess['cold_albedo'].albedo warm_albedo = self.subprocess['warm_albedo'].albedo albedo = Field(np.where(ice, cold_albedo, warm_albedo), domain=self.domains['Ts']) return albedo
[ "def", "_get_current_albedo", "(", "self", ")", ":", "ice", "=", "self", ".", "subprocess", "[", "'iceline'", "]", ".", "ice", "# noice = self.subprocess['iceline'].diagnostics['noice']", "cold_albedo", "=", "self", ".", "subprocess", "[", "'cold_albedo'", "]", ".", "albedo", "warm_albedo", "=", "self", ".", "subprocess", "[", "'warm_albedo'", "]", ".", "albedo", "albedo", "=", "Field", "(", "np", ".", "where", "(", "ice", ",", "cold_albedo", ",", "warm_albedo", ")", ",", "domain", "=", "self", ".", "domains", "[", "'Ts'", "]", ")", "return", "albedo" ]
Simple step-function albedo based on ice line at temperature Tf.
[ "Simple", "step", "-", "function", "albedo", "based", "on", "ice", "line", "at", "temperature", "Tf", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/surface/albedo.py#L374-L381
7,641
brian-rose/climlab
climlab/process/process.py
process_like
def process_like(proc): """Make an exact clone of a process, including state and all subprocesses. The creation date is updated. :param proc: process :type proc: :class:`~climlab.process.process.Process` :return: new process identical to the given process :rtype: :class:`~climlab.process.process.Process` :Example: :: >>> import climlab >>> from climlab.process.process import process_like >>> model = climlab.EBM() >>> model.subprocess.keys() ['diffusion', 'LW', 'albedo', 'insolation'] >>> albedo = model.subprocess['albedo'] >>> albedo_copy = process_like(albedo) >>> albedo.creation_date 'Thu, 24 Mar 2016 01:32:25 +0000' >>> albedo_copy.creation_date 'Thu, 24 Mar 2016 01:33:29 +0000' """ newproc = copy.deepcopy(proc) newproc.creation_date = time.strftime("%a, %d %b %Y %H:%M:%S %z", time.localtime()) return newproc
python
def process_like(proc): """Make an exact clone of a process, including state and all subprocesses. The creation date is updated. :param proc: process :type proc: :class:`~climlab.process.process.Process` :return: new process identical to the given process :rtype: :class:`~climlab.process.process.Process` :Example: :: >>> import climlab >>> from climlab.process.process import process_like >>> model = climlab.EBM() >>> model.subprocess.keys() ['diffusion', 'LW', 'albedo', 'insolation'] >>> albedo = model.subprocess['albedo'] >>> albedo_copy = process_like(albedo) >>> albedo.creation_date 'Thu, 24 Mar 2016 01:32:25 +0000' >>> albedo_copy.creation_date 'Thu, 24 Mar 2016 01:33:29 +0000' """ newproc = copy.deepcopy(proc) newproc.creation_date = time.strftime("%a, %d %b %Y %H:%M:%S %z", time.localtime()) return newproc
[ "def", "process_like", "(", "proc", ")", ":", "newproc", "=", "copy", ".", "deepcopy", "(", "proc", ")", "newproc", ".", "creation_date", "=", "time", ".", "strftime", "(", "\"%a, %d %b %Y %H:%M:%S %z\"", ",", "time", ".", "localtime", "(", ")", ")", "return", "newproc" ]
Make an exact clone of a process, including state and all subprocesses. The creation date is updated. :param proc: process :type proc: :class:`~climlab.process.process.Process` :return: new process identical to the given process :rtype: :class:`~climlab.process.process.Process` :Example: :: >>> import climlab >>> from climlab.process.process import process_like >>> model = climlab.EBM() >>> model.subprocess.keys() ['diffusion', 'LW', 'albedo', 'insolation'] >>> albedo = model.subprocess['albedo'] >>> albedo_copy = process_like(albedo) >>> albedo.creation_date 'Thu, 24 Mar 2016 01:32:25 +0000' >>> albedo_copy.creation_date 'Thu, 24 Mar 2016 01:33:29 +0000'
[ "Make", "an", "exact", "clone", "of", "a", "process", "including", "state", "and", "all", "subprocesses", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L783-L817
7,642
brian-rose/climlab
climlab/process/process.py
get_axes
def get_axes(process_or_domain): """Returns a dictionary of all Axis in a domain or dictionary of domains. :param process_or_domain: a process or a domain object :type process_or_domain: :class:`~climlab.process.process.Process` or :class:`~climlab.domain.domain._Domain` :raises: :exc: `TypeError` if input is not or not having a domain :returns: dictionary of input's Axis :rtype: dict :Example: :: >>> import climlab >>> from climlab.process.process import get_axes >>> model = climlab.EBM() >>> get_axes(model) {'lat': <climlab.domain.axis.Axis object at 0x7ff13b9dd2d0>, 'depth': <climlab.domain.axis.Axis object at 0x7ff13b9dd310>} """ if isinstance(process_or_domain, Process): dom = process_or_domain.domains else: dom = process_or_domain if isinstance(dom, _Domain): return dom.axes elif isinstance(dom, dict): axes = {} for thisdom in list(dom.values()): assert isinstance(thisdom, _Domain) axes.update(thisdom.axes) return axes else: raise TypeError('dom must be a domain or dictionary of domains.')
python
def get_axes(process_or_domain): """Returns a dictionary of all Axis in a domain or dictionary of domains. :param process_or_domain: a process or a domain object :type process_or_domain: :class:`~climlab.process.process.Process` or :class:`~climlab.domain.domain._Domain` :raises: :exc: `TypeError` if input is not or not having a domain :returns: dictionary of input's Axis :rtype: dict :Example: :: >>> import climlab >>> from climlab.process.process import get_axes >>> model = climlab.EBM() >>> get_axes(model) {'lat': <climlab.domain.axis.Axis object at 0x7ff13b9dd2d0>, 'depth': <climlab.domain.axis.Axis object at 0x7ff13b9dd310>} """ if isinstance(process_or_domain, Process): dom = process_or_domain.domains else: dom = process_or_domain if isinstance(dom, _Domain): return dom.axes elif isinstance(dom, dict): axes = {} for thisdom in list(dom.values()): assert isinstance(thisdom, _Domain) axes.update(thisdom.axes) return axes else: raise TypeError('dom must be a domain or dictionary of domains.')
[ "def", "get_axes", "(", "process_or_domain", ")", ":", "if", "isinstance", "(", "process_or_domain", ",", "Process", ")", ":", "dom", "=", "process_or_domain", ".", "domains", "else", ":", "dom", "=", "process_or_domain", "if", "isinstance", "(", "dom", ",", "_Domain", ")", ":", "return", "dom", ".", "axes", "elif", "isinstance", "(", "dom", ",", "dict", ")", ":", "axes", "=", "{", "}", "for", "thisdom", "in", "list", "(", "dom", ".", "values", "(", ")", ")", ":", "assert", "isinstance", "(", "thisdom", ",", "_Domain", ")", "axes", ".", "update", "(", "thisdom", ".", "axes", ")", "return", "axes", "else", ":", "raise", "TypeError", "(", "'dom must be a domain or dictionary of domains.'", ")" ]
Returns a dictionary of all Axis in a domain or dictionary of domains. :param process_or_domain: a process or a domain object :type process_or_domain: :class:`~climlab.process.process.Process` or :class:`~climlab.domain.domain._Domain` :raises: :exc: `TypeError` if input is not or not having a domain :returns: dictionary of input's Axis :rtype: dict :Example: :: >>> import climlab >>> from climlab.process.process import get_axes >>> model = climlab.EBM() >>> get_axes(model) {'lat': <climlab.domain.axis.Axis object at 0x7ff13b9dd2d0>, 'depth': <climlab.domain.axis.Axis object at 0x7ff13b9dd310>}
[ "Returns", "a", "dictionary", "of", "all", "Axis", "in", "a", "domain", "or", "dictionary", "of", "domains", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L820-L857
7,643
brian-rose/climlab
climlab/process/process.py
Process.add_subprocesses
def add_subprocesses(self, procdict): """Adds a dictionary of subproceses to this process. Calls :func:`add_subprocess` for every process given in the input-dictionary. It can also pass a single process, which will be given the name *default*. :param procdict: a dictionary with process names as keys :type procdict: dict """ if isinstance(procdict, Process): try: name = procdict.name except: name = 'default' self.add_subprocess(name, procdict) else: for name, proc in procdict.items(): self.add_subprocess(name, proc)
python
def add_subprocesses(self, procdict): """Adds a dictionary of subproceses to this process. Calls :func:`add_subprocess` for every process given in the input-dictionary. It can also pass a single process, which will be given the name *default*. :param procdict: a dictionary with process names as keys :type procdict: dict """ if isinstance(procdict, Process): try: name = procdict.name except: name = 'default' self.add_subprocess(name, procdict) else: for name, proc in procdict.items(): self.add_subprocess(name, proc)
[ "def", "add_subprocesses", "(", "self", ",", "procdict", ")", ":", "if", "isinstance", "(", "procdict", ",", "Process", ")", ":", "try", ":", "name", "=", "procdict", ".", "name", "except", ":", "name", "=", "'default'", "self", ".", "add_subprocess", "(", "name", ",", "procdict", ")", "else", ":", "for", "name", ",", "proc", "in", "procdict", ".", "items", "(", ")", ":", "self", ".", "add_subprocess", "(", "name", ",", "proc", ")" ]
Adds a dictionary of subproceses to this process. Calls :func:`add_subprocess` for every process given in the input-dictionary. It can also pass a single process, which will be given the name *default*. :param procdict: a dictionary with process names as keys :type procdict: dict
[ "Adds", "a", "dictionary", "of", "subproceses", "to", "this", "process", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L191-L210
7,644
brian-rose/climlab
climlab/process/process.py
Process.add_subprocess
def add_subprocess(self, name, proc): """Adds a single subprocess to this process. :param string name: name of the subprocess :param proc: a Process object :type proc: :class:`~climlab.process.process.Process` :raises: :exc:`ValueError` if ``proc`` is not a process :Example: Replacing an albedo subprocess through adding a subprocess with same name:: >>> from climlab.model.ebm import EBM_seasonal >>> from climlab.surface.albedo import StepFunctionAlbedo >>> # creating EBM model >>> ebm_s = EBM_seasonal() >>> print ebm_s .. code-block:: none :emphasize-lines: 8 climlab Process of type <class 'climlab.model.ebm.EBM_seasonal'>. State variables and domain shapes: Ts: (90, 1) The subprocess tree: top: <class 'climlab.model.ebm.EBM_seasonal'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> albedo: <class 'climlab.surface.albedo.P2Albedo'> insolation: <class 'climlab.radiation.insolation.DailyInsolation'> :: >>> # creating and adding albedo feedback subprocess >>> step_albedo = StepFunctionAlbedo(state=ebm_s.state, **ebm_s.param) >>> ebm_s.add_subprocess('albedo', step_albedo) >>> >>> print ebm_s .. code-block:: none :emphasize-lines: 8 climlab Process of type <class 'climlab.model.ebm.EBM_seasonal'>. State variables and domain shapes: Ts: (90, 1) The subprocess tree: top: <class 'climlab.model.ebm.EBM_seasonal'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> albedo: <class 'climlab.surface.albedo.StepFunctionAlbedo'> iceline: <class 'climlab.surface.albedo.Iceline'> cold_albedo: <class 'climlab.surface.albedo.ConstantAlbedo'> warm_albedo: <class 'climlab.surface.albedo.P2Albedo'> insolation: <class 'climlab.radiation.insolation.DailyInsolation'> """ if isinstance(proc, Process): self.subprocess.update({name: proc}) self.has_process_type_list = False # Add subprocess diagnostics to parent # (if there are no name conflicts) for diagname, value in proc.diagnostics.items(): #if not (diagname in self.diagnostics or hasattr(self, diagname)): # self.add_diagnostic(diagname, value) self.add_diagnostic(diagname, value) else: raise ValueError('subprocess must be Process object')
python
def add_subprocess(self, name, proc): """Adds a single subprocess to this process. :param string name: name of the subprocess :param proc: a Process object :type proc: :class:`~climlab.process.process.Process` :raises: :exc:`ValueError` if ``proc`` is not a process :Example: Replacing an albedo subprocess through adding a subprocess with same name:: >>> from climlab.model.ebm import EBM_seasonal >>> from climlab.surface.albedo import StepFunctionAlbedo >>> # creating EBM model >>> ebm_s = EBM_seasonal() >>> print ebm_s .. code-block:: none :emphasize-lines: 8 climlab Process of type <class 'climlab.model.ebm.EBM_seasonal'>. State variables and domain shapes: Ts: (90, 1) The subprocess tree: top: <class 'climlab.model.ebm.EBM_seasonal'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> albedo: <class 'climlab.surface.albedo.P2Albedo'> insolation: <class 'climlab.radiation.insolation.DailyInsolation'> :: >>> # creating and adding albedo feedback subprocess >>> step_albedo = StepFunctionAlbedo(state=ebm_s.state, **ebm_s.param) >>> ebm_s.add_subprocess('albedo', step_albedo) >>> >>> print ebm_s .. code-block:: none :emphasize-lines: 8 climlab Process of type <class 'climlab.model.ebm.EBM_seasonal'>. State variables and domain shapes: Ts: (90, 1) The subprocess tree: top: <class 'climlab.model.ebm.EBM_seasonal'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> albedo: <class 'climlab.surface.albedo.StepFunctionAlbedo'> iceline: <class 'climlab.surface.albedo.Iceline'> cold_albedo: <class 'climlab.surface.albedo.ConstantAlbedo'> warm_albedo: <class 'climlab.surface.albedo.P2Albedo'> insolation: <class 'climlab.radiation.insolation.DailyInsolation'> """ if isinstance(proc, Process): self.subprocess.update({name: proc}) self.has_process_type_list = False # Add subprocess diagnostics to parent # (if there are no name conflicts) for diagname, value in proc.diagnostics.items(): #if not (diagname in self.diagnostics or hasattr(self, diagname)): # self.add_diagnostic(diagname, value) self.add_diagnostic(diagname, value) else: raise ValueError('subprocess must be Process object')
[ "def", "add_subprocess", "(", "self", ",", "name", ",", "proc", ")", ":", "if", "isinstance", "(", "proc", ",", "Process", ")", ":", "self", ".", "subprocess", ".", "update", "(", "{", "name", ":", "proc", "}", ")", "self", ".", "has_process_type_list", "=", "False", "# Add subprocess diagnostics to parent", "# (if there are no name conflicts)", "for", "diagname", ",", "value", "in", "proc", ".", "diagnostics", ".", "items", "(", ")", ":", "#if not (diagname in self.diagnostics or hasattr(self, diagname)):", "# self.add_diagnostic(diagname, value)", "self", ".", "add_diagnostic", "(", "diagname", ",", "value", ")", "else", ":", "raise", "ValueError", "(", "'subprocess must be Process object'", ")" ]
Adds a single subprocess to this process. :param string name: name of the subprocess :param proc: a Process object :type proc: :class:`~climlab.process.process.Process` :raises: :exc:`ValueError` if ``proc`` is not a process :Example: Replacing an albedo subprocess through adding a subprocess with same name:: >>> from climlab.model.ebm import EBM_seasonal >>> from climlab.surface.albedo import StepFunctionAlbedo >>> # creating EBM model >>> ebm_s = EBM_seasonal() >>> print ebm_s .. code-block:: none :emphasize-lines: 8 climlab Process of type <class 'climlab.model.ebm.EBM_seasonal'>. State variables and domain shapes: Ts: (90, 1) The subprocess tree: top: <class 'climlab.model.ebm.EBM_seasonal'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> albedo: <class 'climlab.surface.albedo.P2Albedo'> insolation: <class 'climlab.radiation.insolation.DailyInsolation'> :: >>> # creating and adding albedo feedback subprocess >>> step_albedo = StepFunctionAlbedo(state=ebm_s.state, **ebm_s.param) >>> ebm_s.add_subprocess('albedo', step_albedo) >>> >>> print ebm_s .. code-block:: none :emphasize-lines: 8 climlab Process of type <class 'climlab.model.ebm.EBM_seasonal'>. State variables and domain shapes: Ts: (90, 1) The subprocess tree: top: <class 'climlab.model.ebm.EBM_seasonal'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> albedo: <class 'climlab.surface.albedo.StepFunctionAlbedo'> iceline: <class 'climlab.surface.albedo.Iceline'> cold_albedo: <class 'climlab.surface.albedo.ConstantAlbedo'> warm_albedo: <class 'climlab.surface.albedo.P2Albedo'> insolation: <class 'climlab.radiation.insolation.DailyInsolation'>
[ "Adds", "a", "single", "subprocess", "to", "this", "process", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L212-L282
7,645
brian-rose/climlab
climlab/process/process.py
Process.remove_subprocess
def remove_subprocess(self, name, verbose=True): """Removes a single subprocess from this process. :param string name: name of the subprocess :param bool verbose: information whether warning message should be printed [default: True] :Example: Remove albedo subprocess from energy balance model:: >>> import climlab >>> model = climlab.EBM() >>> print model climlab Process of type <class 'climlab.model.ebm.EBM'>. State variables and domain shapes: Ts: (90, 1) The subprocess tree: top: <class 'climlab.model.ebm.EBM'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> albedo: <class 'climlab.surface.albedo.StepFunctionAlbedo'> iceline: <class 'climlab.surface.albedo.Iceline'> cold_albedo: <class 'climlab.surface.albedo.ConstantAlbedo'> warm_albedo: <class 'climlab.surface.albedo.P2Albedo'> insolation: <class 'climlab.radiation.insolation.P2Insolation'> >>> model.remove_subprocess('albedo') >>> print model climlab Process of type <class 'climlab.model.ebm.EBM'>. State variables and domain shapes: Ts: (90, 1) The subprocess tree: top: <class 'climlab.model.ebm.EBM'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> insolation: <class 'climlab.radiation.insolation.P2Insolation'> """ try: self.subprocess.pop(name) except KeyError: if verbose: print('WARNING: {} not found in subprocess dictionary.'.format(name)) self.has_process_type_list = False
python
def remove_subprocess(self, name, verbose=True): """Removes a single subprocess from this process. :param string name: name of the subprocess :param bool verbose: information whether warning message should be printed [default: True] :Example: Remove albedo subprocess from energy balance model:: >>> import climlab >>> model = climlab.EBM() >>> print model climlab Process of type <class 'climlab.model.ebm.EBM'>. State variables and domain shapes: Ts: (90, 1) The subprocess tree: top: <class 'climlab.model.ebm.EBM'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> albedo: <class 'climlab.surface.albedo.StepFunctionAlbedo'> iceline: <class 'climlab.surface.albedo.Iceline'> cold_albedo: <class 'climlab.surface.albedo.ConstantAlbedo'> warm_albedo: <class 'climlab.surface.albedo.P2Albedo'> insolation: <class 'climlab.radiation.insolation.P2Insolation'> >>> model.remove_subprocess('albedo') >>> print model climlab Process of type <class 'climlab.model.ebm.EBM'>. State variables and domain shapes: Ts: (90, 1) The subprocess tree: top: <class 'climlab.model.ebm.EBM'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> insolation: <class 'climlab.radiation.insolation.P2Insolation'> """ try: self.subprocess.pop(name) except KeyError: if verbose: print('WARNING: {} not found in subprocess dictionary.'.format(name)) self.has_process_type_list = False
[ "def", "remove_subprocess", "(", "self", ",", "name", ",", "verbose", "=", "True", ")", ":", "try", ":", "self", ".", "subprocess", ".", "pop", "(", "name", ")", "except", "KeyError", ":", "if", "verbose", ":", "print", "(", "'WARNING: {} not found in subprocess dictionary.'", ".", "format", "(", "name", ")", ")", "self", ".", "has_process_type_list", "=", "False" ]
Removes a single subprocess from this process. :param string name: name of the subprocess :param bool verbose: information whether warning message should be printed [default: True] :Example: Remove albedo subprocess from energy balance model:: >>> import climlab >>> model = climlab.EBM() >>> print model climlab Process of type <class 'climlab.model.ebm.EBM'>. State variables and domain shapes: Ts: (90, 1) The subprocess tree: top: <class 'climlab.model.ebm.EBM'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> albedo: <class 'climlab.surface.albedo.StepFunctionAlbedo'> iceline: <class 'climlab.surface.albedo.Iceline'> cold_albedo: <class 'climlab.surface.albedo.ConstantAlbedo'> warm_albedo: <class 'climlab.surface.albedo.P2Albedo'> insolation: <class 'climlab.radiation.insolation.P2Insolation'> >>> model.remove_subprocess('albedo') >>> print model climlab Process of type <class 'climlab.model.ebm.EBM'>. State variables and domain shapes: Ts: (90, 1) The subprocess tree: top: <class 'climlab.model.ebm.EBM'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> insolation: <class 'climlab.radiation.insolation.P2Insolation'>
[ "Removes", "a", "single", "subprocess", "from", "this", "process", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L284-L330
7,646
brian-rose/climlab
climlab/process/process.py
Process.set_state
def set_state(self, name, value): """Sets the variable ``name`` to a new state ``value``. :param string name: name of the state :param value: state variable :type value: :class:`~climlab.domain.field.Field` or *array* :raises: :exc:`ValueError` if state variable ``value`` is not having a domain. :raises: :exc:`ValueError` if shape mismatch between existing domain and new state variable. :Example: Resetting the surface temperature of an EBM to :math:`-5 ^{\circ} \\textrm{C}` on all latitues:: >>> import climlab >>> from climlab import Field >>> import numpy as np >>> # setup model >>> model = climlab.EBM(num_lat=36) >>> # create new temperature distribution >>> initial = -5 * ones(size(model.lat)) >>> model.set_state('Ts', Field(initial, domain=model.domains['Ts'])) >>> np.squeeze(model.Ts) Field([-5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5.]) """ if isinstance(value, Field): # populate domains dictionary with domains from state variables self.domains.update({name: value.domain}) else: try: thisdom = self.state[name].domain domshape = thisdom.shape except: raise ValueError('State variable needs a domain.') value = np.atleast_1d(value) if value.shape == domshape: value = Field(value, domain=thisdom) else: raise ValueError('Shape mismatch between existing domain and new state variable.') # set the state dictionary self.state[name] = value for name, value in self.state.items(): #convert int dtype to float if np.issubdtype(self.state[name].dtype, np.dtype('int').type): value = self.state[name].astype(float) self.state[name]=value self.__setattr__(name, value)
python
def set_state(self, name, value): """Sets the variable ``name`` to a new state ``value``. :param string name: name of the state :param value: state variable :type value: :class:`~climlab.domain.field.Field` or *array* :raises: :exc:`ValueError` if state variable ``value`` is not having a domain. :raises: :exc:`ValueError` if shape mismatch between existing domain and new state variable. :Example: Resetting the surface temperature of an EBM to :math:`-5 ^{\circ} \\textrm{C}` on all latitues:: >>> import climlab >>> from climlab import Field >>> import numpy as np >>> # setup model >>> model = climlab.EBM(num_lat=36) >>> # create new temperature distribution >>> initial = -5 * ones(size(model.lat)) >>> model.set_state('Ts', Field(initial, domain=model.domains['Ts'])) >>> np.squeeze(model.Ts) Field([-5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5.]) """ if isinstance(value, Field): # populate domains dictionary with domains from state variables self.domains.update({name: value.domain}) else: try: thisdom = self.state[name].domain domshape = thisdom.shape except: raise ValueError('State variable needs a domain.') value = np.atleast_1d(value) if value.shape == domshape: value = Field(value, domain=thisdom) else: raise ValueError('Shape mismatch between existing domain and new state variable.') # set the state dictionary self.state[name] = value for name, value in self.state.items(): #convert int dtype to float if np.issubdtype(self.state[name].dtype, np.dtype('int').type): value = self.state[name].astype(float) self.state[name]=value self.__setattr__(name, value)
[ "def", "set_state", "(", "self", ",", "name", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Field", ")", ":", "# populate domains dictionary with domains from state variables", "self", ".", "domains", ".", "update", "(", "{", "name", ":", "value", ".", "domain", "}", ")", "else", ":", "try", ":", "thisdom", "=", "self", ".", "state", "[", "name", "]", ".", "domain", "domshape", "=", "thisdom", ".", "shape", "except", ":", "raise", "ValueError", "(", "'State variable needs a domain.'", ")", "value", "=", "np", ".", "atleast_1d", "(", "value", ")", "if", "value", ".", "shape", "==", "domshape", ":", "value", "=", "Field", "(", "value", ",", "domain", "=", "thisdom", ")", "else", ":", "raise", "ValueError", "(", "'Shape mismatch between existing domain and new state variable.'", ")", "# set the state dictionary", "self", ".", "state", "[", "name", "]", "=", "value", "for", "name", ",", "value", "in", "self", ".", "state", ".", "items", "(", ")", ":", "#convert int dtype to float", "if", "np", ".", "issubdtype", "(", "self", ".", "state", "[", "name", "]", ".", "dtype", ",", "np", ".", "dtype", "(", "'int'", ")", ".", "type", ")", ":", "value", "=", "self", ".", "state", "[", "name", "]", ".", "astype", "(", "float", ")", "self", ".", "state", "[", "name", "]", "=", "value", "self", ".", "__setattr__", "(", "name", ",", "value", ")" ]
Sets the variable ``name`` to a new state ``value``. :param string name: name of the state :param value: state variable :type value: :class:`~climlab.domain.field.Field` or *array* :raises: :exc:`ValueError` if state variable ``value`` is not having a domain. :raises: :exc:`ValueError` if shape mismatch between existing domain and new state variable. :Example: Resetting the surface temperature of an EBM to :math:`-5 ^{\circ} \\textrm{C}` on all latitues:: >>> import climlab >>> from climlab import Field >>> import numpy as np >>> # setup model >>> model = climlab.EBM(num_lat=36) >>> # create new temperature distribution >>> initial = -5 * ones(size(model.lat)) >>> model.set_state('Ts', Field(initial, domain=model.domains['Ts'])) >>> np.squeeze(model.Ts) Field([-5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5., -5.])
[ "Sets", "the", "variable", "name", "to", "a", "new", "state", "value", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L332-L387
7,647
brian-rose/climlab
climlab/process/process.py
Process._add_field
def _add_field(self, field_type, name, value): """Adds a new field to a specified dictionary. The field is also added as a process attribute. field_type can be 'input', 'diagnostics' """ try: self.__getattribute__(field_type).update({name: value}) except: raise ValueError('Problem with field_type %s' %field_type) # Note that if process has attribute name, this will trigger The # setter method for that attribute self.__setattr__(name, value)
python
def _add_field(self, field_type, name, value): """Adds a new field to a specified dictionary. The field is also added as a process attribute. field_type can be 'input', 'diagnostics' """ try: self.__getattribute__(field_type).update({name: value}) except: raise ValueError('Problem with field_type %s' %field_type) # Note that if process has attribute name, this will trigger The # setter method for that attribute self.__setattr__(name, value)
[ "def", "_add_field", "(", "self", ",", "field_type", ",", "name", ",", "value", ")", ":", "try", ":", "self", ".", "__getattribute__", "(", "field_type", ")", ".", "update", "(", "{", "name", ":", "value", "}", ")", "except", ":", "raise", "ValueError", "(", "'Problem with field_type %s'", "%", "field_type", ")", "# Note that if process has attribute name, this will trigger The", "# setter method for that attribute", "self", ".", "__setattr__", "(", "name", ",", "value", ")" ]
Adds a new field to a specified dictionary. The field is also added as a process attribute. field_type can be 'input', 'diagnostics'
[ "Adds", "a", "new", "field", "to", "a", "specified", "dictionary", ".", "The", "field", "is", "also", "added", "as", "a", "process", "attribute", ".", "field_type", "can", "be", "input", "diagnostics" ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L396-L405
7,648
brian-rose/climlab
climlab/process/process.py
Process.add_diagnostic
def add_diagnostic(self, name, value=None): """Create a new diagnostic variable called ``name`` for this process and initialize it with the given ``value``. Quantity is accessible in two ways: * as a process attribute, i.e. ``proc.name`` * as a member of the diagnostics dictionary, i.e. ``proc.diagnostics['name']`` Use attribute method to set values, e.g. ```proc.name = value ``` :param str name: name of diagnostic quantity to be initialized :param array value: initial value for quantity [default: None] :Example: Add a diagnostic CO2 variable to an energy balance model:: >>> import climlab >>> model = climlab.EBM() >>> # initialize CO2 variable with value 280 ppm >>> model.add_diagnostic('CO2',280.) >>> # access variable directly or through diagnostic dictionary >>> model.CO2 280 >>> model.diagnostics.keys() ['ASR', 'CO2', 'net_radiation', 'icelat', 'OLR', 'albedo'] """ self._diag_vars.append(name) self.__setattr__(name, value)
python
def add_diagnostic(self, name, value=None): """Create a new diagnostic variable called ``name`` for this process and initialize it with the given ``value``. Quantity is accessible in two ways: * as a process attribute, i.e. ``proc.name`` * as a member of the diagnostics dictionary, i.e. ``proc.diagnostics['name']`` Use attribute method to set values, e.g. ```proc.name = value ``` :param str name: name of diagnostic quantity to be initialized :param array value: initial value for quantity [default: None] :Example: Add a diagnostic CO2 variable to an energy balance model:: >>> import climlab >>> model = climlab.EBM() >>> # initialize CO2 variable with value 280 ppm >>> model.add_diagnostic('CO2',280.) >>> # access variable directly or through diagnostic dictionary >>> model.CO2 280 >>> model.diagnostics.keys() ['ASR', 'CO2', 'net_radiation', 'icelat', 'OLR', 'albedo'] """ self._diag_vars.append(name) self.__setattr__(name, value)
[ "def", "add_diagnostic", "(", "self", ",", "name", ",", "value", "=", "None", ")", ":", "self", ".", "_diag_vars", ".", "append", "(", "name", ")", "self", ".", "__setattr__", "(", "name", ",", "value", ")" ]
Create a new diagnostic variable called ``name`` for this process and initialize it with the given ``value``. Quantity is accessible in two ways: * as a process attribute, i.e. ``proc.name`` * as a member of the diagnostics dictionary, i.e. ``proc.diagnostics['name']`` Use attribute method to set values, e.g. ```proc.name = value ``` :param str name: name of diagnostic quantity to be initialized :param array value: initial value for quantity [default: None] :Example: Add a diagnostic CO2 variable to an energy balance model:: >>> import climlab >>> model = climlab.EBM() >>> # initialize CO2 variable with value 280 ppm >>> model.add_diagnostic('CO2',280.) >>> # access variable directly or through diagnostic dictionary >>> model.CO2 280 >>> model.diagnostics.keys() ['ASR', 'CO2', 'net_radiation', 'icelat', 'OLR', 'albedo']
[ "Create", "a", "new", "diagnostic", "variable", "called", "name", "for", "this", "process", "and", "initialize", "it", "with", "the", "given", "value", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L407-L441
7,649
brian-rose/climlab
climlab/process/process.py
Process.add_input
def add_input(self, name, value=None): '''Create a new input variable called ``name`` for this process and initialize it with the given ``value``. Quantity is accessible in two ways: * as a process attribute, i.e. ``proc.name`` * as a member of the input dictionary, i.e. ``proc.input['name']`` Use attribute method to set values, e.g. ```proc.name = value ``` :param str name: name of diagnostic quantity to be initialized :param array value: initial value for quantity [default: None] ''' self._input_vars.append(name) self.__setattr__(name, value)
python
def add_input(self, name, value=None): '''Create a new input variable called ``name`` for this process and initialize it with the given ``value``. Quantity is accessible in two ways: * as a process attribute, i.e. ``proc.name`` * as a member of the input dictionary, i.e. ``proc.input['name']`` Use attribute method to set values, e.g. ```proc.name = value ``` :param str name: name of diagnostic quantity to be initialized :param array value: initial value for quantity [default: None] ''' self._input_vars.append(name) self.__setattr__(name, value)
[ "def", "add_input", "(", "self", ",", "name", ",", "value", "=", "None", ")", ":", "self", ".", "_input_vars", ".", "append", "(", "name", ")", "self", ".", "__setattr__", "(", "name", ",", "value", ")" ]
Create a new input variable called ``name`` for this process and initialize it with the given ``value``. Quantity is accessible in two ways: * as a process attribute, i.e. ``proc.name`` * as a member of the input dictionary, i.e. ``proc.input['name']`` Use attribute method to set values, e.g. ```proc.name = value ``` :param str name: name of diagnostic quantity to be initialized :param array value: initial value for quantity [default: None]
[ "Create", "a", "new", "input", "variable", "called", "name", "for", "this", "process", "and", "initialize", "it", "with", "the", "given", "value", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L443-L460
7,650
brian-rose/climlab
climlab/process/process.py
Process.remove_diagnostic
def remove_diagnostic(self, name): """ Removes a diagnostic from the ``process.diagnostic`` dictionary and also delete the associated process attribute. :param str name: name of diagnostic quantity to be removed :Example: Remove diagnostic variable 'icelat' from energy balance model:: >>> import climlab >>> model = climlab.EBM() >>> # display all diagnostic variables >>> model.diagnostics.keys() ['ASR', 'OLR', 'net_radiation', 'albedo', 'icelat'] >>> model.remove_diagnostic('icelat') >>> model.diagnostics.keys() ['ASR', 'OLR', 'net_radiation', 'albedo'] >>> # Watch out for subprocesses that may still want >>> # to access the diagnostic 'icelat' variable !!! """ #_ = self.diagnostics.pop(name) #delattr(type(self), name) try: delattr(self, name) self._diag_vars.remove(name) except: print('No diagnostic named {} was found.'.format(name))
python
def remove_diagnostic(self, name): """ Removes a diagnostic from the ``process.diagnostic`` dictionary and also delete the associated process attribute. :param str name: name of diagnostic quantity to be removed :Example: Remove diagnostic variable 'icelat' from energy balance model:: >>> import climlab >>> model = climlab.EBM() >>> # display all diagnostic variables >>> model.diagnostics.keys() ['ASR', 'OLR', 'net_radiation', 'albedo', 'icelat'] >>> model.remove_diagnostic('icelat') >>> model.diagnostics.keys() ['ASR', 'OLR', 'net_radiation', 'albedo'] >>> # Watch out for subprocesses that may still want >>> # to access the diagnostic 'icelat' variable !!! """ #_ = self.diagnostics.pop(name) #delattr(type(self), name) try: delattr(self, name) self._diag_vars.remove(name) except: print('No diagnostic named {} was found.'.format(name))
[ "def", "remove_diagnostic", "(", "self", ",", "name", ")", ":", "#_ = self.diagnostics.pop(name)", "#delattr(type(self), name)", "try", ":", "delattr", "(", "self", ",", "name", ")", "self", ".", "_diag_vars", ".", "remove", "(", "name", ")", "except", ":", "print", "(", "'No diagnostic named {} was found.'", ".", "format", "(", "name", ")", ")" ]
Removes a diagnostic from the ``process.diagnostic`` dictionary and also delete the associated process attribute. :param str name: name of diagnostic quantity to be removed :Example: Remove diagnostic variable 'icelat' from energy balance model:: >>> import climlab >>> model = climlab.EBM() >>> # display all diagnostic variables >>> model.diagnostics.keys() ['ASR', 'OLR', 'net_radiation', 'albedo', 'icelat'] >>> model.remove_diagnostic('icelat') >>> model.diagnostics.keys() ['ASR', 'OLR', 'net_radiation', 'albedo'] >>> # Watch out for subprocesses that may still want >>> # to access the diagnostic 'icelat' variable !!!
[ "Removes", "a", "diagnostic", "from", "the", "process", ".", "diagnostic", "dictionary", "and", "also", "delete", "the", "associated", "process", "attribute", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L472-L503
7,651
brian-rose/climlab
climlab/process/process.py
Process.to_xarray
def to_xarray(self, diagnostics=False): """ Convert process variables to ``xarray.Dataset`` format. With ``diagnostics=True``, both state and diagnostic variables are included. Otherwise just the state variables are included. Returns an ``xarray.Dataset`` object with all spatial axes, including 'bounds' axes indicating cell boundaries in each spatial dimension. :Example: Create a single column radiation model and view as ``xarray`` object:: >>> import climlab >>> state = climlab.column_state(num_lev=20) >>> model = climlab.radiation.RRTMG(state=state) >>> # display model state as xarray: >>> model.to_xarray() <xarray.Dataset> Dimensions: (depth: 1, depth_bounds: 2, lev: 20, lev_bounds: 21) Coordinates: * depth (depth) float64 0.5 * depth_bounds (depth_bounds) float64 0.0 1.0 * lev (lev) float64 25.0 75.0 125.0 175.0 225.0 275.0 325.0 ... * lev_bounds (lev_bounds) float64 0.0 50.0 100.0 150.0 200.0 250.0 ... Data variables: Ts (depth) float64 288.0 Tatm (lev) float64 200.0 204.1 208.2 212.3 216.4 220.5 224.6 ... >>> # take a single timestep to populate the diagnostic variables >>> model.step_forward() >>> # Now look at the full output in xarray format >>> model.to_xarray(diagnostics=True) <xarray.Dataset> Dimensions: (depth: 1, depth_bounds: 2, lev: 20, lev_bounds: 21) Coordinates: * depth (depth) float64 0.5 * depth_bounds (depth_bounds) float64 0.0 1.0 * lev (lev) float64 25.0 75.0 125.0 175.0 225.0 275.0 325.0 ... * lev_bounds (lev_bounds) float64 0.0 50.0 100.0 150.0 200.0 250.0 ... Data variables: Ts (depth) float64 288.7 Tatm (lev) float64 201.3 204.0 208.0 212.0 216.1 220.2 ... ASR (depth) float64 240.0 ASRcld (depth) float64 0.0 ASRclr (depth) float64 240.0 LW_flux_down (lev_bounds) float64 0.0 12.63 19.47 26.07 32.92 40.1 ... LW_flux_down_clr (lev_bounds) float64 0.0 12.63 19.47 26.07 32.92 40.1 ... LW_flux_net (lev_bounds) float64 240.1 231.2 227.6 224.1 220.5 ... LW_flux_net_clr (lev_bounds) float64 240.1 231.2 227.6 224.1 220.5 ... LW_flux_up (lev_bounds) float64 240.1 243.9 247.1 250.2 253.4 ... LW_flux_up_clr (lev_bounds) float64 240.1 243.9 247.1 250.2 253.4 ... LW_sfc (depth) float64 128.9 LW_sfc_clr (depth) float64 128.9 OLR (depth) float64 240.1 OLRcld (depth) float64 0.0 OLRclr (depth) float64 240.1 SW_flux_down (lev_bounds) float64 341.3 323.1 318.0 313.5 309.5 ... SW_flux_down_clr (lev_bounds) float64 341.3 323.1 318.0 313.5 309.5 ... SW_flux_net (lev_bounds) float64 240.0 223.3 220.2 217.9 215.9 ... SW_flux_net_clr (lev_bounds) float64 240.0 223.3 220.2 217.9 215.9 ... SW_flux_up (lev_bounds) float64 101.3 99.88 97.77 95.64 93.57 ... SW_flux_up_clr (lev_bounds) float64 101.3 99.88 97.77 95.64 93.57 ... SW_sfc (depth) float64 163.8 SW_sfc_clr (depth) float64 163.8 TdotLW (lev) float64 -1.502 -0.6148 -0.5813 -0.6173 -0.6426 ... TdotLW_clr (lev) float64 -1.502 -0.6148 -0.5813 -0.6173 -0.6426 ... TdotSW (lev) float64 2.821 0.5123 0.3936 0.3368 0.3174 0.3299 ... TdotSW_clr (lev) float64 2.821 0.5123 0.3936 0.3368 0.3174 0.3299 ... """ if diagnostics: dic = self.state.copy() dic.update(self.diagnostics) return state_to_xarray(dic) else: return state_to_xarray(self.state)
python
def to_xarray(self, diagnostics=False): """ Convert process variables to ``xarray.Dataset`` format. With ``diagnostics=True``, both state and diagnostic variables are included. Otherwise just the state variables are included. Returns an ``xarray.Dataset`` object with all spatial axes, including 'bounds' axes indicating cell boundaries in each spatial dimension. :Example: Create a single column radiation model and view as ``xarray`` object:: >>> import climlab >>> state = climlab.column_state(num_lev=20) >>> model = climlab.radiation.RRTMG(state=state) >>> # display model state as xarray: >>> model.to_xarray() <xarray.Dataset> Dimensions: (depth: 1, depth_bounds: 2, lev: 20, lev_bounds: 21) Coordinates: * depth (depth) float64 0.5 * depth_bounds (depth_bounds) float64 0.0 1.0 * lev (lev) float64 25.0 75.0 125.0 175.0 225.0 275.0 325.0 ... * lev_bounds (lev_bounds) float64 0.0 50.0 100.0 150.0 200.0 250.0 ... Data variables: Ts (depth) float64 288.0 Tatm (lev) float64 200.0 204.1 208.2 212.3 216.4 220.5 224.6 ... >>> # take a single timestep to populate the diagnostic variables >>> model.step_forward() >>> # Now look at the full output in xarray format >>> model.to_xarray(diagnostics=True) <xarray.Dataset> Dimensions: (depth: 1, depth_bounds: 2, lev: 20, lev_bounds: 21) Coordinates: * depth (depth) float64 0.5 * depth_bounds (depth_bounds) float64 0.0 1.0 * lev (lev) float64 25.0 75.0 125.0 175.0 225.0 275.0 325.0 ... * lev_bounds (lev_bounds) float64 0.0 50.0 100.0 150.0 200.0 250.0 ... Data variables: Ts (depth) float64 288.7 Tatm (lev) float64 201.3 204.0 208.0 212.0 216.1 220.2 ... ASR (depth) float64 240.0 ASRcld (depth) float64 0.0 ASRclr (depth) float64 240.0 LW_flux_down (lev_bounds) float64 0.0 12.63 19.47 26.07 32.92 40.1 ... LW_flux_down_clr (lev_bounds) float64 0.0 12.63 19.47 26.07 32.92 40.1 ... LW_flux_net (lev_bounds) float64 240.1 231.2 227.6 224.1 220.5 ... LW_flux_net_clr (lev_bounds) float64 240.1 231.2 227.6 224.1 220.5 ... LW_flux_up (lev_bounds) float64 240.1 243.9 247.1 250.2 253.4 ... LW_flux_up_clr (lev_bounds) float64 240.1 243.9 247.1 250.2 253.4 ... LW_sfc (depth) float64 128.9 LW_sfc_clr (depth) float64 128.9 OLR (depth) float64 240.1 OLRcld (depth) float64 0.0 OLRclr (depth) float64 240.1 SW_flux_down (lev_bounds) float64 341.3 323.1 318.0 313.5 309.5 ... SW_flux_down_clr (lev_bounds) float64 341.3 323.1 318.0 313.5 309.5 ... SW_flux_net (lev_bounds) float64 240.0 223.3 220.2 217.9 215.9 ... SW_flux_net_clr (lev_bounds) float64 240.0 223.3 220.2 217.9 215.9 ... SW_flux_up (lev_bounds) float64 101.3 99.88 97.77 95.64 93.57 ... SW_flux_up_clr (lev_bounds) float64 101.3 99.88 97.77 95.64 93.57 ... SW_sfc (depth) float64 163.8 SW_sfc_clr (depth) float64 163.8 TdotLW (lev) float64 -1.502 -0.6148 -0.5813 -0.6173 -0.6426 ... TdotLW_clr (lev) float64 -1.502 -0.6148 -0.5813 -0.6173 -0.6426 ... TdotSW (lev) float64 2.821 0.5123 0.3936 0.3368 0.3174 0.3299 ... TdotSW_clr (lev) float64 2.821 0.5123 0.3936 0.3368 0.3174 0.3299 ... """ if diagnostics: dic = self.state.copy() dic.update(self.diagnostics) return state_to_xarray(dic) else: return state_to_xarray(self.state)
[ "def", "to_xarray", "(", "self", ",", "diagnostics", "=", "False", ")", ":", "if", "diagnostics", ":", "dic", "=", "self", ".", "state", ".", "copy", "(", ")", "dic", ".", "update", "(", "self", ".", "diagnostics", ")", "return", "state_to_xarray", "(", "dic", ")", "else", ":", "return", "state_to_xarray", "(", "self", ".", "state", ")" ]
Convert process variables to ``xarray.Dataset`` format. With ``diagnostics=True``, both state and diagnostic variables are included. Otherwise just the state variables are included. Returns an ``xarray.Dataset`` object with all spatial axes, including 'bounds' axes indicating cell boundaries in each spatial dimension. :Example: Create a single column radiation model and view as ``xarray`` object:: >>> import climlab >>> state = climlab.column_state(num_lev=20) >>> model = climlab.radiation.RRTMG(state=state) >>> # display model state as xarray: >>> model.to_xarray() <xarray.Dataset> Dimensions: (depth: 1, depth_bounds: 2, lev: 20, lev_bounds: 21) Coordinates: * depth (depth) float64 0.5 * depth_bounds (depth_bounds) float64 0.0 1.0 * lev (lev) float64 25.0 75.0 125.0 175.0 225.0 275.0 325.0 ... * lev_bounds (lev_bounds) float64 0.0 50.0 100.0 150.0 200.0 250.0 ... Data variables: Ts (depth) float64 288.0 Tatm (lev) float64 200.0 204.1 208.2 212.3 216.4 220.5 224.6 ... >>> # take a single timestep to populate the diagnostic variables >>> model.step_forward() >>> # Now look at the full output in xarray format >>> model.to_xarray(diagnostics=True) <xarray.Dataset> Dimensions: (depth: 1, depth_bounds: 2, lev: 20, lev_bounds: 21) Coordinates: * depth (depth) float64 0.5 * depth_bounds (depth_bounds) float64 0.0 1.0 * lev (lev) float64 25.0 75.0 125.0 175.0 225.0 275.0 325.0 ... * lev_bounds (lev_bounds) float64 0.0 50.0 100.0 150.0 200.0 250.0 ... Data variables: Ts (depth) float64 288.7 Tatm (lev) float64 201.3 204.0 208.0 212.0 216.1 220.2 ... ASR (depth) float64 240.0 ASRcld (depth) float64 0.0 ASRclr (depth) float64 240.0 LW_flux_down (lev_bounds) float64 0.0 12.63 19.47 26.07 32.92 40.1 ... LW_flux_down_clr (lev_bounds) float64 0.0 12.63 19.47 26.07 32.92 40.1 ... LW_flux_net (lev_bounds) float64 240.1 231.2 227.6 224.1 220.5 ... LW_flux_net_clr (lev_bounds) float64 240.1 231.2 227.6 224.1 220.5 ... LW_flux_up (lev_bounds) float64 240.1 243.9 247.1 250.2 253.4 ... LW_flux_up_clr (lev_bounds) float64 240.1 243.9 247.1 250.2 253.4 ... LW_sfc (depth) float64 128.9 LW_sfc_clr (depth) float64 128.9 OLR (depth) float64 240.1 OLRcld (depth) float64 0.0 OLRclr (depth) float64 240.1 SW_flux_down (lev_bounds) float64 341.3 323.1 318.0 313.5 309.5 ... SW_flux_down_clr (lev_bounds) float64 341.3 323.1 318.0 313.5 309.5 ... SW_flux_net (lev_bounds) float64 240.0 223.3 220.2 217.9 215.9 ... SW_flux_net_clr (lev_bounds) float64 240.0 223.3 220.2 217.9 215.9 ... SW_flux_up (lev_bounds) float64 101.3 99.88 97.77 95.64 93.57 ... SW_flux_up_clr (lev_bounds) float64 101.3 99.88 97.77 95.64 93.57 ... SW_sfc (depth) float64 163.8 SW_sfc_clr (depth) float64 163.8 TdotLW (lev) float64 -1.502 -0.6148 -0.5813 -0.6173 -0.6426 ... TdotLW_clr (lev) float64 -1.502 -0.6148 -0.5813 -0.6173 -0.6426 ... TdotSW (lev) float64 2.821 0.5123 0.3936 0.3368 0.3174 0.3299 ... TdotSW_clr (lev) float64 2.821 0.5123 0.3936 0.3368 0.3174 0.3299 ...
[ "Convert", "process", "variables", "to", "xarray", ".", "Dataset", "format", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L505-L583
7,652
brian-rose/climlab
climlab/process/process.py
Process.diagnostics
def diagnostics(self): """Dictionary access to all diagnostic variables :type: dict """ diag_dict = {} for key in self._diag_vars: try: #diag_dict[key] = getattr(self,key) # using self.__dict__ doesn't count diagnostics defined as properties diag_dict[key] = self.__dict__[key] except: pass return diag_dict
python
def diagnostics(self): """Dictionary access to all diagnostic variables :type: dict """ diag_dict = {} for key in self._diag_vars: try: #diag_dict[key] = getattr(self,key) # using self.__dict__ doesn't count diagnostics defined as properties diag_dict[key] = self.__dict__[key] except: pass return diag_dict
[ "def", "diagnostics", "(", "self", ")", ":", "diag_dict", "=", "{", "}", "for", "key", "in", "self", ".", "_diag_vars", ":", "try", ":", "#diag_dict[key] = getattr(self,key)", "# using self.__dict__ doesn't count diagnostics defined as properties", "diag_dict", "[", "key", "]", "=", "self", ".", "__dict__", "[", "key", "]", "except", ":", "pass", "return", "diag_dict" ]
Dictionary access to all diagnostic variables :type: dict
[ "Dictionary", "access", "to", "all", "diagnostic", "variables" ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L586-L600
7,653
brian-rose/climlab
climlab/process/process.py
Process.input
def input(self): """Dictionary access to all input variables That can be boundary conditions and other gridded quantities independent of the `process` :type: dict """ input_dict = {} for key in self._input_vars: try: input_dict[key] = getattr(self,key) except: pass return input_dict
python
def input(self): """Dictionary access to all input variables That can be boundary conditions and other gridded quantities independent of the `process` :type: dict """ input_dict = {} for key in self._input_vars: try: input_dict[key] = getattr(self,key) except: pass return input_dict
[ "def", "input", "(", "self", ")", ":", "input_dict", "=", "{", "}", "for", "key", "in", "self", ".", "_input_vars", ":", "try", ":", "input_dict", "[", "key", "]", "=", "getattr", "(", "self", ",", "key", ")", "except", ":", "pass", "return", "input_dict" ]
Dictionary access to all input variables That can be boundary conditions and other gridded quantities independent of the `process` :type: dict
[ "Dictionary", "access", "to", "all", "input", "variables" ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L602-L617
7,654
brian-rose/climlab
climlab/solar/orbital/table.py
_get_Berger_data
def _get_Berger_data(verbose=True): '''Read in the Berger and Loutre orbital table as a pandas dataframe, convert to xarray ''' # The first column of the data file is used as the row index, and represents kyr from present orbit91_pd, path = load_data_source(local_path = local_path, remote_source_list = [threddspath, NCDCpath], open_method = pd.read_csv, open_method_kwargs = {'delim_whitespace': True, 'skiprows':1}, verbose=verbose,) # As xarray structure with the dimension named 'kyear' orbit = xr.Dataset(orbit91_pd).rename({'dim_0': 'kyear'}) # Now change names orbit = orbit.rename({'ECC': 'ecc', 'OMEGA': 'long_peri', 'OBL': 'obliquity', 'PREC': 'precession'}) # add 180 degrees to long_peri (see lambda definition, Berger 1978 Appendix) orbit['long_peri'] += 180. orbit['precession'] *= -1. orbit.attrs['Description'] = 'The Berger and Loutre (1991) orbital data table' orbit.attrs['Citation'] = 'https://doi.org/10.1016/0277-3791(91)90033-Q' orbit.attrs['Source'] = path orbit.attrs['Note'] = 'Longitude of perihelion is defined to be 0 degrees at Northern Vernal Equinox. This differs by 180 degrees from orbit91 source file.' return orbit
python
def _get_Berger_data(verbose=True): '''Read in the Berger and Loutre orbital table as a pandas dataframe, convert to xarray ''' # The first column of the data file is used as the row index, and represents kyr from present orbit91_pd, path = load_data_source(local_path = local_path, remote_source_list = [threddspath, NCDCpath], open_method = pd.read_csv, open_method_kwargs = {'delim_whitespace': True, 'skiprows':1}, verbose=verbose,) # As xarray structure with the dimension named 'kyear' orbit = xr.Dataset(orbit91_pd).rename({'dim_0': 'kyear'}) # Now change names orbit = orbit.rename({'ECC': 'ecc', 'OMEGA': 'long_peri', 'OBL': 'obliquity', 'PREC': 'precession'}) # add 180 degrees to long_peri (see lambda definition, Berger 1978 Appendix) orbit['long_peri'] += 180. orbit['precession'] *= -1. orbit.attrs['Description'] = 'The Berger and Loutre (1991) orbital data table' orbit.attrs['Citation'] = 'https://doi.org/10.1016/0277-3791(91)90033-Q' orbit.attrs['Source'] = path orbit.attrs['Note'] = 'Longitude of perihelion is defined to be 0 degrees at Northern Vernal Equinox. This differs by 180 degrees from orbit91 source file.' return orbit
[ "def", "_get_Berger_data", "(", "verbose", "=", "True", ")", ":", "# The first column of the data file is used as the row index, and represents kyr from present", "orbit91_pd", ",", "path", "=", "load_data_source", "(", "local_path", "=", "local_path", ",", "remote_source_list", "=", "[", "threddspath", ",", "NCDCpath", "]", ",", "open_method", "=", "pd", ".", "read_csv", ",", "open_method_kwargs", "=", "{", "'delim_whitespace'", ":", "True", ",", "'skiprows'", ":", "1", "}", ",", "verbose", "=", "verbose", ",", ")", "# As xarray structure with the dimension named 'kyear'", "orbit", "=", "xr", ".", "Dataset", "(", "orbit91_pd", ")", ".", "rename", "(", "{", "'dim_0'", ":", "'kyear'", "}", ")", "# Now change names", "orbit", "=", "orbit", ".", "rename", "(", "{", "'ECC'", ":", "'ecc'", ",", "'OMEGA'", ":", "'long_peri'", ",", "'OBL'", ":", "'obliquity'", ",", "'PREC'", ":", "'precession'", "}", ")", "# add 180 degrees to long_peri (see lambda definition, Berger 1978 Appendix)", "orbit", "[", "'long_peri'", "]", "+=", "180.", "orbit", "[", "'precession'", "]", "*=", "-", "1.", "orbit", ".", "attrs", "[", "'Description'", "]", "=", "'The Berger and Loutre (1991) orbital data table'", "orbit", ".", "attrs", "[", "'Citation'", "]", "=", "'https://doi.org/10.1016/0277-3791(91)90033-Q'", "orbit", ".", "attrs", "[", "'Source'", "]", "=", "path", "orbit", ".", "attrs", "[", "'Note'", "]", "=", "'Longitude of perihelion is defined to be 0 degrees at Northern Vernal Equinox. This differs by 180 degrees from orbit91 source file.'", "return", "orbit" ]
Read in the Berger and Loutre orbital table as a pandas dataframe, convert to xarray
[ "Read", "in", "the", "Berger", "and", "Loutre", "orbital", "table", "as", "a", "pandas", "dataframe", "convert", "to", "xarray" ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/solar/orbital/table.py#L14-L36
7,655
brian-rose/climlab
climlab/utils/data_source.py
load_data_source
def load_data_source(local_path, remote_source_list, open_method, open_method_kwargs=dict(), remote_kwargs=dict(), verbose=True): '''Flexible data retreiver to download and cache the data files locally. Usage example (this makes a local copy of the ozone data file): :Example: .. code-block:: python from climlab.utils.data_source import load_data_source from xarray import open_dataset ozonename = 'apeozone_cam3_5_54.nc' ozonepath = 'http://thredds.atmos.albany.edu:8080/thredds/fileServer/CLIMLAB/ozone/' + ozonename data, path = load_data_source(local_path=ozonename, remote_source_list=[ozonepath], open_method=open_dataset) print(data) The order of operations is 1. Try to read the data directly from ``local_path`` 2. If the file doesn't exist then iterate through ``remote_source_list``. Try to download and save the file to ``local_path`` using http request If that works then open the data from ``local_path``. 3. As a last resort, try to read the data remotely from URLs in ``remote_source_list`` In all cases the file is opened and read by the user-supplied ``open_method`` (e.g. ``xarray.open_dataset``), with additional keyword arguments supplied as a dictionary through ``open_method_kwargs``. These are passed straight through to ``open_method``. Additional keyword arguments in ``remote_kwargs`` are only passed to ``open_method`` in option 3 above (remote access, e.g. through OpenDAP) Quiet all output by passing ``verbose=False``. Returns: - ``data`` is the data object returned by the successful call to ``open_method`` - ``path`` is the path that resulted in a successful call to ``open_method``. ''' try: path = local_path data = open_method(path, **open_method_kwargs) if verbose: print('Opened data from {}'.format(path)) #except FileNotFoundError: # this is a more specific exception in Python 3 except IOError: # works for Py2.7 and Py3.x # First try to load from remote sources and cache the file locally for source in remote_source_list: try: response = _download_and_cache(source, local_path) data = open_method(local_path, **open_method_kwargs) if verbose: print('Data retrieved from {} and saved locally.'.format(source)) break except Exception: continue else: # as a final resort, try opening the source remotely for source in remote_source_list: path = source try: # This works fine for Python >= 3.5 #data = open_method(path, **open_method_kwargs, **remote_kwargs) data = open_method(path, **merge_two_dicts(open_method_kwargs, remote_kwargs)) if verbose: print('Opened data remotely from {}'.format(source)) break except Exception: continue else: raise Exception('All data access methods have failed.') return data, path
python
def load_data_source(local_path, remote_source_list, open_method, open_method_kwargs=dict(), remote_kwargs=dict(), verbose=True): '''Flexible data retreiver to download and cache the data files locally. Usage example (this makes a local copy of the ozone data file): :Example: .. code-block:: python from climlab.utils.data_source import load_data_source from xarray import open_dataset ozonename = 'apeozone_cam3_5_54.nc' ozonepath = 'http://thredds.atmos.albany.edu:8080/thredds/fileServer/CLIMLAB/ozone/' + ozonename data, path = load_data_source(local_path=ozonename, remote_source_list=[ozonepath], open_method=open_dataset) print(data) The order of operations is 1. Try to read the data directly from ``local_path`` 2. If the file doesn't exist then iterate through ``remote_source_list``. Try to download and save the file to ``local_path`` using http request If that works then open the data from ``local_path``. 3. As a last resort, try to read the data remotely from URLs in ``remote_source_list`` In all cases the file is opened and read by the user-supplied ``open_method`` (e.g. ``xarray.open_dataset``), with additional keyword arguments supplied as a dictionary through ``open_method_kwargs``. These are passed straight through to ``open_method``. Additional keyword arguments in ``remote_kwargs`` are only passed to ``open_method`` in option 3 above (remote access, e.g. through OpenDAP) Quiet all output by passing ``verbose=False``. Returns: - ``data`` is the data object returned by the successful call to ``open_method`` - ``path`` is the path that resulted in a successful call to ``open_method``. ''' try: path = local_path data = open_method(path, **open_method_kwargs) if verbose: print('Opened data from {}'.format(path)) #except FileNotFoundError: # this is a more specific exception in Python 3 except IOError: # works for Py2.7 and Py3.x # First try to load from remote sources and cache the file locally for source in remote_source_list: try: response = _download_and_cache(source, local_path) data = open_method(local_path, **open_method_kwargs) if verbose: print('Data retrieved from {} and saved locally.'.format(source)) break except Exception: continue else: # as a final resort, try opening the source remotely for source in remote_source_list: path = source try: # This works fine for Python >= 3.5 #data = open_method(path, **open_method_kwargs, **remote_kwargs) data = open_method(path, **merge_two_dicts(open_method_kwargs, remote_kwargs)) if verbose: print('Opened data remotely from {}'.format(source)) break except Exception: continue else: raise Exception('All data access methods have failed.') return data, path
[ "def", "load_data_source", "(", "local_path", ",", "remote_source_list", ",", "open_method", ",", "open_method_kwargs", "=", "dict", "(", ")", ",", "remote_kwargs", "=", "dict", "(", ")", ",", "verbose", "=", "True", ")", ":", "try", ":", "path", "=", "local_path", "data", "=", "open_method", "(", "path", ",", "*", "*", "open_method_kwargs", ")", "if", "verbose", ":", "print", "(", "'Opened data from {}'", ".", "format", "(", "path", ")", ")", "#except FileNotFoundError: # this is a more specific exception in Python 3", "except", "IOError", ":", "# works for Py2.7 and Py3.x", "# First try to load from remote sources and cache the file locally", "for", "source", "in", "remote_source_list", ":", "try", ":", "response", "=", "_download_and_cache", "(", "source", ",", "local_path", ")", "data", "=", "open_method", "(", "local_path", ",", "*", "*", "open_method_kwargs", ")", "if", "verbose", ":", "print", "(", "'Data retrieved from {} and saved locally.'", ".", "format", "(", "source", ")", ")", "break", "except", "Exception", ":", "continue", "else", ":", "# as a final resort, try opening the source remotely", "for", "source", "in", "remote_source_list", ":", "path", "=", "source", "try", ":", "# This works fine for Python >= 3.5", "#data = open_method(path, **open_method_kwargs, **remote_kwargs)", "data", "=", "open_method", "(", "path", ",", "*", "*", "merge_two_dicts", "(", "open_method_kwargs", ",", "remote_kwargs", ")", ")", "if", "verbose", ":", "print", "(", "'Opened data remotely from {}'", ".", "format", "(", "source", ")", ")", "break", "except", "Exception", ":", "continue", "else", ":", "raise", "Exception", "(", "'All data access methods have failed.'", ")", "return", "data", ",", "path" ]
Flexible data retreiver to download and cache the data files locally. Usage example (this makes a local copy of the ozone data file): :Example: .. code-block:: python from climlab.utils.data_source import load_data_source from xarray import open_dataset ozonename = 'apeozone_cam3_5_54.nc' ozonepath = 'http://thredds.atmos.albany.edu:8080/thredds/fileServer/CLIMLAB/ozone/' + ozonename data, path = load_data_source(local_path=ozonename, remote_source_list=[ozonepath], open_method=open_dataset) print(data) The order of operations is 1. Try to read the data directly from ``local_path`` 2. If the file doesn't exist then iterate through ``remote_source_list``. Try to download and save the file to ``local_path`` using http request If that works then open the data from ``local_path``. 3. As a last resort, try to read the data remotely from URLs in ``remote_source_list`` In all cases the file is opened and read by the user-supplied ``open_method`` (e.g. ``xarray.open_dataset``), with additional keyword arguments supplied as a dictionary through ``open_method_kwargs``. These are passed straight through to ``open_method``. Additional keyword arguments in ``remote_kwargs`` are only passed to ``open_method`` in option 3 above (remote access, e.g. through OpenDAP) Quiet all output by passing ``verbose=False``. Returns: - ``data`` is the data object returned by the successful call to ``open_method`` - ``path`` is the path that resulted in a successful call to ``open_method``.
[ "Flexible", "data", "retreiver", "to", "download", "and", "cache", "the", "data", "files", "locally", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/utils/data_source.py#L4-L84
7,656
brian-rose/climlab
climlab/radiation/transmissivity.py
tril
def tril(array, k=0): '''Lower triangle of an array. Return a copy of an array with elements above the k-th diagonal zeroed. Need a multi-dimensional version here because numpy.tril does not broadcast for numpy verison < 1.9.''' try: tril_array = np.tril(array, k=k) except: # have to loop tril_array = np.zeros_like(array) shape = array.shape otherdims = shape[:-2] for index in np.ndindex(otherdims): tril_array[index] = np.tril(array[index], k=k) return tril_array
python
def tril(array, k=0): '''Lower triangle of an array. Return a copy of an array with elements above the k-th diagonal zeroed. Need a multi-dimensional version here because numpy.tril does not broadcast for numpy verison < 1.9.''' try: tril_array = np.tril(array, k=k) except: # have to loop tril_array = np.zeros_like(array) shape = array.shape otherdims = shape[:-2] for index in np.ndindex(otherdims): tril_array[index] = np.tril(array[index], k=k) return tril_array
[ "def", "tril", "(", "array", ",", "k", "=", "0", ")", ":", "try", ":", "tril_array", "=", "np", ".", "tril", "(", "array", ",", "k", "=", "k", ")", "except", ":", "# have to loop", "tril_array", "=", "np", ".", "zeros_like", "(", "array", ")", "shape", "=", "array", ".", "shape", "otherdims", "=", "shape", "[", ":", "-", "2", "]", "for", "index", "in", "np", ".", "ndindex", "(", "otherdims", ")", ":", "tril_array", "[", "index", "]", "=", "np", ".", "tril", "(", "array", "[", "index", "]", ",", "k", "=", "k", ")", "return", "tril_array" ]
Lower triangle of an array. Return a copy of an array with elements above the k-th diagonal zeroed. Need a multi-dimensional version here because numpy.tril does not broadcast for numpy verison < 1.9.
[ "Lower", "triangle", "of", "an", "array", ".", "Return", "a", "copy", "of", "an", "array", "with", "elements", "above", "the", "k", "-", "th", "diagonal", "zeroed", ".", "Need", "a", "multi", "-", "dimensional", "version", "here", "because", "numpy", ".", "tril", "does", "not", "broadcast", "for", "numpy", "verison", "<", "1", ".", "9", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/transmissivity.py#L209-L223
7,657
brian-rose/climlab
climlab/radiation/transmissivity.py
Transmissivity.flux_up
def flux_up(self, fluxUpBottom, emission=None): '''Compute downwelling radiative flux at interfaces between layers. Inputs: * fluxDownTop: flux down at top * emission: emission from atmospheric levels (N) defaults to zero if not given Returns: * vector of downwelling radiative flux between levels (N+1) element 0 is the flux down to the surface. ''' if emission is None: emission = np.zeros_like(self.absorptivity) E = np.concatenate((emission, np.atleast_1d(fluxUpBottom)), axis=-1) # dot product (matrix multiplication) along last axes return np.squeeze(matrix_multiply(self.Tup, E[..., np.newaxis]))
python
def flux_up(self, fluxUpBottom, emission=None): '''Compute downwelling radiative flux at interfaces between layers. Inputs: * fluxDownTop: flux down at top * emission: emission from atmospheric levels (N) defaults to zero if not given Returns: * vector of downwelling radiative flux between levels (N+1) element 0 is the flux down to the surface. ''' if emission is None: emission = np.zeros_like(self.absorptivity) E = np.concatenate((emission, np.atleast_1d(fluxUpBottom)), axis=-1) # dot product (matrix multiplication) along last axes return np.squeeze(matrix_multiply(self.Tup, E[..., np.newaxis]))
[ "def", "flux_up", "(", "self", ",", "fluxUpBottom", ",", "emission", "=", "None", ")", ":", "if", "emission", "is", "None", ":", "emission", "=", "np", ".", "zeros_like", "(", "self", ".", "absorptivity", ")", "E", "=", "np", ".", "concatenate", "(", "(", "emission", ",", "np", ".", "atleast_1d", "(", "fluxUpBottom", ")", ")", ",", "axis", "=", "-", "1", ")", "# dot product (matrix multiplication) along last axes", "return", "np", ".", "squeeze", "(", "matrix_multiply", "(", "self", ".", "Tup", ",", "E", "[", "...", ",", "np", ".", "newaxis", "]", ")", ")" ]
Compute downwelling radiative flux at interfaces between layers. Inputs: * fluxDownTop: flux down at top * emission: emission from atmospheric levels (N) defaults to zero if not given Returns: * vector of downwelling radiative flux between levels (N+1) element 0 is the flux down to the surface.
[ "Compute", "downwelling", "radiative", "flux", "at", "interfaces", "between", "layers", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/transmissivity.py#L121-L140
7,658
brian-rose/climlab
climlab/radiation/transmissivity.py
Transmissivity.flux_down
def flux_down(self, fluxDownTop, emission=None): '''Compute upwelling radiative flux at interfaces between layers. Inputs: * fluxUpBottom: flux up from bottom * emission: emission from atmospheric levels (N) defaults to zero if not given Returns: * vector of upwelling radiative flux between levels (N+1) element N is the flux up to space. ''' if emission is None: emission = np.zeros_like(self.absorptivity) E = np.concatenate((np.atleast_1d(fluxDownTop),emission), axis=-1) # dot product (matrix multiplication) along last axes return np.squeeze(matrix_multiply(self.Tdown, E[..., np.newaxis]))
python
def flux_down(self, fluxDownTop, emission=None): '''Compute upwelling radiative flux at interfaces between layers. Inputs: * fluxUpBottom: flux up from bottom * emission: emission from atmospheric levels (N) defaults to zero if not given Returns: * vector of upwelling radiative flux between levels (N+1) element N is the flux up to space. ''' if emission is None: emission = np.zeros_like(self.absorptivity) E = np.concatenate((np.atleast_1d(fluxDownTop),emission), axis=-1) # dot product (matrix multiplication) along last axes return np.squeeze(matrix_multiply(self.Tdown, E[..., np.newaxis]))
[ "def", "flux_down", "(", "self", ",", "fluxDownTop", ",", "emission", "=", "None", ")", ":", "if", "emission", "is", "None", ":", "emission", "=", "np", ".", "zeros_like", "(", "self", ".", "absorptivity", ")", "E", "=", "np", ".", "concatenate", "(", "(", "np", ".", "atleast_1d", "(", "fluxDownTop", ")", ",", "emission", ")", ",", "axis", "=", "-", "1", ")", "# dot product (matrix multiplication) along last axes", "return", "np", ".", "squeeze", "(", "matrix_multiply", "(", "self", ".", "Tdown", ",", "E", "[", "...", ",", "np", ".", "newaxis", "]", ")", ")" ]
Compute upwelling radiative flux at interfaces between layers. Inputs: * fluxUpBottom: flux up from bottom * emission: emission from atmospheric levels (N) defaults to zero if not given Returns: * vector of upwelling radiative flux between levels (N+1) element N is the flux up to space.
[ "Compute", "upwelling", "radiative", "flux", "at", "interfaces", "between", "layers", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/transmissivity.py#L149-L167
7,659
brian-rose/climlab
climlab/radiation/rrtm/rrtmg_lw.py
RRTMG_LW._compute_heating_rates
def _compute_heating_rates(self): '''Prepare arguments and call the RRTGM_LW driver to calculate radiative fluxes and heating rates''' (ncol, nlay, icld, permuteseed, irng, idrv, cp, play, plev, tlay, tlev, tsfc, h2ovmr, o3vmr, co2vmr, ch4vmr, n2ovmr, o2vmr, cfc11vmr, cfc12vmr, cfc22vmr, ccl4vmr, emis, inflglw, iceflglw, liqflglw, cldfrac, ciwp, clwp, reic, relq, tauc, tauaer,) = self._prepare_lw_arguments() if icld == 0: # clear-sky only cldfmcl = np.zeros((ngptlw,ncol,nlay)) ciwpmcl = np.zeros((ngptlw,ncol,nlay)) clwpmcl = np.zeros((ngptlw,ncol,nlay)) reicmcl = np.zeros((ncol,nlay)) relqmcl = np.zeros((ncol,nlay)) taucmcl = np.zeros((ngptlw,ncol,nlay)) else: # Call the Monte Carlo Independent Column Approximation (McICA, Pincus et al., JC, 2003) (cldfmcl, ciwpmcl, clwpmcl, reicmcl, relqmcl, taucmcl) = \ _rrtmg_lw.climlab_mcica_subcol_lw( ncol, nlay, icld, permuteseed, irng, play, cldfrac, ciwp, clwp, reic, relq, tauc) # Call the RRTMG_LW driver to compute radiative fluxes (uflx, dflx, hr, uflxc, dflxc, hrc, duflx_dt, duflxc_dt) = \ _rrtmg_lw.climlab_rrtmg_lw(ncol, nlay, icld, idrv, play, plev, tlay, tlev, tsfc, h2ovmr, o3vmr, co2vmr, ch4vmr, n2ovmr, o2vmr, cfc11vmr, cfc12vmr, cfc22vmr, ccl4vmr, emis, inflglw, iceflglw, liqflglw, cldfmcl, taucmcl, ciwpmcl, clwpmcl, reicmcl, relqmcl, tauaer) # Output is all (ncol,nlay+1) or (ncol,nlay) self.LW_flux_up = _rrtm_to_climlab(uflx) + 0.*self.LW_flux_up self.LW_flux_down = _rrtm_to_climlab(dflx) + 0.*self.LW_flux_down self.LW_flux_up_clr = _rrtm_to_climlab(uflxc) + 0.*self.LW_flux_up_clr self.LW_flux_down_clr = _rrtm_to_climlab(dflxc) + 0.*self.LW_flux_down_clr # Compute quantities derived from fluxes, including OLR self._compute_LW_flux_diagnostics() # calculate heating rates from flux divergence LWheating_Wm2 = np.array(np.diff(self.LW_flux_net, axis=-1)) + 0.*self.Tatm LWheating_clr_Wm2 = np.array(np.diff(self.LW_flux_net_clr, axis=-1)) + 0.*self.Tatm self.heating_rate['Ts'] = np.array(-self.LW_flux_net[..., -1, np.newaxis]) + 0.*self.Ts self.heating_rate['Tatm'] = LWheating_Wm2 # Convert to K / day Catm = self.Tatm.domain.heat_capacity self.TdotLW = LWheating_Wm2 / Catm * const.seconds_per_day self.TdotLW_clr = LWheating_clr_Wm2 / Catm * const.seconds_per_day
python
def _compute_heating_rates(self): '''Prepare arguments and call the RRTGM_LW driver to calculate radiative fluxes and heating rates''' (ncol, nlay, icld, permuteseed, irng, idrv, cp, play, plev, tlay, tlev, tsfc, h2ovmr, o3vmr, co2vmr, ch4vmr, n2ovmr, o2vmr, cfc11vmr, cfc12vmr, cfc22vmr, ccl4vmr, emis, inflglw, iceflglw, liqflglw, cldfrac, ciwp, clwp, reic, relq, tauc, tauaer,) = self._prepare_lw_arguments() if icld == 0: # clear-sky only cldfmcl = np.zeros((ngptlw,ncol,nlay)) ciwpmcl = np.zeros((ngptlw,ncol,nlay)) clwpmcl = np.zeros((ngptlw,ncol,nlay)) reicmcl = np.zeros((ncol,nlay)) relqmcl = np.zeros((ncol,nlay)) taucmcl = np.zeros((ngptlw,ncol,nlay)) else: # Call the Monte Carlo Independent Column Approximation (McICA, Pincus et al., JC, 2003) (cldfmcl, ciwpmcl, clwpmcl, reicmcl, relqmcl, taucmcl) = \ _rrtmg_lw.climlab_mcica_subcol_lw( ncol, nlay, icld, permuteseed, irng, play, cldfrac, ciwp, clwp, reic, relq, tauc) # Call the RRTMG_LW driver to compute radiative fluxes (uflx, dflx, hr, uflxc, dflxc, hrc, duflx_dt, duflxc_dt) = \ _rrtmg_lw.climlab_rrtmg_lw(ncol, nlay, icld, idrv, play, plev, tlay, tlev, tsfc, h2ovmr, o3vmr, co2vmr, ch4vmr, n2ovmr, o2vmr, cfc11vmr, cfc12vmr, cfc22vmr, ccl4vmr, emis, inflglw, iceflglw, liqflglw, cldfmcl, taucmcl, ciwpmcl, clwpmcl, reicmcl, relqmcl, tauaer) # Output is all (ncol,nlay+1) or (ncol,nlay) self.LW_flux_up = _rrtm_to_climlab(uflx) + 0.*self.LW_flux_up self.LW_flux_down = _rrtm_to_climlab(dflx) + 0.*self.LW_flux_down self.LW_flux_up_clr = _rrtm_to_climlab(uflxc) + 0.*self.LW_flux_up_clr self.LW_flux_down_clr = _rrtm_to_climlab(dflxc) + 0.*self.LW_flux_down_clr # Compute quantities derived from fluxes, including OLR self._compute_LW_flux_diagnostics() # calculate heating rates from flux divergence LWheating_Wm2 = np.array(np.diff(self.LW_flux_net, axis=-1)) + 0.*self.Tatm LWheating_clr_Wm2 = np.array(np.diff(self.LW_flux_net_clr, axis=-1)) + 0.*self.Tatm self.heating_rate['Ts'] = np.array(-self.LW_flux_net[..., -1, np.newaxis]) + 0.*self.Ts self.heating_rate['Tatm'] = LWheating_Wm2 # Convert to K / day Catm = self.Tatm.domain.heat_capacity self.TdotLW = LWheating_Wm2 / Catm * const.seconds_per_day self.TdotLW_clr = LWheating_clr_Wm2 / Catm * const.seconds_per_day
[ "def", "_compute_heating_rates", "(", "self", ")", ":", "(", "ncol", ",", "nlay", ",", "icld", ",", "permuteseed", ",", "irng", ",", "idrv", ",", "cp", ",", "play", ",", "plev", ",", "tlay", ",", "tlev", ",", "tsfc", ",", "h2ovmr", ",", "o3vmr", ",", "co2vmr", ",", "ch4vmr", ",", "n2ovmr", ",", "o2vmr", ",", "cfc11vmr", ",", "cfc12vmr", ",", "cfc22vmr", ",", "ccl4vmr", ",", "emis", ",", "inflglw", ",", "iceflglw", ",", "liqflglw", ",", "cldfrac", ",", "ciwp", ",", "clwp", ",", "reic", ",", "relq", ",", "tauc", ",", "tauaer", ",", ")", "=", "self", ".", "_prepare_lw_arguments", "(", ")", "if", "icld", "==", "0", ":", "# clear-sky only", "cldfmcl", "=", "np", ".", "zeros", "(", "(", "ngptlw", ",", "ncol", ",", "nlay", ")", ")", "ciwpmcl", "=", "np", ".", "zeros", "(", "(", "ngptlw", ",", "ncol", ",", "nlay", ")", ")", "clwpmcl", "=", "np", ".", "zeros", "(", "(", "ngptlw", ",", "ncol", ",", "nlay", ")", ")", "reicmcl", "=", "np", ".", "zeros", "(", "(", "ncol", ",", "nlay", ")", ")", "relqmcl", "=", "np", ".", "zeros", "(", "(", "ncol", ",", "nlay", ")", ")", "taucmcl", "=", "np", ".", "zeros", "(", "(", "ngptlw", ",", "ncol", ",", "nlay", ")", ")", "else", ":", "# Call the Monte Carlo Independent Column Approximation (McICA, Pincus et al., JC, 2003)", "(", "cldfmcl", ",", "ciwpmcl", ",", "clwpmcl", ",", "reicmcl", ",", "relqmcl", ",", "taucmcl", ")", "=", "_rrtmg_lw", ".", "climlab_mcica_subcol_lw", "(", "ncol", ",", "nlay", ",", "icld", ",", "permuteseed", ",", "irng", ",", "play", ",", "cldfrac", ",", "ciwp", ",", "clwp", ",", "reic", ",", "relq", ",", "tauc", ")", "# Call the RRTMG_LW driver to compute radiative fluxes", "(", "uflx", ",", "dflx", ",", "hr", ",", "uflxc", ",", "dflxc", ",", "hrc", ",", "duflx_dt", ",", "duflxc_dt", ")", "=", "_rrtmg_lw", ".", "climlab_rrtmg_lw", "(", "ncol", ",", "nlay", ",", "icld", ",", "idrv", ",", "play", ",", "plev", ",", "tlay", ",", "tlev", ",", "tsfc", ",", "h2ovmr", ",", "o3vmr", ",", "co2vmr", ",", "ch4vmr", ",", "n2ovmr", ",", "o2vmr", ",", "cfc11vmr", ",", "cfc12vmr", ",", "cfc22vmr", ",", "ccl4vmr", ",", "emis", ",", "inflglw", ",", "iceflglw", ",", "liqflglw", ",", "cldfmcl", ",", "taucmcl", ",", "ciwpmcl", ",", "clwpmcl", ",", "reicmcl", ",", "relqmcl", ",", "tauaer", ")", "# Output is all (ncol,nlay+1) or (ncol,nlay)", "self", ".", "LW_flux_up", "=", "_rrtm_to_climlab", "(", "uflx", ")", "+", "0.", "*", "self", ".", "LW_flux_up", "self", ".", "LW_flux_down", "=", "_rrtm_to_climlab", "(", "dflx", ")", "+", "0.", "*", "self", ".", "LW_flux_down", "self", ".", "LW_flux_up_clr", "=", "_rrtm_to_climlab", "(", "uflxc", ")", "+", "0.", "*", "self", ".", "LW_flux_up_clr", "self", ".", "LW_flux_down_clr", "=", "_rrtm_to_climlab", "(", "dflxc", ")", "+", "0.", "*", "self", ".", "LW_flux_down_clr", "# Compute quantities derived from fluxes, including OLR", "self", ".", "_compute_LW_flux_diagnostics", "(", ")", "# calculate heating rates from flux divergence", "LWheating_Wm2", "=", "np", ".", "array", "(", "np", ".", "diff", "(", "self", ".", "LW_flux_net", ",", "axis", "=", "-", "1", ")", ")", "+", "0.", "*", "self", ".", "Tatm", "LWheating_clr_Wm2", "=", "np", ".", "array", "(", "np", ".", "diff", "(", "self", ".", "LW_flux_net_clr", ",", "axis", "=", "-", "1", ")", ")", "+", "0.", "*", "self", ".", "Tatm", "self", ".", "heating_rate", "[", "'Ts'", "]", "=", "np", ".", "array", "(", "-", "self", ".", "LW_flux_net", "[", "...", ",", "-", "1", ",", "np", ".", "newaxis", "]", ")", "+", "0.", "*", "self", ".", "Ts", "self", ".", "heating_rate", "[", "'Tatm'", "]", "=", "LWheating_Wm2", "# Convert to K / day", "Catm", "=", "self", ".", "Tatm", ".", "domain", ".", "heat_capacity", "self", ".", "TdotLW", "=", "LWheating_Wm2", "/", "Catm", "*", "const", ".", "seconds_per_day", "self", ".", "TdotLW_clr", "=", "LWheating_clr_Wm2", "/", "Catm", "*", "const", ".", "seconds_per_day" ]
Prepare arguments and call the RRTGM_LW driver to calculate radiative fluxes and heating rates
[ "Prepare", "arguments", "and", "call", "the", "RRTGM_LW", "driver", "to", "calculate", "radiative", "fluxes", "and", "heating", "rates" ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/rrtm/rrtmg_lw.py#L79-L126
7,660
brian-rose/climlab
climlab/radiation/rrtm/utils.py
_prepare_general_arguments
def _prepare_general_arguments(RRTMGobject): '''Prepare arguments needed for both RRTMG_SW and RRTMG_LW with correct dimensions.''' tlay = _climlab_to_rrtm(RRTMGobject.Tatm) tlev = _climlab_to_rrtm(interface_temperature(**RRTMGobject.state)) play = _climlab_to_rrtm(RRTMGobject.lev * np.ones_like(tlay)) plev = _climlab_to_rrtm(RRTMGobject.lev_bounds * np.ones_like(tlev)) ncol, nlay = tlay.shape tsfc = _climlab_to_rrtm_sfc(RRTMGobject.Ts, RRTMGobject.Ts) # GASES -- put them in proper dimensions and units vapor_mixing_ratio = mmr_to_vmr(RRTMGobject.specific_humidity, gas='H2O') h2ovmr = _climlab_to_rrtm(vapor_mixing_ratio * np.ones_like(RRTMGobject.Tatm)) o3vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['O3'] * np.ones_like(RRTMGobject.Tatm)) co2vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['CO2'] * np.ones_like(RRTMGobject.Tatm)) ch4vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['CH4'] * np.ones_like(RRTMGobject.Tatm)) n2ovmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['N2O'] * np.ones_like(RRTMGobject.Tatm)) o2vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['O2'] * np.ones_like(RRTMGobject.Tatm)) cfc11vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['CFC11'] * np.ones_like(RRTMGobject.Tatm)) cfc12vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['CFC12'] * np.ones_like(RRTMGobject.Tatm)) cfc22vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['CFC22'] * np.ones_like(RRTMGobject.Tatm)) ccl4vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['CCL4'] * np.ones_like(RRTMGobject.Tatm)) # Cloud parameters cldfrac = _climlab_to_rrtm(RRTMGobject.cldfrac * np.ones_like(RRTMGobject.Tatm)) ciwp = _climlab_to_rrtm(RRTMGobject.ciwp * np.ones_like(RRTMGobject.Tatm)) clwp = _climlab_to_rrtm(RRTMGobject.clwp * np.ones_like(RRTMGobject.Tatm)) relq = _climlab_to_rrtm(RRTMGobject.r_liq * np.ones_like(RRTMGobject.Tatm)) reic = _climlab_to_rrtm(RRTMGobject.r_ice * np.ones_like(RRTMGobject.Tatm)) return (ncol, nlay, play, plev, tlay, tlev, tsfc, h2ovmr, o3vmr, co2vmr, ch4vmr, n2ovmr, o2vmr, cfc11vmr, cfc12vmr, cfc12vmr, cfc22vmr, ccl4vmr, cldfrac, ciwp, clwp, relq, reic)
python
def _prepare_general_arguments(RRTMGobject): '''Prepare arguments needed for both RRTMG_SW and RRTMG_LW with correct dimensions.''' tlay = _climlab_to_rrtm(RRTMGobject.Tatm) tlev = _climlab_to_rrtm(interface_temperature(**RRTMGobject.state)) play = _climlab_to_rrtm(RRTMGobject.lev * np.ones_like(tlay)) plev = _climlab_to_rrtm(RRTMGobject.lev_bounds * np.ones_like(tlev)) ncol, nlay = tlay.shape tsfc = _climlab_to_rrtm_sfc(RRTMGobject.Ts, RRTMGobject.Ts) # GASES -- put them in proper dimensions and units vapor_mixing_ratio = mmr_to_vmr(RRTMGobject.specific_humidity, gas='H2O') h2ovmr = _climlab_to_rrtm(vapor_mixing_ratio * np.ones_like(RRTMGobject.Tatm)) o3vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['O3'] * np.ones_like(RRTMGobject.Tatm)) co2vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['CO2'] * np.ones_like(RRTMGobject.Tatm)) ch4vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['CH4'] * np.ones_like(RRTMGobject.Tatm)) n2ovmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['N2O'] * np.ones_like(RRTMGobject.Tatm)) o2vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['O2'] * np.ones_like(RRTMGobject.Tatm)) cfc11vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['CFC11'] * np.ones_like(RRTMGobject.Tatm)) cfc12vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['CFC12'] * np.ones_like(RRTMGobject.Tatm)) cfc22vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['CFC22'] * np.ones_like(RRTMGobject.Tatm)) ccl4vmr = _climlab_to_rrtm(RRTMGobject.absorber_vmr['CCL4'] * np.ones_like(RRTMGobject.Tatm)) # Cloud parameters cldfrac = _climlab_to_rrtm(RRTMGobject.cldfrac * np.ones_like(RRTMGobject.Tatm)) ciwp = _climlab_to_rrtm(RRTMGobject.ciwp * np.ones_like(RRTMGobject.Tatm)) clwp = _climlab_to_rrtm(RRTMGobject.clwp * np.ones_like(RRTMGobject.Tatm)) relq = _climlab_to_rrtm(RRTMGobject.r_liq * np.ones_like(RRTMGobject.Tatm)) reic = _climlab_to_rrtm(RRTMGobject.r_ice * np.ones_like(RRTMGobject.Tatm)) return (ncol, nlay, play, plev, tlay, tlev, tsfc, h2ovmr, o3vmr, co2vmr, ch4vmr, n2ovmr, o2vmr, cfc11vmr, cfc12vmr, cfc12vmr, cfc22vmr, ccl4vmr, cldfrac, ciwp, clwp, relq, reic)
[ "def", "_prepare_general_arguments", "(", "RRTMGobject", ")", ":", "tlay", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "Tatm", ")", "tlev", "=", "_climlab_to_rrtm", "(", "interface_temperature", "(", "*", "*", "RRTMGobject", ".", "state", ")", ")", "play", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "lev", "*", "np", ".", "ones_like", "(", "tlay", ")", ")", "plev", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "lev_bounds", "*", "np", ".", "ones_like", "(", "tlev", ")", ")", "ncol", ",", "nlay", "=", "tlay", ".", "shape", "tsfc", "=", "_climlab_to_rrtm_sfc", "(", "RRTMGobject", ".", "Ts", ",", "RRTMGobject", ".", "Ts", ")", "# GASES -- put them in proper dimensions and units", "vapor_mixing_ratio", "=", "mmr_to_vmr", "(", "RRTMGobject", ".", "specific_humidity", ",", "gas", "=", "'H2O'", ")", "h2ovmr", "=", "_climlab_to_rrtm", "(", "vapor_mixing_ratio", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "o3vmr", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "absorber_vmr", "[", "'O3'", "]", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "co2vmr", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "absorber_vmr", "[", "'CO2'", "]", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "ch4vmr", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "absorber_vmr", "[", "'CH4'", "]", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "n2ovmr", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "absorber_vmr", "[", "'N2O'", "]", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "o2vmr", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "absorber_vmr", "[", "'O2'", "]", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "cfc11vmr", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "absorber_vmr", "[", "'CFC11'", "]", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "cfc12vmr", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "absorber_vmr", "[", "'CFC12'", "]", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "cfc22vmr", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "absorber_vmr", "[", "'CFC22'", "]", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "ccl4vmr", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "absorber_vmr", "[", "'CCL4'", "]", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "# Cloud parameters", "cldfrac", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "cldfrac", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "ciwp", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "ciwp", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "clwp", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "clwp", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "relq", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "r_liq", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "reic", "=", "_climlab_to_rrtm", "(", "RRTMGobject", ".", "r_ice", "*", "np", ".", "ones_like", "(", "RRTMGobject", ".", "Tatm", ")", ")", "return", "(", "ncol", ",", "nlay", ",", "play", ",", "plev", ",", "tlay", ",", "tlev", ",", "tsfc", ",", "h2ovmr", ",", "o3vmr", ",", "co2vmr", ",", "ch4vmr", ",", "n2ovmr", ",", "o2vmr", ",", "cfc11vmr", ",", "cfc12vmr", ",", "cfc12vmr", ",", "cfc22vmr", ",", "ccl4vmr", ",", "cldfrac", ",", "ciwp", ",", "clwp", ",", "relq", ",", "reic", ")" ]
Prepare arguments needed for both RRTMG_SW and RRTMG_LW with correct dimensions.
[ "Prepare", "arguments", "needed", "for", "both", "RRTMG_SW", "and", "RRTMG_LW", "with", "correct", "dimensions", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/rrtm/utils.py#L7-L37
7,661
brian-rose/climlab
climlab/radiation/rrtm/utils.py
interface_temperature
def interface_temperature(Ts, Tatm, **kwargs): '''Compute temperature at model layer interfaces.''' # Actually it's not clear to me how the RRTM code uses these values lev = Tatm.domain.axes['lev'].points lev_bounds = Tatm.domain.axes['lev'].bounds # Interpolate to layer interfaces f = interp1d(lev, Tatm, axis=-1) # interpolation function Tinterp = f(lev_bounds[1:-1]) # add TOA value, Assume surface temperature at bottom boundary Ttoa = Tatm[...,0] Tinterp = np.concatenate((Ttoa[..., np.newaxis], Tinterp, Ts), axis=-1) return Tinterp
python
def interface_temperature(Ts, Tatm, **kwargs): '''Compute temperature at model layer interfaces.''' # Actually it's not clear to me how the RRTM code uses these values lev = Tatm.domain.axes['lev'].points lev_bounds = Tatm.domain.axes['lev'].bounds # Interpolate to layer interfaces f = interp1d(lev, Tatm, axis=-1) # interpolation function Tinterp = f(lev_bounds[1:-1]) # add TOA value, Assume surface temperature at bottom boundary Ttoa = Tatm[...,0] Tinterp = np.concatenate((Ttoa[..., np.newaxis], Tinterp, Ts), axis=-1) return Tinterp
[ "def", "interface_temperature", "(", "Ts", ",", "Tatm", ",", "*", "*", "kwargs", ")", ":", "# Actually it's not clear to me how the RRTM code uses these values", "lev", "=", "Tatm", ".", "domain", ".", "axes", "[", "'lev'", "]", ".", "points", "lev_bounds", "=", "Tatm", ".", "domain", ".", "axes", "[", "'lev'", "]", ".", "bounds", "# Interpolate to layer interfaces", "f", "=", "interp1d", "(", "lev", ",", "Tatm", ",", "axis", "=", "-", "1", ")", "# interpolation function", "Tinterp", "=", "f", "(", "lev_bounds", "[", "1", ":", "-", "1", "]", ")", "# add TOA value, Assume surface temperature at bottom boundary", "Ttoa", "=", "Tatm", "[", "...", ",", "0", "]", "Tinterp", "=", "np", ".", "concatenate", "(", "(", "Ttoa", "[", "...", ",", "np", ".", "newaxis", "]", ",", "Tinterp", ",", "Ts", ")", ",", "axis", "=", "-", "1", ")", "return", "Tinterp" ]
Compute temperature at model layer interfaces.
[ "Compute", "temperature", "at", "model", "layer", "interfaces", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/rrtm/utils.py#L41-L52
7,662
brian-rose/climlab
climlab/dynamics/meridional_moist_diffusion.py
moist_amplification_factor
def moist_amplification_factor(Tkelvin, relative_humidity=0.8): '''Compute the moisture amplification factor for the moist diffusivity given relative humidity and reference temperature profile.''' deltaT = 0.01 # slope of saturation specific humidity at 1000 hPa dqsdTs = (qsat(Tkelvin+deltaT/2, 1000.) - qsat(Tkelvin-deltaT/2, 1000.)) / deltaT return const.Lhvap / const.cp * relative_humidity * dqsdTs
python
def moist_amplification_factor(Tkelvin, relative_humidity=0.8): '''Compute the moisture amplification factor for the moist diffusivity given relative humidity and reference temperature profile.''' deltaT = 0.01 # slope of saturation specific humidity at 1000 hPa dqsdTs = (qsat(Tkelvin+deltaT/2, 1000.) - qsat(Tkelvin-deltaT/2, 1000.)) / deltaT return const.Lhvap / const.cp * relative_humidity * dqsdTs
[ "def", "moist_amplification_factor", "(", "Tkelvin", ",", "relative_humidity", "=", "0.8", ")", ":", "deltaT", "=", "0.01", "# slope of saturation specific humidity at 1000 hPa", "dqsdTs", "=", "(", "qsat", "(", "Tkelvin", "+", "deltaT", "/", "2", ",", "1000.", ")", "-", "qsat", "(", "Tkelvin", "-", "deltaT", "/", "2", ",", "1000.", ")", ")", "/", "deltaT", "return", "const", ".", "Lhvap", "/", "const", ".", "cp", "*", "relative_humidity", "*", "dqsdTs" ]
Compute the moisture amplification factor for the moist diffusivity given relative humidity and reference temperature profile.
[ "Compute", "the", "moisture", "amplification", "factor", "for", "the", "moist", "diffusivity", "given", "relative", "humidity", "and", "reference", "temperature", "profile", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/dynamics/meridional_moist_diffusion.py#L145-L151
7,663
brian-rose/climlab
climlab/solar/insolation.py
daily_insolation
def daily_insolation(lat, day, orb=const.orb_present, S0=const.S0, day_type=1): """Compute daily average insolation given latitude, time of year and orbital parameters. Orbital parameters can be interpolated to any time in the last 5 Myears with ``climlab.solar.orbital.OrbitalTable`` (see example above). Longer orbital tables are available with ``climlab.solar.orbital.LongOrbitalTable`` Inputs can be scalar, ``numpy.ndarray``, or ``xarray.DataArray``. The return value will be ``numpy.ndarray`` if **all** the inputs are ``numpy``. Otherwise ``xarray.DataArray``. **Function-call argument** \n :param array lat: Latitude in degrees (-90 to 90). :param array day: Indicator of time of year. See argument ``day_type`` for details about format. :param dict orb: a dictionary with three members (as provided by ``climlab.solar.orbital.OrbitalTable``) * ``'ecc'`` - eccentricity * unit: dimensionless * default value: ``0.017236`` * ``'long_peri'`` - longitude of perihelion (precession angle) * unit: degrees * default value: ``281.37`` * ``'obliquity'`` - obliquity angle * unit: degrees * default value: ``23.446`` :param float S0: solar constant \n - unit: :math:`\\textrm{W}/\\textrm{m}^2` \n - default value: ``1365.2`` :param int day_type: Convention for specifying time of year (+/- 1,2) [optional]. *day_type=1* (default): day input is calendar day (1-365.24), where day 1 is January first. The calendar is referenced to the vernal equinox which always occurs at day 80. *day_type=2:* day input is solar longitude (0-360 degrees). Solar longitude is the angle of the Earth's orbit measured from spring equinox (21 March). Note that calendar days and solar longitude are not linearly related because, by Kepler's Second Law, Earth's angular velocity varies according to its distance from the sun. :raises: :exc:`ValueError` if day_type is neither 1 nor 2 :returns: Daily average solar radiation in unit :math:`\\textrm{W}/\\textrm{m}^2`. Dimensions of output are ``(lat.size, day.size, ecc.size)`` :rtype: array Code is fully vectorized to handle array input for all arguments. \n Orbital arguments should all have the same sizes. This is automatic if computed from :func:`~climlab.solar.orbital.OrbitalTable.lookup_parameters` For more information about computation of solar insolation see the :ref:`Tutorial` chapter. """ # Inputs can be scalar, numpy vector, or xarray.DataArray. # If numpy, convert to xarray so that it will broadcast correctly lat_is_xarray = True day_is_xarray = True if type(lat) is np.ndarray: lat_is_xarray = False lat = xr.DataArray(lat, coords=[lat], dims=['lat']) if type(day) is np.ndarray: day_is_xarray = False day = xr.DataArray(day, coords=[day], dims=['day']) ecc = orb['ecc'] long_peri = orb['long_peri'] obliquity = orb['obliquity'] # Convert precession angle and latitude to radians phi = deg2rad( lat ) # lambda_long (solar longitude) is the angular distance along Earth's orbit measured from spring equinox (21 March) if day_type==1: # calendar days lambda_long = solar_longitude(day,orb) elif day_type==2: #solar longitude (1-360) is specified in input, no need to convert days to longitude lambda_long = deg2rad(day) else: raise ValueError('Invalid day_type.') # Compute declination angle of the sun delta = arcsin(sin(deg2rad(obliquity)) * sin(lambda_long)) # suppress warning message generated by arccos here! oldsettings = np.seterr(invalid='ignore') # Compute Ho, the hour angle at sunrise / sunset # Check for no sunrise or no sunset: Berger 1978 eqn (8),(9) Ho = xr.where( abs(delta)-pi/2+abs(phi) < 0., # there is sunset/sunrise arccos(-tan(phi)*tan(delta)), # otherwise figure out if it's all night or all day xr.where(phi*delta>0., pi, 0.) ) # this is not really the daily average cosine of the zenith angle... # it's the integral from sunrise to sunset of that quantity... coszen = Ho*sin(phi)*sin(delta) + cos(phi)*cos(delta)*sin(Ho) # Compute insolation: Berger 1978 eq (10) Fsw = S0/pi*( (1+ecc*cos(lambda_long -deg2rad(long_peri)))**2 / (1-ecc**2)**2 * coszen) if not (lat_is_xarray or day_is_xarray): # Dimensional ordering consistent with previous numpy code return Fsw.transpose().values else: return Fsw
python
def daily_insolation(lat, day, orb=const.orb_present, S0=const.S0, day_type=1): """Compute daily average insolation given latitude, time of year and orbital parameters. Orbital parameters can be interpolated to any time in the last 5 Myears with ``climlab.solar.orbital.OrbitalTable`` (see example above). Longer orbital tables are available with ``climlab.solar.orbital.LongOrbitalTable`` Inputs can be scalar, ``numpy.ndarray``, or ``xarray.DataArray``. The return value will be ``numpy.ndarray`` if **all** the inputs are ``numpy``. Otherwise ``xarray.DataArray``. **Function-call argument** \n :param array lat: Latitude in degrees (-90 to 90). :param array day: Indicator of time of year. See argument ``day_type`` for details about format. :param dict orb: a dictionary with three members (as provided by ``climlab.solar.orbital.OrbitalTable``) * ``'ecc'`` - eccentricity * unit: dimensionless * default value: ``0.017236`` * ``'long_peri'`` - longitude of perihelion (precession angle) * unit: degrees * default value: ``281.37`` * ``'obliquity'`` - obliquity angle * unit: degrees * default value: ``23.446`` :param float S0: solar constant \n - unit: :math:`\\textrm{W}/\\textrm{m}^2` \n - default value: ``1365.2`` :param int day_type: Convention for specifying time of year (+/- 1,2) [optional]. *day_type=1* (default): day input is calendar day (1-365.24), where day 1 is January first. The calendar is referenced to the vernal equinox which always occurs at day 80. *day_type=2:* day input is solar longitude (0-360 degrees). Solar longitude is the angle of the Earth's orbit measured from spring equinox (21 March). Note that calendar days and solar longitude are not linearly related because, by Kepler's Second Law, Earth's angular velocity varies according to its distance from the sun. :raises: :exc:`ValueError` if day_type is neither 1 nor 2 :returns: Daily average solar radiation in unit :math:`\\textrm{W}/\\textrm{m}^2`. Dimensions of output are ``(lat.size, day.size, ecc.size)`` :rtype: array Code is fully vectorized to handle array input for all arguments. \n Orbital arguments should all have the same sizes. This is automatic if computed from :func:`~climlab.solar.orbital.OrbitalTable.lookup_parameters` For more information about computation of solar insolation see the :ref:`Tutorial` chapter. """ # Inputs can be scalar, numpy vector, or xarray.DataArray. # If numpy, convert to xarray so that it will broadcast correctly lat_is_xarray = True day_is_xarray = True if type(lat) is np.ndarray: lat_is_xarray = False lat = xr.DataArray(lat, coords=[lat], dims=['lat']) if type(day) is np.ndarray: day_is_xarray = False day = xr.DataArray(day, coords=[day], dims=['day']) ecc = orb['ecc'] long_peri = orb['long_peri'] obliquity = orb['obliquity'] # Convert precession angle and latitude to radians phi = deg2rad( lat ) # lambda_long (solar longitude) is the angular distance along Earth's orbit measured from spring equinox (21 March) if day_type==1: # calendar days lambda_long = solar_longitude(day,orb) elif day_type==2: #solar longitude (1-360) is specified in input, no need to convert days to longitude lambda_long = deg2rad(day) else: raise ValueError('Invalid day_type.') # Compute declination angle of the sun delta = arcsin(sin(deg2rad(obliquity)) * sin(lambda_long)) # suppress warning message generated by arccos here! oldsettings = np.seterr(invalid='ignore') # Compute Ho, the hour angle at sunrise / sunset # Check for no sunrise or no sunset: Berger 1978 eqn (8),(9) Ho = xr.where( abs(delta)-pi/2+abs(phi) < 0., # there is sunset/sunrise arccos(-tan(phi)*tan(delta)), # otherwise figure out if it's all night or all day xr.where(phi*delta>0., pi, 0.) ) # this is not really the daily average cosine of the zenith angle... # it's the integral from sunrise to sunset of that quantity... coszen = Ho*sin(phi)*sin(delta) + cos(phi)*cos(delta)*sin(Ho) # Compute insolation: Berger 1978 eq (10) Fsw = S0/pi*( (1+ecc*cos(lambda_long -deg2rad(long_peri)))**2 / (1-ecc**2)**2 * coszen) if not (lat_is_xarray or day_is_xarray): # Dimensional ordering consistent with previous numpy code return Fsw.transpose().values else: return Fsw
[ "def", "daily_insolation", "(", "lat", ",", "day", ",", "orb", "=", "const", ".", "orb_present", ",", "S0", "=", "const", ".", "S0", ",", "day_type", "=", "1", ")", ":", "# Inputs can be scalar, numpy vector, or xarray.DataArray.", "# If numpy, convert to xarray so that it will broadcast correctly", "lat_is_xarray", "=", "True", "day_is_xarray", "=", "True", "if", "type", "(", "lat", ")", "is", "np", ".", "ndarray", ":", "lat_is_xarray", "=", "False", "lat", "=", "xr", ".", "DataArray", "(", "lat", ",", "coords", "=", "[", "lat", "]", ",", "dims", "=", "[", "'lat'", "]", ")", "if", "type", "(", "day", ")", "is", "np", ".", "ndarray", ":", "day_is_xarray", "=", "False", "day", "=", "xr", ".", "DataArray", "(", "day", ",", "coords", "=", "[", "day", "]", ",", "dims", "=", "[", "'day'", "]", ")", "ecc", "=", "orb", "[", "'ecc'", "]", "long_peri", "=", "orb", "[", "'long_peri'", "]", "obliquity", "=", "orb", "[", "'obliquity'", "]", "# Convert precession angle and latitude to radians", "phi", "=", "deg2rad", "(", "lat", ")", "# lambda_long (solar longitude) is the angular distance along Earth's orbit measured from spring equinox (21 March)", "if", "day_type", "==", "1", ":", "# calendar days", "lambda_long", "=", "solar_longitude", "(", "day", ",", "orb", ")", "elif", "day_type", "==", "2", ":", "#solar longitude (1-360) is specified in input, no need to convert days to longitude", "lambda_long", "=", "deg2rad", "(", "day", ")", "else", ":", "raise", "ValueError", "(", "'Invalid day_type.'", ")", "# Compute declination angle of the sun", "delta", "=", "arcsin", "(", "sin", "(", "deg2rad", "(", "obliquity", ")", ")", "*", "sin", "(", "lambda_long", ")", ")", "# suppress warning message generated by arccos here!", "oldsettings", "=", "np", ".", "seterr", "(", "invalid", "=", "'ignore'", ")", "# Compute Ho, the hour angle at sunrise / sunset", "# Check for no sunrise or no sunset: Berger 1978 eqn (8),(9)", "Ho", "=", "xr", ".", "where", "(", "abs", "(", "delta", ")", "-", "pi", "/", "2", "+", "abs", "(", "phi", ")", "<", "0.", ",", "# there is sunset/sunrise", "arccos", "(", "-", "tan", "(", "phi", ")", "*", "tan", "(", "delta", ")", ")", ",", "# otherwise figure out if it's all night or all day", "xr", ".", "where", "(", "phi", "*", "delta", ">", "0.", ",", "pi", ",", "0.", ")", ")", "# this is not really the daily average cosine of the zenith angle...", "# it's the integral from sunrise to sunset of that quantity...", "coszen", "=", "Ho", "*", "sin", "(", "phi", ")", "*", "sin", "(", "delta", ")", "+", "cos", "(", "phi", ")", "*", "cos", "(", "delta", ")", "*", "sin", "(", "Ho", ")", "# Compute insolation: Berger 1978 eq (10)", "Fsw", "=", "S0", "/", "pi", "*", "(", "(", "1", "+", "ecc", "*", "cos", "(", "lambda_long", "-", "deg2rad", "(", "long_peri", ")", ")", ")", "**", "2", "/", "(", "1", "-", "ecc", "**", "2", ")", "**", "2", "*", "coszen", ")", "if", "not", "(", "lat_is_xarray", "or", "day_is_xarray", ")", ":", "# Dimensional ordering consistent with previous numpy code", "return", "Fsw", ".", "transpose", "(", ")", ".", "values", "else", ":", "return", "Fsw" ]
Compute daily average insolation given latitude, time of year and orbital parameters. Orbital parameters can be interpolated to any time in the last 5 Myears with ``climlab.solar.orbital.OrbitalTable`` (see example above). Longer orbital tables are available with ``climlab.solar.orbital.LongOrbitalTable`` Inputs can be scalar, ``numpy.ndarray``, or ``xarray.DataArray``. The return value will be ``numpy.ndarray`` if **all** the inputs are ``numpy``. Otherwise ``xarray.DataArray``. **Function-call argument** \n :param array lat: Latitude in degrees (-90 to 90). :param array day: Indicator of time of year. See argument ``day_type`` for details about format. :param dict orb: a dictionary with three members (as provided by ``climlab.solar.orbital.OrbitalTable``) * ``'ecc'`` - eccentricity * unit: dimensionless * default value: ``0.017236`` * ``'long_peri'`` - longitude of perihelion (precession angle) * unit: degrees * default value: ``281.37`` * ``'obliquity'`` - obliquity angle * unit: degrees * default value: ``23.446`` :param float S0: solar constant \n - unit: :math:`\\textrm{W}/\\textrm{m}^2` \n - default value: ``1365.2`` :param int day_type: Convention for specifying time of year (+/- 1,2) [optional]. *day_type=1* (default): day input is calendar day (1-365.24), where day 1 is January first. The calendar is referenced to the vernal equinox which always occurs at day 80. *day_type=2:* day input is solar longitude (0-360 degrees). Solar longitude is the angle of the Earth's orbit measured from spring equinox (21 March). Note that calendar days and solar longitude are not linearly related because, by Kepler's Second Law, Earth's angular velocity varies according to its distance from the sun. :raises: :exc:`ValueError` if day_type is neither 1 nor 2 :returns: Daily average solar radiation in unit :math:`\\textrm{W}/\\textrm{m}^2`. Dimensions of output are ``(lat.size, day.size, ecc.size)`` :rtype: array Code is fully vectorized to handle array input for all arguments. \n Orbital arguments should all have the same sizes. This is automatic if computed from :func:`~climlab.solar.orbital.OrbitalTable.lookup_parameters` For more information about computation of solar insolation see the :ref:`Tutorial` chapter.
[ "Compute", "daily", "average", "insolation", "given", "latitude", "time", "of", "year", "and", "orbital", "parameters", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/solar/insolation.py#L46-L160
7,664
brian-rose/climlab
climlab/solar/insolation.py
solar_longitude
def solar_longitude( day, orb=const.orb_present, days_per_year = None ): """Estimates solar longitude from calendar day. Method is using an approximation from :cite:`Berger_1978` section 3 (lambda = 0 at spring equinox). **Function-call arguments** \n :param array day: Indicator of time of year. :param dict orb: a dictionary with three members (as provided by :class:`~climlab.solar.orbital.OrbitalTable`) * ``'ecc'`` - eccentricity * unit: dimensionless * default value: ``0.017236`` * ``'long_peri'`` - longitude of perihelion (precession angle) * unit: degrees * default value: ``281.37`` * ``'obliquity'`` - obliquity angle * unit: degrees * default value: ``23.446`` :param float days_per_year: number of days in a year (optional) (default: 365.2422) Reads the length of the year from :mod:`~climlab.utils.constants` if available. :returns: solar longitude ``lambda_long`` in dimension``( day.size, ecc.size )`` :rtype: array Works for both scalar and vector orbital parameters. """ if days_per_year is None: days_per_year = const.days_per_year ecc = orb['ecc'] long_peri_rad = deg2rad( orb['long_peri']) delta_lambda = (day - 80.) * 2*pi/days_per_year beta = sqrt(1 - ecc**2) lambda_long_m = -2*((ecc/2 + (ecc**3)/8 ) * (1+beta) * sin(-long_peri_rad) - (ecc**2)/4 * (1/2 + beta) * sin(-2*long_peri_rad) + (ecc**3)/8 * (1/3 + beta) * sin(-3*long_peri_rad)) + delta_lambda lambda_long = ( lambda_long_m + (2*ecc - (ecc**3)/4)*sin(lambda_long_m - long_peri_rad) + (5/4)*(ecc**2) * sin(2*(lambda_long_m - long_peri_rad)) + (13/12)*(ecc**3) * sin(3*(lambda_long_m - long_peri_rad)) ) return lambda_long
python
def solar_longitude( day, orb=const.orb_present, days_per_year = None ): """Estimates solar longitude from calendar day. Method is using an approximation from :cite:`Berger_1978` section 3 (lambda = 0 at spring equinox). **Function-call arguments** \n :param array day: Indicator of time of year. :param dict orb: a dictionary with three members (as provided by :class:`~climlab.solar.orbital.OrbitalTable`) * ``'ecc'`` - eccentricity * unit: dimensionless * default value: ``0.017236`` * ``'long_peri'`` - longitude of perihelion (precession angle) * unit: degrees * default value: ``281.37`` * ``'obliquity'`` - obliquity angle * unit: degrees * default value: ``23.446`` :param float days_per_year: number of days in a year (optional) (default: 365.2422) Reads the length of the year from :mod:`~climlab.utils.constants` if available. :returns: solar longitude ``lambda_long`` in dimension``( day.size, ecc.size )`` :rtype: array Works for both scalar and vector orbital parameters. """ if days_per_year is None: days_per_year = const.days_per_year ecc = orb['ecc'] long_peri_rad = deg2rad( orb['long_peri']) delta_lambda = (day - 80.) * 2*pi/days_per_year beta = sqrt(1 - ecc**2) lambda_long_m = -2*((ecc/2 + (ecc**3)/8 ) * (1+beta) * sin(-long_peri_rad) - (ecc**2)/4 * (1/2 + beta) * sin(-2*long_peri_rad) + (ecc**3)/8 * (1/3 + beta) * sin(-3*long_peri_rad)) + delta_lambda lambda_long = ( lambda_long_m + (2*ecc - (ecc**3)/4)*sin(lambda_long_m - long_peri_rad) + (5/4)*(ecc**2) * sin(2*(lambda_long_m - long_peri_rad)) + (13/12)*(ecc**3) * sin(3*(lambda_long_m - long_peri_rad)) ) return lambda_long
[ "def", "solar_longitude", "(", "day", ",", "orb", "=", "const", ".", "orb_present", ",", "days_per_year", "=", "None", ")", ":", "if", "days_per_year", "is", "None", ":", "days_per_year", "=", "const", ".", "days_per_year", "ecc", "=", "orb", "[", "'ecc'", "]", "long_peri_rad", "=", "deg2rad", "(", "orb", "[", "'long_peri'", "]", ")", "delta_lambda", "=", "(", "day", "-", "80.", ")", "*", "2", "*", "pi", "/", "days_per_year", "beta", "=", "sqrt", "(", "1", "-", "ecc", "**", "2", ")", "lambda_long_m", "=", "-", "2", "*", "(", "(", "ecc", "/", "2", "+", "(", "ecc", "**", "3", ")", "/", "8", ")", "*", "(", "1", "+", "beta", ")", "*", "sin", "(", "-", "long_peri_rad", ")", "-", "(", "ecc", "**", "2", ")", "/", "4", "*", "(", "1", "/", "2", "+", "beta", ")", "*", "sin", "(", "-", "2", "*", "long_peri_rad", ")", "+", "(", "ecc", "**", "3", ")", "/", "8", "*", "(", "1", "/", "3", "+", "beta", ")", "*", "sin", "(", "-", "3", "*", "long_peri_rad", ")", ")", "+", "delta_lambda", "lambda_long", "=", "(", "lambda_long_m", "+", "(", "2", "*", "ecc", "-", "(", "ecc", "**", "3", ")", "/", "4", ")", "*", "sin", "(", "lambda_long_m", "-", "long_peri_rad", ")", "+", "(", "5", "/", "4", ")", "*", "(", "ecc", "**", "2", ")", "*", "sin", "(", "2", "*", "(", "lambda_long_m", "-", "long_peri_rad", ")", ")", "+", "(", "13", "/", "12", ")", "*", "(", "ecc", "**", "3", ")", "*", "sin", "(", "3", "*", "(", "lambda_long_m", "-", "long_peri_rad", ")", ")", ")", "return", "lambda_long" ]
Estimates solar longitude from calendar day. Method is using an approximation from :cite:`Berger_1978` section 3 (lambda = 0 at spring equinox). **Function-call arguments** \n :param array day: Indicator of time of year. :param dict orb: a dictionary with three members (as provided by :class:`~climlab.solar.orbital.OrbitalTable`) * ``'ecc'`` - eccentricity * unit: dimensionless * default value: ``0.017236`` * ``'long_peri'`` - longitude of perihelion (precession angle) * unit: degrees * default value: ``281.37`` * ``'obliquity'`` - obliquity angle * unit: degrees * default value: ``23.446`` :param float days_per_year: number of days in a year (optional) (default: 365.2422) Reads the length of the year from :mod:`~climlab.utils.constants` if available. :returns: solar longitude ``lambda_long`` in dimension``( day.size, ecc.size )`` :rtype: array Works for both scalar and vector orbital parameters.
[ "Estimates", "solar", "longitude", "from", "calendar", "day", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/solar/insolation.py#L163-L215
7,665
brian-rose/climlab
climlab/domain/domain.py
single_column
def single_column(num_lev=30, water_depth=1., lev=None, **kwargs): """Creates domains for a single column of atmosphere overlying a slab of water. Can also pass a pressure array or pressure level axis object specified in ``lev``. If argument ``lev`` is not ``None`` then function tries to build a level axis and ``num_lev`` is ignored. **Function-call argument** \n :param int num_lev: number of pressure levels (evenly spaced from surface to TOA) [default: 30] :param float water_depth: depth of the ocean slab [default: 1.] :param lev: specification for height axis (optional) :type lev: :class:`~climlab.domain.axis.Axis` or pressure array :raises: :exc:`ValueError` if `lev` is given but neither Axis nor pressure array. :returns: a list of 2 Domain objects (slab ocean, atmosphere) :rtype: :py:class:`list` of :class:`SlabOcean`, :class:`SlabAtmosphere` :Example: :: >>> from climlab import domain >>> sfc, atm = domain.single_column(num_lev=2, water_depth=10.) >>> print sfc climlab Domain object with domain_type=ocean and shape=(1,) >>> print atm climlab Domain object with domain_type=atm and shape=(2,) """ if lev is None: levax = Axis(axis_type='lev', num_points=num_lev) elif isinstance(lev, Axis): levax = lev else: try: levax = Axis(axis_type='lev', points=lev) except: raise ValueError('lev must be Axis object or pressure array') depthax = Axis(axis_type='depth', bounds=[water_depth, 0.]) slab = SlabOcean(axes=depthax, **kwargs) atm = Atmosphere(axes=levax, **kwargs) return slab, atm
python
def single_column(num_lev=30, water_depth=1., lev=None, **kwargs): """Creates domains for a single column of atmosphere overlying a slab of water. Can also pass a pressure array or pressure level axis object specified in ``lev``. If argument ``lev`` is not ``None`` then function tries to build a level axis and ``num_lev`` is ignored. **Function-call argument** \n :param int num_lev: number of pressure levels (evenly spaced from surface to TOA) [default: 30] :param float water_depth: depth of the ocean slab [default: 1.] :param lev: specification for height axis (optional) :type lev: :class:`~climlab.domain.axis.Axis` or pressure array :raises: :exc:`ValueError` if `lev` is given but neither Axis nor pressure array. :returns: a list of 2 Domain objects (slab ocean, atmosphere) :rtype: :py:class:`list` of :class:`SlabOcean`, :class:`SlabAtmosphere` :Example: :: >>> from climlab import domain >>> sfc, atm = domain.single_column(num_lev=2, water_depth=10.) >>> print sfc climlab Domain object with domain_type=ocean and shape=(1,) >>> print atm climlab Domain object with domain_type=atm and shape=(2,) """ if lev is None: levax = Axis(axis_type='lev', num_points=num_lev) elif isinstance(lev, Axis): levax = lev else: try: levax = Axis(axis_type='lev', points=lev) except: raise ValueError('lev must be Axis object or pressure array') depthax = Axis(axis_type='depth', bounds=[water_depth, 0.]) slab = SlabOcean(axes=depthax, **kwargs) atm = Atmosphere(axes=levax, **kwargs) return slab, atm
[ "def", "single_column", "(", "num_lev", "=", "30", ",", "water_depth", "=", "1.", ",", "lev", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "lev", "is", "None", ":", "levax", "=", "Axis", "(", "axis_type", "=", "'lev'", ",", "num_points", "=", "num_lev", ")", "elif", "isinstance", "(", "lev", ",", "Axis", ")", ":", "levax", "=", "lev", "else", ":", "try", ":", "levax", "=", "Axis", "(", "axis_type", "=", "'lev'", ",", "points", "=", "lev", ")", "except", ":", "raise", "ValueError", "(", "'lev must be Axis object or pressure array'", ")", "depthax", "=", "Axis", "(", "axis_type", "=", "'depth'", ",", "bounds", "=", "[", "water_depth", ",", "0.", "]", ")", "slab", "=", "SlabOcean", "(", "axes", "=", "depthax", ",", "*", "*", "kwargs", ")", "atm", "=", "Atmosphere", "(", "axes", "=", "levax", ",", "*", "*", "kwargs", ")", "return", "slab", ",", "atm" ]
Creates domains for a single column of atmosphere overlying a slab of water. Can also pass a pressure array or pressure level axis object specified in ``lev``. If argument ``lev`` is not ``None`` then function tries to build a level axis and ``num_lev`` is ignored. **Function-call argument** \n :param int num_lev: number of pressure levels (evenly spaced from surface to TOA) [default: 30] :param float water_depth: depth of the ocean slab [default: 1.] :param lev: specification for height axis (optional) :type lev: :class:`~climlab.domain.axis.Axis` or pressure array :raises: :exc:`ValueError` if `lev` is given but neither Axis nor pressure array. :returns: a list of 2 Domain objects (slab ocean, atmosphere) :rtype: :py:class:`list` of :class:`SlabOcean`, :class:`SlabAtmosphere` :Example: :: >>> from climlab import domain >>> sfc, atm = domain.single_column(num_lev=2, water_depth=10.) >>> print sfc climlab Domain object with domain_type=ocean and shape=(1,) >>> print atm climlab Domain object with domain_type=atm and shape=(2,)
[ "Creates", "domains", "for", "a", "single", "column", "of", "atmosphere", "overlying", "a", "slab", "of", "water", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/domain/domain.py#L411-L458
7,666
brian-rose/climlab
climlab/domain/domain.py
zonal_mean_surface
def zonal_mean_surface(num_lat=90, water_depth=10., lat=None, **kwargs): """Creates a 1D slab ocean Domain in latitude with uniform water depth. Domain has a single heat capacity according to the specified water depth. **Function-call argument** \n :param int num_lat: number of latitude points [default: 90] :param float water_depth: depth of the slab ocean in meters [default: 10.] :param lat: specification for latitude axis (optional) :type lat: :class:`~climlab.domain.axis.Axis` or latitude array :raises: :exc:`ValueError` if `lat` is given but neither Axis nor latitude array. :returns: surface domain :rtype: :class:`SlabOcean` :Example: :: >>> from climlab import domain >>> sfc = domain.zonal_mean_surface(num_lat=36) >>> print sfc climlab Domain object with domain_type=ocean and shape=(36, 1) """ if lat is None: latax = Axis(axis_type='lat', num_points=num_lat) elif isinstance(lat, Axis): latax = lat else: try: latax = Axis(axis_type='lat', points=lat) except: raise ValueError('lat must be Axis object or latitude array') depthax = Axis(axis_type='depth', bounds=[water_depth, 0.]) axes = {'depth': depthax, 'lat': latax} slab = SlabOcean(axes=axes, **kwargs) return slab
python
def zonal_mean_surface(num_lat=90, water_depth=10., lat=None, **kwargs): """Creates a 1D slab ocean Domain in latitude with uniform water depth. Domain has a single heat capacity according to the specified water depth. **Function-call argument** \n :param int num_lat: number of latitude points [default: 90] :param float water_depth: depth of the slab ocean in meters [default: 10.] :param lat: specification for latitude axis (optional) :type lat: :class:`~climlab.domain.axis.Axis` or latitude array :raises: :exc:`ValueError` if `lat` is given but neither Axis nor latitude array. :returns: surface domain :rtype: :class:`SlabOcean` :Example: :: >>> from climlab import domain >>> sfc = domain.zonal_mean_surface(num_lat=36) >>> print sfc climlab Domain object with domain_type=ocean and shape=(36, 1) """ if lat is None: latax = Axis(axis_type='lat', num_points=num_lat) elif isinstance(lat, Axis): latax = lat else: try: latax = Axis(axis_type='lat', points=lat) except: raise ValueError('lat must be Axis object or latitude array') depthax = Axis(axis_type='depth', bounds=[water_depth, 0.]) axes = {'depth': depthax, 'lat': latax} slab = SlabOcean(axes=axes, **kwargs) return slab
[ "def", "zonal_mean_surface", "(", "num_lat", "=", "90", ",", "water_depth", "=", "10.", ",", "lat", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "lat", "is", "None", ":", "latax", "=", "Axis", "(", "axis_type", "=", "'lat'", ",", "num_points", "=", "num_lat", ")", "elif", "isinstance", "(", "lat", ",", "Axis", ")", ":", "latax", "=", "lat", "else", ":", "try", ":", "latax", "=", "Axis", "(", "axis_type", "=", "'lat'", ",", "points", "=", "lat", ")", "except", ":", "raise", "ValueError", "(", "'lat must be Axis object or latitude array'", ")", "depthax", "=", "Axis", "(", "axis_type", "=", "'depth'", ",", "bounds", "=", "[", "water_depth", ",", "0.", "]", ")", "axes", "=", "{", "'depth'", ":", "depthax", ",", "'lat'", ":", "latax", "}", "slab", "=", "SlabOcean", "(", "axes", "=", "axes", ",", "*", "*", "kwargs", ")", "return", "slab" ]
Creates a 1D slab ocean Domain in latitude with uniform water depth. Domain has a single heat capacity according to the specified water depth. **Function-call argument** \n :param int num_lat: number of latitude points [default: 90] :param float water_depth: depth of the slab ocean in meters [default: 10.] :param lat: specification for latitude axis (optional) :type lat: :class:`~climlab.domain.axis.Axis` or latitude array :raises: :exc:`ValueError` if `lat` is given but neither Axis nor latitude array. :returns: surface domain :rtype: :class:`SlabOcean` :Example: :: >>> from climlab import domain >>> sfc = domain.zonal_mean_surface(num_lat=36) >>> print sfc climlab Domain object with domain_type=ocean and shape=(36, 1)
[ "Creates", "a", "1D", "slab", "ocean", "Domain", "in", "latitude", "with", "uniform", "water", "depth", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/domain/domain.py#L461-L499
7,667
brian-rose/climlab
climlab/domain/domain.py
surface_2D
def surface_2D(num_lat=90, num_lon=180, water_depth=10., lon=None, lat=None, **kwargs): """Creates a 2D slab ocean Domain in latitude and longitude with uniform water depth. Domain has a single heat capacity according to the specified water depth. **Function-call argument** \n :param int num_lat: number of latitude points [default: 90] :param int num_lon: number of longitude points [default: 180] :param float water_depth: depth of the slab ocean in meters [default: 10.] :param lat: specification for latitude axis (optional) :type lat: :class:`~climlab.domain.axis.Axis` or latitude array :param lon: specification for longitude axis (optional) :type lon: :class:`~climlab.domain.axis.Axis` or longitude array :raises: :exc:`ValueError` if `lat` is given but neither Axis nor latitude array. :raises: :exc:`ValueError` if `lon` is given but neither Axis nor longitude array. :returns: surface domain :rtype: :class:`SlabOcean` :Example: :: >>> from climlab import domain >>> sfc = domain.surface_2D(num_lat=36, num_lat=72) >>> print sfc climlab Domain object with domain_type=ocean and shape=(36, 72, 1) """ if lat is None: latax = Axis(axis_type='lat', num_points=num_lat) elif isinstance(lat, Axis): latax = lat else: try: latax = Axis(axis_type='lat', points=lat) except: raise ValueError('lat must be Axis object or latitude array') if lon is None: lonax = Axis(axis_type='lon', num_points=num_lon) elif isinstance(lon, Axis): lonax = lon else: try: lonax = Axis(axis_type='lon', points=lon) except: raise ValueError('lon must be Axis object or longitude array') depthax = Axis(axis_type='depth', bounds=[water_depth, 0.]) axes = {'lat': latax, 'lon': lonax, 'depth': depthax} slab = SlabOcean(axes=axes, **kwargs) return slab
python
def surface_2D(num_lat=90, num_lon=180, water_depth=10., lon=None, lat=None, **kwargs): """Creates a 2D slab ocean Domain in latitude and longitude with uniform water depth. Domain has a single heat capacity according to the specified water depth. **Function-call argument** \n :param int num_lat: number of latitude points [default: 90] :param int num_lon: number of longitude points [default: 180] :param float water_depth: depth of the slab ocean in meters [default: 10.] :param lat: specification for latitude axis (optional) :type lat: :class:`~climlab.domain.axis.Axis` or latitude array :param lon: specification for longitude axis (optional) :type lon: :class:`~climlab.domain.axis.Axis` or longitude array :raises: :exc:`ValueError` if `lat` is given but neither Axis nor latitude array. :raises: :exc:`ValueError` if `lon` is given but neither Axis nor longitude array. :returns: surface domain :rtype: :class:`SlabOcean` :Example: :: >>> from climlab import domain >>> sfc = domain.surface_2D(num_lat=36, num_lat=72) >>> print sfc climlab Domain object with domain_type=ocean and shape=(36, 72, 1) """ if lat is None: latax = Axis(axis_type='lat', num_points=num_lat) elif isinstance(lat, Axis): latax = lat else: try: latax = Axis(axis_type='lat', points=lat) except: raise ValueError('lat must be Axis object or latitude array') if lon is None: lonax = Axis(axis_type='lon', num_points=num_lon) elif isinstance(lon, Axis): lonax = lon else: try: lonax = Axis(axis_type='lon', points=lon) except: raise ValueError('lon must be Axis object or longitude array') depthax = Axis(axis_type='depth', bounds=[water_depth, 0.]) axes = {'lat': latax, 'lon': lonax, 'depth': depthax} slab = SlabOcean(axes=axes, **kwargs) return slab
[ "def", "surface_2D", "(", "num_lat", "=", "90", ",", "num_lon", "=", "180", ",", "water_depth", "=", "10.", ",", "lon", "=", "None", ",", "lat", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "lat", "is", "None", ":", "latax", "=", "Axis", "(", "axis_type", "=", "'lat'", ",", "num_points", "=", "num_lat", ")", "elif", "isinstance", "(", "lat", ",", "Axis", ")", ":", "latax", "=", "lat", "else", ":", "try", ":", "latax", "=", "Axis", "(", "axis_type", "=", "'lat'", ",", "points", "=", "lat", ")", "except", ":", "raise", "ValueError", "(", "'lat must be Axis object or latitude array'", ")", "if", "lon", "is", "None", ":", "lonax", "=", "Axis", "(", "axis_type", "=", "'lon'", ",", "num_points", "=", "num_lon", ")", "elif", "isinstance", "(", "lon", ",", "Axis", ")", ":", "lonax", "=", "lon", "else", ":", "try", ":", "lonax", "=", "Axis", "(", "axis_type", "=", "'lon'", ",", "points", "=", "lon", ")", "except", ":", "raise", "ValueError", "(", "'lon must be Axis object or longitude array'", ")", "depthax", "=", "Axis", "(", "axis_type", "=", "'depth'", ",", "bounds", "=", "[", "water_depth", ",", "0.", "]", ")", "axes", "=", "{", "'lat'", ":", "latax", ",", "'lon'", ":", "lonax", ",", "'depth'", ":", "depthax", "}", "slab", "=", "SlabOcean", "(", "axes", "=", "axes", ",", "*", "*", "kwargs", ")", "return", "slab" ]
Creates a 2D slab ocean Domain in latitude and longitude with uniform water depth. Domain has a single heat capacity according to the specified water depth. **Function-call argument** \n :param int num_lat: number of latitude points [default: 90] :param int num_lon: number of longitude points [default: 180] :param float water_depth: depth of the slab ocean in meters [default: 10.] :param lat: specification for latitude axis (optional) :type lat: :class:`~climlab.domain.axis.Axis` or latitude array :param lon: specification for longitude axis (optional) :type lon: :class:`~climlab.domain.axis.Axis` or longitude array :raises: :exc:`ValueError` if `lat` is given but neither Axis nor latitude array. :raises: :exc:`ValueError` if `lon` is given but neither Axis nor longitude array. :returns: surface domain :rtype: :class:`SlabOcean` :Example: :: >>> from climlab import domain >>> sfc = domain.surface_2D(num_lat=36, num_lat=72) >>> print sfc climlab Domain object with domain_type=ocean and shape=(36, 72, 1)
[ "Creates", "a", "2D", "slab", "ocean", "Domain", "in", "latitude", "and", "longitude", "with", "uniform", "water", "depth", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/domain/domain.py#L501-L553
7,668
brian-rose/climlab
climlab/domain/domain.py
_Domain._make_axes_dict
def _make_axes_dict(self, axes): """Makes an axes dictionary. .. note:: In case the input is ``None``, the dictionary :code:`{'empty': None}` is returned. **Function-call argument** \n :param axes: axes input :type axes: dict or single instance of :class:`~climlab.domain.axis.Axis` object or ``None`` :raises: :exc:`ValueError` if input is not an instance of Axis class or a dictionary of Axis objetcs :returns: dictionary of input axes :rtype: dict """ if type(axes) is dict: axdict = axes elif type(axes) is Axis: ax = axes axdict = {ax.axis_type: ax} elif axes is None: axdict = {'empty': None} else: raise ValueError('axes needs to be Axis object or dictionary of Axis object') return axdict
python
def _make_axes_dict(self, axes): """Makes an axes dictionary. .. note:: In case the input is ``None``, the dictionary :code:`{'empty': None}` is returned. **Function-call argument** \n :param axes: axes input :type axes: dict or single instance of :class:`~climlab.domain.axis.Axis` object or ``None`` :raises: :exc:`ValueError` if input is not an instance of Axis class or a dictionary of Axis objetcs :returns: dictionary of input axes :rtype: dict """ if type(axes) is dict: axdict = axes elif type(axes) is Axis: ax = axes axdict = {ax.axis_type: ax} elif axes is None: axdict = {'empty': None} else: raise ValueError('axes needs to be Axis object or dictionary of Axis object') return axdict
[ "def", "_make_axes_dict", "(", "self", ",", "axes", ")", ":", "if", "type", "(", "axes", ")", "is", "dict", ":", "axdict", "=", "axes", "elif", "type", "(", "axes", ")", "is", "Axis", ":", "ax", "=", "axes", "axdict", "=", "{", "ax", ".", "axis_type", ":", "ax", "}", "elif", "axes", "is", "None", ":", "axdict", "=", "{", "'empty'", ":", "None", "}", "else", ":", "raise", "ValueError", "(", "'axes needs to be Axis object or dictionary of Axis object'", ")", "return", "axdict" ]
Makes an axes dictionary. .. note:: In case the input is ``None``, the dictionary :code:`{'empty': None}` is returned. **Function-call argument** \n :param axes: axes input :type axes: dict or single instance of :class:`~climlab.domain.axis.Axis` object or ``None`` :raises: :exc:`ValueError` if input is not an instance of Axis class or a dictionary of Axis objetcs :returns: dictionary of input axes :rtype: dict
[ "Makes", "an", "axes", "dictionary", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/domain/domain.py#L129-L157
7,669
brian-rose/climlab
climlab/process/implicit.py
ImplicitProcess._compute
def _compute(self): """Computes the state variable tendencies in time for implicit processes. To calculate the new state the :func:`_implicit_solver()` method is called for daughter classes. This however returns the new state of the variables, not just the tendencies. Therefore, the adjustment is calculated which is the difference between the new and the old state and stored in the object's attribute adjustment. Calculating the new model states through solving the matrix problem already includes the multiplication with the timestep. The derived adjustment is divided by the timestep to calculate the implicit subprocess tendencies, which can be handeled by the :func:`~climlab.process.time_dependent_process.TimeDependentProcess.compute` method of the parent :class:`~climlab.process.time_dependent_process.TimeDependentProcess` class. :ivar dict adjustment: holding all state variables' adjustments of the implicit process which are the differences between the new states (which have been solved through matrix inversion) and the old states. """ newstate = self._implicit_solver() adjustment = {} tendencies = {} for name, var in self.state.items(): adjustment[name] = newstate[name] - var tendencies[name] = adjustment[name] / self.timestep # express the adjustment (already accounting for the finite time step) # as a tendency per unit time, so that it can be applied along with explicit self.adjustment = adjustment self._update_diagnostics(newstate) return tendencies
python
def _compute(self): """Computes the state variable tendencies in time for implicit processes. To calculate the new state the :func:`_implicit_solver()` method is called for daughter classes. This however returns the new state of the variables, not just the tendencies. Therefore, the adjustment is calculated which is the difference between the new and the old state and stored in the object's attribute adjustment. Calculating the new model states through solving the matrix problem already includes the multiplication with the timestep. The derived adjustment is divided by the timestep to calculate the implicit subprocess tendencies, which can be handeled by the :func:`~climlab.process.time_dependent_process.TimeDependentProcess.compute` method of the parent :class:`~climlab.process.time_dependent_process.TimeDependentProcess` class. :ivar dict adjustment: holding all state variables' adjustments of the implicit process which are the differences between the new states (which have been solved through matrix inversion) and the old states. """ newstate = self._implicit_solver() adjustment = {} tendencies = {} for name, var in self.state.items(): adjustment[name] = newstate[name] - var tendencies[name] = adjustment[name] / self.timestep # express the adjustment (already accounting for the finite time step) # as a tendency per unit time, so that it can be applied along with explicit self.adjustment = adjustment self._update_diagnostics(newstate) return tendencies
[ "def", "_compute", "(", "self", ")", ":", "newstate", "=", "self", ".", "_implicit_solver", "(", ")", "adjustment", "=", "{", "}", "tendencies", "=", "{", "}", "for", "name", ",", "var", "in", "self", ".", "state", ".", "items", "(", ")", ":", "adjustment", "[", "name", "]", "=", "newstate", "[", "name", "]", "-", "var", "tendencies", "[", "name", "]", "=", "adjustment", "[", "name", "]", "/", "self", ".", "timestep", "# express the adjustment (already accounting for the finite time step)", "# as a tendency per unit time, so that it can be applied along with explicit", "self", ".", "adjustment", "=", "adjustment", "self", ".", "_update_diagnostics", "(", "newstate", ")", "return", "tendencies" ]
Computes the state variable tendencies in time for implicit processes. To calculate the new state the :func:`_implicit_solver()` method is called for daughter classes. This however returns the new state of the variables, not just the tendencies. Therefore, the adjustment is calculated which is the difference between the new and the old state and stored in the object's attribute adjustment. Calculating the new model states through solving the matrix problem already includes the multiplication with the timestep. The derived adjustment is divided by the timestep to calculate the implicit subprocess tendencies, which can be handeled by the :func:`~climlab.process.time_dependent_process.TimeDependentProcess.compute` method of the parent :class:`~climlab.process.time_dependent_process.TimeDependentProcess` class. :ivar dict adjustment: holding all state variables' adjustments of the implicit process which are the differences between the new states (which have been solved through matrix inversion) and the old states.
[ "Computes", "the", "state", "variable", "tendencies", "in", "time", "for", "implicit", "processes", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/implicit.py#L23-L57
7,670
brian-rose/climlab
climlab/utils/walk.py
walk_processes
def walk_processes(top, topname='top', topdown=True, ignoreFlag=False): """Generator for recursive tree of climlab processes Starts walking from climlab process ``top`` and generates a complete list of all processes and sub-processes that are managed from ``top`` process. ``level`` indicades the rank of specific process in the process hierarchy: .. note:: * level 0: ``top`` process * level 1: sub-processes of ``top`` process * level 2: sub-sub-processes of ``top`` process (=subprocesses of level 1 processes) The method is based on os.walk(). :param top: top process from where walking should start :type top: :class:`~climlab.process.process.Process` :param str topname: name of top process [default: 'top'] :param bool topdown: whether geneterate *process_types* in regular or in reverse order [default: True] :param bool ignoreFlag: whether ``topdown`` flag should be ignored or not [default: False] :returns: name (str), proc (process), level (int) :Example: :: >>> import climlab >>> from climlab.utils import walk >>> model = climlab.EBM() >>> for name, proc, top_proc in walk.walk_processes(model): ... print name ... top diffusion LW iceline cold_albedo warm_albedo albedo insolation """ if not ignoreFlag: flag = topdown else: flag = True proc = top level = 0 if flag: yield topname, proc, level if len(proc.subprocess) > 0: # there are sub-processes level += 1 for name, subproc in proc.subprocess.items(): for name2, subproc2, level2 in walk_processes(subproc, topname=name, topdown=subproc.topdown, ignoreFlag=ignoreFlag): yield name2, subproc2, level+level2 if not flag: yield topname, proc, level
python
def walk_processes(top, topname='top', topdown=True, ignoreFlag=False): """Generator for recursive tree of climlab processes Starts walking from climlab process ``top`` and generates a complete list of all processes and sub-processes that are managed from ``top`` process. ``level`` indicades the rank of specific process in the process hierarchy: .. note:: * level 0: ``top`` process * level 1: sub-processes of ``top`` process * level 2: sub-sub-processes of ``top`` process (=subprocesses of level 1 processes) The method is based on os.walk(). :param top: top process from where walking should start :type top: :class:`~climlab.process.process.Process` :param str topname: name of top process [default: 'top'] :param bool topdown: whether geneterate *process_types* in regular or in reverse order [default: True] :param bool ignoreFlag: whether ``topdown`` flag should be ignored or not [default: False] :returns: name (str), proc (process), level (int) :Example: :: >>> import climlab >>> from climlab.utils import walk >>> model = climlab.EBM() >>> for name, proc, top_proc in walk.walk_processes(model): ... print name ... top diffusion LW iceline cold_albedo warm_albedo albedo insolation """ if not ignoreFlag: flag = topdown else: flag = True proc = top level = 0 if flag: yield topname, proc, level if len(proc.subprocess) > 0: # there are sub-processes level += 1 for name, subproc in proc.subprocess.items(): for name2, subproc2, level2 in walk_processes(subproc, topname=name, topdown=subproc.topdown, ignoreFlag=ignoreFlag): yield name2, subproc2, level+level2 if not flag: yield topname, proc, level
[ "def", "walk_processes", "(", "top", ",", "topname", "=", "'top'", ",", "topdown", "=", "True", ",", "ignoreFlag", "=", "False", ")", ":", "if", "not", "ignoreFlag", ":", "flag", "=", "topdown", "else", ":", "flag", "=", "True", "proc", "=", "top", "level", "=", "0", "if", "flag", ":", "yield", "topname", ",", "proc", ",", "level", "if", "len", "(", "proc", ".", "subprocess", ")", ">", "0", ":", "# there are sub-processes", "level", "+=", "1", "for", "name", ",", "subproc", "in", "proc", ".", "subprocess", ".", "items", "(", ")", ":", "for", "name2", ",", "subproc2", ",", "level2", "in", "walk_processes", "(", "subproc", ",", "topname", "=", "name", ",", "topdown", "=", "subproc", ".", "topdown", ",", "ignoreFlag", "=", "ignoreFlag", ")", ":", "yield", "name2", ",", "subproc2", ",", "level", "+", "level2", "if", "not", "flag", ":", "yield", "topname", ",", "proc", ",", "level" ]
Generator for recursive tree of climlab processes Starts walking from climlab process ``top`` and generates a complete list of all processes and sub-processes that are managed from ``top`` process. ``level`` indicades the rank of specific process in the process hierarchy: .. note:: * level 0: ``top`` process * level 1: sub-processes of ``top`` process * level 2: sub-sub-processes of ``top`` process (=subprocesses of level 1 processes) The method is based on os.walk(). :param top: top process from where walking should start :type top: :class:`~climlab.process.process.Process` :param str topname: name of top process [default: 'top'] :param bool topdown: whether geneterate *process_types* in regular or in reverse order [default: True] :param bool ignoreFlag: whether ``topdown`` flag should be ignored or not [default: False] :returns: name (str), proc (process), level (int) :Example: :: >>> import climlab >>> from climlab.utils import walk >>> model = climlab.EBM() >>> for name, proc, top_proc in walk.walk_processes(model): ... print name ... top diffusion LW iceline cold_albedo warm_albedo albedo insolation
[ "Generator", "for", "recursive", "tree", "of", "climlab", "processes" ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/utils/walk.py#L3-L71
7,671
brian-rose/climlab
climlab/utils/walk.py
process_tree
def process_tree(top, name='top'): """Creates a string representation of the process tree for process top. This method uses the :func:`walk_processes` method to create the process tree. :param top: top process for which process tree string should be created :type top: :class:`~climlab.process.process.Process` :param str name: name of top process :returns: string representation of the process tree :rtype: str :Example: :: >>> import climlab >>> from climlab.utils import walk >>> model = climlab.EBM() >>> proc_tree_str = walk.process_tree(model, name='model') >>> print proc_tree_str model: <class 'climlab.model.ebm.EBM'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> albedo: <class 'climlab.surface.albedo.StepFunctionAlbedo'> iceline: <class 'climlab.surface.albedo.Iceline'> cold_albedo: <class 'climlab.surface.albedo.ConstantAlbedo'> warm_albedo: <class 'climlab.surface.albedo.P2Albedo'> insolation: <class 'climlab.radiation.insolation.P2Insolation'> """ str1 = '' for name, proc, level in walk_processes(top, name, ignoreFlag=True): indent = ' ' * 3 * (level) str1 += ('{}{}: {}\n'.format(indent, name, type(proc))) return str1
python
def process_tree(top, name='top'): """Creates a string representation of the process tree for process top. This method uses the :func:`walk_processes` method to create the process tree. :param top: top process for which process tree string should be created :type top: :class:`~climlab.process.process.Process` :param str name: name of top process :returns: string representation of the process tree :rtype: str :Example: :: >>> import climlab >>> from climlab.utils import walk >>> model = climlab.EBM() >>> proc_tree_str = walk.process_tree(model, name='model') >>> print proc_tree_str model: <class 'climlab.model.ebm.EBM'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> albedo: <class 'climlab.surface.albedo.StepFunctionAlbedo'> iceline: <class 'climlab.surface.albedo.Iceline'> cold_albedo: <class 'climlab.surface.albedo.ConstantAlbedo'> warm_albedo: <class 'climlab.surface.albedo.P2Albedo'> insolation: <class 'climlab.radiation.insolation.P2Insolation'> """ str1 = '' for name, proc, level in walk_processes(top, name, ignoreFlag=True): indent = ' ' * 3 * (level) str1 += ('{}{}: {}\n'.format(indent, name, type(proc))) return str1
[ "def", "process_tree", "(", "top", ",", "name", "=", "'top'", ")", ":", "str1", "=", "''", "for", "name", ",", "proc", ",", "level", "in", "walk_processes", "(", "top", ",", "name", ",", "ignoreFlag", "=", "True", ")", ":", "indent", "=", "' '", "*", "3", "*", "(", "level", ")", "str1", "+=", "(", "'{}{}: {}\\n'", ".", "format", "(", "indent", ",", "name", ",", "type", "(", "proc", ")", ")", ")", "return", "str1" ]
Creates a string representation of the process tree for process top. This method uses the :func:`walk_processes` method to create the process tree. :param top: top process for which process tree string should be created :type top: :class:`~climlab.process.process.Process` :param str name: name of top process :returns: string representation of the process tree :rtype: str :Example: :: >>> import climlab >>> from climlab.utils import walk >>> model = climlab.EBM() >>> proc_tree_str = walk.process_tree(model, name='model') >>> print proc_tree_str model: <class 'climlab.model.ebm.EBM'> diffusion: <class 'climlab.dynamics.diffusion.MeridionalDiffusion'> LW: <class 'climlab.radiation.AplusBT.AplusBT'> albedo: <class 'climlab.surface.albedo.StepFunctionAlbedo'> iceline: <class 'climlab.surface.albedo.Iceline'> cold_albedo: <class 'climlab.surface.albedo.ConstantAlbedo'> warm_albedo: <class 'climlab.surface.albedo.P2Albedo'> insolation: <class 'climlab.radiation.insolation.P2Insolation'>
[ "Creates", "a", "string", "representation", "of", "the", "process", "tree", "for", "process", "top", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/utils/walk.py#L74-L111
7,672
brian-rose/climlab
climlab/radiation/greygas.py
GreyGas._compute_fluxes
def _compute_fluxes(self): ''' All fluxes are band by band''' self.emission = self._compute_emission() self.emission_sfc = self._compute_emission_sfc() fromspace = self._from_space() self.flux_down = self.trans.flux_down(fromspace, self.emission) self.flux_reflected_up = self.trans.flux_reflected_up(self.flux_down, self.albedo_sfc) # this ensure same dimensions as other fields self.flux_to_sfc = self.flux_down[..., -1, np.newaxis] self.flux_from_sfc = (self.emission_sfc + self.flux_reflected_up[..., -1, np.newaxis]) self.flux_up = self.trans.flux_up(self.flux_from_sfc, self.emission + self.flux_reflected_up[...,0:-1]) self.flux_net = self.flux_up - self.flux_down # absorbed radiation (flux convergence) in W / m**2 (per band) self.absorbed = np.diff(self.flux_net, axis=-1) self.absorbed_total = np.sum(self.absorbed, axis=-1) self.flux_to_space = self._compute_flux_top()
python
def _compute_fluxes(self): ''' All fluxes are band by band''' self.emission = self._compute_emission() self.emission_sfc = self._compute_emission_sfc() fromspace = self._from_space() self.flux_down = self.trans.flux_down(fromspace, self.emission) self.flux_reflected_up = self.trans.flux_reflected_up(self.flux_down, self.albedo_sfc) # this ensure same dimensions as other fields self.flux_to_sfc = self.flux_down[..., -1, np.newaxis] self.flux_from_sfc = (self.emission_sfc + self.flux_reflected_up[..., -1, np.newaxis]) self.flux_up = self.trans.flux_up(self.flux_from_sfc, self.emission + self.flux_reflected_up[...,0:-1]) self.flux_net = self.flux_up - self.flux_down # absorbed radiation (flux convergence) in W / m**2 (per band) self.absorbed = np.diff(self.flux_net, axis=-1) self.absorbed_total = np.sum(self.absorbed, axis=-1) self.flux_to_space = self._compute_flux_top()
[ "def", "_compute_fluxes", "(", "self", ")", ":", "self", ".", "emission", "=", "self", ".", "_compute_emission", "(", ")", "self", ".", "emission_sfc", "=", "self", ".", "_compute_emission_sfc", "(", ")", "fromspace", "=", "self", ".", "_from_space", "(", ")", "self", ".", "flux_down", "=", "self", ".", "trans", ".", "flux_down", "(", "fromspace", ",", "self", ".", "emission", ")", "self", ".", "flux_reflected_up", "=", "self", ".", "trans", ".", "flux_reflected_up", "(", "self", ".", "flux_down", ",", "self", ".", "albedo_sfc", ")", "# this ensure same dimensions as other fields", "self", ".", "flux_to_sfc", "=", "self", ".", "flux_down", "[", "...", ",", "-", "1", ",", "np", ".", "newaxis", "]", "self", ".", "flux_from_sfc", "=", "(", "self", ".", "emission_sfc", "+", "self", ".", "flux_reflected_up", "[", "...", ",", "-", "1", ",", "np", ".", "newaxis", "]", ")", "self", ".", "flux_up", "=", "self", ".", "trans", ".", "flux_up", "(", "self", ".", "flux_from_sfc", ",", "self", ".", "emission", "+", "self", ".", "flux_reflected_up", "[", "...", ",", "0", ":", "-", "1", "]", ")", "self", ".", "flux_net", "=", "self", ".", "flux_up", "-", "self", ".", "flux_down", "# absorbed radiation (flux convergence) in W / m**2 (per band)", "self", ".", "absorbed", "=", "np", ".", "diff", "(", "self", ".", "flux_net", ",", "axis", "=", "-", "1", ")", "self", ".", "absorbed_total", "=", "np", ".", "sum", "(", "self", ".", "absorbed", ",", "axis", "=", "-", "1", ")", "self", ".", "flux_to_space", "=", "self", ".", "_compute_flux_top", "(", ")" ]
All fluxes are band by band
[ "All", "fluxes", "are", "band", "by", "band" ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/greygas.py#L129-L146
7,673
brian-rose/climlab
climlab/radiation/greygas.py
GreyGas.flux_components_top
def flux_components_top(self): '''Compute the contributions to the outgoing flux to space due to emissions from each level and the surface.''' N = self.lev.size flux_up_bottom = self.flux_from_sfc emission = np.zeros_like(self.emission) this_flux_up = (np.ones_like(self.Ts) * self.trans.flux_up(flux_up_bottom, emission)) sfcComponent = this_flux_up[..., -1] atmComponents = np.zeros_like(self.Tatm) flux_up_bottom = np.zeros_like(self.Ts) # I'm sure there's a way to write this as a vectorized operation # but the speed doesn't really matter if it's just for diagnostic # and we are not calling it every timestep for n in range(N): emission = np.zeros_like(self.emission) emission[..., n] = self.emission[..., n] this_flux_up = self.trans.flux_up(flux_up_bottom, emission) atmComponents[..., n] = this_flux_up[..., -1] return sfcComponent, atmComponents
python
def flux_components_top(self): '''Compute the contributions to the outgoing flux to space due to emissions from each level and the surface.''' N = self.lev.size flux_up_bottom = self.flux_from_sfc emission = np.zeros_like(self.emission) this_flux_up = (np.ones_like(self.Ts) * self.trans.flux_up(flux_up_bottom, emission)) sfcComponent = this_flux_up[..., -1] atmComponents = np.zeros_like(self.Tatm) flux_up_bottom = np.zeros_like(self.Ts) # I'm sure there's a way to write this as a vectorized operation # but the speed doesn't really matter if it's just for diagnostic # and we are not calling it every timestep for n in range(N): emission = np.zeros_like(self.emission) emission[..., n] = self.emission[..., n] this_flux_up = self.trans.flux_up(flux_up_bottom, emission) atmComponents[..., n] = this_flux_up[..., -1] return sfcComponent, atmComponents
[ "def", "flux_components_top", "(", "self", ")", ":", "N", "=", "self", ".", "lev", ".", "size", "flux_up_bottom", "=", "self", ".", "flux_from_sfc", "emission", "=", "np", ".", "zeros_like", "(", "self", ".", "emission", ")", "this_flux_up", "=", "(", "np", ".", "ones_like", "(", "self", ".", "Ts", ")", "*", "self", ".", "trans", ".", "flux_up", "(", "flux_up_bottom", ",", "emission", ")", ")", "sfcComponent", "=", "this_flux_up", "[", "...", ",", "-", "1", "]", "atmComponents", "=", "np", ".", "zeros_like", "(", "self", ".", "Tatm", ")", "flux_up_bottom", "=", "np", ".", "zeros_like", "(", "self", ".", "Ts", ")", "# I'm sure there's a way to write this as a vectorized operation", "# but the speed doesn't really matter if it's just for diagnostic", "# and we are not calling it every timestep", "for", "n", "in", "range", "(", "N", ")", ":", "emission", "=", "np", ".", "zeros_like", "(", "self", ".", "emission", ")", "emission", "[", "...", ",", "n", "]", "=", "self", ".", "emission", "[", "...", ",", "n", "]", "this_flux_up", "=", "self", ".", "trans", ".", "flux_up", "(", "flux_up_bottom", ",", "emission", ")", "atmComponents", "[", "...", ",", "n", "]", "=", "this_flux_up", "[", "...", ",", "-", "1", "]", "return", "sfcComponent", ",", "atmComponents" ]
Compute the contributions to the outgoing flux to space due to emissions from each level and the surface.
[ "Compute", "the", "contributions", "to", "the", "outgoing", "flux", "to", "space", "due", "to", "emissions", "from", "each", "level", "and", "the", "surface", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/greygas.py#L185-L204
7,674
brian-rose/climlab
climlab/radiation/greygas.py
GreyGas.flux_components_bottom
def flux_components_bottom(self): '''Compute the contributions to the downwelling flux to surface due to emissions from each level.''' N = self.lev.size atmComponents = np.zeros_like(self.Tatm) flux_down_top = np.zeros_like(self.Ts) # same comment as above... would be nice to vectorize for n in range(N): emission = np.zeros_like(self.emission) emission[..., n] = self.emission[..., n] this_flux_down = self.trans.flux_down(flux_down_top, emission) atmComponents[..., n] = this_flux_down[..., 0] return atmComponents
python
def flux_components_bottom(self): '''Compute the contributions to the downwelling flux to surface due to emissions from each level.''' N = self.lev.size atmComponents = np.zeros_like(self.Tatm) flux_down_top = np.zeros_like(self.Ts) # same comment as above... would be nice to vectorize for n in range(N): emission = np.zeros_like(self.emission) emission[..., n] = self.emission[..., n] this_flux_down = self.trans.flux_down(flux_down_top, emission) atmComponents[..., n] = this_flux_down[..., 0] return atmComponents
[ "def", "flux_components_bottom", "(", "self", ")", ":", "N", "=", "self", ".", "lev", ".", "size", "atmComponents", "=", "np", ".", "zeros_like", "(", "self", ".", "Tatm", ")", "flux_down_top", "=", "np", ".", "zeros_like", "(", "self", ".", "Ts", ")", "# same comment as above... would be nice to vectorize", "for", "n", "in", "range", "(", "N", ")", ":", "emission", "=", "np", ".", "zeros_like", "(", "self", ".", "emission", ")", "emission", "[", "...", ",", "n", "]", "=", "self", ".", "emission", "[", "...", ",", "n", "]", "this_flux_down", "=", "self", ".", "trans", ".", "flux_down", "(", "flux_down_top", ",", "emission", ")", "atmComponents", "[", "...", ",", "n", "]", "=", "this_flux_down", "[", "...", ",", "0", "]", "return", "atmComponents" ]
Compute the contributions to the downwelling flux to surface due to emissions from each level.
[ "Compute", "the", "contributions", "to", "the", "downwelling", "flux", "to", "surface", "due", "to", "emissions", "from", "each", "level", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/greygas.py#L206-L218
7,675
brian-rose/climlab
climlab/surface/turbulent.py
LatentHeatFlux._compute
def _compute(self): '''Overides the _compute method of EnergyBudget''' tendencies = self._temperature_tendencies() if 'q' in self.state: # in a model with active water vapor, this flux should affect # water vapor tendency, NOT air temperature tendency! tendencies['Tatm'] *= 0. Pa_per_hPa = 100. air_mass_per_area = self.Tatm.domain.lev.delta[...,-1] * Pa_per_hPa / const.g specific_humidity_tendency = 0.*self.q specific_humidity_tendency[...,-1,np.newaxis] = self.LHF/const.Lhvap / air_mass_per_area tendencies['q'] = specific_humidity_tendency return tendencies
python
def _compute(self): '''Overides the _compute method of EnergyBudget''' tendencies = self._temperature_tendencies() if 'q' in self.state: # in a model with active water vapor, this flux should affect # water vapor tendency, NOT air temperature tendency! tendencies['Tatm'] *= 0. Pa_per_hPa = 100. air_mass_per_area = self.Tatm.domain.lev.delta[...,-1] * Pa_per_hPa / const.g specific_humidity_tendency = 0.*self.q specific_humidity_tendency[...,-1,np.newaxis] = self.LHF/const.Lhvap / air_mass_per_area tendencies['q'] = specific_humidity_tendency return tendencies
[ "def", "_compute", "(", "self", ")", ":", "tendencies", "=", "self", ".", "_temperature_tendencies", "(", ")", "if", "'q'", "in", "self", ".", "state", ":", "# in a model with active water vapor, this flux should affect", "# water vapor tendency, NOT air temperature tendency!", "tendencies", "[", "'Tatm'", "]", "*=", "0.", "Pa_per_hPa", "=", "100.", "air_mass_per_area", "=", "self", ".", "Tatm", ".", "domain", ".", "lev", ".", "delta", "[", "...", ",", "-", "1", "]", "*", "Pa_per_hPa", "/", "const", ".", "g", "specific_humidity_tendency", "=", "0.", "*", "self", ".", "q", "specific_humidity_tendency", "[", "...", ",", "-", "1", ",", "np", ".", "newaxis", "]", "=", "self", ".", "LHF", "/", "const", ".", "Lhvap", "/", "air_mass_per_area", "tendencies", "[", "'q'", "]", "=", "specific_humidity_tendency", "return", "tendencies" ]
Overides the _compute method of EnergyBudget
[ "Overides", "the", "_compute", "method", "of", "EnergyBudget" ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/surface/turbulent.py#L187-L199
7,676
brian-rose/climlab
climlab/utils/legendre.py
Pn
def Pn(x): """Calculate Legendre polyomials P0 to P28 and returns them in a dictionary ``Pn``. :param float x: argument to calculate Legendre polynomials :return Pn: dictionary which contains order of Legendre polynomials (from 0 to 28) as keys and the corresponding evaluation of Legendre polynomials as values. :rtype: dict """ Pn = {} Pn['0'] = P0(x) Pn['1'] = P1(x) Pn['2'] = P2(x) Pn['3'] = P3(x) Pn['4'] = P4(x) Pn['5'] = P5(x) Pn['6'] = P6(x) Pn['8'] = P8(x) Pn['10'] = P10(x) Pn['12'] = P12(x) Pn['14'] = P14(x) Pn['16'] = P16(x) Pn['18'] = P18(x) Pn['20'] = P20(x) Pn['22'] = P22(x) Pn['24'] = P24(x) Pn['26'] = P26(x) Pn['28'] = P28(x) return Pn
python
def Pn(x): """Calculate Legendre polyomials P0 to P28 and returns them in a dictionary ``Pn``. :param float x: argument to calculate Legendre polynomials :return Pn: dictionary which contains order of Legendre polynomials (from 0 to 28) as keys and the corresponding evaluation of Legendre polynomials as values. :rtype: dict """ Pn = {} Pn['0'] = P0(x) Pn['1'] = P1(x) Pn['2'] = P2(x) Pn['3'] = P3(x) Pn['4'] = P4(x) Pn['5'] = P5(x) Pn['6'] = P6(x) Pn['8'] = P8(x) Pn['10'] = P10(x) Pn['12'] = P12(x) Pn['14'] = P14(x) Pn['16'] = P16(x) Pn['18'] = P18(x) Pn['20'] = P20(x) Pn['22'] = P22(x) Pn['24'] = P24(x) Pn['26'] = P26(x) Pn['28'] = P28(x) return Pn
[ "def", "Pn", "(", "x", ")", ":", "Pn", "=", "{", "}", "Pn", "[", "'0'", "]", "=", "P0", "(", "x", ")", "Pn", "[", "'1'", "]", "=", "P1", "(", "x", ")", "Pn", "[", "'2'", "]", "=", "P2", "(", "x", ")", "Pn", "[", "'3'", "]", "=", "P3", "(", "x", ")", "Pn", "[", "'4'", "]", "=", "P4", "(", "x", ")", "Pn", "[", "'5'", "]", "=", "P5", "(", "x", ")", "Pn", "[", "'6'", "]", "=", "P6", "(", "x", ")", "Pn", "[", "'8'", "]", "=", "P8", "(", "x", ")", "Pn", "[", "'10'", "]", "=", "P10", "(", "x", ")", "Pn", "[", "'12'", "]", "=", "P12", "(", "x", ")", "Pn", "[", "'14'", "]", "=", "P14", "(", "x", ")", "Pn", "[", "'16'", "]", "=", "P16", "(", "x", ")", "Pn", "[", "'18'", "]", "=", "P18", "(", "x", ")", "Pn", "[", "'20'", "]", "=", "P20", "(", "x", ")", "Pn", "[", "'22'", "]", "=", "P22", "(", "x", ")", "Pn", "[", "'24'", "]", "=", "P24", "(", "x", ")", "Pn", "[", "'26'", "]", "=", "P26", "(", "x", ")", "Pn", "[", "'28'", "]", "=", "P28", "(", "x", ")", "return", "Pn" ]
Calculate Legendre polyomials P0 to P28 and returns them in a dictionary ``Pn``. :param float x: argument to calculate Legendre polynomials :return Pn: dictionary which contains order of Legendre polynomials (from 0 to 28) as keys and the corresponding evaluation of Legendre polynomials as values. :rtype: dict
[ "Calculate", "Legendre", "polyomials", "P0", "to", "P28", "and", "returns", "them", "in", "a", "dictionary", "Pn", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/utils/legendre.py#L6-L36
7,677
brian-rose/climlab
climlab/utils/legendre.py
Pnprime
def Pnprime(x): """Calculates first derivatives of Legendre polynomials and returns them in a dictionary ``Pnprime``. :param float x: argument to calculate first derivate of Legendre polynomials :return Pn: dictionary which contains order of Legendre polynomials (from 0 to 4 and even numbers until 14) as keys and the corresponding evaluation of first derivative of Legendre polynomials as values. :rtype: dict """ Pnprime = {} Pnprime['0'] = 0 Pnprime['1'] = P1prime(x) Pnprime['2'] = P2prime(x) Pnprime['3'] = P3prime(x) Pnprime['4'] = P4prime(x) Pnprime['6'] = P6prime(x) Pnprime['8'] = P8prime(x) Pnprime['10'] = P10prime(x) Pnprime['12'] = P12prime(x) Pnprime['14'] = P14prime(x) return Pnprime
python
def Pnprime(x): """Calculates first derivatives of Legendre polynomials and returns them in a dictionary ``Pnprime``. :param float x: argument to calculate first derivate of Legendre polynomials :return Pn: dictionary which contains order of Legendre polynomials (from 0 to 4 and even numbers until 14) as keys and the corresponding evaluation of first derivative of Legendre polynomials as values. :rtype: dict """ Pnprime = {} Pnprime['0'] = 0 Pnprime['1'] = P1prime(x) Pnprime['2'] = P2prime(x) Pnprime['3'] = P3prime(x) Pnprime['4'] = P4prime(x) Pnprime['6'] = P6prime(x) Pnprime['8'] = P8prime(x) Pnprime['10'] = P10prime(x) Pnprime['12'] = P12prime(x) Pnprime['14'] = P14prime(x) return Pnprime
[ "def", "Pnprime", "(", "x", ")", ":", "Pnprime", "=", "{", "}", "Pnprime", "[", "'0'", "]", "=", "0", "Pnprime", "[", "'1'", "]", "=", "P1prime", "(", "x", ")", "Pnprime", "[", "'2'", "]", "=", "P2prime", "(", "x", ")", "Pnprime", "[", "'3'", "]", "=", "P3prime", "(", "x", ")", "Pnprime", "[", "'4'", "]", "=", "P4prime", "(", "x", ")", "Pnprime", "[", "'6'", "]", "=", "P6prime", "(", "x", ")", "Pnprime", "[", "'8'", "]", "=", "P8prime", "(", "x", ")", "Pnprime", "[", "'10'", "]", "=", "P10prime", "(", "x", ")", "Pnprime", "[", "'12'", "]", "=", "P12prime", "(", "x", ")", "Pnprime", "[", "'14'", "]", "=", "P14prime", "(", "x", ")", "return", "Pnprime" ]
Calculates first derivatives of Legendre polynomials and returns them in a dictionary ``Pnprime``. :param float x: argument to calculate first derivate of Legendre polynomials :return Pn: dictionary which contains order of Legendre polynomials (from 0 to 4 and even numbers until 14) as keys and the corresponding evaluation of first derivative of Legendre polynomials as values. :rtype: dict
[ "Calculates", "first", "derivatives", "of", "Legendre", "polynomials", "and", "returns", "them", "in", "a", "dictionary", "Pnprime", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/utils/legendre.py#L38-L61
7,678
brian-rose/climlab
climlab/model/ebm.py
EBM.inferred_heat_transport
def inferred_heat_transport(self): """Calculates the inferred heat transport by integrating the TOA energy imbalance from pole to pole. The method is calculating .. math:: H(\\varphi) = 2 \pi R^2 \int_{-\pi/2}^{\\varphi} cos\phi \ R_{TOA} d\phi where :math:`R_{TOA}` is the net radiation at top of atmosphere. :return: total heat transport on the latitude grid in unit :math:`\\textrm{PW}` :rtype: array of size ``np.size(self.lat_lat)`` :Example: .. plot:: code_input_manual/example_EBM_inferred_heat_transport.py :include-source: """ phi = np.deg2rad(self.lat) energy_in = np.squeeze(self.net_radiation) return (1E-15 * 2 * np.math.pi * const.a**2 * integrate.cumtrapz(np.cos(phi)*energy_in, x=phi, initial=0.))
python
def inferred_heat_transport(self): """Calculates the inferred heat transport by integrating the TOA energy imbalance from pole to pole. The method is calculating .. math:: H(\\varphi) = 2 \pi R^2 \int_{-\pi/2}^{\\varphi} cos\phi \ R_{TOA} d\phi where :math:`R_{TOA}` is the net radiation at top of atmosphere. :return: total heat transport on the latitude grid in unit :math:`\\textrm{PW}` :rtype: array of size ``np.size(self.lat_lat)`` :Example: .. plot:: code_input_manual/example_EBM_inferred_heat_transport.py :include-source: """ phi = np.deg2rad(self.lat) energy_in = np.squeeze(self.net_radiation) return (1E-15 * 2 * np.math.pi * const.a**2 * integrate.cumtrapz(np.cos(phi)*energy_in, x=phi, initial=0.))
[ "def", "inferred_heat_transport", "(", "self", ")", ":", "phi", "=", "np", ".", "deg2rad", "(", "self", ".", "lat", ")", "energy_in", "=", "np", ".", "squeeze", "(", "self", ".", "net_radiation", ")", "return", "(", "1E-15", "*", "2", "*", "np", ".", "math", ".", "pi", "*", "const", ".", "a", "**", "2", "*", "integrate", ".", "cumtrapz", "(", "np", ".", "cos", "(", "phi", ")", "*", "energy_in", ",", "x", "=", "phi", ",", "initial", "=", "0.", ")", ")" ]
Calculates the inferred heat transport by integrating the TOA energy imbalance from pole to pole. The method is calculating .. math:: H(\\varphi) = 2 \pi R^2 \int_{-\pi/2}^{\\varphi} cos\phi \ R_{TOA} d\phi where :math:`R_{TOA}` is the net radiation at top of atmosphere. :return: total heat transport on the latitude grid in unit :math:`\\textrm{PW}` :rtype: array of size ``np.size(self.lat_lat)`` :Example: .. plot:: code_input_manual/example_EBM_inferred_heat_transport.py :include-source:
[ "Calculates", "the", "inferred", "heat", "transport", "by", "integrating", "the", "TOA", "energy", "imbalance", "from", "pole", "to", "pole", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/model/ebm.py#L312-L337
7,679
brian-rose/climlab
climlab/radiation/rrtm/_rrtmg_lw/setup.py
rrtmg_lw_gen_source
def rrtmg_lw_gen_source(ext, build_dir): '''Add RRTMG_LW fortran source if Fortran 90 compiler available, if no compiler is found do not try to build the extension.''' thispath = config.local_path module_src = [] for item in modules: fullname = join(thispath,'rrtmg_lw_v4.85','gcm_model','modules',item) module_src.append(fullname) for item in src: if item in mod_src: fullname = join(thispath,'sourcemods',item) else: fullname = join(thispath,'rrtmg_lw_v4.85','gcm_model','src',item) module_src.append(fullname) sourcelist = [join(thispath, '_rrtmg_lw.pyf'), join(thispath, 'Driver.f90')] try: config.have_f90c() return module_src + sourcelist except: print('No Fortran 90 compiler found, not building RRTMG_LW extension!') return None
python
def rrtmg_lw_gen_source(ext, build_dir): '''Add RRTMG_LW fortran source if Fortran 90 compiler available, if no compiler is found do not try to build the extension.''' thispath = config.local_path module_src = [] for item in modules: fullname = join(thispath,'rrtmg_lw_v4.85','gcm_model','modules',item) module_src.append(fullname) for item in src: if item in mod_src: fullname = join(thispath,'sourcemods',item) else: fullname = join(thispath,'rrtmg_lw_v4.85','gcm_model','src',item) module_src.append(fullname) sourcelist = [join(thispath, '_rrtmg_lw.pyf'), join(thispath, 'Driver.f90')] try: config.have_f90c() return module_src + sourcelist except: print('No Fortran 90 compiler found, not building RRTMG_LW extension!') return None
[ "def", "rrtmg_lw_gen_source", "(", "ext", ",", "build_dir", ")", ":", "thispath", "=", "config", ".", "local_path", "module_src", "=", "[", "]", "for", "item", "in", "modules", ":", "fullname", "=", "join", "(", "thispath", ",", "'rrtmg_lw_v4.85'", ",", "'gcm_model'", ",", "'modules'", ",", "item", ")", "module_src", ".", "append", "(", "fullname", ")", "for", "item", "in", "src", ":", "if", "item", "in", "mod_src", ":", "fullname", "=", "join", "(", "thispath", ",", "'sourcemods'", ",", "item", ")", "else", ":", "fullname", "=", "join", "(", "thispath", ",", "'rrtmg_lw_v4.85'", ",", "'gcm_model'", ",", "'src'", ",", "item", ")", "module_src", ".", "append", "(", "fullname", ")", "sourcelist", "=", "[", "join", "(", "thispath", ",", "'_rrtmg_lw.pyf'", ")", ",", "join", "(", "thispath", ",", "'Driver.f90'", ")", "]", "try", ":", "config", ".", "have_f90c", "(", ")", "return", "module_src", "+", "sourcelist", "except", ":", "print", "(", "'No Fortran 90 compiler found, not building RRTMG_LW extension!'", ")", "return", "None" ]
Add RRTMG_LW fortran source if Fortran 90 compiler available, if no compiler is found do not try to build the extension.
[ "Add", "RRTMG_LW", "fortran", "source", "if", "Fortran", "90", "compiler", "available", "if", "no", "compiler", "is", "found", "do", "not", "try", "to", "build", "the", "extension", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/rrtm/_rrtmg_lw/setup.py#L77-L98
7,680
brian-rose/climlab
climlab/process/time_dependent_process.py
TimeDependentProcess.compute
def compute(self): """Computes the tendencies for all state variables given current state and specified input. The function first computes all diagnostic processes. They don't produce any tendencies directly but they may affect the other processes (such as change in solar distribution). Subsequently, all tendencies and diagnostics for all explicit processes are computed. Tendencies due to implicit and adjustment processes need to be calculated from a state that is already adjusted after explicit alteration. For that reason the explicit tendencies are applied to the states temporarily. Now all tendencies from implicit processes are calculated by matrix inversions and similar to the explicit tendencies, the implicit ones are applied to the states temporarily. Subsequently, all instantaneous adjustments are computed. Then the changes that were made to the states from explicit and implicit processes are removed again as this :class:`~climlab.process.time_dependent_process.TimeDependentProcess.compute()` function is supposed to calculate only tendencies and not apply them to the states. Finally, all calculated tendencies from all processes are collected for each state, summed up and stored in the dictionary ``self.tendencies``, which is an attribute of the time-dependent-process object, for which the :class:`~climlab.process.time_dependent_process.TimeDependentProcess.compute()` method has been called. **Object attributes** \n During method execution following object attributes are modified: :ivar dict tendencies: dictionary that holds tendencies for all states is calculated for current timestep through adding up tendencies from explicit, implicit and adjustment processes. :ivar dict diagnostics: process diagnostic dictionary is updated by diagnostic dictionaries of subprocesses after computation of tendencies. """ # First reset tendencies to zero -- recomputing them is the point of this method for varname in self.tendencies: self.tendencies[varname] *= 0. if not self.has_process_type_list: self._build_process_type_list() tendencies = {} ignored = self._compute_type('diagnostic') tendencies['explicit'] = self._compute_type('explicit') # Tendencies due to implicit and adjustment processes need to be # calculated from a state that is already adjusted after explicit stuff # So apply the tendencies temporarily and then remove them again for name, var in self.state.items(): var += tendencies['explicit'][name] * self.timestep # Now compute all implicit processes -- matrix inversions tendencies['implicit'] = self._compute_type('implicit') # Same deal ... temporarily apply tendencies from implicit step for name, var in self.state.items(): var += tendencies['implicit'][name] * self.timestep # Finally compute all instantaneous adjustments -- expressed as explicit forward step tendencies['adjustment'] = self._compute_type('adjustment') # Now remove the changes from the model state for name, var in self.state.items(): var -= ( (tendencies['implicit'][name] + tendencies['explicit'][name]) * self.timestep) # Sum up all subprocess tendencies for proctype in ['explicit', 'implicit', 'adjustment']: for varname, tend in tendencies[proctype].items(): self.tendencies[varname] += tend # Finally compute my own tendencies, if any self_tend = self._compute() # Adjustment processes _compute method returns absolute adjustment # Needs to be converted to rate of change if self.time_type is 'adjustment': for varname, adj in self_tend.items(): self_tend[varname] /= self.timestep for varname, tend in self_tend.items(): self.tendencies[varname] += tend return self.tendencies
python
def compute(self): """Computes the tendencies for all state variables given current state and specified input. The function first computes all diagnostic processes. They don't produce any tendencies directly but they may affect the other processes (such as change in solar distribution). Subsequently, all tendencies and diagnostics for all explicit processes are computed. Tendencies due to implicit and adjustment processes need to be calculated from a state that is already adjusted after explicit alteration. For that reason the explicit tendencies are applied to the states temporarily. Now all tendencies from implicit processes are calculated by matrix inversions and similar to the explicit tendencies, the implicit ones are applied to the states temporarily. Subsequently, all instantaneous adjustments are computed. Then the changes that were made to the states from explicit and implicit processes are removed again as this :class:`~climlab.process.time_dependent_process.TimeDependentProcess.compute()` function is supposed to calculate only tendencies and not apply them to the states. Finally, all calculated tendencies from all processes are collected for each state, summed up and stored in the dictionary ``self.tendencies``, which is an attribute of the time-dependent-process object, for which the :class:`~climlab.process.time_dependent_process.TimeDependentProcess.compute()` method has been called. **Object attributes** \n During method execution following object attributes are modified: :ivar dict tendencies: dictionary that holds tendencies for all states is calculated for current timestep through adding up tendencies from explicit, implicit and adjustment processes. :ivar dict diagnostics: process diagnostic dictionary is updated by diagnostic dictionaries of subprocesses after computation of tendencies. """ # First reset tendencies to zero -- recomputing them is the point of this method for varname in self.tendencies: self.tendencies[varname] *= 0. if not self.has_process_type_list: self._build_process_type_list() tendencies = {} ignored = self._compute_type('diagnostic') tendencies['explicit'] = self._compute_type('explicit') # Tendencies due to implicit and adjustment processes need to be # calculated from a state that is already adjusted after explicit stuff # So apply the tendencies temporarily and then remove them again for name, var in self.state.items(): var += tendencies['explicit'][name] * self.timestep # Now compute all implicit processes -- matrix inversions tendencies['implicit'] = self._compute_type('implicit') # Same deal ... temporarily apply tendencies from implicit step for name, var in self.state.items(): var += tendencies['implicit'][name] * self.timestep # Finally compute all instantaneous adjustments -- expressed as explicit forward step tendencies['adjustment'] = self._compute_type('adjustment') # Now remove the changes from the model state for name, var in self.state.items(): var -= ( (tendencies['implicit'][name] + tendencies['explicit'][name]) * self.timestep) # Sum up all subprocess tendencies for proctype in ['explicit', 'implicit', 'adjustment']: for varname, tend in tendencies[proctype].items(): self.tendencies[varname] += tend # Finally compute my own tendencies, if any self_tend = self._compute() # Adjustment processes _compute method returns absolute adjustment # Needs to be converted to rate of change if self.time_type is 'adjustment': for varname, adj in self_tend.items(): self_tend[varname] /= self.timestep for varname, tend in self_tend.items(): self.tendencies[varname] += tend return self.tendencies
[ "def", "compute", "(", "self", ")", ":", "# First reset tendencies to zero -- recomputing them is the point of this method", "for", "varname", "in", "self", ".", "tendencies", ":", "self", ".", "tendencies", "[", "varname", "]", "*=", "0.", "if", "not", "self", ".", "has_process_type_list", ":", "self", ".", "_build_process_type_list", "(", ")", "tendencies", "=", "{", "}", "ignored", "=", "self", ".", "_compute_type", "(", "'diagnostic'", ")", "tendencies", "[", "'explicit'", "]", "=", "self", ".", "_compute_type", "(", "'explicit'", ")", "# Tendencies due to implicit and adjustment processes need to be", "# calculated from a state that is already adjusted after explicit stuff", "# So apply the tendencies temporarily and then remove them again", "for", "name", ",", "var", "in", "self", ".", "state", ".", "items", "(", ")", ":", "var", "+=", "tendencies", "[", "'explicit'", "]", "[", "name", "]", "*", "self", ".", "timestep", "# Now compute all implicit processes -- matrix inversions", "tendencies", "[", "'implicit'", "]", "=", "self", ".", "_compute_type", "(", "'implicit'", ")", "# Same deal ... temporarily apply tendencies from implicit step", "for", "name", ",", "var", "in", "self", ".", "state", ".", "items", "(", ")", ":", "var", "+=", "tendencies", "[", "'implicit'", "]", "[", "name", "]", "*", "self", ".", "timestep", "# Finally compute all instantaneous adjustments -- expressed as explicit forward step", "tendencies", "[", "'adjustment'", "]", "=", "self", ".", "_compute_type", "(", "'adjustment'", ")", "# Now remove the changes from the model state", "for", "name", ",", "var", "in", "self", ".", "state", ".", "items", "(", ")", ":", "var", "-=", "(", "(", "tendencies", "[", "'implicit'", "]", "[", "name", "]", "+", "tendencies", "[", "'explicit'", "]", "[", "name", "]", ")", "*", "self", ".", "timestep", ")", "# Sum up all subprocess tendencies", "for", "proctype", "in", "[", "'explicit'", ",", "'implicit'", ",", "'adjustment'", "]", ":", "for", "varname", ",", "tend", "in", "tendencies", "[", "proctype", "]", ".", "items", "(", ")", ":", "self", ".", "tendencies", "[", "varname", "]", "+=", "tend", "# Finally compute my own tendencies, if any", "self_tend", "=", "self", ".", "_compute", "(", ")", "# Adjustment processes _compute method returns absolute adjustment", "# Needs to be converted to rate of change", "if", "self", ".", "time_type", "is", "'adjustment'", ":", "for", "varname", ",", "adj", "in", "self_tend", ".", "items", "(", ")", ":", "self_tend", "[", "varname", "]", "/=", "self", ".", "timestep", "for", "varname", ",", "tend", "in", "self_tend", ".", "items", "(", ")", ":", "self", ".", "tendencies", "[", "varname", "]", "+=", "tend", "return", "self", ".", "tendencies" ]
Computes the tendencies for all state variables given current state and specified input. The function first computes all diagnostic processes. They don't produce any tendencies directly but they may affect the other processes (such as change in solar distribution). Subsequently, all tendencies and diagnostics for all explicit processes are computed. Tendencies due to implicit and adjustment processes need to be calculated from a state that is already adjusted after explicit alteration. For that reason the explicit tendencies are applied to the states temporarily. Now all tendencies from implicit processes are calculated by matrix inversions and similar to the explicit tendencies, the implicit ones are applied to the states temporarily. Subsequently, all instantaneous adjustments are computed. Then the changes that were made to the states from explicit and implicit processes are removed again as this :class:`~climlab.process.time_dependent_process.TimeDependentProcess.compute()` function is supposed to calculate only tendencies and not apply them to the states. Finally, all calculated tendencies from all processes are collected for each state, summed up and stored in the dictionary ``self.tendencies``, which is an attribute of the time-dependent-process object, for which the :class:`~climlab.process.time_dependent_process.TimeDependentProcess.compute()` method has been called. **Object attributes** \n During method execution following object attributes are modified: :ivar dict tendencies: dictionary that holds tendencies for all states is calculated for current timestep through adding up tendencies from explicit, implicit and adjustment processes. :ivar dict diagnostics: process diagnostic dictionary is updated by diagnostic dictionaries of subprocesses after computation of tendencies.
[ "Computes", "the", "tendencies", "for", "all", "state", "variables", "given", "current", "state", "and", "specified", "input", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/time_dependent_process.py#L162-L243
7,681
brian-rose/climlab
climlab/process/time_dependent_process.py
TimeDependentProcess._compute_type
def _compute_type(self, proctype): """Computes tendencies due to all subprocesses of given type ``'proctype'``. Also pass all diagnostics up to parent process.""" tendencies = {} for varname in self.state: tendencies[varname] = 0. * self.state[varname] for proc in self.process_types[proctype]: # Asynchronous coupling # if subprocess has longer timestep than parent # We compute subprocess tendencies once # and apply the same tendency at each substep step_ratio = int(proc.timestep / self.timestep) # Does the number of parent steps divide evenly by the ratio? # If so, it's time to do a subprocess step. if self.time['steps'] % step_ratio == 0: proc.time['active_now'] = True tenddict = proc.compute() else: # proc.tendencies is unchanged from last subprocess timestep if we didn't recompute it above proc.time['active_now'] = False tenddict = proc.tendencies for name, tend in tenddict.items(): tendencies[name] += tend for diagname, value in proc.diagnostics.items(): self.__setattr__(diagname, value) return tendencies
python
def _compute_type(self, proctype): """Computes tendencies due to all subprocesses of given type ``'proctype'``. Also pass all diagnostics up to parent process.""" tendencies = {} for varname in self.state: tendencies[varname] = 0. * self.state[varname] for proc in self.process_types[proctype]: # Asynchronous coupling # if subprocess has longer timestep than parent # We compute subprocess tendencies once # and apply the same tendency at each substep step_ratio = int(proc.timestep / self.timestep) # Does the number of parent steps divide evenly by the ratio? # If so, it's time to do a subprocess step. if self.time['steps'] % step_ratio == 0: proc.time['active_now'] = True tenddict = proc.compute() else: # proc.tendencies is unchanged from last subprocess timestep if we didn't recompute it above proc.time['active_now'] = False tenddict = proc.tendencies for name, tend in tenddict.items(): tendencies[name] += tend for diagname, value in proc.diagnostics.items(): self.__setattr__(diagname, value) return tendencies
[ "def", "_compute_type", "(", "self", ",", "proctype", ")", ":", "tendencies", "=", "{", "}", "for", "varname", "in", "self", ".", "state", ":", "tendencies", "[", "varname", "]", "=", "0.", "*", "self", ".", "state", "[", "varname", "]", "for", "proc", "in", "self", ".", "process_types", "[", "proctype", "]", ":", "# Asynchronous coupling", "# if subprocess has longer timestep than parent", "# We compute subprocess tendencies once", "# and apply the same tendency at each substep", "step_ratio", "=", "int", "(", "proc", ".", "timestep", "/", "self", ".", "timestep", ")", "# Does the number of parent steps divide evenly by the ratio?", "# If so, it's time to do a subprocess step.", "if", "self", ".", "time", "[", "'steps'", "]", "%", "step_ratio", "==", "0", ":", "proc", ".", "time", "[", "'active_now'", "]", "=", "True", "tenddict", "=", "proc", ".", "compute", "(", ")", "else", ":", "# proc.tendencies is unchanged from last subprocess timestep if we didn't recompute it above", "proc", ".", "time", "[", "'active_now'", "]", "=", "False", "tenddict", "=", "proc", ".", "tendencies", "for", "name", ",", "tend", "in", "tenddict", ".", "items", "(", ")", ":", "tendencies", "[", "name", "]", "+=", "tend", "for", "diagname", ",", "value", "in", "proc", ".", "diagnostics", ".", "items", "(", ")", ":", "self", ".", "__setattr__", "(", "diagname", ",", "value", ")", "return", "tendencies" ]
Computes tendencies due to all subprocesses of given type ``'proctype'``. Also pass all diagnostics up to parent process.
[ "Computes", "tendencies", "due", "to", "all", "subprocesses", "of", "given", "type", "proctype", ".", "Also", "pass", "all", "diagnostics", "up", "to", "parent", "process", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/time_dependent_process.py#L245-L270
7,682
brian-rose/climlab
climlab/process/time_dependent_process.py
TimeDependentProcess._compute
def _compute(self): """Where the tendencies are actually computed... Needs to be implemented for each daughter class Returns a dictionary with same keys as self.state""" tendencies = {} for name, value in self.state.items(): tendencies[name] = value * 0. return tendencies
python
def _compute(self): """Where the tendencies are actually computed... Needs to be implemented for each daughter class Returns a dictionary with same keys as self.state""" tendencies = {} for name, value in self.state.items(): tendencies[name] = value * 0. return tendencies
[ "def", "_compute", "(", "self", ")", ":", "tendencies", "=", "{", "}", "for", "name", ",", "value", "in", "self", ".", "state", ".", "items", "(", ")", ":", "tendencies", "[", "name", "]", "=", "value", "*", "0.", "return", "tendencies" ]
Where the tendencies are actually computed... Needs to be implemented for each daughter class Returns a dictionary with same keys as self.state
[ "Where", "the", "tendencies", "are", "actually", "computed", "..." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/time_dependent_process.py#L272-L281
7,683
brian-rose/climlab
climlab/process/time_dependent_process.py
TimeDependentProcess._build_process_type_list
def _build_process_type_list(self): """Generates lists of processes organized by process type. Following object attributes are generated or updated: :ivar dict process_types: a dictionary with entries: ``'diagnostic'``, ``'explicit'``, ``'implicit'`` and ``'adjustment'`` which point to a list of processes according to the process types. The ``process_types`` dictionary is created while walking through the processes with :func:`~climlab.utils.walk.walk_processes` CHANGING THIS TO REFER ONLY TO THE CURRENT LEVEL IN SUBPROCESS TREE """ self.process_types = {'diagnostic': [], 'explicit': [], 'implicit': [], 'adjustment': []} #for name, proc, level in walk.walk_processes(self, topdown=self.topdown): # self.process_types[proc.time_type].append(proc) for name, proc in self.subprocess.items(): self.process_types[proc.time_type].append(proc) self.has_process_type_list = True
python
def _build_process_type_list(self): """Generates lists of processes organized by process type. Following object attributes are generated or updated: :ivar dict process_types: a dictionary with entries: ``'diagnostic'``, ``'explicit'``, ``'implicit'`` and ``'adjustment'`` which point to a list of processes according to the process types. The ``process_types`` dictionary is created while walking through the processes with :func:`~climlab.utils.walk.walk_processes` CHANGING THIS TO REFER ONLY TO THE CURRENT LEVEL IN SUBPROCESS TREE """ self.process_types = {'diagnostic': [], 'explicit': [], 'implicit': [], 'adjustment': []} #for name, proc, level in walk.walk_processes(self, topdown=self.topdown): # self.process_types[proc.time_type].append(proc) for name, proc in self.subprocess.items(): self.process_types[proc.time_type].append(proc) self.has_process_type_list = True
[ "def", "_build_process_type_list", "(", "self", ")", ":", "self", ".", "process_types", "=", "{", "'diagnostic'", ":", "[", "]", ",", "'explicit'", ":", "[", "]", ",", "'implicit'", ":", "[", "]", ",", "'adjustment'", ":", "[", "]", "}", "#for name, proc, level in walk.walk_processes(self, topdown=self.topdown):", "# self.process_types[proc.time_type].append(proc)", "for", "name", ",", "proc", "in", "self", ".", "subprocess", ".", "items", "(", ")", ":", "self", ".", "process_types", "[", "proc", ".", "time_type", "]", ".", "append", "(", "proc", ")", "self", ".", "has_process_type_list", "=", "True" ]
Generates lists of processes organized by process type. Following object attributes are generated or updated: :ivar dict process_types: a dictionary with entries: ``'diagnostic'``, ``'explicit'``, ``'implicit'`` and ``'adjustment'`` which point to a list of processes according to the process types. The ``process_types`` dictionary is created while walking through the processes with :func:`~climlab.utils.walk.walk_processes` CHANGING THIS TO REFER ONLY TO THE CURRENT LEVEL IN SUBPROCESS TREE
[ "Generates", "lists", "of", "processes", "organized", "by", "process", "type", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/time_dependent_process.py#L283-L305
7,684
brian-rose/climlab
climlab/process/time_dependent_process.py
TimeDependentProcess.step_forward
def step_forward(self): """Updates state variables with computed tendencies. Calls the :func:`compute` method to get current tendencies for all process states. Multiplied with the timestep and added up to the state variables is updating all model states. :Example: :: >>> import climlab >>> model = climlab.EBM() >>> # checking time step counter >>> model.time['steps'] 0 >>> # stepping the model forward >>> model.step_forward() >>> # step counter increased >>> model.time['steps'] 1 """ tenddict = self.compute() # Total tendency is applied as an explicit forward timestep # (already accounting properly for order of operations in compute() ) for varname, tend in tenddict.items(): self.state[varname] += tend * self.timestep # Update all time counters for this and all subprocesses in the tree # Also pass diagnostics up the process tree for name, proc, level in walk.walk_processes(self, ignoreFlag=True): if proc.time['active_now']: proc._update_time()
python
def step_forward(self): """Updates state variables with computed tendencies. Calls the :func:`compute` method to get current tendencies for all process states. Multiplied with the timestep and added up to the state variables is updating all model states. :Example: :: >>> import climlab >>> model = climlab.EBM() >>> # checking time step counter >>> model.time['steps'] 0 >>> # stepping the model forward >>> model.step_forward() >>> # step counter increased >>> model.time['steps'] 1 """ tenddict = self.compute() # Total tendency is applied as an explicit forward timestep # (already accounting properly for order of operations in compute() ) for varname, tend in tenddict.items(): self.state[varname] += tend * self.timestep # Update all time counters for this and all subprocesses in the tree # Also pass diagnostics up the process tree for name, proc, level in walk.walk_processes(self, ignoreFlag=True): if proc.time['active_now']: proc._update_time()
[ "def", "step_forward", "(", "self", ")", ":", "tenddict", "=", "self", ".", "compute", "(", ")", "# Total tendency is applied as an explicit forward timestep", "# (already accounting properly for order of operations in compute() )", "for", "varname", ",", "tend", "in", "tenddict", ".", "items", "(", ")", ":", "self", ".", "state", "[", "varname", "]", "+=", "tend", "*", "self", ".", "timestep", "# Update all time counters for this and all subprocesses in the tree", "# Also pass diagnostics up the process tree", "for", "name", ",", "proc", ",", "level", "in", "walk", ".", "walk_processes", "(", "self", ",", "ignoreFlag", "=", "True", ")", ":", "if", "proc", ".", "time", "[", "'active_now'", "]", ":", "proc", ".", "_update_time", "(", ")" ]
Updates state variables with computed tendencies. Calls the :func:`compute` method to get current tendencies for all process states. Multiplied with the timestep and added up to the state variables is updating all model states. :Example: :: >>> import climlab >>> model = climlab.EBM() >>> # checking time step counter >>> model.time['steps'] 0 >>> # stepping the model forward >>> model.step_forward() >>> # step counter increased >>> model.time['steps'] 1
[ "Updates", "state", "variables", "with", "computed", "tendencies", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/time_dependent_process.py#L307-L342
7,685
brian-rose/climlab
climlab/process/time_dependent_process.py
TimeDependentProcess._update_time
def _update_time(self): """Increments the timestep counter by one. Furthermore ``self.time['days_elapsed']`` and ``self.time['num_steps_per_year']`` are updated. The function is called by the time stepping methods. """ self.time['steps'] += 1 # time in days since beginning self.time['days_elapsed'] += self.time['timestep'] / const.seconds_per_day if self.time['day_of_year_index'] >= self.time['num_steps_per_year']-1: self._do_new_calendar_year() else: self.time['day_of_year_index'] += 1
python
def _update_time(self): """Increments the timestep counter by one. Furthermore ``self.time['days_elapsed']`` and ``self.time['num_steps_per_year']`` are updated. The function is called by the time stepping methods. """ self.time['steps'] += 1 # time in days since beginning self.time['days_elapsed'] += self.time['timestep'] / const.seconds_per_day if self.time['day_of_year_index'] >= self.time['num_steps_per_year']-1: self._do_new_calendar_year() else: self.time['day_of_year_index'] += 1
[ "def", "_update_time", "(", "self", ")", ":", "self", ".", "time", "[", "'steps'", "]", "+=", "1", "# time in days since beginning", "self", ".", "time", "[", "'days_elapsed'", "]", "+=", "self", ".", "time", "[", "'timestep'", "]", "/", "const", ".", "seconds_per_day", "if", "self", ".", "time", "[", "'day_of_year_index'", "]", ">=", "self", ".", "time", "[", "'num_steps_per_year'", "]", "-", "1", ":", "self", ".", "_do_new_calendar_year", "(", ")", "else", ":", "self", ".", "time", "[", "'day_of_year_index'", "]", "+=", "1" ]
Increments the timestep counter by one. Furthermore ``self.time['days_elapsed']`` and ``self.time['num_steps_per_year']`` are updated. The function is called by the time stepping methods.
[ "Increments", "the", "timestep", "counter", "by", "one", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/time_dependent_process.py#L354-L369
7,686
brian-rose/climlab
climlab/process/time_dependent_process.py
TimeDependentProcess.integrate_years
def integrate_years(self, years=1.0, verbose=True): """Integrates the model by a given number of years. :param float years: integration time for the model in years [default: 1.0] :param bool verbose: information whether model time details should be printed [default: True] It calls :func:`step_forward` repetitively and calculates a time averaged value over the integrated period for every model state and all diagnostics processes. :Example: :: >>> import climlab >>> model = climlab.EBM() >>> model.global_mean_temperature() Field(11.997968598413685) >>> model.integrate_years(2.) Integrating for 180 steps, 730.4844 days, or 2.0 years. Total elapsed time is 2.0 years. >>> model.global_mean_temperature() Field(13.531055349437258) """ days = years * const.days_per_year numsteps = int(self.time['num_steps_per_year'] * years) if verbose: print("Integrating for " + str(numsteps) + " steps, " + str(days) + " days, or " + str(years) + " years.") # begin time loop for count in range(numsteps): # Compute the timestep self.step_forward() if count == 0: # on first step only... # This implements a generic time-averaging feature # using the list of model state variables self.timeave = self.state.copy() # add any new diagnostics to the timeave dictionary self.timeave.update(self.diagnostics) # reset all values to zero for varname, value in self.timeave.items(): # moves on to the next varname if value is None # this preserves NoneType diagnostics if value is None: continue self.timeave[varname] = 0*value # adding up all values for each timestep for varname in list(self.timeave.keys()): try: self.timeave[varname] += self.state[varname] except: try: self.timeave[varname] += self.diagnostics[varname] except: pass # calculating mean values through dividing the sum by number of steps for varname, value in self.timeave.items(): if value is None: continue self.timeave[varname] /= numsteps if verbose: print("Total elapsed time is %s years." % str(self.time['days_elapsed']/const.days_per_year))
python
def integrate_years(self, years=1.0, verbose=True): """Integrates the model by a given number of years. :param float years: integration time for the model in years [default: 1.0] :param bool verbose: information whether model time details should be printed [default: True] It calls :func:`step_forward` repetitively and calculates a time averaged value over the integrated period for every model state and all diagnostics processes. :Example: :: >>> import climlab >>> model = climlab.EBM() >>> model.global_mean_temperature() Field(11.997968598413685) >>> model.integrate_years(2.) Integrating for 180 steps, 730.4844 days, or 2.0 years. Total elapsed time is 2.0 years. >>> model.global_mean_temperature() Field(13.531055349437258) """ days = years * const.days_per_year numsteps = int(self.time['num_steps_per_year'] * years) if verbose: print("Integrating for " + str(numsteps) + " steps, " + str(days) + " days, or " + str(years) + " years.") # begin time loop for count in range(numsteps): # Compute the timestep self.step_forward() if count == 0: # on first step only... # This implements a generic time-averaging feature # using the list of model state variables self.timeave = self.state.copy() # add any new diagnostics to the timeave dictionary self.timeave.update(self.diagnostics) # reset all values to zero for varname, value in self.timeave.items(): # moves on to the next varname if value is None # this preserves NoneType diagnostics if value is None: continue self.timeave[varname] = 0*value # adding up all values for each timestep for varname in list(self.timeave.keys()): try: self.timeave[varname] += self.state[varname] except: try: self.timeave[varname] += self.diagnostics[varname] except: pass # calculating mean values through dividing the sum by number of steps for varname, value in self.timeave.items(): if value is None: continue self.timeave[varname] /= numsteps if verbose: print("Total elapsed time is %s years." % str(self.time['days_elapsed']/const.days_per_year))
[ "def", "integrate_years", "(", "self", ",", "years", "=", "1.0", ",", "verbose", "=", "True", ")", ":", "days", "=", "years", "*", "const", ".", "days_per_year", "numsteps", "=", "int", "(", "self", ".", "time", "[", "'num_steps_per_year'", "]", "*", "years", ")", "if", "verbose", ":", "print", "(", "\"Integrating for \"", "+", "str", "(", "numsteps", ")", "+", "\" steps, \"", "+", "str", "(", "days", ")", "+", "\" days, or \"", "+", "str", "(", "years", ")", "+", "\" years.\"", ")", "# begin time loop", "for", "count", "in", "range", "(", "numsteps", ")", ":", "# Compute the timestep", "self", ".", "step_forward", "(", ")", "if", "count", "==", "0", ":", "# on first step only...", "# This implements a generic time-averaging feature", "# using the list of model state variables", "self", ".", "timeave", "=", "self", ".", "state", ".", "copy", "(", ")", "# add any new diagnostics to the timeave dictionary", "self", ".", "timeave", ".", "update", "(", "self", ".", "diagnostics", ")", "# reset all values to zero", "for", "varname", ",", "value", "in", "self", ".", "timeave", ".", "items", "(", ")", ":", "# moves on to the next varname if value is None", "# this preserves NoneType diagnostics", "if", "value", "is", "None", ":", "continue", "self", ".", "timeave", "[", "varname", "]", "=", "0", "*", "value", "# adding up all values for each timestep", "for", "varname", "in", "list", "(", "self", ".", "timeave", ".", "keys", "(", ")", ")", ":", "try", ":", "self", ".", "timeave", "[", "varname", "]", "+=", "self", ".", "state", "[", "varname", "]", "except", ":", "try", ":", "self", ".", "timeave", "[", "varname", "]", "+=", "self", ".", "diagnostics", "[", "varname", "]", "except", ":", "pass", "# calculating mean values through dividing the sum by number of steps", "for", "varname", ",", "value", "in", "self", ".", "timeave", ".", "items", "(", ")", ":", "if", "value", "is", "None", ":", "continue", "self", ".", "timeave", "[", "varname", "]", "/=", "numsteps", "if", "verbose", ":", "print", "(", "\"Total elapsed time is %s years.\"", "%", "str", "(", "self", ".", "time", "[", "'days_elapsed'", "]", "/", "const", ".", "days_per_year", ")", ")" ]
Integrates the model by a given number of years. :param float years: integration time for the model in years [default: 1.0] :param bool verbose: information whether model time details should be printed [default: True] It calls :func:`step_forward` repetitively and calculates a time averaged value over the integrated period for every model state and all diagnostics processes. :Example: :: >>> import climlab >>> model = climlab.EBM() >>> model.global_mean_temperature() Field(11.997968598413685) >>> model.integrate_years(2.) Integrating for 180 steps, 730.4844 days, or 2.0 years. Total elapsed time is 2.0 years. >>> model.global_mean_temperature() Field(13.531055349437258)
[ "Integrates", "the", "model", "by", "a", "given", "number", "of", "years", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/time_dependent_process.py#L380-L449
7,687
brian-rose/climlab
climlab/process/time_dependent_process.py
TimeDependentProcess.integrate_days
def integrate_days(self, days=1.0, verbose=True): """Integrates the model forward for a specified number of days. It convertes the given number of days into years and calls :func:`integrate_years`. :param float days: integration time for the model in days [default: 1.0] :param bool verbose: information whether model time details should be printed [default: True] :Example: :: >>> import climlab >>> model = climlab.EBM() >>> model.global_mean_temperature() Field(11.997968598413685) >>> model.integrate_days(80.) Integrating for 19 steps, 80.0 days, or 0.219032740466 years. Total elapsed time is 0.211111111111 years. >>> model.global_mean_temperature() Field(11.873680783355553) """ years = days / const.days_per_year self.integrate_years(years=years, verbose=verbose)
python
def integrate_days(self, days=1.0, verbose=True): """Integrates the model forward for a specified number of days. It convertes the given number of days into years and calls :func:`integrate_years`. :param float days: integration time for the model in days [default: 1.0] :param bool verbose: information whether model time details should be printed [default: True] :Example: :: >>> import climlab >>> model = climlab.EBM() >>> model.global_mean_temperature() Field(11.997968598413685) >>> model.integrate_days(80.) Integrating for 19 steps, 80.0 days, or 0.219032740466 years. Total elapsed time is 0.211111111111 years. >>> model.global_mean_temperature() Field(11.873680783355553) """ years = days / const.days_per_year self.integrate_years(years=years, verbose=verbose)
[ "def", "integrate_days", "(", "self", ",", "days", "=", "1.0", ",", "verbose", "=", "True", ")", ":", "years", "=", "days", "/", "const", ".", "days_per_year", "self", ".", "integrate_years", "(", "years", "=", "years", ",", "verbose", "=", "verbose", ")" ]
Integrates the model forward for a specified number of days. It convertes the given number of days into years and calls :func:`integrate_years`. :param float days: integration time for the model in days [default: 1.0] :param bool verbose: information whether model time details should be printed [default: True] :Example: :: >>> import climlab >>> model = climlab.EBM() >>> model.global_mean_temperature() Field(11.997968598413685) >>> model.integrate_days(80.) Integrating for 19 steps, 80.0 days, or 0.219032740466 years. Total elapsed time is 0.211111111111 years. >>> model.global_mean_temperature() Field(11.873680783355553)
[ "Integrates", "the", "model", "forward", "for", "a", "specified", "number", "of", "days", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/time_dependent_process.py#L451-L481
7,688
brian-rose/climlab
climlab/process/time_dependent_process.py
TimeDependentProcess.integrate_converge
def integrate_converge(self, crit=1e-4, verbose=True): """Integrates the model until model states are converging. :param crit: exit criteria for difference of iterated solutions [default: 0.0001] :type crit: float :param bool verbose: information whether total elapsed time should be printed [default: True] :Example: :: >>> import climlab >>> model = climlab.EBM() >>> model.global_mean_temperature() Field(11.997968598413685) >>> model.integrate_converge() Total elapsed time is 10.0 years. >>> model.global_mean_temperature() Field(14.288155406577301) """ # implemented by m-kreuzer for varname, value in self.state.items(): value_old = copy.deepcopy(value) self.integrate_years(1,verbose=False) while np.max(np.abs(value_old-value)) > crit : value_old = copy.deepcopy(value) self.integrate_years(1,verbose=False) if verbose == True: print("Total elapsed time is %s years." % str(self.time['days_elapsed']/const.days_per_year))
python
def integrate_converge(self, crit=1e-4, verbose=True): """Integrates the model until model states are converging. :param crit: exit criteria for difference of iterated solutions [default: 0.0001] :type crit: float :param bool verbose: information whether total elapsed time should be printed [default: True] :Example: :: >>> import climlab >>> model = climlab.EBM() >>> model.global_mean_temperature() Field(11.997968598413685) >>> model.integrate_converge() Total elapsed time is 10.0 years. >>> model.global_mean_temperature() Field(14.288155406577301) """ # implemented by m-kreuzer for varname, value in self.state.items(): value_old = copy.deepcopy(value) self.integrate_years(1,verbose=False) while np.max(np.abs(value_old-value)) > crit : value_old = copy.deepcopy(value) self.integrate_years(1,verbose=False) if verbose == True: print("Total elapsed time is %s years." % str(self.time['days_elapsed']/const.days_per_year))
[ "def", "integrate_converge", "(", "self", ",", "crit", "=", "1e-4", ",", "verbose", "=", "True", ")", ":", "# implemented by m-kreuzer", "for", "varname", ",", "value", "in", "self", ".", "state", ".", "items", "(", ")", ":", "value_old", "=", "copy", ".", "deepcopy", "(", "value", ")", "self", ".", "integrate_years", "(", "1", ",", "verbose", "=", "False", ")", "while", "np", ".", "max", "(", "np", ".", "abs", "(", "value_old", "-", "value", ")", ")", ">", "crit", ":", "value_old", "=", "copy", ".", "deepcopy", "(", "value", ")", "self", ".", "integrate_years", "(", "1", ",", "verbose", "=", "False", ")", "if", "verbose", "==", "True", ":", "print", "(", "\"Total elapsed time is %s years.\"", "%", "str", "(", "self", ".", "time", "[", "'days_elapsed'", "]", "/", "const", ".", "days_per_year", ")", ")" ]
Integrates the model until model states are converging. :param crit: exit criteria for difference of iterated solutions [default: 0.0001] :type crit: float :param bool verbose: information whether total elapsed time should be printed [default: True] :Example: :: >>> import climlab >>> model = climlab.EBM() >>> model.global_mean_temperature() Field(11.997968598413685) >>> model.integrate_converge() Total elapsed time is 10.0 years. >>> model.global_mean_temperature() Field(14.288155406577301)
[ "Integrates", "the", "model", "until", "model", "states", "are", "converging", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/time_dependent_process.py#L483-L518
7,689
brian-rose/climlab
climlab/radiation/cam3/setup.py
cam3_gen_source
def cam3_gen_source(ext, build_dir): '''Add CAM3 fortran source if Fortran 90 compiler available, if no compiler is found do not try to build the extension.''' # Fortran 90 sources in order of compilation fort90source = ['pmgrid.F90', 'prescribed_aerosols.F90', 'shr_kind_mod.F90', 'quicksort.F90', 'abortutils.F90', 'absems.F90', 'wv_saturation.F90', 'aer_optics.F90', 'cmparray_mod.F90', 'shr_const_mod.F90', 'physconst.F90', 'pkg_cldoptics.F90', 'gffgch.F90', 'chem_surfvals.F90', 'volcrad.F90', 'radae.F90', 'radlw.F90', 'radsw.F90', 'crm.F90',] #thispath = abspath(config.local_path) thispath = config.local_path sourcelist = [] sourcelist.append(join(thispath,'_cam3.pyf')) for item in fort90source: sourcelist.append(join(thispath, 'src', item)) sourcelist.append(join(thispath,'Driver.f90')) try: config.have_f90c() return sourcelist except: print('No Fortran 90 compiler found, not building CAM3 extension!') return None
python
def cam3_gen_source(ext, build_dir): '''Add CAM3 fortran source if Fortran 90 compiler available, if no compiler is found do not try to build the extension.''' # Fortran 90 sources in order of compilation fort90source = ['pmgrid.F90', 'prescribed_aerosols.F90', 'shr_kind_mod.F90', 'quicksort.F90', 'abortutils.F90', 'absems.F90', 'wv_saturation.F90', 'aer_optics.F90', 'cmparray_mod.F90', 'shr_const_mod.F90', 'physconst.F90', 'pkg_cldoptics.F90', 'gffgch.F90', 'chem_surfvals.F90', 'volcrad.F90', 'radae.F90', 'radlw.F90', 'radsw.F90', 'crm.F90',] #thispath = abspath(config.local_path) thispath = config.local_path sourcelist = [] sourcelist.append(join(thispath,'_cam3.pyf')) for item in fort90source: sourcelist.append(join(thispath, 'src', item)) sourcelist.append(join(thispath,'Driver.f90')) try: config.have_f90c() return sourcelist except: print('No Fortran 90 compiler found, not building CAM3 extension!') return None
[ "def", "cam3_gen_source", "(", "ext", ",", "build_dir", ")", ":", "# Fortran 90 sources in order of compilation", "fort90source", "=", "[", "'pmgrid.F90'", ",", "'prescribed_aerosols.F90'", ",", "'shr_kind_mod.F90'", ",", "'quicksort.F90'", ",", "'abortutils.F90'", ",", "'absems.F90'", ",", "'wv_saturation.F90'", ",", "'aer_optics.F90'", ",", "'cmparray_mod.F90'", ",", "'shr_const_mod.F90'", ",", "'physconst.F90'", ",", "'pkg_cldoptics.F90'", ",", "'gffgch.F90'", ",", "'chem_surfvals.F90'", ",", "'volcrad.F90'", ",", "'radae.F90'", ",", "'radlw.F90'", ",", "'radsw.F90'", ",", "'crm.F90'", ",", "]", "#thispath = abspath(config.local_path)", "thispath", "=", "config", ".", "local_path", "sourcelist", "=", "[", "]", "sourcelist", ".", "append", "(", "join", "(", "thispath", ",", "'_cam3.pyf'", ")", ")", "for", "item", "in", "fort90source", ":", "sourcelist", ".", "append", "(", "join", "(", "thispath", ",", "'src'", ",", "item", ")", ")", "sourcelist", ".", "append", "(", "join", "(", "thispath", ",", "'Driver.f90'", ")", ")", "try", ":", "config", ".", "have_f90c", "(", ")", "return", "sourcelist", "except", ":", "print", "(", "'No Fortran 90 compiler found, not building CAM3 extension!'", ")", "return", "None" ]
Add CAM3 fortran source if Fortran 90 compiler available, if no compiler is found do not try to build the extension.
[ "Add", "CAM3", "fortran", "source", "if", "Fortran", "90", "compiler", "available", "if", "no", "compiler", "is", "found", "do", "not", "try", "to", "build", "the", "extension", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/cam3/setup.py#L39-L74
7,690
brian-rose/climlab
climlab/domain/field.py
global_mean
def global_mean(field): """Calculates the latitude weighted global mean of a field with latitude dependence. :param Field field: input field :raises: :exc:`ValueError` if input field has no latitude axis :return: latitude weighted global mean of the field :rtype: float :Example: initial global mean temperature of EBM model:: >>> import climlab >>> model = climlab.EBM() >>> climlab.global_mean(model.Ts) Field(11.997968598413685) """ try: lat = field.domain.lat.points except: raise ValueError('No latitude axis in input field.') try: # Field is 2D latitude / longitude lon = field.domain.lon.points return _global_mean_latlon(field.squeeze()) except: # Field is 1D latitude only (zonal average) lat_radians = np.deg2rad(lat) return _global_mean(field.squeeze(), lat_radians)
python
def global_mean(field): """Calculates the latitude weighted global mean of a field with latitude dependence. :param Field field: input field :raises: :exc:`ValueError` if input field has no latitude axis :return: latitude weighted global mean of the field :rtype: float :Example: initial global mean temperature of EBM model:: >>> import climlab >>> model = climlab.EBM() >>> climlab.global_mean(model.Ts) Field(11.997968598413685) """ try: lat = field.domain.lat.points except: raise ValueError('No latitude axis in input field.') try: # Field is 2D latitude / longitude lon = field.domain.lon.points return _global_mean_latlon(field.squeeze()) except: # Field is 1D latitude only (zonal average) lat_radians = np.deg2rad(lat) return _global_mean(field.squeeze(), lat_radians)
[ "def", "global_mean", "(", "field", ")", ":", "try", ":", "lat", "=", "field", ".", "domain", ".", "lat", ".", "points", "except", ":", "raise", "ValueError", "(", "'No latitude axis in input field.'", ")", "try", ":", "# Field is 2D latitude / longitude", "lon", "=", "field", ".", "domain", ".", "lon", ".", "points", "return", "_global_mean_latlon", "(", "field", ".", "squeeze", "(", ")", ")", "except", ":", "# Field is 1D latitude only (zonal average)", "lat_radians", "=", "np", ".", "deg2rad", "(", "lat", ")", "return", "_global_mean", "(", "field", ".", "squeeze", "(", ")", ",", "lat_radians", ")" ]
Calculates the latitude weighted global mean of a field with latitude dependence. :param Field field: input field :raises: :exc:`ValueError` if input field has no latitude axis :return: latitude weighted global mean of the field :rtype: float :Example: initial global mean temperature of EBM model:: >>> import climlab >>> model = climlab.EBM() >>> climlab.global_mean(model.Ts) Field(11.997968598413685)
[ "Calculates", "the", "latitude", "weighted", "global", "mean", "of", "a", "field", "with", "latitude", "dependence", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/domain/field.py#L194-L224
7,691
brian-rose/climlab
climlab/domain/field.py
to_latlon
def to_latlon(array, domain, axis = 'lon'): """Broadcasts a 1D axis dependent array across another axis. :param array input_array: the 1D array used for broadcasting :param domain: the domain associated with that array :param axis: the axis that the input array will be broadcasted across [default: 'lon'] :return: Field with the same shape as the domain :Example: :: >>> import climlab >>> from climlab.domain.field import to_latlon >>> import numpy as np >>> state = climlab.surface_state(num_lat=3, num_lon=4) >>> m = climlab.EBM_annual(state=state) >>> insolation = np.array([237., 417., 237.]) >>> insolation = to_latlon(insolation, domain = m.domains['Ts']) >>> insolation.shape (3, 4, 1) >>> insolation Field([[[ 237.], [[ 417.], [[ 237.], [ 237.], [ 417.], [ 237.], [ 237.], [ 417.], [ 237.], [ 237.]], [ 417.]], [ 237.]]]) """ # if array is latitude dependent (has the same shape as lat) axis, array, depth = np.meshgrid(domain.axes[axis].points, array, domain.axes['depth'].points) if axis == 'lat': # if array is longitude dependent (has the same shape as lon) np.swapaxes(array,1,0) return Field(array, domain=domain)
python
def to_latlon(array, domain, axis = 'lon'): """Broadcasts a 1D axis dependent array across another axis. :param array input_array: the 1D array used for broadcasting :param domain: the domain associated with that array :param axis: the axis that the input array will be broadcasted across [default: 'lon'] :return: Field with the same shape as the domain :Example: :: >>> import climlab >>> from climlab.domain.field import to_latlon >>> import numpy as np >>> state = climlab.surface_state(num_lat=3, num_lon=4) >>> m = climlab.EBM_annual(state=state) >>> insolation = np.array([237., 417., 237.]) >>> insolation = to_latlon(insolation, domain = m.domains['Ts']) >>> insolation.shape (3, 4, 1) >>> insolation Field([[[ 237.], [[ 417.], [[ 237.], [ 237.], [ 417.], [ 237.], [ 237.], [ 417.], [ 237.], [ 237.]], [ 417.]], [ 237.]]]) """ # if array is latitude dependent (has the same shape as lat) axis, array, depth = np.meshgrid(domain.axes[axis].points, array, domain.axes['depth'].points) if axis == 'lat': # if array is longitude dependent (has the same shape as lon) np.swapaxes(array,1,0) return Field(array, domain=domain)
[ "def", "to_latlon", "(", "array", ",", "domain", ",", "axis", "=", "'lon'", ")", ":", "# if array is latitude dependent (has the same shape as lat)", "axis", ",", "array", ",", "depth", "=", "np", ".", "meshgrid", "(", "domain", ".", "axes", "[", "axis", "]", ".", "points", ",", "array", ",", "domain", ".", "axes", "[", "'depth'", "]", ".", "points", ")", "if", "axis", "==", "'lat'", ":", "# if array is longitude dependent (has the same shape as lon)", "np", ".", "swapaxes", "(", "array", ",", "1", ",", "0", ")", "return", "Field", "(", "array", ",", "domain", "=", "domain", ")" ]
Broadcasts a 1D axis dependent array across another axis. :param array input_array: the 1D array used for broadcasting :param domain: the domain associated with that array :param axis: the axis that the input array will be broadcasted across [default: 'lon'] :return: Field with the same shape as the domain :Example: :: >>> import climlab >>> from climlab.domain.field import to_latlon >>> import numpy as np >>> state = climlab.surface_state(num_lat=3, num_lon=4) >>> m = climlab.EBM_annual(state=state) >>> insolation = np.array([237., 417., 237.]) >>> insolation = to_latlon(insolation, domain = m.domains['Ts']) >>> insolation.shape (3, 4, 1) >>> insolation Field([[[ 237.], [[ 417.], [[ 237.], [ 237.], [ 417.], [ 237.], [ 237.], [ 417.], [ 237.], [ 237.]], [ 417.]], [ 237.]]])
[ "Broadcasts", "a", "1D", "axis", "dependent", "array", "across", "another", "axis", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/domain/field.py#L243-L281
7,692
brian-rose/climlab
climlab/domain/xarray.py
Field_to_xarray
def Field_to_xarray(field): '''Convert a climlab.Field object to xarray.DataArray''' dom = field.domain dims = []; dimlist = []; coords = {}; for axname in dom.axes: dimlist.append(axname) try: assert field.interfaces[dom.axis_index[axname]] bounds_name = axname + '_bounds' dims.append(bounds_name) coords[bounds_name] = dom.axes[axname].bounds except: dims.append(axname) coords[axname] = dom.axes[axname].points # Might need to reorder the data da = DataArray(field.transpose([dom.axis_index[name] for name in dimlist]), dims=dims, coords=coords) for name in dims: try: da[name].attrs['units'] = dom.axes[name].units except: pass return da
python
def Field_to_xarray(field): '''Convert a climlab.Field object to xarray.DataArray''' dom = field.domain dims = []; dimlist = []; coords = {}; for axname in dom.axes: dimlist.append(axname) try: assert field.interfaces[dom.axis_index[axname]] bounds_name = axname + '_bounds' dims.append(bounds_name) coords[bounds_name] = dom.axes[axname].bounds except: dims.append(axname) coords[axname] = dom.axes[axname].points # Might need to reorder the data da = DataArray(field.transpose([dom.axis_index[name] for name in dimlist]), dims=dims, coords=coords) for name in dims: try: da[name].attrs['units'] = dom.axes[name].units except: pass return da
[ "def", "Field_to_xarray", "(", "field", ")", ":", "dom", "=", "field", ".", "domain", "dims", "=", "[", "]", "dimlist", "=", "[", "]", "coords", "=", "{", "}", "for", "axname", "in", "dom", ".", "axes", ":", "dimlist", ".", "append", "(", "axname", ")", "try", ":", "assert", "field", ".", "interfaces", "[", "dom", ".", "axis_index", "[", "axname", "]", "]", "bounds_name", "=", "axname", "+", "'_bounds'", "dims", ".", "append", "(", "bounds_name", ")", "coords", "[", "bounds_name", "]", "=", "dom", ".", "axes", "[", "axname", "]", ".", "bounds", "except", ":", "dims", ".", "append", "(", "axname", ")", "coords", "[", "axname", "]", "=", "dom", ".", "axes", "[", "axname", "]", ".", "points", "# Might need to reorder the data", "da", "=", "DataArray", "(", "field", ".", "transpose", "(", "[", "dom", ".", "axis_index", "[", "name", "]", "for", "name", "in", "dimlist", "]", ")", ",", "dims", "=", "dims", ",", "coords", "=", "coords", ")", "for", "name", "in", "dims", ":", "try", ":", "da", "[", "name", "]", ".", "attrs", "[", "'units'", "]", "=", "dom", ".", "axes", "[", "name", "]", ".", "units", "except", ":", "pass", "return", "da" ]
Convert a climlab.Field object to xarray.DataArray
[ "Convert", "a", "climlab", ".", "Field", "object", "to", "xarray", ".", "DataArray" ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/domain/xarray.py#L8-L30
7,693
brian-rose/climlab
climlab/domain/xarray.py
state_to_xarray
def state_to_xarray(state): '''Convert a dictionary of climlab.Field objects to xarray.Dataset Input: dictionary of climlab.Field objects (e.g. process.state or process.diagnostics dictionary) Output: xarray.Dataset object with all spatial axes, including 'bounds' axes indicating cell boundaries in each spatial dimension. Any items in the dictionary that are not instances of climlab.Field are ignored.''' from climlab.domain.field import Field ds = Dataset() for name, field in state.items(): if isinstance(field, Field): ds[name] = Field_to_xarray(field) dom = field.domain for axname, ax in dom.axes.items(): bounds_name = axname + '_bounds' ds.coords[bounds_name] = DataArray(ax.bounds, dims=[bounds_name], coords={bounds_name:ax.bounds}) try: ds[bounds_name].attrs['units'] = ax.units except: pass else: warnings.warn('{} excluded from Dataset because it is not a Field variable.'.format(name)) return ds
python
def state_to_xarray(state): '''Convert a dictionary of climlab.Field objects to xarray.Dataset Input: dictionary of climlab.Field objects (e.g. process.state or process.diagnostics dictionary) Output: xarray.Dataset object with all spatial axes, including 'bounds' axes indicating cell boundaries in each spatial dimension. Any items in the dictionary that are not instances of climlab.Field are ignored.''' from climlab.domain.field import Field ds = Dataset() for name, field in state.items(): if isinstance(field, Field): ds[name] = Field_to_xarray(field) dom = field.domain for axname, ax in dom.axes.items(): bounds_name = axname + '_bounds' ds.coords[bounds_name] = DataArray(ax.bounds, dims=[bounds_name], coords={bounds_name:ax.bounds}) try: ds[bounds_name].attrs['units'] = ax.units except: pass else: warnings.warn('{} excluded from Dataset because it is not a Field variable.'.format(name)) return ds
[ "def", "state_to_xarray", "(", "state", ")", ":", "from", "climlab", ".", "domain", ".", "field", "import", "Field", "ds", "=", "Dataset", "(", ")", "for", "name", ",", "field", "in", "state", ".", "items", "(", ")", ":", "if", "isinstance", "(", "field", ",", "Field", ")", ":", "ds", "[", "name", "]", "=", "Field_to_xarray", "(", "field", ")", "dom", "=", "field", ".", "domain", "for", "axname", ",", "ax", "in", "dom", ".", "axes", ".", "items", "(", ")", ":", "bounds_name", "=", "axname", "+", "'_bounds'", "ds", ".", "coords", "[", "bounds_name", "]", "=", "DataArray", "(", "ax", ".", "bounds", ",", "dims", "=", "[", "bounds_name", "]", ",", "coords", "=", "{", "bounds_name", ":", "ax", ".", "bounds", "}", ")", "try", ":", "ds", "[", "bounds_name", "]", ".", "attrs", "[", "'units'", "]", "=", "ax", ".", "units", "except", ":", "pass", "else", ":", "warnings", ".", "warn", "(", "'{} excluded from Dataset because it is not a Field variable.'", ".", "format", "(", "name", ")", ")", "return", "ds" ]
Convert a dictionary of climlab.Field objects to xarray.Dataset Input: dictionary of climlab.Field objects (e.g. process.state or process.diagnostics dictionary) Output: xarray.Dataset object with all spatial axes, including 'bounds' axes indicating cell boundaries in each spatial dimension. Any items in the dictionary that are not instances of climlab.Field are ignored.
[ "Convert", "a", "dictionary", "of", "climlab", ".", "Field", "objects", "to", "xarray", ".", "Dataset" ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/domain/xarray.py#L32-L60
7,694
brian-rose/climlab
climlab/domain/xarray.py
to_xarray
def to_xarray(input): '''Convert climlab input to xarray format. If input is a climlab.Field object, return xarray.DataArray If input is a dictionary (e.g. process.state or process.diagnostics), return xarray.Dataset object with all spatial axes, including 'bounds' axes indicating cell boundaries in each spatial dimension. Any items in the dictionary that are not instances of climlab.Field are ignored.''' from climlab.domain.field import Field if isinstance(input, Field): return Field_to_xarray(input) elif isinstance(input, dict): return state_to_xarray(input) else: raise TypeError('input must be Field object or dictionary of Field objects')
python
def to_xarray(input): '''Convert climlab input to xarray format. If input is a climlab.Field object, return xarray.DataArray If input is a dictionary (e.g. process.state or process.diagnostics), return xarray.Dataset object with all spatial axes, including 'bounds' axes indicating cell boundaries in each spatial dimension. Any items in the dictionary that are not instances of climlab.Field are ignored.''' from climlab.domain.field import Field if isinstance(input, Field): return Field_to_xarray(input) elif isinstance(input, dict): return state_to_xarray(input) else: raise TypeError('input must be Field object or dictionary of Field objects')
[ "def", "to_xarray", "(", "input", ")", ":", "from", "climlab", ".", "domain", ".", "field", "import", "Field", "if", "isinstance", "(", "input", ",", "Field", ")", ":", "return", "Field_to_xarray", "(", "input", ")", "elif", "isinstance", "(", "input", ",", "dict", ")", ":", "return", "state_to_xarray", "(", "input", ")", "else", ":", "raise", "TypeError", "(", "'input must be Field object or dictionary of Field objects'", ")" ]
Convert climlab input to xarray format. If input is a climlab.Field object, return xarray.DataArray If input is a dictionary (e.g. process.state or process.diagnostics), return xarray.Dataset object with all spatial axes, including 'bounds' axes indicating cell boundaries in each spatial dimension. Any items in the dictionary that are not instances of climlab.Field are ignored.
[ "Convert", "climlab", "input", "to", "xarray", "format", "." ]
eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/domain/xarray.py#L62-L79
7,695
adamrehn/slidingwindow
slidingwindow/SlidingWindow.py
generate
def generate(data, dimOrder, maxWindowSize, overlapPercent, transforms = []): """ Generates a set of sliding windows for the specified dataset. """ # Determine the dimensions of the input data width = data.shape[dimOrder.index('w')] height = data.shape[dimOrder.index('h')] # Generate the windows return generateForSize(width, height, dimOrder, maxWindowSize, overlapPercent, transforms)
python
def generate(data, dimOrder, maxWindowSize, overlapPercent, transforms = []): """ Generates a set of sliding windows for the specified dataset. """ # Determine the dimensions of the input data width = data.shape[dimOrder.index('w')] height = data.shape[dimOrder.index('h')] # Generate the windows return generateForSize(width, height, dimOrder, maxWindowSize, overlapPercent, transforms)
[ "def", "generate", "(", "data", ",", "dimOrder", ",", "maxWindowSize", ",", "overlapPercent", ",", "transforms", "=", "[", "]", ")", ":", "# Determine the dimensions of the input data", "width", "=", "data", ".", "shape", "[", "dimOrder", ".", "index", "(", "'w'", ")", "]", "height", "=", "data", ".", "shape", "[", "dimOrder", ".", "index", "(", "'h'", ")", "]", "# Generate the windows", "return", "generateForSize", "(", "width", ",", "height", ",", "dimOrder", ",", "maxWindowSize", ",", "overlapPercent", ",", "transforms", ")" ]
Generates a set of sliding windows for the specified dataset.
[ "Generates", "a", "set", "of", "sliding", "windows", "for", "the", "specified", "dataset", "." ]
17ea9395b48671e8cb7321b9510c6b25fec5e45f
https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/SlidingWindow.py#L87-L97
7,696
adamrehn/slidingwindow
slidingwindow/SlidingWindow.py
generateForSize
def generateForSize(width, height, dimOrder, maxWindowSize, overlapPercent, transforms = []): """ Generates a set of sliding windows for a dataset with the specified dimensions and order. """ # If the input data is smaller than the specified window size, # clip the window size to the input size on both dimensions windowSizeX = min(maxWindowSize, width) windowSizeY = min(maxWindowSize, height) # Compute the window overlap and step size windowOverlapX = int(math.floor(windowSizeX * overlapPercent)) windowOverlapY = int(math.floor(windowSizeY * overlapPercent)) stepSizeX = windowSizeX - windowOverlapX stepSizeY = windowSizeY - windowOverlapY # Determine how many windows we will need in order to cover the input data lastX = width - windowSizeX lastY = height - windowSizeY xOffsets = list(range(0, lastX+1, stepSizeX)) yOffsets = list(range(0, lastY+1, stepSizeY)) # Unless the input data dimensions are exact multiples of the step size, # we will need one additional row and column of windows to get 100% coverage if len(xOffsets) == 0 or xOffsets[-1] != lastX: xOffsets.append(lastX) if len(yOffsets) == 0 or yOffsets[-1] != lastY: yOffsets.append(lastY) # Generate the list of windows windows = [] for xOffset in xOffsets: for yOffset in yOffsets: for transform in [None] + transforms: windows.append(SlidingWindow( x=xOffset, y=yOffset, w=windowSizeX, h=windowSizeY, dimOrder=dimOrder, transform=transform )) return windows
python
def generateForSize(width, height, dimOrder, maxWindowSize, overlapPercent, transforms = []): """ Generates a set of sliding windows for a dataset with the specified dimensions and order. """ # If the input data is smaller than the specified window size, # clip the window size to the input size on both dimensions windowSizeX = min(maxWindowSize, width) windowSizeY = min(maxWindowSize, height) # Compute the window overlap and step size windowOverlapX = int(math.floor(windowSizeX * overlapPercent)) windowOverlapY = int(math.floor(windowSizeY * overlapPercent)) stepSizeX = windowSizeX - windowOverlapX stepSizeY = windowSizeY - windowOverlapY # Determine how many windows we will need in order to cover the input data lastX = width - windowSizeX lastY = height - windowSizeY xOffsets = list(range(0, lastX+1, stepSizeX)) yOffsets = list(range(0, lastY+1, stepSizeY)) # Unless the input data dimensions are exact multiples of the step size, # we will need one additional row and column of windows to get 100% coverage if len(xOffsets) == 0 or xOffsets[-1] != lastX: xOffsets.append(lastX) if len(yOffsets) == 0 or yOffsets[-1] != lastY: yOffsets.append(lastY) # Generate the list of windows windows = [] for xOffset in xOffsets: for yOffset in yOffsets: for transform in [None] + transforms: windows.append(SlidingWindow( x=xOffset, y=yOffset, w=windowSizeX, h=windowSizeY, dimOrder=dimOrder, transform=transform )) return windows
[ "def", "generateForSize", "(", "width", ",", "height", ",", "dimOrder", ",", "maxWindowSize", ",", "overlapPercent", ",", "transforms", "=", "[", "]", ")", ":", "# If the input data is smaller than the specified window size,", "# clip the window size to the input size on both dimensions", "windowSizeX", "=", "min", "(", "maxWindowSize", ",", "width", ")", "windowSizeY", "=", "min", "(", "maxWindowSize", ",", "height", ")", "# Compute the window overlap and step size", "windowOverlapX", "=", "int", "(", "math", ".", "floor", "(", "windowSizeX", "*", "overlapPercent", ")", ")", "windowOverlapY", "=", "int", "(", "math", ".", "floor", "(", "windowSizeY", "*", "overlapPercent", ")", ")", "stepSizeX", "=", "windowSizeX", "-", "windowOverlapX", "stepSizeY", "=", "windowSizeY", "-", "windowOverlapY", "# Determine how many windows we will need in order to cover the input data", "lastX", "=", "width", "-", "windowSizeX", "lastY", "=", "height", "-", "windowSizeY", "xOffsets", "=", "list", "(", "range", "(", "0", ",", "lastX", "+", "1", ",", "stepSizeX", ")", ")", "yOffsets", "=", "list", "(", "range", "(", "0", ",", "lastY", "+", "1", ",", "stepSizeY", ")", ")", "# Unless the input data dimensions are exact multiples of the step size,", "# we will need one additional row and column of windows to get 100% coverage", "if", "len", "(", "xOffsets", ")", "==", "0", "or", "xOffsets", "[", "-", "1", "]", "!=", "lastX", ":", "xOffsets", ".", "append", "(", "lastX", ")", "if", "len", "(", "yOffsets", ")", "==", "0", "or", "yOffsets", "[", "-", "1", "]", "!=", "lastY", ":", "yOffsets", ".", "append", "(", "lastY", ")", "# Generate the list of windows", "windows", "=", "[", "]", "for", "xOffset", "in", "xOffsets", ":", "for", "yOffset", "in", "yOffsets", ":", "for", "transform", "in", "[", "None", "]", "+", "transforms", ":", "windows", ".", "append", "(", "SlidingWindow", "(", "x", "=", "xOffset", ",", "y", "=", "yOffset", ",", "w", "=", "windowSizeX", ",", "h", "=", "windowSizeY", ",", "dimOrder", "=", "dimOrder", ",", "transform", "=", "transform", ")", ")", "return", "windows" ]
Generates a set of sliding windows for a dataset with the specified dimensions and order.
[ "Generates", "a", "set", "of", "sliding", "windows", "for", "a", "dataset", "with", "the", "specified", "dimensions", "and", "order", "." ]
17ea9395b48671e8cb7321b9510c6b25fec5e45f
https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/SlidingWindow.py#L100-L143
7,697
adamrehn/slidingwindow
slidingwindow/SlidingWindow.py
SlidingWindow.apply
def apply(self, matrix): """ Slices the supplied matrix and applies any transform bound to this window """ view = matrix[ self.indices() ] return self.transform(view) if self.transform != None else view
python
def apply(self, matrix): """ Slices the supplied matrix and applies any transform bound to this window """ view = matrix[ self.indices() ] return self.transform(view) if self.transform != None else view
[ "def", "apply", "(", "self", ",", "matrix", ")", ":", "view", "=", "matrix", "[", "self", ".", "indices", "(", ")", "]", "return", "self", ".", "transform", "(", "view", ")", "if", "self", ".", "transform", "!=", "None", "else", "view" ]
Slices the supplied matrix and applies any transform bound to this window
[ "Slices", "the", "supplied", "matrix", "and", "applies", "any", "transform", "bound", "to", "this", "window" ]
17ea9395b48671e8cb7321b9510c6b25fec5e45f
https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/SlidingWindow.py#L27-L32
7,698
adamrehn/slidingwindow
slidingwindow/SlidingWindow.py
SlidingWindow.indices
def indices(self, includeChannel=True): """ Retrieves the indices for this window as a tuple of slices """ if self.dimOrder == DimOrder.HeightWidthChannel: # Equivalent to [self.y:self.y+self.h+1, self.x:self.x+self.w+1] return ( slice(self.y, self.y+self.h), slice(self.x, self.x+self.w) ) elif self.dimOrder == DimOrder.ChannelHeightWidth: if includeChannel is True: # Equivalent to [:, self.y:self.y+self.h+1, self.x:self.x+self.w+1] return ( slice(None, None), slice(self.y, self.y+self.h), slice(self.x, self.x+self.w) ) else: # Equivalent to [self.y:self.y+self.h+1, self.x:self.x+self.w+1] return ( slice(self.y, self.y+self.h), slice(self.x, self.x+self.w) ) else: raise Error('Unsupported order of dimensions: ' + str(self.dimOrder))
python
def indices(self, includeChannel=True): """ Retrieves the indices for this window as a tuple of slices """ if self.dimOrder == DimOrder.HeightWidthChannel: # Equivalent to [self.y:self.y+self.h+1, self.x:self.x+self.w+1] return ( slice(self.y, self.y+self.h), slice(self.x, self.x+self.w) ) elif self.dimOrder == DimOrder.ChannelHeightWidth: if includeChannel is True: # Equivalent to [:, self.y:self.y+self.h+1, self.x:self.x+self.w+1] return ( slice(None, None), slice(self.y, self.y+self.h), slice(self.x, self.x+self.w) ) else: # Equivalent to [self.y:self.y+self.h+1, self.x:self.x+self.w+1] return ( slice(self.y, self.y+self.h), slice(self.x, self.x+self.w) ) else: raise Error('Unsupported order of dimensions: ' + str(self.dimOrder))
[ "def", "indices", "(", "self", ",", "includeChannel", "=", "True", ")", ":", "if", "self", ".", "dimOrder", "==", "DimOrder", ".", "HeightWidthChannel", ":", "# Equivalent to [self.y:self.y+self.h+1, self.x:self.x+self.w+1]", "return", "(", "slice", "(", "self", ".", "y", ",", "self", ".", "y", "+", "self", ".", "h", ")", ",", "slice", "(", "self", ".", "x", ",", "self", ".", "x", "+", "self", ".", "w", ")", ")", "elif", "self", ".", "dimOrder", "==", "DimOrder", ".", "ChannelHeightWidth", ":", "if", "includeChannel", "is", "True", ":", "# Equivalent to [:, self.y:self.y+self.h+1, self.x:self.x+self.w+1]", "return", "(", "slice", "(", "None", ",", "None", ")", ",", "slice", "(", "self", ".", "y", ",", "self", ".", "y", "+", "self", ".", "h", ")", ",", "slice", "(", "self", ".", "x", ",", "self", ".", "x", "+", "self", ".", "w", ")", ")", "else", ":", "# Equivalent to [self.y:self.y+self.h+1, self.x:self.x+self.w+1]", "return", "(", "slice", "(", "self", ".", "y", ",", "self", ".", "y", "+", "self", ".", "h", ")", ",", "slice", "(", "self", ".", "x", ",", "self", ".", "x", "+", "self", ".", "w", ")", ")", "else", ":", "raise", "Error", "(", "'Unsupported order of dimensions: '", "+", "str", "(", "self", ".", "dimOrder", ")", ")" ]
Retrieves the indices for this window as a tuple of slices
[ "Retrieves", "the", "indices", "for", "this", "window", "as", "a", "tuple", "of", "slices" ]
17ea9395b48671e8cb7321b9510c6b25fec5e45f
https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/SlidingWindow.py#L46-L78
7,699
adamrehn/slidingwindow
slidingwindow/Batching.py
batchWindows
def batchWindows(windows, batchSize): """ Splits a list of windows into a series of batches. """ return np.array_split(np.array(windows), len(windows) // batchSize)
python
def batchWindows(windows, batchSize): """ Splits a list of windows into a series of batches. """ return np.array_split(np.array(windows), len(windows) // batchSize)
[ "def", "batchWindows", "(", "windows", ",", "batchSize", ")", ":", "return", "np", ".", "array_split", "(", "np", ".", "array", "(", "windows", ")", ",", "len", "(", "windows", ")", "//", "batchSize", ")" ]
Splits a list of windows into a series of batches.
[ "Splits", "a", "list", "of", "windows", "into", "a", "series", "of", "batches", "." ]
17ea9395b48671e8cb7321b9510c6b25fec5e45f
https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/Batching.py#L3-L7