sdfr 1.1.0__py3-none-win32.whl → 1.2.1__py3-none-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sdfr/sdf_helper.py CHANGED
@@ -1,11 +1,16 @@
1
1
  import os
2
2
  import re
3
+
3
4
  try:
4
5
  import numpy as np
5
6
  import matplotlib.pyplot as plt
6
7
  from matplotlib.transforms import Bbox
7
- from matplotlib.offsetbox import HPacker, VPacker, TextArea, \
8
- AnchoredOffsetbox
8
+ from matplotlib.offsetbox import (
9
+ HPacker,
10
+ VPacker,
11
+ TextArea,
12
+ AnchoredOffsetbox,
13
+ )
9
14
  except:
10
15
  pass
11
16
  try:
@@ -15,8 +20,10 @@ except:
15
20
  # Workaround for broken macOS installation
16
21
  import sys
17
22
  import matplotlib
18
- sys.path.append(os.path.join(matplotlib.__path__[0],
19
- '..', 'mpl_toolkits'))
23
+
24
+ sys.path.append(
25
+ os.path.join(matplotlib.__path__[0], "..", "mpl_toolkits")
26
+ )
20
27
  from axes_grid1 import make_axes_locatable
21
28
  except:
22
29
  pass
@@ -26,13 +33,15 @@ except:
26
33
  import __builtin__ as builtins
27
34
 
28
35
  try:
29
- import sdf
36
+ import sdfr as sdf
37
+
30
38
  got_sdf = True
31
39
  except ImportError:
32
40
  got_sdf = False
33
41
 
34
42
  try:
35
43
  from matplotlib.pyplot import * # NOQA
44
+
36
45
  got_mpl = True
37
46
  except ImportError:
38
47
  got_mpl = False
@@ -47,10 +56,10 @@ global old_mtime, wkdir, verbose, fig, im, cbar
47
56
 
48
57
  verbose = True
49
58
 
50
- wkdir = 'Data'
59
+ wkdir = "Data"
51
60
  old_mtime = 0
52
61
  old_size = 0
53
- old_filename = ''
62
+ old_filename = ""
54
63
  cached = False
55
64
  fig = None
56
65
  im = None
@@ -59,7 +68,7 @@ mult_x = 1
59
68
  mult_y = 1
60
69
 
61
70
 
62
- class ic_type():
71
+ class ic_type:
63
72
  NEW = 1
64
73
  RESTART = 2
65
74
  SOD = 3
@@ -74,83 +83,83 @@ class ic_type():
74
83
  def get_si_prefix(scale, full_units=False):
75
84
  scale = abs(scale)
76
85
  mult = 1
77
- sym = ''
86
+ sym = ""
78
87
 
79
88
  if scale < 1e-24:
80
89
  full_units = True
81
90
  elif scale < 1e-21:
82
91
  # yocto
83
92
  mult = 1e24
84
- sym = 'y'
93
+ sym = "y"
85
94
  elif scale < 1e-19:
86
95
  # zepto
87
96
  mult = 1e21
88
- sym = 'z'
97
+ sym = "z"
89
98
  elif scale < 1e-16:
90
99
  # atto
91
100
  mult = 1e18
92
- sym = 'a'
101
+ sym = "a"
93
102
  elif scale < 1e-13:
94
103
  # femto
95
104
  mult = 1e15
96
- sym = 'f'
105
+ sym = "f"
97
106
  elif scale < 1e-10:
98
107
  # pico
99
108
  mult = 1e12
100
- sym = 'p'
109
+ sym = "p"
101
110
  elif scale < 1e-7:
102
111
  # nano
103
112
  mult = 1e9
104
- sym = 'n'
113
+ sym = "n"
105
114
  elif scale < 1e-4:
106
115
  # micro
107
116
  mult = 1e6
108
- sym = '{\mu}'
117
+ sym = r"{\mu}"
109
118
  elif scale < 1e-1:
110
119
  # milli
111
120
  mult = 1e3
112
- sym = 'm'
121
+ sym = "m"
113
122
  elif scale >= 1e27:
114
123
  full_units = True
115
124
  elif scale >= 1e24:
116
125
  # yotta
117
126
  mult = 1e-24
118
- sym = 'Y'
127
+ sym = "Y"
119
128
  elif scale >= 1e21:
120
129
  # zetta
121
130
  mult = 1e-21
122
- sym = 'Z'
131
+ sym = "Z"
123
132
  elif scale >= 1e18:
124
133
  # exa
125
134
  mult = 1e-18
126
- sym = 'E'
135
+ sym = "E"
127
136
  elif scale >= 1e15:
128
137
  # peta
129
138
  mult = 1e-15
130
- sym = 'P'
139
+ sym = "P"
131
140
  elif scale >= 1e12:
132
141
  # tera
133
142
  mult = 1e-12
134
- sym = 'T'
143
+ sym = "T"
135
144
  elif scale >= 1e9:
136
145
  # giga
137
146
  mult = 1e-9
138
- sym = 'G'
147
+ sym = "G"
139
148
  elif scale >= 1e6:
140
149
  # mega
141
150
  mult = 1e-6
142
- sym = 'M'
151
+ sym = "M"
143
152
  elif scale >= 1e3:
144
153
  # kilo
145
154
  mult = 1e-3
146
- sym = 'k'
155
+ sym = "k"
147
156
 
148
157
  if full_units:
149
158
  scale = scale * mult
150
159
  if scale <= 0:
151
160
  pwr = 0
152
161
  else:
153
- pwr = (-np.floor(np.log10(scale)))
162
+ pwr = -np.floor(np.log10(scale))
154
163
  mult = mult * np.power(10.0, pwr)
155
164
  if np.rint(pwr) != 0:
156
165
  sym = "(10^{%.0f})" % (-pwr) + sym
@@ -162,60 +171,75 @@ def get_title(var=None, geom=False, extra_info=True):
162
171
  global data
163
172
 
164
173
  if var is not None:
165
- if hasattr(var, 'blocklist'):
174
+ if hasattr(var, "blocklist"):
166
175
  data = var.blocklist
167
176
 
168
- t = data.Header['time']
177
+ t = data.Header["time"]
169
178
  mult, sym = get_si_prefix(t)
170
179
 
171
- stitle = r'$t = {:.3}{}s$'.format(mult * t, sym)
180
+ stitle = r"$t = {:.3}{}s$".format(mult * t, sym)
172
181
 
173
182
  if not extra_info:
174
183
  return stitle
175
184
 
176
- if hasattr(data, 'Logical_flags'):
177
- if hasattr(data.Logical_flags, 'use_szp') \
178
- and data.Logical_flags.use_szp:
179
- stitle += r', $m_f = {:.1}$'.format(data.Real_flags.m_f)
180
- if hasattr(data.Logical_flags, 'use_tts') \
181
- and data.Logical_flags.use_tts:
182
- stitle += r', TTS'
183
- if hasattr(data.Logical_flags, 'use_tav') \
184
- and data.Logical_flags.use_tav:
185
- stitle += r', Tensor viscosity'
185
+ if hasattr(data, "Logical_flags"):
186
+ if (
187
+ hasattr(data.Logical_flags, "use_szp")
188
+ and data.Logical_flags.use_szp
189
+ ):
190
+ stitle += r", $m_f = {:.1}$".format(data.Real_flags.m_f)
191
+ if (
192
+ hasattr(data.Logical_flags, "use_tts")
193
+ and data.Logical_flags.use_tts
194
+ ):
195
+ stitle += r", TTS"
196
+ if (
197
+ hasattr(data.Logical_flags, "use_tav")
198
+ and data.Logical_flags.use_tav
199
+ ):
200
+ stitle += r", Tensor viscosity"
186
201
  else:
187
- if hasattr(data.Logical_flags, 'use_qmono') \
188
- and data.Logical_flags.use_qmono:
189
- stitle += r', Edge viscosity'
190
- if hasattr(data.Logical_flags, 'use_edge') \
191
- and data.Logical_flags.use_edge:
192
- stitle += r', Edge viscosity'
193
-
194
- if hasattr(data, 'Real_flags'):
195
- if hasattr(data.Real_flags, 'visc1'):
196
- stitle += r', $c_1 = ' + str(data.Real_flags.visc1) + '$'
197
- if hasattr(data.Real_flags, 'visc2'):
198
- stitle += r'$,\,c_2 = ' + str(data.Real_flags.visc2) + '$'
202
+ if (
203
+ hasattr(data.Logical_flags, "use_qmono")
204
+ and data.Logical_flags.use_qmono
205
+ ):
206
+ stitle += r", Edge viscosity"
207
+ if (
208
+ hasattr(data.Logical_flags, "use_edge")
209
+ and data.Logical_flags.use_edge
210
+ ):
211
+ stitle += r", Edge viscosity"
212
+
213
+ if hasattr(data, "Real_flags"):
214
+ if hasattr(data.Real_flags, "visc1"):
215
+ stitle += r", $c_1 = " + str(data.Real_flags.visc1) + "$"
216
+ if hasattr(data.Real_flags, "visc2"):
217
+ stitle += r"$,\,c_2 = " + str(data.Real_flags.visc2) + "$"
199
218
 
200
219
  if geom:
201
- if hasattr(data, 'Logical_flags'):
202
- if hasattr(data.Logical_flags, 'use_rz') \
203
- and data.Logical_flags.use_rz:
204
- stitle += r', R-Z'
220
+ if hasattr(data, "Logical_flags"):
221
+ if (
222
+ hasattr(data.Logical_flags, "use_rz")
223
+ and data.Logical_flags.use_rz
224
+ ):
225
+ stitle += r", R-Z"
205
226
  else:
206
- stitle += r', Cartesian'
227
+ stitle += r", Cartesian"
207
228
 
208
- if hasattr(data.Logical_flags, 'polar_grid') \
209
- and data.Logical_flags.polar_grid:
210
- stitle += r' Polar'
229
+ if (
230
+ hasattr(data.Logical_flags, "polar_grid")
231
+ and data.Logical_flags.polar_grid
232
+ ):
233
+ stitle += r" Polar"
211
234
 
212
235
  return stitle
213
236
 
214
237
 
215
238
  def get_default_iso(data):
216
239
  iso = True
217
- if hasattr(data, 'Integer_flags') \
218
- and hasattr(data.Integer_flags, 'ic_type'):
240
+ if hasattr(data, "Integer_flags") and hasattr(
241
+ data.Integer_flags, "ic_type"
242
+ ):
219
243
  ic = data.Integer_flags.ic_type
220
244
  if ic == ic_type.NOH or ic == ic_type.SEDOV:
221
245
  iso = True
@@ -225,24 +249,25 @@ def get_default_iso(data):
225
249
  def get_file_list(wkd=None, base=None, block=None):
226
250
  """Get a list of SDF filenames containing sequence numbers
227
251
 
228
- Parameters
229
- ----------
230
- wkd : str
231
- The directory in which to search
232
- If no other keyword arguments are passed, then the code will
233
- automatically attempt to detect if this field is base or block
234
- base : str
235
- A representative filename or directory
236
- block : sdf.Block or sdf.BlockList
237
- A representative sdf dataset or block
238
-
239
- Returns
240
- -------
241
- file_list : str array
242
- An array of filenames
252
+ Parameters
253
+ ----------
254
+ wkd : str
255
+ The directory in which to search
256
+ If no other keyword arguments are passed, then the code will
257
+ automatically attempt to detect if this field is base or block
258
+ base : str
259
+ A representative filename or directory
260
+ block : sdf.Block or sdf.BlockList
261
+ A representative sdf dataset or block
262
+
263
+ Returns
264
+ -------
265
+ file_list : str array
266
+ An array of filenames
243
267
  """
244
268
  import os.path
245
269
  import glob
270
+
246
271
  global wkdir
247
272
 
248
273
  if wkd is not None:
@@ -250,17 +275,20 @@ def get_file_list(wkd=None, base=None, block=None):
250
275
  wkdir = wkd
251
276
  elif os.path.exists(wkd):
252
277
  base = wkd
253
- elif isinstance(wkd, sdf.BlockList) \
254
- or isinstance(wkd, sdf.Block) or type(wkd) is dict:
278
+ elif (
279
+ isinstance(wkd, sdf.BlockList)
280
+ or isinstance(wkd, sdf.Block)
281
+ or type(wkd) is dict
282
+ ):
255
283
  block = wkd
256
284
 
257
285
  if base is None and block is not None:
258
- if hasattr(block, 'blocklist'):
286
+ if hasattr(block, "blocklist"):
259
287
  bl = block.blocklist
260
- if hasattr(bl, 'Header') and 'filename' in bl.Header:
261
- base = bl.Header['filename']
262
- elif hasattr(block, 'Header') and 'filename' in block.Header:
263
- base = block.Header['filename']
288
+ if hasattr(bl, "Header") and "filename" in bl.Header:
289
+ base = bl.Header["filename"]
290
+ elif hasattr(block, "Header") and "filename" in block.Header:
291
+ base = block.Header["filename"]
264
292
 
265
293
  if base is not None:
266
294
  if os.path.isfile(base[0]):
@@ -283,45 +311,48 @@ def get_file_list(wkd=None, base=None, block=None):
283
311
  def get_job_id(file_list=None, base=None, block=None):
284
312
  """Get a representative job ID for a list of files
285
313
 
286
- Parameters
287
- ----------
288
- file_list : str list
289
- A list of filenames to search
290
- If no other keyword arguments are passed, then the code will
291
- automatically attempt to detect if this field is base or block
292
- base : str
293
- A representative filename or directory
294
- block : sdf.Block or sdf.BlockList
295
- A representative sdf dataset or block
296
-
297
- Returns
298
- -------
299
- job_id : str
300
- The job ID
314
+ Parameters
315
+ ----------
316
+ file_list : str list
317
+ A list of filenames to search
318
+ If no other keyword arguments are passed, then the code will
319
+ automatically attempt to detect if this field is base or block
320
+ base : str
321
+ A representative filename or directory
322
+ block : sdf.Block or sdf.BlockList
323
+ A representative sdf dataset or block
324
+
325
+ Returns
326
+ -------
327
+ job_id : str
328
+ The job ID
301
329
  """
302
330
 
303
- if file_list is not None and type(file_list) is not list:
331
+ if file_list is not None and not isinstance(file_list, list):
304
332
  if os.path.exists(file_list):
305
333
  base = file_list
306
334
  file_list = None
307
- elif isinstance(file_list, sdf.BlockList) \
308
- or isinstance(file_list, sdf.Block) or type(file_list) is dict:
335
+ elif (
336
+ isinstance(file_list, sdf.BlockList)
337
+ or isinstance(file_list, sdf.Block)
338
+ or type(file_list) is dict
339
+ ):
309
340
  block = file_list
310
341
  file_list = None
311
342
 
312
343
  if block is not None and base is None:
313
- if hasattr(block, 'blocklist'):
344
+ if hasattr(block, "blocklist"):
314
345
  bl = block.blocklist
315
- if hasattr(bl, 'Header') and 'filename' in bl.Header:
316
- base = bl.Header['filename']
317
- elif hasattr(block, 'Header') and 'filename' in block.Header:
318
- base = block.Header['filename']
346
+ if hasattr(bl, "Header") and "filename" in bl.Header:
347
+ base = bl.Header["filename"]
348
+ elif hasattr(block, "Header") and "filename" in block.Header:
349
+ base = block.Header["filename"]
319
350
 
320
351
  if base is not None:
321
352
  try:
322
353
  data = sdf.read(base, mmap=0)
323
354
  if len(data.__dict__) > 1:
324
- return data.Header['jobid1']
355
+ return data.Header["jobid1"]
325
356
  except:
326
357
  pass
327
358
 
@@ -332,7 +363,7 @@ def get_job_id(file_list=None, base=None, block=None):
332
363
  data = sdf.read(f, mmap=0)
333
364
  if len(data.__dict__) < 2:
334
365
  continue
335
- return data.Header['jobid1']
366
+ return data.Header["jobid1"]
336
367
  except:
337
368
  pass
338
369
 
@@ -342,26 +373,26 @@ def get_job_id(file_list=None, base=None, block=None):
342
373
  def get_files(wkd=None, base=None, block=None, varname=None, fast=True):
343
374
  """Get a list of SDF filenames belonging to the same run
344
375
 
345
- Parameters
346
- ----------
347
- wkd : str
348
- The directory in which to search
349
- If no other keyword arguments are passed, then the code will
350
- automatically attempt to detect if this field is base or block
351
- base : str
352
- A representative filename or directory
353
- block : sdf.Block or sdf.BlockList
354
- A representative sdf dataset or block
355
- varname : str
356
- A variable name that must be present in the file
357
- fast : bool
358
- Assume that files follow strict datestamp ordering and exit once
359
- the first file that doesn't match the job ID
360
-
361
- Returns
362
- -------
363
- file_list : str array
364
- An array of filenames
376
+ Parameters
377
+ ----------
378
+ wkd : str
379
+ The directory in which to search
380
+ If no other keyword arguments are passed, then the code will
381
+ automatically attempt to detect if this field is base or block
382
+ base : str
383
+ A representative filename or directory
384
+ block : sdf.Block or sdf.BlockList
385
+ A representative sdf dataset or block
386
+ varname : str
387
+ A variable name that must be present in the file
388
+ fast : bool
389
+ Assume that files follow strict datestamp ordering and exit once
390
+ the first file that doesn't match the job ID
391
+
392
+ Returns
393
+ -------
394
+ file_list : str array
395
+ An array of filenames
365
396
  """
366
397
 
367
398
  if wkd is not None:
@@ -369,17 +400,20 @@ def get_files(wkd=None, base=None, block=None, varname=None, fast=True):
369
400
  pass
370
401
  elif os.path.exists(wkd):
371
402
  base = wkd
372
- elif isinstance(wkd, sdf.BlockList) \
373
- or isinstance(wkd, sdf.Block) or type(wkd) is dict:
403
+ elif (
404
+ isinstance(wkd, sdf.BlockList)
405
+ or isinstance(wkd, sdf.Block)
406
+ or type(wkd) is dict
407
+ ):
374
408
  block = wkd
375
409
 
376
410
  if block is not None and base is None:
377
- if hasattr(block, 'blocklist'):
411
+ if hasattr(block, "blocklist"):
378
412
  bl = block.blocklist
379
- if hasattr(bl, 'Header') and 'filename' in bl.Header:
380
- base = bl.Header['filename']
381
- elif hasattr(block, 'Header') and 'filename' in block.Header:
382
- base = block.Header['filename']
413
+ if hasattr(bl, "Header") and "filename" in bl.Header:
414
+ base = bl.Header["filename"]
415
+ elif hasattr(block, "Header") and "filename" in block.Header:
416
+ base = block.Header["filename"]
383
417
 
384
418
  flist = get_file_list(wkd=wkd, base=base)
385
419
  flist.sort(key=lambda x: os.path.getmtime(x))
@@ -393,7 +427,7 @@ def get_files(wkd=None, base=None, block=None, varname=None, fast=True):
393
427
  data = sdf.read(f, mmap=0, dict=True)
394
428
  if len(data) < 2:
395
429
  continue
396
- file_job_id = data['Header']['jobid1']
430
+ file_job_id = data["Header"]["jobid1"]
397
431
  if file_job_id == job_id:
398
432
  if varname is None:
399
433
  file_list.append(f)
@@ -407,34 +441,35 @@ def get_files(wkd=None, base=None, block=None, varname=None, fast=True):
407
441
  return list(reversed(file_list))
408
442
 
409
443
 
410
- def get_time(time=0, first=False, last=False, wkd=None, base=None, block=None,
411
- fast=True):
444
+ def get_time(
445
+ time=0, first=False, last=False, wkd=None, base=None, block=None, fast=True
446
+ ):
412
447
  """Get an SDF dataset that matches a given time
413
448
 
414
- Parameters
415
- ----------
416
- time : float
417
- The time to search for. If specified then the dateset that is
418
- closest to this time will be returned
419
- first : bool
420
- If set to True then the dataset with the earliest simulation time
421
- will be returned
422
- last : bool
423
- If set to True then the dataset with the latest simulation time
424
- will be returned
425
- wkd : str
426
- The directory in which to search
427
- base : str
428
- A representative filename or directory
429
- block : sdf.Block or sdf.BlockList
430
- A representative sdf dataset or block
431
- fast : bool
432
- Use a faster but less thorough method for returning first/last
433
-
434
- Returns
435
- -------
436
- data : sdf.BlockList
437
- An SDF dataset
449
+ Parameters
450
+ ----------
451
+ time : float
452
+ The time to search for. If specified then the dateset that is
453
+ closest to this time will be returned
454
+ first : bool
455
+ If set to True then the dataset with the earliest simulation time
456
+ will be returned
457
+ last : bool
458
+ If set to True then the dataset with the latest simulation time
459
+ will be returned
460
+ wkd : str
461
+ The directory in which to search
462
+ base : str
463
+ A representative filename or directory
464
+ block : sdf.Block or sdf.BlockList
465
+ A representative sdf dataset or block
466
+ fast : bool
467
+ Use a faster but less thorough method for returning first/last
468
+
469
+ Returns
470
+ -------
471
+ data : sdf.BlockList
472
+ An SDF dataset
438
473
  """
439
474
  global data, wkdir
440
475
 
@@ -462,10 +497,10 @@ def get_time(time=0, first=False, last=False, wkd=None, base=None, block=None,
462
497
  dat_tmp = sdf.read(f)
463
498
  if len(dat_tmp.__dict__) < 2:
464
499
  continue
465
- if job_id != dat_tmp.Header['jobid1']:
500
+ if job_id != dat_tmp.Header["jobid1"]:
466
501
  continue
467
502
 
468
- t = dat_tmp.Header['time']
503
+ t = dat_tmp.Header["time"]
469
504
  if last:
470
505
  if fast:
471
506
  fname = f
@@ -496,34 +531,35 @@ def get_time(time=0, first=False, last=False, wkd=None, base=None, block=None,
496
531
  return data
497
532
 
498
533
 
499
- def get_step(step=0, first=False, last=False, wkd=None, base=None, block=None,
500
- fast=True):
534
+ def get_step(
535
+ step=0, first=False, last=False, wkd=None, base=None, block=None, fast=True
536
+ ):
501
537
  """Get an SDF dataset that matches a given step
502
538
 
503
- Parameters
504
- ----------
505
- step : int
506
- The time to search for. If specified then the dateset that is
507
- closest to this time will be returned
508
- first : bool
509
- If set to True then the dataset with the earliest simulation step
510
- will be returned
511
- last : bool
512
- If set to True then the dataset with the latest simulation step
513
- will be returned
514
- wkd : str
515
- The directory in which to search
516
- base : str
517
- A representative filename or directory
518
- block : sdf.Block or sdf.BlockList
519
- A representative sdf dataset or block
520
- fast : bool
521
- Use a faster but less thorough method for returning first/last
522
-
523
- Returns
524
- -------
525
- data : sdf.BlockList
526
- An SDF dataset
539
+ Parameters
540
+ ----------
541
+ step : int
542
+ The time to search for. If specified then the dateset that is
543
+ closest to this time will be returned
544
+ first : bool
545
+ If set to True then the dataset with the earliest simulation step
546
+ will be returned
547
+ last : bool
548
+ If set to True then the dataset with the latest simulation step
549
+ will be returned
550
+ wkd : str
551
+ The directory in which to search
552
+ base : str
553
+ A representative filename or directory
554
+ block : sdf.Block or sdf.BlockList
555
+ A representative sdf dataset or block
556
+ fast : bool
557
+ Use a faster but less thorough method for returning first/last
558
+
559
+ Returns
560
+ -------
561
+ data : sdf.BlockList
562
+ An SDF dataset
527
563
  """
528
564
  global data, wkdir
529
565
 
@@ -551,10 +587,10 @@ def get_step(step=0, first=False, last=False, wkd=None, base=None, block=None,
551
587
  dat_tmp = sdf.read(f)
552
588
  if len(dat_tmp.__dict__) < 2:
553
589
  continue
554
- if job_id != dat_tmp.Header['jobid1']:
590
+ if job_id != dat_tmp.Header["jobid1"]:
555
591
  continue
556
592
 
557
- t = dat_tmp.Header['step']
593
+ t = dat_tmp.Header["step"]
558
594
  if last:
559
595
  if fast:
560
596
  fname = f
@@ -588,21 +624,21 @@ def get_step(step=0, first=False, last=False, wkd=None, base=None, block=None,
588
624
  def get_latest(wkd=None, base=None, block=None):
589
625
  """Get the latest SDF dataset in a directory
590
626
 
591
- Parameters
592
- ----------
593
- wkd : str
594
- The directory in which to search
595
- If no other keyword arguments are passed, then the code will
596
- automatically attempt to detect if this field is base or block
597
- base : str
598
- A representative filename or directory
599
- block : sdf.Block or sdf.BlockList
600
- A representative sdf dataset or block
601
-
602
- Returns
603
- -------
604
- data : sdf.BlockList
605
- An SDF dataset
627
+ Parameters
628
+ ----------
629
+ wkd : str
630
+ The directory in which to search
631
+ If no other keyword arguments are passed, then the code will
632
+ automatically attempt to detect if this field is base or block
633
+ base : str
634
+ A representative filename or directory
635
+ block : sdf.Block or sdf.BlockList
636
+ A representative sdf dataset or block
637
+
638
+ Returns
639
+ -------
640
+ data : sdf.BlockList
641
+ An SDF dataset
606
642
  """
607
643
  return get_step(last=True, wkd=wkd, base=base, block=base)
608
644
 
@@ -639,7 +675,7 @@ def get_newest_file(wkd=None, base=None, block=None):
639
675
  flist = get_file_list(wkd=wkd, base=base, block=block)
640
676
  flist.sort(key=lambda x: os.path.getmtime(x))
641
677
  for n in range(len(flist)):
642
- f = flist[-n-1]
678
+ f = flist[-n - 1]
643
679
  data = sdf.read(f, mmap=0, dict=True)
644
680
  if len(data) > 1:
645
681
  return f
@@ -673,46 +709,72 @@ def plot_auto(*args, **kwargs):
673
709
  try:
674
710
  dims = args[0].dims
675
711
  except:
676
- print('error: Variable cannot be auto determined. '
677
- + 'Use plot1d or plot2d')
712
+ print(
713
+ "error: Variable cannot be auto determined. "
714
+ + "Use plot1d or plot2d"
715
+ )
678
716
  return
679
- if (len(dims) == 1):
680
- if type(args[0]) is sdf.BlockStitchedPath:
717
+ if len(dims) == 1:
718
+ if isinstance(args[0], sdf.BlockStitchedPath):
681
719
  plot_rays(*args, **kwargs)
682
- elif (len(args[0].grid.dims) == 1):
720
+ elif isinstance(args[0], sdf.BlockStitched):
721
+ newargs = list(args[:])
722
+ for block in args[0].data:
723
+ newargs[0] = block
724
+ plot_auto(*newargs, **kwargs)
725
+ elif len(args[0].grid.dims) == 1:
683
726
  plot1d(*args, **kwargs)
684
727
  else:
685
728
  plot_path(*args, **kwargs)
686
- elif (len(dims) == 2):
687
- k = 'set_ylabel'
729
+ elif isinstance(args[0], sdf.BlockLagrangianMesh) and dims[1] == 1:
730
+ plot_path(*args, **kwargs)
731
+ elif isinstance(args[0], sdf.BlockStitchedPath):
732
+ plot_rays(*args, **kwargs)
733
+ elif len(dims) == 2:
734
+ k = "set_ylabel"
688
735
  if k in kwargs:
689
736
  del kwargs[k]
690
737
  plot2d(*args, **kwargs)
691
- elif len(dims) == 3 and \
692
- ('ix' in kwargs or 'iy' in kwargs or 'iz' in kwargs):
693
- k = 'set_ylabel'
738
+ elif len(dims) == 3 and (
739
+ "ix" in kwargs or "iy" in kwargs or "iz" in kwargs
740
+ ):
741
+ k = "set_ylabel"
694
742
  if k in kwargs:
695
743
  del kwargs[k]
696
744
  plot2d(*args, **kwargs)
697
745
  else:
698
- print('error: Unable to plot variables of this dimensionality')
746
+ print("error: Unable to plot variables of this dimensionality")
699
747
 
700
748
 
701
749
  def oplot_auto(*args, **kwargs):
702
- kwargs['set_ylabel'] = False
703
- kwargs['hold'] = True
750
+ kwargs["set_ylabel"] = False
751
+ kwargs["hold"] = True
704
752
  plot_auto(*args, **kwargs)
705
753
 
706
754
 
707
755
  def oplot1d(*args, **kwargs):
708
- kwargs['set_ylabel'] = False
709
- kwargs['hold'] = True
756
+ kwargs["set_ylabel"] = False
757
+ kwargs["hold"] = True
710
758
  plot1d(*args, **kwargs)
711
759
 
712
760
 
713
- def plot1d(var, fmt=None, xdir=None, idx=-1, xscale=0, yscale=0, scale=0,
714
- cgs=False, title=True, sym=True, set_ylabel=True, hold=True,
715
- subplot=None, figure=None, **kwargs):
761
+ def plot1d(
762
+ var,
763
+ fmt=None,
764
+ xdir=None,
765
+ idx=-1,
766
+ xscale=0,
767
+ yscale=0,
768
+ scale=0,
769
+ cgs=False,
770
+ title=True,
771
+ sym=True,
772
+ set_ylabel=True,
773
+ hold=True,
774
+ subplot=None,
775
+ figure=None,
776
+ **kwargs
777
+ ):
716
778
  global data
717
779
  global x, y, mult_x, mult_y
718
780
 
@@ -739,7 +801,7 @@ def plot1d(var, fmt=None, xdir=None, idx=-1, xscale=0, yscale=0, scale=0,
739
801
  figure = subplot.figure
740
802
  if not hold:
741
803
  subplot.clear()
742
- if hasattr(subplot, 'colorbar'):
804
+ if hasattr(subplot, "colorbar"):
743
805
  subplot.colorbar.remove()
744
806
 
745
807
  if var.dims[0] == var.grid.dims[0]:
@@ -812,92 +874,116 @@ def plot1d(var, fmt=None, xdir=None, idx=-1, xscale=0, yscale=0, scale=0,
812
874
  else:
813
875
  subplot.plot(X, Y, **kwargs)
814
876
 
815
- subplot.set_xlabel(grid.labels[xdir] + ' $('
816
- + escape_latex(sym_x + grid.units[xdir]) + ')$')
877
+ subplot.set_xlabel(
878
+ grid.labels[xdir]
879
+ + " $("
880
+ + escape_latex(sym_x + grid.units[xdir])
881
+ + ")$"
882
+ )
817
883
  if set_ylabel:
818
- subplot.set_ylabel(var.name + ' $('
819
- + escape_latex(sym_y + var.units) + ')$')
884
+ subplot.set_ylabel(
885
+ var.name + " $(" + escape_latex(sym_y + var.units) + ")$"
886
+ )
820
887
 
821
888
  if title:
822
- subplot.set_title(get_title(var), fontsize='large', y=1.03)
889
+ subplot.set_title(get_title(var), fontsize="large", y=1.03)
823
890
 
824
891
  figure.set_tight_layout(True)
825
892
  figure.canvas.draw()
826
893
 
827
894
 
828
- def plot_path(var, xdir=None, ydir=None, xscale=0, yscale=0, scale=0,
829
- title=True, hold=True, subplot=None, figure=None, iso=True,
830
- add_cbar=True, cbar_label=True, cbar_wd=5, cbar_top=False,
831
- svar=None, update=True, axis_only=False, clip_reflect=False,
832
- power=(-3,3), **kwargs):
895
+ def plot_path(
896
+ var,
897
+ xdir=None,
898
+ ydir=None,
899
+ xscale=0,
900
+ yscale=0,
901
+ scale=0,
902
+ title=True,
903
+ hold=True,
904
+ subplot=None,
905
+ figure=None,
906
+ iso=True,
907
+ add_cbar=True,
908
+ cbar_label=True,
909
+ cbar_wd=5,
910
+ cbar_top=False,
911
+ svar=None,
912
+ update=True,
913
+ axis_only=False,
914
+ clip_reflect=False,
915
+ power=(-3, 3),
916
+ **kwargs
917
+ ):
833
918
  """Plot an SDF path variable (eg. a laser ray)
834
919
 
835
- Parameters
836
- ----------
837
- var : sdf.Block
838
- The SDF block for the path to plot
839
- xdir : integer
840
- The dimension to use for the x-direction. If the path is 2D then
841
- ydir will automatically be selected.
842
- ydir : integer
843
- The dimension to use for the y-direction. If the path is 2D then
844
- xdir will automatically be selected.
845
- xscale : real
846
- Value to use for scaling the x-axis. If not set then the x-axis will
847
- be scaled automatically. Set this to 1 to disable scaling.
848
- yscale : real
849
- Value to use for scaling the y-axis. If not set then the x-axis will
850
- be scaled automatically. Set this to 1 to disable scaling.
851
- scale : real
852
- Value to use for scaling both axes. If not set then the axes will
853
- be scaled automatically. Set this to 1 to disable scaling.
854
- title : logical or string
855
- If set to False, don't add a title to the plot.
856
- Otherwise, add the specified value if it is a string or
857
- automatically generate one if it is just True.
858
- hold : logical
859
- If True, do not clear the figure before plotting.
860
- subplot :
861
- The subplot to use for plotting
862
- figure :
863
- The figure to use for plotting
864
- iso : logical
865
- If True, generate an isotropic plot (x/y axis equal).
866
- add_cbar : logical
867
- Add a colorbar if true
868
- cbar_label : logical or string
869
- If set to False, don't add a label to the colorbar.
870
- Otherwise, add the specified value if it is a string or
871
- automatically generate one if it is just True.
872
- cbar_wd : integer
873
- The width of the colorbar
874
- cbar_top : logical
875
- If set to true, the colorbar is plotted along the top of the figure
876
- instead of the right-hand side
877
- update : logical
878
- If set to true then update the axis limits for this path
879
- axis_only : logical
880
- If set to true then only update the axis limits for this path
881
- svar : sdf.Block
882
- If set, use the extents of this variable to set the axis range for
883
- this plot
884
- clip_reflect : logical
885
- If set to true, then rays are clipped at the point where the path
886
- gradient is either zero or huge
887
- power : sequence
888
- Sets size thresholds for scientific notation.
889
- Two-element sequence passed throuth to set_powerlimits()
890
-
891
- **kwargs : dict
892
- All other keyword arguments are passed to matplotlib plotting
893
- routine
920
+ Parameters
921
+ ----------
922
+ var : sdf.Block
923
+ The SDF block for the path to plot
924
+ xdir : integer
925
+ The dimension to use for the x-direction. If the path is 2D then
926
+ ydir will automatically be selected.
927
+ ydir : integer
928
+ The dimension to use for the y-direction. If the path is 2D then
929
+ xdir will automatically be selected.
930
+ xscale : real
931
+ Value to use for scaling the x-axis. If not set then the x-axis will
932
+ be scaled automatically. Set this to 1 to disable scaling.
933
+ yscale : real
934
+ Value to use for scaling the y-axis. If not set then the x-axis will
935
+ be scaled automatically. Set this to 1 to disable scaling.
936
+ scale : real
937
+ Value to use for scaling both axes. If not set then the axes will
938
+ be scaled automatically. Set this to 1 to disable scaling.
939
+ title : logical or string
940
+ If set to False, don't add a title to the plot.
941
+ Otherwise, add the specified value if it is a string or
942
+ automatically generate one if it is just True.
943
+ hold : logical
944
+ If True, do not clear the figure before plotting.
945
+ subplot :
946
+ The subplot to use for plotting
947
+ figure :
948
+ The figure to use for plotting
949
+ iso : logical
950
+ If True, generate an isotropic plot (x/y axis equal).
951
+ add_cbar : logical
952
+ Add a colorbar if true
953
+ cbar_label : logical or string
954
+ If set to False, don't add a label to the colorbar.
955
+ Otherwise, add the specified value if it is a string or
956
+ automatically generate one if it is just True.
957
+ cbar_wd : integer
958
+ The width of the colorbar
959
+ cbar_top : logical
960
+ If set to true, the colorbar is plotted along the top of the figure
961
+ instead of the right-hand side
962
+ update : logical
963
+ If set to true then update the axis limits for this path
964
+ axis_only : logical
965
+ If set to true then only update the axis limits for this path
966
+ svar : sdf.Block
967
+ If set, use the extents of this variable to set the axis range for
968
+ this plot
969
+ clip_reflect : logical
970
+ If set to true, then rays are clipped at the point where the path
971
+ gradient is either zero or huge
972
+ power : sequence
973
+ Sets size thresholds for scientific notation.
974
+ Two-element sequence passed throuth to set_powerlimits()
975
+
976
+ **kwargs : dict
977
+ All other keyword arguments are passed to matplotlib plotting
978
+ routine
894
979
  """
895
980
  import matplotlib.pyplot as plt
896
981
  from matplotlib.collections import LineCollection
982
+
897
983
  global data
898
984
  global x, y, mult_x, mult_y
899
985
 
900
- if 'norm_values' not in plot_path.__dict__:
986
+ if "norm_values" not in plot_path.__dict__:
901
987
  plot_path.norm_values = None
902
988
  plot_path.axis = None
903
989
 
@@ -915,7 +1001,12 @@ def plot_path(var, xdir=None, ydir=None, xscale=0, yscale=0, scale=0,
915
1001
  figure.canvas.draw()
916
1002
  return
917
1003
 
918
- if len(var.dims) != 1:
1004
+ isvar = True
1005
+ if isinstance(var, sdf.BlockLagrangianMesh):
1006
+ isvar = False
1007
+ add_cbar = False
1008
+
1009
+ if isvar and len(var.dims) != 1:
919
1010
  print("error: Not a 1d dataset")
920
1011
  return
921
1012
 
@@ -941,18 +1032,21 @@ def plot_path(var, xdir=None, ydir=None, xscale=0, yscale=0, scale=0,
941
1032
  figure = subplot.figure
942
1033
  if not hold:
943
1034
  subplot.clear()
944
- if hasattr(subplot, 'colorbar'):
1035
+ if hasattr(subplot, "colorbar"):
945
1036
  subplot.colorbar.remove()
946
1037
 
947
1038
  if not hold:
948
1039
  plot_path.norm_values = None
949
1040
  plot_path.axis = None
950
1041
 
951
- #if var.dims[0] == var.grid.dims[0]:
1042
+ # if var.dims[0] == var.grid.dims[0]:
952
1043
  # grid = var.grid
953
- #else:
1044
+ # else:
954
1045
  # grid = var.grid_mid
955
- grid = var.grid
1046
+ if isvar:
1047
+ grid = var.grid
1048
+ else:
1049
+ grid = var
956
1050
 
957
1051
  test_dir = False
958
1052
  if xdir is None:
@@ -1008,73 +1102,85 @@ def plot_path(var, xdir=None, ydir=None, xscale=0, yscale=0, scale=0,
1008
1102
 
1009
1103
  X = mult_x * X
1010
1104
  Y = mult_y * Y
1011
- c = var.data
1105
+ if isvar:
1106
+ c = var.data
1012
1107
 
1013
1108
  if clip_reflect:
1014
1109
  g = (X[0] - X[1]) / (Y[0] - Y[1])
1015
1110
  for i in range(len(c) - 1):
1016
- ddx = X[i] - X[i+1]
1017
- ddy = Y[i] - Y[i+1]
1111
+ ddx = X[i] - X[i + 1]
1112
+ ddy = Y[i] - Y[i + 1]
1018
1113
  if abs(ddy) < 1e-16:
1019
1114
  grad = 100
1020
1115
  else:
1021
1116
  grad = ddx / ddy / g
1022
1117
  if abs(grad) > 10 or grad < 0:
1023
- X = np.copy(X[:i+1])
1024
- Y = np.copy(Y[:i+1])
1025
- c = np.copy(c[:i+1])
1118
+ X = np.copy(X[: i + 1])
1119
+ Y = np.copy(Y[: i + 1])
1120
+ if isvar:
1121
+ c = np.copy(c[: i + 1])
1026
1122
  break
1027
1123
 
1028
1124
  points = np.array([X, Y]).T.reshape(-1, 1, 2)
1029
1125
  segments = np.concatenate([points[:-1], points[1:]], axis=1)
1030
1126
 
1031
- if not hold or plot_path.norm_values is None:
1032
- k = 'vmin'
1033
- k1 = 'vrange'
1034
- if k in kwargs:
1035
- vmin = kwargs[k]
1036
- elif k1 in kwargs:
1037
- vmin = kwargs[k1][0]
1038
- else:
1039
- vmin = c.min()
1127
+ if isvar:
1128
+ if not hold or plot_path.norm_values is None:
1129
+ k = "vmin"
1130
+ k1 = "vrange"
1131
+ if k in kwargs:
1132
+ vmin = kwargs[k]
1133
+ elif k1 in kwargs:
1134
+ vmin = kwargs[k1][0]
1135
+ else:
1136
+ vmin = c.min()
1040
1137
 
1041
- k = 'vmax'
1042
- if k in kwargs:
1043
- vmax = kwargs[k]
1044
- elif k1 in kwargs:
1045
- vmax = kwargs[k1][1]
1046
- else:
1047
- vmax = c.max()
1138
+ k = "vmax"
1139
+ if k in kwargs:
1140
+ vmax = kwargs[k]
1141
+ elif k1 in kwargs:
1142
+ vmax = kwargs[k1][1]
1143
+ else:
1144
+ vmax = c.max()
1048
1145
 
1049
- plot_path.norm_values = plt.Normalize(vmin, vmax)
1146
+ plot_path.norm_values = plt.Normalize(vmin, vmax)
1050
1147
 
1051
1148
  kk = {}
1052
- k = 'lw'
1149
+ k = "lw"
1053
1150
  if k in kwargs:
1054
1151
  kk[k] = kwargs[k]
1055
- k = 'linewidth'
1152
+ k = "linewidth"
1056
1153
  if k in kwargs:
1057
1154
  kk[k] = kwargs[k]
1058
1155
  lc = LineCollection(segments, norm=plot_path.norm_values, **kk)
1059
- lc.set_array(c)
1156
+ if isvar:
1157
+ lc.set_array(c)
1060
1158
  im = subplot.add_collection(lc)
1061
1159
 
1062
1160
  if not hold:
1063
- subplot.set_xlabel(grid.labels[xdir] + ' $('
1064
- + escape_latex(sym_x + grid.units[xdir]) + ')$')
1065
- subplot.set_ylabel(grid.labels[ydir] + ' $('
1066
- + escape_latex(sym_y + grid.units[ydir]) + ')$')
1161
+ subplot.set_xlabel(
1162
+ grid.labels[xdir]
1163
+ + " $("
1164
+ + escape_latex(sym_x + grid.units[xdir])
1165
+ + ")$"
1166
+ )
1167
+ subplot.set_ylabel(
1168
+ grid.labels[ydir]
1169
+ + " $("
1170
+ + escape_latex(sym_y + grid.units[ydir])
1171
+ + ")$"
1172
+ )
1067
1173
 
1068
1174
  if title:
1069
- if type(title) is str:
1175
+ if isinstance(title, str):
1070
1176
  title_label = title
1071
1177
  else:
1072
1178
  title_label = get_title(var, extra_info=False)
1073
- subplot.set_title(title_label, fontsize='large', y=1.03)
1179
+ subplot.set_title(title_label, fontsize="large", y=1.03)
1074
1180
 
1075
- subplot.axis('tight')
1181
+ subplot.axis("tight")
1076
1182
  if iso:
1077
- subplot.axis('image')
1183
+ subplot.axis("image")
1078
1184
 
1079
1185
  plot_path.axis = subplot.axis()
1080
1186
  if update:
@@ -1087,14 +1193,13 @@ def plot_path(var, xdir=None, ydir=None, xscale=0, yscale=0, scale=0,
1087
1193
  divider = make_axes_locatable(ca)
1088
1194
  pad = int(0.6 * cbar_wd + 0.5)
1089
1195
  if cbar_top:
1090
- cax = divider.append_axes("top", "%i%%" % cbar_wd,
1091
- pad="%i%%" % pad)
1092
- cbar = figure.colorbar(im, orientation='horizontal',
1093
- cax=cax, ax=ax)
1094
- cax.xaxis.set_ticks_position('top')
1196
+ cax = divider.append_axes("top", "%i%%" % cbar_wd, pad="%i%%" % pad)
1197
+ cbar = figure.colorbar(im, orientation="horizontal", cax=cax, ax=ax)
1198
+ cax.xaxis.set_ticks_position("top")
1095
1199
  else:
1096
- cax = divider.append_axes("right", "%i%%" % cbar_wd,
1097
- pad="%i%%" % pad)
1200
+ cax = divider.append_axes(
1201
+ "right", "%i%%" % cbar_wd, pad="%i%%" % pad
1202
+ )
1098
1203
  cbar = figure.colorbar(im, cax=cax, ax=ax)
1099
1204
  try:
1100
1205
  cbar.formatter.set_powerlimits(power)
@@ -1104,15 +1209,15 @@ def plot_path(var, xdir=None, ydir=None, xscale=0, yscale=0, scale=0,
1104
1209
  subplot.colorbar = cax
1105
1210
  plt.sca(ax)
1106
1211
  if cbar_label:
1107
- if type(cbar_label) is str:
1212
+ if isinstance(cbar_label, str):
1108
1213
  var_label = cbar_label
1109
1214
  else:
1110
- var_label = var.name + ' $(' + escape_latex(var.units) + ')$'
1215
+ var_label = var.name + " $(" + escape_latex(var.units) + ")$"
1111
1216
  if cbar_top:
1112
- cbar.set_label(var_label, fontsize='large')
1113
- cax.xaxis.set_label_position('top')
1217
+ cbar.set_label(var_label, fontsize="large")
1218
+ cax.xaxis.set_label_position("top")
1114
1219
  else:
1115
- cbar.set_label(var_label, fontsize='large', x=1.2)
1220
+ cbar.set_label(var_label, fontsize="large", x=1.2)
1116
1221
 
1117
1222
  if not hold and svar is not None:
1118
1223
  lim = np.array(svar.grid.extents)
@@ -1153,83 +1258,86 @@ def plot_path(var, xdir=None, ydir=None, xscale=0, yscale=0, scale=0,
1153
1258
  def plot_rays(var, skip=1, rays=None, **kwargs):
1154
1259
  """Plot all rays found in an SDF file
1155
1260
 
1156
- Parameters
1157
- ----------
1158
- var : sdf.Block
1159
- The SDF variable for the rays to plot
1160
- skip : integer
1161
- Number of rays to skip before selecting the next one to plot
1261
+ Parameters
1262
+ ----------
1263
+ var : sdf.Block
1264
+ The SDF variable for the rays to plot
1265
+ skip : integer
1266
+ Number of rays to skip before selecting the next one to plot
1162
1267
  """
1163
1268
 
1164
1269
  ray_start = -1
1165
- l = 'ray_start'
1270
+ l = "ray_start"
1166
1271
  if l in kwargs:
1167
1272
  ray_start = kwargs[l]
1168
1273
 
1169
1274
  ray_stop = 1e9
1170
- l = 'ray_stop'
1275
+ l = "ray_stop"
1171
1276
  if l in kwargs:
1172
1277
  ray_stop = kwargs[l]
1173
1278
 
1174
- if type(var) is sdf.BlockStitchedPath:
1279
+ if isinstance(var, sdf.BlockStitchedPath):
1175
1280
  v = var.data[0]
1176
- l = '_label'
1281
+ l = "_label"
1177
1282
  if l not in kwargs:
1178
1283
  kwargs[l] = var.name
1179
1284
 
1180
- if type(v) is sdf.BlockStitchedPath:
1285
+ if isinstance(v, sdf.BlockStitchedPath):
1181
1286
  for v in var.data:
1182
1287
  plot_rays(v, skip=skip, rays=rays, **kwargs)
1183
- kwargs['hold'] = True
1288
+ kwargs["hold"] = True
1184
1289
  return
1185
1290
 
1186
- k = 'cbar_label'
1187
- if k not in kwargs or (kwargs[k] and type(kwargs[k]) != str):
1188
- kwargs[k] = kwargs[l] + ' $(' + escape_latex(v.units) + ')$'
1189
- del kwargs[l]
1190
-
1191
- k0 = 'vmin'
1192
- k1 = 'vmax'
1193
- k = 'vrange'
1194
- if k not in kwargs and not (k0 in kwargs and k1 in kwargs):
1195
- v = var.data[0]
1196
- vmin = v.data.min()
1197
- vmax = v.data.max()
1198
- for iray, v in enumerate(var.data):
1199
- if iray < ray_start:
1200
- continue
1201
- if iray > ray_stop:
1202
- break
1203
- if iray%skip == 0:
1204
- vmin = min(vmin, v.data.min())
1205
- vmax = max(vmax, v.data.max())
1206
- if k0 not in kwargs:
1207
- kwargs[k0] = vmin
1208
- if k1 not in kwargs:
1209
- kwargs[k1] = vmax
1291
+ if not isinstance(v, sdf.BlockLagrangianMesh):
1292
+ k = "cbar_label"
1293
+ if k not in kwargs or (
1294
+ kwargs[k] and not isinstance(kwargs[k], str)
1295
+ ):
1296
+ kwargs[k] = kwargs[l] + " $(" + escape_latex(v.units) + ")$"
1297
+ del kwargs[l]
1298
+
1299
+ k0 = "vmin"
1300
+ k1 = "vmax"
1301
+ k = "vrange"
1302
+ if k not in kwargs and not (k0 in kwargs and k1 in kwargs):
1303
+ v = var.data[0]
1304
+ vmin = v.data.min()
1305
+ vmax = v.data.max()
1306
+ for iray, v in enumerate(var.data):
1307
+ if iray < ray_start:
1308
+ continue
1309
+ if iray > ray_stop:
1310
+ break
1311
+ if iray % skip == 0:
1312
+ vmin = min(vmin, v.data.min())
1313
+ vmax = max(vmax, v.data.max())
1314
+ if k0 not in kwargs:
1315
+ kwargs[k0] = vmin
1316
+ if k1 not in kwargs:
1317
+ kwargs[k1] = vmax
1210
1318
 
1211
1319
  for iray, v in enumerate(var.data):
1212
1320
  if iray < ray_start:
1213
1321
  continue
1214
1322
  if iray > ray_stop:
1215
1323
  break
1216
- if iray%skip == 0:
1324
+ if iray % skip == 0:
1217
1325
  plot_auto(v, update=False, **kwargs)
1218
- kwargs['hold'] = True
1326
+ kwargs["hold"] = True
1219
1327
 
1220
1328
  plot_auto(var.data[0], axis_only=True, **kwargs)
1221
- kwargs['hold'] = True
1329
+ kwargs["hold"] = True
1222
1330
 
1223
1331
  return
1224
1332
 
1225
- split_name = var.name.split('/')
1226
- start = split_name[0] + '_'
1227
- end = '_' + split_name[-1]
1333
+ split_name = var.name.split("/")
1334
+ start = split_name[0] + "_"
1335
+ end = "_" + split_name[-1]
1228
1336
  data = var.blocklist.__dict__
1229
1337
 
1230
- k0 = 'vmin'
1231
- k1 = 'vmax'
1232
- k = 'vrange'
1338
+ k0 = "vmin"
1339
+ k1 = "vmax"
1340
+ k = "vrange"
1233
1341
  if k not in kwargs and not (k0 in kwargs and k1 in kwargs):
1234
1342
  vmin = var.data.min()
1235
1343
  vmax = var.data.max()
@@ -1241,7 +1349,7 @@ def plot_rays(var, skip=1, rays=None, **kwargs):
1241
1349
  continue
1242
1350
  if iray > ray_stop:
1243
1351
  break
1244
- if iray%skip == 0:
1352
+ if iray % skip == 0:
1245
1353
  vmin = min(vmin, data[k].data.min())
1246
1354
  vmax = max(vmax, data[k].data.max())
1247
1355
  if k0 not in kwargs:
@@ -1249,11 +1357,15 @@ def plot_rays(var, skip=1, rays=None, **kwargs):
1249
1357
  if k1 not in kwargs:
1250
1358
  kwargs[k1] = vmax
1251
1359
 
1252
- k = 'cbar_label'
1253
- if k not in kwargs or (kwargs[k] and type(kwargs[k]) != str):
1360
+ k = "cbar_label"
1361
+ if k not in kwargs or (kwargs[k] and not isinstance(kwargs[k], str)):
1254
1362
  # Remove /Ray[1-9]+ from the name
1255
- kwargs[k] = '/'.join([split_name[0]] + split_name[2:]) \
1256
- + ' $(' + escape_latex(var.units) + ')$'
1363
+ kwargs[k] = (
1364
+ "/".join([split_name[0]] + split_name[2:])
1365
+ + " $("
1366
+ + escape_latex(var.units)
1367
+ + ")$"
1368
+ )
1257
1369
 
1258
1370
  iray = -1
1259
1371
  for k in data.keys():
@@ -1263,25 +1375,50 @@ def plot_rays(var, skip=1, rays=None, **kwargs):
1263
1375
  continue
1264
1376
  if iray > ray_stop:
1265
1377
  break
1266
- if iray%skip == 0:
1378
+ if iray % skip == 0:
1267
1379
  plot_auto(data[k], hold=True, update=False, **kwargs)
1268
- kwargs['hold'] = True
1380
+ kwargs["hold"] = True
1269
1381
 
1270
1382
  plot_auto(var, axis_only=True, **kwargs)
1271
- kwargs['hold'] = True
1383
+ kwargs["hold"] = True
1272
1384
 
1273
1385
 
1274
1386
  def oplot2d(*args, **kwargs):
1275
- kwargs['hold'] = True
1387
+ kwargs["hold"] = True
1276
1388
  plot2d(*args, **kwargs)
1277
1389
 
1278
1390
 
1279
- def plot2d_array(array, x, y, extents, var_label, xlabel, ylabel, idx=None,
1280
- iso=None, fast=None, title=True, full=True, vrange=None,
1281
- reflect=0, norm=None, hold=True, xscale=0, yscale=0, scale=0,
1282
- figure=None, subplot=None, add_cbar=True, cbar_label=True,
1283
- cbar_wd=5, cbar_top=False, power=(-3,3), **kwargs):
1391
+ def plot2d_array(
1392
+ array,
1393
+ x,
1394
+ y,
1395
+ extents,
1396
+ var_label,
1397
+ xlabel,
1398
+ ylabel,
1399
+ idx=None,
1400
+ iso=None,
1401
+ fast=None,
1402
+ title=True,
1403
+ full=True,
1404
+ vrange=None,
1405
+ reflect=0,
1406
+ norm=None,
1407
+ hold=True,
1408
+ xscale=0,
1409
+ yscale=0,
1410
+ scale=0,
1411
+ figure=None,
1412
+ subplot=None,
1413
+ add_cbar=True,
1414
+ cbar_label=True,
1415
+ cbar_wd=5,
1416
+ cbar_top=False,
1417
+ power=(-3, 3),
1418
+ **kwargs
1419
+ ):
1284
1420
  import matplotlib as mpl
1421
+
1285
1422
  global data, fig, im, cbar
1286
1423
  global mult_x, mult_y
1287
1424
 
@@ -1302,15 +1439,16 @@ def plot2d_array(array, x, y, extents, var_label, xlabel, ylabel, idx=None,
1302
1439
  v0 = np.min(array) - norm
1303
1440
  v1 = np.max(array) - norm
1304
1441
 
1305
- if abs(v0/v1) > 1:
1442
+ if abs(v0 / v1) > 1:
1306
1443
  low = 0
1307
- high = 0.5 * (1 - v1/v0)
1444
+ high = 0.5 * (1 - v1 / v0)
1308
1445
  else:
1309
- low = 0.5 * (1 + v0/v1)
1446
+ low = 0.5 * (1 + v0 / v1)
1310
1447
  high = 1.0
1311
1448
 
1312
1449
  cmap = mpl.colors.LinearSegmentedColormap.from_list(
1313
- 'tr', cmap(np.linspace(low, high, 256)))
1450
+ "tr", cmap(np.linspace(low, high, 256))
1451
+ )
1314
1452
 
1315
1453
  if subplot is None:
1316
1454
  if figure is None:
@@ -1331,7 +1469,7 @@ def plot2d_array(array, x, y, extents, var_label, xlabel, ylabel, idx=None,
1331
1469
  figure = subplot.figure
1332
1470
  if not hold:
1333
1471
  subplot.clear()
1334
- if hasattr(subplot, 'colorbar'):
1472
+ if hasattr(subplot, "colorbar"):
1335
1473
  subplot.colorbar.remove()
1336
1474
 
1337
1475
  if iso is None:
@@ -1411,23 +1549,32 @@ def plot2d_array(array, x, y, extents, var_label, xlabel, ylabel, idx=None,
1411
1549
  ext[i1] = ext[i2]
1412
1550
  ext[i2] = e
1413
1551
  ext = [ext[i0], ext[i1], ext[i2], ext[i3]]
1414
- k = 'interpolation'
1552
+ k = "interpolation"
1415
1553
  if k not in kwargs:
1416
- kwargs[k] = 'none'
1554
+ kwargs[k] = "none"
1417
1555
  if vrange is None:
1418
- im = subplot.imshow(array.T, origin='lower', extent=ext, cmap=cmap,
1419
- **kwargs)
1556
+ im = subplot.imshow(
1557
+ array.T, origin="lower", extent=ext, cmap=cmap, **kwargs
1558
+ )
1420
1559
  else:
1421
- im = subplot.imshow(array.T, origin='lower', extent=ext, cmap=cmap,
1422
- vmin=vrange[0], vmax=vrange[1], **kwargs)
1560
+ im = subplot.imshow(
1561
+ array.T,
1562
+ origin="lower",
1563
+ extent=ext,
1564
+ cmap=cmap,
1565
+ vmin=vrange[0],
1566
+ vmax=vrange[1],
1567
+ **kwargs
1568
+ )
1423
1569
  else:
1424
1570
  X = np.multiply(mult_x, X)
1425
1571
  Y = np.multiply(mult_y, Y)
1426
1572
  if vrange is None:
1427
1573
  im = subplot.pcolormesh(X, Y, array, cmap=cmap, **kwargs)
1428
1574
  else:
1429
- im = subplot.pcolormesh(X, Y, array, cmap=cmap,
1430
- vmin=vrange[0], vmax=vrange[1], **kwargs)
1575
+ im = subplot.pcolormesh(
1576
+ X, Y, array, cmap=cmap, vmin=vrange[0], vmax=vrange[1], **kwargs
1577
+ )
1431
1578
 
1432
1579
  subplot.set_xlabel(xlabel)
1433
1580
  subplot.set_ylabel(ylabel)
@@ -1437,17 +1584,17 @@ def plot2d_array(array, x, y, extents, var_label, xlabel, ylabel, idx=None,
1437
1584
  if add_cbar and cbar_label:
1438
1585
  title_text = get_title()
1439
1586
  else:
1440
- title_text = var_label + ', ' + get_title()
1587
+ title_text = var_label + ", " + get_title()
1441
1588
  elif title:
1442
1589
  if not (add_cbar and cbar_label):
1443
1590
  title_text = var_label
1444
1591
 
1445
1592
  if title and title_text:
1446
- subplot.set_title(title_text, fontsize='large', y=1.03)
1593
+ subplot.set_title(title_text, fontsize="large", y=1.03)
1447
1594
 
1448
- subplot.axis('tight')
1595
+ subplot.axis("tight")
1449
1596
  if iso:
1450
- subplot.axis('image')
1597
+ subplot.axis("image")
1451
1598
 
1452
1599
  if not hold and add_cbar:
1453
1600
  ax = subplot.axes
@@ -1455,14 +1602,13 @@ def plot2d_array(array, x, y, extents, var_label, xlabel, ylabel, idx=None,
1455
1602
  divider = make_axes_locatable(ca)
1456
1603
  pad = int(0.6 * cbar_wd + 0.5)
1457
1604
  if cbar_top:
1458
- cax = divider.append_axes("top", "%i%%" % cbar_wd,
1459
- pad="%i%%" % pad)
1460
- cbar = figure.colorbar(im, orientation='horizontal',
1461
- cax=cax, ax=ax)
1462
- cax.xaxis.set_ticks_position('top')
1605
+ cax = divider.append_axes("top", "%i%%" % cbar_wd, pad="%i%%" % pad)
1606
+ cbar = figure.colorbar(im, orientation="horizontal", cax=cax, ax=ax)
1607
+ cax.xaxis.set_ticks_position("top")
1463
1608
  else:
1464
- cax = divider.append_axes("right", "%i%%" % cbar_wd,
1465
- pad="%i%%" % pad)
1609
+ cax = divider.append_axes(
1610
+ "right", "%i%%" % cbar_wd, pad="%i%%" % pad
1611
+ )
1466
1612
  cbar = figure.colorbar(im, cax=cax, ax=ax)
1467
1613
  try:
1468
1614
  cbar.formatter.set_powerlimits(power)
@@ -1472,33 +1618,53 @@ def plot2d_array(array, x, y, extents, var_label, xlabel, ylabel, idx=None,
1472
1618
  subplot.colorbar = cax
1473
1619
  plt.sca(ax)
1474
1620
  if cbar_label:
1475
- if type(cbar_label) is str:
1621
+ if isinstance(cbar_label, str):
1476
1622
  var_label = cbar_label
1477
1623
  if cbar_top:
1478
- cbar.set_label(var_label, fontsize='large')
1479
- cax.xaxis.set_label_position('top')
1624
+ cbar.set_label(var_label, fontsize="large")
1625
+ cax.xaxis.set_label_position("top")
1480
1626
  else:
1481
- cbar.set_label(var_label, fontsize='large', x=1.2)
1627
+ cbar.set_label(var_label, fontsize="large", x=1.2)
1482
1628
  figure.canvas.draw()
1483
1629
 
1484
1630
  figure.set_tight_layout(True)
1485
1631
  figure.canvas.draw()
1486
1632
 
1487
1633
 
1488
- def plot2d(var, iso=None, fast=None, title=True, full=True, vrange=None,
1489
- ix=None, iy=None, iz=None, reflect=0, norm=None, irange=None,
1490
- jrange=None, hold=True, xscale=0, yscale=0, scale=0, figure=None,
1491
- subplot=None, add_cbar=True, cbar_label=True, cbar_top=False,
1492
- **kwargs):
1634
+ def plot2d(
1635
+ var,
1636
+ iso=None,
1637
+ fast=None,
1638
+ title=True,
1639
+ full=True,
1640
+ vrange=None,
1641
+ ix=None,
1642
+ iy=None,
1643
+ iz=None,
1644
+ reflect=0,
1645
+ norm=None,
1646
+ irange=None,
1647
+ jrange=None,
1648
+ hold=True,
1649
+ xscale=0,
1650
+ yscale=0,
1651
+ scale=0,
1652
+ figure=None,
1653
+ subplot=None,
1654
+ add_cbar=True,
1655
+ cbar_label=True,
1656
+ cbar_top=False,
1657
+ **kwargs
1658
+ ):
1493
1659
  global data, fig, im, cbar
1494
1660
  global x, y, mult_x, mult_y
1495
1661
 
1496
- if type(irange) is list or type(irange) is tuple:
1662
+ if isinstance(irange, list) or isinstance(irange, tuple):
1497
1663
  si = slice(*irange)
1498
1664
  else:
1499
1665
  si = slice(None, irange)
1500
1666
 
1501
- if type(jrange) is list or type(jrange) is tuple:
1667
+ if isinstance(jrange, list) or isinstance(jrange, tuple):
1502
1668
  sj = slice(*jrange)
1503
1669
  else:
1504
1670
  sj = slice(None, jrange)
@@ -1589,23 +1755,51 @@ def plot2d(var, iso=None, fast=None, title=True, full=True, vrange=None,
1589
1755
  else:
1590
1756
  mult_y, sym_y = get_si_prefix(yscale)
1591
1757
 
1592
- xlabel = var.grid.labels[i0] \
1593
- + ' $(' + escape_latex(sym_x + var.grid.units[i0]) + ')$'
1594
- ylabel = var.grid.labels[i1] \
1595
- + ' $(' + escape_latex(sym_y + var.grid.units[i1]) + ')$'
1596
-
1597
- var_label = var.name + ' $(' + escape_latex(var.units) + ')$'
1598
-
1599
- if hasattr(var, 'blocklist'):
1758
+ xlabel = (
1759
+ var.grid.labels[i0]
1760
+ + " $("
1761
+ + escape_latex(sym_x + var.grid.units[i0])
1762
+ + ")$"
1763
+ )
1764
+ ylabel = (
1765
+ var.grid.labels[i1]
1766
+ + " $("
1767
+ + escape_latex(sym_y + var.grid.units[i1])
1768
+ + ")$"
1769
+ )
1770
+
1771
+ var_label = var.name + " $(" + escape_latex(var.units) + ")$"
1772
+
1773
+ if hasattr(var, "blocklist"):
1600
1774
  data = var.blocklist
1601
1775
 
1602
- plot2d_array(array=array, x=x, y=y, extents=extents, var_label=var_label,
1603
- xlabel=xlabel, ylabel=ylabel, idx=idx, iso=iso, fast=fast,
1604
- title=title, full=full, vrange=vrange, reflect=reflect,
1605
- norm=norm, hold=hold, xscale=xscale, yscale=yscale,
1606
- scale=scale, figure=figure, subplot=subplot,
1607
- add_cbar=add_cbar, cbar_label=cbar_label, cbar_top=cbar_top,
1608
- **kwargs)
1776
+ plot2d_array(
1777
+ array=array,
1778
+ x=x,
1779
+ y=y,
1780
+ extents=extents,
1781
+ var_label=var_label,
1782
+ xlabel=xlabel,
1783
+ ylabel=ylabel,
1784
+ idx=idx,
1785
+ iso=iso,
1786
+ fast=fast,
1787
+ title=title,
1788
+ full=full,
1789
+ vrange=vrange,
1790
+ reflect=reflect,
1791
+ norm=norm,
1792
+ hold=hold,
1793
+ xscale=xscale,
1794
+ yscale=yscale,
1795
+ scale=scale,
1796
+ figure=figure,
1797
+ subplot=subplot,
1798
+ add_cbar=add_cbar,
1799
+ cbar_label=cbar_label,
1800
+ cbar_top=cbar_top,
1801
+ **kwargs
1802
+ )
1609
1803
 
1610
1804
 
1611
1805
  def plot2d_update(var):
@@ -1616,8 +1810,17 @@ def plot2d_update(var):
1616
1810
  fig.canvas.draw()
1617
1811
 
1618
1812
 
1619
- def plot_levels(var, r0=None, r1=None, nl=10, iso=None, out=False,
1620
- title=True, levels=True, **kwargs):
1813
+ def plot_levels(
1814
+ var,
1815
+ r0=None,
1816
+ r1=None,
1817
+ nl=10,
1818
+ iso=None,
1819
+ out=False,
1820
+ title=True,
1821
+ levels=True,
1822
+ **kwargs
1823
+ ):
1621
1824
  global data
1622
1825
 
1623
1826
  try:
@@ -1626,7 +1829,7 @@ def plot_levels(var, r0=None, r1=None, nl=10, iso=None, out=False,
1626
1829
  pass
1627
1830
 
1628
1831
  if iso is None:
1629
- if hasattr(var, 'blocklist'):
1832
+ if hasattr(var, "blocklist"):
1630
1833
  data = var.blocklist
1631
1834
  iso = get_default_iso(data)
1632
1835
 
@@ -1656,13 +1859,13 @@ def plot_levels(var, r0=None, r1=None, nl=10, iso=None, out=False,
1656
1859
  else:
1657
1860
  ax = plt.gca()
1658
1861
 
1659
- k = 'colors'
1862
+ k = "colors"
1660
1863
  if k not in kwargs:
1661
- kwargs[k] = 'k'
1662
- k = 'linewidths'
1864
+ kwargs[k] = "k"
1865
+ k = "linewidths"
1663
1866
  if k not in kwargs:
1664
1867
  kwargs[k] = 0.5
1665
- k = 'levels'
1868
+ k = "levels"
1666
1869
  if k not in kwargs:
1667
1870
  kwargs[k] = rl
1668
1871
 
@@ -1670,57 +1873,73 @@ def plot_levels(var, r0=None, r1=None, nl=10, iso=None, out=False,
1670
1873
 
1671
1874
  if levels:
1672
1875
  fmt = {}
1673
- for l, i in zip(cs.levels, range(1, len(cs.levels)+1)):
1876
+ for l, i in zip(cs.levels, range(1, len(cs.levels) + 1)):
1674
1877
  fmt[l] = str(i)
1675
1878
 
1676
1879
  sidx = ""
1677
1880
  slvl = ""
1678
- for l, i in reversed(list(zip(cs.levels, range(1, len(cs.levels)+1)))):
1881
+ for l, i in reversed(
1882
+ list(zip(cs.levels, range(1, len(cs.levels) + 1)))
1883
+ ):
1679
1884
  # sidx += rtn + "%i" % i
1680
1885
  # slvl += rtn + "%-6.4g" % l
1681
1886
  # rtn = "\n"
1682
1887
  sidx += "%i\n" % i
1683
1888
  slvl += "%-6.4g\n" % l
1684
1889
 
1685
- t1 = TextArea('Level', textprops=dict(color='k', fontsize='small'))
1686
- t2 = TextArea(sidx, textprops=dict(color='k', fontsize='small'))
1890
+ t1 = TextArea("Level", textprops=dict(color="k", fontsize="small"))
1891
+ t2 = TextArea(sidx, textprops=dict(color="k", fontsize="small"))
1687
1892
  tl = VPacker(children=[t1, t2], align="center", pad=0, sep=2)
1688
1893
 
1689
1894
  lname = var.name.replace("_node", "")
1690
- t3 = TextArea(lname, textprops=dict(color='k', fontsize='small'))
1691
- t4 = TextArea(slvl, textprops=dict(color='k', fontsize='small'))
1895
+ t3 = TextArea(lname, textprops=dict(color="k", fontsize="small"))
1896
+ t4 = TextArea(slvl, textprops=dict(color="k", fontsize="small"))
1692
1897
  tr = VPacker(children=[t3, t4], align="center", pad=0, sep=2)
1693
1898
 
1694
1899
  t = HPacker(children=[tl, tr], align="center", pad=0, sep=8)
1695
1900
 
1696
1901
  if out:
1697
- t = AnchoredOffsetbox(loc=2, child=t, pad=.4,
1698
- bbox_to_anchor=(1.01, 1), frameon=True,
1699
- bbox_transform=ax.transAxes, borderpad=0)
1902
+ t = AnchoredOffsetbox(
1903
+ loc=2,
1904
+ child=t,
1905
+ pad=0.4,
1906
+ bbox_to_anchor=(1.01, 1),
1907
+ frameon=True,
1908
+ bbox_transform=ax.transAxes,
1909
+ borderpad=0,
1910
+ )
1700
1911
  else:
1701
- t = AnchoredOffsetbox(loc=1, child=t, pad=.4,
1702
- bbox_to_anchor=(1, 1), frameon=True,
1703
- bbox_transform=ax.transAxes, borderpad=.4)
1912
+ t = AnchoredOffsetbox(
1913
+ loc=1,
1914
+ child=t,
1915
+ pad=0.4,
1916
+ bbox_to_anchor=(1, 1),
1917
+ frameon=True,
1918
+ bbox_transform=ax.transAxes,
1919
+ borderpad=0.4,
1920
+ )
1704
1921
  t.set_clip_on(False)
1705
1922
  ax.add_artist(t)
1706
1923
 
1707
1924
  plt.clabel(cs, cs.levels, fmt=fmt, inline_spacing=2, fontsize=8)
1708
1925
 
1709
- ax.set_xlabel(var.grid.labels[0] + ' $('
1710
- + escape_latex(var.grid.units[0]) + ')$')
1711
- ax.set_ylabel(var.grid.labels[1] + ' $('
1712
- + escape_latex(var.grid.units[1]) + ')$')
1926
+ ax.set_xlabel(
1927
+ var.grid.labels[0] + " $(" + escape_latex(var.grid.units[0]) + ")$"
1928
+ )
1929
+ ax.set_ylabel(
1930
+ var.grid.labels[1] + " $(" + escape_latex(var.grid.units[1]) + ")$"
1931
+ )
1713
1932
 
1714
1933
  if title:
1715
1934
  if out:
1716
1935
  # suptitle(get_title(), fontsize='large')
1717
- plt.suptitle(get_title(var), fontsize='large', y=0.92)
1936
+ plt.suptitle(get_title(var), fontsize="large", y=0.92)
1718
1937
  else:
1719
- plt.title(get_title(var), fontsize='large', y=1.03)
1938
+ plt.title(get_title(var), fontsize="large", y=1.03)
1720
1939
 
1721
- plt.axis('tight')
1940
+ plt.axis("tight")
1722
1941
  if iso:
1723
- plt.axis('image')
1942
+ plt.axis("image")
1724
1943
 
1725
1944
  plt.draw()
1726
1945
  if out:
@@ -1737,8 +1956,17 @@ def plot_levels(var, r0=None, r1=None, nl=10, iso=None, out=False,
1737
1956
 
1738
1957
 
1739
1958
  def plot_contour(var, r0=None, r1=None, nl=10, iso=None, title=True, **kwargs):
1740
- return plot_levels(var, r0=r0, r1=r1, nl=nl, iso=iso, out=False,
1741
- title=title, levels=False, **kwargs)
1959
+ return plot_levels(
1960
+ var,
1961
+ r0=r0,
1962
+ r1=r1,
1963
+ nl=nl,
1964
+ iso=iso,
1965
+ out=False,
1966
+ title=title,
1967
+ levels=False,
1968
+ **kwargs
1969
+ )
1742
1970
 
1743
1971
 
1744
1972
  def getdata(fname, wkd=None, verbose=True, squeeze=False):
@@ -1767,13 +1995,16 @@ def getdata(fname, wkd=None, verbose=True, squeeze=False):
1767
1995
  filename = "./" + fname
1768
1996
  try:
1769
1997
  st = os.stat(filename)
1770
- wkdir = '.'
1998
+ wkdir = "."
1771
1999
  except OSError as e:
1772
2000
  print("ERROR opening file {0}: {1}".format(filename, e.strerror))
1773
2001
  raise
1774
2002
 
1775
- if st.st_mtime != old_mtime or st.st_size != old_size \
1776
- or filename != old_filename:
2003
+ if (
2004
+ st.st_mtime != old_mtime
2005
+ or st.st_size != old_size
2006
+ or filename != old_filename
2007
+ ):
1777
2008
  if verbose:
1778
2009
  print("Reading file " + filename)
1779
2010
  data = sdf.read(filename)
@@ -1792,7 +2023,7 @@ def getdata(fname, wkd=None, verbose=True, squeeze=False):
1792
2023
  try:
1793
2024
  dims = []
1794
2025
  for element in value.dims:
1795
- dims.append([0, element-1])
2026
+ dims.append([0, element - 1])
1796
2027
  subarray(value, dims)
1797
2028
  except:
1798
2029
  pass
@@ -1805,8 +2036,8 @@ def getdata(fname, wkd=None, verbose=True, squeeze=False):
1805
2036
  sdfdict[key] = value
1806
2037
 
1807
2038
  fdict = {}
1808
- table = {'time': 't'}
1809
- k = 'Header'
2039
+ table = {"time": "t"}
2040
+ k = "Header"
1810
2041
  if k in sdfdict:
1811
2042
  h = sdfdict[k]
1812
2043
  k = list(table.keys())[0]
@@ -1814,44 +2045,46 @@ def getdata(fname, wkd=None, verbose=True, squeeze=False):
1814
2045
  key = table[k]
1815
2046
  var = h[k]
1816
2047
  if verbose:
1817
- print(key + str(np.shape(var)) + ' = ' + k)
2048
+ print(key + str(np.shape(var)) + " = " + k)
1818
2049
  fdict[key] = var
1819
2050
  globals()[key] = var
1820
2051
  builtins.__dict__[key] = var
1821
2052
 
1822
- table = {'Pressure': 'p',
1823
- 'Pressure_ion': 'ppi',
1824
- 'Pressure_electron': 'ppe',
1825
- 'Rho': 'rho',
1826
- 'Energy_ion': 'ei',
1827
- 'Energy_electron': 'ee',
1828
- 'Vx': 'vx',
1829
- 'Vy': 'vy',
1830
- 'Vz': 'vz',
1831
- 'Vr': 'vx',
1832
- 'VTheta': 'vz',
1833
- 'Bx': 'bx',
1834
- 'By': 'by',
1835
- 'Bz': 'bz',
1836
- 'Br': 'bx',
1837
- 'Bt': 'bz',
1838
- 'bx': 'bx',
1839
- 'by': 'by',
1840
- 'bz': 'bz',
1841
- 'ex': 'ex',
1842
- 'ey': 'ey',
1843
- 'ez': 'ez',
1844
- 'jx': 'jx',
1845
- 'jy': 'jy',
1846
- 'jz': 'jz'}
2053
+ table = {
2054
+ "Pressure": "p",
2055
+ "Pressure_ion": "ppi",
2056
+ "Pressure_electron": "ppe",
2057
+ "Rho": "rho",
2058
+ "Energy_ion": "ei",
2059
+ "Energy_electron": "ee",
2060
+ "Vx": "vx",
2061
+ "Vy": "vy",
2062
+ "Vz": "vz",
2063
+ "Vr": "vx",
2064
+ "VTheta": "vz",
2065
+ "Bx": "bx",
2066
+ "By": "by",
2067
+ "Bz": "bz",
2068
+ "Br": "bx",
2069
+ "Bt": "bz",
2070
+ "bx": "bx",
2071
+ "by": "by",
2072
+ "bz": "bz",
2073
+ "ex": "ex",
2074
+ "ey": "ey",
2075
+ "ez": "ez",
2076
+ "jx": "jx",
2077
+ "jy": "jy",
2078
+ "jz": "jz",
2079
+ }
1847
2080
 
1848
2081
  rz = False
1849
- if 'Vr' in sdfdict:
2082
+ if "Vr" in sdfdict:
1850
2083
  rz = True
1851
2084
 
1852
2085
  if rz:
1853
- table['Vz'] = 'vy'
1854
- table['Bz'] = 'by'
2086
+ table["Vz"] = "vy"
2087
+ table["Bz"] = "by"
1855
2088
 
1856
2089
  inv_table = {}
1857
2090
  for k, v in table.items():
@@ -1867,68 +2100,69 @@ def getdata(fname, wkd=None, verbose=True, squeeze=False):
1867
2100
  var = sdfdict[k]
1868
2101
  dims = str(tuple(int(i) for i in sdfdict[k].dims))
1869
2102
  if verbose:
1870
- print(key + dims + ' = ' + k)
2103
+ print(key + dims + " = " + k)
1871
2104
  fdict[key] = var
1872
2105
  globals()[key] = var
1873
2106
  builtins.__dict__[key] = var
1874
2107
 
1875
- k = 'grid'
2108
+ k = "grid"
1876
2109
  if k in sdfdict:
1877
2110
  vargrid = sdfdict[k]
1878
2111
  grid = vargrid
1879
- keys = 'x', 'y', 'z'
2112
+ keys = "x", "y", "z"
1880
2113
  for n in range(np.size(vargrid.dims)):
1881
2114
  key = keys[n]
1882
2115
  var = vargrid.data[n]
1883
2116
  dims = str(tuple(int(i) for i in sdfdict[k].dims))
1884
2117
  if verbose:
1885
- print(key + dims + ' = ' + k)
2118
+ print(key + dims + " = " + k)
1886
2119
  fdict[key] = var
1887
2120
  globals()[key] = var
1888
2121
  builtins.__dict__[key] = var
1889
2122
 
1890
- k = 'grid_mid'
2123
+ k = "grid_mid"
1891
2124
  if k in sdfdict:
1892
2125
  vargrid = sdfdict[k]
1893
2126
  grid_mid = vargrid
1894
- keys = 'xc', 'yc', 'zc'
2127
+ keys = "xc", "yc", "zc"
1895
2128
  for n in range(np.size(vargrid.dims)):
1896
2129
  key = keys[n]
1897
2130
  var = vargrid.data[n]
1898
2131
  dims = str(tuple(int(i) for i in sdfdict[k].dims))
1899
2132
  if verbose:
1900
- print(key + dims + ' = ' + k)
2133
+ print(key + dims + " = " + k)
1901
2134
  fdict[key] = var
1902
2135
  globals()[key] = var
1903
2136
  builtins.__dict__[key] = var
1904
2137
 
1905
2138
  # Export particle arrays
1906
2139
  for k, value in data.__dict__.items():
1907
- if type(value) != sdf.BlockPointVariable \
1908
- and type(value) != sdf.BlockPointMesh:
2140
+ if not isinstance(value, sdf.BlockPointVariable) and not isinstance(
2141
+ value, sdf.BlockPointMesh
2142
+ ):
1909
2143
  continue
1910
- key = re.sub(r'[^a-z0-9]', '_', value.id.lower())
2144
+ key = re.sub(r"[^a-z0-9]", "_", value.id.lower())
1911
2145
  if hasattr(value, "data"):
1912
2146
  var = value.data
1913
2147
  else:
1914
2148
  var = value
1915
2149
  dims = str(tuple(int(i) for i in value.dims))
1916
- if type(value) == sdf.BlockPointVariable:
2150
+ if isinstance(value, sdf.BlockPointVariable):
1917
2151
  if verbose:
1918
- print(key + dims + ' = ' + value.name)
2152
+ print(key + dims + " = " + value.name)
1919
2153
  fdict[key] = var
1920
2154
  globals()[key] = var
1921
2155
  builtins.__dict__[key] = var
1922
2156
  else:
1923
2157
  vargrid = value
1924
2158
  grid = vargrid
1925
- keys = 'x', 'y', 'z'
2159
+ keys = "x", "y", "z"
1926
2160
  for n in range(np.size(value.dims)):
1927
- gkey = keys[n] + '_' + key
2161
+ gkey = keys[n] + "_" + key
1928
2162
  var = value.data[n]
1929
2163
  dims = str(tuple(int(i) for i in value.dims))
1930
2164
  if verbose:
1931
- print(gkey + dims + ' = ' + k + ' ' + keys[n])
2165
+ print(gkey + dims + " = " + k + " " + keys[n])
1932
2166
  fdict[gkey] = var
1933
2167
  globals()[gkey] = var
1934
2168
  builtins.__dict__[gkey] = var
@@ -1947,18 +2181,18 @@ def ogrid(skip=None, **kwargs):
1947
2181
  Y = y[s, s]
1948
2182
  X = np.multiply(mult_x, X)
1949
2183
  Y = np.multiply(mult_y, Y)
1950
- k = 'lw'
1951
- if k not in kwargs and 'linewidth' not in kwargs:
2184
+ k = "lw"
2185
+ if k not in kwargs and "linewidth" not in kwargs:
1952
2186
  kwargs[k] = 0.5
1953
- k = 'color'
2187
+ k = "color"
1954
2188
  if k not in kwargs:
1955
- kwargs[k] = 'k'
2189
+ kwargs[k] = "k"
1956
2190
  plt.plot(X, Y, **kwargs)
1957
2191
  plt.plot(X.transpose(), Y.transpose(), **kwargs)
1958
2192
 
1959
2193
 
1960
2194
  def plotgrid(fname=None, iso=None, title=True):
1961
- if type(fname) is sdf.BlockList or type(fname) is dict:
2195
+ if isinstance(fname, sdf.BlockList) or isinstance(fname, dict):
1962
2196
  dat = fname
1963
2197
  elif fname is not None:
1964
2198
  dat = getdata(fname, verbose=verbose)
@@ -1970,15 +2204,15 @@ def plotgrid(fname=None, iso=None, title=True):
1970
2204
 
1971
2205
  ax = plt.gca()
1972
2206
 
1973
- ax.set_xlabel(grid.labels[0] + ' $(' + escape_latex(grid.units[0]) + ')$')
1974
- ax.set_ylabel(grid.labels[1] + ' $(' + escape_latex(grid.units[1]) + ')$')
2207
+ ax.set_xlabel(grid.labels[0] + " $(" + escape_latex(grid.units[0]) + ")$")
2208
+ ax.set_ylabel(grid.labels[1] + " $(" + escape_latex(grid.units[1]) + ")$")
1975
2209
 
1976
2210
  if title:
1977
- plt.title(get_title(), fontsize='large', y=1.03)
2211
+ plt.title(get_title(), fontsize="large", y=1.03)
1978
2212
 
1979
- plt.axis('tight')
2213
+ plt.axis("tight")
1980
2214
  if iso:
1981
- plt.axis('image')
2215
+ plt.axis("image")
1982
2216
 
1983
2217
  plt.draw()
1984
2218
 
@@ -1997,28 +2231,28 @@ def axis_offset(boxed=False):
1997
2231
  # for o in ax.findobj():
1998
2232
  for l in ax.get_lines():
1999
2233
  bb = l.get_clip_box()
2000
- bb._bbox = Bbox([[-f, -f], [1+2*f, 1+2*f]])
2234
+ bb._bbox = Bbox([[-f, -f], [1 + 2 * f, 1 + 2 * f]])
2001
2235
  l.set_clip_box(bb)
2002
2236
  # l.set_clip_on(False)
2003
2237
 
2004
2238
  if boxed:
2005
- r = matplotlib.patches.Rectangle((-f, -f), 1+2*f, 1+2*f,
2006
- transform=ax.transAxes)
2239
+ r = matplotlib.patches.Rectangle(
2240
+ (-f, -f), 1 + 2 * f, 1 + 2 * f, transform=ax.transAxes
2241
+ )
2007
2242
  r.set_color((0, 0, 0, 0))
2008
- r.set_edgecolor('k')
2243
+ r.set_edgecolor("k")
2009
2244
  r.set_clip_on(False)
2010
2245
  ax.add_patch(r)
2011
2246
 
2012
2247
  w = 1.1
2013
2248
  gap = 8
2014
- ax.spines['top'].set_visible(False)
2015
- ax.spines['right'].set_visible(False)
2016
- ax.spines['left'].set_position(('outward', gap))
2017
- ax.spines['left'].set_linewidth(w)
2018
- ax.spines['bottom'].set_position(('outward', gap))
2019
- ax.spines['bottom'].set_linewidth(w)
2020
- ax.tick_params(direction='out', width=w, length=4.5, top='off',
2021
- right='off')
2249
+ ax.spines["top"].set_visible(False)
2250
+ ax.spines["right"].set_visible(False)
2251
+ ax.spines["left"].set_position(("outward", gap))
2252
+ ax.spines["left"].set_linewidth(w)
2253
+ ax.spines["bottom"].set_position(("outward", gap))
2254
+ ax.spines["bottom"].set_linewidth(w)
2255
+ ax.tick_params(direction="out", width=w, length=4.5, top="off", right="off")
2022
2256
  ax.set_xlabel(xlab)
2023
2257
  ax.set_ylabel(ylab)
2024
2258
 
@@ -2038,7 +2272,7 @@ def tuple_to_slice(slices):
2038
2272
 
2039
2273
 
2040
2274
  def subarray(base, slices):
2041
- if (len(slices) != len(base.dims)):
2275
+ if len(slices) != len(base.dims):
2042
2276
  print("Must specify a range in all dimensions")
2043
2277
  return None
2044
2278
  dims = []
@@ -2050,8 +2284,8 @@ def subarray(base, slices):
2050
2284
  begin = 0
2051
2285
  if end is None:
2052
2286
  end = base.dims[x]
2053
- if (end-begin != 0):
2054
- dims.append(end-begin+1)
2287
+ if end - begin != 0:
2288
+ dims.append(end - begin + 1)
2055
2289
 
2056
2290
  subscripts = tuple_to_slice(slices)
2057
2291
  base.data = np.squeeze(base.data[subscripts])
@@ -2063,14 +2297,19 @@ def list_variables(data):
2063
2297
  for key in sorted(dct):
2064
2298
  try:
2065
2299
  val = dct[key]
2066
- print('{} {} {}'.format(key, type(val),
2067
- np.array2string(np.array(val.dims), separator=', ')))
2300
+ print(
2301
+ "{} {} {}".format(
2302
+ key,
2303
+ type(val),
2304
+ np.array2string(np.array(val.dims), separator=", "),
2305
+ )
2306
+ )
2068
2307
  except:
2069
2308
  pass
2070
2309
 
2071
2310
 
2072
2311
  def escape_latex(string):
2073
- return string.replace('%', '\%')
2312
+ return string.replace("%", r"\%")
2074
2313
 
2075
2314
 
2076
2315
  pi = 3.141592653589793238462643383279503