-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathvlsvreader.py
3394 lines (2772 loc) · 144 KB
/
vlsvreader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# This file is part of Analysator.
# Copyright 2013-2016 Finnish Meteorological Institute
# Copyright 2017-2018 University of Helsinki
#
# For details of usage, see the COPYING file and read the "Rules of the Road"
# at http://www.physics.helsinki.fi/vlasiator/
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
import struct
import xml.etree.ElementTree as ET
import ast
import numpy as np
import os
import sys
import re
import numbers
import vlsvvariables
from reduction import datareducers,multipopdatareducers,data_operators,v5reducers,multipopv5reducers
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from collections import OrderedDict
from vlsvwriter import VlsvWriter
from variable import get_data
import warnings
import time
from interpolator_amr import AMRInterpolator
from operator import itemgetter
def dict_keys_exist(dictionary, query_keys, prune_unique=False):
if query_keys.shape[0] == 0:
return np.array([],dtype=bool)
# this helps quite a lot... for some cases.
if prune_unique:
unique_keys, indices = np.unique(query_keys, axis=0, return_inverse=True)
# these are all about the same...
# if (unique_keys.ndim == 1):
mask = np.array([k in dictionary.keys() for k in unique_keys],dtype=bool)
# else: # and this isn't worth it?
# mask = np.array([tuple(k) in dictionary.keys() for k in unique_keys],dtype=bool)
# mask = np.empty(query_keys.shape, dtype=bool)
# for i,k in enumerate(query_keys):
# mask[i] = [k in dictionary.keys() for k in query_keys],dtype=bool)
# mask = np.array(list(map(lambda c: c in dictionary.keys(),query_keys)), dtype=bool)
# dlambda = np.frompyfunc(lambda c: c in dictionary.keys(),1,1)
# mask = np.array(dlambda(query_keys),dtype=bool)
mask = mask[indices]
else:
mask = np.array([k in dictionary.keys() for k in query_keys],dtype=bool)
return mask
def fsGlobalIdToGlobalIndex(globalids, bbox):
indices = np.zeros((globalids.shape[0],3),dtype=np.int64)
stride = np.int64(1)
for d in [0,1,2]:
indices[:,d] = (globalids // stride) % bbox[d]
stride *= np.int64(bbox[d])
return indices
# Read in the global ids and indices for FsGrid cells, returns
# min and max corners of the fsGrid chunk by rank
def fsReadGlobalIdsPerRank(reader):
numWritingRanks = reader.read_parameter("numWritingRanks")
rawData = reader.read(tag="MESH", name="fsgrid")
bbox = reader.read(tag="MESH_BBOX", mesh="fsgrid")
sizes = reader.read(tag="MESH_DOMAIN_SIZES", mesh="fsgrid")
currentOffset = np.int64(0)
rankIds = {}
rankIndices = {}
for i in range(0,numWritingRanks):
taskIds = rawData[currentOffset:int(currentOffset+sizes[i,0])]
rankIds[i] = np.array([min(taskIds),max(taskIds)])
rankIndices[i] = fsGlobalIdToGlobalIndex(rankIds[i], bbox)
currentOffset += int(sizes[i,0])
return rankIds, rankIndices
# Read global ID bboxes per rank and figure out the decomposition from
# the number of unique corner coordinates per dimension
def fsDecompositionFromGlobalIds(reader):
ids, inds = fsReadGlobalIdsPerRank(reader)
lows = np.array([inds[i][0] for i in inds.keys()])
xs = np.unique(lows[:,0])
ys = np.unique(lows[:,1])
zs = np.unique(lows[:,2])
return [xs.size, ys.size, zs.size]
class VlsvReader(object):
''' Class for reading VLSV files
'''
''' Meshinfo is an information container for multiple meshes.
Implemented as an empty class.
'''
class MeshInfo:
pass
file_name=""
def __init__(self, file_name, fsGridDecomposition=None):
''' Initializes the vlsv file (opens the file, reads the file footer and reads in some parameters)
:param file_name: Name of the vlsv file
:param fsGridDecomposition: Either None or a len-3 list of ints.
List (length 3): Use this as the decomposition directly. Product needs to match numWritingRanks.
'''
# Make sure the path is set in file name:
file_name = os.path.abspath(file_name)
self.file_name = file_name
try:
self.__fptr = open(self.file_name,"rb")
except FileNotFoundError as e:
print("File not found: ", self.file_name)
raise e
self.__xml_root = ET.fromstring("<VLSV></VLSV>")
self.__fileindex_for_cellid={}
self.__max_spatial_amr_level = -1
self.__fsGridDecomposition = fsGridDecomposition
self.use_dict_for_blocks = False
self.__fileindex_for_cellid_blocks={} # [0] is index, [1] is blockcount
self.__cells_with_blocks = {} # per-pop
self.__blocks_per_cell = {} # per-pop
self.__blocks_per_cell_offsets = {} # per-pop
self.__order_for_cellid_blocks = {} # per-pop
self.__vg_indexes_on_fg = np.array([]) # SEE: map_vg_onto_fg(self)
self.variable_cache = {} # {(varname, operator):data}
self.__read_xml_footer()
# vertex-indices is a 3-tuple of integers
self.__dual_cells = {(0,0,0):(1,1,1,1,1,1,1,1)} # vertex-indices : 8-tuple of cellids at each corner (for x for y for z)
self.__dual_bboxes = {} # vertex-indices : 6-list of (xmin, ymin, zmin, xmax, ymax, zmax) for the bounding box of each dual cell
self.__cell_vertices = {} # cellid : varying-length tuple of vertex-indices - includes hanging nodes!
self.__cell_corner_vertices = {} # cellid : varying-length tuple of vertex-indices - no hanging nodes!
self.__cell_neighbours = {} # cellid : set of cellids (all neighbors sharing a vertex)
self.__cell_duals = {} # cellid : tuple of vertex-indices that span this cell
self.__regular_neighbor_cache = {} # cellid-of-low-corner : (8,) np.array of cellids)
# Check if the file is using new or old vlsv format
# Read parameters (Note: Reading the spatial cell locations and
# storing them will anyway take the most time and memory):
meshName="SpatialGrid"
bbox = self.read(tag="MESH_BBOX", mesh=meshName)
if bbox is None:
try:
#read in older vlsv files where the mesh is defined with parameters
self.__xcells = (int)(self.read_parameter("xcells_ini"))
self.__ycells = (int)(self.read_parameter("ycells_ini"))
self.__zcells = (int)(self.read_parameter("zcells_ini"))
self.__xblock_size = 1
self.__yblock_size = 1
self.__zblock_size = 1
self.__xmin = self.read_parameter("xmin")
self.__ymin = self.read_parameter("ymin")
self.__zmin = self.read_parameter("zmin")
self.__xmax = self.read_parameter("xmax")
self.__ymax = self.read_parameter("ymax")
self.__zmax = self.read_parameter("zmax")
except:
# Apparently, SpatialGrid doesn't even exist in this file (because it is, for example an ionosphere test output)
# Fill in dummy values.
self.__xcells = 1
self.__ycells = 1
self.__zcells = 1
self.__xblock_size = 1
self.__yblock_size = 1
self.__zblock_size = 1
self.__xmin = 0
self.__ymin = 0
self.__zmin = 0
self.__xmax = 1
self.__ymax = 1
self.__zmax = 1
else:
#new style vlsv file with
nodeCoordinatesX = self.read(tag="MESH_NODE_CRDS_X", mesh=meshName)
nodeCoordinatesY = self.read(tag="MESH_NODE_CRDS_Y", mesh=meshName)
nodeCoordinatesZ = self.read(tag="MESH_NODE_CRDS_Z", mesh=meshName)
self.__xcells = bbox[0]
self.__ycells = bbox[1]
self.__zcells = bbox[2]
self.__xblock_size = bbox[3]
self.__yblock_size = bbox[4]
self.__zblock_size = bbox[5]
self.__xmin = nodeCoordinatesX[0]
self.__ymin = nodeCoordinatesY[0]
self.__zmin = nodeCoordinatesZ[0]
self.__xmax = nodeCoordinatesX[-1]
self.__ymax = nodeCoordinatesY[-1]
self.__zmax = nodeCoordinatesZ[-1]
self.__dx = (self.__xmax - self.__xmin) / (float)(self.__xcells)
self.__dy = (self.__ymax - self.__ymin) / (float)(self.__ycells)
self.__dz = (self.__zmax - self.__zmin) / (float)(self.__zcells)
self.__meshes = {}
# Iterate through the XML tree, find all populations
# (identified by their BLOCKIDS tag)
self.active_populations=[]
for child in self.__xml_root:
if child.tag == "BLOCKIDS":
if "name" in child.attrib:
popname = child.attrib["name"]
else:
popname = "avgs"
# Create a new (empty) MeshInfo-object for this population
pop = self.MeshInfo()
# Update list of active populations
if not popname in self.active_populations: self.active_populations.append(popname)
bbox = self.read(tag="MESH_BBOX", mesh=popname)
if bbox is None:
if self.read_parameter("vxblocks_ini") is not None:
#read in older vlsv files where the mesh is defined with
#parameters (only one possible)
pop.__vxblocks = (int)(self.read_parameter("vxblocks_ini"))
pop.__vyblocks = (int)(self.read_parameter("vyblocks_ini"))
pop.__vzblocks = (int)(self.read_parameter("vzblocks_ini"))
pop.__vxblock_size = 4 # Old files will always have WID=4, newer files read it from bbox
pop.__vyblock_size = 4
pop.__vzblock_size = 4
pop.__vxmin = self.read_parameter("vxmin")
pop.__vymin = self.read_parameter("vymin")
pop.__vzmin = self.read_parameter("vzmin")
pop.__vxmax = self.read_parameter("vxmax")
pop.__vymax = self.read_parameter("vymax")
pop.__vzmax = self.read_parameter("vzmax")
# Velocity cell lengths
pop.__dvx = ((pop.__vxmax - pop.__vxmin) / (float)(pop.__vxblocks)) / (float)(pop.__vxblock_size)
pop.__dvy = ((pop.__vymax - pop.__vymin) / (float)(pop.__vyblocks)) / (float)(pop.__vyblock_size)
pop.__dvz = ((pop.__vzmax - pop.__vzmin) / (float)(pop.__vzblocks)) / (float)(pop.__vzblock_size)
else:
#no velocity space in this file, e.g., file not written by Vlasiator
pop.__vxblocks = 0
pop.__vyblocks = 0
pop.__vzblocks = 0
pop.__vxblock_size = 4
pop.__vyblock_size = 4
pop.__vzblock_size = 4
pop.__vxmin = 0
pop.__vymin = 0
pop.__vzmin = 0
pop.__vxmax = 0
pop.__vymax = 0
pop.__vzmax = 0
# Velocity cell lengths
pop.__dvx = 1
pop.__dvy = 1
pop.__dvz = 1
else:
#new style vlsv file with bounding box
nodeCoordinatesX = self.read(tag="MESH_NODE_CRDS_X", mesh=popname)
nodeCoordinatesY = self.read(tag="MESH_NODE_CRDS_Y", mesh=popname)
nodeCoordinatesZ = self.read(tag="MESH_NODE_CRDS_Z", mesh=popname)
pop.__vxblocks = bbox[0]
pop.__vyblocks = bbox[1]
pop.__vzblocks = bbox[2]
pop.__vxblock_size = bbox[3]
pop.__vyblock_size = bbox[4]
pop.__vzblock_size = bbox[5]
pop.__vxmin = nodeCoordinatesX[0]
pop.__vymin = nodeCoordinatesY[0]
pop.__vzmin = nodeCoordinatesZ[0]
pop.__vxmax = nodeCoordinatesX[-1]
pop.__vymax = nodeCoordinatesY[-1]
pop.__vzmax = nodeCoordinatesZ[-1]
# Velocity cell lengths
pop.__dvx = ((pop.__vxmax - pop.__vxmin) / (float)(pop.__vxblocks)) / (float)(pop.__vxblock_size)
pop.__dvy = ((pop.__vymax - pop.__vymin) / (float)(pop.__vyblocks)) / (float)(pop.__vyblock_size)
pop.__dvz = ((pop.__vzmax - pop.__vzmin) / (float)(pop.__vzblocks)) / (float)(pop.__vzblock_size)
self.__meshes[popname]=pop
if not os.getenv('PTNONINTERACTIVE'):
print("Found population " + popname)
# Precipitation energy bins
i = 0
energybins = []
binexists = True
while binexists:
binexists = self.check_parameter("{}_PrecipitationCentreEnergy{}".format(popname,i))
if binexists:
binvalue = self.read_parameter("{}_PrecipitationCentreEnergy{}".format(popname,i))
energybins.append(binvalue)
i = i + 1
if i > 1:
pop.__precipitation_centre_energy = np.asarray(energybins)
vlsvvariables.speciesprecipitationenergybins[popname] = energybins
vlsvvariables.cellsize = self.__dx
if self.check_parameter("j_per_b_modifier"):
vlsvvariables.J_per_B_modifier = self.read_parameter("j_per_b_modifier")
self.__fptr.close()
def __read_xml_footer(self):
''' Reads in the XML footer of the VLSV file and store all the content
'''
#(endianness,) = struct.unpack("c", fptr.read(1))
if self.__fptr.closed:
fptr = open(self.file_name,"rb")
else:
fptr = self.__fptr
# Eight first bytes indicate whether the system is big_endianness or something else
endianness_offset = 8
fptr.seek(endianness_offset)
# Read 8 bytes as unsigned long long (uint64_t in this case) after endianness, this tells the offset of the XML file.
uint64_byte_amount = 8
(offset,) = struct.unpack("Q", fptr.read(uint64_byte_amount))
# Move to the xml offset
fptr.seek(offset)
# Read the xml data
xml_data = bytearray()
for chunk in iter(lambda: fptr.read(4096), ''):
if chunk == b'':
break
xml_data += chunk
# Read the xml as string
(xml_string,) = struct.unpack("%ds" % len(xml_data), xml_data)
# Input the xml data into xml_root
self.__xml_root = ET.fromstring(xml_string)
if self.__fptr.closed:
fptr.close()
def __read_fileindex_for_cellid(self):
""" Read in the cell ids and create an internal dictionary to give the index of an arbitrary cellID
"""
if not self.__fileindex_for_cellid == {}:
return
cellids=self.read(mesh="SpatialGrid",name="CellID", tag="VARIABLE")
#Check if it is not iterable. If it is a scale then make it a list
if(not isinstance(cellids, Iterable)):
cellids=[ cellids ]
# self.__fileindex_for_cellid = {cellid:index for index,cellid in enumerate(cellids)}
for index,cellid in enumerate(cellids):
self.__fileindex_for_cellid[cellid] = index
def __read_blocks(self, cellid, pop="proton"):
''' Read raw velocity block data from the open file.
:param cellid: Cell ID of the cell whose velocity blocks are read
:returns: A numpy array with block ids and their data
'''
if self.use_dict_for_blocks: #deprecated version
if not pop in self.__fileindex_for_cellid_blocks:
self.__set_cell_offset_and_blocks(pop)
if( (cellid in self.__fileindex_for_cellid_blocks[pop]) == False ):
# Cell id has no blocks
return []
offset = self.__fileindex_for_cellid_blocks[pop][cellid][0]
num_of_blocks = self.__fileindex_for_cellid_blocks[pop][cellid][1]
else:
# Uses arrays (much faster to initialize)
if not pop in self.__cells_with_blocks:
self.__set_cell_offset_and_blocks_nodict(pop)
# Check that cells has vspace
try:
cells_with_blocks_index = self.__order_for_cellid_blocks[pop][cellid]
except:
print("Cell does not have velocity distribution")
return []
offset = self.__blocks_per_cell_offsets[pop][cells_with_blocks_index]
num_of_blocks = self.__blocks_per_cell[pop][cells_with_blocks_index]
if self.__fptr.closed:
fptr = open(self.file_name,"rb")
else:
fptr = self.__fptr
# Read in avgs and velocity cell ids:
for child in self.__xml_root:
# Read in block values
if ("name" in child.attrib) and (child.attrib["name"] == pop) and (child.tag == "BLOCKVARIABLE"):
vector_size = ast.literal_eval(child.attrib["vectorsize"])
#array_size = ast.literal_eval(child.attrib["arraysize"])
element_size = ast.literal_eval(child.attrib["datasize"])
datatype = child.attrib["datatype"]
# Navigate to the correct position
offset_avgs = int(offset * vector_size * element_size + ast.literal_eval(child.text))
# for i in range(0, cells_with_blocks_index[0]):
# offset_avgs += blocks_per_cell[i]*vector_size*element_size
fptr.seek(offset_avgs)
if datatype == "float" and element_size == 4:
data_avgs = np.fromfile(fptr, dtype = np.float32, count = vector_size*num_of_blocks)
if datatype == "float" and element_size == 8:
data_avgs = np.fromfile(fptr, dtype = np.float64, count = vector_size*num_of_blocks)
data_avgs = data_avgs.reshape(num_of_blocks, vector_size)
# Read in block coordinates:
# (note the special treatment in case the population is named 'avgs'
if (pop == 'avgs' or ("name" in child.attrib) and (child.attrib["name"] == pop)) and (child.tag == "BLOCKIDS"):
vector_size = ast.literal_eval(child.attrib["vectorsize"])
#array_size = ast.literal_eval(child.attrib["arraysize"])
element_size = ast.literal_eval(child.attrib["datasize"])
datatype = child.attrib["datatype"]
offset_block_ids = int(offset * vector_size * element_size + ast.literal_eval(child.text))
fptr.seek(offset_block_ids)
if datatype == "uint" and element_size == 4:
data_block_ids = np.fromfile(fptr, dtype = np.uint32, count = vector_size*num_of_blocks)
elif datatype == "uint" and element_size == 8:
data_block_ids = np.fromfile(fptr, dtype = np.uint64, count = vector_size*num_of_blocks)
else:
print("Error! Bad block id data!")
print("Data type: " + datatype + ", element size: " + str(element_size))
return
data_block_ids = np.reshape(data_block_ids, (len(data_block_ids),) )
if self.__fptr.closed:
fptr.close()
# Check to make sure the sizes match (just some extra debugging)
print("data_avgs = " + str(data_avgs) + ", data_block_ids = " + str(data_block_ids))
if len(data_avgs) != len(data_block_ids):
print("BAD DATA SIZES")
return [data_block_ids, data_avgs]
def __set_cell_offset_and_blocks(self, pop="proton"):
''' Read blocks per cell and the offset in the velocity space arrays for
every cell with blocks into a private dictionary.
Deprecated in favor of below version.
'''
print("Getting offsets for population " + pop)
if pop in self.__fileindex_for_cellid_blocks:
# There's stuff already saved into the dictionary, don't save it again
return
#these two arrays are in the same order:
#list of cells for which dist function is saved
cells_with_blocks = self.read(mesh="SpatialGrid",tag="CELLSWITHBLOCKS", name=pop)
#number of blocks in each cell for which data is stored
blocks_per_cell = self.read(mesh="SpatialGrid",tag="BLOCKSPERCELL", name=pop)
# Navigate to the correct position:
from copy import copy
offset = 0
#self.__fileindex_for_cellid_blocks[pop] = {}
self.__fileindex_for_cellid_blocks[pop] = dict.fromkeys(cells_with_blocks) # should be faster but negligible difference
for i in range(0, len(cells_with_blocks)):
self.__fileindex_for_cellid_blocks[pop][cells_with_blocks[i]] = [copy(offset), copy(blocks_per_cell[i])]
offset += blocks_per_cell[i]
def __set_cell_offset_and_blocks_nodict(self, pop="proton"):
''' Read blocks per cell and the offset in the velocity space arrays for every cell with blocks.
Stores them in arrays. Creates a private dictionary with addressing to the array.
This method should be faster than the above function.
'''
if pop in self.__cells_with_blocks:
# There's stuff already saved into the dictionary, don't save it again
return
print("Getting offsets for population " + pop)
self.__cells_with_blocks[pop] = np.atleast_1d(self.read(mesh="SpatialGrid",tag="CELLSWITHBLOCKS", name=pop))
self.__blocks_per_cell[pop] = np.atleast_1d(self.read(mesh="SpatialGrid",tag="BLOCKSPERCELL", name=pop))
self.__blocks_per_cell_offsets[pop] = np.empty(len(self.__cells_with_blocks[pop]))
self.__blocks_per_cell_offsets[pop][0] = 0.0
self.__blocks_per_cell_offsets[pop][1:] = np.cumsum(self.__blocks_per_cell[pop][:-1])
self.__order_for_cellid_blocks[pop] = {}
for index,cellid in enumerate(self.__cells_with_blocks[pop]):
self.__order_for_cellid_blocks[pop][cellid]=index
def list(self, parameter=True, variable=True, mesh=False, datareducer=False, operator=False, other=False):
''' Print out a description of the content of the file. Useful
for interactive usage. Default is to list parameters and variables, query selection can be adjusted with keywords:
Default and supported keywords:
parameter=True
variable=True
mesh=False
datareducer=False
operator=False
other=False
'''
if parameter:
print("tag = PARAMETER")
for child in self.__xml_root:
if child.tag == "PARAMETER" and "name" in child.attrib:
print(" ", child.attrib["name"])
if variable:
print("tag = VARIABLE")
for child in self.__xml_root:
if child.tag == "VARIABLE" and "name" in child.attrib:
print(" ", child.attrib["name"])
if mesh:
print("tag = MESH")
for child in self.__xml_root:
if child.tag == "MESH" and "name" in child.attrib:
print(" ", child.attrib["name"])
if datareducer:
print("Datareducers:")
for name in datareducers:
print(" ",name, " based on ", datareducers[name].variables)
if operator:
print("Data operators:")
for name in data_operators:
if type(name) is str:
if not name.isdigit():
print(" ",name)
if other:
print("Other:")
for child in self.__xml_root:
if child.tag != "PARAMETER" and child.tag != "VARIABLE" and child.tag != "MESH":
print(" tag = ", child.tag, " mesh = ", child.attrib["mesh"])
def check_parameter( self, name ):
''' Checks if a given parameter is in the vlsv reader
:param name: Name of the parameter
:returns: True if the parameter is in the vlsv file, false if not
.. note:: This should be used for checking if a parameter exists, e.g. for different Vlasiator versions and time output
.. code-block:: python
# Example usage:
vlsvReader = pt.vlsvfile.VlsvReader("test.vlsv")
if vlsvReader.check_parameter( "time" ):
time = vlsvReader.read_parameter("time")
elif vlsvReader.check_parameter( "t" ):
time = vlsvReader.read_parameter("t")
else:
time = None
'''
for child in self.__xml_root:
if child.tag == "PARAMETER" and "name" in child.attrib:
if child.attrib["name"].lower() == name.lower():
return True
return False
def check_variable( self, name ):
''' Checks if a given variable is in the vlsv reader
:param name: Name of the variable
:returns: True if the variable is in the vlsv file, false if not
.. note:: This should be used for checking if a variable exists in case a function behaves differently for ex. if B vector is in the vlsv and if not
.. code-block:: python
# Example usage:
vlsvReader = pt.vlsvfile.VlsvReader("test.vlsv")
if vlsvReader.check_variable( "B" ):
# Variable can be plotted
plot_B()
else:
# Variable not in the vlsv file
plot_B_vol()
'''
for child in self.__xml_root:
if child.tag == "VARIABLE" and "name" in child.attrib:
if child.attrib["name"].lower() == name.lower():
return True
return False
def check_population( self, popname ):
''' Checks if a given population is in the vlsv file
:param name: Name of the population
:returns: True if the population is in the vlsv file, false if not
.. code-block:: python
# Example usage:
vlsvReader = pt.vlsvfile.VlsvReader("test.vlsv")
if vlsvReader.check_population( "avgs" ):
plot_population('avgs')
else:
if vlsvReader.check_population( "proton" ):
# File is newer with proton population
plot_population('proton')
'''
blockidsexist = False
foundpop = False
for child in self.__xml_root:
if child.tag == "BLOCKIDS":
if "name" in child.attrib:
if popname.lower() == child.attrib["name"].lower():
foundpop = True
else:
blockidsexist = True
if blockidsexist:
for child in self.__xml_root:
if child.tag == "BLOCKVARIABLE":
if "name" in child.attrib:
if popname.lower() == child.attrib["name"].lower(): # avgs
foundpop = True
return foundpop
def get_all_variables( self ):
''' Returns all variables in the vlsv reader and the data reducer
:returns: List of variable is in the vlsv file
.. code-block:: python
# Example usage:
vlsvReader = pt.vlsvfile.VlsvReader("test.vlsv")
vars = vlsvReader.get_variables()
'''
varlist = [];
for child in self.__xml_root:
if child.tag == "VARIABLE" and "name" in child.attrib:
varlist.append(child.attrib["name"])
return varlist
def get_cellid_locations(self):
''' Returns a dictionary with cell id as the key and the index of the cell id as the value. The index is used to locate the cell id's values in the arrays that this reader returns
'''
# if len( self.__fileindex_for_cellid ) == 0:
self.__read_fileindex_for_cellid()
return self.__fileindex_for_cellid
def print_version(self):
'''
Prints version information from VLSV file.
TAG is hardcoded to VERSION
:returns True if version is found otherwise returns False
'''
import sys
tag="VERSION"
# Seek for requested data in VLSV file
for child in self.__xml_root:
if child.tag != tag:
continue
if child.tag == tag:
# Found the requested data entry in the file
array_size = ast.literal_eval(child.attrib["arraysize"])
variable_offset = ast.literal_eval(child.text)
if self.__fptr.closed:
fptr = open(self.file_name,"rb")
else:
fptr = self.__fptr
fptr.seek(variable_offset)
info = fptr.read(array_size).decode("utf-8")
print("Version Info for ",self.file_name)
print(info)
return True
#if we end up here the file does not contain any version info
print("File ",self.file_name," contains no version information")
return False
def get_config_string(self):
'''
Gets config information from VLSV file.
TAG is hardcoded to CONFIG
:returns configuration file string if config is found otherwise returns None
'''
tag="CONFIG"
# Seek for requested data in VLSV file
for child in self.__xml_root:
if child.tag != tag:
continue
if child.tag == tag:
# Found the requested data entry in the file
array_size = ast.literal_eval(child.attrib["arraysize"])
variable_offset = ast.literal_eval(child.text)
if self.__fptr.closed:
fptr = open(self.file_name,"rb")
else:
fptr = self.__fptr
fptr.seek(variable_offset)
configuration = fptr.read(array_size).decode("utf-8")
return configuration
#if we end up here the file does not contain any config info
return None
def get_config(self):
'''
Gets config information from VLSV file
:returns a nested dictionary of dictionaries,
where keys (str) are config file group headings (appearing in '[]')
and values are dictionaries which contain (lists of) strings
If the same heading/parameter pair appears >once in the config file,
the different values are appended to the list .
EXAMPLE:
if the config contains these lines:
[proton_precipitation]
nChannels = 9
then the following returns ['9']:
vlsvReader.get_config()['proton_precipitation']['nChannels']
'''
confstring = self.get_config_string()
if confstring is None:
return None
fa = re.findall(r'\[\w+\]|\w+ = \S+', confstring)
heading = ''
output = {heading:{}}
for i, sfa in enumerate(fa):
if (sfa[0] == '[') and (sfa[-1] == ']'):
heading = sfa[1:-1]
output[heading] = {}
else:
var_name = sfa.split('=')[0].strip()
var_value = sfa.split('=')[1].strip()
if var_name in output[heading]:
# when the same parameter is assigned a value multiple times
output[heading][var_name].append(var_value)
else:
output[heading][var_name] = [var_value]
return output
def print_config(self):
'''
Prints config information from VLSV file.
:returns True if config is found otherwise returns False
'''
config_string = self.get_config_string()
if config_string is not None:
print(config_string)
return True
else:
#if we end up here the file does not contain any config info
print("File ",self.file_name," contains no config information")
return False
def read_variable_vectorsize(self, name):
if name.startswith('fg_'):
mesh = "fsgrid"
elif name.startswith('ig_'):
mesh = "ionosphere"
else:
mesh = "SpatialGrid"
return self.read_attribute(name=name, mesh=mesh,attribute="vectorsize", tag="VARIABLE")
def read_attribute(self, name="", mesh="", attribute="", tag=""):
''' Read data from the open vlsv file.
:param name: Name of the data array
:param tag: Tag of the data array.
:param mesh: Mesh for the data array
:param operator: Datareduction operator. "pass" does no operation on data.
:param cellids: If -1 then all data is read. If nonzero then only the vector
for the specified cell id or cellids is read
:returns: numpy array with the data
.. seealso:: :func:`read_variable` :func:`read_variable_info`
'''
if tag == "" and name == "":
print("Bad (empty) arguments at VlsvReader.read")
raise ValueError()
# Force lowercase name for internal checks
name = name.lower()
# Seek for requested data in VLSV file
for child in self.__xml_root:
if tag != "":
if child.tag != tag:
continue
if name != "":
if "name" in child.attrib and child.attrib["name"].lower() != name:
continue
if mesh != "":
if "mesh" in child.attrib and child.attrib["mesh"] != mesh:
continue
if child.tag == tag:
# Found the requested data entry in the file
return ast.literal_eval(child.attrib[attribute])
raise ValueError("Variable or attribute not found")
def read(self, name="", tag="", mesh="", operator="pass", cellids=-1):
''' Read data from the open vlsv file.
:param name: Name of the data array
:param tag: Tag of the data array.
:param mesh: Mesh for the data array
:param operator: Datareduction operator. "pass" does no operation on data.
:param cellids: If -1 then all data is read. If nonzero then only the vector
for the specified cell id or cellids is read
:returns: numpy array with the data
.. seealso:: :func:`read_variable` :func:`read_variable_info`
'''
if tag == "" and name == "":
print("Bad (empty) arguments at VlsvReader.read")
raise ValueError()
if mesh == None:
mesh = ''
# Force lowercase name for internal checks
name = name.lower()
if (len( self.__fileindex_for_cellid ) == 0):
# Do we need to construct the cellid index?
if isinstance(cellids, numbers.Number): # single or all cells
if cellids >= 0: # single cell
self.__read_fileindex_for_cellid()
else: # list of cellids
self.__read_fileindex_for_cellid()
if self.__fptr.closed:
fptr = open(self.file_name,"rb")
else:
fptr = self.__fptr
# Get population and variable names from data array name
if '/' in name:
popname = name.split('/')[0]
if popname in self.active_populations:
varname = name.split('/',1)[1]
else:
popname = 'pop'
varname = name
else:
popname = 'pop'
varname = name
# Seek for requested data in VLSV file
for child in self.__xml_root:
if tag != "":
if child.tag != tag:
continue
# Verify that any requested name or mesh matches those of the data
if name != "":
if not "name" in child.attrib:
continue
if child.attrib["name"].lower() != name:
continue
if mesh != "":
if not "mesh" in child.attrib:
continue
if child.attrib["mesh"] != mesh:
continue
if child.tag == tag:
# Found the requested data entry in the file
vector_size = ast.literal_eval(child.attrib["vectorsize"])
array_size = ast.literal_eval(child.attrib["arraysize"])
element_size = ast.literal_eval(child.attrib["datasize"])
datatype = child.attrib["datatype"]
variable_offset = ast.literal_eval(child.text)
# Define efficient method to read data in
try: # try-except to see how many cellids were given
lencellids=len(cellids)
# Read multiple specified cells
# If we're reading a large amount of single cells, it'll be faster to just read all
# data from the file system and sort through it. For the CSC disk system, this
# becomes more efficient for over ca. 5000 cellids.
arraydata = []
if lencellids>5000:
result_size = len(cellids)
read_size = array_size
read_offsets = [0]
else: # Read multiple cell ids one-by-one
result_size = len(cellids)
read_size = 1
read_offsets = [self.__fileindex_for_cellid[cid]*element_size*vector_size for cid in cellids]
except: # single cell or all cells
if cellids < 0: # -1, read all cells
result_size = array_size
read_size = array_size
read_offsets = [0]
else: # single cell id
result_size = 1
read_size = 1
read_offsets = [self.__fileindex_for_cellid[cellids]*element_size*vector_size]
for r_offset in read_offsets:
use_offset = int(variable_offset + r_offset)
fptr.seek(use_offset)
if datatype == "float" and element_size == 4:
data = np.fromfile(fptr, dtype = np.float32, count=vector_size*read_size)
if datatype == "float" and element_size == 8:
data = np.fromfile(fptr, dtype=np.float64, count=vector_size*read_size)
if datatype == "int" and element_size == 4:
data = np.fromfile(fptr, dtype=np.int32, count=vector_size*read_size)
if datatype == "int" and element_size == 8:
data = np.fromfile(fptr, dtype=np.int64, count=vector_size*read_size)
if datatype == "uint" and element_size == 4:
data = np.fromfile(fptr, dtype=np.uint32, count=vector_size*read_size)
if datatype == "uint" and element_size == 8:
data = np.fromfile(fptr, dtype=np.uint64, count=vector_size*read_size)
if len(read_offsets)!=1:
arraydata.append(data)
if len(read_offsets)==1 and result_size<read_size:
# Many single cell id's requested
# Pick the elements corresponding to the requested cells
for cid in cellids:
append_offset = self.__fileindex_for_cellid[cid]*vector_size
arraydata.append(data[append_offset:append_offset+vector_size])
data = np.squeeze(np.array(arraydata))
if len(read_offsets)!=1:
# Not-so-many single cell id's requested
data = np.squeeze(np.array(arraydata))
if self.__fptr.closed:
fptr.close()
if vector_size > 1:
data=data.reshape(result_size, vector_size)
# If variable vector size is 1, and requested magnitude, change it to "absolute"
if vector_size == 1 and operator=="magnitude":
print("Data variable with vector size 1: Changed magnitude operation to absolute")
operator="absolute"
if result_size == 1:
return data_operators[operator](data[0])
else:
return data_operators[operator](data)
# Check which set of datareducers to use
if varname[0:3]=="vg_" or varname[0:3]=="ig_":
reducer_reg = v5reducers
reducer_multipop = multipopv5reducers
else:
reducer_reg = datareducers
reducer_multipop = multipopdatareducers
# If this is a variable that can be summed over the populations (Ex. rho, PTensorDiagonal, ...)
if hasattr(self, 'active_populations') and len(self.active_populations) > 0 and self.check_variable(self.active_populations[0]+'/'+name):
tmp_vars = []
for pname in self.active_populations:
vlsvvariables.activepopulation = pname
tmp_vars.append( self.read( pname+'/'+name, tag, mesh, "pass", cellids ) )
return data_operators[operator](data_operators["sum"](tmp_vars))
# Check if the name is in datareducers
if name in reducer_reg:
reducer = reducer_reg[name]
# Read the necessary variables:
# If variable vector size is 1, and requested magnitude, change it to "absolute"
if reducer.vector_size == 1 and operator=="magnitude":
print("Data reducer with vector size 1: Changed magnitude operation to absolute")
operator="absolute"
# Return the output of the datareducer
if reducer.useVspace and not reducer.useReader: