zblz / naima

Derivation of non-thermal particle distributions through MCMC spectral fitting
http://naima.readthedocs.io
BSD 3-Clause "New" or "Revised" License
43 stars 54 forks source link

freeze parameters #158

Closed nuk34 closed 2 years ago

nuk34 commented 6 years ago

Hi Victor, I am afraid this is a stupid question, but I haven't found a solution... I want to pass a parameter to my model which is not fitted (for example the temperature of the IC target photon field). This could be done either by passing an additional argument or by freezing a parameter. How can this be done? Currently I am using global variables, but I want to get rid of that. Thanks a lot. All the best, Nukri

zblz commented 6 years ago

@nuk34 - In general, freezing a parameter in naima is done by setting it to a constant instead of from one of the arguments of the function being passed to run_sampler. I'm not sure I understand how you are using the global variable. A hacky way to get around creating a model with a fixed parameter programatically would be with a function-builder function (see also functools.partial).

def model(par0, par1, par2):
     ....

def fixed_par2_model_builder(par2):
    return lambda par0, par1: model(par0, par1, par2)

for par2 in [1, 2, 3]:
    par2_frozen_model = fixed_par2_model_builder(par2)
    .... [use par2_frozen_model as needed] ....
nuk34 commented 6 years ago

Thanks @zblz . Currently I have a global variable for my temperature, and inside the model function I use this variable to set the temperature of the photon field. This works well, except that I am not safe from accidentally overwriting this variable. I guess functools.partial would do the trick, I will have a look. This would completely hide this parameter from the run_sampler, which is exactly what I want. Alternatively, I could use uniform_prior(pars[0], T, T) to freeze the parameter to T. I haven't tried that yet. Cheers, Nukri

zblz commented 6 years ago

Alternatively, I could use uniform_prior(pars[0], T, T) to freeze the parameter to T. I haven't tried that yet.

I'd strongly recommend against that. The sampler will still try to sample parameter T and all of the samples will be rejected because it is not equal to the value you have set in the prior, so you will struggle to produce enough samples for analysis.