(
variables: T_Variables, attributes: T_Attrs, non_dim_coord_names
)
| 648 | |
| 649 | |
| 650 | def _encode_coordinates( |
| 651 | variables: T_Variables, attributes: T_Attrs, non_dim_coord_names |
| 652 | ): |
| 653 | # calculate global and variable specific coordinates |
| 654 | non_dim_coord_names = set(non_dim_coord_names) |
| 655 | |
| 656 | for name in list(non_dim_coord_names): |
| 657 | if isinstance(name, str) and " " in name: |
| 658 | emit_user_level_warning( |
| 659 | f"coordinate {name!r} has a space in its name, which means it " |
| 660 | "cannot be marked as a coordinate on disk and will be " |
| 661 | "saved as a data variable instead", |
| 662 | category=SerializationWarning, |
| 663 | ) |
| 664 | non_dim_coord_names.discard(name) |
| 665 | |
| 666 | global_coordinates = non_dim_coord_names.copy() |
| 667 | variable_coordinates = defaultdict(set) |
| 668 | not_technically_coordinates = set() |
| 669 | for coord_name in non_dim_coord_names: |
| 670 | target_dims = variables[coord_name].dims |
| 671 | for k, v in variables.items(): |
| 672 | if ( |
| 673 | k not in non_dim_coord_names |
| 674 | and k not in v.dims |
| 675 | and set(target_dims) <= set(v.dims) |
| 676 | ): |
| 677 | variable_coordinates[k].add(coord_name) |
| 678 | |
| 679 | if any( |
| 680 | coord_name in v.encoding.get(attr_name, tuple()) |
| 681 | for attr_name in CF_RELATED_DATA |
| 682 | ): |
| 683 | not_technically_coordinates.add(coord_name) |
| 684 | global_coordinates.discard(coord_name) |
| 685 | |
| 686 | variables = {k: v.copy(deep=False) for k, v in variables.items()} |
| 687 | |
| 688 | # keep track of variable names written to file under the "coordinates" attributes |
| 689 | written_coords = set() |
| 690 | for name, var in variables.items(): |
| 691 | encoding = var.encoding |
| 692 | attrs = var.attrs |
| 693 | if "coordinates" in attrs and "coordinates" in encoding: |
| 694 | raise ValueError( |
| 695 | f"'coordinates' found in both attrs and encoding for variable {name!r}." |
| 696 | ) |
| 697 | |
| 698 | # if coordinates set to None, don't write coordinates attribute |
| 699 | if ("coordinates" in attrs and attrs.get("coordinates") is None) or ( |
| 700 | "coordinates" in encoding and encoding.get("coordinates") is None |
| 701 | ): |
| 702 | # make sure "coordinates" is removed from attrs/encoding |
| 703 | attrs.pop("coordinates", None) |
| 704 | encoding.pop("coordinates", None) |
| 705 | continue |
| 706 | |
| 707 | # this will copy coordinates from encoding to attrs if "coordinates" in attrs |
no test coverage detected
searching dependent graphs…