Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
VotingBot.subscribe_to_streams | (self) | Subscribes to zulip streams
| Subscribes to zulip streams
| def subscribe_to_streams(self):
''' Subscribes to zulip streams
'''
self.client.add_subscriptions(self.streams) | [
"def",
"subscribe_to_streams",
"(",
"self",
")",
":",
"self",
".",
"client",
".",
"add_subscriptions",
"(",
"self",
".",
"streams",
")"
] | [
58,
4
] | [
61,
51
] | python | en | ['en', 'en', 'de'] | True |
VotingBot.respond | (self, msg) | checks msg against key_word. If key_word is in msg, gets a gif url,
picks a caption, and calls send_message()
| checks msg against key_word. If key_word is in msg, gets a gif url,
picks a caption, and calls send_message()
| def respond(self, msg):
''' checks msg against key_word. If key_word is in msg, gets a gif url,
picks a caption, and calls send_message()
'''
# decode if necessary
if type(msg["content"]) == unicode:
content = msg["content"]
else:
content = ms... | [
"def",
"respond",
"(",
"self",
",",
"msg",
")",
":",
"# decode if necessary",
"if",
"type",
"(",
"msg",
"[",
"\"content\"",
"]",
")",
"==",
"unicode",
":",
"content",
"=",
"msg",
"[",
"\"content\"",
"]",
"else",
":",
"content",
"=",
"msg",
"[",
"\"cont... | [
63,
4
] | [
81,
52
] | python | en | ['en', 'en', 'en'] | True |
VotingBot.send_message | (self, msg) | Sends a message to zulip stream
| Sends a message to zulip stream
| def send_message(self, msg):
''' Sends a message to zulip stream
'''
if msg["type"] == "stream":
msg["to"] = msg['display_recipient']
elif msg["type"] == "private":
msg["to"] = msg["sender_email"]
self.client.send_message(msg) | [
"def",
"send_message",
"(",
"self",
",",
"msg",
")",
":",
"if",
"msg",
"[",
"\"type\"",
"]",
"==",
"\"stream\"",
":",
"msg",
"[",
"\"to\"",
"]",
"=",
"msg",
"[",
"'display_recipient'",
"]",
"elif",
"msg",
"[",
"\"type\"",
"]",
"==",
"\"private\"",
":",... | [
83,
4
] | [
92,
37
] | python | de | ['en', 'lb', 'de'] | False |
VotingBot.parse_public_message | (self, msg, content) | Parse public message given to the bot.
The resulting actions can be:
-send_results
-send_help
-add_voting_option
-add_vote
-new_voting_topic
-post_error
| Parse public message given to the bot. | def parse_public_message(self, msg, content):
'''Parse public message given to the bot.
The resulting actions can be:
-send_results
-send_help
-add_voting_option
-add_vote
-new_voting_topic
-post_error
'''
action, ... | [
"def",
"parse_public_message",
"(",
"self",
",",
"msg",
",",
"content",
")",
":",
"action",
",",
"title",
",",
"arg",
"=",
"self",
".",
"_parse_public_message",
"(",
"content",
")",
"if",
"action",
"==",
"\"results\"",
":",
"self",
".",
"send_results",
"("... | [
94,
4
] | [
125,
32
] | python | en | ['en', 'en', 'en'] | True |
VotingBot.parse_private_message | (self, msg, content) | Parse private message given to the bot.
The resulting actions can be:
-add_vote
-send_voting_help
-post_error
-send_partial_results
| Parse private message given to the bot. | def parse_private_message(self, msg, content):
'''Parse private message given to the bot.
The resulting actions can be:
-add_vote
-send_voting_help
-post_error
-send_partial_results
'''
msg_content = content.lower()
title = msg_co... | [
"def",
"parse_private_message",
"(",
"self",
",",
"msg",
",",
"content",
")",
":",
"msg_content",
"=",
"content",
".",
"lower",
"(",
")",
"title",
"=",
"msg_content",
".",
"split",
"(",
"\"\\n\"",
")",
"[",
"0",
"]",
"if",
"content",
".",
"lower",
"(",... | [
206,
4
] | [
245,
38
] | python | en | ['en', 'en', 'en'] | True |
VotingBot.new_voting_topic | (self, msg, title, options) | Create a new voting topic. | Create a new voting topic. | def new_voting_topic(self, msg, title, options):
'''Create a new voting topic.'''
print "Voting topic", title, "already?:", title.lower() in self.voting_topics
if title.lower() in self.voting_topics:
self.send_repeated_voting(msg)
elif title:
msg["content"] = t... | [
"def",
"new_voting_topic",
"(",
"self",
",",
"msg",
",",
"title",
",",
"options",
")",
":",
"print",
"\"Voting topic\"",
",",
"title",
",",
"\"already?:\"",
",",
"title",
".",
"lower",
"(",
")",
"in",
"self",
".",
"voting_topics",
"if",
"title",
".",
"lo... | [
265,
4
] | [
288,
31
] | python | en | ['en', 'en', 'en'] | True |
VotingBot.add_voting_option | (self, msg, title, new_voting_option) | Add a new voting option to an existing voting topic. | Add a new voting option to an existing voting topic. | def add_voting_option(self, msg, title, new_voting_option):
'''Add a new voting option to an existing voting topic.'''
if title.lower().strip() in self.voting_topics:
vote = self.voting_topics[title.lower().strip()]
options = vote["options"]
if self._not_already_the... | [
"def",
"add_voting_option",
"(",
"self",
",",
"msg",
",",
"title",
",",
"new_voting_option",
")",
":",
"if",
"title",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"in",
"self",
".",
"voting_topics",
":",
"vote",
"=",
"self",
".",
"voting_topics",
"[... | [
290,
4
] | [
315,
56
] | python | en | ['en', 'en', 'en'] | True |
VotingBot.add_vote | (self, msg, title, option_number) | Add a vote to an existing voting topic. | Add a vote to an existing voting topic. | def add_vote(self, msg, title, option_number):
'''Add a vote to an existing voting topic.'''
vote = self.voting_topics[title]
print vote
if option_number in vote["options"].keys():
if msg["sender_email"] not in vote["people_who_have_voted"]:
vote["options"]... | [
"def",
"add_vote",
"(",
"self",
",",
"msg",
",",
"title",
",",
"option_number",
")",
":",
"vote",
"=",
"self",
".",
"voting_topics",
"[",
"title",
"]",
"print",
"vote",
"if",
"option_number",
"in",
"vote",
"[",
"\"options\"",
"]",
".",
"keys",
"(",
")"... | [
321,
4
] | [
364,
48
] | python | en | ['en', 'en', 'en'] | True |
VotingBot._get_add_vote_msg | (self, msg, vote, option_number, changed_vote, title) | Creates a different msg if the vote was private or public. | Creates a different msg if the vote was private or public. | def _get_add_vote_msg(self, msg, vote, option_number, changed_vote, title):
'''Creates a different msg if the vote was private or public.'''
option_desc = vote["options"][option_number][0]
if changed_vote:
msg_content = "You have changed your vote. \n"
else:
msg... | [
"def",
"_get_add_vote_msg",
"(",
"self",
",",
"msg",
",",
"vote",
",",
"option_number",
",",
"changed_vote",
",",
"title",
")",
":",
"option_desc",
"=",
"vote",
"[",
"\"options\"",
"]",
"[",
"option_number",
"]",
"[",
"0",
"]",
"if",
"changed_vote",
":",
... | [
366,
4
] | [
382,
26
] | python | en | ['en', 'en', 'en'] | True |
VotingBot.send_results | (self, msg, title) | Publicly send results of voting in the thread that was used. | Publicly send results of voting in the thread that was used. | def send_results(self, msg, title):
'''Publicly send results of voting in the thread that was used.'''
if title.lower() in self.voting_topics:
msg["content"] = self._get_topic_results(title)
del self.voting_topics[title.lower()]
self.send_message(msg) | [
"def",
"send_results",
"(",
"self",
",",
"msg",
",",
"title",
")",
":",
"if",
"title",
".",
"lower",
"(",
")",
"in",
"self",
".",
"voting_topics",
":",
"msg",
"[",
"\"content\"",
"]",
"=",
"self",
".",
"_get_topic_results",
"(",
"title",
")",
"del",
... | [
401,
4
] | [
407,
34
] | python | en | ['en', 'en', 'en'] | True |
VotingBot.main | (self) | Blocking call that runs forever. Calls self.respond() on every
message received.
| Blocking call that runs forever. Calls self.respond() on every
message received.
| def main(self):
''' Blocking call that runs forever. Calls self.respond() on every
message received.
'''
self.client.call_on_each_message(lambda msg: self.respond(msg)) | [
"def",
"main",
"(",
"self",
")",
":",
"self",
".",
"client",
".",
"call_on_each_message",
"(",
"lambda",
"msg",
":",
"self",
".",
"respond",
"(",
"msg",
")",
")"
] | [
430,
4
] | [
434,
71
] | python | en | ['en', 'en', 'en'] | True |
Executor.run | (self, exe_path, cmd, local_cwd, file_deps=None, env=None) | Execute a command.
Be very careful not to change shared state in this function.
Executor objects are shared between python processes in `lit -jN`.
Args:
exe_path: str: Local path to the executable to be run
cmd: [str]: subprocess.call style command
... | Execute a command.
Be very careful not to change shared state in this function.
Executor objects are shared between python processes in `lit -jN`.
Args:
exe_path: str: Local path to the executable to be run
cmd: [str]: subprocess.call style command
... | def run(self, exe_path, cmd, local_cwd, file_deps=None, env=None):
"""Execute a command.
Be very careful not to change shared state in this function.
Executor objects are shared between python processes in `lit -jN`.
Args:
exe_path: str: Local path to the executabl... | [
"def",
"run",
"(",
"self",
",",
"exe_path",
",",
"cmd",
",",
"local_cwd",
",",
"file_deps",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"raise",
"NotImplementedError"
] | [
17,
4
] | [
30,
33
] | python | en | ['ro', 'en', 'en'] | True |
AdminNotifyHandlerTest.test_basic | (self, mock_function: MagicMock) | A random exception passes happily through AdminNotifyHandler | A random exception passes happily through AdminNotifyHandler | def test_basic(self, mock_function: MagicMock) -> None:
mock_function.return_value = None
"""A random exception passes happily through AdminNotifyHandler"""
handler = self.get_admin_zulip_handler()
try:
raise Exception("Testing error!")
except Exception:
e... | [
"def",
"test_basic",
"(",
"self",
",",
"mock_function",
":",
"MagicMock",
")",
"->",
"None",
":",
"mock_function",
".",
"return_value",
"=",
"None",
"handler",
"=",
"self",
".",
"get_admin_zulip_handler",
"(",
")",
"try",
":",
"raise",
"Exception",
"(",
"\"T... | [
64,
4
] | [
75,
28
] | python | en | ['en', 'en', 'en'] | True |
AdminNotifyHandlerTest.test_long_exception_request | (self, mock_function: MagicMock) | A request with no stack and multi-line report.getMessage() is handled properly | A request with no stack and multi-line report.getMessage() is handled properly | def test_long_exception_request(self, mock_function: MagicMock) -> None:
mock_function.return_value = None
"""A request with no stack and multi-line report.getMessage() is handled properly"""
record = self.simulate_error()
record.exc_info = None
record.msg = "message\nmoremesssag... | [
"def",
"test_long_exception_request",
"(",
"self",
",",
"mock_function",
":",
"MagicMock",
")",
"->",
"None",
":",
"mock_function",
".",
"return_value",
"=",
"None",
"record",
"=",
"self",
".",
"simulate_error",
"(",
")",
"record",
".",
"exc_info",
"=",
"None"... | [
116,
4
] | [
130,
54
] | python | en | ['en', 'en', 'en'] | True |
AdminNotifyHandlerTest.test_request | (self, mock_function: MagicMock) | A normal request is handled properly | A normal request is handled properly | def test_request(self, mock_function: MagicMock) -> None:
mock_function.return_value = None
"""A normal request is handled properly"""
record = self.simulate_error()
assert isinstance(record, HasRequest)
report = self.run_handler(record)
self.assertIn("user", report)
... | [
"def",
"test_request",
"(",
"self",
",",
"mock_function",
":",
"MagicMock",
")",
"->",
"None",
":",
"mock_function",
".",
"return_value",
"=",
"None",
"record",
"=",
"self",
".",
"simulate_error",
"(",
")",
"assert",
"isinstance",
"(",
"record",
",",
"HasReq... | [
133,
4
] | [
237,
44
] | python | en | ['en', 'en', 'en'] | True |
default_filter | (src, dst) | The default progress/filter callback; returns True for all files | The default progress/filter callback; returns True for all files | def default_filter(src, dst):
"""The default progress/filter callback; returns True for all files"""
return dst | [
"def",
"default_filter",
"(",
"src",
",",
"dst",
")",
":",
"return",
"dst"
] | [
22,
0
] | [
24,
14
] | python | en | ['en', 'sv', 'en'] | True |
unpack_archive | (
filename, extract_dir, progress_filter=default_filter,
drivers=None) | Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
`progress_filter` is a function taking two arguments: a source path
internal to the archive ('/'-separated), and a filesystem path where it
will be extracted. The callback must return the desired extract path
(which may be the same as... | Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat`` | def unpack_archive(
filename, extract_dir, progress_filter=default_filter,
drivers=None):
"""Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
`progress_filter` is a function taking two arguments: a source path
internal to the archive ('/'-separated), and a filesystem path... | [
"def",
"unpack_archive",
"(",
"filename",
",",
"extract_dir",
",",
"progress_filter",
"=",
"default_filter",
",",
"drivers",
"=",
"None",
")",
":",
"for",
"driver",
"in",
"drivers",
"or",
"extraction_drivers",
":",
"try",
":",
"driver",
"(",
"filename",
",",
... | [
27,
0
] | [
60,
9
] | python | en | ['en', 'la', 'en'] | True |
unpack_directory | (filename, extract_dir, progress_filter=default_filter) | Unpack" a directory, using the same interface as for archives
Raises ``UnrecognizedFormat`` if `filename` is not a directory
| Unpack" a directory, using the same interface as for archives | def unpack_directory(filename, extract_dir, progress_filter=default_filter):
""""Unpack" a directory, using the same interface as for archives
Raises ``UnrecognizedFormat`` if `filename` is not a directory
"""
if not os.path.isdir(filename):
raise UnrecognizedFormat("%s is not a directory" % fi... | [
"def",
"unpack_directory",
"(",
"filename",
",",
"extract_dir",
",",
"progress_filter",
"=",
"default_filter",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"filename",
")",
":",
"raise",
"UnrecognizedFormat",
"(",
"\"%s is not a directory\"",
"%"... | [
63,
0
] | [
87,
38
] | python | en | ['en', 'en', 'en'] | True |
unpack_zipfile | (filename, extract_dir, progress_filter=default_filter) | Unpack zip `filename` to `extract_dir`
Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation
of the `progress_filter` argument.
| Unpack zip `filename` to `extract_dir` | def unpack_zipfile(filename, extract_dir, progress_filter=default_filter):
"""Unpack zip `filename` to `extract_dir`
Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation
of the `progress_filter` argument.
... | [
"def",
"unpack_zipfile",
"(",
"filename",
",",
"extract_dir",
",",
"progress_filter",
"=",
"default_filter",
")",
":",
"if",
"not",
"zipfile",
".",
"is_zipfile",
"(",
"filename",
")",
":",
"raise",
"UnrecognizedFormat",
"(",
"\"%s is not a zip file\"",
"%",
"(",
... | [
90,
0
] | [
124,
49
] | python | en | ['en', 'nl', 'ur'] | False |
unpack_tarfile | (filename, extract_dir, progress_filter=default_filter) | Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
of the `progress_filter` argument.
| Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` | def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
"""Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
of the `progress_filter` a... | [
"def",
"unpack_tarfile",
"(",
"filename",
",",
"extract_dir",
",",
"progress_filter",
"=",
"default_filter",
")",
":",
"try",
":",
"tarobj",
"=",
"tarfile",
".",
"open",
"(",
"filename",
")",
"except",
"tarfile",
".",
"TarError",
"as",
"e",
":",
"raise",
"... | [
127,
0
] | [
171,
19
] | python | en | ['en', 'id', 'hi'] | False |
EmailBackend.send_messages | (self, email_messages) | Write all messages to the stream in a thread-safe way. | Write all messages to the stream in a thread-safe way. | def send_messages(self, email_messages):
"""Write all messages to the stream in a thread-safe way."""
if not email_messages:
return
msg_count = 0
with self._lock:
try:
stream_created = self.open()
for message in email_messages:
... | [
"def",
"send_messages",
"(",
"self",
",",
"email_messages",
")",
":",
"if",
"not",
"email_messages",
":",
"return",
"msg_count",
"=",
"0",
"with",
"self",
".",
"_lock",
":",
"try",
":",
"stream_created",
"=",
"self",
".",
"open",
"(",
")",
"for",
"messag... | [
26,
4
] | [
43,
24
] | python | en | ['en', 'en', 'en'] | True |
LinearStudentT.pdf | (self, X, Y) | Conditional probability density function p(y|x) of the underlying probability model
Args:
X: x to be conditioned on - numpy array of shape (n_points, ndim_x)
Y: y target values for witch the pdf shall be evaluated - numpy array of shape (n_points, ndim_y)
Returns:
p(X|Y) conditional density... | Conditional probability density function p(y|x) of the underlying probability model | def pdf(self, X, Y):
""" Conditional probability density function p(y|x) of the underlying probability model
Args:
X: x to be conditioned on - numpy array of shape (n_points, ndim_x)
Y: y target values for witch the pdf shall be evaluated - numpy array of shape (n_points, ndim_y)
Returns:
... | [
"def",
"pdf",
"(",
"self",
",",
"X",
",",
"Y",
")",
":",
"X",
",",
"Y",
"=",
"self",
".",
"_handle_input_dimensionality",
"(",
"X",
",",
"Y",
")",
"loc",
",",
"scale",
",",
"dof",
"=",
"self",
".",
"_loc_scale_dof_mapping",
"(",
"X",
")",
"p",
"=... | [
47,
2
] | [
61,
12
] | python | en | ['en', 'en', 'en'] | True |
LinearStudentT.cdf | (self, X, Y) | Conditional cumulated probability density function P(Y < y | x) of the underlying probability model
Args:
X: x to be conditioned on - numpy array of shape (n_points, ndim_x)
Y: y target values for witch the cdf shall be evaluated - numpy array of shape (n_points, ndim_y)
Returns:
... | Conditional cumulated probability density function P(Y < y | x) of the underlying probability model | def cdf(self, X, Y):
""" Conditional cumulated probability density function P(Y < y | x) of the underlying probability model
Args:
X: x to be conditioned on - numpy array of shape (n_points, ndim_x)
Y: y target values for witch the cdf shall be evaluated - numpy array of shape (n_points, n... | [
"def",
"cdf",
"(",
"self",
",",
"X",
",",
"Y",
")",
":",
"X",
",",
"Y",
"=",
"self",
".",
"_handle_input_dimensionality",
"(",
"X",
",",
"Y",
")",
"loc",
",",
"scale",
",",
"dof",
"=",
"self",
".",
"_loc_scale_dof_mapping",
"(",
"X",
")",
"p",
"=... | [
63,
2
] | [
77,
12
] | python | en | ['en', 'en', 'en'] | True |
LinearStudentT.simulate_conditional | (self, X) | Draws random samples from the conditional distribution
Args:
X: x to be conditioned on when drawing a sample from y ~ p(y|x) - numpy array of shape (n_samples, ndim_x)
Returns:
Conditional random samples y drawn from p(y|x) - numpy array of shape (n_samples, ndim_y)
| Draws random samples from the conditional distribution | def simulate_conditional(self, X):
""" Draws random samples from the conditional distribution
Args:
X: x to be conditioned on when drawing a sample from y ~ p(y|x) - numpy array of shape (n_samples, ndim_x)
Returns:
Conditional random samples y drawn from p(y|x) - numpy array of shape (n_sampl... | [
"def",
"simulate_conditional",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"self",
".",
"_handle_input_dimensionality",
"(",
"X",
")",
"loc",
",",
"scale",
",",
"dof",
"=",
"self",
".",
"_loc_scale_dof_mapping",
"(",
"X",
")",
"Y",
"=",
"batched_univ_t_rvs"... | [
79,
2
] | [
92,
15
] | python | en | ['en', 'en', 'en'] | True |
LinearStudentT.simulate | (self, n_samples=1000) | Draws random samples from the joint distribution p(x,y)
Args:
n_samples: (int) number of samples to be drawn from the joint distribution
Returns:
(X,Y) - random samples drawn from p(x,y) - numpy arrays of shape (n_samples, ndim_x) and (n_samples, ndim_y)
| Draws random samples from the joint distribution p(x,y)
Args:
n_samples: (int) number of samples to be drawn from the joint distribution | def simulate(self, n_samples=1000):
""" Draws random samples from the joint distribution p(x,y)
Args:
n_samples: (int) number of samples to be drawn from the joint distribution
Returns:
(X,Y) - random samples drawn from p(x,y) - numpy arrays of shape (n_samples, ndim_x) and (n_samples, ndim_y)
... | [
"def",
"simulate",
"(",
"self",
",",
"n_samples",
"=",
"1000",
")",
":",
"assert",
"n_samples",
">",
"0",
"X",
"=",
"self",
".",
"random_state",
".",
"normal",
"(",
"loc",
"=",
"0",
",",
"scale",
"=",
"1",
",",
"size",
"=",
"(",
"n_samples",
",",
... | [
94,
2
] | [
104,
39
] | python | en | ['en', 'en', 'en'] | True |
LinearStudentT.mean_ | (self, x_cond, n_samples=None) | Conditional mean of the distribution
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
Returns:
Means E[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y)
| Conditional mean of the distribution
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x) | def mean_(self, x_cond, n_samples=None):
""" Conditional mean of the distribution
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
Returns:
Means E[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y)
"""
assert x_cond.ndim == ... | [
"def",
"mean_",
"(",
"self",
",",
"x_cond",
",",
"n_samples",
"=",
"None",
")",
":",
"assert",
"x_cond",
".",
"ndim",
"==",
"2",
"and",
"x_cond",
".",
"shape",
"[",
"1",
"]",
"==",
"self",
".",
"ndim_x",
"x_cond",
"=",
"self",
".",
"_handle_input_dim... | [
106,
2
] | [
116,
28
] | python | en | ['en', 'en', 'en'] | True |
LinearStudentT.std_ | (self, x_cond, n_samples=None) | Standard deviation of the distribution conditioned on x_cond
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
Returns:
Conditional standard deviations Std[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y)
| Standard deviation of the distribution conditioned on x_cond | def std_(self, x_cond, n_samples=None):
""" Standard deviation of the distribution conditioned on x_cond
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
Returns:
Conditional standard deviations Std[y|x] corresponding to x_cond - numpy array of... | [
"def",
"std_",
"(",
"self",
",",
"x_cond",
",",
"n_samples",
"=",
"None",
")",
":",
"assert",
"x_cond",
".",
"ndim",
"==",
"2",
"and",
"x_cond",
".",
"shape",
"[",
"1",
"]",
"==",
"self",
".",
"ndim_x",
"x_cond",
"=",
"self",
".",
"_handle_input_dime... | [
118,
2
] | [
131,
14
] | python | en | ['en', 'en', 'en'] | True |
empirical_evaluation | (estimator, valid_portion=0.2, moment_r2=True, eval_by_fc=False, fit_by_cv=False) |
Fits the estimator and, based on a left out validation splot, computes the
Root Mean Squared Error (RMSE) between realized and estimated mean and std
Args:
estimator: estimator object
valid_portion: portion of dataset to be separated as validation set
moment_r2: (bool) whether to compute... |
Fits the estimator and, based on a left out validation splot, computes the
Root Mean Squared Error (RMSE) between realized and estimated mean and std | def empirical_evaluation(estimator, valid_portion=0.2, moment_r2=True, eval_by_fc=False, fit_by_cv=False):
"""
Fits the estimator and, based on a left out validation splot, computes the
Root Mean Squared Error (RMSE) between realized and estimated mean and std
Args:
estimator: estimator object
... | [
"def",
"empirical_evaluation",
"(",
"estimator",
",",
"valid_portion",
"=",
"0.2",
",",
"moment_r2",
"=",
"True",
",",
"eval_by_fc",
"=",
"False",
",",
"fit_by_cv",
"=",
"False",
")",
":",
"# get data and split into train and valid set",
"df_train",
",",
"df_valid",... | [
51,
0
] | [
105,
59
] | python | en | ['en', 'error', 'th'] | False |
initialize_models | (model_dict, verbose=False, model_name_prefix='') | make kartesian product of listed parameters per model | make kartesian product of listed parameters per model | def initialize_models(model_dict, verbose=False, model_name_prefix=''):
''' make kartesian product of listed parameters per model '''
model_configs = {}
for model_key, conf_dict in model_dict.items():
model_configs[model_key] = [dict(zip(conf_dict.keys(), value_tuple)) for value_tuple in
... | [
"def",
"initialize_models",
"(",
"model_dict",
",",
"verbose",
"=",
"False",
",",
"model_name_prefix",
"=",
"''",
")",
":",
"model_configs",
"=",
"{",
"}",
"for",
"model_key",
",",
"conf_dict",
"in",
"model_dict",
".",
"items",
"(",
")",
":",
"model_configs"... | [
155,
0
] | [
172,
30
] | python | en | ['en', 'id', 'en'] | True |
unpack_udp_packet | (packet: bytes) | Convert raw UDP packet to an appropriately-typed telemetry packet.
Args:
packet: the contents of the UDP packet to be unpacked.
Returns:
The decoded packet structure.
Raises:
UnpackError if a problem is detected.
| Convert raw UDP packet to an appropriately-typed telemetry packet. | def unpack_udp_packet(packet: bytes) -> PackedLittleEndianStructure:
"""Convert raw UDP packet to an appropriately-typed telemetry packet.
Args:
packet: the contents of the UDP packet to be unpacked.
Returns:
The decoded packet structure.
Raises:
UnpackError if a problem is de... | [
"def",
"unpack_udp_packet",
"(",
"packet",
":",
"bytes",
")",
"->",
"PackedLittleEndianStructure",
":",
"actual_packet_size",
"=",
"len",
"(",
"packet",
")",
"header_size",
"=",
"ctypes",
".",
"sizeof",
"(",
"PacketHeader",
")",
"if",
"actual_packet_size",
"<",
... | [
812,
0
] | [
852,
47
] | python | en | ['en', 'en', 'en'] | True |
TestLocaleModel.test_change_root_page_locale_on_locale_deletion | (self) |
On deleting the locale used for the root page (but no 'real' pages), the
root page should be reassigned to a new locale (the default one, if possible)
|
On deleting the locale used for the root page (but no 'real' pages), the
root page should be reassigned to a new locale (the default one, if possible)
| def test_change_root_page_locale_on_locale_deletion(self):
"""
On deleting the locale used for the root page (but no 'real' pages), the
root page should be reassigned to a new locale (the default one, if possible)
"""
# change 'real' pages first
Page.objects.filter(depth_... | [
"def",
"test_change_root_page_locale_on_locale_deletion",
"(",
"self",
")",
":",
"# change 'real' pages first",
"Page",
".",
"objects",
".",
"filter",
"(",
"depth__gt",
"=",
"1",
")",
".",
"update",
"(",
"locale",
"=",
"Locale",
".",
"objects",
".",
"get",
"(",
... | [
62,
4
] | [
71,
79
] | python | en | ['en', 'error', 'th'] | False |
sanitize_name | (value: str) |
Sanitizes a value to be safe to store in a Linux filesystem, in
S3, and in a URL. So Unicode is allowed, but not special
characters other than ".", "-", and "_".
This implementation is based on django.utils.text.slugify; it is
modified by:
* adding '.' to the list of allowed characters.
*... |
Sanitizes a value to be safe to store in a Linux filesystem, in
S3, and in a URL. So Unicode is allowed, but not special
characters other than ".", "-", and "_". | def sanitize_name(value: str) -> str:
"""
Sanitizes a value to be safe to store in a Linux filesystem, in
S3, and in a URL. So Unicode is allowed, but not special
characters other than ".", "-", and "_".
This implementation is based on django.utils.text.slugify; it is
modified by:
* adding... | [
"def",
"sanitize_name",
"(",
"value",
":",
"str",
")",
"->",
"str",
":",
"value",
"=",
"unicodedata",
".",
"normalize",
"(",
"\"NFKC\"",
",",
"value",
")",
"value",
"=",
"re",
".",
"sub",
"(",
"r\"[^\\w\\s.-]\"",
",",
"\"\"",
",",
"value",
",",
"flags"... | [
81,
0
] | [
97,
27
] | python | en | ['en', 'error', 'th'] | False |
Wallet.hack_populate_secret_keys_for_coin_solutions | (self, coin_solutions: List[CoinSolution]) |
This hack forces secret keys into the `_pk2sk` lookup. This should eventually be replaced
by a persistent DB table that can do this look-up directly.
|
This hack forces secret keys into the `_pk2sk` lookup. This should eventually be replaced
by a persistent DB table that can do this look-up directly.
| async def hack_populate_secret_keys_for_coin_solutions(self, coin_solutions: List[CoinSolution]) -> None:
"""
This hack forces secret keys into the `_pk2sk` lookup. This should eventually be replaced
by a persistent DB table that can do this look-up directly.
"""
for coin_solutio... | [
"async",
"def",
"hack_populate_secret_keys_for_coin_solutions",
"(",
"self",
",",
"coin_solutions",
":",
"List",
"[",
"CoinSolution",
"]",
")",
"->",
"None",
":",
"for",
"coin_solution",
"in",
"coin_solutions",
":",
"await",
"self",
".",
"hack_populate_secret_key_for_... | [
165,
4
] | [
171,
95
] | python | en | ['en', 'error', 'th'] | False |
Wallet.select_coins | (self, amount, exclude: List[Coin] = None) |
Returns a set of coins that can be used for generating a new transaction.
Note: This must be called under a wallet state manager lock
|
Returns a set of coins that can be used for generating a new transaction.
Note: This must be called under a wallet state manager lock
| async def select_coins(self, amount, exclude: List[Coin] = None) -> Set[Coin]:
"""
Returns a set of coins that can be used for generating a new transaction.
Note: This must be called under a wallet state manager lock
"""
if exclude is None:
exclude = []
spend... | [
"async",
"def",
"select_coins",
"(",
"self",
",",
"amount",
",",
"exclude",
":",
"List",
"[",
"Coin",
"]",
"=",
"None",
")",
"->",
"Set",
"[",
"Coin",
"]",
":",
"if",
"exclude",
"is",
"None",
":",
"exclude",
"=",
"[",
"]",
"spendable_amount",
"=",
... | [
231,
4
] | [
283,
25
] | python | en | ['en', 'error', 'th'] | False |
Wallet._generate_unsigned_transaction | (
self,
amount: uint64,
newpuzzlehash: bytes32,
fee: uint64 = uint64(0),
origin_id: bytes32 = None,
coins: Set[Coin] = None,
primaries_input: Optional[List[Dict[str, Any]]] = None,
ignore_max_send_amount: bool = False,
) |
Generates a unsigned transaction in form of List(Puzzle, Solutions)
Note: this must be called under a wallet state manager lock
|
Generates a unsigned transaction in form of List(Puzzle, Solutions)
Note: this must be called under a wallet state manager lock
| async def _generate_unsigned_transaction(
self,
amount: uint64,
newpuzzlehash: bytes32,
fee: uint64 = uint64(0),
origin_id: bytes32 = None,
coins: Set[Coin] = None,
primaries_input: Optional[List[Dict[str, Any]]] = None,
ignore_max_send_amount: bool = Fals... | [
"async",
"def",
"_generate_unsigned_transaction",
"(",
"self",
",",
"amount",
":",
"uint64",
",",
"newpuzzlehash",
":",
"bytes32",
",",
"fee",
":",
"uint64",
"=",
"uint64",
"(",
"0",
")",
",",
"origin_id",
":",
"bytes32",
"=",
"None",
",",
"coins",
":",
... | [
285,
4
] | [
361,
21
] | python | en | ['en', 'error', 'th'] | False |
Wallet.generate_signed_transaction | (
self,
amount: uint64,
puzzle_hash: bytes32,
fee: uint64 = uint64(0),
origin_id: bytes32 = None,
coins: Set[Coin] = None,
primaries: Optional[List[Dict[str, bytes32]]] = None,
ignore_max_send_amount: bool = False,
) |
Use this to generate transaction.
Note: this must be called under a wallet state manager lock
|
Use this to generate transaction.
Note: this must be called under a wallet state manager lock
| async def generate_signed_transaction(
self,
amount: uint64,
puzzle_hash: bytes32,
fee: uint64 = uint64(0),
origin_id: bytes32 = None,
coins: Set[Coin] = None,
primaries: Optional[List[Dict[str, bytes32]]] = None,
ignore_max_send_amount: bool = False,
... | [
"async",
"def",
"generate_signed_transaction",
"(",
"self",
",",
"amount",
":",
"uint64",
",",
"puzzle_hash",
":",
"bytes32",
",",
"fee",
":",
"uint64",
"=",
"uint64",
"(",
"0",
")",
",",
"origin_id",
":",
"bytes32",
"=",
"None",
",",
"coins",
":",
"Set"... | [
371,
4
] | [
425,
9
] | python | en | ['en', 'error', 'th'] | False |
Wallet.push_transaction | (self, tx: TransactionRecord) | Use this API to send transactions. | Use this API to send transactions. | async def push_transaction(self, tx: TransactionRecord) -> None:
"""Use this API to send transactions."""
await self.wallet_state_manager.add_pending_transaction(tx) | [
"async",
"def",
"push_transaction",
"(",
"self",
",",
"tx",
":",
"TransactionRecord",
")",
"->",
"None",
":",
"await",
"self",
".",
"wallet_state_manager",
".",
"add_pending_transaction",
"(",
"tx",
")"
] | [
427,
4
] | [
429,
67
] | python | en | ['en', 'en', 'en'] | True |
run_app_happily | (root, other_task) | This method, which runs Kivy, is run by the asyncio loop as one of the
coroutines.
| This method, which runs Kivy, is run by the asyncio loop as one of the
coroutines.
| async def run_app_happily(root, other_task):
'''This method, which runs Kivy, is run by the asyncio loop as one of the
coroutines.
'''
# we don't actually need to set asyncio as the lib because it is the
# default, but it doesn't hurt to be explicit
await async_runTouchApp(root, async_lib='async... | [
"async",
"def",
"run_app_happily",
"(",
"root",
",",
"other_task",
")",
":",
"# we don't actually need to set asyncio as the lib because it is the",
"# default, but it doesn't hurt to be explicit",
"await",
"async_runTouchApp",
"(",
"root",
",",
"async_lib",
"=",
"'asyncio'",
"... | [
21,
0
] | [
30,
23
] | python | en | ['en', 'en', 'en'] | True |
waste_time_freely | () | This method is also run by the asyncio loop and periodically prints
something.
| This method is also run by the asyncio loop and periodically prints
something.
| async def waste_time_freely():
'''This method is also run by the asyncio loop and periodically prints
something.
'''
try:
while True:
print('Sitting on the beach')
await asyncio.sleep(2)
except asyncio.CancelledError as e:
print('Wasting time was canceled', e)... | [
"async",
"def",
"waste_time_freely",
"(",
")",
":",
"try",
":",
"while",
"True",
":",
"print",
"(",
"'Sitting on the beach'",
")",
"await",
"asyncio",
".",
"sleep",
"(",
"2",
")",
"except",
"asyncio",
".",
"CancelledError",
"as",
"e",
":",
"print",
"(",
... | [
33,
0
] | [
45,
34
] | python | en | ['en', 'en', 'en'] | True |
differential_evolution | (func, bounds, args=(), strategy='best1bin',
maxiter=1000, popsize=15, tol=0.01,
mutation=(0.5, 1), recombination=0.7, seed=None,
callback=None, disp=False, polish=True,
init='latinhypercube', atol=0) | Finds the global minimum of a multivariate function.
Differential Evolution is stochastic in nature (does not use gradient
methods) to find the minimium, and can search large areas of candidate
space, but often requires larger numbers of function evaluations than
conventional gradient based techniques.
... | Finds the global minimum of a multivariate function.
Differential Evolution is stochastic in nature (does not use gradient
methods) to find the minimium, and can search large areas of candidate
space, but often requires larger numbers of function evaluations than
conventional gradient based techniques.
... | def differential_evolution(func, bounds, args=(), strategy='best1bin',
maxiter=1000, popsize=15, tol=0.01,
mutation=(0.5, 1), recombination=0.7, seed=None,
callback=None, disp=False, polish=True,
init='latinhyper... | [
"def",
"differential_evolution",
"(",
"func",
",",
"bounds",
",",
"args",
"=",
"(",
")",
",",
"strategy",
"=",
"'best1bin'",
",",
"maxiter",
"=",
"1000",
",",
"popsize",
"=",
"15",
",",
"tol",
"=",
"0.01",
",",
"mutation",
"=",
"(",
"0.5",
",",
"1",
... | [
26,
0
] | [
213,
25
] | python | en | ['en', 'en', 'en'] | True |
DifferentialEvolutionSolver.init_population_lhs | (self) |
Initializes the population with Latin Hypercube Sampling.
Latin Hypercube Sampling ensures that each parameter is uniformly
sampled over its range.
|
Initializes the population with Latin Hypercube Sampling.
Latin Hypercube Sampling ensures that each parameter is uniformly
sampled over its range.
| def init_population_lhs(self):
"""
Initializes the population with Latin Hypercube Sampling.
Latin Hypercube Sampling ensures that each parameter is uniformly
sampled over its range.
"""
rng = self.random_number_generator
# Each parameter range needs to be sample... | [
"def",
"init_population_lhs",
"(",
"self",
")",
":",
"rng",
"=",
"self",
".",
"random_number_generator",
"# Each parameter range needs to be sampled uniformly. The scaled",
"# parameter range ([0, 1)) needs to be split into",
"# `self.num_population_members` segments, each of which has the... | [
432,
4
] | [
468,
22
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver.init_population_random | (self) |
Initialises the population at random. This type of initialization
can possess clustering, Latin Hypercube sampling is generally better.
|
Initialises the population at random. This type of initialization
can possess clustering, Latin Hypercube sampling is generally better.
| def init_population_random(self):
"""
Initialises the population at random. This type of initialization
can possess clustering, Latin Hypercube sampling is generally better.
"""
rng = self.random_number_generator
self.population = rng.random_sample(self.population_shape)... | [
"def",
"init_population_random",
"(",
"self",
")",
":",
"rng",
"=",
"self",
".",
"random_number_generator",
"self",
".",
"population",
"=",
"rng",
".",
"random_sample",
"(",
"self",
".",
"population_shape",
")",
"# reset population energies",
"self",
".",
"populat... | [
470,
4
] | [
483,
22
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver.init_population_array | (self, init) |
Initialises the population with a user specified population.
Parameters
----------
init : np.ndarray
Array specifying subset of the initial population. The array should
have shape (M, len(x)), where len(x) is the number of parameters.
The population i... |
Initialises the population with a user specified population.
Parameters
----------
init : np.ndarray
Array specifying subset of the initial population. The array should
have shape (M, len(x)), where len(x) is the number of parameters.
The population i... | def init_population_array(self, init):
"""
Initialises the population with a user specified population.
Parameters
----------
init : np.ndarray
Array specifying subset of the initial population. The array should
have shape (M, len(x)), where len(x) is the ... | [
"def",
"init_population_array",
"(",
"self",
",",
"init",
")",
":",
"# make sure you're using a float array",
"popn",
"=",
"np",
".",
"asfarray",
"(",
"init",
")",
"if",
"(",
"np",
".",
"size",
"(",
"popn",
",",
"0",
")",
"<",
"5",
"or",
"popn",
".",
"... | [
485,
4
] | [
517,
22
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver.x | (self) |
The best solution from the solver
Returns
-------
x : ndarray
The best solution from the solver.
|
The best solution from the solver
Returns
-------
x : ndarray
The best solution from the solver.
| def x(self):
"""
The best solution from the solver
Returns
-------
x : ndarray
The best solution from the solver.
"""
return self._scale_parameters(self.population[0]) | [
"def",
"x",
"(",
"self",
")",
":",
"return",
"self",
".",
"_scale_parameters",
"(",
"self",
".",
"population",
"[",
"0",
"]",
")"
] | [
520,
4
] | [
528,
57
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver.convergence | (self) |
The standard deviation of the population energies divided by their
mean.
|
The standard deviation of the population energies divided by their
mean.
| def convergence(self):
"""
The standard deviation of the population energies divided by their
mean.
"""
return (np.std(self.population_energies) /
np.abs(np.mean(self.population_energies) + _MACHEPS)) | [
"def",
"convergence",
"(",
"self",
")",
":",
"return",
"(",
"np",
".",
"std",
"(",
"self",
".",
"population_energies",
")",
"/",
"np",
".",
"abs",
"(",
"np",
".",
"mean",
"(",
"self",
".",
"population_energies",
")",
"+",
"_MACHEPS",
")",
")"
] | [
531,
4
] | [
537,
69
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver.solve | (self) |
Runs the DifferentialEvolutionSolver.
Returns
-------
res : OptimizeResult
The optimization result represented as a ``OptimizeResult`` object.
Important attributes are: ``x`` the solution array, ``success`` a
Boolean flag indicating if the optimizer e... |
Runs the DifferentialEvolutionSolver.
Returns
-------
res : OptimizeResult
The optimization result represented as a ``OptimizeResult`` object.
Important attributes are: ``x`` the solution array, ``success`` a
Boolean flag indicating if the optimizer e... | def solve(self):
"""
Runs the DifferentialEvolutionSolver.
Returns
-------
res : OptimizeResult
The optimization result represented as a ``OptimizeResult`` object.
Important attributes are: ``x`` the solution array, ``success`` a
Boolean flag i... | [
"def",
"solve",
"(",
"self",
")",
":",
"nit",
",",
"warning_flag",
"=",
"0",
",",
"False",
"status_message",
"=",
"_status_message",
"[",
"'success'",
"]",
"# The population may have just been initialized (all entries are",
"# np.inf). If it has you have to calculate the init... | [
539,
4
] | [
627,
24
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver._calculate_population_energies | (self) |
Calculate the energies of all the population members at the same time.
Puts the best member in first place. Useful if the population has just
been initialised.
|
Calculate the energies of all the population members at the same time.
Puts the best member in first place. Useful if the population has just
been initialised.
| def _calculate_population_energies(self):
"""
Calculate the energies of all the population members at the same time.
Puts the best member in first place. Useful if the population has just
been initialised.
"""
##############
## CHANGES: self.func operates on the ... | [
"def",
"_calculate_population_energies",
"(",
"self",
")",
":",
"##############",
"## CHANGES: self.func operates on the entire parameters array",
"##############",
"itersize",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"len",
"(",
"self",
".",
"population",
")",
",",
"se... | [
629,
4
] | [
667,
73
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver.__next__ | (self) |
Evolve the population by a single generation
Returns
-------
x : ndarray
The best solution from the solver.
fun : float
Value of objective function obtained from the best solution.
|
Evolve the population by a single generation
Returns
-------
x : ndarray
The best solution from the solver.
fun : float
Value of objective function obtained from the best solution.
| def __next__(self):
"""
Evolve the population by a single generation
Returns
-------
x : ndarray
The best solution from the solver.
fun : float
Value of objective function obtained from the best solution.
"""
# the population may ha... | [
"def",
"__next__",
"(",
"self",
")",
":",
"# the population may have just been initialized (all entries are",
"# np.inf). If it has you have to calculate the initial energies",
"if",
"np",
".",
"all",
"(",
"np",
".",
"isinf",
"(",
"self",
".",
"population_energies",
")",
")... | [
672,
4
] | [
747,
50
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver.next | (self) |
Evolve the population by a single generation
Returns
-------
x : ndarray
The best solution from the solver.
fun : float
Value of objective function obtained from the best solution.
|
Evolve the population by a single generation
Returns
-------
x : ndarray
The best solution from the solver.
fun : float
Value of objective function obtained from the best solution.
| def next(self):
"""
Evolve the population by a single generation
Returns
-------
x : ndarray
The best solution from the solver.
fun : float
Value of objective function obtained from the best solution.
"""
# next() is required for co... | [
"def",
"next",
"(",
"self",
")",
":",
"# next() is required for compatibility with Python2.7.",
"return",
"self",
".",
"__next__",
"(",
")"
] | [
749,
4
] | [
760,
30
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver._scale_parameters | (self, trial) |
scale from a number between 0 and 1 to parameters.
|
scale from a number between 0 and 1 to parameters.
| def _scale_parameters(self, trial):
"""
scale from a number between 0 and 1 to parameters.
"""
return self.__scale_arg1 + (trial - 0.5) * self.__scale_arg2 | [
"def",
"_scale_parameters",
"(",
"self",
",",
"trial",
")",
":",
"return",
"self",
".",
"__scale_arg1",
"+",
"(",
"trial",
"-",
"0.5",
")",
"*",
"self",
".",
"__scale_arg2"
] | [
762,
4
] | [
766,
68
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver._unscale_parameters | (self, parameters) |
scale from parameters to a number between 0 and 1.
|
scale from parameters to a number between 0 and 1.
| def _unscale_parameters(self, parameters):
"""
scale from parameters to a number between 0 and 1.
"""
return (parameters - self.__scale_arg1) / self.__scale_arg2 + 0.5 | [
"def",
"_unscale_parameters",
"(",
"self",
",",
"parameters",
")",
":",
"return",
"(",
"parameters",
"-",
"self",
".",
"__scale_arg1",
")",
"/",
"self",
".",
"__scale_arg2",
"+",
"0.5"
] | [
768,
4
] | [
772,
73
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver._ensure_constraint | (self, trial) |
make sure the parameters lie between the limits
|
make sure the parameters lie between the limits
| def _ensure_constraint(self, trial):
"""
make sure the parameters lie between the limits
"""
for index in np.where((trial < 0) | (trial > 1))[0]:
trial[index] = self.random_number_generator.rand() | [
"def",
"_ensure_constraint",
"(",
"self",
",",
"trial",
")",
":",
"for",
"index",
"in",
"np",
".",
"where",
"(",
"(",
"trial",
"<",
"0",
")",
"|",
"(",
"trial",
">",
"1",
")",
")",
"[",
"0",
"]",
":",
"trial",
"[",
"index",
"]",
"=",
"self",
... | [
774,
4
] | [
779,
62
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver._mutate | (self, candidate) |
create a trial vector based on a mutation strategy
|
create a trial vector based on a mutation strategy
| def _mutate(self, candidate):
"""
create a trial vector based on a mutation strategy
"""
trial = np.copy(self.population[candidate])
rng = self.random_number_generator
fill_point = rng.randint(0, self.parameter_count)
if self.strategy in ['currenttobest1exp', '... | [
"def",
"_mutate",
"(",
"self",
",",
"candidate",
")",
":",
"trial",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"population",
"[",
"candidate",
"]",
")",
"rng",
"=",
"self",
".",
"random_number_generator",
"fill_point",
"=",
"rng",
".",
"randint",
"(",
"... | [
781,
4
] | [
817,
24
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver._best1 | (self, samples) |
best1bin, best1exp
|
best1bin, best1exp
| def _best1(self, samples):
"""
best1bin, best1exp
"""
r0, r1 = samples[:2]
return (self.population[0] + self.scale *
(self.population[r0] - self.population[r1])) | [
"def",
"_best1",
"(",
"self",
",",
"samples",
")",
":",
"r0",
",",
"r1",
"=",
"samples",
"[",
":",
"2",
"]",
"return",
"(",
"self",
".",
"population",
"[",
"0",
"]",
"+",
"self",
".",
"scale",
"*",
"(",
"self",
".",
"population",
"[",
"r0",
"]"... | [
819,
4
] | [
825,
60
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver._rand1 | (self, samples) |
rand1bin, rand1exp
|
rand1bin, rand1exp
| def _rand1(self, samples):
"""
rand1bin, rand1exp
"""
r0, r1, r2 = samples[:3]
return (self.population[r0] + self.scale *
(self.population[r1] - self.population[r2])) | [
"def",
"_rand1",
"(",
"self",
",",
"samples",
")",
":",
"r0",
",",
"r1",
",",
"r2",
"=",
"samples",
"[",
":",
"3",
"]",
"return",
"(",
"self",
".",
"population",
"[",
"r0",
"]",
"+",
"self",
".",
"scale",
"*",
"(",
"self",
".",
"population",
"[... | [
827,
4
] | [
833,
60
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver._randtobest1 | (self, samples) |
randtobest1bin, randtobest1exp
|
randtobest1bin, randtobest1exp
| def _randtobest1(self, samples):
"""
randtobest1bin, randtobest1exp
"""
r0, r1, r2 = samples[:3]
bprime = np.copy(self.population[r0])
bprime += self.scale * (self.population[0] - bprime)
bprime += self.scale * (self.population[r1] -
... | [
"def",
"_randtobest1",
"(",
"self",
",",
"samples",
")",
":",
"r0",
",",
"r1",
",",
"r2",
"=",
"samples",
"[",
":",
"3",
"]",
"bprime",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"population",
"[",
"r0",
"]",
")",
"bprime",
"+=",
"self",
".",
"s... | [
835,
4
] | [
844,
21
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver._currenttobest1 | (self, candidate, samples) |
currenttobest1bin, currenttobest1exp
|
currenttobest1bin, currenttobest1exp
| def _currenttobest1(self, candidate, samples):
"""
currenttobest1bin, currenttobest1exp
"""
r0, r1 = samples[:2]
bprime = (self.population[candidate] + self.scale *
(self.population[0] - self.population[candidate] +
self.population[r0] - self... | [
"def",
"_currenttobest1",
"(",
"self",
",",
"candidate",
",",
"samples",
")",
":",
"r0",
",",
"r1",
"=",
"samples",
"[",
":",
"2",
"]",
"bprime",
"=",
"(",
"self",
".",
"population",
"[",
"candidate",
"]",
"+",
"self",
".",
"scale",
"*",
"(",
"self... | [
846,
4
] | [
854,
21
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver._best2 | (self, samples) |
best2bin, best2exp
|
best2bin, best2exp
| def _best2(self, samples):
"""
best2bin, best2exp
"""
r0, r1, r2, r3 = samples[:4]
bprime = (self.population[0] + self.scale *
(self.population[r0] + self.population[r1] -
self.population[r2] - self.population[r3]))
return bprime | [
"def",
"_best2",
"(",
"self",
",",
"samples",
")",
":",
"r0",
",",
"r1",
",",
"r2",
",",
"r3",
"=",
"samples",
"[",
":",
"4",
"]",
"bprime",
"=",
"(",
"self",
".",
"population",
"[",
"0",
"]",
"+",
"self",
".",
"scale",
"*",
"(",
"self",
".",... | [
856,
4
] | [
865,
21
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver._rand2 | (self, samples) |
rand2bin, rand2exp
|
rand2bin, rand2exp
| def _rand2(self, samples):
"""
rand2bin, rand2exp
"""
r0, r1, r2, r3, r4 = samples
bprime = (self.population[r0] + self.scale *
(self.population[r1] + self.population[r2] -
self.population[r3] - self.population[r4]))
return bprime | [
"def",
"_rand2",
"(",
"self",
",",
"samples",
")",
":",
"r0",
",",
"r1",
",",
"r2",
",",
"r3",
",",
"r4",
"=",
"samples",
"bprime",
"=",
"(",
"self",
".",
"population",
"[",
"r0",
"]",
"+",
"self",
".",
"scale",
"*",
"(",
"self",
".",
"populati... | [
867,
4
] | [
876,
21
] | python | en | ['en', 'error', 'th'] | False |
DifferentialEvolutionSolver._select_samples | (self, candidate, number_samples) |
obtain random integers from range(self.num_population_members),
without replacement. You can't have the original candidate either.
|
obtain random integers from range(self.num_population_members),
without replacement. You can't have the original candidate either.
| def _select_samples(self, candidate, number_samples):
"""
obtain random integers from range(self.num_population_members),
without replacement. You can't have the original candidate either.
"""
idxs = list(range(self.num_population_members))
idxs.remove(candidate)
... | [
"def",
"_select_samples",
"(",
"self",
",",
"candidate",
",",
"number_samples",
")",
":",
"idxs",
"=",
"list",
"(",
"range",
"(",
"self",
".",
"num_population_members",
")",
")",
"idxs",
".",
"remove",
"(",
"candidate",
")",
"self",
".",
"random_number_gener... | [
878,
4
] | [
887,
19
] | python | en | ['en', 'error', 'th'] | False |
_filter_heads | (heads, heads_height, radius, polygon) | Filter the head candidates following Kienholz et al. (2014), Ch. 4.1.2
Parameters
----------
heads : list of shapely.geometry.Point instances
The heads to filter out (in raster coordinates).
heads_height : list
The heads altitudes.
radius : float
The radius around each head ... | Filter the head candidates following Kienholz et al. (2014), Ch. 4.1.2 | def _filter_heads(heads, heads_height, radius, polygon):
"""Filter the head candidates following Kienholz et al. (2014), Ch. 4.1.2
Parameters
----------
heads : list of shapely.geometry.Point instances
The heads to filter out (in raster coordinates).
heads_height : list
The heads al... | [
"def",
"_filter_heads",
"(",
"heads",
",",
"heads_height",
",",
"radius",
",",
"polygon",
")",
":",
"heads",
"=",
"copy",
".",
"copy",
"(",
"heads",
")",
"heads_height",
"=",
"copy",
".",
"copy",
"(",
"heads_height",
")",
"i",
"=",
"0",
"# I think a \"wh... | [
307,
0
] | [
380,
30
] | python | en | ['en', 'fr', 'en'] | True |
_filter_lines | (lines, heads, k, r) | Filter the centerline candidates by length.
Kienholz et al. (2014), Ch. 4.3.1
Parameters
----------
lines : list of shapely.geometry.LineString instances
The lines to filter out (in raster coordinates).
heads : list of shapely.geometry.Point instances
The heads corresponding to th... | Filter the centerline candidates by length. | def _filter_lines(lines, heads, k, r):
"""Filter the centerline candidates by length.
Kienholz et al. (2014), Ch. 4.3.1
Parameters
----------
lines : list of shapely.geometry.LineString instances
The lines to filter out (in raster coordinates).
heads : list of shapely.geometry.Point i... | [
"def",
"_filter_lines",
"(",
"lines",
",",
"heads",
",",
"k",
",",
"r",
")",
":",
"olines",
"=",
"[",
"]",
"oheads",
"=",
"[",
"]",
"ilines",
"=",
"copy",
".",
"copy",
"(",
"lines",
")",
"lastline",
"=",
"None",
"while",
"len",
"(",
"ilines",
")"... | [
383,
0
] | [
465,
25
] | python | en | ['en', 'en', 'en'] | True |
_filter_lines_slope | (lines, heads, topo, gdir, min_slope) | Filter the centerline candidates by slope: if they go up, remove
Kienholz et al. (2014), Ch. 4.3.1
Parameters
----------
lines : list of shapely.geometry.LineString instances
The lines to filter out (in raster coordinates).
topo : the glacier topography
gdir : the glacier directory for... | Filter the centerline candidates by slope: if they go up, remove | def _filter_lines_slope(lines, heads, topo, gdir, min_slope):
"""Filter the centerline candidates by slope: if they go up, remove
Kienholz et al. (2014), Ch. 4.3.1
Parameters
----------
lines : list of shapely.geometry.LineString instances
The lines to filter out (in raster coordinates).
... | [
"def",
"_filter_lines_slope",
"(",
"lines",
",",
"heads",
",",
"topo",
",",
"gdir",
",",
"min_slope",
")",
":",
"dx_cls",
"=",
"cfg",
".",
"PARAMS",
"[",
"'flowline_dx'",
"]",
"lid",
"=",
"int",
"(",
"cfg",
".",
"PARAMS",
"[",
"'flowline_junction_pix'",
... | [
468,
0
] | [
528,
25
] | python | en | ['en', 'en', 'en'] | True |
_projection_point | (centerline, point) | Projects a point on a line and returns the closest integer point
guaranteed to be on the line, and guaranteed to be far enough from the
head and tail.
Parameters
----------
centerline : Centerline instance
point : Shapely Point geometry
Returns
-------
(flow_point, ind_closest): Sh... | Projects a point on a line and returns the closest integer point
guaranteed to be on the line, and guaranteed to be far enough from the
head and tail. | def _projection_point(centerline, point):
"""Projects a point on a line and returns the closest integer point
guaranteed to be on the line, and guaranteed to be far enough from the
head and tail.
Parameters
----------
centerline : Centerline instance
point : Shapely Point geometry
Retu... | [
"def",
"_projection_point",
"(",
"centerline",
",",
"point",
")",
":",
"prdis",
"=",
"centerline",
".",
"line",
".",
"project",
"(",
"point",
",",
"normalized",
"=",
"False",
")",
"ind_closest",
"=",
"np",
".",
"argmin",
"(",
"np",
".",
"abs",
"(",
"ce... | [
531,
0
] | [
548,
21
] | python | en | ['en', 'en', 'en'] | True |
_join_lines | (lines, heads) | Re-joins the lines that have been cut by _filter_lines
Compute the rooting scheme.
Parameters
----------
lines: list of shapely lines instances
Returns
-------
Centerline instances, updated with flow routing properties
| Re-joins the lines that have been cut by _filter_lines | def _join_lines(lines, heads):
"""Re-joins the lines that have been cut by _filter_lines
Compute the rooting scheme.
Parameters
----------
lines: list of shapely lines instances
Returns
-------
Centerline instances, updated with flow routing properties
"""
olines = [Centerl... | [
"def",
"_join_lines",
"(",
"lines",
",",
"heads",
")",
":",
"olines",
"=",
"[",
"Centerline",
"(",
"l",
",",
"orig_head",
"=",
"h",
")",
"for",
"l",
",",
"h",
"in",
"zip",
"(",
"lines",
"[",
":",
":",
"-",
"1",
"]",
",",
"heads",
"[",
":",
":... | [
551,
0
] | [
599,
23
] | python | en | ['en', 'en', 'en'] | True |
line_order | (line) | Recursive search for the line's hydrological level.
Parameters
----------
line: a Centerline instance
Returns
-------
The line's order
| Recursive search for the line's hydrological level. | def line_order(line):
"""Recursive search for the line's hydrological level.
Parameters
----------
line: a Centerline instance
Returns
-------
The line's order
"""
if len(line.inflows) == 0:
return 0
else:
levels = [line_order(s) for s in line.inflows]
... | [
"def",
"line_order",
"(",
"line",
")",
":",
"if",
"len",
"(",
"line",
".",
"inflows",
")",
"==",
"0",
":",
"return",
"0",
"else",
":",
"levels",
"=",
"[",
"line_order",
"(",
"s",
")",
"for",
"s",
"in",
"line",
".",
"inflows",
"]",
"return",
"np",... | [
602,
0
] | [
618,
33
] | python | en | ['en', 'en', 'en'] | True |
line_inflows | (line, keep=True) | Recursive search for all inflows of the given line.
Parameters
----------
line: a Centerline instance
keep : bool
whether or not the line itself should be kept
Returns
-------
A list of lines (including the line itself) sorted in order
| Recursive search for all inflows of the given line. | def line_inflows(line, keep=True):
"""Recursive search for all inflows of the given line.
Parameters
----------
line: a Centerline instance
keep : bool
whether or not the line itself should be kept
Returns
-------
A list of lines (including the line itself) sorted in order
... | [
"def",
"line_inflows",
"(",
"line",
",",
"keep",
"=",
"True",
")",
":",
"out",
"=",
"set",
"(",
"[",
"line",
"]",
")",
"for",
"l",
"in",
"line",
".",
"inflows",
":",
"out",
"=",
"out",
".",
"union",
"(",
"line_inflows",
"(",
"l",
")",
")",
"out... | [
621,
0
] | [
643,
14
] | python | en | ['en', 'en', 'en'] | True |
_make_costgrid | (mask, ext, z) | Computes a costgrid following Kienholz et al. (2014) Eq. (2)
Parameters
----------
mask : numpy.array
The glacier mask.
ext : numpy.array
The glacier boundaries' mask.
z : numpy.array
The terrain height.
Returns
-------
numpy.array of the costgrid
| Computes a costgrid following Kienholz et al. (2014) Eq. (2) | def _make_costgrid(mask, ext, z):
"""Computes a costgrid following Kienholz et al. (2014) Eq. (2)
Parameters
----------
mask : numpy.array
The glacier mask.
ext : numpy.array
The glacier boundaries' mask.
z : numpy.array
The terrain height.
Returns
-------
n... | [
"def",
"_make_costgrid",
"(",
"mask",
",",
"ext",
",",
"z",
")",
":",
"dis",
"=",
"np",
".",
"where",
"(",
"mask",
",",
"distance_transform_edt",
"(",
"mask",
")",
",",
"np",
".",
"NaN",
")",
"z",
"=",
"np",
".",
"where",
"(",
"mask",
",",
"z",
... | [
646,
0
] | [
676,
39
] | python | en | ['en', 'ca', 'en'] | True |
_get_terminus_coord | (gdir, ext_yx, zoutline) | This finds the terminus coordinate of the glacier.
There is a special case for marine terminating glaciers/
| This finds the terminus coordinate of the glacier. | def _get_terminus_coord(gdir, ext_yx, zoutline):
"""This finds the terminus coordinate of the glacier.
There is a special case for marine terminating glaciers/
"""
perc = cfg.PARAMS['terminus_search_percentile']
deltah = cfg.PARAMS['terminus_search_altitude_range']
if gdir.is_tidewater and ... | [
"def",
"_get_terminus_coord",
"(",
"gdir",
",",
"ext_yx",
",",
"zoutline",
")",
":",
"perc",
"=",
"cfg",
".",
"PARAMS",
"[",
"'terminus_search_percentile'",
"]",
"deltah",
"=",
"cfg",
".",
"PARAMS",
"[",
"'terminus_search_altitude_range'",
"]",
"if",
"gdir",
"... | [
679,
0
] | [
721,
59
] | python | en | ['en', 'en', 'en'] | True |
_normalize | (n) | Computes the normals of a vector n.
Returns
-------
the two normals (n1, n2)
| Computes the normals of a vector n. | def _normalize(n):
"""Computes the normals of a vector n.
Returns
-------
the two normals (n1, n2)
"""
nn = n / np.sqrt(np.sum(n*n))
n1 = np.array([-nn[1], nn[0]])
n2 = np.array([nn[1], -nn[0]])
return n1, n2 | [
"def",
"_normalize",
"(",
"n",
")",
":",
"nn",
"=",
"n",
"/",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"n",
"*",
"n",
")",
")",
"n1",
"=",
"np",
".",
"array",
"(",
"[",
"-",
"nn",
"[",
"1",
"]",
",",
"nn",
"[",
"0",
"]",
"]",
")... | [
724,
0
] | [
734,
17
] | python | en | ['en', 'en', 'en'] | True |
_line_extend | (uline, dline, dx) | Adds a downstream line to a flowline
Parameters
----------
uline: a shapely.geometry.LineString instance
dline: a shapely.geometry.LineString instance
dx: the spacing
Returns
-------
(line, line) : two shapely.geometry.LineString instances. The first
contains the newly created (lon... | Adds a downstream line to a flowline | def _line_extend(uline, dline, dx):
"""Adds a downstream line to a flowline
Parameters
----------
uline: a shapely.geometry.LineString instance
dline: a shapely.geometry.LineString instance
dx: the spacing
Returns
-------
(line, line) : two shapely.geometry.LineString instances. Th... | [
"def",
"_line_extend",
"(",
"uline",
",",
"dline",
",",
"dx",
")",
":",
"# First points is easy",
"points",
"=",
"[",
"shpg",
".",
"Point",
"(",
"c",
")",
"for",
"c",
"in",
"uline",
".",
"coords",
"]",
"if",
"len",
"(",
"points",
")",
"==",
"0",
":... | [
782,
0
] | [
833,
60
] | python | en | ['en', 'pl', 'en'] | True |
compute_centerlines | (gdir, heads=None) | Compute the centerlines following Kienholz et al., (2014).
They are then sorted according to the modified Strahler number:
http://en.wikipedia.org/wiki/Strahler_number
This function does not initialize a :py:class:`oggm.Centerline` but
calculates routes along the topography and makes a
:py:class:`... | Compute the centerlines following Kienholz et al., (2014). | def compute_centerlines(gdir, heads=None):
"""Compute the centerlines following Kienholz et al., (2014).
They are then sorted according to the modified Strahler number:
http://en.wikipedia.org/wiki/Strahler_number
This function does not initialize a :py:class:`oggm.Centerline` but
calculates route... | [
"def",
"compute_centerlines",
"(",
"gdir",
",",
"heads",
"=",
"None",
")",
":",
"# Params",
"single_fl",
"=",
"not",
"cfg",
".",
"PARAMS",
"[",
"'use_multiple_flowlines'",
"]",
"do_filter_slope",
"=",
"cfg",
".",
"PARAMS",
"[",
"'filter_min_slope'",
"]",
"min_... | [
837,
0
] | [
943,
63
] | python | en | ['en', 'fr', 'en'] | True |
compute_downstream_line | (gdir) | Computes the Flowline along the unglaciated downstream topography
The idea is simple: starting from the glacier tail, compute all the routes
to all local minima found at the domain edge. The cheapest is "The One".
The rest of the job (merging centerlines + downstream into
one single glacier is realize... | Computes the Flowline along the unglaciated downstream topography | def compute_downstream_line(gdir):
"""Computes the Flowline along the unglaciated downstream topography
The idea is simple: starting from the glacier tail, compute all the routes
to all local minima found at the domain edge. The cheapest is "The One".
The rest of the job (merging centerlines + downstr... | [
"def",
"compute_downstream_line",
"(",
"gdir",
")",
":",
"# For tidewater glaciers no need for all this",
"if",
"gdir",
".",
"is_tidewater",
":",
"return",
"with",
"utils",
".",
"ncDataset",
"(",
"gdir",
".",
"get_filepath",
"(",
"'gridded_data'",
")",
")",
"as",
... | [
947,
0
] | [
1025,
45
] | python | en | ['en', 'en', 'en'] | True |
_approx_parabola | (x, y, y0=0) | Fit a parabola to the equation y = a x**2 + y0
Parameters
----------
x : array
the x axis variabls
y : array
the dependent variable
y0 : float, optional
the intercept
Returns
-------
[a, 0, y0]
| Fit a parabola to the equation y = a x**2 + y0 | def _approx_parabola(x, y, y0=0):
"""Fit a parabola to the equation y = a x**2 + y0
Parameters
----------
x : array
the x axis variabls
y : array
the dependent variable
y0 : float, optional
the intercept
Returns
-------
[a, 0, y0]
"""
# y=ax**2+y0
x... | [
"def",
"_approx_parabola",
"(",
"x",
",",
"y",
",",
"y0",
"=",
"0",
")",
":",
"# y=ax**2+y0",
"x",
",",
"y",
"=",
"np",
".",
"array",
"(",
"x",
")",
",",
"np",
".",
"array",
"(",
"y",
")",
"a",
"=",
"np",
".",
"sum",
"(",
"x",
"**",
"2",
... | [
1028,
0
] | [
1047,
31
] | python | en | ['en', 'en', 'es'] | True |
_parabolic_bed_from_topo | (gdir, idl, interpolator) | this returns the parabolic bedshape for all points on idl | this returns the parabolic bedshape for all points on idl | def _parabolic_bed_from_topo(gdir, idl, interpolator):
"""this returns the parabolic bedshape for all points on idl"""
# Volume area scaling formula for the probable ice thickness
h_mean = 0.034 * gdir.rgi_area_km2**0.375 * 1000
gnx, gny = gdir.grid.nx, gdir.grid.ny
# Far Factor
r = 40
# n... | [
"def",
"_parabolic_bed_from_topo",
"(",
"gdir",
",",
"idl",
",",
"interpolator",
")",
":",
"# Volume area scaling formula for the probable ice thickness",
"h_mean",
"=",
"0.034",
"*",
"gdir",
".",
"rgi_area_km2",
"**",
"0.375",
"*",
"1000",
"gnx",
",",
"gny",
"=",
... | [
1063,
0
] | [
1181,
24
] | python | en | ['en', 'en', 'en'] | True |
compute_downstream_bedshape | (gdir) | The bedshape obtained by fitting a parabola to the line's normals.
Also computes the downstream's altitude.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
| The bedshape obtained by fitting a parabola to the line's normals. | def compute_downstream_bedshape(gdir):
"""The bedshape obtained by fitting a parabola to the line's normals.
Also computes the downstream's altitude.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
"""
# For tidewater glaciers no need for all... | [
"def",
"compute_downstream_bedshape",
"(",
"gdir",
")",
":",
"# For tidewater glaciers no need for all this",
"if",
"gdir",
".",
"is_tidewater",
":",
"return",
"# We make a flowline out of the downstream for simplicity",
"tpl",
"=",
"gdir",
".",
"read_pickle",
"(",
"'inversio... | [
1185,
0
] | [
1229,
45
] | python | en | ['en', 'en', 'en'] | True |
_mask_to_polygon | (mask, gdir=None) | Converts a mask to a single polygon.
The mask should be a single entity with nunataks: I didn't test for more
than one "blob".
Parameters
----------
mask: 2d array with ones and zeros
the mask to convert
gdir: GlacierDirectory
for logging
Returns
-------
(poly, pol... | Converts a mask to a single polygon. | def _mask_to_polygon(mask, gdir=None):
"""Converts a mask to a single polygon.
The mask should be a single entity with nunataks: I didn't test for more
than one "blob".
Parameters
----------
mask: 2d array with ones and zeros
the mask to convert
gdir: GlacierDirectory
for l... | [
"def",
"_mask_to_polygon",
"(",
"mask",
",",
"gdir",
"=",
"None",
")",
":",
"regions",
",",
"nregions",
"=",
"label",
"(",
"mask",
",",
"structure",
"=",
"LABEL_STRUCT",
")",
"if",
"nregions",
">",
"1",
":",
"rid",
"=",
"''",
"if",
"gdir",
"is",
"not... | [
1232,
0
] | [
1278,
24
] | python | en | ['en', 'mk', 'en'] | True |
_point_width | (normals, point, centerline, poly, poly_no_nunataks) | Compute the geometrical width on a specific point.
Called by catchment_width_geom.
Parameters
----------
normals: normals of the current point, before, and after
point: the centerline's point
centerline: Centerline object
poly, poly_no_nuntaks: subcatchment polygons
Returns
-----... | Compute the geometrical width on a specific point. | def _point_width(normals, point, centerline, poly, poly_no_nunataks):
""" Compute the geometrical width on a specific point.
Called by catchment_width_geom.
Parameters
----------
normals: normals of the current point, before, and after
point: the centerline's point
centerline: Centerline o... | [
"def",
"_point_width",
"(",
"normals",
",",
"point",
",",
"centerline",
",",
"poly",
",",
"poly_no_nunataks",
")",
":",
"# How far should the normal vector reach? (make it large)",
"far_factor",
"=",
"150.",
"normal",
"=",
"shpg",
".",
"LineString",
"(",
"[",
"shpg"... | [
1281,
0
] | [
1347,
22
] | python | en | ['en', 'en', 'en'] | True |
_filter_small_slopes | (hgt, dx, min_slope) | Masks out slopes with NaN until the slope if all valid points is at
least min_slope (in radians).
| Masks out slopes with NaN until the slope if all valid points is at
least min_slope (in radians).
| def _filter_small_slopes(hgt, dx, min_slope):
"""Masks out slopes with NaN until the slope if all valid points is at
least min_slope (in radians).
"""
slope = np.arctan(-np.gradient(hgt, dx)) # beware the minus sign
# slope at the end always OK
slope[-1] = min_slope
# Find the locs where ... | [
"def",
"_filter_small_slopes",
"(",
"hgt",
",",
"dx",
",",
"min_slope",
")",
":",
"slope",
"=",
"np",
".",
"arctan",
"(",
"-",
"np",
".",
"gradient",
"(",
"hgt",
",",
"dx",
")",
")",
"# beware the minus sign",
"# slope at the end always OK",
"slope",
"[",
... | [
1350,
0
] | [
1378,
14
] | python | en | ['en', 'en', 'en'] | True |
_filter_for_altitude_range | (widths, wlines, topo) | Some width lines have unrealistic length and go over the whole
glacier. Filter them out. | Some width lines have unrealistic length and go over the whole
glacier. Filter them out. | def _filter_for_altitude_range(widths, wlines, topo):
"""Some width lines have unrealistic length and go over the whole
glacier. Filter them out."""
# altitude range threshold (if range over the line > threshold, filter it)
alt_range_th = cfg.PARAMS['width_alt_range_thres']
while True:
out... | [
"def",
"_filter_for_altitude_range",
"(",
"widths",
",",
"wlines",
",",
"topo",
")",
":",
"# altitude range threshold (if range over the line > threshold, filter it)",
"alt_range_th",
"=",
"cfg",
".",
"PARAMS",
"[",
"'width_alt_range_thres'",
"]",
"while",
"True",
":",
"o... | [
1381,
0
] | [
1418,
20
] | python | en | ['en', 'en', 'en'] | True |
_filter_grouplen | (arr, minsize=3) | Filter out the groups of grid points smaller than minsize
Parameters
----------
arr : the array to filter (should be False and Trues)
minsize : the minimum size of the group
Returns
-------
the array, with small groups removed
| Filter out the groups of grid points smaller than minsize | def _filter_grouplen(arr, minsize=3):
"""Filter out the groups of grid points smaller than minsize
Parameters
----------
arr : the array to filter (should be False and Trues)
minsize : the minimum size of the group
Returns
-------
the array, with small groups removed
"""
# Do ... | [
"def",
"_filter_grouplen",
"(",
"arr",
",",
"minsize",
"=",
"3",
")",
":",
"# Do it with trues",
"r",
",",
"nr",
"=",
"label",
"(",
"arr",
")",
"nr",
"=",
"[",
"i",
"+",
"1",
"for",
"i",
",",
"o",
"in",
"enumerate",
"(",
"find_objects",
"(",
"r",
... | [
1421,
0
] | [
1444,
14
] | python | en | ['en', 'en', 'en'] | True |
catchment_area | (gdir) | Compute the catchment areas of each tributary line.
The idea is to compute the route of lowest cost for any point on the
glacier to rejoin a centerline. These routes are then put together if
they belong to the same centerline, thus creating "catchment areas" for
each centerline.
Parameters
---... | Compute the catchment areas of each tributary line. | def catchment_area(gdir):
"""Compute the catchment areas of each tributary line.
The idea is to compute the route of lowest cost for any point on the
glacier to rejoin a centerline. These routes are then put together if
they belong to the same centerline, thus creating "catchment areas" for
each ce... | [
"def",
"catchment_area",
"(",
"gdir",
")",
":",
"# Variables",
"cls",
"=",
"gdir",
".",
"read_pickle",
"(",
"'centerlines'",
")",
"geom",
"=",
"gdir",
".",
"read_pickle",
"(",
"'geometries'",
")",
"glacier_pix",
"=",
"geom",
"[",
"'polygon_pix'",
"]",
"fpath... | [
1453,
0
] | [
1565,
41
] | python | en | ['en', 'en', 'en'] | True |
catchment_intersections | (gdir) | Computes the intersections between the catchments.
A glacier usually consists of several flowlines and each flowline has a
distinct catchment area. This function calculates the intersections between
these areas.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to wr... | Computes the intersections between the catchments. | def catchment_intersections(gdir):
"""Computes the intersections between the catchments.
A glacier usually consists of several flowlines and each flowline has a
distinct catchment area. This function calculates the intersections between
these areas.
Parameters
----------
gdir : :py:class:`... | [
"def",
"catchment_intersections",
"(",
"gdir",
")",
":",
"catchment_indices",
"=",
"gdir",
".",
"read_pickle",
"(",
"'geometries'",
")",
"[",
"'catchment_indices'",
"]",
"# Loop over the lines",
"mask",
"=",
"np",
".",
"zeros",
"(",
"(",
"gdir",
".",
"grid",
"... | [
1569,
0
] | [
1620,
59
] | python | en | ['en', 'en', 'en'] | True |
initialize_flowlines | (gdir) | Computes more physical Inversion Flowlines from geometrical Centerlines
This interpolates the centerlines on a regular spacing (i.e. not the
grid's (i, j) indices. Cuts out the tail of the tributaries to make more
realistic junctions. Also checks for low and negative slopes and corrects
them by interp... | Computes more physical Inversion Flowlines from geometrical Centerlines | def initialize_flowlines(gdir):
""" Computes more physical Inversion Flowlines from geometrical Centerlines
This interpolates the centerlines on a regular spacing (i.e. not the
grid's (i, j) indices. Cuts out the tail of the tributaries to make more
realistic junctions. Also checks for low and negative... | [
"def",
"initialize_flowlines",
"(",
"gdir",
")",
":",
"# variables",
"cls",
"=",
"gdir",
".",
"read_pickle",
"(",
"'centerlines'",
")",
"# Initialise the flowlines",
"dx",
"=",
"cfg",
".",
"PARAMS",
"[",
"'flowline_dx'",
"]",
"do_filter",
"=",
"cfg",
".",
"PAR... | [
1624,
0
] | [
1732,
61
] | python | en | ['en', 'en', 'en'] | True |
catchment_width_geom | (gdir) | Compute geometrical catchment widths for each point of the flowlines.
Updates the 'inversion_flowlines' save file.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
| Compute geometrical catchment widths for each point of the flowlines. | def catchment_width_geom(gdir):
"""Compute geometrical catchment widths for each point of the flowlines.
Updates the 'inversion_flowlines' save file.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
"""
# variables
flowlines = gdir.read_pi... | [
"def",
"catchment_width_geom",
"(",
"gdir",
")",
":",
"# variables",
"flowlines",
"=",
"gdir",
".",
"read_pickle",
"(",
"'inversion_flowlines'",
")",
"catchment_indices",
"=",
"gdir",
".",
"read_pickle",
"(",
"'geometries'",
")",
"[",
"'catchment_indices'",
"]",
"... | [
1736,
0
] | [
1843,
55
] | python | en | ['en', 'en', 'en'] | True |
catchment_width_correction | (gdir) | Corrects for NaNs and inconsistencies in the geometrical widths.
Interpolates missing values, ensures consistency of the
surface-area distribution AND with the geometrical area of the glacier
polygon, avoiding errors due to gridded representation.
Updates the 'inversion_flowlines' save file.
Para... | Corrects for NaNs and inconsistencies in the geometrical widths. | def catchment_width_correction(gdir):
"""Corrects for NaNs and inconsistencies in the geometrical widths.
Interpolates missing values, ensures consistency of the
surface-area distribution AND with the geometrical area of the glacier
polygon, avoiding errors due to gridded representation.
Updates t... | [
"def",
"catchment_width_correction",
"(",
"gdir",
")",
":",
"# variables",
"fls",
"=",
"gdir",
".",
"read_pickle",
"(",
"'inversion_flowlines'",
")",
"catchment_indices",
"=",
"gdir",
".",
"read_pickle",
"(",
"'geometries'",
")",
"[",
"'catchment_indices'",
"]",
"... | [
1847,
0
] | [
1992,
49
] | python | en | ['en', 'en', 'en'] | True |
terminus_width_correction | (gdir, new_width=None) | Sets a new value for the terminus width.
This can be useful for e.g. tidewater glaciers where we know the width
and don't like the OGGM one.
This task preserves the glacier area but will change the fit of the
altitude-area distribution slightly.
Parameters
----------
gdir : oggm.GlacierDi... | Sets a new value for the terminus width. | def terminus_width_correction(gdir, new_width=None):
"""Sets a new value for the terminus width.
This can be useful for e.g. tidewater glaciers where we know the width
and don't like the OGGM one.
This task preserves the glacier area but will change the fit of the
altitude-area distribution slight... | [
"def",
"terminus_width_correction",
"(",
"gdir",
",",
"new_width",
"=",
"None",
")",
":",
"# variables",
"fls",
"=",
"gdir",
".",
"read_pickle",
"(",
"'inversion_flowlines'",
")",
"fl",
"=",
"fls",
"[",
"-",
"1",
"]",
"mapdx",
"=",
"gdir",
".",
"grid",
"... | [
1996,
0
] | [
2035,
49
] | python | en | ['en', 'en', 'en'] | True |
intersect_downstream_lines | (gdir, candidates=None) | Find tributaries to a main glacier by intersecting downstream lines
The GlacierDirectories must at least contain a `downstream_line`.
If you have a lot of candidates, only execute the necessary tasks for that
and do the rest of the preprocessing after this function identified the
true tributary glacier... | Find tributaries to a main glacier by intersecting downstream lines | def intersect_downstream_lines(gdir, candidates=None):
"""Find tributaries to a main glacier by intersecting downstream lines
The GlacierDirectories must at least contain a `downstream_line`.
If you have a lot of candidates, only execute the necessary tasks for that
and do the rest of the preprocessing... | [
"def",
"intersect_downstream_lines",
"(",
"gdir",
",",
"candidates",
"=",
"None",
")",
":",
"# make sure tributaries are iteratable",
"candidates",
"=",
"utils",
".",
"tolist",
"(",
"candidates",
")",
"# Buffer in pixels around the flowline",
"buffer",
"=",
"cfg",
".",
... | [
2038,
0
] | [
2089,
22
] | python | en | ['en', 'en', 'en'] | True |
elevation_band_flowline | (gdir, bin_variables=None, preserve_totals=True) | Compute "squeezed" or "collapsed" glacier flowlines from Huss 2012.
This writes out a table of along glacier bins, strictly following the
method described in Werder, M. A., Huss, M., Paul, F., Dehecq, A. and
Farinotti, D.: A Bayesian ice thickness estimation model for large-scale
applications, J. Glaci... | Compute "squeezed" or "collapsed" glacier flowlines from Huss 2012. | def elevation_band_flowline(gdir, bin_variables=None, preserve_totals=True):
"""Compute "squeezed" or "collapsed" glacier flowlines from Huss 2012.
This writes out a table of along glacier bins, strictly following the
method described in Werder, M. A., Huss, M., Paul, F., Dehecq, A. and
Farinotti, D.: ... | [
"def",
"elevation_band_flowline",
"(",
"gdir",
",",
"bin_variables",
"=",
"None",
",",
"preserve_totals",
"=",
"True",
")",
":",
"# Variables",
"bin_variables",
"=",
"[",
"]",
"if",
"bin_variables",
"is",
"None",
"else",
"utils",
".",
"tolist",
"(",
"bin_varia... | [
2093,
0
] | [
2246,
59
] | python | en | ['en', 'en', 'en'] | True |
fixed_dx_elevation_band_flowline | (gdir, bin_variables=None,
preserve_totals=True) | Converts the "collapsed" flowline into a regular "inversion flowline".
You need to run `tasks.elevation_band_flowline` first. It then interpolates
onto a regular grid with the same dx as the one that OGGM would choose
(cfg.PARAMS['flowline_dx'] * map_dx).
Parameters
----------
gdir : :py:class... | Converts the "collapsed" flowline into a regular "inversion flowline". | def fixed_dx_elevation_band_flowline(gdir, bin_variables=None,
preserve_totals=True):
"""Converts the "collapsed" flowline into a regular "inversion flowline".
You need to run `tasks.elevation_band_flowline` first. It then interpolates
onto a regular grid with the same ... | [
"def",
"fixed_dx_elevation_band_flowline",
"(",
"gdir",
",",
"bin_variables",
"=",
"None",
",",
"preserve_totals",
"=",
"True",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"gdir",
".",
"get_filepath",
"(",
"'elevation_band_flowline'",
")",
",",
"index_col",... | [
2250,
0
] | [
2342,
62
] | python | en | ['en', 'en', 'en'] | True |
Centerline.__init__ | (self, line, dx=None, surface_h=None, orig_head=None,
rgi_id=None, map_dx=None) | Initialize a Centerline
Parameters
----------
line : :py:class:`shapely.geometry.LineString`
The geometrically calculated centerline
dx : float
Grid spacing of the initialised flowline in pixel coordinates
surface_h : :py:class:`numpy.ndarray`
... | Initialize a Centerline | def __init__(self, line, dx=None, surface_h=None, orig_head=None,
rgi_id=None, map_dx=None):
""" Initialize a Centerline
Parameters
----------
line : :py:class:`shapely.geometry.LineString`
The geometrically calculated centerline
dx : float
... | [
"def",
"__init__",
"(",
"self",
",",
"line",
",",
"dx",
"=",
"None",
",",
"surface_h",
"=",
"None",
",",
"orig_head",
"=",
"None",
",",
"rgi_id",
"=",
"None",
",",
"map_dx",
"=",
"None",
")",
":",
"self",
".",
"line",
"=",
"None",
"# Shapely LineStri... | [
72,
4
] | [
130,
28
] | python | en | ['en', 'en', 'en'] | True |
Centerline.set_flows_to | (self, other, check_tail=True, to_head=False) | Find the closest point in "other" and sets all the corresponding
attributes. Btw, it modifies the state of "other" too.
Parameters
----------
other : :py:class:`oggm.Centerline`
another flowline where self should flow to
| Find the closest point in "other" and sets all the corresponding
attributes. Btw, it modifies the state of "other" too. | def set_flows_to(self, other, check_tail=True, to_head=False):
"""Find the closest point in "other" and sets all the corresponding
attributes. Btw, it modifies the state of "other" too.
Parameters
----------
other : :py:class:`oggm.Centerline`
another flowline where ... | [
"def",
"set_flows_to",
"(",
"self",
",",
"other",
",",
"check_tail",
"=",
"True",
",",
"to_head",
"=",
"False",
")",
":",
"self",
".",
"flows_to",
"=",
"other",
"if",
"check_tail",
":",
"# Project the point and Check that its not too close",
"prdis",
"=",
"other... | [
132,
4
] | [
163,
34
] | python | en | ['en', 'en', 'en'] | True |
Centerline.set_line | (self, line) | Update the Shapely LineString coordinate.
Parameters
----------
line : :py:class`shapely.geometry.LineString`
| Update the Shapely LineString coordinate. | def set_line(self, line):
"""Update the Shapely LineString coordinate.
Parameters
----------
line : :py:class`shapely.geometry.LineString`
"""
self.nx = len(line.coords)
self.line = line
dis = [line.project(shpg.Point(co)) for co in line.coords]
... | [
"def",
"set_line",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"nx",
"=",
"len",
"(",
"line",
".",
"coords",
")",
"self",
".",
"line",
"=",
"line",
"dis",
"=",
"[",
"line",
".",
"project",
"(",
"shpg",
".",
"Point",
"(",
"co",
")",
")",
... | [
165,
4
] | [
179,
46
] | python | en | ['en', 'en', 'en'] | True |
Centerline.flows_to_indice | (self) | Indices instead of geometry | Indices instead of geometry | def flows_to_indice(self):
"""Indices instead of geometry"""
ind = []
tofind = self.flows_to_point.coords[0]
for i, p in enumerate(self.flows_to.line.coords):
if p == tofind:
ind.append(i)
assert len(ind) == 1, 'We expect exactly one point to be found... | [
"def",
"flows_to_indice",
"(",
"self",
")",
":",
"ind",
"=",
"[",
"]",
"tofind",
"=",
"self",
".",
"flows_to_point",
".",
"coords",
"[",
"0",
"]",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"self",
".",
"flows_to",
".",
"line",
".",
"coords",
")... | [
182,
4
] | [
191,
21
] | python | en | ['en', 'en', 'en'] | True |
Centerline.inflow_indices | (self) | Indices instead of geometries | Indices instead of geometries | def inflow_indices(self):
"""Indices instead of geometries"""
inds = []
for p in self.inflow_points:
ind = [i for (i, pi) in enumerate(self.line.coords)
if (p.coords[0] == pi)]
inds.append(ind[0])
assert len(inds) == len(self.inflow_points), ('... | [
"def",
"inflow_indices",
"(",
"self",
")",
":",
"inds",
"=",
"[",
"]",
"for",
"p",
"in",
"self",
".",
"inflow_points",
":",
"ind",
"=",
"[",
"i",
"for",
"(",
"i",
",",
"pi",
")",
"in",
"enumerate",
"(",
"self",
".",
"line",
".",
"coords",
")",
... | [
194,
4
] | [
206,
19
] | python | en | ['en', 'en', 'en'] | True |
Centerline.normals | (self) | List of (n1, n2) normal vectors at each point.
We use second order derivatives for smoother widths.
| List of (n1, n2) normal vectors at each point. | def normals(self):
"""List of (n1, n2) normal vectors at each point.
We use second order derivatives for smoother widths.
"""
pcoords = np.array(self.line.coords)
normals = []
# First
normal = np.array(pcoords[1, :] - pcoords[0, :])
normals.append(_norm... | [
"def",
"normals",
"(",
"self",
")",
":",
"pcoords",
"=",
"np",
".",
"array",
"(",
"self",
".",
"line",
".",
"coords",
")",
"normals",
"=",
"[",
"]",
"# First",
"normal",
"=",
"np",
".",
"array",
"(",
"pcoords",
"[",
"1",
",",
":",
"]",
"-",
"pc... | [
209,
4
] | [
239,
22
] | python | en | ['en', 'af', 'en'] | True |
Centerline.widths | (self) | Needed for overriding later | Needed for overriding later | def widths(self):
"""Needed for overriding later"""
return self._widths | [
"def",
"widths",
"(",
"self",
")",
":",
"return",
"self",
".",
"_widths"
] | [
242,
4
] | [
244,
27
] | python | en | ['en', 'en', 'en'] | True |
Centerline.surface_h | (self) | Needed for overriding later | Needed for overriding later | def surface_h(self):
"""Needed for overriding later"""
return self._surface_h | [
"def",
"surface_h",
"(",
"self",
")",
":",
"return",
"self",
".",
"_surface_h"
] | [
255,
4
] | [
257,
30
] | python | en | ['en', 'en', 'en'] | True |
Centerline.set_apparent_mb | (self, mb, mu_star=None) | Set the apparent mb and flux for the flowline.
MB is expected in kg m-2 yr-1 (= mm w.e. yr-1)
This should happen in line order, otherwise it will be wrong.
Parameters
----------
mu_star : float
if appropriate, the mu_star associated with this apparent mb
| Set the apparent mb and flux for the flowline. | def set_apparent_mb(self, mb, mu_star=None):
"""Set the apparent mb and flux for the flowline.
MB is expected in kg m-2 yr-1 (= mm w.e. yr-1)
This should happen in line order, otherwise it will be wrong.
Parameters
----------
mu_star : float
if appropriate,... | [
"def",
"set_apparent_mb",
"(",
"self",
",",
"mb",
",",
"mu_star",
"=",
"None",
")",
":",
"self",
".",
"apparent_mb",
"=",
"mb",
"self",
".",
"mu_star",
"=",
"mu_star",
"# Add MB to current flux and sum",
"# no more changes should happen after that",
"flux_needs_correc... | [
263,
4
] | [
304,
64
] | python | en | ['en', 'en', 'en'] | True |
safe_name | (name) | Convert an arbitrary string to a standard distribution name
Any runs of non-alphanumeric/. characters are replaced with a single '-'.
| Convert an arbitrary string to a standard distribution name | def safe_name(name):
"""Convert an arbitrary string to a standard distribution name
Any runs of non-alphanumeric/. characters are replaced with a single '-'.
"""
return re.sub('[^A-Za-z0-9.]+', '-', name) | [
"def",
"safe_name",
"(",
"name",
")",
":",
"return",
"re",
".",
"sub",
"(",
"'[^A-Za-z0-9.]+'",
",",
"'-'",
",",
"name",
")"
] | [
53,
0
] | [
58,
46
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.