Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactoring UnivariateSolver #472

Merged
merged 4 commits into from
Nov 27, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions src/ott/geometry/distrib_cost.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Copyright OTT-JAX
marcocuturi marked this conversation as resolved.
Show resolved Hide resolved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Any, Optional

import jax
import jax.numpy as jnp

from ott.geometry import costs, pointcloud
from ott.problems.linear import linear_problem
from ott.solvers.linear import univariate

__all__ = [
"UnivariateWasserstein",
]


@jax.tree_util.register_pytree_node_class
class UnivariateWasserstein(costs.CostFn):
marcocuturi marked this conversation as resolved.
Show resolved Hide resolved
"""1D Wasserstein cost for two 1D distributions.

This ground cost between considers vectors as a family of values. The
Wasserstein distance between them is the 1D OT cost, using a user-defined
ground cost.
"""

def __init__(
self,
ground_cost: Optional[costs.TICost] = None,
kwargs_solve: Optional[Any] = None,
marcocuturi marked this conversation as resolved.
Show resolved Hide resolved
**kwargs: Any
):
super().__init__()
if ground_cost is None:
self.ground_cost = costs.SqEuclidean()
else:
self.ground_cost = ground_cost
marcocuturi marked this conversation as resolved.
Show resolved Hide resolved
self._kwargs_solve = {} if kwargs_solve is None else kwargs_solve
self._kwargs = kwargs
marcocuturi marked this conversation as resolved.
Show resolved Hide resolved
self._solver = univariate.UnivariateSolver(**kwargs)

def pairwise(self, x: jnp.ndarray, y: jnp.ndarray) -> float:
"""Wasserstein distance between :math:`x` and :math:`y` seen as a 1D dist.

Args:
x: vector
marcocuturi marked this conversation as resolved.
Show resolved Hide resolved
y: vector
kwargs: arguments passed on when calling the
marcocuturi marked this conversation as resolved.
Show resolved Hide resolved
:class:`~ott.solvers.linear.univariate.UnivariateSolver`. May include
random key, or specific instructions to subsample or compute using
quantiles.

Returns:
The transport cost.
"""
out = self._solver(
marcocuturi marked this conversation as resolved.
Show resolved Hide resolved
linear_problem.LinearProblem(
pointcloud.PointCloud(
x[:, None], y[:, None], cost_fn=self.ground_cost
)
), **self._kwargs_solve
)
return jnp.squeeze(out.ot_costs)

def tree_flatten(self): # noqa: D102
return (), (self.ground_cost, self._kwargs_solve, self._kwargs)
marcocuturi marked this conversation as resolved.
Show resolved Hide resolved

@classmethod
def tree_unflatten(cls, aux_data, children): # noqa: D102
del children
gc, kws, kw = aux_data
marcocuturi marked this conversation as resolved.
Show resolved Hide resolved
return cls(gc, kws, **kw)
10 changes: 10 additions & 0 deletions src/ott/problems/linear/linear_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,16 @@ def is_balanced(self) -> bool:
"""Whether the problem is balanced."""
return self.tau_a == 1.0 and self.tau_b == 1.0

@property
def is_uniform(self) -> bool:
"""Test if no weights were passed."""
marcocuturi marked this conversation as resolved.
Show resolved Hide resolved
return self._a is None and self._b is None

@property
def is_equal_size(self) -> bool:
"""Test if square shape, i.e. n == m."""
marcocuturi marked this conversation as resolved.
Show resolved Hide resolved
return self.geom.shape[0] == self.geom.shape[1]

@property
def epsilon(self) -> float:
"""Entropic regularization."""
Expand Down
Loading
Loading