Пример #1
0
def run_slow_burst_models():
    """
	Runs the slow burst models.
	"""
    kwargs = {
        "schmidt": True,
        "schmidt_index": 0.5,
        "dt": _TIMESTEP_,
        "bins": bins[:]
    }
    sz1 = vice.singlezone(name="simulations/slowburst_episodic_infall",
                          func=slow_gaussian_generator(
                              lambda t: 10 * t**2 * m.exp(-t / 2.2), 12, 60,
                              1),
                          Mg0=0,
                          **kwargs)
    print(sz1)
    sz1.run(_SLOWBURST_TIMES_[:], overwrite=True)
    sz1.name = "simulations/episodic_infall"
    sz1.func = lambda t: 10 * t**2 * m.exp(-t / 2.2)
    print(sz1)
    sz1.run(_SLOWBURST_TIMES_[:], overwrite=True)
    sz2 = vice.singlezone(name="simulations/slowburst_constant",
                          func=slow_gaussian_generator(lambda t: 5, 12, 15, 1),
                          mode="sfr",
                          **kwargs)
    print(sz2)
    sz2.run(_SLOWBURST_TIMES_[:], overwrite=True)
    sz2.name = "simulations/constant"
    sz2.func = lambda t: 5
    print(sz2)
    sz2.run(_SLOWBURST_TIMES_[:], overwrite=True)
Пример #2
0
def single_burst(which, generator, *gen_args, **kwargs):
    """
	Runs a gas- or efficiency driven starburst simulation given a generator,
	parameters to pass to that generator, and keyword args to pass as
	attributes to vice.singlezone

	Parameters
	==========
	which :: str
		Either "func" or "tau_star" - the attribute to assign the function to
	generator :: <function>
		One of the two generators to use
	gen_args :: real numbers
		The parameters to pass to the generator function
	kwargs :: varying types
		Other keyword args to pass as attributes to a vice.singlezone object
	"""
    kwargs[which] = generator(*gen_args)
    outtimes = _TIMES_[:]
    for i in range(9):
        """
		Force output to be written for the next 9 timesteps. The 10th is
		taken care of automatically given how we're defining the timestep size
		and output times
		"""
        outtimes.append(gen_args[0] * (i + 1) * kwargs["dt"])
    sz = vice.singlezone(**kwargs)
    print(sz)
    sz.run(outtimes[:], overwrite=True)
Пример #3
0
def get_integrator(): 
	"""
	Get an instance of VICE's singlezone integrator. 
	"""
	sz = vice.singlezone(name = sys.argv[1]) 
	sz.tau_star = tau_star 
	return sz 
Пример #4
0
def run_simulation(args):
	r"""
	Runs the simulation according to the arguments passed on the command line.
	
	Parameters
	----------
	args : argparse.Namespace
		The command line arguments parsed via argparse.
	"""

	# Stitch together the evolutionary function of time
	if args.timedep == "constant":
		function = lambda t: args.normalization
	elif args.timedep == "exp":
		function = lambda t: args.normalization * m.exp(-t / args.timescale)
	elif args.timedep == "linexp":
		function = lambda t: args.normalization * t * m.exp(-t / args.timescale)
	else:
		raise ValueError("Unrecognized time dependence: %s" % (args.timedep))

	# keyword args to vice.singlezone
	params = dict(
		name = args.name,
		func = function,
		mode = args.mode,
		elements = [i.lower() for i in args.elements.split('_')],
		IMF = args.IMF,
		eta = args.eta,
		enhancement = args.enhancement,
		delay = args.delay,
		RIa = args.RIa,
		Mg0 = args.Mg0,
		smoothing = args.smoothing,
		tau_ia = args.tau_ia,
		tau_star = args.tau_star,
		dt = args.dt,
		verbose = args.verbose,
		recycling = "continuous" if args.recycling < 0 else args.recycling,
		schmidt = args.schmidt,
		MgSchmidt = args.MgSchmidt,
		schmidt_index = args.schmidt_index,
		postMS = args.postMS
	)

	outtimes = [i * args.dt for i in range(int(args.end / args.dt) + 1)]
	vice.singlezone(**params).run(outtimes, overwrite = args.force)
Пример #5
0
def cc_settings_assertions(x):
    if isinstance(x, numbers.Number):
        pass_ = True
    elif callable(x):
        if not singlezone()._singlezone__args(x):
            pass_ = True
        else:
            pass_ = False
    else:
        pass_ = False
    assert pass_
Пример #6
0
def run_kirby2010_comparisons():
    """
	Runs the models intended for comparison with the Kirby et al. (2010)
	data in the Appendix of Johnson & Weinberg (2020).
	"""
    kwargs = {
        "dt": _TIMESTEP_,
        "bins": bins[:],
        "Mg0": 0,
        "tau_star": 10,
        "eta": 30,
        "elements": ["fe", "sr", "mg"],
        "enhancement": 3
    }
    sz1 = vice.singlezone(name="simulations/kirby2010_smooth",
                          func=lambda t: 9.1 * m.exp(-t / 2),
                          **kwargs)
    print(sz1)
    sz1.run(_TIMES_, overwrite=True)
    sz1.name = "simulations/kirby2010_smooth_enh1"
    sz1.enhancement = 1
    print(sz1)
    sz1.run(_TIMES_, overwrite=True)

    def exp_with_burst(t):
        if 5. <= t < 5. + _TIMESTEP_:
            return 5 / _TIMESTEP_
        else:
            return 9.1 * m.exp(-t / 2)

    sz2 = vice.singlezone(name="simulations/kirby2010_burst",
                          func=exp_with_burst,
                          **kwargs)
    print(sz2)
    outtimes = _TIMES_[:]
    for i in range(10):
        outtimes.append(5. + (i + 1) * _TIMESTEP_)
    sz2.run(outtimes[:], overwrite=True)
Пример #7
0
def oscillatory(mean, amplitude, period, which, **kwargs):
    """
	Runs a simulation in which a singlezone parameter oscillates with time,
	emulating a series of minor episodic starbursts

	Parameters
	==========
	mean :: real number
		The mean of the function
	amplitude :: real number
		The amplitude of the oscillations
	period :: real number
		The period of the oscillations in Gyr
	which :: str
		either "func" or "tau_star" - the attribute to assign the function to
	kwargs :: varying types
		Other keywords to pass to vice.singlezone as attributes
	"""
    kwargs[which] = lambda t: mean + amplitude * m.sin(2 * m.pi * t / period)
    if which == "func": kwargs["mode"] = "sfr"
    sz = vice.singlezone(**kwargs)
    print(sz)
    sz.run(_ALL_TIMES_[:], overwrite=True)  # output at all times needed
Пример #8
0
def main():
    """
	Runs the tests on the singlezone object, the output object, and the 
	mirror function. 
	"""
    warnings.filterwarnings("ignore")
    print("=================================================================")
    print("TESTING: vice.singlezone")
    print("         vice.output")
    print("         vice.mirror")
    out = open("test_sz_output_mirror.out", 'w')
    _MODES_ = ["ifr", "sfr", "gas"]
    _IMF_ = ["kroupa", "salpeter"]
    _ETA_ = [2.5, lambda t: 2.5 * math.exp(-t / 4.0)]
    _ZIN_ = [
        0, 1.0e-8, lambda t: 1.0e-8 * (t / 10.0), {
            "o": lambda t: 0.0057 * (t / 10.0),
            "fe": 0.0013
        }
    ]
    _RECYCLING_ = ["continuous", 0.4]
    _RIA_ = ["plaw", "exp", lambda t: t**-1.5]
    _TAU_STAR_ = [2.0, lambda t: 2.0 + t / 10.0]
    _SCHMIDT_ = [False, True]
    _AGB_MODEL_ = ["cristallo11", "karakas10"]

    a = 0
    b = 2304
    keys = ["success", "failure"]
    singlezone_tracker = dict(zip(keys, [0, 0]))
    mirror_tracker = dict(zip(keys, [0, 0]))
    output_tracker = dict(zip(keys, [0, 0]))
    history_tracker = dict(zip(keys, [0, 0]))
    mdf_tracker = dict(zip(keys, [0, 0]))
    for i in _MODES_:
        for j in _IMF_:
            for k in _ETA_:
                for l in _ZIN_:
                    for m in _RECYCLING_:
                        for n in _RIA_:
                            for o in _TAU_STAR_:
                                for p in _SCHMIDT_:
                                    for q in _AGB_MODEL_:
                                        metadata = dict(
                                            elements=["fe", "o", "c"],
                                            mode=i,
                                            IMF=j,
                                            eta=k,
                                            Zin=l,
                                            recycling=m,
                                            RIa=n,
                                            tau_star=o,
                                            schmidt=p,
                                            agb_model=q,
                                            dt=0.05)
                                        try:
                                            vice.singlezone(**metadata).run(
                                                _OUTTIMES_, overwrite=True)
                                            singlezone_tracker["success"] += 1
                                        except:
                                            singlezone_tracker["failure"] += 1
                                        try:
                                            foo = vice.history("onezonemodel")
                                            assert isinstance(
                                                foo, vice.dataframe)
                                            history_tracker["success"] += 1
                                        except:
                                            history_tracker["failure"] += 1
                                        try:
                                            foo = vice.mdf("onezonemodel")
                                            assert isinstance(
                                                foo, vice.dataframe)
                                            mdf_tracker["success"] += 1
                                        except:
                                            mdf_tracker["failure"] += 1
                                        success = True
                                        try:
                                            foo = vice.output("onezonemodel")
                                            assert isinstance(foo, vice.output)
                                            assert isinstance(
                                                foo.history, vice.dataframe)
                                            assert isinstance(
                                                foo.mdf, vice.dataframe)
                                            assert isinstance(
                                                foo.ccsne_yields,
                                                vice.dataframe)
                                            assert isinstance(
                                                foo.sneia_yields,
                                                vice.dataframe)
                                            assert isinstance(
                                                foo.elements, tuple)
                                            output_tracker["success"] += 1
                                            try:
                                                mir = vice.mirror(foo)
                                                assert isinstance(
                                                    mir, vice.singlezone)
                                                mirror_tracker["success"] += 1
                                            except:
                                                mirror_tracker["failure"] += 1
                                        except:
                                            output_tracker["failure"] += 1

                                        a += 1
                                        sys.stdout.write("Progress: %.1f%%\r" %
                                                         (a / b * 100))
                                        sys.stdout.flush()

    #######
    message = """\
vice.singlezone :: %d successes :: %d failures 
vice.history :: %d successes :: %d failures 
vice.mdf :: %d successes :: %d failures 
vice.output :: %d successes :: %d failures 
vice.mirror :: %d successes :: %d failures \
""" % (singlezone_tracker["success"], singlezone_tracker["failure"],
       history_tracker["success"], history_tracker["failure"],
       mdf_tracker["success"], mdf_tracker["failure"],
       output_tracker["success"], output_tracker["failure"],
       mirror_tracker["success"], mirror_tracker["failure"])
    print(message)
    out.write(message)
    out.close()
Пример #9
0
3) 			The name of the output file
"""

import numpy as np
import vice
import time
import sys
import os

with open(sys.argv[3], 'w') as f:
	print("Timing VICE for N = %d elements..." % (int(sys.argv[1])))

	# write the header
	f.write("# Number of elements: %d\n" % (int(sys.argv[1])))
	f.write("# 1) Timestep Size [Gyr]\n")
	f.write("# 2) Execution time of a 10 Gyr simulation [sec]\n")

	# start at .05 and divide by a small amount until .0005
	dt = 5.e-2
	while dt >= 5.e-4:
		start = time.time()
		vice.singlezone(name = sys.argv[2],
			elements = vice._globals._RECOGNIZED_ELEMENTS_[:int(sys.argv[1])],
			dt = dt).run(np.linspace(0, 10, 201), overwrite = True)
		stop = time.time()
		print("dt = %.5e | T_exec = %.5e seconds" % (dt, stop - start))
		f.write("%.5e\t%.5e\n" % (dt, stop - start))
		dt /= 1.01
	f.close()

Пример #10
0
		Normalization :: the value of the exponential at t = 0 
		timescale :: the e-folding timescale of the parameter 
		"""

        # Store them as attributes like so
        self._norm = normalization
        self._tau = timescale

    def __call__(self, time):
        """ 
		To make your class callable, give it a __call__ function. This should 
		always take self as the first argument, even if this is going to be a 
		function of only one variable, which we're denoting as time. 
		"""
        return self._norm * m.exp(-time / self._tau)


sz = vice.singlezone()

# Infall rate of 9.1 Msun/yr with an e-folding timescale of 6 Gyr
sz.func = exponential_decay(9.1, 6)
sz.mode = "ifr"

# mass loading factor of 3 with an e-folding timescale of 4 Gyr
sz.eta = exponential_decay(3, 4)

# A SN Ia delay time distribution with an e-folding timescale of 1.2 Gyr
sz.RIa = exponential_decay(1, 1.2)

print(sz)