本文整理汇总了Python中astropy.coordinates.Angle.to_string方法的典型用法代码示例。如果您正苦于以下问题:Python Angle.to_string方法的具体用法?Python Angle.to_string怎么用?Python Angle.to_string使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类astropy.coordinates.Angle
的用法示例。
在下文中一共展示了Angle.to_string方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: deg_to_sex
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
def deg_to_sex(ra, dec):
"""
Convert an Ra and Dec position in decimal degrees to hexadecimal
Parameters
----------
ra : float
Ra in decimal degrees
dec : float
Dec in decimal degrees
Returns
-------
ra : str
Ra in hexadecimal HH:MM:SS
dec : str
Dec in hexadecimal DD:MM:SS
"""
from astropy import units as u
from astropy.coordinates import Angle
rad = Angle(ra * u.deg)
decd = Angle(dec * u.deg)
ra = rad.to_string(unit=u.hour, sep=':')
dec = decd.to_string(unit=u.deg, sep=':')
return ra, dec
示例2: deg_to_sex
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
def deg_to_sex(ra, dec):
from astropy import units as u
from astropy.coordinates import Angle
rad = Angle(ra * u.deg)
decd = Angle(dec * u.deg)
ra = rad.to_string(unit=u.hour, sep=':')
dec = decd.to_string(unit=u.deg, sep=':')
return ra, dec
示例3: time_scatterplot
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
def time_scatterplot(time, peakr, flux, proto, num, t_init, posx, posy):
#Convert the decimal degrees to HMS strings.
ra_deg = Angle(str(posx)+'d')
dec_deg = Angle(str(posy)+'d')
ra_hms = ra_deg.to_string(unit=units.hour, sep=':', precision=2)
dec_dms = dec_deg.to_string(unit=units.degree, sep=':', precision=2)
#Set the x-range.
x_hi = max(time)*1.1
x_lo = -max(time)*0.1
plt.xlim(x_lo, x_hi)
#Set the y-range.
y_hi = 1.25
y_lo = 0.75
if np.amax(peakr) > 1.25:
y_hi = np.amax(peakr)*1.5
##fi
if np.amax(peakr) < 0.75:
y_lo = min(peakr)*0.7
##fi
plt.ylim(y_lo, y_hi)
#Define the labels.
plt.xlabel('Time (days + '+t_init+')')
#Write important details about the source on the plot.
plt.annotate('Source Number: '+str(num), xy = (0.05,0.2),
xycoords = 'axes fraction', size = 'small')
plt.annotate('Peak Flux: '+'{:.4}'.format(flux)+' (Jy/Beam)',
xy = (0.05,0.15), xycoords = 'axes fraction', size = 'small')
plt.annotate('Class: '+proto, xy = (0.05,0.1), xycoords = 'axes fraction',
size = 'small')
plt.annotate('RA: '+ra_hms+', Dec: '+dec_dms, xy = (0.05,0.05),
xycoords = 'axes fraction', size = 'small')
#Plot the data.
plt.scatter(time, peakr, alpha = 0.6, s = 60, marker = 'o', facecolor = 'r')
#Plot reference lines.
plt.plot((x_lo,x_hi),(1.0,1.0), '-k')
plt.plot((x_lo,x_hi),(0.9,0.9), '--k')
plt.plot((x_lo,x_hi),(1.1,1.1), '--k')
示例4: formatter
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
def formatter(self, values, spacing):
if not isinstance(values, u.Quantity) and values is not None:
raise TypeError("values should be a Quantities array")
if len(values) > 0:
if self.format is None:
spacing = spacing.to(u.arcsec).value
if spacing > 3600:
fields = 1
precision = 0
elif spacing > 60:
fields = 2
precision = 0
elif spacing > 1:
fields = 3
precision = 0
else:
fields = 3
precision = -int(np.floor(np.log10(spacing)))
decimal = False
unit = u.degree
else:
fields = self._fields
precision = self._precision
decimal = self._decimal
unit = self._unit
if decimal:
sep = None
elif self._sep is not None:
sep = self._sep
else:
if unit == u.degree:
if rcParams['text.usetex']:
deg = r'$^\circ$'
else:
deg = six.u('\xb0')
sep = (deg, "'", '"')
else:
sep = ('h', 'm', 's')
angles = Angle(values)
string = angles.to_string(unit=unit,
precision=precision,
decimal=decimal,
fields=fields,
sep=sep).tolist()
return string
else:
return []
示例5: step
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
def step(self, uniform_factor=1):
"""
Randomly steps all parameters with uncertainties in parifle.
"""
n_dim = len(self.fit_parameters)
for parameter in self.fit_parameters:
if (hasattr(self,parameter + 'err')):
value = getattr(self, parameter)
err = getattr(self, parameter + 'err') * uniform_factor / n_dim
if (err != 0.):
if (parameter == 'RAJ'):
ra = Angle(getattr(self, 'RAJ'), unit=u.hour)
err = getattr(self, 'RAJerr') / 3600
ra_new = ra.deg + err * np.random.uniform(-1., 1.)
ra_new = Angle(ra_new, unit=u.deg)
setattr(self, parameter, str(ra_new.to_string(unit=u.hour, sep=':', precision=10)))
elif (parameter == 'DECJ'):
dec = Angle(getattr(self, 'DECJ'), unit=u.deg)
err = getattr(self, 'DECJerr') / 3600
dec_new = dec.deg + err * np.random.uniform(-1., 1.)
dec_new = Angle(dec_new, unit=u.deg)
setattr(self, parameter, str(dec_new.to_string(unit=u.deg, sep=':', precision=10)))
elif (parameter == 'SINI'):
cosi = np.sqrt(1 - getattr(self, 'SINI')**2)
err = getattr(self, 'DECJerr') / 3600
cosi += err * np.random.uniform(-1., 1.)
setattr(self, parameter, np.sqrt(1.-cosi**2))
else:
setattr(self, parameter, value + err * np.random.uniform(-1., 1.))
setattr(self,parameter + 'flag', 0)
示例6: formatter
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
def formatter(self, values, spacing):
if len(values) > 0:
if self.format is None:
spacing = spacing.to(u.arcsec).value
if spacing > 3600:
fields = 1
precision = 0
elif spacing > 60:
fields = 2
precision = 0
elif spacing > 1:
fields = 3
precision = 0
else:
fields = 3
precision = -int(np.floor(np.log10(spacing)))
decimal = False
unit = u.degree
else:
fields = self._fields
precision = self._precision
decimal = self._decimal
unit = self._unit
if decimal:
sep = None
else:
if unit == u.degree:
sep=(six.u('\xb0'), "'", '"')[:fields]
else:
sep=('h', 'm', 's')[:fields]
angles = Angle(np.asarray(values), unit=u.deg)
string = angles.to_string(unit=unit,
precision=precision,
decimal=decimal,
fields=fields,
sep=sep).tolist()
return string
else:
return []
示例7: SkyEvent
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
class SkyEvent(object):
"""
Represents universal attributes of an observed event on sky.
I.e. the most basic details that we expect to find in all packets
reporting events with sky-positions.
Attributes:
position (:class:`astropy.coordinates.SkyCoord`): Best-estimate
sky-coordinates of the event being reported.
position error (:class:`astropy.coordinates.Angle`): Error-cone on the
position estimate.
timestamp of event (:class:`datetime.datetime`):
Timestamp for the reported event (UTC timezone).
"""
def __init__(self, skyevent_dict):
d = skyevent_dict
self.position = SkyCoord(d['ra'], d['dec'], unit='deg')
self.position_error = Angle(d['error'], unit='deg')
self.timestamp = None
if d.get('time'):
self.timestamp = iso8601.parse_date(d['time'])
def __repr__(self):
return (str(self.position)
+ ' +/- ' + self.position_error.to_string(decimal=True)
+ ' @ ' + self.timestamp.isoformat())
@staticmethod
def _parse_coords_dict(coords_dict):
d = coords_dict
posn = SkyCoord(d['ra'], d['dec'], unit='deg')
posn_error = Angle(d['error'], unit='deg')
time = iso8601.parse_date(d['time'])
return SkyEvent(sky_position=posn,
sky_position_error=posn_error,
event_timestamp=time)
示例8: factorDirectionsWriter
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
def factorDirectionsWriter(table, fileName):
"""
Writes patches to a Factor directions file.
Note that Factor respects the order of patches and they are sorted here by
apparent flux from brightest to faintest.
Parameters
----------
table : astropy.table.Table object
Input sky model table; must have patches defined
fileName : str
Output file to which the sky model is written
"""
log = logging.getLogger('LSMTool.Write')
regionFile = open(fileName, 'w')
log.debug('Writing Factor directions file to {0}'.format(fileName))
outLines = []
outLines.append('# name position atrous_do mscale_field_do cal_imsize '
'solint_ph solint_amp dynamic_range region_selfcal '
'region_field peel_skymodel outlier_source cal_radius_deg cal_flux\n')
if 'History' in table.meta:
outLines.append('\n# LSMTool history:\n# ')
outLines.append('\n# '.join(table.meta['History']))
outLines.append('\n')
outLines.append('\n')
# Make sure all columns have the correct units
for colName in table.columns:
units = allowedColumnUnits[colName.lower()]
if units is not None:
table[colName].convert_unit_to(units)
table = table.group_by('Patch')
patchNames = table.groups.keys['Patch']
if 'patch_order' in table.meta:
indx = table.meta['patch_order']
else:
indx = range(len(table.groups))
if 'patch_size' in table.meta:
sizes = table.meta['patch_size']
else:
sizes = [''] * len(table.groups)
if 'patch_flux' in table.meta:
fluxes = table.meta['patch_flux']
else:
fluxes = [''] * len(table.groups)
for patchName, size, flux in zip(patchNames[indx], sizes[indx], fluxes[indx]):
if patchName in table.meta:
gRA, gDec = table.meta[patchName]
else:
gRA = Angle(0.0)
gDec = Angle(0.0)
outLines.append('{0} {1},{2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} '
'{13} {14}\n'.format(patchName,
gRA.to_string(unit='hourangle', sep='hms'), gDec.to_string(sep='dms'),
'empty', 'empty', 0, 0, 0, 'LD', 'empty', 'empty', 'empty', False,
size, flux))
regionFile.writelines(outLines)
regionFile.close()
示例9: formatter
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
def formatter(self, values, spacing, format='auto'):
if not isinstance(values, u.Quantity) and values is not None:
raise TypeError("values should be a Quantities array")
if len(values) > 0:
decimal = self.decimal
unit = self._format_unit
if unit is u.hour:
unit = u.hourangle
if self.format is None:
if decimal:
# Here we assume the spacing can be arbitrary, so for example
# 1.000223 degrees, in which case we don't want to have a
# format that rounds to degrees. So we find the number of
# decimal places we get from representing the spacing as a
# string in the desired units. The easiest way to find
# the smallest number of decimal places required is to
# format the number as a decimal float and strip any zeros
# from the end. We do this rather than just trusting e.g.
# str() because str(15.) == 15.0. We format using 10 decimal
# places by default before stripping the zeros since this
# corresponds to a resolution of less than a microarcecond,
# which should be sufficient.
spacing = spacing.to_value(unit)
fields = 0
precision = len("{0:.10f}".format(spacing).replace('0', ' ').strip().split('.', 1)[1])
else:
spacing = spacing.to_value(unit / 3600)
if spacing >= 3600:
fields = 1
precision = 0
elif spacing >= 60:
fields = 2
precision = 0
elif spacing >= 1:
fields = 3
precision = 0
else:
fields = 3
precision = -int(np.floor(np.log10(spacing)))
else:
fields = self._fields
precision = self._precision
is_latex = format == 'latex' or (format == 'auto' and rcParams['text.usetex'])
if decimal:
# At the moment, the Angle class doesn't have a consistent way
# to always convert angles to strings in decimal form with
# symbols for units (instead of e.g 3arcsec). So as a workaround
# we take advantage of the fact that Angle.to_string converts
# the unit to a string manually when decimal=False and the unit
# is not strictly u.degree or u.hourangle
if self.show_decimal_unit:
decimal = False
sep = 'fromunit'
if is_latex:
fmt = 'latex'
else:
if unit is u.hourangle:
fmt = 'unicode'
else:
fmt = None
unit = CUSTOM_UNITS.get(unit, unit)
else:
sep = None
fmt = None
elif self.sep is not None:
sep = self.sep
fmt = None
else:
sep = 'fromunit'
if unit == u.degree:
if is_latex:
fmt = 'latex'
else:
sep = ('\xb0', "'", '"')
fmt = None
else:
if format == 'ascii':
fmt = None
elif is_latex:
fmt = 'latex'
else:
# Here we still use LaTeX but this is for Matplotlib's
# LaTeX engine - we can't use fmt='latex' as this
# doesn't produce LaTeX output that respects the fonts.
sep = (r'$\mathregular{^h}$', r'$\mathregular{^m}$', r'$\mathregular{^s}$')
fmt = None
angles = Angle(values)
string = angles.to_string(unit=unit,
precision=precision,
decimal=decimal,
fields=fields,
sep=sep,
#.........这里部分代码省略.........
示例10: _parse_result
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
#.........这里部分代码省略.........
names = ('Date', 'RA', 'Dec', 'Delta',
'r', 'Elongation', 'Phase', 'V')
col_starts = (0, 18, 29, 39, 47, 56, 62, 69)
col_ends = (17, 28, 38, 46, 55, 61, 68, 72)
units = (None, None, None, 'au', 'au', 'deg', 'deg', 'mag')
if 's=t' in result.request.body: # total motion
names += ('Proper motion', 'Direction')
units += ('arcsec/h', 'deg')
elif 's=c' in result.request.body: # coord Motion
names += ('dRA', 'dDec')
units += ('arcsec/h', 'arcsec/h')
elif 's=s' in result.request.body: # sky Motion
names += ('dRA cos(Dec)', 'dDec')
units += ('arcsec/h', 'arcsec/h')
col_starts += (73, 81)
col_ends += (80, 89)
if 'Moon' in columns:
# table includes Alt, Az, Sun and Moon geometry
names += ('Azimuth', 'Altitude', 'Sun altitude', 'Moon phase',
'Moon distance', 'Moon altitude')
col_starts += tuple((col_ends[-1] + offset for offset in
(2, 9, 14, 20, 27, 33)))
col_ends += tuple((col_ends[-1] + offset for offset in
(8, 13, 19, 26, 32, 37)))
units += ('deg', 'deg', 'deg', None, 'deg', 'deg')
if 'Uncertainty' in columns:
names += ('Uncertainty 3sig', 'Unc. P.A.')
col_starts += tuple((col_ends[-1] + offset for offset in
(2, 11)))
col_ends += tuple((col_ends[-1] + offset for offset in
(10, 16)))
units += ('arcsec', 'deg')
if ">Map</a>" in first_row and self._unc_links:
names += ('Unc. map', 'Unc. offsets')
col_starts += (first_row.index(' / <a') + 3, )
col_starts += (
first_row.index(' / <a', col_starts[-1]) + 3, )
# Unc. offsets is always last
col_ends += (col_starts[-1] - 3,
first_row.rindex('</a>') + 4)
units += (None, None)
elif HELIOCENTRIC:
names = ('Object', 'JD', 'X', 'Y', 'Z', "X'", "Y'", "Z'")
col_starts = (0, 12, 28, 45, 61, 77, 92, 108)
col_ends = None
units = (None, None, 'au', 'au', 'au', 'au/d', 'au/d', 'au/d')
elif GEOCENTRIC:
names = ('Object', 'JD', 'X', 'Y', 'Z')
col_starts = (0, 12, 28, 45, 61)
col_ends = None
units = (None, None, 'au', 'au', 'au')
tab = ascii.read(text_table, format='fixed_width_no_header',
names=names, col_starts=col_starts,
col_ends=col_ends, data_start=data_start,
fill_values=(('N/A', np.nan),))
for col, unit in zip(names, units):
tab[col].unit = unit
# Time for dates, Angle for RA and Dec; convert columns at user's request
if SKY:
# convert from MPES string to Time, MPES uses UT timescale
tab['Date'] = Time(['{}-{}-{} {}:{}:{}'.format(
d[:4], d[5:7], d[8:10], d[11:13], d[13:15], d[15:17])
for d in tab['Date']], scale='utc')
# convert from MPES string:
ra = Angle(tab['RA'], unit='hourangle').to('deg')
dec = Angle(tab['Dec'], unit='deg')
# optionally convert back to a string
if self._ra_format is not None:
ra_unit = self._ra_format.get('unit', ra.unit)
ra = ra.to_string(**self._ra_format)
else:
ra_unit = ra.unit
if self._dec_format is not None:
dec_unit = self._dec_format.get('unit', dec.unit)
dec = dec.to_string(**self._dec_format)
else:
dec_unit = dec.unit
# replace columns
tab.remove_columns(('RA', 'Dec'))
tab.add_column(Column(ra, name='RA', unit=ra_unit), index=1)
tab.add_column(Column(dec, name='Dec', unit=dec_unit), index=2)
# convert proper motion columns
for col in ('Proper motion', 'dRA', 'dRA cos(Dec)', 'dDec'):
if col in tab.colnames:
tab[col].convert_unit_to(self._proper_motion_unit)
else:
# convert from MPES string to Time
tab['JD'] = Time(tab['JD'], format='jd', scale='tt')
return tab
示例11: Angle
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
deg = r'$^\circ$'
else:
deg = six.u('\xb0')
sep = (deg, "'", '"')
else:
sep = ('h', 'm', 's')
<<<<<<< HEAD
>>>>>>> upstream/master
angles = Angle(np.asarray(values), unit=u.deg)
=======
angles = Angle(values)
>>>>>>> upstream/master
string = angles.to_string(unit=unit,
precision=precision,
decimal=decimal,
fields=fields,
sep=sep).tolist()
return string
else:
return []
class ScalarFormatterLocator(BaseFormatterLocator):
"""
A joint formatter/locator
"""
<<<<<<< HEAD
def __init__(self, values=None, number=None, spacing=None, format=None):
示例12: main
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
#.........这里部分代码省略.........
v_print("Median obs time in JD {}".format(np.median(jd_days)))
date = Time(mean_obs_time, format="jd")
date.format = "fits" # Turn back into fits format
date = date.value[:-5] + "Z" # Going from Time object back to string and adding Z to end for Tapas
target_ra = header["RA"] # of the last observation in the list
target_dec = header["DEC"]
obs_wl_min = header["HIERARCH ESO INS WLEN MIN"]
obs_wl_max = header["HIERARCH ESO INS WLEN MAX"]
else:
header = fits.getheader(fname)
date = header["DATE-OBS"][:-1]+"Z"
target_ra = header["RA"]
target_dec = header["DEC"]
obs_wl_min = header["HIERARCH ESO INS WLEN MIN"]
obs_wl_max = header["HIERARCH ESO INS WLEN MAX"]
slit_width = header["HIERARCH ESO INS SLIT1 WID"]
####### Observatory Settings
instrument = header["INSTRUME"]
telescope = header["TELESCOP"]
if "VLT" in telescope:
obs_name = "ESO Paranal Chile (VLT)"
else:
v_print("Don't have TAPAS telecope location name (Using the Obervation value)")
obs_name = telescope
obs_long = header["HIERARCH ESO TEL GEOLON"]
obs_lat = header["HIERARCH ESO TEL GEOLAT"]
obs_alt = header["HIERARCH ESO TEL GEOELEV"]
####### Target Settings
ra_angle = Angle(target_ra, u.degree)
ra_j2000 = str(ra_angle.to_string(unit=u.hour, sep=':', precision=0, pad=True)) # Extra str to get rid of u"string" which failed in template
dec_angle = Angle(target_dec, u.deg)
dec_j2000 = str(dec_angle.to_string(unit=u.degree, sep=':', precision=0, pad=True)) # Extra str to get rid of u"string" which failed in template
v_print("RA degrees = {0}, RA Angle = {1}, RA for tapas = {2}".format(target_ra, ra_angle, ra_j2000))
v_print("DEC degrees = {0}, DEC Angle = {1}, DEC for tapas = {2}".format(target_dec, dec_angle, dec_j2000))
if wl_min:
spec_range_min = int(wl_min)
else:
spec_range_min = int(obs_wl_min - 10)
if wl_max:
spec_range_max = int(wl_max)
else:
spec_range_max = int(obs_wl_max + 10)
# Check for TAPAS consistency
#Tapas wavelength range is from 350 to 2500 nm in vacuum.
if spec_range_min < 350:
v_print("Lower wavelength bound of {} was below tapas minimum. Setting to tapas minimum of 350 nm".format(spec_range_min))
spec_range_min = 350
elif spec_range_min > 2500:
v_print("Wavelength Lower bound of {} is above Tapas maximum wavelength of 2500 nm. Check your wavelength units".format(spec_range_min))
raise("Wavelength bounds Error")
if spec_range_max > 2500:
v_print("Upper wavelength bound of {} was above tapas maximum. Setting to tapas maximum of 2500 nm".format(spec_range_max))
spec_range_max = 2500
elif spec_range_max < 350:
v_print("Wavelength Upper bound of {} is below Tapas minimum wavelength of 350 nm. Check your wavelength units".format(spec_range_max))
raise("Wavelength bounds Error")
########### Tapas Specifications
if tapas_format in ["ascii","fits","vetcdf","vo"]:
tapas_format = tapas_format.upper()
示例13: main
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
def main(argv):
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-f','--filename',
help = 'Input file with output from donut (.npy).'
,type='string')
parser.add_option('-i','--image',
help = 'Fits file where the zernike coefficients where measured (to read current offsets).'
,type='string')
parser.add_option('--niter',
help = 'Number of iterations on the linear fitting procedure (default = 1).'
,type='int',default=1)
parser.add_option('--maxreject',
help = 'Maximum number of rejected points (default=3).'
,type='int',default=3)
parser.add_option('-o','--output',
help = 'Output file name.'
,type='string')
opt, args = parser.parse_args(argv)
log.info('Reading input catalog: %s'%opt.filename)
rcat = np.load(opt.filename).T
cat = np.array([])
for col in rcat:
cat = np.append(cat,np.array([col.reshape(-1),]))
cat = cat.reshape(rcat.shape[0],-1)
fitmask = cat[0] == 1
cat = cat[1:]
niter = opt.niter if opt.niter > 0 else 1
pix2mm = 0.01 # pixel size in um
id_seeing = 2
id_focus = 5
id_astigx = 6
id_astigy = 7
id_commay = 8
id_commax = 9
def fitPlaneOptimize(XYZ):
def residiuals(parameter,f,x,y):
return [(f[i] - model(parameter,x[i],y[i])) for i in range(len(f))]
def model(parameter, x, y):
a, b, c = parameter
return a*x + b*y + c
X = XYZ[:,0]
Y = XYZ[:,1]
Z = XYZ[:,2]
p0 = [1., 1.,1.] # initial guess
result = leastsq(residiuals, p0, args=(Z,X,Y))[0]
return result
def astigmatism(Axis=0):
median = np.median(z)
std = np.std(z)
mask = np.abs(z-median) < std*2
# print median,std
fitx = (x[mask]-center[0])*pix2mm
fity = (y[mask]-center[1])*pix2mm
plane = fitPlaneOptimize(np.array([fitx,fity,z[mask]]).T)
ix = Angle(plane[0]*u.rad)/10.
iy = Angle(plane[1]*u.rad)/10.
CFP = 291.36 # Comma Free Point in mm
zcfp = - CFP * (2. - np.cos(ix.rad) - np.cos(iy.rad))
xcfp = CFP * np.sin(iy.rad)
ycfp = CFP * np.sin(ix.rad)
res = OrderedDict([('X',0),
('Y',0),
('Z',0),
('U',0),
('V',0)])
if Axis == 0:
res['U'] = -ix
res['V'] = iy
res['X'] = xcfp
res['Y'] = ycfp
res['Z'] = zcfp
else:
res['U'] = iy
res['V'] = ix
res['X'] = ycfp
res['Y'] = -xcfp
res['Z'] = zcfp
print "###########################"
print "Inclination U: %s"%res['U'].to_string(unit=u.degree, sep=(':', ':', ' '))
print "Inclination V: %s"%res['V'].to_string(unit=u.degree, sep=(':', ':', ' '))
print 'Corrections:'
#.........这里部分代码省略.........
示例14: main
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
#.........这里部分代码省略.........
Obs_name = header["ESO OBS NAME"]
Nabcycles = header["ESO SEQ NABCYCLES"] # ESO SEQ NABCYCLES: 4
NEXP = header["ESO TPL NEXP"] # ESO TPL NEXP: 8
# Observation IDs
obs_pi_id= header["ESO OBS PI-COI ID"]
prosal_id= header["ESO OBS PROG ID"]
tpl_id = header["ESO TPL ID"] #CRIRES_spec_obs_AutoNodOnSlit
ao_loop_state = header["ESO AOS RTC LOOP STATE"]
#Airmass calculation
mean_airmass = np.mean(nod_airmass)
airmass_range = np.max(nod_airmass)-np.min(nod_airmass)
####### Observatory Settings
instrument = header["INSTRUME"]
telescope = header["TELESCOP"]
if "VLT" in telescope:
obs_name = "ESO Paranal Chile (VLT)"
else:
v_print("Don't have TAPAS telecope location name (Using the Obervation value)")
obs_name = telescope
obs_long = header["HIERARCH ESO TEL GEOLON"]
obs_lat = header["HIERARCH ESO TEL GEOLAT"]
obs_alt = header["HIERARCH ESO TEL GEOELEV"]
####### Target Settings
ra_angle = Angle(target_ra, u.degree)
ra_j2000 = str(ra_angle.to_string(unit=u.hour, sep=':', precision=0, pad=True)) # Extra str to get rid of u"string" which failed in template
dec_angle = Angle(target_dec, u.deg)
dec_j2000 = str(dec_angle.to_string(unit=u.degree, sep=':', precision=0, pad=True)) # Extra str to get rid of u"string" which failed in template
v_print("RA degrees = {0}, RA Angle = {1}, RA for tapas = {2}".format(target_ra, ra_angle, ra_j2000))
v_print("DEC degrees = {0}, DEC Angle = {1}, DEC for tapas = {2}".format(target_dec, dec_angle, dec_j2000))
# Resolving power rule of thumb
R = 100000*0.2 / slit_width
resolving_power = int(R)
print("Resolving Power = {}".format(resolving_power))
if output:
output_file = output
else:
output_file = "key_observation_values.txt"
try:
with open(output_file, "w") as out:
############################################################
#Put the useful parameters I need to know here
out.write("KEY CRIRES OBSERVATION PARAMETERS:\n------------------\n")
out.write("Target Name = {}\n".format(Object))
out.write("Observation Name = {}\n".format(Obs_name))
out.write("RA = {}, {} \n".format(ra_angle, ra_j2000))
out.write("DEC = {}, {} \n".format(dec_angle, dec_j2000))
out.write("\nOBS IDs:\n------------------\n")
示例15: len
# 需要导入模块: from astropy.coordinates import Angle [as 别名]
# 或者: from astropy.coordinates.Angle import to_string [as 别名]
Deccenter=numpy.unique(Deccenters).mean()
# command-line option Dec overwrites automatic Dec
if options.dec is None:
Deccenter=Angle(Deccenter, unit=u.deg)
else:
try:
Deccenter=Angle(float(options.dec), unit=u.deg)
except:
logger.warning('Unable to interpret dec center %s' % options.dec)
Deccenter=Angle(Deccenter, unit=u.deg)
# And the image width and height
width=(f[0].header['NAXIS1'])
height=(f[0].header['NAXIS2'])
center='%s,%s' % (RAcenterhours.to_string(unit=u.hour, sep=':'),
Deccenter.to_string(unit=u.deg, sep=':'))
logger.info('Determined center RA=%sh, Dec=%sd' % (RAcenterhours.to_string(unit=u.hour, sep=':'),
Deccenter.to_string(unit=u.deg, sep=':')))
command='%s -c %s %s -OVERSAMPLING %d -CENTER %s -IMAGE_SIZE 0' % (swarp,
localswarpconfig,
','.join(images),
options.oversample,
center)
command+=' -PROJECTION_TYPE %s' % options.projection
if len(options.swarpcommands)>0:
command+=' ' + options.swarp
outname='%s.swarp.fits' % options.root
outweightname='%s.weight.fits' % options.root