def test_companion_star_fraction():
    """
    Test the companion_star fraction on the MultiplicityUnresolved object.
    """
    from popstar.imf import multiplicity

    # First set of multiplicity parameters
    mu1 = multiplicity.MultiplicityUnresolved()

    csf1_1 = mu1.companion_star_fraction(1.0)
    nose.tools.assert_almost_equal(csf1_1, 0.5, places=2)

    csf1_2 = mu1.companion_star_fraction(70.0)
    nose.tools.assert_almost_equal(csf1_2, 3.0, places=2)

    csf1_3 = mu1.companion_star_fraction(0.1)
    nose.tools.assert_almost_equal(csf1_3, 0.177, places=2)

    # Second set of multiplicity parameters
    mu2 = multiplicity.MultiplicityUnresolved(MF_amp=0.4,
                                              MF_power=0.4,
                                              CSF_amp=0.4,
                                              CSF_power=0.4,
                                              CSF_max=2,
                                              q_power=0.4,
                                              q_min=0.04)
Exemple #2
0
def time_test_cluster():
    from popstar import synthetic as syn
    from popstar import atmospheres as atm
    from popstar import evolution
    from popstar import reddening
    from popstar.imf import imf
    from popstar.imf import multiplicity

    logAge = 6.7
    AKs = 2.7
    distance = 4000
    cluster_mass = 10**4

    startTime = time.time()
    
    evo = evolution.MergedBaraffePisaEkstromParsec()
    atm_func = atm.get_merged_atmosphere
    red_law = reddening.RedLawNishiyama09()
    filt_list = ['nirc2,J', 'nirc2,Kp']
    
    iso = syn.IsochronePhot(logAge, AKs, distance,
                            evo_model=evo, atm_func=atm_func,
                            red_law=red_law, filters=filt_list)
    print('Constructed isochrone: %d seconds' % (time.time() - startTime))

    imf_limits = np.array([0.07, 0.5, 150])
    imf_powers = np.array([-1.3, -2.35])
    multi = multiplicity.MultiplicityUnresolved()
    my_imf = imf.IMF_broken_powerlaw(imf_limits, imf_powers, multiplicity=multi)
    print('Constructed IMF with multiples: %d seconds' % (time.time() - startTime))
    
    cluster = syn.ResolvedCluster(iso, my_imf, cluster_mass)
    print('Constructed cluster: %d seconds' % (time.time() - startTime))

    return
Exemple #3
0
def test_UnresolvedCluster():
    from popstar import synthetic as syn
    from popstar import atmospheres as atm
    from popstar import evolution
    from popstar.imf import imf
    from popstar.imf import multiplicity
    
    log_age = 6.7
    AKs = 0.0
    distance = 4000
    metallicity=0
    cluster_mass = 10**4.

    startTime = time.time()    
    multi = multiplicity.MultiplicityUnresolved()
    imf_in = imf.Kroupa_2001(multiplicity=multi)
    evo = evolution.MergedBaraffePisaEkstromParsec()
    atm_func = atm.get_merged_atmosphere
    iso = syn.Isochrone(log_age, AKs, distance, metallicity=metallicity,
                            evo_model=evo, atm_func=atm_func, mass_sampling=10)
    print('Made Isochrone: %d seconds' % (time.time() - startTime))

    cluster = syn.UnresolvedCluster(iso, imf_in, cluster_mass)
    print('Constructed unresolved cluster: %d seconds' % (time.time() - startTime))

    # Plot an integrated spectrum of the whole cluster.
    wave = cluster.wave_trim
    flux = cluster.spec_trim
    plt.clf()
    plt.plot(wave, flux, 'k.')

    return
Exemple #4
0
def test_UnresolvedCluster():
    from popstar import synthetic as syn
    from popstar import atmospheres as atm
    from popstar import evolution
    from popstar.imf import imf
    from popstar.imf import multiplicity

    log_age = 6.7
    AKs = 0.0
    distance = 4000
    cluster_mass = 30.

    startTime = time.time()
    multi = multiplicity.MultiplicityUnresolved()
    imf_in = imf.Kroupa_2001(multiplicity=multi)
    evo = evolution.MergedBaraffePisaEkstromParsec()
    iso = syn.Isochrone(log_age, AKs, distance, evo, mass_sampling=10)
    print 'Made cluster: %d seconds' % (time.time() - startTime)

    cluster = syn.UnresolvedCluster(iso, imf_in, cluster_mass)
    print 'Constructed unresolved cluster: %d seconds' % (time.time() -
                                                          startTime)

    # Plot an integrated spectrum of the whole cluster.
    wave = cluster.spec_trim.wave
    flux = cluster.spec_trim.flux
    plt.clf()
    plt.plot(wave, flux, 'k.')
    pdb.set_trace()
    return
def test_multiplicity_fraction():
    """
    Test creating a MultiplicityUnresolved object and getting
    the multiplicity fraction out.
    """
    from popstar.imf import multiplicity

    # First set of multiplicity parameters
    mu1 = multiplicity.MultiplicityUnresolved()

    mf1_1 = mu1.multiplicity_fraction(1.0)
    nose.tools.assert_almost_equal(mf1_1, 0.44, places=2)

    mf1_2 = mu1.multiplicity_fraction(10.0)
    nose.tools.assert_almost_equal(mf1_2, 1.0, places=2)

    mf1_3 = mu1.multiplicity_fraction(0.1)
    nose.tools.assert_almost_equal(mf1_3, 0.136, places=2)

    # Second set of multiplicity parameters
    mu2 = multiplicity.MultiplicityUnresolved(MF_amp=0.4,
                                              MF_power=0.4,
                                              CSF_amp=0.4,
                                              CSF_power=0.4,
                                              CSF_max=4,
                                              q_power=0.4,
                                              q_min=0.04)

    mf2_1 = mu1.multiplicity_fraction(1.0)
    nose.tools.assert_almost_equal(mf2_1, 0.4, places=2)

    mf2_2 = mu1.multiplicity_fraction(10.0)
    nose.tools.assert_almost_equal(mf2_2, 1.0, places=2)

    mf2_3 = mu1.multiplicity_fraction(0.1)
    nose.tools.assert_almost_equal(mf2_3, 0.159, places=2)
def test_multiplicity_fraction_array():
    """
    Test multiplicity_fraction() on the MultiplicityUnresolved object
    where the inputs and outputs are in array form.
    """
    from popstar.imf import multiplicity

    # First set of multiplicity parameters
    mu1 = multiplicity.MultiplicityUnresolved()

    mass_array = np.array([1.0, 10.0, 0.1])
    mf_array = mu1.multiplicity_fraction(mass_array)

    nose.tools.assert_almost_equal(mf_array[0], 0.44, places=2)
    nose.tools.assert_almost_equal(mf_array[1], 1.0, places=2)
    nose.tools.assert_almost_equal(mf_array[2], 0.136, places=2)
Exemple #7
0
def model_young_cluster_object(resolved=False):
    from popstar import synthetic as syn
    from popstar import atmospheres as atm
    from popstar import evolution
    from popstar.imf import imf
    from popstar.imf import multiplicity

    log_age = 6.5
    AKs = 0.1
    distance = 8000.0
    cluster_mass = 10000.

    multi = multiplicity.MultiplicityUnresolved()
    imf_in = imf.Kroupa_2001(multiplicity=multi)
    evo = evolution.MergedPisaEkstromParsec()
    atm_func = atm.get_merged_atmosphere
    iso = syn.Isochrone(log_age, AKs, distance, evo, mass_sampling=10)

    if resolved:
        cluster = syn.ResolvedCluster(iso, imf_in, cluster_mass)
    else:
        cluster = syn.UnresolvedCluster(iso,
                                        imf_in,
                                        cluster_mass,
                                        wave_range=[19000, 24000])

    # Plot the spectrum of the most massive star
    idx = cluster.mass_all.argmax()
    print('Most massive star is {0:f} M_sun.'.format(cluster.mass_all[idx]))
    #bigstar = cluster.spec_list_trim[idx]
    plt.figure(1)
    plt.clf()
    plt.plot(cluster.spec_list_trim[idx]._wavetable,
             cluster.spec_list_trim[idx]._fluxtable, 'k.')

    # Plot an integrated spectrum of the whole cluster.
    wave, flux = cluster.spec_list_trim[idx]._wavetable, cluster.spec_trim
    plt.figure(2)
    plt.clf()
    plt.plot(wave, flux, 'k.')

    return
def make_sim_cluster():
    work_dir = '/u/jlu/work/gc/jwst/2018_03_19/'

    ages = [4e6, 1e8, 8e9]
    cluster_mass = [1e4, 1e4, 1e7]
    AKs = 2.7
    deltaAKs = 1.0
    distance = 8000
    mass_sampling = 5

    isochrones = []
    clusters = []

    evo = evolution.MergedBaraffePisaEkstromParsec()
    atm_func = atm.get_merged_atmosphere
    red_law = reddening.RedLawHosek18()
    multi = multiplicity.MultiplicityUnresolved()

    imf_mass_limits = np.array([0.07, 0.5, 1, np.inf])
    imf_powers_old = np.array([-1.3, -2.3, -2.3])
    imf_powers_yng = np.array([-1.3, -1.8, -1.8])
    my_imf_old = imf.IMF_broken_powerlaw(imf_mass_limits,
                                         imf_powers_old,
                                         multiplicity=multi)
    my_imf_yng = imf.IMF_broken_powerlaw(imf_mass_limits,
                                         imf_powers_yng,
                                         multiplicity=multi)

    # Test all filters
    filt_list = [
        'wfc3,ir,f127m', 'wfc3,ir,f139m', 'wfc3,ir,f153m', 'acs,wfc1,f814w',
        'wfc3,ir,f125w', 'wfc3,ir,f160w', 'jwst,F090W', 'jwst,F115W',
        'jwst,F164N', 'jwst,F187N', 'jwst,F212N', 'jwst,F323N', 'jwst,F405N',
        'jwst,F466N', 'jwst,F470N', 'jwst,F140M', 'jwst,F162M', 'jwst,F182M',
        'jwst,F210M', 'jwst,F250M', 'jwst,F300M', 'jwst,F335M', 'jwst,F360M',
        'jwst,F410M', 'jwst,F430M', 'jwst,F460M', 'jwst,F480M', 'nirc2,J',
        'nirc2,H', 'nirc2,Kp', 'nirc2,Lp', 'nirc2,Ms'
    ]

    startTime = time.time()
    for ii in range(len(ages)):
        logAge = np.log10(ages[ii])

        iso = syn.IsochronePhot(logAge,
                                AKs,
                                distance,
                                evo_model=evo,
                                atm_func=atm_func,
                                red_law=red_law,
                                filters=filt_list,
                                mass_sampling=mass_sampling,
                                iso_dir=work_dir)

        print('Constructed isochrone: %d seconds' % (time.time() - startTime))

        if ii < 2:
            imf_ii = my_imf_yng
        else:
            imf_ii = my_imf_old

        cluster = syn.ResolvedClusterDiffRedden(iso, imf_ii, cluster_mass[ii],
                                                deltaAKs)

        # Save generated clusters to file.
        save_file_fmt = '{0}/clust_{1:.2f}_{2:4.2f}_{3:4s}.fits'
        save_file_txt = save_file_fmt.format(work_dir, logAge, AKs,
                                             str(distance).zfill(5))
        save_file = open(save_file_txt, 'wb')
        pickle.dump(cluster, save_file)

    return

    return
Exemple #9
0
def test_ifmr_multiplicity():
    from popstar import synthetic as syn
    from popstar import atmospheres as atm
    from popstar import evolution
    from popstar import reddening
    from popstar import ifmr
    from popstar.imf import imf
    from popstar.imf import multiplicity

    # Define cluster parameters
    logAge = 9.7
    AKs = 0.0
    distance = 1000
    cluster_mass = 1e6
    mass_sampling = 5

    # Test all filters
    filt_list = ['nirc2,Kp', 'nirc2,H', 'nirc2,J']

    startTime = time.time()

    evo = evolution.MISTv1()
    atm_func = atm.get_merged_atmosphere
    ifmr_obj = ifmr.IFMR()

    red_law = reddening.RedLawNishiyama09()

    iso = syn.IsochronePhot(logAge,
                            AKs,
                            distance,
                            evo_model=evo,
                            atm_func=atm_func,
                            red_law=red_law,
                            filters=filt_list,
                            mass_sampling=mass_sampling)

    print('Constructed isochrone: %d seconds' % (time.time() - startTime))

    # Now to create the cluster.
    imf_mass_limits = np.array([0.07, 0.5, 1, np.inf])
    imf_powers = np.array([-1.3, -2.3, -2.3])

    ##########
    # Start without multiplicity and IFMR
    ##########
    my_imf1 = imf.IMF_broken_powerlaw(imf_mass_limits,
                                      imf_powers,
                                      multiplicity=None)
    print('Constructed IMF: %d seconds' % (time.time() - startTime))

    cluster1 = syn.ResolvedCluster(iso, my_imf1, cluster_mass, ifmr=ifmr_obj)
    clust1 = cluster1.star_systems
    print('Constructed cluster: %d seconds' % (time.time() - startTime))

    ##########
    # Test with multiplicity and IFMR
    ##########
    multi = multiplicity.MultiplicityUnresolved()
    my_imf2 = imf.IMF_broken_powerlaw(imf_mass_limits,
                                      imf_powers,
                                      multiplicity=multi)
    print('Constructed IMF with multiples: %d seconds' %
          (time.time() - startTime))

    cluster2 = syn.ResolvedCluster(iso, my_imf2, cluster_mass, ifmr=ifmr_obj)
    clust2 = cluster2.star_systems
    comps2 = cluster2.companions
    print('Constructed cluster with multiples: %d seconds' %
          (time.time() - startTime))

    ##########
    # Tests
    ##########

    # Check that we have black holes, neutron stars, and white dwarfs in both.
    assert len(np.where(clust1['phase'] == 101)) > 0  # WD
    assert len(np.where(clust2['phase'] == 101)) > 0
    assert len(np.where(clust1['phase'] == 102)) > 0  # NS
    assert len(np.where(clust2['phase'] == 102)) > 0
    assert len(np.where(clust1['phase'] == 103)) > 0  # BH
    assert len(np.where(clust2['phase'] == 103)) > 0

    # Now check that we have companions that are WDs, NSs, and BHs
    assert len(np.where(comps2['phase'] == 101)) > 0
    assert len(np.where(comps2['phase'] == 102)) > 0
    assert len(np.where(comps2['phase'] == 103)) > 0

    # Make sure no funky phase designations (due to interpolation effects)
    # slipped through
    idx = np.where((clust1['phase'] > 5) & (clust1['phase'] < 101)
                   & (clust1['phase'] != 9))
    idx2 = np.where((comps2['phase'] > 5) & (comps2['phase'] < 101)
                    & (comps2['phase'] != 9))
    assert len(idx[0]) == 0

    return
Exemple #10
0
def test_ResolvedClusterDiffRedden():
    from popstar import synthetic as syn
    from popstar import atmospheres as atm
    from popstar import evolution
    from popstar import reddening
    from popstar.imf import imf
    from popstar.imf import multiplicity

    logAge = 6.7
    AKs = 2.4
    distance = 4000
    cluster_mass = 10**5.
    deltaAKs = 0.05
    mass_sampling = 5

    # Test filters
    filt_list = ['nirc2,J', 'nirc2,Kp']

    startTime = time.time()

    evo = evolution.MergedBaraffePisaEkstromParsec()
    atm_func = atm.get_merged_atmosphere

    red_law = reddening.RedLawNishiyama09()

    iso = syn.IsochronePhot(logAge,
                            AKs,
                            distance,
                            evo_model=evo,
                            atm_func=atm_func,
                            red_law=red_law,
                            filters=filt_list,
                            mass_sampling=mass_sampling)

    print('Constructed isochrone: %d seconds' % (time.time() - startTime))

    imf_mass_limits = np.array([0.07, 0.5, 1, np.inf])
    imf_powers = np.array([-1.3, -2.3, -2.3])

    ##########
    # Start without multiplicity
    ##########
    my_imf1 = imf.IMF_broken_powerlaw(imf_mass_limits,
                                      imf_powers,
                                      multiplicity=None)
    print('Constructed IMF: %d seconds' % (time.time() - startTime))

    cluster1 = syn.ResolvedClusterDiffRedden(iso, my_imf1, cluster_mass,
                                             deltaAKs)
    clust1 = cluster1.star_systems
    print('Constructed cluster: %d seconds' % (time.time() - startTime))

    assert len(clust1) > 0

    plt.figure(3)
    plt.clf()
    plt.plot(clust1['m_nirc2_J'] - clust1['m_nirc2_Kp'], clust1['m_nirc2_J'],
             'r.')
    plt.plot(iso.points['m_nirc2_J'] - iso.points['m_nirc2_Kp'],
             iso.points['m_nirc2_J'], 'c.')
    plt.gca().invert_yaxis()

    # *** Visual Inspections: ***
    #  - check that points (red) fall between isochrone points (blue)

    ##########
    # Test with multiplicity
    ##########
    multi = multiplicity.MultiplicityUnresolved()
    my_imf2 = imf.IMF_broken_powerlaw(imf_mass_limits,
                                      imf_powers,
                                      multiplicity=multi)
    print('Constructed IMF with multiples: %d seconds' %
          (time.time() - startTime))

    cluster2 = syn.ResolvedClusterDiffRedden(iso, my_imf2, cluster_mass,
                                             deltaAKs)
    clust2 = cluster2.star_systems
    print('Constructed cluster with multiples: %d seconds' %
          (time.time() - startTime))

    assert len(clust2) > 0
    assert len(cluster2.companions) > 0
    assert np.sum(clust2['N_companions']) == len(cluster2.companions)

    ##########
    # Plots
    ##########
    # Plot an IR CMD and compare cluster members to isochrone.
    plt.figure(1)
    plt.clf()
    plt.plot(clust1['m_nirc2_J'] - clust1['m_nirc2_Kp'], clust1['m_nirc2_J'],
             'r.')
    plt.plot(clust2['m_nirc2_J'] - clust2['m_nirc2_Kp'], clust2['m_nirc2_J'],
             'b.')
    plt.plot(iso.points['m_nirc2_J'] - iso.points['m_nirc2_Kp'],
             iso.points['m_nirc2_J'], 'c-')
    plt.gca().invert_yaxis()
    plt.xlabel('J - Kp (mag)')
    plt.ylabel('J (mag')

    # Plot a mass-magnitude relationship.
    plt.figure(2)
    plt.clf()
    plt.semilogx(clust1['mass'], clust1['m_nirc2_J'], 'r.')
    plt.semilogx(clust2['mass'], clust2['m_nirc2_J'], 'r.')
    plt.gca().invert_yaxis()
    plt.xlabel('Mass (Msun)')
    plt.ylabel('J (mag)')

    return
Exemple #11
0
def test_ResolvedCluster():
    from popstar import synthetic as syn
    from popstar import atmospheres as atm
    from popstar import evolution
    from popstar import reddening
    from popstar.imf import imf
    from popstar.imf import multiplicity

    # Define cluster parameters
    logAge = 6.7
    AKs = 2.4
    distance = 4000
    cluster_mass = 10**5.
    mass_sampling=5

    # Test all filters
    filt_list = ['wfc3,ir,f127m', 'wfc3,ir,f139m', 'wfc3,ir,f153m', 'acs,wfc1,f814w',
                     'wfc3,ir,f125w', 'wfc3,ir,f160w', 'decam,y', 'decam,i', 'decam,z',
                         'decam,u', 'decam,g', 'decam,r', 'vista,Y', 'vista,Z',
                         'vista,J', 'vista,H', 'vista,Ks', 'ps1,z', 'ps1,g', 'ps1,r',
                         'ps1,i', 'ps1,y', 'jwst,F090W', 'jwst,F164N', 'jwst,F212N',
                         'jwst,F323N', 'jwst,F466N', 'nirc2,J', 'nirc2,H', 'nirc2,Kp',
                         'nirc2,K', 'nirc2,Lp', 'nirc2,Ms', 'nirc2,Hcont', 'nirc2,FeII',
                         'nirc2,Brgamma', 'jg,J', 'jg,H', 'jg,K']

    startTime = time.time()
    
    evo = evolution.MergedBaraffePisaEkstromParsec()
    atm_func = atm.get_merged_atmosphere

    red_law = reddening.RedLawNishiyama09()
    
    iso = syn.IsochronePhot(logAge, AKs, distance,
                            evo_model=evo, atm_func=atm_func,
                            red_law=red_law, filters=filt_list,
                            mass_sampling=mass_sampling)

    print('Constructed isochrone: %d seconds' % (time.time() - startTime))

    # Now to create the cluster.
    imf_mass_limits = np.array([0.07, 0.5, 1, np.inf])
    imf_powers = np.array([-1.3, -2.3, -2.3])

    ##########
    # Start without multiplicity
    ##########
    my_imf1 = imf.IMF_broken_powerlaw(imf_mass_limits, imf_powers,
                                      multiplicity=None)
    print('Constructed IMF: %d seconds' % (time.time() - startTime))
    
    cluster1 = syn.ResolvedCluster(iso, my_imf1, cluster_mass)
    clust1 = cluster1.star_systems
    print('Constructed cluster: %d seconds' % (time.time() - startTime))

    plt.figure(3)
    plt.clf()
    plt.plot(clust1['m_nirc2_J'] - clust1['m_nirc2_Kp'], clust1['m_nirc2_J'], 'r.')
    plt.plot(iso.points['m_nirc2_J'] - iso.points['m_nirc2_Kp'], iso.points['m_nirc2_J'], 'c.')
    plt.gca().invert_yaxis()

    # *** Visual Inspections: ***
    #  - check that points (red) fall between isochrone points (blue)

    ##########
    # Test with multiplicity
    ##########
    multi = multiplicity.MultiplicityUnresolved()
    my_imf2 = imf.IMF_broken_powerlaw(imf_mass_limits, imf_powers,
                                      multiplicity=multi)
    print('Constructed IMF with multiples: %d seconds' % (time.time() - startTime))
    
    cluster2 = syn.ResolvedCluster(iso, my_imf2, cluster_mass)
    clust2 = cluster2.star_systems
    print('Constructed cluster with multiples: %d seconds' % (time.time() - startTime))

    ##########
    # Plots 
    ##########
    # Plot an IR CMD and compare cluster members to isochrone.
    plt.figure(1)
    plt.clf()
    plt.plot(clust1['m_nirc2_J'] - clust1['m_nirc2_Kp'], clust1['m_nirc2_J'], 'r.')
    plt.plot(clust2['m_nirc2_J'] - clust2['m_nirc2_Kp'], clust2['m_nirc2_J'], 'b.')
    plt.plot(iso.points['m_nirc2_J'] - iso.points['m_nirc2_Kp'], iso.points['m_nirc2_J'], 'c-')
    plt.gca().invert_yaxis()
    plt.xlabel('J - Kp (mag)')
    plt.ylabel('J (mag')

    # Plot a mass-magnitude relationship.
    plt.figure(2)
    plt.clf()
    plt.semilogx(clust1['mass'], clust1['m_nirc2_J'], 'r.')
    plt.semilogx(clust2['mass'], clust2['m_nirc2_J'], 'r.')
    plt.gca().invert_yaxis()
    plt.xlabel('Mass (Msun)')
    plt.ylabel('J (mag)')
    
    # # Plot the spectrum of the most massive star
    # idx = cluster.mass.argmax()
    # plt.clf()
    # plt.plot(cluster.stars[idx].wave, cluster.stars[idx].flux, 'k.')

    # # Plot an integrated spectrum of the whole cluster.
    # wave, flux = cluster.get_integrated_spectrum()
    # plt.clf()
    # plt.plot(wave, flux, 'k.')

    return
Exemple #12
0
def multinest_run(root_dir='/Users/jlu/work/wd1/analysis_2015_01_05/',
                  data_tab='catalog_diffDered_NN_opt_10.fits',
                  comp_tab='completeness_ccmd.fits',
                  out_dir='multinest/fit_0001/'):

    if not os.path.exists(root_dir + out_dir):
        os.makedirs(root_dir + out_dir)

    # Input the observed data
    t = Table.read(root_dir + data_tab)

    # Input the completeness table and bins.
    completeness_map = pyfits.getdata(root_dir + comp_tab)
    completeness_map = completeness_map.T
    _in_bins = open(root_dir + comp_tab.replace('.fits', '_bins.pickle'), 'r')
    bins_mag = pickle.load(_in_bins)
    bins_col1 = pickle.load(_in_bins)
    bins_col2 = pickle.load(_in_bins)

    # Some components of our model are static.
    imf_multi = multiplicity.MultiplicityUnresolved()
    imf_mmin = 0.1  # msun
    imf_mmax = 150.0  # msun
    evo_model = evolution.MergedBaraffePisaEkstromParsec()
    red_law = reddening.RedLawNishiyama09()
    atm_func = atmospheres.get_merged_atmosphere
    Mcl_sim = 5.0e6

    # Our data vs. model comparison will be done in
    # magnitude-color-color space. Models will be binned
    # to construct 3D probability density spaces.
    # These are the bin sizes for the models.
    #
    # Note Dimensions:
    #   mag = m_2010_F160W
    #   col1 = m_2005_F814W - m_2010_F160W
    #   col2 = m_2010_F125W - m_2010_F160W
    #
    bins = np.array([bins_mag, bins_col1, bins_col2])

    def priors(cube, ndim, nparams):
        return

    def likelihood(cube, ndim, nparams):
        ##########
        # Priors (I think order matters)
        ##########
        parName = [
            'distance', 'LogAge', 'AKs', 'dAKs', 'alpha1', 'alpha2', 'mbreak',
            'Mcl'
        ]
        par, par_prior_logp = get_prior_info(cube, parName)

        sysMass = np.zeros(len(t))

        ##########
        # Load up the model cluster.
        ##########
        imf_mass_limits = np.array([imf_mmin, par['mbreak'], imf_mmax])
        imf_powers = np.array([par['alpha2'], par['alpha1']])
        imf_multi = None
        new_imf = imf.IMF_broken_powerlaw(imf_mass_limits, imf_powers,
                                          imf_multi)

        print 'Getting Isochrone'
        new_iso = synthetic.IsochronePhot(par['LogAge'],
                                          par['AKs'],
                                          par['distance'],
                                          evo_model=evo_model,
                                          atm_func=atm_func,
                                          red_law=red_law)

        print 'Getting Cluster'
        cluster = synthetic.ResolvedClusterDiffRedden(new_iso,
                                                      new_imf,
                                                      Mcl_sim,
                                                      par['dAKs'],
                                                      red_law=red_law)

        # Convert simulated cluster into agnitude-color-color histogram
        mag = cluster.star_systems['mag160w']
        col1 = cluster.star_systems['mag814w'] - mag
        col2 = cluster.star_systems['mag125w'] - mag

        data = np.array([mag, col1, col2]).T
        bins = np.array([bins_mag, bins_col1, bins_col2])

        H_sim_c, edges = np.histogramdd(data, bins=bins, normed=True)
        H_sim = H_sim_c * completeness_map

        # Convert Observed cluster into magnitude-color-color histogram
        mag = t['m_2010_F160W']
        col1 = t['m_2005_F814W'] - t['m_2010_F160W']
        col2 = t['m_2010_F125W'] - t['m_2010_F160W']

        data = np.array([mag, col1, col2]).T
        bins = np.array([bins_mag, bins_col1, bins_col2])

        H_obs, edges = np.histogramdd(data, bins=bins)

        # Plotting
        extent = (bins_col1[0], bins_col2[-1], bins_mag[0], bins_mag[-1])
        py.figure(1)
        py.clf()
        py.imshow(H_sim_c.sum(axis=2), extent=extent)
        py.gca().invert_yaxis()
        py.colorbar()
        py.axis('tight')
        py.title('Sim Complete')

        py.figure(2)
        py.clf()
        py.imshow(H_sim.sum(axis=2), extent=extent)
        py.gca().invert_yaxis()
        py.colorbar()
        py.axis('tight')
        py.title('Sim Incomplete')

        py.figure(3)
        py.clf()
        py.imshow(H_obs.sum(axis=2), extent=extent)
        py.gca().invert_yaxis()
        py.colorbar()
        py.axis('tight')
        py.title('Obs Incomplete')

        py.figure(4)
        py.clf()
        py.imshow(completeness_map.mean(axis=2), extent=extent, vmin=0, vmax=1)
        py.gca().invert_yaxis()
        py.colorbar()
        py.axis('tight')
        py.title('Completeness Map')

        pdb.set_trace()

        mcc_cluster = 1

        print likei.sum()
        return likei.sum()

    num_dims = 8
    num_params = 8
    ev_tol = 0.3
    samp_eff = 0.8
    n_live_points = 300

    # pymultinest.run(likelihood, priors, num_dims, n_params=num_params,
    #                 outputfiles_basename=out_dir + 'test',
    #                 verbose=True, resume=False, evidence_tolerance=ev_tol,
    #                 sampling_efficiency=samp_eff, n_live_points=n_live_points,
    #                 multimodal=True, n_clustering_params=num_dims)
    cube_test = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]
    likelihood(cube_test, num_dims, num_params)
Exemple #13
0
def test_cluster_mass():
    from popstar import synthetic as syn
    from popstar import atmospheres as atm
    from popstar import evolution
    from popstar import reddening
    from popstar import ifmr
    from popstar.imf import imf
    from popstar.imf import multiplicity

    # Define cluster parameters
    logAge = 6.7
    AKs = 2.4
    distance = 4000
    cluster_mass = 10**5.
    mass_sampling = 5

    # Test filters
    filt_list = ['nirc2,J', 'nirc2,Kp']

    startTime = time.time()

    # Define evolution/atmosphere models and extinction law
    evo = evolution.MISTv1()
    atm_func = atmospheres.get_merged_atmosphere
    red_law = reddening.RedLawHosek18b()

    iso = syn.IsochronePhot(logAge,
                            AKs,
                            distance,
                            evo_model=evo,
                            atm_func=atm_func,
                            red_law=red_law,
                            filters=filt_list,
                            mass_sampling=mass_sampling)

    print('Constructed isochrone: %d seconds' % (time.time() - startTime))

    # Now to create the cluster.
    imf_mass_limits = np.array([0.2, 0.5, 1, 120.0])
    imf_powers = np.array([-1.3, -2.3, -2.3])

    # IFMR
    my_ifmr = ifmr.IFMR()

    ##########
    # Start without multiplicity
    ##########
    my_imf1 = imf.IMF_broken_powerlaw(imf_mass_limits,
                                      imf_powers,
                                      multiplicity=None)
    print('Constructed IMF: %d seconds' % (time.time() - startTime))

    cluster1 = syn.ResolvedCluster(iso, my_imf1, cluster_mass, ifmr=my_ifmr)
    clust1 = cluster1.star_systems
    print('Constructed cluster: %d seconds' % (time.time() - startTime))

    # Check that the total mass is within tolerance of input mass
    cluster_mass_out = clust1['systemMass'].sum()
    assert np.abs(cluster_mass_out -
                  cluster_mass) < 200.0  # within 200 Msun of desired mass.
    print('Cluster Mass: IN = ', cluster_mass, " OUT = ", cluster_mass_out)

    ##########
    # Test with multiplicity
    ##########
    multi = multiplicity.MultiplicityUnresolved()
    my_imf2 = imf.IMF_broken_powerlaw(imf_mass_limits,
                                      imf_powers,
                                      multiplicity=multi)
    print('Constructed IMF with multiples: %d seconds' %
          (time.time() - startTime))

    cluster2 = syn.ResolvedCluster(iso, my_imf2, cluster_mass, ifmr=my_ifmr)
    clust2 = cluster2.star_systems
    print('Constructed cluster with multiples: %d seconds' %
          (time.time() - startTime))

    # Check that the total mass is within tolerance of input mass
    cluster_mass_out = clust2['systemMass'].sum()
    assert np.abs(cluster_mass_out -
                  cluster_mass) < 200.0  # within 200 Msun of desired mass.
    print('Cluster Mass: IN = ', cluster_mass, " OUT = ", cluster_mass_out)

    return