尧图网络 高端网站定制 · 原创设计
免费咨询热线
400-888-6620
免费获取方案
astropy.units API 参考:单位体系、物理类型、格式与配置项详解
科学计算科研数据分析【免费下载链接】astropyAstronomy and astrophysics core library项目地址https://gitcode.com/gh_mirrors/as/astropy点击查看免费下载本文以astropy.units包的官方 API 参考docs/units/ref_api.rst为主线系统梳理该子包对外暴露的全部核心 API从顶层astropy.units命名空间的聚合导入到si、cgs、astrophys、misc、photometric等各标准单位模块再到对数/函数单位、物理类型、单位格式转换器以及Quantity的两个全局配置项。读完后你将清楚每个模块的职责边界、默认启用的单位集合、enable()上下文管理器的使用方式以及如何在代码中安全地切换单位注册表。一、astropy.units顶层命名空间与默认单位注册表ref_api.rst的第一条指令automodapi:: astropy.units对应的是子包入口 astropy/units/init.py。它本身几乎不含实现主要做两件事聚合导入所有子模块并把它们拼进一个排序后的__all__方便文档生成与from astropy.units import *。从源码结构看入口在文件末尾显式设定了默认启用的单位集合# astropy/units/__init__.py from . import ( astrophys, cgs, core, decorators, errors, imperial, misc, photometric, physical, quantity, required_by_vounit, si, structured, ) ... # Enable the set of default units. This notably does *not* include # Imperial units. set_enabled_units( [si, cgs, astrophys, function.units, misc, photometric, required_by_vounit] )这里有两点值得注意默认不启用英制单位注释明确写着This notably does *not* include Imperial units。因此u.Unit(mi)这类字符串解析在默认状态下不会命中英制单位需要先用u.imperial.enable()。set_enabled_units的语义它是设置而非追加会替换当前注册表。astropy.units.core还提供了对应的add_enabled_units追加以及返回上下文管理器的版本这也是各模块enable()的底层实现来源。astropy.units.core子包astropy/units/core.py是上述 API 的定义源头其__all__列出了本参考页自动文档化的核心类型与函数__all__ [ CompositeUnit, IrreducibleUnit, NamedUnit, PrefixUnit, Unit, UnitBase, UnitPrefix, UnrecognizedUnit, add_enabled_aliases, add_enabled_equivalencies, add_enabled_units, def_unit, dimensionless_unscaled, get_current_unit_registry, one, set_enabled_aliases, set_enabled_equivalencies, set_enabled_units, ]其中UnitBase是几乎所有单位运算的基类Unit既是类也是从字符串解析单位的构造函数def_unit则是各标准模块定义单位时调用的工厂函数dimensionless_unscaled与one代表无量纲单位。二、标准单位定义模块ref_api.rst用一连串automodapi指令展开了若干单位定义模块。它们共同的模式是调用def_unit把单位注入本模块命名空间再用docgen生成的__all__汇总导出。下面按模块逐一说明其职责与代表性单位。SI 单位astropy.units.si模块文档声明这些单位也在并应当通过astropy.units命名空间使用见 astropy/units/si.py 顶部 docstring。它定义 SI 制单位且大量单位通过def_unit的prefixes参数自动生成 SI 前缀变体。典型定义如# astropy/units/si.py节选 def_unit( [m, meter], namespace_ns, prefixesTrue, exclude_prefixes[c], docmeter: base unit of length in SI, ) def_unit( [cm, centimeter], 0.01 * m, namespace_ns, prefixesFalse, doccm: 0.01 m in SI, base unit of length in cgs, )exclude_prefixes[c]是为了避免cm既被当作centi-meter前缀、又被显式定义为0.01 * m二者冲突显式定义让cm能在 CGS 里作为基本单位。def_unit还支持format参数为不同输出格式如latex、ogip、vounit指定专门拼写例如Å/Angstrom在不同格式下有各自的表示。CGS 单位astropy.units.cgsastropy/units/cgs.py 定义 CGS 制单位并直接复用si中已定义的基本量cm si.cm、g si.g、s si.s等。代表性派生单位有Galcm / s**2CGS 加速度单位与ergg * cm**2 / s**2CGS 能量单位def_unit([Gal, gal], cm / s**2, namespace_ns, prefixesTrue, docGal: CGS unit of acceleration) def_unit([erg], g * cm**2 / s**2, namespace_ns, prefixesTrue, docerg: CGS unit of energy)由于cm、g、s同时是 SI 与 CGS 的共享基本单位这解释了为何si定义cm时要把它从m的前缀里排除。天体物理单位astropy.units.astrophysastropy/units/astrophys.py 定义天文常用单位并在文件开头set_enabled_units([si])以保证能引用astropy.constants中的常数如R_sun、M_sun、pc。代表性单位覆盖长度、质量、能量、光度与光谱密度def_unit(([AU, au], [astronomical_unit]), _si.au, namespace_ns, prefixesTrue, docastronomical unit: ...) def_unit([pc, parsec], _si.pc, namespace_ns, prefixesTrue, docparsec: approximately 3.26 light-years.) def_unit([solMass, M_sun, Msun], _si.M_sun, namespace_ns, prefixesFalse, format{latex: rM_{\odot}, unicode: M\N{SUN}}) def_unit([Jy, Jansky, jansky], 1e-26 * si.W / si.m**2 / si.Hz, namespace_ns, prefixesTrue, docJansky: spectral flux density)注意solMass、solRad、solLum等都以prefixesFalse定义其 SI 前缀变体如msolMass被刻意放到required_by_vounit见下文而不是直接挂在天文模块里。杂项单位astropy.units.miscastropy/units/misc.py 汇集一些跨领域单位并导入si_prefixes、binary_prefixes以支持二进制前缀。代表性单位def_unit([barn, barn], 10**-28 * si.m**2, namespace_ns, prefixesTrue, docbarn: unit of area used in HEP) def_unit([cycle, cy], 2.0 * np.pi * si.rad, namespace_ns, prefixesFalse, doccycle: angular measurement, a full turn or rotation) def_unit([bar], 1e5 * si.Pa, namespace_ns, prefixes[([m], [milli], 1.0e-3)], docbar: pressure)bar通过prefixes参数只显式启用mbar毫巴而非全量前缀。光度学零点astropy.units.photometricastropy/units/photometric.py 定义星等零点对应的物理单位其文档指出真正的函数单位如ABmag在astropy.units.function.units中实例化。本模块只定义零点对应的线性通量单位def_unit([Bol, L_bol], L_bol0, namespace_ns, prefixesFalse, docLuminosity corresponding to absolute bolometric magnitude zero ...) def_unit([AB, ABflux], 10.0 ** (48.6 / -2.5) * cgs.erg * cgs.cm**-2 / si.s / si.Hz, namespace_ns, prefixesFalse, docAB magnitude zero flux density ...) def_unit([ST, STflux], 10.0 ** (21.1 / -2.5) * cgs.erg * cgs.cm**-2 / si.s / si.AA, namespace_ns, prefixesFalse, docST magnitude zero flux density ...)Bol、bol、AB、ST、mgyMaggies等即在此定义它们随后被function.units用作mag(...)的实参。对数 / 函数单位astropy.units.function.unitsastropy/units/function/units.py 定义可被当作函数调用的单位——对数型单位。调用它们即构造对应的函数单位实例而前缀变体不可调用因为u.mmag(u.ct/u.s)语义不清dex IrreducibleFunctionUnit([dex], namespace_ns, docDex: Base 10 logarithmic unit) dB RegularFunctionUnit([dB, decibel], 0.1 * dex, namespace_ns, ...) mag RegularFunctionUnit([mag], -0.4 * dex, namespace_ns, ...) STmag mag(photometric.STflux) # STmag-21.1 对应 1 erg/s/cm2/A ABmag mag(photometric.ABflux) # ABmag-48.6 对应 1 erg/s/cm2/Hz M_bol mag(photometric.Bol) m_bol mag(photometric.bol)这里体现了photometric与function.units的分工前者给出线性通量零点单位后者把它包装成mag(零点)形式。CDS 目录单位astropy.units.cdsastropy/units/cds.py 定义 CDS 目录格式VOTable ≤1.2 使用的单位。文档明确这些单位不在顶层astropy.units命名空间里需显式导入并推荐用上下文管理器避免与顶层单位冲突 import astropy.units as u from astropy.units import cds unit_string mmHg with cds.enable(): ... pressure_unit u.Unit(unit_string) (720 * pressure_unit).to(u.bar) Quantity 0.95992119 barcds.enable()返回add_enabled_units(...)产生的上下文对象既支持with也支持装饰器用法。英制单位astropy.units.imperialastropy/units/imperial.py 定义常用英制/美制单位默认不在顶层命名空间。文档给出典型用法u.imperial.mile / u.hour得到Unit(mi / h)。代表性定义def_unit([inch], 2.54 * si.cm, namespace_ns, docInternational inch) def_unit([mi, mile], 5280 * ft, namespace_ns, docInternational mile) def_unit([deg_F, Fahrenheit], namespace_ns, docDegrees Fahrenheit, format{latex: r{}^{\circ}F, unicode: °F})其enable()与cds.enable()一样返回_UnitContext可临时把英制单位纳入find_equivalent_units与compose的结果。VOUnit 必需的 SI 前缀单位astropy.units.required_by_vounitastropy/units/required_by_vounit.py 是一个常被忽略但很重要的模块。文档解释这里定义的是VOUnit 标准需要、但实际很少用且易引起混淆的 SI 前缀单位例如msolMass表示毫太阳质量。这些前缀单位默认是启用的所以Unit(msolMass)可直接解析但要直接访问该单位对象需用astropy.units.required_by_vounit.msolMass而非u.msolMass_add_prefixes(astrophys.solMass, namespaceglobals(), prefixesTrue) _add_prefixes(astrophys.solRad, namespaceglobals(), prefixesTrue) _add_prefixes(astrophys.solLum, namespaceglobals(), prefixesTrue)这也解释了为何solMass等本体在astrophys中以prefixesFalse定义——前缀变体被集中到本模块既满足 VOUnit 解析需求又不污染顶层命名空间。该模块在 astropy/units/init.py 的set_enabled_units列表中被启用。已弃用单位astropy.units.deprecatedref_api.rst顶部有一条醒目提示astropy.units.deprecated已在 v7.1 弃用并将在未来版本移除。astropy/units/deprecated.py 的源码印证了这一点def_unit([emu], cgs.Bi, namespacelocal_units, docBiot: CGS (EMU) unit of current) # Add only some *prefixes* as deprecated units. _add_prefixes(astrophys.jupiterMass, namespacelocal_units, prefixesTrue) ... def __getattr__(name): if unit : local_units.get(name): warnings.warn( f{name!r} is deprecated since version 7.1, AstropyDeprecationWarning ) return unit raise AttributeError(...) deprecated(since7.1) def enable(): ... return add_enabled_units(local_units)要点这些弃用单位不在顶层astropy.units命名空间需from astropy.units import deprecated后访问__getattr__在属性访问时发出AstropyDeprecationWarningenable()本身也带deprecated(since7.1)。对应测试见 astropy/units/tests/test_deprecated.py。三、物理类型astropy.units.physicalautomodapi:: astropy.units.physical对应 astropy/units/physical.py。该模块维护单位 ↔ 物理类型名的映射并暴露三类 APIPhysicalType类、def_physical_type、get_physical_type__all__ [PhysicalType, def_physical_type, get_physical_type]。模块内一张_units_and_physical_types表把具体单位绑定到物理类型名部分单位对应多个同维度类型例如(si.m / si.s, {speed, velocity}), (si.J, {energy, work, torque}), (si.Pa, {pressure, energy density, stress}), (si.m**-3, number density),get_physical_type接受单位、Quantity、纯数字视为无量纲或类型名字符串返回PhysicalType实例 u.get_physical_type(u.meter ** -2) PhysicalType(column density) u.get_physical_type(energy) PhysicalType({energy, torque, work})PhysicalType支持与等价的PhysicalType或含其名字符串比较、*、/、**等运算可像单位一样做代数组合这在u.quantity_input一类的单位注解校验中非常有用。四、单位格式astropy.units.formatautomodapi:: astropy.units.format对应 astropy/units/format/init.py。该子包聚合各种单位字符串解析/输出器文档说明它们的常规用法是按名称出现在Unit构造函数或UnitBase.to_string方法中很少需要直接导入类from .base import Base from .cds import CDS from .console import Console from .fits import FITS from .generic import Generic from .latex import Latex, LatexInline from .ogip import OGIP from .unicode_format import Unicode from .vounit import VOUnit __all__ [ CDS, FITS, OGIP, Base, Console, Generic, Latex, LatexInline, Unicode, VOUnit, get_format, ]三个辅助函数值得单独说明get_format(format)按名字或类返回格式化器None返回默认的Generic字符串按Base.registry的小写键查表未知名抛ValueErrorknown_formats()/known_parsers()返回Valid formatter/parser names are: ...的帮助文本其中解析器只列出真正实现了parse的子类兼容性处理Fits已在 7.0 改名为FITS模块级__getattr__对旧名Fits发出AstropyDeprecationWarning并返回FITS。这套格式器正是to_string(formatFITS)、to_string(formatlatex)等调用的实现基础也决定了u.Unit(m/s).to_string(vounit)这类输出。五、Quantity配置项astropy.units.quantity.Confref_api.rst的Configuration小节用.. currentmodule:: astropy.units.quantity.. autoclass:: Conf :members:自动文档化了配置类。其定义在 astropy/units/quantity.pyclass Conf(_config.ConfigNamespace): Configuration parameters for Quantity. latex_array_threshold _config.ConfigItem( 100, The maximum size an array Quantity can be before its LaTeX representation for IPython gets summarized ..., ) quantity_convert_int_to_float _config.ConfigItem( [default, always, never], Whether integer values are converted to float when a Quantity is created without an explicit dtype. ..., ) conf Conf()两个配置项的语义第一个参数为默认值ConfigItem对列表型参数表示允许的取值集合默认取首项配置项默认值取值作用latex_array_threshold100整数负数则沿用 numpyget_printoptions数组型Quantity在 IPython 的 LaTeX 表示中超过该元素个数即被摘要化只显首尾若干元素中间以...表示quantity_convert_int_to_floatdefaultdefault/always/never控制未显式指定dtype时整数输入是否上转为floatquantity_convert_int_to_float的三种取值可结合配套上下文管理器理解# default整数输入会被上转为 float但不应改变输入 dtype的操作可覆盖该行为 # 向 QTable 添加列、从序列化列重建时即如此故带单位的整数列保持 dtype # always一律上转为 float且忽略上述覆盖astropy 8.0 及更早的行为 # never整数输入保留其 dtype from astropy.units.quantity import conf with conf.set_temp(quantity_convert_int_to_float, never): ... q u.Quantity([1, 2], u.ct) q.dtype dtype(int64)与配置项配套的还有preserve_dtype_by_default()上下文管理器同文件定义 data np.array([1, 2], dtypeint64) with u.preserve_dtype_by_default(): ... q u.Quantity(data, u.ct) q.dtype dtype(int64)其实现会读取当前conf.quantity_convert_int_to_float当其为default时临时设为neveralways则被尊重从而让应保留输入 dtype的操作如向QTable加列不受全局默认值影响。这一机制与Quantity的dtype参数、_upcast_int_to_float内部函数协同共同决定了整数Quantity的最终 dtype。小结ref_api.rst用automodapi把astropy.units及其十一个子模块聚合为一页 API 参考。结合源码可以归纳出清晰的职责划分标准单位由si/cgs/astrophys/misc/photometric定义并默认启用对数/函数单位在function.units特殊注册表cds、imperial、deprecated默认不启用顶层命名空间需用各自的enable()上下文临时纳入required_by_vounit单独承载 VOUnit 必需的 SI 前缀单位physical提供单位到物理类型名的映射format提供可插拔的字符串解析/输出器quantity.Conf则以latex_array_threshold与quantity_convert_int_to_float两项配置控制Quantity的显示与 dtype 行为。理解这些模块的边界与默认启用集合是正确使用和扩展astropy.units的前提。赞分享科学计算科研数据分析【免费下载链接】astropyAstronomy and astrophysics core library项目地址https://gitcode.com/gh_mirrors/as/astropy点击查看免费下载相关推荐Daft Schema API 详解零物化获取 DataFrame 结构与类型系统的完整参考Daft Schema API 详解零物化获取 DataFrame 结构与类型系统的完整参考 Daft 允许在不物化materializeDataFram大数据数据分析数据工程AI 应用google-drive-ocamlfuse 配置系统详解TOML 配置文件的位置与优先级、全量参数参考与旧格式迁移机制google drive ocamlfuse 配置系统详解TOML 配置文件的位置与优先级、全量参数参考与旧格式迁移机制 本文基于 google drive存储RPCS3汉化5分钟把PS3模拟器调成中文界面RPCS3汉化5分钟把PS3模拟器调成中文界面 这篇文章带你5分钟完成RPCS3汉化固件装好、补丁放进目录、勾选生效PS3模拟器中文设置就齐了。适用当前主虚拟化图形学调试器上一篇openEuler/mugen测试结果分析与报告如何有效调试测试用例下一篇UniProton架构设计揭秘如何实现毫秒级实时响应与低资源占用创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
RELATED

相关推荐

单片机毕设项目:基于单片机的4G老人跌倒检测健康监护与定位装置设计 基于STM32的老人跌倒报警与4G远程监测系统实现(032604)

单片机毕设项目:基于单片机的4G老人跌倒检测健康监护与定位装置设计 基于STM32的老人跌倒报警与4G远程监测系统实现(032604)

博主介绍:✌️码农一枚 ,专注于大学生项目实战开发、讲解和毕业🚢文撰写修改等。全栈领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于嵌入式单片机,Java、小程序技术领域和毕业项目实战 ✌️…

📅 2026/10/14 7:05:14
菲涅尔透镜设计全解析:齿形参数、材料工艺与三大应用避坑指南

菲涅尔透镜设计全解析:齿形参数、材料工艺与三大应用避坑指南

简介:该PDF文档是一篇关于菲涅尔透镜及其应用的论文,适合光学、红外探测、安防监控领域的技术人员与相关专业学习者阅读。文档从菲涅尔透镜由同心圆环凸起构成的设计原理讲起,说明其重量轻、成本低、便于生产运输的特点,并重点分析…

📅 2026/10/14 7:05:14
Pandas数据变频与插值:升采样降采样实战指南

Pandas数据变频与插值:升采样降采样实战指南

数据变频这件事,说白了就是"把时间序列从一种采样频率换成另一种采样频率"。我最早接触它是在处理某传感器采集的振动信号,设备每10ms采一个点,我要跟另一套按秒记录的工艺参数做联动分析,两边频率对不上,什…

📅 2026/10/14 7:00:14
MORE NEWS

更多资讯

📰

Java方法深度解析:从值传递、重载重写到Lambda的设计艺术

Java里最基础也最容易被低估的知识点,就是方法。我面试过不少候选人,问框架技术能聊一小时,但问到“方法传参到底是值传递还是引用传递”,很多人一下就卡住了。工作这些年我越发觉得,方法不仅是一段代码的容器&#xf…

📰

具身智能可信度分级:从系统框架到工程实践的完整指南

1. 项目概述1.1 核心需求解析说起来,具身智能在圈子里已经火了好一阵子了,但真正把它当成一个系统性问题来看待的人并不多。我见过不少团队拿到机器人和机械臂之后,第一反应就是“赶紧跑通一个demo”,结果demo是跑起来了&#xff…

📰

小米14系列定价策略与智能手机成本分析

1. 事件背景与核心议题2023年第四季度,多家国产手机品牌陆续发布新一代旗舰机型,行业普遍出现价格上浮趋势。作为国内市场份额前三的小米集团,其产品定价策略受到消费者广泛关注。在小米14系列发布会后的媒体访谈环节,集团创始人雷…

📰

从极简命名到自动化实践:拆解轻量级任务聚合工具的设计与实现

1. 从“rea”这个标题说起:一个极简命名背后的完整项目思维 第一次看到“rea”这个标题,很多人会愣一下——三个字母,没有上下文,没有说明,甚至不知道它指代什么。但恰恰是这种极简命名,在技术圈和创意圈里…

📰

Python约束求解实战:2018刑侦科推理测试题穷举与剪枝

1. 这道题到底在考什么第一次看到"2018刑侦科推理测试题"这个标题,很多人以为是某个真实案件的卷宗,点进去才发现是一道纯逻辑推理题。它最早在2018年刷屏,号称是某类推理能力测试的题目,一共10道选择题,每道…

📰

React Native鸿蒙应用Tab导航实现指南

1. 项目概述 作为一名从React Native转战鸿蒙开发的工程师,我深刻理解跨平台开发中导航系统的重要性。这次要分享的是一个完整的React Native鸿蒙应用主页Tab导航实现方案,包含底部导航栏、页面切换和图标状态切换三大核心功能。 在移动应用开发中&…

TODAY

今日更新

THIS WEEK

本周精选

THIS MONTH

本月热门

读完文章,想聊聊您的网站?

告诉我们您的行业与需求,资深顾问一对一梳理方案与报价,全程免费。

📞 💬