Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 19
segy_to_mdio_v1#577
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Uh oh!
There was an error while loading. Please reload this page.
segy_to_mdio_v1 #577
Changes from all commits
7ff26e75ae7258e8b95dcbe772c7e43e4da80dd2347caca552b2acf273d827abefeca0ec057e659d12e92f3eabf0477bed5f7b135d6a4a350b4c29f340f78a2c34d3493c4b30324879a5debcf97b96b2931152994b1ae8f21e9e04c5f9a63b73cc6855315aa3e64fba1f4687fe39d8c6972a05d84ceb574ff62bc543e8868017d9890754d3f0a1c285d07ea4b50306915febc95980ec98e5f7a0f0f42f3a441db8d574a47cf90b7ea5ae874ab08ef4b970d742f37c194f30d9571dcd0d17714911f820a4b52f5347c6a38fba3307f5e8a1c5d03e460c8f7cff047ea4508c1e7081af582f2d59a918726ed75a0915174c8fd63737a6c55c080406a6b373073e729bbb70b13a57c4d1dc8f0d410d3e7cecedfafe8ab2b984860517a57eb8bac722c461319812e900ef757528acb1d7b9013792286cc31bc45bdde865e1405ecFile filter
Filter by extension
Conversations
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Uh oh!
There was an error while loading. Please reload this page.
dmitriyrepin marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| """A module for converting numpy dtypes to MDIO scalar and structured types.""" | ||
| from numpy import dtype as np_dtype | ||
| from mdio.schemas.dtype import ScalarType | ||
| from mdio.schemas.dtype import StructuredField | ||
| from mdio.schemas.dtype import StructuredType | ||
| def to_scalar_type(data_type: np_dtype) -> ScalarType: | ||
| """Convert numpy dtype to MDIO ScalarType. | ||
| Out of the 24 built-in numpy scalar type objects | ||
| (see https://numpy.org/doc/stable/reference/arrays.dtypes.html) | ||
| this function supports only a limited subset: | ||
| ScalarType.INT8 <-> int8 | ||
| ScalarType.INT16 <-> int16 | ||
| ScalarType.INT32 <-> int32 | ||
| ScalarType.INT64 <-> int64 | ||
| ScalarType.UINT8 <-> uint8 | ||
| ScalarType.UINT16 <-> uint16 | ||
| ScalarType.UINT32 <-> uint32 | ||
| ScalarType.UINT64 <-> uint64 | ||
| ScalarType.FLOAT32 <-> float32 | ||
| ScalarType.FLOAT64 <-> float64 | ||
| ScalarType.COMPLEX64 <-> complex64 | ||
| ScalarType.COMPLEX128 <-> complex128 | ||
| ScalarType.BOOL <-> bool | ||
| Args: | ||
| data_type: numpy dtype to convert | ||
| Returns: | ||
| ScalarType: corresponding MDIO scalar type | ||
| Raises: | ||
| ValueError: if dtype is not supported | ||
| """ | ||
| try: | ||
| return ScalarType(data_type.name) | ||
| except ValueError as exc: | ||
| err = f"Unsupported numpy dtype '{data_type.name}' for conversion to ScalarType." | ||
| raise ValueError(err) from exc | ||
| def to_structured_type(data_type: np_dtype) -> StructuredType: | ||
| """Convert numpy dtype to MDIO StructuredType. | ||
| This function supports only a limited subset of structured types. | ||
| In particular: | ||
| It does not support nested structured types. | ||
| It supports fields of only 13 out of 24 built-in numpy scalar types. | ||
| (see `to_scalar_type` for details). | ||
| Args: | ||
| data_type: numpy dtype to convert | ||
| Returns: | ||
| StructuredType: corresponding MDIO structured type | ||
| Raises: | ||
| ValueError: if dtype is not structured or has no fields | ||
| """ | ||
| if data_type is None or len(data_type.names or []) == 0: | ||
| err = "None or empty dtype provided, cannot convert to StructuredType." | ||
| raise ValueError(err) | ||
| fields = [] | ||
| for field_name in data_type.names: | ||
| field_dtype = data_type.fields[field_name][0] | ||
| scalar_type = to_scalar_type(field_dtype) | ||
| structured_field = StructuredField(name=field_name, format=scalar_type) | ||
| fields.append(structured_field) | ||
| return StructuredType(fields=fields) | ||
| def to_numpy_dtype(data_type: ScalarType | StructuredType) -> np_dtype: | ||
| """Get the numpy dtype for a variable.""" | ||
| if isinstance(data_type, ScalarType): | ||
| return np_dtype(data_type.value) | ||
| if isinstance(data_type, StructuredType): | ||
| return np_dtype([(f.name, f.format.value) for f in data_type.fields]) | ||
| msg = f"Expected ScalarType or StructuredType, got '{type(data_type).__name__}'" | ||
| raise ValueError(msg) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| """StorageLocation class for managing local and cloud storage locations.""" | ||
| from pathlib import Path | ||
| from typing import Any | ||
| import fsspec | ||
| # TODO(Dmitriy Repin): Reuse fsspec functions for some methods we implemented here | ||
| # https://github.com/TGSAI/mdio-python/issues/597 | ||
| class StorageLocation: | ||
tasansal marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| """A class to represent a local or cloud storage location for SEG-Y or MDIO files. | ||
| This class abstracts the storage location, allowing for both local file paths and | ||
| cloud storage URIs (e.g., S3, GCS). It uses fsspec to check existence and manage options. | ||
| Note, we do not want to make it a dataclass because we want the uri and the options to | ||
| be read-only immutable properties. | ||
| uri: The URI of the storage location (e.g., '/path/to/file', 'file:///path/to/file', | ||
| 's3://bucket/path', 'gs://bucket/path'). | ||
| options: Optional dictionary of options for the cloud, such as credentials. | ||
| """ | ||
| def __init__(self, uri: str = "", options: dict[str, Any] = None): | ||
| self._uri = uri | ||
| self._options = options or {} | ||
| self._fs = None | ||
| if uri.startswith(("s3://", "gs://")): | ||
| return | ||
| if uri.startswith("file://"): | ||
| self._uri = self._uri.removeprefix("file://") | ||
| # For local paths, ensure they are absolute and resolved | ||
| self._uri = str(Path(self._uri).resolve()) | ||
| return | ||
| @property | ||
| def uri(self) -> str: | ||
| """Get the URI (read-only).""" | ||
| return self._uri | ||
| @property | ||
| def options(self) -> dict[str, Any]: | ||
| """Get the options (read-only).""" | ||
| # Return a copy to prevent external modification | ||
| return self._options.copy() | ||
| @property | ||
| def _filesystem(self) -> fsspec.AbstractFileSystem: | ||
| """Get the fsspec filesystem instance for this storage location.""" | ||
| if self._fs is None: | ||
| self._fs = fsspec.filesystem(self._protocol, **self._options) | ||
| return self._fs | ||
| @property | ||
| def _path(self) -> str: | ||
| """Extract the path portion from the URI.""" | ||
| if "://" in self._uri: | ||
| return self._uri.split("://", 1)[1] | ||
| return self._uri # For local paths without file:// prefix | ||
| @property | ||
| def _protocol(self) -> str: | ||
| """Extract the protocol/scheme from the URI.""" | ||
| if "://" in self._uri: | ||
| return self._uri.split("://", 1)[0] | ||
| return "file" # Default to file protocol | ||
| def exists(self) -> bool: | ||
| """Check if the storage location exists using fsspec.""" | ||
| try: | ||
| return self._filesystem.exists(self._path) | ||
| except Exception as e: | ||
| # Log the error and return False for safety | ||
| # In a production environment, you might want to use proper logging | ||
| print(f"Error checking existence of {self._uri}: {e}") | ||
| return False | ||
| def __str__(self) -> str: | ||
| """String representation of the storage location.""" | ||
| return self._uri | ||
| def __repr__(self) -> str: | ||
| """Developer representation of the storage location.""" | ||
| return f"StorageLocation(uri='{self._uri}', options={self._options})" | ||
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.