def test_calculate_all():
    Mv,  = tangos.get_timestep("sim/ts2").calculate_all("Mvir")
    npt.assert_allclose(Mv,[5,6,7,8])

    Mv, Rv  = tangos.get_timestep("sim/ts1").calculate_all("Mvir", "Rvir")
    npt.assert_allclose(Mv,[1,2,3,4])
    npt.assert_allclose(Rv,[0.1,0.2,0.3,0.4])
Exemplo n.º 2
0
def test_ahf_merger_tree_import():
    importer = tools.ahf_merger_tree_importer.AHFTreeImporter()
    importer.parse_command_line("--for test_ahf_merger_tree".split())
    with log.LogCapturer():
        importer.run_calculation_loop()

    assert (np.array([
        x.finder_offset for x in tangos.get_timestep(
            "test_ahf_merger_tree/tiny_000832").halos.all()
    ]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]).all()
    testing.assert_halolists_equal(
        tangos.get_timestep("test_ahf_merger_tree/tiny.000832").calculate_all(
            "earlier(1)", object_typetag='halo')[0], [
                "test_ahf_merger_tree/tiny.000640/halo_1",
                "test_ahf_merger_tree/tiny.000640/halo_2",
                "test_ahf_merger_tree/tiny.000640/halo_3",
                "test_ahf_merger_tree/tiny.000640/halo_4",
                "test_ahf_merger_tree/tiny.000640/halo_5",
                "test_ahf_merger_tree/tiny.000640/halo_6",
                "test_ahf_merger_tree/tiny.000640/halo_1",
                "test_ahf_merger_tree/tiny.000640/halo_2"
            ])

    assert tangos.get_halo("%/%640/halo_7").next == tangos.get_halo(
        "%/%832/halo_1")

    assert tangos.get_halo("%/%832/halo_1").previous == tangos.get_halo(
        "%/%640/halo_1")
def test_gather_linked_property():
    BH_mass, = tangos.get_timestep("sim/ts1").calculate_all("BH.hole_mass")
    npt.assert_allclose(BH_mass, [100.,200.,300.])

    BH_mass, Mv = tangos.get_timestep("sim/ts1").calculate_all("BH.hole_mass", "Mvir")
    npt.assert_allclose(BH_mass, [100.,200.,300.])
    npt.assert_allclose(Mv, [1.,2.,3.])
def test_gather_function():

    Vv, = tangos.get_timestep("sim/ts1").calculate_all("RvirPlusMvir()")
    npt.assert_allclose(Vv,[1.1,2.2,3.3,4.4])

    Vv, = tangos.get_timestep("sim/ts2").calculate_all("RvirPlusMvir()")
    npt.assert_allclose(Vv,[5.5,6.6,7.7,8.8])
def test_return_nones():
    dbids, masses = tangos.get_timestep("sim/ts3").calculate_all("dbid()","hole_mass")
    assert len(masses)==4 # only the BHs have a hole_mass
    assert len(dbids)==4

    dbids, masses = tangos.get_timestep("sim/ts3").calculate_all("dbid()", "hole_mass", sanitize=False)
    assert len(masses)==7 # BHs + halos all now returning a row
    assert len(dbids)==7
def test_gather_linked_property_with_fn():
    BH_mass, Mv = tangos.get_timestep("sim/ts1").calculate_all('my_BH().hole_mass', "Mvir")
    npt.assert_allclose(BH_mass, [100.,200.,400.])
    npt.assert_allclose(Mv, [1.,2.,3.])

    BH_mass, Mv = tangos.get_timestep("sim/ts1").calculate_all('my_BH("hole_spin").hole_mass', "Mvir")
    npt.assert_allclose(BH_mass, [100.,200.,300.])
    npt.assert_allclose(Mv, [1.,2.,3.])
Exemplo n.º 7
0
def test_calculate_all_object_restriction():
    assert np.all(
        tangos.get_timestep("sim/ts1").calculate_all("dbid()")[0] ==
        [1, 2, 3, 4])
    assert np.all(
        tangos.get_timestep("sim/ts1").calculate_all(
            "dbid()", object_type='halo')[0] == [1, 2])
    assert np.all(
        tangos.get_timestep("sim/ts1").calculate_all(
            "dbid()", object_type='BH')[0] == [3, 4])
Exemplo n.º 8
0
def test_merging():

    source, dest = tangos.get_timestep("sim/ts1").calculate_all("halo_number()","later(2)", object_typetag='halo')
    assert np.all(source==[1,2,3,4,6,7])
    testing.assert_halolists_equal(dest, ['sim/ts3/1', 'sim/ts3/1', 'sim/ts3/2', 'sim/ts3/3', 'sim/ts3/4', 'sim/ts3/4'])

    source, dest = tangos.get_timestep("sim/ts1").calculate_all("halo_number()", "latest()", object_typetag='halo')
    print(source,dest)
    assert np.all(source==[1,2,3,4,5,6,7])
    testing.assert_halolists_equal(dest, ['sim/ts3/1', 'sim/ts3/1', 'sim/ts3/2', 'sim/ts3/3', 'sim/ts1/5',
                                          'sim/ts3/4', 'sim/ts3/4'])
def test_historical_value_finding():
    vals = db.get_halo("sim/ts3/1").calculate_for_progenitors("testval")
    halo = db.get_halo("sim/ts3/1")
    assert_halolists_equal([halo.calculate("find_progenitor(testval, 'max')")], ["sim/ts2/1"])
    assert_halolists_equal([halo.calculate("find_progenitor(testval, 'min')")], ["sim/ts3/1"])

    timestep = db.get_timestep("sim/ts3")
    assert_halolists_equal(timestep.calculate_all("find_progenitor(testval, 'max')")[0], ["sim/ts2/1", "sim/ts3/2"])
    assert_halolists_equal(timestep.calculate_all("find_progenitor(testval, 'min')")[0], ["sim/ts3/1", "sim/ts1/3"])
    assert_halolists_equal(db.get_timestep("sim/ts1").calculate_all("find_descendant(testval, 'min')")[0],
                           ["sim/ts3/1", "sim/ts1/3", "sim/ts1/4", "sim/ts1/5"])
Exemplo n.º 10
0
def test_offset_outputs_dont_confuse_match():
    # This tests for a bug where crosslinked timesteps at slightly different times could confuse the
    # search for a progentior or descendant because the recursive search strayed into a different simulation
    tangos.get_timestep("sim2/ts2").time_gyr *= 1.01
    try:
        ts1_2_next = tangos.get_item("sim/ts2/2").next
        ts1_2_later = tangos.get_item("sim/ts2/2").calculate("later(1)")
        correct = ["sim/ts3/1"]
        testing.assert_halolists_equal([ts1_2_next], correct)
        testing.assert_halolists_equal([ts1_2_later], correct)
    finally:
        tangos.get_timestep("sim2/ts2").time_gyr /= 1.01
Exemplo n.º 11
0
def test_crosslinking():
    cl = crosslink.CrossLinker()
    cl.parse_command_line(["dummy_sim_2","dummy_sim_1"])

    with log.LogCapturer():
        assert cl.need_crosslink_ts(db.get_timestep("dummy_sim_1/step.1"), db.get_timestep("dummy_sim_2/step.1"))
        cl.run_calculation_loop()
        assert not cl.need_crosslink_ts(db.get_timestep("dummy_sim_1/step.1"), db.get_timestep("dummy_sim_2/step.1"))

    assert db.get_halo('dummy_sim_1/step.1/1').calculate('match("dummy_sim_2").dbid()')==db.get_halo('dummy_sim_2/step.1/1').id
    assert db.get_halo('dummy_sim_2/step.2/3').calculate('match("dummy_sim_1").dbid()') == db.get_halo(
        'dummy_sim_1/step.2/3').id

    with assert_raises(live_calculation.NoResultsError):
        result = db.get_halo('dummy_sim_2/step.3/1').calculate('match("dummy_sim_1").dbid()')
Exemplo n.º 12
0
def test_NDM_cut(fresh_database_no_contents):
    manager = add_simulation.SimulationAdderUpdater(
        output_testing.TestInputHandlerReverseHaloNDM("dummy_sim_2"))
    manager.min_halo_particles = 2005
    manager.scan_simulation_and_add_all_descendants()
    ndm, = db.get_timestep("dummy_sim_2/step.1").calculate_all("NDM()")
    assert ndm.min() == 2005
Exemplo n.º 13
0
def test_earlier():
    ts3_halos, ts1_halos = tangos.get_timestep("sim/ts3").calculate_all(
        'dbid()', 'earlier(2).dbid()')
    testing.assert_halolists_equal(
        ts1_halos, ['sim/ts1/1', 'sim/ts1/2', 'sim/ts1/3', 'sim/ts1/1.1'])
    testing.assert_halolists_equal(
        ts3_halos, ['sim/ts3/1', 'sim/ts3/2', 'sim/ts3/3', 'sim/ts3/1.1'])
Exemplo n.º 14
0
def test_gather_function_fails():
    with npt.assert_raises(KeyError):
        # The following should fail.
        # If it does not raise a keyerror, the live calculation has ignored the directive
        # to only load in the named properties.
        Vv, = tangos.get_timestep("sim/ts1").calculate_all(
            "RvirPlusMvirMiscoded()")
Exemplo n.º 15
0
def test_setup():
    ndm_test = [[x.NDM for x in tangos.get_timestep(ts).halos] for ts in range(1,6)]
    assert np.all(ndm_test[0] == [1000, 600])
    assert np.all(ndm_test[1] == [1000, 600])
    assert np.all(ndm_test[2] == [900, 700])
    assert np.all(ndm_test[3] == [935, 665])
    assert np.all(ndm_test[4] == [1600])
Exemplo n.º 16
0
def test_histogram_written_as_expected():
    dumhistprop = DummyHistogramProperty(db.get_simulation("sim"))
    ts1 = db.get_timestep("sim/ts1")
    ts2 = db.get_timestep("sim/ts2")
    ts1_h1 = db.get_halo("sim/ts1/1")
    ts1_h2 = db.get_halo("sim/ts1/2")
    ts2_h1 = db.get_halo("sim/ts2/1")
    npt.assert_almost_equal(
        ts1_h1.calculate('raw(dummy_histogram)'),
        test_histogram[dumhistprop.store_slice(ts1.time_gyr)])
    npt.assert_almost_equal(
        ts1_h2.calculate('raw(dummy_histogram)'),
        test_histogram[dumhistprop.store_slice(ts1.time_gyr)] * 0.5)
    npt.assert_almost_equal(
        ts2_h1.calculate('raw(dummy_histogram)'),
        test_histogram[dumhistprop.store_slice(ts2.time_gyr)])
Exemplo n.º 17
0
def test_multi_calculation_link_returned_halo_is_usable():
    all_links = db.get_timestep("sim/ts1").calculate_all('link(testlink)')
    assert all_links[0][0]['testval'] == 1.0

    all_links = db.get_halo("sim/ts1/1").calculate_for_progenitors(
        'link(testlink)')
    assert all_links[0][0]['testval'] == 1.0
Exemplo n.º 18
0
def test_load_persistence():
    f = db.get_timestep("test_tipsy/tiny.000640").load()
    f2 = db.get_timestep("test_tipsy/tiny.000640").load()
    h = db.get_halo("test_tipsy/tiny.000640/1").load()
    h_tracker = db.get_halo("test_tipsy/tiny.000640/tracker_1").load()
    assert id(f) == id(f2)
    assert id(h.ancestor) == id(f)
    assert id(h_tracker.ancestor) == id(f)

    old_id = id(f)

    del f, f2, h, h_tracker
    gc.collect()

    f3 = db.get_timestep("test_tipsy/tiny.000640").load()
    assert id(f3) != old_id
Exemplo n.º 19
0
def plt_BHMStar(simname, step, marker='o', size = 100, color='blue', label=None, fit=True, fiterr=True, remove_sats=True, alpha=1.0):
    from .. import plotting
    import tangos as db
    print "getting data from database..."
    bhdata, Mstar, cen, Rvir, Mvir = db.get_timestep(simname+'/%'+step).gather_property('bh().BH_mass', 'Mstar', 'SSC', 'Rvir', 'Mvir')
    sats = np.zeros(len(Mstar))
    if remove_sats is True:
        for i in range(len(Mstar)):
            D = np.sqrt(np.sum((cen[i] - cen)**2,axis=1))
            close = np.where((D>0)&(D<Rvir)&(Mvir[i]<Mvir))[0]
            if len(close)>0:
                sats[i] = 1
        ok = np.where(sats==0)
        Mstar = Mstar[ok]
        bhdata = bhdata[ok]
    plotting.plt.scatter(Mstar*0.6, bhdata, marker=marker, s=size, color=color, label=label, alpha=alpha)
    if fit is True:
        lmstar = np.arange(np.log10(Mstar[(Mstar > 0)]).min() - 1., np.log10(Mstar[(Mstar > 0)]).max() + 1., 0.1)
        bhmass = BHMstar(lmstar)
        plotting.plt.plot(10**lmstar, 10**bhmass,'k-', label='Schramm+Silverman 13',lw=2)
        if fiterr is True:
            plotting.plt.fill_between(10**lmstar,10**(bhmass+0.3),10**(bhmass-0.3),color='Grey',alpha=0.5)

    plotting.plt.yscale('log',base=10)
    plotting.plt.xscale('log',base=10)
    plotting.plt.legend(loc='upper left',fontsize=25)
    plotting.plt.ylabel(r"M$_{BH}$ [M$_{\odot}$]")
    plotting.plt.xlabel(r"M$_{\star}$ [M$_{\odot}$]")
Exemplo n.º 20
0
def test_custom_delta_t():
    try:
        db.get_simulation("sim")["histogram_delta_t_Gyr"] = 0.01
        reconstructed_lc = db.get_halo("sim/ts2/1").calculate("reassemble(dummy_histogram, 'place')")
        assert len(reconstructed_lc) == int(db.get_timestep("sim/ts2").time_gyr/0.01)
    finally:
        # restore to default
        db.get_simulation("sim")["histogram_delta_t_Gyr"] = DummyHistogramProperty.pixel_delta_t_Gyr
Exemplo n.º 21
0
def test_earlier_equal_weight():
    """Regression test for problem where earlier(x) or later(x) failed when there was more than one link
    with the identical same weight, meaning the major progenitor was undefined. Now the match is
    disambiguiated by looking for the link with the highest primary key (not very physical, but at least
    unambiguous)."""
    ts5_halo, ts4_halo = tangos.get_timestep("sim/ts5").calculate_all("dbid()","earlier(1).dbid()")
    testing.assert_halolists_equal(ts5_halo, ['sim/ts5/1'])
    assert testing.halolists_equal(ts4_halo, ['sim/ts4/1']) or testing.halolists_equal(ts4_halo, ['sim/ts4/2'])
Exemplo n.º 22
0
def test_load_region():
    region = db.get_timestep("test_tipsy/tiny.000640").load_region(
        pynbody.filt.Sphere(2000, [1000, 1000, 1000]))
    assert (region['iord'] == [
        9980437, 10570437, 10630437, 10640437, 10770437, 10890437, 10900437,
        10960437, 11030437, 11090437, 11480437, 11490437, 11550437, 11740437,
        12270437, 12590437, 12600437, 12920437, 13380437, 13710437
    ]).all()
Exemplo n.º 23
0
def test_earlier_equal_weight():
    """Regression test for problem where earlier(x) or later(x) failed when there was more than one link
    with the identical same weight, meaning the major progenitor was undefined. An interim fix picks one or the
    other possibility, so that at least the code does not crash. However, a better long-term solution should
    be found - see TODO in multi_source.py"""
    ts5_halo, ts4_halo = tangos.get_timestep("sim/ts5").calculate_all("dbid()","earlier(1).dbid()")
    testing.assert_halolists_equal(ts5_halo, ['sim/ts5/1'])
    assert testing.halolists_equal(ts4_halo, ['sim/ts4/1']) or testing.halolists_equal(ts4_halo, ['sim/ts4/2'])
Exemplo n.º 24
0
def test_gather_restricted_object_type():
    ts = tangos.get_timestep("sim/ts1")
    non_existent, = ts.calculate_all("hole_mass", object_typetag='halo')
    assert len(non_existent)==0
    ok_1, = ts.calculate_all("hole_mass",object_typetag='BH')
    ok_2, = ts.calculate_all("hole_mass")
    npt.assert_allclose(ok_1, [100., 200., 300., 400.])
    npt.assert_allclose(ok_2, [100., 200., 300., 400.])
Exemplo n.º 25
0
def test_unresolvable_proxy_object():
    incomplete = po.IncompleteProxyObjectFromFinderId(10, 'halo')
    assert incomplete.relative_to_timestep_id(1).resolve(
        tangos.get_default_session()) is None

    cache = toc.TimestepObjectCache(tangos.get_timestep('sim/ts1'))
    assert incomplete.relative_to_timestep_cache(cache).resolve(
        tangos.get_default_session()) is None
Exemplo n.º 26
0
def test_consistent_tree_import():
    importer = tools.consistent_trees_importer.ConsistentTreesImporter()
    importer.parse_command_line(
        "--for test_gadget_rockstar --with-ids".split())
    with log.LogCapturer():
        importer.run_calculation_loop()
    assert (
        tangos.get_timestep("test_gadget_rockstar/snapshot_014").calculate_all(
            "consistent_trees_id",
            object_typetag='halo')[0] == [17081, 19718, 19129]).all()
    testing.assert_halolists_equal(
        tangos.get_timestep("test_gadget_rockstar/snapshot_014").calculate_all(
            "earlier(1)", object_typetag='halo')[0], [
                "test_gadget_rockstar/snapshot_013/halo_2",
                "test_gadget_rockstar/snapshot_013/halo_4"
            ])

    assert tangos.get_halo("%/%13/halo_1").next == tangos.get_halo(
        "%/%14/phantom_1")
Exemplo n.º 27
0
 def get_tnext(self):
     import tangos as db
     self.data['time_next'] = np.ones(len(self.data['time']))*-1
     self.data['redshift_next'] = np.ones(len(self.data['time']))*-1
     for ii in range(len(self.data['time'])):
         if ii % 100 == 0:
             print float(ii)/float(len(self.data['time'])) * 100, "% done"
         step = db.get_timestep(self.data['dbstep'][ii])
         self.data['time_next'][ii] = step.next.time_gyr
         self.data['redshift_next'][ii] = step.next.redshift
Exemplo n.º 28
0
def test_update_simulation():
    with testing.autorevert():
        assert db.get_simulation("dummy_sim_1")['dummy_sim_property_2'] == 'banana'
        _perform_simulation_update()
        assert db.get_simulation("dummy_sim_1").properties.count() == 4
        assert db.get_simulation("dummy_sim_1")['dummy_sim_property_2']=='orange'
        assert db.get_simulation("dummy_sim_1")['dummy_sim_property_new'] == 'fruits'
        assert len(db.get_simulation("dummy_sim_1").timesteps) == 3
        assert db.get_timestep("dummy_sim_1/step.3").halos.count()==7
    assert db.get_simulation("dummy_sim_1")['dummy_sim_property_2'] == 'banana'
Exemplo n.º 29
0
def _multiprocess_test():

    time.sleep(0.5)

    ts = tangos.get_timestep("sim/ts1")

    new_halo = tangos.core.halo.Halo(ts, 6, 0, 0, 0, 0)

    db.core.get_default_session().merge(new_halo)

    db.core.get_default_session().commit()
Exemplo n.º 30
0
def test_property_import():
    importer = tools.property_importer.PropertyImporter()
    importer.parse_command_line(
        "X Y Z Mvir --for test_gadget_rockstar".split())
    with log.LogCapturer():
        parallel_tasks.use('multiprocessing')
        parallel_tasks.launch(importer.run_calculation_loop, 2)

    Mvir_test, = tangos.get_timestep(
        "test_gadget_rockstar/snapshot_013").calculate_all("Mvir")
    npt.assert_allclose(
        Mvir_test, [1.160400e+13, 8.341900e+12, 5.061400e+12, 5.951900e+12])
Exemplo n.º 31
0
def _multiprocess_block():

    session = db.core.get_default_session()

    ts = tangos.get_timestep("sim/ts1")
    new_halo = tangos.core.halo.Halo(ts, 5, 0, 0, 0, 0)

    session.merge(new_halo)
    session.flush()

    time.sleep(1.0)

    session.commit()
Exemplo n.º 32
0
def _multiprocess_test():
    session = db.core.get_default_session()

    time.sleep(0.5)

    ts = tangos.get_timestep("sim/ts1")

    tangos.core.creator.get_creator(session) # this stops a warning being issued if the creator object is created during creation of Halo
    new_halo = tangos.core.halo.Halo(ts, 6, 6, 6, 0, 0, 0, 0)

    session.add(new_halo)

    session.commit()
Exemplo n.º 33
0
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import tangos as db
import pynbody 
from matplotlib import rc
import gc

#Halo numbers
#numbers =  [18, 23, 24, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 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, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 151, 152, 153, 154, 155, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 186, 187, 188, 189, 190, 191, 192, 193, 194, 196, 197, 198, 199, 200, 201, 202, 204, 206, 207, 208, 209, 210, 213, 214, 215, 216]
numbers = [38]

#Simulation data
sim = db.get_simulation('cosmo25')
step1 = db.get_timestep('cosmo25%/%8192')
s = pynbody.load('/oasis/scratch/comet/mjt29/temp_project/Romulus25/cosmo25p.768sg1bwK1BHe75.008192')
s.physical_units()
gal = s.halos(dosort=True)

#Skirt data & comparison data
data =  np.genfromtxt('skirt_faceon.dat', names = ['halo', 'IRX', 'beta', 'neg_ebeta', 'pos_ebeta', 'intercept', 'neg_eint', 'pos_eint'])
#data = data_angles[data_angles['angle'] == 90.]
compare_data = np.genfromtxt('BF_IRXBdata_comparison.dat', names = ['IRX', 'e_IRX', 'beta', 'e_beta'], skip_header =11)

#Fit from Forrest et al.
B = np.linspace(-2.5, 2.5, 100)
y = np.log10(10**(0.4*(5.05 + 2.39*B)) - 1) + np.log10(1.68)

#Grabbing my variables
halomvir = []
Exemplo n.º 34
0
def SMHM_db(sim, step, style, fitstyle=['c-','r-'], fit=['Mos', 'Krav'], minmass=None,
            maxmass=None, markersize=5,label=None, correct=True, error=True, return_subs=False, remove_sats=True, contam_limit=None):
    import tangos as db
    step = db.get_timestep(sim+'/%'+str(step))
    if contam_limit:
        Mvir, Mstar, Rvir, cen, contam = step.gather_property('Mvir', 'Mstar', 'Rvir','SSC','contamination_fraction')
        ok = np.where(contam<contam_limit)
        Mvir = Mvir[ok]
        Mstar = Mstar[ok]
        Rvir = Rvir[ok]
        cen = cen[ok]
    else:
        Mvir, Mstar, Rvir, cen = step.gather_property('Mvir', 'Mstar', 'Rvir','SSC')
    if remove_sats is True or return_subs is True:
        sub = np.zeros(len(Mstar))
        for i in range(len(Mvir)):
            int = np.where((np.sqrt(np.sum((cen[i] - cen)**2,axis=1))<Rvir)&(np.sum((cen[i] - cen)**2,axis=1)>0)&(Mvir[i]<Mvir))
            if len(int[0])>0:
                sub[i] = 1
        if remove_sats is True:
            ok = np.where(sub==0)
            Mvir = Mvir[ok]
            Mstar = Mstar[ok]
            Rvir = Rvir[ok]

    if correct is True:
        Mstar *= 0.6
        Mvir /= 0.8

    plotting.plt.plot(Mvir, Mstar/Mvir, style, markersize=markersize, label=label,zorder=1)

    if minmass is None:
        minmass = Mvir.min()/2.
    if maxmass is None:
        maxmass = Mvir.max()*2.

    cnt = 0
    logmv_fit = np.arange(np.log10(minmass),np.log10(maxmass),0.1)
    if fit is not None:
        for ff in fit:
            if ff not in ['Mos','Beh', 'Krav', 'Moster', 'Behroozi', 'Kravtsov']:
                print "fit request ", ff, " not understood... should be in list", \
                    ['Mos','Beh', 'Krav', 'Moster', 'Behroozi', 'Kravtsov']
                continue
            print "found fit relation for", ff

            if ff in ['Mos', 'Moster']:
                fitfunc = moster13
                flabel = 'Moster+ 13'
            if ff in ['Beh', 'Behroozi']:
                fitfunc = behroozi13
                flabel = 'Behroozi+ 13'
            if ff in ['Krav', 'Kravtsov']:
                fitfunc = kravstov14
                flabel = 'Kravtsov+ 14'

            ratio_fit = fitfunc(logmv_fit, step.redshift)
            plotting.plt.plot(10**logmv_fit, ratio_fit, fitstyle[cnt], label=flabel, lw=5,alpha=0.75,zorder=10)
            if ff in ['Mos','Moster'] and error is True:
                sigma = errmoster13(logmv_fit, step.redshift)
                plotting.plt.fill_between(10**logmv_fit,ratio_fit-sigma,ratio_fit+sigma,facecolor='grey',
                                          edgecolor='k', lw=1.5, alpha=0.5,zorder=10)

            cnt += 1

    plotting.plt.ylabel(r'M$_{*}$/M$_{vir}$')
    plotting.plt.xlabel(r'M$_{vir}$ [M$_{\odot}$]')
    plotting.plt.legend(loc='lower right',fontsize=25)
    plotting.plt.yscale('log',base=10)
    plotting.plt.xscale('log',base=10)
    plotting.plt.xlim(minmass, maxmass)

    if return_subs:
        return sub
Exemplo n.º 35
0
def SMHM(sim, step, style, color, fitstyle=['k-','k--'], fit=['Mos', 'Krav'], minmass=None, maxmass=None,
         markersize=5,label=None, correct=True, usedb=False, remove_sats=True, only_sats=False, error=True, alpha=1.0,
         remove_sats_hard=False, boxsize=25, ret_data=False):
    if usedb is True:
        import tangos as db
        dbstep = db.get_timestep(sim+'/%'+step)
        if remove_sats or only_sats:
            Mvir, Mstar, sub = dbstep.gather_property('Mvir', 'Mstar', 'Sub')
            if len(Mvir)==0:
                print "Warning Sub halos not implemented yet in your database! " \
                      "please turn off sats options or re-run with usedb False"
                return
        else:
            Mvir, Mstar = dbstep.gather_property('Mvir', 'Mstar')
        redshift = dbstep.redshift
    else:
        amigastat, redshift, type = getstats(sim, step)
        Mvir = amigastat['Mvir(M_sol)'].astype(np.float)
        Mstar = amigastat['StarMass(M_sol)'].astype(np.float)
        Mgas = amigastat['GasMass(M_sol)'].astype(np.float)
        xC = amigastat['Xc'].astype(np.float)
        yC = amigastat['Yc'].astype(np.float)
        zC = amigastat['Zc'].astype(np.float)
        Rvir = amigastat['Rvir(kpc)'].astype(np.float)
        grp = amigastat['Grp'].astype(np.int64)

        if minmass is None:
            minmass = Mvir.min()/2.
        if maxmass is None:
            maxmass = Mvir.max()*2.

        if remove_sats is True:
            if type == 'rockstar':
                ok, = np.where(amigastat['Satellite?'] == -1)
            if type == 'amiga':
                ok, = np.where(amigastat['Satellite?'] == 'no')
        if remove_sats_hard is True:
            satsarray = np.zeros(len(amigastat['Grp']))
            for i in range(len(amigastat['Grp'])):
                if Mvir[i] < minmass or Mvir[i] > maxmass:
                    continue
                xd = xC[i] - xC
                yd = yC[i] - yC
                zd = zC[i] - zC
                oo = np.where(np.abs(xd) > boxsize*1e3/2.)[0]
                xd[oo] = -1.0 * (xd[oo]/np.abs(xd[oo])) * (boxsize*1e3 - np.abs(xd[oo]))
                oo = np.where(np.abs(yd) > boxsize*1e3/2.)[0]
                yd[oo] = -1.0 * (yd[oo]/np.abs(yd[oo])) * (boxsize*1e3 - np.abs(yd[oo]))
                oo = np.where(np.abs(zd) > boxsize*1e3/2.)[0]
                zd[oo] = -1.0 * (zd[oo]/np.abs(zd[oo])) * (boxsize*1e3 - np.abs(zd[oo]))

                dist = np.sqrt(xd**2 + yd**2 + zd**2)
                bad = np.where((dist*1e3<2*(Rvir+Rvir[i]))&(0.5*Mvir[i]<Mvir)&(grp[i] != grp))[0]
                if len(bad)>0 or Mgas[i]==0:
                    satsarray[i] = 1
            if type == 'rockstar':
                ok = np.where((satsarray==0)&(amigastat['Satellite?']==-1))[0]
            if type == 'amiga':
                ok = np.where((satsarray==0)&(amigastat['Satellite?']=='no'))[0]
        if only_sats is True:
            if type == 'rockstar':
                ok, = np.where(amigastat['Satellite?'] != -1)
            if type == 'amiga':
                ok, = np.where(amigastat['Satellite?'] == 'yes')
        if only_sats is True or remove_sats is True or remove_sats_hard:
            Mvir = Mvir[ok]
            Mstar = Mstar[ok]
            grp = grp[ok]

    if correct is True:
        Mstar *= 0.6
        Mvir /= 0.8

    if minmass is None:
        minmass = Mvir.min()/2.
    if maxmass is None:
        maxmass = Mvir.max()*2.

    logmv_fit = np.arange(np.log10(minmass),np.log10(maxmass),0.1)
    cnt = 0
    plotting.plt.plot(Mvir, Mstar/Mvir, style, color=color, markersize=markersize, label=label, alpha=alpha,zorder=1)
    if fit is not None:
        for ff in fit:
            if ff not in ['Mos','Beh', 'Krav', 'Moster', 'Behroozi', 'Kravtsov']:
                print "fit request ", ff, " not understood... should be in list", \
                    ['Mos','Beh', 'Krav', 'Moster', 'Behroozi', 'Kravtsov']
                continue
            print "found fit relation for", ff

            if ff in ['Mos', 'Moster']:
                fitfunc = moster13
                flabel = 'Moster+ 13, z = %0.2f' % (redshift)
            if ff in ['Beh', 'Behroozi']:
                fitfunc = behroozi13
                flabel = 'Behroozi+ 13, z = %0.2f' % (redshift)
            if ff in ['Krav', 'Kravtsov']:
                fitfunc = kravstov14
                flabel = 'Kravtsov+ 14, z < 0.1'

            ratio_fit = fitfunc(logmv_fit, redshift)
            plotting.plt.plot(10**logmv_fit, ratio_fit, fitstyle[cnt], label=flabel, lw=5,alpha=0.75,zorder=10)
            if ff in ['Mos', 'Moster'] and error is True:
                sigma = errmoster13(logmv_fit, redshift)
                plotting.plt.fill_between(10**logmv_fit,ratio_fit-sigma,ratio_fit+sigma, facecolor='grey',
                                          edgecolor='k', lw=1.5, alpha=0.5,zorder=10)

            cnt += 1

    plotting.plt.ylabel(r'M$_{*}$/M$_{vir}$')
    plotting.plt.xlabel(r'M$_{vir}$ [M$_{\odot}$]')
    plotting.plt.legend(loc='lower right',fontsize=25)
    plotting.plt.yscale('log',base=10)
    plotting.plt.xscale('log',base=10)
    plotting.plt.xlim(minmass, maxmass)

    if ret_data:
        return Mvir, Mstar, grp