All the logic for creating a new DataArray
(
shape: tuple[int, ...],
coords: (
Sequence[Sequence | pd.Index | DataArray | Variable | np.ndarray]
| Mapping
| None
),
dims: str | Iterable[Hashable] | None,
)
| 128 | |
| 129 | |
| 130 | def _infer_coords_and_dims( |
| 131 | shape: tuple[int, ...], |
| 132 | coords: ( |
| 133 | Sequence[Sequence | pd.Index | DataArray | Variable | np.ndarray] |
| 134 | | Mapping |
| 135 | | None |
| 136 | ), |
| 137 | dims: str | Iterable[Hashable] | None, |
| 138 | ) -> tuple[Mapping[Hashable, Any], tuple[Hashable, ...]]: |
| 139 | """All the logic for creating a new DataArray""" |
| 140 | |
| 141 | if ( |
| 142 | coords is not None |
| 143 | and not utils.is_dict_like(coords) |
| 144 | and len(coords) != len(shape) |
| 145 | ): |
| 146 | raise ValueError( |
| 147 | f"coords is not dict-like, but it has {len(coords)} items, " |
| 148 | f"which does not match the {len(shape)} dimensions of the " |
| 149 | "data" |
| 150 | ) |
| 151 | |
| 152 | if isinstance(dims, str): |
| 153 | dims = (dims,) |
| 154 | elif dims is None: |
| 155 | dims = [f"dim_{n}" for n in range(len(shape))] |
| 156 | if coords is not None and len(coords) == len(shape): |
| 157 | # try to infer dimensions from coords |
| 158 | if utils.is_dict_like(coords): |
| 159 | dims = list(coords.keys()) |
| 160 | else: |
| 161 | for n, (dim, coord) in enumerate(zip(dims, coords, strict=True)): |
| 162 | coord = as_variable( |
| 163 | coord, name=dim, auto_convert=False |
| 164 | ).to_index_variable() |
| 165 | dims[n] = coord.name |
| 166 | dims_tuple = tuple(dims) |
| 167 | if len(dims_tuple) != len(shape): |
| 168 | raise ValueError( |
| 169 | "different number of dimensions on data " |
| 170 | f"and dims: {len(shape)} vs {len(dims_tuple)}" |
| 171 | ) |
| 172 | for d in dims_tuple: |
| 173 | if not hashable(d): |
| 174 | raise TypeError(f"Dimension {d} is not hashable") |
| 175 | |
| 176 | new_coords: Mapping[Hashable, Any] |
| 177 | |
| 178 | if isinstance(coords, Coordinates): |
| 179 | new_coords = coords |
| 180 | else: |
| 181 | new_coords = {} |
| 182 | if utils.is_dict_like(coords): |
| 183 | for k, v in coords.items(): |
| 184 | new_coords[k] = as_variable(v, name=k, auto_convert=False) |
| 185 | if new_coords[k].dims == (k,): |
| 186 | new_coords[k] = new_coords[k].to_index_variable() |
| 187 | elif coords is not None: |
no test coverage detected
searching dependent graphs…