@@ -7149,14 +7149,37 @@ def collapse(
7149
7149
if dim is None:
7150
7150
continue
7151
7151
7152
- # Create a new dimension coordinate for this axis
7152
+ # Create new dimension coordinate bounds
7153
7153
if dim.has_bounds():
7154
- bounds_data = [ dim.bounds.datum(0), dim.bounds.datum(-1)]
7154
+ b = dim.bounds.data
7155
7155
else:
7156
- bounds_data = [ dim.datum(0), dim.datum(-1)]
7156
+ b = dim.data
7157
7157
7158
- units = dim.Units
7158
+ cached_elements = b._get_cached_elements()
7159
+ try:
7160
+ # Try to set the new bounds from cached values
7161
+ bounds_data = Data(
7162
+ [[cached_elements[0], cached_elements[-1]]],
7163
+ dtype=b.dtype,
7164
+ units=b.Units,
7165
+ )
7166
+ except KeyError:
7167
+ # Otherwise create the new bounds lazily
7168
+ ndim = b.ndim
7169
+ bounds_data = Data.concatenate(
7170
+ [
7171
+ b[(slice(0, 1, 1),) * ndim],
7172
+ b[(slice(-1, None, 1),) * ndim],
7173
+ ],
7174
+ axis=-1,
7175
+ copy=False,
7176
+ )
7177
+ if ndim == 1:
7178
+ bounds_data.insert_dimension(0, inplace=True)
7159
7179
7180
+ bounds = self._Bounds(data=bounds_data)
7181
+
7182
+ # Create a new dimension coordinate value
7160
7183
if coordinate == "min":
7161
7184
coordinate = "minimum"
7162
7185
print(
@@ -7171,21 +7194,17 @@ def collapse(
7171
7194
)
7172
7195
7173
7196
if coordinate == "mid_range":
7174
- data = Data(
7175
- [(bounds_data[0] + bounds_data[1]) * 0.5], units=units
7176
- )
7197
+ data = bounds_data.mean(axes=1, weights=None, squeeze=True)
7177
7198
elif coordinate == "minimum":
7178
- data = dim.data.min()
7199
+ data = dim.data.min(squeeze=False )
7179
7200
elif coordinate == "maximum":
7180
- data = dim.data.max()
7201
+ data = dim.data.max(squeeze=False )
7181
7202
else:
7182
7203
raise ValueError(
7183
7204
"Can't collapse: Bad parameter value: "
7184
7205
f"coordinate={coordinate!r}"
7185
7206
)
7186
7207
7187
- bounds = self._Bounds(data=Data([bounds_data], units=units))
7188
-
7189
7208
dim.set_data(data, copy=False)
7190
7209
dim.set_bounds(bounds, copy=False)
7191
7210
0 commit comments