Source

IRATE-format / irate / gadgettype2binary.py

Full commit
  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
#!/bin/python
from __future__ import division
import h5py
from numpy import *
import struct,os,sys

def gb2_to_irate(inname,outname,potential,accel,entropy,timestep,gasgroup,gasname,
    t1_group,t1_name,t2_group,t2_name,t3_group,t3_name,stargroup,starname,t5_group,t5_name,ics):
    """Reads a GADGET type 2 format file block by block (e.g. coordinate block
    for gas particles), writes the block to an IRATE formate HDF5 file, and
    then deletes that block from memory. inname is the name of the gadget 
    binary file to be read, outname the name of the IRATE file to be written, 
    potential, accel, entropy, and timestep are true if that property is 
    included in the gadget file, and the group and names determine where the
    various data goes.  Note that if the first 5 blocks aren't HEAD, POS, VEL,
    ID, and MASS, the script will fail and exit."""
    print "\nOpening type 2 Gadget binary"+inname    
    f = open(inname,'rb')
    #First let's find out the total length of the file
    f.seek(0,2)
    flen = f.tell()
    f.seek(0,0)
    print "Creating output file "+outname
    irate = h5py.File(outname,'w')
    #Create the file structure
    irate.create_group('Analysis')    
    gas = irate.create_group('Gas')
    dark = irate.create_group('Dark')
    star = irate.create_group('Star')
    #Nothing else should be done to irate from here on, except of course closing it.

    #First read the header so I know how many particles of each type I have
    #Since this is a type 2 binary, first I have to read the size of a block that tells me that the header block is next, etc.
    bsize = struct.unpack('<I',f.read(4))[0]   #This should be an 8
    if f.read(4) != 'HEAD':      #Most of the time I'm going to be using the labels to tell me what something is, but here I know that I have to read the header
        print "You're reading the wrong file type or HEAD isn't the first block.  Exiting..."
        sys.exit(1337)
    hblocksize = struct.unpack('<I',f.read(4))[0]      #So this is the size of the header block, including the numbers before and after that tell you how big it is
    assert struct.unpack('<I',f.read(4))[0] == bsize   #So this is the close of the block that includes nothing but the information about what block is next
    
    #Now I can actually read the header:
    header_size = struct.unpack('<I',f.read(4))[0]

    #number of particles of each type in this file
    nfile = struct.unpack('<6I',f.read(24)) #Number of particles in this file

    masstable = struct.unpack('<6d',f.read(48))  #masses of the particle groups
        
    a = struct.unpack('<d',f.read(8))[0]        #expansion factor
    z = struct.unpack('<d',f.read(8))[0]        #redshift

    flag_sfr = struct.unpack('<i',f.read(4))[0] #star formation included?
    flag_feed = struct.unpack('<i',f.read(4))[0] #feedback included?

    ntot = struct.unpack('<6i',f.read(24))      #total number of particles in the simulation (= nfile if numfiles == 1)
        
    flag_cool = struct.unpack('<i',f.read(4))[0]  #cooling included?
    numfiles = struct.unpack('<i',f.read(4))[0]   #number of files in each snapshot
    boxsize = struct.unpack('<d',f.read(8))[0] #Size of the box, if periodic
    omega0 = struct.unpack('<d',f.read(8))[0]  #matter density at z = 0
    omegaL = struct.unpack('<d',f.read(8))[0]  #vacuum energy density at z = 0
    h = struct.unpack('<d',f.read(8))[0] #hubble parameter in units of 100 km/s/Mpc
    flag_age = struct.unpack('<i',f.read(4))[0]  #stellar age included?
    flag_metals = struct.unpack('<i',f.read(4))[0]  #use metals?
    nhighword = struct.unpack('<6i',f.read(24))   #contains the most significant word of 64-bit particle numbers (if npart > 2^32)

    flag_entropy = struct.unpack('<i',f.read(4))[0] #entropy instead of thermal energy in initial conditions?

    f.seek(280,0)   #Moves to the end of the header (and block that tells you size of header)

    #Create the header group
    fileheader = irate.create_group('Header')
    #Write the gadget header as attributes to the group:
    gheader = fileheader.create_group('GadgetHeader')
    gheader.attrs["NumPart_ThisFile"] = nfile
    gheader.attrs["MassTable"] = masstable
    gheader.attrs["Time"] = a
    gheader.attrs["Redshift"] = z
    gheader.attrs["Flag_Sfr"] = flag_sfr
    gheader.attrs["Flag_Feedback"] = flag_feed
    gheader.attrs["NumPart_Total"] = ntot
    gheader.attrs["Flag_Cooling"] = flag_cool
    gheader.attrs["NumFilesPerSnapshot"] = numfiles
    gheader.attrs["BoxSize"] = boxsize
    gheader.attrs["Omega0"] = omega0
    gheader.attrs["OmegaLambda"] = omegaL
    gheader.attrs["HubbleParam"] = h
    gheader.attrs["Flag_StellarAge"] = flag_age
    gheader.attrs["Flag_Metals"] = flag_metals
    gheader.attrs["NumPart_Total_HW"] = nhighword
    gheader.attrs["Flag_Entropy_ICs"] = flag_entropy

    ngas = nfile[0]
    nhalo = nfile[1]
    ndisk = nfile[2]
    nbulge = nfile[3]
    nstar = nfile[4]
    nbndry = nfile[5]

    #Now create the rest of the file structure in the IRATE file
    if ngas > 0:     #i.e. if there are gas particles in the simulation
        #Create a subgroup for the particles that were in the gadget gas block
        if gasgroup == 'gas':
            print "Saving gas data in /Gas/"+gasname
            gas_tree = gas.create_group(gasname)
        elif gasgroup == 'dark':
            print "Saving gas data in /Dark/"+gasname
            gas_tree = dark.create_group(gasname)
        elif gasgroup == 'star':
            print "Saving gas data in /Star/"+gasname
            gas_tree = star.create_group(gasname)
        else:
            print "I shouldn't be here!  Somehow you got away with trying to place the particle data for the gas group into a nonexistant tree."
            sys.exit(1337)

    if nhalo > 0:  #i.e. if there are particles in the first group (otherwise it's a zero length array)
        if t1_group == 'gas':
            print "Saving halo data in /Gas/"+t1_name
            halo_tree = gas.create_group(t1_name)
        elif t1_group == 'dark':
            print "Saving halo data in /Dark/"+t1_name
            halo_tree = dark.create_group(t1_name)
        elif t1_group == 'star':
            print "Saving halo data in /Star/"+t1_name
            halo_tree = star.create_group(t1_name)
        else:
            print "I shouldn't be here!  Somehow you got away with trying to place the particle data for group 1 into a nonexistant tree."
            sys.exit(1337)

    if ndisk > 0:
        if t2_group == 'gas':
            print "Saving disk data in /Gas/"+t2_name
            disk_tree = gas.create_group(t2_name)
        elif t2_group == 'dark':
            print "Saving disk data in /Dark/"+t2_name
            disk_tree = dark.create_group(t2_name)
        elif t2_group == 'star':
            print "Saving disk data in /Star/"+t2_name
            disk_tree = star.create_group(t2_name)
        else:
            print "I shouldn't be here!  Somehow you got away with trying to place the particle data for group 2 into a nonexistant tree."
            sys.exit(1337)

    if nbulge > 0:
        if t3_group == 'gas':
            print "Saving bulge data in /Gas/"+t3_name
            bulge_tree = gas.create_group(t3_name)
        elif t3_group == 'dark':
            print "Saving bulge data in /Dark/"+t3_name
            bulge_tree = dark.create_group(t3_name)
        elif t3_group == 'star':
            print "Saving bulge data in /Star/"+t3_name
            bulge_tree = star.create_group(t3_name)
        else:
            print "I shouldn't be here!  Somehow you got away with trying to place the particle data for group 3 into a nonexistant tree."
            sys.exit(1337)

    if nstar > 0:
        if stargroup == 'gas':
            print "Saving star data in /Gas/"+starname
            star_tree = gas.create_group(starname)
        elif stargroup == 'dark':
            print "Saving star data in /Dark/"+starname
            star_tree = dark.create_group(starname)
        elif stargroup == 'star':
            print "Saving star data in /Star/"+starname
            star_tree = star.create_group(starname)
        else:
            print "I shouldn't be here!  Somehow you got away with trying to place the particle data for group 4 into a nonexistant tree."
            sys.exit(1337)

    if nbndry > 0:
        if t5_group == 'gas':
            print "Saving boundary data in /Gas/"+t5_name
            bndry_tree = gas.create_group(t5_name)
        elif t5_group == 'dark':
            print "Saving boundary data in /Dark/"+t5_name
            bndry_tree = dark.create_group(t5_name)
        elif t5_group == 'star':
            print "Saving boundary data in /Star/"+t5_name
            bndry_tree = star.create_group(t5_name)
        else:
            print "I shouldn't be here!  Somehow you got away with trying to place the particle data for group 5 into a nonexistant tree."
            sys.exit(1337)
    
    #Now next up is positions (I'm going to strictly enforce that)
    bsize = struct.unpack('<I',f.read(4))
    label = f.read(4)
    if label != 'POS ':
        print "You're reading the wrong file type or POS isn't the second block in the file.  Exiting..."
        sys.exit(1337) 
    postot = struct.unpack('<I',f.read(4))[0]
    assert struct.unpack('<I',f.read(4)) == bsize

    #Ok, now to read in the actual positions and immediately save them in the file
    #Read in the coordinates, starting with the size of the block    
    print "Reading coordinates"
    coord_size = struct.unpack('<I',f.read(4))[0]

    if ngas > 0:    #Only try to do something for a group of particles if they exist
        #Read in the binary data and convert to the appropriate type and save in the appropriate place
        gas_tree.create_dataset("Position",data=fromstring(f.read(12*ngas),dtype='f').reshape((-1,3)))
    if nhalo > 0:
        halo_tree.create_dataset("Position",data=fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
    if ndisk > 0:
        disk_tree.create_dataset("Position",data=fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))
    print "Read coordinates for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
    if nbulge > 0:
        bulge_tree.create_dataset("Position",data=fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
    if nstar > 0:
        star_tree.create_dataset("Position",data=fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
    if nbndry > 0:
        bndry_tree.create_dataset("Position",data=fromstring(f.read(12*nbndry),dtype='f').reshape((-1,3)))
        
    #And read the size of the coordinate block again.
    if struct.unpack('<I',f.read(4))[0] != coord_size:
        raise StandardError("The block size at the end of the coordinate block doesn't match that at the beginning.  This is an issue.")
    

    #And next up is velocities, again strictly enforced:
    bsize = struct.unpack('<I',f.read(4))
    if f.read(4) != 'VEL ':
        print "You're reading the wrong file type or VEL isn't the third block in the file.  Exiting..."
        sys.exit(1337)
    veltot = struct.unpack('<I',f.read(4))[0]
    assert struct.unpack('<I',f.read(4)) == bsize
    
    vel_size = struct.unpack('<I',f.read(4))[0]
    print "Reading velocities"
    
    if ngas > 0:    #Only try to do something for a group of particles if they exist
        gas_tree.create_dataset("Velocity",data=fromstring(f.read(12*ngas),dtype='f').reshape((-1,3)))
    if nhalo > 0:
        halo_tree.create_dataset("Velocity",data=fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
    if ndisk > 0:
        disk_tree.create_dataset("Velocity",data=fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))
    print "Read velocities for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
    if nbulge > 0:
        bulge_tree.create_dataset("Velocity",data=fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
    if nstar > 0:
        star_tree.create_dataset("Velocity",data=fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
    if nbndry > 0:
        bndry_tree.create_dataset("Velocity",data=fromstring(f.read(12*nbndry),dtype='f').reshape((-1,3)))

    if struct.unpack('<I',f.read(4))[0] != vel_size:   #And read the size of the block again.
        raise StandardError("The block size at the end of the velocity block doesn't match that at the beginning.  This is an issue.")
    
    
    #And then the IDs, again strictly enforced:
    bsize = struct.unpack('<I',f.read(4))
    if f.read(4) != 'ID  ':
        print "You're reading the wrong file type or ID isn't the fourth block in the file.  Exiting..."
        sys.exit(1337)
    idtot = struct.unpack('<I',f.read(4))[0]
    assert struct.unpack('<I',f.read(4)) == bsize
    
    id_size = struct.unpack('<I',f.read(4))[0]
    print "Reading particle IDs"

    if ngas > 0:
        gas_tree.create_dataset("ParticleIDs",data=fromstring(f.read(4*ngas),dtype='I'))
    if nhalo > 0:
        halo_tree.create_dataset("ParticleIDs",data=fromstring(f.read(4*nhalo),dtype='I'))
    if ndisk > 0:
        disk_tree.create_dataset("ParticleIDs",data=fromstring(f.read(4*ndisk),dtype='I'))
    print "Read IDs for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
    if nbulge > 0:
        bulge_tree.create_dataset("ParticleIDs",data=fromstring(f.read(4*nbulge),dtype='I'))
    if nstar > 0:
        star_tree.create_dataset("ParticleIDs",data=fromstring(f.read(4*nstar),dtype='I'))
    if nbndry > 0:
        bndry_tree.create_dataset("ParticleIDs",data=fromstring(f.read(4*nbndry),dtype='I'))

    if struct.unpack('<I',f.read(4))[0] != id_size:   #And read the size of the block again.
        raise StandardError("The block size at the end of the IDs block doesn't match that at the beginning.  This is an issue.")
        
        
    #Now, this could potentially be the end of the file, so I need to check that now (and every time that I start another block
    if f.tell() == flen:
        print "There are no blocks beyond the IDs. Created IRATE format file "+outname
        f.close()
        irate.close()
        sys.exit(0)   #Exit with success
    
    #Next up is the optional mass block (probably).  
    #In type 1, I had to check if there were any particles that had a zero in the mass table, but now I can just check if the string is MASS
    bsize = struct.unpack('<I',f.read(4))
    label = f.read(4)
    btot = struct.unpack('<I',f.read(4))[0]
    assert struct.unpack('<I',f.read(4)) == bsize
    
    if label == 'MASS':
        mass_size = struct.unpack('<I',f.read(4))[0]
    
        if ngas > 0 and masstable[0] == 0:    #There are particles in the group, but their masses aren't in the header (so they must be in the file)
            print "Reading variable masses for gas group"
            gas_tree.create_dataset("Mass",data=fromstring(f.read(4*ngas),dtype='f'))
        elif ngas > 0 and masstable[0] > 0:    #There are particles in the group, and their masses are in the header (so I have to fill in a variable block)
            marray = empty(ngas)
            marray.fill(masstable[0])
            gas_tree.create_dataset("Mass",data=marray)
        
        if nhalo > 0 and masstable[1] == 0:
            print "Reading variable masses for halo group"
            halo_tree.create_dataset("Mass",data=fromstring(f.read(4*nhalo),dtype='f'))
        elif nhalo > 0 and masstable[1] > 0:
            marray = empty(nhalo)
            marray.fill(masstable[1])
            halo_tree.create_dataset("Mass",data=marray)
            
        if ndisk > 0 and masstable[2] == 0:
            print "Reading variable masses for disk group"
            disk_tree.create_dataset("Mass",data=fromstring(f.read(4*ndisk),dtype='f'))
        elif ndisk > 0 and masstable[2] > 0:
            marray = empty(ndisk)
            marray.fill(masstable[2])
            disk_tree.create_dataset("Mass",data=marray)
            
        if nbulge > 0 and masstable[3] == 0:
            print "Reading variable masses for bulge group"
            bulge_tree.create_dataset("Mass",data=fromstring(f.read(4*nbulge),dtype='f'))
        elif nbulge > 0 and masstable[3] > 0:
            marray = empty(nbulge)
            marray.fill(masstable[3])
            bulge_tree.create_dataset("Mass",data=marray)
            
        if nstar > 0 and masstable[4] == 0:
            print "Reading variable masses for star group"
            star_tree.create_dataset("Mass",data=fromstring(f.read(4*nstar),dtype='f'))
        elif nstar > 0 and masstable[4] > 0:
            marray = empty(nstar)
            marray.fill(masstable[4])
            star_tree.create_dataset("Mass",data=marray)
            
        if nbndry > 0 and masstable[5] == 0:
            print "Reading variable masses for boundary group"
            bndry_tree.create_dataset("Mass",data=fromstring(f.read(4*nbndry),dtype='f'))
        elif nbndry > 0 and masstable[5] > 0:
            marray = empty(nbndry)
            marray.fill(masstable[5])
            bndry_tree.create_dataset("Mass",data=marray)
        
        try:    
            del marray      #If there are no masses in the mass table, marray will have never been defined
        except NameError:
            pass
            
        if struct.unpack('<I',f.read(4))[0] != mass_size:   #And read the size of the block again.
            raise StandardError("The block size at the end of the mass block doesn't match that at the beginning.  This is an issue.")
    
    else:       #Then all the particles in the file have their mass defined in the header, so I need to fill arrays
        if ngas > 0:
            marray = empty(ngas)
            marray.fill(masstable[0])
            gas_tree.create_dataset("Mass",data=marray)
        if nhalo > 0:
            marray = empty(nhalo)
            marray.fill(masstable[1])
            halo_tree.create_dataset("Mass",data=marray)
        if ndisk > 0:
            marray = empty(ndisk)
            marray.fill(masstable[2])
            disk_tree.create_dataset("Mass",data=marray)
        if nbulge > 0:
            marray = empty(nbulge)
            marray.fill(masstable[3])
            bulge_tree.create_dataset("Mass",data=marray)
        if nstar > 0:
            marray = empty(nstar)
            marray.fill(masstable[4])
            star_tree.create_dataset("Mass",data=marray)
        if nbndry > 0:
            marray = empty(nbndry)
            marray.fill(masstable[5])
            bndry_tree.create_dataset("Mass",data=marray)
            
        del marray      #marray had to have been defined if there are any particles in the file
    
        #And now I need to figure out what the block that I'm on actually is
        if label == 'U   ':     #Then it's internal energy, and I should do that
            u_size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset("InternalEnergy",data=fromstring(f.read(4*ngas),dtype='f'))
            if struct.unpack('<I',f.read(4))[0] != u_size:
                raise StandardError("The block size at the end of the internal energy block doesn't match that at the beginning.  This is an issue.")
            print "Read gas internal energy."
        
        #Now, if it's not U, then it can't be either rho or hsml (because those have to come after U), but it could be one of the Makefile enabled blocks or an extra block
        
        #But, since if statements take no time, I may as well check explicitely that it's not rho or hsml
        
        elif label == "RHO ":
            print "Reading density."
            rho_size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset("Density",data=fromstring(f.read(4*ngas),dtype='f'))  
            if struct.unpack('<I',f.read(4))[0] != rho_size:
                raise StandardError("The block size at the end of the density block doesn't match that at the beginning.  This is an issue.")
                
        elif label == "HSML":
            print "Reading smoothings lengths."
            hsml_size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset("SmoothingLength",data=fromstring(f.read(4*ngas),dtype='f'))       
            if struct.unpack('<I',f.read(4))[0] != hsml_size:
                raise StandardError("The block size at the end of the HSML block doesn't match that at the beginning.  This is an issue.")
        
        #Now check if it's a standard Makefile enabled block:
        elif label == "POT ":
            print "Reading gravitational potentials."
            phi_size = struct.unpack('<I',f.read(4))[0]
            
            if ngas > 0:
                gas_tree.create_dataset("Potential",data=fromstring(f.read(4*ngas),dtype='f'))     
            if nhalo > 0:
                halo_tree.create_dataset("Potential",data=fromstring(f.read(4*nhalo),dtype='f'))
            if ndisk > 0:
                disk_tree.create_dataset("Potential",data=fromstring(f.read(4*ndisk),dtype='f'))
            print "Read gravitational potentials for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
            if nbulge > 0:
                bulge_tree.create_dataset("Potential",data=fromstring(f.read(4*nbulge),dtype='f'))
            if nstar > 0:
                star_tree.create_dataset("Potential",data=fromstring(f.read(4*nstar),dtype='f'))
            if nbndry > 0:
                bndry_tree.create_dataset("Potential",data=fromstring(f.read(4*nbndry),dtype='f'))
            
            if struct.unpack('<I',f.read(4))[0] != phi_size:
                print "The block size at the end of the gravitational potential block doesn't match that at the beginning.  This is an issue."
                sys.exit(1337)
        elif label == "ACCE":
            print "Reading accelerations."
            accel_size = struct.unpack('<I',f.read(4))[0]
            
            if ngas > 0:
                gas_tree.create_dataset("Acceleration",data=fromstring(f.read(12*ngas),dtype='f').reshape((-1,3)))
            if nhalo > 0:
                halo_tree.create_dataset("Acceleration",data=fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
            if ndisk > 0:
                disk_tree.create_dataset("Acceleration",data=fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))
            print "Read accelerations for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
            if nbulge > 0:
                bulge_tree.create_dataset("Acceleration",data=fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
            if nstar > 0:
                star_tree.create_dataset("Acceleration",data=fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
            if nbndry > 0:
                bndry_tree.create_dataset("Acceleration",data=fromstring(f.read(12*nbndry),dtype='f').reshape((-1,3)))
            
            if struct.unpack('<I',f.read(4))[0] != accel_size:
                raise StandardError("The block size at the end of the acceleration block doesn't match that at the beginning.  This is an issue.")
            
        elif label == "ENDT":
            print "Reading rate of change of entropy for gas data"
            dsdt_size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset("RateofChangeofEntropy",data=fromstring(f.read(4*ngas),dtype='f'))
            if struct.unpack('<I',f.read(4))[0] != dsdt_size:
                raise StandardError("The block size at the end of the entropy block doesn't match that at the beginning.  This is an issue.")
        
        elif label == "TSTP":
            print "Reading timesteps"
            timestep_size = struct.unpack('<I',f.read(4))[0]
        
            if ngas > 0:
                gas_tree.create_dataset("TimeStep",data=fromstring(f.read(4*ngas),dtype='f'))
            if nhalo > 0:
                halo_tree.create_dataset("TimeStep",data=fromstring(f.read(4*nhalo),dtype='f'))
            if ndisk > 0:
                disk_tree.create_dataset("TimeStep",data=fromstring(f.read(4*ndisk),dtype='f'))     
            print "Read timesteps for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))    
            if nbulge > 0:
                bulge_tree.create_dataset("TimeStep",data=fromstring(f.read(4*nbulge),dtype='f')) 
            if nstar > 0:
                star_tree.create_dataset("TimeStep",data=fromstring(f.read(4*nstar),dtype='f'))
            if nbndry > 0:
                bndry_tree.create_dataset("TimeStep",data=fromstring(f.read(4*nbndry),dtype='f'))
                                
            if struct.unpack('<I',f.read(4))[0] != timestep_size:
                raise StandardError("The block size at the end of the timestep block doesn't match that at the beginning.  This is an issue.")
        
        #Ok, so if I'm here, it's a nonstandard block.  How to handle those....hmm
        #Well, I'm definitely not going to bother renaming things; rather, I'll just use the strings as names
        #The primary difficulty lies in determining what type of particle the various blocks belong to...
        #Certain blocks I know belong to gas and/or stars, others it's not obvious
        #If a block is unrecognized, I'm going to give the option to skip or exit.
        elif label == "NE  ":   #A gas only thing
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
        
        #If it's not NE, it can't be NH (because they're both on for cooling), so I can skip that...but there's really no reason to, so let's put it in
        
        elif label == "NH  ":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
                        
        elif label == "SFR ":   #A gas only block
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
                
        elif label == "AGE ":   #Stars only block
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            star_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*nstar),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
                        
        elif label == "Z   ":   #Gas and stars
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            if ngas > 0:  gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*ngas),dtype='f'))
            if nstar > 0:  star_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*nstar),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")    
        
        elif label == "BFLD":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
        
        #If it's not the B field, then it can't be dB/dt either, but again, let's put it in for safety's sake
        elif label == "DBDT":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
        
        elif label == "DIVB":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")  
                
        elif label == "ABVC":  
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
                
        elif label == "COOR":    
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
        
        #If it's not cooling rate, then it can't be conduction rate either, but again, let's check explicitely
        elif label == "CONR":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
        
        elif label == "BFSM":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
        
        elif label == "DENN":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
        
        else:
            cont = raw_input("Block labeled '"+label+"' isn't recognized by this script.  Press enter to skip it or enter anything to exit.")
            if len(cont) > 0:
                f.close()
                irate.close()
                sys.exit(1)
            else:
                f.seek(btot,1)
                
    #Ok, so now I need to do the above for every single block in the file (except for those before MASS)
    
    while f.tell() < flen:
        #If I have this loop right, it'll check whether it's at the end of the file
        #If it's not, it'll read in an 8 byte block that includes a label and the size of the next block
        #Then, it'll go through and compare the labels to everything that's known, find where it goes, then read that block and save it to the appropriate tree
        bsize = struct.unpack('<I',f.read(4))
        label = f.read(4)
        btot = struct.unpack('<I',f.read(4))[0]
        assert struct.unpack('<I',f.read(4)) == bsize
        
        if label == 'U   ':     #Then it's internal energy, and I should do that
            u_size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset("InternalEnergy",data=fromstring(f.read(4*ngas),dtype='f'))
            if struct.unpack('<I',f.read(4))[0] != u_size:
                raise StandardError("The block size at the end of the internal energy block doesn't match that at the beginning.  This is an issue.")
            print "Read gas internal energy."
            continue
        
        #Now, if it's not U, then it can't be either rho or hsml (because those have to come after U), but it could be one of the Makefile enabled blocks or an extra block
        
        #But, since if statements take no time, I may as well check explicitely that it's not rho or hsml
        
        elif label == "RHO ":
            print "Reading density."
            rho_size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset("Density",data=fromstring(f.read(4*ngas),dtype='f'))  
            if struct.unpack('<I',f.read(4))[0] != rho_size:
                raise StandardError("The block size at the end of the density block doesn't match that at the beginning.  This is an issue.")
            continue        #These continues are probably unnecessary, but better safe (and faster) then sorry
            
        elif label == "HSML":
            print "Reading smoothings lengths."
            hsml_size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset("SmoothingLength",data=fromstring(f.read(4*ngas),dtype='f'))       
            if struct.unpack('<I',f.read(4))[0] != hsml_size:
                raise StandardError("The block size at the end of the HSML block doesn't match that at the beginning.  This is an issue.")
            continue
            
        #Now check if it's a standard Makefile enabled block:
        elif label == "POT ":
            print "Reading gravitational potentials."
            phi_size = struct.unpack('<I',f.read(4))[0]
            
            if ngas > 0:
                gas_tree.create_dataset("Potential",data=fromstring(f.read(4*ngas),dtype='f'))     
            if nhalo > 0:
                halo_tree.create_dataset("Potential",data=fromstring(f.read(4*nhalo),dtype='f'))
            if ndisk > 0:
                disk_tree.create_dataset("Potential",data=fromstring(f.read(4*ndisk),dtype='f'))
            print "Read gravitational potentials for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
            if nbulge > 0:
                bulge_tree.create_dataset("Potential",data=fromstring(f.read(4*nbulge),dtype='f'))
            if nstar > 0:
                star_tree.create_dataset("Potential",data=fromstring(f.read(4*nstar),dtype='f'))
            if nbndry > 0:
                bndry_tree.create_dataset("Potential",data=fromstring(f.read(4*nbndry),dtype='f'))
            
            if struct.unpack('<I',f.read(4))[0] != phi_size:
                print "The block size at the end of the gravitational potential block doesn't match that at the beginning.  This is an issue."
                sys.exit(1337)
            continue
            
        elif label == "ACCE":
            print "Reading accelerations."
            accel_size = struct.unpack('<I',f.read(4))[0]
            
            if ngas > 0:
                gas_tree.create_dataset("Acceleration",data=fromstring(f.read(12*ngas),dtype='f').reshape((-1,3)))
            if nhalo > 0:
                halo_tree.create_dataset("Acceleration",data=fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
            if ndisk > 0:
                disk_tree.create_dataset("Acceleration",data=fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))
            print "Read accelerations for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
            if nbulge > 0:
                bulge_tree.create_dataset("Acceleration",data=fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
            if nstar > 0:
                star_tree.create_dataset("Acceleration",data=fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
            if nbndry > 0:
                bndry_tree.create_dataset("Acceleration",data=fromstring(f.read(12*nbndry),dtype='f').reshape((-1,3)))
            
            if struct.unpack('<I',f.read(4))[0] != accel_size:
                raise StandardError("The block size at the end of the acceleration block doesn't match that at the beginning.  This is an issue.")
            continue
            
        elif label == "ENDT":
            print "Reading rate of change of entropy for gas data"
            dsdt_size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset("RateofChangeofEntropy",data=fromstring(f.read(4*ngas),dtype='f'))
            if struct.unpack('<I',f.read(4))[0] != dsdt_size:
                raise StandardError("The block size at the end of the entropy block doesn't match that at the beginning.  This is an issue.")
            continue
            
        elif label == "TSTP":
            print "Reading timesteps"
            timestep_size = struct.unpack('<I',f.read(4))[0]
        
            if ngas > 0:
                gas_tree.create_dataset("TimeStep",data=fromstring(f.read(4*ngas),dtype='f'))
            if nhalo > 0:
                halo_tree.create_dataset("TimeStep",data=fromstring(f.read(4*nhalo),dtype='f'))
            if ndisk > 0:
                disk_tree.create_dataset("TimeStep",data=fromstring(f.read(4*ndisk),dtype='f'))     
            print "Read timesteps for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))    
            if nbulge > 0:
                bulge_tree.create_dataset("TimeStep",data=fromstring(f.read(4*nbulge),dtype='f')) 
            if nstar > 0:
                star_tree.create_dataset("TimeStep",data=fromstring(f.read(4*nstar),dtype='f'))
            if nbndry > 0:
                bndry_tree.create_dataset("TimeStep",data=fromstring(f.read(4*nbndry),dtype='f'))
                                
            if struct.unpack('<I',f.read(4))[0] != timestep_size:
                raise StandardError("The block size at the end of the timestep block doesn't match that at the beginning.  This is an issue.")
            continue
        
        #Ok, so if I'm here, it's a nonstandard block.  How to handle those....hmm
        #Well, I'm definitely not going to bother renaming things; rather, I'll just use the strings as names
        #The primary difficulty lies in determining what type of particle the various blocks belong to...
        #Certain blocks I know belong to gas and/or stars, others it's not obvious
        #If a block is unrecognized, I'm going to give the option to skip or exit.
        elif label == "NE  ":   #A gas only thing
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
            continue
        
        elif label == "NH  ":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
            continue
                        
        elif label == "SFR ":   #A gas only block
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
            continue
                
        elif label == "AGE ":   #Stars only block
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            star_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*nstar),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
            continue
                        
        elif label == "Z   ":   #Gas and stars
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            if ngas > 0:  gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*ngas),dtype='f'))
            if nstar > 0:  star_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*nstar),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")    
            continue
        
        elif label == "BFLD":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
            continue
        
        elif label == "DBDT":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
        
        elif label == "DIVB":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")  
            continue
                
        elif label == "ABVC":  
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
            continue
                
        elif label == "COOR":    
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
            continue
        
        elif label == "CONR":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
            continue
            
        elif label == "BFSM":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
            continue

        elif label == "DENN":
            print "Reading "+label
            size = struct.unpack('<I',f.read(4))[0]
            gas_tree.create_dataset(label.rstrip(' '),data=fromstring(f.read(4*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise StandardError("The block size at the end of the"+label.rstrip(' ')+" block doesn't match that at the beginning.  This is an issue.")
            continue

        else:
            cont = raw_input("Block labeled '"+label+"' isn't recognized by this script.  Press enter to skip it or enter anything to exit.")
            if len(cont) > 0:
                f.close()
                irate.close()
                sys.exit(1)
            else:
                f.seek(btot,1)
                continue

    print "Finished reading type 2 file "+inname+" and saved it to "+outname