repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 out waiting for the user to respond.
"""
with self._cond:
if self._prompt:
if timeout_s is None:
self._cond.wait(3600 * 24 * 365)
else:
self._cond.wait(timeout_s)
if self._response is None:
raise PromptUnansweredError
return self._response | 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 out waiting for the user to respond.
"""
with self._cond:
if self._prompt:
if timeout_s is None:
self._cond.wait(3600 * 24 * 365)
else:
self._cond.wait(timeout_s)
if self._response is None:
raise PromptUnansweredError
return self._response | [
"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 | 221,900 |
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.
Returns:
True if the prompt with the given ID was active, otherwise False.
"""
_LOG.debug('Responding to prompt (%s): "%s"', prompt_id, response)
with self._cond:
if not (self._prompt and self._prompt.id == prompt_id):
return False
self._response = response
self.last_response = (prompt_id, response)
self.remove_prompt()
self._cond.notifyAll()
return True | 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.
Returns:
True if the prompt with the given ID was active, otherwise False.
"""
_LOG.debug('Responding to prompt (%s): "%s"', prompt_id, response)
with self._cond:
if not (self._prompt and self._prompt.id == prompt_id):
return False
self._response = response
self.last_response = (prompt_id, response)
self.remove_prompt()
self._cond.notifyAll()
return True | [
"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 ID was active, otherwise False. | [
"Respond",
"to",
"the",
"prompt",
"with",
"the",
"given",
"ID",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L240-L261 | train | 221,901 |
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 | 221,902 |
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 invalid, this will raise, and _phase_execution_outcome
# will get set to the InvalidPhaseResultError in _thread_exception instead.
self._phase_execution_outcome = PhaseExecutionOutcome(phase_return) | 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 invalid, this will raise, and _phase_execution_outcome
# will get set to the InvalidPhaseResultError in _thread_exception instead.
self._phase_execution_outcome = PhaseExecutionOutcome(phase_return) | [
"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 | 221,903 |
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 it.
if isinstance(self._phase_execution_outcome, PhaseExecutionOutcome):
return self._phase_execution_outcome
# Check for timeout, indicated by None for
# PhaseExecutionOutcome.phase_result.
if self.is_alive():
self.kill()
return PhaseExecutionOutcome(None)
# Phase was killed.
return PhaseExecutionOutcome(threads.ThreadTerminationError()) | 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 it.
if isinstance(self._phase_execution_outcome, PhaseExecutionOutcome):
return self._phase_execution_outcome
# Check for timeout, indicated by None for
# PhaseExecutionOutcome.phase_result.
if self.is_alive():
self.kill()
return PhaseExecutionOutcome(None)
# Phase was killed.
return PhaseExecutionOutcome(threads.ThreadTerminationError()) | [
"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 | 221,904 |
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,
are REPEAT and handled internally. Returning REPEAT here means the phase
hit its limit for repetitions.
"""
repeat_count = 1
repeat_limit = phase.options.repeat_limit or sys.maxsize
while not self._stopping.is_set():
is_last_repeat = repeat_count >= repeat_limit
phase_execution_outcome = self._execute_phase_once(phase, is_last_repeat)
if phase_execution_outcome.is_repeat and not is_last_repeat:
repeat_count += 1
continue
return phase_execution_outcome
# We've been cancelled, so just 'timeout' the phase.
return PhaseExecutionOutcome(None) | 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,
are REPEAT and handled internally. Returning REPEAT here means the phase
hit its limit for repetitions.
"""
repeat_count = 1
repeat_limit = phase.options.repeat_limit or sys.maxsize
while not self._stopping.is_set():
is_last_repeat = repeat_count >= repeat_limit
phase_execution_outcome = self._execute_phase_once(phase, is_last_repeat)
if phase_execution_outcome.is_repeat and not is_last_repeat:
repeat_count += 1
continue
return phase_execution_outcome
# We've been cancelled, so just 'timeout' the phase.
return PhaseExecutionOutcome(None) | [
"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. Returning REPEAT here means the phase
hit its limit for repetitions. | [
"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 | 221,905 |
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 returning falsey.',
phase_desc.name)
return PhaseExecutionOutcome(openhtf.PhaseResult.SKIP)
override_result = None
with self.test_state.running_phase_context(phase_desc) as phase_state:
_LOG.debug('Executing phase %s', phase_desc.name)
with self._current_phase_thread_lock:
# Checking _stopping must be in the lock context, otherwise there is a
# race condition: this thread checks _stopping and then switches to
# another thread where stop() sets _stopping and checks
# _current_phase_thread (which would not be set yet). In that case, the
# new phase thread will be still be started.
if self._stopping.is_set():
# PhaseRecord will be written at this point, so ensure that it has a
# Killed result.
result = PhaseExecutionOutcome(threads.ThreadTerminationError())
phase_state.result = result
return result
phase_thread = PhaseExecutorThread(phase_desc, self.test_state)
phase_thread.start()
self._current_phase_thread = phase_thread
phase_state.result = phase_thread.join_or_die()
if phase_state.result.is_repeat and is_last_repeat:
_LOG.error('Phase returned REPEAT, exceeding repeat_limit.')
phase_state.hit_repeat_limit = True
override_result = PhaseExecutionOutcome(openhtf.PhaseResult.STOP)
self._current_phase_thread = None
# Refresh the result in case a validation for a partially set measurement
# raised an exception.
result = override_result or phase_state.result
_LOG.debug('Phase %s finished with result %s', phase_desc.name,
result.phase_result)
return result | 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 returning falsey.',
phase_desc.name)
return PhaseExecutionOutcome(openhtf.PhaseResult.SKIP)
override_result = None
with self.test_state.running_phase_context(phase_desc) as phase_state:
_LOG.debug('Executing phase %s', phase_desc.name)
with self._current_phase_thread_lock:
# Checking _stopping must be in the lock context, otherwise there is a
# race condition: this thread checks _stopping and then switches to
# another thread where stop() sets _stopping and checks
# _current_phase_thread (which would not be set yet). In that case, the
# new phase thread will be still be started.
if self._stopping.is_set():
# PhaseRecord will be written at this point, so ensure that it has a
# Killed result.
result = PhaseExecutionOutcome(threads.ThreadTerminationError())
phase_state.result = result
return result
phase_thread = PhaseExecutorThread(phase_desc, self.test_state)
phase_thread.start()
self._current_phase_thread = phase_thread
phase_state.result = phase_thread.join_or_die()
if phase_state.result.is_repeat and is_last_repeat:
_LOG.error('Phase returned REPEAT, exceeding repeat_limit.')
phase_state.hit_repeat_limit = True
override_result = PhaseExecutionOutcome(openhtf.PhaseResult.STOP)
self._current_phase_thread = None
# Refresh the result in case a validation for a partially set measurement
# raised an exception.
result = override_result or phase_state.result
_LOG.debug('Phase %s finished with result %s', phase_desc.name,
result.phase_result)
return result | [
"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 | 221,906 |
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._stopping.set()
with self._current_phase_thread_lock:
phase_thread = self._current_phase_thread
if not phase_thread:
return
if phase_thread.is_alive():
phase_thread.kill()
_LOG.debug('Waiting for cancelled phase to exit: %s', phase_thread)
timeout = timeouts.PolledTimeout.from_seconds(timeout_s)
while phase_thread.is_alive() and not timeout.has_expired():
time.sleep(0.1)
_LOG.debug('Cancelled phase %s exit',
"didn't" if phase_thread.is_alive() else 'did')
# Clear the currently running phase, whether it finished or timed out.
self.test_state.stop_running_phase() | 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._stopping.set()
with self._current_phase_thread_lock:
phase_thread = self._current_phase_thread
if not phase_thread:
return
if phase_thread.is_alive():
phase_thread.kill()
_LOG.debug('Waiting for cancelled phase to exit: %s', phase_thread)
timeout = timeouts.PolledTimeout.from_seconds(timeout_s)
while phase_thread.is_alive() and not timeout.has_expired():
time.sleep(0.1)
_LOG.debug('Cancelled phase %s exit',
"didn't" if phase_thread.is_alive() else 'did')
# Clear the currently running phase, whether it finished or timed out.
self.test_state.stop_running_phase() | [
"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 | 221,907 |
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_code_info())
else:
ret.append(
mutablerecords.CopyRecord(
phase, code_info=test_record.CodeInfo.for_function(phase.func)))
return ret | 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_code_info())
else:
ret.append(
mutablerecords.CopyRecord(
phase, code_info=test_record.CodeInfo.for_function(phase.func)))
return ret | [
"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 | 221,908 |
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.flatten())
elif isinstance(phase, collections.Iterable):
ret.extend(flatten_phases_and_groups(phase))
else:
ret.append(phase_descriptor.PhaseDescriptor.wrap_or_copy(phase))
return ret | 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.flatten())
elif isinstance(phase, collections.Iterable):
ret.extend(flatten_phases_and_groups(phase))
else:
ret.append(phase_descriptor.PhaseDescriptor.wrap_or_copy(phase))
return ret | [
"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 | 221,909 |
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 apply
with_args to.
**kwargs: arguments to apply to the phase.
Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
args.
"""
if isinstance(phase, PhaseGroup):
return phase.with_args(**kwargs)
if isinstance(phase, collections.Iterable):
return [optionally_with_args(p, **kwargs) for p in phase]
if not isinstance(phase, phase_descriptor.PhaseDescriptor):
phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase)
return phase.with_known_args(**kwargs) | 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 apply
with_args to.
**kwargs: arguments to apply to the phase.
Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
args.
"""
if isinstance(phase, PhaseGroup):
return phase.with_args(**kwargs)
if isinstance(phase, collections.Iterable):
return [optionally_with_args(p, **kwargs) for p in phase]
if not isinstance(phase, phase_descriptor.PhaseDescriptor):
phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase)
return phase.with_known_args(**kwargs) | [
"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: arguments to apply to the phase.
Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
args. | [
"Apply",
"only",
"the",
"args",
"that",
"the",
"phase",
"knows",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L222-L244 | train | 221,910 |
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 group (or iterable) to apply the
plug changes to.
**subplugs: mapping from plug name to derived plug class, the subplugs to
apply.
Raises:
openhtf.plugs.InvalidPlugError: if a specified subplug class is not a valid
replacement for the specified plug name.
Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
plugs.
"""
if isinstance(phase, PhaseGroup):
return phase.with_plugs(**subplugs)
if isinstance(phase, collections.Iterable):
return [optionally_with_plugs(p, **subplugs) for p in phase]
if not isinstance(phase, phase_descriptor.PhaseDescriptor):
phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase)
return phase.with_known_plugs(**subplugs) | 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 group (or iterable) to apply the
plug changes to.
**subplugs: mapping from plug name to derived plug class, the subplugs to
apply.
Raises:
openhtf.plugs.InvalidPlugError: if a specified subplug class is not a valid
replacement for the specified plug name.
Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
plugs.
"""
if isinstance(phase, PhaseGroup):
return phase.with_plugs(**subplugs)
if isinstance(phase, collections.Iterable):
return [optionally_with_plugs(p, **subplugs) for p in phase]
if not isinstance(phase, phase_descriptor.PhaseDescriptor):
phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase)
return phase.with_known_plugs(**subplugs) | [
"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 changes to.
**subplugs: mapping from plug name to derived plug class, the subplugs to
apply.
Raises:
openhtf.plugs.InvalidPlugError: if a specified subplug class is not a valid
replacement for the specified plug name.
Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
plugs. | [
"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 | 221,911 |
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 | 221,912 |
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 the created function.
teardown_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/
callables/iterables, phases to run during the teardown for the
PhaseGroup returned from the created function.
Returns:
Function that takes *phases and returns a PhaseGroup with the predefined
setup and teardown phases, with *phases as the main phases.
"""
setup = flatten_phases_and_groups(setup_phases)
teardown = flatten_phases_and_groups(teardown_phases)
def _context_wrapper(*phases):
return cls(setup=setup,
main=flatten_phases_and_groups(phases),
teardown=teardown)
return _context_wrapper | 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 the created function.
teardown_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/
callables/iterables, phases to run during the teardown for the
PhaseGroup returned from the created function.
Returns:
Function that takes *phases and returns a PhaseGroup with the predefined
setup and teardown phases, with *phases as the main phases.
"""
setup = flatten_phases_and_groups(setup_phases)
teardown = flatten_phases_and_groups(teardown_phases)
def _context_wrapper(*phases):
return cls(setup=setup,
main=flatten_phases_and_groups(phases),
teardown=teardown)
return _context_wrapper | [
"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_descriptor.PhaseDescriptors/PhaseGroups/
callables/iterables, phases to run during the teardown for the
PhaseGroup returned from the created function.
Returns:
Function that takes *phases and returns a PhaseGroup with the predefined
setup and teardown phases, with *phases as the main phases. | [
"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 | 221,913 |
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 | 221,914 |
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,
main=new_main,
teardown=self.teardown,
name=name) | 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,
main=new_main,
teardown=self.teardown,
name=name) | [
"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 | 221,915 |
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 | 221,916 |
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 | 221,917 |
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 sent to them.
"""
with cls._lock:
for client in cls.subscribers:
if (not client_filter) or client_filter(client):
client.send(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 sent to them.
"""
with cls._lock:
for client in cls.subscribers:
if (not client_filter) or client_filter(client):
client.send(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 | 221,918 |
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 | 221,919 |
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 | 221,920 |
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: Options to update on the result.
Raises:
PhaseWrapError: if func is a openhtf.PhaseGroup.
Returns:
A new PhaseDescriptor object.
"""
if isinstance(func, openhtf.PhaseGroup):
raise PhaseWrapError('Cannot wrap PhaseGroup <%s> as a phase.' % (
func.name or 'Unnamed'))
if isinstance(func, cls):
# We want to copy so that a phase can be reused with different options
# or kwargs. See with_args() below for more details.
retval = mutablerecords.CopyRecord(func)
else:
retval = cls(func)
retval.options.update(**options)
return retval | 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: Options to update on the result.
Raises:
PhaseWrapError: if func is a openhtf.PhaseGroup.
Returns:
A new PhaseDescriptor object.
"""
if isinstance(func, openhtf.PhaseGroup):
raise PhaseWrapError('Cannot wrap PhaseGroup <%s> as a phase.' % (
func.name or 'Unnamed'))
if isinstance(func, cls):
# We want to copy so that a phase can be reused with different options
# or kwargs. See with_args() below for more details.
retval = mutablerecords.CopyRecord(func)
else:
retval = cls(func)
retval.options.update(**options)
return retval | [
"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:
PhaseWrapError: if func is a openhtf.PhaseGroup.
Returns:
A new PhaseDescriptor object. | [
"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 | 221,921 |
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.with_args(**stored)
return self | 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.with_args(**stored)
return self | [
"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 | 221,922 |
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_info.extra_kwargs.update(kwargs)
new_info.measurements = [m.with_args(**kwargs) for m in self.measurements]
return new_info | 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_info.extra_kwargs.update(kwargs)
new_info.measurements = [m.with_args(**kwargs) for m in self.measurements]
return new_info | [
"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 | 221,923 |
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:
openhtf.plugs.InvalidPlugError if for one of the plug names one of the
following is true:
- error_on_unknown is True and the plug name is not registered.
- The new plug subclass is not a subclass of the original.
- The original plug class is not a placeholder or automatic placeholder.
Returns:
PhaseDescriptor with updated plugs.
"""
plugs_by_name = {plug.name: plug for plug in self.plugs}
new_plugs = dict(plugs_by_name)
for name, sub_class in six.iteritems(subplugs):
original_plug = plugs_by_name.get(name)
accept_substitute = True
if original_plug is None:
if not error_on_unknown:
continue
accept_substitute = False
elif isinstance(original_plug.cls, openhtf.plugs.PlugPlaceholder):
accept_substitute = issubclass(sub_class, original_plug.cls.base_class)
else:
# Check __dict__ to see if the attribute is explicitly defined in the
# class, rather than being defined in a parent class.
accept_substitute = ('auto_placeholder' in original_plug.cls.__dict__
and original_plug.cls.auto_placeholder
and issubclass(sub_class, original_plug.cls))
if not accept_substitute:
raise openhtf.plugs.InvalidPlugError(
'Could not find valid placeholder for substitute plug %s '
'required for phase %s' % (name, self.name))
new_plugs[name] = mutablerecords.CopyRecord(original_plug, cls=sub_class)
return mutablerecords.CopyRecord(
self,
plugs=list(new_plugs.values()),
options=self.options.format_strings(**subplugs),
measurements=[m.with_args(**subplugs) for m in self.measurements]) | 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:
openhtf.plugs.InvalidPlugError if for one of the plug names one of the
following is true:
- error_on_unknown is True and the plug name is not registered.
- The new plug subclass is not a subclass of the original.
- The original plug class is not a placeholder or automatic placeholder.
Returns:
PhaseDescriptor with updated plugs.
"""
plugs_by_name = {plug.name: plug for plug in self.plugs}
new_plugs = dict(plugs_by_name)
for name, sub_class in six.iteritems(subplugs):
original_plug = plugs_by_name.get(name)
accept_substitute = True
if original_plug is None:
if not error_on_unknown:
continue
accept_substitute = False
elif isinstance(original_plug.cls, openhtf.plugs.PlugPlaceholder):
accept_substitute = issubclass(sub_class, original_plug.cls.base_class)
else:
# Check __dict__ to see if the attribute is explicitly defined in the
# class, rather than being defined in a parent class.
accept_substitute = ('auto_placeholder' in original_plug.cls.__dict__
and original_plug.cls.auto_placeholder
and issubclass(sub_class, original_plug.cls))
if not accept_substitute:
raise openhtf.plugs.InvalidPlugError(
'Could not find valid placeholder for substitute plug %s '
'required for phase %s' % (name, self.name))
new_plugs[name] = mutablerecords.CopyRecord(original_plug, cls=sub_class)
return mutablerecords.CopyRecord(
self,
plugs=list(new_plugs.values()),
options=self.options.format_strings(**subplugs),
measurements=[m.with_args(**subplugs) for m in self.measurements]) | [
"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 the
following is true:
- error_on_unknown is True and the plug name is not registered.
- The new plug subclass is not a subclass of the original.
- The original plug class is not a placeholder or automatic placeholder.
Returns:
PhaseDescriptor with updated plugs. | [
"Substitute",
"plugs",
"for",
"placeholders",
"for",
"this",
"phase",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L208-L255 | train | 221,924 |
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: A class method on a subclass of UsbHandle
Raises:
HandleClosedError: If this handle has been closed.
Returns:
A wrapper around method that ensures the handle is open before calling through
to the wrapped method.
"""
@functools.wraps(method)
def wrapper_requiring_open_handle(self, *args, **kwargs):
"""The wrapper to be returned."""
if self.is_closed():
raise usb_exceptions.HandleClosedError()
return method(self, *args, **kwargs)
return wrapper_requiring_open_handle | 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: A class method on a subclass of UsbHandle
Raises:
HandleClosedError: If this handle has been closed.
Returns:
A wrapper around method that ensures the handle is open before calling through
to the wrapped method.
"""
@functools.wraps(method)
def wrapper_requiring_open_handle(self, *args, **kwargs):
"""The wrapper to be returned."""
if self.is_closed():
raise usb_exceptions.HandleClosedError()
return method(self, *args, **kwargs)
return wrapper_requiring_open_handle | [
"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:
HandleClosedError: If this handle has been closed.
Returns:
A wrapper around method that ensures the handle is open before calling through
to the wrapped method. | [
"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 | 221,925 |
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 | 221,926 |
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), binascii.hexlify(data),
self._dotify(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), binascii.hexlify(data),
self._dotify(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 | 221,927 |
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 | 221,928 |
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])
info = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
serial = None
if "SERIAL" in info:
serial_info = info.split('SERIAL:')[1]
serial = serial_info.split('\n')[0].strip()
use_info = info.split('BY')[1].split(' ')[1]
if use_info == 'NO':
cmd = (['esuit64', '-t', 'AUTO USE ALL'])
subprocess.check_output(cmd, stderr=subprocess.STDOUT)
time.sleep(50.0/1000.0)
else:
raise ValueError('No USB device detected')
return serial | 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])
info = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
serial = None
if "SERIAL" in info:
serial_info = info.split('SERIAL:')[1]
serial = serial_info.split('\n')[0].strip()
use_info = info.split('BY')[1].split(' ')[1]
if use_info == 'NO':
cmd = (['esuit64', '-t', 'AUTO USE ALL'])
subprocess.check_output(cmd, stderr=subprocess.STDOUT)
time.sleep(50.0/1000.0)
else:
raise ValueError('No USB device detected')
return serial | [
"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 | 221,929 |
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 | 221,930 |
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 | 221,931 |
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. You can
concatenate colorama color strings together in order to get any set of
effects you want.
width: Total width for the resulting banner.
file: A file object to which the banner text will be written. Intended for
use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging.
Example:
>>> banner_print('Foo Bar Baz')
======================== Foo Bar Baz =======================
"""
if logger:
logger.debug(ANSI_ESC_RE.sub('', msg))
if CLI_QUIET:
return
lpad = int(math.ceil((width - _printed_len(msg) - 2) / 2.0)) * '='
rpad = int(math.floor((width - _printed_len(msg) - 2) / 2.0)) * '='
file.write('{sep}{color}{lpad} {msg} {rpad}{reset}{sep}{sep}'.format(
sep=_linesep_for_file(file), color=color, lpad=lpad, msg=msg, rpad=rpad,
reset=colorama.Style.RESET_ALL))
file.flush() | 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. You can
concatenate colorama color strings together in order to get any set of
effects you want.
width: Total width for the resulting banner.
file: A file object to which the banner text will be written. Intended for
use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging.
Example:
>>> banner_print('Foo Bar Baz')
======================== Foo Bar Baz =======================
"""
if logger:
logger.debug(ANSI_ESC_RE.sub('', msg))
if CLI_QUIET:
return
lpad = int(math.ceil((width - _printed_len(msg) - 2) / 2.0)) * '='
rpad = int(math.floor((width - _printed_len(msg) - 2) / 2.0)) * '='
file.write('{sep}{color}{lpad} {msg} {rpad}{reset}{sep}{sep}'.format(
sep=_linesep_for_file(file), color=color, lpad=lpad, msg=msg, rpad=rpad,
reset=colorama.Style.RESET_ALL))
file.flush() | [
"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 set of
effects you want.
width: Total width for the resulting banner.
file: A file object to which the banner text will be written. Intended for
use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging.
Example:
>>> banner_print('Foo Bar Baz')
======================== Foo Bar Baz ======================= | [
"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 | 221,932 |
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 colorama color strings together in order to get any set of
effects you want.
width: Total desired width of the bracketed message.
file: A file object to which the bracketed text will be written. Intended
for use with CLI output file objects like sys.stdout.
"""
if CLI_QUIET:
return
lpad = int(math.ceil((width - 2 - _printed_len(msg)) / 2.0)) * ' '
rpad = int(math.floor((width - 2 - _printed_len(msg)) / 2.0)) * ' '
file.write('[{lpad}{bright}{color}{msg}{reset}{rpad}]'.format(
lpad=lpad, bright=colorama.Style.BRIGHT, color=color, msg=msg,
reset=colorama.Style.RESET_ALL, rpad=rpad))
file.write(colorama.Style.RESET_ALL)
file.write(_linesep_for_file(file))
file.flush() | 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 colorama color strings together in order to get any set of
effects you want.
width: Total desired width of the bracketed message.
file: A file object to which the bracketed text will be written. Intended
for use with CLI output file objects like sys.stdout.
"""
if CLI_QUIET:
return
lpad = int(math.ceil((width - 2 - _printed_len(msg)) / 2.0)) * ' '
rpad = int(math.floor((width - 2 - _printed_len(msg)) / 2.0)) * ' '
file.write('[{lpad}{bright}{color}{msg}{reset}{rpad}]'.format(
lpad=lpad, bright=colorama.Style.BRIGHT, color=color, msg=msg,
reset=colorama.Style.RESET_ALL, rpad=rpad))
file.write(colorama.Style.RESET_ALL)
file.write(_linesep_for_file(file))
file.flush() | [
"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
effects you want.
width: Total desired width of the bracketed message.
file: A file object to which the bracketed text will be written. Intended
for use with CLI output file objects like sys.stdout. | [
"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 | 221,933 |
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 test record for later inspection.
Args:
msg: The message to print/log.
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
effects you want.
end: A custom line-ending string to print instead of newline.
file: A file object to which the baracketed text will be written. Intended
for use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging.
"""
if logger:
logger.debug('-> {}'.format(msg))
if CLI_QUIET:
return
if end is None:
end = _linesep_for_file(file)
file.write('{color}{msg}{reset}{end}'.format(
color=color, msg=msg, reset=colorama.Style.RESET_ALL, end=end)) | 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 test record for later inspection.
Args:
msg: The message to print/log.
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
effects you want.
end: A custom line-ending string to print instead of newline.
file: A file object to which the baracketed text will be written. Intended
for use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging.
"""
if logger:
logger.debug('-> {}'.format(msg))
if CLI_QUIET:
return
if end is None:
end = _linesep_for_file(file)
file.write('{color}{msg}{reset}{end}'.format(
color=color, msg=msg, reset=colorama.Style.RESET_ALL, end=end)) | [
"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.
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
effects you want.
end: A custom line-ending string to print instead of newline.
file: A file object to which the baracketed text will be written. Intended
for use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging. | [
"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 | 221,934 |
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, but note that style
strings will not be applied.
file: A file object to which the baracketed text will be written. Intended
for use with CLI output file objects, specifically sys.stderr.
"""
if CLI_QUIET:
return
file.write('{sep}{bright}{color}Error: {normal}{msg}{sep}{reset}'.format(
sep=_linesep_for_file(file), bright=colorama.Style.BRIGHT, color=color,
normal=colorama.Style.NORMAL, msg=msg, reset=colorama.Style.RESET_ALL))
file.flush() | 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, but note that style
strings will not be applied.
file: A file object to which the baracketed text will be written. Intended
for use with CLI output file objects, specifically sys.stderr.
"""
if CLI_QUIET:
return
file.write('{sep}{bright}{color}Error: {normal}{msg}{sep}{reset}'.format(
sep=_linesep_for_file(file), bright=colorama.Style.BRIGHT, color=color,
normal=colorama.Style.NORMAL, msg=msg, reset=colorama.Style.RESET_ALL))
file.flush() | [
"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 file object to which the baracketed text will be written. Intended
for use with CLI output file objects, specifically sys.stderr. | [
"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 | 221,935 |
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,
logger=_LOG):
"""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 result in the action being marked fail. If the result is
left unset, then indicative text ("????") will be printed as the result.
Args:
action_text: Text to be displayed that describes the action being taken.
width: Total width for each line of output.
status_width: Width of the just the status message portion of each line.
succeed_text: Status message displayed when the action succeeds.
fail_text: Status message displayed when the action fails.
unknown_text: Status message displayed when the result is left unset.
file: Specific file object to write to write CLI output to.
logger: A logger to use, or None to disable logging.
Example usage:
with action_result_context('Doing an action that will succeed...') as act:
time.sleep(2)
act.succeed()
with action_result_context('Doing an action with unset result...') as act:
time.sleep(2)
with action_result_context('Doing an action that will fail...') as act:
time.sleep(2)
act.fail()
with action_result_context('Doing an action that will raise...') as act:
time.sleep(2)
import textwrap
raise RuntimeError(textwrap.dedent('''\
Uh oh, looks like there was a raise in the mix.
If you see this message, it means you are running the console_output
module directly rather than using it as a library. Things to try:
* Not running it as a module.
* Running it as a module and enjoying the preview text.
* Getting another coffee.'''))
Example output:
Doing an action that will succeed... [ OK ]
Doing an action with unset result... [ ???? ]
Doing an action that will fail... [ FAIL ]
Doing an action that will raise... [ FAIL ]
...
"""
if logger:
logger.debug('Action - %s', action_text)
if not CLI_QUIET:
file.write(''.join((action_text, '\r')))
file.flush()
spacing = (width - status_width - _printed_len(action_text)) * ' '
result = ActionResult()
try:
yield result
except Exception as err:
if logger:
logger.debug('Result - %s [ %s ]', action_text, fail_text)
if not CLI_QUIET:
file.write(''.join((action_text, spacing)))
bracket_print(fail_text, width=status_width, color=colorama.Fore.RED,
file=file)
if not isinstance(err, ActionFailedError):
raise
return
result_text = succeed_text if result.success else unknown_text
result_color = colorama.Fore.GREEN if result.success else colorama.Fore.YELLOW
if logger:
logger.debug('Result - %s [ %s ]', action_text, result_text)
if not CLI_QUIET:
file.write(''.join((action_text, spacing)))
bracket_print(result_text, width=status_width, color=result_color,
file=file) | python | def action_result_context(action_text,
width=60,
status_width=8,
succeed_text='OK',
fail_text='FAIL',
unknown_text='????',
file=sys.stdout,
logger=_LOG):
"""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 result in the action being marked fail. If the result is
left unset, then indicative text ("????") will be printed as the result.
Args:
action_text: Text to be displayed that describes the action being taken.
width: Total width for each line of output.
status_width: Width of the just the status message portion of each line.
succeed_text: Status message displayed when the action succeeds.
fail_text: Status message displayed when the action fails.
unknown_text: Status message displayed when the result is left unset.
file: Specific file object to write to write CLI output to.
logger: A logger to use, or None to disable logging.
Example usage:
with action_result_context('Doing an action that will succeed...') as act:
time.sleep(2)
act.succeed()
with action_result_context('Doing an action with unset result...') as act:
time.sleep(2)
with action_result_context('Doing an action that will fail...') as act:
time.sleep(2)
act.fail()
with action_result_context('Doing an action that will raise...') as act:
time.sleep(2)
import textwrap
raise RuntimeError(textwrap.dedent('''\
Uh oh, looks like there was a raise in the mix.
If you see this message, it means you are running the console_output
module directly rather than using it as a library. Things to try:
* Not running it as a module.
* Running it as a module and enjoying the preview text.
* Getting another coffee.'''))
Example output:
Doing an action that will succeed... [ OK ]
Doing an action with unset result... [ ???? ]
Doing an action that will fail... [ FAIL ]
Doing an action that will raise... [ FAIL ]
...
"""
if logger:
logger.debug('Action - %s', action_text)
if not CLI_QUIET:
file.write(''.join((action_text, '\r')))
file.flush()
spacing = (width - status_width - _printed_len(action_text)) * ' '
result = ActionResult()
try:
yield result
except Exception as err:
if logger:
logger.debug('Result - %s [ %s ]', action_text, fail_text)
if not CLI_QUIET:
file.write(''.join((action_text, spacing)))
bracket_print(fail_text, width=status_width, color=colorama.Fore.RED,
file=file)
if not isinstance(err, ActionFailedError):
raise
return
result_text = succeed_text if result.success else unknown_text
result_color = colorama.Fore.GREEN if result.success else colorama.Fore.YELLOW
if logger:
logger.debug('Result - %s [ %s ]', action_text, result_text)
if not CLI_QUIET:
file.write(''.join((action_text, spacing)))
bracket_print(result_text, width=status_width, color=result_color,
file=file) | [
"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 result in the action being marked fail. If the result is
left unset, then indicative text ("????") will be printed as the result.
Args:
action_text: Text to be displayed that describes the action being taken.
width: Total width for each line of output.
status_width: Width of the just the status message portion of each line.
succeed_text: Status message displayed when the action succeeds.
fail_text: Status message displayed when the action fails.
unknown_text: Status message displayed when the result is left unset.
file: Specific file object to write to write CLI output to.
logger: A logger to use, or None to disable logging.
Example usage:
with action_result_context('Doing an action that will succeed...') as act:
time.sleep(2)
act.succeed()
with action_result_context('Doing an action with unset result...') as act:
time.sleep(2)
with action_result_context('Doing an action that will fail...') as act:
time.sleep(2)
act.fail()
with action_result_context('Doing an action that will raise...') as act:
time.sleep(2)
import textwrap
raise RuntimeError(textwrap.dedent('''\
Uh oh, looks like there was a raise in the mix.
If you see this message, it means you are running the console_output
module directly rather than using it as a library. Things to try:
* Not running it as a module.
* Running it as a module and enjoying the preview text.
* Getting another coffee.'''))
Example output:
Doing an action that will succeed... [ OK ]
Doing an action with unset result... [ ???? ]
Doing an action that will fail... [ FAIL ]
Doing an action that will raise... [ FAIL ]
... | [
"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 | 221,936 |
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 in the library implementation that is being abstracted. The
advantage of this helper function is somewhat preserve traceback information
although it is polluted by the reraise frame.
Example Code:
def A():
raise Exception('Whoops')
def main():
try:
A()
except Exception as e:
exceptions.reraise(ValueError)
main()
Traceback (most recent call last):
File "exception.py", line 53, in <module>
main()
File "exception.py", line 49, in main
reraise(ValueError)
File "exception.py", line 47, in main
A()
File "exception.py", line 42, in A
raise Exception('Whoops')
ValueError: line 49
When this code is run, the additional stack frames for calling A() and raising
within A() are printed out in exception, whereas a bare exception translation
would lose this information. As long as you ignore the reraise stack frame,
the stack trace is okay looking.
Generally this can be fixed by hacking on CPython to allow modification of
traceback objects ala
https://github.com/mitsuhiko/jinja2/blob/master/jinja2/debug.py, but this is
fixed in Python 3 anyways and that method is the definition of hackery.
Args:
exc_type: (Exception) Exception class to create.
message: (str) Optional message to place in exception instance. Usually not
needed as the original exception probably has a message that will be
printed out in the modified stacktrace.
*args: Args to pass to exception constructor.
**kwargs: Kwargs to pass to exception constructor.
"""
last_lineno = inspect.currentframe().f_back.f_lineno
line_msg = 'line %s: ' % last_lineno
if message:
line_msg += str(message)
raise exc_type(line_msg, *args, **kwargs).raise_with_traceback(sys.exc_info()[2]) | 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 in the library implementation that is being abstracted. The
advantage of this helper function is somewhat preserve traceback information
although it is polluted by the reraise frame.
Example Code:
def A():
raise Exception('Whoops')
def main():
try:
A()
except Exception as e:
exceptions.reraise(ValueError)
main()
Traceback (most recent call last):
File "exception.py", line 53, in <module>
main()
File "exception.py", line 49, in main
reraise(ValueError)
File "exception.py", line 47, in main
A()
File "exception.py", line 42, in A
raise Exception('Whoops')
ValueError: line 49
When this code is run, the additional stack frames for calling A() and raising
within A() are printed out in exception, whereas a bare exception translation
would lose this information. As long as you ignore the reraise stack frame,
the stack trace is okay looking.
Generally this can be fixed by hacking on CPython to allow modification of
traceback objects ala
https://github.com/mitsuhiko/jinja2/blob/master/jinja2/debug.py, but this is
fixed in Python 3 anyways and that method is the definition of hackery.
Args:
exc_type: (Exception) Exception class to create.
message: (str) Optional message to place in exception instance. Usually not
needed as the original exception probably has a message that will be
printed out in the modified stacktrace.
*args: Args to pass to exception constructor.
**kwargs: Kwargs to pass to exception constructor.
"""
last_lineno = inspect.currentframe().f_back.f_lineno
line_msg = 'line %s: ' % last_lineno
if message:
line_msg += str(message)
raise exc_type(line_msg, *args, **kwargs).raise_with_traceback(sys.exc_info()[2]) | [
"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 function is somewhat preserve traceback information
although it is polluted by the reraise frame.
Example Code:
def A():
raise Exception('Whoops')
def main():
try:
A()
except Exception as e:
exceptions.reraise(ValueError)
main()
Traceback (most recent call last):
File "exception.py", line 53, in <module>
main()
File "exception.py", line 49, in main
reraise(ValueError)
File "exception.py", line 47, in main
A()
File "exception.py", line 42, in A
raise Exception('Whoops')
ValueError: line 49
When this code is run, the additional stack frames for calling A() and raising
within A() are printed out in exception, whereas a bare exception translation
would lose this information. As long as you ignore the reraise stack frame,
the stack trace is okay looking.
Generally this can be fixed by hacking on CPython to allow modification of
traceback objects ala
https://github.com/mitsuhiko/jinja2/blob/master/jinja2/debug.py, but this is
fixed in Python 3 anyways and that method is the definition of hackery.
Args:
exc_type: (Exception) Exception class to create.
message: (str) Optional message to place in exception instance. Usually not
needed as the original exception probably has a message that will be
printed out in the modified stacktrace.
*args: Args to pass to exception constructor.
**kwargs: Kwargs to pass to exception constructor. | [
"reraises",
"an",
"exception",
"for",
"exception",
"translation",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/exceptions.py#L22-L74 | train | 221,937 |
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 distribution
b : np.array, shape (nb,)
Target distribution
M : np.array, shape (na,nb)
Matrix to plot
"""
na, nb = M.shape
gs = gridspec.GridSpec(3, 3)
xa = np.arange(na)
xb = np.arange(nb)
ax1 = pl.subplot(gs[0, 1:])
pl.plot(xb, b, 'r', label='Target distribution')
pl.yticks(())
pl.title(title)
ax2 = pl.subplot(gs[1:, 0])
pl.plot(a, xa, 'b', label='Source distribution')
pl.gca().invert_xaxis()
pl.gca().invert_yaxis()
pl.xticks(())
pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2)
pl.imshow(M, interpolation='nearest')
pl.axis('off')
pl.xlim((0, nb))
pl.tight_layout()
pl.subplots_adjust(wspace=0., hspace=0.2) | 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 distribution
b : np.array, shape (nb,)
Target distribution
M : np.array, shape (na,nb)
Matrix to plot
"""
na, nb = M.shape
gs = gridspec.GridSpec(3, 3)
xa = np.arange(na)
xb = np.arange(nb)
ax1 = pl.subplot(gs[0, 1:])
pl.plot(xb, b, 'r', label='Target distribution')
pl.yticks(())
pl.title(title)
ax2 = pl.subplot(gs[1:, 0])
pl.plot(a, xa, 'b', label='Source distribution')
pl.gca().invert_xaxis()
pl.gca().invert_yaxis()
pl.xticks(())
pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2)
pl.imshow(M, interpolation='nearest')
pl.axis('off')
pl.xlim((0, nb))
pl.tight_layout()
pl.subplots_adjust(wspace=0., hspace=0.2) | [
"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,)
Target distribution
M : np.array, shape (na,nb)
Matrix to plot | [
"Plot",
"matrix",
"M",
"with",
"the",
"source",
"and",
"target",
"1D",
"distribution"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/plot.py#L14-L54 | train | 221,938 |
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)
Source samples positions
b : ndarray, shape (nt,2)
Target samples positions
G : ndarray, shape (na,nb)
OT matrix
thr : float, optional
threshold above which the line is drawn
**kwargs : dict
paameters given to the plot functions (default color is black if
nothing given)
"""
if ('color' not in kwargs) and ('c' not in kwargs):
kwargs['color'] = 'k'
mx = G.max()
for i in range(xs.shape[0]):
for j in range(xt.shape[0]):
if G[i, j] / mx > thr:
pl.plot([xs[i, 0], xt[j, 0]], [xs[i, 1], xt[j, 1]],
alpha=G[i, j] / mx, **kwargs) | 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)
Source samples positions
b : ndarray, shape (nt,2)
Target samples positions
G : ndarray, shape (na,nb)
OT matrix
thr : float, optional
threshold above which the line is drawn
**kwargs : dict
paameters given to the plot functions (default color is black if
nothing given)
"""
if ('color' not in kwargs) and ('c' not in kwargs):
kwargs['color'] = 'k'
mx = G.max()
for i in range(xs.shape[0]):
for j in range(xt.shape[0]):
if G[i, j] / mx > thr:
pl.plot([xs[i, 0], xt[j, 0]], [xs[i, 1], xt[j, 1]],
alpha=G[i, j] / mx, **kwargs) | [
"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)
Target samples positions
G : ndarray, shape (na,nb)
OT matrix
thr : float, optional
threshold above which the line is drawn
**kwargs : dict
paameters given to the plot functions (default color is black if
nothing given) | [
"Plot",
"matrix",
"M",
"in",
"2D",
"with",
"lines",
"using",
"alpha",
"values"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/plot.py#L57-L85 | train | 221,939 |
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
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::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)
+ \eta \Omega_g(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega_e` is the entropic regularization term
:math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`\Omega_g` is the group lasso regulaization term
:math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1`
where :math:`\mathcal{I}_c` are the index of samples from class c
in the source domain.
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalised conditional
gradient as proposed in [5]_ [7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
labels_a : np.ndarray (ns,)
labels of samples in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term for entropic regularization >0
eta : float, optional
Regularization term for group lasso regularization >0
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations (inner sinkhorn solver)
stopInnerThr : float, optional
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
to_numpy : boolean, optional (default True)
If true convert back the GPU array result to numpy format.
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
"Optimal Transport for Domain Adaptation," in IEEE
Transactions on Pattern Analysis and Machine Intelligence ,
vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence
and applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.lp.emd : Unregularized OT
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT
"""
a, labels_a, b, M = utils.to_gpu(a, labels_a, b, M)
p = 0.5
epsilon = 1e-3
indices_labels = []
labels_a2 = cp.asnumpy(labels_a)
classes = npp.unique(labels_a2)
for c in classes:
idxc, = utils.to_gpu(npp.where(labels_a2 == c))
indices_labels.append(idxc)
W = np.zeros(M.shape)
for cpt in range(numItermax):
Mreg = M + eta * W
transp = sinkhorn(a, b, Mreg, reg, numItermax=numInnerItermax,
stopThr=stopInnerThr, to_numpy=False)
# the transport has been computed. Check if classes are really
# separated
W = np.ones(M.shape)
for (i, c) in enumerate(classes):
majs = np.sum(transp[indices_labels[i]], axis=0)
majs = p * ((majs + epsilon)**(p - 1))
W[indices_labels[i]] = majs
if to_numpy:
return utils.to_np(transp)
else:
return transp | 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
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::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)
+ \eta \Omega_g(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega_e` is the entropic regularization term
:math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`\Omega_g` is the group lasso regulaization term
:math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1`
where :math:`\mathcal{I}_c` are the index of samples from class c
in the source domain.
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalised conditional
gradient as proposed in [5]_ [7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
labels_a : np.ndarray (ns,)
labels of samples in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term for entropic regularization >0
eta : float, optional
Regularization term for group lasso regularization >0
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations (inner sinkhorn solver)
stopInnerThr : float, optional
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
to_numpy : boolean, optional (default True)
If true convert back the GPU array result to numpy format.
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
"Optimal Transport for Domain Adaptation," in IEEE
Transactions on Pattern Analysis and Machine Intelligence ,
vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence
and applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.lp.emd : Unregularized OT
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT
"""
a, labels_a, b, M = utils.to_gpu(a, labels_a, b, M)
p = 0.5
epsilon = 1e-3
indices_labels = []
labels_a2 = cp.asnumpy(labels_a)
classes = npp.unique(labels_a2)
for c in classes:
idxc, = utils.to_gpu(npp.where(labels_a2 == c))
indices_labels.append(idxc)
W = np.zeros(M.shape)
for cpt in range(numItermax):
Mreg = M + eta * W
transp = sinkhorn(a, b, Mreg, reg, numItermax=numInnerItermax,
stopThr=stopInnerThr, to_numpy=False)
# the transport has been computed. Check if classes are really
# separated
W = np.ones(M.shape)
for (i, c) in enumerate(classes):
majs = np.sum(transp[indices_labels[i]], axis=0)
majs = p * ((majs + epsilon)**(p - 1))
W[indices_labels[i]] = majs
if to_numpy:
return utils.to_np(transp)
else:
return transp | [
"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::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)
+ \eta \Omega_g(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega_e` is the entropic regularization term
:math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`\Omega_g` is the group lasso regulaization term
:math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1`
where :math:`\mathcal{I}_c` are the index of samples from class c
in the source domain.
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalised conditional
gradient as proposed in [5]_ [7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
labels_a : np.ndarray (ns,)
labels of samples in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term for entropic regularization >0
eta : float, optional
Regularization term for group lasso regularization >0
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations (inner sinkhorn solver)
stopInnerThr : float, optional
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
to_numpy : boolean, optional (default True)
If true convert back the GPU array result to numpy format.
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
"Optimal Transport for Domain Adaptation," in IEEE
Transactions on Pattern Analysis and Machine Intelligence ,
vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence
and applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.lp.emd : Unregularized OT
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT | [
"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 | 221,940 |
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 | 221,941 |
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 | 221,942 |
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 = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
method : str
method used for the solver either 'sinkhorn', 'greenkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.sinkhorn(a,b,M,1)
array([[ 0.36552929, 0.13447071],
[ 0.13447071, 0.36552929]])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10]
"""
if method.lower() == 'sinkhorn':
def sink():
return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'greenkhorn':
def sink():
return greenkhorn(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log)
elif method.lower() == 'sinkhorn_stabilized':
def sink():
return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'sinkhorn_epsilon_scaling':
def sink():
return sinkhorn_epsilon_scaling(
a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
else:
print('Warning : unknown method using classic Sinkhorn Knopp')
def sink():
return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
return sink() | 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 = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
method : str
method used for the solver either 'sinkhorn', 'greenkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.sinkhorn(a,b,M,1)
array([[ 0.36552929, 0.13447071],
[ 0.13447071, 0.36552929]])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10]
"""
if method.lower() == 'sinkhorn':
def sink():
return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'greenkhorn':
def sink():
return greenkhorn(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log)
elif method.lower() == 'sinkhorn_stabilized':
def sink():
return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'sinkhorn_epsilon_scaling':
def sink():
return sinkhorn_epsilon_scaling(
a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
else:
print('Warning : unknown method using classic Sinkhorn Knopp')
def sink():
return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
return sink() | [
"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 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
method : str
method used for the solver either 'sinkhorn', 'greenkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.sinkhorn(a,b,M,1)
array([[ 0.36552929, 0.13447071],
[ 0.13447071, 0.36552929]])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10] | [
"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 | 221,943 |
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_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
method : str
method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
W : (nt) ndarray or float
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.sinkhorn2(a,b,M,1)
array([ 0.26894142])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[21] Altschuler J., Weed J., Rigollet P. : Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration, Advances in Neural Information Processing Systems (NIPS) 31, 2017
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]
ot.bregman.greenkhorn : Greenkhorn [21]
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10]
"""
if method.lower() == 'sinkhorn':
def sink():
return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'sinkhorn_stabilized':
def sink():
return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'sinkhorn_epsilon_scaling':
def sink():
return sinkhorn_epsilon_scaling(
a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
else:
print('Warning : unknown method using classic Sinkhorn Knopp')
def sink():
return sinkhorn_knopp(a, b, M, reg, **kwargs)
b = np.asarray(b, dtype=np.float64)
if len(b.shape) < 2:
b = b.reshape((-1, 1))
return sink() | 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_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
method : str
method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
W : (nt) ndarray or float
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.sinkhorn2(a,b,M,1)
array([ 0.26894142])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[21] Altschuler J., Weed J., Rigollet P. : Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration, Advances in Neural Information Processing Systems (NIPS) 31, 2017
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]
ot.bregman.greenkhorn : Greenkhorn [21]
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10]
"""
if method.lower() == 'sinkhorn':
def sink():
return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'sinkhorn_stabilized':
def sink():
return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'sinkhorn_epsilon_scaling':
def sink():
return sinkhorn_epsilon_scaling(
a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
else:
print('Warning : unknown method using classic Sinkhorn Knopp')
def sink():
return sinkhorn_knopp(a, b, M, reg, **kwargs)
b = np.asarray(b, dtype=np.float64)
if len(b.shape) < 2:
b = b.reshape((-1, 1))
return sink() | [
"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 :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
method : str
method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
W : (nt) ndarray or float
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.sinkhorn2(a,b,M,1)
array([ 0.26894142])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[21] Altschuler J., Weed J., Rigollet P. : Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration, Advances in Neural Information Processing Systems (NIPS) 31, 2017
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]
ot.bregman.greenkhorn : Greenkhorn [21]
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10] | [
"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 | 221,944 |
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 | 221,945 |
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 | 221,946 |
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 | 221,947 |
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 | 221,948 |
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_{reg}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`
- reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_
Parameters
----------
A : np.ndarray (d,n)
n training distributions a_i of size d
M : np.ndarray (d,d)
loss matrix for OT
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each histogram a_i on the simplex (barycentric coodinates)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
"""
if weights is None:
weights = np.ones(A.shape[1]) / A.shape[1]
else:
assert(len(weights) == A.shape[1])
if log:
log = {'err': []}
# M = M/np.median(M) # suggested by G. Peyre
K = np.exp(-M / reg)
cpt = 0
err = 1
UKv = np.dot(K, np.divide(A.T, np.sum(K, axis=0)).T)
u = (geometricMean(UKv) / UKv.T).T
while (err > stopThr and cpt < numItermax):
cpt = cpt + 1
UKv = u * np.dot(K, np.divide(A, np.dot(K, u)))
u = (u.T * geometricBar(weights, UKv)).T / UKv
if cpt % 10 == 1:
err = np.sum(np.std(UKv, axis=1))
# log and verbose print
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print(
'{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
if log:
log['niter'] = cpt
return geometricBar(weights, UKv), log
else:
return geometricBar(weights, UKv) | 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_{reg}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`
- reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_
Parameters
----------
A : np.ndarray (d,n)
n training distributions a_i of size d
M : np.ndarray (d,d)
loss matrix for OT
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each histogram a_i on the simplex (barycentric coodinates)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
"""
if weights is None:
weights = np.ones(A.shape[1]) / A.shape[1]
else:
assert(len(weights) == A.shape[1])
if log:
log = {'err': []}
# M = M/np.median(M) # suggested by G. Peyre
K = np.exp(-M / reg)
cpt = 0
err = 1
UKv = np.dot(K, np.divide(A.T, np.sum(K, axis=0)).T)
u = (geometricMean(UKv) / UKv.T).T
while (err > stopThr and cpt < numItermax):
cpt = cpt + 1
UKv = u * np.dot(K, np.divide(A, np.dot(K, u)))
u = (u.T * geometricBar(weights, UKv)).T / UKv
if cpt % 10 == 1:
err = np.sum(np.std(UKv, axis=1))
# log and verbose print
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print(
'{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
if log:
log['niter'] = cpt
return geometricBar(weights, UKv), log
else:
return geometricBar(weights, UKv) | [
"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 distance (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`
- reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_
Parameters
----------
A : np.ndarray (d,n)
n training distributions a_i of size d
M : np.ndarray (d,d)
loss matrix for OT
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each histogram a_i on the simplex (barycentric coodinates)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138. | [
"Compute",
"the",
"entropic",
"regularized",
"wasserstein",
"barycenter",
"of",
"distributions",
"A"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L989-L1082 | train | 221,949 |
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:
.. 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 distance (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions (2D images) in the mast two dimensions of matrix :math:`\mathbf{A}`
- reg is the regularization strength scalar value
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [21]_
Parameters
----------
A : np.ndarray (n,w,h)
n distributions (2D images) of size w x h
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each image on the simplex (barycentric coodinates)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
stabThr : float, optional
Stabilization threshold to avoid numerical precision issue
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (w,h) ndarray
2D Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [21] Solomon, J., De Goes, F., Peyré, G., Cuturi, M., Butscher, A., Nguyen, A. & Guibas, L. (2015).
Convolutional wasserstein distances: Efficient optimal transportation on geometric domains
ACM Transactions on Graphics (TOG), 34(4), 66
"""
if weights is None:
weights = np.ones(A.shape[0]) / A.shape[0]
else:
assert(len(weights) == A.shape[0])
if log:
log = {'err': []}
b = np.zeros_like(A[0, :, :])
U = np.ones_like(A)
KV = np.ones_like(A)
cpt = 0
err = 1
# build the convolution operator
t = np.linspace(0, 1, A.shape[1])
[Y, X] = np.meshgrid(t, t)
xi1 = np.exp(-(X - Y)**2 / reg)
def K(x):
return np.dot(np.dot(xi1, x), xi1)
while (err > stopThr and cpt < numItermax):
bold = b
cpt = cpt + 1
b = np.zeros_like(A[0, :, :])
for r in range(A.shape[0]):
KV[r, :, :] = K(A[r, :, :] / np.maximum(stabThr, K(U[r, :, :])))
b += weights[r] * np.log(np.maximum(stabThr, U[r, :, :] * KV[r, :, :]))
b = np.exp(b)
for r in range(A.shape[0]):
U[r, :, :] = b / np.maximum(stabThr, KV[r, :, :])
if cpt % 10 == 1:
err = np.sum(np.abs(bold - b))
# log and verbose print
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
if log:
log['niter'] = cpt
log['U'] = U
return b, log
else:
return b | 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:
.. 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 distance (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions (2D images) in the mast two dimensions of matrix :math:`\mathbf{A}`
- reg is the regularization strength scalar value
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [21]_
Parameters
----------
A : np.ndarray (n,w,h)
n distributions (2D images) of size w x h
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each image on the simplex (barycentric coodinates)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
stabThr : float, optional
Stabilization threshold to avoid numerical precision issue
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (w,h) ndarray
2D Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [21] Solomon, J., De Goes, F., Peyré, G., Cuturi, M., Butscher, A., Nguyen, A. & Guibas, L. (2015).
Convolutional wasserstein distances: Efficient optimal transportation on geometric domains
ACM Transactions on Graphics (TOG), 34(4), 66
"""
if weights is None:
weights = np.ones(A.shape[0]) / A.shape[0]
else:
assert(len(weights) == A.shape[0])
if log:
log = {'err': []}
b = np.zeros_like(A[0, :, :])
U = np.ones_like(A)
KV = np.ones_like(A)
cpt = 0
err = 1
# build the convolution operator
t = np.linspace(0, 1, A.shape[1])
[Y, X] = np.meshgrid(t, t)
xi1 = np.exp(-(X - Y)**2 / reg)
def K(x):
return np.dot(np.dot(xi1, x), xi1)
while (err > stopThr and cpt < numItermax):
bold = b
cpt = cpt + 1
b = np.zeros_like(A[0, :, :])
for r in range(A.shape[0]):
KV[r, :, :] = K(A[r, :, :] / np.maximum(stabThr, K(U[r, :, :])))
b += weights[r] * np.log(np.maximum(stabThr, U[r, :, :] * KV[r, :, :]))
b = np.exp(b)
for r in range(A.shape[0]):
U[r, :, :] = b / np.maximum(stabThr, KV[r, :, :])
if cpt % 10 == 1:
err = np.sum(np.abs(bold - b))
# log and verbose print
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
if log:
log['niter'] = cpt
log['U'] = U
return b, log
else:
return b | [
"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)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions (2D images) in the mast two dimensions of matrix :math:`\mathbf{A}`
- reg is the regularization strength scalar value
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [21]_
Parameters
----------
A : np.ndarray (n,w,h)
n distributions (2D images) of size w x h
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each image on the simplex (barycentric coodinates)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
stabThr : float, optional
Stabilization threshold to avoid numerical precision issue
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (w,h) ndarray
2D Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [21] Solomon, J., De Goes, F., Peyré, G., Cuturi, M., Butscher, A., Nguyen, A. & Guibas, L. (2015).
Convolutional wasserstein distances: Efficient optimal transportation on geometric domains
ACM Transactions on Graphics (TOG), 34(4), 66 | [
"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 | 221,950 |
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_\mathbf{h} (1- \\alpha) W_{M,reg}(\mathbf{a},\mathbf{Dh})+\\alpha W_{M0,reg0}(\mathbf{h}_0,\mathbf{h})
where :
- :math:`W_{M,reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance with M loss matrix (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}` is an observed distribution, :math:`\mathbf{h}_0` is aprior on unmixing
- reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT data fitting
- reg0 and :math:`\mathbf{M0}` are respectively the regularization term and the cost matrix for regularization
- :math:`\\alpha`weight data fitting and regularization
The optimization problem is solved suing the algorithm described in [4]
Parameters
----------
a : np.ndarray (d)
observed distribution
D : np.ndarray (d,n)
dictionary matrix
M : np.ndarray (d,d)
loss matrix
M0 : np.ndarray (n,n)
loss matrix
h0 : np.ndarray (n,)
prior on h
reg : float
Regularization term >0 (Wasserstein data fitting)
reg0 : float
Regularization term >0 (Wasserstein reg with h0)
alpha : float
How much should we trust the prior ([0,1])
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [4] S. Nakhostin, N. Courty, R. Flamary, D. Tuia, T. Corpetti, Supervised planetary unmixing with optimal transport, Whorkshop on Hyperspectral Image and Signal Processing : Evolution in Remote Sensing (WHISPERS), 2016.
"""
# M = M/np.median(M)
K = np.exp(-M / reg)
# M0 = M0/np.median(M0)
K0 = np.exp(-M0 / reg0)
old = h0
err = 1
cpt = 0
# log = {'niter':0, 'all_err':[]}
if log:
log = {'err': []}
while (err > stopThr and cpt < numItermax):
K = projC(K, a)
K0 = projC(K0, h0)
new = np.sum(K0, axis=1)
# we recombine the current selection from dictionnary
inv_new = np.dot(D, new)
other = np.sum(K, axis=1)
# geometric interpolation
delta = np.exp(alpha * np.log(other) + (1 - alpha) * np.log(inv_new))
K = projR(K, delta)
K0 = np.dot(np.diag(np.dot(D.T, delta / inv_new)), K0)
err = np.linalg.norm(np.sum(K0, axis=1) - old)
old = new
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
cpt = cpt + 1
if log:
log['niter'] = cpt
return np.sum(K0, axis=1), log
else:
return np.sum(K0, axis=1) | 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_\mathbf{h} (1- \\alpha) W_{M,reg}(\mathbf{a},\mathbf{Dh})+\\alpha W_{M0,reg0}(\mathbf{h}_0,\mathbf{h})
where :
- :math:`W_{M,reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance with M loss matrix (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}` is an observed distribution, :math:`\mathbf{h}_0` is aprior on unmixing
- reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT data fitting
- reg0 and :math:`\mathbf{M0}` are respectively the regularization term and the cost matrix for regularization
- :math:`\\alpha`weight data fitting and regularization
The optimization problem is solved suing the algorithm described in [4]
Parameters
----------
a : np.ndarray (d)
observed distribution
D : np.ndarray (d,n)
dictionary matrix
M : np.ndarray (d,d)
loss matrix
M0 : np.ndarray (n,n)
loss matrix
h0 : np.ndarray (n,)
prior on h
reg : float
Regularization term >0 (Wasserstein data fitting)
reg0 : float
Regularization term >0 (Wasserstein reg with h0)
alpha : float
How much should we trust the prior ([0,1])
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [4] S. Nakhostin, N. Courty, R. Flamary, D. Tuia, T. Corpetti, Supervised planetary unmixing with optimal transport, Whorkshop on Hyperspectral Image and Signal Processing : Evolution in Remote Sensing (WHISPERS), 2016.
"""
# M = M/np.median(M)
K = np.exp(-M / reg)
# M0 = M0/np.median(M0)
K0 = np.exp(-M0 / reg0)
old = h0
err = 1
cpt = 0
# log = {'niter':0, 'all_err':[]}
if log:
log = {'err': []}
while (err > stopThr and cpt < numItermax):
K = projC(K, a)
K0 = projC(K0, h0)
new = np.sum(K0, axis=1)
# we recombine the current selection from dictionnary
inv_new = np.dot(D, new)
other = np.sum(K, axis=1)
# geometric interpolation
delta = np.exp(alpha * np.log(other) + (1 - alpha) * np.log(inv_new))
K = projR(K, delta)
K0 = np.dot(np.diag(np.dot(D.T, delta / inv_new)), K0)
err = np.linalg.norm(np.sum(K0, axis=1) - old)
old = new
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
cpt = cpt + 1
if log:
log['niter'] = cpt
return np.sum(K0, axis=1), log
else:
return np.sum(K0, axis=1) | [
"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 :
- :math:`W_{M,reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance with M loss matrix (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}` is an observed distribution, :math:`\mathbf{h}_0` is aprior on unmixing
- reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT data fitting
- reg0 and :math:`\mathbf{M0}` are respectively the regularization term and the cost matrix for regularization
- :math:`\\alpha`weight data fitting and regularization
The optimization problem is solved suing the algorithm described in [4]
Parameters
----------
a : np.ndarray (d)
observed distribution
D : np.ndarray (d,n)
dictionary matrix
M : np.ndarray (d,d)
loss matrix
M0 : np.ndarray (n,n)
loss matrix
h0 : np.ndarray (n,)
prior on h
reg : float
Regularization term >0 (Wasserstein data fitting)
reg0 : float
Regularization term >0 (Wasserstein reg with h0)
alpha : float
How much should we trust the prior ([0,1])
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [4] S. Nakhostin, N. Courty, R. Flamary, D. Tuia, T. Corpetti, Supervised planetary unmixing with optimal transport, Whorkshop on Hyperspectral Image and Signal Processing : Evolution in Remote Sensing (WHISPERS), 2016. | [
"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 | 221,951 |
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 problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- :math:`M` is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> emp_sinkhorn = empirical_sinkhorn(X_s, X_t, reg, verbose=False)
>>> print(emp_sinkhorn)
>>> [[4.99977301e-01 2.26989344e-05]
[2.26989344e-05 4.99977301e-01]]
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
'''
if a is None:
a = unif(np.shape(X_s)[0])
if b is None:
b = unif(np.shape(X_t)[0])
M = dist(X_s, X_t, metric=metric)
if log:
pi, log = sinkhorn(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=True, **kwargs)
return pi, log
else:
pi = sinkhorn(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=False, **kwargs)
return pi | 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 problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- :math:`M` is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> emp_sinkhorn = empirical_sinkhorn(X_s, X_t, reg, verbose=False)
>>> print(emp_sinkhorn)
>>> [[4.99977301e-01 2.26989344e-05]
[2.26989344e-05 4.99977301e-01]]
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
'''
if a is None:
a = unif(np.shape(X_s)[0])
if b is None:
b = unif(np.shape(X_t)[0])
M = dist(X_s, X_t, metric=metric)
if log:
pi, log = sinkhorn(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=True, **kwargs)
return pi, log
else:
pi = sinkhorn(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=False, **kwargs)
return pi | [
"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
\gamma\geq 0
where :
- :math:`M` is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> emp_sinkhorn = empirical_sinkhorn(X_s, X_t, reg, verbose=False)
>>> print(emp_sinkhorn)
>>> [[4.99977301e-01 2.26989344e-05]
[2.26989344e-05 4.99977301e-01]]
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. | [
"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 | 221,952 |
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 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 :
- :math:`M` is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> loss_sinkhorn = empirical_sinkhorn2(X_s, X_t, reg, verbose=False)
>>> print(loss_sinkhorn)
>>> [4.53978687e-05]
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
'''
if a is None:
a = unif(np.shape(X_s)[0])
if b is None:
b = unif(np.shape(X_t)[0])
M = dist(X_s, X_t, metric=metric)
if log:
sinkhorn_loss, log = sinkhorn2(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=log, **kwargs)
return sinkhorn_loss, log
else:
sinkhorn_loss = sinkhorn2(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=log, **kwargs)
return sinkhorn_loss | 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 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 :
- :math:`M` is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> loss_sinkhorn = empirical_sinkhorn2(X_s, X_t, reg, verbose=False)
>>> print(loss_sinkhorn)
>>> [4.53978687e-05]
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
'''
if a is None:
a = unif(np.shape(X_s)[0])
if b is None:
b = unif(np.shape(X_t)[0])
M = dist(X_s, X_t, metric=metric)
if log:
sinkhorn_loss, log = sinkhorn2(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=log, **kwargs)
return sinkhorn_loss, log
else:
sinkhorn_loss = sinkhorn2(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=log, **kwargs)
return sinkhorn_loss | [
"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
\gamma\geq 0
where :
- :math:`M` is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> loss_sinkhorn = empirical_sinkhorn2(X_s, X_t, reg, verbose=False)
>>> print(loss_sinkhorn)
>>> [4.53978687e-05]
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. | [
"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 | 221,953 |
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 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_a)
W_b &= \min_{\gamma_b} <\gamma_b,M_b>_F + reg\cdot\Omega(\gamma_b)
S &= W - 1/2 * (W_a + W_b)
.. math::
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
\gamma_a 1 = a
\gamma_a^T 1= a
\gamma_a\geq 0
\gamma_b 1 = b
\gamma_b^T 1= b
\gamma_b\geq 0
where :
- :math:`M` (resp. :math:`M_a, M_b`) is the (ns,nt) metric cost matrix (resp (ns, ns) and (nt, nt))
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 4
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> emp_sinkhorn_div = empirical_sinkhorn_divergence(X_s, X_t, reg)
>>> print(emp_sinkhorn_div)
>>> [2.99977435]
References
----------
.. [23] Aude Genevay, Gabriel Peyré, Marco Cuturi, Learning Generative Models with Sinkhorn Divergences, Proceedings of the Twenty-First International Conference on Artficial Intelligence and Statistics, (AISTATS) 21, 2018
'''
if log:
sinkhorn_loss_ab, log_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs)
sinkhorn_loss_a, log_a = empirical_sinkhorn2(X_s, X_s, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs)
sinkhorn_loss_b, log_b = empirical_sinkhorn2(X_t, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs)
sinkhorn_div = sinkhorn_loss_ab - 1 / 2 * (sinkhorn_loss_a + sinkhorn_loss_b)
log = {}
log['sinkhorn_loss_ab'] = sinkhorn_loss_ab
log['sinkhorn_loss_a'] = sinkhorn_loss_a
log['sinkhorn_loss_b'] = sinkhorn_loss_b
log['log_sinkhorn_ab'] = log_ab
log['log_sinkhorn_a'] = log_a
log['log_sinkhorn_b'] = log_b
return max(0, sinkhorn_div), log
else:
sinkhorn_loss_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs)
sinkhorn_loss_a = empirical_sinkhorn2(X_s, X_s, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs)
sinkhorn_loss_b = empirical_sinkhorn2(X_t, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs)
sinkhorn_div = sinkhorn_loss_ab - 1 / 2 * (sinkhorn_loss_a + sinkhorn_loss_b)
return max(0, sinkhorn_div) | 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 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_a)
W_b &= \min_{\gamma_b} <\gamma_b,M_b>_F + reg\cdot\Omega(\gamma_b)
S &= W - 1/2 * (W_a + W_b)
.. math::
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
\gamma_a 1 = a
\gamma_a^T 1= a
\gamma_a\geq 0
\gamma_b 1 = b
\gamma_b^T 1= b
\gamma_b\geq 0
where :
- :math:`M` (resp. :math:`M_a, M_b`) is the (ns,nt) metric cost matrix (resp (ns, ns) and (nt, nt))
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 4
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> emp_sinkhorn_div = empirical_sinkhorn_divergence(X_s, X_t, reg)
>>> print(emp_sinkhorn_div)
>>> [2.99977435]
References
----------
.. [23] Aude Genevay, Gabriel Peyré, Marco Cuturi, Learning Generative Models with Sinkhorn Divergences, Proceedings of the Twenty-First International Conference on Artficial Intelligence and Statistics, (AISTATS) 21, 2018
'''
if log:
sinkhorn_loss_ab, log_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs)
sinkhorn_loss_a, log_a = empirical_sinkhorn2(X_s, X_s, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs)
sinkhorn_loss_b, log_b = empirical_sinkhorn2(X_t, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs)
sinkhorn_div = sinkhorn_loss_ab - 1 / 2 * (sinkhorn_loss_a + sinkhorn_loss_b)
log = {}
log['sinkhorn_loss_ab'] = sinkhorn_loss_ab
log['sinkhorn_loss_a'] = sinkhorn_loss_a
log['sinkhorn_loss_b'] = sinkhorn_loss_b
log['log_sinkhorn_ab'] = log_ab
log['log_sinkhorn_a'] = log_a
log['log_sinkhorn_b'] = log_b
return max(0, sinkhorn_div), log
else:
sinkhorn_loss_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs)
sinkhorn_loss_a = empirical_sinkhorn2(X_s, X_s, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs)
sinkhorn_loss_b = empirical_sinkhorn2(X_t, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs)
sinkhorn_div = sinkhorn_loss_ab - 1 / 2 * (sinkhorn_loss_a + sinkhorn_loss_b)
return max(0, sinkhorn_div) | [
"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_a)
W_b &= \min_{\gamma_b} <\gamma_b,M_b>_F + reg\cdot\Omega(\gamma_b)
S &= W - 1/2 * (W_a + W_b)
.. math::
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
\gamma_a 1 = a
\gamma_a^T 1= a
\gamma_a\geq 0
\gamma_b 1 = b
\gamma_b^T 1= b
\gamma_b\geq 0
where :
- :math:`M` (resp. :math:`M_a, M_b`) is the (ns,nt) metric cost matrix (resp (ns, ns) and (nt, nt))
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 4
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> emp_sinkhorn_div = empirical_sinkhorn_divergence(X_s, X_t, reg)
>>> print(emp_sinkhorn_div)
>>> [2.99977435]
References
----------
.. [23] Aude Genevay, Gabriel Peyré, Marco Cuturi, Learning Generative Models with Sinkhorn Divergences, Proceedings of the Twenty-First International Conference on Artficial Intelligence and Statistics, (AISTATS) 21, 2018 | [
"Compute",
"the",
"sinkhorn",
"divergence",
"loss",
"from",
"empirical",
"data"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1483-L1599 | train | 221,954 |
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 and b are the sample weights
Uses the algorithm proposed in [1]_
Parameters
----------
a : (ns,) ndarray, float64
Source histogram (uniform weigth if empty list)
b : (nt,) ndarray, float64
Target histogram (uniform weigth if empty list)
M : (ns,nt) ndarray, float64
loss matrix
numItermax : int, optional (default=100000)
The maximum number of iterations before stopping the optimization
algorithm if it has not converged.
log: boolean, optional (default=False)
If True, returns a dictionary containing the cost and dual
variables. Otherwise returns only the optimal transportation matrix.
Returns
-------
gamma: (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log: dict
If input log is true, a dictionary containing the cost and dual
variables and exit status
Examples
--------
Simple example with obvious solution. The function emd accepts lists and
perform automatic conversion to numpy arrays
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.emd(a,b,M)
array([[ 0.5, 0. ],
[ 0. , 0.5]])
References
----------
.. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W.
(2011, December). Displacement interpolation using Lagrangian mass
transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p.
158). ACM.
See Also
--------
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT"""
a = np.asarray(a, dtype=np.float64)
b = np.asarray(b, dtype=np.float64)
M = np.asarray(M, dtype=np.float64)
# if empty array given then use unifor distributions
if len(a) == 0:
a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0]
if len(b) == 0:
b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1]
G, cost, u, v, result_code = emd_c(a, b, M, numItermax)
result_code_string = check_result(result_code)
if log:
log = {}
log['cost'] = cost
log['u'] = u
log['v'] = v
log['warning'] = result_code_string
log['result_code'] = result_code
return G, log
return G | 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 and b are the sample weights
Uses the algorithm proposed in [1]_
Parameters
----------
a : (ns,) ndarray, float64
Source histogram (uniform weigth if empty list)
b : (nt,) ndarray, float64
Target histogram (uniform weigth if empty list)
M : (ns,nt) ndarray, float64
loss matrix
numItermax : int, optional (default=100000)
The maximum number of iterations before stopping the optimization
algorithm if it has not converged.
log: boolean, optional (default=False)
If True, returns a dictionary containing the cost and dual
variables. Otherwise returns only the optimal transportation matrix.
Returns
-------
gamma: (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log: dict
If input log is true, a dictionary containing the cost and dual
variables and exit status
Examples
--------
Simple example with obvious solution. The function emd accepts lists and
perform automatic conversion to numpy arrays
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.emd(a,b,M)
array([[ 0.5, 0. ],
[ 0. , 0.5]])
References
----------
.. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W.
(2011, December). Displacement interpolation using Lagrangian mass
transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p.
158). ACM.
See Also
--------
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT"""
a = np.asarray(a, dtype=np.float64)
b = np.asarray(b, dtype=np.float64)
M = np.asarray(M, dtype=np.float64)
# if empty array given then use unifor distributions
if len(a) == 0:
a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0]
if len(b) == 0:
b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1]
G, cost, u, v, result_code = emd_c(a, b, M, numItermax)
result_code_string = check_result(result_code)
if log:
log = {}
log['cost'] = cost
log['u'] = u
log['v'] = v
log['warning'] = result_code_string
log['result_code'] = result_code
return G, log
return G | [
"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 proposed in [1]_
Parameters
----------
a : (ns,) ndarray, float64
Source histogram (uniform weigth if empty list)
b : (nt,) ndarray, float64
Target histogram (uniform weigth if empty list)
M : (ns,nt) ndarray, float64
loss matrix
numItermax : int, optional (default=100000)
The maximum number of iterations before stopping the optimization
algorithm if it has not converged.
log: boolean, optional (default=False)
If True, returns a dictionary containing the cost and dual
variables. Otherwise returns only the optimal transportation matrix.
Returns
-------
gamma: (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log: dict
If input log is true, a dictionary containing the cost and dual
variables and exit status
Examples
--------
Simple example with obvious solution. The function emd accepts lists and
perform automatic conversion to numpy arrays
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.emd(a,b,M)
array([[ 0.5, 0. ],
[ 0. , 0.5]])
References
----------
.. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W.
(2011, December). Displacement interpolation using Lagrangian mass
transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p.
158). ACM.
See Also
--------
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT | [
"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 | 221,955 |
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\geq 0
where :
- M is the metric cost matrix
- a and b are the sample weights
Uses the algorithm proposed in [1]_
Parameters
----------
a : (ns,) ndarray, float64
Source histogram (uniform weigth if empty list)
b : (nt,) ndarray, float64
Target histogram (uniform weigth if empty list)
M : (ns,nt) ndarray, float64
loss matrix
numItermax : int, optional (default=100000)
The maximum number of iterations before stopping the optimization
algorithm if it has not converged.
log: boolean, optional (default=False)
If True, returns a dictionary containing the cost and dual
variables. Otherwise returns only the optimal transportation cost.
return_matrix: boolean, optional (default=False)
If True, returns the optimal transportation matrix in the log.
Returns
-------
gamma: (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log: dict
If input log is true, a dictionary containing the cost and dual
variables and exit status
Examples
--------
Simple example with obvious solution. The function emd accepts lists and
perform automatic conversion to numpy arrays
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.emd2(a,b,M)
0.0
References
----------
.. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W.
(2011, December). Displacement interpolation using Lagrangian mass
transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p.
158). ACM.
See Also
--------
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT"""
a = np.asarray(a, dtype=np.float64)
b = np.asarray(b, dtype=np.float64)
M = np.asarray(M, dtype=np.float64)
# if empty array given then use unifor distributions
if len(a) == 0:
a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0]
if len(b) == 0:
b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1]
if log or return_matrix:
def f(b):
G, cost, u, v, resultCode = emd_c(a, b, M, numItermax)
result_code_string = check_result(resultCode)
log = {}
if return_matrix:
log['G'] = G
log['u'] = u
log['v'] = v
log['warning'] = result_code_string
log['result_code'] = resultCode
return [cost, log]
else:
def f(b):
G, cost, u, v, result_code = emd_c(a, b, M, numItermax)
check_result(result_code)
return cost
if len(b.shape) == 1:
return f(b)
nb = b.shape[1]
res = parmap(f, [b[:, i] for i in range(nb)], processes)
return res | 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\geq 0
where :
- M is the metric cost matrix
- a and b are the sample weights
Uses the algorithm proposed in [1]_
Parameters
----------
a : (ns,) ndarray, float64
Source histogram (uniform weigth if empty list)
b : (nt,) ndarray, float64
Target histogram (uniform weigth if empty list)
M : (ns,nt) ndarray, float64
loss matrix
numItermax : int, optional (default=100000)
The maximum number of iterations before stopping the optimization
algorithm if it has not converged.
log: boolean, optional (default=False)
If True, returns a dictionary containing the cost and dual
variables. Otherwise returns only the optimal transportation cost.
return_matrix: boolean, optional (default=False)
If True, returns the optimal transportation matrix in the log.
Returns
-------
gamma: (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log: dict
If input log is true, a dictionary containing the cost and dual
variables and exit status
Examples
--------
Simple example with obvious solution. The function emd accepts lists and
perform automatic conversion to numpy arrays
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.emd2(a,b,M)
0.0
References
----------
.. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W.
(2011, December). Displacement interpolation using Lagrangian mass
transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p.
158). ACM.
See Also
--------
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT"""
a = np.asarray(a, dtype=np.float64)
b = np.asarray(b, dtype=np.float64)
M = np.asarray(M, dtype=np.float64)
# if empty array given then use unifor distributions
if len(a) == 0:
a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0]
if len(b) == 0:
b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1]
if log or return_matrix:
def f(b):
G, cost, u, v, resultCode = emd_c(a, b, M, numItermax)
result_code_string = check_result(resultCode)
log = {}
if return_matrix:
log['G'] = G
log['u'] = u
log['v'] = v
log['warning'] = result_code_string
log['result_code'] = resultCode
return [cost, log]
else:
def f(b):
G, cost, u, v, result_code = emd_c(a, b, M, numItermax)
check_result(result_code)
return cost
if len(b.shape) == 1:
return f(b)
nb = b.shape[1]
res = parmap(f, [b[:, i] for i in range(nb)], processes)
return res | [
"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 in [1]_
Parameters
----------
a : (ns,) ndarray, float64
Source histogram (uniform weigth if empty list)
b : (nt,) ndarray, float64
Target histogram (uniform weigth if empty list)
M : (ns,nt) ndarray, float64
loss matrix
numItermax : int, optional (default=100000)
The maximum number of iterations before stopping the optimization
algorithm if it has not converged.
log: boolean, optional (default=False)
If True, returns a dictionary containing the cost and dual
variables. Otherwise returns only the optimal transportation cost.
return_matrix: boolean, optional (default=False)
If True, returns the optimal transportation matrix in the log.
Returns
-------
gamma: (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log: dict
If input log is true, a dictionary containing the cost and dual
variables and exit status
Examples
--------
Simple example with obvious solution. The function emd accepts lists and
perform automatic conversion to numpy arrays
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.emd2(a,b,M)
0.0
References
----------
.. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W.
(2011, December). Displacement interpolation using Lagrangian mass
transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p.
158). ACM.
See Also
--------
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT | [
"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 | 221,956 |
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 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
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega_e` is the entropic regularization term
:math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`\Omega_g` is the group lasso regulaization term
:math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^2`
where :math:`\mathcal{I}_c` are the index of samples from class
c in the source domain.
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalised conditional
gradient as proposed in [5]_ [7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
labels_a : np.ndarray (ns,)
labels of samples in the source domain
b : np.ndarray (nt,)
samples in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term for entropic regularization >0
eta : float, optional
Regularization term for group lasso regularization >0
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations (inner sinkhorn solver)
stopInnerThr : float, optional
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
"Optimal Transport for Domain Adaptation," in IEEE Transactions
on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence and
applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.optim.gcg : Generalized conditional gradient for OT problems
"""
lstlab = np.unique(labels_a)
def f(G):
res = 0
for i in range(G.shape[1]):
for lab in lstlab:
temp = G[labels_a == lab, i]
res += np.linalg.norm(temp)
return res
def df(G):
W = np.zeros(G.shape)
for i in range(G.shape[1]):
for lab in lstlab:
temp = G[labels_a == lab, i]
n = np.linalg.norm(temp)
if n:
W[labels_a == lab, i] = temp / n
return W
return gcg(a, b, M, reg, eta, f, df, G0=None, numItermax=numItermax,
numInnerItermax=numInnerItermax, stopThr=stopInnerThr,
verbose=verbose, log=log) | 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 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
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega_e` is the entropic regularization term
:math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`\Omega_g` is the group lasso regulaization term
:math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^2`
where :math:`\mathcal{I}_c` are the index of samples from class
c in the source domain.
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalised conditional
gradient as proposed in [5]_ [7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
labels_a : np.ndarray (ns,)
labels of samples in the source domain
b : np.ndarray (nt,)
samples in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term for entropic regularization >0
eta : float, optional
Regularization term for group lasso regularization >0
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations (inner sinkhorn solver)
stopInnerThr : float, optional
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
"Optimal Transport for Domain Adaptation," in IEEE Transactions
on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence and
applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.optim.gcg : Generalized conditional gradient for OT problems
"""
lstlab = np.unique(labels_a)
def f(G):
res = 0
for i in range(G.shape[1]):
for lab in lstlab:
temp = G[labels_a == lab, i]
res += np.linalg.norm(temp)
return res
def df(G):
W = np.zeros(G.shape)
for i in range(G.shape[1]):
for lab in lstlab:
temp = G[labels_a == lab, i]
n = np.linalg.norm(temp)
if n:
W[labels_a == lab, i] = temp / n
return W
return gcg(a, b, M, reg, eta, f, df, G0=None, numItermax=numItermax,
numInnerItermax=numInnerItermax, stopThr=stopInnerThr,
verbose=verbose, log=log) | [
"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
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega_e` is the entropic regularization term
:math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`\Omega_g` is the group lasso regulaization term
:math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^2`
where :math:`\mathcal{I}_c` are the index of samples from class
c in the source domain.
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalised conditional
gradient as proposed in [5]_ [7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
labels_a : np.ndarray (ns,)
labels of samples in the source domain
b : np.ndarray (nt,)
samples in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term for entropic regularization >0
eta : float, optional
Regularization term for group lasso regularization >0
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations (inner sinkhorn solver)
stopInnerThr : float, optional
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
"Optimal Transport for Domain Adaptation," in IEEE Transactions
on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence and
applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.optim.gcg : Generalized conditional gradient for OT problems | [
"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 | 221,957 |
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 between two Gaussian distributions :math:`N(\mu_s,\Sigma_s)`
and :math:`N(\mu_t,\Sigma_t)` as proposed in [14] and discussed in remark 2.29 in [15].
The linear operator from source to target :math:`M`
.. math::
M(x)=Ax+b
where :
.. math::
A=\Sigma_s^{-1/2}(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2})^{1/2}
\Sigma_s^{-1/2}
.. math::
b=\mu_t-A\mu_s
Parameters
----------
xs : np.ndarray (ns,d)
samples in the source domain
xt : np.ndarray (nt,d)
samples in the target domain
reg : float,optional
regularization added to the diagonals of convariances (>0)
ws : np.ndarray (ns,1), optional
weights for the source samples
wt : np.ndarray (ns,1), optional
weights for the target samples
bias: boolean, optional
estimate bias b else b=0 (default:True)
log : bool, optional
record log if True
Returns
-------
A : (d x d) ndarray
Linear operator
b : (1 x d) ndarray
bias
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [14] Knott, M. and Smith, C. S. "On the optimal mapping of
distributions", Journal of Optimization Theory and Applications
Vol 43, 1984
.. [15] Peyré, G., & Cuturi, M. (2017). "Computational Optimal
Transport", 2018.
"""
d = xs.shape[1]
if bias:
mxs = xs.mean(0, keepdims=True)
mxt = xt.mean(0, keepdims=True)
xs = xs - mxs
xt = xt - mxt
else:
mxs = np.zeros((1, d))
mxt = np.zeros((1, d))
if ws is None:
ws = np.ones((xs.shape[0], 1)) / xs.shape[0]
if wt is None:
wt = np.ones((xt.shape[0], 1)) / xt.shape[0]
Cs = (xs * ws).T.dot(xs) / ws.sum() + reg * np.eye(d)
Ct = (xt * wt).T.dot(xt) / wt.sum() + reg * np.eye(d)
Cs12 = linalg.sqrtm(Cs)
Cs_12 = linalg.inv(Cs12)
M0 = linalg.sqrtm(Cs12.dot(Ct.dot(Cs12)))
A = Cs_12.dot(M0.dot(Cs_12))
b = mxt - mxs.dot(A)
if log:
log = {}
log['Cs'] = Cs
log['Ct'] = Ct
log['Cs12'] = Cs12
log['Cs_12'] = Cs_12
return A, b, log
else:
return A, 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 between two Gaussian distributions :math:`N(\mu_s,\Sigma_s)`
and :math:`N(\mu_t,\Sigma_t)` as proposed in [14] and discussed in remark 2.29 in [15].
The linear operator from source to target :math:`M`
.. math::
M(x)=Ax+b
where :
.. math::
A=\Sigma_s^{-1/2}(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2})^{1/2}
\Sigma_s^{-1/2}
.. math::
b=\mu_t-A\mu_s
Parameters
----------
xs : np.ndarray (ns,d)
samples in the source domain
xt : np.ndarray (nt,d)
samples in the target domain
reg : float,optional
regularization added to the diagonals of convariances (>0)
ws : np.ndarray (ns,1), optional
weights for the source samples
wt : np.ndarray (ns,1), optional
weights for the target samples
bias: boolean, optional
estimate bias b else b=0 (default:True)
log : bool, optional
record log if True
Returns
-------
A : (d x d) ndarray
Linear operator
b : (1 x d) ndarray
bias
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [14] Knott, M. and Smith, C. S. "On the optimal mapping of
distributions", Journal of Optimization Theory and Applications
Vol 43, 1984
.. [15] Peyré, G., & Cuturi, M. (2017). "Computational Optimal
Transport", 2018.
"""
d = xs.shape[1]
if bias:
mxs = xs.mean(0, keepdims=True)
mxt = xt.mean(0, keepdims=True)
xs = xs - mxs
xt = xt - mxt
else:
mxs = np.zeros((1, d))
mxt = np.zeros((1, d))
if ws is None:
ws = np.ones((xs.shape[0], 1)) / xs.shape[0]
if wt is None:
wt = np.ones((xt.shape[0], 1)) / xt.shape[0]
Cs = (xs * ws).T.dot(xs) / ws.sum() + reg * np.eye(d)
Ct = (xt * wt).T.dot(xt) / wt.sum() + reg * np.eye(d)
Cs12 = linalg.sqrtm(Cs)
Cs_12 = linalg.inv(Cs12)
M0 = linalg.sqrtm(Cs12.dot(Ct.dot(Cs12)))
A = Cs_12.dot(M0.dot(Cs_12))
b = mxt - mxs.dot(A)
if log:
log = {}
log['Cs'] = Cs
log['Ct'] = Ct
log['Cs12'] = Cs12
log['Cs_12'] = Cs_12
return A, b, log
else:
return A, 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 [14] and discussed in remark 2.29 in [15].
The linear operator from source to target :math:`M`
.. math::
M(x)=Ax+b
where :
.. math::
A=\Sigma_s^{-1/2}(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2})^{1/2}
\Sigma_s^{-1/2}
.. math::
b=\mu_t-A\mu_s
Parameters
----------
xs : np.ndarray (ns,d)
samples in the source domain
xt : np.ndarray (nt,d)
samples in the target domain
reg : float,optional
regularization added to the diagonals of convariances (>0)
ws : np.ndarray (ns,1), optional
weights for the source samples
wt : np.ndarray (ns,1), optional
weights for the target samples
bias: boolean, optional
estimate bias b else b=0 (default:True)
log : bool, optional
record log if True
Returns
-------
A : (d x d) ndarray
Linear operator
b : (1 x d) ndarray
bias
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [14] Knott, M. and Smith, C. S. "On the optimal mapping of
distributions", Journal of Optimization Theory and Applications
Vol 43, 1984
.. [15] Peyré, G., & Cuturi, M. (2017). "Computational Optimal
Transport", 2018. | [
"return",
"OT",
"linear",
"operator",
"between",
"samples"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/da.py#L639-L740 | train | 221,958 |
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 (n, f)
first matrix
b : np.ndarray (m, f)
second matrix
to_numpy : boolean, optional (default True)
If true convert back the GPU array result to numpy format.
squared : boolean, optional (default False)
if True, return squared euclidean distance matrix
Returns
-------
c : (n x m) np.ndarray or cupy.ndarray
pairwise euclidean distance distance matrix
"""
a, b = to_gpu(a, b)
a2 = np.sum(np.square(a), 1)
b2 = np.sum(np.square(b), 1)
c = -2 * np.dot(a, b.T)
c += a2[:, None]
c += b2[None, :]
if not squared:
np.sqrt(c, out=c)
if to_numpy:
return to_np(c)
else:
return c | 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 (n, f)
first matrix
b : np.ndarray (m, f)
second matrix
to_numpy : boolean, optional (default True)
If true convert back the GPU array result to numpy format.
squared : boolean, optional (default False)
if True, return squared euclidean distance matrix
Returns
-------
c : (n x m) np.ndarray or cupy.ndarray
pairwise euclidean distance distance matrix
"""
a, b = to_gpu(a, b)
a2 = np.sum(np.square(a), 1)
b2 = np.sum(np.square(b), 1)
c = -2 * np.dot(a, b.T)
c += a2[:, None]
c += b2[None, :]
if not squared:
np.sqrt(c, out=c)
if to_numpy:
return to_np(c)
else:
return c | [
"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 matrix
to_numpy : boolean, optional (default True)
If true convert back the GPU array result to numpy format.
squared : boolean, optional (default False)
if True, return squared euclidean distance matrix
Returns
-------
c : (n x m) np.ndarray or cupy.ndarray
pairwise euclidean distance distance matrix | [
"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 | 221,959 |
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)
metric : str
Metric from 'sqeuclidean', 'euclidean',
Returns
-------
M : np.array (n1,n2)
distance matrix computed with given metric
"""
if x2 is None:
x2 = x1
if metric == "sqeuclidean":
return euclidean_distances(x1, x2, squared=True, to_numpy=to_numpy)
elif metric == "euclidean":
return euclidean_distances(x1, x2, squared=False, to_numpy=to_numpy)
else:
raise NotImplementedError | 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)
metric : str
Metric from 'sqeuclidean', 'euclidean',
Returns
-------
M : np.array (n1,n2)
distance matrix computed with given metric
"""
if x2 is None:
x2 = x1
if metric == "sqeuclidean":
return euclidean_distances(x1, x2, squared=True, to_numpy=to_numpy)
elif metric == "euclidean":
return euclidean_distances(x1, x2, squared=False, to_numpy=to_numpy)
else:
raise NotImplementedError | [
"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',
Returns
-------
M : np.array (n1,n2)
distance matrix computed with given metric | [
"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 | 221,960 |
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 | 221,961 |
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 | 221,962 |
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 | 221,963 |
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
loss function
xk : np.ndarray
initial position
pk : np.ndarray
descent direction
gfk : np.ndarray
gradient of f at xk
old_fval : float
loss value at xk
args : tuple, optional
arguments given to f
c1 : float, optional
c1 const in armijo rule (>0)
alpha0 : float, optional
initial step (>0)
Returns
-------
alpha : float
step that satisfy armijo conditions
fc : int
nb of function call
fa : float
loss value at step alpha
"""
xk = np.atleast_1d(xk)
fc = [0]
def phi(alpha1):
fc[0] += 1
return f(xk + alpha1 * pk, *args)
if old_fval is None:
phi0 = phi(0.)
else:
phi0 = old_fval
derphi0 = np.sum(pk * gfk) # Quickfix for matrices
alpha, phi1 = scalar_search_armijo(
phi, phi0, derphi0, c1=c1, alpha0=alpha0)
return alpha, fc[0], phi1 | 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
loss function
xk : np.ndarray
initial position
pk : np.ndarray
descent direction
gfk : np.ndarray
gradient of f at xk
old_fval : float
loss value at xk
args : tuple, optional
arguments given to f
c1 : float, optional
c1 const in armijo rule (>0)
alpha0 : float, optional
initial step (>0)
Returns
-------
alpha : float
step that satisfy armijo conditions
fc : int
nb of function call
fa : float
loss value at step alpha
"""
xk = np.atleast_1d(xk)
fc = [0]
def phi(alpha1):
fc[0] += 1
return f(xk + alpha1 * pk, *args)
if old_fval is None:
phi0 = phi(0.)
else:
phi0 = old_fval
derphi0 = np.sum(pk * gfk) # Quickfix for matrices
alpha, phi1 = scalar_search_armijo(
phi, phi0, derphi0, c1=c1, alpha0=alpha0)
return alpha, fc[0], phi1 | [
"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.ndarray
gradient of f at xk
old_fval : float
loss value at xk
args : tuple, optional
arguments given to f
c1 : float, optional
c1 const in armijo rule (>0)
alpha0 : float, optional
initial step (>0)
Returns
-------
alpha : float
step that satisfy armijo conditions
fc : int
nb of function call
fa : float
loss value at step alpha | [
"Armijo",
"linesearch",
"function",
"that",
"works",
"with",
"matrices"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/optim.py#L18-L72 | train | 221,964 |
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)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`f` is the regularization term ( and df is its gradient)
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is conditional gradient as discussed in [1]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
G0 : np.ndarray (ns,nt), optional
initial guess (default is indep joint density)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [1] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014). Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882.
See Also
--------
ot.lp.emd : Unregularized optimal ransport
ot.bregman.sinkhorn : Entropic regularized optimal transport
"""
loop = 1
if log:
log = {'loss': []}
if G0 is None:
G = np.outer(a, b)
else:
G = G0
def cost(G):
return np.sum(M * G) + reg * f(G)
f_val = cost(G)
if log:
log['loss'].append(f_val)
it = 0
if verbose:
print('{:5s}|{:12s}|{:8s}'.format(
'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32)
print('{:5d}|{:8e}|{:8e}'.format(it, f_val, 0))
while loop:
it += 1
old_fval = f_val
# problem linearization
Mi = M + reg * df(G)
# set M positive
Mi += Mi.min()
# solve linear program
Gc = emd(a, b, Mi)
deltaG = Gc - G
# line search
alpha, fc, f_val = line_search_armijo(cost, G, deltaG, Mi, f_val)
G = G + alpha * deltaG
# test convergence
if it >= numItermax:
loop = 0
delta_fval = (f_val - old_fval) / abs(f_val)
if abs(delta_fval) < stopThr:
loop = 0
if log:
log['loss'].append(f_val)
if verbose:
if it % 20 == 0:
print('{:5s}|{:12s}|{:8s}'.format(
'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32)
print('{:5d}|{:8e}|{:8e}'.format(it, f_val, delta_fval))
if log:
return G, log
else:
return G | 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)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`f` is the regularization term ( and df is its gradient)
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is conditional gradient as discussed in [1]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
G0 : np.ndarray (ns,nt), optional
initial guess (default is indep joint density)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [1] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014). Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882.
See Also
--------
ot.lp.emd : Unregularized optimal ransport
ot.bregman.sinkhorn : Entropic regularized optimal transport
"""
loop = 1
if log:
log = {'loss': []}
if G0 is None:
G = np.outer(a, b)
else:
G = G0
def cost(G):
return np.sum(M * G) + reg * f(G)
f_val = cost(G)
if log:
log['loss'].append(f_val)
it = 0
if verbose:
print('{:5s}|{:12s}|{:8s}'.format(
'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32)
print('{:5d}|{:8e}|{:8e}'.format(it, f_val, 0))
while loop:
it += 1
old_fval = f_val
# problem linearization
Mi = M + reg * df(G)
# set M positive
Mi += Mi.min()
# solve linear program
Gc = emd(a, b, Mi)
deltaG = Gc - G
# line search
alpha, fc, f_val = line_search_armijo(cost, G, deltaG, Mi, f_val)
G = G + alpha * deltaG
# test convergence
if it >= numItermax:
loop = 0
delta_fval = (f_val - old_fval) / abs(f_val)
if abs(delta_fval) < stopThr:
loop = 0
if log:
log['loss'].append(f_val)
if verbose:
if it % 20 == 0:
print('{:5s}|{:12s}|{:8s}'.format(
'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32)
print('{:5d}|{:8e}|{:8e}'.format(it, f_val, delta_fval))
if log:
return G, log
else:
return G | [
"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 (ns,nt) metric cost matrix
- :math:`f` is the regularization term ( and df is its gradient)
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is conditional gradient as discussed in [1]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
G0 : np.ndarray (ns,nt), optional
initial guess (default is indep joint density)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [1] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014). Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882.
See Also
--------
ot.lp.emd : Unregularized optimal ransport
ot.bregman.sinkhorn : Entropic regularized optimal transport | [
"Solve",
"the",
"general",
"regularized",
"OT",
"problem",
"with",
"conditional",
"gradient"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/optim.py#L75-L204 | train | 221,965 |
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 = arg\min_\gamma <\gamma,M>_F + reg1\cdot\Omega(\gamma) + reg2\cdot f(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`f` is the regularization term ( and df is its gradient)
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalized conditional gradient as discussed in [5,7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg1 : float
Entropic Regularization term >0
reg2 : float
Second Regularization term >0
G0 : np.ndarray (ns,nt), optional
initial guess (default is indep joint density)
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations of Sinkhorn
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.optim.cg : conditional gradient
"""
loop = 1
if log:
log = {'loss': []}
if G0 is None:
G = np.outer(a, b)
else:
G = G0
def cost(G):
return np.sum(M * G) + reg1 * np.sum(G * np.log(G)) + reg2 * f(G)
f_val = cost(G)
if log:
log['loss'].append(f_val)
it = 0
if verbose:
print('{:5s}|{:12s}|{:8s}'.format(
'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32)
print('{:5d}|{:8e}|{:8e}'.format(it, f_val, 0))
while loop:
it += 1
old_fval = f_val
# problem linearization
Mi = M + reg2 * df(G)
# solve linear program with Sinkhorn
# Gc = sinkhorn_stabilized(a,b, Mi, reg1, numItermax = numInnerItermax)
Gc = sinkhorn(a, b, Mi, reg1, numItermax=numInnerItermax)
deltaG = Gc - G
# line search
dcost = Mi + reg1 * (1 + np.log(G)) # ??
alpha, fc, f_val = line_search_armijo(cost, G, deltaG, dcost, f_val)
G = G + alpha * deltaG
# test convergence
if it >= numItermax:
loop = 0
delta_fval = (f_val - old_fval) / abs(f_val)
if abs(delta_fval) < stopThr:
loop = 0
if log:
log['loss'].append(f_val)
if verbose:
if it % 20 == 0:
print('{:5s}|{:12s}|{:8s}'.format(
'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32)
print('{:5d}|{:8e}|{:8e}'.format(it, f_val, delta_fval))
if log:
return G, log
else:
return G | 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 = arg\min_\gamma <\gamma,M>_F + reg1\cdot\Omega(\gamma) + reg2\cdot f(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`f` is the regularization term ( and df is its gradient)
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalized conditional gradient as discussed in [5,7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg1 : float
Entropic Regularization term >0
reg2 : float
Second Regularization term >0
G0 : np.ndarray (ns,nt), optional
initial guess (default is indep joint density)
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations of Sinkhorn
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.optim.cg : conditional gradient
"""
loop = 1
if log:
log = {'loss': []}
if G0 is None:
G = np.outer(a, b)
else:
G = G0
def cost(G):
return np.sum(M * G) + reg1 * np.sum(G * np.log(G)) + reg2 * f(G)
f_val = cost(G)
if log:
log['loss'].append(f_val)
it = 0
if verbose:
print('{:5s}|{:12s}|{:8s}'.format(
'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32)
print('{:5d}|{:8e}|{:8e}'.format(it, f_val, 0))
while loop:
it += 1
old_fval = f_val
# problem linearization
Mi = M + reg2 * df(G)
# solve linear program with Sinkhorn
# Gc = sinkhorn_stabilized(a,b, Mi, reg1, numItermax = numInnerItermax)
Gc = sinkhorn(a, b, Mi, reg1, numItermax=numInnerItermax)
deltaG = Gc - G
# line search
dcost = Mi + reg1 * (1 + np.log(G)) # ??
alpha, fc, f_val = line_search_armijo(cost, G, deltaG, dcost, f_val)
G = G + alpha * deltaG
# test convergence
if it >= numItermax:
loop = 0
delta_fval = (f_val - old_fval) / abs(f_val)
if abs(delta_fval) < stopThr:
loop = 0
if log:
log['loss'].append(f_val)
if verbose:
if it % 20 == 0:
print('{:5s}|{:12s}|{:8s}'.format(
'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32)
print('{:5d}|{:8e}|{:8e}'.format(it, f_val, delta_fval))
if log:
return G, log
else:
return G | [
"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
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`f` is the regularization term ( and df is its gradient)
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalized conditional gradient as discussed in [5,7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg1 : float
Entropic Regularization term >0
reg2 : float
Second Regularization term >0
G0 : np.ndarray (ns,nt), optional
initial guess (default is indep joint density)
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations of Sinkhorn
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.optim.cg : conditional gradient | [
"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 | 221,966 |
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: project each V[i] by P(V[i]; z[i])
- axis=0: project each V[:, j] by P(V[:, j]; z[j])
"""
if axis == 1:
n_features = V.shape[1]
U = np.sort(V, axis=1)[:, ::-1]
z = np.ones(len(V)) * z
cssv = np.cumsum(U, axis=1) - z[:, np.newaxis]
ind = np.arange(n_features) + 1
cond = U - cssv / ind > 0
rho = np.count_nonzero(cond, axis=1)
theta = cssv[np.arange(len(V)), rho - 1] / rho
return np.maximum(V - theta[:, np.newaxis], 0)
elif axis == 0:
return projection_simplex(V.T, z, axis=1).T
else:
V = V.ravel().reshape(1, -1)
return projection_simplex(V, z, axis=1).ravel() | 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: project each V[i] by P(V[i]; z[i])
- axis=0: project each V[:, j] by P(V[:, j]; z[j])
"""
if axis == 1:
n_features = V.shape[1]
U = np.sort(V, axis=1)[:, ::-1]
z = np.ones(len(V)) * z
cssv = np.cumsum(U, axis=1) - z[:, np.newaxis]
ind = np.arange(n_features) + 1
cond = U - cssv / ind > 0
rho = np.count_nonzero(cond, axis=1)
theta = cssv[np.arange(len(V)), rho - 1] / rho
return np.maximum(V - theta[:, np.newaxis], 0)
elif axis == 0:
return projection_simplex(V.T, z, axis=1).T
else:
V = V.ravel().reshape(1, -1)
return projection_simplex(V, z, axis=1).ravel() | [
"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: project each V[:, j] by P(V[:, j]; z[j]) | [
"Projection",
"of",
"x",
"onto",
"the",
"simplex",
"scaled",
"by",
"z"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L47-L74 | train | 221,967 |
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)
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 delta_Omega(X) method.
Returns
-------
obj: float
Objective value (higher is better).
grad_alpha: array, shape = len(a)
Gradient w.r.t. alpha.
grad_beta: array, shape = len(b)
Gradient w.r.t. beta.
"""
obj = np.dot(alpha, a) + np.dot(beta, b)
grad_alpha = a.copy()
grad_beta = b.copy()
# X[:, j] = alpha + beta[j] - C[:, j]
X = alpha[:, np.newaxis] + beta - C
# val.shape = len(b)
# G.shape = len(a) x len(b)
val, G = regul.delta_Omega(X)
obj -= np.sum(val)
grad_alpha -= G.sum(axis=1)
grad_beta -= G.sum(axis=0)
return obj, grad_alpha, grad_beta | 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)
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 delta_Omega(X) method.
Returns
-------
obj: float
Objective value (higher is better).
grad_alpha: array, shape = len(a)
Gradient w.r.t. alpha.
grad_beta: array, shape = len(b)
Gradient w.r.t. beta.
"""
obj = np.dot(alpha, a) + np.dot(beta, b)
grad_alpha = a.copy()
grad_beta = b.copy()
# X[:, j] = alpha + beta[j] - C[:, j]
X = alpha[:, np.newaxis] + beta - C
# val.shape = len(b)
# G.shape = len(a) x len(b)
val, G = regul.delta_Omega(X)
obj -= np.sum(val)
grad_alpha -= G.sum(axis=1)
grad_beta -= G.sum(axis=0)
return obj, grad_alpha, grad_beta | [
"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).
C: array, shape = len(a) x len(b)
Ground cost matrix.
regul: Regularization object
Should implement a delta_Omega(X) method.
Returns
-------
obj: float
Objective value (higher is better).
grad_alpha: array, shape = len(a)
Gradient w.r.t. alpha.
grad_beta: array, shape = len(b)
Gradient w.r.t. beta. | [
"Compute",
"objective",
"value",
"and",
"gradients",
"of",
"dual",
"objective",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L192-L233 | train | 221,968 |
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, shape = len(a) x len(b)
Ground cost matrix.
regul: Regularization object
Should implement a delta_Omega(X) method.
method: str
Solver to be used (passed to `scipy.optimize.minimize`).
tol: float
Tolerance parameter.
max_iter: int
Maximum number of iterations.
Returns
-------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Dual potentials.
"""
def _func(params):
# Unpack alpha and beta.
alpha = params[:len(a)]
beta = params[len(a):]
obj, grad_alpha, grad_beta = dual_obj_grad(alpha, beta, a, b, C, regul)
# Pack grad_alpha and grad_beta.
grad = np.concatenate((grad_alpha, grad_beta))
# We need to maximize the dual.
return -obj, -grad
# Unfortunately, `minimize` only supports functions whose argument is a
# vector. So, we need to concatenate alpha and beta.
alpha_init = np.zeros(len(a))
beta_init = np.zeros(len(b))
params_init = np.concatenate((alpha_init, beta_init))
res = minimize(_func, params_init, method=method, jac=True,
tol=tol, options=dict(maxiter=max_iter, disp=verbose))
alpha = res.x[:len(a)]
beta = res.x[len(a):]
return alpha, beta, res | 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, shape = len(a) x len(b)
Ground cost matrix.
regul: Regularization object
Should implement a delta_Omega(X) method.
method: str
Solver to be used (passed to `scipy.optimize.minimize`).
tol: float
Tolerance parameter.
max_iter: int
Maximum number of iterations.
Returns
-------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Dual potentials.
"""
def _func(params):
# Unpack alpha and beta.
alpha = params[:len(a)]
beta = params[len(a):]
obj, grad_alpha, grad_beta = dual_obj_grad(alpha, beta, a, b, C, regul)
# Pack grad_alpha and grad_beta.
grad = np.concatenate((grad_alpha, grad_beta))
# We need to maximize the dual.
return -obj, -grad
# Unfortunately, `minimize` only supports functions whose argument is a
# vector. So, we need to concatenate alpha and beta.
alpha_init = np.zeros(len(a))
beta_init = np.zeros(len(b))
params_init = np.concatenate((alpha_init, beta_init))
res = minimize(_func, params_init, method=method, jac=True,
tol=tol, options=dict(maxiter=max_iter, disp=verbose))
alpha = res.x[:len(a)]
beta = res.x[len(a):]
return alpha, beta, res | [
"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 delta_Omega(X) method.
method: str
Solver to be used (passed to `scipy.optimize.minimize`).
tol: float
Tolerance parameter.
max_iter: int
Maximum number of iterations.
Returns
-------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Dual potentials. | [
"Solve",
"the",
"smoothed",
"dual",
"objective",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L236-L289 | train | 221,969 |
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 (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 max_Omega(X) method.
Returns
-------
obj: float
Objective value (higher is better).
grad: array, shape = len(a)
Gradient w.r.t. alpha.
"""
obj = np.dot(alpha, a)
grad = a.copy()
# X[:, j] = alpha - C[:, j]
X = alpha[:, np.newaxis] - C
# val.shape = len(b)
# G.shape = len(a) x len(b)
val, G = regul.max_Omega(X, b)
obj -= np.dot(b, val)
grad -= np.dot(G, b)
return obj, grad | 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 (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 max_Omega(X) method.
Returns
-------
obj: float
Objective value (higher is better).
grad: array, shape = len(a)
Gradient w.r.t. alpha.
"""
obj = np.dot(alpha, a)
grad = a.copy()
# X[:, j] = alpha - C[:, j]
X = alpha[:, np.newaxis] - C
# val.shape = len(b)
# G.shape = len(a) x len(b)
val, G = regul.max_Omega(X, b)
obj -= np.dot(b, val)
grad -= np.dot(G, b)
return obj, grad | [
"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 = len(a) x len(b)
Ground cost matrix.
regul: Regularization object
Should implement a max_Omega(X) method.
Returns
-------
obj: float
Objective value (higher is better).
grad: array, shape = len(a)
Gradient w.r.t. alpha. | [
"Compute",
"objective",
"value",
"and",
"gradient",
"of",
"semi",
"-",
"dual",
"objective",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L292-L328 | train | 221,970 |
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).
C: array, shape = len(a) x len(b)
Ground cost matrix.
regul: Regularization object
Should implement a max_Omega(X) method.
method: str
Solver to be used (passed to `scipy.optimize.minimize`).
tol: float
Tolerance parameter.
max_iter: int
Maximum number of iterations.
Returns
-------
alpha: array, shape = len(a)
Semi-dual potentials.
"""
def _func(alpha):
obj, grad = semi_dual_obj_grad(alpha, a, b, C, regul)
# We need to maximize the semi-dual.
return -obj, -grad
alpha_init = np.zeros(len(a))
res = minimize(_func, alpha_init, method=method, jac=True,
tol=tol, options=dict(maxiter=max_iter, disp=verbose))
return res.x, res | 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).
C: array, shape = len(a) x len(b)
Ground cost matrix.
regul: Regularization object
Should implement a max_Omega(X) method.
method: str
Solver to be used (passed to `scipy.optimize.minimize`).
tol: float
Tolerance parameter.
max_iter: int
Maximum number of iterations.
Returns
-------
alpha: array, shape = len(a)
Semi-dual potentials.
"""
def _func(alpha):
obj, grad = semi_dual_obj_grad(alpha, a, b, C, regul)
# We need to maximize the semi-dual.
return -obj, -grad
alpha_init = np.zeros(len(a))
res = minimize(_func, alpha_init, method=method, jac=True,
tol=tol, options=dict(maxiter=max_iter, disp=verbose))
return res.x, res | [
"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 max_Omega(X) method.
method: str
Solver to be used (passed to `scipy.optimize.minimize`).
tol: float
Tolerance parameter.
max_iter: int
Maximum number of iterations.
Returns
-------
alpha: array, shape = len(a)
Semi-dual potentials. | [
"Solve",
"the",
"smoothed",
"semi",
"-",
"dual",
"objective",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L331-L368 | train | 221,971 |
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.
regul: Regularization object
Should implement a delta_Omega(X) method.
Returns
-------
T: array, shape = len(a) x len(b)
Optimal transportation plan.
"""
X = alpha[:, np.newaxis] + beta - C
return regul.delta_Omega(X)[1] | 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.
regul: Regularization object
Should implement a delta_Omega(X) method.
Returns
-------
T: array, shape = len(a) x len(b)
Optimal transportation plan.
"""
X = alpha[:, np.newaxis] + beta - C
return regul.delta_Omega(X)[1] | [
"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 a delta_Omega(X) method.
Returns
-------
T: array, shape = len(a) x len(b)
Optimal transportation plan. | [
"Retrieve",
"optimal",
"transportation",
"plan",
"from",
"optimal",
"dual",
"potentials",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L371-L391 | train | 221,972 |
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 and sum to 1).
C: array, shape = len(a) x len(b)
Ground cost matrix.
regul: Regularization object
Should implement a delta_Omega(X) method.
Returns
-------
T: array, shape = len(a) x len(b)
Optimal transportation plan.
"""
X = alpha[:, np.newaxis] - C
return regul.max_Omega(X, b)[1] * b | 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 and sum to 1).
C: array, shape = len(a) x len(b)
Ground cost matrix.
regul: Regularization object
Should implement a delta_Omega(X) method.
Returns
-------
T: array, shape = len(a) x len(b)
Optimal transportation plan.
"""
X = alpha[:, np.newaxis] - C
return regul.max_Omega(X, b)[1] * b | [
"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)
Ground cost matrix.
regul: Regularization object
Should implement a delta_Omega(X) method.
Returns
-------
T: array, shape = len(a) x len(b)
Optimal transportation plan. | [
"Retrieve",
"optimal",
"transportation",
"plan",
"from",
"optimal",
"semi",
"-",
"dual",
"potentials",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L394-L415 | train | 221,973 |
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::
\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 jth column of the cost matrix
- :math:`\delta_\Omega` is the convex conjugate of the regularization term :math:`\Omega`
- a and b are source and target weights (sum to 1)
The OT matrix can is reconstructed from the gradient of :math:`\delta_\Omega`
(See [17]_ Proposition 1).
The optimization algorithm is using gradient decent (L-BFGS by default).
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
reg_type : str
Regularization type, can be the following (default ='l2'):
- 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_)
- 'l2' : Squared Euclidean regularization
method : str
Solver to use for scipy.optimize.minimize
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS).
See Also
--------
ot.lp.emd : Unregularized OT
ot.sinhorn : Entropic regularized OT
ot.optim.cg : General regularized OT
"""
if reg_type.lower() in ['l2', 'squaredl2']:
regul = SquaredL2(gamma=reg)
elif reg_type.lower() in ['entropic', 'negentropy', 'kl']:
regul = NegEntropy(gamma=reg)
else:
raise NotImplementedError('Unknown regularization')
# solve dual
alpha, beta, res = solve_dual(a, b, M, regul, max_iter=numItermax,
tol=stopThr, verbose=verbose)
# reconstruct transport matrix
G = get_plan_from_dual(alpha, beta, M, regul)
if log:
log = {'alpha': alpha, 'beta': beta, 'res': res}
return G, log
else:
return G | 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::
\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 jth column of the cost matrix
- :math:`\delta_\Omega` is the convex conjugate of the regularization term :math:`\Omega`
- a and b are source and target weights (sum to 1)
The OT matrix can is reconstructed from the gradient of :math:`\delta_\Omega`
(See [17]_ Proposition 1).
The optimization algorithm is using gradient decent (L-BFGS by default).
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
reg_type : str
Regularization type, can be the following (default ='l2'):
- 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_)
- 'l2' : Squared Euclidean regularization
method : str
Solver to use for scipy.optimize.minimize
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS).
See Also
--------
ot.lp.emd : Unregularized OT
ot.sinhorn : Entropic regularized OT
ot.optim.cg : General regularized OT
"""
if reg_type.lower() in ['l2', 'squaredl2']:
regul = SquaredL2(gamma=reg)
elif reg_type.lower() in ['entropic', 'negentropy', 'kl']:
regul = NegEntropy(gamma=reg)
else:
raise NotImplementedError('Unknown regularization')
# solve dual
alpha, beta, res = solve_dual(a, b, M, regul, max_iter=numItermax,
tol=stopThr, verbose=verbose)
# reconstruct transport matrix
G = get_plan_from_dual(alpha, beta, M, regul)
if log:
log = {'alpha': alpha, 'beta': beta, 'res': res}
return G, log
else:
return G | [
"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 jth column of the cost matrix
- :math:`\delta_\Omega` is the convex conjugate of the regularization term :math:`\Omega`
- a and b are source and target weights (sum to 1)
The OT matrix can is reconstructed from the gradient of :math:`\delta_\Omega`
(See [17]_ Proposition 1).
The optimization algorithm is using gradient decent (L-BFGS by default).
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
reg_type : str
Regularization type, can be the following (default ='l2'):
- 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_)
- 'l2' : Squared Euclidean regularization
method : str
Solver to use for scipy.optimize.minimize
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS).
See Also
--------
ot.lp.emd : Unregularized OT
ot.sinhorn : Entropic regularized OT
ot.optim.cg : General regularized OT | [
"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 | 221,974 |
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]_ :
.. math::
\max_{\alpha}\quad a^T\alpha-OT_\Omega^*(\alpha,b)
where :
.. math::
OT_\Omega^*(\alpha,b)=\sum_j b_j
- :math:`\mathbf{m}_j` is the jth column of the cost matrix
- :math:`OT_\Omega^*(\alpha,b)` is defined in Eq. (9) in [17]
- a and b are source and target weights (sum to 1)
The OT matrix can is reconstructed using [17]_ Proposition 2.
The optimization algorithm is using gradient decent (L-BFGS by default).
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
reg_type : str
Regularization type, can be the following (default ='l2'):
- 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_)
- 'l2' : Squared Euclidean regularization
method : str
Solver to use for scipy.optimize.minimize
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS).
See Also
--------
ot.lp.emd : Unregularized OT
ot.sinhorn : Entropic regularized OT
ot.optim.cg : General regularized OT
"""
if reg_type.lower() in ['l2', 'squaredl2']:
regul = SquaredL2(gamma=reg)
elif reg_type.lower() in ['entropic', 'negentropy', 'kl']:
regul = NegEntropy(gamma=reg)
else:
raise NotImplementedError('Unknown regularization')
# solve dual
alpha, res = solve_semi_dual(a, b, M, regul, max_iter=numItermax,
tol=stopThr, verbose=verbose)
# reconstruct transport matrix
G = get_plan_from_semi_dual(alpha, b, M, regul)
if log:
log = {'alpha': alpha, 'res': res}
return G, log
else:
return G | 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]_ :
.. math::
\max_{\alpha}\quad a^T\alpha-OT_\Omega^*(\alpha,b)
where :
.. math::
OT_\Omega^*(\alpha,b)=\sum_j b_j
- :math:`\mathbf{m}_j` is the jth column of the cost matrix
- :math:`OT_\Omega^*(\alpha,b)` is defined in Eq. (9) in [17]
- a and b are source and target weights (sum to 1)
The OT matrix can is reconstructed using [17]_ Proposition 2.
The optimization algorithm is using gradient decent (L-BFGS by default).
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
reg_type : str
Regularization type, can be the following (default ='l2'):
- 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_)
- 'l2' : Squared Euclidean regularization
method : str
Solver to use for scipy.optimize.minimize
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS).
See Also
--------
ot.lp.emd : Unregularized OT
ot.sinhorn : Entropic regularized OT
ot.optim.cg : General regularized OT
"""
if reg_type.lower() in ['l2', 'squaredl2']:
regul = SquaredL2(gamma=reg)
elif reg_type.lower() in ['entropic', 'negentropy', 'kl']:
regul = NegEntropy(gamma=reg)
else:
raise NotImplementedError('Unknown regularization')
# solve dual
alpha, res = solve_semi_dual(a, b, M, regul, max_iter=numItermax,
tol=stopThr, verbose=verbose)
# reconstruct transport matrix
G = get_plan_from_semi_dual(alpha, b, M, regul)
if log:
log = {'alpha': alpha, 'res': res}
return G, log
else:
return G | [
"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:`\mathbf{m}_j` is the jth column of the cost matrix
- :math:`OT_\Omega^*(\alpha,b)` is defined in Eq. (9) in [17]
- a and b are source and target weights (sum to 1)
The OT matrix can is reconstructed using [17]_ Proposition 2.
The optimization algorithm is using gradient decent (L-BFGS by default).
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
reg_type : str
Regularization type, can be the following (default ='l2'):
- 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_)
- 'l2' : Squared Euclidean regularization
method : str
Solver to use for scipy.optimize.minimize
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS).
See Also
--------
ot.lp.emd : Unregularized OT
ot.sinhorn : Entropic regularized OT
ot.optim.cg : General regularized OT | [
"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 | 221,975 |
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 | 221,976 |
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 | 221,977 |
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 None then x2=x1)
metric : str, fun, optional
name of the metric to be computed (full list in the doc of scipy), If a string,
the distance function can be 'braycurtis', 'canberra', 'chebyshev', 'cityblock',
'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski',
'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean',
'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', 'yule'.
Returns
-------
M : np.array (n1,n2)
distance matrix computed with given metric
"""
if x2 is None:
x2 = x1
if metric == "sqeuclidean":
return euclidean_distances(x1, x2, squared=True)
return cdist(x1, x2, metric=metric) | 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 None then x2=x1)
metric : str, fun, optional
name of the metric to be computed (full list in the doc of scipy), If a string,
the distance function can be 'braycurtis', 'canberra', 'chebyshev', 'cityblock',
'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski',
'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean',
'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', 'yule'.
Returns
-------
M : np.array (n1,n2)
distance matrix computed with given metric
"""
if x2 is None:
x2 = x1
if metric == "sqeuclidean":
return euclidean_distances(x1, x2, squared=True)
return cdist(x1, x2, metric=metric) | [
"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
name of the metric to be computed (full list in the doc of scipy), If a string,
the distance function can be 'braycurtis', 'canberra', 'chebyshev', 'cityblock',
'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski',
'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean',
'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', 'yule'.
Returns
-------
M : np.array (n1,n2)
distance matrix computed with given metric | [
"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 | 221,978 |
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
-------
C : np.array (n1, n2)
The input cost matrix normalized according to given norm.
"""
if norm == "median":
C /= float(np.median(C))
elif norm == "max":
C /= float(np.max(C))
elif norm == "log":
C = np.log(1 + C)
elif norm == "loglog":
C = np.log(1 + np.log(1 + C))
return C | 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
-------
C : np.array (n1, n2)
The input cost matrix normalized according to given norm.
"""
if norm == "median":
C /= float(np.median(C))
elif norm == "max":
C /= float(np.max(C))
elif norm == "log":
C = np.log(1 + C)
elif norm == "loglog":
C = np.log(1 + np.log(1 + C))
return C | [
"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)
The input cost matrix normalized according to given norm. | [
"Apply",
"normalization",
"to",
"the",
"loss",
"matrix"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L169-L199 | train | 221,979 |
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 = True
p.start()
sent = [q_in.put((i, x)) for i, x in enumerate(X)]
[q_in.put((None, None)) for _ in range(nprocs)]
res = [q_out.get() for _ in range(len(sent))]
[p.join() for p in proc]
return [x for i, x in sorted(res)] | 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 = True
p.start()
sent = [q_in.put((i, x)) for i, x in enumerate(X)]
[q_in.put((None, None)) for _ in range(nprocs)]
res = [q_out.get() for _ in range(len(sent))]
[p.join() for p in proc]
return [x for i, x in sorted(res)] | [
"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 | 221,980 |
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 None:
closures = []
is_deprecated = ('deprecated' in ''.join([c.cell_contents
for c in closures
if isinstance(c.cell_contents, str)]))
return is_deprecated | 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 None:
closures = []
is_deprecated = ('deprecated' in ''.join([c.cell_contents
for c in closures
if isinstance(c.cell_contents, str)]))
return is_deprecated | [
"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 | 221,981 |
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, **kwargs)
wrapped.__name__ = fun.__name__
wrapped.__dict__ = fun.__dict__
wrapped.__doc__ = self._update_doc(fun.__doc__)
return wrapped | 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, **kwargs)
wrapped.__name__ = fun.__name__
wrapped.__dict__ = fun.__dict__
wrapped.__doc__ = self._update_doc(fun.__doc__)
return wrapped | [
"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 | 221,982 |
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 | 221,983 |
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
Regularization term >0 (ridge regularization)
Returns
-------
P : (d x p) ndarray
Optimal transportation matrix for the given parameters
proj : fun
projection function including mean centering
"""
mx = np.mean(X)
X -= mx.reshape((1, -1))
# data split between classes
d = X.shape[1]
xc = split_classes(X, y)
nc = len(xc)
p = min(nc - 1, p)
Cw = 0
for x in xc:
Cw += np.cov(x, rowvar=False)
Cw /= nc
mxc = np.zeros((d, nc))
for i in range(nc):
mxc[:, i] = np.mean(xc[i])
mx0 = np.mean(mxc, 1)
Cb = 0
for i in range(nc):
Cb += (mxc[:, i] - mx0).reshape((-1, 1)) * \
(mxc[:, i] - mx0).reshape((1, -1))
w, V = linalg.eig(Cb, Cw + reg * np.eye(d))
idx = np.argsort(w.real)
Popt = V[:, idx[-p:]]
def proj(X):
return (X - mx.reshape((1, -1))).dot(Popt)
return Popt, proj | 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
Regularization term >0 (ridge regularization)
Returns
-------
P : (d x p) ndarray
Optimal transportation matrix for the given parameters
proj : fun
projection function including mean centering
"""
mx = np.mean(X)
X -= mx.reshape((1, -1))
# data split between classes
d = X.shape[1]
xc = split_classes(X, y)
nc = len(xc)
p = min(nc - 1, p)
Cw = 0
for x in xc:
Cw += np.cov(x, rowvar=False)
Cw /= nc
mxc = np.zeros((d, nc))
for i in range(nc):
mxc[:, i] = np.mean(xc[i])
mx0 = np.mean(mxc, 1)
Cb = 0
for i in range(nc):
Cb += (mxc[:, i] - mx0).reshape((-1, 1)) * \
(mxc[:, i] - mx0).reshape((1, -1))
w, V = linalg.eig(Cb, Cw + reg * np.eye(d))
idx = np.argsort(w.real)
Popt = V[:, idx[-p:]]
def proj(X):
return (X - mx.reshape((1, -1))).dot(Popt)
return Popt, proj | [
"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)
Returns
-------
P : (d x p) ndarray
Optimal transportation matrix for the given parameters
proj : fun
projection function including mean centering | [
"Fisher",
"Discriminant",
"Analysis"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/dr.py#L45-L107 | train | 221,984 |
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\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1 = b
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the SAG algorithm
as proposed in [18]_ [alg.1]
Parameters
----------
a : np.ndarray(ns,),
source measure
b : np.ndarray(nt,),
target measure
M : np.ndarray(ns, nt),
cost matrix
reg : float number,
Regularization term > 0
numItermax : int number
number of iteration
lr : float number
learning rate
Returns
-------
v : np.ndarray(nt,)
dual variable
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
method, numItermax)
>>> print(asgd_pi)
References
----------
[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.
'''
if lr is None:
lr = 1. / max(a / reg)
n_source = np.shape(M)[0]
n_target = np.shape(M)[1]
cur_beta = np.zeros(n_target)
stored_gradient = np.zeros((n_source, n_target))
sum_stored_gradient = np.zeros(n_target)
for _ in range(numItermax):
i = np.random.randint(n_source)
cur_coord_grad = a[i] * coordinate_grad_semi_dual(b, M, reg,
cur_beta, i)
sum_stored_gradient += (cur_coord_grad - stored_gradient[i])
stored_gradient[i] = cur_coord_grad
cur_beta += lr * (1. / n_source) * sum_stored_gradient
return cur_beta | 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\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1 = b
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the SAG algorithm
as proposed in [18]_ [alg.1]
Parameters
----------
a : np.ndarray(ns,),
source measure
b : np.ndarray(nt,),
target measure
M : np.ndarray(ns, nt),
cost matrix
reg : float number,
Regularization term > 0
numItermax : int number
number of iteration
lr : float number
learning rate
Returns
-------
v : np.ndarray(nt,)
dual variable
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
method, numItermax)
>>> print(asgd_pi)
References
----------
[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.
'''
if lr is None:
lr = 1. / max(a / reg)
n_source = np.shape(M)[0]
n_target = np.shape(M)[1]
cur_beta = np.zeros(n_target)
stored_gradient = np.zeros((n_source, n_target))
sum_stored_gradient = np.zeros(n_target)
for _ in range(numItermax):
i = np.random.randint(n_source)
cur_coord_grad = a[i] * coordinate_grad_semi_dual(b, M, reg,
cur_beta, i)
sum_stored_gradient += (cur_coord_grad - stored_gradient[i])
stored_gradient[i] = cur_coord_grad
cur_beta += lr * (1. / n_source) * sum_stored_gradient
return cur_beta | [
"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
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the SAG algorithm
as proposed in [18]_ [alg.1]
Parameters
----------
a : np.ndarray(ns,),
source measure
b : np.ndarray(nt,),
target measure
M : np.ndarray(ns, nt),
cost matrix
reg : float number,
Regularization term > 0
numItermax : int number
number of iteration
lr : float number
learning rate
Returns
-------
v : np.ndarray(nt,)
dual variable
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
method, numItermax)
>>> print(asgd_pi)
References
----------
[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527. | [
"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 | 221,985 |
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 + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the ASGD algorithm
as proposed in [18]_ [alg.2]
Parameters
----------
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
numItermax : int number
number of iteration
lr : float number
learning rate
Returns
-------
ave_v : np.ndarray(nt,)
dual variable
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
method, numItermax)
>>> print(asgd_pi)
References
----------
[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.
'''
if lr is None:
lr = 1. / max(a / reg)
n_source = np.shape(M)[0]
n_target = np.shape(M)[1]
cur_beta = np.zeros(n_target)
ave_beta = np.zeros(n_target)
for cur_iter in range(numItermax):
k = cur_iter + 1
i = np.random.randint(n_source)
cur_coord_grad = coordinate_grad_semi_dual(b, M, reg, cur_beta, i)
cur_beta += (lr / np.sqrt(k)) * cur_coord_grad
ave_beta = (1. / k) * cur_beta + (1 - 1. / k) * ave_beta
return ave_beta | 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 + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the ASGD algorithm
as proposed in [18]_ [alg.2]
Parameters
----------
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
numItermax : int number
number of iteration
lr : float number
learning rate
Returns
-------
ave_v : np.ndarray(nt,)
dual variable
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
method, numItermax)
>>> print(asgd_pi)
References
----------
[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.
'''
if lr is None:
lr = 1. / max(a / reg)
n_source = np.shape(M)[0]
n_target = np.shape(M)[1]
cur_beta = np.zeros(n_target)
ave_beta = np.zeros(n_target)
for cur_iter in range(numItermax):
k = cur_iter + 1
i = np.random.randint(n_source)
cur_coord_grad = coordinate_grad_semi_dual(b, M, reg, cur_beta, i)
cur_beta += (lr / np.sqrt(k)) * cur_coord_grad
ave_beta = (1. / k) * cur_beta + (1 - 1. / k) * ave_beta
return ave_beta | [
"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
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the ASGD algorithm
as proposed in [18]_ [alg.2]
Parameters
----------
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
numItermax : int number
number of iteration
lr : float number
learning rate
Returns
-------
ave_v : np.ndarray(nt,)
dual variable
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
method, numItermax)
>>> print(asgd_pi)
References
----------
[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527. | [
"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 | 221,986 |
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 matrix
- u, v are dual variables in R^IxR^J
- reg is the regularization term
It is used to recover an optimal u from optimal v solving the semi dual
problem, see Proposition 2.1 of [18]_
Parameters
----------
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float
regularization term > 0
v : np.ndarray(nt,)
dual variable
Returns
-------
u : np.ndarray(ns,)
dual variable
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
method, numItermax)
>>> print(asgd_pi)
References
----------
[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.
'''
n_source = np.shape(M)[0]
alpha = np.zeros(n_source)
for i in range(n_source):
r = M[i, :] - beta
min_r = np.min(r)
exp_beta = np.exp(-(r - min_r) / reg) * b
alpha[i] = min_r - reg * np.log(np.sum(exp_beta))
return alpha | 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 matrix
- u, v are dual variables in R^IxR^J
- reg is the regularization term
It is used to recover an optimal u from optimal v solving the semi dual
problem, see Proposition 2.1 of [18]_
Parameters
----------
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float
regularization term > 0
v : np.ndarray(nt,)
dual variable
Returns
-------
u : np.ndarray(ns,)
dual variable
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
method, numItermax)
>>> print(asgd_pi)
References
----------
[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.
'''
n_source = np.shape(M)[0]
alpha = np.zeros(n_source)
for i in range(n_source):
r = M[i, :] - beta
min_r = np.min(r)
exp_beta = np.exp(-(r - min_r) / reg) * b
alpha[i] = min_r - reg * np.log(np.sum(exp_beta))
return alpha | [
"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
- reg is the regularization term
It is used to recover an optimal u from optimal v solving the semi dual
problem, see Proposition 2.1 of [18]_
Parameters
----------
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float
regularization term > 0
v : np.ndarray(nt,)
dual variable
Returns
-------
u : np.ndarray(ns,)
dual variable
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
method, numItermax)
>>> print(asgd_pi)
References
----------
[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527. | [
"The",
"goal",
"is",
"to",
"recover",
"u",
"from",
"the",
"c",
"-",
"transform",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L266-L338 | train | 221,987 |
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:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the SAG or ASGD algorithms
as proposed in [18]_
Parameters
----------
a : np.ndarray(ns,)
source measure
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
methode : str
used method (SAG or ASGD)
numItermax : int number
number of iteration
lr : float number
learning rate
n_source : int number
size of the source measure
n_target : int number
size of the target measure
log : bool, optional
record log if True
Returns
-------
pi : np.ndarray(ns, nt)
transportation matrix
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
method, numItermax)
>>> print(asgd_pi)
References
----------
[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.
'''
if method.lower() == "sag":
opt_beta = sag_entropic_transport(a, b, M, reg, numItermax, lr)
elif method.lower() == "asgd":
opt_beta = averaged_sgd_entropic_transport(a, b, M, reg, numItermax, lr)
else:
print("Please, select your method between SAG and ASGD")
return None
opt_alpha = c_transform_entropic(b, M, reg, opt_beta)
pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) *
a[:, None] * b[None, :])
if log:
log = {}
log['alpha'] = opt_alpha
log['beta'] = opt_beta
return pi, log
else:
return pi | 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:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the SAG or ASGD algorithms
as proposed in [18]_
Parameters
----------
a : np.ndarray(ns,)
source measure
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
methode : str
used method (SAG or ASGD)
numItermax : int number
number of iteration
lr : float number
learning rate
n_source : int number
size of the source measure
n_target : int number
size of the target measure
log : bool, optional
record log if True
Returns
-------
pi : np.ndarray(ns, nt)
transportation matrix
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
method, numItermax)
>>> print(asgd_pi)
References
----------
[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.
'''
if method.lower() == "sag":
opt_beta = sag_entropic_transport(a, b, M, reg, numItermax, lr)
elif method.lower() == "asgd":
opt_beta = averaged_sgd_entropic_transport(a, b, M, reg, numItermax, lr)
else:
print("Please, select your method between SAG and ASGD")
return None
opt_alpha = c_transform_entropic(b, M, reg, opt_beta)
pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) *
a[:, None] * b[None, :])
if log:
log = {}
log['alpha'] = opt_alpha
log['beta'] = opt_beta
return pi, log
else:
return pi | [
"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
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the SAG or ASGD algorithms
as proposed in [18]_
Parameters
----------
a : np.ndarray(ns,)
source measure
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
methode : str
used method (SAG or ASGD)
numItermax : int number
number of iteration
lr : float number
learning rate
n_source : int number
size of the source measure
n_target : int number
size of the target measure
log : bool, optional
record log if True
Returns
-------
pi : np.ndarray(ns, nt)
transportation matrix
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
method, numItermax)
>>> print(asgd_pi)
References
----------
[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527. | [
"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 | 221,988 |
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} - \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 \in B_u} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j
Where :
- M is the (ns,nt) metric cost matrix
- u, v are dual variables in R^ixR^J
- reg is the regularization term
- :math:`B_u` and :math:`B_v` are lists of index
- :math:`b_s` is the size of the batchs :math:`B_u` and :math:`B_v`
- :math:`l_u` and :math:`l_v` are the lenghts of :math:`B_u` and :math:`B_v`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the dual problem is the SGD algorithm
as proposed in [19]_ [alg.1]
Parameters
----------
a : np.ndarray(ns,)
source measure
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
alpha : np.ndarray(ns,)
dual variable
beta : np.ndarray(nt,)
dual variable
batch_size : int number
size of the batch
batch_alpha : np.ndarray(bs,)
batch of index of alpha
batch_beta : np.ndarray(bs,)
batch of index of beta
Returns
-------
grad : np.ndarray(ns,)
partial grad F
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 20000
>>> lr = 0.1
>>> batch_size = 3
>>> log = True
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg,
batch_size,
numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)
References
----------
[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283.
'''
G = - (np.exp((alpha[batch_alpha, None] + beta[None, batch_beta] -
M[batch_alpha, :][:, batch_beta]) / reg) *
a[batch_alpha, None] * b[None, batch_beta])
grad_beta = np.zeros(np.shape(M)[1])
grad_alpha = np.zeros(np.shape(M)[0])
grad_beta[batch_beta] = (b[batch_beta] * len(batch_alpha) / np.shape(M)[0]
+ G.sum(0))
grad_alpha[batch_alpha] = (a[batch_alpha] * len(batch_beta)
/ np.shape(M)[1] + G.sum(1))
return grad_alpha, grad_beta | 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} - \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 \in B_u} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j
Where :
- M is the (ns,nt) metric cost matrix
- u, v are dual variables in R^ixR^J
- reg is the regularization term
- :math:`B_u` and :math:`B_v` are lists of index
- :math:`b_s` is the size of the batchs :math:`B_u` and :math:`B_v`
- :math:`l_u` and :math:`l_v` are the lenghts of :math:`B_u` and :math:`B_v`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the dual problem is the SGD algorithm
as proposed in [19]_ [alg.1]
Parameters
----------
a : np.ndarray(ns,)
source measure
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
alpha : np.ndarray(ns,)
dual variable
beta : np.ndarray(nt,)
dual variable
batch_size : int number
size of the batch
batch_alpha : np.ndarray(bs,)
batch of index of alpha
batch_beta : np.ndarray(bs,)
batch of index of beta
Returns
-------
grad : np.ndarray(ns,)
partial grad F
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 20000
>>> lr = 0.1
>>> batch_size = 3
>>> log = True
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg,
batch_size,
numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)
References
----------
[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283.
'''
G = - (np.exp((alpha[batch_alpha, None] + beta[None, batch_beta] -
M[batch_alpha, :][:, batch_beta]) / reg) *
a[batch_alpha, None] * b[None, batch_beta])
grad_beta = np.zeros(np.shape(M)[1])
grad_alpha = np.zeros(np.shape(M)[0])
grad_beta[batch_beta] = (b[batch_beta] * len(batch_alpha) / np.shape(M)[0]
+ G.sum(0))
grad_alpha[batch_alpha] = (a[batch_alpha] * len(batch_beta)
/ np.shape(M)[1] + G.sum(1))
return grad_alpha, grad_beta | [
"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 \in B_u} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j
Where :
- M is the (ns,nt) metric cost matrix
- u, v are dual variables in R^ixR^J
- reg is the regularization term
- :math:`B_u` and :math:`B_v` are lists of index
- :math:`b_s` is the size of the batchs :math:`B_u` and :math:`B_v`
- :math:`l_u` and :math:`l_v` are the lenghts of :math:`B_u` and :math:`B_v`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the dual problem is the SGD algorithm
as proposed in [19]_ [alg.1]
Parameters
----------
a : np.ndarray(ns,)
source measure
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
alpha : np.ndarray(ns,)
dual variable
beta : np.ndarray(nt,)
dual variable
batch_size : int number
size of the batch
batch_alpha : np.ndarray(bs,)
batch of index of alpha
batch_beta : np.ndarray(bs,)
batch of index of beta
Returns
-------
grad : np.ndarray(ns,)
partial grad F
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 20000
>>> lr = 0.1
>>> batch_size = 3
>>> log = True
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg,
batch_size,
numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)
References
----------
[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283. | [
"Computes",
"the",
"partial",
"gradient",
"of",
"the",
"dual",
"optimal",
"transport",
"problem",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L452-L547 | train | 221,989 |
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 + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
Parameters
----------
a : np.ndarray(ns,)
source measure
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
batch_size : int number
size of the batch
numItermax : int number
number of iteration
lr : float number
learning rate
Returns
-------
alpha : np.ndarray(ns,)
dual variable
beta : np.ndarray(nt,)
dual variable
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 20000
>>> lr = 0.1
>>> batch_size = 3
>>> log = True
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg,
batch_size,
numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)
References
----------
[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283.
'''
n_source = np.shape(M)[0]
n_target = np.shape(M)[1]
cur_alpha = np.zeros(n_source)
cur_beta = np.zeros(n_target)
for cur_iter in range(numItermax):
k = np.sqrt(cur_iter + 1)
batch_alpha = np.random.choice(n_source, batch_size, replace=False)
batch_beta = np.random.choice(n_target, batch_size, replace=False)
update_alpha, update_beta = batch_grad_dual(a, b, M, reg, cur_alpha,
cur_beta, batch_size,
batch_alpha, batch_beta)
cur_alpha[batch_alpha] += (lr / k) * update_alpha[batch_alpha]
cur_beta[batch_beta] += (lr / k) * update_beta[batch_beta]
return cur_alpha, cur_beta | 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 + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
Parameters
----------
a : np.ndarray(ns,)
source measure
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
batch_size : int number
size of the batch
numItermax : int number
number of iteration
lr : float number
learning rate
Returns
-------
alpha : np.ndarray(ns,)
dual variable
beta : np.ndarray(nt,)
dual variable
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 20000
>>> lr = 0.1
>>> batch_size = 3
>>> log = True
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg,
batch_size,
numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)
References
----------
[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283.
'''
n_source = np.shape(M)[0]
n_target = np.shape(M)[1]
cur_alpha = np.zeros(n_source)
cur_beta = np.zeros(n_target)
for cur_iter in range(numItermax):
k = np.sqrt(cur_iter + 1)
batch_alpha = np.random.choice(n_source, batch_size, replace=False)
batch_beta = np.random.choice(n_target, batch_size, replace=False)
update_alpha, update_beta = batch_grad_dual(a, b, M, reg, cur_alpha,
cur_beta, batch_size,
batch_alpha, batch_beta)
cur_alpha[batch_alpha] += (lr / k) * update_alpha[batch_alpha]
cur_beta[batch_beta] += (lr / k) * update_beta[batch_beta]
return cur_alpha, cur_beta | [
"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
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
Parameters
----------
a : np.ndarray(ns,)
source measure
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
batch_size : int number
size of the batch
numItermax : int number
number of iteration
lr : float number
learning rate
Returns
-------
alpha : np.ndarray(ns,)
dual variable
beta : np.ndarray(nt,)
dual variable
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 20000
>>> lr = 0.1
>>> batch_size = 3
>>> log = True
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg,
batch_size,
numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)
References
----------
[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283. | [
"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 | 221,990 |
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::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
Parameters
----------
a : np.ndarray(ns,)
source measure
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
batch_size : int number
size of the batch
numItermax : int number
number of iteration
lr : float number
learning rate
log : bool, optional
record log if True
Returns
-------
pi : np.ndarray(ns, nt)
transportation matrix
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 20000
>>> lr = 0.1
>>> batch_size = 3
>>> log = True
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg,
batch_size,
numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)
References
----------
[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283.
'''
opt_alpha, opt_beta = sgd_entropic_regularization(a, b, M, reg, batch_size,
numItermax, lr)
pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) *
a[:, None] * b[None, :])
if log:
log = {}
log['alpha'] = opt_alpha
log['beta'] = opt_beta
return pi, log
else:
return pi | 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::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
Parameters
----------
a : np.ndarray(ns,)
source measure
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
batch_size : int number
size of the batch
numItermax : int number
number of iteration
lr : float number
learning rate
log : bool, optional
record log if True
Returns
-------
pi : np.ndarray(ns, nt)
transportation matrix
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 20000
>>> lr = 0.1
>>> batch_size = 3
>>> log = True
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg,
batch_size,
numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)
References
----------
[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283.
'''
opt_alpha, opt_beta = sgd_entropic_regularization(a, b, M, reg, batch_size,
numItermax, lr)
pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) *
a[:, None] * b[None, :])
if log:
log = {}
log['alpha'] = opt_alpha
log['beta'] = opt_beta
return pi, log
else:
return pi | [
"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
\gamma \geq 0
Where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
Parameters
----------
a : np.ndarray(ns,)
source measure
b : np.ndarray(nt,)
target measure
M : np.ndarray(ns, nt)
cost matrix
reg : float number
Regularization term > 0
batch_size : int number
size of the batch
numItermax : int number
number of iteration
lr : float number
learning rate
log : bool, optional
record log if True
Returns
-------
pi : np.ndarray(ns, nt)
transportation matrix
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 20000
>>> lr = 0.1
>>> batch_size = 3
>>> log = True
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg,
batch_size,
numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)
References
----------
[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283. | [
"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 | 221,991 |
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 | 221,992 |
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 | 221,993 |
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 | 221,994 |
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)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, 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)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, 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 | 221,995 |
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 = f.read(max_bytes)
if not text:
return False
except IOError:
return False
first_line = text.splitlines()[0]
return PYTHON_SHEBANG_REGEX.match(first_line) | 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 = f.read(max_bytes)
if not text:
return False
except IOError:
return False
first_line = text.splitlines()[0]
return PYTHON_SHEBANG_REGEX.match(first_line) | [
"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 | 221,996 |
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:
# the signal constants defined in the signal module are defined by
# whether the C library supports them or not. So, SIGPIPE might not
# even be defined.
return
def handler(sig, f):
sys.exit(message)
try:
signal.signal(sigNumber, handler)
except ValueError:
# It's also possible the signal is defined, but then it's invalid. In
# this case, signal.signal raises ValueError.
pass | 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:
# the signal constants defined in the signal module are defined by
# whether the C library supports them or not. So, SIGPIPE might not
# even be defined.
return
def handler(sig, f):
sys.exit(message)
try:
signal.signal(sigNumber, handler)
except ValueError:
# It's also possible the signal is defined, but then it's invalid. In
# this case, signal.signal raises ValueError.
pass | [
"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 | 221,997 |
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.get_fields()
if isinstance(f, OneToOneRel)]
rels = [
rel for rel in related_objects
if isinstance(rel.field, OneToOneField)
and issubclass(rel.field.model, model)
and model is not rel.field.model
and rel.parent_link
]
subclasses = []
if levels:
levels -= 1
for rel in rels:
if levels or levels is None:
for subclass in self._get_subclasses_recurse(
rel.field.model, levels=levels):
subclasses.append(
rel.get_accessor_name() + LOOKUP_SEP + subclass)
subclasses.append(rel.get_accessor_name())
return subclasses | 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.get_fields()
if isinstance(f, OneToOneRel)]
rels = [
rel for rel in related_objects
if isinstance(rel.field, OneToOneField)
and issubclass(rel.field.model, model)
and model is not rel.field.model
and rel.parent_link
]
subclasses = []
if levels:
levels -= 1
for rel in rels:
if levels or levels is None:
for subclass in self._get_subclasses_recurse(
rel.field.model, levels=levels):
subclasses.append(
rel.get_accessor_name() + LOOKUP_SEP + subclass)
subclasses.append(rel.get_accessor_name())
return subclasses | [
"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 | 221,998 |
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):
raise ValueError(
"%r is not a subclass of %r" % (model, self.model))
ancestry = []
# should be a OneToOneField or None
parent_link = model._meta.get_ancestor_link(self.model)
if levels:
levels -= 1
while parent_link is not None:
related = parent_link.remote_field
ancestry.insert(0, related.get_accessor_name())
if levels or levels is None:
parent_model = related.model
parent_link = parent_model._meta.get_ancestor_link(
self.model)
else:
parent_link = None
return LOOKUP_SEP.join(ancestry) | 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):
raise ValueError(
"%r is not a subclass of %r" % (model, self.model))
ancestry = []
# should be a OneToOneField or None
parent_link = model._meta.get_ancestor_link(self.model)
if levels:
levels -= 1
while parent_link is not None:
related = parent_link.remote_field
ancestry.insert(0, related.get_accessor_name())
if levels or levels is None:
parent_model = related.model
parent_link = parent_model._meta.get_ancestor_link(
self.model)
else:
parent_link = None
return LOOKUP_SEP.join(ancestry) | [
"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 | 221,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.