repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
google/openhtf | openhtf/plugs/user_input.py | UserInput.wait_for_prompt | def wait_for_prompt(self, timeout_s=None):
"""Wait for the user to respond to the current prompt.
Args:
timeout_s: Seconds to wait before raising a PromptUnansweredError.
Returns:
A string response, or the empty string if text_input was False.
Raises:
PromptUnansweredError: Timed ou... | python | def wait_for_prompt(self, timeout_s=None):
"""Wait for the user to respond to the current prompt.
Args:
timeout_s: Seconds to wait before raising a PromptUnansweredError.
Returns:
A string response, or the empty string if text_input was False.
Raises:
PromptUnansweredError: Timed ou... | [
"def",
"wait_for_prompt",
"(",
"self",
",",
"timeout_s",
"=",
"None",
")",
":",
"with",
"self",
".",
"_cond",
":",
"if",
"self",
".",
"_prompt",
":",
"if",
"timeout_s",
"is",
"None",
":",
"self",
".",
"_cond",
".",
"wait",
"(",
"3600",
"*",
"24",
"... | Wait for the user to respond to the current prompt.
Args:
timeout_s: Seconds to wait before raising a PromptUnansweredError.
Returns:
A string response, or the empty string if text_input was False.
Raises:
PromptUnansweredError: Timed out waiting for the user to respond. | [
"Wait",
"for",
"the",
"user",
"to",
"respond",
"to",
"the",
"current",
"prompt",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L218-L238 | train |
google/openhtf | openhtf/plugs/user_input.py | UserInput.respond | def respond(self, prompt_id, response):
"""Respond to the prompt with the given ID.
If there is no active prompt or the given ID doesn't match the active
prompt, do nothing.
Args:
prompt_id: A string uniquely identifying the prompt.
response: A string response to the given prompt.
Ret... | python | def respond(self, prompt_id, response):
"""Respond to the prompt with the given ID.
If there is no active prompt or the given ID doesn't match the active
prompt, do nothing.
Args:
prompt_id: A string uniquely identifying the prompt.
response: A string response to the given prompt.
Ret... | [
"def",
"respond",
"(",
"self",
",",
"prompt_id",
",",
"response",
")",
":",
"_LOG",
".",
"debug",
"(",
"'Responding to prompt (%s): \"%s\"'",
",",
"prompt_id",
",",
"response",
")",
"with",
"self",
".",
"_cond",
":",
"if",
"not",
"(",
"self",
".",
"_prompt... | Respond to the prompt with the given ID.
If there is no active prompt or the given ID doesn't match the active
prompt, do nothing.
Args:
prompt_id: A string uniquely identifying the prompt.
response: A string response to the given prompt.
Returns:
True if the prompt with the given I... | [
"Respond",
"to",
"the",
"prompt",
"with",
"the",
"given",
"ID",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L240-L261 | train |
google/openhtf | openhtf/core/phase_executor.py | PhaseExecutionOutcome.is_terminal | def is_terminal(self):
"""True if this result will stop the test."""
return (self.raised_exception or self.is_timeout or
self.phase_result == openhtf.PhaseResult.STOP) | python | def is_terminal(self):
"""True if this result will stop the test."""
return (self.raised_exception or self.is_timeout or
self.phase_result == openhtf.PhaseResult.STOP) | [
"def",
"is_terminal",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"raised_exception",
"or",
"self",
".",
"is_timeout",
"or",
"self",
".",
"phase_result",
"==",
"openhtf",
".",
"PhaseResult",
".",
"STOP",
")"
] | True if this result will stop the test. | [
"True",
"if",
"this",
"result",
"will",
"stop",
"the",
"test",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L119-L122 | train |
google/openhtf | openhtf/core/phase_executor.py | PhaseExecutorThread._thread_proc | def _thread_proc(self):
"""Execute the encompassed phase and save the result."""
# Call the phase, save the return value, or default it to CONTINUE.
phase_return = self._phase_desc(self._test_state)
if phase_return is None:
phase_return = openhtf.PhaseResult.CONTINUE
# If phase_return is inva... | python | def _thread_proc(self):
"""Execute the encompassed phase and save the result."""
# Call the phase, save the return value, or default it to CONTINUE.
phase_return = self._phase_desc(self._test_state)
if phase_return is None:
phase_return = openhtf.PhaseResult.CONTINUE
# If phase_return is inva... | [
"def",
"_thread_proc",
"(",
"self",
")",
":",
"# Call the phase, save the return value, or default it to CONTINUE.",
"phase_return",
"=",
"self",
".",
"_phase_desc",
"(",
"self",
".",
"_test_state",
")",
"if",
"phase_return",
"is",
"None",
":",
"phase_return",
"=",
"o... | Execute the encompassed phase and save the result. | [
"Execute",
"the",
"encompassed",
"phase",
"and",
"save",
"the",
"result",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L152-L161 | train |
google/openhtf | openhtf/core/phase_executor.py | PhaseExecutorThread.join_or_die | def join_or_die(self):
"""Wait for thread to finish, returning a PhaseExecutionOutcome instance."""
if self._phase_desc.options.timeout_s is not None:
self.join(self._phase_desc.options.timeout_s)
else:
self.join(DEFAULT_PHASE_TIMEOUT_S)
# We got a return value or an exception and handled i... | python | def join_or_die(self):
"""Wait for thread to finish, returning a PhaseExecutionOutcome instance."""
if self._phase_desc.options.timeout_s is not None:
self.join(self._phase_desc.options.timeout_s)
else:
self.join(DEFAULT_PHASE_TIMEOUT_S)
# We got a return value or an exception and handled i... | [
"def",
"join_or_die",
"(",
"self",
")",
":",
"if",
"self",
".",
"_phase_desc",
".",
"options",
".",
"timeout_s",
"is",
"not",
"None",
":",
"self",
".",
"join",
"(",
"self",
".",
"_phase_desc",
".",
"options",
".",
"timeout_s",
")",
"else",
":",
"self",... | Wait for thread to finish, returning a PhaseExecutionOutcome instance. | [
"Wait",
"for",
"thread",
"to",
"finish",
"returning",
"a",
"PhaseExecutionOutcome",
"instance",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L172-L190 | train |
google/openhtf | openhtf/core/phase_executor.py | PhaseExecutor.execute_phase | def execute_phase(self, phase):
"""Executes a phase or skips it, yielding PhaseExecutionOutcome instances.
Args:
phase: Phase to execute.
Returns:
The final PhaseExecutionOutcome that wraps the phase return value
(or exception) of the final phase run. All intermediary results, if any,
... | python | def execute_phase(self, phase):
"""Executes a phase or skips it, yielding PhaseExecutionOutcome instances.
Args:
phase: Phase to execute.
Returns:
The final PhaseExecutionOutcome that wraps the phase return value
(or exception) of the final phase run. All intermediary results, if any,
... | [
"def",
"execute_phase",
"(",
"self",
",",
"phase",
")",
":",
"repeat_count",
"=",
"1",
"repeat_limit",
"=",
"phase",
".",
"options",
".",
"repeat_limit",
"or",
"sys",
".",
"maxsize",
"while",
"not",
"self",
".",
"_stopping",
".",
"is_set",
"(",
")",
":",... | Executes a phase or skips it, yielding PhaseExecutionOutcome instances.
Args:
phase: Phase to execute.
Returns:
The final PhaseExecutionOutcome that wraps the phase return value
(or exception) of the final phase run. All intermediary results, if any,
are REPEAT and handled internally. ... | [
"Executes",
"a",
"phase",
"or",
"skips",
"it",
"yielding",
"PhaseExecutionOutcome",
"instances",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L211-L235 | train |
google/openhtf | openhtf/core/phase_executor.py | PhaseExecutor._execute_phase_once | def _execute_phase_once(self, phase_desc, is_last_repeat):
"""Executes the given phase, returning a PhaseExecutionOutcome."""
# Check this before we create a PhaseState and PhaseRecord.
if phase_desc.options.run_if and not phase_desc.options.run_if():
_LOG.debug('Phase %s skipped due to run_if returni... | python | def _execute_phase_once(self, phase_desc, is_last_repeat):
"""Executes the given phase, returning a PhaseExecutionOutcome."""
# Check this before we create a PhaseState and PhaseRecord.
if phase_desc.options.run_if and not phase_desc.options.run_if():
_LOG.debug('Phase %s skipped due to run_if returni... | [
"def",
"_execute_phase_once",
"(",
"self",
",",
"phase_desc",
",",
"is_last_repeat",
")",
":",
"# Check this before we create a PhaseState and PhaseRecord.",
"if",
"phase_desc",
".",
"options",
".",
"run_if",
"and",
"not",
"phase_desc",
".",
"options",
".",
"run_if",
... | Executes the given phase, returning a PhaseExecutionOutcome. | [
"Executes",
"the",
"given",
"phase",
"returning",
"a",
"PhaseExecutionOutcome",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L237-L276 | train |
google/openhtf | openhtf/core/phase_executor.py | PhaseExecutor.stop | def stop(self, timeout_s=None):
"""Stops execution of the current phase, if any.
It will raise a ThreadTerminationError, which will cause the test to stop
executing and terminate with an ERROR state.
Args:
timeout_s: int or None, timeout in seconds to wait for the phase to stop.
"""
self... | python | def stop(self, timeout_s=None):
"""Stops execution of the current phase, if any.
It will raise a ThreadTerminationError, which will cause the test to stop
executing and terminate with an ERROR state.
Args:
timeout_s: int or None, timeout in seconds to wait for the phase to stop.
"""
self... | [
"def",
"stop",
"(",
"self",
",",
"timeout_s",
"=",
"None",
")",
":",
"self",
".",
"_stopping",
".",
"set",
"(",
")",
"with",
"self",
".",
"_current_phase_thread_lock",
":",
"phase_thread",
"=",
"self",
".",
"_current_phase_thread",
"if",
"not",
"phase_thread... | Stops execution of the current phase, if any.
It will raise a ThreadTerminationError, which will cause the test to stop
executing and terminate with an ERROR state.
Args:
timeout_s: int or None, timeout in seconds to wait for the phase to stop. | [
"Stops",
"execution",
"of",
"the",
"current",
"phase",
"if",
"any",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L281-L306 | train |
google/openhtf | openhtf/core/phase_group.py | load_code_info | def load_code_info(phases_or_groups):
"""Recursively load code info for a PhaseGroup or list of phases or groups."""
if isinstance(phases_or_groups, PhaseGroup):
return phases_or_groups.load_code_info()
ret = []
for phase in phases_or_groups:
if isinstance(phase, PhaseGroup):
ret.append(phase.load... | python | def load_code_info(phases_or_groups):
"""Recursively load code info for a PhaseGroup or list of phases or groups."""
if isinstance(phases_or_groups, PhaseGroup):
return phases_or_groups.load_code_info()
ret = []
for phase in phases_or_groups:
if isinstance(phase, PhaseGroup):
ret.append(phase.load... | [
"def",
"load_code_info",
"(",
"phases_or_groups",
")",
":",
"if",
"isinstance",
"(",
"phases_or_groups",
",",
"PhaseGroup",
")",
":",
"return",
"phases_or_groups",
".",
"load_code_info",
"(",
")",
"ret",
"=",
"[",
"]",
"for",
"phase",
"in",
"phases_or_groups",
... | Recursively load code info for a PhaseGroup or list of phases or groups. | [
"Recursively",
"load",
"code",
"info",
"for",
"a",
"PhaseGroup",
"or",
"list",
"of",
"phases",
"or",
"groups",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L192-L204 | train |
google/openhtf | openhtf/core/phase_group.py | flatten_phases_and_groups | def flatten_phases_and_groups(phases_or_groups):
"""Recursively flatten nested lists for the list of phases or groups."""
if isinstance(phases_or_groups, PhaseGroup):
phases_or_groups = [phases_or_groups]
ret = []
for phase in phases_or_groups:
if isinstance(phase, PhaseGroup):
ret.append(phase.fl... | python | def flatten_phases_and_groups(phases_or_groups):
"""Recursively flatten nested lists for the list of phases or groups."""
if isinstance(phases_or_groups, PhaseGroup):
phases_or_groups = [phases_or_groups]
ret = []
for phase in phases_or_groups:
if isinstance(phase, PhaseGroup):
ret.append(phase.fl... | [
"def",
"flatten_phases_and_groups",
"(",
"phases_or_groups",
")",
":",
"if",
"isinstance",
"(",
"phases_or_groups",
",",
"PhaseGroup",
")",
":",
"phases_or_groups",
"=",
"[",
"phases_or_groups",
"]",
"ret",
"=",
"[",
"]",
"for",
"phase",
"in",
"phases_or_groups",
... | Recursively flatten nested lists for the list of phases or groups. | [
"Recursively",
"flatten",
"nested",
"lists",
"for",
"the",
"list",
"of",
"phases",
"or",
"groups",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L207-L219 | train |
google/openhtf | openhtf/core/phase_group.py | optionally_with_args | def optionally_with_args(phase, **kwargs):
"""Apply only the args that the phase knows.
If the phase has a **kwargs-style argument, it counts as knowing all args.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to ... | python | def optionally_with_args(phase, **kwargs):
"""Apply only the args that the phase knows.
If the phase has a **kwargs-style argument, it counts as knowing all args.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to ... | [
"def",
"optionally_with_args",
"(",
"phase",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"phase",
",",
"PhaseGroup",
")",
":",
"return",
"phase",
".",
"with_args",
"(",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"phase",
",",
"co... | Apply only the args that the phase knows.
If the phase has a **kwargs-style argument, it counts as knowing all args.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to apply
with_args to.
**kwargs: argume... | [
"Apply",
"only",
"the",
"args",
"that",
"the",
"phase",
"knows",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L222-L244 | train |
google/openhtf | openhtf/core/phase_group.py | optionally_with_plugs | def optionally_with_plugs(phase, **subplugs):
"""Apply only the with_plugs that the phase knows.
This will determine the subset of plug overrides for only plugs the phase
actually has.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase... | python | def optionally_with_plugs(phase, **subplugs):
"""Apply only the with_plugs that the phase knows.
This will determine the subset of plug overrides for only plugs the phase
actually has.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase... | [
"def",
"optionally_with_plugs",
"(",
"phase",
",",
"*",
"*",
"subplugs",
")",
":",
"if",
"isinstance",
"(",
"phase",
",",
"PhaseGroup",
")",
":",
"return",
"phase",
".",
"with_plugs",
"(",
"*",
"*",
"subplugs",
")",
"if",
"isinstance",
"(",
"phase",
",",... | Apply only the with_plugs that the phase knows.
This will determine the subset of plug overrides for only plugs the phase
actually has.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to apply the
plug chan... | [
"Apply",
"only",
"the",
"with_plugs",
"that",
"the",
"phase",
"knows",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L247-L275 | train |
google/openhtf | openhtf/core/phase_group.py | PhaseGroup.convert_if_not | def convert_if_not(cls, phases_or_groups):
"""Convert list of phases or groups into a new PhaseGroup if not already."""
if isinstance(phases_or_groups, PhaseGroup):
return mutablerecords.CopyRecord(phases_or_groups)
flattened = flatten_phases_and_groups(phases_or_groups)
return cls(main=flattened... | python | def convert_if_not(cls, phases_or_groups):
"""Convert list of phases or groups into a new PhaseGroup if not already."""
if isinstance(phases_or_groups, PhaseGroup):
return mutablerecords.CopyRecord(phases_or_groups)
flattened = flatten_phases_and_groups(phases_or_groups)
return cls(main=flattened... | [
"def",
"convert_if_not",
"(",
"cls",
",",
"phases_or_groups",
")",
":",
"if",
"isinstance",
"(",
"phases_or_groups",
",",
"PhaseGroup",
")",
":",
"return",
"mutablerecords",
".",
"CopyRecord",
"(",
"phases_or_groups",
")",
"flattened",
"=",
"flatten_phases_and_group... | Convert list of phases or groups into a new PhaseGroup if not already. | [
"Convert",
"list",
"of",
"phases",
"or",
"groups",
"into",
"a",
"new",
"PhaseGroup",
"if",
"not",
"already",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L79-L85 | train |
google/openhtf | openhtf/core/phase_group.py | PhaseGroup.with_context | def with_context(cls, setup_phases, teardown_phases):
"""Create PhaseGroup creator function with setup and teardown phases.
Args:
setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/
callables/iterables, phases to run during the setup for the PhaseGroup
returned from t... | python | def with_context(cls, setup_phases, teardown_phases):
"""Create PhaseGroup creator function with setup and teardown phases.
Args:
setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/
callables/iterables, phases to run during the setup for the PhaseGroup
returned from t... | [
"def",
"with_context",
"(",
"cls",
",",
"setup_phases",
",",
"teardown_phases",
")",
":",
"setup",
"=",
"flatten_phases_and_groups",
"(",
"setup_phases",
")",
"teardown",
"=",
"flatten_phases_and_groups",
"(",
"teardown_phases",
")",
"def",
"_context_wrapper",
"(",
... | Create PhaseGroup creator function with setup and teardown phases.
Args:
setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/
callables/iterables, phases to run during the setup for the PhaseGroup
returned from the created function.
teardown_phases: list of phase_des... | [
"Create",
"PhaseGroup",
"creator",
"function",
"with",
"setup",
"and",
"teardown",
"phases",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L88-L110 | train |
google/openhtf | openhtf/core/phase_group.py | PhaseGroup.combine | def combine(self, other, name=None):
"""Combine with another PhaseGroup and return the result."""
return PhaseGroup(
setup=self.setup + other.setup,
main=self.main + other.main,
teardown=self.teardown + other.teardown,
name=name) | python | def combine(self, other, name=None):
"""Combine with another PhaseGroup and return the result."""
return PhaseGroup(
setup=self.setup + other.setup,
main=self.main + other.main,
teardown=self.teardown + other.teardown,
name=name) | [
"def",
"combine",
"(",
"self",
",",
"other",
",",
"name",
"=",
"None",
")",
":",
"return",
"PhaseGroup",
"(",
"setup",
"=",
"self",
".",
"setup",
"+",
"other",
".",
"setup",
",",
"main",
"=",
"self",
".",
"main",
"+",
"other",
".",
"main",
",",
"... | Combine with another PhaseGroup and return the result. | [
"Combine",
"with",
"another",
"PhaseGroup",
"and",
"return",
"the",
"result",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L122-L128 | train |
google/openhtf | openhtf/core/phase_group.py | PhaseGroup.wrap | def wrap(self, main_phases, name=None):
"""Returns PhaseGroup with additional main phases."""
new_main = list(self.main)
if isinstance(main_phases, collections.Iterable):
new_main.extend(main_phases)
else:
new_main.append(main_phases)
return PhaseGroup(
setup=self.setup,
... | python | def wrap(self, main_phases, name=None):
"""Returns PhaseGroup with additional main phases."""
new_main = list(self.main)
if isinstance(main_phases, collections.Iterable):
new_main.extend(main_phases)
else:
new_main.append(main_phases)
return PhaseGroup(
setup=self.setup,
... | [
"def",
"wrap",
"(",
"self",
",",
"main_phases",
",",
"name",
"=",
"None",
")",
":",
"new_main",
"=",
"list",
"(",
"self",
".",
"main",
")",
"if",
"isinstance",
"(",
"main_phases",
",",
"collections",
".",
"Iterable",
")",
":",
"new_main",
".",
"extend"... | Returns PhaseGroup with additional main phases. | [
"Returns",
"PhaseGroup",
"with",
"additional",
"main",
"phases",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L130-L141 | train |
google/openhtf | openhtf/core/phase_group.py | PhaseGroup.flatten | def flatten(self):
"""Internally flatten out nested iterables."""
return PhaseGroup(
setup=flatten_phases_and_groups(self.setup),
main=flatten_phases_and_groups(self.main),
teardown=flatten_phases_and_groups(self.teardown),
name=self.name) | python | def flatten(self):
"""Internally flatten out nested iterables."""
return PhaseGroup(
setup=flatten_phases_and_groups(self.setup),
main=flatten_phases_and_groups(self.main),
teardown=flatten_phases_and_groups(self.teardown),
name=self.name) | [
"def",
"flatten",
"(",
"self",
")",
":",
"return",
"PhaseGroup",
"(",
"setup",
"=",
"flatten_phases_and_groups",
"(",
"self",
".",
"setup",
")",
",",
"main",
"=",
"flatten_phases_and_groups",
"(",
"self",
".",
"main",
")",
",",
"teardown",
"=",
"flatten_phas... | Internally flatten out nested iterables. | [
"Internally",
"flatten",
"out",
"nested",
"iterables",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L175-L181 | train |
google/openhtf | openhtf/core/phase_group.py | PhaseGroup.load_code_info | def load_code_info(self):
"""Load coded info for all contained phases."""
return PhaseGroup(
setup=load_code_info(self.setup),
main=load_code_info(self.main),
teardown=load_code_info(self.teardown),
name=self.name) | python | def load_code_info(self):
"""Load coded info for all contained phases."""
return PhaseGroup(
setup=load_code_info(self.setup),
main=load_code_info(self.main),
teardown=load_code_info(self.teardown),
name=self.name) | [
"def",
"load_code_info",
"(",
"self",
")",
":",
"return",
"PhaseGroup",
"(",
"setup",
"=",
"load_code_info",
"(",
"self",
".",
"setup",
")",
",",
"main",
"=",
"load_code_info",
"(",
"self",
".",
"main",
")",
",",
"teardown",
"=",
"load_code_info",
"(",
"... | Load coded info for all contained phases. | [
"Load",
"coded",
"info",
"for",
"all",
"contained",
"phases",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L183-L189 | train |
google/openhtf | openhtf/output/servers/pub_sub.py | PubSub.publish | def publish(cls, message, client_filter=None):
"""Publish messages to subscribers.
Args:
message: The message to publish.
client_filter: A filter function to call passing in each client. Only
clients for whom the function returns True will have the
message ... | python | def publish(cls, message, client_filter=None):
"""Publish messages to subscribers.
Args:
message: The message to publish.
client_filter: A filter function to call passing in each client. Only
clients for whom the function returns True will have the
message ... | [
"def",
"publish",
"(",
"cls",
",",
"message",
",",
"client_filter",
"=",
"None",
")",
":",
"with",
"cls",
".",
"_lock",
":",
"for",
"client",
"in",
"cls",
".",
"subscribers",
":",
"if",
"(",
"not",
"client_filter",
")",
"or",
"client_filter",
"(",
"cli... | Publish messages to subscribers.
Args:
message: The message to publish.
client_filter: A filter function to call passing in each client. Only
clients for whom the function returns True will have the
message sent to them. | [
"Publish",
"messages",
"to",
"subscribers",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/pub_sub.py#L43-L55 | train |
google/openhtf | examples/repeat.py | FailTwicePlug.run | def run(self):
"""Increments counter and raises an exception for first two runs."""
self.count += 1
print('FailTwicePlug: Run number %s' % (self.count))
if self.count < 3:
raise RuntimeError('Fails a couple times')
return True | python | def run(self):
"""Increments counter and raises an exception for first two runs."""
self.count += 1
print('FailTwicePlug: Run number %s' % (self.count))
if self.count < 3:
raise RuntimeError('Fails a couple times')
return True | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"count",
"+=",
"1",
"print",
"(",
"'FailTwicePlug: Run number %s'",
"%",
"(",
"self",
".",
"count",
")",
")",
"if",
"self",
".",
"count",
"<",
"3",
":",
"raise",
"RuntimeError",
"(",
"'Fails a couple time... | Increments counter and raises an exception for first two runs. | [
"Increments",
"counter",
"and",
"raises",
"an",
"exception",
"for",
"first",
"two",
"runs",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/repeat.py#L41-L48 | train |
google/openhtf | openhtf/core/phase_descriptor.py | PhaseOptions.format_strings | def format_strings(self, **kwargs):
"""String substitution of name."""
return mutablerecords.CopyRecord(
self, name=util.format_string(self.name, kwargs)) | python | def format_strings(self, **kwargs):
"""String substitution of name."""
return mutablerecords.CopyRecord(
self, name=util.format_string(self.name, kwargs)) | [
"def",
"format_strings",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"mutablerecords",
".",
"CopyRecord",
"(",
"self",
",",
"name",
"=",
"util",
".",
"format_string",
"(",
"self",
".",
"name",
",",
"kwargs",
")",
")"
] | String substitution of name. | [
"String",
"substitution",
"of",
"name",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L96-L99 | train |
google/openhtf | openhtf/core/phase_descriptor.py | PhaseDescriptor.wrap_or_copy | def wrap_or_copy(cls, func, **options):
"""Return a new PhaseDescriptor from the given function or instance.
We want to return a new copy so that you can reuse a phase with different
options, plugs, measurements, etc.
Args:
func: A phase function or PhaseDescriptor instance.
**options: Opt... | python | def wrap_or_copy(cls, func, **options):
"""Return a new PhaseDescriptor from the given function or instance.
We want to return a new copy so that you can reuse a phase with different
options, plugs, measurements, etc.
Args:
func: A phase function or PhaseDescriptor instance.
**options: Opt... | [
"def",
"wrap_or_copy",
"(",
"cls",
",",
"func",
",",
"*",
"*",
"options",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"openhtf",
".",
"PhaseGroup",
")",
":",
"raise",
"PhaseWrapError",
"(",
"'Cannot wrap PhaseGroup <%s> as a phase.'",
"%",
"(",
"func",
"... | Return a new PhaseDescriptor from the given function or instance.
We want to return a new copy so that you can reuse a phase with different
options, plugs, measurements, etc.
Args:
func: A phase function or PhaseDescriptor instance.
**options: Options to update on the result.
Raises:
... | [
"Return",
"a",
"new",
"PhaseDescriptor",
"from",
"the",
"given",
"function",
"or",
"instance",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L135-L161 | train |
google/openhtf | openhtf/core/phase_descriptor.py | PhaseDescriptor.with_known_args | def with_known_args(self, **kwargs):
"""Send only known keyword-arguments to the phase when called."""
argspec = inspect.getargspec(self.func)
stored = {}
for key, arg in six.iteritems(kwargs):
if key in argspec.args or argspec.keywords:
stored[key] = arg
if stored:
return self.w... | python | def with_known_args(self, **kwargs):
"""Send only known keyword-arguments to the phase when called."""
argspec = inspect.getargspec(self.func)
stored = {}
for key, arg in six.iteritems(kwargs):
if key in argspec.args or argspec.keywords:
stored[key] = arg
if stored:
return self.w... | [
"def",
"with_known_args",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"self",
".",
"func",
")",
"stored",
"=",
"{",
"}",
"for",
"key",
",",
"arg",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
... | Send only known keyword-arguments to the phase when called. | [
"Send",
"only",
"known",
"keyword",
"-",
"arguments",
"to",
"the",
"phase",
"when",
"called",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L179-L188 | train |
google/openhtf | openhtf/core/phase_descriptor.py | PhaseDescriptor.with_args | def with_args(self, **kwargs):
"""Send these keyword-arguments to the phase when called."""
# Make a copy so we can have multiple of the same phase with different args
# in the same test.
new_info = mutablerecords.CopyRecord(self)
new_info.options = new_info.options.format_strings(**kwargs)
new_... | python | def with_args(self, **kwargs):
"""Send these keyword-arguments to the phase when called."""
# Make a copy so we can have multiple of the same phase with different args
# in the same test.
new_info = mutablerecords.CopyRecord(self)
new_info.options = new_info.options.format_strings(**kwargs)
new_... | [
"def",
"with_args",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Make a copy so we can have multiple of the same phase with different args",
"# in the same test.",
"new_info",
"=",
"mutablerecords",
".",
"CopyRecord",
"(",
"self",
")",
"new_info",
".",
"options",
... | Send these keyword-arguments to the phase when called. | [
"Send",
"these",
"keyword",
"-",
"arguments",
"to",
"the",
"phase",
"when",
"called",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L190-L198 | train |
google/openhtf | openhtf/core/phase_descriptor.py | PhaseDescriptor._apply_with_plugs | def _apply_with_plugs(self, subplugs, error_on_unknown):
"""Substitute plugs for placeholders for this phase.
Args:
subplugs: dict of plug name to plug class, plug classes to replace.
error_on_unknown: bool, if True, then error when an unknown plug name is
provided.
Raises:
ope... | python | def _apply_with_plugs(self, subplugs, error_on_unknown):
"""Substitute plugs for placeholders for this phase.
Args:
subplugs: dict of plug name to plug class, plug classes to replace.
error_on_unknown: bool, if True, then error when an unknown plug name is
provided.
Raises:
ope... | [
"def",
"_apply_with_plugs",
"(",
"self",
",",
"subplugs",
",",
"error_on_unknown",
")",
":",
"plugs_by_name",
"=",
"{",
"plug",
".",
"name",
":",
"plug",
"for",
"plug",
"in",
"self",
".",
"plugs",
"}",
"new_plugs",
"=",
"dict",
"(",
"plugs_by_name",
")",
... | Substitute plugs for placeholders for this phase.
Args:
subplugs: dict of plug name to plug class, plug classes to replace.
error_on_unknown: bool, if True, then error when an unknown plug name is
provided.
Raises:
openhtf.plugs.InvalidPlugError if for one of the plug names one of ... | [
"Substitute",
"plugs",
"for",
"placeholders",
"for",
"this",
"phase",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L208-L255 | train |
google/openhtf | openhtf/plugs/usb/usb_handle.py | requires_open_handle | def requires_open_handle(method): # pylint: disable=invalid-name
"""Decorator to ensure a handle is open for certain methods.
Subclasses should decorate their Read() and Write() with this rather than
checking their own internal state, keeping all "is this handle open" logic
in is_closed().
Args:
method... | python | def requires_open_handle(method): # pylint: disable=invalid-name
"""Decorator to ensure a handle is open for certain methods.
Subclasses should decorate their Read() and Write() with this rather than
checking their own internal state, keeping all "is this handle open" logic
in is_closed().
Args:
method... | [
"def",
"requires_open_handle",
"(",
"method",
")",
":",
"# pylint: disable=invalid-name",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper_requiring_open_handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"The wra... | Decorator to ensure a handle is open for certain methods.
Subclasses should decorate their Read() and Write() with this rather than
checking their own internal state, keeping all "is this handle open" logic
in is_closed().
Args:
method: A class method on a subclass of UsbHandle
Raises:
HandleClosed... | [
"Decorator",
"to",
"ensure",
"a",
"handle",
"is",
"open",
"for",
"certain",
"methods",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle.py#L36-L59 | train |
google/openhtf | openhtf/plugs/usb/usb_handle_stub.py | StubUsbHandle._dotify | def _dotify(cls, data):
"""Add dots."""
return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data) | python | def _dotify(cls, data):
"""Add dots."""
return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data) | [
"def",
"_dotify",
"(",
"cls",
",",
"data",
")",
":",
"return",
"''",
".",
"join",
"(",
"char",
"if",
"char",
"in",
"cls",
".",
"PRINTABLE_DATA",
"else",
"'.'",
"for",
"char",
"in",
"data",
")"
] | Add dots. | [
"Add",
"dots",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle_stub.py#L36-L38 | train |
google/openhtf | openhtf/plugs/usb/usb_handle_stub.py | StubUsbHandle.write | def write(self, data, dummy=None):
"""Stub Write method."""
assert not self.closed
if self.expected_write_data is None:
return
expected_data = self.expected_write_data.pop(0)
if expected_data != data:
raise ValueError('Expected %s, got %s (%s)' % (
self._dotify(expected_data),... | python | def write(self, data, dummy=None):
"""Stub Write method."""
assert not self.closed
if self.expected_write_data is None:
return
expected_data = self.expected_write_data.pop(0)
if expected_data != data:
raise ValueError('Expected %s, got %s (%s)' % (
self._dotify(expected_data),... | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"dummy",
"=",
"None",
")",
":",
"assert",
"not",
"self",
".",
"closed",
"if",
"self",
".",
"expected_write_data",
"is",
"None",
":",
"return",
"expected_data",
"=",
"self",
".",
"expected_write_data",
".",
"... | Stub Write method. | [
"Stub",
"Write",
"method",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle_stub.py#L40-L50 | train |
google/openhtf | openhtf/plugs/usb/usb_handle_stub.py | StubUsbHandle.read | def read(self, length, dummy=None):
"""Stub Read method."""
assert not self.closed
data = self.expected_read_data.pop(0)
if length < len(data):
raise ValueError(
'Overflow packet length. Read %d bytes, got %d bytes: %s',
length, len(data), self._dotify(data))
return data | python | def read(self, length, dummy=None):
"""Stub Read method."""
assert not self.closed
data = self.expected_read_data.pop(0)
if length < len(data):
raise ValueError(
'Overflow packet length. Read %d bytes, got %d bytes: %s',
length, len(data), self._dotify(data))
return data | [
"def",
"read",
"(",
"self",
",",
"length",
",",
"dummy",
"=",
"None",
")",
":",
"assert",
"not",
"self",
".",
"closed",
"data",
"=",
"self",
".",
"expected_read_data",
".",
"pop",
"(",
"0",
")",
"if",
"length",
"<",
"len",
"(",
"data",
")",
":",
... | Stub Read method. | [
"Stub",
"Read",
"method",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle_stub.py#L52-L60 | train |
google/openhtf | openhtf/plugs/cambrionix/__init__.py | EtherSync.get_usb_serial | def get_usb_serial(self, port_num):
"""Get the device serial number
Args:
port_num: port number on the Cambrionix unit
Return:
usb device serial number
"""
port = self.port_map[str(port_num)]
arg = ''.join(['DEVICE INFO,', self._addr, '.', port])
cmd = (['esuit64', '-t', arg])... | python | def get_usb_serial(self, port_num):
"""Get the device serial number
Args:
port_num: port number on the Cambrionix unit
Return:
usb device serial number
"""
port = self.port_map[str(port_num)]
arg = ''.join(['DEVICE INFO,', self._addr, '.', port])
cmd = (['esuit64', '-t', arg])... | [
"def",
"get_usb_serial",
"(",
"self",
",",
"port_num",
")",
":",
"port",
"=",
"self",
".",
"port_map",
"[",
"str",
"(",
"port_num",
")",
"]",
"arg",
"=",
"''",
".",
"join",
"(",
"[",
"'DEVICE INFO,'",
",",
"self",
".",
"_addr",
",",
"'.'",
",",
"po... | Get the device serial number
Args:
port_num: port number on the Cambrionix unit
Return:
usb device serial number | [
"Get",
"the",
"device",
"serial",
"number"
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/cambrionix/__init__.py#L47-L72 | train |
google/openhtf | openhtf/plugs/cambrionix/__init__.py | EtherSync.open_usb_handle | def open_usb_handle(self, port_num):
"""open usb port
Args:
port_num: port number on the Cambrionix unit
Return:
usb handle
"""
serial = self.get_usb_serial(port_num)
return local_usb.LibUsbHandle.open(serial_number=serial) | python | def open_usb_handle(self, port_num):
"""open usb port
Args:
port_num: port number on the Cambrionix unit
Return:
usb handle
"""
serial = self.get_usb_serial(port_num)
return local_usb.LibUsbHandle.open(serial_number=serial) | [
"def",
"open_usb_handle",
"(",
"self",
",",
"port_num",
")",
":",
"serial",
"=",
"self",
".",
"get_usb_serial",
"(",
"port_num",
")",
"return",
"local_usb",
".",
"LibUsbHandle",
".",
"open",
"(",
"serial_number",
"=",
"serial",
")"
] | open usb port
Args:
port_num: port number on the Cambrionix unit
Return:
usb handle | [
"open",
"usb",
"port"
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/cambrionix/__init__.py#L74-L84 | train |
google/openhtf | openhtf/util/console_output.py | _printed_len | def _printed_len(some_string):
"""Compute the visible length of the string when printed."""
return len([x for x in ANSI_ESC_RE.sub('', some_string)
if x in string.printable]) | python | def _printed_len(some_string):
"""Compute the visible length of the string when printed."""
return len([x for x in ANSI_ESC_RE.sub('', some_string)
if x in string.printable]) | [
"def",
"_printed_len",
"(",
"some_string",
")",
":",
"return",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"ANSI_ESC_RE",
".",
"sub",
"(",
"''",
",",
"some_string",
")",
"if",
"x",
"in",
"string",
".",
"printable",
"]",
")"
] | Compute the visible length of the string when printed. | [
"Compute",
"the",
"visible",
"length",
"of",
"the",
"string",
"when",
"printed",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L65-L68 | train |
google/openhtf | openhtf/util/console_output.py | banner_print | def banner_print(msg, color='', width=60, file=sys.stdout, logger=_LOG):
"""Print the message as a banner with a fixed width.
Also logs the message (un-bannered) to the given logger at the debug level.
Args:
msg: The message to print.
color: Optional colorama color string to be applied to the message. Y... | python | def banner_print(msg, color='', width=60, file=sys.stdout, logger=_LOG):
"""Print the message as a banner with a fixed width.
Also logs the message (un-bannered) to the given logger at the debug level.
Args:
msg: The message to print.
color: Optional colorama color string to be applied to the message. Y... | [
"def",
"banner_print",
"(",
"msg",
",",
"color",
"=",
"''",
",",
"width",
"=",
"60",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"logger",
"=",
"_LOG",
")",
":",
"if",
"logger",
":",
"logger",
".",
"debug",
"(",
"ANSI_ESC_RE",
".",
"sub",
"(",
"... | Print the message as a banner with a fixed width.
Also logs the message (un-bannered) to the given logger at the debug level.
Args:
msg: The message to print.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any... | [
"Print",
"the",
"message",
"as",
"a",
"banner",
"with",
"a",
"fixed",
"width",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L78-L109 | train |
google/openhtf | openhtf/util/console_output.py | bracket_print | def bracket_print(msg, color='', width=8, file=sys.stdout):
"""Prints the message in brackets in the specified color and end the line.
Args:
msg: The message to put inside the brackets (a brief status message).
color: Optional colorama color string to be applied to the message. You can
concatenate ... | python | def bracket_print(msg, color='', width=8, file=sys.stdout):
"""Prints the message in brackets in the specified color and end the line.
Args:
msg: The message to put inside the brackets (a brief status message).
color: Optional colorama color string to be applied to the message. You can
concatenate ... | [
"def",
"bracket_print",
"(",
"msg",
",",
"color",
"=",
"''",
",",
"width",
"=",
"8",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"CLI_QUIET",
":",
"return",
"lpad",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"(",
"width",
"-",
"2",
... | Prints the message in brackets in the specified color and end the line.
Args:
msg: The message to put inside the brackets (a brief status message).
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any set of
... | [
"Prints",
"the",
"message",
"in",
"brackets",
"in",
"the",
"specified",
"color",
"and",
"end",
"the",
"line",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L112-L133 | train |
google/openhtf | openhtf/util/console_output.py | cli_print | def cli_print(msg, color='', end=None, file=sys.stdout, logger=_LOG):
"""Print the message to file and also log it.
This function is intended as a 'tee' mechanism to enable the CLI interface as
a first-class citizen, while ensuring that everything the operator sees also
has an analogous logging entry in the te... | python | def cli_print(msg, color='', end=None, file=sys.stdout, logger=_LOG):
"""Print the message to file and also log it.
This function is intended as a 'tee' mechanism to enable the CLI interface as
a first-class citizen, while ensuring that everything the operator sees also
has an analogous logging entry in the te... | [
"def",
"cli_print",
"(",
"msg",
",",
"color",
"=",
"''",
",",
"end",
"=",
"None",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"logger",
"=",
"_LOG",
")",
":",
"if",
"logger",
":",
"logger",
".",
"debug",
"(",
"'-> {}'",
".",
"format",
"(",
"msg"... | Print the message to file and also log it.
This function is intended as a 'tee' mechanism to enable the CLI interface as
a first-class citizen, while ensuring that everything the operator sees also
has an analogous logging entry in the test record for later inspection.
Args:
msg: The message to print/log.... | [
"Print",
"the",
"message",
"to",
"file",
"and",
"also",
"log",
"it",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L136-L160 | train |
google/openhtf | openhtf/util/console_output.py | error_print | def error_print(msg, color=colorama.Fore.RED, file=sys.stderr):
"""Print the error message to the file in the specified color.
Args:
msg: The error message to be printed.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together here, bu... | python | def error_print(msg, color=colorama.Fore.RED, file=sys.stderr):
"""Print the error message to the file in the specified color.
Args:
msg: The error message to be printed.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together here, bu... | [
"def",
"error_print",
"(",
"msg",
",",
"color",
"=",
"colorama",
".",
"Fore",
".",
"RED",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
":",
"if",
"CLI_QUIET",
":",
"return",
"file",
".",
"write",
"(",
"'{sep}{bright}{color}Error: {normal}{msg}{sep}{reset}'",
... | Print the error message to the file in the specified color.
Args:
msg: The error message to be printed.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together here, but note that style
strings will not be applied.
file: A fi... | [
"Print",
"the",
"error",
"message",
"to",
"the",
"file",
"in",
"the",
"specified",
"color",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L163-L179 | train |
google/openhtf | openhtf/util/console_output.py | action_result_context | def action_result_context(action_text,
width=60,
status_width=8,
succeed_text='OK',
fail_text='FAIL',
unknown_text='????',
file=sys.stdout,
... | python | def action_result_context(action_text,
width=60,
status_width=8,
succeed_text='OK',
fail_text='FAIL',
unknown_text='????',
file=sys.stdout,
... | [
"def",
"action_result_context",
"(",
"action_text",
",",
"width",
"=",
"60",
",",
"status_width",
"=",
"8",
",",
"succeed_text",
"=",
"'OK'",
",",
"fail_text",
"=",
"'FAIL'",
",",
"unknown_text",
"=",
"'????'",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
... | A contextmanager that prints actions and results to the CLI.
When entering the context, the action will be printed, and when the context
is exited, the result will be printed. The object yielded by the context is
used to mark the action as a success or failure, and a raise from inside the
context will also res... | [
"A",
"contextmanager",
"that",
"prints",
"actions",
"and",
"results",
"to",
"the",
"CLI",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L204-L290 | train |
google/openhtf | openhtf/util/exceptions.py | reraise | def reraise(exc_type, message=None, *args, **kwargs): # pylint: disable=invalid-name
"""reraises an exception for exception translation.
This is primarily used for when you immediately reraise an exception that is
thrown in a library, so that your client will not have to depend on various
exceptions defined i... | python | def reraise(exc_type, message=None, *args, **kwargs): # pylint: disable=invalid-name
"""reraises an exception for exception translation.
This is primarily used for when you immediately reraise an exception that is
thrown in a library, so that your client will not have to depend on various
exceptions defined i... | [
"def",
"reraise",
"(",
"exc_type",
",",
"message",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"last_lineno",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
".",
"f_lineno",
"line_msg",
... | reraises an exception for exception translation.
This is primarily used for when you immediately reraise an exception that is
thrown in a library, so that your client will not have to depend on various
exceptions defined in the library implementation that is being abstracted. The
advantage of this helper funct... | [
"reraises",
"an",
"exception",
"for",
"exception",
"translation",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/exceptions.py#L22-L74 | train |
rflamary/POT | ot/plot.py | plot1D_mat | def plot1D_mat(a, b, M, title=''):
""" Plot matrix M with the source and target 1D distribution
Creates a subplot with the source distribution a on the left and
target distribution b on the tot. The matrix M is shown in between.
Parameters
----------
a : np.array, shape (na,)
Source ... | python | def plot1D_mat(a, b, M, title=''):
""" Plot matrix M with the source and target 1D distribution
Creates a subplot with the source distribution a on the left and
target distribution b on the tot. The matrix M is shown in between.
Parameters
----------
a : np.array, shape (na,)
Source ... | [
"def",
"plot1D_mat",
"(",
"a",
",",
"b",
",",
"M",
",",
"title",
"=",
"''",
")",
":",
"na",
",",
"nb",
"=",
"M",
".",
"shape",
"gs",
"=",
"gridspec",
".",
"GridSpec",
"(",
"3",
",",
"3",
")",
"xa",
"=",
"np",
".",
"arange",
"(",
"na",
")",
... | Plot matrix M with the source and target 1D distribution
Creates a subplot with the source distribution a on the left and
target distribution b on the tot. The matrix M is shown in between.
Parameters
----------
a : np.array, shape (na,)
Source distribution
b : np.array, shape (nb,)
... | [
"Plot",
"matrix",
"M",
"with",
"the",
"source",
"and",
"target",
"1D",
"distribution"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/plot.py#L14-L54 | train |
rflamary/POT | ot/plot.py | plot2D_samples_mat | def plot2D_samples_mat(xs, xt, G, thr=1e-8, **kwargs):
""" Plot matrix M in 2D with lines using alpha values
Plot lines between source and target 2D samples with a color
proportional to the value of the matrix G between samples.
Parameters
----------
xs : ndarray, shape (ns,2)
Sourc... | python | def plot2D_samples_mat(xs, xt, G, thr=1e-8, **kwargs):
""" Plot matrix M in 2D with lines using alpha values
Plot lines between source and target 2D samples with a color
proportional to the value of the matrix G between samples.
Parameters
----------
xs : ndarray, shape (ns,2)
Sourc... | [
"def",
"plot2D_samples_mat",
"(",
"xs",
",",
"xt",
",",
"G",
",",
"thr",
"=",
"1e-8",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"'color'",
"not",
"in",
"kwargs",
")",
"and",
"(",
"'c'",
"not",
"in",
"kwargs",
")",
":",
"kwargs",
"[",
"'color'... | Plot matrix M in 2D with lines using alpha values
Plot lines between source and target 2D samples with a color
proportional to the value of the matrix G between samples.
Parameters
----------
xs : ndarray, shape (ns,2)
Source samples positions
b : ndarray, shape (nt,2)
Targe... | [
"Plot",
"matrix",
"M",
"in",
"2D",
"with",
"lines",
"using",
"alpha",
"values"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/plot.py#L57-L85 | train |
rflamary/POT | ot/gpu/da.py | sinkhorn_lpl1_mm | def sinkhorn_lpl1_mm(a, labels_a, b, M, reg, eta=0.1, numItermax=10,
numInnerItermax=200, stopInnerThr=1e-9, verbose=False,
log=False, to_numpy=True):
"""
Solve the entropic regularization optimal transport problem with nonconvex
group lasso regularization on GPU
... | python | def sinkhorn_lpl1_mm(a, labels_a, b, M, reg, eta=0.1, numItermax=10,
numInnerItermax=200, stopInnerThr=1e-9, verbose=False,
log=False, to_numpy=True):
"""
Solve the entropic regularization optimal transport problem with nonconvex
group lasso regularization on GPU
... | [
"def",
"sinkhorn_lpl1_mm",
"(",
"a",
",",
"labels_a",
",",
"b",
",",
"M",
",",
"reg",
",",
"eta",
"=",
"0.1",
",",
"numItermax",
"=",
"10",
",",
"numInnerItermax",
"=",
"200",
",",
"stopInnerThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log"... | Solve the entropic regularization optimal transport problem with nonconvex
group lasso regularization on GPU
If the input matrix are in numpy format, they will be uploaded to the
GPU first which can incur significant time overhead.
The function solves the following optimization problem:
.. math:... | [
"Solve",
"the",
"entropic",
"regularization",
"optimal",
"transport",
"problem",
"with",
"nonconvex",
"group",
"lasso",
"regularization",
"on",
"GPU"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/da.py#L22-L144 | train |
rflamary/POT | ot/datasets.py | get_2D_samples_gauss | def get_2D_samples_gauss(n, m, sigma, random_state=None):
""" Deprecated see make_2D_samples_gauss """
return make_2D_samples_gauss(n, m, sigma, random_state=None) | python | def get_2D_samples_gauss(n, m, sigma, random_state=None):
""" Deprecated see make_2D_samples_gauss """
return make_2D_samples_gauss(n, m, sigma, random_state=None) | [
"def",
"get_2D_samples_gauss",
"(",
"n",
",",
"m",
",",
"sigma",
",",
"random_state",
"=",
"None",
")",
":",
"return",
"make_2D_samples_gauss",
"(",
"n",
",",
"m",
",",
"sigma",
",",
"random_state",
"=",
"None",
")"
] | Deprecated see make_2D_samples_gauss | [
"Deprecated",
"see",
"make_2D_samples_gauss"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/datasets.py#L83-L85 | train |
rflamary/POT | ot/datasets.py | get_data_classif | def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs):
""" Deprecated see make_data_classif """
return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs) | python | def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs):
""" Deprecated see make_data_classif """
return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs) | [
"def",
"get_data_classif",
"(",
"dataset",
",",
"n",
",",
"nz",
"=",
".5",
",",
"theta",
"=",
"0",
",",
"random_state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"make_data_classif",
"(",
"dataset",
",",
"n",
",",
"nz",
"=",
".5",
"... | Deprecated see make_data_classif | [
"Deprecated",
"see",
"make_data_classif"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/datasets.py#L170-L172 | train |
rflamary/POT | ot/bregman.py | sinkhorn | def sinkhorn(a, b, M, reg, method='sinkhorn', numItermax=1000,
stopThr=1e-9, verbose=False, log=False, **kwargs):
u"""
Solve the entropic regularization optimal transport problem and return the OT matrix
The function solves the following optimization problem:
.. math::
\gamma = ar... | python | def sinkhorn(a, b, M, reg, method='sinkhorn', numItermax=1000,
stopThr=1e-9, verbose=False, log=False, **kwargs):
u"""
Solve the entropic regularization optimal transport problem and return the OT matrix
The function solves the following optimization problem:
.. math::
\gamma = ar... | [
"def",
"sinkhorn",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"method",
"=",
"'sinkhorn'",
",",
"numItermax",
"=",
"1000",
",",
"stopThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",... | u"""
Solve the entropic regularization optimal transport problem and return the OT matrix
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq ... | [
"u",
"Solve",
"the",
"entropic",
"regularization",
"optimal",
"transport",
"problem",
"and",
"return",
"the",
"OT",
"matrix"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L16-L128 | train |
rflamary/POT | ot/bregman.py | sinkhorn2 | def sinkhorn2(a, b, M, reg, method='sinkhorn', numItermax=1000,
stopThr=1e-9, verbose=False, log=False, **kwargs):
u"""
Solve the entropic regularization optimal transport problem and return the loss
The function solves the following optimization problem:
.. math::
W = \min_\gamm... | python | def sinkhorn2(a, b, M, reg, method='sinkhorn', numItermax=1000,
stopThr=1e-9, verbose=False, log=False, **kwargs):
u"""
Solve the entropic regularization optimal transport problem and return the loss
The function solves the following optimization problem:
.. math::
W = \min_\gamm... | [
"def",
"sinkhorn2",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"method",
"=",
"'sinkhorn'",
",",
"numItermax",
"=",
"1000",
",",
"stopThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":"... | u"""
Solve the entropic regularization optimal transport problem and return the loss
The function solves the following optimization problem:
.. math::
W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :... | [
"u",
"Solve",
"the",
"entropic",
"regularization",
"optimal",
"transport",
"problem",
"and",
"return",
"the",
"loss"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L131-L245 | train |
rflamary/POT | ot/bregman.py | geometricBar | def geometricBar(weights, alldistribT):
"""return the weighted geometric mean of distributions"""
assert(len(weights) == alldistribT.shape[1])
return np.exp(np.dot(np.log(alldistribT), weights.T)) | python | def geometricBar(weights, alldistribT):
"""return the weighted geometric mean of distributions"""
assert(len(weights) == alldistribT.shape[1])
return np.exp(np.dot(np.log(alldistribT), weights.T)) | [
"def",
"geometricBar",
"(",
"weights",
",",
"alldistribT",
")",
":",
"assert",
"(",
"len",
"(",
"weights",
")",
"==",
"alldistribT",
".",
"shape",
"[",
"1",
"]",
")",
"return",
"np",
".",
"exp",
"(",
"np",
".",
"dot",
"(",
"np",
".",
"log",
"(",
... | return the weighted geometric mean of distributions | [
"return",
"the",
"weighted",
"geometric",
"mean",
"of",
"distributions"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L968-L971 | train |
rflamary/POT | ot/bregman.py | geometricMean | def geometricMean(alldistribT):
"""return the geometric mean of distributions"""
return np.exp(np.mean(np.log(alldistribT), axis=1)) | python | def geometricMean(alldistribT):
"""return the geometric mean of distributions"""
return np.exp(np.mean(np.log(alldistribT), axis=1)) | [
"def",
"geometricMean",
"(",
"alldistribT",
")",
":",
"return",
"np",
".",
"exp",
"(",
"np",
".",
"mean",
"(",
"np",
".",
"log",
"(",
"alldistribT",
")",
",",
"axis",
"=",
"1",
")",
")"
] | return the geometric mean of distributions | [
"return",
"the",
"geometric",
"mean",
"of",
"distributions"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L974-L976 | train |
rflamary/POT | ot/bregman.py | projR | def projR(gamma, p):
"""return the KL projection on the row constrints """
return np.multiply(gamma.T, p / np.maximum(np.sum(gamma, axis=1), 1e-10)).T | python | def projR(gamma, p):
"""return the KL projection on the row constrints """
return np.multiply(gamma.T, p / np.maximum(np.sum(gamma, axis=1), 1e-10)).T | [
"def",
"projR",
"(",
"gamma",
",",
"p",
")",
":",
"return",
"np",
".",
"multiply",
"(",
"gamma",
".",
"T",
",",
"p",
"/",
"np",
".",
"maximum",
"(",
"np",
".",
"sum",
"(",
"gamma",
",",
"axis",
"=",
"1",
")",
",",
"1e-10",
")",
")",
".",
"T... | return the KL projection on the row constrints | [
"return",
"the",
"KL",
"projection",
"on",
"the",
"row",
"constrints"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L979-L981 | train |
rflamary/POT | ot/bregman.py | projC | def projC(gamma, q):
"""return the KL projection on the column constrints """
return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10)) | python | def projC(gamma, q):
"""return the KL projection on the column constrints """
return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10)) | [
"def",
"projC",
"(",
"gamma",
",",
"q",
")",
":",
"return",
"np",
".",
"multiply",
"(",
"gamma",
",",
"q",
"/",
"np",
".",
"maximum",
"(",
"np",
".",
"sum",
"(",
"gamma",
",",
"axis",
"=",
"0",
")",
",",
"1e-10",
")",
")"
] | return the KL projection on the column constrints | [
"return",
"the",
"KL",
"projection",
"on",
"the",
"column",
"constrints"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L984-L986 | train |
rflamary/POT | ot/bregman.py | barycenter | def barycenter(A, M, reg, weights=None, numItermax=1000,
stopThr=1e-4, verbose=False, log=False):
"""Compute the entropic regularized wasserstein barycenter of distributions A
The function solves the following optimization problem:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_... | python | def barycenter(A, M, reg, weights=None, numItermax=1000,
stopThr=1e-4, verbose=False, log=False):
"""Compute the entropic regularized wasserstein barycenter of distributions A
The function solves the following optimization problem:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_... | [
"def",
"barycenter",
"(",
"A",
",",
"M",
",",
"reg",
",",
"weights",
"=",
"None",
",",
"numItermax",
"=",
"1000",
",",
"stopThr",
"=",
"1e-4",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
")",
":",
"if",
"weights",
"is",
"None",
":",
"... | Compute the entropic regularized wasserstein barycenter of distributions A
The function solves the following optimization problem:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein ... | [
"Compute",
"the",
"entropic",
"regularized",
"wasserstein",
"barycenter",
"of",
"distributions",
"A"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L989-L1082 | train |
rflamary/POT | ot/bregman.py | convolutional_barycenter2d | def convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-9, stabThr=1e-30, verbose=False, log=False):
"""Compute the entropic regularized wasserstein barycenter of distributions A
where A is a collection of 2D images.
The function solves the following optimization problem:
..... | python | def convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-9, stabThr=1e-30, verbose=False, log=False):
"""Compute the entropic regularized wasserstein barycenter of distributions A
where A is a collection of 2D images.
The function solves the following optimization problem:
..... | [
"def",
"convolutional_barycenter2d",
"(",
"A",
",",
"reg",
",",
"weights",
"=",
"None",
",",
"numItermax",
"=",
"10000",
",",
"stopThr",
"=",
"1e-9",
",",
"stabThr",
"=",
"1e-30",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
")",
":",
"if",
... | Compute the entropic regularized wasserstein barycenter of distributions A
where A is a collection of 2D images.
The function solves the following optimization problem:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_{reg}(\cdot,\cdot)... | [
"Compute",
"the",
"entropic",
"regularized",
"wasserstein",
"barycenter",
"of",
"distributions",
"A",
"where",
"A",
"is",
"a",
"collection",
"of",
"2D",
"images",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1085-L1192 | train |
rflamary/POT | ot/bregman.py | unmix | def unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000,
stopThr=1e-3, verbose=False, log=False):
"""
Compute the unmixing of an observation with a given dictionary using Wasserstein distance
The function solve the following optimization problem:
.. math::
\mathbf{h} = arg\min_\m... | python | def unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000,
stopThr=1e-3, verbose=False, log=False):
"""
Compute the unmixing of an observation with a given dictionary using Wasserstein distance
The function solve the following optimization problem:
.. math::
\mathbf{h} = arg\min_\m... | [
"def",
"unmix",
"(",
"a",
",",
"D",
",",
"M",
",",
"M0",
",",
"h0",
",",
"reg",
",",
"reg0",
",",
"alpha",
",",
"numItermax",
"=",
"1000",
",",
"stopThr",
"=",
"1e-3",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
")",
":",
"# M = M/n... | Compute the unmixing of an observation with a given dictionary using Wasserstein distance
The function solve the following optimization problem:
.. math::
\mathbf{h} = arg\min_\mathbf{h} (1- \\alpha) W_{M,reg}(\mathbf{a},\mathbf{Dh})+\\alpha W_{M0,reg0}(\mathbf{h}_0,\mathbf{h})
where :
- :m... | [
"Compute",
"the",
"unmixing",
"of",
"an",
"observation",
"with",
"a",
"given",
"dictionary",
"using",
"Wasserstein",
"distance"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1195-L1300 | train |
rflamary/POT | ot/bregman.py | empirical_sinkhorn | def empirical_sinkhorn(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs):
'''
Solve the entropic regularization optimal transport problem and return the
OT matrix from empirical data
The function solves the following optimization pr... | python | def empirical_sinkhorn(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs):
'''
Solve the entropic regularization optimal transport problem and return the
OT matrix from empirical data
The function solves the following optimization pr... | [
"def",
"empirical_sinkhorn",
"(",
"X_s",
",",
"X_t",
",",
"reg",
",",
"a",
"=",
"None",
",",
"b",
"=",
"None",
",",
"metric",
"=",
"'sqeuclidean'",
",",
"numIterMax",
"=",
"10000",
",",
"stopThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log"... | Solve the entropic regularization optimal transport problem and return the
OT matrix from empirical data
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
... | [
"Solve",
"the",
"entropic",
"regularization",
"optimal",
"transport",
"problem",
"and",
"return",
"the",
"OT",
"matrix",
"from",
"empirical",
"data"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1303-L1390 | train |
rflamary/POT | ot/bregman.py | empirical_sinkhorn2 | def empirical_sinkhorn2(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs):
'''
Solve the entropic regularization optimal transport problem from empirical
data and return the OT loss
The function solves the following optimization pr... | python | def empirical_sinkhorn2(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs):
'''
Solve the entropic regularization optimal transport problem from empirical
data and return the OT loss
The function solves the following optimization pr... | [
"def",
"empirical_sinkhorn2",
"(",
"X_s",
",",
"X_t",
",",
"reg",
",",
"a",
"=",
"None",
",",
"b",
"=",
"None",
",",
"metric",
"=",
"'sqeuclidean'",
",",
"numIterMax",
"=",
"10000",
",",
"stopThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log... | Solve the entropic regularization optimal transport problem from empirical
data and return the OT loss
The function solves the following optimization problem:
.. math::
W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamm... | [
"Solve",
"the",
"entropic",
"regularization",
"optimal",
"transport",
"problem",
"from",
"empirical",
"data",
"and",
"return",
"the",
"OT",
"loss"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1393-L1480 | train |
rflamary/POT | ot/bregman.py | empirical_sinkhorn_divergence | def empirical_sinkhorn_divergence(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs):
'''
Compute the sinkhorn divergence loss from empirical data
The function solves the following optimization problems and return the
sinkhorn diverg... | python | def empirical_sinkhorn_divergence(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs):
'''
Compute the sinkhorn divergence loss from empirical data
The function solves the following optimization problems and return the
sinkhorn diverg... | [
"def",
"empirical_sinkhorn_divergence",
"(",
"X_s",
",",
"X_t",
",",
"reg",
",",
"a",
"=",
"None",
",",
"b",
"=",
"None",
",",
"metric",
"=",
"'sqeuclidean'",
",",
"numIterMax",
"=",
"10000",
",",
"stopThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
"... | Compute the sinkhorn divergence loss from empirical data
The function solves the following optimization problems and return the
sinkhorn divergence :math:`S`:
.. math::
W &= \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
W_a &= \min_{\gamma_a} <\gamma_a,M_a>_F + reg\cdot\Omega(\gamma_... | [
"Compute",
"the",
"sinkhorn",
"divergence",
"loss",
"from",
"empirical",
"data"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1483-L1599 | train |
rflamary/POT | ot/lp/__init__.py | emd | def emd(a, b, M, numItermax=100000, log=False):
"""Solves the Earth Movers distance problem and returns the OT matrix
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the metric cost matrix
- a an... | python | def emd(a, b, M, numItermax=100000, log=False):
"""Solves the Earth Movers distance problem and returns the OT matrix
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the metric cost matrix
- a an... | [
"def",
"emd",
"(",
"a",
",",
"b",
",",
"M",
",",
"numItermax",
"=",
"100000",
",",
"log",
"=",
"False",
")",
":",
"a",
"=",
"np",
".",
"asarray",
"(",
"a",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"b",
"=",
"np",
".",
"asarray",
"(",
"... | Solves the Earth Movers distance problem and returns the OT matrix
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the metric cost matrix
- a and b are the sample weights
Uses the algorithm prop... | [
"Solves",
"the",
"Earth",
"Movers",
"distance",
"problem",
"and",
"returns",
"the",
"OT",
"matrix"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/lp/__init__.py#L25-L113 | train |
rflamary/POT | ot/lp/__init__.py | emd2 | def emd2(a, b, M, processes=multiprocessing.cpu_count(),
numItermax=100000, log=False, return_matrix=False):
"""Solves the Earth Movers distance problem and returns the loss
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma... | python | def emd2(a, b, M, processes=multiprocessing.cpu_count(),
numItermax=100000, log=False, return_matrix=False):
"""Solves the Earth Movers distance problem and returns the loss
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma... | [
"def",
"emd2",
"(",
"a",
",",
"b",
",",
"M",
",",
"processes",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
",",
"numItermax",
"=",
"100000",
",",
"log",
"=",
"False",
",",
"return_matrix",
"=",
"False",
")",
":",
"a",
"=",
"np",
".",
"asarr... | Solves the Earth Movers distance problem and returns the loss
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the metric cost matrix
- a and b are the sample weights
Uses the algorithm proposed i... | [
"Solves",
"the",
"Earth",
"Movers",
"distance",
"problem",
"and",
"returns",
"the",
"loss"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/lp/__init__.py#L116-L219 | train |
rflamary/POT | ot/da.py | sinkhorn_l1l2_gl | def sinkhorn_l1l2_gl(a, labels_a, b, M, reg, eta=0.1, numItermax=10,
numInnerItermax=200, stopInnerThr=1e-9, verbose=False,
log=False):
"""
Solve the entropic regularization optimal transport problem with group
lasso regularization
The function solves the follo... | python | def sinkhorn_l1l2_gl(a, labels_a, b, M, reg, eta=0.1, numItermax=10,
numInnerItermax=200, stopInnerThr=1e-9, verbose=False,
log=False):
"""
Solve the entropic regularization optimal transport problem with group
lasso regularization
The function solves the follo... | [
"def",
"sinkhorn_l1l2_gl",
"(",
"a",
",",
"labels_a",
",",
"b",
",",
"M",
",",
"reg",
",",
"eta",
"=",
"0.1",
",",
"numItermax",
"=",
"10",
",",
"numInnerItermax",
"=",
"200",
",",
"stopInnerThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log"... | Solve the entropic regularization optimal transport problem with group
lasso regularization
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)+
\eta \Omega_g(\gamma)
s.t. \gamma 1 = a
\gam... | [
"Solve",
"the",
"entropic",
"regularization",
"optimal",
"transport",
"problem",
"with",
"group",
"lasso",
"regularization"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/da.py#L134-L238 | train |
rflamary/POT | ot/da.py | OT_mapping_linear | def OT_mapping_linear(xs, xt, reg=1e-6, ws=None,
wt=None, bias=True, log=False):
""" return OT linear operator between samples
The function estimates the optimal linear operator that aligns the two
empirical distributions. This is equivalent to estimating the closed
form mapping b... | python | def OT_mapping_linear(xs, xt, reg=1e-6, ws=None,
wt=None, bias=True, log=False):
""" return OT linear operator between samples
The function estimates the optimal linear operator that aligns the two
empirical distributions. This is equivalent to estimating the closed
form mapping b... | [
"def",
"OT_mapping_linear",
"(",
"xs",
",",
"xt",
",",
"reg",
"=",
"1e-6",
",",
"ws",
"=",
"None",
",",
"wt",
"=",
"None",
",",
"bias",
"=",
"True",
",",
"log",
"=",
"False",
")",
":",
"d",
"=",
"xs",
".",
"shape",
"[",
"1",
"]",
"if",
"bias"... | return OT linear operator between samples
The function estimates the optimal linear operator that aligns the two
empirical distributions. This is equivalent to estimating the closed
form mapping between two Gaussian distributions :math:`N(\mu_s,\Sigma_s)`
and :math:`N(\mu_t,\Sigma_t)` as proposed in [1... | [
"return",
"OT",
"linear",
"operator",
"between",
"samples"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/da.py#L639-L740 | train |
rflamary/POT | ot/gpu/utils.py | euclidean_distances | def euclidean_distances(a, b, squared=False, to_numpy=True):
"""
Compute the pairwise euclidean distance between matrices a and b.
If the input matrix are in numpy format, they will be uploaded to the
GPU first which can incur significant time overhead.
Parameters
----------
a : np.ndarray... | python | def euclidean_distances(a, b, squared=False, to_numpy=True):
"""
Compute the pairwise euclidean distance between matrices a and b.
If the input matrix are in numpy format, they will be uploaded to the
GPU first which can incur significant time overhead.
Parameters
----------
a : np.ndarray... | [
"def",
"euclidean_distances",
"(",
"a",
",",
"b",
",",
"squared",
"=",
"False",
",",
"to_numpy",
"=",
"True",
")",
":",
"a",
",",
"b",
"=",
"to_gpu",
"(",
"a",
",",
"b",
")",
"a2",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"square",
"(",
"a",
")... | Compute the pairwise euclidean distance between matrices a and b.
If the input matrix are in numpy format, they will be uploaded to the
GPU first which can incur significant time overhead.
Parameters
----------
a : np.ndarray (n, f)
first matrix
b : np.ndarray (m, f)
second mat... | [
"Compute",
"the",
"pairwise",
"euclidean",
"distance",
"between",
"matrices",
"a",
"and",
"b",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/utils.py#L16-L54 | train |
rflamary/POT | ot/gpu/utils.py | dist | def dist(x1, x2=None, metric='sqeuclidean', to_numpy=True):
"""Compute distance between samples in x1 and x2 on gpu
Parameters
----------
x1 : np.array (n1,d)
matrix with n1 samples of size d
x2 : np.array (n2,d), optional
matrix with n2 samples of size d (if None then x2=x1)
m... | python | def dist(x1, x2=None, metric='sqeuclidean', to_numpy=True):
"""Compute distance between samples in x1 and x2 on gpu
Parameters
----------
x1 : np.array (n1,d)
matrix with n1 samples of size d
x2 : np.array (n2,d), optional
matrix with n2 samples of size d (if None then x2=x1)
m... | [
"def",
"dist",
"(",
"x1",
",",
"x2",
"=",
"None",
",",
"metric",
"=",
"'sqeuclidean'",
",",
"to_numpy",
"=",
"True",
")",
":",
"if",
"x2",
"is",
"None",
":",
"x2",
"=",
"x1",
"if",
"metric",
"==",
"\"sqeuclidean\"",
":",
"return",
"euclidean_distances"... | Compute distance between samples in x1 and x2 on gpu
Parameters
----------
x1 : np.array (n1,d)
matrix with n1 samples of size d
x2 : np.array (n2,d), optional
matrix with n2 samples of size d (if None then x2=x1)
metric : str
Metric from 'sqeuclidean', 'euclidean',
R... | [
"Compute",
"distance",
"between",
"samples",
"in",
"x1",
"and",
"x2",
"on",
"gpu"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/utils.py#L57-L85 | train |
rflamary/POT | ot/gpu/utils.py | to_gpu | def to_gpu(*args):
""" Upload numpy arrays to GPU and return them"""
if len(args) > 1:
return (cp.asarray(x) for x in args)
else:
return cp.asarray(args[0]) | python | def to_gpu(*args):
""" Upload numpy arrays to GPU and return them"""
if len(args) > 1:
return (cp.asarray(x) for x in args)
else:
return cp.asarray(args[0]) | [
"def",
"to_gpu",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"return",
"(",
"cp",
".",
"asarray",
"(",
"x",
")",
"for",
"x",
"in",
"args",
")",
"else",
":",
"return",
"cp",
".",
"asarray",
"(",
"args",
"[",
"0",
... | Upload numpy arrays to GPU and return them | [
"Upload",
"numpy",
"arrays",
"to",
"GPU",
"and",
"return",
"them"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/utils.py#L88-L93 | train |
rflamary/POT | ot/gpu/utils.py | to_np | def to_np(*args):
""" convert GPU arras to numpy and return them"""
if len(args) > 1:
return (cp.asnumpy(x) for x in args)
else:
return cp.asnumpy(args[0]) | python | def to_np(*args):
""" convert GPU arras to numpy and return them"""
if len(args) > 1:
return (cp.asnumpy(x) for x in args)
else:
return cp.asnumpy(args[0]) | [
"def",
"to_np",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"return",
"(",
"cp",
".",
"asnumpy",
"(",
"x",
")",
"for",
"x",
"in",
"args",
")",
"else",
":",
"return",
"cp",
".",
"asnumpy",
"(",
"args",
"[",
"0",
... | convert GPU arras to numpy and return them | [
"convert",
"GPU",
"arras",
"to",
"numpy",
"and",
"return",
"them"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/utils.py#L96-L101 | train |
rflamary/POT | ot/lp/cvx.py | scipy_sparse_to_spmatrix | def scipy_sparse_to_spmatrix(A):
"""Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"""
coo = A.tocoo()
SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
return SP | python | def scipy_sparse_to_spmatrix(A):
"""Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"""
coo = A.tocoo()
SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
return SP | [
"def",
"scipy_sparse_to_spmatrix",
"(",
"A",
")",
":",
"coo",
"=",
"A",
".",
"tocoo",
"(",
")",
"SP",
"=",
"spmatrix",
"(",
"coo",
".",
"data",
".",
"tolist",
"(",
")",
",",
"coo",
".",
"row",
".",
"tolist",
"(",
")",
",",
"coo",
".",
"col",
".... | Efficient conversion from scipy sparse matrix to cvxopt sparse matrix | [
"Efficient",
"conversion",
"from",
"scipy",
"sparse",
"matrix",
"to",
"cvxopt",
"sparse",
"matrix"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/lp/cvx.py#L22-L26 | train |
rflamary/POT | ot/optim.py | line_search_armijo | def line_search_armijo(f, xk, pk, gfk, old_fval,
args=(), c1=1e-4, alpha0=0.99):
"""
Armijo linesearch function that works with matrices
find an approximate minimum of f(xk+alpha*pk) that satifies the
armijo conditions.
Parameters
----------
f : function
los... | python | def line_search_armijo(f, xk, pk, gfk, old_fval,
args=(), c1=1e-4, alpha0=0.99):
"""
Armijo linesearch function that works with matrices
find an approximate minimum of f(xk+alpha*pk) that satifies the
armijo conditions.
Parameters
----------
f : function
los... | [
"def",
"line_search_armijo",
"(",
"f",
",",
"xk",
",",
"pk",
",",
"gfk",
",",
"old_fval",
",",
"args",
"=",
"(",
")",
",",
"c1",
"=",
"1e-4",
",",
"alpha0",
"=",
"0.99",
")",
":",
"xk",
"=",
"np",
".",
"atleast_1d",
"(",
"xk",
")",
"fc",
"=",
... | Armijo linesearch function that works with matrices
find an approximate minimum of f(xk+alpha*pk) that satifies the
armijo conditions.
Parameters
----------
f : function
loss function
xk : np.ndarray
initial position
pk : np.ndarray
descent direction
gfk : np.n... | [
"Armijo",
"linesearch",
"function",
"that",
"works",
"with",
"matrices"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/optim.py#L18-L72 | train |
rflamary/POT | ot/optim.py | cg | def cg(a, b, M, reg, f, df, G0=None, numItermax=200,
stopThr=1e-9, verbose=False, log=False):
"""
Solve the general regularized OT problem with conditional gradient
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg*f(\gamma)... | python | def cg(a, b, M, reg, f, df, G0=None, numItermax=200,
stopThr=1e-9, verbose=False, log=False):
"""
Solve the general regularized OT problem with conditional gradient
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg*f(\gamma)... | [
"def",
"cg",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"f",
",",
"df",
",",
"G0",
"=",
"None",
",",
"numItermax",
"=",
"200",
",",
"stopThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
")",
":",
"loop",
"=",
"... | Solve the general regularized OT problem with conditional gradient
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg*f(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (n... | [
"Solve",
"the",
"general",
"regularized",
"OT",
"problem",
"with",
"conditional",
"gradient"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/optim.py#L75-L204 | train |
rflamary/POT | ot/optim.py | gcg | def gcg(a, b, M, reg1, reg2, f, df, G0=None, numItermax=10,
numInnerItermax=200, stopThr=1e-9, verbose=False, log=False):
"""
Solve the general regularized OT problem with the generalized conditional gradient
The function solves the following optimization problem:
.. math::
\gamma ... | python | def gcg(a, b, M, reg1, reg2, f, df, G0=None, numItermax=10,
numInnerItermax=200, stopThr=1e-9, verbose=False, log=False):
"""
Solve the general regularized OT problem with the generalized conditional gradient
The function solves the following optimization problem:
.. math::
\gamma ... | [
"def",
"gcg",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg1",
",",
"reg2",
",",
"f",
",",
"df",
",",
"G0",
"=",
"None",
",",
"numItermax",
"=",
"10",
",",
"numInnerItermax",
"=",
"200",
",",
"stopThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",... | Solve the general regularized OT problem with the generalized conditional gradient
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg1\cdot\Omega(\gamma) + reg2\cdot f(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
... | [
"Solve",
"the",
"general",
"regularized",
"OT",
"problem",
"with",
"the",
"generalized",
"conditional",
"gradient"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/optim.py#L207-L341 | train |
rflamary/POT | ot/smooth.py | projection_simplex | def projection_simplex(V, z=1, axis=None):
""" Projection of x onto the simplex, scaled by z
P(x; z) = argmin_{y >= 0, sum(y) = z} ||y - x||^2
z: float or array
If array, len(z) must be compatible with V
axis: None or int
- axis=None: project V by P(V.ravel(); z)
- axis=1: p... | python | def projection_simplex(V, z=1, axis=None):
""" Projection of x onto the simplex, scaled by z
P(x; z) = argmin_{y >= 0, sum(y) = z} ||y - x||^2
z: float or array
If array, len(z) must be compatible with V
axis: None or int
- axis=None: project V by P(V.ravel(); z)
- axis=1: p... | [
"def",
"projection_simplex",
"(",
"V",
",",
"z",
"=",
"1",
",",
"axis",
"=",
"None",
")",
":",
"if",
"axis",
"==",
"1",
":",
"n_features",
"=",
"V",
".",
"shape",
"[",
"1",
"]",
"U",
"=",
"np",
".",
"sort",
"(",
"V",
",",
"axis",
"=",
"1",
... | Projection of x onto the simplex, scaled by z
P(x; z) = argmin_{y >= 0, sum(y) = z} ||y - x||^2
z: float or array
If array, len(z) must be compatible with V
axis: None or int
- axis=None: project V by P(V.ravel(); z)
- axis=1: project each V[i] by P(V[i]; z[i])
- axis=0:... | [
"Projection",
"of",
"x",
"onto",
"the",
"simplex",
"scaled",
"by",
"z"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L47-L74 | train |
rflamary/POT | ot/smooth.py | dual_obj_grad | def dual_obj_grad(alpha, beta, a, b, C, regul):
"""
Compute objective value and gradients of dual objective.
Parameters
----------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Current iterate of dual potentials.
a: array, shape = len(a)
b: array, shape = len(b)
... | python | def dual_obj_grad(alpha, beta, a, b, C, regul):
"""
Compute objective value and gradients of dual objective.
Parameters
----------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Current iterate of dual potentials.
a: array, shape = len(a)
b: array, shape = len(b)
... | [
"def",
"dual_obj_grad",
"(",
"alpha",
",",
"beta",
",",
"a",
",",
"b",
",",
"C",
",",
"regul",
")",
":",
"obj",
"=",
"np",
".",
"dot",
"(",
"alpha",
",",
"a",
")",
"+",
"np",
".",
"dot",
"(",
"beta",
",",
"b",
")",
"grad_alpha",
"=",
"a",
"... | Compute objective value and gradients of dual objective.
Parameters
----------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Current iterate of dual potentials.
a: array, shape = len(a)
b: array, shape = len(b)
Input histograms (should be non-negative and sum to 1).
... | [
"Compute",
"objective",
"value",
"and",
"gradients",
"of",
"dual",
"objective",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L192-L233 | train |
rflamary/POT | ot/smooth.py | solve_dual | def solve_dual(a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500,
verbose=False):
"""
Solve the "smoothed" dual objective.
Parameters
----------
a: array, shape = len(a)
b: array, shape = len(b)
Input histograms (should be non-negative and sum to 1).
C: array,... | python | def solve_dual(a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500,
verbose=False):
"""
Solve the "smoothed" dual objective.
Parameters
----------
a: array, shape = len(a)
b: array, shape = len(b)
Input histograms (should be non-negative and sum to 1).
C: array,... | [
"def",
"solve_dual",
"(",
"a",
",",
"b",
",",
"C",
",",
"regul",
",",
"method",
"=",
"\"L-BFGS-B\"",
",",
"tol",
"=",
"1e-3",
",",
"max_iter",
"=",
"500",
",",
"verbose",
"=",
"False",
")",
":",
"def",
"_func",
"(",
"params",
")",
":",
"# Unpack al... | Solve the "smoothed" dual objective.
Parameters
----------
a: array, shape = len(a)
b: array, shape = len(b)
Input histograms (should be non-negative and sum to 1).
C: array, shape = len(a) x len(b)
Ground cost matrix.
regul: Regularization object
Should implement a delt... | [
"Solve",
"the",
"smoothed",
"dual",
"objective",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L236-L289 | train |
rflamary/POT | ot/smooth.py | semi_dual_obj_grad | def semi_dual_obj_grad(alpha, a, b, C, regul):
"""
Compute objective value and gradient of semi-dual objective.
Parameters
----------
alpha: array, shape = len(a)
Current iterate of semi-dual potentials.
a: array, shape = len(a)
b: array, shape = len(b)
Input histograms (sho... | python | def semi_dual_obj_grad(alpha, a, b, C, regul):
"""
Compute objective value and gradient of semi-dual objective.
Parameters
----------
alpha: array, shape = len(a)
Current iterate of semi-dual potentials.
a: array, shape = len(a)
b: array, shape = len(b)
Input histograms (sho... | [
"def",
"semi_dual_obj_grad",
"(",
"alpha",
",",
"a",
",",
"b",
",",
"C",
",",
"regul",
")",
":",
"obj",
"=",
"np",
".",
"dot",
"(",
"alpha",
",",
"a",
")",
"grad",
"=",
"a",
".",
"copy",
"(",
")",
"# X[:, j] = alpha - C[:, j]",
"X",
"=",
"alpha",
... | Compute objective value and gradient of semi-dual objective.
Parameters
----------
alpha: array, shape = len(a)
Current iterate of semi-dual potentials.
a: array, shape = len(a)
b: array, shape = len(b)
Input histograms (should be non-negative and sum to 1).
C: array, shape = le... | [
"Compute",
"objective",
"value",
"and",
"gradient",
"of",
"semi",
"-",
"dual",
"objective",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L292-L328 | train |
rflamary/POT | ot/smooth.py | solve_semi_dual | def solve_semi_dual(a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500,
verbose=False):
"""
Solve the "smoothed" semi-dual objective.
Parameters
----------
a: array, shape = len(a)
b: array, shape = len(b)
Input histograms (should be non-negative and sum to 1)... | python | def solve_semi_dual(a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500,
verbose=False):
"""
Solve the "smoothed" semi-dual objective.
Parameters
----------
a: array, shape = len(a)
b: array, shape = len(b)
Input histograms (should be non-negative and sum to 1)... | [
"def",
"solve_semi_dual",
"(",
"a",
",",
"b",
",",
"C",
",",
"regul",
",",
"method",
"=",
"\"L-BFGS-B\"",
",",
"tol",
"=",
"1e-3",
",",
"max_iter",
"=",
"500",
",",
"verbose",
"=",
"False",
")",
":",
"def",
"_func",
"(",
"alpha",
")",
":",
"obj",
... | Solve the "smoothed" semi-dual objective.
Parameters
----------
a: array, shape = len(a)
b: array, shape = len(b)
Input histograms (should be non-negative and sum to 1).
C: array, shape = len(a) x len(b)
Ground cost matrix.
regul: Regularization object
Should implement a... | [
"Solve",
"the",
"smoothed",
"semi",
"-",
"dual",
"objective",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L331-L368 | train |
rflamary/POT | ot/smooth.py | get_plan_from_dual | def get_plan_from_dual(alpha, beta, C, regul):
"""
Retrieve optimal transportation plan from optimal dual potentials.
Parameters
----------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Optimal dual potentials.
C: array, shape = len(a) x len(b)
Ground cost matrix.... | python | def get_plan_from_dual(alpha, beta, C, regul):
"""
Retrieve optimal transportation plan from optimal dual potentials.
Parameters
----------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Optimal dual potentials.
C: array, shape = len(a) x len(b)
Ground cost matrix.... | [
"def",
"get_plan_from_dual",
"(",
"alpha",
",",
"beta",
",",
"C",
",",
"regul",
")",
":",
"X",
"=",
"alpha",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"+",
"beta",
"-",
"C",
"return",
"regul",
".",
"delta_Omega",
"(",
"X",
")",
"[",
"1",
"]"
] | Retrieve optimal transportation plan from optimal dual potentials.
Parameters
----------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Optimal dual potentials.
C: array, shape = len(a) x len(b)
Ground cost matrix.
regul: Regularization object
Should implement ... | [
"Retrieve",
"optimal",
"transportation",
"plan",
"from",
"optimal",
"dual",
"potentials",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L371-L391 | train |
rflamary/POT | ot/smooth.py | get_plan_from_semi_dual | def get_plan_from_semi_dual(alpha, b, C, regul):
"""
Retrieve optimal transportation plan from optimal semi-dual potentials.
Parameters
----------
alpha: array, shape = len(a)
Optimal semi-dual potentials.
b: array, shape = len(b)
Second input histogram (should be non-negative a... | python | def get_plan_from_semi_dual(alpha, b, C, regul):
"""
Retrieve optimal transportation plan from optimal semi-dual potentials.
Parameters
----------
alpha: array, shape = len(a)
Optimal semi-dual potentials.
b: array, shape = len(b)
Second input histogram (should be non-negative a... | [
"def",
"get_plan_from_semi_dual",
"(",
"alpha",
",",
"b",
",",
"C",
",",
"regul",
")",
":",
"X",
"=",
"alpha",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"-",
"C",
"return",
"regul",
".",
"max_Omega",
"(",
"X",
",",
"b",
")",
"[",
"1",
"]",
"*",... | Retrieve optimal transportation plan from optimal semi-dual potentials.
Parameters
----------
alpha: array, shape = len(a)
Optimal semi-dual potentials.
b: array, shape = len(b)
Second input histogram (should be non-negative and sum to 1).
C: array, shape = len(a) x len(b)
G... | [
"Retrieve",
"optimal",
"transportation",
"plan",
"from",
"optimal",
"semi",
"-",
"dual",
"potentials",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L394-L415 | train |
rflamary/POT | ot/smooth.py | smooth_ot_dual | def smooth_ot_dual(a, b, M, reg, reg_type='l2', method="L-BFGS-B", stopThr=1e-9,
numItermax=500, verbose=False, log=False):
r"""
Solve the regularized OT problem in the dual and return the OT matrix
The function solves the smooth relaxed dual formulation (7) in [17]_ :
.. math::
... | python | def smooth_ot_dual(a, b, M, reg, reg_type='l2', method="L-BFGS-B", stopThr=1e-9,
numItermax=500, verbose=False, log=False):
r"""
Solve the regularized OT problem in the dual and return the OT matrix
The function solves the smooth relaxed dual formulation (7) in [17]_ :
.. math::
... | [
"def",
"smooth_ot_dual",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"reg_type",
"=",
"'l2'",
",",
"method",
"=",
"\"L-BFGS-B\"",
",",
"stopThr",
"=",
"1e-9",
",",
"numItermax",
"=",
"500",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
... | r"""
Solve the regularized OT problem in the dual and return the OT matrix
The function solves the smooth relaxed dual formulation (7) in [17]_ :
.. math::
\max_{\alpha,\beta}\quad a^T\alpha+b^T\beta-\sum_j\delta_\Omega(\alpha+\beta_j-\mathbf{m}_j)
where :
- :math:`\mathbf{m}_j` is the j... | [
"r",
"Solve",
"the",
"regularized",
"OT",
"problem",
"in",
"the",
"dual",
"and",
"return",
"the",
"OT",
"matrix"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L418-L507 | train |
rflamary/POT | ot/smooth.py | smooth_ot_semi_dual | def smooth_ot_semi_dual(a, b, M, reg, reg_type='l2', method="L-BFGS-B", stopThr=1e-9,
numItermax=500, verbose=False, log=False):
r"""
Solve the regularized OT problem in the semi-dual and return the OT matrix
The function solves the smooth relaxed dual formulation (10) in [17]_ :
... | python | def smooth_ot_semi_dual(a, b, M, reg, reg_type='l2', method="L-BFGS-B", stopThr=1e-9,
numItermax=500, verbose=False, log=False):
r"""
Solve the regularized OT problem in the semi-dual and return the OT matrix
The function solves the smooth relaxed dual formulation (10) in [17]_ :
... | [
"def",
"smooth_ot_semi_dual",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"reg_type",
"=",
"'l2'",
",",
"method",
"=",
"\"L-BFGS-B\"",
",",
"stopThr",
"=",
"1e-9",
",",
"numItermax",
"=",
"500",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"Fals... | r"""
Solve the regularized OT problem in the semi-dual and return the OT matrix
The function solves the smooth relaxed dual formulation (10) in [17]_ :
.. math::
\max_{\alpha}\quad a^T\alpha-OT_\Omega^*(\alpha,b)
where :
.. math::
OT_\Omega^*(\alpha,b)=\sum_j b_j
- :math:`\m... | [
"r",
"Solve",
"the",
"regularized",
"OT",
"problem",
"in",
"the",
"semi",
"-",
"dual",
"and",
"return",
"the",
"OT",
"matrix"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L510-L600 | train |
rflamary/POT | ot/utils.py | kernel | def kernel(x1, x2, method='gaussian', sigma=1, **kwargs):
"""Compute kernel matrix"""
if method.lower() in ['gaussian', 'gauss', 'rbf']:
K = np.exp(-dist(x1, x2) / (2 * sigma**2))
return K | python | def kernel(x1, x2, method='gaussian', sigma=1, **kwargs):
"""Compute kernel matrix"""
if method.lower() in ['gaussian', 'gauss', 'rbf']:
K = np.exp(-dist(x1, x2) / (2 * sigma**2))
return K | [
"def",
"kernel",
"(",
"x1",
",",
"x2",
",",
"method",
"=",
"'gaussian'",
",",
"sigma",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"method",
".",
"lower",
"(",
")",
"in",
"[",
"'gaussian'",
",",
"'gauss'",
",",
"'rbf'",
"]",
":",
"K",
"=... | Compute kernel matrix | [
"Compute",
"kernel",
"matrix"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L45-L49 | train |
rflamary/POT | ot/utils.py | clean_zeros | def clean_zeros(a, b, M):
""" Remove all components with zeros weights in a and b
"""
M2 = M[a > 0, :][:, b > 0].copy() # copy force c style matrix (froemd)
a2 = a[a > 0]
b2 = b[b > 0]
return a2, b2, M2 | python | def clean_zeros(a, b, M):
""" Remove all components with zeros weights in a and b
"""
M2 = M[a > 0, :][:, b > 0].copy() # copy force c style matrix (froemd)
a2 = a[a > 0]
b2 = b[b > 0]
return a2, b2, M2 | [
"def",
"clean_zeros",
"(",
"a",
",",
"b",
",",
"M",
")",
":",
"M2",
"=",
"M",
"[",
"a",
">",
"0",
",",
":",
"]",
"[",
":",
",",
"b",
">",
"0",
"]",
".",
"copy",
"(",
")",
"# copy force c style matrix (froemd)",
"a2",
"=",
"a",
"[",
"a",
">",
... | Remove all components with zeros weights in a and b | [
"Remove",
"all",
"components",
"with",
"zeros",
"weights",
"in",
"a",
"and",
"b"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L71-L77 | train |
rflamary/POT | ot/utils.py | dist | def dist(x1, x2=None, metric='sqeuclidean'):
"""Compute distance between samples in x1 and x2 using function scipy.spatial.distance.cdist
Parameters
----------
x1 : np.array (n1,d)
matrix with n1 samples of size d
x2 : np.array (n2,d), optional
matrix with n2 samples of size d (if ... | python | def dist(x1, x2=None, metric='sqeuclidean'):
"""Compute distance between samples in x1 and x2 using function scipy.spatial.distance.cdist
Parameters
----------
x1 : np.array (n1,d)
matrix with n1 samples of size d
x2 : np.array (n2,d), optional
matrix with n2 samples of size d (if ... | [
"def",
"dist",
"(",
"x1",
",",
"x2",
"=",
"None",
",",
"metric",
"=",
"'sqeuclidean'",
")",
":",
"if",
"x2",
"is",
"None",
":",
"x2",
"=",
"x1",
"if",
"metric",
"==",
"\"sqeuclidean\"",
":",
"return",
"euclidean_distances",
"(",
"x1",
",",
"x2",
",",... | Compute distance between samples in x1 and x2 using function scipy.spatial.distance.cdist
Parameters
----------
x1 : np.array (n1,d)
matrix with n1 samples of size d
x2 : np.array (n2,d), optional
matrix with n2 samples of size d (if None then x2=x1)
metric : str, fun, optional
... | [
"Compute",
"distance",
"between",
"samples",
"in",
"x1",
"and",
"x2",
"using",
"function",
"scipy",
".",
"spatial",
".",
"distance",
".",
"cdist"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L108-L137 | train |
rflamary/POT | ot/utils.py | cost_normalization | def cost_normalization(C, norm=None):
""" Apply normalization to the loss matrix
Parameters
----------
C : np.array (n1, n2)
The cost matrix to normalize.
norm : str
type of normalization from 'median','max','log','loglog'. Any other
value do not normalize.
Returns
... | python | def cost_normalization(C, norm=None):
""" Apply normalization to the loss matrix
Parameters
----------
C : np.array (n1, n2)
The cost matrix to normalize.
norm : str
type of normalization from 'median','max','log','loglog'. Any other
value do not normalize.
Returns
... | [
"def",
"cost_normalization",
"(",
"C",
",",
"norm",
"=",
"None",
")",
":",
"if",
"norm",
"==",
"\"median\"",
":",
"C",
"/=",
"float",
"(",
"np",
".",
"median",
"(",
"C",
")",
")",
"elif",
"norm",
"==",
"\"max\"",
":",
"C",
"/=",
"float",
"(",
"np... | Apply normalization to the loss matrix
Parameters
----------
C : np.array (n1, n2)
The cost matrix to normalize.
norm : str
type of normalization from 'median','max','log','loglog'. Any other
value do not normalize.
Returns
-------
C : np.array (n1, n2)
T... | [
"Apply",
"normalization",
"to",
"the",
"loss",
"matrix"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L169-L199 | train |
rflamary/POT | ot/utils.py | parmap | def parmap(f, X, nprocs=multiprocessing.cpu_count()):
""" paralell map for multiprocessing """
q_in = multiprocessing.Queue(1)
q_out = multiprocessing.Queue()
proc = [multiprocessing.Process(target=fun, args=(f, q_in, q_out))
for _ in range(nprocs)]
for p in proc:
p.daemon = Tru... | python | def parmap(f, X, nprocs=multiprocessing.cpu_count()):
""" paralell map for multiprocessing """
q_in = multiprocessing.Queue(1)
q_out = multiprocessing.Queue()
proc = [multiprocessing.Process(target=fun, args=(f, q_in, q_out))
for _ in range(nprocs)]
for p in proc:
p.daemon = Tru... | [
"def",
"parmap",
"(",
"f",
",",
"X",
",",
"nprocs",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
")",
":",
"q_in",
"=",
"multiprocessing",
".",
"Queue",
"(",
"1",
")",
"q_out",
"=",
"multiprocessing",
".",
"Queue",
"(",
")",
"proc",
"=",
"[",
... | paralell map for multiprocessing | [
"paralell",
"map",
"for",
"multiprocessing"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L216-L233 | train |
rflamary/POT | ot/utils.py | _is_deprecated | def _is_deprecated(func):
"""Helper to check if func is wraped by our deprecated decorator"""
if sys.version_info < (3, 5):
raise NotImplementedError("This is only available for python3.5 "
"or above")
closures = getattr(func, '__closure__', [])
if closures is N... | python | def _is_deprecated(func):
"""Helper to check if func is wraped by our deprecated decorator"""
if sys.version_info < (3, 5):
raise NotImplementedError("This is only available for python3.5 "
"or above")
closures = getattr(func, '__closure__', [])
if closures is N... | [
"def",
"_is_deprecated",
"(",
"func",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"5",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"This is only available for python3.5 \"",
"\"or above\"",
")",
"closures",
"=",
"getattr",
"(",
"func",
... | Helper to check if func is wraped by our deprecated decorator | [
"Helper",
"to",
"check",
"if",
"func",
"is",
"wraped",
"by",
"our",
"deprecated",
"decorator"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L361-L372 | train |
rflamary/POT | ot/utils.py | deprecated._decorate_fun | def _decorate_fun(self, fun):
"""Decorate function fun"""
msg = "Function %s is deprecated" % fun.__name__
if self.extra:
msg += "; %s" % self.extra
def wrapped(*args, **kwargs):
warnings.warn(msg, category=DeprecationWarning)
return fun(*args, **kwa... | python | def _decorate_fun(self, fun):
"""Decorate function fun"""
msg = "Function %s is deprecated" % fun.__name__
if self.extra:
msg += "; %s" % self.extra
def wrapped(*args, **kwargs):
warnings.warn(msg, category=DeprecationWarning)
return fun(*args, **kwa... | [
"def",
"_decorate_fun",
"(",
"self",
",",
"fun",
")",
":",
"msg",
"=",
"\"Function %s is deprecated\"",
"%",
"fun",
".",
"__name__",
"if",
"self",
".",
"extra",
":",
"msg",
"+=",
"\"; %s\"",
"%",
"self",
".",
"extra",
"def",
"wrapped",
"(",
"*",
"args",
... | Decorate function fun | [
"Decorate",
"function",
"fun"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L335-L350 | train |
rflamary/POT | ot/dr.py | split_classes | def split_classes(X, y):
"""split samples in X by classes in y
"""
lstsclass = np.unique(y)
return [X[y == i, :].astype(np.float32) for i in lstsclass] | python | def split_classes(X, y):
"""split samples in X by classes in y
"""
lstsclass = np.unique(y)
return [X[y == i, :].astype(np.float32) for i in lstsclass] | [
"def",
"split_classes",
"(",
"X",
",",
"y",
")",
":",
"lstsclass",
"=",
"np",
".",
"unique",
"(",
"y",
")",
"return",
"[",
"X",
"[",
"y",
"==",
"i",
",",
":",
"]",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"for",
"i",
"in",
"lstsclass",
... | split samples in X by classes in y | [
"split",
"samples",
"in",
"X",
"by",
"classes",
"in",
"y"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/dr.py#L38-L42 | train |
rflamary/POT | ot/dr.py | fda | def fda(X, y, p=2, reg=1e-16):
"""
Fisher Discriminant Analysis
Parameters
----------
X : numpy.ndarray (n,d)
Training samples
y : np.ndarray (n,)
labels for training samples
p : int, optional
size of dimensionnality reduction
reg : float, optional
Regul... | python | def fda(X, y, p=2, reg=1e-16):
"""
Fisher Discriminant Analysis
Parameters
----------
X : numpy.ndarray (n,d)
Training samples
y : np.ndarray (n,)
labels for training samples
p : int, optional
size of dimensionnality reduction
reg : float, optional
Regul... | [
"def",
"fda",
"(",
"X",
",",
"y",
",",
"p",
"=",
"2",
",",
"reg",
"=",
"1e-16",
")",
":",
"mx",
"=",
"np",
".",
"mean",
"(",
"X",
")",
"X",
"-=",
"mx",
".",
"reshape",
"(",
"(",
"1",
",",
"-",
"1",
")",
")",
"# data split between classes",
... | Fisher Discriminant Analysis
Parameters
----------
X : numpy.ndarray (n,d)
Training samples
y : np.ndarray (n,)
labels for training samples
p : int, optional
size of dimensionnality reduction
reg : float, optional
Regularization term >0 (ridge regularization)
... | [
"Fisher",
"Discriminant",
"Analysis"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/dr.py#L45-L107 | train |
rflamary/POT | ot/stochastic.py | sag_entropic_transport | def sag_entropic_transport(a, b, M, reg, numItermax=10000, lr=None):
'''
Compute the SAG algorithm to solve the regularized discrete measures
optimal transport max problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\... | python | def sag_entropic_transport(a, b, M, reg, numItermax=10000, lr=None):
'''
Compute the SAG algorithm to solve the regularized discrete measures
optimal transport max problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\... | [
"def",
"sag_entropic_transport",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"10000",
",",
"lr",
"=",
"None",
")",
":",
"if",
"lr",
"is",
"None",
":",
"lr",
"=",
"1.",
"/",
"max",
"(",
"a",
"/",
"reg",
")",
"n_source",
"="... | Compute the SAG algorithm to solve the regularized discrete measures
optimal transport max problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1 = b
... | [
"Compute",
"the",
"SAG",
"algorithm",
"to",
"solve",
"the",
"regularized",
"discrete",
"measures",
"optimal",
"transport",
"max",
"problem"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L86-L175 | train |
rflamary/POT | ot/stochastic.py | averaged_sgd_entropic_transport | def averaged_sgd_entropic_transport(a, b, M, reg, numItermax=300000, lr=None):
'''
Compute the ASGD algorithm to solve the regularized semi continous measures optimal transport max problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + ... | python | def averaged_sgd_entropic_transport(a, b, M, reg, numItermax=300000, lr=None):
'''
Compute the ASGD algorithm to solve the regularized semi continous measures optimal transport max problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + ... | [
"def",
"averaged_sgd_entropic_transport",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"300000",
",",
"lr",
"=",
"None",
")",
":",
"if",
"lr",
"is",
"None",
":",
"lr",
"=",
"1.",
"/",
"max",
"(",
"a",
"/",
"reg",
")",
"n_sour... | Compute the ASGD algorithm to solve the regularized semi continous measures optimal transport max problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
... | [
"Compute",
"the",
"ASGD",
"algorithm",
"to",
"solve",
"the",
"regularized",
"semi",
"continous",
"measures",
"optimal",
"transport",
"max",
"problem"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L178-L263 | train |
rflamary/POT | ot/stochastic.py | c_transform_entropic | def c_transform_entropic(b, M, reg, beta):
'''
The goal is to recover u from the c-transform.
The function computes the c_transform of a dual variable from the other
dual variable:
.. math::
u = v^{c,reg} = -reg \sum_j exp((v - M)/reg) b_j
Where :
- M is the (ns,nt) metric cost m... | python | def c_transform_entropic(b, M, reg, beta):
'''
The goal is to recover u from the c-transform.
The function computes the c_transform of a dual variable from the other
dual variable:
.. math::
u = v^{c,reg} = -reg \sum_j exp((v - M)/reg) b_j
Where :
- M is the (ns,nt) metric cost m... | [
"def",
"c_transform_entropic",
"(",
"b",
",",
"M",
",",
"reg",
",",
"beta",
")",
":",
"n_source",
"=",
"np",
".",
"shape",
"(",
"M",
")",
"[",
"0",
"]",
"alpha",
"=",
"np",
".",
"zeros",
"(",
"n_source",
")",
"for",
"i",
"in",
"range",
"(",
"n_... | The goal is to recover u from the c-transform.
The function computes the c_transform of a dual variable from the other
dual variable:
.. math::
u = v^{c,reg} = -reg \sum_j exp((v - M)/reg) b_j
Where :
- M is the (ns,nt) metric cost matrix
- u, v are dual variables in R^IxR^J
- re... | [
"The",
"goal",
"is",
"to",
"recover",
"u",
"from",
"the",
"c",
"-",
"transform",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L266-L338 | train |
rflamary/POT | ot/stochastic.py | solve_semi_dual_entropic | def solve_semi_dual_entropic(a, b, M, reg, method, numItermax=10000, lr=None,
log=False):
'''
Compute the transportation matrix to solve the regularized discrete
measures optimal transport max problem
The function solves the following optimization problem:
.. ma... | python | def solve_semi_dual_entropic(a, b, M, reg, method, numItermax=10000, lr=None,
log=False):
'''
Compute the transportation matrix to solve the regularized discrete
measures optimal transport max problem
The function solves the following optimization problem:
.. ma... | [
"def",
"solve_semi_dual_entropic",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"method",
",",
"numItermax",
"=",
"10000",
",",
"lr",
"=",
"None",
",",
"log",
"=",
"False",
")",
":",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"\"sag\"",
":",
... | Compute the transportation matrix to solve the regularized discrete
measures optimal transport max problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
... | [
"Compute",
"the",
"transportation",
"matrix",
"to",
"solve",
"the",
"regularized",
"discrete",
"measures",
"optimal",
"transport",
"max",
"problem"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L341-L444 | train |
rflamary/POT | ot/stochastic.py | batch_grad_dual | def batch_grad_dual(a, b, M, reg, alpha, beta, batch_size, batch_alpha,
batch_beta):
'''
Computes the partial gradient of the dual optimal transport problem.
For each (i,j) in a batch of coordinates, the partial gradients are :
.. math::
\partial_{u_i} F = u_i * b_s/l_{v} -... | python | def batch_grad_dual(a, b, M, reg, alpha, beta, batch_size, batch_alpha,
batch_beta):
'''
Computes the partial gradient of the dual optimal transport problem.
For each (i,j) in a batch of coordinates, the partial gradients are :
.. math::
\partial_{u_i} F = u_i * b_s/l_{v} -... | [
"def",
"batch_grad_dual",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"alpha",
",",
"beta",
",",
"batch_size",
",",
"batch_alpha",
",",
"batch_beta",
")",
":",
"G",
"=",
"-",
"(",
"np",
".",
"exp",
"(",
"(",
"alpha",
"[",
"batch_alpha",
",",
"... | Computes the partial gradient of the dual optimal transport problem.
For each (i,j) in a batch of coordinates, the partial gradients are :
.. math::
\partial_{u_i} F = u_i * b_s/l_{v} - \sum_{j \in B_v} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j
\partial_{v_j} F = v_j * b_s/l_{u} - \sum_{i \i... | [
"Computes",
"the",
"partial",
"gradient",
"of",
"the",
"dual",
"optimal",
"transport",
"problem",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L452-L547 | train |
rflamary/POT | ot/stochastic.py | sgd_entropic_regularization | def sgd_entropic_regularization(a, b, M, reg, batch_size, numItermax, lr):
'''
Compute the sgd algorithm to solve the regularized discrete measures
optimal transport dual problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + re... | python | def sgd_entropic_regularization(a, b, M, reg, batch_size, numItermax, lr):
'''
Compute the sgd algorithm to solve the regularized discrete measures
optimal transport dual problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + re... | [
"def",
"sgd_entropic_regularization",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"batch_size",
",",
"numItermax",
",",
"lr",
")",
":",
"n_source",
"=",
"np",
".",
"shape",
"(",
"M",
")",
"[",
"0",
"]",
"n_target",
"=",
"np",
".",
"shape",
"(",
... | Compute the sgd algorithm to solve the regularized discrete measures
optimal transport dual problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
... | [
"Compute",
"the",
"sgd",
"algorithm",
"to",
"solve",
"the",
"regularized",
"discrete",
"measures",
"optimal",
"transport",
"dual",
"problem"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L550-L642 | train |
rflamary/POT | ot/stochastic.py | solve_dual_entropic | def solve_dual_entropic(a, b, M, reg, batch_size, numItermax=10000, lr=1,
log=False):
'''
Compute the transportation matrix to solve the regularized discrete measures
optimal transport dual problem
The function solves the following optimization problem:
.. math::
... | python | def solve_dual_entropic(a, b, M, reg, batch_size, numItermax=10000, lr=1,
log=False):
'''
Compute the transportation matrix to solve the regularized discrete measures
optimal transport dual problem
The function solves the following optimization problem:
.. math::
... | [
"def",
"solve_dual_entropic",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"batch_size",
",",
"numItermax",
"=",
"10000",
",",
"lr",
"=",
"1",
",",
"log",
"=",
"False",
")",
":",
"opt_alpha",
",",
"opt_beta",
"=",
"sgd_entropic_regularization",
"(",
... | Compute the transportation matrix to solve the regularized discrete measures
optimal transport dual problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
... | [
"Compute",
"the",
"transportation",
"matrix",
"to",
"solve",
"the",
"regularized",
"discrete",
"measures",
"optimal",
"transport",
"dual",
"problem"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L645-L736 | train |
PyCQA/pyflakes | pyflakes/reporter.py | Reporter.flake | def flake(self, message):
"""
pyflakes found something wrong with the code.
@param: A L{pyflakes.messages.Message}.
"""
self._stdout.write(str(message))
self._stdout.write('\n') | python | def flake(self, message):
"""
pyflakes found something wrong with the code.
@param: A L{pyflakes.messages.Message}.
"""
self._stdout.write(str(message))
self._stdout.write('\n') | [
"def",
"flake",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"_stdout",
".",
"write",
"(",
"str",
"(",
"message",
")",
")",
"self",
".",
"_stdout",
".",
"write",
"(",
"'\\n'",
")"
] | pyflakes found something wrong with the code.
@param: A L{pyflakes.messages.Message}. | [
"pyflakes",
"found",
"something",
"wrong",
"with",
"the",
"code",
"."
] | 232cb1d27ee134bf96adc8f37e53589dc259b159 | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/reporter.py#L68-L75 | train |
PyCQA/pyflakes | pyflakes/checker.py | counter | def counter(items):
"""
Simplest required implementation of collections.Counter. Required as 2.6
does not have Counter in collections.
"""
results = {}
for item in items:
results[item] = results.get(item, 0) + 1
return results | python | def counter(items):
"""
Simplest required implementation of collections.Counter. Required as 2.6
does not have Counter in collections.
"""
results = {}
for item in items:
results[item] = results.get(item, 0) + 1
return results | [
"def",
"counter",
"(",
"items",
")",
":",
"results",
"=",
"{",
"}",
"for",
"item",
"in",
"items",
":",
"results",
"[",
"item",
"]",
"=",
"results",
".",
"get",
"(",
"item",
",",
"0",
")",
"+",
"1",
"return",
"results"
] | Simplest required implementation of collections.Counter. Required as 2.6
does not have Counter in collections. | [
"Simplest",
"required",
"implementation",
"of",
"collections",
".",
"Counter",
".",
"Required",
"as",
"2",
".",
"6",
"does",
"not",
"have",
"Counter",
"in",
"collections",
"."
] | 232cb1d27ee134bf96adc8f37e53589dc259b159 | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L103-L111 | train |
PyCQA/pyflakes | pyflakes/checker.py | Importation.source_statement | def source_statement(self):
"""Generate a source statement equivalent to the import."""
if self._has_alias():
return 'import %s as %s' % (self.fullName, self.name)
else:
return 'import %s' % self.fullName | python | def source_statement(self):
"""Generate a source statement equivalent to the import."""
if self._has_alias():
return 'import %s as %s' % (self.fullName, self.name)
else:
return 'import %s' % self.fullName | [
"def",
"source_statement",
"(",
"self",
")",
":",
"if",
"self",
".",
"_has_alias",
"(",
")",
":",
"return",
"'import %s as %s'",
"%",
"(",
"self",
".",
"fullName",
",",
"self",
".",
"name",
")",
"else",
":",
"return",
"'import %s'",
"%",
"self",
".",
"... | Generate a source statement equivalent to the import. | [
"Generate",
"a",
"source",
"statement",
"equivalent",
"to",
"the",
"import",
"."
] | 232cb1d27ee134bf96adc8f37e53589dc259b159 | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L265-L270 | train |
PyCQA/pyflakes | pyflakes/checker.py | Checker.CLASSDEF | def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
... | python | def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
... | [
"def",
"CLASSDEF",
"(",
"self",
",",
"node",
")",
":",
"for",
"deco",
"in",
"node",
".",
"decorator_list",
":",
"self",
".",
"handleNode",
"(",
"deco",
",",
"node",
")",
"for",
"baseNode",
"in",
"node",
".",
"bases",
":",
"self",
".",
"handleNode",
"... | Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope. | [
"Check",
"names",
"used",
"in",
"a",
"class",
"definition",
"including",
"its",
"decorators",
"base",
"classes",
"and",
"the",
"body",
"of",
"its",
"definition",
".",
"Additionally",
"add",
"its",
"name",
"to",
"the",
"current",
"scope",
"."
] | 232cb1d27ee134bf96adc8f37e53589dc259b159 | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L1519-L1542 | train |
PyCQA/pyflakes | pyflakes/api.py | isPythonFile | def isPythonFile(filename):
"""Return True if filename points to a Python file."""
if filename.endswith('.py'):
return True
# Avoid obvious Emacs backup files
if filename.endswith("~"):
return False
max_bytes = 128
try:
with open(filename, 'rb') as f:
text ... | python | def isPythonFile(filename):
"""Return True if filename points to a Python file."""
if filename.endswith('.py'):
return True
# Avoid obvious Emacs backup files
if filename.endswith("~"):
return False
max_bytes = 128
try:
with open(filename, 'rb') as f:
text ... | [
"def",
"isPythonFile",
"(",
"filename",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.py'",
")",
":",
"return",
"True",
"# Avoid obvious Emacs backup files",
"if",
"filename",
".",
"endswith",
"(",
"\"~\"",
")",
":",
"return",
"False",
"max_bytes",
"=",... | Return True if filename points to a Python file. | [
"Return",
"True",
"if",
"filename",
"points",
"to",
"a",
"Python",
"file",
"."
] | 232cb1d27ee134bf96adc8f37e53589dc259b159 | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/api.py#L102-L122 | train |
PyCQA/pyflakes | pyflakes/api.py | _exitOnSignal | def _exitOnSignal(sigName, message):
"""Handles a signal with sys.exit.
Some of these signals (SIGPIPE, for example) don't exist or are invalid on
Windows. So, ignore errors that might arise.
"""
import signal
try:
sigNumber = getattr(signal, sigName)
except AttributeError:
... | python | def _exitOnSignal(sigName, message):
"""Handles a signal with sys.exit.
Some of these signals (SIGPIPE, for example) don't exist or are invalid on
Windows. So, ignore errors that might arise.
"""
import signal
try:
sigNumber = getattr(signal, sigName)
except AttributeError:
... | [
"def",
"_exitOnSignal",
"(",
"sigName",
",",
"message",
")",
":",
"import",
"signal",
"try",
":",
"sigNumber",
"=",
"getattr",
"(",
"signal",
",",
"sigName",
")",
"except",
"AttributeError",
":",
"# the signal constants defined in the signal module are defined by",
"#... | Handles a signal with sys.exit.
Some of these signals (SIGPIPE, for example) don't exist or are invalid on
Windows. So, ignore errors that might arise. | [
"Handles",
"a",
"signal",
"with",
"sys",
".",
"exit",
"."
] | 232cb1d27ee134bf96adc8f37e53589dc259b159 | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/api.py#L160-L184 | train |
jazzband/django-model-utils | model_utils/managers.py | InheritanceQuerySetMixin._get_subclasses_recurse | def _get_subclasses_recurse(self, model, levels=None):
"""
Given a Model class, find all related objects, exploring children
recursively, returning a `list` of strings representing the
relations for select_related
"""
related_objects = [
f for f in model._meta... | python | def _get_subclasses_recurse(self, model, levels=None):
"""
Given a Model class, find all related objects, exploring children
recursively, returning a `list` of strings representing the
relations for select_related
"""
related_objects = [
f for f in model._meta... | [
"def",
"_get_subclasses_recurse",
"(",
"self",
",",
"model",
",",
"levels",
"=",
"None",
")",
":",
"related_objects",
"=",
"[",
"f",
"for",
"f",
"in",
"model",
".",
"_meta",
".",
"get_fields",
"(",
")",
"if",
"isinstance",
"(",
"f",
",",
"OneToOneRel",
... | Given a Model class, find all related objects, exploring children
recursively, returning a `list` of strings representing the
relations for select_related | [
"Given",
"a",
"Model",
"class",
"find",
"all",
"related",
"objects",
"exploring",
"children",
"recursively",
"returning",
"a",
"list",
"of",
"strings",
"representing",
"the",
"relations",
"for",
"select_related"
] | d557c4253312774a7c2f14bcd02675e9ac2ea05f | https://github.com/jazzband/django-model-utils/blob/d557c4253312774a7c2f14bcd02675e9ac2ea05f/model_utils/managers.py#L146-L174 | train |
jazzband/django-model-utils | model_utils/managers.py | InheritanceQuerySetMixin._get_ancestors_path | def _get_ancestors_path(self, model, levels=None):
"""
Serves as an opposite to _get_subclasses_recurse, instead walking from
the Model class up the Model's ancestry and constructing the desired
select_related string backwards.
"""
if not issubclass(model, self.model):
... | python | def _get_ancestors_path(self, model, levels=None):
"""
Serves as an opposite to _get_subclasses_recurse, instead walking from
the Model class up the Model's ancestry and constructing the desired
select_related string backwards.
"""
if not issubclass(model, self.model):
... | [
"def",
"_get_ancestors_path",
"(",
"self",
",",
"model",
",",
"levels",
"=",
"None",
")",
":",
"if",
"not",
"issubclass",
"(",
"model",
",",
"self",
".",
"model",
")",
":",
"raise",
"ValueError",
"(",
"\"%r is not a subclass of %r\"",
"%",
"(",
"model",
",... | Serves as an opposite to _get_subclasses_recurse, instead walking from
the Model class up the Model's ancestry and constructing the desired
select_related string backwards. | [
"Serves",
"as",
"an",
"opposite",
"to",
"_get_subclasses_recurse",
"instead",
"walking",
"from",
"the",
"Model",
"class",
"up",
"the",
"Model",
"s",
"ancestry",
"and",
"constructing",
"the",
"desired",
"select_related",
"string",
"backwards",
"."
] | d557c4253312774a7c2f14bcd02675e9ac2ea05f | https://github.com/jazzband/django-model-utils/blob/d557c4253312774a7c2f14bcd02675e9ac2ea05f/model_utils/managers.py#L176-L200 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.