|
| 1 | +"""Write context for configuring MF6 input file writing.""" |
| 2 | + |
| 3 | +import threading |
| 4 | +from typing import Literal, Optional |
| 5 | + |
| 6 | +from attrs import define, field |
| 7 | + |
| 8 | +ArrayFormat = Literal["internal", "constant", "open/close"] |
| 9 | + |
| 10 | + |
| 11 | +@define |
| 12 | +class WriteContext: |
| 13 | + """ |
| 14 | + Configuration context for writing MODFLOW 6 input files. |
| 15 | +
|
| 16 | + This class controls how simulation data is written to input files, |
| 17 | + including numeric precision, binary vs ASCII format, and path handling. |
| 18 | +
|
| 19 | + Can be used in three ways: |
| 20 | + 1. Attached to a component: component.write_context = ctx |
| 21 | + 2. Passed to write method: component.write(context=ctx) |
| 22 | + 3. As a context manager for temporary configuration |
| 23 | +
|
| 24 | + Parameters |
| 25 | + ---------- |
| 26 | + use_binary : bool, optional |
| 27 | + Prefer binary files for arrays. Default is False. |
| 28 | + binary_threshold : int, optional |
| 29 | + Size threshold (in bytes) for using binary format. |
| 30 | + Arrays larger than this will be written as binary. |
| 31 | + If None, use_binary setting is used unconditionally. |
| 32 | + float_precision : int, optional |
| 33 | + Number of decimal places for float output. Default is 6. |
| 34 | + use_relative_paths : bool, optional |
| 35 | + Use relative paths in input files. Default is True. |
| 36 | + array_format : ArrayFormat, optional |
| 37 | + How to write array data: 'internal', 'constant', or 'open/close'. |
| 38 | + If None, automatically determined based on array properties. |
| 39 | +
|
| 40 | + Examples |
| 41 | + -------- |
| 42 | + >>> # Attach to component |
| 43 | + >>> ctx = WriteContext(float_precision=8, use_binary=True) |
| 44 | + >>> sim.write_context = ctx |
| 45 | + >>> sim.write() |
| 46 | +
|
| 47 | + >>> # Pass to write method |
| 48 | + >>> sim.write(context=WriteContext(float_precision=4)) |
| 49 | +
|
| 50 | + >>> # Use as context manager |
| 51 | + >>> with WriteContext(use_binary=True, float_precision=8): |
| 52 | + ... sim.write() |
| 53 | + """ |
| 54 | + |
| 55 | + use_binary: bool = field(default=False) |
| 56 | + binary_threshold: Optional[int] = field(default=None) |
| 57 | + float_precision: int = field(default=6) |
| 58 | + use_relative_paths: bool = field(default=True) |
| 59 | + array_format: Optional[ArrayFormat] = field(default=None) |
| 60 | + |
| 61 | + # Class-level thread-local storage for context stack |
| 62 | + _context_stack: threading.local = field(init=False, factory=threading.local) |
| 63 | + |
| 64 | + def __enter__(self) -> "WriteContext": |
| 65 | + """Enter context manager, pushing this context onto the stack.""" |
| 66 | + if not hasattr(self._context_stack, "stack"): |
| 67 | + self._context_stack.stack = [] |
| 68 | + self._context_stack.stack.append(self) |
| 69 | + return self |
| 70 | + |
| 71 | + def __exit__(self, exc_type, exc_val, exc_tb) -> None: |
| 72 | + """Exit context manager, popping this context from the stack.""" |
| 73 | + if hasattr(self._context_stack, "stack") and self._context_stack.stack: |
| 74 | + self._context_stack.stack.pop() |
| 75 | + |
| 76 | + @classmethod |
| 77 | + def current(cls) -> "WriteContext": |
| 78 | + """ |
| 79 | + Get the currently active WriteContext from the context stack. |
| 80 | +
|
| 81 | + Returns the most recently entered context manager, or a default |
| 82 | + context if no context manager is active. |
| 83 | +
|
| 84 | + Returns |
| 85 | + ------- |
| 86 | + WriteContext |
| 87 | + The active context, or a default context. |
| 88 | + """ |
| 89 | + # Create a class-level thread-local if it doesn't exist |
| 90 | + if not hasattr(cls, "_global_context_stack"): |
| 91 | + cls._global_context_stack = threading.local() |
| 92 | + |
| 93 | + if ( |
| 94 | + hasattr(cls._global_context_stack, "stack") |
| 95 | + and cls._global_context_stack.stack |
| 96 | + ): |
| 97 | + return cls._global_context_stack.stack[-1] |
| 98 | + return cls.default() |
| 99 | + |
| 100 | + @classmethod |
| 101 | + def default(cls) -> "WriteContext": |
| 102 | + """ |
| 103 | + Create a WriteContext with default settings. |
| 104 | +
|
| 105 | + Returns |
| 106 | + ------- |
| 107 | + WriteContext |
| 108 | + A context with default configuration values. |
| 109 | + """ |
| 110 | + return cls() |
| 111 | + |
| 112 | + def to_numpy_printoptions(self) -> dict: |
| 113 | + """ |
| 114 | + Convert WriteContext settings to numpy printoptions dict. |
| 115 | +
|
| 116 | + Returns |
| 117 | + ------- |
| 118 | + dict |
| 119 | + Dictionary suitable for use with np.printoptions() |
| 120 | + """ |
| 121 | + import sys |
| 122 | + |
| 123 | + return { |
| 124 | + "precision": self.float_precision, |
| 125 | + "linewidth": sys.maxsize, |
| 126 | + "threshold": sys.maxsize, |
| 127 | + } |
| 128 | + |
| 129 | + def get_float_format(self) -> str: |
| 130 | + """ |
| 131 | + Get the float format string based on precision setting. |
| 132 | +
|
| 133 | + Returns |
| 134 | + ------- |
| 135 | + str |
| 136 | + Format string for floating point numbers (e.g., "%.6e") |
| 137 | + """ |
| 138 | + return f"%.{self.float_precision}e" |
0 commit comments