invrs-opt 0.6.0__py3-none-any.whl → 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -62,6 +62,20 @@ def density_gaussian_filter_and_tanh(
62
62
  return transformed_density
63
63
 
64
64
 
65
+ def _gaussian_kernel(fwhm: float, fwhm_size_multiple: float) -> jnp.ndarray:
66
+ """Returns a Gaussian kernel with the specified full-width at half-maximum."""
67
+ with jax.ensure_compile_time_eval():
68
+ kernel_size = max(1, int(jnp.ceil(fwhm * fwhm_size_multiple)))
69
+ # Ensure the kernel size is odd, so that there is always a central pixel which will
70
+ # contain the peak value of the Gaussian.
71
+ kernel_size += (kernel_size + 1) % 2
72
+ d = jnp.arange(0.5, kernel_size) - kernel_size / 2
73
+ x = d[:, jnp.newaxis]
74
+ y = d[jnp.newaxis, :]
75
+ sigma = fwhm / (2 * jnp.sqrt(2 * jnp.log(2)))
76
+ return jnp.exp(-(x**2 + y**2) / (2 * sigma**2))
77
+
78
+
65
79
  def normalized_array_from_density(density: types.Density2DArray) -> jnp.ndarray:
66
80
  """Returns an array with values scaled to the range `(-1, 1)`."""
67
81
  value_mid = (density.upper_bound + density.lower_bound) / 2
@@ -154,15 +168,66 @@ def _pad_mode_for_density(density: types.Density2DArray) -> Union[str, Tuple[str
154
168
  )
155
169
 
156
170
 
157
- def _gaussian_kernel(fwhm: float, fwhm_size_multiple: float) -> jnp.ndarray:
158
- """Returns a Gaussian kernel with the specified full-width at half-maximum."""
171
+ def resample(
172
+ x: jnp.ndarray,
173
+ shape: Tuple[int, ...],
174
+ method: jax.image.ResizeMethod = jax.image.ResizeMethod.LINEAR,
175
+ ) -> jnp.ndarray:
176
+ """Resamples `x` to have the specified `shape`.
177
+
178
+ The algorithm first upsamples `x` so that the pixels in the output image are
179
+ comprised of an integer number of pixels in the upsampled `x`, and then
180
+ performs box downsampling.
181
+
182
+ Args:
183
+ x: The array to be resampled.
184
+ shape: The shape of the output array.
185
+ method: The method used to resize `x` prior to box downsampling.
186
+
187
+ Returns:
188
+ The resampled array.
189
+ """
190
+ if x.ndim != len(shape):
191
+ raise ValueError(
192
+ f"`shape` must have length matching number of dimensions in `x`, "
193
+ f"but got {shape} when `x` had shape {x.shape}."
194
+ )
195
+
159
196
  with jax.ensure_compile_time_eval():
160
- kernel_size = max(1, int(jnp.ceil(fwhm * fwhm_size_multiple)))
161
- # Ensure the kernel size is odd, so that there is always a central pixel which will
162
- # contain the peak value of the Gaussian.
163
- kernel_size += (kernel_size + 1) % 2
164
- d = jnp.arange(0.5, kernel_size) - kernel_size / 2
165
- x = d[:, jnp.newaxis]
166
- y = d[jnp.newaxis, :]
167
- sigma = fwhm / (2 * jnp.sqrt(2 * jnp.log(2)))
168
- return jnp.exp(-(x**2 + y**2) / (2 * sigma**2))
197
+ factor = [int(jnp.ceil(dx / d)) for dx, d in zip(x.shape, shape)]
198
+ upsampled_shape = tuple([d * f for d, f in zip(shape, factor)])
199
+
200
+ x_upsampled = jax.image.resize(
201
+ image=x,
202
+ shape=upsampled_shape,
203
+ method=method,
204
+ )
205
+
206
+ return box_downsample(x_upsampled, shape)
207
+
208
+
209
+ def box_downsample(x: jnp.ndarray, shape: Tuple[int, ...]) -> jnp.ndarray:
210
+ """Downsamples `x` to a coarser resolution array using box downsampling.
211
+
212
+ Box downsampling forms nonoverlapping windows and simply averages the
213
+ pixels within each window. For example, downsampling `(0, 1, 2, 3, 4, 5)`
214
+ with a factor of `2` yields `(0.5, 2.5, 4.5)`.
215
+
216
+ Args:
217
+ x: The array to be downsampled.
218
+ shape: The shape of the output array; each axis dimension must evenly
219
+ divide the corresponding axis dimension in `x`.
220
+
221
+ Returns:
222
+ The output array with shape `shape`.
223
+ """
224
+ if x.ndim != len(shape) or any([(d % s) != 0 for d, s in zip(x.shape, shape)]):
225
+ raise ValueError(
226
+ f"Each axis of `shape` must evenly divide the corresponding axis "
227
+ f"dimension in `x`, but got shape {shape} when `x` has shape "
228
+ f"{x.shape}."
229
+ )
230
+ shape = sum([(s, d // s) for d, s in zip(x.shape, shape)], ())
231
+ axes = list(range(1, 2 * x.ndim, 2))
232
+ x = x.reshape(shape)
233
+ return jnp.mean(x, axis=axes)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: invrs_opt
3
- Version: 0.6.0
3
+ Version: 0.7.0
4
4
  Summary: Algorithms for inverse design
5
5
  Author-email: "Martin F. Schubert" <mfschubert@gmail.com>
6
6
  Maintainer-email: "Martin F. Schubert" <mfschubert@gmail.com>
@@ -39,18 +39,18 @@ Requires-Dist: scipy
39
39
  Requires-Dist: totypes
40
40
  Requires-Dist: types-requests
41
41
  Provides-Extra: dev
42
- Requires-Dist: bump-my-version ; extra == 'dev'
43
- Requires-Dist: darglint ; extra == 'dev'
44
- Requires-Dist: mypy ; extra == 'dev'
45
- Requires-Dist: pre-commit ; extra == 'dev'
42
+ Requires-Dist: bump-my-version; extra == "dev"
43
+ Requires-Dist: darglint; extra == "dev"
44
+ Requires-Dist: mypy; extra == "dev"
45
+ Requires-Dist: pre-commit; extra == "dev"
46
46
  Provides-Extra: tests
47
- Requires-Dist: parameterized ; extra == 'tests'
48
- Requires-Dist: pytest ; extra == 'tests'
49
- Requires-Dist: pytest-cov ; extra == 'tests'
50
- Requires-Dist: pytest-subtests ; extra == 'tests'
47
+ Requires-Dist: parameterized; extra == "tests"
48
+ Requires-Dist: pytest; extra == "tests"
49
+ Requires-Dist: pytest-cov; extra == "tests"
50
+ Requires-Dist: pytest-subtests; extra == "tests"
51
51
 
52
52
  # invrs-opt - Optimization algorithms for inverse design
53
- `v0.6.0`
53
+ `v0.7.0`
54
54
 
55
55
  ## Overview
56
56
 
@@ -0,0 +1,20 @@
1
+ invrs_opt/__init__.py,sha256=cRGTL0pWiEmPY26dG0bfKaS_RV5I5N3FdFkKLM8Z-Wk,585
2
+ invrs_opt/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ invrs_opt/experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ invrs_opt/experimental/client.py,sha256=t4XxnditYbM9DWZeyBPj0Sa2acvkikT0ybhUdmH2r-Y,4852
5
+ invrs_opt/experimental/labels.py,sha256=dQDAMPyFMV6mXnMy295z8Ap205DRdVzysXny_Be8FmY,562
6
+ invrs_opt/optimizers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ invrs_opt/optimizers/base.py,sha256=ol9skiS4_itx6pmqTx49fqqRZGzHHSxjKPKguy6602s,1199
8
+ invrs_opt/optimizers/lbfgsb.py,sha256=d7i02NZZ3yYdJg7wkERDMPpdBD3GaRPhmQexGrZPz_Y,34597
9
+ invrs_opt/optimizers/wrapped_optax.py,sha256=L836gwzWbwxPNWh8Y7PSgFHV4PZluSklnbh3BR5djlc,11859
10
+ invrs_opt/parameterization/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ invrs_opt/parameterization/base.py,sha256=QTnhOfMYbDchZOFzk9graryMd6rYHlyd7E2T1TtucB8,3570
12
+ invrs_opt/parameterization/filter_project.py,sha256=XCPqQ2ECv7DDTLRtVGJePfnjKYB2XndI6DssSr-4MZw,3239
13
+ invrs_opt/parameterization/gaussian_levelset.py,sha256=OYXPNC3GIGqCxea-u7rTXCOAEERLoict9kqnjYvGGto,24838
14
+ invrs_opt/parameterization/pixel.py,sha256=4qCYDUCcFPr8W94whX5YFllrXgyZbPBVIJBf8m_Dv4k,1173
15
+ invrs_opt/parameterization/transforms.py,sha256=8GzaIsUuuXvMCLiqAEEfxmi9qE9KqHzbuTj_m0GjH3w,8216
16
+ invrs_opt-0.7.0.dist-info/LICENSE,sha256=ty6jHPvpyjHy6dbhnu6aDSY05bbl2jQTjnq9u1sBCfM,1078
17
+ invrs_opt-0.7.0.dist-info/METADATA,sha256=EBEC3SgXD2hwdZ5s-z2dydbr5oSPSsgB34iMSdhaLeE,3339
18
+ invrs_opt-0.7.0.dist-info/WHEEL,sha256=R0nc6qTxuoLk7ShA2_Y-UWkN8ZdfDBG2B6Eqpz2WXbs,91
19
+ invrs_opt-0.7.0.dist-info/top_level.txt,sha256=hOziS2uJ_NgwaW9yhtOfeuYnm1X7vobPBcp_6eVWKfM,10
20
+ invrs_opt-0.7.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.43.0)
2
+ Generator: setuptools (72.1.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,150 +0,0 @@
1
- import dataclasses
2
- from typing import Any, Callable, Tuple
3
-
4
- import jax
5
- import jax.numpy as jnp
6
- import optax # type: ignore[import-untyped]
7
- from jax import tree_util
8
- from totypes import types
9
-
10
- from invrs_opt import base, transform
11
-
12
- PyTree = Any
13
- WrappedOptaxState = Tuple[PyTree, PyTree, PyTree]
14
-
15
-
16
- def wrapped_optax(opt: optax.GradientTransformation) -> base.Optimizer:
17
- """Return a wrapped optax optimizer."""
18
- return transformed_wrapped_optax(
19
- opt=opt,
20
- transform_fn=lambda x: x,
21
- initialize_latent_fn=lambda x: x,
22
- )
23
-
24
-
25
- def density_wrapped_optax(
26
- opt: optax.GradientTransformation,
27
- beta: float,
28
- ) -> base.Optimizer:
29
- """Return a wrapped optax optimizer with transforms for density arrays."""
30
-
31
- def transform_fn(tree: PyTree) -> PyTree:
32
- return tree_util.tree_map(
33
- lambda x: transform_density(x) if _is_density(x) else x,
34
- tree,
35
- is_leaf=_is_density,
36
- )
37
-
38
- def initialize_latent_fn(tree: PyTree) -> PyTree:
39
- return tree_util.tree_map(
40
- lambda x: initialize_latent_density(x) if _is_density(x) else x,
41
- tree,
42
- is_leaf=_is_density,
43
- )
44
-
45
- def transform_density(density: types.Density2DArray) -> types.Density2DArray:
46
- transformed = types.symmetrize_density(density)
47
- transformed = transform.density_gaussian_filter_and_tanh(transformed, beta=beta)
48
- # Scale to ensure that the full valid range of the density array is reachable.
49
- mid_value = (density.lower_bound + density.upper_bound) / 2
50
- transformed = tree_util.tree_map(
51
- lambda array: mid_value + (array - mid_value) / jnp.tanh(beta), transformed
52
- )
53
- return transform.apply_fixed_pixels(transformed)
54
-
55
- def initialize_latent_density(
56
- density: types.Density2DArray,
57
- ) -> types.Density2DArray:
58
- array = transform.normalized_array_from_density(density)
59
- array = jnp.clip(array, -1, 1)
60
- array *= jnp.tanh(beta)
61
- latent_array = jnp.arctanh(array) / beta
62
- latent_array = transform.rescale_array_for_density(latent_array, density)
63
- return dataclasses.replace(density, array=latent_array)
64
-
65
- return transformed_wrapped_optax(
66
- opt=opt,
67
- transform_fn=transform_fn,
68
- initialize_latent_fn=initialize_latent_fn,
69
- )
70
-
71
-
72
- def transformed_wrapped_optax(
73
- opt: optax.GradientTransformation,
74
- transform_fn: Callable[[PyTree], PyTree],
75
- initialize_latent_fn: Callable[[PyTree], PyTree],
76
- ) -> base.Optimizer:
77
- """Return a wrapped optax optimizer for transformed latent parameters.
78
-
79
- Args:
80
- opt: The optax `GradientTransformation` to be wrapped.
81
- transform_fn: Function which transforms the internal latent parameters to
82
- the parameters returned by the optimizer.
83
- initialize_latent_fn: Function which computes the initial latent parameters
84
- given the initial parameters.
85
-
86
- Returns:
87
- The `base.Optimizer`.
88
- """
89
-
90
- def init_fn(params: PyTree) -> WrappedOptaxState:
91
- """Initializes the optimization state."""
92
- latent_params = initialize_latent_fn(_clip(params))
93
- params = transform_fn(latent_params)
94
- return params, latent_params, opt.init(latent_params)
95
-
96
- def params_fn(state: WrappedOptaxState) -> PyTree:
97
- """Returns the parameters for the given `state`."""
98
- params, _, _ = state
99
- return params
100
-
101
- def update_fn(
102
- *,
103
- grad: PyTree,
104
- value: float,
105
- params: PyTree,
106
- state: WrappedOptaxState,
107
- ) -> WrappedOptaxState:
108
- """Updates the state."""
109
- del value
110
-
111
- _, latent_params, opt_state = state
112
- _, vjp_fn = jax.vjp(transform_fn, latent_params)
113
- (latent_grad,) = vjp_fn(grad)
114
-
115
- updates, opt_state = opt.update(latent_grad, opt_state)
116
- latent_params = optax.apply_updates(params=latent_params, updates=updates)
117
- latent_params = _clip(latent_params)
118
- params = transform_fn(latent_params)
119
- return params, latent_params, opt_state
120
-
121
- return base.Optimizer(
122
- init=init_fn,
123
- params=params_fn,
124
- update=update_fn,
125
- )
126
-
127
-
128
- def _is_density(leaf: Any) -> Any:
129
- """Return `True` if `leaf` is a density array."""
130
- return isinstance(leaf, types.Density2DArray)
131
-
132
-
133
- def _is_custom_type(leaf: Any) -> bool:
134
- """Return `True` if `leaf` is a recognized custom type."""
135
- return isinstance(leaf, (types.BoundedArray, types.Density2DArray))
136
-
137
-
138
- def _clip(pytree: PyTree) -> PyTree:
139
- """Clips leaves on `pytree` to their bounds."""
140
-
141
- def _clip_fn(leaf: Any) -> Any:
142
- if not _is_custom_type(leaf):
143
- return leaf
144
- if leaf.lower_bound is None and leaf.upper_bound is None:
145
- return leaf
146
- return tree_util.tree_map(
147
- lambda x: jnp.clip(x, leaf.lower_bound, leaf.upper_bound), leaf
148
- )
149
-
150
- return tree_util.tree_map(_clip_fn, pytree, is_leaf=_is_custom_type)
@@ -1,16 +0,0 @@
1
- invrs_opt/__init__.py,sha256=35pvMpeqvJgU4DizUO5hTzeE9j93prbB9RMtcaoFYwg,496
2
- invrs_opt/base.py,sha256=FdQyPTlWGo03YztI3K2_QBN6Q-v0PeXv6XCyXu_uh_4,1160
3
- invrs_opt/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- invrs_opt/transform.py,sha256=a_Saj9Wq4lvqCJBrg5L2Z9DZ2NVs1xqrHLqha90a9Ws,5971
5
- invrs_opt/experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
- invrs_opt/experimental/client.py,sha256=MqC_TguT9IGrG7WW54vwz6QQMylKkbCjHxFPIG9vQMA,4841
7
- invrs_opt/experimental/labels.py,sha256=dQDAMPyFMV6mXnMy295z8Ap205DRdVzysXny_Be8FmY,562
8
- invrs_opt/lbfgsb/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
- invrs_opt/lbfgsb/lbfgsb.py,sha256=pfrqCaOMco-eHUQe2q03hbla9D2TYqmMB-07jK4-5Ik,27792
10
- invrs_opt/wrapped_optax/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
- invrs_opt/wrapped_optax/wrapped_optax.py,sha256=-ke0MNCb2EB0ntlj5IHIHrvybOVF4m24DM6JI4_Ktcc,4974
12
- invrs_opt-0.6.0.dist-info/LICENSE,sha256=ty6jHPvpyjHy6dbhnu6aDSY05bbl2jQTjnq9u1sBCfM,1078
13
- invrs_opt-0.6.0.dist-info/METADATA,sha256=V4hpzjEovC2CU0IgUBMAgKzPfgqGvLlutQ9X5-FOuIk,3347
14
- invrs_opt-0.6.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
15
- invrs_opt-0.6.0.dist-info/top_level.txt,sha256=hOziS2uJ_NgwaW9yhtOfeuYnm1X7vobPBcp_6eVWKfM,10
16
- invrs_opt-0.6.0.dist-info/RECORD,,
File without changes