Skip to content

Commit

Permalink
Consolidate nwb writing methods and check file exists
Browse files Browse the repository at this point in the history
  • Loading branch information
bjhardcastle committed May 28, 2024
1 parent 4239e27 commit 8ba3e78
Showing 1 changed file with 14 additions and 26 deletions.
40 changes: 14 additions & 26 deletions src/npc_sessions/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,8 +348,8 @@ def nwb(self) -> pynwb.NWBFile:
units=self.units if self.is_sorted else None,
)

def write_nwb_hdf5(
self, path: str | npc_io.PathLike | None = None, metadata_only: bool = False
def write_nwb(
self, path: str | npc_io.PathLike | None = None, metadata_only: bool = False, zarr=True, force=False,
) -> upath.UPath:
"""Write NWB file to disk - file path is normalized and returned"""
if path is None:
Expand All @@ -358,32 +358,20 @@ def write_nwb_hdf5(
path = npc_io.from_pathlike(path)
path = path.with_stem(
path.name.replace(".hdf5", "").replace(".nwb", "").replace(".zarr", "")
).with_suffix(".nwb")
).with_suffix(".nwb.zarr" if zarr else ".nwb")
if not force and path.exists() and (npc_io.get_size(path) // 1024) > 1:
raise FileExistsError(f"{path} already exists - use `force=True` to overwrite")
elif force and zarr and path.exists():
logger.warning(f"Overwriting zarr directories is not advised: remnants of previous data may remain.\nSuggest deleting {path} first.")
nwb = self.nwb if not metadata_only else self.metadata
with pynwb.NWBHDF5IO(path.as_posix(), "w") as io:
io.write(nwb)
logger.info(
f"Saved NWB file to {path}: {npc_io.get_size(path) // 1024 ** 2} MB"
)
return path

def write_nwb_zarr(
self, path: str | npc_io.PathLike | None = None, metadata_only: bool = False
) -> upath.UPath:
"""Write NWB file to disk - file path is normalized and returned"""
if path is None:
path = npc_lims.get_nwb_path(self.id)
if zarr:
with hdmf_zarr.NWBZarrIO(path.as_posix(), "w") as io:
io.write(
nwb, link_data=False
) # link_data=False so that lazily-opened zarrays are read and copied into nwb (instead of being added as a link, which is currently broken)
else:
path = npc_io.from_pathlike(path)
path = path.with_stem(
path.name.replace(".hdf5", "").replace(".nwb", "").replace(".zarr", "")
).with_suffix(".nwb.zarr")
nwb = self.nwb if not metadata_only else self.metadata
with hdmf_zarr.NWBZarrIO(path.as_posix(), "w") as io:
io.write(
nwb, link_data=False
) # link_data=False so that lazily-opened zarrays are read and copied into nwb (instead of being added as a link, which is currently broken)
# zarr "file" is a directory:
with pynwb.NWBHDF5IO(path.as_posix(), "w") as io:
io.write(nwb)
logger.info(
f"Saved NWB file to {path}: {npc_io.get_size(path) // 1024 ** 2} MB"
)
Expand Down

0 comments on commit 8ba3e78

Please sign in to comment.