Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def mpfitfun(x,y,err):
if err is None:
def f(p,fjac=None):
return [0,(y-self.n_ammonia(pars=p,
parnames=parinfo.parnames,
**fitfun_kwargs)(x))]
else:
def f(p,fjac=None):
return [0,(y-self.n_ammonia(pars=p,
parnames=parinfo.parnames,
**fitfun_kwargs)(x))/err]
return f
if veryverbose:
log.info("GUESSES: ")
log.info(str(parinfo))
#log.info "\n".join(["%s: %s" % (p['parname'],p['value']) for p in parinfo])
if use_lmfit:
return self.lmfitter(xax, data, err=err,
parinfo=parinfo,
quiet=quiet,
debug=debug)
else:
mp = mpfit(mpfitfun(xax,data,err),
parinfo=parinfo,
maxiter=maxiter,
quiet=quiet,
debug=debug)
mpp = mp.params
if mp.perror is not None:
mpperr = mp.perror
#plt.colorbar()
#plt.show()
#mould=mould/mould.max()
#discretize delta
delta=np.floor(np.array(mould.shape)/2)
# Create energy matrix
energy=np.zeros(data.shape)
#np.empty_like(data)
#mask=np.isnan(energy)
#energy.data[np.logical_not(mask)]=max_val
# check for diagonality
#dstruct=np.all(a == np.diag(np.diag(P)))
# compute
if debug:
log.info("Delta = "+str(delta))
log.info("Max Iter = "+str(max_iter))
#plt.imshow(mould.sum(axis=(0)))
#plt.show()
_update_energies(energy,residual,mould,nlevel,delta)
while True:
niter+=1
if (niter > max_iter):
message="Maximum iterations reached = "+str(niter)
break
max_idx=np.array(np.unravel_index(energy.argmax(),energy.shape))
max_val=energy[tuple(max_idx)]
# tlb=base-delta
# tub=base+delta + 1
# plt.imshow(residual[slab(residual,tlb,tub)].sum(axis=0))
# print energy[tuple(base)]
# print residual[slab(residual,tlb,tub)]
log.info("Reading model from {0}".format(args.parfile))
m = pint.models.get_model(args.parfile)
log.warning(m.params)
log.info("Reading TOAs")
use_planets = False
if m.PLANET_SHAPIRO.value:
use_planets = True
model_ephem = "DE421"
if m.EPHEM is not None:
model_ephem = m.EPHEM.value
t = pint.toa.get_TOAs(args.timfile, planets=use_planets, ephem=model_ephem)
prefit_resids = pint.residuals.Residuals(t, m).time_resids
log.info("Fitting...")
f = pint.fitter.WLSFitter(t, m)
f.fit_toas()
# Print fit summary
print(
"============================================================================"
)
f.print_summary()
if args.plot:
import matplotlib.pyplot as plt
# Turn on support for plotting quantities
from astropy.visualization import quantity_support
quantity_support()
def setup(self):
"""Check out parameters setup.
"""
super(BinaryDDK, self).setup()
log.info(
"Using ICRS equatorial coordinate. The parameter KOM is"
" measured respect to equatorial North."
)
if "PMRA" not in self._parent.params or "PMDEC" not in self._parent.params:
# Check ecliptic coordinates proper motion.
if (
"PMELONG" not in self._parent.params
or "PMELAT" not in self._parent.params
):
raise MissingParameter(
"DDK", "DDK model needs proper motion parameters."
)
for flag_dict in toas.table["flags"]:
if "jump" in flag_dict.keys():
break
elif "gui_jump" in flag_dict.keys():
break
else:
log.info("No jump flags to process")
return None
for flag_dict in toas.table["flags"]:
if "jump" in flag_dict.keys():
jump_nums = [
flag_dict["jump"] if "jump" in flag_dict.keys() else np.nan
for flag_dict in toas.table["flags"]
]
if "PhaseJump" not in self.components:
log.info("PhaseJump component added")
a = jump.PhaseJump()
a.setup()
self.add_component(a)
self.remove_param("JUMP1")
for num in np.arange(1, np.nanmax(jump_nums) + 1):
if "JUMP" + str(int(num)) not in self.params:
param = maskParameter(
name="JUMP",
index=int(num),
key="jump",
key_value=int(num),
value=0.0,
units="second",
uncertainty=0.0,
)
self.add_param_from_top(param, "PhaseJump")
def formresiduals(self):
"""Form the residuals"""
log.info("Computing residuals...")
t0 = time.time()
self.resids_us = resids(self.t, self.model).time_resids.to(u.us)
time_phase = time.time() - t0
log.info("Computed phases and residuals in %.3f sec" % time_phase)
# resids in (approximate) us:
log.info("RMS PINT residuals are %.3f us" % self.resids_us.std().value)
if len(nightflat_list) > 0:
for filename in sorted(nightflat_list):
log.info('Trimming and bias subtracting frame ' + filename + ' --> ' + prefix + filename)
ccd = CCDData.read(os.path.join(image_collection.location, '') + filename, unit=u.adu)
ccd = ccdproc.trim_image(ccd, fits_section=ccd.header['TRIMSEC'])
ccd.header['HISTORY'] = "Trimmed"
if slit is True:
ccd = ccdproc.trim_image(ccd[self.slit1:self.slit2, :])
if self.master_bias is not None:
ccd = ccdproc.subtract_bias(ccd, self.master_bias)
ccd.header['HISTORY'] = "Bias subtracted."
else:
ccd.header['HISTORY'] = "Bias NOT subtracted."
log.warning('No bias subtraction!')
ccd.write(prefix + filename, clobber=True)
log.info('Done --> Night flat frames have been reduced.')
print('\n')
return
def add_jump(self, selected):
"""
jump the toas selected or unjump them if already jumped
:param selected: boolean array to apply to toas, True = selected toa
"""
# TODO: split into two functions
if "PhaseJump" not in self.prefit_model.components:
# if no PhaseJump component, add one
log.info("PhaseJump component added")
a = pint.models.jump.PhaseJump()
a.setup()
self.prefit_model.add_component(a, order=-1)
self.prefit_model.remove_param("JUMP1")
param = pint.models.parameter.maskParameter(
name="JUMP", index=1, key="jump", key_value=1, value=0.0, units="second"
)
self.prefit_model.add_param_from_top(param, "PhaseJump")
getattr(self.prefit_model, param.name).frozen = False
self.prefit_model.components["PhaseJump"]._parent = self.prefit_model
if self.fitted:
self.postfit_model.add_component(a)
for dict1, dict2 in zip(
self.all_toas.table["flags"][selected],
self.selected_toas.table["flags"],
):
def compute_planet_posvel_c(self,ephem = "DE421",planets = False):
"""
compute_planet_posvel_table()
Takes an list of toa in tdb scale and returns the position and velocity
of the planets.
If the planets == Falus. Only the earth postion velocity are calculated
If the planets == True. Jupiter, Saturn, Venus, Uranus position and
velocity are calculated
"""
# Load the appropriate JPL ephemeris
#load_kernels_cython(ephem)
pth = os.path.join(pintdir,"datafiles")
ephem_file = os.path.join(pth, "%s.bsp"%ephem.lower())
spice_util.furnsh_py(ephem_file)
log.info("Loaded ephemeris from %s" % ephem_file)
spice_util.furnsh_py(os.path.join(pth, "naif0010.tls"))
log.info("Loaded naif0010.tls")
# Set up the j2000 start time for calcluat spice formate et
j2000 = time.Time('2000-01-01 12:00:00', scale='utc')
j2000_mjd = j2000.utc.jd1- 240000.5 + j2000.utc.jd2
self.dataTable['earth_posvel'] = numpy.zeros((self.NumToa,6))
self.dataTable['sun_posvel'] = numpy.zeros((self.NumToa,6))
self.dataTable['obs_posvel'] = numpy.zeros((self.NumToa,6))
tdbld = numpy.longdouble(self.dataTable['tdb'][:,0]) \
-numpy.longdouble(240000.5) \
+numpy.longdouble(self.dataTable['tdb'][:,1])
et = (tdbld-j2000_mjd)*SECS_PER_DAY
et = numpy.double(et.data)
# get obseroatory xyz coords ITRF
for obsname in self.dataTable.groups.keys._data:
obsname = obsname[0]
self.dust = []
self.grid['density'] = []
if specific_energy is not None:
self.grid['specific_energy'] = []
# Check whether the density can be added to an existing one
if merge_if_possible:
# Only consider this if the specific energy is not specified
if specific_energy is None:
if isinstance(dust, six.string_types):
if dust in self.dust:
logger.info("Merging densities (identical filenames)")
ip = self.dust.index(dust)
self.grid['density'][ip].add(density)
return
else:
dust_hashes = []
for d in self.dust:
if not isinstance(d, six.string_types):
dust_hashes.append(d.hash())
else:
dust_hashes.append(None)
if dust.hash() in dust_hashes: