Source

IRATE-format / irate / gadgetbinary.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
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
#!/bin/python
from __future__ import division
import h5py
from numpy import *
import struct,os,sys

def gbin2irate(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 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. 

    :param inname: the name of the gadget binary file to be read
    :param  outname: the name of the IRATE file to be written, 
    :param potential: True to read the Makefile enabled potential block
 	:param accel: True to read the Makefile enabled acceleration block
	:param entropy: True to read the Makefile enabled dA/dt block
	:param timestep: True to read the Makefile enabled timestep block 
    :param t#_group: determines the group that particles in the # are placed;
		must be either dark, star, or gas
	:param t#_name: determines the name of the group that contains the data 
		from #
	:param ics:  True if the file being converted is an initial conditions
		file, in which case the gas density and smoothing length blocks won't
		be looked for.
	# refers to the same names as Gadget2:
	0 = gas particles
	1 = halo particles
	2 = disk particles
	3 = bulge particles
	4 = star particles
	5 = bndry particles
	"""
    print "\nOpening "+inname    
    f = open(inname,'rb')
    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
    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(264,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)

    #Ok, now to read in the blocks 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.")

    #next up is velocities.  pretty identical to the coordinates.
    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.")

    #Next up are the particle IDs, which are unsigned integers.
    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 I have to do the mass block.  Do this by checking if there are particles in a block that have a zero in the mass table.    
    if (ngas > 0 and masstable[0] == 0) or (nhalo > 0 and masstable[1] == 0) or (ndisk > 0 and masstable[2] == 0) or (nbulge > 0 and masstable[3] == 0) or (nstar > 0 and masstable[4] == 0) or (nbndry > 0 and masstable[5] == 0):
    #In other words, only read the size of the mass block if there is a mass block (for any of the groups)
        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
            
    #Next up is gas specific stuff:
    if ngas > 0:
        print "Reading gas specific data."
        
        #Put all this inside the if statement because I don't want it reading block sizes for gas blocks if there is no gas data (cause then there will be no block size and I will accidentally read into other data or past the end of the file.)
        
        #Internal energy:
        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."
        
        if not ics:     #These two blocks aren't required in IC files.
            #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.")
            
            #Smoothing length:
            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.") 
            
            print "Read gas density and smoothing lengths."
            
        else:
            print "Skipping blocks for gas density and smoothing lengths because this is an initial conditions file."
        
    #Now for the things that have to be specifically enabled in the makefile
    if potential:
        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 may be because the file contains extra unexpected blocks.  It is suggested that you rerun, ignoring the extra optional blocks, in the hopes that the standard blocks haven't been modified."
            sys.exit(1337)

    
    #Next, acceleration, which is the same as velocity:
    if accel:
        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.")
    
    if entropy and ngas > 0:    #i.e. neglect their call for entropy data if there are no gas particles
        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.")    
    else:
        if entropy:  print "Warning:  You specified that entropy is included, but there are no gas particles."
        
    if timestep:
        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.")
    
    current_pos = f.tell()
    f.seek(0,2) #Jump to the end of the file
    if current_pos == f.tell():
        print "Read "+inname
    else:
        print "Completed reading "+inname+" but there remain {0} bytes at the end of the file unread.".format(f.tell()-current_pos)
    f.close()
    print "Created IRATE format file "+outname
    irate.close()        
            
            
def read_gbin(fname,potential,accel,entropy,timestep):
	"""Reads a GADGET format file and returns the data in lists, one for
		each type of particle that contains arrays for each bit of data about
		each particle.  Currently unused in the IRATE suite, and possibly not
		maintained either.  Use at your own risk.

    :param inname: the name of the gadget binary file to be read
    :param potential: true to read the Makefile enabled potential block
 	:param accel: true to read the Makefile enabled acceleration block
	:param entropy: true to read the Makefile enabled dA/dt block
	:param timestep: true to read the Makefile enabled timestep block 
	"""       
    #The header and each data group gets its own list.
    
    #For non-gas groups, eg halodata = [halocoords,halovels,haloids,halomasses,halophi (if exists),haloaccel (if exists), halotimestep (if exists).  The (if exists) blocks must be enabled in the makefile; code will ask if they are or not.  The mass block may also be empty if all particles in that group have the same mass.
    
    #For gas, gasdata = [gascoords,gasvels,gasids,gasmass (if exists),gasU,gasdensity,gasHSML,gasphi (if exists),gasaccel (if exists), gas dS/dt (if exists), gastimestep (if exists), with the same conditions as non-gas groups.
    
    print "\nOpening "+fname
    f = open(fname,'rb')

    #First 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?

    #That's it for the header, so let's assemble it into a list then skip to the end:
    header = [nfile,masstable,a,z,flag_sfr,flag_feed,ntot,flag_cool,numfiles,boxsize,omega0,omegaL,h,flag_age,flag_metals,nhighword,flag_entropy]


    f.seek(264,0)   #Moves to the end of the header (and block that tells you size of header)
    """
    print "According to the header:"
    print "Ntotal = "+str(ntot[0]+ntot[1]+ntot[2]+ntot[3]+ntot[4]+ntot[5])
    print "There are "+str(ntot[0])+" gas particles.  According to the mass table, their mass is "+str(masstable[0])
    print "There are "+str(ntot[1])+" halo particles.  According to the mass table, their mass is "+str(masstable[1])
    print "There are "+str(ntot[2])+" disk particles.  According to the mass table, their mass is "+str(masstable[2])
    print "There are "+str(ntot[3])+" bulge particles.  According to the mass table, their mass is "+str(masstable[3])
    print "There are "+str(ntot[4])+" star particles.  According to the mass table, their mass is "+str(masstable[4])
    print "There are "+str(ntot[5])+" boundary particles.  According to the mass table, their mass is "+str(masstable[5])+"\n"
    """
    
    ngas = nfile[0]
    nhalo = nfile[1]
    ndisk = nfile[2]
    nbulge = nfile[3]
    nstar = nfile[4]
    nbndry = nfile[5]
    
    gasdata = []        #Use lists to keep the data for a specific particle species together, but it's a list of arrays
    halodata = []
    diskdata = []
    bulgedata = []
    stardata = []
    bndrydata = []
    
    #Rread in the coordinates, separate list for each particle type    
    coord_size = struct.unpack('<I',f.read(4))[0]   
    print "Reading coordinates..."
    #Read in all the coordinate data for the gas particles, Convert the string to an array, reshape it, and append it to the list of data for that particle type
    gasdata.append(fromstring(f.read(12*ngas) ,dtype='f').reshape((-1,3)))
    halodata.append(fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
    diskdata.append(fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))
    print "Read gas, halo, disk coordinates..."
    bulgedata.append(fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
    stardata.append(fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
    bndrydata.append(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.")
    
    #next up is velocities.  pretty identical to the coordinates.
    vel_size = struct.unpack('<I',f.read(4))[0]
    print "Reading velocities..."
    gasdata.append(fromstring(f.read(12*ngas),dtype='f').reshape((-1,3)))
    halodata.append(fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
    diskdata.append(fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))   
    print "Read gas, halo, disk velocities..."            
    bulgedata.append(fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
    stardata.append(fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
    bndrydata.append(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.")
        
    #Next up are the particle IDs, which are unsigned integers.
    id_size = struct.unpack('<I',f.read(4))[0]
    print "Reading particle IDs..."
    gasdata.append(fromstring(f.read(4*ngas),dtype='I'))
    halodata.append(fromstring(f.read(4*nhalo),dtype='I'))
    diskdata.append(fromstring(f.read(4*ndisk),dtype='I'))
    print "Read gas, halo, disk IDs..."            
    bulgedata.append(fromstring(f.read(4*nbulge),dtype='I'))
    stardata.append(fromstring(f.read(4*nstar),dtype='I'))
    bndrydata.append(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 I have to do the mass block.  Do this by checking if there are particles in a block that have a zero in the mass table.    
    if (ngas > 0 and masstable[0] == 0) or (nhalo > 0 and masstable[1] == 0) or (ndisk > 0 and masstable[2] == 0) or (nbulge > 0 and masstable[3] == 0) or (nstar > 0 and masstable[4] == 0) or (nbndry > 0 and masstable[5] == 0):
    #In other words, only read the size of the mass block if there is a mass block (for any of the groups); otherwise I'm just going to assign an empty list.
        mass_size = struct.unpack('<I',f.read(4))[0]
        
        if ngas > 0 and masstable[0] == 0:   #Then there are gas masses (ngas != 0 but the masstable has m = 0)
            print "Reading variable masses for gas group."
            gasmass = fromstring(f.read(4*ngas),dtype='f')
        else:
            gasmass = 0     #Just a placeholder so that my indices stay the same
            
        if nhalo > 0 and masstable[1] == 0:   #Then masses for particle group 1 are included
            print "Reading variable masses for group 1 (halo)."
            halomass = fromstring(f.read(4*nhalo),dtype='f')
        else:
            halomass = 0
            
        if ndisk > 0 and masstable[2] == 0:
            print "Reading variable masses for group 2 (disk)."
            diskmass = fromstring(f.read(4*ndisk),dtype='f')
        else:
            diskmass = 0
                        
        if nbulge > 0 and masstable[3] == 0:
            print "Reading variable masses for group 3 (bulge)."
            bulgemass = fromstring(f.read(4*nbulge),dtype='f')
        else:
            bulgemass = 0
            
        if nstar > 0 and masstable[4] == 0:
            print "Reading variable masses for group 4 (star)."
            starmass = fromstring(f.read(4*nstar),dtype='f')
        else:
            starmass = 0
            
        if nbndry > 0 and masstable[5] == 0:
            print "Reading variable masses for group 5 (boundary)."
            bndrymass = fromstring(f.read(4*nbndry),dtype='f')
        else:
            bndrymass = 0

        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:
        gasmass = 0
        halomass = 0
        diskmass = 0
        bulgemass = 0
        starmass = 0
        bndrymass = 0

    gasdata.append(gasmass)
    halodata.append(halomass)
    diskdata.append(diskmass)
    bulgedata.append(bulgemass)
    stardata.append(starmass)
    bndrydata.append(bndrymass)
    del gasmass,halomass,diskmass,bulgemass,starmass,bndrymass
    
    #Next up is some gas specific stuff.
    if ngas > 0:
        print "Reading gas specific data."
        
        #Put all this inside the if statement because I don't want it reading block sizes for gas blocks if there is no gas data (cause then there will be no block size and I will accidentally read into other data or past the end of the file.)
        
        #Internal energy:
        u_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(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.")
        
        #Density:
        rho_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(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.")
        
        #Smoothing length:
        hsml_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(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.") 
        
        print "Read gas internal energy, gas density, and gas smoothing lengths."
    
    #That's it for the gas stuff; now I have to read stuff that's only there if enabled in the Makefile.
    #First, potential:
    #Create and append the lists regardless of whether or not they'll be empty
    if potential:
        print "Reading gravitational potentials."
        phi_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(fromstring(f.read(4*ngas),dtype='f'))
        halodata.append(fromstring(f.read(4*nhalo),dtype='f'))
        diskdata.append(fromstring(f.read(4*ndisk),dtype='f'))
        print "Read potentials for gas, halo, and disk groups..."
        bulgedata.append(fromstring(f.read(4*nbulge),dtype='f'))
        stardata.append(fromstring(f.read(4*nstar),dtype='f'))
        bndrydata.append(fromstring(f.read(4*nbndry),dtype='f'))
        
        if struct.unpack('<I',f.read(4))[0] != phi_size:
            raise StandardError("The block size at the end of the phi block doesn't match that at the beginning.  This is an issue.")
    else:
    #append a placeholder to keep the indices the same either way
        gasdata.append(0)
        halodata.append(0)
        diskdata.append(0)
        bulgedata.append(0)
        stardata.append(0)
        bndrydata.append(0)
    
    #Next, acceleration, which is the same as velocity:
    if accel:
        print "Reading accelerations."
        accel_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(fromstring(f.read(12*ngas),dtype='f').reshape((-1,3)))
        halodata.append(fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
        diskdata.append(fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))
        print "Read gas, halo, disk velocities..."            
        bulgedata.append(fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
        stardata.append(fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
        bndrydata.append(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.")
    else:
        gasdata.append(0)
        halodata.append(0)
        diskdata.append(0)
        bulgedata.append(0)
        stardata.append(0)
        bndrydata.append(0) 
    
    if entropy and ngas > 0:    #i.e. neglect their call for entropy data if there are no gas particles
        print "Reading rate of change of entropy for gas data"
        dsdt_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(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.")    
    else:
        if entropy:  print "Warning:  You specified that entropy is included, but there are no gas particles."
        gasdata.append(0)
        
    if timestep:
        print "Reading timesteps"
        timestep_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(fromstring(f.read(4*ngas),dtype='f'))
        halodata.append(fromstring(f.read(4*nhalo),dtype='f'))
        diskdata.append(fromstring(f.read(4*ndisk),dtype='f'))
        print "Read potentials for gas, halo, and disk groups..."
        bulgedata.append(fromstring(f.read(4*nbulge),dtype='f'))
        stardata.append(fromstring(f.read(4*nstar),dtype='f'))
        bndrydata.append(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.")
    
    else:
        gasdata.append(0)
        halodata.append(0)
        diskdata.append(0)
        bulgedata.append(0)
        stardata.append(0)
        bndrydata.append(0)

    current_pos = f.tell()
    f.seek(0,2) #Jump to the end of the file
    if current_pos == f.tell():
        print "Read "+fname
    else:
        print "Completed reading "+fname+" but there remain {0} bytes at the end of the file unread.".format(f.tell()-current_pos)
    f.close()

    return [header,gasdata,halodata,diskdata,bulgedata,stardata,bndrydata]
    
    
def gb_write(outname,header,gasdata,t1data,t2data,t3data,stardata,t5data,potential,accel,entropy,timestep,
    gasgroup,gasname,t1_group,t1_name,t2_group,t2_name,t3_group,t3_name,stargroup,starname,t5_group,t5_name):
    """Writes an IRATE format file from the data passed to it.  Currently
		not used in the IRATE converter and probably not maintained.  Use
		at your own risk.

    :param  outname: the name of the IRATE file to be written
	:param header: the header of a Gadget file, as a list in the usual order
	:param ____data:  a list containing the coords, velocity, IDs, and 
		possibly other Makefile enabled blocks
	:param potential: true to read the Makefile enabled potential block
	:param accel: true to read the Makefile enabled acceleration block
	:param entropy: true to read the Makefile enabled dA/dt block
	:param timestep: true to read the Makefile enabled timestep block
    :param t#_group: determines the group that particles in the # are placed;
		must be either dark, star, or gas
	:param t#_name: determines the name of the group that contains the data 
		from #
	# refers to the same names as Gadget2:
	0 = gas particles
	1 = halo particles
	2 = disk particles
	3 = bulge particles
	4 = star particles
	5 = bndry particles
	"""
    #First this program is going to query what group each particle type should go to, then what the subgroup should be named.
    #Then it's going to create the HDF5 file using the structure that the user set up.
        
    #Now I have the structure that the user wants; just have to create it and write it
    #Note that, fortunately, H5Py will automatically convert a list into an array, so that's not something that I need to worry about
    f = h5py.File(outname,'w')  #Open the file for writing
    
    #Create the header group
    fileheader = f.create_group('Header')
    #Write the gadget header as attributes to the group:
    gheader = fileheader.create_group('GadgetHeader')
    gheader.attrs["NumPart_ThisFile"] = header[0]
    gheader.attrs["MassTable"] = header[1]
    gheader.attrs["Time"] = header[2]
    gheader.attrs["Redshift"] = header[3]
    gheader.attrs["Flag_Sfr"] = header[4]
    gheader.attrs["Flag_Feedback"] = header[5]
    gheader.attrs["NumPart_Total"] = header[6]
    gheader.attrs["Flag_Cooling"] = header[7]
    gheader.attrs["NumFilesPerSnapshot"] = header[8]
    gheader.attrs["BoxSize"] = header[9]
    gheader.attrs["Omega0"] = header[10]
    gheader.attrs["OmegaLambda"] = header[11]
    gheader.attrs["HubbleParam"] = header[12]
    gheader.attrs["Flag_StellarAge"] = header[13]
    gheader.attrs["Flag_Metals"] = header[14]
    gheader.attrs["NumPart_Total_HW"] = header[15]
    gheader.attrs["Flag_Entropy_ICs"] = header[16]
    
    
    #Create the file structure
    analysis = f.create_group('Analysis')    
    gas = f.create_group('Gas')
    dark = f.create_group('Dark')
    star = f.create_group('Star')
    #Nothing else should be done to f from here on, except of course closing it.
    
    #If particles in a group all have the same mass, the mass dataset will contain a list of that mass.

    if len(gasdata[0]) > 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':
            gas_tree = gas.create_group(gasname)
        elif gasgroup == 'dark':
            gas_tree = dark.create_group(gasname)
        elif gasgroup == 'star':
            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)
        
        gaspos = gas_tree.create_dataset("Position",data=gasdata[0])
        gasvel = gas_tree.create_dataset("Velocity",data=gasdata[1])
        gasids = gas_tree.create_dataset("ParticleIDs",data=gasdata[2])
        #A length check here does no good because the length will always be nonzero if there are particles; it'll just be filled with zeros.        
        if (gasdata[3] == 0):   #Then did not vary and they're saved in the header
            gasmassarray = empty(header[0][0])
            gasmassarray.fill(header[1][0])  #header[1] is the mass table  
            gasmass = gas_tree.create_dataset("Mass",data=gasmassarray)
            del gasmassarray            
        else:   #Masses varied because not all entries are zero
            gasmass = gas_tree.create_dataset("Mass",data=gasdata[3])
        gasu = gas_tree.create_dataset("InternalEnergy",data=gasdata[4])
        gas_rho = gas_tree.create_dataset("Density",data=gasdata[5])
        gas_smoothing = gas_tree.create_dataset("SmoothingLength",data=gasdata[6])
        #Only include optional blocks if they were there; that way I don't have any empty datasets
        if potential:
            gasphi = gas_tree.create_dataset("Potential",data=gasdata[7])
        if accel:
            gasaccel = gas_tree.create_dataset("Acceleration",data=gasdata[8])
            #Using gasdata[8] works because even if potential is false, an empty list would still be in it's place
        if entropy:
            gasdSdt = gas_tree.create_dataset("RateofChangeofEntropy",data=gasdata[9])
        if timestep:
            gastime = gas_tree.create_dataset("TimeStep",data=gasdata[10])
    
    del gasdata
    
    if len(t1data[0]) > 0:  #i.e. if there are particles in the first group (otherwise it's a zero length array)
        if t1_group == 'gas':
            print "Creating group "+t1_name+" in Gas tree."
            t1_tree = gas.create_group(t1_name)
        elif t1_group == 'dark':
            print "Creating group "+t1_name+" in Dark tree."
            t1_tree = dark.create_group(t1_name)
        elif t1_group == 'star':
            print "Creating group "+t1_name+" in Star tree."
            t1_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)
        
        t1pos = t1_tree.create_dataset("Position",data=t1data[0])
        t1vel = t1_tree.create_dataset("Velocity",data=t1data[1])
        t1ids = t1_tree.create_dataset("ParticleIDs",data=t1data[2])
        if t1data[3] == 0:  #Then masses didn't vary and they're stored in the header
            t1massarray = empty(header[0][1])
            t1massarray.fill(header[1][1])
            t1mass = t1_tree.create_dataset("Mass",data=t1massarray)
            del t1massarray
        else:
            t1mass = t1_tree.create_dataset("Mass",data=t1data[3])
        if potential:
            t1phi = t1_tree.create_dataset("Potential",data=t1data[4])
        if accel:
            t1accel = t1_tree.create_dataset("Acceleration",data=t1data[5])
        if timestep:    #Skip dS/dt because it only exists for gas particles
            t1time = t1_tree.create_dataset("TimeStep",data=t1data[6])
        
    del t1data
        
    if len(t2data[0]) > 0:
        if t2_group == 'gas':
            print "Creating group "+t2_name+" in Gas tree."
            t2_tree = gas.create_group(t2_name)
        elif t2_group == 'dark':
            print "Creating group "+t2_name+" in Dark tree."
            t2_tree = dark.create_group(t2_name)
        elif t2_group == 'star':
            print "Creating group "+t2_name+" in Star tree."
            t2_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)
            
        t2pos = t2_tree.create_dataset("Position",data=t2data[0])
        t2vel = t2_tree.create_dataset("Velocity",data=t2data[1])
        t2ids = t2_tree.create_dataset("ParticleIDs",data=t2data[2])
        if t2data[3] == 0: #Then masses didn't vary and they're stored in the header
            t2massarray = empty(header[0][2])
            t2massarray.fill(header[1][2])
            t2mass = t2_tree.create_dataset("Mass",data=t2massarray)
            del t2massarray
        else:
            t2mass = t2_tree.create_dataset("Mass",data=t2data[3])
        if potential:
            t2phi = t2_tree.create_dataset("Potential",data=t2data[4])
        if accel:
            t2accel = t2_tree.create_dataset("Acceleration",data=t2data[5])
        if timestep:
            t2time = t2_tree.create_dataset("TimeStep",data=t2data[6])
    
    del t2data

    if len(t3data[0]) > 0:
        if t3_group == 'gas':
            print "Creating group "+t3_name+" in Gas tree."
            t3_tree = gas.create_group(t3_name)
        elif t3_group == 'dark':
            print "Creating group "+t3_name+" in Dark tree."
            t3_tree = dark.create_group(t3_name)
        elif t3_group == 'star':
            print "Creating group "+t3_name+" in Star tree."
            t3_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)
            
        t3pos = t3_tree.create_dataset("Position",data=t3data[0])
        t3vel = t3_tree.create_dataset("Velocity",data=t3data[1])
        t3ids = t3_tree.create_dataset("ParticleIDs",data=t3data[2])
        if t3data[3] == 0: #Then masses didn't vary and they're stored in the header
            t3massarray = empty(header[0][3])
            t3massarray.fill(header[1][3])
            t3mass = t3_tree.create_dataset("Mass",data=t3massarray)
            del t3massarray
        else:
            t3mass = t3_tree.create_dataset("Mass",data=t3data[3])
        if potential:
            t3phi = t3_tree.create_dataset("Potential",data=t3data[4])
        if accel:
            t3accel = t3_tree.create_dataset("Acceleration",data=t3data[5])
        if timestep:
            t3time = t3_tree.create_dataset("TimeStep",data=t3data[6])
    
    del t3data
            
    if len(stardata[0]) > 0:
        if stargroup == 'gas':
            print "Creating group "+starname+" in Gas tree."
            startree = gas.create_group(starname)
        elif stargroup == 'dark':
            print "Creating group "+starname+" in Dark tree."
            startree = dark.create_group(starname)
        elif stargroup == 'star':
            print "Creating group "+starname+" in Star tree."
            startree = 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)
            
        starpos = startree.create_dataset("Position",data=stardata[0])
        starvel = startree.create_dataset("Velocity",data=stardata[1])
        starids = startree.create_dataset("ParticleIDs",data=stardata[2])
        if stardata[3] == 0:   #Then masses didn't vary and they're stored in the header
            starmassarray = empty(header[0][4])
            starmassarray.fill(header[1][4])
            starmass = startree.create_dataset("Mass",data=starmassarray)
            del starmassarray
        else:
            starmass = startree.create_dataset("Mass",data=stardata[3])
        if potential:
            starphi = startree.create_dataset("Potential",data=stardata[4])
        if accel:
            staraccel = startree.create_dataset("Acceleration",data=stardata[5])
        if timestep:
            startime = startree.create_dataset("TimeStep",data=stardata[6])

    del stardata

    if len(t5data[0]) > 0:
        if t5_group == 'gas':
            print "Creating group "+t5_name+" in Gas tree."
            t5_tree = gas.create_group(t5_name)
        elif t5_group == 'dark':
            print "Creating group "+t5_name+" in Dark tree."
            t5_tree = dark.create_group(t5_name)
        elif t5_group == 'star':
            print "Creating group "+t5_name+" in Star tree."
            t5_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 4 into a nonexistant tree."
            sys.exit(1337)
            
        t5pos = t5_tree.create_dataset("Position",data=t5data[0])
        t5vel = t5_tree.create_dataset("Velocity",data=t5data[1])
        t5ids = t5_tree.create_dataset("ParticleIDs",data=t5data[2])
        if t5data[3] == 0:   #Then masses didn't vary and they're stored in the header
            t5massarray = empty(header[0][5])
            t5massarray.fill(header[1][5])
            t5mass = t5_tree.create_dataset("Mass",data=t5massarray)
            del t5massarray
        else:
            t5mass = t5_tree.create_dataset("Mass",data=t5data[3])
        if potential:
            t5phi = t5_tree.create_dataset("Potential",data=t5data[4])
        if accel:
            t5accel = t5_tree.create_dataset("Acceleration",data=t5data[5])
        if timestep:
            t5time = t5_tree.create_dataset("TimeStep",data=t5data[6])

    del t5data
    
    f.close()