@@ -474,6 +474,139 @@ def find_detection_rate(path, filename="COMPAS_Output.h5", dco_type="BBH", weigh
474474
475475 return detection_rate , formation_rate , merger_rate , redshifts , COMPAS
476476
477+
478+ def append_rates (path , filename , detection_rate , formation_rate , merger_rate , redshifts , COMPAS , n_redshifts_detection ,
479+ maxz = 1. , sensitivity = "O1" , dco_type = "BHBH" , mu0 = 0.035 , muz = - 0.23 , sigma0 = 0.39 , sigmaz = 0. , alpha = 0. ,
480+ remove_group = False , append_binned_by_z = False , redshift_binsize = 0.1 ):
481+ """
482+ Append the formation rate, merger rate, detection rate and redshifts as a new group to your COMPAS output with weights hdf5 file
483+
484+ Args:
485+ path --> [string] Path to the COMPAS file that contains the output
486+ filename --> [string] Name of the COMPAS file
487+ detection_rate --> [2D float array] Detection rate for each binary at each redshift in 1/yr
488+ formation_rate --> [2D float array] Formation rate for each binary at each redshift in 1/yr/Gpc^3
489+ merger_rate --> [2D float array] Merger rate for each binary at each redshift in 1/yr/Gpc^3
490+ redshifts --> [list of floats] List of redshifts
491+ COMPAS --> [Object] Relevant COMPAS data in COMPASData Class
492+ n_redshifts_detection --> [int] Number of redshifts in list that should be used to calculate detection rates
493+
494+ maxz --> [float] Maximum redshhift up to where we would like to store the data
495+ sensitivity --> [string] Which detector sensitivity you used to calculate rates
496+ dco_type --> [string] Which DCO type you used to calculate rates
497+ mu0 --> [float] Parameter used for calculating metallicity density dist
498+ muz --> [float] Parameter used for calculating metallicity density dist
499+ sigma0 --> [float] Parameter used for calculating metallicity density dist
500+ sigmaz --> [float] Parameter used for calculating metallicity density dist
501+ alpha --> [float] Parameter used for calculating metallicity density dist
502+
503+ remove_group --> [Bool] if you completely want to remove this group from the hdf5 file, set this to True
504+ append_binned_by_z --> [Bool] to save space, bin rates by redshiftbin and append binned rates
505+
506+ Returns:
507+ h_new --> [hdf5 file] Compas output file with a new group "rates" with the same shape as DoubleCompactObjects
508+ """
509+ print ('shape redshifts' , np .shape (redshifts ))
510+ print ('shape COMPAS.sw_weights' , np .shape (COMPAS .sw_weights ) )
511+ print ('shape COMPAS COMPAS.DCO_masks["BHBH"]]' , np .shape (COMPAS .sw_weights [COMPAS .DCO_masks [dco_type ]]) )
512+
513+ n_redshifts_detection = int (max_redshift_detection / redshift_step )
514+
515+ #################################################
516+ #Open hdf5 file that we will write on
517+ print ('filename' , filename )
518+ with h5 .File (path + '/' + filename , 'r+' ) as h_new :
519+ # The rate info is shaped as DoubleCompactObjects[COMPAS.DCO_masks["BHBH"]] , len(redshifts)
520+ DCO = h_new ['DoubleCompactObjects' ]#
521+ print ('shape DCO[SEED]' , np .shape (DCO ['SEED' ][()]) )
522+
523+ #################################################
524+ # Create a new group where we will store data
525+ new_rate_group = 'Rates_mu0' + str (mu0 )+ '_muz' + str (muz )+ '_alpha' + str (alpha )+ '_sigma0' + str (sigma0 )+ '_sigmaz' + str (sigmaz )
526+ if append_binned_by_z :
527+ new_rate_group = new_rate_group + '_zBinned'
528+
529+ if new_rate_group not in h_new :
530+ h_new .create_group (new_rate_group )
531+ else :
532+ print (new_rate_group , 'exists, we will overrwrite the data' )
533+
534+
535+ ######################s###########################
536+ # If you just want to get rid of this point
537+ print ('remove_group' , remove_group )
538+ if remove_group :
539+ print ('You really want to remove this group fromm the hdf5 file, removing now..' )
540+ del h_new [new_rate_group ]
541+ return
542+
543+
544+ #################################################
545+ # Bin rates by redshifts
546+ #################################################
547+ if append_binned_by_z :
548+ print ('IN append_binned_by_z' )
549+
550+ # Choose how you want to bin the redshift, these represent the left and right boundaries
551+ redshift_bins = np .arange (0 , redshifts [- 1 ]+ redshift_binsize , redshift_binsize )
552+
553+ # Use digitize to assign the redshifts to a bin (detection list is shorter)
554+ digitized = np .digitize (redshifts , redshift_bins )
555+ digitized_det = np .digitize (redshifts [:n_redshifts_detection ], redshift_bins )
556+
557+ # The number of merging BBHs that need a weight
558+ N_dco = len (merger_rate [:,0 ])
559+
560+ ####################
561+ # binned_merger_rate will be the (observed) weights, binned by redshhift
562+ binned_merger_rate = np .zeros ( (N_dco , len (redshift_bins )- 1 ) )# create an empty list to fill
563+ binned_detection_rate = np .zeros ( (N_dco , len (redshift_bins )- 1 ) )# create an empty list to fill
564+ print ('x' , range (0 , len (redshift_bins )- 1 ))
565+ # loop over all redshift redshift_bins
566+ for i in range (len (redshift_bins )- 1 ):
567+ binned_merger_rate [:,i ] = np .sum (merger_rate [:, digitized == i + 1 ], axis = 1 )
568+ # only add detected rates for the 'detectable' redshiifts
569+ if redshift_bins [i ] < redshifts [n_redshifts_detection ]:
570+ binned_detection_rate [:,i ] = np .sum (detection_rate [:, digitized_det == i + 1 ], axis = 1 )
571+ save_redshifts = redshift_bins
572+ save_merger_rate = binned_merger_rate
573+ save_detection_rate = binned_detection_rate
574+
575+ else :
576+ # We don't really wan't All the data, so we're going to save only up to some redshift
577+ z_index = np .digitize (maxz , redshifts ) - 1
578+ # The detection_rate is a smaller array, make sure you don't go beyond the end
579+ detection_index = z_index if z_index < n_redshifts_detection else n_redshifts_detection
580+ print ('You will only save data up to redshift ' , maxz , ', i.e. index' , redshifts [z_index ])
581+ save_redshifts = redshifts
582+ save_merger_rate = merger_rate [:,:z_index ]
583+ save_detection_rate = detection_rate [:,:detection_index ]
584+
585+ print ('save_redshifts' , save_redshifts )
586+
587+ #################################################
588+ # Write the rates as a seperate dataset
589+ # re-arrange your list of rate parameters
590+ DCO_to_rate_mask = COMPAS .DCO_masks [dco_type ]
591+ print ('DCO_to_rate_mask' , DCO_to_rate_mask )
592+ rate_data_list = [DCO ['SEED' ][DCO_to_rate_mask ], DCO_to_rate_mask , save_redshifts , save_merger_rate , merger_rate [:,0 ], save_detection_rate ]
593+ rate_list_names = ['SEED' , 'DCO_mask' , 'redshifts' , 'merger_rate' ,'merger_rate_z0' , 'detection_rate' + sensitivity ]
594+ for i , data in enumerate (rate_data_list ):
595+ print ('Adding rate info of shape' , np .shape (data ))
596+ # Check if dataset exists, if so, just delete it
597+ if rate_list_names [i ] in h_new [new_rate_group ].keys ():
598+ del h_new [new_rate_group ][rate_list_names [i ]]
599+ # write rates as a new data set
600+ dataNew = h_new [new_rate_group ].create_dataset (rate_list_names [i ], data = data )
601+
602+ #Always close your files again
603+ h_new .close ()
604+ print ('Done :) your new files are here: ' , path + '/' + filename )
605+
606+
607+
608+
609+
477610def plot_rates (save_dir , formation_rate , merger_rate , detection_rate , redshifts , chirp_masses , show_plot = False , mu0 = 0.035 , muz = - 0.23 , sigma0 = 0.39 , sigmaz = 0. , alpha = 0 ):
478611 """
479612 Show a summary plot of the results, it also returns the summaries that it computes
@@ -557,6 +690,8 @@ def plot_rates(save_dir, formation_rate, merger_rate, detection_rate, redshifts,
557690###
558691##################################################################
559692if __name__ == "__main__" :
693+
694+ #####################################
560695 # Define command line options for the most commonly varied options
561696 parser = argparse .ArgumentParser ()
562697 parser .add_argument ("--path" , dest = 'path' , help = "Path to the COMPAS file that contains the output" ,type = str , default = './' )
@@ -592,8 +727,9 @@ def plot_rates(save_dir, formation_rate, merger_rate, detection_rate, redshifts,
592727
593728 args = parser .parse_args ()
594729
595- start_CI = time . time ()
730+ #####################################
596731 # Run the cosmic integration
732+ start_CI = time .time ()
597733 detection_rate , formation_rate , merger_rate , redshifts , COMPAS = find_detection_rate (args .path , filename = args .fname , dco_type = args .dco_type , weight_column = None , #"mixture_weight"
598734 max_redshift = args .max_redshift , max_redshift_detection = args .max_redshift_detection , redshift_step = args .redshift_step , z_first_SF = args .z_first_SF ,
599735 m1_min = args .m1_min * u .Msun , m1_max = args .m1_max * u .Msun , m2_min = args .m2_min * u .Msun , fbin = args .fbin ,
@@ -605,12 +741,22 @@ def plot_rates(save_dir, formation_rate, merger_rate, detection_rate, redshifts,
605741 snr_max = 1000.0 , snr_step = 0.1 )
606742 end_CI = time .time ()
607743
744+ #####################################
745+ # Append your freshly calculated merger rates to the hdf5 file
746+ start_append = time .time ()
747+ append_rates (args .path , args .fname , detection_rate , formation_rate , merger_rate , redshifts , COMPAS ,
748+ maxz = args .max_redshift_detection , sensitivity = args .sensitivity , dco_type = args .dco_type , mu0 = args .mu0 , muz = args .muz , alpha = args .alpha , sigma0 = args .sigma0 , sigmaz = args .sigmaz ,
749+ remove_group = False , max_redshift_detection = args .max_redshift_detection , redshift_step = args .redshift_step , append_binned_by_z = False , redshift_binsize = 0.05 )
750+ end_append = time .time ()
751+
752+ #####################################
608753 # Plot your result
609754 start_plot = time .time ()
610755 chirp_masses = (COMPAS .mass1 * COMPAS .mass2 )** (3. / 5. ) / (COMPAS .mass1 + COMPAS .mass2 )** (1. / 5. )
611756 plot_rates (args .path , formation_rate , merger_rate , detection_rate , redshifts , chirp_masses , show_plot = False , mu0 = args .mu0 , muz = args .muz , sigma0 = args .sigma0 , sigmaz = args .sigmaz , alpha = args .alpha )
612757 end_plot = time .time ()
613758
614759 print ('CI took ' , end_CI - start_CI , 's' )
760+ print ('Appending rates took ' , end_append - start_append , 's' )
615761 print ('plot took ' , end_plot - start_plot , 's' )
616762
0 commit comments