|
| 1 | +from abc import abstractmethod |
| 2 | +from dataclasses import copy, dataclass, fields |
| 3 | + |
| 4 | +from sisl.messages import SislError, warn |
| 5 | + |
| 6 | +__all__ = ["composite_geometry", "CompositeGeometrySection"] |
| 7 | + |
| 8 | + |
| 9 | +@dataclass |
| 10 | +class CompositeGeometrySection: |
| 11 | + |
| 12 | + @abstractmethod |
| 13 | + def build_section(self, geometry): |
| 14 | + ... |
| 15 | + |
| 16 | + @abstractmethod |
| 17 | + def add_section(self, geometry, geometry_addition): |
| 18 | + ... |
| 19 | + |
| 20 | + def _junction_error(self, prev, msg, what): |
| 21 | + """Helper function to raise an error if the junction is not valid. |
| 22 | +
|
| 23 | + It extends the error by specifying details about the sections that |
| 24 | + are being joined. |
| 25 | + """ |
| 26 | + msg = f"Error at junction between sections {prev} and {self}. {msg}" |
| 27 | + if what == "raise": |
| 28 | + raise SislError(msg) |
| 29 | + elif what == "warn": |
| 30 | + warn(msg) |
| 31 | + |
| 32 | + |
| 33 | +def composite_geometry(sections, section_cls, **kwargs): |
| 34 | + """Creates a composite geometry from a list of sections. |
| 35 | +
|
| 36 | + The sections are added one after another in the provided order. |
| 37 | +
|
| 38 | + Parameters |
| 39 | + ---------- |
| 40 | + sections: array-like of (_geom_section or tuple or dict) |
| 41 | + A list of sections to be added to the ribbon. |
| 42 | +
|
| 43 | + Each section is either a `composite_geometry.section` or something that will |
| 44 | + be parsed to a `composite_geometry.section`. |
| 45 | + section_cls: class, optional |
| 46 | + The class to use for parsing sections. |
| 47 | + **kwargs: |
| 48 | + Keyword arguments used as defaults for the sections when the . |
| 49 | + """ |
| 50 | + # Parse sections into Section objects |
| 51 | + def conv(s): |
| 52 | + # If it is some arbitrary type, convert it to a tuple |
| 53 | + if not isinstance(s, (section_cls, tuple, dict)): |
| 54 | + s = (s, ) |
| 55 | + # If we arrived here with a tuple, convert it to a dict |
| 56 | + if isinstance(s, tuple): |
| 57 | + s = {field.name: val for field, val in zip(fields(section_cls), s)} |
| 58 | + # At this point it is either a dict or already a section object. |
| 59 | + if isinstance(s, dict): |
| 60 | + return section_cls(**{**kwargs, **s}) |
| 61 | + |
| 62 | + return copy.copy(s) |
| 63 | + |
| 64 | + # Then loop through all the sections. |
| 65 | + geom = None |
| 66 | + prev = None |
| 67 | + for i, section in enumerate(sections): |
| 68 | + section = conv(section) |
| 69 | + |
| 70 | + new_addition = section.build_section(prev) |
| 71 | + |
| 72 | + if i == 0: |
| 73 | + geom = new_addition |
| 74 | + else: |
| 75 | + geom = section.add_section(geom, new_addition) |
| 76 | + |
| 77 | + prev = section |
| 78 | + |
| 79 | + return geom |
| 80 | + |
| 81 | + |
| 82 | +composite_geometry.section = CompositeGeometrySection |
0 commit comments