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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
aaugustin/django-sesame | sesame/backends.py | UrlAuthBackendMixin.parse_token | def parse_token(self, token):
"""
Obtain a user from a signed token.
"""
try:
data = self.unsign(token)
except signing.SignatureExpired:
logger.debug("Expired token: %s", token)
return
except signing.BadSignature:
logger.debug("Bad token: %s", token)
return
except Exception:
logger.exception(
"Valid signature but unexpected token - if you changed "
"django-sesame settings, you must regenerate tokens")
return
user_pk, data = self.packer.unpack_pk(data)
user = self.get_user(user_pk)
if user is None:
logger.debug("Unknown token: %s", token)
return
h = crypto.pbkdf2(
self.get_revocation_key(user),
self.salt,
self.iterations,
digest=self.digest,
)
if not crypto.constant_time_compare(data, h):
logger.debug("Invalid token: %s", token)
return
logger.debug("Valid token for user %s: %s", user, token)
return user | python | def parse_token(self, token):
"""
Obtain a user from a signed token.
"""
try:
data = self.unsign(token)
except signing.SignatureExpired:
logger.debug("Expired token: %s", token)
return
except signing.BadSignature:
logger.debug("Bad token: %s", token)
return
except Exception:
logger.exception(
"Valid signature but unexpected token - if you changed "
"django-sesame settings, you must regenerate tokens")
return
user_pk, data = self.packer.unpack_pk(data)
user = self.get_user(user_pk)
if user is None:
logger.debug("Unknown token: %s", token)
return
h = crypto.pbkdf2(
self.get_revocation_key(user),
self.salt,
self.iterations,
digest=self.digest,
)
if not crypto.constant_time_compare(data, h):
logger.debug("Invalid token: %s", token)
return
logger.debug("Valid token for user %s: %s", user, token)
return user | [
"def",
"parse_token",
"(",
"self",
",",
"token",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"unsign",
"(",
"token",
")",
"except",
"signing",
".",
"SignatureExpired",
":",
"logger",
".",
"debug",
"(",
"\"Expired token: %s\"",
",",
"token",
")",
"ret... | Obtain a user from a signed token. | [
"Obtain",
"a",
"user",
"from",
"a",
"signed",
"token",
"."
] | 4bf902c637b0674b8fc78bc95937271948c99282 | https://github.com/aaugustin/django-sesame/blob/4bf902c637b0674b8fc78bc95937271948c99282/sesame/backends.py#L114-L147 | train | 33,200 |
aaugustin/django-sesame | sesame/backends.py | ModelBackend.authenticate | def authenticate(self, request, url_auth_token=None):
"""
Check the token and return the corresponding user.
"""
try:
return self.parse_token(url_auth_token)
except TypeError:
backend = "%s.%s" % (self.__module__, self.__class__.__name__)
logger.exception("TypeError in %s, here's the traceback before "
"Django swallows it:", backend)
raise | python | def authenticate(self, request, url_auth_token=None):
"""
Check the token and return the corresponding user.
"""
try:
return self.parse_token(url_auth_token)
except TypeError:
backend = "%s.%s" % (self.__module__, self.__class__.__name__)
logger.exception("TypeError in %s, here's the traceback before "
"Django swallows it:", backend)
raise | [
"def",
"authenticate",
"(",
"self",
",",
"request",
",",
"url_auth_token",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"parse_token",
"(",
"url_auth_token",
")",
"except",
"TypeError",
":",
"backend",
"=",
"\"%s.%s\"",
"%",
"(",
"self",
".",
... | Check the token and return the corresponding user. | [
"Check",
"the",
"token",
"and",
"return",
"the",
"corresponding",
"user",
"."
] | 4bf902c637b0674b8fc78bc95937271948c99282 | https://github.com/aaugustin/django-sesame/blob/4bf902c637b0674b8fc78bc95937271948c99282/sesame/backends.py#L155-L166 | train | 33,201 |
nlppln/nlppln | nlppln/commands/frog_to_saf.py | _add_pos1 | def _add_pos1(token):
"""
Adds a 'pos1' element to a frog token.
"""
result = token.copy()
result['pos1'] = _POSMAP[token['pos'].split("(")[0]]
return result | python | def _add_pos1(token):
"""
Adds a 'pos1' element to a frog token.
"""
result = token.copy()
result['pos1'] = _POSMAP[token['pos'].split("(")[0]]
return result | [
"def",
"_add_pos1",
"(",
"token",
")",
":",
"result",
"=",
"token",
".",
"copy",
"(",
")",
"result",
"[",
"'pos1'",
"]",
"=",
"_POSMAP",
"[",
"token",
"[",
"'pos'",
"]",
".",
"split",
"(",
"\"(\"",
")",
"[",
"0",
"]",
"]",
"return",
"result"
] | Adds a 'pos1' element to a frog token. | [
"Adds",
"a",
"pos1",
"element",
"to",
"a",
"frog",
"token",
"."
] | 1155191921289a65ba2becd2bf8dfabb48eaf1f1 | https://github.com/nlppln/nlppln/blob/1155191921289a65ba2becd2bf8dfabb48eaf1f1/nlppln/commands/frog_to_saf.py#L53-L59 | train | 33,202 |
nlppln/nlppln | nlppln/commands/frog_to_saf.py | frog_to_saf | def frog_to_saf(tokens):
"""
Convert frog tokens into a new SAF document
"""
tokens = [_add_pos1(token) for token in tokens]
module = {'module': "frog",
"started": datetime.datetime.now().isoformat()}
return {"header": {'format': "SAF",
'format-version': "0.0",
'processed': [module]
}, "tokens": tokens} | python | def frog_to_saf(tokens):
"""
Convert frog tokens into a new SAF document
"""
tokens = [_add_pos1(token) for token in tokens]
module = {'module': "frog",
"started": datetime.datetime.now().isoformat()}
return {"header": {'format': "SAF",
'format-version': "0.0",
'processed': [module]
}, "tokens": tokens} | [
"def",
"frog_to_saf",
"(",
"tokens",
")",
":",
"tokens",
"=",
"[",
"_add_pos1",
"(",
"token",
")",
"for",
"token",
"in",
"tokens",
"]",
"module",
"=",
"{",
"'module'",
":",
"\"frog\"",
",",
"\"started\"",
":",
"datetime",
".",
"datetime",
".",
"now",
"... | Convert frog tokens into a new SAF document | [
"Convert",
"frog",
"tokens",
"into",
"a",
"new",
"SAF",
"document"
] | 1155191921289a65ba2becd2bf8dfabb48eaf1f1 | https://github.com/nlppln/nlppln/blob/1155191921289a65ba2becd2bf8dfabb48eaf1f1/nlppln/commands/frog_to_saf.py#L62-L72 | train | 33,203 |
nlppln/nlppln | nlppln/copycwl.py | copy_cwl_files | def copy_cwl_files(from_dir=CWL_PATH, to_dir=None):
"""Copy cwl files to a directory where the cwl-runner can find them.
Args:
from_dir (str): Path to directory where to copy files from (default:
the cwl directory of nlppln).
to_dir (str): Path to directory where the files should be copied to
(e.g., the CWL working directory).
"""
cwl_files = glob.glob('{}{}*.cwl'.format(from_dir, os.sep))
# if no files are found, the output directory should not be created
if len(cwl_files) > 0:
create_dirs(to_dir)
for fi in cwl_files:
fo = os.path.join(to_dir, os.path.basename(fi))
shutil.copy2(fi, fo)
return len(cwl_files) | python | def copy_cwl_files(from_dir=CWL_PATH, to_dir=None):
"""Copy cwl files to a directory where the cwl-runner can find them.
Args:
from_dir (str): Path to directory where to copy files from (default:
the cwl directory of nlppln).
to_dir (str): Path to directory where the files should be copied to
(e.g., the CWL working directory).
"""
cwl_files = glob.glob('{}{}*.cwl'.format(from_dir, os.sep))
# if no files are found, the output directory should not be created
if len(cwl_files) > 0:
create_dirs(to_dir)
for fi in cwl_files:
fo = os.path.join(to_dir, os.path.basename(fi))
shutil.copy2(fi, fo)
return len(cwl_files) | [
"def",
"copy_cwl_files",
"(",
"from_dir",
"=",
"CWL_PATH",
",",
"to_dir",
"=",
"None",
")",
":",
"cwl_files",
"=",
"glob",
".",
"glob",
"(",
"'{}{}*.cwl'",
".",
"format",
"(",
"from_dir",
",",
"os",
".",
"sep",
")",
")",
"# if no files are found, the output ... | Copy cwl files to a directory where the cwl-runner can find them.
Args:
from_dir (str): Path to directory where to copy files from (default:
the cwl directory of nlppln).
to_dir (str): Path to directory where the files should be copied to
(e.g., the CWL working directory). | [
"Copy",
"cwl",
"files",
"to",
"a",
"directory",
"where",
"the",
"cwl",
"-",
"runner",
"can",
"find",
"them",
"."
] | 1155191921289a65ba2becd2bf8dfabb48eaf1f1 | https://github.com/nlppln/nlppln/blob/1155191921289a65ba2becd2bf8dfabb48eaf1f1/nlppln/copycwl.py#L10-L27 | train | 33,204 |
nlppln/nlppln | nlppln/copycwl.py | main | def main(to_dir, from_dir):
"""Copy CWL files."""
num = copy_cwl_files(from_dir=from_dir, to_dir=to_dir)
if num > 0:
click.echo('Copied {} CWL files to "{}".'.format(num, to_dir))
else:
msg = 'No CWL files found in "{}". Copied 0 files'.format(from_dir)
click.echo(msg) | python | def main(to_dir, from_dir):
"""Copy CWL files."""
num = copy_cwl_files(from_dir=from_dir, to_dir=to_dir)
if num > 0:
click.echo('Copied {} CWL files to "{}".'.format(num, to_dir))
else:
msg = 'No CWL files found in "{}". Copied 0 files'.format(from_dir)
click.echo(msg) | [
"def",
"main",
"(",
"to_dir",
",",
"from_dir",
")",
":",
"num",
"=",
"copy_cwl_files",
"(",
"from_dir",
"=",
"from_dir",
",",
"to_dir",
"=",
"to_dir",
")",
"if",
"num",
">",
"0",
":",
"click",
".",
"echo",
"(",
"'Copied {} CWL files to \"{}\".'",
".",
"f... | Copy CWL files. | [
"Copy",
"CWL",
"files",
"."
] | 1155191921289a65ba2becd2bf8dfabb48eaf1f1 | https://github.com/nlppln/nlppln/blob/1155191921289a65ba2becd2bf8dfabb48eaf1f1/nlppln/copycwl.py#L35-L42 | train | 33,205 |
sileht/python-jsonpath-rw-ext | jsonpath_rw_ext/_iterable.py | SortedThis.find | def find(self, datum):
"""Return sorted value of This if list or dict."""
if isinstance(datum.value, dict) and self.expressions:
return datum
if isinstance(datum.value, dict) or isinstance(datum.value, list):
key = (functools.cmp_to_key(self._compare)
if self.expressions else None)
return [jsonpath_rw.DatumInContext.wrap(
[value for value in sorted(datum.value, key=key)])]
return datum | python | def find(self, datum):
"""Return sorted value of This if list or dict."""
if isinstance(datum.value, dict) and self.expressions:
return datum
if isinstance(datum.value, dict) or isinstance(datum.value, list):
key = (functools.cmp_to_key(self._compare)
if self.expressions else None)
return [jsonpath_rw.DatumInContext.wrap(
[value for value in sorted(datum.value, key=key)])]
return datum | [
"def",
"find",
"(",
"self",
",",
"datum",
")",
":",
"if",
"isinstance",
"(",
"datum",
".",
"value",
",",
"dict",
")",
"and",
"self",
".",
"expressions",
":",
"return",
"datum",
"if",
"isinstance",
"(",
"datum",
".",
"value",
",",
"dict",
")",
"or",
... | Return sorted value of This if list or dict. | [
"Return",
"sorted",
"value",
"of",
"This",
"if",
"list",
"or",
"dict",
"."
] | 30dd6f209ae16d448e1e071aac90cc9d3f10cff5 | https://github.com/sileht/python-jsonpath-rw-ext/blob/30dd6f209ae16d448e1e071aac90cc9d3f10cff5/jsonpath_rw_ext/_iterable.py#L46-L56 | train | 33,206 |
nlppln/nlppln | nlppln/wfgenerator.py | WorkflowGenerator.save | def save(self, fname, mode=None, validate=True, wd=False, inline=False,
relative=True, pack=False, encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save workflows with relative paths.
"""
super(WorkflowGenerator, self).save(fname,
mode=mode,
validate=validate,
wd=wd,
inline=inline,
relative=relative,
pack=pack,
encoding=encoding) | python | def save(self, fname, mode=None, validate=True, wd=False, inline=False,
relative=True, pack=False, encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save workflows with relative paths.
"""
super(WorkflowGenerator, self).save(fname,
mode=mode,
validate=validate,
wd=wd,
inline=inline,
relative=relative,
pack=pack,
encoding=encoding) | [
"def",
"save",
"(",
"self",
",",
"fname",
",",
"mode",
"=",
"None",
",",
"validate",
"=",
"True",
",",
"wd",
"=",
"False",
",",
"inline",
"=",
"False",
",",
"relative",
"=",
"True",
",",
"pack",
"=",
"False",
",",
"encoding",
"=",
"'utf-8'",
")",
... | Save workflow to file
For nlppln, the default is to save workflows with relative paths. | [
"Save",
"workflow",
"to",
"file"
] | 1155191921289a65ba2becd2bf8dfabb48eaf1f1 | https://github.com/nlppln/nlppln/blob/1155191921289a65ba2becd2bf8dfabb48eaf1f1/nlppln/wfgenerator.py#L15-L28 | train | 33,207 |
sileht/python-jsonpath-rw-ext | jsonpath_rw_ext/parser.py | match | def match(pattern, data, **parse_kwargs):
"""Returns all matched values of pattern in data"""
return [m.value for m in parse(pattern, **parse_kwargs).find(data)] | python | def match(pattern, data, **parse_kwargs):
"""Returns all matched values of pattern in data"""
return [m.value for m in parse(pattern, **parse_kwargs).find(data)] | [
"def",
"match",
"(",
"pattern",
",",
"data",
",",
"*",
"*",
"parse_kwargs",
")",
":",
"return",
"[",
"m",
".",
"value",
"for",
"m",
"in",
"parse",
"(",
"pattern",
",",
"*",
"*",
"parse_kwargs",
")",
".",
"find",
"(",
"data",
")",
"]"
] | Returns all matched values of pattern in data | [
"Returns",
"all",
"matched",
"values",
"of",
"pattern",
"in",
"data"
] | 30dd6f209ae16d448e1e071aac90cc9d3f10cff5 | https://github.com/sileht/python-jsonpath-rw-ext/blob/30dd6f209ae16d448e1e071aac90cc9d3f10cff5/jsonpath_rw_ext/parser.py#L182-L184 | train | 33,208 |
sileht/python-jsonpath-rw-ext | jsonpath_rw_ext/parser.py | match1 | def match1(pattern, data, **parse_kwargs):
"""Returns first matched value of pattern in data or None if no matches"""
matches = match(pattern, data, **parse_kwargs)
return matches[0] if matches else None | python | def match1(pattern, data, **parse_kwargs):
"""Returns first matched value of pattern in data or None if no matches"""
matches = match(pattern, data, **parse_kwargs)
return matches[0] if matches else None | [
"def",
"match1",
"(",
"pattern",
",",
"data",
",",
"*",
"*",
"parse_kwargs",
")",
":",
"matches",
"=",
"match",
"(",
"pattern",
",",
"data",
",",
"*",
"*",
"parse_kwargs",
")",
"return",
"matches",
"[",
"0",
"]",
"if",
"matches",
"else",
"None"
] | Returns first matched value of pattern in data or None if no matches | [
"Returns",
"first",
"matched",
"value",
"of",
"pattern",
"in",
"data",
"or",
"None",
"if",
"no",
"matches"
] | 30dd6f209ae16d448e1e071aac90cc9d3f10cff5 | https://github.com/sileht/python-jsonpath-rw-ext/blob/30dd6f209ae16d448e1e071aac90cc9d3f10cff5/jsonpath_rw_ext/parser.py#L187-L190 | train | 33,209 |
nlppln/nlppln | nlppln/commands/create_chunked_list.py | create_chunked_list | def create_chunked_list(in_dir, size, out_dir, out_name):
"""Create a division of the input files in chunks.
The result is stored to a JSON file.
"""
create_dirs(out_dir)
in_files = get_files(in_dir)
chunks = chunk(in_files, size)
division = {}
for i, files in enumerate(chunks):
division[i] = [os.path.basename(f) for f in files]
out_file = os.path.join(out_dir, out_name)
with codecs.open(out_file, 'wb', encoding='utf-8') as f:
json.dump(division, f, indent=4) | python | def create_chunked_list(in_dir, size, out_dir, out_name):
"""Create a division of the input files in chunks.
The result is stored to a JSON file.
"""
create_dirs(out_dir)
in_files = get_files(in_dir)
chunks = chunk(in_files, size)
division = {}
for i, files in enumerate(chunks):
division[i] = [os.path.basename(f) for f in files]
out_file = os.path.join(out_dir, out_name)
with codecs.open(out_file, 'wb', encoding='utf-8') as f:
json.dump(division, f, indent=4) | [
"def",
"create_chunked_list",
"(",
"in_dir",
",",
"size",
",",
"out_dir",
",",
"out_name",
")",
":",
"create_dirs",
"(",
"out_dir",
")",
"in_files",
"=",
"get_files",
"(",
"in_dir",
")",
"chunks",
"=",
"chunk",
"(",
"in_files",
",",
"size",
")",
"division"... | Create a division of the input files in chunks.
The result is stored to a JSON file. | [
"Create",
"a",
"division",
"of",
"the",
"input",
"files",
"in",
"chunks",
"."
] | 1155191921289a65ba2becd2bf8dfabb48eaf1f1 | https://github.com/nlppln/nlppln/blob/1155191921289a65ba2becd2bf8dfabb48eaf1f1/nlppln/commands/create_chunked_list.py#L22-L39 | train | 33,210 |
nlppln/nlppln | nlppln/utils.py | remove_ext | def remove_ext(fname):
"""Removes the extension from a filename
"""
bn = os.path.basename(fname)
return os.path.splitext(bn)[0] | python | def remove_ext(fname):
"""Removes the extension from a filename
"""
bn = os.path.basename(fname)
return os.path.splitext(bn)[0] | [
"def",
"remove_ext",
"(",
"fname",
")",
":",
"bn",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"fname",
")",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"bn",
")",
"[",
"0",
"]"
] | Removes the extension from a filename | [
"Removes",
"the",
"extension",
"from",
"a",
"filename"
] | 1155191921289a65ba2becd2bf8dfabb48eaf1f1 | https://github.com/nlppln/nlppln/blob/1155191921289a65ba2becd2bf8dfabb48eaf1f1/nlppln/utils.py#L14-L18 | train | 33,211 |
nlppln/nlppln | nlppln/utils.py | out_file_name | def out_file_name(out_dir, fname, ext=None):
"""Return path of output file, given a directory, file name and extension.
If fname is a path, it is converted to its basename.
Args:
out_dir (str): path to the directory where output should be written.
fname (str): path to the input file.
ext (str): file extension of the output file (defaults to None).
Returns:
str: out_dir + fname with extension replaced. If `ext` is `None`, the
original extension is kept.
"""
if ext is None:
return os.path.join(out_dir, os.path.basename(fname))
fname = remove_ext(fname)
return os.path.join(out_dir, '{}.{}'.format(fname, ext)) | python | def out_file_name(out_dir, fname, ext=None):
"""Return path of output file, given a directory, file name and extension.
If fname is a path, it is converted to its basename.
Args:
out_dir (str): path to the directory where output should be written.
fname (str): path to the input file.
ext (str): file extension of the output file (defaults to None).
Returns:
str: out_dir + fname with extension replaced. If `ext` is `None`, the
original extension is kept.
"""
if ext is None:
return os.path.join(out_dir, os.path.basename(fname))
fname = remove_ext(fname)
return os.path.join(out_dir, '{}.{}'.format(fname, ext)) | [
"def",
"out_file_name",
"(",
"out_dir",
",",
"fname",
",",
"ext",
"=",
"None",
")",
":",
"if",
"ext",
"is",
"None",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"os",
".",
"path",
".",
"basename",
"(",
"fname",
")",
")",
"f... | Return path of output file, given a directory, file name and extension.
If fname is a path, it is converted to its basename.
Args:
out_dir (str): path to the directory where output should be written.
fname (str): path to the input file.
ext (str): file extension of the output file (defaults to None).
Returns:
str: out_dir + fname with extension replaced. If `ext` is `None`, the
original extension is kept. | [
"Return",
"path",
"of",
"output",
"file",
"given",
"a",
"directory",
"file",
"name",
"and",
"extension",
"."
] | 1155191921289a65ba2becd2bf8dfabb48eaf1f1 | https://github.com/nlppln/nlppln/blob/1155191921289a65ba2becd2bf8dfabb48eaf1f1/nlppln/utils.py#L34-L52 | train | 33,212 |
nlppln/nlppln | nlppln/utils.py | get_files | def get_files(directory, recursive=False):
"""Return a list of all files in the directory."""
files_out = []
if recursive:
for root, dirs, files in os.walk(os.path.abspath(directory)):
files = [os.path.join(root, f) for f in files]
files_out.append(files)
files_out = list(itertools.chain(*files_out))
else:
files_out = [os.path.join(directory, f) for f in os.listdir(directory)]
files_out = list(filter(lambda f: os.path.isfile(f), files_out))
# order alphabetically on file name
return sorted(files_out) | python | def get_files(directory, recursive=False):
"""Return a list of all files in the directory."""
files_out = []
if recursive:
for root, dirs, files in os.walk(os.path.abspath(directory)):
files = [os.path.join(root, f) for f in files]
files_out.append(files)
files_out = list(itertools.chain(*files_out))
else:
files_out = [os.path.join(directory, f) for f in os.listdir(directory)]
files_out = list(filter(lambda f: os.path.isfile(f), files_out))
# order alphabetically on file name
return sorted(files_out) | [
"def",
"get_files",
"(",
"directory",
",",
"recursive",
"=",
"False",
")",
":",
"files_out",
"=",
"[",
"]",
"if",
"recursive",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"dir... | Return a list of all files in the directory. | [
"Return",
"a",
"list",
"of",
"all",
"files",
"in",
"the",
"directory",
"."
] | 1155191921289a65ba2becd2bf8dfabb48eaf1f1 | https://github.com/nlppln/nlppln/blob/1155191921289a65ba2becd2bf8dfabb48eaf1f1/nlppln/utils.py#L59-L72 | train | 33,213 |
gplepage/lsqfit | src/lsqfit/__init__.py | _reformat | def _reformat(p, buf):
""" Apply format of ``p`` to data in 1-d array ``buf``. """
if numpy.ndim(buf) != 1:
raise ValueError("Buffer ``buf`` must be 1-d.")
if hasattr(p, 'keys'):
ans = _gvar.BufferDict(p)
if ans.size != len(buf):
raise ValueError( #
"p, buf size mismatch: %d, %d"%(ans.size, len(buf)))
ans = _gvar.BufferDict(ans, buf=buf)
else:
if numpy.size(p) != len(buf):
raise ValueError( #
"p, buf size mismatch: %d, %d"%(numpy.size(p), len(buf)))
ans = numpy.array(buf).reshape(numpy.shape(p))
return ans | python | def _reformat(p, buf):
""" Apply format of ``p`` to data in 1-d array ``buf``. """
if numpy.ndim(buf) != 1:
raise ValueError("Buffer ``buf`` must be 1-d.")
if hasattr(p, 'keys'):
ans = _gvar.BufferDict(p)
if ans.size != len(buf):
raise ValueError( #
"p, buf size mismatch: %d, %d"%(ans.size, len(buf)))
ans = _gvar.BufferDict(ans, buf=buf)
else:
if numpy.size(p) != len(buf):
raise ValueError( #
"p, buf size mismatch: %d, %d"%(numpy.size(p), len(buf)))
ans = numpy.array(buf).reshape(numpy.shape(p))
return ans | [
"def",
"_reformat",
"(",
"p",
",",
"buf",
")",
":",
"if",
"numpy",
".",
"ndim",
"(",
"buf",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"Buffer ``buf`` must be 1-d.\"",
")",
"if",
"hasattr",
"(",
"p",
",",
"'keys'",
")",
":",
"ans",
"=",
"_gva... | Apply format of ``p`` to data in 1-d array ``buf``. | [
"Apply",
"format",
"of",
"p",
"to",
"data",
"in",
"1",
"-",
"d",
"array",
"buf",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/__init__.py#L1543-L1558 | train | 33,214 |
gplepage/lsqfit | src/lsqfit/__init__.py | _unpack_gvars | def _unpack_gvars(g):
""" Unpack collection of GVars to BufferDict or numpy array. """
if g is not None:
g = _gvar.gvar(g)
if not hasattr(g, 'flat'):
# must be a scalar (ie, not an array and not a dictionary)
g = numpy.asarray(g)
return g | python | def _unpack_gvars(g):
""" Unpack collection of GVars to BufferDict or numpy array. """
if g is not None:
g = _gvar.gvar(g)
if not hasattr(g, 'flat'):
# must be a scalar (ie, not an array and not a dictionary)
g = numpy.asarray(g)
return g | [
"def",
"_unpack_gvars",
"(",
"g",
")",
":",
"if",
"g",
"is",
"not",
"None",
":",
"g",
"=",
"_gvar",
".",
"gvar",
"(",
"g",
")",
"if",
"not",
"hasattr",
"(",
"g",
",",
"'flat'",
")",
":",
"# must be a scalar (ie, not an array and not a dictionary)",
"g",
... | Unpack collection of GVars to BufferDict or numpy array. | [
"Unpack",
"collection",
"of",
"GVars",
"to",
"BufferDict",
"or",
"numpy",
"array",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/__init__.py#L1658-L1665 | train | 33,215 |
gplepage/lsqfit | src/lsqfit/__init__.py | _unpack_p0 | def _unpack_p0(p0, p0file, prior):
""" Create proper p0.
Try to read from a file. If that doesn't work, try using p0,
and then, finally, the prior. If the p0 is from the file, it is
checked against the prior to make sure that all elements have the
right shape; if not the p0 elements are adjusted (using info from
the prior) to be the correct shape. If p0 is a dictionary,
keys in p0 that are not in prior are discarded. If p0 is True,
then a random p0 is generated from the prior.
"""
if p0file is not None:
# p0 is a filename; read in values
try:
with open(p0file, "rb") as f:
p0 = pickle.load(f)
except (IOError, EOFError):
if prior is None:
raise IOError(
"No prior and can't read parameters from " + p0file
)
else:
p0 = None
if p0 is not None:
# repackage as BufferDict or numpy array
if p0 is True:
p0 = next(_gvar.raniter(prior))
if hasattr(p0, 'keys'):
p0 = _gvar.BufferDict(p0)
if p0.dtype != float:
p0.buf = numpy.asarray(p0.buf, dtype=float)
else:
p0 = numpy.array(p0, float)
if prior is not None:
# build new p0 from p0, plus the prior as needed
pp = _reformat(prior, buf=[x.mean if x.mean != 0.0
else x.mean + 0.1 * x.sdev for x in prior.flat])
if p0 is None:
p0 = pp
else:
if pp.shape is not None:
# pp and p0 are arrays
pp_shape = pp.shape
p0_shape = p0.shape
if len(pp_shape)!=len(p0_shape):
raise ValueError( #
"p0 and prior shapes incompatible: %s, %s"
% (str(p0_shape), str(pp_shape)))
idx = []
for npp, np0 in zip(pp_shape, p0_shape):
idx.append(slice(0, min(npp, np0)))
idx = tuple(idx) # overlapping slices in each dir
pp[idx] = p0[idx]
p0 = pp
else:
# pp and p0 are dicts
# if set(pp.keys()) != set(p0.keys()):
# # mismatch in keys between prior and p0
# raise ValueError("Key mismatch between prior and p0: "
# + ' '.join(str(k) for k in
# set(prior.keys()) ^ set(p0.keys())))
# adjust p0[k] to be compatible with shape of prior[k]
for k in pp:
if k not in p0:
continue
pp_shape = numpy.shape(pp[k])
p0_shape = numpy.shape(p0[k])
if len(pp_shape)!=len(p0_shape):
raise ValueError("p0 and prior incompatible: "
+str(k))
if pp_shape == p0_shape:
pp[k] = p0[k]
else:
# find overlap between p0 and pp
pp_shape = pp[k].shape
p0_shape = p0[k].shape
if len(pp_shape)!=len(p0_shape):
raise ValueError( #
"p0 and prior incompatible: "+str(k))
idx = []
for npp, np0 in zip(pp_shape, p0_shape):
idx.append(slice(0, min(npp, np0)))
idx = tuple(idx) # overlapping slices in each dir
pp[k][idx] = p0[k][idx]
p0 = pp
if p0 is None:
raise ValueError("No starting values for parameters")
return p0 | python | def _unpack_p0(p0, p0file, prior):
""" Create proper p0.
Try to read from a file. If that doesn't work, try using p0,
and then, finally, the prior. If the p0 is from the file, it is
checked against the prior to make sure that all elements have the
right shape; if not the p0 elements are adjusted (using info from
the prior) to be the correct shape. If p0 is a dictionary,
keys in p0 that are not in prior are discarded. If p0 is True,
then a random p0 is generated from the prior.
"""
if p0file is not None:
# p0 is a filename; read in values
try:
with open(p0file, "rb") as f:
p0 = pickle.load(f)
except (IOError, EOFError):
if prior is None:
raise IOError(
"No prior and can't read parameters from " + p0file
)
else:
p0 = None
if p0 is not None:
# repackage as BufferDict or numpy array
if p0 is True:
p0 = next(_gvar.raniter(prior))
if hasattr(p0, 'keys'):
p0 = _gvar.BufferDict(p0)
if p0.dtype != float:
p0.buf = numpy.asarray(p0.buf, dtype=float)
else:
p0 = numpy.array(p0, float)
if prior is not None:
# build new p0 from p0, plus the prior as needed
pp = _reformat(prior, buf=[x.mean if x.mean != 0.0
else x.mean + 0.1 * x.sdev for x in prior.flat])
if p0 is None:
p0 = pp
else:
if pp.shape is not None:
# pp and p0 are arrays
pp_shape = pp.shape
p0_shape = p0.shape
if len(pp_shape)!=len(p0_shape):
raise ValueError( #
"p0 and prior shapes incompatible: %s, %s"
% (str(p0_shape), str(pp_shape)))
idx = []
for npp, np0 in zip(pp_shape, p0_shape):
idx.append(slice(0, min(npp, np0)))
idx = tuple(idx) # overlapping slices in each dir
pp[idx] = p0[idx]
p0 = pp
else:
# pp and p0 are dicts
# if set(pp.keys()) != set(p0.keys()):
# # mismatch in keys between prior and p0
# raise ValueError("Key mismatch between prior and p0: "
# + ' '.join(str(k) for k in
# set(prior.keys()) ^ set(p0.keys())))
# adjust p0[k] to be compatible with shape of prior[k]
for k in pp:
if k not in p0:
continue
pp_shape = numpy.shape(pp[k])
p0_shape = numpy.shape(p0[k])
if len(pp_shape)!=len(p0_shape):
raise ValueError("p0 and prior incompatible: "
+str(k))
if pp_shape == p0_shape:
pp[k] = p0[k]
else:
# find overlap between p0 and pp
pp_shape = pp[k].shape
p0_shape = p0[k].shape
if len(pp_shape)!=len(p0_shape):
raise ValueError( #
"p0 and prior incompatible: "+str(k))
idx = []
for npp, np0 in zip(pp_shape, p0_shape):
idx.append(slice(0, min(npp, np0)))
idx = tuple(idx) # overlapping slices in each dir
pp[k][idx] = p0[k][idx]
p0 = pp
if p0 is None:
raise ValueError("No starting values for parameters")
return p0 | [
"def",
"_unpack_p0",
"(",
"p0",
",",
"p0file",
",",
"prior",
")",
":",
"if",
"p0file",
"is",
"not",
"None",
":",
"# p0 is a filename; read in values",
"try",
":",
"with",
"open",
"(",
"p0file",
",",
"\"rb\"",
")",
"as",
"f",
":",
"p0",
"=",
"pickle",
"... | Create proper p0.
Try to read from a file. If that doesn't work, try using p0,
and then, finally, the prior. If the p0 is from the file, it is
checked against the prior to make sure that all elements have the
right shape; if not the p0 elements are adjusted (using info from
the prior) to be the correct shape. If p0 is a dictionary,
keys in p0 that are not in prior are discarded. If p0 is True,
then a random p0 is generated from the prior. | [
"Create",
"proper",
"p0",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/__init__.py#L1667-L1754 | train | 33,216 |
gplepage/lsqfit | src/lsqfit/__init__.py | _unpack_fcn | def _unpack_fcn(fcn, p0, y, x):
""" reconfigure fitting fcn so inputs, outputs = flat arrays; hide x """
if y.shape is not None:
if p0.shape is not None:
def nfcn(p, x=x, fcn=fcn, pshape=p0.shape):
po = p.reshape(pshape)
ans = fcn(po) if x is False else fcn(x, po)
if hasattr(ans, 'flat'):
return ans.flat
else:
return numpy.array(ans).flat
else:
po = _gvar.BufferDict(p0, buf=numpy.zeros(p0.size, float))
def nfcn(p, x=x, fcn=fcn, po=po):
po.buf = p
ans = fcn(po) if x is False else fcn(x, po)
if hasattr(ans, 'flat'):
return ans.flat
else:
return numpy.array(ans).flat
else:
yo = _gvar.BufferDict(y, buf=y.size*[None])
if p0.shape is not None:
def nfcn(p, x=x, fcn=fcn, pshape=p0.shape, yo=yo):
po = p.reshape(pshape)
fxp = fcn(po) if x is False else fcn(x, po)
for k in yo:
yo[k] = fxp[k]
return yo.flat
else:
po = _gvar.BufferDict(p0, buf=numpy.zeros(p0.size, float))
def nfcn(p, x=x, fcn=fcn, po=po, yo=yo):
po.buf = p
fxp = fcn(po) if x is False else fcn(x, po)
for k in yo:
yo[k] = fxp[k]
return yo.flat
return nfcn | python | def _unpack_fcn(fcn, p0, y, x):
""" reconfigure fitting fcn so inputs, outputs = flat arrays; hide x """
if y.shape is not None:
if p0.shape is not None:
def nfcn(p, x=x, fcn=fcn, pshape=p0.shape):
po = p.reshape(pshape)
ans = fcn(po) if x is False else fcn(x, po)
if hasattr(ans, 'flat'):
return ans.flat
else:
return numpy.array(ans).flat
else:
po = _gvar.BufferDict(p0, buf=numpy.zeros(p0.size, float))
def nfcn(p, x=x, fcn=fcn, po=po):
po.buf = p
ans = fcn(po) if x is False else fcn(x, po)
if hasattr(ans, 'flat'):
return ans.flat
else:
return numpy.array(ans).flat
else:
yo = _gvar.BufferDict(y, buf=y.size*[None])
if p0.shape is not None:
def nfcn(p, x=x, fcn=fcn, pshape=p0.shape, yo=yo):
po = p.reshape(pshape)
fxp = fcn(po) if x is False else fcn(x, po)
for k in yo:
yo[k] = fxp[k]
return yo.flat
else:
po = _gvar.BufferDict(p0, buf=numpy.zeros(p0.size, float))
def nfcn(p, x=x, fcn=fcn, po=po, yo=yo):
po.buf = p
fxp = fcn(po) if x is False else fcn(x, po)
for k in yo:
yo[k] = fxp[k]
return yo.flat
return nfcn | [
"def",
"_unpack_fcn",
"(",
"fcn",
",",
"p0",
",",
"y",
",",
"x",
")",
":",
"if",
"y",
".",
"shape",
"is",
"not",
"None",
":",
"if",
"p0",
".",
"shape",
"is",
"not",
"None",
":",
"def",
"nfcn",
"(",
"p",
",",
"x",
"=",
"x",
",",
"fcn",
"=",
... | reconfigure fitting fcn so inputs, outputs = flat arrays; hide x | [
"reconfigure",
"fitting",
"fcn",
"so",
"inputs",
"outputs",
"=",
"flat",
"arrays",
";",
"hide",
"x"
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/__init__.py#L1757-L1794 | train | 33,217 |
gplepage/lsqfit | src/lsqfit/__init__.py | nonlinear_fit.check_roundoff | def check_roundoff(self, rtol=0.25, atol=1e-6):
""" Check for roundoff errors in fit.p.
Compares standard deviations from fit.p and fit.palt to see if they
agree to within relative tolerance ``rtol`` and absolute tolerance
``atol``. Generates a warning if they do not (in which
case an SVD cut might be advisable).
"""
psdev = _gvar.sdev(self.p.flat)
paltsdev = _gvar.sdev(self.palt.flat)
if not numpy.allclose(psdev, paltsdev, rtol=rtol, atol=atol):
warnings.warn("Possible roundoff errors in fit.p; try svd cut.") | python | def check_roundoff(self, rtol=0.25, atol=1e-6):
""" Check for roundoff errors in fit.p.
Compares standard deviations from fit.p and fit.palt to see if they
agree to within relative tolerance ``rtol`` and absolute tolerance
``atol``. Generates a warning if they do not (in which
case an SVD cut might be advisable).
"""
psdev = _gvar.sdev(self.p.flat)
paltsdev = _gvar.sdev(self.palt.flat)
if not numpy.allclose(psdev, paltsdev, rtol=rtol, atol=atol):
warnings.warn("Possible roundoff errors in fit.p; try svd cut.") | [
"def",
"check_roundoff",
"(",
"self",
",",
"rtol",
"=",
"0.25",
",",
"atol",
"=",
"1e-6",
")",
":",
"psdev",
"=",
"_gvar",
".",
"sdev",
"(",
"self",
".",
"p",
".",
"flat",
")",
"paltsdev",
"=",
"_gvar",
".",
"sdev",
"(",
"self",
".",
"palt",
".",... | Check for roundoff errors in fit.p.
Compares standard deviations from fit.p and fit.palt to see if they
agree to within relative tolerance ``rtol`` and absolute tolerance
``atol``. Generates a warning if they do not (in which
case an SVD cut might be advisable). | [
"Check",
"for",
"roundoff",
"errors",
"in",
"fit",
".",
"p",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/__init__.py#L831-L842 | train | 33,218 |
gplepage/lsqfit | src/lsqfit/__init__.py | nonlinear_fit.plot_residuals | def plot_residuals(self, plot=None):
""" Plot normalized fit residuals.
The sum of the squares of the residuals equals ``self.chi2``.
Individual residuals should be distributed about one, in
a Gaussian distribution.
Args:
plot: :mod:`matplotlib` plotter. If ``None``, uses
``matplotlib.pyplot`.
Returns:
Plotter ``plot``.
"""
if plot is None:
import matplotlib.pyplot as plot
x = numpy.arange(1, len(self.residuals) + 1)
y = _gvar.mean(self.residuals)
yerr = _gvar.sdev(self.residuals)
plot.errorbar(x=x, y=y, yerr=yerr, fmt='o', color='b')
plot.ylabel('normalized residuals')
xr = [x[0], x[-1]]
plot.plot([x[0], x[-1]], [0, 0], 'r-')
plot.fill_between(
x=xr, y1=[-1,-1], y2=[1,1], color='r', alpha=0.075
)
return plot | python | def plot_residuals(self, plot=None):
""" Plot normalized fit residuals.
The sum of the squares of the residuals equals ``self.chi2``.
Individual residuals should be distributed about one, in
a Gaussian distribution.
Args:
plot: :mod:`matplotlib` plotter. If ``None``, uses
``matplotlib.pyplot`.
Returns:
Plotter ``plot``.
"""
if plot is None:
import matplotlib.pyplot as plot
x = numpy.arange(1, len(self.residuals) + 1)
y = _gvar.mean(self.residuals)
yerr = _gvar.sdev(self.residuals)
plot.errorbar(x=x, y=y, yerr=yerr, fmt='o', color='b')
plot.ylabel('normalized residuals')
xr = [x[0], x[-1]]
plot.plot([x[0], x[-1]], [0, 0], 'r-')
plot.fill_between(
x=xr, y1=[-1,-1], y2=[1,1], color='r', alpha=0.075
)
return plot | [
"def",
"plot_residuals",
"(",
"self",
",",
"plot",
"=",
"None",
")",
":",
"if",
"plot",
"is",
"None",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plot",
"x",
"=",
"numpy",
".",
"arange",
"(",
"1",
",",
"len",
"(",
"self",
".",
"residuals",
"... | Plot normalized fit residuals.
The sum of the squares of the residuals equals ``self.chi2``.
Individual residuals should be distributed about one, in
a Gaussian distribution.
Args:
plot: :mod:`matplotlib` plotter. If ``None``, uses
``matplotlib.pyplot`.
Returns:
Plotter ``plot``. | [
"Plot",
"normalized",
"fit",
"residuals",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/__init__.py#L875-L901 | train | 33,219 |
gplepage/lsqfit | src/lsqfit/__init__.py | nonlinear_fit.load_parameters | def load_parameters(filename):
""" Load parameters stored in file ``filename``.
``p = nonlinear_fit.load_p(filename)`` is used to recover the
values of fit parameters dumped using ``fit.dump_p(filename)`` (or
``fit.dump_pmean(filename)``) where ``fit`` is of type
:class:`lsqfit.nonlinear_fit`. The layout of the returned
parameters ``p`` is the same as that of ``fit.p`` (or
``fit.pmean``).
"""
warnings.warn(
"nonlinear_fit.load_parameters deprecated; use pickle.load or gvar.load instead",
DeprecationWarning,
)
with open(filename,"rb") as f:
return pickle.load(f) | python | def load_parameters(filename):
""" Load parameters stored in file ``filename``.
``p = nonlinear_fit.load_p(filename)`` is used to recover the
values of fit parameters dumped using ``fit.dump_p(filename)`` (or
``fit.dump_pmean(filename)``) where ``fit`` is of type
:class:`lsqfit.nonlinear_fit`. The layout of the returned
parameters ``p`` is the same as that of ``fit.p`` (or
``fit.pmean``).
"""
warnings.warn(
"nonlinear_fit.load_parameters deprecated; use pickle.load or gvar.load instead",
DeprecationWarning,
)
with open(filename,"rb") as f:
return pickle.load(f) | [
"def",
"load_parameters",
"(",
"filename",
")",
":",
"warnings",
".",
"warn",
"(",
"\"nonlinear_fit.load_parameters deprecated; use pickle.load or gvar.load instead\"",
",",
"DeprecationWarning",
",",
")",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
... | Load parameters stored in file ``filename``.
``p = nonlinear_fit.load_p(filename)`` is used to recover the
values of fit parameters dumped using ``fit.dump_p(filename)`` (or
``fit.dump_pmean(filename)``) where ``fit`` is of type
:class:`lsqfit.nonlinear_fit`. The layout of the returned
parameters ``p`` is the same as that of ``fit.p`` (or
``fit.pmean``). | [
"Load",
"parameters",
"stored",
"in",
"file",
"filename",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/__init__.py#L1228-L1243 | train | 33,220 |
gplepage/lsqfit | src/lsqfit/__init__.py | nonlinear_fit.simulated_fit_iter | def simulated_fit_iter(
self, n=None, pexact=None, add_priornoise=False, bootstrap=None, **kargs
):
""" Iterator that returns simulation copies of a fit.
Fit reliability is tested using simulated data which
replaces the mean values in ``self.y`` with random numbers
drawn from a distribution whose mean equals ``self.fcn(pexact)``
and whose covariance matrix is the same as ``self.y``'s. Simulated
data is very similar to the original fit data, ``self.y``,
but corresponds to a world where the correct values for
the parameters (*i.e.*, averaged over many simulated data
sets) are given by ``pexact``. ``pexact`` is usually taken
equal to ``fit.pmean``.
Each iteration of the iterator creates new simulated data,
with different random numbers, and fits it, returning the
the :class:`lsqfit.nonlinear_fit` that results. The simulated
data has the same covariance matrix as ``fit.y``.
Typical usage is::
...
fit = nonlinear_fit(...)
...
for sfit in fit.simulated_fit_iter(n=3):
... verify that sfit has a good chi**2 ...
... verify that sfit.p agrees with pexact=fit.pmean within errors ...
Only a few iterations are needed to get a sense of the fit's
reliability since we know the correct answer in each case. The
simulated fit's output results should agree with ``pexact``
(``=fit.pmean`` here) within the simulated fit's errors.
Setting parameter ``add_priornoise=True`` varies the means of the
priors as well as the means of the data. This option is useful
for testing goodness of fit because with it ``chi**2/N`` should
be ``1 ± sqrt(2/N)``, where ``N`` is the
number of degrees of freedom. (``chi**2/N`` can be significantly
smaller than one without added noise in prior means.)
Simulated fits can also be used to estimate biases in the fit's
output parameters or functions of them, should non-Gaussian behavior
arise. This is possible, again, because we know the correct value for
every parameter before we do the fit. Again only a few iterations
may be needed for reliable estimates.
Args:
n (int or ``None``): Maximum number of iterations (equals
infinity if ``None``).
pexact (``None`` or array/dict of numbers): Fit-parameter values
for the underlying distribution used to generate simulated
data; replaced by ``self.pmean`` if is ``None`` (default).
add_priornoise (bool): Vary prior means if ``True``;
otherwise vary only the means in ``self.y`` (default).
kargs: Dictionary containing override values for fit parameters.
Returns:
An iterator that returns :class:`lsqfit.nonlinear_fit`\s
for different simulated data.
"""
pexact = self.pmean if pexact is None else pexact
# bootstrap is old name for add_priornoise; keep for legacy code
if bootstrap is not None:
add_priornoise = bootstrap
# Note: don't need svdcut since these are built into the data_iter
fargs = dict(
fcn=self.fcn, svdcut=None, p0=pexact, fitter=self.fitter,
)
fargs.update(self.fitterargs)
fargs.update(kargs)
for ysim, priorsim in self.simulated_data_iter(
n, pexact=pexact, add_priornoise=add_priornoise
):
fit = nonlinear_fit(
data=(self.x, ysim), prior=priorsim, _fdata=self.fdata,
**fargs
)
fit.pexact = pexact
yield fit | python | def simulated_fit_iter(
self, n=None, pexact=None, add_priornoise=False, bootstrap=None, **kargs
):
""" Iterator that returns simulation copies of a fit.
Fit reliability is tested using simulated data which
replaces the mean values in ``self.y`` with random numbers
drawn from a distribution whose mean equals ``self.fcn(pexact)``
and whose covariance matrix is the same as ``self.y``'s. Simulated
data is very similar to the original fit data, ``self.y``,
but corresponds to a world where the correct values for
the parameters (*i.e.*, averaged over many simulated data
sets) are given by ``pexact``. ``pexact`` is usually taken
equal to ``fit.pmean``.
Each iteration of the iterator creates new simulated data,
with different random numbers, and fits it, returning the
the :class:`lsqfit.nonlinear_fit` that results. The simulated
data has the same covariance matrix as ``fit.y``.
Typical usage is::
...
fit = nonlinear_fit(...)
...
for sfit in fit.simulated_fit_iter(n=3):
... verify that sfit has a good chi**2 ...
... verify that sfit.p agrees with pexact=fit.pmean within errors ...
Only a few iterations are needed to get a sense of the fit's
reliability since we know the correct answer in each case. The
simulated fit's output results should agree with ``pexact``
(``=fit.pmean`` here) within the simulated fit's errors.
Setting parameter ``add_priornoise=True`` varies the means of the
priors as well as the means of the data. This option is useful
for testing goodness of fit because with it ``chi**2/N`` should
be ``1 ± sqrt(2/N)``, where ``N`` is the
number of degrees of freedom. (``chi**2/N`` can be significantly
smaller than one without added noise in prior means.)
Simulated fits can also be used to estimate biases in the fit's
output parameters or functions of them, should non-Gaussian behavior
arise. This is possible, again, because we know the correct value for
every parameter before we do the fit. Again only a few iterations
may be needed for reliable estimates.
Args:
n (int or ``None``): Maximum number of iterations (equals
infinity if ``None``).
pexact (``None`` or array/dict of numbers): Fit-parameter values
for the underlying distribution used to generate simulated
data; replaced by ``self.pmean`` if is ``None`` (default).
add_priornoise (bool): Vary prior means if ``True``;
otherwise vary only the means in ``self.y`` (default).
kargs: Dictionary containing override values for fit parameters.
Returns:
An iterator that returns :class:`lsqfit.nonlinear_fit`\s
for different simulated data.
"""
pexact = self.pmean if pexact is None else pexact
# bootstrap is old name for add_priornoise; keep for legacy code
if bootstrap is not None:
add_priornoise = bootstrap
# Note: don't need svdcut since these are built into the data_iter
fargs = dict(
fcn=self.fcn, svdcut=None, p0=pexact, fitter=self.fitter,
)
fargs.update(self.fitterargs)
fargs.update(kargs)
for ysim, priorsim in self.simulated_data_iter(
n, pexact=pexact, add_priornoise=add_priornoise
):
fit = nonlinear_fit(
data=(self.x, ysim), prior=priorsim, _fdata=self.fdata,
**fargs
)
fit.pexact = pexact
yield fit | [
"def",
"simulated_fit_iter",
"(",
"self",
",",
"n",
"=",
"None",
",",
"pexact",
"=",
"None",
",",
"add_priornoise",
"=",
"False",
",",
"bootstrap",
"=",
"None",
",",
"*",
"*",
"kargs",
")",
":",
"pexact",
"=",
"self",
".",
"pmean",
"if",
"pexact",
"i... | Iterator that returns simulation copies of a fit.
Fit reliability is tested using simulated data which
replaces the mean values in ``self.y`` with random numbers
drawn from a distribution whose mean equals ``self.fcn(pexact)``
and whose covariance matrix is the same as ``self.y``'s. Simulated
data is very similar to the original fit data, ``self.y``,
but corresponds to a world where the correct values for
the parameters (*i.e.*, averaged over many simulated data
sets) are given by ``pexact``. ``pexact`` is usually taken
equal to ``fit.pmean``.
Each iteration of the iterator creates new simulated data,
with different random numbers, and fits it, returning the
the :class:`lsqfit.nonlinear_fit` that results. The simulated
data has the same covariance matrix as ``fit.y``.
Typical usage is::
...
fit = nonlinear_fit(...)
...
for sfit in fit.simulated_fit_iter(n=3):
... verify that sfit has a good chi**2 ...
... verify that sfit.p agrees with pexact=fit.pmean within errors ...
Only a few iterations are needed to get a sense of the fit's
reliability since we know the correct answer in each case. The
simulated fit's output results should agree with ``pexact``
(``=fit.pmean`` here) within the simulated fit's errors.
Setting parameter ``add_priornoise=True`` varies the means of the
priors as well as the means of the data. This option is useful
for testing goodness of fit because with it ``chi**2/N`` should
be ``1 ± sqrt(2/N)``, where ``N`` is the
number of degrees of freedom. (``chi**2/N`` can be significantly
smaller than one without added noise in prior means.)
Simulated fits can also be used to estimate biases in the fit's
output parameters or functions of them, should non-Gaussian behavior
arise. This is possible, again, because we know the correct value for
every parameter before we do the fit. Again only a few iterations
may be needed for reliable estimates.
Args:
n (int or ``None``): Maximum number of iterations (equals
infinity if ``None``).
pexact (``None`` or array/dict of numbers): Fit-parameter values
for the underlying distribution used to generate simulated
data; replaced by ``self.pmean`` if is ``None`` (default).
add_priornoise (bool): Vary prior means if ``True``;
otherwise vary only the means in ``self.y`` (default).
kargs: Dictionary containing override values for fit parameters.
Returns:
An iterator that returns :class:`lsqfit.nonlinear_fit`\s
for different simulated data. | [
"Iterator",
"that",
"returns",
"simulation",
"copies",
"of",
"a",
"fit",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/__init__.py#L1282-L1360 | train | 33,221 |
gplepage/lsqfit | src/lsqfit/__init__.py | nonlinear_fit.simulated_data_iter | def simulated_data_iter(
self, n=None, pexact=None, add_priornoise=False, bootstrap=None
):
""" Iterator that returns simulated data based upon a fit's data.
Simulated data is generated from a fit's data ``fit.y`` by
replacing the mean values in that data with random numbers
drawn from a distribution whose mean is ``self.fcn(pexact)``
and whose covariance matrix is the same as that of ``self.y``.
Each iteration of the iterator returns new simulated data,
with different random numbers for the means and a covariance
matrix equal to that of ``self.y``. This iterator is used by
``self.simulated_fit_iter``.
Typical usage::
fit = nonlinear_fit(data=(x,y), prior=prior, fcn=fcn)
...
for ysim, priorsim in fit.simulate_data_iter(n=10):
fitsim = nonlinear_fit(data=(x, ysim), prior=priorsim, fcn=fcn)
print(fitsim)
print('chi2 =', gv.chi2(fit.p, fitsim.p))
This code tests the fitting protocol on simulated data, comparing the
best fit parameters in each case with the correct values (``fit.p``).
The loop in this code is functionally the same as (but probably not
as fast as)::
for fitsim in fit.simulated_fit_iter(n=10):
print(fitsim)
print('chi2 =', gv.chi2(fit.p, fitsim.p))
Args:
n (int or None): Maximum number of iterations (equals
infinity if ``None``).
pexact (None or dict/array of numbers): Fit-parameter values for
the underlying distribution used to generate simulated data;
replaced by ``self.pmean`` if is ``None`` (default).
add_priornoise (bool): Vary prior means if ``True``; otherwise
vary only the means in ``self.y`` (default).
Returns:
An iterator that returns a 2-tuple containing simulated
versions of self.y and self.prior: ``(ysim, priorsim)``.
"""
pexact = self.pmean if pexact is None else pexact
# bootstrap is old name for add_priornoise; keep for legacy code
if bootstrap is not None:
add_priornoise = bootstrap
f = self.fcn(pexact) if self.x is False else self.fcn(self.x, pexact)
y = copy.deepcopy(self.y)
if isinstance(y, _gvar.BufferDict):
# y,f dictionaries; fresh copy of y, reorder f
tmp_f = _gvar.BufferDict([(k, f[k]) for k in y])
y.buf += tmp_f.buf - _gvar.mean(y.buf)
else:
# y,f arrays; fresh copy of y
y += numpy.asarray(f) - _gvar.mean(y)
prior = copy.deepcopy(self.prior)
if prior is None or not add_priornoise:
yiter = _gvar.bootstrap_iter(y, n)
for ysim in _gvar.bootstrap_iter(y, n):
yield ysim, prior
else:
yp = numpy.empty(y.size + prior.size, object)
yp[:y.size] = y.flat
yp[y.size:] = prior.flat
for ypsim in _gvar.bootstrap_iter(yp, n):
y.flat = ypsim[:y.size]
prior.flat = ypsim[y.size:]
yield y, prior | python | def simulated_data_iter(
self, n=None, pexact=None, add_priornoise=False, bootstrap=None
):
""" Iterator that returns simulated data based upon a fit's data.
Simulated data is generated from a fit's data ``fit.y`` by
replacing the mean values in that data with random numbers
drawn from a distribution whose mean is ``self.fcn(pexact)``
and whose covariance matrix is the same as that of ``self.y``.
Each iteration of the iterator returns new simulated data,
with different random numbers for the means and a covariance
matrix equal to that of ``self.y``. This iterator is used by
``self.simulated_fit_iter``.
Typical usage::
fit = nonlinear_fit(data=(x,y), prior=prior, fcn=fcn)
...
for ysim, priorsim in fit.simulate_data_iter(n=10):
fitsim = nonlinear_fit(data=(x, ysim), prior=priorsim, fcn=fcn)
print(fitsim)
print('chi2 =', gv.chi2(fit.p, fitsim.p))
This code tests the fitting protocol on simulated data, comparing the
best fit parameters in each case with the correct values (``fit.p``).
The loop in this code is functionally the same as (but probably not
as fast as)::
for fitsim in fit.simulated_fit_iter(n=10):
print(fitsim)
print('chi2 =', gv.chi2(fit.p, fitsim.p))
Args:
n (int or None): Maximum number of iterations (equals
infinity if ``None``).
pexact (None or dict/array of numbers): Fit-parameter values for
the underlying distribution used to generate simulated data;
replaced by ``self.pmean`` if is ``None`` (default).
add_priornoise (bool): Vary prior means if ``True``; otherwise
vary only the means in ``self.y`` (default).
Returns:
An iterator that returns a 2-tuple containing simulated
versions of self.y and self.prior: ``(ysim, priorsim)``.
"""
pexact = self.pmean if pexact is None else pexact
# bootstrap is old name for add_priornoise; keep for legacy code
if bootstrap is not None:
add_priornoise = bootstrap
f = self.fcn(pexact) if self.x is False else self.fcn(self.x, pexact)
y = copy.deepcopy(self.y)
if isinstance(y, _gvar.BufferDict):
# y,f dictionaries; fresh copy of y, reorder f
tmp_f = _gvar.BufferDict([(k, f[k]) for k in y])
y.buf += tmp_f.buf - _gvar.mean(y.buf)
else:
# y,f arrays; fresh copy of y
y += numpy.asarray(f) - _gvar.mean(y)
prior = copy.deepcopy(self.prior)
if prior is None or not add_priornoise:
yiter = _gvar.bootstrap_iter(y, n)
for ysim in _gvar.bootstrap_iter(y, n):
yield ysim, prior
else:
yp = numpy.empty(y.size + prior.size, object)
yp[:y.size] = y.flat
yp[y.size:] = prior.flat
for ypsim in _gvar.bootstrap_iter(yp, n):
y.flat = ypsim[:y.size]
prior.flat = ypsim[y.size:]
yield y, prior | [
"def",
"simulated_data_iter",
"(",
"self",
",",
"n",
"=",
"None",
",",
"pexact",
"=",
"None",
",",
"add_priornoise",
"=",
"False",
",",
"bootstrap",
"=",
"None",
")",
":",
"pexact",
"=",
"self",
".",
"pmean",
"if",
"pexact",
"is",
"None",
"else",
"pexa... | Iterator that returns simulated data based upon a fit's data.
Simulated data is generated from a fit's data ``fit.y`` by
replacing the mean values in that data with random numbers
drawn from a distribution whose mean is ``self.fcn(pexact)``
and whose covariance matrix is the same as that of ``self.y``.
Each iteration of the iterator returns new simulated data,
with different random numbers for the means and a covariance
matrix equal to that of ``self.y``. This iterator is used by
``self.simulated_fit_iter``.
Typical usage::
fit = nonlinear_fit(data=(x,y), prior=prior, fcn=fcn)
...
for ysim, priorsim in fit.simulate_data_iter(n=10):
fitsim = nonlinear_fit(data=(x, ysim), prior=priorsim, fcn=fcn)
print(fitsim)
print('chi2 =', gv.chi2(fit.p, fitsim.p))
This code tests the fitting protocol on simulated data, comparing the
best fit parameters in each case with the correct values (``fit.p``).
The loop in this code is functionally the same as (but probably not
as fast as)::
for fitsim in fit.simulated_fit_iter(n=10):
print(fitsim)
print('chi2 =', gv.chi2(fit.p, fitsim.p))
Args:
n (int or None): Maximum number of iterations (equals
infinity if ``None``).
pexact (None or dict/array of numbers): Fit-parameter values for
the underlying distribution used to generate simulated data;
replaced by ``self.pmean`` if is ``None`` (default).
add_priornoise (bool): Vary prior means if ``True``; otherwise
vary only the means in ``self.y`` (default).
Returns:
An iterator that returns a 2-tuple containing simulated
versions of self.y and self.prior: ``(ysim, priorsim)``. | [
"Iterator",
"that",
"returns",
"simulated",
"data",
"based",
"upon",
"a",
"fit",
"s",
"data",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/__init__.py#L1362-L1434 | train | 33,222 |
gplepage/lsqfit | src/lsqfit/_extras.py | chained_nonlinear_fit.formatall | def formatall(self, *args, **kargs):
" Add-on method for fits returned by chained_nonlinear_fit. "
ans = ''
for x in self.chained_fits:
ans += 10 * '=' + ' ' + str(x) + '\n'
ans += self.chained_fits[x].format(*args, **kargs)
ans += '\n'
return ans[:-1] | python | def formatall(self, *args, **kargs):
" Add-on method for fits returned by chained_nonlinear_fit. "
ans = ''
for x in self.chained_fits:
ans += 10 * '=' + ' ' + str(x) + '\n'
ans += self.chained_fits[x].format(*args, **kargs)
ans += '\n'
return ans[:-1] | [
"def",
"formatall",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"ans",
"=",
"''",
"for",
"x",
"in",
"self",
".",
"chained_fits",
":",
"ans",
"+=",
"10",
"*",
"'='",
"+",
"' '",
"+",
"str",
"(",
"x",
")",
"+",
"'\\n'",
"an... | Add-on method for fits returned by chained_nonlinear_fit. | [
"Add",
"-",
"on",
"method",
"for",
"fits",
"returned",
"by",
"chained_nonlinear_fit",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L758-L765 | train | 33,223 |
gplepage/lsqfit | src/lsqfit/_extras.py | MultiFitter.set | def set(self, **kargs):
""" Reset default keyword parameters.
Assigns new default values from dictionary ``kargs`` to the fitter's
keyword parameters. Keywords for the underlying :mod:`lsqfit` fitters
can also be included (or grouped together in dictionary
``fitterargs``).
Returns tuple ``(kargs, oldkargs)`` where ``kargs`` is a dictionary
containing all :class:`lsqfit.MultiFitter` keywords after they have
been updated, and ``oldkargs`` contains the original values for these
keywords. Use ``fitter.set(**oldkargs)`` to restore the original
values.
"""
kwords = set([
'mopt', 'fast', 'ratio', 'wavg_kargs', 'wavg_all',
'fitterargs', 'fitname',
])
kargs = dict(kargs)
oldkargs = {}
fargs = {}
# changed
for k in list(kargs.keys()): # list() needed since changing kargs
if k in kwords:
oldkargs[k] = getattr(self, k)
setattr(self, k, kargs[k])
kwords.remove(k)
else:
fargs[k] = kargs[k]
del kargs[k]
# unchanged
for k in kwords:
kargs[k] = getattr(self, k)
# manage fitterargs
if 'fitterargs' in kwords:
# means wasn't in kargs initially
oldkargs['fitterargs'] = self.fitterargs
self.fitterargs = dict(self.fitterargs)
if len(fargs) > 0:
self.fitterargs.update(fargs)
kargs['fitterargs'] = dict(self.fitterargs)
return kargs, oldkargs | python | def set(self, **kargs):
""" Reset default keyword parameters.
Assigns new default values from dictionary ``kargs`` to the fitter's
keyword parameters. Keywords for the underlying :mod:`lsqfit` fitters
can also be included (or grouped together in dictionary
``fitterargs``).
Returns tuple ``(kargs, oldkargs)`` where ``kargs`` is a dictionary
containing all :class:`lsqfit.MultiFitter` keywords after they have
been updated, and ``oldkargs`` contains the original values for these
keywords. Use ``fitter.set(**oldkargs)`` to restore the original
values.
"""
kwords = set([
'mopt', 'fast', 'ratio', 'wavg_kargs', 'wavg_all',
'fitterargs', 'fitname',
])
kargs = dict(kargs)
oldkargs = {}
fargs = {}
# changed
for k in list(kargs.keys()): # list() needed since changing kargs
if k in kwords:
oldkargs[k] = getattr(self, k)
setattr(self, k, kargs[k])
kwords.remove(k)
else:
fargs[k] = kargs[k]
del kargs[k]
# unchanged
for k in kwords:
kargs[k] = getattr(self, k)
# manage fitterargs
if 'fitterargs' in kwords:
# means wasn't in kargs initially
oldkargs['fitterargs'] = self.fitterargs
self.fitterargs = dict(self.fitterargs)
if len(fargs) > 0:
self.fitterargs.update(fargs)
kargs['fitterargs'] = dict(self.fitterargs)
return kargs, oldkargs | [
"def",
"set",
"(",
"self",
",",
"*",
"*",
"kargs",
")",
":",
"kwords",
"=",
"set",
"(",
"[",
"'mopt'",
",",
"'fast'",
",",
"'ratio'",
",",
"'wavg_kargs'",
",",
"'wavg_all'",
",",
"'fitterargs'",
",",
"'fitname'",
",",
"]",
")",
"kargs",
"=",
"dict",
... | Reset default keyword parameters.
Assigns new default values from dictionary ``kargs`` to the fitter's
keyword parameters. Keywords for the underlying :mod:`lsqfit` fitters
can also be included (or grouped together in dictionary
``fitterargs``).
Returns tuple ``(kargs, oldkargs)`` where ``kargs`` is a dictionary
containing all :class:`lsqfit.MultiFitter` keywords after they have
been updated, and ``oldkargs`` contains the original values for these
keywords. Use ``fitter.set(**oldkargs)`` to restore the original
values. | [
"Reset",
"default",
"keyword",
"parameters",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L837-L878 | train | 33,224 |
gplepage/lsqfit | src/lsqfit/_extras.py | MultiFitter.buildfitfcn | def buildfitfcn(self):
""" Create fit function to fit models in list ``models``. """
def _fitfcn(p, flatmodels=self.flatmodels):
ans = gvar.BufferDict()
for m in flatmodels:
ans[m.datatag] = (
m.fitfcn(p) if m.ncg <= 1 else
MultiFitter.coarse_grain(m.fitfcn(p), m.ncg)
)
return ans
return _fitfcn | python | def buildfitfcn(self):
""" Create fit function to fit models in list ``models``. """
def _fitfcn(p, flatmodels=self.flatmodels):
ans = gvar.BufferDict()
for m in flatmodels:
ans[m.datatag] = (
m.fitfcn(p) if m.ncg <= 1 else
MultiFitter.coarse_grain(m.fitfcn(p), m.ncg)
)
return ans
return _fitfcn | [
"def",
"buildfitfcn",
"(",
"self",
")",
":",
"def",
"_fitfcn",
"(",
"p",
",",
"flatmodels",
"=",
"self",
".",
"flatmodels",
")",
":",
"ans",
"=",
"gvar",
".",
"BufferDict",
"(",
")",
"for",
"m",
"in",
"flatmodels",
":",
"ans",
"[",
"m",
".",
"datat... | Create fit function to fit models in list ``models``. | [
"Create",
"fit",
"function",
"to",
"fit",
"models",
"in",
"list",
"models",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L880-L890 | train | 33,225 |
gplepage/lsqfit | src/lsqfit/_extras.py | MultiFitter.builddata | def builddata(self, mopt=None, data=None, pdata=None, prior=None):
""" Rebuild pdata to account for marginalization. """
if pdata is None:
if data is None:
raise ValueError('no data or pdata')
pdata = gvar.BufferDict()
for m in self.flatmodels:
pdata[m.datatag] = (
m.builddata(data) if m.ncg <= 1 else
MultiFitter.coarse_grain(m.builddata(data), m.ncg)
)
else:
npdata = gvar.BufferDict()
for m in self.flatmodels:
npdata[m.datatag] = pdata[m.datatag]
pdata = npdata
if mopt is not None:
fitfcn = self.buildfitfcn()
p_all = self.buildprior(prior=prior, mopt=None)
f_all = fitfcn(p_all)
# fcn with part we want to keep
p_trunc = self.buildprior(prior=prior, mopt=mopt)
f_trunc = fitfcn(p_trunc)
# correct pdata
pdata = gvar.BufferDict(pdata)
if not self.ratio:
for m in self.flatmodels:
pdata[m.datatag] += f_trunc[m.datatag] - f_all[m.datatag]
else:
for m in self.flatmodels:
ii = (gvar.mean(f_all[m.datatag]) != 0)
ratio = f_trunc[m.datatag][ii] / f_all[m.datatag][ii]
pdata[m.datatag][ii] *= ratio
return pdata | python | def builddata(self, mopt=None, data=None, pdata=None, prior=None):
""" Rebuild pdata to account for marginalization. """
if pdata is None:
if data is None:
raise ValueError('no data or pdata')
pdata = gvar.BufferDict()
for m in self.flatmodels:
pdata[m.datatag] = (
m.builddata(data) if m.ncg <= 1 else
MultiFitter.coarse_grain(m.builddata(data), m.ncg)
)
else:
npdata = gvar.BufferDict()
for m in self.flatmodels:
npdata[m.datatag] = pdata[m.datatag]
pdata = npdata
if mopt is not None:
fitfcn = self.buildfitfcn()
p_all = self.buildprior(prior=prior, mopt=None)
f_all = fitfcn(p_all)
# fcn with part we want to keep
p_trunc = self.buildprior(prior=prior, mopt=mopt)
f_trunc = fitfcn(p_trunc)
# correct pdata
pdata = gvar.BufferDict(pdata)
if not self.ratio:
for m in self.flatmodels:
pdata[m.datatag] += f_trunc[m.datatag] - f_all[m.datatag]
else:
for m in self.flatmodels:
ii = (gvar.mean(f_all[m.datatag]) != 0)
ratio = f_trunc[m.datatag][ii] / f_all[m.datatag][ii]
pdata[m.datatag][ii] *= ratio
return pdata | [
"def",
"builddata",
"(",
"self",
",",
"mopt",
"=",
"None",
",",
"data",
"=",
"None",
",",
"pdata",
"=",
"None",
",",
"prior",
"=",
"None",
")",
":",
"if",
"pdata",
"is",
"None",
":",
"if",
"data",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'... | Rebuild pdata to account for marginalization. | [
"Rebuild",
"pdata",
"to",
"account",
"for",
"marginalization",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L892-L927 | train | 33,226 |
gplepage/lsqfit | src/lsqfit/_extras.py | MultiFitter.buildprior | def buildprior(self, prior, mopt=None):
""" Create prior to fit models in list ``models``. """
nprior = gvar.BufferDict()
for m in self.flatmodels:
nprior.update(m.buildprior(
prior, mopt=mopt,
))
if not self.fast:
for k in prior:
if k not in nprior:
nprior[k] = prior[k]
return nprior | python | def buildprior(self, prior, mopt=None):
""" Create prior to fit models in list ``models``. """
nprior = gvar.BufferDict()
for m in self.flatmodels:
nprior.update(m.buildprior(
prior, mopt=mopt,
))
if not self.fast:
for k in prior:
if k not in nprior:
nprior[k] = prior[k]
return nprior | [
"def",
"buildprior",
"(",
"self",
",",
"prior",
",",
"mopt",
"=",
"None",
")",
":",
"nprior",
"=",
"gvar",
".",
"BufferDict",
"(",
")",
"for",
"m",
"in",
"self",
".",
"flatmodels",
":",
"nprior",
".",
"update",
"(",
"m",
".",
"buildprior",
"(",
"pr... | Create prior to fit models in list ``models``. | [
"Create",
"prior",
"to",
"fit",
"models",
"in",
"list",
"models",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L929-L940 | train | 33,227 |
gplepage/lsqfit | src/lsqfit/_extras.py | MultiFitter._flatten_models | def _flatten_models(tasklist):
" Create 1d-array containing all disctinct models from ``tasklist``. "
ans = gvar.BufferDict()
for task, mlist in tasklist:
if task != 'fit':
continue
for m in mlist:
id_m = id(m)
if id_m not in ans:
ans[id_m] = m
return ans.buf.tolist() | python | def _flatten_models(tasklist):
" Create 1d-array containing all disctinct models from ``tasklist``. "
ans = gvar.BufferDict()
for task, mlist in tasklist:
if task != 'fit':
continue
for m in mlist:
id_m = id(m)
if id_m not in ans:
ans[id_m] = m
return ans.buf.tolist() | [
"def",
"_flatten_models",
"(",
"tasklist",
")",
":",
"ans",
"=",
"gvar",
".",
"BufferDict",
"(",
")",
"for",
"task",
",",
"mlist",
"in",
"tasklist",
":",
"if",
"task",
"!=",
"'fit'",
":",
"continue",
"for",
"m",
"in",
"mlist",
":",
"id_m",
"=",
"id",... | Create 1d-array containing all disctinct models from ``tasklist``. | [
"Create",
"1d",
"-",
"array",
"containing",
"all",
"disctinct",
"models",
"from",
"tasklist",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L943-L953 | train | 33,228 |
gplepage/lsqfit | src/lsqfit/_extras.py | MultiFitter.flatten_models | def flatten_models(models):
" Create 1d-array containing all disctinct models from ``models``. "
if isinstance(models, MultiFitterModel):
ans = [models]
else:
tasklist = MultiFitter._compile_models(models)
ans = MultiFitter._flatten_models(tasklist)
return ans | python | def flatten_models(models):
" Create 1d-array containing all disctinct models from ``models``. "
if isinstance(models, MultiFitterModel):
ans = [models]
else:
tasklist = MultiFitter._compile_models(models)
ans = MultiFitter._flatten_models(tasklist)
return ans | [
"def",
"flatten_models",
"(",
"models",
")",
":",
"if",
"isinstance",
"(",
"models",
",",
"MultiFitterModel",
")",
":",
"ans",
"=",
"[",
"models",
"]",
"else",
":",
"tasklist",
"=",
"MultiFitter",
".",
"_compile_models",
"(",
"models",
")",
"ans",
"=",
"... | Create 1d-array containing all disctinct models from ``models``. | [
"Create",
"1d",
"-",
"array",
"containing",
"all",
"disctinct",
"models",
"from",
"models",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L956-L963 | train | 33,229 |
gplepage/lsqfit | src/lsqfit/_extras.py | MultiFitter.lsqfit | def lsqfit(self, data=None, pdata=None, prior=None, p0=None, **kargs):
""" Compute least-squares fit of models to data.
:meth:`MultiFitter.lsqfit` fits all of the models together, in
a single fit. It returns the |nonlinear_fit| object from the fit.
To see plots of the fit data divided by the fit function
with the best-fit parameters use
fit.show_plots()
This method has optional keyword arguments ``save`` and ``view``;
see documentation for :class:`lsqfit.MultiFitter.show_plots`
for more information. Plotting requires module :mod:`matplotlib`.
To bootstrap a fit, use ``fit.bootstrapped_fit_iter(...)``;
see :meth:`lsqfit.nonlinear_fit.bootstrapped_fit_iter` for more
information.
Args:
data: Input data. One of ``data`` or ``pdata`` must be
specified but not both. ``pdata`` is obtained from ``data``
by collecting the output from ``m.builddata(data)``
for each model ``m`` and storing it in a dictionary
with key ``m.datatag``.
pdata: Input data that has been processed by the
models using :meth:`MultiFitter.process_data` or
:meth:`MultiFitter.process_dataset`. One of
``data`` or ``pdata`` must be specified but not both.
prior (dict): Bayesian prior for fit parameters used by the models.
p0: Dictionary , indexed by parameter labels, containing
initial values for the parameters in the fit. Setting
``p0=None`` implies that initial values are extracted from the
prior. Setting ``p0="filename"`` causes the fitter to look in
the file with name ``"filename"`` for initial values and to
write out best-fit parameter values after the fit (for the
next call to ``self.lsqfit()``).
kargs: Arguments that (temporarily) override parameters specified
when the :class:`MultiFitter` was created. Can also include
additional arguments to be passed through to the :mod:`lsqfit`
fitter.
"""
# gather parameters
if prior is None:
raise ValueError('no prior')
kargs, oldargs = self.set(**kargs)
# save parameters for bootstrap (in case needed)
fitter_args_kargs = (
self.chained_lsqfit,
dict(data=data, prior=prior, pdata=pdata, models=self.models),
dict(kargs),
)
# build prior, data and function
fitprior = self.buildprior(prior=prior, mopt=self.mopt)
fitdata = self.builddata(
mopt=self.mopt, data=data, pdata=pdata, prior=prior
)
fitfcn = self.buildfitfcn()
# fit
self.fit = lsqfit.nonlinear_fit(
data=fitdata, prior=fitprior, fcn=fitfcn, p0=p0,
**self.fitterargs
)
if len(self.flatmodels) > 1:
fname = self.fitname(
'(' +
','.join([self.fitname(k.datatag) for k in self.flatmodels])
+ ')'
)
else:
fname = self.fitname(self.flatmodels[0].datatag)
self.fit.chained_fits = collections.OrderedDict([(fname, self.fit)])
# add methods for printing and plotting
def _formatall(*args, **kargs):
" Add-on method for fits returned by chained_lsqfit. "
ans = ''
for x in self.fit.chained_fits:
ans += 10 * '=' + ' ' + str(x) + '\n'
ans += self.fit.chained_fits[x].format(*args, **kargs)
ans += '\n'
return ans[:-1]
self.fit.formatall = _formatall
def _show_plots(save=False, view='ratio'):
MultiFitter.show_plots(
fitdata=fitdata, fitval=fitfcn(self.fit.p),
save=save, view=view,
)
self.fit.show_plots = _show_plots
# restore default keywords
self.set(**oldargs)
# add bootstrap method
fitter_args_kargs[1]['p0'] = self.fit.pmean
def _bstrap_iter(
n=None, datalist=None, pdatalist=None, **kargs
):
return MultiFitter._bootstrapped_fit_iter(
fitter_args_kargs,
n=n, datalist=datalist, pdatalist=pdatalist, **kargs
)
self.fit.bootstrapped_fit_iter = _bstrap_iter
return self.fit | python | def lsqfit(self, data=None, pdata=None, prior=None, p0=None, **kargs):
""" Compute least-squares fit of models to data.
:meth:`MultiFitter.lsqfit` fits all of the models together, in
a single fit. It returns the |nonlinear_fit| object from the fit.
To see plots of the fit data divided by the fit function
with the best-fit parameters use
fit.show_plots()
This method has optional keyword arguments ``save`` and ``view``;
see documentation for :class:`lsqfit.MultiFitter.show_plots`
for more information. Plotting requires module :mod:`matplotlib`.
To bootstrap a fit, use ``fit.bootstrapped_fit_iter(...)``;
see :meth:`lsqfit.nonlinear_fit.bootstrapped_fit_iter` for more
information.
Args:
data: Input data. One of ``data`` or ``pdata`` must be
specified but not both. ``pdata`` is obtained from ``data``
by collecting the output from ``m.builddata(data)``
for each model ``m`` and storing it in a dictionary
with key ``m.datatag``.
pdata: Input data that has been processed by the
models using :meth:`MultiFitter.process_data` or
:meth:`MultiFitter.process_dataset`. One of
``data`` or ``pdata`` must be specified but not both.
prior (dict): Bayesian prior for fit parameters used by the models.
p0: Dictionary , indexed by parameter labels, containing
initial values for the parameters in the fit. Setting
``p0=None`` implies that initial values are extracted from the
prior. Setting ``p0="filename"`` causes the fitter to look in
the file with name ``"filename"`` for initial values and to
write out best-fit parameter values after the fit (for the
next call to ``self.lsqfit()``).
kargs: Arguments that (temporarily) override parameters specified
when the :class:`MultiFitter` was created. Can also include
additional arguments to be passed through to the :mod:`lsqfit`
fitter.
"""
# gather parameters
if prior is None:
raise ValueError('no prior')
kargs, oldargs = self.set(**kargs)
# save parameters for bootstrap (in case needed)
fitter_args_kargs = (
self.chained_lsqfit,
dict(data=data, prior=prior, pdata=pdata, models=self.models),
dict(kargs),
)
# build prior, data and function
fitprior = self.buildprior(prior=prior, mopt=self.mopt)
fitdata = self.builddata(
mopt=self.mopt, data=data, pdata=pdata, prior=prior
)
fitfcn = self.buildfitfcn()
# fit
self.fit = lsqfit.nonlinear_fit(
data=fitdata, prior=fitprior, fcn=fitfcn, p0=p0,
**self.fitterargs
)
if len(self.flatmodels) > 1:
fname = self.fitname(
'(' +
','.join([self.fitname(k.datatag) for k in self.flatmodels])
+ ')'
)
else:
fname = self.fitname(self.flatmodels[0].datatag)
self.fit.chained_fits = collections.OrderedDict([(fname, self.fit)])
# add methods for printing and plotting
def _formatall(*args, **kargs):
" Add-on method for fits returned by chained_lsqfit. "
ans = ''
for x in self.fit.chained_fits:
ans += 10 * '=' + ' ' + str(x) + '\n'
ans += self.fit.chained_fits[x].format(*args, **kargs)
ans += '\n'
return ans[:-1]
self.fit.formatall = _formatall
def _show_plots(save=False, view='ratio'):
MultiFitter.show_plots(
fitdata=fitdata, fitval=fitfcn(self.fit.p),
save=save, view=view,
)
self.fit.show_plots = _show_plots
# restore default keywords
self.set(**oldargs)
# add bootstrap method
fitter_args_kargs[1]['p0'] = self.fit.pmean
def _bstrap_iter(
n=None, datalist=None, pdatalist=None, **kargs
):
return MultiFitter._bootstrapped_fit_iter(
fitter_args_kargs,
n=n, datalist=datalist, pdatalist=pdatalist, **kargs
)
self.fit.bootstrapped_fit_iter = _bstrap_iter
return self.fit | [
"def",
"lsqfit",
"(",
"self",
",",
"data",
"=",
"None",
",",
"pdata",
"=",
"None",
",",
"prior",
"=",
"None",
",",
"p0",
"=",
"None",
",",
"*",
"*",
"kargs",
")",
":",
"# gather parameters",
"if",
"prior",
"is",
"None",
":",
"raise",
"ValueError",
... | Compute least-squares fit of models to data.
:meth:`MultiFitter.lsqfit` fits all of the models together, in
a single fit. It returns the |nonlinear_fit| object from the fit.
To see plots of the fit data divided by the fit function
with the best-fit parameters use
fit.show_plots()
This method has optional keyword arguments ``save`` and ``view``;
see documentation for :class:`lsqfit.MultiFitter.show_plots`
for more information. Plotting requires module :mod:`matplotlib`.
To bootstrap a fit, use ``fit.bootstrapped_fit_iter(...)``;
see :meth:`lsqfit.nonlinear_fit.bootstrapped_fit_iter` for more
information.
Args:
data: Input data. One of ``data`` or ``pdata`` must be
specified but not both. ``pdata`` is obtained from ``data``
by collecting the output from ``m.builddata(data)``
for each model ``m`` and storing it in a dictionary
with key ``m.datatag``.
pdata: Input data that has been processed by the
models using :meth:`MultiFitter.process_data` or
:meth:`MultiFitter.process_dataset`. One of
``data`` or ``pdata`` must be specified but not both.
prior (dict): Bayesian prior for fit parameters used by the models.
p0: Dictionary , indexed by parameter labels, containing
initial values for the parameters in the fit. Setting
``p0=None`` implies that initial values are extracted from the
prior. Setting ``p0="filename"`` causes the fitter to look in
the file with name ``"filename"`` for initial values and to
write out best-fit parameter values after the fit (for the
next call to ``self.lsqfit()``).
kargs: Arguments that (temporarily) override parameters specified
when the :class:`MultiFitter` was created. Can also include
additional arguments to be passed through to the :mod:`lsqfit`
fitter. | [
"Compute",
"least",
"-",
"squares",
"fit",
"of",
"models",
"to",
"data",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L965-L1071 | train | 33,230 |
gplepage/lsqfit | src/lsqfit/_extras.py | MultiFitter._compile_models | def _compile_models(models):
""" Convert ``models`` into a list of tasks.
Each task is tuple ``(name, data)`` where ``name`` indicates the task
task and ``data`` is the relevant data for that task.
Supported tasks and data:
- ``'fit'`` and list of models
- ``'update-kargs'`` and ``None``
- ``'update-prior'`` and ``None``
- ``'wavg'`` and number of (previous) fits to average
"""
tasklist = []
for m in models:
if isinstance(m, MultiFitterModel):
tasklist += [('fit', [m])]
tasklist += [('update-prior', None)]
elif hasattr(m, 'keys'):
tasklist += [('update-kargs', m)]
elif isinstance(m, tuple):
tasklist += [('fit', list(m))]
tasklist += [('update-prior', None)]
elif isinstance(m, list):
for sm in m:
if isinstance(sm, MultiFitterModel):
tasklist += [('fit', [sm])]
elif isinstance(sm, tuple):
tasklist += [('fit', list(sm))]
else:
raise ValueError(
'type {} not allowed in sublists '.format(
str(type(sm))
)
)
tasklist += [('wavg', len(m))]
tasklist += [('update-prior', None)]
else:
raise RuntimeError('bad model list')
return tasklist | python | def _compile_models(models):
""" Convert ``models`` into a list of tasks.
Each task is tuple ``(name, data)`` where ``name`` indicates the task
task and ``data`` is the relevant data for that task.
Supported tasks and data:
- ``'fit'`` and list of models
- ``'update-kargs'`` and ``None``
- ``'update-prior'`` and ``None``
- ``'wavg'`` and number of (previous) fits to average
"""
tasklist = []
for m in models:
if isinstance(m, MultiFitterModel):
tasklist += [('fit', [m])]
tasklist += [('update-prior', None)]
elif hasattr(m, 'keys'):
tasklist += [('update-kargs', m)]
elif isinstance(m, tuple):
tasklist += [('fit', list(m))]
tasklist += [('update-prior', None)]
elif isinstance(m, list):
for sm in m:
if isinstance(sm, MultiFitterModel):
tasklist += [('fit', [sm])]
elif isinstance(sm, tuple):
tasklist += [('fit', list(sm))]
else:
raise ValueError(
'type {} not allowed in sublists '.format(
str(type(sm))
)
)
tasklist += [('wavg', len(m))]
tasklist += [('update-prior', None)]
else:
raise RuntimeError('bad model list')
return tasklist | [
"def",
"_compile_models",
"(",
"models",
")",
":",
"tasklist",
"=",
"[",
"]",
"for",
"m",
"in",
"models",
":",
"if",
"isinstance",
"(",
"m",
",",
"MultiFitterModel",
")",
":",
"tasklist",
"+=",
"[",
"(",
"'fit'",
",",
"[",
"m",
"]",
")",
"]",
"task... | Convert ``models`` into a list of tasks.
Each task is tuple ``(name, data)`` where ``name`` indicates the task
task and ``data`` is the relevant data for that task.
Supported tasks and data:
- ``'fit'`` and list of models
- ``'update-kargs'`` and ``None``
- ``'update-prior'`` and ``None``
- ``'wavg'`` and number of (previous) fits to average | [
"Convert",
"models",
"into",
"a",
"list",
"of",
"tasks",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L1250-L1290 | train | 33,231 |
gplepage/lsqfit | src/lsqfit/_extras.py | MultiFitter.coarse_grain | def coarse_grain(G, ncg):
""" Coarse-grain last index of array ``G``.
Bin the last index of array ``G`` in bins of width ``ncg``, and
replace each bin by its average. Return the binned results.
Args:
G: Array to be coarse-grained.
ncg: Bin width for coarse-graining.
"""
if ncg <= 1:
return G
G = numpy.asarray(G)
nbin, remainder = divmod(G.shape[-1], ncg)
if remainder != 0:
nbin += 1
return numpy.transpose([
numpy.sum(G[..., i:i+ncg], axis=-1) / G[..., i:i+ncg].shape[-1]
for i in numpy.arange(0, ncg * nbin, ncg)
]) | python | def coarse_grain(G, ncg):
""" Coarse-grain last index of array ``G``.
Bin the last index of array ``G`` in bins of width ``ncg``, and
replace each bin by its average. Return the binned results.
Args:
G: Array to be coarse-grained.
ncg: Bin width for coarse-graining.
"""
if ncg <= 1:
return G
G = numpy.asarray(G)
nbin, remainder = divmod(G.shape[-1], ncg)
if remainder != 0:
nbin += 1
return numpy.transpose([
numpy.sum(G[..., i:i+ncg], axis=-1) / G[..., i:i+ncg].shape[-1]
for i in numpy.arange(0, ncg * nbin, ncg)
]) | [
"def",
"coarse_grain",
"(",
"G",
",",
"ncg",
")",
":",
"if",
"ncg",
"<=",
"1",
":",
"return",
"G",
"G",
"=",
"numpy",
".",
"asarray",
"(",
"G",
")",
"nbin",
",",
"remainder",
"=",
"divmod",
"(",
"G",
".",
"shape",
"[",
"-",
"1",
"]",
",",
"nc... | Coarse-grain last index of array ``G``.
Bin the last index of array ``G`` in bins of width ``ncg``, and
replace each bin by its average. Return the binned results.
Args:
G: Array to be coarse-grained.
ncg: Bin width for coarse-graining. | [
"Coarse",
"-",
"grain",
"last",
"index",
"of",
"array",
"G",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L1355-L1374 | train | 33,232 |
gplepage/lsqfit | src/lsqfit/_extras.py | MultiFitter.process_data | def process_data(data, models):
""" Convert ``data`` to processed data using ``models``.
Data from dictionary ``data`` is processed by each model
in list ``models``, and the results collected into a new
dictionary ``pdata`` for use in :meth:`MultiFitter.lsqfit`
and :meth:`MultiFitter.chained_lsqft`.
"""
pdata = gvar.BufferDict()
for m in MultiFitter.flatten_models(models):
pdata[m.datatag] = (
m.builddata(data) if m.ncg <= 1 else
MultiFitter.coarse_grain(m.builddata(data), ncg=m.ncg)
)
return pdata | python | def process_data(data, models):
""" Convert ``data`` to processed data using ``models``.
Data from dictionary ``data`` is processed by each model
in list ``models``, and the results collected into a new
dictionary ``pdata`` for use in :meth:`MultiFitter.lsqfit`
and :meth:`MultiFitter.chained_lsqft`.
"""
pdata = gvar.BufferDict()
for m in MultiFitter.flatten_models(models):
pdata[m.datatag] = (
m.builddata(data) if m.ncg <= 1 else
MultiFitter.coarse_grain(m.builddata(data), ncg=m.ncg)
)
return pdata | [
"def",
"process_data",
"(",
"data",
",",
"models",
")",
":",
"pdata",
"=",
"gvar",
".",
"BufferDict",
"(",
")",
"for",
"m",
"in",
"MultiFitter",
".",
"flatten_models",
"(",
"models",
")",
":",
"pdata",
"[",
"m",
".",
"datatag",
"]",
"=",
"(",
"m",
... | Convert ``data`` to processed data using ``models``.
Data from dictionary ``data`` is processed by each model
in list ``models``, and the results collected into a new
dictionary ``pdata`` for use in :meth:`MultiFitter.lsqfit`
and :meth:`MultiFitter.chained_lsqft`. | [
"Convert",
"data",
"to",
"processed",
"data",
"using",
"models",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L1377-L1391 | train | 33,233 |
gplepage/lsqfit | src/lsqfit/_extras.py | MultiFitter.process_dataset | def process_dataset(dataset, models, **kargs):
""" Convert ``dataset`` to processed data using ``models``.
:class:`gvar.dataset.Dataset` (or similar dictionary) object
``dataset`` is processed by each model in list ``models``,
and the results collected into a new dictionary ``pdata`` for use in
:meth:`MultiFitter.lsqfit` and :meth:`MultiFitter.chained_lsqft`.
Assumes that the models have defined method
:meth:`MultiFitterModel.builddataset`. Keyword arguments
``kargs`` are passed on to :func:`gvar.dataset.avg_data` when
averaging the data.
"""
dset = collections.OrderedDict()
for m in MultiFitter.flatten_models(models):
dset[m.datatag] = (
m.builddataset(dataset) if m.ncg <= 1 else
MultiFitter.coarse_grain(m.builddataset(dataset), ncg=m.ncg)
)
return gvar.dataset.avg_data(dset, **kargs) | python | def process_dataset(dataset, models, **kargs):
""" Convert ``dataset`` to processed data using ``models``.
:class:`gvar.dataset.Dataset` (or similar dictionary) object
``dataset`` is processed by each model in list ``models``,
and the results collected into a new dictionary ``pdata`` for use in
:meth:`MultiFitter.lsqfit` and :meth:`MultiFitter.chained_lsqft`.
Assumes that the models have defined method
:meth:`MultiFitterModel.builddataset`. Keyword arguments
``kargs`` are passed on to :func:`gvar.dataset.avg_data` when
averaging the data.
"""
dset = collections.OrderedDict()
for m in MultiFitter.flatten_models(models):
dset[m.datatag] = (
m.builddataset(dataset) if m.ncg <= 1 else
MultiFitter.coarse_grain(m.builddataset(dataset), ncg=m.ncg)
)
return gvar.dataset.avg_data(dset, **kargs) | [
"def",
"process_dataset",
"(",
"dataset",
",",
"models",
",",
"*",
"*",
"kargs",
")",
":",
"dset",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"m",
"in",
"MultiFitter",
".",
"flatten_models",
"(",
"models",
")",
":",
"dset",
"[",
"m",
".",... | Convert ``dataset`` to processed data using ``models``.
:class:`gvar.dataset.Dataset` (or similar dictionary) object
``dataset`` is processed by each model in list ``models``,
and the results collected into a new dictionary ``pdata`` for use in
:meth:`MultiFitter.lsqfit` and :meth:`MultiFitter.chained_lsqft`.
Assumes that the models have defined method
:meth:`MultiFitterModel.builddataset`. Keyword arguments
``kargs`` are passed on to :func:`gvar.dataset.avg_data` when
averaging the data. | [
"Convert",
"dataset",
"to",
"processed",
"data",
"using",
"models",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L1394-L1412 | train | 33,234 |
gplepage/lsqfit | examples/multifitter.py | Linear.buildprior | def buildprior(self, prior, mopt=None, extend=False):
" Extract the model's parameters from prior. "
newprior = {}
# allow for log-normal, etc priors
intercept, slope = gv.get_dictkeys(
prior, [self.intercept, self.slope]
)
newprior[intercept] = prior[intercept]
if mopt is None:
# slope parameter marginalized if mopt is not None
newprior[slope] = prior[slope]
return newprior | python | def buildprior(self, prior, mopt=None, extend=False):
" Extract the model's parameters from prior. "
newprior = {}
# allow for log-normal, etc priors
intercept, slope = gv.get_dictkeys(
prior, [self.intercept, self.slope]
)
newprior[intercept] = prior[intercept]
if mopt is None:
# slope parameter marginalized if mopt is not None
newprior[slope] = prior[slope]
return newprior | [
"def",
"buildprior",
"(",
"self",
",",
"prior",
",",
"mopt",
"=",
"None",
",",
"extend",
"=",
"False",
")",
":",
"newprior",
"=",
"{",
"}",
"# allow for log-normal, etc priors",
"intercept",
",",
"slope",
"=",
"gv",
".",
"get_dictkeys",
"(",
"prior",
",",
... | Extract the model's parameters from prior. | [
"Extract",
"the",
"model",
"s",
"parameters",
"from",
"prior",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/examples/multifitter.py#L98-L109 | train | 33,235 |
gplepage/lsqfit | examples/pendulum.py | show_plot | def show_plot(t_array, th_array):
""" Display theta vs t plot. """
th_mean = gv.mean(th_array)
th_sdev = gv.sdev(th_array)
thp = th_mean + th_sdev
thm = th_mean - th_sdev
plt.fill_between(t_array, thp, thm, color='0.8')
plt.plot(t_array, th_mean, linewidth=0.5)
plt.xlabel('$t$')
plt.ylabel(r'$\theta(t)$')
plt.savefig('pendulum.pdf', bbox_inches='tight')
plt.show() | python | def show_plot(t_array, th_array):
""" Display theta vs t plot. """
th_mean = gv.mean(th_array)
th_sdev = gv.sdev(th_array)
thp = th_mean + th_sdev
thm = th_mean - th_sdev
plt.fill_between(t_array, thp, thm, color='0.8')
plt.plot(t_array, th_mean, linewidth=0.5)
plt.xlabel('$t$')
plt.ylabel(r'$\theta(t)$')
plt.savefig('pendulum.pdf', bbox_inches='tight')
plt.show() | [
"def",
"show_plot",
"(",
"t_array",
",",
"th_array",
")",
":",
"th_mean",
"=",
"gv",
".",
"mean",
"(",
"th_array",
")",
"th_sdev",
"=",
"gv",
".",
"sdev",
"(",
"th_array",
")",
"thp",
"=",
"th_mean",
"+",
"th_sdev",
"thm",
"=",
"th_mean",
"-",
"th_sd... | Display theta vs t plot. | [
"Display",
"theta",
"vs",
"t",
"plot",
"."
] | 6a57fd687632c175fccb47d8e8e943cda5e9ce9d | https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/examples/pendulum.py#L127-L138 | train | 33,236 |
obsrvbl/flowlogs-reader | flowlogs_reader/aggregation.py | aggregated_records | def aggregated_records(all_records, key_fields=KEY_FIELDS):
"""
Yield dicts that correspond to aggregates of the flow records given by
the sequence of FlowRecords in `all_records`. Skips incomplete records.
This will consume the `all_records` iterator, and requires enough memory to
be able to read it entirely.
`key_fields` optionally contains the fields over which to aggregate. By
default it's the typical flow 5-tuple.
"""
flow_table = defaultdict(_FlowStats)
for flow_record in all_records:
key = tuple(getattr(flow_record, attr) for attr in key_fields)
if any(x is None for x in key):
continue
flow_table[key].update(flow_record)
for key in flow_table:
item = {k: v for k, v in zip(key_fields, key)}
item.update(flow_table[key].to_dict())
yield item | python | def aggregated_records(all_records, key_fields=KEY_FIELDS):
"""
Yield dicts that correspond to aggregates of the flow records given by
the sequence of FlowRecords in `all_records`. Skips incomplete records.
This will consume the `all_records` iterator, and requires enough memory to
be able to read it entirely.
`key_fields` optionally contains the fields over which to aggregate. By
default it's the typical flow 5-tuple.
"""
flow_table = defaultdict(_FlowStats)
for flow_record in all_records:
key = tuple(getattr(flow_record, attr) for attr in key_fields)
if any(x is None for x in key):
continue
flow_table[key].update(flow_record)
for key in flow_table:
item = {k: v for k, v in zip(key_fields, key)}
item.update(flow_table[key].to_dict())
yield item | [
"def",
"aggregated_records",
"(",
"all_records",
",",
"key_fields",
"=",
"KEY_FIELDS",
")",
":",
"flow_table",
"=",
"defaultdict",
"(",
"_FlowStats",
")",
"for",
"flow_record",
"in",
"all_records",
":",
"key",
"=",
"tuple",
"(",
"getattr",
"(",
"flow_record",
... | Yield dicts that correspond to aggregates of the flow records given by
the sequence of FlowRecords in `all_records`. Skips incomplete records.
This will consume the `all_records` iterator, and requires enough memory to
be able to read it entirely.
`key_fields` optionally contains the fields over which to aggregate. By
default it's the typical flow 5-tuple. | [
"Yield",
"dicts",
"that",
"correspond",
"to",
"aggregates",
"of",
"the",
"flow",
"records",
"given",
"by",
"the",
"sequence",
"of",
"FlowRecords",
"in",
"all_records",
".",
"Skips",
"incomplete",
"records",
".",
"This",
"will",
"consume",
"the",
"all_records",
... | 248d8cb3cc586859b6744d30cebce0f359d9900c | https://github.com/obsrvbl/flowlogs-reader/blob/248d8cb3cc586859b6744d30cebce0f359d9900c/flowlogs_reader/aggregation.py#L48-L67 | train | 33,237 |
obsrvbl/flowlogs-reader | flowlogs_reader/__main__.py | action_print | def action_print(reader, *args):
"""Simply print the Flow Log records to output."""
arg_count = len(args)
if arg_count == 0:
stop_after = 0
elif arg_count == 1:
stop_after = int(args[0])
else:
raise RuntimeError("0 or 1 arguments expected for action 'print'")
for i, record in enumerate(reader, 1):
print(record.to_message())
if i == stop_after:
break | python | def action_print(reader, *args):
"""Simply print the Flow Log records to output."""
arg_count = len(args)
if arg_count == 0:
stop_after = 0
elif arg_count == 1:
stop_after = int(args[0])
else:
raise RuntimeError("0 or 1 arguments expected for action 'print'")
for i, record in enumerate(reader, 1):
print(record.to_message())
if i == stop_after:
break | [
"def",
"action_print",
"(",
"reader",
",",
"*",
"args",
")",
":",
"arg_count",
"=",
"len",
"(",
"args",
")",
"if",
"arg_count",
"==",
"0",
":",
"stop_after",
"=",
"0",
"elif",
"arg_count",
"==",
"1",
":",
"stop_after",
"=",
"int",
"(",
"args",
"[",
... | Simply print the Flow Log records to output. | [
"Simply",
"print",
"the",
"Flow",
"Log",
"records",
"to",
"output",
"."
] | 248d8cb3cc586859b6744d30cebce0f359d9900c | https://github.com/obsrvbl/flowlogs-reader/blob/248d8cb3cc586859b6744d30cebce0f359d9900c/flowlogs_reader/__main__.py#L31-L44 | train | 33,238 |
obsrvbl/flowlogs-reader | flowlogs_reader/__main__.py | action_ipset | def action_ipset(reader, *args):
"""Show the set of IPs seen in Flow Log records."""
ip_set = set()
for record in reader:
if record.log_status in (SKIPDATA, NODATA):
continue
ip_set.add(record.srcaddr)
ip_set.add(record.dstaddr)
for ip in ip_set:
print(ip) | python | def action_ipset(reader, *args):
"""Show the set of IPs seen in Flow Log records."""
ip_set = set()
for record in reader:
if record.log_status in (SKIPDATA, NODATA):
continue
ip_set.add(record.srcaddr)
ip_set.add(record.dstaddr)
for ip in ip_set:
print(ip) | [
"def",
"action_ipset",
"(",
"reader",
",",
"*",
"args",
")",
":",
"ip_set",
"=",
"set",
"(",
")",
"for",
"record",
"in",
"reader",
":",
"if",
"record",
".",
"log_status",
"in",
"(",
"SKIPDATA",
",",
"NODATA",
")",
":",
"continue",
"ip_set",
".",
"add... | Show the set of IPs seen in Flow Log records. | [
"Show",
"the",
"set",
"of",
"IPs",
"seen",
"in",
"Flow",
"Log",
"records",
"."
] | 248d8cb3cc586859b6744d30cebce0f359d9900c | https://github.com/obsrvbl/flowlogs-reader/blob/248d8cb3cc586859b6744d30cebce0f359d9900c/flowlogs_reader/__main__.py#L50-L60 | train | 33,239 |
obsrvbl/flowlogs-reader | flowlogs_reader/__main__.py | action_findip | def action_findip(reader, *args):
"""Find Flow Log records involving a specific IP or IPs."""
target_ips = set(args)
for record in reader:
if (record.srcaddr in target_ips) or (record.dstaddr in target_ips):
print(record.to_message()) | python | def action_findip(reader, *args):
"""Find Flow Log records involving a specific IP or IPs."""
target_ips = set(args)
for record in reader:
if (record.srcaddr in target_ips) or (record.dstaddr in target_ips):
print(record.to_message()) | [
"def",
"action_findip",
"(",
"reader",
",",
"*",
"args",
")",
":",
"target_ips",
"=",
"set",
"(",
"args",
")",
"for",
"record",
"in",
"reader",
":",
"if",
"(",
"record",
".",
"srcaddr",
"in",
"target_ips",
")",
"or",
"(",
"record",
".",
"dstaddr",
"i... | Find Flow Log records involving a specific IP or IPs. | [
"Find",
"Flow",
"Log",
"records",
"involving",
"a",
"specific",
"IP",
"or",
"IPs",
"."
] | 248d8cb3cc586859b6744d30cebce0f359d9900c | https://github.com/obsrvbl/flowlogs-reader/blob/248d8cb3cc586859b6744d30cebce0f359d9900c/flowlogs_reader/__main__.py#L66-L71 | train | 33,240 |
obsrvbl/flowlogs-reader | flowlogs_reader/__main__.py | action_aggregate | def action_aggregate(reader, *args):
"""Aggregate flow records by 5-tuple and print a tab-separated stream"""
all_aggregated = aggregated_records(reader)
first_row = next(all_aggregated)
keys = sorted(first_row.keys())
print(*keys, sep='\t')
# Join the first row with the rest of the rows and print them
iterable = chain([first_row], all_aggregated)
for item in iterable:
print(*[item[k] for k in keys], sep='\t') | python | def action_aggregate(reader, *args):
"""Aggregate flow records by 5-tuple and print a tab-separated stream"""
all_aggregated = aggregated_records(reader)
first_row = next(all_aggregated)
keys = sorted(first_row.keys())
print(*keys, sep='\t')
# Join the first row with the rest of the rows and print them
iterable = chain([first_row], all_aggregated)
for item in iterable:
print(*[item[k] for k in keys], sep='\t') | [
"def",
"action_aggregate",
"(",
"reader",
",",
"*",
"args",
")",
":",
"all_aggregated",
"=",
"aggregated_records",
"(",
"reader",
")",
"first_row",
"=",
"next",
"(",
"all_aggregated",
")",
"keys",
"=",
"sorted",
"(",
"first_row",
".",
"keys",
"(",
")",
")"... | Aggregate flow records by 5-tuple and print a tab-separated stream | [
"Aggregate",
"flow",
"records",
"by",
"5",
"-",
"tuple",
"and",
"print",
"a",
"tab",
"-",
"separated",
"stream"
] | 248d8cb3cc586859b6744d30cebce0f359d9900c | https://github.com/obsrvbl/flowlogs-reader/blob/248d8cb3cc586859b6744d30cebce0f359d9900c/flowlogs_reader/__main__.py#L77-L87 | train | 33,241 |
erdc/RAPIDpy | RAPIDpy/gis/weight.py | get_poly_area_geo | def get_poly_area_geo(poly):
"""
Calculates the area in meters squared of the individual polygon
"""
minx, miny, maxx, maxy = poly.bounds
# reproject polygon to get area
reprojected_for_area = Proj("+proj=aea +lat_1={0} +lat_1={1} "
"+lat_0={2} +lon_0={3}"
.format(miny,
maxy,
(miny + maxy) / 2.0,
(minx + maxx) / 2.0))
geographic_proj = Proj(init='epsg:4326')
project_func = partial(transform,
geographic_proj,
reprojected_for_area)
reprojected_poly = shapely_transform(project_func, poly)
return reprojected_poly.area | python | def get_poly_area_geo(poly):
"""
Calculates the area in meters squared of the individual polygon
"""
minx, miny, maxx, maxy = poly.bounds
# reproject polygon to get area
reprojected_for_area = Proj("+proj=aea +lat_1={0} +lat_1={1} "
"+lat_0={2} +lon_0={3}"
.format(miny,
maxy,
(miny + maxy) / 2.0,
(minx + maxx) / 2.0))
geographic_proj = Proj(init='epsg:4326')
project_func = partial(transform,
geographic_proj,
reprojected_for_area)
reprojected_poly = shapely_transform(project_func, poly)
return reprojected_poly.area | [
"def",
"get_poly_area_geo",
"(",
"poly",
")",
":",
"minx",
",",
"miny",
",",
"maxx",
",",
"maxy",
"=",
"poly",
".",
"bounds",
"# reproject polygon to get area",
"reprojected_for_area",
"=",
"Proj",
"(",
"\"+proj=aea +lat_1={0} +lat_1={1} \"",
"\"+lat_0={2} +lon_0={3}\""... | Calculates the area in meters squared of the individual polygon | [
"Calculates",
"the",
"area",
"in",
"meters",
"squared",
"of",
"the",
"individual",
"polygon"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/weight.py#L30-L47 | train | 33,242 |
erdc/RAPIDpy | RAPIDpy/gis/weight.py | CreateWeightTableECMWF | def CreateWeightTableECMWF(in_ecmwf_nc,
in_catchment_shapefile,
river_id,
in_connectivity_file,
out_weight_table,
area_id=None,
file_geodatabase=None):
"""
Create Weight Table for ECMWF Grids
.. note:: The grids are in the RAPIDpy package under
the gis/lsm_grids folder.
Parameters
----------
in_ecmwf_nc: str
Path to the ECMWF NetCDF grid.
in_catchment_shapefile: str
Path to the Catchment shapefile.
river_id: str
The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').
in_connectivity_file: str
The path to the RAPID connectivity file.
out_weight_table: str
The path to the output weight table file.
area_id: str, optional
The name of the field with the area of each catchment stored in meters
squared. Default is it calculate the area.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option, in_drainage_line
is the name of the stream network feature class.
(WARNING: Not always stable with GDAL.)
Example:
.. code:: python
from RAPIDpy.gis.weight import CreateWeightTableECMWF
CreateWeightTableECMWF(
in_ecmwf_nc='/path/to/runoff_ecmwf_grid.nc'
in_catchment_shapefile='/path/to/catchment.shp',
river_id='LINKNO',
in_connectivity_file='/path/to/rapid_connect.csv',
out_weight_table='/path/to/ecmwf_weight.csv',
)
"""
# extract ECMWF GRID
data_ecmwf_nc = Dataset(in_ecmwf_nc)
variables_list = data_ecmwf_nc.variables.keys()
in_ecmwf_lat_var = 'lat'
if 'latitude' in variables_list:
in_ecmwf_lat_var = 'latitude'
in_ecmwf_lon_var = 'lon'
if 'longitude' in variables_list:
in_ecmwf_lon_var = 'longitude'
# convert [0, 360] to [-180, 180]
ecmwf_lon = \
(data_ecmwf_nc.variables[in_ecmwf_lon_var][:] + 180) % 360 - 180
# assume [-90, 90]
ecmwf_lat = data_ecmwf_nc.variables[in_ecmwf_lat_var][:]
data_ecmwf_nc.close()
rtree_create_weight_table(ecmwf_lat, ecmwf_lon,
in_catchment_shapefile, river_id,
in_connectivity_file, out_weight_table,
file_geodatabase, area_id) | python | def CreateWeightTableECMWF(in_ecmwf_nc,
in_catchment_shapefile,
river_id,
in_connectivity_file,
out_weight_table,
area_id=None,
file_geodatabase=None):
"""
Create Weight Table for ECMWF Grids
.. note:: The grids are in the RAPIDpy package under
the gis/lsm_grids folder.
Parameters
----------
in_ecmwf_nc: str
Path to the ECMWF NetCDF grid.
in_catchment_shapefile: str
Path to the Catchment shapefile.
river_id: str
The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').
in_connectivity_file: str
The path to the RAPID connectivity file.
out_weight_table: str
The path to the output weight table file.
area_id: str, optional
The name of the field with the area of each catchment stored in meters
squared. Default is it calculate the area.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option, in_drainage_line
is the name of the stream network feature class.
(WARNING: Not always stable with GDAL.)
Example:
.. code:: python
from RAPIDpy.gis.weight import CreateWeightTableECMWF
CreateWeightTableECMWF(
in_ecmwf_nc='/path/to/runoff_ecmwf_grid.nc'
in_catchment_shapefile='/path/to/catchment.shp',
river_id='LINKNO',
in_connectivity_file='/path/to/rapid_connect.csv',
out_weight_table='/path/to/ecmwf_weight.csv',
)
"""
# extract ECMWF GRID
data_ecmwf_nc = Dataset(in_ecmwf_nc)
variables_list = data_ecmwf_nc.variables.keys()
in_ecmwf_lat_var = 'lat'
if 'latitude' in variables_list:
in_ecmwf_lat_var = 'latitude'
in_ecmwf_lon_var = 'lon'
if 'longitude' in variables_list:
in_ecmwf_lon_var = 'longitude'
# convert [0, 360] to [-180, 180]
ecmwf_lon = \
(data_ecmwf_nc.variables[in_ecmwf_lon_var][:] + 180) % 360 - 180
# assume [-90, 90]
ecmwf_lat = data_ecmwf_nc.variables[in_ecmwf_lat_var][:]
data_ecmwf_nc.close()
rtree_create_weight_table(ecmwf_lat, ecmwf_lon,
in_catchment_shapefile, river_id,
in_connectivity_file, out_weight_table,
file_geodatabase, area_id) | [
"def",
"CreateWeightTableECMWF",
"(",
"in_ecmwf_nc",
",",
"in_catchment_shapefile",
",",
"river_id",
",",
"in_connectivity_file",
",",
"out_weight_table",
",",
"area_id",
"=",
"None",
",",
"file_geodatabase",
"=",
"None",
")",
":",
"# extract ECMWF GRID",
"data_ecmwf_nc... | Create Weight Table for ECMWF Grids
.. note:: The grids are in the RAPIDpy package under
the gis/lsm_grids folder.
Parameters
----------
in_ecmwf_nc: str
Path to the ECMWF NetCDF grid.
in_catchment_shapefile: str
Path to the Catchment shapefile.
river_id: str
The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').
in_connectivity_file: str
The path to the RAPID connectivity file.
out_weight_table: str
The path to the output weight table file.
area_id: str, optional
The name of the field with the area of each catchment stored in meters
squared. Default is it calculate the area.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option, in_drainage_line
is the name of the stream network feature class.
(WARNING: Not always stable with GDAL.)
Example:
.. code:: python
from RAPIDpy.gis.weight import CreateWeightTableECMWF
CreateWeightTableECMWF(
in_ecmwf_nc='/path/to/runoff_ecmwf_grid.nc'
in_catchment_shapefile='/path/to/catchment.shp',
river_id='LINKNO',
in_connectivity_file='/path/to/rapid_connect.csv',
out_weight_table='/path/to/ecmwf_weight.csv',
) | [
"Create",
"Weight",
"Table",
"for",
"ECMWF",
"Grids"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/weight.py#L277-L346 | train | 33,243 |
erdc/RAPIDpy | RAPIDpy/gis/weight.py | CreateWeightTableLDAS | def CreateWeightTableLDAS(in_ldas_nc,
in_nc_lon_var,
in_nc_lat_var,
in_catchment_shapefile,
river_id,
in_connectivity_file,
out_weight_table,
area_id=None,
file_geodatabase=None):
"""
Create Weight Table for NLDAS, GLDAS grids as well as for 2D Joules,
or LIS Grids
Parameters
----------
in_ldas_nc: str
Path to the land surface model NetCDF grid.
in_nc_lon_var: str
The variable name in the NetCDF file for the longitude.
in_nc_lat_var: str
The variable name in the NetCDF file for the latitude.
in_catchment_shapefile: str
Path to the Catchment shapefile.
river_id: str
The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').
in_connectivity_file: str
The path to the RAPID connectivity file.
out_weight_table: str
The path to the output weight table file.
area_id: str, optional
The name of the field with the area of each catchment stored in meters
squared. Default is it calculate the area.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option, in_drainage_line
is the name of the stream network feature class.
(WARNING: Not always stable with GDAL.)
Example:
.. code:: python
from RAPIDpy.gis.weight import CreateWeightTableLDAS
CreateWeightTableLDAS(
in_ldas_nc='/path/to/runoff_grid.nc',
in_nc_lon_var="lon_110",
in_nc_lat_var="lat_110",
in_catchment_shapefile='/path/to/catchment.shp',
river_id='LINKNO',
in_connectivity_file='/path/to/rapid_connect.csv',
out_weight_table='/path/to/ldas_weight.csv',
)
"""
# extract LDAS GRID
data_ldas_nc = Dataset(in_ldas_nc)
variables_list = data_ldas_nc.variables.keys()
if in_nc_lon_var not in variables_list:
raise Exception("Invalid longitude variable. Choose from: {0}"
.format(variables_list))
if in_nc_lat_var not in variables_list:
raise Exception("Invalid latitude variable. Choose from: {0}"
.format(variables_list))
ldas_lon = data_ldas_nc.variables[in_nc_lon_var][:] # assume [-180, 180]
ldas_lat = data_ldas_nc.variables[in_nc_lat_var][:] # assume [-90,90]
data_ldas_nc.close()
rtree_create_weight_table(ldas_lat, ldas_lon,
in_catchment_shapefile, river_id,
in_connectivity_file, out_weight_table,
file_geodatabase, area_id) | python | def CreateWeightTableLDAS(in_ldas_nc,
in_nc_lon_var,
in_nc_lat_var,
in_catchment_shapefile,
river_id,
in_connectivity_file,
out_weight_table,
area_id=None,
file_geodatabase=None):
"""
Create Weight Table for NLDAS, GLDAS grids as well as for 2D Joules,
or LIS Grids
Parameters
----------
in_ldas_nc: str
Path to the land surface model NetCDF grid.
in_nc_lon_var: str
The variable name in the NetCDF file for the longitude.
in_nc_lat_var: str
The variable name in the NetCDF file for the latitude.
in_catchment_shapefile: str
Path to the Catchment shapefile.
river_id: str
The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').
in_connectivity_file: str
The path to the RAPID connectivity file.
out_weight_table: str
The path to the output weight table file.
area_id: str, optional
The name of the field with the area of each catchment stored in meters
squared. Default is it calculate the area.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option, in_drainage_line
is the name of the stream network feature class.
(WARNING: Not always stable with GDAL.)
Example:
.. code:: python
from RAPIDpy.gis.weight import CreateWeightTableLDAS
CreateWeightTableLDAS(
in_ldas_nc='/path/to/runoff_grid.nc',
in_nc_lon_var="lon_110",
in_nc_lat_var="lat_110",
in_catchment_shapefile='/path/to/catchment.shp',
river_id='LINKNO',
in_connectivity_file='/path/to/rapid_connect.csv',
out_weight_table='/path/to/ldas_weight.csv',
)
"""
# extract LDAS GRID
data_ldas_nc = Dataset(in_ldas_nc)
variables_list = data_ldas_nc.variables.keys()
if in_nc_lon_var not in variables_list:
raise Exception("Invalid longitude variable. Choose from: {0}"
.format(variables_list))
if in_nc_lat_var not in variables_list:
raise Exception("Invalid latitude variable. Choose from: {0}"
.format(variables_list))
ldas_lon = data_ldas_nc.variables[in_nc_lon_var][:] # assume [-180, 180]
ldas_lat = data_ldas_nc.variables[in_nc_lat_var][:] # assume [-90,90]
data_ldas_nc.close()
rtree_create_weight_table(ldas_lat, ldas_lon,
in_catchment_shapefile, river_id,
in_connectivity_file, out_weight_table,
file_geodatabase, area_id) | [
"def",
"CreateWeightTableLDAS",
"(",
"in_ldas_nc",
",",
"in_nc_lon_var",
",",
"in_nc_lat_var",
",",
"in_catchment_shapefile",
",",
"river_id",
",",
"in_connectivity_file",
",",
"out_weight_table",
",",
"area_id",
"=",
"None",
",",
"file_geodatabase",
"=",
"None",
")",... | Create Weight Table for NLDAS, GLDAS grids as well as for 2D Joules,
or LIS Grids
Parameters
----------
in_ldas_nc: str
Path to the land surface model NetCDF grid.
in_nc_lon_var: str
The variable name in the NetCDF file for the longitude.
in_nc_lat_var: str
The variable name in the NetCDF file for the latitude.
in_catchment_shapefile: str
Path to the Catchment shapefile.
river_id: str
The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').
in_connectivity_file: str
The path to the RAPID connectivity file.
out_weight_table: str
The path to the output weight table file.
area_id: str, optional
The name of the field with the area of each catchment stored in meters
squared. Default is it calculate the area.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option, in_drainage_line
is the name of the stream network feature class.
(WARNING: Not always stable with GDAL.)
Example:
.. code:: python
from RAPIDpy.gis.weight import CreateWeightTableLDAS
CreateWeightTableLDAS(
in_ldas_nc='/path/to/runoff_grid.nc',
in_nc_lon_var="lon_110",
in_nc_lat_var="lat_110",
in_catchment_shapefile='/path/to/catchment.shp',
river_id='LINKNO',
in_connectivity_file='/path/to/rapid_connect.csv',
out_weight_table='/path/to/ldas_weight.csv',
) | [
"Create",
"Weight",
"Table",
"for",
"NLDAS",
"GLDAS",
"grids",
"as",
"well",
"as",
"for",
"2D",
"Joules",
"or",
"LIS",
"Grids"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/weight.py#L349-L419 | train | 33,244 |
erdc/RAPIDpy | RAPIDpy/postprocess/generate_seasonal_averages.py | generate_single_seasonal_average | def generate_single_seasonal_average(args):
"""
This function calculates the seasonal average for a single day of the year
for all river segments
"""
qout_file = args[0]
seasonal_average_file = args[1]
day_of_year = args[2]
mp_lock = args[3]
min_day = day_of_year - 3
max_day = day_of_year + 3
with RAPIDDataset(qout_file) as qout_nc_file:
time_indices = []
for idx, t in enumerate(qout_nc_file.get_time_array()):
var_time = gmtime(t)
compare_yday = var_time.tm_yday
# move day back one past because of leap year adds
# a day after feb 29 (day 60)
if isleap(var_time.tm_year) and compare_yday > 60:
compare_yday -= 1
# check if date within range of season
if max_day > compare_yday >= min_day:
time_indices.append(idx)
if not time_indices:
raise IndexError("No time steps found within range ...")
streamflow_array = qout_nc_file.get_qout(time_index_array=time_indices)
avg_streamflow_array = np.mean(streamflow_array, axis=1)
std_streamflow_array = np.std(streamflow_array, axis=1)
max_streamflow_array = np.amax(streamflow_array, axis=1)
min_streamflow_array = np.min(streamflow_array, axis=1)
mp_lock.acquire()
seasonal_avg_nc = Dataset(seasonal_average_file, 'a')
seasonal_avg_nc.variables['average_flow'][:, day_of_year-1] = \
avg_streamflow_array
seasonal_avg_nc.variables['std_dev_flow'][:, day_of_year-1] = \
std_streamflow_array
seasonal_avg_nc.variables['max_flow'][:, day_of_year-1] = \
max_streamflow_array
seasonal_avg_nc.variables['min_flow'][:, day_of_year-1] = \
min_streamflow_array
seasonal_avg_nc.close()
mp_lock.release() | python | def generate_single_seasonal_average(args):
"""
This function calculates the seasonal average for a single day of the year
for all river segments
"""
qout_file = args[0]
seasonal_average_file = args[1]
day_of_year = args[2]
mp_lock = args[3]
min_day = day_of_year - 3
max_day = day_of_year + 3
with RAPIDDataset(qout_file) as qout_nc_file:
time_indices = []
for idx, t in enumerate(qout_nc_file.get_time_array()):
var_time = gmtime(t)
compare_yday = var_time.tm_yday
# move day back one past because of leap year adds
# a day after feb 29 (day 60)
if isleap(var_time.tm_year) and compare_yday > 60:
compare_yday -= 1
# check if date within range of season
if max_day > compare_yday >= min_day:
time_indices.append(idx)
if not time_indices:
raise IndexError("No time steps found within range ...")
streamflow_array = qout_nc_file.get_qout(time_index_array=time_indices)
avg_streamflow_array = np.mean(streamflow_array, axis=1)
std_streamflow_array = np.std(streamflow_array, axis=1)
max_streamflow_array = np.amax(streamflow_array, axis=1)
min_streamflow_array = np.min(streamflow_array, axis=1)
mp_lock.acquire()
seasonal_avg_nc = Dataset(seasonal_average_file, 'a')
seasonal_avg_nc.variables['average_flow'][:, day_of_year-1] = \
avg_streamflow_array
seasonal_avg_nc.variables['std_dev_flow'][:, day_of_year-1] = \
std_streamflow_array
seasonal_avg_nc.variables['max_flow'][:, day_of_year-1] = \
max_streamflow_array
seasonal_avg_nc.variables['min_flow'][:, day_of_year-1] = \
min_streamflow_array
seasonal_avg_nc.close()
mp_lock.release() | [
"def",
"generate_single_seasonal_average",
"(",
"args",
")",
":",
"qout_file",
"=",
"args",
"[",
"0",
"]",
"seasonal_average_file",
"=",
"args",
"[",
"1",
"]",
"day_of_year",
"=",
"args",
"[",
"2",
"]",
"mp_lock",
"=",
"args",
"[",
"3",
"]",
"min_day",
"... | This function calculates the seasonal average for a single day of the year
for all river segments | [
"This",
"function",
"calculates",
"the",
"seasonal",
"average",
"for",
"a",
"single",
"day",
"of",
"the",
"year",
"for",
"all",
"river",
"segments"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/postprocess/generate_seasonal_averages.py#L20-L67 | train | 33,245 |
erdc/RAPIDpy | RAPIDpy/postprocess/generate_seasonal_averages.py | generate_seasonal_averages | def generate_seasonal_averages(qout_file, seasonal_average_file,
num_cpus=multiprocessing.cpu_count()):
"""
This function loops through a CF compliant rapid streamflow
file to produce a netCDF file with a seasonal average for
365 days a year
"""
with RAPIDDataset(qout_file) as qout_nc_file:
print("Generating seasonal average file ...")
seasonal_avg_nc = Dataset(seasonal_average_file, 'w')
seasonal_avg_nc.createDimension('rivid', qout_nc_file.size_river_id)
seasonal_avg_nc.createDimension('day_of_year', 365)
time_series_var = seasonal_avg_nc.createVariable('rivid', 'i4',
('rivid',))
time_series_var.long_name = (
'unique identifier for each river reach')
average_flow_var = \
seasonal_avg_nc.createVariable('average_flow', 'f8',
('rivid', 'day_of_year'))
average_flow_var.long_name = 'seasonal average streamflow'
average_flow_var.units = 'm3/s'
std_dev_flow_var = \
seasonal_avg_nc.createVariable('std_dev_flow', 'f8',
('rivid', 'day_of_year'))
std_dev_flow_var.long_name = 'seasonal std. dev. streamflow'
std_dev_flow_var.units = 'm3/s'
std_dev_flow_var = \
seasonal_avg_nc.createVariable('max_flow', 'f8',
('rivid', 'day_of_year'))
std_dev_flow_var.long_name = 'seasonal max streamflow'
std_dev_flow_var.units = 'm3/s'
std_dev_flow_var = \
seasonal_avg_nc.createVariable('min_flow', 'f8',
('rivid', 'day_of_year'))
std_dev_flow_var.long_name = 'seasonal min streamflow'
std_dev_flow_var.units = 'm3/s'
lat_var = seasonal_avg_nc.createVariable('lat', 'f8', ('rivid',),
fill_value=-9999.0)
lon_var = seasonal_avg_nc.createVariable('lon', 'f8', ('rivid',),
fill_value=-9999.0)
add_latlon_metadata(lat_var, lon_var)
seasonal_avg_nc.variables['lat'][:] = \
qout_nc_file.qout_nc.variables['lat'][:]
seasonal_avg_nc.variables['lon'][:] = \
qout_nc_file.qout_nc.variables['lon'][:]
river_id_list = qout_nc_file.get_river_id_array()
seasonal_avg_nc.variables['rivid'][:] = river_id_list
seasonal_avg_nc.close()
# generate multiprocessing jobs
mp_lock = multiprocessing.Manager().Lock() # pylint: disable=no-member
job_combinations = []
for day_of_year in range(1, 366):
job_combinations.append((qout_file,
seasonal_average_file,
day_of_year,
mp_lock
))
pool = multiprocessing.Pool(num_cpus)
pool.map(generate_single_seasonal_average,
job_combinations)
pool.close()
pool.join() | python | def generate_seasonal_averages(qout_file, seasonal_average_file,
num_cpus=multiprocessing.cpu_count()):
"""
This function loops through a CF compliant rapid streamflow
file to produce a netCDF file with a seasonal average for
365 days a year
"""
with RAPIDDataset(qout_file) as qout_nc_file:
print("Generating seasonal average file ...")
seasonal_avg_nc = Dataset(seasonal_average_file, 'w')
seasonal_avg_nc.createDimension('rivid', qout_nc_file.size_river_id)
seasonal_avg_nc.createDimension('day_of_year', 365)
time_series_var = seasonal_avg_nc.createVariable('rivid', 'i4',
('rivid',))
time_series_var.long_name = (
'unique identifier for each river reach')
average_flow_var = \
seasonal_avg_nc.createVariable('average_flow', 'f8',
('rivid', 'day_of_year'))
average_flow_var.long_name = 'seasonal average streamflow'
average_flow_var.units = 'm3/s'
std_dev_flow_var = \
seasonal_avg_nc.createVariable('std_dev_flow', 'f8',
('rivid', 'day_of_year'))
std_dev_flow_var.long_name = 'seasonal std. dev. streamflow'
std_dev_flow_var.units = 'm3/s'
std_dev_flow_var = \
seasonal_avg_nc.createVariable('max_flow', 'f8',
('rivid', 'day_of_year'))
std_dev_flow_var.long_name = 'seasonal max streamflow'
std_dev_flow_var.units = 'm3/s'
std_dev_flow_var = \
seasonal_avg_nc.createVariable('min_flow', 'f8',
('rivid', 'day_of_year'))
std_dev_flow_var.long_name = 'seasonal min streamflow'
std_dev_flow_var.units = 'm3/s'
lat_var = seasonal_avg_nc.createVariable('lat', 'f8', ('rivid',),
fill_value=-9999.0)
lon_var = seasonal_avg_nc.createVariable('lon', 'f8', ('rivid',),
fill_value=-9999.0)
add_latlon_metadata(lat_var, lon_var)
seasonal_avg_nc.variables['lat'][:] = \
qout_nc_file.qout_nc.variables['lat'][:]
seasonal_avg_nc.variables['lon'][:] = \
qout_nc_file.qout_nc.variables['lon'][:]
river_id_list = qout_nc_file.get_river_id_array()
seasonal_avg_nc.variables['rivid'][:] = river_id_list
seasonal_avg_nc.close()
# generate multiprocessing jobs
mp_lock = multiprocessing.Manager().Lock() # pylint: disable=no-member
job_combinations = []
for day_of_year in range(1, 366):
job_combinations.append((qout_file,
seasonal_average_file,
day_of_year,
mp_lock
))
pool = multiprocessing.Pool(num_cpus)
pool.map(generate_single_seasonal_average,
job_combinations)
pool.close()
pool.join() | [
"def",
"generate_seasonal_averages",
"(",
"qout_file",
",",
"seasonal_average_file",
",",
"num_cpus",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
")",
":",
"with",
"RAPIDDataset",
"(",
"qout_file",
")",
"as",
"qout_nc_file",
":",
"print",
"(",
"\"Generatin... | This function loops through a CF compliant rapid streamflow
file to produce a netCDF file with a seasonal average for
365 days a year | [
"This",
"function",
"loops",
"through",
"a",
"CF",
"compliant",
"rapid",
"streamflow",
"file",
"to",
"produce",
"a",
"netCDF",
"file",
"with",
"a",
"seasonal",
"average",
"for",
"365",
"days",
"a",
"year"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/postprocess/generate_seasonal_averages.py#L70-L143 | train | 33,246 |
erdc/RAPIDpy | RAPIDpy/gis/__init__.py | open_shapefile | def open_shapefile(shapefile_path, file_geodatabase=None):
"""Opens a shapefile using either a shapefile path
or a file geodatabase
"""
if file_geodatabase:
gdb_driver = ogr.GetDriverByName("OpenFileGDB")
ogr_shapefile = gdb_driver.Open(file_geodatabase)
ogr_shapefile_lyr = ogr_shapefile.GetLayer(shapefile_path)
else:
ogr_shapefile = ogr.Open(shapefile_path)
ogr_shapefile_lyr = ogr_shapefile.GetLayer()
return ogr_shapefile_lyr, ogr_shapefile | python | def open_shapefile(shapefile_path, file_geodatabase=None):
"""Opens a shapefile using either a shapefile path
or a file geodatabase
"""
if file_geodatabase:
gdb_driver = ogr.GetDriverByName("OpenFileGDB")
ogr_shapefile = gdb_driver.Open(file_geodatabase)
ogr_shapefile_lyr = ogr_shapefile.GetLayer(shapefile_path)
else:
ogr_shapefile = ogr.Open(shapefile_path)
ogr_shapefile_lyr = ogr_shapefile.GetLayer()
return ogr_shapefile_lyr, ogr_shapefile | [
"def",
"open_shapefile",
"(",
"shapefile_path",
",",
"file_geodatabase",
"=",
"None",
")",
":",
"if",
"file_geodatabase",
":",
"gdb_driver",
"=",
"ogr",
".",
"GetDriverByName",
"(",
"\"OpenFileGDB\"",
")",
"ogr_shapefile",
"=",
"gdb_driver",
".",
"Open",
"(",
"f... | Opens a shapefile using either a shapefile path
or a file geodatabase | [
"Opens",
"a",
"shapefile",
"using",
"either",
"a",
"shapefile",
"path",
"or",
"a",
"file",
"geodatabase"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/__init__.py#L12-L23 | train | 33,247 |
erdc/RAPIDpy | RAPIDpy/rapid.py | RAPID._get_cygwin_path | def _get_cygwin_path(self, windows_path):
"""
Convert windows path to cygpath
"""
conv_cmd = [os.path.join(self._cygwin_bin_location, "cygpath.exe"),
"-u", windows_path]
process = Popen(conv_cmd,
stdout=PIPE, stderr=PIPE, shell=False)
out, err = process.communicate()
if err:
print(err)
raise Exception(err)
return out.strip() | python | def _get_cygwin_path(self, windows_path):
"""
Convert windows path to cygpath
"""
conv_cmd = [os.path.join(self._cygwin_bin_location, "cygpath.exe"),
"-u", windows_path]
process = Popen(conv_cmd,
stdout=PIPE, stderr=PIPE, shell=False)
out, err = process.communicate()
if err:
print(err)
raise Exception(err)
return out.strip() | [
"def",
"_get_cygwin_path",
"(",
"self",
",",
"windows_path",
")",
":",
"conv_cmd",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_cygwin_bin_location",
",",
"\"cygpath.exe\"",
")",
",",
"\"-u\"",
",",
"windows_path",
"]",
"process",
"=",
"Po... | Convert windows path to cygpath | [
"Convert",
"windows",
"path",
"to",
"cygpath"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/rapid.py#L255-L268 | train | 33,248 |
erdc/RAPIDpy | RAPIDpy/rapid.py | RAPID._create_symlink_cygwin | def _create_symlink_cygwin(self, initial_path, final_path):
"""
Use cygqin to generate symbolic link
"""
symlink_cmd = [os.path.join(self._cygwin_bin_location, "ln.exe"),
"-s", self._get_cygwin_path(initial_path),
self._get_cygwin_path(final_path)]
process = Popen(symlink_cmd,
stdout=PIPE, stderr=PIPE, shell=False)
out, err = process.communicate()
if err:
print(err)
raise Exception(err)
return out.strip() | python | def _create_symlink_cygwin(self, initial_path, final_path):
"""
Use cygqin to generate symbolic link
"""
symlink_cmd = [os.path.join(self._cygwin_bin_location, "ln.exe"),
"-s", self._get_cygwin_path(initial_path),
self._get_cygwin_path(final_path)]
process = Popen(symlink_cmd,
stdout=PIPE, stderr=PIPE, shell=False)
out, err = process.communicate()
if err:
print(err)
raise Exception(err)
return out.strip() | [
"def",
"_create_symlink_cygwin",
"(",
"self",
",",
"initial_path",
",",
"final_path",
")",
":",
"symlink_cmd",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_cygwin_bin_location",
",",
"\"ln.exe\"",
")",
",",
"\"-s\"",
",",
"self",
".",
"_ge... | Use cygqin to generate symbolic link | [
"Use",
"cygqin",
"to",
"generate",
"symbolic",
"link"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/rapid.py#L270-L284 | train | 33,249 |
erdc/RAPIDpy | RAPIDpy/rapid.py | RAPID._dos2unix_cygwin | def _dos2unix_cygwin(self, file_path):
"""
Use cygwin to convert file to unix format
"""
dos2unix_cmd = \
[os.path.join(self._cygwin_bin_location, "dos2unix.exe"),
self._get_cygwin_path(file_path)]
process = Popen(dos2unix_cmd,
stdout=PIPE, stderr=PIPE, shell=False)
process.communicate() | python | def _dos2unix_cygwin(self, file_path):
"""
Use cygwin to convert file to unix format
"""
dos2unix_cmd = \
[os.path.join(self._cygwin_bin_location, "dos2unix.exe"),
self._get_cygwin_path(file_path)]
process = Popen(dos2unix_cmd,
stdout=PIPE, stderr=PIPE, shell=False)
process.communicate() | [
"def",
"_dos2unix_cygwin",
"(",
"self",
",",
"file_path",
")",
":",
"dos2unix_cmd",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_cygwin_bin_location",
",",
"\"dos2unix.exe\"",
")",
",",
"self",
".",
"_get_cygwin_path",
"(",
"file_path",
")",... | Use cygwin to convert file to unix format | [
"Use",
"cygwin",
"to",
"convert",
"file",
"to",
"unix",
"format"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/rapid.py#L286-L295 | train | 33,250 |
erdc/RAPIDpy | RAPIDpy/rapid.py | RAPID.update_reach_number_data | def update_reach_number_data(self):
"""
Update the reach number data for the namelist based on input files.
.. warning:: You need to make sure you set *rapid_connect_file*
and *riv_bas_id_file* before running this function.
Example:
.. code:: python
from RAPIDpy import RAPID
rapid_manager = RAPID(
rapid_connect_file='../rapid-io/input/rapid_connect.csv',
riv_bas_id_file='../rapid-io/input/riv_bas_id.csv',
)
rapid_manager.update_reach_number_data()
Example with forcing data:
.. code:: python
from RAPIDpy import RAPID
rapid_manager = RAPID(
rapid_connect_file='../rapid-io/input/rapid_connect.csv',
riv_bas_id_file='../rapid-io/input/riv_bas_id.csv',
Qfor_file='../rapid-io/input/qfor_file.csv',
for_tot_id_file='../rapid-io/input/for_tot_id_file.csv',
for_use_id_file='../rapid-io/input/for_use_id_file.csv',
ZS_dtF=3*60*60,
BS_opt_for=True
)
rapid_manager.update_reach_number_data()
"""
if not self.rapid_connect_file:
log("Missing rapid_connect_file. "
"Please set before running this function ...",
"ERROR")
if not self.riv_bas_id_file:
log("Missing riv_bas_id_file. "
"Please set before running this function ...",
"ERROR")
# get rapid connect info
rapid_connect_table = np.loadtxt(self.rapid_connect_file,
ndmin=2, delimiter=",", dtype=int)
self.IS_riv_tot = int(rapid_connect_table.shape[0])
self.IS_max_up = int(rapid_connect_table[:, 2].max())
# get riv_bas_id info
riv_bas_id_table = np.loadtxt(self.riv_bas_id_file,
ndmin=1, delimiter=",",
usecols=(0,), dtype=int)
self.IS_riv_bas = int(riv_bas_id_table.size)
# add the forcing files
if not self.for_tot_id_file:
self.IS_for_tot = 0
log("Missing for_tot_id_file. Skipping ...",
"WARNING")
else:
# get riv_bas_id info
for_tot_id_table = np.loadtxt(self.for_tot_id_file,
ndmin=1, delimiter=",",
usecols=(0,), dtype=int)
self.IS_for_tot = int(for_tot_id_table.size)
if not self.for_use_id_file:
self.IS_for_use = 0
log("Missing for_use_id_file. Skipping ...",
"WARNING")
else:
# get riv_bas_id info
for_use_id_table = np.loadtxt(self.for_use_id_file,
ndmin=1, delimiter=",",
usecols=(0,), dtype=int)
self.IS_for_use = int(for_use_id_table.size) | python | def update_reach_number_data(self):
"""
Update the reach number data for the namelist based on input files.
.. warning:: You need to make sure you set *rapid_connect_file*
and *riv_bas_id_file* before running this function.
Example:
.. code:: python
from RAPIDpy import RAPID
rapid_manager = RAPID(
rapid_connect_file='../rapid-io/input/rapid_connect.csv',
riv_bas_id_file='../rapid-io/input/riv_bas_id.csv',
)
rapid_manager.update_reach_number_data()
Example with forcing data:
.. code:: python
from RAPIDpy import RAPID
rapid_manager = RAPID(
rapid_connect_file='../rapid-io/input/rapid_connect.csv',
riv_bas_id_file='../rapid-io/input/riv_bas_id.csv',
Qfor_file='../rapid-io/input/qfor_file.csv',
for_tot_id_file='../rapid-io/input/for_tot_id_file.csv',
for_use_id_file='../rapid-io/input/for_use_id_file.csv',
ZS_dtF=3*60*60,
BS_opt_for=True
)
rapid_manager.update_reach_number_data()
"""
if not self.rapid_connect_file:
log("Missing rapid_connect_file. "
"Please set before running this function ...",
"ERROR")
if not self.riv_bas_id_file:
log("Missing riv_bas_id_file. "
"Please set before running this function ...",
"ERROR")
# get rapid connect info
rapid_connect_table = np.loadtxt(self.rapid_connect_file,
ndmin=2, delimiter=",", dtype=int)
self.IS_riv_tot = int(rapid_connect_table.shape[0])
self.IS_max_up = int(rapid_connect_table[:, 2].max())
# get riv_bas_id info
riv_bas_id_table = np.loadtxt(self.riv_bas_id_file,
ndmin=1, delimiter=",",
usecols=(0,), dtype=int)
self.IS_riv_bas = int(riv_bas_id_table.size)
# add the forcing files
if not self.for_tot_id_file:
self.IS_for_tot = 0
log("Missing for_tot_id_file. Skipping ...",
"WARNING")
else:
# get riv_bas_id info
for_tot_id_table = np.loadtxt(self.for_tot_id_file,
ndmin=1, delimiter=",",
usecols=(0,), dtype=int)
self.IS_for_tot = int(for_tot_id_table.size)
if not self.for_use_id_file:
self.IS_for_use = 0
log("Missing for_use_id_file. Skipping ...",
"WARNING")
else:
# get riv_bas_id info
for_use_id_table = np.loadtxt(self.for_use_id_file,
ndmin=1, delimiter=",",
usecols=(0,), dtype=int)
self.IS_for_use = int(for_use_id_table.size) | [
"def",
"update_reach_number_data",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"rapid_connect_file",
":",
"log",
"(",
"\"Missing rapid_connect_file. \"",
"\"Please set before running this function ...\"",
",",
"\"ERROR\"",
")",
"if",
"not",
"self",
".",
"riv_bas_id... | Update the reach number data for the namelist based on input files.
.. warning:: You need to make sure you set *rapid_connect_file*
and *riv_bas_id_file* before running this function.
Example:
.. code:: python
from RAPIDpy import RAPID
rapid_manager = RAPID(
rapid_connect_file='../rapid-io/input/rapid_connect.csv',
riv_bas_id_file='../rapid-io/input/riv_bas_id.csv',
)
rapid_manager.update_reach_number_data()
Example with forcing data:
.. code:: python
from RAPIDpy import RAPID
rapid_manager = RAPID(
rapid_connect_file='../rapid-io/input/rapid_connect.csv',
riv_bas_id_file='../rapid-io/input/riv_bas_id.csv',
Qfor_file='../rapid-io/input/qfor_file.csv',
for_tot_id_file='../rapid-io/input/for_tot_id_file.csv',
for_use_id_file='../rapid-io/input/for_use_id_file.csv',
ZS_dtF=3*60*60,
BS_opt_for=True
)
rapid_manager.update_reach_number_data() | [
"Update",
"the",
"reach",
"number",
"data",
"for",
"the",
"namelist",
"based",
"on",
"input",
"files",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/rapid.py#L342-L427 | train | 33,251 |
erdc/RAPIDpy | RAPIDpy/rapid.py | RAPID.generate_namelist_file | def generate_namelist_file(self, rapid_namelist_file):
"""
Generate rapid_namelist file.
Parameters
----------
rapid_namelist_file: str
Path of namelist file to generate from
parameters added to the RAPID manager.
"""
log("Generating RAPID namelist file ...",
"INFO")
try:
os.remove(rapid_namelist_file)
except OSError:
pass
with open(rapid_namelist_file, 'w') as new_file:
new_file.write('&NL_namelist\n')
for attr, value in sorted(list(self.__dict__.items())):
if not attr.startswith('_'):
if attr.startswith('BS'):
new_file.write("{0} = .{1}.\n"
.format(attr, str(value).lower()))
elif isinstance(value, int):
new_file.write("%s = %s\n" % (attr, value))
else:
if value:
if os.name == "nt":
# if windows generate file with cygpath
value = self._get_cygwin_path(value)
new_file.write("%s = \'%s\'\n" % (attr, value))
new_file.write("/\n") | python | def generate_namelist_file(self, rapid_namelist_file):
"""
Generate rapid_namelist file.
Parameters
----------
rapid_namelist_file: str
Path of namelist file to generate from
parameters added to the RAPID manager.
"""
log("Generating RAPID namelist file ...",
"INFO")
try:
os.remove(rapid_namelist_file)
except OSError:
pass
with open(rapid_namelist_file, 'w') as new_file:
new_file.write('&NL_namelist\n')
for attr, value in sorted(list(self.__dict__.items())):
if not attr.startswith('_'):
if attr.startswith('BS'):
new_file.write("{0} = .{1}.\n"
.format(attr, str(value).lower()))
elif isinstance(value, int):
new_file.write("%s = %s\n" % (attr, value))
else:
if value:
if os.name == "nt":
# if windows generate file with cygpath
value = self._get_cygwin_path(value)
new_file.write("%s = \'%s\'\n" % (attr, value))
new_file.write("/\n") | [
"def",
"generate_namelist_file",
"(",
"self",
",",
"rapid_namelist_file",
")",
":",
"log",
"(",
"\"Generating RAPID namelist file ...\"",
",",
"\"INFO\"",
")",
"try",
":",
"os",
".",
"remove",
"(",
"rapid_namelist_file",
")",
"except",
"OSError",
":",
"pass",
"wit... | Generate rapid_namelist file.
Parameters
----------
rapid_namelist_file: str
Path of namelist file to generate from
parameters added to the RAPID manager. | [
"Generate",
"rapid_namelist",
"file",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/rapid.py#L469-L501 | train | 33,252 |
erdc/RAPIDpy | RAPIDpy/rapid.py | RAPID.update_namelist_file | def update_namelist_file(self, rapid_namelist_file,
new_namelist_file=None):
"""
Update existing namelist file with new parameters
Parameters
----------
rapid_namelist_file: str
Path of namelist file to use in the simulation. It will be
updated with any parameters added to the RAPID manager.
new_namelist_file: str, optional
Path to output the updated namelist file.
"""
if os.path.exists(rapid_namelist_file) and rapid_namelist_file:
log("Adding missing inputs from RAPID input file ...",
"INFO")
with open(rapid_namelist_file, 'r') as old_file:
for line in old_file:
line = line.strip()
if not line[:1].isalpha() or not line:
continue
line_split = line.split("=")
attr = line_split[0].strip()
value = None
if len(line_split) > 1:
value = line_split[1].strip()\
.replace("'", "").replace('"', "")
# convert integers to integers
try:
value = int(value)
except ValueError:
pass
# remove dots from beginning & end of value
if attr.startswith('BS'):
value = value.replace(".", "")
# add attribute if exists
if attr in dir(self) and not attr.startswith('_'):
# set attribute if not set already
if not getattr(self, attr):
setattr(self, attr, value)
else:
log("Invalid argument {0}. Skipping ...".format(attr),
"INFO")
if new_namelist_file is None:
new_namelist_file = rapid_namelist_file
self.generate_namelist_file(new_namelist_file)
else:
log("RAPID namelist file to update not found.",
"ERROR") | python | def update_namelist_file(self, rapid_namelist_file,
new_namelist_file=None):
"""
Update existing namelist file with new parameters
Parameters
----------
rapid_namelist_file: str
Path of namelist file to use in the simulation. It will be
updated with any parameters added to the RAPID manager.
new_namelist_file: str, optional
Path to output the updated namelist file.
"""
if os.path.exists(rapid_namelist_file) and rapid_namelist_file:
log("Adding missing inputs from RAPID input file ...",
"INFO")
with open(rapid_namelist_file, 'r') as old_file:
for line in old_file:
line = line.strip()
if not line[:1].isalpha() or not line:
continue
line_split = line.split("=")
attr = line_split[0].strip()
value = None
if len(line_split) > 1:
value = line_split[1].strip()\
.replace("'", "").replace('"', "")
# convert integers to integers
try:
value = int(value)
except ValueError:
pass
# remove dots from beginning & end of value
if attr.startswith('BS'):
value = value.replace(".", "")
# add attribute if exists
if attr in dir(self) and not attr.startswith('_'):
# set attribute if not set already
if not getattr(self, attr):
setattr(self, attr, value)
else:
log("Invalid argument {0}. Skipping ...".format(attr),
"INFO")
if new_namelist_file is None:
new_namelist_file = rapid_namelist_file
self.generate_namelist_file(new_namelist_file)
else:
log("RAPID namelist file to update not found.",
"ERROR") | [
"def",
"update_namelist_file",
"(",
"self",
",",
"rapid_namelist_file",
",",
"new_namelist_file",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"rapid_namelist_file",
")",
"and",
"rapid_namelist_file",
":",
"log",
"(",
"\"Adding missing input... | Update existing namelist file with new parameters
Parameters
----------
rapid_namelist_file: str
Path of namelist file to use in the simulation. It will be
updated with any parameters added to the RAPID manager.
new_namelist_file: str, optional
Path to output the updated namelist file. | [
"Update",
"existing",
"namelist",
"file",
"with",
"new",
"parameters"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/rapid.py#L503-L553 | train | 33,253 |
erdc/RAPIDpy | RAPIDpy/rapid.py | RAPID.generate_qinit_from_past_qout | def generate_qinit_from_past_qout(self, qinit_file, time_index=-1,
out_datetime=None):
"""
Generate qinit from a RAPID qout file
Parameters
----------
qinit_file: str
Path to output qinit_file.
time_index: int, optional
Index of simulation to generate initial flow file.
Default is the last index.
out_datetime: :obj:`datetime.datetime`, optional
Datetime object containing time of initialization.
Example:
.. code:: python
from RAPIDpy import RAPID
rapid_manager = RAPID(
Qout_file='/output_mississippi-nfie/Qout_k2v1_2005to2009.nc',
rapid_connect_file='/input_mississippi_nfie/rapid_connect.csv'
)
rapid_manager.generate_qinit_from_past_qout(
qinit_file='/input_mississippi_nfie/Qinit_2008_flood.csv',
time_index=10162
)
"""
if not self.Qout_file or not os.path.exists(self.Qout_file):
log('Missing Qout_file. '
'Please set before running this function ...',
"ERROR")
if not self.rapid_connect_file or not self.rapid_connect_file:
log('Missing rapid_connect file. '
'Please set before running this function ...',
"ERROR")
log("Generating qinit file from qout file ...",
"INFO")
# get information from dataset
with xarray.open_dataset(self.Qout_file) as qds:
rivid_array = qds.rivid.values
if out_datetime is None:
streamflow_values = qds.isel(time=time_index).Qout.values
else:
streamflow_values = qds.sel(time=str(out_datetime)).Qout.values
log("Reordering data ...",
"INFO")
stream_id_array = np.loadtxt(self.rapid_connect_file,
ndmin=1, delimiter=",",
usecols=(0,), dtype=int)
init_flows_array = np.zeros(stream_id_array.size)
for riv_bas_index, riv_bas_id in enumerate(rivid_array):
try:
data_index = np.where(stream_id_array == riv_bas_id)[0][0]
init_flows_array[data_index] = streamflow_values[riv_bas_index]
except IndexError:
log('riv bas id {0} not found in connectivity list.'
.format(riv_bas_id),
"WARNING")
log("Writing to file ...",
"INFO")
with open_csv(qinit_file, 'w') as qinit_out:
for init_flow in init_flows_array:
qinit_out.write('{0}\n'.format(init_flow))
self.Qinit_file = qinit_file
self.BS_opt_Qinit = True
log("Initialization Complete!",
"INFO") | python | def generate_qinit_from_past_qout(self, qinit_file, time_index=-1,
out_datetime=None):
"""
Generate qinit from a RAPID qout file
Parameters
----------
qinit_file: str
Path to output qinit_file.
time_index: int, optional
Index of simulation to generate initial flow file.
Default is the last index.
out_datetime: :obj:`datetime.datetime`, optional
Datetime object containing time of initialization.
Example:
.. code:: python
from RAPIDpy import RAPID
rapid_manager = RAPID(
Qout_file='/output_mississippi-nfie/Qout_k2v1_2005to2009.nc',
rapid_connect_file='/input_mississippi_nfie/rapid_connect.csv'
)
rapid_manager.generate_qinit_from_past_qout(
qinit_file='/input_mississippi_nfie/Qinit_2008_flood.csv',
time_index=10162
)
"""
if not self.Qout_file or not os.path.exists(self.Qout_file):
log('Missing Qout_file. '
'Please set before running this function ...',
"ERROR")
if not self.rapid_connect_file or not self.rapid_connect_file:
log('Missing rapid_connect file. '
'Please set before running this function ...',
"ERROR")
log("Generating qinit file from qout file ...",
"INFO")
# get information from dataset
with xarray.open_dataset(self.Qout_file) as qds:
rivid_array = qds.rivid.values
if out_datetime is None:
streamflow_values = qds.isel(time=time_index).Qout.values
else:
streamflow_values = qds.sel(time=str(out_datetime)).Qout.values
log("Reordering data ...",
"INFO")
stream_id_array = np.loadtxt(self.rapid_connect_file,
ndmin=1, delimiter=",",
usecols=(0,), dtype=int)
init_flows_array = np.zeros(stream_id_array.size)
for riv_bas_index, riv_bas_id in enumerate(rivid_array):
try:
data_index = np.where(stream_id_array == riv_bas_id)[0][0]
init_flows_array[data_index] = streamflow_values[riv_bas_index]
except IndexError:
log('riv bas id {0} not found in connectivity list.'
.format(riv_bas_id),
"WARNING")
log("Writing to file ...",
"INFO")
with open_csv(qinit_file, 'w') as qinit_out:
for init_flow in init_flows_array:
qinit_out.write('{0}\n'.format(init_flow))
self.Qinit_file = qinit_file
self.BS_opt_Qinit = True
log("Initialization Complete!",
"INFO") | [
"def",
"generate_qinit_from_past_qout",
"(",
"self",
",",
"qinit_file",
",",
"time_index",
"=",
"-",
"1",
",",
"out_datetime",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"Qout_file",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
... | Generate qinit from a RAPID qout file
Parameters
----------
qinit_file: str
Path to output qinit_file.
time_index: int, optional
Index of simulation to generate initial flow file.
Default is the last index.
out_datetime: :obj:`datetime.datetime`, optional
Datetime object containing time of initialization.
Example:
.. code:: python
from RAPIDpy import RAPID
rapid_manager = RAPID(
Qout_file='/output_mississippi-nfie/Qout_k2v1_2005to2009.nc',
rapid_connect_file='/input_mississippi_nfie/rapid_connect.csv'
)
rapid_manager.generate_qinit_from_past_qout(
qinit_file='/input_mississippi_nfie/Qinit_2008_flood.csv',
time_index=10162
) | [
"Generate",
"qinit",
"from",
"a",
"RAPID",
"qout",
"file"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/rapid.py#L802-L880 | train | 33,254 |
erdc/RAPIDpy | RAPIDpy/rapid.py | RAPID.generate_seasonal_intitialization | def generate_seasonal_intitialization(
self,
qinit_file,
datetime_start_initialization=datetime.datetime.utcnow()
):
"""This creates a seasonal qinit file from a RAPID qout file. This
requires a simulation Qout file with a longer time period of record and
to be CF compliant. It takes the average of the current date +- 3 days
and goes back as far as possible.
Parameters
----------
qinit_file: str
Path to output qinit_file.
datetime_start_initialization: :obj:`datetime.datetime`, optional
Datetime object with date of simulation to go back through the
years and get a running average to generate streamflow
initialization. Default is utcnow.
Example:
.. code:: python
from RAPIDpy.rapid import RAPID
rapid_manager = RAPID(
Qout_file='/output_mississippi-nfie/Qout_2000to2015.nc',
rapid_connect_file='/input_mississippi_nfie/rapid_connect.csv'
)
rapid_manager.generate_seasonal_intitialization(
qinit_file='/input_mississippi_nfie/Qinit_seasonal_avg.csv'
)
"""
if not self.Qout_file or not os.path.exists(self.Qout_file):
log("Missing Qout_file. "
"Please set before running this function ...",
"ERROR")
if not self.rapid_connect_file or not self.rapid_connect_file:
log("Missing rapid_connect file. "
"Please set before running this function ...",
"ERROR")
day_of_year = datetime_start_initialization.timetuple().tm_yday
min_day = day_of_year - 3
max_day = day_of_year + 3
with RAPIDDataset(self.Qout_file) as qout_hist_nc:
if not qout_hist_nc.is_time_variable_valid():
log("File must be CF 1.6 compliant "
"with valid time variable ...",
"ERROR")
log("Generating seasonal average qinit file from qout file ...",
"INFO")
log("Determining dates with streamflows of interest ...",
"INFO")
time_indices = []
for idx, ttt in enumerate(qout_hist_nc.get_time_array()):
var_time = gmtime(ttt)
compare_yday = var_time.tm_yday
# move day back one past because of leap year adds
# a day after feb 29 (day 60)
if isleap(var_time.tm_year) and compare_yday > 60:
compare_yday -= 1
# check if date within range of season
if min_day <= compare_yday < max_day:
time_indices.append(idx)
if not time_indices:
log("No time steps found within range ...",
"ERROR")
log("Extracting data ...",
"INFO")
streamflow_array = \
qout_hist_nc.get_qout(time_index_array=time_indices)
log("Reordering data...",
"INFO")
stream_id_array = np.loadtxt(self.rapid_connect_file,
ndmin=1, delimiter=",",
usecols=(0,), dtype=int)
init_flows_array = np.zeros(stream_id_array.size)
for riv_bas_index, riv_bas_id in enumerate(
qout_hist_nc.get_river_id_array()):
try:
data_index = np.where(stream_id_array == riv_bas_id)[0][0]
init_flows_array[data_index] = \
np.mean(streamflow_array[riv_bas_index])
except IndexError:
log('riv_bas_id {0} not found in connectivity list.'
.format(riv_bas_id),
"WARNING")
log("Writing to file ...",
"INFO")
with open_csv(qinit_file, 'w') as qinit_out:
for init_flow in init_flows_array:
qinit_out.write('{}\n'.format(init_flow))
log("Initialization Complete!",
"INFO") | python | def generate_seasonal_intitialization(
self,
qinit_file,
datetime_start_initialization=datetime.datetime.utcnow()
):
"""This creates a seasonal qinit file from a RAPID qout file. This
requires a simulation Qout file with a longer time period of record and
to be CF compliant. It takes the average of the current date +- 3 days
and goes back as far as possible.
Parameters
----------
qinit_file: str
Path to output qinit_file.
datetime_start_initialization: :obj:`datetime.datetime`, optional
Datetime object with date of simulation to go back through the
years and get a running average to generate streamflow
initialization. Default is utcnow.
Example:
.. code:: python
from RAPIDpy.rapid import RAPID
rapid_manager = RAPID(
Qout_file='/output_mississippi-nfie/Qout_2000to2015.nc',
rapid_connect_file='/input_mississippi_nfie/rapid_connect.csv'
)
rapid_manager.generate_seasonal_intitialization(
qinit_file='/input_mississippi_nfie/Qinit_seasonal_avg.csv'
)
"""
if not self.Qout_file or not os.path.exists(self.Qout_file):
log("Missing Qout_file. "
"Please set before running this function ...",
"ERROR")
if not self.rapid_connect_file or not self.rapid_connect_file:
log("Missing rapid_connect file. "
"Please set before running this function ...",
"ERROR")
day_of_year = datetime_start_initialization.timetuple().tm_yday
min_day = day_of_year - 3
max_day = day_of_year + 3
with RAPIDDataset(self.Qout_file) as qout_hist_nc:
if not qout_hist_nc.is_time_variable_valid():
log("File must be CF 1.6 compliant "
"with valid time variable ...",
"ERROR")
log("Generating seasonal average qinit file from qout file ...",
"INFO")
log("Determining dates with streamflows of interest ...",
"INFO")
time_indices = []
for idx, ttt in enumerate(qout_hist_nc.get_time_array()):
var_time = gmtime(ttt)
compare_yday = var_time.tm_yday
# move day back one past because of leap year adds
# a day after feb 29 (day 60)
if isleap(var_time.tm_year) and compare_yday > 60:
compare_yday -= 1
# check if date within range of season
if min_day <= compare_yday < max_day:
time_indices.append(idx)
if not time_indices:
log("No time steps found within range ...",
"ERROR")
log("Extracting data ...",
"INFO")
streamflow_array = \
qout_hist_nc.get_qout(time_index_array=time_indices)
log("Reordering data...",
"INFO")
stream_id_array = np.loadtxt(self.rapid_connect_file,
ndmin=1, delimiter=",",
usecols=(0,), dtype=int)
init_flows_array = np.zeros(stream_id_array.size)
for riv_bas_index, riv_bas_id in enumerate(
qout_hist_nc.get_river_id_array()):
try:
data_index = np.where(stream_id_array == riv_bas_id)[0][0]
init_flows_array[data_index] = \
np.mean(streamflow_array[riv_bas_index])
except IndexError:
log('riv_bas_id {0} not found in connectivity list.'
.format(riv_bas_id),
"WARNING")
log("Writing to file ...",
"INFO")
with open_csv(qinit_file, 'w') as qinit_out:
for init_flow in init_flows_array:
qinit_out.write('{}\n'.format(init_flow))
log("Initialization Complete!",
"INFO") | [
"def",
"generate_seasonal_intitialization",
"(",
"self",
",",
"qinit_file",
",",
"datetime_start_initialization",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
")",
":",
"if",
"not",
"self",
".",
"Qout_file",
"or",
"not",
"os",
".",
"path",
".",
... | This creates a seasonal qinit file from a RAPID qout file. This
requires a simulation Qout file with a longer time period of record and
to be CF compliant. It takes the average of the current date +- 3 days
and goes back as far as possible.
Parameters
----------
qinit_file: str
Path to output qinit_file.
datetime_start_initialization: :obj:`datetime.datetime`, optional
Datetime object with date of simulation to go back through the
years and get a running average to generate streamflow
initialization. Default is utcnow.
Example:
.. code:: python
from RAPIDpy.rapid import RAPID
rapid_manager = RAPID(
Qout_file='/output_mississippi-nfie/Qout_2000to2015.nc',
rapid_connect_file='/input_mississippi_nfie/rapid_connect.csv'
)
rapid_manager.generate_seasonal_intitialization(
qinit_file='/input_mississippi_nfie/Qinit_seasonal_avg.csv'
) | [
"This",
"creates",
"a",
"seasonal",
"qinit",
"file",
"from",
"a",
"RAPID",
"qout",
"file",
".",
"This",
"requires",
"a",
"simulation",
"Qout",
"file",
"with",
"a",
"longer",
"time",
"period",
"of",
"record",
"and",
"to",
"be",
"CF",
"compliant",
".",
"It... | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/rapid.py#L882-L989 | train | 33,255 |
erdc/RAPIDpy | RAPIDpy/inflow/CreateInflowFileFromGriddedRunoff.py | CreateInflowFileFromGriddedRunoff.read_in_weight_table | def read_in_weight_table(self, in_weight_table):
"""
Read in weight table
"""
print("Reading the weight table...")
with open_csv(in_weight_table, "r") as csvfile:
reader = csv.reader(csvfile)
header_row = next(reader)
# check number of columns in the weight table
if len(header_row) < len(self.header_wt):
raise Exception(self.error_messages[4])
# check header
if header_row[1:len(self.header_wt)] != self.header_wt[1:]:
raise Exception(self.error_messages[5])
self.dict_list = \
np.loadtxt(
in_weight_table,
delimiter=",",
usecols=(0, 1, 2, 3, 4),
skiprows=1,
dtype={
'names': (self.header_wt[0],
self.header_wt[1],
self.header_wt[2],
self.header_wt[3],
self.header_wt[4]),
'formats': ('i8', 'f8', 'i8', 'i8', 'i8')
},
)
self.count = self.dict_list.shape[0]
self.size_stream_id = \
len(np.unique(np.array(self.dict_list[self.header_wt[0]],
dtype=np.int32))) | python | def read_in_weight_table(self, in_weight_table):
"""
Read in weight table
"""
print("Reading the weight table...")
with open_csv(in_weight_table, "r") as csvfile:
reader = csv.reader(csvfile)
header_row = next(reader)
# check number of columns in the weight table
if len(header_row) < len(self.header_wt):
raise Exception(self.error_messages[4])
# check header
if header_row[1:len(self.header_wt)] != self.header_wt[1:]:
raise Exception(self.error_messages[5])
self.dict_list = \
np.loadtxt(
in_weight_table,
delimiter=",",
usecols=(0, 1, 2, 3, 4),
skiprows=1,
dtype={
'names': (self.header_wt[0],
self.header_wt[1],
self.header_wt[2],
self.header_wt[3],
self.header_wt[4]),
'formats': ('i8', 'f8', 'i8', 'i8', 'i8')
},
)
self.count = self.dict_list.shape[0]
self.size_stream_id = \
len(np.unique(np.array(self.dict_list[self.header_wt[0]],
dtype=np.int32))) | [
"def",
"read_in_weight_table",
"(",
"self",
",",
"in_weight_table",
")",
":",
"print",
"(",
"\"Reading the weight table...\"",
")",
"with",
"open_csv",
"(",
"in_weight_table",
",",
"\"r\"",
")",
"as",
"csvfile",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"... | Read in weight table | [
"Read",
"in",
"weight",
"table"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/inflow/CreateInflowFileFromGriddedRunoff.py#L52-L86 | train | 33,256 |
erdc/RAPIDpy | RAPIDpy/inflow/CreateInflowFileFromGriddedRunoff.py | CreateInflowFileFromGriddedRunoff._write_lat_lon | def _write_lat_lon(data_out_nc, rivid_lat_lon_z_file):
"""Add latitude and longitude each netCDF feature
Lookup table is a CSV file with rivid, Lat, Lon, columns.
Columns must be in that order and these must be the first
three columns.
"""
# only add if user adds
if rivid_lat_lon_z_file and os.path.exists(rivid_lat_lon_z_file):
# get list of COMIDS
lookup_table = np.loadtxt(
rivid_lat_lon_z_file,
delimiter=",",
usecols=(0, 1, 2),
skiprows=1,
dtype={
'names': ('rivid', 'lat', 'lon'),
'formats': ('i8', 'f8', 'f8'),
},
)
# Get relevant arrays while we update them
nc_rivids = data_out_nc.variables['rivid'][:]
lats = data_out_nc.variables['lat'][:]
lons = data_out_nc.variables['lon'][:]
lat_min = None
lat_max = None
lon_min = None
lon_max = None
# Process each row in the lookup table
for nc_index, nc_rivid in enumerate(nc_rivids):
try:
lookup_index = \
np.where(lookup_table['rivid'] == nc_rivid)[0][0]
except Exception:
raise Exception('rivid {0} misssing in '
'comid_lat_lon_z file'.format(nc_rivid))
lat = float(lookup_table['lat'][lookup_index])
lats[nc_index] = lat
if lat_min is None or lat < lat_min:
lat_min = lat
if lat_max is None or lat > lat_max:
lat_max = lat
lon = float(lookup_table['lon'][lookup_index])
lons[nc_index] = lon
if lon_min is None or lon < lon_min:
lon_min = lon
if lon_max is None or lon > lon_max:
lon_max = lon
# Overwrite netCDF variable values
data_out_nc.variables['lat'][:] = lats
data_out_nc.variables['lon'][:] = lons
# Update metadata
if lat_min is not None:
data_out_nc.geospatial_lat_min = lat_min
if lat_max is not None:
data_out_nc.geospatial_lat_max = lat_max
if lon_min is not None:
data_out_nc.geospatial_lon_min = lon_min
if lon_max is not None:
data_out_nc.geospatial_lon_max = lon_max
else:
print('No comid_lat_lon_z file. Not adding values ...') | python | def _write_lat_lon(data_out_nc, rivid_lat_lon_z_file):
"""Add latitude and longitude each netCDF feature
Lookup table is a CSV file with rivid, Lat, Lon, columns.
Columns must be in that order and these must be the first
three columns.
"""
# only add if user adds
if rivid_lat_lon_z_file and os.path.exists(rivid_lat_lon_z_file):
# get list of COMIDS
lookup_table = np.loadtxt(
rivid_lat_lon_z_file,
delimiter=",",
usecols=(0, 1, 2),
skiprows=1,
dtype={
'names': ('rivid', 'lat', 'lon'),
'formats': ('i8', 'f8', 'f8'),
},
)
# Get relevant arrays while we update them
nc_rivids = data_out_nc.variables['rivid'][:]
lats = data_out_nc.variables['lat'][:]
lons = data_out_nc.variables['lon'][:]
lat_min = None
lat_max = None
lon_min = None
lon_max = None
# Process each row in the lookup table
for nc_index, nc_rivid in enumerate(nc_rivids):
try:
lookup_index = \
np.where(lookup_table['rivid'] == nc_rivid)[0][0]
except Exception:
raise Exception('rivid {0} misssing in '
'comid_lat_lon_z file'.format(nc_rivid))
lat = float(lookup_table['lat'][lookup_index])
lats[nc_index] = lat
if lat_min is None or lat < lat_min:
lat_min = lat
if lat_max is None or lat > lat_max:
lat_max = lat
lon = float(lookup_table['lon'][lookup_index])
lons[nc_index] = lon
if lon_min is None or lon < lon_min:
lon_min = lon
if lon_max is None or lon > lon_max:
lon_max = lon
# Overwrite netCDF variable values
data_out_nc.variables['lat'][:] = lats
data_out_nc.variables['lon'][:] = lons
# Update metadata
if lat_min is not None:
data_out_nc.geospatial_lat_min = lat_min
if lat_max is not None:
data_out_nc.geospatial_lat_max = lat_max
if lon_min is not None:
data_out_nc.geospatial_lon_min = lon_min
if lon_max is not None:
data_out_nc.geospatial_lon_max = lon_max
else:
print('No comid_lat_lon_z file. Not adding values ...') | [
"def",
"_write_lat_lon",
"(",
"data_out_nc",
",",
"rivid_lat_lon_z_file",
")",
":",
"# only add if user adds\r",
"if",
"rivid_lat_lon_z_file",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"rivid_lat_lon_z_file",
")",
":",
"# get list of COMIDS\r",
"lookup_table",
"=",
... | Add latitude and longitude each netCDF feature
Lookup table is a CSV file with rivid, Lat, Lon, columns.
Columns must be in that order and these must be the first
three columns. | [
"Add",
"latitude",
"and",
"longitude",
"each",
"netCDF",
"feature",
"Lookup",
"table",
"is",
"a",
"CSV",
"file",
"with",
"rivid",
"Lat",
"Lon",
"columns",
".",
"Columns",
"must",
"be",
"in",
"that",
"order",
"and",
"these",
"must",
"be",
"the",
"first",
... | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/inflow/CreateInflowFileFromGriddedRunoff.py#L89-L156 | train | 33,257 |
erdc/RAPIDpy | RAPIDpy/postprocess/goodness_of_fit.py | filter_nan | def filter_nan(s, o):
"""
this functions removed the data from simulated and observed data
whereever the observed data contains nan
this is used by all other functions, otherwise they will produce nan as
output
"""
data = np.array([s.flatten(), o.flatten()])
data = np.transpose(data)
data = data[~np.isnan(data).any(1)]
return data[:, 0], data[:, 1] | python | def filter_nan(s, o):
"""
this functions removed the data from simulated and observed data
whereever the observed data contains nan
this is used by all other functions, otherwise they will produce nan as
output
"""
data = np.array([s.flatten(), o.flatten()])
data = np.transpose(data)
data = data[~np.isnan(data).any(1)]
return data[:, 0], data[:, 1] | [
"def",
"filter_nan",
"(",
"s",
",",
"o",
")",
":",
"data",
"=",
"np",
".",
"array",
"(",
"[",
"s",
".",
"flatten",
"(",
")",
",",
"o",
".",
"flatten",
"(",
")",
"]",
")",
"data",
"=",
"np",
".",
"transpose",
"(",
"data",
")",
"data",
"=",
"... | this functions removed the data from simulated and observed data
whereever the observed data contains nan
this is used by all other functions, otherwise they will produce nan as
output | [
"this",
"functions",
"removed",
"the",
"data",
"from",
"simulated",
"and",
"observed",
"data",
"whereever",
"the",
"observed",
"data",
"contains",
"nan"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/postprocess/goodness_of_fit.py#L21-L32 | train | 33,258 |
erdc/RAPIDpy | RAPIDpy/postprocess/goodness_of_fit.py | find_goodness_of_fit | def find_goodness_of_fit(rapid_qout_file, reach_id_file, observed_file,
out_analysis_file, daily=False):
"""
Finds the goodness of fit comparing observed streamflow in a rapid Qout
file with simulated flows in a csv file.
Parameters
----------
rapid_qout_file: str
Path to the RAPID Qout file.
reach_id_file: str
ath to file with river reach ID's associate with the RAPID Qout file.
It is in the format of the RAPID observed flows reach ID file.
observed_file: str
Path to input csv with with observed flows corresponding to the
RAPID Qout. It is in the format of the RAPID observed flows file.
out_analysis_file: str
Path to the analysis output csv file.
daily: bool, optional
If True and the file is CF-Compliant, it will compare the
*observed_file* with daily average flow from Qout. Default is False.
Example with CF-Compliant RAPID Qout file:
.. code:: python
import os
from RAPIDpy.postprocess import find_goodness_of_fit
INPUT_DATA_PATH = '/path/to/data'
reach_id_file = os.path.join(INPUT_DATA_PATH, 'obs_reach_id.csv')
observed_file = os.path.join(INPUT_DATA_PATH, 'obs_flow.csv')
cf_input_qout_file = os.path.join(COMPARE_DATA_PATH,
'Qout_nasa_lis_3hr_20020830_CF.nc')
cf_out_analysis_file = \
os.path.join(OUTPUT_DATA_PATH,
'cf_goodness_of_fit_results-daily.csv')
find_goodness_of_fit(cf_input_qout_file,
reach_id_file,
observed_file,
cf_out_analysis_file,
daily=True)
"""
reach_id_list = np.loadtxt(reach_id_file,
delimiter=",", usecols=(0,),
ndmin=1, dtype=np.int32)
data_nc = RAPIDDataset(rapid_qout_file)
# analyze and write
observed_table = np.loadtxt(observed_file,
ndmin=2, delimiter=",",
usecols=tuple(range(reach_id_list.size)))
with open(out_analysis_file, 'w') as outcsv:
writer = csvwriter(outcsv)
writer.writerow(["reach_id",
"percent_bias",
"abs_percent_bias",
"rmse",
"mae",
"bias",
"NSE",
"likelihood",
"correlation_coeff",
"index_agreement",
"KGE"])
for index, reach_id in enumerate(reach_id_list):
observed_array = observed_table[:, index]
simulated_array = data_nc.get_qout(reach_id, daily=daily)
# make sure they are the same length
simulated_array = simulated_array[:len(observed_array)]
observed_array = observed_array[:len(simulated_array)]
simulated_array, observed_array = \
filter_nan(simulated_array, observed_array)
writer.writerow([reach_id,
pc_bias(simulated_array, observed_array),
apb(simulated_array, observed_array),
rmse(simulated_array, observed_array),
mae(simulated_array, observed_array),
bias(simulated_array, observed_array),
NS(simulated_array, observed_array),
L(simulated_array, observed_array),
correlation(simulated_array, observed_array),
index_agreement(simulated_array, observed_array),
KGE(simulated_array, observed_array)[0]]) | python | def find_goodness_of_fit(rapid_qout_file, reach_id_file, observed_file,
out_analysis_file, daily=False):
"""
Finds the goodness of fit comparing observed streamflow in a rapid Qout
file with simulated flows in a csv file.
Parameters
----------
rapid_qout_file: str
Path to the RAPID Qout file.
reach_id_file: str
ath to file with river reach ID's associate with the RAPID Qout file.
It is in the format of the RAPID observed flows reach ID file.
observed_file: str
Path to input csv with with observed flows corresponding to the
RAPID Qout. It is in the format of the RAPID observed flows file.
out_analysis_file: str
Path to the analysis output csv file.
daily: bool, optional
If True and the file is CF-Compliant, it will compare the
*observed_file* with daily average flow from Qout. Default is False.
Example with CF-Compliant RAPID Qout file:
.. code:: python
import os
from RAPIDpy.postprocess import find_goodness_of_fit
INPUT_DATA_PATH = '/path/to/data'
reach_id_file = os.path.join(INPUT_DATA_PATH, 'obs_reach_id.csv')
observed_file = os.path.join(INPUT_DATA_PATH, 'obs_flow.csv')
cf_input_qout_file = os.path.join(COMPARE_DATA_PATH,
'Qout_nasa_lis_3hr_20020830_CF.nc')
cf_out_analysis_file = \
os.path.join(OUTPUT_DATA_PATH,
'cf_goodness_of_fit_results-daily.csv')
find_goodness_of_fit(cf_input_qout_file,
reach_id_file,
observed_file,
cf_out_analysis_file,
daily=True)
"""
reach_id_list = np.loadtxt(reach_id_file,
delimiter=",", usecols=(0,),
ndmin=1, dtype=np.int32)
data_nc = RAPIDDataset(rapid_qout_file)
# analyze and write
observed_table = np.loadtxt(observed_file,
ndmin=2, delimiter=",",
usecols=tuple(range(reach_id_list.size)))
with open(out_analysis_file, 'w') as outcsv:
writer = csvwriter(outcsv)
writer.writerow(["reach_id",
"percent_bias",
"abs_percent_bias",
"rmse",
"mae",
"bias",
"NSE",
"likelihood",
"correlation_coeff",
"index_agreement",
"KGE"])
for index, reach_id in enumerate(reach_id_list):
observed_array = observed_table[:, index]
simulated_array = data_nc.get_qout(reach_id, daily=daily)
# make sure they are the same length
simulated_array = simulated_array[:len(observed_array)]
observed_array = observed_array[:len(simulated_array)]
simulated_array, observed_array = \
filter_nan(simulated_array, observed_array)
writer.writerow([reach_id,
pc_bias(simulated_array, observed_array),
apb(simulated_array, observed_array),
rmse(simulated_array, observed_array),
mae(simulated_array, observed_array),
bias(simulated_array, observed_array),
NS(simulated_array, observed_array),
L(simulated_array, observed_array),
correlation(simulated_array, observed_array),
index_agreement(simulated_array, observed_array),
KGE(simulated_array, observed_array)[0]]) | [
"def",
"find_goodness_of_fit",
"(",
"rapid_qout_file",
",",
"reach_id_file",
",",
"observed_file",
",",
"out_analysis_file",
",",
"daily",
"=",
"False",
")",
":",
"reach_id_list",
"=",
"np",
".",
"loadtxt",
"(",
"reach_id_file",
",",
"delimiter",
"=",
"\",\"",
"... | Finds the goodness of fit comparing observed streamflow in a rapid Qout
file with simulated flows in a csv file.
Parameters
----------
rapid_qout_file: str
Path to the RAPID Qout file.
reach_id_file: str
ath to file with river reach ID's associate with the RAPID Qout file.
It is in the format of the RAPID observed flows reach ID file.
observed_file: str
Path to input csv with with observed flows corresponding to the
RAPID Qout. It is in the format of the RAPID observed flows file.
out_analysis_file: str
Path to the analysis output csv file.
daily: bool, optional
If True and the file is CF-Compliant, it will compare the
*observed_file* with daily average flow from Qout. Default is False.
Example with CF-Compliant RAPID Qout file:
.. code:: python
import os
from RAPIDpy.postprocess import find_goodness_of_fit
INPUT_DATA_PATH = '/path/to/data'
reach_id_file = os.path.join(INPUT_DATA_PATH, 'obs_reach_id.csv')
observed_file = os.path.join(INPUT_DATA_PATH, 'obs_flow.csv')
cf_input_qout_file = os.path.join(COMPARE_DATA_PATH,
'Qout_nasa_lis_3hr_20020830_CF.nc')
cf_out_analysis_file = \
os.path.join(OUTPUT_DATA_PATH,
'cf_goodness_of_fit_results-daily.csv')
find_goodness_of_fit(cf_input_qout_file,
reach_id_file,
observed_file,
cf_out_analysis_file,
daily=True) | [
"Finds",
"the",
"goodness",
"of",
"fit",
"comparing",
"observed",
"streamflow",
"in",
"a",
"rapid",
"Qout",
"file",
"with",
"simulated",
"flows",
"in",
"a",
"csv",
"file",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/postprocess/goodness_of_fit.py#L183-L271 | train | 33,259 |
erdc/RAPIDpy | RAPIDpy/postprocess/goodness_of_fit.py | find_goodness_of_fit_csv | def find_goodness_of_fit_csv(observed_simulated_file, out_file=None):
"""
Finds the goodness of fit comparing observed and simulated flows
In the file, the first column is the observed flows and the
second column is the simulated flows.
Example::
33.5, 77.2
34.7, 73.0
Parameters
----------
observed_simulated_file: str
Path to the csv file with the observed and simulated flows.
out_file: str, optional
Path to output file. If not provided, it will print to console.
Example:
.. code:: python
from RAPIDpy.postprocess import find_goodness_of_fit_csv
find_goodness_of_fit_csv('
/united_kingdom-thames/flows_kingston_gage_noah.csv')
"""
observed_simulated_table = np.loadtxt(observed_simulated_file,
ndmin=2, delimiter=",",
usecols=(0, 1))
observed_array, simulated_array = \
filter_nan(observed_simulated_table[:, 0],
observed_simulated_table[:, 1])
# print error indices
if out_file:
print_file = open(out_file, 'w')
else:
print_file = None
print("\n".join([
"Percent Bias: {0:.4f}"
.format(pc_bias(simulated_array, observed_array)),
"Absolute Percent Bias: {0:.4f}"
.format(apb(simulated_array, observed_array)),
"Root Mean Squared Error: {0:.4f}"
.format(rmse(simulated_array, observed_array)),
"Mean Absolute Error: {0:.4f}"
.format(mae(simulated_array, observed_array)),
"Bias: {0}".format(bias(simulated_array, observed_array)),
"Nash Sutcliffe efficiency coefficient: {0:.4f}"
.format(NS(simulated_array, observed_array)),
"Likelihood: {0:.4f}"
.format(L(simulated_array, observed_array)),
"correlation coefficient: {0:.4f}"
.format(correlation(simulated_array, observed_array)),
"index of agreement: {0:.4f}"
.format(index_agreement(simulated_array, observed_array)),
"Kling-Gupta Efficiency: {0:.4f}"
.format(KGE(simulated_array, observed_array)[0]),
]),
file=print_file)
if print_file:
print_file.close() | python | def find_goodness_of_fit_csv(observed_simulated_file, out_file=None):
"""
Finds the goodness of fit comparing observed and simulated flows
In the file, the first column is the observed flows and the
second column is the simulated flows.
Example::
33.5, 77.2
34.7, 73.0
Parameters
----------
observed_simulated_file: str
Path to the csv file with the observed and simulated flows.
out_file: str, optional
Path to output file. If not provided, it will print to console.
Example:
.. code:: python
from RAPIDpy.postprocess import find_goodness_of_fit_csv
find_goodness_of_fit_csv('
/united_kingdom-thames/flows_kingston_gage_noah.csv')
"""
observed_simulated_table = np.loadtxt(observed_simulated_file,
ndmin=2, delimiter=",",
usecols=(0, 1))
observed_array, simulated_array = \
filter_nan(observed_simulated_table[:, 0],
observed_simulated_table[:, 1])
# print error indices
if out_file:
print_file = open(out_file, 'w')
else:
print_file = None
print("\n".join([
"Percent Bias: {0:.4f}"
.format(pc_bias(simulated_array, observed_array)),
"Absolute Percent Bias: {0:.4f}"
.format(apb(simulated_array, observed_array)),
"Root Mean Squared Error: {0:.4f}"
.format(rmse(simulated_array, observed_array)),
"Mean Absolute Error: {0:.4f}"
.format(mae(simulated_array, observed_array)),
"Bias: {0}".format(bias(simulated_array, observed_array)),
"Nash Sutcliffe efficiency coefficient: {0:.4f}"
.format(NS(simulated_array, observed_array)),
"Likelihood: {0:.4f}"
.format(L(simulated_array, observed_array)),
"correlation coefficient: {0:.4f}"
.format(correlation(simulated_array, observed_array)),
"index of agreement: {0:.4f}"
.format(index_agreement(simulated_array, observed_array)),
"Kling-Gupta Efficiency: {0:.4f}"
.format(KGE(simulated_array, observed_array)[0]),
]),
file=print_file)
if print_file:
print_file.close() | [
"def",
"find_goodness_of_fit_csv",
"(",
"observed_simulated_file",
",",
"out_file",
"=",
"None",
")",
":",
"observed_simulated_table",
"=",
"np",
".",
"loadtxt",
"(",
"observed_simulated_file",
",",
"ndmin",
"=",
"2",
",",
"delimiter",
"=",
"\",\"",
",",
"usecols"... | Finds the goodness of fit comparing observed and simulated flows
In the file, the first column is the observed flows and the
second column is the simulated flows.
Example::
33.5, 77.2
34.7, 73.0
Parameters
----------
observed_simulated_file: str
Path to the csv file with the observed and simulated flows.
out_file: str, optional
Path to output file. If not provided, it will print to console.
Example:
.. code:: python
from RAPIDpy.postprocess import find_goodness_of_fit_csv
find_goodness_of_fit_csv('
/united_kingdom-thames/flows_kingston_gage_noah.csv') | [
"Finds",
"the",
"goodness",
"of",
"fit",
"comparing",
"observed",
"and",
"simulated",
"flows",
"In",
"the",
"file",
"the",
"first",
"column",
"is",
"the",
"observed",
"flows",
"and",
"the",
"second",
"column",
"is",
"the",
"simulated",
"flows",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/postprocess/goodness_of_fit.py#L274-L341 | train | 33,260 |
erdc/RAPIDpy | RAPIDpy/helper_functions.py | log | def log(message, severity="INFO", print_debug=True):
"""Logs, prints, or raises a message.
Arguments:
message -- message to report
severity -- string of one of these values:
CRITICAL|ERROR|WARNING|INFO|DEBUG
"""
print_me = ['WARNING', 'INFO', 'DEBUG']
if severity in print_me:
if severity == 'DEBUG':
if print_debug:
print("{0}: {1}".format(severity, message))
else:
print("{0}: {1}".format(severity, message))
else:
raise Exception("{0}: {1}".format(severity, message)) | python | def log(message, severity="INFO", print_debug=True):
"""Logs, prints, or raises a message.
Arguments:
message -- message to report
severity -- string of one of these values:
CRITICAL|ERROR|WARNING|INFO|DEBUG
"""
print_me = ['WARNING', 'INFO', 'DEBUG']
if severity in print_me:
if severity == 'DEBUG':
if print_debug:
print("{0}: {1}".format(severity, message))
else:
print("{0}: {1}".format(severity, message))
else:
raise Exception("{0}: {1}".format(severity, message)) | [
"def",
"log",
"(",
"message",
",",
"severity",
"=",
"\"INFO\"",
",",
"print_debug",
"=",
"True",
")",
":",
"print_me",
"=",
"[",
"'WARNING'",
",",
"'INFO'",
",",
"'DEBUG'",
"]",
"if",
"severity",
"in",
"print_me",
":",
"if",
"severity",
"==",
"'DEBUG'",
... | Logs, prints, or raises a message.
Arguments:
message -- message to report
severity -- string of one of these values:
CRITICAL|ERROR|WARNING|INFO|DEBUG | [
"Logs",
"prints",
"or",
"raises",
"a",
"message",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/helper_functions.py#L36-L53 | train | 33,261 |
erdc/RAPIDpy | RAPIDpy/helper_functions.py | csv_to_list | def csv_to_list(csv_file, delimiter=','):
"""
Reads in a CSV file and returns the contents as list,
where every row is stored as a sublist, and each element
in the sublist represents 1 cell in the table.
"""
with open_csv(csv_file) as csv_con:
if len(delimiter) > 1:
dialect = csv.Sniffer().sniff(csv_con.read(1024),
delimiters=delimiter)
csv_con.seek(0)
reader = csv.reader(csv_con, dialect)
else:
reader = csv.reader(csv_con, delimiter=delimiter)
return list(reader) | python | def csv_to_list(csv_file, delimiter=','):
"""
Reads in a CSV file and returns the contents as list,
where every row is stored as a sublist, and each element
in the sublist represents 1 cell in the table.
"""
with open_csv(csv_file) as csv_con:
if len(delimiter) > 1:
dialect = csv.Sniffer().sniff(csv_con.read(1024),
delimiters=delimiter)
csv_con.seek(0)
reader = csv.reader(csv_con, dialect)
else:
reader = csv.reader(csv_con, delimiter=delimiter)
return list(reader) | [
"def",
"csv_to_list",
"(",
"csv_file",
",",
"delimiter",
"=",
"','",
")",
":",
"with",
"open_csv",
"(",
"csv_file",
")",
"as",
"csv_con",
":",
"if",
"len",
"(",
"delimiter",
")",
">",
"1",
":",
"dialect",
"=",
"csv",
".",
"Sniffer",
"(",
")",
".",
... | Reads in a CSV file and returns the contents as list,
where every row is stored as a sublist, and each element
in the sublist represents 1 cell in the table. | [
"Reads",
"in",
"a",
"CSV",
"file",
"and",
"returns",
"the",
"contents",
"as",
"list",
"where",
"every",
"row",
"is",
"stored",
"as",
"a",
"sublist",
"and",
"each",
"element",
"in",
"the",
"sublist",
"represents",
"1",
"cell",
"in",
"the",
"table",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/helper_functions.py#L56-L70 | train | 33,262 |
erdc/RAPIDpy | RAPIDpy/helper_functions.py | add_latlon_metadata | def add_latlon_metadata(lat_var, lon_var):
"""Adds latitude and longitude metadata"""
lat_var.long_name = 'latitude'
lat_var.standard_name = 'latitude'
lat_var.units = 'degrees_north'
lat_var.axis = 'Y'
lon_var.long_name = 'longitude'
lon_var.standard_name = 'longitude'
lon_var.units = 'degrees_east'
lon_var.axis = 'X' | python | def add_latlon_metadata(lat_var, lon_var):
"""Adds latitude and longitude metadata"""
lat_var.long_name = 'latitude'
lat_var.standard_name = 'latitude'
lat_var.units = 'degrees_north'
lat_var.axis = 'Y'
lon_var.long_name = 'longitude'
lon_var.standard_name = 'longitude'
lon_var.units = 'degrees_east'
lon_var.axis = 'X' | [
"def",
"add_latlon_metadata",
"(",
"lat_var",
",",
"lon_var",
")",
":",
"lat_var",
".",
"long_name",
"=",
"'latitude'",
"lat_var",
".",
"standard_name",
"=",
"'latitude'",
"lat_var",
".",
"units",
"=",
"'degrees_north'",
"lat_var",
".",
"axis",
"=",
"'Y'",
"lo... | Adds latitude and longitude metadata | [
"Adds",
"latitude",
"and",
"longitude",
"metadata"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/helper_functions.py#L126-L136 | train | 33,263 |
erdc/RAPIDpy | RAPIDpy/inflow/lsm_rapid_process.py | generate_inflows_from_runoff | def generate_inflows_from_runoff(args):
"""
prepare runoff inflow file for rapid
"""
runoff_file_list = args[0]
file_index_list = args[1]
weight_table_file = args[2]
grid_type = args[3]
rapid_inflow_file = args[4]
rapid_inflow_tool = args[5]
mp_lock = args[6]
time_start_all = datetime.utcnow()
if not isinstance(runoff_file_list, list):
runoff_file_list = [runoff_file_list]
else:
runoff_file_list = runoff_file_list
if not isinstance(file_index_list, list):
file_index_list = [file_index_list]
else:
file_index_list = file_index_list
if runoff_file_list and file_index_list:
# prepare ECMWF file for RAPID
index_string = "Index: {0}".format(file_index_list[0])
if len(file_index_list) > 1:
index_string += " to {0}".format(file_index_list[-1])
print(index_string)
runoff_string = "File(s): {0}".format(runoff_file_list[0])
if len(runoff_file_list) > 1:
runoff_string += " to {0}".format(runoff_file_list[-1])
print(runoff_string)
print("Converting inflow ...")
try:
rapid_inflow_tool.execute(nc_file_list=runoff_file_list,
index_list=file_index_list,
in_weight_table=weight_table_file,
out_nc=rapid_inflow_file,
grid_type=grid_type,
mp_lock=mp_lock)
except Exception:
# This prints the type, value, and stack trace of the
# current exception being handled.
traceback.print_exc()
raise
time_finish_ecmwf = datetime.utcnow()
print("Time to convert inflows: {0}"
.format(time_finish_ecmwf-time_start_all)) | python | def generate_inflows_from_runoff(args):
"""
prepare runoff inflow file for rapid
"""
runoff_file_list = args[0]
file_index_list = args[1]
weight_table_file = args[2]
grid_type = args[3]
rapid_inflow_file = args[4]
rapid_inflow_tool = args[5]
mp_lock = args[6]
time_start_all = datetime.utcnow()
if not isinstance(runoff_file_list, list):
runoff_file_list = [runoff_file_list]
else:
runoff_file_list = runoff_file_list
if not isinstance(file_index_list, list):
file_index_list = [file_index_list]
else:
file_index_list = file_index_list
if runoff_file_list and file_index_list:
# prepare ECMWF file for RAPID
index_string = "Index: {0}".format(file_index_list[0])
if len(file_index_list) > 1:
index_string += " to {0}".format(file_index_list[-1])
print(index_string)
runoff_string = "File(s): {0}".format(runoff_file_list[0])
if len(runoff_file_list) > 1:
runoff_string += " to {0}".format(runoff_file_list[-1])
print(runoff_string)
print("Converting inflow ...")
try:
rapid_inflow_tool.execute(nc_file_list=runoff_file_list,
index_list=file_index_list,
in_weight_table=weight_table_file,
out_nc=rapid_inflow_file,
grid_type=grid_type,
mp_lock=mp_lock)
except Exception:
# This prints the type, value, and stack trace of the
# current exception being handled.
traceback.print_exc()
raise
time_finish_ecmwf = datetime.utcnow()
print("Time to convert inflows: {0}"
.format(time_finish_ecmwf-time_start_all)) | [
"def",
"generate_inflows_from_runoff",
"(",
"args",
")",
":",
"runoff_file_list",
"=",
"args",
"[",
"0",
"]",
"file_index_list",
"=",
"args",
"[",
"1",
"]",
"weight_table_file",
"=",
"args",
"[",
"2",
"]",
"grid_type",
"=",
"args",
"[",
"3",
"]",
"rapid_in... | prepare runoff inflow file for rapid | [
"prepare",
"runoff",
"inflow",
"file",
"for",
"rapid"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/inflow/lsm_rapid_process.py#L38-L87 | train | 33,264 |
erdc/RAPIDpy | RAPIDpy/inflow/lsm_rapid_process.py | determine_start_end_timestep | def determine_start_end_timestep(lsm_file_list,
file_re_match=None,
file_datetime_pattern=None,
expected_time_step=None,
lsm_grid_info=None):
"""
Determine the start and end date from LSM input files
"""
if lsm_grid_info is None:
lsm_grid_info = identify_lsm_grid(lsm_file_list[0])
if None in (lsm_grid_info['time_var'], lsm_grid_info['time_dim'])\
or lsm_grid_info['model_name'] in ('era_20cm', 'erai'):
# NOTE: the ERA20CM and ERA 24hr time variables
# in the tests are erroneous
if None in (file_re_match, file_datetime_pattern):
raise ValueError("LSM files missing time dimension and/or "
"variable.To mitigate this, add the "
"'file_re_match' and 'file_datetime_pattern' "
"arguments.")
if lsm_grid_info['time_dim'] is None:
print("Assuming time dimension is 1")
file_size_time = 1
else:
lsm_example_file = Dataset(lsm_file_list[0])
file_size_time = \
len(lsm_example_file.dimensions[lsm_grid_info['time_dim']])
lsm_example_file.close()
total_num_time_steps = int(file_size_time * len(lsm_file_list))
# determine the start time from the existing files
actual_simulation_start_datetime = \
datetime.strptime(file_re_match.search(lsm_file_list[0]).group(0),
file_datetime_pattern)
# check to see if the time step matches expected
if len(lsm_file_list) > 1:
time_step = \
int((datetime.strptime(
file_re_match.search(lsm_file_list[1]).group(0),
file_datetime_pattern) -
actual_simulation_start_datetime).total_seconds()
/ float(file_size_time))
elif expected_time_step is not None:
time_step = int(expected_time_step)
else:
raise ValueError("Only one LSM file with one timestep present. "
"'expected_time_step' parameter required to "
"continue.")
# determine the end datetime
actual_simulation_end_datetime = \
datetime.strptime(file_re_match.search(lsm_file_list[-1]).group(0),
file_datetime_pattern) \
+ timedelta(seconds=(file_size_time-1) * time_step)
else:
with pangaea.open_mfdataset(lsm_file_list,
lat_var=lsm_grid_info['latitude_var'],
lon_var=lsm_grid_info['longitude_var'],
time_var=lsm_grid_info['time_var'],
lat_dim=lsm_grid_info['latitude_dim'],
lon_dim=lsm_grid_info['longitude_dim'],
time_dim=lsm_grid_info['time_dim']) as xds:
datetime_arr = [pd.to_datetime(dval) for dval in
xds.lsm.datetime.values]
actual_simulation_start_datetime = datetime_arr[0]
actual_simulation_end_datetime = datetime_arr[-1]
total_num_time_steps = len(datetime_arr)
if total_num_time_steps <= 1:
if expected_time_step is not None:
time_step = int(expected_time_step)
else:
raise ValueError("Only one LSM file with one timestep "
"present. 'expected_time_step' parameter "
"required to continue.")
else:
time_step = int(np.diff(xds.lsm.datetime.values)[0]
/ np.timedelta64(1, 's'))
if expected_time_step is not None:
if time_step != int(expected_time_step):
print("WARNING: The time step used {0} is different than "
"expected {1}".format(time_step, expected_time_step))
return (actual_simulation_start_datetime, actual_simulation_end_datetime,
time_step, total_num_time_steps) | python | def determine_start_end_timestep(lsm_file_list,
file_re_match=None,
file_datetime_pattern=None,
expected_time_step=None,
lsm_grid_info=None):
"""
Determine the start and end date from LSM input files
"""
if lsm_grid_info is None:
lsm_grid_info = identify_lsm_grid(lsm_file_list[0])
if None in (lsm_grid_info['time_var'], lsm_grid_info['time_dim'])\
or lsm_grid_info['model_name'] in ('era_20cm', 'erai'):
# NOTE: the ERA20CM and ERA 24hr time variables
# in the tests are erroneous
if None in (file_re_match, file_datetime_pattern):
raise ValueError("LSM files missing time dimension and/or "
"variable.To mitigate this, add the "
"'file_re_match' and 'file_datetime_pattern' "
"arguments.")
if lsm_grid_info['time_dim'] is None:
print("Assuming time dimension is 1")
file_size_time = 1
else:
lsm_example_file = Dataset(lsm_file_list[0])
file_size_time = \
len(lsm_example_file.dimensions[lsm_grid_info['time_dim']])
lsm_example_file.close()
total_num_time_steps = int(file_size_time * len(lsm_file_list))
# determine the start time from the existing files
actual_simulation_start_datetime = \
datetime.strptime(file_re_match.search(lsm_file_list[0]).group(0),
file_datetime_pattern)
# check to see if the time step matches expected
if len(lsm_file_list) > 1:
time_step = \
int((datetime.strptime(
file_re_match.search(lsm_file_list[1]).group(0),
file_datetime_pattern) -
actual_simulation_start_datetime).total_seconds()
/ float(file_size_time))
elif expected_time_step is not None:
time_step = int(expected_time_step)
else:
raise ValueError("Only one LSM file with one timestep present. "
"'expected_time_step' parameter required to "
"continue.")
# determine the end datetime
actual_simulation_end_datetime = \
datetime.strptime(file_re_match.search(lsm_file_list[-1]).group(0),
file_datetime_pattern) \
+ timedelta(seconds=(file_size_time-1) * time_step)
else:
with pangaea.open_mfdataset(lsm_file_list,
lat_var=lsm_grid_info['latitude_var'],
lon_var=lsm_grid_info['longitude_var'],
time_var=lsm_grid_info['time_var'],
lat_dim=lsm_grid_info['latitude_dim'],
lon_dim=lsm_grid_info['longitude_dim'],
time_dim=lsm_grid_info['time_dim']) as xds:
datetime_arr = [pd.to_datetime(dval) for dval in
xds.lsm.datetime.values]
actual_simulation_start_datetime = datetime_arr[0]
actual_simulation_end_datetime = datetime_arr[-1]
total_num_time_steps = len(datetime_arr)
if total_num_time_steps <= 1:
if expected_time_step is not None:
time_step = int(expected_time_step)
else:
raise ValueError("Only one LSM file with one timestep "
"present. 'expected_time_step' parameter "
"required to continue.")
else:
time_step = int(np.diff(xds.lsm.datetime.values)[0]
/ np.timedelta64(1, 's'))
if expected_time_step is not None:
if time_step != int(expected_time_step):
print("WARNING: The time step used {0} is different than "
"expected {1}".format(time_step, expected_time_step))
return (actual_simulation_start_datetime, actual_simulation_end_datetime,
time_step, total_num_time_steps) | [
"def",
"determine_start_end_timestep",
"(",
"lsm_file_list",
",",
"file_re_match",
"=",
"None",
",",
"file_datetime_pattern",
"=",
"None",
",",
"expected_time_step",
"=",
"None",
",",
"lsm_grid_info",
"=",
"None",
")",
":",
"if",
"lsm_grid_info",
"is",
"None",
":"... | Determine the start and end date from LSM input files | [
"Determine",
"the",
"start",
"and",
"end",
"date",
"from",
"LSM",
"input",
"files"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/inflow/lsm_rapid_process.py#L471-L561 | train | 33,265 |
erdc/RAPIDpy | RAPIDpy/gis/voronoi.py | _get_voronoi_centroid_array | def _get_voronoi_centroid_array(lsm_lat_array, lsm_lon_array, extent):
"""
This function generates a voronoi centroid point
list from arrays of latitude and longitude
"""
YMin = extent[2]
YMax = extent[3]
XMin = extent[0]
XMax = extent[1]
ptList = []
if (lsm_lat_array.ndim == 2) and (lsm_lon_array.ndim == 2):
# generate point list with 2D lat lon lists
if extent:
# exctract subset within extent
lsm_dx = np.max(np.absolute(np.diff(lsm_lon_array)))
lsm_dy = np.max(np.absolute(np.diff(lsm_lat_array, axis=0)))
# remove values with NaN
lsm_lat_array = np.ma.filled(lsm_lat_array, fill_value=-9999)
lsm_lon_array = np.ma.filled(lsm_lon_array, fill_value=-9999)
lsm_lat_indices_from_lat, lsm_lon_indices_from_lat = \
np.where((lsm_lat_array >= (YMin - 2*lsm_dy)) &
(lsm_lat_array <= (YMax + 2*lsm_dy)))
lsm_lat_indices_from_lon, lsm_lon_indices_from_lon = \
np.where((lsm_lon_array >= (XMin - 2*lsm_dx)) &
(lsm_lon_array <= (XMax + 2*lsm_dx)))
lsm_lat_indices = np.intersect1d(lsm_lat_indices_from_lat,
lsm_lat_indices_from_lon)
lsm_lon_indices = np.intersect1d(lsm_lon_indices_from_lat,
lsm_lon_indices_from_lon)
lsm_lat_list = \
lsm_lat_array[lsm_lat_indices, :][:, lsm_lon_indices]
lsm_lon_list = \
lsm_lon_array[lsm_lat_indices, :][:, lsm_lon_indices]
# Create a list of geographic coordinate pairs
for i in range(len(lsm_lat_indices)):
for j in range(len(lsm_lon_indices)):
ptList.append([lsm_lon_list[i][j], lsm_lat_list[i][j]])
elif lsm_lat_array.ndim == 1 and lsm_lon_array.ndim == 1:
# generate point list with 1D lat lon lists
if extent:
Ybuffer = 2 * abs(lsm_lat_array[0]-lsm_lat_array[1])
Xbuffer = 2 * abs(lsm_lon_array[0]-lsm_lon_array[1])
# Extract the lat and lon within buffered extent
# (buffer with 2* interval degree)
lsm_lat_list = lsm_lat_array[(lsm_lat_array >= (YMin - Ybuffer)) &
(lsm_lat_array <= (YMax + Ybuffer))]
lsm_lon_list = lsm_lon_array[(lsm_lon_array >= (XMin - Xbuffer)) &
(lsm_lon_array <= (XMax + Xbuffer))]
# Create a list of geographic coordinate pairs
for ptX in lsm_lon_list:
for ptY in lsm_lat_list:
ptList.append([ptX, ptY])
else:
raise IndexError("Lat/Lon lists have invalid dimensions. "
"Only 1D or 2D arrays allowed ...")
if len(ptList) <= 0:
raise IndexError("The watershed is outside of the bounds of the"
" land surface model grid ...")
return np.array(ptList) | python | def _get_voronoi_centroid_array(lsm_lat_array, lsm_lon_array, extent):
"""
This function generates a voronoi centroid point
list from arrays of latitude and longitude
"""
YMin = extent[2]
YMax = extent[3]
XMin = extent[0]
XMax = extent[1]
ptList = []
if (lsm_lat_array.ndim == 2) and (lsm_lon_array.ndim == 2):
# generate point list with 2D lat lon lists
if extent:
# exctract subset within extent
lsm_dx = np.max(np.absolute(np.diff(lsm_lon_array)))
lsm_dy = np.max(np.absolute(np.diff(lsm_lat_array, axis=0)))
# remove values with NaN
lsm_lat_array = np.ma.filled(lsm_lat_array, fill_value=-9999)
lsm_lon_array = np.ma.filled(lsm_lon_array, fill_value=-9999)
lsm_lat_indices_from_lat, lsm_lon_indices_from_lat = \
np.where((lsm_lat_array >= (YMin - 2*lsm_dy)) &
(lsm_lat_array <= (YMax + 2*lsm_dy)))
lsm_lat_indices_from_lon, lsm_lon_indices_from_lon = \
np.where((lsm_lon_array >= (XMin - 2*lsm_dx)) &
(lsm_lon_array <= (XMax + 2*lsm_dx)))
lsm_lat_indices = np.intersect1d(lsm_lat_indices_from_lat,
lsm_lat_indices_from_lon)
lsm_lon_indices = np.intersect1d(lsm_lon_indices_from_lat,
lsm_lon_indices_from_lon)
lsm_lat_list = \
lsm_lat_array[lsm_lat_indices, :][:, lsm_lon_indices]
lsm_lon_list = \
lsm_lon_array[lsm_lat_indices, :][:, lsm_lon_indices]
# Create a list of geographic coordinate pairs
for i in range(len(lsm_lat_indices)):
for j in range(len(lsm_lon_indices)):
ptList.append([lsm_lon_list[i][j], lsm_lat_list[i][j]])
elif lsm_lat_array.ndim == 1 and lsm_lon_array.ndim == 1:
# generate point list with 1D lat lon lists
if extent:
Ybuffer = 2 * abs(lsm_lat_array[0]-lsm_lat_array[1])
Xbuffer = 2 * abs(lsm_lon_array[0]-lsm_lon_array[1])
# Extract the lat and lon within buffered extent
# (buffer with 2* interval degree)
lsm_lat_list = lsm_lat_array[(lsm_lat_array >= (YMin - Ybuffer)) &
(lsm_lat_array <= (YMax + Ybuffer))]
lsm_lon_list = lsm_lon_array[(lsm_lon_array >= (XMin - Xbuffer)) &
(lsm_lon_array <= (XMax + Xbuffer))]
# Create a list of geographic coordinate pairs
for ptX in lsm_lon_list:
for ptY in lsm_lat_list:
ptList.append([ptX, ptY])
else:
raise IndexError("Lat/Lon lists have invalid dimensions. "
"Only 1D or 2D arrays allowed ...")
if len(ptList) <= 0:
raise IndexError("The watershed is outside of the bounds of the"
" land surface model grid ...")
return np.array(ptList) | [
"def",
"_get_voronoi_centroid_array",
"(",
"lsm_lat_array",
",",
"lsm_lon_array",
",",
"extent",
")",
":",
"YMin",
"=",
"extent",
"[",
"2",
"]",
"YMax",
"=",
"extent",
"[",
"3",
"]",
"XMin",
"=",
"extent",
"[",
"0",
"]",
"XMax",
"=",
"extent",
"[",
"1"... | This function generates a voronoi centroid point
list from arrays of latitude and longitude | [
"This",
"function",
"generates",
"a",
"voronoi",
"centroid",
"point",
"list",
"from",
"arrays",
"of",
"latitude",
"and",
"longitude"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/voronoi.py#L19-L86 | train | 33,266 |
erdc/RAPIDpy | RAPIDpy/gis/voronoi.py | _get_voronoi_poly_points | def _get_voronoi_poly_points(vert_index_list, voronoi_vertices,
voronoi_centroid):
"""
This function returns the corner points for a
polygon from scipy voronoi information
"""
voronoi_poly_points = []
if -1 not in vert_index_list and len(vert_index_list) > 3:
voronoi_poly_points = voronoi_vertices[vert_index_list]
elif vert_index_list.size > 0:
# ASSUME RECTANGLE
vert_index_list = vert_index_list[vert_index_list >= 0]
voronoi_poly_points = voronoi_vertices[vert_index_list]
# CASE 1: 2 valid voronoi vertices
if vert_index_list.size == 2:
center_lon = voronoi_centroid[0]
center_lat = voronoi_centroid[1]
corner_lon1 = voronoi_poly_points[0][0]
corner_lat1 = voronoi_poly_points[0][1]
corner_lon2 = voronoi_poly_points[1][0]
corner_lat2 = voronoi_poly_points[1][1]
# check if need to add points in lon or lat
if abs(corner_lon1-corner_lon2) > abs(corner_lat1-corner_lat2):
dLat = center_lat - corner_lat1
# append the corners in order
voronoi_poly_points = np.array([
[corner_lon1, corner_lat1],
[corner_lon2, corner_lat2],
[corner_lon2, center_lat + dLat],
[corner_lon1, center_lat + dLat]
])
else:
dLon = center_lon - corner_lon1
# append the corners in order
voronoi_poly_points = np.array([
[corner_lon1, corner_lat1],
[corner_lon2, corner_lat2],
[center_lon + dLon, corner_lat2],
[center_lon + dLon, corner_lat1]
])
# CASE 2: 1 valid voronoi vertex
elif vert_index_list.size == 1:
center_lon = voronoi_centroid[0]
center_lat = voronoi_centroid[1]
corner_lon = voronoi_poly_points[0][0]
corner_lat = voronoi_poly_points[0][1]
dLat = center_lat - corner_lat
dLon = center_lon - corner_lon
# append the corners in order
voronoi_poly_points = np.array([
[corner_lon, corner_lat],
[center_lon + dLon, corner_lat],
[center_lon + dLon, center_lat + dLat],
[corner_lon, center_lat + dLat]
])
return voronoi_poly_points | python | def _get_voronoi_poly_points(vert_index_list, voronoi_vertices,
voronoi_centroid):
"""
This function returns the corner points for a
polygon from scipy voronoi information
"""
voronoi_poly_points = []
if -1 not in vert_index_list and len(vert_index_list) > 3:
voronoi_poly_points = voronoi_vertices[vert_index_list]
elif vert_index_list.size > 0:
# ASSUME RECTANGLE
vert_index_list = vert_index_list[vert_index_list >= 0]
voronoi_poly_points = voronoi_vertices[vert_index_list]
# CASE 1: 2 valid voronoi vertices
if vert_index_list.size == 2:
center_lon = voronoi_centroid[0]
center_lat = voronoi_centroid[1]
corner_lon1 = voronoi_poly_points[0][0]
corner_lat1 = voronoi_poly_points[0][1]
corner_lon2 = voronoi_poly_points[1][0]
corner_lat2 = voronoi_poly_points[1][1]
# check if need to add points in lon or lat
if abs(corner_lon1-corner_lon2) > abs(corner_lat1-corner_lat2):
dLat = center_lat - corner_lat1
# append the corners in order
voronoi_poly_points = np.array([
[corner_lon1, corner_lat1],
[corner_lon2, corner_lat2],
[corner_lon2, center_lat + dLat],
[corner_lon1, center_lat + dLat]
])
else:
dLon = center_lon - corner_lon1
# append the corners in order
voronoi_poly_points = np.array([
[corner_lon1, corner_lat1],
[corner_lon2, corner_lat2],
[center_lon + dLon, corner_lat2],
[center_lon + dLon, corner_lat1]
])
# CASE 2: 1 valid voronoi vertex
elif vert_index_list.size == 1:
center_lon = voronoi_centroid[0]
center_lat = voronoi_centroid[1]
corner_lon = voronoi_poly_points[0][0]
corner_lat = voronoi_poly_points[0][1]
dLat = center_lat - corner_lat
dLon = center_lon - corner_lon
# append the corners in order
voronoi_poly_points = np.array([
[corner_lon, corner_lat],
[center_lon + dLon, corner_lat],
[center_lon + dLon, center_lat + dLat],
[corner_lon, center_lat + dLat]
])
return voronoi_poly_points | [
"def",
"_get_voronoi_poly_points",
"(",
"vert_index_list",
",",
"voronoi_vertices",
",",
"voronoi_centroid",
")",
":",
"voronoi_poly_points",
"=",
"[",
"]",
"if",
"-",
"1",
"not",
"in",
"vert_index_list",
"and",
"len",
"(",
"vert_index_list",
")",
">",
"3",
":",... | This function returns the corner points for a
polygon from scipy voronoi information | [
"This",
"function",
"returns",
"the",
"corner",
"points",
"for",
"a",
"polygon",
"from",
"scipy",
"voronoi",
"information"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/voronoi.py#L89-L146 | train | 33,267 |
erdc/RAPIDpy | RAPIDpy/gis/voronoi.py | pointsToVoronoiGridShapefile | def pointsToVoronoiGridShapefile(lat, lon, vor_shp_path, extent=None):
"""
Converts points to shapefile grid via voronoi
"""
voronoi_centroids = _get_voronoi_centroid_array(lat, lon, extent)
# set-up output polygon shp
log("Creating output polygon shp {0}"
.format(os.path.basename(vor_shp_path)))
if os.path.exists(vor_shp_path):
os.remove(vor_shp_path)
drv = ogr.GetDriverByName('ESRI Shapefile')
outShp = drv.CreateDataSource(vor_shp_path)
osr_geographic_proj = osr.SpatialReference()
osr_geographic_proj.ImportFromEPSG(4326)
layer = outShp.CreateLayer('', osr_geographic_proj, ogr.wkbPolygon)
layer.CreateField(ogr.FieldDefn('GRID_LAT', ogr.OFTReal))
layer.CreateField(ogr.FieldDefn('GRID_LON', ogr.OFTReal))
layerDefn = layer.GetLayerDefn()
# find nodes surrounding polygon centroid
# sort nodes in counterclockwise order
# create polygon perimeter through nodes
log("Building Voronoi polygons...")
# compute voronoi
voronoi_manager = Voronoi(voronoi_centroids)
voronoi_vertices = voronoi_manager.vertices
voronoi_regions = voronoi_manager.regions
for point_id, region_index in enumerate(voronoi_manager.point_region):
vert_index_list = np.array(voronoi_regions[region_index])
voronoi_centroid = voronoi_centroids[point_id]
voronoi_poly_points = _get_voronoi_poly_points(vert_index_list,
voronoi_vertices,
voronoi_centroid)
if len(voronoi_poly_points) == 4:
poly = ogr.Geometry(ogr.wkbPolygon)
ring = ogr.Geometry(ogr.wkbLinearRing)
for node in voronoi_poly_points:
ring.AddPoint(node[0], node[1])
# grab first node to close ring
ring.AddPoint(voronoi_poly_points[0][0], voronoi_poly_points[0][1])
poly.AddGeometry(ring)
feat = ogr.Feature(layerDefn)
feat.SetField('GRID_LON', float(voronoi_centroid[0]))
feat.SetField('GRID_LAT', float(voronoi_centroid[1]))
feat.SetGeometry(poly)
layer.CreateFeature(feat) | python | def pointsToVoronoiGridShapefile(lat, lon, vor_shp_path, extent=None):
"""
Converts points to shapefile grid via voronoi
"""
voronoi_centroids = _get_voronoi_centroid_array(lat, lon, extent)
# set-up output polygon shp
log("Creating output polygon shp {0}"
.format(os.path.basename(vor_shp_path)))
if os.path.exists(vor_shp_path):
os.remove(vor_shp_path)
drv = ogr.GetDriverByName('ESRI Shapefile')
outShp = drv.CreateDataSource(vor_shp_path)
osr_geographic_proj = osr.SpatialReference()
osr_geographic_proj.ImportFromEPSG(4326)
layer = outShp.CreateLayer('', osr_geographic_proj, ogr.wkbPolygon)
layer.CreateField(ogr.FieldDefn('GRID_LAT', ogr.OFTReal))
layer.CreateField(ogr.FieldDefn('GRID_LON', ogr.OFTReal))
layerDefn = layer.GetLayerDefn()
# find nodes surrounding polygon centroid
# sort nodes in counterclockwise order
# create polygon perimeter through nodes
log("Building Voronoi polygons...")
# compute voronoi
voronoi_manager = Voronoi(voronoi_centroids)
voronoi_vertices = voronoi_manager.vertices
voronoi_regions = voronoi_manager.regions
for point_id, region_index in enumerate(voronoi_manager.point_region):
vert_index_list = np.array(voronoi_regions[region_index])
voronoi_centroid = voronoi_centroids[point_id]
voronoi_poly_points = _get_voronoi_poly_points(vert_index_list,
voronoi_vertices,
voronoi_centroid)
if len(voronoi_poly_points) == 4:
poly = ogr.Geometry(ogr.wkbPolygon)
ring = ogr.Geometry(ogr.wkbLinearRing)
for node in voronoi_poly_points:
ring.AddPoint(node[0], node[1])
# grab first node to close ring
ring.AddPoint(voronoi_poly_points[0][0], voronoi_poly_points[0][1])
poly.AddGeometry(ring)
feat = ogr.Feature(layerDefn)
feat.SetField('GRID_LON', float(voronoi_centroid[0]))
feat.SetField('GRID_LAT', float(voronoi_centroid[1]))
feat.SetGeometry(poly)
layer.CreateFeature(feat) | [
"def",
"pointsToVoronoiGridShapefile",
"(",
"lat",
",",
"lon",
",",
"vor_shp_path",
",",
"extent",
"=",
"None",
")",
":",
"voronoi_centroids",
"=",
"_get_voronoi_centroid_array",
"(",
"lat",
",",
"lon",
",",
"extent",
")",
"# set-up output polygon shp",
"log",
"("... | Converts points to shapefile grid via voronoi | [
"Converts",
"points",
"to",
"shapefile",
"grid",
"via",
"voronoi"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/voronoi.py#L149-L197 | train | 33,268 |
erdc/RAPIDpy | RAPIDpy/gis/voronoi.py | pointsToVoronoiGridArray | def pointsToVoronoiGridArray(lat, lon, extent=None):
"""
Converts points to grid array via voronoi
"""
voronoi_centroids = _get_voronoi_centroid_array(lat, lon, extent)
# find nodes surrounding polygon centroid
# sort nodes in counterclockwise order
# create polygon perimeter through nodes
log("Building Voronoi polygons...")
# compute voronoi
voronoi_manager = Voronoi(voronoi_centroids)
voronoi_vertices = voronoi_manager.vertices
voronoi_regions = voronoi_manager.regions
feature_list = []
for point_id, region_index in enumerate(voronoi_manager.point_region):
vert_index_list = np.array(voronoi_regions[region_index])
voronoi_centroid = voronoi_centroids[point_id]
voronoi_poly_points = _get_voronoi_poly_points(vert_index_list,
voronoi_vertices,
voronoi_centroid)
if len(voronoi_poly_points) == 4:
feature_list.append({'polygon': Polygon(voronoi_poly_points),
'lon': voronoi_centroid[0],
'lat': voronoi_centroid[1]})
return feature_list | python | def pointsToVoronoiGridArray(lat, lon, extent=None):
"""
Converts points to grid array via voronoi
"""
voronoi_centroids = _get_voronoi_centroid_array(lat, lon, extent)
# find nodes surrounding polygon centroid
# sort nodes in counterclockwise order
# create polygon perimeter through nodes
log("Building Voronoi polygons...")
# compute voronoi
voronoi_manager = Voronoi(voronoi_centroids)
voronoi_vertices = voronoi_manager.vertices
voronoi_regions = voronoi_manager.regions
feature_list = []
for point_id, region_index in enumerate(voronoi_manager.point_region):
vert_index_list = np.array(voronoi_regions[region_index])
voronoi_centroid = voronoi_centroids[point_id]
voronoi_poly_points = _get_voronoi_poly_points(vert_index_list,
voronoi_vertices,
voronoi_centroid)
if len(voronoi_poly_points) == 4:
feature_list.append({'polygon': Polygon(voronoi_poly_points),
'lon': voronoi_centroid[0],
'lat': voronoi_centroid[1]})
return feature_list | [
"def",
"pointsToVoronoiGridArray",
"(",
"lat",
",",
"lon",
",",
"extent",
"=",
"None",
")",
":",
"voronoi_centroids",
"=",
"_get_voronoi_centroid_array",
"(",
"lat",
",",
"lon",
",",
"extent",
")",
"# find nodes surrounding polygon centroid",
"# sort nodes in counterclo... | Converts points to grid array via voronoi | [
"Converts",
"points",
"to",
"grid",
"array",
"via",
"voronoi"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/voronoi.py#L200-L226 | train | 33,269 |
erdc/RAPIDpy | RAPIDpy/postprocess/merge.py | ConvertRAPIDOutputToCF._generate_time_values | def _generate_time_values(self):
"""
Generates time values for out nc file
"""
# Populate time values
log('writing times', 'INFO')
d1970 = datetime(1970, 1, 1, tzinfo=utc)
time_array = [[int((self.start_datetime - d1970).total_seconds())]]
datetime_nc_start_simulation = self.start_datetime
for raw_nc_index, raw_nc in enumerate(self.raw_nc_list):
raw_nc_time = raw_nc.get_time_array(
datetime_simulation_start=datetime_nc_start_simulation,
simulation_time_step_seconds=self.time_step_array[
raw_nc_index])
time_array.append(raw_nc_time)
datetime_nc_start_simulation = \
datetime.utcfromtimestamp(raw_nc_time[-1])
self.cf_nc.variables['time'][:] = np.concatenate(time_array)
end_date = datetime.utcfromtimestamp(self.cf_nc.variables['time'][-1])
self.cf_nc.time_coverage_start = self.start_datetime.isoformat() + 'Z'
self.cf_nc.time_coverage_end = end_date.isoformat() + 'Z' | python | def _generate_time_values(self):
"""
Generates time values for out nc file
"""
# Populate time values
log('writing times', 'INFO')
d1970 = datetime(1970, 1, 1, tzinfo=utc)
time_array = [[int((self.start_datetime - d1970).total_seconds())]]
datetime_nc_start_simulation = self.start_datetime
for raw_nc_index, raw_nc in enumerate(self.raw_nc_list):
raw_nc_time = raw_nc.get_time_array(
datetime_simulation_start=datetime_nc_start_simulation,
simulation_time_step_seconds=self.time_step_array[
raw_nc_index])
time_array.append(raw_nc_time)
datetime_nc_start_simulation = \
datetime.utcfromtimestamp(raw_nc_time[-1])
self.cf_nc.variables['time'][:] = np.concatenate(time_array)
end_date = datetime.utcfromtimestamp(self.cf_nc.variables['time'][-1])
self.cf_nc.time_coverage_start = self.start_datetime.isoformat() + 'Z'
self.cf_nc.time_coverage_end = end_date.isoformat() + 'Z' | [
"def",
"_generate_time_values",
"(",
"self",
")",
":",
"# Populate time values\r",
"log",
"(",
"'writing times'",
",",
"'INFO'",
")",
"d1970",
"=",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"utc",
")",
"time_array",
"=",
"[",
"[",
... | Generates time values for out nc file | [
"Generates",
"time",
"values",
"for",
"out",
"nc",
"file"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/postprocess/merge.py#L401-L424 | train | 33,270 |
erdc/RAPIDpy | RAPIDpy/postprocess/merge.py | ConvertRAPIDOutputToCF.convert | def convert(self):
"""
Copies data from RAPID netCDF output to a CF-compliant netCDF file.
"""
try:
log('Processing %s ...' % self.rapid_output_file_list[0])
time_start_conversion = datetime.utcnow()
# Validate the raw netCDF file
log('validating input netCDF file', 'INFO')
id_len, time_len = self._validate_raw_nc()
# Initialize the output file (create dimensions and variables)
log('initializing output', 'INFO')
self._initialize_output(time_len, id_len)
self._generate_time_values()
# copy river ids over
self.cf_nc.variables[self.output_id_dim_name][:] = \
self.raw_nc_list[0].get_river_id_array()
# Populate comid, lat, lon, z
log('writing comid lat lon z')
lookup_start = datetime.now()
self._write_comid_lat_lon_z()
duration = str((datetime.now() - lookup_start).total_seconds())
log('Lookup Duration (s): ' + duration)
# Create a variable for streamflow. This is big, and slows down
# previous steps if we do it earlier.
self._copy_streamflow_values()
# close files
for raw_nc in self.raw_nc_list:
raw_nc.close()
self.cf_nc.close()
# delete original RAPID output
remove_files(*self.rapid_output_file_list)
# rename nc compliant file to original name
os.rename(self.cf_compliant_file, self.rapid_output_file_list[0])
log('Time to process %s' %
(datetime.utcnow()-time_start_conversion))
except Exception:
# delete cf RAPID output
remove_files(self.cf_compliant_file)
raise | python | def convert(self):
"""
Copies data from RAPID netCDF output to a CF-compliant netCDF file.
"""
try:
log('Processing %s ...' % self.rapid_output_file_list[0])
time_start_conversion = datetime.utcnow()
# Validate the raw netCDF file
log('validating input netCDF file', 'INFO')
id_len, time_len = self._validate_raw_nc()
# Initialize the output file (create dimensions and variables)
log('initializing output', 'INFO')
self._initialize_output(time_len, id_len)
self._generate_time_values()
# copy river ids over
self.cf_nc.variables[self.output_id_dim_name][:] = \
self.raw_nc_list[0].get_river_id_array()
# Populate comid, lat, lon, z
log('writing comid lat lon z')
lookup_start = datetime.now()
self._write_comid_lat_lon_z()
duration = str((datetime.now() - lookup_start).total_seconds())
log('Lookup Duration (s): ' + duration)
# Create a variable for streamflow. This is big, and slows down
# previous steps if we do it earlier.
self._copy_streamflow_values()
# close files
for raw_nc in self.raw_nc_list:
raw_nc.close()
self.cf_nc.close()
# delete original RAPID output
remove_files(*self.rapid_output_file_list)
# rename nc compliant file to original name
os.rename(self.cf_compliant_file, self.rapid_output_file_list[0])
log('Time to process %s' %
(datetime.utcnow()-time_start_conversion))
except Exception:
# delete cf RAPID output
remove_files(self.cf_compliant_file)
raise | [
"def",
"convert",
"(",
"self",
")",
":",
"try",
":",
"log",
"(",
"'Processing %s ...'",
"%",
"self",
".",
"rapid_output_file_list",
"[",
"0",
"]",
")",
"time_start_conversion",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"# Validate the raw netCDF file\r",
"log",
... | Copies data from RAPID netCDF output to a CF-compliant netCDF file. | [
"Copies",
"data",
"from",
"RAPID",
"netCDF",
"output",
"to",
"a",
"CF",
"-",
"compliant",
"netCDF",
"file",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/postprocess/merge.py#L495-L543 | train | 33,271 |
erdc/RAPIDpy | RAPIDpy/gis/muskingum.py | CreateMuskingumKFile | def CreateMuskingumKFile(lambda_k,
in_kfac_file,
out_k_file):
"""
Creates muskingum k file from kfac file.
Parameters
----------
lambda_k: float
The value for lambda given from RAPID after the calibration process.
If no calibration has been performed, 0.35 is reasonable.
in_kfac_file: str
The path to the input kfac file.
out_k_file: str
The path to the output k file.
Example::
from RAPIDpy.gis.muskingum import CreateMuskingumKFile
CreateMuskingumKFile(
lambda_k=0.35,
in_kfac_file='/path/to/kfac.csv',
out_k_file='/path/to/k.csv')
"""
kfac_table = csv_to_list(in_kfac_file)
with open_csv(out_k_file, 'w') as kfile:
k_writer = csv_writer(kfile)
for row in kfac_table:
k_writer.writerow([lambda_k * float(row[0])]) | python | def CreateMuskingumKFile(lambda_k,
in_kfac_file,
out_k_file):
"""
Creates muskingum k file from kfac file.
Parameters
----------
lambda_k: float
The value for lambda given from RAPID after the calibration process.
If no calibration has been performed, 0.35 is reasonable.
in_kfac_file: str
The path to the input kfac file.
out_k_file: str
The path to the output k file.
Example::
from RAPIDpy.gis.muskingum import CreateMuskingumKFile
CreateMuskingumKFile(
lambda_k=0.35,
in_kfac_file='/path/to/kfac.csv',
out_k_file='/path/to/k.csv')
"""
kfac_table = csv_to_list(in_kfac_file)
with open_csv(out_k_file, 'w') as kfile:
k_writer = csv_writer(kfile)
for row in kfac_table:
k_writer.writerow([lambda_k * float(row[0])]) | [
"def",
"CreateMuskingumKFile",
"(",
"lambda_k",
",",
"in_kfac_file",
",",
"out_k_file",
")",
":",
"kfac_table",
"=",
"csv_to_list",
"(",
"in_kfac_file",
")",
"with",
"open_csv",
"(",
"out_k_file",
",",
"'w'",
")",
"as",
"kfile",
":",
"k_writer",
"=",
"csv_writ... | Creates muskingum k file from kfac file.
Parameters
----------
lambda_k: float
The value for lambda given from RAPID after the calibration process.
If no calibration has been performed, 0.35 is reasonable.
in_kfac_file: str
The path to the input kfac file.
out_k_file: str
The path to the output k file.
Example::
from RAPIDpy.gis.muskingum import CreateMuskingumKFile
CreateMuskingumKFile(
lambda_k=0.35,
in_kfac_file='/path/to/kfac.csv',
out_k_file='/path/to/k.csv') | [
"Creates",
"muskingum",
"k",
"file",
"from",
"kfac",
"file",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/muskingum.py#L227-L259 | train | 33,272 |
erdc/RAPIDpy | RAPIDpy/gis/muskingum.py | CreateMuskingumXFileFromDranageLine | def CreateMuskingumXFileFromDranageLine(in_drainage_line,
x_id,
out_x_file,
file_geodatabase=None):
"""
Create muskingum X file from drainage line.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
x_id: str
The name of the muksingum X field (i.e. 'Musk_x').
out_x_file: str
The path to the output x file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.muskingum import CreateMuskingumXFileFromDranageLine
CreateMuskingumXFileFromDranageLine(
in_drainage_line='/path/to/drainageline.shp',
x_id='Musk_x',
out_x_file='/path/to/x.csv')
"""
ogr_drainage_line_shapefile_lyr, ogr_drainage_line_shapefile = \
open_shapefile(in_drainage_line, file_geodatabase)
with open_csv(out_x_file, 'w') as kfile:
x_writer = csv_writer(kfile)
for drainage_line_feature in ogr_drainage_line_shapefile_lyr:
x_writer.writerow([drainage_line_feature.GetField(x_id)])
del ogr_drainage_line_shapefile | python | def CreateMuskingumXFileFromDranageLine(in_drainage_line,
x_id,
out_x_file,
file_geodatabase=None):
"""
Create muskingum X file from drainage line.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
x_id: str
The name of the muksingum X field (i.e. 'Musk_x').
out_x_file: str
The path to the output x file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.muskingum import CreateMuskingumXFileFromDranageLine
CreateMuskingumXFileFromDranageLine(
in_drainage_line='/path/to/drainageline.shp',
x_id='Musk_x',
out_x_file='/path/to/x.csv')
"""
ogr_drainage_line_shapefile_lyr, ogr_drainage_line_shapefile = \
open_shapefile(in_drainage_line, file_geodatabase)
with open_csv(out_x_file, 'w') as kfile:
x_writer = csv_writer(kfile)
for drainage_line_feature in ogr_drainage_line_shapefile_lyr:
x_writer.writerow([drainage_line_feature.GetField(x_id)])
del ogr_drainage_line_shapefile | [
"def",
"CreateMuskingumXFileFromDranageLine",
"(",
"in_drainage_line",
",",
"x_id",
",",
"out_x_file",
",",
"file_geodatabase",
"=",
"None",
")",
":",
"ogr_drainage_line_shapefile_lyr",
",",
"ogr_drainage_line_shapefile",
"=",
"open_shapefile",
"(",
"in_drainage_line",
",",... | Create muskingum X file from drainage line.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
x_id: str
The name of the muksingum X field (i.e. 'Musk_x').
out_x_file: str
The path to the output x file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.muskingum import CreateMuskingumXFileFromDranageLine
CreateMuskingumXFileFromDranageLine(
in_drainage_line='/path/to/drainageline.shp',
x_id='Musk_x',
out_x_file='/path/to/x.csv') | [
"Create",
"muskingum",
"X",
"file",
"from",
"drainage",
"line",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/muskingum.py#L262-L301 | train | 33,273 |
erdc/RAPIDpy | RAPIDpy/gis/muskingum.py | CreateConstMuskingumXFile | def CreateConstMuskingumXFile(x_value,
in_connectivity_file,
out_x_file):
"""
Create muskingum X file from value that is constant all the way through
for each river segment.
Parameters
----------
x_value: float
Value for the muskingum X parameter [0-0.5].
in_connectivity_file: str
The path to the RAPID connectivity file.
out_x_file: str
The path to the output x file.
Example::
from RAPIDpy.gis.muskingum import CreateConstMuskingumXFile
CreateConstMuskingumXFile(
x_value=0.3,
in_connectivity_file='/path/to/rapid_connect.csv',
out_x_file='/path/to/x.csv')
"""
num_rivers = 0
with open_csv(in_connectivity_file, "r") as csvfile:
reader = csv_reader(csvfile)
for _ in reader:
num_rivers += 1
with open_csv(out_x_file, 'w') as kfile:
x_writer = csv_writer(kfile)
for _ in xrange(num_rivers):
x_writer.writerow([x_value]) | python | def CreateConstMuskingumXFile(x_value,
in_connectivity_file,
out_x_file):
"""
Create muskingum X file from value that is constant all the way through
for each river segment.
Parameters
----------
x_value: float
Value for the muskingum X parameter [0-0.5].
in_connectivity_file: str
The path to the RAPID connectivity file.
out_x_file: str
The path to the output x file.
Example::
from RAPIDpy.gis.muskingum import CreateConstMuskingumXFile
CreateConstMuskingumXFile(
x_value=0.3,
in_connectivity_file='/path/to/rapid_connect.csv',
out_x_file='/path/to/x.csv')
"""
num_rivers = 0
with open_csv(in_connectivity_file, "r") as csvfile:
reader = csv_reader(csvfile)
for _ in reader:
num_rivers += 1
with open_csv(out_x_file, 'w') as kfile:
x_writer = csv_writer(kfile)
for _ in xrange(num_rivers):
x_writer.writerow([x_value]) | [
"def",
"CreateConstMuskingumXFile",
"(",
"x_value",
",",
"in_connectivity_file",
",",
"out_x_file",
")",
":",
"num_rivers",
"=",
"0",
"with",
"open_csv",
"(",
"in_connectivity_file",
",",
"\"r\"",
")",
"as",
"csvfile",
":",
"reader",
"=",
"csv_reader",
"(",
"csv... | Create muskingum X file from value that is constant all the way through
for each river segment.
Parameters
----------
x_value: float
Value for the muskingum X parameter [0-0.5].
in_connectivity_file: str
The path to the RAPID connectivity file.
out_x_file: str
The path to the output x file.
Example::
from RAPIDpy.gis.muskingum import CreateConstMuskingumXFile
CreateConstMuskingumXFile(
x_value=0.3,
in_connectivity_file='/path/to/rapid_connect.csv',
out_x_file='/path/to/x.csv') | [
"Create",
"muskingum",
"X",
"file",
"from",
"value",
"that",
"is",
"constant",
"all",
"the",
"way",
"through",
"for",
"each",
"river",
"segment",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/muskingum.py#L304-L340 | train | 33,274 |
erdc/RAPIDpy | RAPIDpy/gis/network.py | StreamIDNextDownIDToConnectivity | def StreamIDNextDownIDToConnectivity(stream_id_array,
next_down_id_array,
out_csv_file):
"""
Creates RAPID connect file from stream_id array and next down id array
"""
list_all = []
max_count_upstream = 0
for hydroid in np.sort(stream_id_array):
# find the HydroID of the upstreams
list_upstreamID = stream_id_array[next_down_id_array == hydroid]
# count the total number of the upstreams
count_upstream = len(list_upstreamID)
if count_upstream > max_count_upstream:
max_count_upstream = count_upstream
nextDownID = next_down_id_array[stream_id_array == hydroid][0]
# append the list of Stream HydroID, NextDownID, Count of Upstream ID,
# and HydroID of each Upstream into a larger list
list_all.append(
np.concatenate(
[np.array([hydroid, nextDownID, count_upstream]),
list_upstreamID]
).astype(int))
with open_csv(out_csv_file, 'w') as csvfile:
connectwriter = csv_writer(csvfile)
for row_list in list_all:
out = np.concatenate([
row_list,
np.array([0 for _ in xrange(max_count_upstream - row_list[2])])
])
connectwriter.writerow(out.astype(int)) | python | def StreamIDNextDownIDToConnectivity(stream_id_array,
next_down_id_array,
out_csv_file):
"""
Creates RAPID connect file from stream_id array and next down id array
"""
list_all = []
max_count_upstream = 0
for hydroid in np.sort(stream_id_array):
# find the HydroID of the upstreams
list_upstreamID = stream_id_array[next_down_id_array == hydroid]
# count the total number of the upstreams
count_upstream = len(list_upstreamID)
if count_upstream > max_count_upstream:
max_count_upstream = count_upstream
nextDownID = next_down_id_array[stream_id_array == hydroid][0]
# append the list of Stream HydroID, NextDownID, Count of Upstream ID,
# and HydroID of each Upstream into a larger list
list_all.append(
np.concatenate(
[np.array([hydroid, nextDownID, count_upstream]),
list_upstreamID]
).astype(int))
with open_csv(out_csv_file, 'w') as csvfile:
connectwriter = csv_writer(csvfile)
for row_list in list_all:
out = np.concatenate([
row_list,
np.array([0 for _ in xrange(max_count_upstream - row_list[2])])
])
connectwriter.writerow(out.astype(int)) | [
"def",
"StreamIDNextDownIDToConnectivity",
"(",
"stream_id_array",
",",
"next_down_id_array",
",",
"out_csv_file",
")",
":",
"list_all",
"=",
"[",
"]",
"max_count_upstream",
"=",
"0",
"for",
"hydroid",
"in",
"np",
".",
"sort",
"(",
"stream_id_array",
")",
":",
"... | Creates RAPID connect file from stream_id array and next down id array | [
"Creates",
"RAPID",
"connect",
"file",
"from",
"stream_id",
"array",
"and",
"next",
"down",
"id",
"array"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/network.py#L25-L57 | train | 33,275 |
erdc/RAPIDpy | RAPIDpy/gis/network.py | CreateNetworkConnectivity | def CreateNetworkConnectivity(in_drainage_line,
river_id,
next_down_id,
out_connectivity_file,
file_geodatabase=None):
"""
Creates Network Connectivity input CSV file for RAPID
based on the Drainage Line shapefile with river ID and
next downstream ID fields.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
river_id: str
The name of the field with the river ID
(Ex. 'HydroID', 'COMID', or 'LINKNO').
next_down_id: str
The name of the field with the river ID of the next downstream
river segment (Ex. 'NextDownID' or 'DSLINKNO').
out_connectivity_file: str
The path to the output connectivity file.
file_geodatabase
Path to the file geodatabase. If you use this option, in_drainage_line
is the name of the stream network feature class.
(WARNING: Not always stable with GDAL.)
Example::
from RAPIDpy.gis.network import CreateNetworkConnectivity
CreateNetworkConnectivity(
in_drainage_line='/path/to/drainageline.shp',
river_id='LINKNO',
next_down_id='DSLINKNO',
out_connectivity_file='/path/to/rapid_connect.csv')
"""
ogr_drainage_line_shapefile_lyr, ogr_drainage_line_shapefile = \
open_shapefile(in_drainage_line, file_geodatabase)
stream_id_array = []
next_down_id_array = []
for drainage_line_feature in ogr_drainage_line_shapefile_lyr:
stream_id_array.append(drainage_line_feature.GetField(river_id))
next_down_id_array.append(drainage_line_feature.GetField(next_down_id))
stream_id_array = np.array(stream_id_array, dtype=np.int32)
next_down_id_array = np.array(next_down_id_array, dtype=np.int32)
StreamIDNextDownIDToConnectivity(stream_id_array,
next_down_id_array,
out_connectivity_file)
del ogr_drainage_line_shapefile | python | def CreateNetworkConnectivity(in_drainage_line,
river_id,
next_down_id,
out_connectivity_file,
file_geodatabase=None):
"""
Creates Network Connectivity input CSV file for RAPID
based on the Drainage Line shapefile with river ID and
next downstream ID fields.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
river_id: str
The name of the field with the river ID
(Ex. 'HydroID', 'COMID', or 'LINKNO').
next_down_id: str
The name of the field with the river ID of the next downstream
river segment (Ex. 'NextDownID' or 'DSLINKNO').
out_connectivity_file: str
The path to the output connectivity file.
file_geodatabase
Path to the file geodatabase. If you use this option, in_drainage_line
is the name of the stream network feature class.
(WARNING: Not always stable with GDAL.)
Example::
from RAPIDpy.gis.network import CreateNetworkConnectivity
CreateNetworkConnectivity(
in_drainage_line='/path/to/drainageline.shp',
river_id='LINKNO',
next_down_id='DSLINKNO',
out_connectivity_file='/path/to/rapid_connect.csv')
"""
ogr_drainage_line_shapefile_lyr, ogr_drainage_line_shapefile = \
open_shapefile(in_drainage_line, file_geodatabase)
stream_id_array = []
next_down_id_array = []
for drainage_line_feature in ogr_drainage_line_shapefile_lyr:
stream_id_array.append(drainage_line_feature.GetField(river_id))
next_down_id_array.append(drainage_line_feature.GetField(next_down_id))
stream_id_array = np.array(stream_id_array, dtype=np.int32)
next_down_id_array = np.array(next_down_id_array, dtype=np.int32)
StreamIDNextDownIDToConnectivity(stream_id_array,
next_down_id_array,
out_connectivity_file)
del ogr_drainage_line_shapefile | [
"def",
"CreateNetworkConnectivity",
"(",
"in_drainage_line",
",",
"river_id",
",",
"next_down_id",
",",
"out_connectivity_file",
",",
"file_geodatabase",
"=",
"None",
")",
":",
"ogr_drainage_line_shapefile_lyr",
",",
"ogr_drainage_line_shapefile",
"=",
"open_shapefile",
"("... | Creates Network Connectivity input CSV file for RAPID
based on the Drainage Line shapefile with river ID and
next downstream ID fields.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
river_id: str
The name of the field with the river ID
(Ex. 'HydroID', 'COMID', or 'LINKNO').
next_down_id: str
The name of the field with the river ID of the next downstream
river segment (Ex. 'NextDownID' or 'DSLINKNO').
out_connectivity_file: str
The path to the output connectivity file.
file_geodatabase
Path to the file geodatabase. If you use this option, in_drainage_line
is the name of the stream network feature class.
(WARNING: Not always stable with GDAL.)
Example::
from RAPIDpy.gis.network import CreateNetworkConnectivity
CreateNetworkConnectivity(
in_drainage_line='/path/to/drainageline.shp',
river_id='LINKNO',
next_down_id='DSLINKNO',
out_connectivity_file='/path/to/rapid_connect.csv') | [
"Creates",
"Network",
"Connectivity",
"input",
"CSV",
"file",
"for",
"RAPID",
"based",
"on",
"the",
"Drainage",
"Line",
"shapefile",
"with",
"river",
"ID",
"and",
"next",
"downstream",
"ID",
"fields",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/network.py#L60-L115 | train | 33,276 |
erdc/RAPIDpy | RAPIDpy/gis/network.py | CreateNetworkConnectivityTauDEMTree | def CreateNetworkConnectivityTauDEMTree(network_connectivity_tree_file,
out_csv_file):
"""
Creates Network Connectivity input CSV file for RAPID
based on the TauDEM network connectivity tree file
"""
stream_id_array = []
next_down_id_array = []
with open_csv(network_connectivity_tree_file, "r") as csvfile:
for row in csvfile:
split_row = row.split()
# link number
stream_id_array.append(split_row[0].strip())
# next downstream link number
next_down_id_array.append(split_row[3].strip())
stream_id_array = np.array(stream_id_array, dtype=np.int32)
next_down_id_array = np.array(next_down_id_array, dtype=np.int32)
StreamIDNextDownIDToConnectivity(stream_id_array,
next_down_id_array,
out_csv_file) | python | def CreateNetworkConnectivityTauDEMTree(network_connectivity_tree_file,
out_csv_file):
"""
Creates Network Connectivity input CSV file for RAPID
based on the TauDEM network connectivity tree file
"""
stream_id_array = []
next_down_id_array = []
with open_csv(network_connectivity_tree_file, "r") as csvfile:
for row in csvfile:
split_row = row.split()
# link number
stream_id_array.append(split_row[0].strip())
# next downstream link number
next_down_id_array.append(split_row[3].strip())
stream_id_array = np.array(stream_id_array, dtype=np.int32)
next_down_id_array = np.array(next_down_id_array, dtype=np.int32)
StreamIDNextDownIDToConnectivity(stream_id_array,
next_down_id_array,
out_csv_file) | [
"def",
"CreateNetworkConnectivityTauDEMTree",
"(",
"network_connectivity_tree_file",
",",
"out_csv_file",
")",
":",
"stream_id_array",
"=",
"[",
"]",
"next_down_id_array",
"=",
"[",
"]",
"with",
"open_csv",
"(",
"network_connectivity_tree_file",
",",
"\"r\"",
")",
"as",... | Creates Network Connectivity input CSV file for RAPID
based on the TauDEM network connectivity tree file | [
"Creates",
"Network",
"Connectivity",
"input",
"CSV",
"file",
"for",
"RAPID",
"based",
"on",
"the",
"TauDEM",
"network",
"connectivity",
"tree",
"file"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/network.py#L118-L139 | train | 33,277 |
erdc/RAPIDpy | RAPIDpy/gis/network.py | CreateNetworkConnectivityNHDPlus | def CreateNetworkConnectivityNHDPlus(in_drainage_line,
out_connectivity_file,
file_geodatabase=None):
"""
Creates Network Connectivity input CSV file for RAPID
based on the NHDPlus drainage lines with
COMID, FROMNODE, TONODE, and DIVERGENCE fields.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
out_connectivity_file: str
The path to the output connectivity file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.network import CreateNetworkConnectivityNHDPlus
CreateNetworkConnectivityNHDPlus(
in_drainage_line='/path/to/drainageline.shp',
out_connectivity_file='/path/to/rapid_connect.csv')
"""
ogr_drainage_line_shapefile_lyr, ogr_drainage_line_shapefile = \
open_shapefile(in_drainage_line, file_geodatabase)
ogr_drainage_line_definition = \
ogr_drainage_line_shapefile_lyr.GetLayerDefn()
orig_field_names = []
for idx in xrange(ogr_drainage_line_definition.GetFieldCount()):
orig_field_names.append(
ogr_drainage_line_definition.GetFieldDefn(idx).GetName())
upper_field_names = [field.upper() for field in orig_field_names]
def get_field_name_index(upper_field_name, _upper_field_names):
"""
returns index of field name
"""
try:
return _upper_field_names.index(upper_field_name)
except ValueError:
raise IndexError("{0} not found in shapefile .."
.format(_upper_field_names))
rivid_field = \
orig_field_names[get_field_name_index('COMID', upper_field_names)]
fromnode_field = \
orig_field_names[get_field_name_index('FROMNODE', upper_field_names)]
tonode_field = \
orig_field_names[get_field_name_index('TONODE', upper_field_names)]
divergence_field =\
orig_field_names[get_field_name_index('DIVERGENCE', upper_field_names)]
number_of_features = ogr_drainage_line_shapefile_lyr.GetFeatureCount()
rivid_list = np.zeros(number_of_features, dtype=np.int32)
fromnode_list = np.zeros(number_of_features, dtype=np.int32)
tonode_list = np.zeros(number_of_features, dtype=np.int32)
divergence_list = np.zeros(number_of_features, dtype=np.int32)
for feature_idx, catchment_feature in \
enumerate(ogr_drainage_line_shapefile_lyr):
rivid_list[feature_idx] = catchment_feature.GetField(rivid_field)
fromnode_list[feature_idx] = catchment_feature.GetField(fromnode_field)
tonode_list[feature_idx] = catchment_feature.GetField(tonode_field)
divergence_list[feature_idx] = \
catchment_feature.GetField(divergence_field)
del ogr_drainage_line_shapefile
# -------------------------------------------------------------------------
# Compute connectivity, based on:
# https://github.com/c-h-david/rrr/blob/master/src/rrr_riv_tot_gen_all_nhdplus.py
# -------------------------------------------------------------------------
fromnode_list[fromnode_list == 0] = -9999
# Some NHDPlus v1 reaches have FLOWDIR='With Digitized'
# but no info in VAA table
fromnode_list[divergence_list == 2] = -9999
# Virtually disconnect the upstream node of all minor divergences
del divergence_list # delete information in list
next_down_id_list = np.zeros(number_of_features, dtype=np.int32)
for rivid_index in xrange(len(rivid_list)):
try:
next_down_id_list[rivid_index] = \
rivid_list[
np.where(fromnode_list == tonode_list[rivid_index])[0][0]]
except IndexError:
# this is an outlet
next_down_id_list[rivid_index] = -1
# determine the downstream reach for each reach
# empty unecessary lists
del fromnode_list
del tonode_list
StreamIDNextDownIDToConnectivity(rivid_list,
next_down_id_list,
out_connectivity_file) | python | def CreateNetworkConnectivityNHDPlus(in_drainage_line,
out_connectivity_file,
file_geodatabase=None):
"""
Creates Network Connectivity input CSV file for RAPID
based on the NHDPlus drainage lines with
COMID, FROMNODE, TONODE, and DIVERGENCE fields.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
out_connectivity_file: str
The path to the output connectivity file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.network import CreateNetworkConnectivityNHDPlus
CreateNetworkConnectivityNHDPlus(
in_drainage_line='/path/to/drainageline.shp',
out_connectivity_file='/path/to/rapid_connect.csv')
"""
ogr_drainage_line_shapefile_lyr, ogr_drainage_line_shapefile = \
open_shapefile(in_drainage_line, file_geodatabase)
ogr_drainage_line_definition = \
ogr_drainage_line_shapefile_lyr.GetLayerDefn()
orig_field_names = []
for idx in xrange(ogr_drainage_line_definition.GetFieldCount()):
orig_field_names.append(
ogr_drainage_line_definition.GetFieldDefn(idx).GetName())
upper_field_names = [field.upper() for field in orig_field_names]
def get_field_name_index(upper_field_name, _upper_field_names):
"""
returns index of field name
"""
try:
return _upper_field_names.index(upper_field_name)
except ValueError:
raise IndexError("{0} not found in shapefile .."
.format(_upper_field_names))
rivid_field = \
orig_field_names[get_field_name_index('COMID', upper_field_names)]
fromnode_field = \
orig_field_names[get_field_name_index('FROMNODE', upper_field_names)]
tonode_field = \
orig_field_names[get_field_name_index('TONODE', upper_field_names)]
divergence_field =\
orig_field_names[get_field_name_index('DIVERGENCE', upper_field_names)]
number_of_features = ogr_drainage_line_shapefile_lyr.GetFeatureCount()
rivid_list = np.zeros(number_of_features, dtype=np.int32)
fromnode_list = np.zeros(number_of_features, dtype=np.int32)
tonode_list = np.zeros(number_of_features, dtype=np.int32)
divergence_list = np.zeros(number_of_features, dtype=np.int32)
for feature_idx, catchment_feature in \
enumerate(ogr_drainage_line_shapefile_lyr):
rivid_list[feature_idx] = catchment_feature.GetField(rivid_field)
fromnode_list[feature_idx] = catchment_feature.GetField(fromnode_field)
tonode_list[feature_idx] = catchment_feature.GetField(tonode_field)
divergence_list[feature_idx] = \
catchment_feature.GetField(divergence_field)
del ogr_drainage_line_shapefile
# -------------------------------------------------------------------------
# Compute connectivity, based on:
# https://github.com/c-h-david/rrr/blob/master/src/rrr_riv_tot_gen_all_nhdplus.py
# -------------------------------------------------------------------------
fromnode_list[fromnode_list == 0] = -9999
# Some NHDPlus v1 reaches have FLOWDIR='With Digitized'
# but no info in VAA table
fromnode_list[divergence_list == 2] = -9999
# Virtually disconnect the upstream node of all minor divergences
del divergence_list # delete information in list
next_down_id_list = np.zeros(number_of_features, dtype=np.int32)
for rivid_index in xrange(len(rivid_list)):
try:
next_down_id_list[rivid_index] = \
rivid_list[
np.where(fromnode_list == tonode_list[rivid_index])[0][0]]
except IndexError:
# this is an outlet
next_down_id_list[rivid_index] = -1
# determine the downstream reach for each reach
# empty unecessary lists
del fromnode_list
del tonode_list
StreamIDNextDownIDToConnectivity(rivid_list,
next_down_id_list,
out_connectivity_file) | [
"def",
"CreateNetworkConnectivityNHDPlus",
"(",
"in_drainage_line",
",",
"out_connectivity_file",
",",
"file_geodatabase",
"=",
"None",
")",
":",
"ogr_drainage_line_shapefile_lyr",
",",
"ogr_drainage_line_shapefile",
"=",
"open_shapefile",
"(",
"in_drainage_line",
",",
"file_... | Creates Network Connectivity input CSV file for RAPID
based on the NHDPlus drainage lines with
COMID, FROMNODE, TONODE, and DIVERGENCE fields.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
out_connectivity_file: str
The path to the output connectivity file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.network import CreateNetworkConnectivityNHDPlus
CreateNetworkConnectivityNHDPlus(
in_drainage_line='/path/to/drainageline.shp',
out_connectivity_file='/path/to/rapid_connect.csv') | [
"Creates",
"Network",
"Connectivity",
"input",
"CSV",
"file",
"for",
"RAPID",
"based",
"on",
"the",
"NHDPlus",
"drainage",
"lines",
"with",
"COMID",
"FROMNODE",
"TONODE",
"and",
"DIVERGENCE",
"fields",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/network.py#L142-L247 | train | 33,278 |
erdc/RAPIDpy | RAPIDpy/gis/network.py | CreateSubsetFile | def CreateSubsetFile(in_drainage_line,
river_id,
out_riv_bas_id_file,
file_geodatabase=None):
"""
Creates River Basin ID subset input CSV file for RAPID
based on the Drainage Line shapefile with river ID and
next downstream ID fields
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
river_id: str
The name of the field with the river ID
(Ex. 'HydroID', 'COMID', or 'LINKNO').
out_riv_bas_id_file: str
The path to the output river basin ID subset file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.network import CreateSubsetFile
CreateSubsetFile(
in_drainage_line='/path/to/drainageline.shp',
river_id='LINKNO',
out_riv_bas_id_file='/path/to/riv_bas_id.csv')
"""
ogr_drainage_line_shapefile_lyr, ogr_drainage_line_shapefile = \
open_shapefile(in_drainage_line, file_geodatabase)
ogr_drainage_line_definition = \
ogr_drainage_line_shapefile_lyr.GetLayerDefn()
orig_field_names = []
for idx in xrange(ogr_drainage_line_definition.GetFieldCount()):
orig_field_names.append(
ogr_drainage_line_definition.GetFieldDefn(idx).GetName())
upper_field_names = [field.upper() for field in orig_field_names]
sort_field = None
# Sort by HYDROSEQ order if the option exists
if 'HYDROSEQ' in upper_field_names:
# with this method, smaller is downstream
sort_field = orig_field_names[upper_field_names.index('HYDROSEQ')]
log("Sorting by {0}".format(sort_field))
hydroseq_list = []
hydroid_list = []
# The script line below makes sure that rows in the subset file are
# arranged in descending order of NextDownID of stream segements
for drainage_line_feature in ogr_drainage_line_shapefile_lyr:
hydroid_list.append(drainage_line_feature.GetField(river_id))
if sort_field:
hydroseq_list.append(drainage_line_feature.GetField(sort_field))
del ogr_drainage_line_shapefile
hydroid_list = np.array(hydroid_list, dtype=np.int32)
if hydroseq_list:
hydroseq_list = np.array(hydroseq_list, dtype=np.int32)
sort_order = hydroseq_list.argsort()[::-1]
hydroid_list = hydroid_list[sort_order]
else:
hydroid_list = np.sort(hydroid_list)
with open_csv(out_riv_bas_id_file, 'w') as csvfile:
connectwriter = csv_writer(csvfile)
for hydroid in hydroid_list:
connectwriter.writerow([hydroid]) | python | def CreateSubsetFile(in_drainage_line,
river_id,
out_riv_bas_id_file,
file_geodatabase=None):
"""
Creates River Basin ID subset input CSV file for RAPID
based on the Drainage Line shapefile with river ID and
next downstream ID fields
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
river_id: str
The name of the field with the river ID
(Ex. 'HydroID', 'COMID', or 'LINKNO').
out_riv_bas_id_file: str
The path to the output river basin ID subset file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.network import CreateSubsetFile
CreateSubsetFile(
in_drainage_line='/path/to/drainageline.shp',
river_id='LINKNO',
out_riv_bas_id_file='/path/to/riv_bas_id.csv')
"""
ogr_drainage_line_shapefile_lyr, ogr_drainage_line_shapefile = \
open_shapefile(in_drainage_line, file_geodatabase)
ogr_drainage_line_definition = \
ogr_drainage_line_shapefile_lyr.GetLayerDefn()
orig_field_names = []
for idx in xrange(ogr_drainage_line_definition.GetFieldCount()):
orig_field_names.append(
ogr_drainage_line_definition.GetFieldDefn(idx).GetName())
upper_field_names = [field.upper() for field in orig_field_names]
sort_field = None
# Sort by HYDROSEQ order if the option exists
if 'HYDROSEQ' in upper_field_names:
# with this method, smaller is downstream
sort_field = orig_field_names[upper_field_names.index('HYDROSEQ')]
log("Sorting by {0}".format(sort_field))
hydroseq_list = []
hydroid_list = []
# The script line below makes sure that rows in the subset file are
# arranged in descending order of NextDownID of stream segements
for drainage_line_feature in ogr_drainage_line_shapefile_lyr:
hydroid_list.append(drainage_line_feature.GetField(river_id))
if sort_field:
hydroseq_list.append(drainage_line_feature.GetField(sort_field))
del ogr_drainage_line_shapefile
hydroid_list = np.array(hydroid_list, dtype=np.int32)
if hydroseq_list:
hydroseq_list = np.array(hydroseq_list, dtype=np.int32)
sort_order = hydroseq_list.argsort()[::-1]
hydroid_list = hydroid_list[sort_order]
else:
hydroid_list = np.sort(hydroid_list)
with open_csv(out_riv_bas_id_file, 'w') as csvfile:
connectwriter = csv_writer(csvfile)
for hydroid in hydroid_list:
connectwriter.writerow([hydroid]) | [
"def",
"CreateSubsetFile",
"(",
"in_drainage_line",
",",
"river_id",
",",
"out_riv_bas_id_file",
",",
"file_geodatabase",
"=",
"None",
")",
":",
"ogr_drainage_line_shapefile_lyr",
",",
"ogr_drainage_line_shapefile",
"=",
"open_shapefile",
"(",
"in_drainage_line",
",",
"fi... | Creates River Basin ID subset input CSV file for RAPID
based on the Drainage Line shapefile with river ID and
next downstream ID fields
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
river_id: str
The name of the field with the river ID
(Ex. 'HydroID', 'COMID', or 'LINKNO').
out_riv_bas_id_file: str
The path to the output river basin ID subset file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.network import CreateSubsetFile
CreateSubsetFile(
in_drainage_line='/path/to/drainageline.shp',
river_id='LINKNO',
out_riv_bas_id_file='/path/to/riv_bas_id.csv') | [
"Creates",
"River",
"Basin",
"ID",
"subset",
"input",
"CSV",
"file",
"for",
"RAPID",
"based",
"on",
"the",
"Drainage",
"Line",
"shapefile",
"with",
"river",
"ID",
"and",
"next",
"downstream",
"ID",
"fields"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/network.py#L250-L326 | train | 33,279 |
erdc/RAPIDpy | RAPIDpy/gis/workflow.py | CreateAllStaticECMWFFiles | def CreateAllStaticECMWFFiles(in_catchment,
catchment_river_id,
rapid_output_folder,
rapid_connect_file,
file_geodatabase=None
):
"""
This creates all of the ECMWF grid weight tables using an area
weighted method based on Esri's RAPID_Toolbox.
Parameters
----------
in_catchment: str
Path to the Catchment shapefile.
catchment_river_id: str
The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').
rapid_output_folder: str
The path to the folder where all of the RAPID output will be generated.
rapid_connect_file: str
The path to the RAPID connectivity file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class.
(WARNING: Not always stable with GDAL.)
Example::
from RAPIDpy.gis.workflow import CreateAllStaticECMWFFiles
CreateAllStaticECMWFFiles(
in_catchment="/path/to/catchment.shp",
catchment_river_id="DrainLnID",
rapid_output_folder="/path/to/rapid/output",
rapid_connect_file="/path/to/rapid_connect.csv",
)
"""
lsm_grid_folder = \
os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lsm_grids')
# create from ECMWF high reslution grid
ecmwf_t1279_grid_file = \
os.path.join(lsm_grid_folder, 'runoff_ecmwf_t1279_grid.nc')
weight_ecmwf_t1279_file = \
os.path.join(rapid_output_folder, 'weight_ecmwf_t1279.csv')
CreateWeightTableECMWF(ecmwf_t1279_grid_file,
in_catchment,
catchment_river_id,
rapid_connect_file,
weight_ecmwf_t1279_file,
file_geodatabase=file_geodatabase)
# create from ECMWF low reslution grid
ecmwf_tco639_grid_file = \
os.path.join(lsm_grid_folder, 'runoff_ecmwf_tco639_grid.nc')
weight_ecmwf_tco639_file = \
os.path.join(rapid_output_folder, 'weight_ecmwf_tco639.csv')
CreateWeightTableECMWF(ecmwf_tco639_grid_file,
in_catchment,
catchment_river_id,
rapid_connect_file,
weight_ecmwf_tco639_file,
file_geodatabase=file_geodatabase)
# create from ERA Interim grid
era_t511_grid_file = \
os.path.join(lsm_grid_folder, 'runoff_era_t511_grid.nc')
weight_era_t511_file = \
os.path.join(rapid_output_folder, 'weight_era_t511.csv')
CreateWeightTableECMWF(era_t511_grid_file,
in_catchment,
catchment_river_id,
rapid_connect_file,
weight_era_t511_file,
file_geodatabase=file_geodatabase) | python | def CreateAllStaticECMWFFiles(in_catchment,
catchment_river_id,
rapid_output_folder,
rapid_connect_file,
file_geodatabase=None
):
"""
This creates all of the ECMWF grid weight tables using an area
weighted method based on Esri's RAPID_Toolbox.
Parameters
----------
in_catchment: str
Path to the Catchment shapefile.
catchment_river_id: str
The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').
rapid_output_folder: str
The path to the folder where all of the RAPID output will be generated.
rapid_connect_file: str
The path to the RAPID connectivity file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class.
(WARNING: Not always stable with GDAL.)
Example::
from RAPIDpy.gis.workflow import CreateAllStaticECMWFFiles
CreateAllStaticECMWFFiles(
in_catchment="/path/to/catchment.shp",
catchment_river_id="DrainLnID",
rapid_output_folder="/path/to/rapid/output",
rapid_connect_file="/path/to/rapid_connect.csv",
)
"""
lsm_grid_folder = \
os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lsm_grids')
# create from ECMWF high reslution grid
ecmwf_t1279_grid_file = \
os.path.join(lsm_grid_folder, 'runoff_ecmwf_t1279_grid.nc')
weight_ecmwf_t1279_file = \
os.path.join(rapid_output_folder, 'weight_ecmwf_t1279.csv')
CreateWeightTableECMWF(ecmwf_t1279_grid_file,
in_catchment,
catchment_river_id,
rapid_connect_file,
weight_ecmwf_t1279_file,
file_geodatabase=file_geodatabase)
# create from ECMWF low reslution grid
ecmwf_tco639_grid_file = \
os.path.join(lsm_grid_folder, 'runoff_ecmwf_tco639_grid.nc')
weight_ecmwf_tco639_file = \
os.path.join(rapid_output_folder, 'weight_ecmwf_tco639.csv')
CreateWeightTableECMWF(ecmwf_tco639_grid_file,
in_catchment,
catchment_river_id,
rapid_connect_file,
weight_ecmwf_tco639_file,
file_geodatabase=file_geodatabase)
# create from ERA Interim grid
era_t511_grid_file = \
os.path.join(lsm_grid_folder, 'runoff_era_t511_grid.nc')
weight_era_t511_file = \
os.path.join(rapid_output_folder, 'weight_era_t511.csv')
CreateWeightTableECMWF(era_t511_grid_file,
in_catchment,
catchment_river_id,
rapid_connect_file,
weight_era_t511_file,
file_geodatabase=file_geodatabase) | [
"def",
"CreateAllStaticECMWFFiles",
"(",
"in_catchment",
",",
"catchment_river_id",
",",
"rapid_output_folder",
",",
"rapid_connect_file",
",",
"file_geodatabase",
"=",
"None",
")",
":",
"lsm_grid_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path... | This creates all of the ECMWF grid weight tables using an area
weighted method based on Esri's RAPID_Toolbox.
Parameters
----------
in_catchment: str
Path to the Catchment shapefile.
catchment_river_id: str
The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').
rapid_output_folder: str
The path to the folder where all of the RAPID output will be generated.
rapid_connect_file: str
The path to the RAPID connectivity file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class.
(WARNING: Not always stable with GDAL.)
Example::
from RAPIDpy.gis.workflow import CreateAllStaticECMWFFiles
CreateAllStaticECMWFFiles(
in_catchment="/path/to/catchment.shp",
catchment_river_id="DrainLnID",
rapid_output_folder="/path/to/rapid/output",
rapid_connect_file="/path/to/rapid_connect.csv",
) | [
"This",
"creates",
"all",
"of",
"the",
"ECMWF",
"grid",
"weight",
"tables",
"using",
"an",
"area",
"weighted",
"method",
"based",
"on",
"Esri",
"s",
"RAPID_Toolbox",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/workflow.py#L151-L226 | train | 33,280 |
erdc/RAPIDpy | RAPIDpy/gis/workflow.py | CreateAllStaticECMWFRAPIDFiles | def CreateAllStaticECMWFRAPIDFiles(in_drainage_line,
river_id,
length_id,
slope_id,
next_down_id,
in_catchment,
catchment_river_id,
rapid_output_folder,
kfac_celerity=1000.0/3600.0,
kfac_formula_type=3,
kfac_length_units="km",
lambda_k=0.35,
x_value=0.3,
nhdplus=False,
taudem_network_connectivity_tree_file=None,
file_geodatabase=None):
"""
This creates all of the static RAPID files and ECMWF grid weight tables.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
river_id: str
The name of the field with the river ID
(Ex. 'HydroID', 'COMID', or 'LINKNO').
length_id: str
The field name containging the length of the river segment
(Ex. 'LENGTHKM' or 'Length').
slope_id: str
The field name containging the slope of the river segment
(Ex. 'Avg_Slope' or 'Slope').
next_down_id: str
The name of the field with the river ID of the next downstream
river segment (Ex. 'NextDownID' or 'DSLINKNO').
in_catchment: str
Path to the Catchment shapefile.
catchment_river_id: str
The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').
rapid_output_folder: str
The path to the folder where all of the RAPID output will be generated.
kfac_celerity: float, optional
The flow wave celerity for the watershed in meters per second.
1 km/hr or 1000.0/3600.0 m/s is a reasonable value if unknown.
kfac_formula_type: int, optional
An integer representing the formula type to use when calculating kfac.
Default is 3.
kfac_length_units: str, optional
The units for the length_id field. Supported types are "m" for meters
and "km" for kilometers. Default is "km".
lambda_k: float, optional
The value for lambda given from RAPID after the calibration process.
Default is 0.35.
x_value: float, optional
Value for the muskingum X parameter [0-0.5].Default is 0.3.
nhdplus: bool, optional
If True, the drainage line is from the NHDPlus dataset with the
VAA fields COMID, FROMNODE, TONODE, and DIVERGENCE. Default is False.
taudem_network_connectivity_tree_file: str, optional
If set, the connectivity file will be generated from the
TauDEM connectivity tree file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.workflow import CreateAllStaticECMWFRAPIDFiles
CreateAllStaticECMWFRAPIDFiles(
in_drainage_line="/path/to/drainage_line.shp",
river_id="HydroID",
length_id="LENGTHKM",
slope_id="SLOPE",
next_down_id="NextDownID",
in_catchment="/path/to/catchment.shp",
catchment_river_id="DrainLnID",
rapid_output_folder="/path/to/rapid/output",
)
"""
CreateAllStaticRAPIDFiles(in_drainage_line,
river_id,
length_id,
slope_id,
next_down_id,
rapid_output_folder,
kfac_celerity,
kfac_formula_type,
kfac_length_units,
lambda_k,
x_value,
nhdplus,
taudem_network_connectivity_tree_file,
file_geodatabase)
rapid_connect_file = os.path.join(rapid_output_folder, 'rapid_connect.csv')
CreateAllStaticECMWFFiles(in_catchment,
catchment_river_id,
rapid_output_folder,
rapid_connect_file,
file_geodatabase) | python | def CreateAllStaticECMWFRAPIDFiles(in_drainage_line,
river_id,
length_id,
slope_id,
next_down_id,
in_catchment,
catchment_river_id,
rapid_output_folder,
kfac_celerity=1000.0/3600.0,
kfac_formula_type=3,
kfac_length_units="km",
lambda_k=0.35,
x_value=0.3,
nhdplus=False,
taudem_network_connectivity_tree_file=None,
file_geodatabase=None):
"""
This creates all of the static RAPID files and ECMWF grid weight tables.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
river_id: str
The name of the field with the river ID
(Ex. 'HydroID', 'COMID', or 'LINKNO').
length_id: str
The field name containging the length of the river segment
(Ex. 'LENGTHKM' or 'Length').
slope_id: str
The field name containging the slope of the river segment
(Ex. 'Avg_Slope' or 'Slope').
next_down_id: str
The name of the field with the river ID of the next downstream
river segment (Ex. 'NextDownID' or 'DSLINKNO').
in_catchment: str
Path to the Catchment shapefile.
catchment_river_id: str
The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').
rapid_output_folder: str
The path to the folder where all of the RAPID output will be generated.
kfac_celerity: float, optional
The flow wave celerity for the watershed in meters per second.
1 km/hr or 1000.0/3600.0 m/s is a reasonable value if unknown.
kfac_formula_type: int, optional
An integer representing the formula type to use when calculating kfac.
Default is 3.
kfac_length_units: str, optional
The units for the length_id field. Supported types are "m" for meters
and "km" for kilometers. Default is "km".
lambda_k: float, optional
The value for lambda given from RAPID after the calibration process.
Default is 0.35.
x_value: float, optional
Value for the muskingum X parameter [0-0.5].Default is 0.3.
nhdplus: bool, optional
If True, the drainage line is from the NHDPlus dataset with the
VAA fields COMID, FROMNODE, TONODE, and DIVERGENCE. Default is False.
taudem_network_connectivity_tree_file: str, optional
If set, the connectivity file will be generated from the
TauDEM connectivity tree file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.workflow import CreateAllStaticECMWFRAPIDFiles
CreateAllStaticECMWFRAPIDFiles(
in_drainage_line="/path/to/drainage_line.shp",
river_id="HydroID",
length_id="LENGTHKM",
slope_id="SLOPE",
next_down_id="NextDownID",
in_catchment="/path/to/catchment.shp",
catchment_river_id="DrainLnID",
rapid_output_folder="/path/to/rapid/output",
)
"""
CreateAllStaticRAPIDFiles(in_drainage_line,
river_id,
length_id,
slope_id,
next_down_id,
rapid_output_folder,
kfac_celerity,
kfac_formula_type,
kfac_length_units,
lambda_k,
x_value,
nhdplus,
taudem_network_connectivity_tree_file,
file_geodatabase)
rapid_connect_file = os.path.join(rapid_output_folder, 'rapid_connect.csv')
CreateAllStaticECMWFFiles(in_catchment,
catchment_river_id,
rapid_output_folder,
rapid_connect_file,
file_geodatabase) | [
"def",
"CreateAllStaticECMWFRAPIDFiles",
"(",
"in_drainage_line",
",",
"river_id",
",",
"length_id",
",",
"slope_id",
",",
"next_down_id",
",",
"in_catchment",
",",
"catchment_river_id",
",",
"rapid_output_folder",
",",
"kfac_celerity",
"=",
"1000.0",
"/",
"3600.0",
"... | This creates all of the static RAPID files and ECMWF grid weight tables.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
river_id: str
The name of the field with the river ID
(Ex. 'HydroID', 'COMID', or 'LINKNO').
length_id: str
The field name containging the length of the river segment
(Ex. 'LENGTHKM' or 'Length').
slope_id: str
The field name containging the slope of the river segment
(Ex. 'Avg_Slope' or 'Slope').
next_down_id: str
The name of the field with the river ID of the next downstream
river segment (Ex. 'NextDownID' or 'DSLINKNO').
in_catchment: str
Path to the Catchment shapefile.
catchment_river_id: str
The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').
rapid_output_folder: str
The path to the folder where all of the RAPID output will be generated.
kfac_celerity: float, optional
The flow wave celerity for the watershed in meters per second.
1 km/hr or 1000.0/3600.0 m/s is a reasonable value if unknown.
kfac_formula_type: int, optional
An integer representing the formula type to use when calculating kfac.
Default is 3.
kfac_length_units: str, optional
The units for the length_id field. Supported types are "m" for meters
and "km" for kilometers. Default is "km".
lambda_k: float, optional
The value for lambda given from RAPID after the calibration process.
Default is 0.35.
x_value: float, optional
Value for the muskingum X parameter [0-0.5].Default is 0.3.
nhdplus: bool, optional
If True, the drainage line is from the NHDPlus dataset with the
VAA fields COMID, FROMNODE, TONODE, and DIVERGENCE. Default is False.
taudem_network_connectivity_tree_file: str, optional
If set, the connectivity file will be generated from the
TauDEM connectivity tree file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.workflow import CreateAllStaticECMWFRAPIDFiles
CreateAllStaticECMWFRAPIDFiles(
in_drainage_line="/path/to/drainage_line.shp",
river_id="HydroID",
length_id="LENGTHKM",
slope_id="SLOPE",
next_down_id="NextDownID",
in_catchment="/path/to/catchment.shp",
catchment_river_id="DrainLnID",
rapid_output_folder="/path/to/rapid/output",
) | [
"This",
"creates",
"all",
"of",
"the",
"static",
"RAPID",
"files",
"and",
"ECMWF",
"grid",
"weight",
"tables",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/workflow.py#L229-L332 | train | 33,281 |
erdc/RAPIDpy | RAPIDpy/dataset.py | compare_qout_files | def compare_qout_files(dataset1_path, dataset2_path):
"""
This function compares the output of RAPID Qout and tells you where
they are different.
"""
qout_same = False
d1 = RAPIDDataset(dataset1_path)
d2 = RAPIDDataset(dataset2_path)
if len(d1.get_river_id_array()) != len(d2.get_river_id_array()):
log("Length of COMID/rivid input not the same.",
"ERROR")
if not (d1.get_river_id_array() == d2.get_river_id_array()).all():
log("COMID/rivid order is different in each dataset."
" Reordering data for comparison.",
"WARNING")
d2_reordered_river_index_list = []
for rivid in d1.get_river_id_array():
reordered_index = np.where(d2.get_river_id_array() == rivid)[0][0]
d2_reordered_river_index_list.append(reordered_index)
d2_reordered_qout = d2.get_qout_index(d2_reordered_river_index_list)
else:
d2_reordered_qout = d2.get_qout()
# get where the files are different
d1_qout = d1.get_qout()
where_diff = np.where(d1_qout != d2_reordered_qout)
un_where_diff = np.unique(where_diff[0])
# if different, check to see how different
if un_where_diff.any():
decimal_test = 7
while decimal_test > 0:
try:
np.testing.assert_almost_equal(d1_qout,
d2_reordered_qout,
decimal=decimal_test)
log("ALMOST EQUAL to {0} decimal places.".format(decimal_test),
"INFO")
qout_same = True
decimal_test = -1
except AssertionError as ex:
if decimal_test <= 1:
log(ex, "WARNING")
decimal_test -= 1
log("Number of different timeseries: {0}".format(len(un_where_diff)),
"INFO")
log("COMID idexes where different: {0}".format(un_where_diff),
"INFO")
log("COMID idexes where different: {0}".format(un_where_diff),
"INFO")
index = un_where_diff[0]
log("Dataset 1 example. COMID index: "
"{0}".format(d1.get_qout_index(index)),
"INFO")
log("Dataset 2 example. COMID index: "
"{0}".format(d2_reordered_qout[index, :]),
"INFO")
else:
qout_same = True
log("Output Qout data is the same.",
"INFO")
d1.close()
d2.close()
return qout_same | python | def compare_qout_files(dataset1_path, dataset2_path):
"""
This function compares the output of RAPID Qout and tells you where
they are different.
"""
qout_same = False
d1 = RAPIDDataset(dataset1_path)
d2 = RAPIDDataset(dataset2_path)
if len(d1.get_river_id_array()) != len(d2.get_river_id_array()):
log("Length of COMID/rivid input not the same.",
"ERROR")
if not (d1.get_river_id_array() == d2.get_river_id_array()).all():
log("COMID/rivid order is different in each dataset."
" Reordering data for comparison.",
"WARNING")
d2_reordered_river_index_list = []
for rivid in d1.get_river_id_array():
reordered_index = np.where(d2.get_river_id_array() == rivid)[0][0]
d2_reordered_river_index_list.append(reordered_index)
d2_reordered_qout = d2.get_qout_index(d2_reordered_river_index_list)
else:
d2_reordered_qout = d2.get_qout()
# get where the files are different
d1_qout = d1.get_qout()
where_diff = np.where(d1_qout != d2_reordered_qout)
un_where_diff = np.unique(where_diff[0])
# if different, check to see how different
if un_where_diff.any():
decimal_test = 7
while decimal_test > 0:
try:
np.testing.assert_almost_equal(d1_qout,
d2_reordered_qout,
decimal=decimal_test)
log("ALMOST EQUAL to {0} decimal places.".format(decimal_test),
"INFO")
qout_same = True
decimal_test = -1
except AssertionError as ex:
if decimal_test <= 1:
log(ex, "WARNING")
decimal_test -= 1
log("Number of different timeseries: {0}".format(len(un_where_diff)),
"INFO")
log("COMID idexes where different: {0}".format(un_where_diff),
"INFO")
log("COMID idexes where different: {0}".format(un_where_diff),
"INFO")
index = un_where_diff[0]
log("Dataset 1 example. COMID index: "
"{0}".format(d1.get_qout_index(index)),
"INFO")
log("Dataset 2 example. COMID index: "
"{0}".format(d2_reordered_qout[index, :]),
"INFO")
else:
qout_same = True
log("Output Qout data is the same.",
"INFO")
d1.close()
d2.close()
return qout_same | [
"def",
"compare_qout_files",
"(",
"dataset1_path",
",",
"dataset2_path",
")",
":",
"qout_same",
"=",
"False",
"d1",
"=",
"RAPIDDataset",
"(",
"dataset1_path",
")",
"d2",
"=",
"RAPIDDataset",
"(",
"dataset2_path",
")",
"if",
"len",
"(",
"d1",
".",
"get_river_id... | This function compares the output of RAPID Qout and tells you where
they are different. | [
"This",
"function",
"compares",
"the",
"output",
"of",
"RAPID",
"Qout",
"and",
"tells",
"you",
"where",
"they",
"are",
"different",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/dataset.py#L25-L95 | train | 33,282 |
erdc/RAPIDpy | RAPIDpy/dataset.py | RAPIDDataset.is_time_variable_valid | def is_time_variable_valid(self):
"""
This function returns whether or not the time variable
is valid.
Returns
-------
boolean
True if the time variable is valid, otherwise false.
Example::
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
if qout_nc.is_time_variable_valid():
#DO WORK HERE
"""
# pylint: disable=len-as-condition
time_var_valid = False
if 'time' in self.qout_nc.variables.keys():
if len(self.qout_nc.dimensions['time']) > 0:
if not is_masked(self.qout_nc.variables['time'][:]):
try:
timestep = (datetime.datetime
.utcfromtimestamp(
self.qout_nc.variables['time'][1]
) -
datetime.datetime
.utcfromtimestamp(
self.qout_nc.variables['time'][0]
)).total_seconds()
if timestep > 0:
time_var_valid = True
except ValueError:
pass
return time_var_valid | python | def is_time_variable_valid(self):
"""
This function returns whether or not the time variable
is valid.
Returns
-------
boolean
True if the time variable is valid, otherwise false.
Example::
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
if qout_nc.is_time_variable_valid():
#DO WORK HERE
"""
# pylint: disable=len-as-condition
time_var_valid = False
if 'time' in self.qout_nc.variables.keys():
if len(self.qout_nc.dimensions['time']) > 0:
if not is_masked(self.qout_nc.variables['time'][:]):
try:
timestep = (datetime.datetime
.utcfromtimestamp(
self.qout_nc.variables['time'][1]
) -
datetime.datetime
.utcfromtimestamp(
self.qout_nc.variables['time'][0]
)).total_seconds()
if timestep > 0:
time_var_valid = True
except ValueError:
pass
return time_var_valid | [
"def",
"is_time_variable_valid",
"(",
"self",
")",
":",
"# pylint: disable=len-as-condition",
"time_var_valid",
"=",
"False",
"if",
"'time'",
"in",
"self",
".",
"qout_nc",
".",
"variables",
".",
"keys",
"(",
")",
":",
"if",
"len",
"(",
"self",
".",
"qout_nc",
... | This function returns whether or not the time variable
is valid.
Returns
-------
boolean
True if the time variable is valid, otherwise false.
Example::
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
if qout_nc.is_time_variable_valid():
#DO WORK HERE | [
"This",
"function",
"returns",
"whether",
"or",
"not",
"the",
"time",
"variable",
"is",
"valid",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/dataset.py#L248-L288 | train | 33,283 |
erdc/RAPIDpy | RAPIDpy/dataset.py | RAPIDDataset.get_time_array | def get_time_array(self,
datetime_simulation_start=None,
simulation_time_step_seconds=None,
return_datetime=False,
time_index_array=None):
"""
This method extracts or generates an array of time.
The new version of RAPID output has the time array stored.
However, the old version requires the user to know when the
simulation began and the time step of the output.
Parameters
----------
datetime_simulation_start: :obj:`datetime.datetime`, optional
The start datetime of the simulation. Only required if the time
variable is not included in the file.
simulation_time_step_seconds: int, optional
The time step of the file in seconds. Only required if the time
variable is not included in the file.
return_datetime: bool, optional
If true, it converts the data to a list of datetime objects.
Default is False.
time_index_array: list or :obj:`numpy.array`, optional
This is used to extract the datetime values by index from the main
list. This can be from the *get_time_index_range* function.
Returns
-------
list:
An array of integers representing seconds since Jan 1, 1970 UTC
or datetime objects if *return_datetime* is set to True.
These examples demonstrates how to retrieve or generate a time array
to go along with your RAPID streamflow series.
CF-Compliant Qout File Example:
.. code:: python
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
#retrieve integer timestamp array
time_array = qout_nc.get_time_array()
#or, to get datetime array
time_datetime = qout_nc.get_time_array(return_datetime=True)
Legacy Qout File Example:
.. code:: python
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout,
datetime_simulation_start=datetime(1980, 1, 1),
simulation_time_step_seconds=3 * 3600)\
as qout_nc:
#retrieve integer timestamp array
time_array = qout_nc.get_time_array()
#or, to get datetime array
time_datetime = qout_nc.get_time_array(return_datetime=True)
"""
# Original Qout file
if datetime_simulation_start is not None:
self.datetime_simulation_start = datetime_simulation_start
if simulation_time_step_seconds is not None:
self.simulation_time_step_seconds = simulation_time_step_seconds
epoch = datetime.datetime(1970, 1, 1, tzinfo=utc)
time_units = "seconds since {0}".format(epoch)
# CF-1.6 compliant file
if self.is_time_variable_valid():
time_array = self.qout_nc.variables['time'][:]
if self.qout_nc.variables['time'].units:
time_units = self.qout_nc.variables['time'].units
# Original Qout file
elif self._is_legacy_time_valid():
initial_time_seconds = ((self.datetime_simulation_start
.replace(tzinfo=utc) - epoch)
.total_seconds() +
self.simulation_time_step_seconds)
final_time_seconds = (initial_time_seconds +
self.size_time *
self.simulation_time_step_seconds)
time_array = np.arange(initial_time_seconds,
final_time_seconds,
self.simulation_time_step_seconds)
else:
raise ValueError("This file does not contain the time"
" variable. To get time array, add"
" datetime_simulation_start and"
" simulation_time_step_seconds")
if time_index_array is not None:
time_array = time_array[time_index_array]
if return_datetime:
time_array = num2date(time_array, time_units)
if self.out_tzinfo is not None:
for i in xrange(len(time_array)):
# convert time to output timezone
time_array[i] = utc.localize(time_array[i]) \
.astimezone(self.out_tzinfo) \
.replace(tzinfo=None)
return time_array | python | def get_time_array(self,
datetime_simulation_start=None,
simulation_time_step_seconds=None,
return_datetime=False,
time_index_array=None):
"""
This method extracts or generates an array of time.
The new version of RAPID output has the time array stored.
However, the old version requires the user to know when the
simulation began and the time step of the output.
Parameters
----------
datetime_simulation_start: :obj:`datetime.datetime`, optional
The start datetime of the simulation. Only required if the time
variable is not included in the file.
simulation_time_step_seconds: int, optional
The time step of the file in seconds. Only required if the time
variable is not included in the file.
return_datetime: bool, optional
If true, it converts the data to a list of datetime objects.
Default is False.
time_index_array: list or :obj:`numpy.array`, optional
This is used to extract the datetime values by index from the main
list. This can be from the *get_time_index_range* function.
Returns
-------
list:
An array of integers representing seconds since Jan 1, 1970 UTC
or datetime objects if *return_datetime* is set to True.
These examples demonstrates how to retrieve or generate a time array
to go along with your RAPID streamflow series.
CF-Compliant Qout File Example:
.. code:: python
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
#retrieve integer timestamp array
time_array = qout_nc.get_time_array()
#or, to get datetime array
time_datetime = qout_nc.get_time_array(return_datetime=True)
Legacy Qout File Example:
.. code:: python
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout,
datetime_simulation_start=datetime(1980, 1, 1),
simulation_time_step_seconds=3 * 3600)\
as qout_nc:
#retrieve integer timestamp array
time_array = qout_nc.get_time_array()
#or, to get datetime array
time_datetime = qout_nc.get_time_array(return_datetime=True)
"""
# Original Qout file
if datetime_simulation_start is not None:
self.datetime_simulation_start = datetime_simulation_start
if simulation_time_step_seconds is not None:
self.simulation_time_step_seconds = simulation_time_step_seconds
epoch = datetime.datetime(1970, 1, 1, tzinfo=utc)
time_units = "seconds since {0}".format(epoch)
# CF-1.6 compliant file
if self.is_time_variable_valid():
time_array = self.qout_nc.variables['time'][:]
if self.qout_nc.variables['time'].units:
time_units = self.qout_nc.variables['time'].units
# Original Qout file
elif self._is_legacy_time_valid():
initial_time_seconds = ((self.datetime_simulation_start
.replace(tzinfo=utc) - epoch)
.total_seconds() +
self.simulation_time_step_seconds)
final_time_seconds = (initial_time_seconds +
self.size_time *
self.simulation_time_step_seconds)
time_array = np.arange(initial_time_seconds,
final_time_seconds,
self.simulation_time_step_seconds)
else:
raise ValueError("This file does not contain the time"
" variable. To get time array, add"
" datetime_simulation_start and"
" simulation_time_step_seconds")
if time_index_array is not None:
time_array = time_array[time_index_array]
if return_datetime:
time_array = num2date(time_array, time_units)
if self.out_tzinfo is not None:
for i in xrange(len(time_array)):
# convert time to output timezone
time_array[i] = utc.localize(time_array[i]) \
.astimezone(self.out_tzinfo) \
.replace(tzinfo=None)
return time_array | [
"def",
"get_time_array",
"(",
"self",
",",
"datetime_simulation_start",
"=",
"None",
",",
"simulation_time_step_seconds",
"=",
"None",
",",
"return_datetime",
"=",
"False",
",",
"time_index_array",
"=",
"None",
")",
":",
"# Original Qout file",
"if",
"datetime_simulat... | This method extracts or generates an array of time.
The new version of RAPID output has the time array stored.
However, the old version requires the user to know when the
simulation began and the time step of the output.
Parameters
----------
datetime_simulation_start: :obj:`datetime.datetime`, optional
The start datetime of the simulation. Only required if the time
variable is not included in the file.
simulation_time_step_seconds: int, optional
The time step of the file in seconds. Only required if the time
variable is not included in the file.
return_datetime: bool, optional
If true, it converts the data to a list of datetime objects.
Default is False.
time_index_array: list or :obj:`numpy.array`, optional
This is used to extract the datetime values by index from the main
list. This can be from the *get_time_index_range* function.
Returns
-------
list:
An array of integers representing seconds since Jan 1, 1970 UTC
or datetime objects if *return_datetime* is set to True.
These examples demonstrates how to retrieve or generate a time array
to go along with your RAPID streamflow series.
CF-Compliant Qout File Example:
.. code:: python
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
#retrieve integer timestamp array
time_array = qout_nc.get_time_array()
#or, to get datetime array
time_datetime = qout_nc.get_time_array(return_datetime=True)
Legacy Qout File Example:
.. code:: python
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout,
datetime_simulation_start=datetime(1980, 1, 1),
simulation_time_step_seconds=3 * 3600)\
as qout_nc:
#retrieve integer timestamp array
time_array = qout_nc.get_time_array()
#or, to get datetime array
time_datetime = qout_nc.get_time_array(return_datetime=True) | [
"This",
"method",
"extracts",
"or",
"generates",
"an",
"array",
"of",
"time",
".",
"The",
"new",
"version",
"of",
"RAPID",
"output",
"has",
"the",
"time",
"array",
"stored",
".",
"However",
"the",
"old",
"version",
"requires",
"the",
"user",
"to",
"know",
... | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/dataset.py#L296-L412 | train | 33,284 |
erdc/RAPIDpy | RAPIDpy/dataset.py | RAPIDDataset.get_time_index_range | def get_time_index_range(self,
date_search_start=None,
date_search_end=None,
time_index_start=None,
time_index_end=None,
time_index=None):
"""
Generates a time index range based on time bounds given.
This is useful for subset data extraction.
Parameters
----------
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date for
starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date
for ending.
time_index_start: int, optional
This is the index of the start of the time array subset.
Useful for the old file version.
time_index_end: int, optional
This is the index of the end of the time array subset.
Useful for the old file version.
time_index: int, optional
This is the index of time to return in the case that your
code only wants one index. Used internally.
Returns
-------
:obj:`numpy.array`:
This is an array of time indices used to extract a subset of data.
CF-Compliant Qout File Example:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
time_index_range = qout_nc.get_time_index_range(
date_search_start=datetime(1980, 1, 1),
date_search_end=datetime(1980, 12, 11))
Legacy Qout File Example:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout,
datetime_simulation_start=datetime(1980, 1, 1),
simulation_time_step_seconds=3600) as qout_nc:
time_index_range = qout_nc.get_time_index_range(
date_search_start=datetime(1980, 1, 1),
date_search_end=datetime(1980, 12, 11))
"""
# get the range of time based on datetime range
time_range = None
if ((self.is_time_variable_valid() or self._is_legacy_time_valid()) and
(date_search_start is not None or
date_search_end is not None)):
log("Determining time range ({0} to {1})"
"...".format(date_search_start, date_search_end),
"INFO")
time_array = self.get_time_array()
if date_search_start is not None:
date_search_start_utc = date_search_start
if self.out_tzinfo is not None:
date_search_start_utc = self.out_tzinfo \
.localize(date_search_start) \
.astimezone(utc) \
.replace(tzinfo=None)
seconds_start = (date_search_start_utc -
datetime.datetime(1970, 1, 1)).total_seconds()
time_range = np.where(time_array >= seconds_start)[0]
if date_search_end is not None:
date_search_end_utc = date_search_end
if self.out_tzinfo is not None:
date_search_end_utc = self.out_tzinfo \
.localize(date_search_end) \
.astimezone(utc) \
.replace(tzinfo=None)
seconds_end = (date_search_end_utc -
datetime.datetime(1970, 1, 1)).total_seconds()
if time_range is not None:
time_range = np.intersect1d(time_range,
np.where(time_array <=
seconds_end)[0])
else:
time_range = np.where(time_array <= seconds_end)[0]
# get the range of time based on time index range
elif time_index_start is not None or time_index_end is not None:
if time_index_start is None:
time_index_start = 0
if time_index_end is None:
time_index_end = self.size_time
time_range = range(time_index_start, time_index_end)
# get only one time step
elif time_index is not None:
time_range = [time_index]
# return all
else:
time_range = range(self.size_time)
return time_range | python | def get_time_index_range(self,
date_search_start=None,
date_search_end=None,
time_index_start=None,
time_index_end=None,
time_index=None):
"""
Generates a time index range based on time bounds given.
This is useful for subset data extraction.
Parameters
----------
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date for
starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date
for ending.
time_index_start: int, optional
This is the index of the start of the time array subset.
Useful for the old file version.
time_index_end: int, optional
This is the index of the end of the time array subset.
Useful for the old file version.
time_index: int, optional
This is the index of time to return in the case that your
code only wants one index. Used internally.
Returns
-------
:obj:`numpy.array`:
This is an array of time indices used to extract a subset of data.
CF-Compliant Qout File Example:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
time_index_range = qout_nc.get_time_index_range(
date_search_start=datetime(1980, 1, 1),
date_search_end=datetime(1980, 12, 11))
Legacy Qout File Example:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout,
datetime_simulation_start=datetime(1980, 1, 1),
simulation_time_step_seconds=3600) as qout_nc:
time_index_range = qout_nc.get_time_index_range(
date_search_start=datetime(1980, 1, 1),
date_search_end=datetime(1980, 12, 11))
"""
# get the range of time based on datetime range
time_range = None
if ((self.is_time_variable_valid() or self._is_legacy_time_valid()) and
(date_search_start is not None or
date_search_end is not None)):
log("Determining time range ({0} to {1})"
"...".format(date_search_start, date_search_end),
"INFO")
time_array = self.get_time_array()
if date_search_start is not None:
date_search_start_utc = date_search_start
if self.out_tzinfo is not None:
date_search_start_utc = self.out_tzinfo \
.localize(date_search_start) \
.astimezone(utc) \
.replace(tzinfo=None)
seconds_start = (date_search_start_utc -
datetime.datetime(1970, 1, 1)).total_seconds()
time_range = np.where(time_array >= seconds_start)[0]
if date_search_end is not None:
date_search_end_utc = date_search_end
if self.out_tzinfo is not None:
date_search_end_utc = self.out_tzinfo \
.localize(date_search_end) \
.astimezone(utc) \
.replace(tzinfo=None)
seconds_end = (date_search_end_utc -
datetime.datetime(1970, 1, 1)).total_seconds()
if time_range is not None:
time_range = np.intersect1d(time_range,
np.where(time_array <=
seconds_end)[0])
else:
time_range = np.where(time_array <= seconds_end)[0]
# get the range of time based on time index range
elif time_index_start is not None or time_index_end is not None:
if time_index_start is None:
time_index_start = 0
if time_index_end is None:
time_index_end = self.size_time
time_range = range(time_index_start, time_index_end)
# get only one time step
elif time_index is not None:
time_range = [time_index]
# return all
else:
time_range = range(self.size_time)
return time_range | [
"def",
"get_time_index_range",
"(",
"self",
",",
"date_search_start",
"=",
"None",
",",
"date_search_end",
"=",
"None",
",",
"time_index_start",
"=",
"None",
",",
"time_index_end",
"=",
"None",
",",
"time_index",
"=",
"None",
")",
":",
"# get the range of time bas... | Generates a time index range based on time bounds given.
This is useful for subset data extraction.
Parameters
----------
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date for
starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date
for ending.
time_index_start: int, optional
This is the index of the start of the time array subset.
Useful for the old file version.
time_index_end: int, optional
This is the index of the end of the time array subset.
Useful for the old file version.
time_index: int, optional
This is the index of time to return in the case that your
code only wants one index. Used internally.
Returns
-------
:obj:`numpy.array`:
This is an array of time indices used to extract a subset of data.
CF-Compliant Qout File Example:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
time_index_range = qout_nc.get_time_index_range(
date_search_start=datetime(1980, 1, 1),
date_search_end=datetime(1980, 12, 11))
Legacy Qout File Example:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout,
datetime_simulation_start=datetime(1980, 1, 1),
simulation_time_step_seconds=3600) as qout_nc:
time_index_range = qout_nc.get_time_index_range(
date_search_start=datetime(1980, 1, 1),
date_search_end=datetime(1980, 12, 11)) | [
"Generates",
"a",
"time",
"index",
"range",
"based",
"on",
"time",
"bounds",
"given",
".",
"This",
"is",
"useful",
"for",
"subset",
"data",
"extraction",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/dataset.py#L414-L532 | train | 33,285 |
erdc/RAPIDpy | RAPIDpy/dataset.py | RAPIDDataset.get_river_index | def get_river_index(self, river_id):
"""
This method retrieves the river index in the netCDF
dataset corresponding to the river ID.
Parameters
----------
river_id: int
The ID of the river segment.
Returns
-------
int:
The index of the river ID's in the file.
Example::
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
river_id = 53458
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
river_index = qout_nc.get_river_index(river_id)
"""
try:
return np.where(self.get_river_id_array() == river_id)[0][0]
except IndexError:
raise IndexError("ERROR: River ID {0} not found in dataset "
"...".format(river_id)) | python | def get_river_index(self, river_id):
"""
This method retrieves the river index in the netCDF
dataset corresponding to the river ID.
Parameters
----------
river_id: int
The ID of the river segment.
Returns
-------
int:
The index of the river ID's in the file.
Example::
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
river_id = 53458
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
river_index = qout_nc.get_river_index(river_id)
"""
try:
return np.where(self.get_river_id_array() == river_id)[0][0]
except IndexError:
raise IndexError("ERROR: River ID {0} not found in dataset "
"...".format(river_id)) | [
"def",
"get_river_index",
"(",
"self",
",",
"river_id",
")",
":",
"try",
":",
"return",
"np",
".",
"where",
"(",
"self",
".",
"get_river_id_array",
"(",
")",
"==",
"river_id",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"... | This method retrieves the river index in the netCDF
dataset corresponding to the river ID.
Parameters
----------
river_id: int
The ID of the river segment.
Returns
-------
int:
The index of the river ID's in the file.
Example::
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
river_id = 53458
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
river_index = qout_nc.get_river_index(river_id) | [
"This",
"method",
"retrieves",
"the",
"river",
"index",
"in",
"the",
"netCDF",
"dataset",
"corresponding",
"to",
"the",
"river",
"ID",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/dataset.py#L555-L586 | train | 33,286 |
erdc/RAPIDpy | RAPIDpy/dataset.py | RAPIDDataset.get_subset_riverid_index_list | def get_subset_riverid_index_list(self, river_id_list):
"""
Gets the subset riverid_list from the netcdf file
Optional returns include the list of valid river ids in the dataset
as well as a list of missing rive rids
Parameters
----------
river_id_list: list or :obj:`numpy.array`
Array of river ID's for the river segments you want the index of.
Returns
-------
:obj:`numpy.array`
A sorted array of the river index in the NetCDF file that
were found.
:obj:`numpy.array`
A sorted array of the river IDs that were found.
list
An array of the missing river ids.
"""
netcdf_river_indices_list = []
valid_river_ids = []
missing_river_ids = []
for river_id in river_id_list:
# get where streamids are in netcdf file
try:
netcdf_river_indices_list \
.append(self.get_river_index(river_id))
valid_river_ids.append(river_id)
except IndexError:
log("ReachID {0} not found in netCDF dataset."
" Skipping ...".format(river_id),
"WARNING")
missing_river_ids.append(river_id)
np_valid_river_indices_list = np.array(netcdf_river_indices_list)
np_valid_river_ids = np.array(valid_river_ids)
sorted_indexes = np.argsort(np_valid_river_indices_list)
return(np_valid_river_indices_list[sorted_indexes],
np_valid_river_ids[sorted_indexes],
np.array(missing_river_ids)) | python | def get_subset_riverid_index_list(self, river_id_list):
"""
Gets the subset riverid_list from the netcdf file
Optional returns include the list of valid river ids in the dataset
as well as a list of missing rive rids
Parameters
----------
river_id_list: list or :obj:`numpy.array`
Array of river ID's for the river segments you want the index of.
Returns
-------
:obj:`numpy.array`
A sorted array of the river index in the NetCDF file that
were found.
:obj:`numpy.array`
A sorted array of the river IDs that were found.
list
An array of the missing river ids.
"""
netcdf_river_indices_list = []
valid_river_ids = []
missing_river_ids = []
for river_id in river_id_list:
# get where streamids are in netcdf file
try:
netcdf_river_indices_list \
.append(self.get_river_index(river_id))
valid_river_ids.append(river_id)
except IndexError:
log("ReachID {0} not found in netCDF dataset."
" Skipping ...".format(river_id),
"WARNING")
missing_river_ids.append(river_id)
np_valid_river_indices_list = np.array(netcdf_river_indices_list)
np_valid_river_ids = np.array(valid_river_ids)
sorted_indexes = np.argsort(np_valid_river_indices_list)
return(np_valid_river_indices_list[sorted_indexes],
np_valid_river_ids[sorted_indexes],
np.array(missing_river_ids)) | [
"def",
"get_subset_riverid_index_list",
"(",
"self",
",",
"river_id_list",
")",
":",
"netcdf_river_indices_list",
"=",
"[",
"]",
"valid_river_ids",
"=",
"[",
"]",
"missing_river_ids",
"=",
"[",
"]",
"for",
"river_id",
"in",
"river_id_list",
":",
"# get where streami... | Gets the subset riverid_list from the netcdf file
Optional returns include the list of valid river ids in the dataset
as well as a list of missing rive rids
Parameters
----------
river_id_list: list or :obj:`numpy.array`
Array of river ID's for the river segments you want the index of.
Returns
-------
:obj:`numpy.array`
A sorted array of the river index in the NetCDF file that
were found.
:obj:`numpy.array`
A sorted array of the river IDs that were found.
list
An array of the missing river ids. | [
"Gets",
"the",
"subset",
"riverid_list",
"from",
"the",
"netcdf",
"file",
"Optional",
"returns",
"include",
"the",
"list",
"of",
"valid",
"river",
"ids",
"in",
"the",
"dataset",
"as",
"well",
"as",
"a",
"list",
"of",
"missing",
"rive",
"rids"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/dataset.py#L588-L631 | train | 33,287 |
erdc/RAPIDpy | RAPIDpy/dataset.py | RAPIDDataset.get_qout | def get_qout(self,
river_id_array=None,
date_search_start=None,
date_search_end=None,
time_index_start=None,
time_index_end=None,
time_index=None,
time_index_array=None,
daily=False,
pd_filter=None,
filter_mode="mean",
as_dataframe=False):
"""
This method extracts streamflow data by a single river ID
or by a river ID array. It has options to extract by date
or by date index.
Parameters
----------
river_id_array: :obj:`numpy.array` or list or int, optional
A single river ID or an array of river IDs.
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date
for starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date
for ending.
time_index_start: int, optional
This is the index of the start of the time array subset.
Useful for the old file version.
time_index_end: int, optional
This is the index of the end of the time array subset.
Useful for the old file version.
time_index: int, optional
This is the index of time to return in the case that your
code only wants one index. Used internally.
time_index_array: list or :obj:`numpy.array`, optional
This is used to extract the vales only for particular dates.
This can be from the *get_time_index_range* function.
daily: bool, optional
If true, this will convert qout to daily average.
pd_filter: str, optional
This is a valid pandas resample frequency filter.
filter_mode: str, optional
You can get the daily average "mean" or the maximum "max".
Default is "mean".
as_dataframe: bool, optional
Return as a pandas dataframe object. Default is False.
Returns
-------
qout_array: :obj:`numpy.array`
This is a 1D or 2D array or a single value depending on your
input search.
This example demonstrates how to retrieve the streamflow associated
with the reach you are interested in::
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
river_id = 500
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
streamflow_array = qout_nc.get_qout(river_id)
This example demonstrates how to retrieve the streamflow within a date
range associated with the reach you are interested in::
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
river_id = 500
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
streamflow_array = qout_nc.get_qout(
river_id,
date_search_start=datetime(1985,1,1),
date_search_end=datetime(1985,2,4))
"""
# get indices of where the streamflow data is
riverid_index_list_subset = None
if river_id_array is not None:
if not hasattr(river_id_array, "__len__"):
river_id_array = [river_id_array]
riverid_index_list_subset = \
self.get_subset_riverid_index_list(river_id_array)[0]
return self.get_qout_index(riverid_index_list_subset,
date_search_start,
date_search_end,
time_index_start,
time_index_end,
time_index,
time_index_array,
daily,
pd_filter,
filter_mode,
as_dataframe) | python | def get_qout(self,
river_id_array=None,
date_search_start=None,
date_search_end=None,
time_index_start=None,
time_index_end=None,
time_index=None,
time_index_array=None,
daily=False,
pd_filter=None,
filter_mode="mean",
as_dataframe=False):
"""
This method extracts streamflow data by a single river ID
or by a river ID array. It has options to extract by date
or by date index.
Parameters
----------
river_id_array: :obj:`numpy.array` or list or int, optional
A single river ID or an array of river IDs.
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date
for starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date
for ending.
time_index_start: int, optional
This is the index of the start of the time array subset.
Useful for the old file version.
time_index_end: int, optional
This is the index of the end of the time array subset.
Useful for the old file version.
time_index: int, optional
This is the index of time to return in the case that your
code only wants one index. Used internally.
time_index_array: list or :obj:`numpy.array`, optional
This is used to extract the vales only for particular dates.
This can be from the *get_time_index_range* function.
daily: bool, optional
If true, this will convert qout to daily average.
pd_filter: str, optional
This is a valid pandas resample frequency filter.
filter_mode: str, optional
You can get the daily average "mean" or the maximum "max".
Default is "mean".
as_dataframe: bool, optional
Return as a pandas dataframe object. Default is False.
Returns
-------
qout_array: :obj:`numpy.array`
This is a 1D or 2D array or a single value depending on your
input search.
This example demonstrates how to retrieve the streamflow associated
with the reach you are interested in::
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
river_id = 500
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
streamflow_array = qout_nc.get_qout(river_id)
This example demonstrates how to retrieve the streamflow within a date
range associated with the reach you are interested in::
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
river_id = 500
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
streamflow_array = qout_nc.get_qout(
river_id,
date_search_start=datetime(1985,1,1),
date_search_end=datetime(1985,2,4))
"""
# get indices of where the streamflow data is
riverid_index_list_subset = None
if river_id_array is not None:
if not hasattr(river_id_array, "__len__"):
river_id_array = [river_id_array]
riverid_index_list_subset = \
self.get_subset_riverid_index_list(river_id_array)[0]
return self.get_qout_index(riverid_index_list_subset,
date_search_start,
date_search_end,
time_index_start,
time_index_end,
time_index,
time_index_array,
daily,
pd_filter,
filter_mode,
as_dataframe) | [
"def",
"get_qout",
"(",
"self",
",",
"river_id_array",
"=",
"None",
",",
"date_search_start",
"=",
"None",
",",
"date_search_end",
"=",
"None",
",",
"time_index_start",
"=",
"None",
",",
"time_index_end",
"=",
"None",
",",
"time_index",
"=",
"None",
",",
"ti... | This method extracts streamflow data by a single river ID
or by a river ID array. It has options to extract by date
or by date index.
Parameters
----------
river_id_array: :obj:`numpy.array` or list or int, optional
A single river ID or an array of river IDs.
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date
for starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date
for ending.
time_index_start: int, optional
This is the index of the start of the time array subset.
Useful for the old file version.
time_index_end: int, optional
This is the index of the end of the time array subset.
Useful for the old file version.
time_index: int, optional
This is the index of time to return in the case that your
code only wants one index. Used internally.
time_index_array: list or :obj:`numpy.array`, optional
This is used to extract the vales only for particular dates.
This can be from the *get_time_index_range* function.
daily: bool, optional
If true, this will convert qout to daily average.
pd_filter: str, optional
This is a valid pandas resample frequency filter.
filter_mode: str, optional
You can get the daily average "mean" or the maximum "max".
Default is "mean".
as_dataframe: bool, optional
Return as a pandas dataframe object. Default is False.
Returns
-------
qout_array: :obj:`numpy.array`
This is a 1D or 2D array or a single value depending on your
input search.
This example demonstrates how to retrieve the streamflow associated
with the reach you are interested in::
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
river_id = 500
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
streamflow_array = qout_nc.get_qout(river_id)
This example demonstrates how to retrieve the streamflow within a date
range associated with the reach you are interested in::
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
river_id = 500
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
streamflow_array = qout_nc.get_qout(
river_id,
date_search_start=datetime(1985,1,1),
date_search_end=datetime(1985,2,4)) | [
"This",
"method",
"extracts",
"streamflow",
"data",
"by",
"a",
"single",
"river",
"ID",
"or",
"by",
"a",
"river",
"ID",
"array",
".",
"It",
"has",
"options",
"to",
"extract",
"by",
"date",
"or",
"by",
"date",
"index",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/dataset.py#L633-L732 | train | 33,288 |
erdc/RAPIDpy | RAPIDpy/dataset.py | RAPIDDataset.get_qout_index | def get_qout_index(self,
river_index_array=None,
date_search_start=None,
date_search_end=None,
time_index_start=None,
time_index_end=None,
time_index=None,
time_index_array=None,
daily=False,
pd_filter=None,
filter_mode="mean",
as_dataframe=False):
"""
This method extracts streamflow data by river index.
It allows for extracting single or multiple river streamflow arrays
It has options to extract by date or by date index.
See: :meth:`RAPIDpy.RAPIDDataset.get_qout`
"""
if river_index_array is not None:
if hasattr(river_index_array, "__len__"):
if len(river_index_array) == 1:
river_index_array = river_index_array[0]
if time_index_array is None:
time_index_array = self.get_time_index_range(date_search_start,
date_search_end,
time_index_start,
time_index_end,
time_index)
qout_variable = self.qout_nc.variables[self.q_var_name]
qout_dimensions = qout_variable.dimensions
if qout_dimensions[0].lower() == 'time' and \
qout_dimensions[1].lower() == self.river_id_dimension.lower():
if time_index_array is not None and river_index_array is not None:
streamflow_array = qout_variable[time_index_array,
river_index_array].transpose()
elif time_index_array is not None:
streamflow_array = qout_variable[time_index_array, :] \
.transpose()
elif river_index_array is not None:
streamflow_array = qout_variable[:, river_index_array] \
.transpose()
else:
streamflow_array = qout_variable[:].transpose()
elif qout_dimensions[1].lower() == 'time' and \
qout_dimensions[0].lower() == self.river_id_dimension.lower():
if time_index_array is not None and river_index_array is not None:
streamflow_array = qout_variable[river_index_array,
time_index_array]
elif time_index_array is not None:
streamflow_array = qout_variable[:, time_index_array]
elif river_index_array is not None:
streamflow_array = qout_variable[river_index_array, :]
else:
streamflow_array = qout_variable[:]
else:
raise Exception("Invalid RAPID Qout file dimensions ...")
if daily:
pd_filter = "D"
if pd_filter is not None or as_dataframe:
time_array = self.get_time_array(return_datetime=True,
time_index_array=time_index_array)
qout_df = pd.DataFrame(streamflow_array.T, index=time_array)
if pd_filter is not None:
qout_df = qout_df.resample(pd_filter)
if filter_mode == "mean":
qout_df = qout_df.mean()
elif filter_mode == "max":
qout_df = qout_df.max()
else:
raise Exception("Invalid filter_mode ...")
if as_dataframe:
return qout_df
streamflow_array = qout_df.as_matrix().T
if streamflow_array.ndim > 0 and streamflow_array.shape[0] == 1:
streamflow_array = streamflow_array[0]
return streamflow_array | python | def get_qout_index(self,
river_index_array=None,
date_search_start=None,
date_search_end=None,
time_index_start=None,
time_index_end=None,
time_index=None,
time_index_array=None,
daily=False,
pd_filter=None,
filter_mode="mean",
as_dataframe=False):
"""
This method extracts streamflow data by river index.
It allows for extracting single or multiple river streamflow arrays
It has options to extract by date or by date index.
See: :meth:`RAPIDpy.RAPIDDataset.get_qout`
"""
if river_index_array is not None:
if hasattr(river_index_array, "__len__"):
if len(river_index_array) == 1:
river_index_array = river_index_array[0]
if time_index_array is None:
time_index_array = self.get_time_index_range(date_search_start,
date_search_end,
time_index_start,
time_index_end,
time_index)
qout_variable = self.qout_nc.variables[self.q_var_name]
qout_dimensions = qout_variable.dimensions
if qout_dimensions[0].lower() == 'time' and \
qout_dimensions[1].lower() == self.river_id_dimension.lower():
if time_index_array is not None and river_index_array is not None:
streamflow_array = qout_variable[time_index_array,
river_index_array].transpose()
elif time_index_array is not None:
streamflow_array = qout_variable[time_index_array, :] \
.transpose()
elif river_index_array is not None:
streamflow_array = qout_variable[:, river_index_array] \
.transpose()
else:
streamflow_array = qout_variable[:].transpose()
elif qout_dimensions[1].lower() == 'time' and \
qout_dimensions[0].lower() == self.river_id_dimension.lower():
if time_index_array is not None and river_index_array is not None:
streamflow_array = qout_variable[river_index_array,
time_index_array]
elif time_index_array is not None:
streamflow_array = qout_variable[:, time_index_array]
elif river_index_array is not None:
streamflow_array = qout_variable[river_index_array, :]
else:
streamflow_array = qout_variable[:]
else:
raise Exception("Invalid RAPID Qout file dimensions ...")
if daily:
pd_filter = "D"
if pd_filter is not None or as_dataframe:
time_array = self.get_time_array(return_datetime=True,
time_index_array=time_index_array)
qout_df = pd.DataFrame(streamflow_array.T, index=time_array)
if pd_filter is not None:
qout_df = qout_df.resample(pd_filter)
if filter_mode == "mean":
qout_df = qout_df.mean()
elif filter_mode == "max":
qout_df = qout_df.max()
else:
raise Exception("Invalid filter_mode ...")
if as_dataframe:
return qout_df
streamflow_array = qout_df.as_matrix().T
if streamflow_array.ndim > 0 and streamflow_array.shape[0] == 1:
streamflow_array = streamflow_array[0]
return streamflow_array | [
"def",
"get_qout_index",
"(",
"self",
",",
"river_index_array",
"=",
"None",
",",
"date_search_start",
"=",
"None",
",",
"date_search_end",
"=",
"None",
",",
"time_index_start",
"=",
"None",
",",
"time_index_end",
"=",
"None",
",",
"time_index",
"=",
"None",
"... | This method extracts streamflow data by river index.
It allows for extracting single or multiple river streamflow arrays
It has options to extract by date or by date index.
See: :meth:`RAPIDpy.RAPIDDataset.get_qout` | [
"This",
"method",
"extracts",
"streamflow",
"data",
"by",
"river",
"index",
".",
"It",
"allows",
"for",
"extracting",
"single",
"or",
"multiple",
"river",
"streamflow",
"arrays",
"It",
"has",
"options",
"to",
"extract",
"by",
"date",
"or",
"by",
"date",
"ind... | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/dataset.py#L734-L819 | train | 33,289 |
erdc/RAPIDpy | RAPIDpy/dataset.py | RAPIDDataset.write_flows_to_csv | def write_flows_to_csv(self, path_to_output_file,
river_index=None,
river_id=None,
date_search_start=None,
date_search_end=None,
daily=False,
filter_mode="mean"):
"""
Write out RAPID output to CSV file.
.. note:: Need either *reach_id* or *reach_index* parameter,
but either can be used.
Parameters
----------
path_to_output_file: str
Path to the output csv file.
river_index: :obj:`datetime.datetime`, optional
This is the index of the river in the file you want the
streamflow for.
river_id: :obj:`datetime.datetime`, optional
This is the river ID that you want the streamflow for.
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date
for starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date
for ending.
daily: bool, optional
If True and the file is CF-Compliant, write out daily flows.
filter_mode: str, optional
You can get the daily average "mean" or the maximum "max".
Default is "mean".
Example writing entire time series to file:
.. code:: python
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
#for writing entire time series to file
qout_nc.write_flows_to_csv('/timeseries/Qout_3624735.csv',
river_id=river_id,
)
#if file is CF compliant, you can write out daily average
#NOTE: Getting the river index is not necessary
#this is just an example of how to use this
river_index = qout_nc.get_river_index(river_id)
qout_nc.write_flows_to_csv('/timeseries/Qout_daily.csv',
river_index=river_index,
daily=True,
)
Example writing entire time series as daily average to file:
.. code:: python
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
#NOTE: Getting the river index is not necessary
#this is just an example of how to use this
river_index = qout_nc.get_river_index(river_id)
#if file is CF compliant, you can write out daily average
qout_nc.write_flows_to_csv('/timeseries/Qout_daily.csv',
river_index=river_index,
daily=True,
)
Example writing entire time series as daily average to file:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# if file is CF compliant, you can filter by date
qout_nc.write_flows_to_csv(
'/timeseries/Qout_daily_date_filter.csv',
river_id=river_id,
daily=True,
date_search_start=datetime(2002, 8, 31),
date_search_end=datetime(2002, 9, 15),
filter_mode="max"
)
"""
if river_id is not None:
river_index = self.get_river_index(river_id)
elif river_id is None and river_index is None:
raise ValueError("Need reach id or reach index ...")
# analyze and write
if self.is_time_variable_valid() or self._is_legacy_time_valid():
qout_df = self.get_qout_index(river_index,
date_search_start=date_search_start,
date_search_end=date_search_end,
daily=daily,
filter_mode=filter_mode,
as_dataframe=True)
qout_df.to_csv(path_to_output_file, header=False)
else:
log("Valid time variable not found. Printing values only ...",
"WARNING")
qout_arr = self.get_qout_index(river_index)
with open_csv(path_to_output_file, 'w') as outcsv:
writer = csv_writer(outcsv)
for index in xrange(len(qout_arr)):
writer.writerow([index, "{0:.5f}".format(qout_arr[index])]) | python | def write_flows_to_csv(self, path_to_output_file,
river_index=None,
river_id=None,
date_search_start=None,
date_search_end=None,
daily=False,
filter_mode="mean"):
"""
Write out RAPID output to CSV file.
.. note:: Need either *reach_id* or *reach_index* parameter,
but either can be used.
Parameters
----------
path_to_output_file: str
Path to the output csv file.
river_index: :obj:`datetime.datetime`, optional
This is the index of the river in the file you want the
streamflow for.
river_id: :obj:`datetime.datetime`, optional
This is the river ID that you want the streamflow for.
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date
for starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date
for ending.
daily: bool, optional
If True and the file is CF-Compliant, write out daily flows.
filter_mode: str, optional
You can get the daily average "mean" or the maximum "max".
Default is "mean".
Example writing entire time series to file:
.. code:: python
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
#for writing entire time series to file
qout_nc.write_flows_to_csv('/timeseries/Qout_3624735.csv',
river_id=river_id,
)
#if file is CF compliant, you can write out daily average
#NOTE: Getting the river index is not necessary
#this is just an example of how to use this
river_index = qout_nc.get_river_index(river_id)
qout_nc.write_flows_to_csv('/timeseries/Qout_daily.csv',
river_index=river_index,
daily=True,
)
Example writing entire time series as daily average to file:
.. code:: python
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
#NOTE: Getting the river index is not necessary
#this is just an example of how to use this
river_index = qout_nc.get_river_index(river_id)
#if file is CF compliant, you can write out daily average
qout_nc.write_flows_to_csv('/timeseries/Qout_daily.csv',
river_index=river_index,
daily=True,
)
Example writing entire time series as daily average to file:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# if file is CF compliant, you can filter by date
qout_nc.write_flows_to_csv(
'/timeseries/Qout_daily_date_filter.csv',
river_id=river_id,
daily=True,
date_search_start=datetime(2002, 8, 31),
date_search_end=datetime(2002, 9, 15),
filter_mode="max"
)
"""
if river_id is not None:
river_index = self.get_river_index(river_id)
elif river_id is None and river_index is None:
raise ValueError("Need reach id or reach index ...")
# analyze and write
if self.is_time_variable_valid() or self._is_legacy_time_valid():
qout_df = self.get_qout_index(river_index,
date_search_start=date_search_start,
date_search_end=date_search_end,
daily=daily,
filter_mode=filter_mode,
as_dataframe=True)
qout_df.to_csv(path_to_output_file, header=False)
else:
log("Valid time variable not found. Printing values only ...",
"WARNING")
qout_arr = self.get_qout_index(river_index)
with open_csv(path_to_output_file, 'w') as outcsv:
writer = csv_writer(outcsv)
for index in xrange(len(qout_arr)):
writer.writerow([index, "{0:.5f}".format(qout_arr[index])]) | [
"def",
"write_flows_to_csv",
"(",
"self",
",",
"path_to_output_file",
",",
"river_index",
"=",
"None",
",",
"river_id",
"=",
"None",
",",
"date_search_start",
"=",
"None",
",",
"date_search_end",
"=",
"None",
",",
"daily",
"=",
"False",
",",
"filter_mode",
"="... | Write out RAPID output to CSV file.
.. note:: Need either *reach_id* or *reach_index* parameter,
but either can be used.
Parameters
----------
path_to_output_file: str
Path to the output csv file.
river_index: :obj:`datetime.datetime`, optional
This is the index of the river in the file you want the
streamflow for.
river_id: :obj:`datetime.datetime`, optional
This is the river ID that you want the streamflow for.
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date
for starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date
for ending.
daily: bool, optional
If True and the file is CF-Compliant, write out daily flows.
filter_mode: str, optional
You can get the daily average "mean" or the maximum "max".
Default is "mean".
Example writing entire time series to file:
.. code:: python
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
#for writing entire time series to file
qout_nc.write_flows_to_csv('/timeseries/Qout_3624735.csv',
river_id=river_id,
)
#if file is CF compliant, you can write out daily average
#NOTE: Getting the river index is not necessary
#this is just an example of how to use this
river_index = qout_nc.get_river_index(river_id)
qout_nc.write_flows_to_csv('/timeseries/Qout_daily.csv',
river_index=river_index,
daily=True,
)
Example writing entire time series as daily average to file:
.. code:: python
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
#NOTE: Getting the river index is not necessary
#this is just an example of how to use this
river_index = qout_nc.get_river_index(river_id)
#if file is CF compliant, you can write out daily average
qout_nc.write_flows_to_csv('/timeseries/Qout_daily.csv',
river_index=river_index,
daily=True,
)
Example writing entire time series as daily average to file:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# if file is CF compliant, you can filter by date
qout_nc.write_flows_to_csv(
'/timeseries/Qout_daily_date_filter.csv',
river_id=river_id,
daily=True,
date_search_start=datetime(2002, 8, 31),
date_search_end=datetime(2002, 9, 15),
filter_mode="max"
) | [
"Write",
"out",
"RAPID",
"output",
"to",
"CSV",
"file",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/dataset.py#L821-L946 | train | 33,290 |
erdc/RAPIDpy | RAPIDpy/dataset.py | RAPIDDataset.write_flows_to_gssha_time_series_xys | def write_flows_to_gssha_time_series_xys(self,
path_to_output_file,
series_name,
series_id,
river_index=None,
river_id=None,
date_search_start=None,
date_search_end=None,
daily=False,
filter_mode="mean"):
"""
Write out RAPID output to GSSHA WMS time series xys file.
Parameters
----------
path_to_output_file: str
Path to the output xys file.
series_name: str
The name for the series.
series_id: int
The ID to give the series.
river_index: :obj:`datetime.datetime`, optional
This is the index of the river in the file you want the
streamflow for.
river_id: :obj:`datetime.datetime`, optional
This is the river ID that you want the streamflow for.
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date for
starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date for
ending.
daily: bool, optional
If True and the file is CF-Compliant, write out daily flows.
filter_mode: str, optional
You can get the daily average "mean" or the maximum "max".
Defauls is "mean".
Example writing entire time series to file:
.. code:: python
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
qout_nc.write_flows_to_gssha_time_series_xys(
'/timeseries/Qout_{0}.xys'.format(river_id),
series_name="RAPID_TO_GSSHA_{0}".format(river_id),
series_id=34,
river_id=river_id)
Example writing entire time series as daily average to file:
.. code:: python
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# NOTE: Getting the river index is not necessary
# this is just an example of how to use this
river_index = qout_nc.get_river_index(river_id)
# if file is CF compliant, you can write out daily average
qout_nc.write_flows_to_gssha_time_series_xys(
'/timeseries/Qout_daily.xys',
series_name="RAPID_TO_GSSHA_{0}".format(river_id),
series_id=34,
river_index=river_index,
daily=True)
Example writing subset of time series as daily maximum to file:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# NOTE: Getting the river index is not necessary
# this is just an example of how to use this
river_index = qout_nc.get_river_index(river_id)
# if file is CF compliant, you can filter by date and
# get daily values
qout_nc.write_flows_to_gssha_time_series_xys(
'/timeseries/Qout_daily_date_filter.xys',
series_name="RAPID_TO_GSSHA_{0}".format(river_id),
series_id=34,
river_index=river_index,
date_search_start=datetime(2002, 8, 31),
date_search_end=datetime(2002, 9, 15),
daily=True,
filter_mode="max")
"""
if river_id is not None:
river_index = self.get_river_index(river_id)
elif river_id is None and river_index is None:
raise ValueError(" Need reach id or reach index ...")
self.raise_time_valid()
# analyze and write
qout_df = self.get_qout_index(river_index,
date_search_start=date_search_start,
date_search_end=date_search_end,
daily=daily,
filter_mode=filter_mode,
as_dataframe=True)
with open_csv(path_to_output_file, 'w') as out_ts:
out_ts.write("XYS {0} {1} \"{2}\"\r\n".format(series_id,
len(qout_df.index),
series_name))
for index, pd_row in qout_df.iterrows():
date_str = index.strftime("%m/%d/%Y %I:%M:%S %p")
out_ts.write("\"{0}\" {1:.5f}\n".format(date_str,
pd_row[0])) | python | def write_flows_to_gssha_time_series_xys(self,
path_to_output_file,
series_name,
series_id,
river_index=None,
river_id=None,
date_search_start=None,
date_search_end=None,
daily=False,
filter_mode="mean"):
"""
Write out RAPID output to GSSHA WMS time series xys file.
Parameters
----------
path_to_output_file: str
Path to the output xys file.
series_name: str
The name for the series.
series_id: int
The ID to give the series.
river_index: :obj:`datetime.datetime`, optional
This is the index of the river in the file you want the
streamflow for.
river_id: :obj:`datetime.datetime`, optional
This is the river ID that you want the streamflow for.
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date for
starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date for
ending.
daily: bool, optional
If True and the file is CF-Compliant, write out daily flows.
filter_mode: str, optional
You can get the daily average "mean" or the maximum "max".
Defauls is "mean".
Example writing entire time series to file:
.. code:: python
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
qout_nc.write_flows_to_gssha_time_series_xys(
'/timeseries/Qout_{0}.xys'.format(river_id),
series_name="RAPID_TO_GSSHA_{0}".format(river_id),
series_id=34,
river_id=river_id)
Example writing entire time series as daily average to file:
.. code:: python
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# NOTE: Getting the river index is not necessary
# this is just an example of how to use this
river_index = qout_nc.get_river_index(river_id)
# if file is CF compliant, you can write out daily average
qout_nc.write_flows_to_gssha_time_series_xys(
'/timeseries/Qout_daily.xys',
series_name="RAPID_TO_GSSHA_{0}".format(river_id),
series_id=34,
river_index=river_index,
daily=True)
Example writing subset of time series as daily maximum to file:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# NOTE: Getting the river index is not necessary
# this is just an example of how to use this
river_index = qout_nc.get_river_index(river_id)
# if file is CF compliant, you can filter by date and
# get daily values
qout_nc.write_flows_to_gssha_time_series_xys(
'/timeseries/Qout_daily_date_filter.xys',
series_name="RAPID_TO_GSSHA_{0}".format(river_id),
series_id=34,
river_index=river_index,
date_search_start=datetime(2002, 8, 31),
date_search_end=datetime(2002, 9, 15),
daily=True,
filter_mode="max")
"""
if river_id is not None:
river_index = self.get_river_index(river_id)
elif river_id is None and river_index is None:
raise ValueError(" Need reach id or reach index ...")
self.raise_time_valid()
# analyze and write
qout_df = self.get_qout_index(river_index,
date_search_start=date_search_start,
date_search_end=date_search_end,
daily=daily,
filter_mode=filter_mode,
as_dataframe=True)
with open_csv(path_to_output_file, 'w') as out_ts:
out_ts.write("XYS {0} {1} \"{2}\"\r\n".format(series_id,
len(qout_df.index),
series_name))
for index, pd_row in qout_df.iterrows():
date_str = index.strftime("%m/%d/%Y %I:%M:%S %p")
out_ts.write("\"{0}\" {1:.5f}\n".format(date_str,
pd_row[0])) | [
"def",
"write_flows_to_gssha_time_series_xys",
"(",
"self",
",",
"path_to_output_file",
",",
"series_name",
",",
"series_id",
",",
"river_index",
"=",
"None",
",",
"river_id",
"=",
"None",
",",
"date_search_start",
"=",
"None",
",",
"date_search_end",
"=",
"None",
... | Write out RAPID output to GSSHA WMS time series xys file.
Parameters
----------
path_to_output_file: str
Path to the output xys file.
series_name: str
The name for the series.
series_id: int
The ID to give the series.
river_index: :obj:`datetime.datetime`, optional
This is the index of the river in the file you want the
streamflow for.
river_id: :obj:`datetime.datetime`, optional
This is the river ID that you want the streamflow for.
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date for
starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date for
ending.
daily: bool, optional
If True and the file is CF-Compliant, write out daily flows.
filter_mode: str, optional
You can get the daily average "mean" or the maximum "max".
Defauls is "mean".
Example writing entire time series to file:
.. code:: python
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
qout_nc.write_flows_to_gssha_time_series_xys(
'/timeseries/Qout_{0}.xys'.format(river_id),
series_name="RAPID_TO_GSSHA_{0}".format(river_id),
series_id=34,
river_id=river_id)
Example writing entire time series as daily average to file:
.. code:: python
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# NOTE: Getting the river index is not necessary
# this is just an example of how to use this
river_index = qout_nc.get_river_index(river_id)
# if file is CF compliant, you can write out daily average
qout_nc.write_flows_to_gssha_time_series_xys(
'/timeseries/Qout_daily.xys',
series_name="RAPID_TO_GSSHA_{0}".format(river_id),
series_id=34,
river_index=river_index,
daily=True)
Example writing subset of time series as daily maximum to file:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
river_id = 3624735
path_to_rapid_qout = '/path/to/Qout.nc'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# NOTE: Getting the river index is not necessary
# this is just an example of how to use this
river_index = qout_nc.get_river_index(river_id)
# if file is CF compliant, you can filter by date and
# get daily values
qout_nc.write_flows_to_gssha_time_series_xys(
'/timeseries/Qout_daily_date_filter.xys',
series_name="RAPID_TO_GSSHA_{0}".format(river_id),
series_id=34,
river_index=river_index,
date_search_start=datetime(2002, 8, 31),
date_search_end=datetime(2002, 9, 15),
daily=True,
filter_mode="max") | [
"Write",
"out",
"RAPID",
"output",
"to",
"GSSHA",
"WMS",
"time",
"series",
"xys",
"file",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/dataset.py#L948-L1077 | train | 33,291 |
erdc/RAPIDpy | RAPIDpy/dataset.py | RAPIDDataset.write_flows_to_gssha_time_series_ihg | def write_flows_to_gssha_time_series_ihg(self,
path_to_output_file,
connection_list_file,
date_search_start=None,
date_search_end=None,
daily=False,
filter_mode="mean"):
# pylint: disable=line-too-long
"""
Write out RAPID output to GSSHA time series ihg file
.. note:: See: http://www.gsshawiki.com/Surface_Water_Routing:Introducing_Dischage/Constituent_Hydrographs
.. note:: GSSHA project card is CHAN_POINT_INPUT
Parameters
----------
path_to_output_file: str
Path to the output xys file.
connection_list_file: str
CSV file with link_id, node_id, baseflow, and rapid_rivid header
and rows with data.
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date
for starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date
for ending.
daily: bool, optional
If True and the file is CF-Compliant, write out daily flows.
filter_mode: str, optional
You can get the daily average "mean" or the maximum "max".
Defauls is "mean".
Example connection list file::
link_id, node_id, baseflow, rapid_rivid
599, 1, 0.0, 80968
603, 1, 0.0, 80967
Example writing entire time series to file:
.. code:: python
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
connection_list_file = '/path/to/connection_list_file.csv'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
#for writing entire time series to file
qout_nc.write_flows_to_gssha_time_series_ihg(
'/timeseries/Qout_3624735.ihg',
connection_list_file)
Example writing entire time series as daily average to file:
.. code:: python
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
connection_list_file = '/path/to/connection_list_file.csv'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# if file is CF compliant, you can write out daily average
qout_nc.write_flows_to_gssha_time_series_ihg(
'/timeseries/Qout_3624735.ihg',
connection_list_file,
daily=True)
Example writing subset of time series as daily maximum to file:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
connection_list_file = '/path/to/connection_list_file.csv'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# if file is CF compliant, you can filter by
# date and get daily values
qout_nc.write_flows_to_gssha_time_series_ihg(
'/timeseries/Qout_daily_date_filter.ihg',
connection_list_file,
date_search_start=datetime(2002, 8, 31),
date_search_end=datetime(2002, 9, 15),
daily=True,
filter_mode="max")
""" # noqa
self.raise_time_valid()
# analyze and write
with open_csv(path_to_output_file, 'w') as out_ts:
# HEADER SECTION EXAMPLE:
# NUMPT 3
# POINT 1 599 0.0
# POINT 1 603 0.0
# POINT 1 605 0.0
connection_list = np.loadtxt(connection_list_file,
skiprows=1, ndmin=1,
delimiter=',',
usecols=(0, 1, 2, 3),
dtype={'names': ('link_id',
'node_id',
'baseflow',
'rapid_rivid'),
'formats': ('i8', 'i8',
'f4', 'i8')
},
)
out_ts.write("NUMPT {0}\n".format(connection_list.size))
river_idx_list = []
for connection in connection_list:
out_ts.write("POINT {0} {1} {2}\n"
"".format(connection['node_id'],
connection['link_id'],
connection['baseflow'],
),
)
river_idx_list.append(
self.get_river_index(connection['rapid_rivid'])
)
# INFLOW SECTION EXAMPLE:
# NRPDS 54
# INPUT 2002 01 01 00 00 15.551210 12.765090 0.000000
# INPUT 2002 01 02 00 00 15.480830 12.765090 0.000000
# INPUT 2002 01 03 00 00 16.078910 12.765090 0.000000
# ...
qout_df = self.get_qout_index(
river_idx_list,
date_search_start=date_search_start,
date_search_end=date_search_end,
daily=daily,
filter_mode=filter_mode,
as_dataframe=True)
out_ts.write("NRPDS {0}\n".format(len(qout_df.index)))
for index, pd_row in qout_df.iterrows():
date_str = index.strftime("%Y %m %d %H %M")
qout_str = " ".join(["{0:.5f}".format(pd_row[column])
for column in qout_df])
out_ts.write("INPUT {0} {1}\n".format(date_str, qout_str)) | python | def write_flows_to_gssha_time_series_ihg(self,
path_to_output_file,
connection_list_file,
date_search_start=None,
date_search_end=None,
daily=False,
filter_mode="mean"):
# pylint: disable=line-too-long
"""
Write out RAPID output to GSSHA time series ihg file
.. note:: See: http://www.gsshawiki.com/Surface_Water_Routing:Introducing_Dischage/Constituent_Hydrographs
.. note:: GSSHA project card is CHAN_POINT_INPUT
Parameters
----------
path_to_output_file: str
Path to the output xys file.
connection_list_file: str
CSV file with link_id, node_id, baseflow, and rapid_rivid header
and rows with data.
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date
for starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date
for ending.
daily: bool, optional
If True and the file is CF-Compliant, write out daily flows.
filter_mode: str, optional
You can get the daily average "mean" or the maximum "max".
Defauls is "mean".
Example connection list file::
link_id, node_id, baseflow, rapid_rivid
599, 1, 0.0, 80968
603, 1, 0.0, 80967
Example writing entire time series to file:
.. code:: python
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
connection_list_file = '/path/to/connection_list_file.csv'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
#for writing entire time series to file
qout_nc.write_flows_to_gssha_time_series_ihg(
'/timeseries/Qout_3624735.ihg',
connection_list_file)
Example writing entire time series as daily average to file:
.. code:: python
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
connection_list_file = '/path/to/connection_list_file.csv'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# if file is CF compliant, you can write out daily average
qout_nc.write_flows_to_gssha_time_series_ihg(
'/timeseries/Qout_3624735.ihg',
connection_list_file,
daily=True)
Example writing subset of time series as daily maximum to file:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
connection_list_file = '/path/to/connection_list_file.csv'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# if file is CF compliant, you can filter by
# date and get daily values
qout_nc.write_flows_to_gssha_time_series_ihg(
'/timeseries/Qout_daily_date_filter.ihg',
connection_list_file,
date_search_start=datetime(2002, 8, 31),
date_search_end=datetime(2002, 9, 15),
daily=True,
filter_mode="max")
""" # noqa
self.raise_time_valid()
# analyze and write
with open_csv(path_to_output_file, 'w') as out_ts:
# HEADER SECTION EXAMPLE:
# NUMPT 3
# POINT 1 599 0.0
# POINT 1 603 0.0
# POINT 1 605 0.0
connection_list = np.loadtxt(connection_list_file,
skiprows=1, ndmin=1,
delimiter=',',
usecols=(0, 1, 2, 3),
dtype={'names': ('link_id',
'node_id',
'baseflow',
'rapid_rivid'),
'formats': ('i8', 'i8',
'f4', 'i8')
},
)
out_ts.write("NUMPT {0}\n".format(connection_list.size))
river_idx_list = []
for connection in connection_list:
out_ts.write("POINT {0} {1} {2}\n"
"".format(connection['node_id'],
connection['link_id'],
connection['baseflow'],
),
)
river_idx_list.append(
self.get_river_index(connection['rapid_rivid'])
)
# INFLOW SECTION EXAMPLE:
# NRPDS 54
# INPUT 2002 01 01 00 00 15.551210 12.765090 0.000000
# INPUT 2002 01 02 00 00 15.480830 12.765090 0.000000
# INPUT 2002 01 03 00 00 16.078910 12.765090 0.000000
# ...
qout_df = self.get_qout_index(
river_idx_list,
date_search_start=date_search_start,
date_search_end=date_search_end,
daily=daily,
filter_mode=filter_mode,
as_dataframe=True)
out_ts.write("NRPDS {0}\n".format(len(qout_df.index)))
for index, pd_row in qout_df.iterrows():
date_str = index.strftime("%Y %m %d %H %M")
qout_str = " ".join(["{0:.5f}".format(pd_row[column])
for column in qout_df])
out_ts.write("INPUT {0} {1}\n".format(date_str, qout_str)) | [
"def",
"write_flows_to_gssha_time_series_ihg",
"(",
"self",
",",
"path_to_output_file",
",",
"connection_list_file",
",",
"date_search_start",
"=",
"None",
",",
"date_search_end",
"=",
"None",
",",
"daily",
"=",
"False",
",",
"filter_mode",
"=",
"\"mean\"",
")",
":"... | Write out RAPID output to GSSHA time series ihg file
.. note:: See: http://www.gsshawiki.com/Surface_Water_Routing:Introducing_Dischage/Constituent_Hydrographs
.. note:: GSSHA project card is CHAN_POINT_INPUT
Parameters
----------
path_to_output_file: str
Path to the output xys file.
connection_list_file: str
CSV file with link_id, node_id, baseflow, and rapid_rivid header
and rows with data.
date_search_start: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the minimum date
for starting.
date_search_end: :obj:`datetime.datetime`, optional
This is a datetime object with the date of the maximum date
for ending.
daily: bool, optional
If True and the file is CF-Compliant, write out daily flows.
filter_mode: str, optional
You can get the daily average "mean" or the maximum "max".
Defauls is "mean".
Example connection list file::
link_id, node_id, baseflow, rapid_rivid
599, 1, 0.0, 80968
603, 1, 0.0, 80967
Example writing entire time series to file:
.. code:: python
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
connection_list_file = '/path/to/connection_list_file.csv'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
#for writing entire time series to file
qout_nc.write_flows_to_gssha_time_series_ihg(
'/timeseries/Qout_3624735.ihg',
connection_list_file)
Example writing entire time series as daily average to file:
.. code:: python
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
connection_list_file = '/path/to/connection_list_file.csv'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# if file is CF compliant, you can write out daily average
qout_nc.write_flows_to_gssha_time_series_ihg(
'/timeseries/Qout_3624735.ihg',
connection_list_file,
daily=True)
Example writing subset of time series as daily maximum to file:
.. code:: python
from datetime import datetime
from RAPIDpy import RAPIDDataset
path_to_rapid_qout = '/path/to/Qout.nc'
connection_list_file = '/path/to/connection_list_file.csv'
with RAPIDDataset(path_to_rapid_qout) as qout_nc:
# if file is CF compliant, you can filter by
# date and get daily values
qout_nc.write_flows_to_gssha_time_series_ihg(
'/timeseries/Qout_daily_date_filter.ihg',
connection_list_file,
date_search_start=datetime(2002, 8, 31),
date_search_end=datetime(2002, 9, 15),
daily=True,
filter_mode="max") | [
"Write",
"out",
"RAPID",
"output",
"to",
"GSSHA",
"time",
"series",
"ihg",
"file"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/dataset.py#L1079-L1232 | train | 33,292 |
erdc/RAPIDpy | RAPIDpy/utilities.py | case_insensitive_file_search | def case_insensitive_file_search(directory, pattern):
"""
Looks for file with pattern with case insensitive search
"""
try:
return os.path.join(
directory,
[filename for filename in os.listdir(directory)
if re.search(pattern, filename, re.IGNORECASE)][0])
except IndexError:
print("{0} not found".format(pattern))
raise | python | def case_insensitive_file_search(directory, pattern):
"""
Looks for file with pattern with case insensitive search
"""
try:
return os.path.join(
directory,
[filename for filename in os.listdir(directory)
if re.search(pattern, filename, re.IGNORECASE)][0])
except IndexError:
print("{0} not found".format(pattern))
raise | [
"def",
"case_insensitive_file_search",
"(",
"directory",
",",
"pattern",
")",
":",
"try",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"[",
"filename",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
"if",
"... | Looks for file with pattern with case insensitive search | [
"Looks",
"for",
"file",
"with",
"pattern",
"with",
"case",
"insensitive",
"search"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/utilities.py#L18-L29 | train | 33,293 |
erdc/RAPIDpy | RAPIDpy/utilities.py | partition | def partition(lst, n):
"""
Divide list into n equal parts
"""
q, r = divmod(len(lst), n)
indices = [q*i + min(i, r) for i in xrange(n+1)]
return [lst[indices[i]:indices[i+1]] for i in xrange(n)], \
[list(xrange(indices[i], indices[i+1])) for i in xrange(n)] | python | def partition(lst, n):
"""
Divide list into n equal parts
"""
q, r = divmod(len(lst), n)
indices = [q*i + min(i, r) for i in xrange(n+1)]
return [lst[indices[i]:indices[i+1]] for i in xrange(n)], \
[list(xrange(indices[i], indices[i+1])) for i in xrange(n)] | [
"def",
"partition",
"(",
"lst",
",",
"n",
")",
":",
"q",
",",
"r",
"=",
"divmod",
"(",
"len",
"(",
"lst",
")",
",",
"n",
")",
"indices",
"=",
"[",
"q",
"*",
"i",
"+",
"min",
"(",
"i",
",",
"r",
")",
"for",
"i",
"in",
"xrange",
"(",
"n",
... | Divide list into n equal parts | [
"Divide",
"list",
"into",
"n",
"equal",
"parts"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/utilities.py#L32-L39 | train | 33,294 |
erdc/RAPIDpy | RAPIDpy/utilities.py | get_valid_directory_list | def get_valid_directory_list(input_directory):
"""
Get a list of folders
"""
valid_input_directories = []
for directory in os.listdir(input_directory):
if os.path.isdir(os.path.join(input_directory, directory)):
valid_input_directories.append(directory)
else:
print("{0} not a directory. Skipping ...".format(directory))
return valid_input_directories | python | def get_valid_directory_list(input_directory):
"""
Get a list of folders
"""
valid_input_directories = []
for directory in os.listdir(input_directory):
if os.path.isdir(os.path.join(input_directory, directory)):
valid_input_directories.append(directory)
else:
print("{0} not a directory. Skipping ...".format(directory))
return valid_input_directories | [
"def",
"get_valid_directory_list",
"(",
"input_directory",
")",
":",
"valid_input_directories",
"=",
"[",
"]",
"for",
"directory",
"in",
"os",
".",
"listdir",
"(",
"input_directory",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
... | Get a list of folders | [
"Get",
"a",
"list",
"of",
"folders"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/utilities.py#L42-L52 | train | 33,295 |
erdc/RAPIDpy | RAPIDpy/gis/taudem.py | TauDEM._run_mpi_cmd | def _run_mpi_cmd(self, cmd):
"""
This runs the command you send in
"""
log("Number of Processes: {0}".format(self.num_processors))
time_start = datetime.utcnow()
# Construct the taudem command line.
cmd = [self.mpiexec_path, '-n', str(self.num_processors)] + cmd
log("Command Line: {0}".format(" ".join(cmd)))
process = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=False)
out, err = process.communicate()
if out:
log("OUTPUT:")
for line in out.split(b'\n'):
log(line)
if err:
log(err, severity="WARNING")
log("Time to complete: {0}".format(datetime.utcnow()-time_start)) | python | def _run_mpi_cmd(self, cmd):
"""
This runs the command you send in
"""
log("Number of Processes: {0}".format(self.num_processors))
time_start = datetime.utcnow()
# Construct the taudem command line.
cmd = [self.mpiexec_path, '-n', str(self.num_processors)] + cmd
log("Command Line: {0}".format(" ".join(cmd)))
process = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=False)
out, err = process.communicate()
if out:
log("OUTPUT:")
for line in out.split(b'\n'):
log(line)
if err:
log(err, severity="WARNING")
log("Time to complete: {0}".format(datetime.utcnow()-time_start)) | [
"def",
"_run_mpi_cmd",
"(",
"self",
",",
"cmd",
")",
":",
"log",
"(",
"\"Number of Processes: {0}\"",
".",
"format",
"(",
"self",
".",
"num_processors",
")",
")",
"time_start",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"# Construct the taudem command line.",
"cm... | This runs the command you send in | [
"This",
"runs",
"the",
"command",
"you",
"send",
"in"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/taudem.py#L79-L97 | train | 33,296 |
erdc/RAPIDpy | RAPIDpy/gis/taudem.py | TauDEM._add_prj_file | def _add_prj_file(original_gis_file, new_gis_file):
"""
Adds projection file
"""
out_prj_file = "{0}.prj".format(os.path.splitext(new_gis_file)[0])
if original_gis_file.endswith(".shp"):
dataset = ogr.Open(original_gis_file)
layer = dataset.GetLayer()
spatial_ref = layer.GetSpatialRef()
spatial_ref.MorphToESRI()
spatial_ref_str = spatial_ref.ExportToWkt()
else:
dataset = gdal.Open(original_gis_file)
spatial_ref_str = dataset.GetProjection()
with open(out_prj_file, 'w') as prj_file:
prj_file.write(spatial_ref_str) | python | def _add_prj_file(original_gis_file, new_gis_file):
"""
Adds projection file
"""
out_prj_file = "{0}.prj".format(os.path.splitext(new_gis_file)[0])
if original_gis_file.endswith(".shp"):
dataset = ogr.Open(original_gis_file)
layer = dataset.GetLayer()
spatial_ref = layer.GetSpatialRef()
spatial_ref.MorphToESRI()
spatial_ref_str = spatial_ref.ExportToWkt()
else:
dataset = gdal.Open(original_gis_file)
spatial_ref_str = dataset.GetProjection()
with open(out_prj_file, 'w') as prj_file:
prj_file.write(spatial_ref_str) | [
"def",
"_add_prj_file",
"(",
"original_gis_file",
",",
"new_gis_file",
")",
":",
"out_prj_file",
"=",
"\"{0}.prj\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"new_gis_file",
")",
"[",
"0",
"]",
")",
"if",
"original_gis_file",
".",
"endswi... | Adds projection file | [
"Adds",
"projection",
"file"
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/taudem.py#L100-L116 | train | 33,297 |
erdc/RAPIDpy | RAPIDpy/gis/taudem.py | TauDEM.extractSubNetwork | def extractSubNetwork(network_file,
out_subset_network_file,
outlet_ids,
river_id_field,
next_down_id_field,
river_magnitude_field,
safe_mode=True):
"""
Extracts a subset river network from the main river network based on
the outlet IDs.
Parameters
----------
network_file: str
Path to the stream network shapefile.
out_subset_network_file: str
Path to the output subset stream network shapefile.
outlet_ids: list
List of integers reperesenting the outlet IDs to be included in
the subset stream network.
river_id_field: str
Name of the river ID field in the stream network shapefile.
next_down_id_field: str
Name if the field with the river ID of the next downstream
river segment in the stream network shapefile.
river_magnitude_field: str
Name of the river magnitude field in the stream network shapefile.
safe_mode: bool, optional
If True, it will kill the simulation early before over taxing
your computer. If you are confident your computer can handle it,
set it to False.
Here is an example of how to use this:
.. code:: python
import os
from RAPIDpy.gis.taudem import TauDEM
output_directory = '/path/to/output/files'
network_shp = os.path.join(output_directory,
"stream_reach_file.shp")
out_shp = os.path.join(output_directory,
"stream_reach_file_subset.shp")
TauDEM.extractSubNetwork(
network_file=network_shp,
out_subset_network_file=out_shp,
outlet_ids=[60830],
river_id_field="LINKNO",
next_down_id_field="DSLINKNO",
river_magnitude_field="Magnitude",
)
"""
network_shapefile = ogr.Open(network_file)
network_layer = network_shapefile.GetLayer()
number_of_features = network_layer.GetFeatureCount()
network_layer_defn = network_layer.GetLayerDefn()
rivid_list = np.zeros(number_of_features, dtype=np.int32)
next_down_rivid_list = np.zeros(number_of_features, dtype=np.int32)
for feature_idx, drainage_line_feature in enumerate(network_layer):
rivid_list[feature_idx] = \
drainage_line_feature.GetField(river_id_field)
next_down_rivid_list[feature_idx] = \
drainage_line_feature.GetField(next_down_id_field)
def getSubNetworkIDList(outlet_river_id,
_rivid_list,
_next_down_rivid_list):
"""
Adds ids upstream of the outlet to a list
"""
sub_network_index_list = []
try:
for feature_ii in \
np.where(_next_down_rivid_list == outlet_river_id)[0]:
sub_network_index_list.append(feature_ii)
sub_network_index_list += \
getSubNetworkIDList(_rivid_list[feature_ii],
_rivid_list,
_next_down_rivid_list)
except IndexError:
pass
return sub_network_index_list
original_recursion_limit = getrecursionlimit()
try:
main_sub_network_index_list = []
for outlet_id in outlet_ids:
outlet_index = np.where(rivid_list == outlet_id)[0][0]
outlet_feature = network_layer.GetFeature(outlet_index)
outlet_magnitude = \
outlet_feature.GetField(river_magnitude_field)
if outlet_magnitude > original_recursion_limit:
if not safe_mode:
setrecursionlimit(outlet_magnitude)
else:
raise Exception("Current recursion limit {0} will not "
"allow extraction for stream magnitude"
" {1}. To override, set safe_mode to "
"False ..."
.format(original_recursion_limit,
outlet_magnitude))
main_sub_network_index_list.append(outlet_index)
main_sub_network_index_list += \
getSubNetworkIDList(outlet_id,
rivid_list,
next_down_rivid_list)
except Exception:
setrecursionlimit(original_recursion_limit)
raise
setrecursionlimit(original_recursion_limit)
# Write out subset to new shapefile
shp_drv = ogr.GetDriverByName('ESRI Shapefile')
# Remove output shapefile if it already exists
if os.path.exists(out_subset_network_file):
shp_drv.DeleteDataSource(out_subset_network_file)
network_subset_shp = shp_drv.CreateDataSource(out_subset_network_file)
network_subset_layer = \
network_subset_shp.CreateLayer('',
network_layer.GetSpatialRef(),
ogr.wkbLineString)
# Add input Layer Fields to the output Layer if it is the one we want
for iii in xrange(network_layer_defn.GetFieldCount()):
network_subset_layer.CreateField(
network_layer_defn.GetFieldDefn(iii))
network_subset_layer_defn = network_subset_layer.GetLayerDefn()
for feature_index in main_sub_network_index_list:
subset_feature = network_layer.GetFeature(feature_index)
# add to list
new_feat = ogr.Feature(network_subset_layer_defn)
# Add field values from input Layer
for iii in xrange(network_layer_defn.GetFieldCount()):
new_feat.SetField(
network_subset_layer_defn.GetFieldDefn(iii).GetNameRef(),
subset_feature.GetField(iii))
# Set geometry as centroid
geom = subset_feature.GetGeometryRef()
new_feat.SetGeometry(geom.Clone())
# Add new feature to output Layer
network_subset_layer.CreateFeature(new_feat) | python | def extractSubNetwork(network_file,
out_subset_network_file,
outlet_ids,
river_id_field,
next_down_id_field,
river_magnitude_field,
safe_mode=True):
"""
Extracts a subset river network from the main river network based on
the outlet IDs.
Parameters
----------
network_file: str
Path to the stream network shapefile.
out_subset_network_file: str
Path to the output subset stream network shapefile.
outlet_ids: list
List of integers reperesenting the outlet IDs to be included in
the subset stream network.
river_id_field: str
Name of the river ID field in the stream network shapefile.
next_down_id_field: str
Name if the field with the river ID of the next downstream
river segment in the stream network shapefile.
river_magnitude_field: str
Name of the river magnitude field in the stream network shapefile.
safe_mode: bool, optional
If True, it will kill the simulation early before over taxing
your computer. If you are confident your computer can handle it,
set it to False.
Here is an example of how to use this:
.. code:: python
import os
from RAPIDpy.gis.taudem import TauDEM
output_directory = '/path/to/output/files'
network_shp = os.path.join(output_directory,
"stream_reach_file.shp")
out_shp = os.path.join(output_directory,
"stream_reach_file_subset.shp")
TauDEM.extractSubNetwork(
network_file=network_shp,
out_subset_network_file=out_shp,
outlet_ids=[60830],
river_id_field="LINKNO",
next_down_id_field="DSLINKNO",
river_magnitude_field="Magnitude",
)
"""
network_shapefile = ogr.Open(network_file)
network_layer = network_shapefile.GetLayer()
number_of_features = network_layer.GetFeatureCount()
network_layer_defn = network_layer.GetLayerDefn()
rivid_list = np.zeros(number_of_features, dtype=np.int32)
next_down_rivid_list = np.zeros(number_of_features, dtype=np.int32)
for feature_idx, drainage_line_feature in enumerate(network_layer):
rivid_list[feature_idx] = \
drainage_line_feature.GetField(river_id_field)
next_down_rivid_list[feature_idx] = \
drainage_line_feature.GetField(next_down_id_field)
def getSubNetworkIDList(outlet_river_id,
_rivid_list,
_next_down_rivid_list):
"""
Adds ids upstream of the outlet to a list
"""
sub_network_index_list = []
try:
for feature_ii in \
np.where(_next_down_rivid_list == outlet_river_id)[0]:
sub_network_index_list.append(feature_ii)
sub_network_index_list += \
getSubNetworkIDList(_rivid_list[feature_ii],
_rivid_list,
_next_down_rivid_list)
except IndexError:
pass
return sub_network_index_list
original_recursion_limit = getrecursionlimit()
try:
main_sub_network_index_list = []
for outlet_id in outlet_ids:
outlet_index = np.where(rivid_list == outlet_id)[0][0]
outlet_feature = network_layer.GetFeature(outlet_index)
outlet_magnitude = \
outlet_feature.GetField(river_magnitude_field)
if outlet_magnitude > original_recursion_limit:
if not safe_mode:
setrecursionlimit(outlet_magnitude)
else:
raise Exception("Current recursion limit {0} will not "
"allow extraction for stream magnitude"
" {1}. To override, set safe_mode to "
"False ..."
.format(original_recursion_limit,
outlet_magnitude))
main_sub_network_index_list.append(outlet_index)
main_sub_network_index_list += \
getSubNetworkIDList(outlet_id,
rivid_list,
next_down_rivid_list)
except Exception:
setrecursionlimit(original_recursion_limit)
raise
setrecursionlimit(original_recursion_limit)
# Write out subset to new shapefile
shp_drv = ogr.GetDriverByName('ESRI Shapefile')
# Remove output shapefile if it already exists
if os.path.exists(out_subset_network_file):
shp_drv.DeleteDataSource(out_subset_network_file)
network_subset_shp = shp_drv.CreateDataSource(out_subset_network_file)
network_subset_layer = \
network_subset_shp.CreateLayer('',
network_layer.GetSpatialRef(),
ogr.wkbLineString)
# Add input Layer Fields to the output Layer if it is the one we want
for iii in xrange(network_layer_defn.GetFieldCount()):
network_subset_layer.CreateField(
network_layer_defn.GetFieldDefn(iii))
network_subset_layer_defn = network_subset_layer.GetLayerDefn()
for feature_index in main_sub_network_index_list:
subset_feature = network_layer.GetFeature(feature_index)
# add to list
new_feat = ogr.Feature(network_subset_layer_defn)
# Add field values from input Layer
for iii in xrange(network_layer_defn.GetFieldCount()):
new_feat.SetField(
network_subset_layer_defn.GetFieldDefn(iii).GetNameRef(),
subset_feature.GetField(iii))
# Set geometry as centroid
geom = subset_feature.GetGeometryRef()
new_feat.SetGeometry(geom.Clone())
# Add new feature to output Layer
network_subset_layer.CreateFeature(new_feat) | [
"def",
"extractSubNetwork",
"(",
"network_file",
",",
"out_subset_network_file",
",",
"outlet_ids",
",",
"river_id_field",
",",
"next_down_id_field",
",",
"river_magnitude_field",
",",
"safe_mode",
"=",
"True",
")",
":",
"network_shapefile",
"=",
"ogr",
".",
"Open",
... | Extracts a subset river network from the main river network based on
the outlet IDs.
Parameters
----------
network_file: str
Path to the stream network shapefile.
out_subset_network_file: str
Path to the output subset stream network shapefile.
outlet_ids: list
List of integers reperesenting the outlet IDs to be included in
the subset stream network.
river_id_field: str
Name of the river ID field in the stream network shapefile.
next_down_id_field: str
Name if the field with the river ID of the next downstream
river segment in the stream network shapefile.
river_magnitude_field: str
Name of the river magnitude field in the stream network shapefile.
safe_mode: bool, optional
If True, it will kill the simulation early before over taxing
your computer. If you are confident your computer can handle it,
set it to False.
Here is an example of how to use this:
.. code:: python
import os
from RAPIDpy.gis.taudem import TauDEM
output_directory = '/path/to/output/files'
network_shp = os.path.join(output_directory,
"stream_reach_file.shp")
out_shp = os.path.join(output_directory,
"stream_reach_file_subset.shp")
TauDEM.extractSubNetwork(
network_file=network_shp,
out_subset_network_file=out_shp,
outlet_ids=[60830],
river_id_field="LINKNO",
next_down_id_field="DSLINKNO",
river_magnitude_field="Magnitude",
) | [
"Extracts",
"a",
"subset",
"river",
"network",
"from",
"the",
"main",
"river",
"network",
"based",
"on",
"the",
"outlet",
"IDs",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/taudem.py#L119-L268 | train | 33,298 |
erdc/RAPIDpy | RAPIDpy/gis/taudem.py | TauDEM.extractLargestSubNetwork | def extractLargestSubNetwork(cls,
network_file,
out_subset_network_file,
river_id_field,
next_down_id_field,
river_magnitude_field,
safe_mode=True):
"""
Extracts the larges sub network from the watershed based on the
magnitude parameter.
Parameters
----------
network_file: str
Path to the stream network shapefile.
out_subset_network_file: str
Path to the output subset stream network shapefile.
river_id_field: str
Name of the river ID field in the stream network shapefile.
next_down_id_field: str
Name of the field with the river ID of the next downstream river
segment in the stream network shapefile.
river_magnitude_field: str
Name of the river magnitude field in the stream network shapefile.
safe_mode: bool, optional
If True, it will kill the simulation early before over taxing
your computer. If you are confident your computer can handle it,
set it to False.
Here is an example of how to use this:
.. code:: python
import os
from RAPIDpy.gis.taudem import TauDEM
output_directory = '/path/to/output/files'
network_shp = os.path.join(output_directory,
"stream_reach_file.shp")
out_shp = os.path.join(output_directory,
"stream_reach_file_subset.shp")
TauDEM.extractLargestSubNetwork(
network_file=network_shp,
out_subset_network_file=out_shp,
river_id_field="LINKNO",
next_down_id_field="DSLINKNO",
river_magnitude_field="Magnitude",
)
"""
network_shapefile = ogr.Open(network_file)
network_layer = network_shapefile.GetLayer()
number_of_features = network_layer.GetFeatureCount()
riv_magnuitude_list = np.zeros(number_of_features, dtype=np.int32)
for feature_idx, drainage_line_feature in enumerate(network_layer):
riv_magnuitude_list[feature_idx] =\
drainage_line_feature.GetField(river_magnitude_field)
max_magnitude_feature = \
network_layer.GetFeature(np.argmax(riv_magnuitude_list))
cls.extractSubNetwork(network_file,
out_subset_network_file,
[max_magnitude_feature.GetField(river_id_field)],
river_id_field,
next_down_id_field,
river_magnitude_field,
safe_mode) | python | def extractLargestSubNetwork(cls,
network_file,
out_subset_network_file,
river_id_field,
next_down_id_field,
river_magnitude_field,
safe_mode=True):
"""
Extracts the larges sub network from the watershed based on the
magnitude parameter.
Parameters
----------
network_file: str
Path to the stream network shapefile.
out_subset_network_file: str
Path to the output subset stream network shapefile.
river_id_field: str
Name of the river ID field in the stream network shapefile.
next_down_id_field: str
Name of the field with the river ID of the next downstream river
segment in the stream network shapefile.
river_magnitude_field: str
Name of the river magnitude field in the stream network shapefile.
safe_mode: bool, optional
If True, it will kill the simulation early before over taxing
your computer. If you are confident your computer can handle it,
set it to False.
Here is an example of how to use this:
.. code:: python
import os
from RAPIDpy.gis.taudem import TauDEM
output_directory = '/path/to/output/files'
network_shp = os.path.join(output_directory,
"stream_reach_file.shp")
out_shp = os.path.join(output_directory,
"stream_reach_file_subset.shp")
TauDEM.extractLargestSubNetwork(
network_file=network_shp,
out_subset_network_file=out_shp,
river_id_field="LINKNO",
next_down_id_field="DSLINKNO",
river_magnitude_field="Magnitude",
)
"""
network_shapefile = ogr.Open(network_file)
network_layer = network_shapefile.GetLayer()
number_of_features = network_layer.GetFeatureCount()
riv_magnuitude_list = np.zeros(number_of_features, dtype=np.int32)
for feature_idx, drainage_line_feature in enumerate(network_layer):
riv_magnuitude_list[feature_idx] =\
drainage_line_feature.GetField(river_magnitude_field)
max_magnitude_feature = \
network_layer.GetFeature(np.argmax(riv_magnuitude_list))
cls.extractSubNetwork(network_file,
out_subset_network_file,
[max_magnitude_feature.GetField(river_id_field)],
river_id_field,
next_down_id_field,
river_magnitude_field,
safe_mode) | [
"def",
"extractLargestSubNetwork",
"(",
"cls",
",",
"network_file",
",",
"out_subset_network_file",
",",
"river_id_field",
",",
"next_down_id_field",
",",
"river_magnitude_field",
",",
"safe_mode",
"=",
"True",
")",
":",
"network_shapefile",
"=",
"ogr",
".",
"Open",
... | Extracts the larges sub network from the watershed based on the
magnitude parameter.
Parameters
----------
network_file: str
Path to the stream network shapefile.
out_subset_network_file: str
Path to the output subset stream network shapefile.
river_id_field: str
Name of the river ID field in the stream network shapefile.
next_down_id_field: str
Name of the field with the river ID of the next downstream river
segment in the stream network shapefile.
river_magnitude_field: str
Name of the river magnitude field in the stream network shapefile.
safe_mode: bool, optional
If True, it will kill the simulation early before over taxing
your computer. If you are confident your computer can handle it,
set it to False.
Here is an example of how to use this:
.. code:: python
import os
from RAPIDpy.gis.taudem import TauDEM
output_directory = '/path/to/output/files'
network_shp = os.path.join(output_directory,
"stream_reach_file.shp")
out_shp = os.path.join(output_directory,
"stream_reach_file_subset.shp")
TauDEM.extractLargestSubNetwork(
network_file=network_shp,
out_subset_network_file=out_shp,
river_id_field="LINKNO",
next_down_id_field="DSLINKNO",
river_magnitude_field="Magnitude",
) | [
"Extracts",
"the",
"larges",
"sub",
"network",
"from",
"the",
"watershed",
"based",
"on",
"the",
"magnitude",
"parameter",
"."
] | 50e14e130554b254a00ff23b226cd7e4c6cfe91a | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/taudem.py#L271-L338 | train | 33,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.