Calculate the dimensions corresponding to a set of variables. Returns dictionary mapping from dimension names to sizes. Raises ValueError if any of the dimension sizes conflict.
(variables: Mapping[Any, Variable])
| 3135 | |
| 3136 | |
| 3137 | def calculate_dimensions(variables: Mapping[Any, Variable]) -> dict[Hashable, int]: |
| 3138 | """Calculate the dimensions corresponding to a set of variables. |
| 3139 | |
| 3140 | Returns dictionary mapping from dimension names to sizes. Raises ValueError |
| 3141 | if any of the dimension sizes conflict. |
| 3142 | """ |
| 3143 | dims: dict[Hashable, int] = {} |
| 3144 | last_used = {} |
| 3145 | scalar_vars = {k for k, v in variables.items() if not v.dims} |
| 3146 | for k, var in variables.items(): |
| 3147 | for dim, size in zip(var.dims, var.shape, strict=True): |
| 3148 | if dim in scalar_vars: |
| 3149 | raise ValueError( |
| 3150 | f"dimension {dim!r} already exists as a scalar variable" |
| 3151 | ) |
| 3152 | if dim not in dims: |
| 3153 | dims[dim] = size |
| 3154 | last_used[dim] = k |
| 3155 | elif dims[dim] != size: |
| 3156 | raise ValueError( |
| 3157 | f"conflicting sizes for dimension {dim!r}: " |
| 3158 | f"length {size} on {k!r} and length {dims[dim]} on {last_used!r}" |
| 3159 | ) |
| 3160 | return dims |
no test coverage detected
searching dependent graphs…