| 1 |
""" |
| 2 |
Search for information within NIX file(s). Use the "file" command for |
| 3 |
general information about the file(s). The verbose flag can be used to get |
| 4 |
more detailed information about the file structure. Multiple -v options |
| 5 |
increase the verbosity. |
| 6 |
(e.g. 'nixio explore file nix_file -vvv' for most detailed output). |
| 7 |
|
| 8 |
The "metadata" (mdata) and "data" commands provide further options for finding |
| 9 |
and viewing data and metadata information. With the "dump" subcommand data can |
| 10 |
be dumped to file (up to 3D data). |
| 11 |
|
| 12 |
The "plot" command is only available if the nixworks package is installed |
| 13 |
(https://github.com/G-node/nixworks). |
| 14 |
|
| 15 |
NOTE: This tool is under active development. Please use the github issue |
| 16 |
tracker (https://github.com/G-node/nixpy/issues) for bug reports and feature |
| 17 |
requests. |
| 18 |
""" |
| 19 |
import os |
| 20 |
import nixio as nix |
| 21 |
import numpy as np |
| 22 |
import glob |
| 23 |
import datetime as dt |
| 24 |
import sys |
| 25 |
|
| 26 |
try: |
| 27 |
import nixworks as nw |
| 28 |
NIX_WORKS = True |
| 29 |
except ImportError: |
| 30 |
NIX_WORKS = False |
| 31 |
|
| 32 |
TOOL_DESCRIPTION = """ |
| 33 |
nixio explore functionality is split into sub-commands for file, metadata, and data exploration. For help on the |
| 34 |
commands type e.g.: 'nixio explore file --help'. |
| 35 |
""" |
| 36 |
|
| 37 |
METADATA_PATTERN_HELP = """ |
| 38 |
Pattern(s) with which to look for sections and properties. The pattern can be either 1) type_or_name: First looks for a |
| 39 |
section matching in type or name or a property with matching name. 2) type_or_name/prop_name: first looks for a matching |
| 40 |
section and within those for matching properties. Patterns are applied case-insensitive and can be partial matches. You |
| 41 |
can provide multiple patterns by calling the command like: `nixio explore metadata -p "subject" -p "species" file1.nix |
| 42 |
file2.nix` |
| 43 |
""" |
| 44 |
|
| 45 |
DATA_PARSER_HELP = """ |
| 46 |
Display information about data entities such as DataArrays, Tags, or MultiTags. |
| 47 |
""" |
| 48 |
|
| 49 |
DATA_PATTERN_HELP = """ |
| 50 |
A string pattern that is parsed to find the data entity. |
| 51 |
""" |
| 52 |
|
| 53 |
DUMP_PARSER_HELP = """ |
| 54 |
Dump data to file or stdout. This command can process up to 3D data. The data dump contains dimension information as |
| 55 |
well as the stored data. To write the data to text file use e.g. 'nixio explore dump path_to_nix_file -p "name or type |
| 56 |
of data entity" > data.dump' or provide the "--outfile" argument. |
| 57 |
""" |
| 58 |
|
| 59 |
DUMP_PATTERN_HELP = DATA_PATTERN_HELP |
| 60 |
|
| 61 |
DUMP_OUTFILE_HELP = """ |
| 62 |
Name of a file into which the data should be dumped. If not given data will be dumped to stdout. |
| 63 |
""" |
| 64 |
|
| 65 |
PLOT_PARSER_HELP = """ |
| 66 |
Create basic plots of the stored data. This command is only available if nixworks is installed. |
| 67 |
""" |
| 68 |
|
| 69 |
|
| 70 |
def progress(count, total, status='', bar_len=60): |
| 71 |
""" |
| 72 |
Modified after https://gist.github.com/vladignatyev/06860ec2040cb497f0f3 by Vladimir Ignatev published under MIT |
| 73 |
License |
| 74 |
""" |
| 75 |
percents = count / total |
| 76 |
filled_len = int(percents * bar_len) |
| 77 |
prog_bar = '=' * filled_len + '-' * (bar_len - filled_len) |
| 78 |
|
| 79 |
sys.stderr.write('[%s] %.2f%s ...%s\r' % |
| 80 |
(prog_bar, percents * 100, '%', status)) |
| 81 |
sys.stderr.flush() |
| 82 |
|
| 83 |
|
| 84 |
def open_nix_file(filename): |
| 85 |
nf = None |
| 86 |
try: |
| 87 |
nf = nix.File.open(filename, nix.FileMode.ReadOnly) |
| 88 |
except Exception as exc: |
| 89 |
print("ERROR: '{}' is not a valid NIX file!\n\t error message was: '{}'".format(filename, |
| 90 |
exc)) |
| 91 |
return nf |
| 92 |
|
| 93 |
|
| 94 |
def assemble_files(arguments): |
| 95 |
filenames = sorted(arguments.file) |
| 96 |
all_files = [] |
| 97 |
for filename in filenames: |
| 98 |
if os.path.isfile(filename): |
| 99 |
all_files.append(filename) |
| 100 |
elif os.path.isdir(filename): |
| 101 |
filename = os.sep.join((filename, "*." + arguments.suffix)) |
| 102 |
all_files.extend(sorted(glob.glob(filename))) |
| 103 |
else: |
| 104 |
candidates = sorted(glob.glob(filename)) |
| 105 |
if len(candidates) == 0: |
| 106 |
print( |
| 107 |
"Error: invalid file or directory! No matches found. '{}'".format(filename)) |
| 108 |
for candidate in candidates: |
| 109 |
if os.path.isdir(candidate): |
| 110 |
candidate = os.sep.join( |
| 111 |
(candidate, "*." + arguments.suffix)) |
| 112 |
all_files.extend(sorted(glob.glob(candidate))) |
| 113 |
elif os.path.isfile(candidate): |
| 114 |
all_files.append(candidate) |
| 115 |
|
| 116 |
return all_files |
| 117 |
|
| 118 |
|
| 119 |
def disp_file_structure(nix_file, verbosity): |
| 120 |
def block_content(nix_file, verbosity): |
| 121 |
def array_content(block, verbosity): |
| 122 |
def dimension_description(data_array, _): |
| 123 |
content = ", dimensions: [" |
| 124 |
dim_desc = [d.label if d.dimension_type == nix.DimensionType.Sample or |
| 125 |
d.dimension_type == nix.DimensionType.Range else d.dimension_type |
| 126 |
for d in data_array.dimensions] |
| 127 |
content += ",".join(dim_desc) |
| 128 |
content += "]" |
| 129 |
return content |
| 130 |
|
| 131 |
def array_structure(data_array, verbosity): |
| 132 |
dims = dimension_description(data_array, verbosity) |
| 133 |
content = "\n shape: %s, dtype: %s %s" % ( |
| 134 |
data_array.shape, data_array.dtype, dims) |
| 135 |
return content |
| 136 |
|
| 137 |
content = " Data Arrays:\n" if len( |
| 138 |
block.data_arrays) > 0 else "" |
| 139 |
for da in block.data_arrays: |
| 140 |
array_struct = array_structure( |
| 141 |
da, verbosity) if verbosity > 2 else "" |
| 142 |
content += " %s [%s] --- id: %s %s\n" % ( |
| 143 |
da.name, da.type, da.id, array_struct) |
| 144 |
return content |
| 145 |
|
| 146 |
def group_content(block, _): |
| 147 |
content = " Groups:\n" if len(block.groups) > 0 else "" |
| 148 |
for grp in block.groups: |
| 149 |
content += " %s [%s] -- id: %s\n" % ( |
| 150 |
grp.name, grp.type, grp.id) |
| 151 |
return content |
| 152 |
|
| 153 |
def tag_content(block, verbosity): |
| 154 |
def tag_details(tag, verbosity): |
| 155 |
if verbosity < 3: |
| 156 |
return "" |
| 157 |
|
| 158 |
content = " start: %s, extent: %s" % ( |
| 159 |
tag.position, tag.extent) |
| 160 |
for ref in tag.references: |
| 161 |
content += "\n refers to -> %s" % ref.name |
| 162 |
for feat in tag.features: |
| 163 |
content += "\n feature in -> %s" % feat.data.name |
| 164 |
content += "\n" |
| 165 |
return content |
| 166 |
|
| 167 |
content = " Tags:\n" |
| 168 |
for tag in block.tags: |
| 169 |
content += " %s [%s] --- id: %s\n %s" % ( |
| 170 |
tag.name, tag.type, tag.id, tag_details(tag, verbosity)) |
| 171 |
return content |
| 172 |
|
| 173 |
def mtag_content(block, verbosity): |
| 174 |
def tag_details(tag, verbosity): |
| 175 |
if verbosity < 3: |
| 176 |
return "" |
| 177 |
|
| 178 |
content = " start: %s, extent: %s" % ( |
| 179 |
tag.position[:], tag.extent[:]) |
| 180 |
for ref in tag.references: |
| 181 |
content += "\n segment refers to -> %s" % ref.name |
| 182 |
for feat in tag.features: |
| 183 |
content += "\n segment feature(s) in -> %s" % feat.data.name |
| 184 |
content += "\n" |
| 185 |
return content |
| 186 |
|
| 187 |
content = " Multi-Tags:\n" |
| 188 |
for tag in block.tags: |
| 189 |
content += " %s [%s] --- id: %s\n %s" % (tag.name, tag.type, tag.id, |
| 190 |
tag_details(tag, verbosity)) |
| 191 |
return content |
| 192 |
|
| 193 |
def frame_content(block, _): |
| 194 |
content = " Data frames:\n" if len( |
| 195 |
block.data_frames) > 0 else "" |
| 196 |
for df in block.data_frames: |
| 197 |
content += " %s [%s] -- id: %s\n" % ( |
| 198 |
df.name, df.type, df.id) |
| 199 |
return content |
| 200 |
|
| 201 |
def source_content(block, _): |
| 202 |
content = " Sources:\n" if len(block.groups) > 0 else "" |
| 203 |
for src in block.sources: |
| 204 |
content += " %s [%s] -- id: %s\n" % ( |
| 205 |
src.name, src.type, src.id) |
| 206 |
return content |
| 207 |
|
| 208 |
content = "" |
| 209 |
if verbosity < 1: |
| 210 |
content += " %i block(s)" % len(nix_file.blocks) |
| 211 |
else: |
| 212 |
for blk in nix_file.blocks: |
| 213 |
arrays = array_content(blk, verbosity) if verbosity > 1 \ |
| 214 |
else " %i data arrays\n" % len(blk.data_arrays) |
| 215 |
if getattr(blk, "data_frames", None) is not None: |
| 216 |
frames = frame_content(blk, verbosity) if verbosity > 1 \ |
| 217 |
else " %i data frames\n" % len(blk.data_frames) |
| 218 |
else: |
| 219 |
frames = "" |
| 220 |
groups = group_content(blk, verbosity) if verbosity > 1 \ |
| 221 |
else " %i groups\n" % len(blk.groups) |
| 222 |
tags = tag_content(blk, verbosity) if verbosity > 1 \ |
| 223 |
else " %i tags\n" % len(blk.tags) |
| 224 |
mtags = mtag_content(blk, verbosity) if verbosity > 1 \ |
| 225 |
else " %i multi-tags\n" % len(blk.multi_tags) |
| 226 |
srcs = source_content(blk, verbosity) if verbosity > 1 \ |
| 227 |
else " %i sources\n" % len(blk.sources) |
| 228 |
content += " %s [%s] --- id: %s\n%s%s%s%s%s%s\n" % (blk.name, blk.type, blk.id, arrays, frames, |
| 229 |
groups, tags, mtags, srcs) |
| 230 |
return content |
| 231 |
|
| 232 |
def section_content(nix_file, verbosity): |
| 233 |
def subsections(section, _): |
| 234 |
content = "" |
| 235 |
sections = section.find_sections() |
| 236 |
prop_count = sum([len(sec) for sec in sections]) |
| 237 |
content += "\n %i sub-section(s), %i properties\n" % ( |
| 238 |
len(sections), prop_count) |
| 239 |
return content |
| 240 |
|
| 241 |
content = "" |
| 242 |
if verbosity < 1: |
| 243 |
content += " %i section(s)" % len(nix_file.find_sections()) |
| 244 |
else: |
| 245 |
for section in nix_file.sections: |
| 246 |
subs_props = subsections(section, verbosity) |
| 247 |
content += " %s [%s] --- id: %s%s" % ( |
| 248 |
section.name, section.type, section.id, subs_props) |
| 249 |
return content |
| 250 |
|
| 251 |
def file_content(nix_file, verbosity): |
| 252 |
if verbosity is None: |
| 253 |
verbosity = 0 |
| 254 |
content = "" |
| 255 |
if verbosity < 1: |
| 256 |
content += "%s\n%s" % (block_content(nix_file, verbosity), |
| 257 |
section_content(nix_file, verbosity)) |
| 258 |
else: |
| 259 |
content += " data:\n%s" % block_content(nix_file, verbosity) |
| 260 |
content += " metadata:\n%s\n" % section_content( |
| 261 |
nix_file, verbosity) |
| 262 |
return content |
| 263 |
|
| 264 |
print("\n%s\n\n" % file_content(nix_file, verbosity)) |
| 265 |
|
| 266 |
|
| 267 |
def disp_file_info(filename, arguments): |
| 268 |
nf = open_nix_file(filename) |
| 269 |
if nf is None: |
| 270 |
pass |
| 271 |
|
| 272 |
print(" File: %s" % (filename.split(os.sep)[-1])) |
| 273 |
print(" format: %s \n version: %s " % (nf.format, nf.version)) |
| 274 |
print(" created at: %s \n last updated: %s" % |
| 275 |
(str(dt.datetime.fromtimestamp(nf.created_at)), |
| 276 |
str(dt.datetime.fromtimestamp(nf.updated_at)))) |
| 277 |
print(" size on disk: %.2f MB" % (os.path.getsize(filename) / 10**6)) |
| 278 |
print(" location: %s" % os.path.split(filename)[0]) |
| 279 |
disp_file_structure(nf, arguments.verbosity) |
| 280 |
nf.close() |
| 281 |
|
| 282 |
|
| 283 |
def find_section(nix_file, pattern, case_sensitive=False, full_match=False): |
| 284 |
def type_lambda(typ, full_match): |
| 285 |
if full_match: |
| 286 |
return lambda s: typ.lower() == s.type.lower() |
| 287 |
else: |
| 288 |
return lambda s: typ.lower() in s.type.lower() |
| 289 |
|
| 290 |
def name_lambda(name, full_match): |
| 291 |
if full_match: |
| 292 |
return lambda s: name.lower() == s.name.lower() |
| 293 |
else: |
| 294 |
return lambda s: name.lower() in s.name.lower() |
| 295 |
|
| 296 |
def name_lambda_cs(name, full_match): |
| 297 |
if full_match: |
| 298 |
return lambda s: name == s.name |
| 299 |
else: |
| 300 |
return lambda s: name in s.name |
| 301 |
|
| 302 |
secs = nix_file.find_sections(type_lambda(pattern, full_match)) |
| 303 |
if len(secs) == 0: |
| 304 |
secs = nix_file.find_sections(name_lambda_cs(pattern, full_match) if case_sensitive |
| 305 |
else name_lambda(pattern, full_match)) |
| 306 |
return secs |
| 307 |
|
| 308 |
|
| 309 |
def find_props(nix_file, pattern, case_sensitive=False, full_match=False): |
| 310 |
name = pattern if case_sensitive else pattern.lower() |
| 311 |
props = {} |
| 312 |
for sec in nix_file.find_sections(lambda s: True): |
| 313 |
for prop in sec.props: |
| 314 |
pname = prop.name if case_sensitive else prop.name.lower() |
| 315 |
if name == pname if full_match else name in pname: |
| 316 |
if sec not in props.keys(): |
| 317 |
props[sec] = [] |
| 318 |
props[sec].append(prop) |
| 319 |
return props |
| 320 |
|
| 321 |
|
| 322 |
def disp_metadata(filename, arguments): |
| 323 |
case_sensitive = arguments.case_sensitive |
| 324 |
full_match = arguments.full_match |
| 325 |
nf = open_nix_file(filename) |
| 326 |
if nf is None: |
| 327 |
return |
| 328 |
print("%s: " % (filename.split(os.sep)[-1]), end="\n") |
| 329 |
if arguments.pattern is None or len(arguments.pattern) == 0: |
| 330 |
for sec in nf.sections: |
| 331 |
sec.pprint(max_depth=arguments.depth) |
| 332 |
else: |
| 333 |
for patt in arguments.pattern: |
| 334 |
if "/" in patt: |
| 335 |
parts = patt.split("/") |
| 336 |
sections = find_section(nf, parts[0], case_sensitive) |
| 337 |
for sec in sections: |
| 338 |
for prop in sec.props: |
| 339 |
part = parts[1] if case_sensitive else parts[1].lower() |
| 340 |
pname = prop.name if case_sensitive else prop.name.lower() |
| 341 |
if part == pname if full_match else part in pname: |
| 342 |
print("[section: %s, type: %s, id: %s] >> " % |
| 343 |
(sec.name, sec.type, sec.id), end="") |
| 344 |
prop.pprint() |
| 345 |
else: |
| 346 |
sections = find_section(nf, patt, case_sensitive) |
| 347 |
if len(sections) == 0: |
| 348 |
props = find_props(nf, patt, case_sensitive) |
| 349 |
for sec in props.keys(): |
| 350 |
for prop in props[sec]: |
| 351 |
print("[section: %s, type: %s, id: %s] >> " % |
| 352 |
(sec.name, sec.type, sec.id), end="") |
| 353 |
prop.pprint() |
| 354 |
else: |
| 355 |
for sec in sections: |
| 356 |
sec.pprint(max_depth=arguments.depth) |
| 357 |
|
| 358 |
nf.close() |
| 359 |
print("\n\n") |
| 360 |
|
| 361 |
|
| 362 |
def mdata_worker(arguments): |
| 363 |
files = assemble_files(arguments) |
| 364 |
for nf in files: |
| 365 |
disp_metadata(nf, arguments) |
| 366 |
|
| 367 |
|
| 368 |
def find_data_entity(nix_file, arguments): |
| 369 |
name_or_type = arguments.pattern if arguments.case_sensitive else arguments.pattern.lower() |
| 370 |
classes = ["data_arrays"] |
| 371 |
entities = [] |
| 372 |
for block in nix_file.blocks: |
| 373 |
for cls in classes: |
| 374 |
for entity in getattr(block, cls): |
| 375 |
ename = entity.name() if arguments.case_sensitive else entity.name.lower() |
| 376 |
etype = entity.type() if arguments.case_sensitive else entity.type.lower() |
| 377 |
if arguments.full_match: |
| 378 |
if ename == name_or_type or etype == name_or_type: |
| 379 |
entities.append(entity) |
| 380 |
else: |
| 381 |
if name_or_type in ename or name_or_type in etype: |
| 382 |
entities.append(entity) |
| 383 |
return entities |
| 384 |
|
| 385 |
|
| 386 |
def get_ticks(dimension, extent): |
| 387 |
ticks = None |
| 388 |
dim_type = dimension.dimension_type |
| 389 |
if dim_type == nix.DimensionType.Sample: |
| 390 |
ticks = np.array(dimension.axis(extent)) |
| 391 |
elif dim_type == nix.DimensionType.Range: |
| 392 |
ticks = np.array(dimension.ticks) |
| 393 |
elif dim_type == nix.DimensionType.Set: |
| 394 |
ticks = np.array(dimension.labels) |
| 395 |
if len(ticks) == 0: |
| 396 |
ticks = np.arange(0., extent, 1.0) |
| 397 |
elif dim_type == nix.DimensionType.DataFrame: |
| 398 |
ticks = np.array(dimension.ticks) |
| 399 |
else: |
| 400 |
print("Unsupported dimension type!") |
| 401 |
return ticks |
| 402 |
|
| 403 |
|
| 404 |
def get_dim_label_and_unit(dimension): |
| 405 |
dim_label = getattr(dimension, "label") if hasattr(dimension, "label") \ |
| 406 |
and getattr(dimension, "label") else "" |
| 407 |
dim_unit = getattr(dimension, "unit") if hasattr(dimension, "unit") \ |
| 408 |
and getattr(dimension, "unit") else "" |
| 409 |
return dim_label, dim_unit |
| 410 |
|
| 411 |
|
| 412 |
def dump_oned(data, dimension, label, unit, outfile, fmt="%.6f", end="\n\n", |
| 413 |
forgiving=True, show_progress=False): |
| 414 |
if len(data.shape) > 1: |
| 415 |
raise ValueError("data dimensionality is too deep, " |
| 416 |
"expected 1D data, got %iD" % len(data.shape)) |
| 417 |
ticks = get_ticks(dimension, data.shape[0]) |
| 418 |
if len(ticks) != len(data): |
| 419 |
if not forgiving: |
| 420 |
print("Cannot dump data, could not read the dimension values on dimension " |
| 421 |
"%i (type: %s)!" % (dimension.index, dimension.dimension_type)) |
| 422 |
return |
| 423 |
else: |
| 424 |
ticks = np.arange(len(data)) |
| 425 |
dim_label, dim_unit = get_dim_label_and_unit(dimension) |
| 426 |
if isinstance(ticks[-1], str): |
| 427 |
max_tick_len = max([len(ticks[-1]), len(dim_label)]) |
| 428 |
else: |
| 429 |
max_tick_len = max([len(fmt % ticks[-1]), len(dim_label)]) |
| 430 |
|
| 431 |
numeric_dim_ticks = isinstance(ticks[0], (int, float)) |
| 432 |
numeric_data = isinstance(data[0], (int, float)) |
| 433 |
data_conv_func = (lambda x: fmt % x) if numeric_data else str |
| 434 |
dim_ticks_conv_func = (lambda x: fmt % x) if numeric_dim_ticks else str |
| 435 |
|
| 436 |
if dimension.dimension_type == nix.DimensionType.Range and dimension.has_link: |
| 437 |
print("# %s" % dim_label, file=outfile) |
| 438 |
print("# %s" % dim_unit, file=outfile) |
| 439 |
for idx, tick in enumerate(ticks): |
| 440 |
print(data_conv_func(tick), file=outfile) |
| 441 |
if show_progress and idx % 1000 == 0: |
| 442 |
progress(idx, data.shape[0], status='') |
| 443 |
else: |
| 444 |
padding = " " * (max_tick_len - len(dim_label) if dim_label else 0) |
| 445 |
print("# %s%s%s" % (dim_label, padding, label), file=outfile) |
| 446 |
padding = " " * (max_tick_len - len(dim_unit) if dim_unit else 0) |
| 447 |
print("# %s%s%s" % (dim_unit, padding, unit), file=outfile) |
| 448 |
|
| 449 |
for idx in range(data.shape[0]): |
| 450 |
if show_progress and idx % 1000 == 0: |
| 451 |
progress(idx, data.shape[0], status='') |
| 452 |
print(dim_ticks_conv_func(ticks[idx]) + " " + data_conv_func(data[idx]), |
| 453 |
file=outfile) |
| 454 |
if show_progress: |
| 455 |
progress(data.shape[0], data.shape[0], "Done") |
| 456 |
print(end, file=outfile) |
| 457 |
|
| 458 |
|
| 459 |
def dump_twod(data, dimensions, label, unit, outfile, fmt="%.6f", end="\n\n", |
| 460 |
show_progress=False): |
| 461 |
if len(data.shape) != 2 or len(dimensions) != 2: |
| 462 |
raise ValueError("data must be 2 dimensional and exactly two dimensions must be passed " |
| 463 |
"in order to dump the content properly.") |
| 464 |
first_dim_ticks = get_ticks(dimensions[0], data.shape[0]) |
| 465 |
second_dim_ticks = get_ticks(dimensions[1], data.shape[1]) |
| 466 |
if len(first_dim_ticks) != data.shape[0] or len(second_dim_ticks) != data.shape[1]: |
| 467 |
raise ValueError("dimension ticks for first or second dimension " |
| 468 |
"do not match the data shape.") |
| 469 |
|
| 470 |
first_dim_label, first_dim_unit = get_dim_label_and_unit(dimensions[0]) |
| 471 |
second_dim_label, second_dim_unit = get_dim_label_and_unit(dimensions[1]) |
| 472 |
|
| 473 |
numeric_1st_dim_ticks = isinstance(first_dim_ticks[0], (int, float)) |
| 474 |
numeric_2nd_dim_ticks = isinstance(second_dim_ticks[0], (int, float)) |
| 475 |
numeric_data = isinstance(data[0, 0], (int, float)) |
| 476 |
data_conv_func = (lambda x: fmt % x) if numeric_data else str |
| 477 |
dim_ticks_conv_func1 = (lambda x: fmt % |
| 478 |
x) if numeric_1st_dim_ticks else str |
| 479 |
dim_ticks_conv_func2 = (lambda x: fmt % |
| 480 |
x) if numeric_2nd_dim_ticks else str |
| 481 |
|
| 482 |
max_tick_len = max( |
| 483 |
[len(dim_ticks_conv_func1(first_dim_ticks[-1])), len(first_dim_label)]) |
| 484 |
print("# data label: %s" % label, file=outfile) |
| 485 |
print("# data unit: %s\n" % unit, file=outfile) |
| 486 |
padding = " " * (max_tick_len - (len(first_dim_label) |
| 487 |
if first_dim_unit else 0)) |
| 488 |
print("# %s%s%s" % (first_dim_label, padding, second_dim_label), file=outfile) |
| 489 |
padding = " " * (max_tick_len - (len(first_dim_unit) |
| 490 |
if first_dim_unit else 0)) |
| 491 |
print("# %s%s%s" % (first_dim_unit, padding, second_dim_unit), file=outfile) |
| 492 |
|
| 493 |
print(" " * max_tick_len + " " + (" " * max_tick_len + " ").join(map(dim_ticks_conv_func2, second_dim_ticks)), |
| 494 |
file=outfile) |
| 495 |
|
| 496 |
for i in range(len(first_dim_ticks)): |
| 497 |
print(dim_ticks_conv_func1(first_dim_ticks[i]) + " " + " ".join(map(data_conv_func, data[i, :])), |
| 498 |
file=outfile) |
| 499 |
if show_progress and i % 500 == 0: |
| 500 |
progress(i, data.shape[0], status='') |
| 501 |
if show_progress: |
| 502 |
progress(data.shape[0], data.shape[0], "Done") |
| 503 |
print(end, file=outfile) |
| 504 |
|
| 505 |
|
| 506 |
def dump_threed(data, dimensions, label, unit, outfile, fmt="%.6f", end="\n\n", |
| 507 |
show_progress=False): |
| 508 |
if len(data.shape) != 3 or len(dimensions) != 3: |
| 509 |
raise ValueError("data must be 3 dimensional and exactly three dimensions must be passed in order to dump " |
| 510 |
"the content properly.") |
| 511 |
ticks = get_ticks(dimensions[2], data.shape[2]) |
| 512 |
dim_label, dim_unit = get_dim_label_and_unit(dimensions[2]) |
| 513 |
|
| 514 |
for i in range(data.shape[2]): |
| 515 |
print("# data[:, :, %i]: %s" % (i, dim_label + "%s%s" % (ticks[i], dim_unit) |
| 516 |
if dim_unit else ""), file=outfile) |
| 517 |
dump_twod(data[:, :, i], [dimensions[0], dimensions[1]], label, unit, outfile, fmt, |
| 518 |
end="\n", show_progress=show_progress) |
| 519 |
|
| 520 |
print(end, file=outfile) |
| 521 |
|
| 522 |
|
| 523 |
def dump_data_array(array, filename, outfile, show_progress=False): |
| 524 |
print("# File: %s\n# entity: %s\n# type: %s\n# id: %s" % (filename, array.name, array.type, array.id), |
| 525 |
file=outfile) |
| 526 |
print("# created at: %s\n# last edited at: %s\n" % (str(dt.datetime.fromtimestamp(array.created_at)), |
| 527 |
str(dt.datetime.fromtimestamp(array.updated_at))), |
| 528 |
file=outfile) |
| 529 |
dims = len(array.shape) |
| 530 |
data = array[:] |
| 531 |
if dims == 1: |
| 532 |
dump_oned(data, array.dimensions[0], array.label, array.unit, outfile, |
| 533 |
show_progress=show_progress) |
| 534 |
elif dims == 2: |
| 535 |
dump_twod(data, array.dimensions, array.label, array.unit, outfile, |
| 536 |
show_progress=show_progress) |
| 537 |
elif dims == 3: |
| 538 |
dump_threed(data, array.dimensions, array.label, array.unit, outfile, |
| 539 |
show_progress=show_progress) |
| 540 |
else: |
| 541 |
print("Sorry, cannot dump data with more than 3 dimensions!") |
| 542 |
|
| 543 |
|
| 544 |
def data_dump(filename, arguments, outfile, show_progress=False): |
| 545 |
nix_file = open_nix_file(filename) |
| 546 |
entities = find_data_entity(nix_file, arguments) |
| 547 |
for ent in entities: |
| 548 |
if isinstance(ent, nix.DataArray): |
| 549 |
sys.stderr.write("Dumping %s to %s...\n" % |
| 550 |
(ent.name, arguments.outfile)) |
| 551 |
dump_data_array(ent, filename, outfile, show_progress) |
| 552 |
sys.stderr.write("\n") |
| 553 |
nix_file.close() |
| 554 |
|
| 555 |
|
| 556 |
def data_plotter(filename, arguments): |
| 557 |
nix_file = open_nix_file(filename) |
| 558 |
entities = find_data_entity(nix_file, arguments) |
| 559 |
for ent in entities: |
| 560 |
if isinstance(ent, nix.DataArray): |
| 561 |
plotter = nw.plotter.suggested_plotter(ent) |
| 562 |
if plotter: |
| 563 |
plotter.plot() |
| 564 |
plotter.show() |
| 565 |
else: |
| 566 |
print( |
| 567 |
"Could not find a suitable plotter for the DataArray: %s" % str(ent)) |
| 568 |
else: |
| 569 |
print("Sorry, so far I can only try to plot DataArrays.") |
| 570 |
|
| 571 |
nix_file.close() |
| 572 |
|
| 573 |
|
| 574 |
def disp_data(filename, arguments): |
| 575 |
nix_file = open_nix_file(filename) |
| 576 |
entities = find_data_entity(nix_file, arguments) |
| 577 |
print("# File: %s" % filename) |
| 578 |
for ent in entities: |
| 579 |
print("# entity: %s\n# type: %s\n# id: %s" % |
| 580 |
(ent.name, ent.type, ent.id)) |
| 581 |
print("# created at: %s\n# last edited at: %s\n" % (str(dt.datetime.fromtimestamp(ent.created_at)), |
| 582 |
str(dt.datetime.fromtimestamp(ent.updated_at)))) |
| 583 |
print(ent) |
| 584 |
print("\n") |
| 585 |
nix_file.close() |
| 586 |
|
| 587 |
|
| 588 |
def data_worker(arguments): |
| 589 |
files = assemble_files(arguments) |
| 590 |
for nf in files: |
| 591 |
disp_data(nf, arguments) |
| 592 |
|
| 593 |
|
| 594 |
def file_worker(arguments): |
| 595 |
files = assemble_files(arguments) |
| 596 |
for nf in files: |
| 597 |
disp_file_info(nf, arguments) |
| 598 |
|
| 599 |
|
| 600 |
def dump_worker(arguments): |
| 601 |
files = assemble_files(arguments) |
| 602 |
func = data_dump |
| 603 |
if len(arguments.outfile) > 0: |
| 604 |
if os.path.exists(arguments.outfile): |
| 605 |
response = input( |
| 606 |
"File %s already exists, are you sure to overwrite it? y/N:" % arguments.outfile) |
| 607 |
if response.lower() != "y": |
| 608 |
print("... data dump aborted.") |
| 609 |
return |
| 610 |
out_file = open(arguments.outfile, 'w') |
| 611 |
to_file = True |
| 612 |
else: |
| 613 |
out_file = sys.stdout |
| 614 |
to_file = False |
| 615 |
show_progress = to_file |
| 616 |
for out_file in files: |
| 617 |
func(out_file, arguments, out_file, show_progress) |
| 618 |
if to_file: |
| 619 |
out_file.close() |
| 620 |
|
| 621 |
|
| 622 |
def plot_worker(arguments): |
| 623 |
files = assemble_files(arguments) |
| 624 |
func = data_plotter |
| 625 |
for nf in files: |
| 626 |
func(nf, arguments) |
| 627 |
|
| 628 |
|
| 629 |
def add_default_file_args(parent_parser): |
| 630 |
parent_parser.add_argument("file", type=str, nargs="+", |
| 631 |
help="Path to file (at least one)") |
| 632 |
parent_parser.add_argument("-s", "--suffix", type=str, default="nix", nargs="?", |
| 633 |
help="The file suffix used for nix data files (default: %(default)s).") |
| 634 |
|
| 635 |
|
| 636 |
def add_default_args(parent_parser): |
| 637 |
parent_parser.add_argument("-c", "--case_sensitive", action="store_true", |
| 638 |
help=("matching of entitiy names and types is case sensitive, " |
| 639 |
"by default the case is ignored")) |
| 640 |
parent_parser.add_argument("-fm", "--full_match", action="store_true", |
| 641 |
help="names and types must be full matches, by default a partial match is sufficient") |
| 642 |
|
| 643 |
|
| 644 |
def create_metadata_parser(parent_parser): |
| 645 |
meta_parser = parent_parser.add_parser("metadata", help="Filter and display metadata", |
| 646 |
aliases=["mdata"], |
| 647 |
description="Search for metadata items or display metadata (sub)trees.") |
| 648 |
meta_parser.add_argument("-p", "--pattern", type=str, action="append", |
| 649 |
help=METADATA_PATTERN_HELP) |
| 650 |
meta_parser.add_argument("-d", "--depth", type=int, default=-1, |
| 651 |
help="maximum depth of metadata tree output, default is %(default)s, full depth") |
| 652 |
add_default_args(meta_parser) |
| 653 |
add_default_file_args(meta_parser) |
| 654 |
meta_parser.set_defaults(func=mdata_worker) |
| 655 |
|
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
def create_data_parser(parent_parser): |
| 660 |
data_parser = parent_parser.add_parser("data", |
| 661 |
help=( |
| 662 |
"Search and display information about data entities"), |
| 663 |
description=DATA_PARSER_HELP) |
| 664 |
data_parser.add_argument( |
| 665 |
"-p", "--pattern", default="", type=str, help=DATA_PATTERN_HELP) |
| 666 |
add_default_args(data_parser) |
| 667 |
add_default_file_args(data_parser) |
| 668 |
data_parser.set_defaults(func=data_worker) |
| 669 |
|
| 670 |
|
| 671 |
def create_dump_parser(parent_parser): |
| 672 |
dump_parser = parent_parser.add_parser( |
| 673 |
"dump", help="Dump stored data to stdout", description=DUMP_PARSER_HELP) |
| 674 |
dump_parser.add_argument( |
| 675 |
"-p", "--pattern", default="", type=str, help=DUMP_PATTERN_HELP) |
| 676 |
dump_parser.add_argument( |
| 677 |
"-o", "--outfile", default="", type=str, help=DUMP_OUTFILE_HELP) |
| 678 |
add_default_args(dump_parser) |
| 679 |
add_default_file_args(dump_parser) |
| 680 |
dump_parser.set_defaults(func=dump_worker) |
| 681 |
|
| 682 |
|
| 683 |
def create_plot_parser(parent_parser): |
| 684 |
if not NIX_WORKS: |
| 685 |
return |
| 686 |
plot_parser = parent_parser.add_parser("plot", help="Create basic plots of stored data.", |
| 687 |
description=PLOT_PARSER_HELP) |
| 688 |
plot_parser.add_argument( |
| 689 |
"-p", "--pattern", type=str, help=DATA_PATTERN_HELP) |
| 690 |
add_default_args(plot_parser) |
| 691 |
add_default_file_args(plot_parser) |
| 692 |
plot_parser.set_defaults(func=plot_worker) |
| 693 |
|
| 694 |
|
| 695 |
def create_file_parser(parent_parser): |
| 696 |
file_parser = parent_parser.add_parser("file", help="Display basic file info", |
| 697 |
description=("Quick display of file information such as creation date, " |
| 698 |
"file size and structure etc.")) |
| 699 |
file_parser.add_argument("-v", "--verbosity", action="count", |
| 700 |
help="increase output verbosity, use -v, -vv, -vvv for more verbose output") |
| 701 |
add_default_file_args(file_parser) |
| 702 |
file_parser.set_defaults(func=file_worker) |
| 703 |
|
| 704 |
|
| 705 |
def create_subcmd_parsers(parser): |
| 706 |
subparsers = parser.add_subparsers(title="commands", |
| 707 |
help="Sub commands for working on data and metadata", |
| 708 |
description=TOOL_DESCRIPTION, dest="explore_cmd") |
| 709 |
create_file_parser(subparsers) |
| 710 |
create_data_parser(subparsers) |
| 711 |
create_dump_parser(subparsers) |
| 712 |
create_metadata_parser(subparsers) |
| 713 |
create_plot_parser(subparsers) |
| 714 |
|
| 715 |
return parser |
| 716 |
|
| 717 |
|
| 718 |
def main(args): |
| 719 |
args.func(args) |