惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
N
News and Events Feed by Topic
S
Schneier on Security
G
GRAHAM CLULEY
Scott Helme
Scott Helme
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
C
CERT Recently Published Vulnerability Notes
T
The Exploit Database - CXSecurity.com
C
Cisco Blogs
T
The Blog of Author Tim Ferriss
Cisco Talos Blog
Cisco Talos Blog
P
Privacy & Cybersecurity Law Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 司徒正美
Blog — PlanetScale
Blog — PlanetScale
Project Zero
Project Zero
MyScale Blog
MyScale Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Apple Machine Learning Research
Apple Machine Learning Research
小众软件
小众软件
The Last Watchdog
The Last Watchdog
Vercel News
Vercel News
The Cloudflare Blog
C
Check Point Blog
Help Net Security
Help Net Security
Microsoft Security Blog
Microsoft Security Blog
AI
AI
Simon Willison's Weblog
Simon Willison's Weblog
云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
腾讯CDC
NISL@THU
NISL@THU
S
Security @ Cisco Blogs
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
S
SegmentFault 最新的问题
MongoDB | Blog
MongoDB | Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threatpost
AWS News Blog
AWS News Blog
Cloudbric
Cloudbric
N
News and Events Feed by Topic
PCI Perspectives
PCI Perspectives
S
Securelist
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
Vulnerabilities – Threatpost
S
Secure Thoughts

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Astrophysics & AI with Python: Unlocking the Secrets of Spectral Lines and Redshift
Programming Central · 2026-06-23 · via DEV Community

The universe is a symphony of light, but to the naked eye, it often looks like a static painting. Stars are points; galaxies are fuzzy patches. But hidden within that light is a rich, dynamic story—a cosmic fingerprint that tells us exactly what an object is made of, how hot it is, and—most importantly—how fast it is moving away from us.

This is the power of spectroscopy, the astronomer’s most indispensable tool. By breaking light into its constituent wavelengths, we transform a single beam of photons into a detailed dataset. In this guide, we’ll explore the theoretical foundations of spectral analysis, the physics of redshift, and how to build a Python "Stellar Speedometer" to calculate the expansion of the universe from your own computer.

The Cosmic Fingerprint: Emission and Absorption

At its core, spectroscopy relies on quantum mechanics. Electrons orbiting an atom can only exist at specific energy levels. When an electron jumps between these levels, it must absorb or emit a photon with energy exactly equal to the difference between those levels.

Because energy is related to wavelength ( E=hc/λE = hc/\lambda ), every element has a unique, immutable set of "rest wavelengths" ( λrest\lambda_{rest} ) where it absorbs or emits light.

  • Emission Lines: When hot, diffuse gas (like a nebula) is excited, electrons drop back down and release photons at specific wavelengths, creating bright spikes on a spectrum.
  • Absorption Lines: When light from a hot source (like a star's core) passes through cooler gas, the gas absorbs specific wavelengths, leaving dark dips.

By matching the observed pattern to known laboratory data, we can identify the chemical composition of a star billions of light-years away.

The Doppler Effect: From Sirens to Stars

While the pattern tells us what the object is, the position of the pattern tells us where it is going. This is governed by the Doppler effect—the same phenomenon that changes the pitch of an ambulance siren as it passes you.

  1. Blueshift: If an object moves toward us, light waves are compressed. The observed wavelength ( λobs\lambda_{obs} ) is shorter than the rest wavelength. The spectrum shifts blue.
  2. Redshift: If an object moves away from us, light waves are stretched. The observed wavelength is longer. The spectrum shifts red.

We quantify this shift using the dimensionless parameter zz :

z=λobs−λrestλrest z = \frac{\lambda_{obs} - \lambda_{rest}}{\lambda_{rest}}

For nearby objects, we can calculate velocity simply by multiplying the redshift by the speed of light ( v≈c⋅zv \approx c \cdot z ). However, for distant galaxies moving at a significant fraction of light speed, we must use the full relativistic formula to ensure accuracy.

Line Profile Analysis: Finding the Center

In a perfect world, a spectral line would be an infinitely thin spike. In reality, thermal motion and collisions broaden the line into a shape called a profile. To find the precise center wavelength ( λobs\lambda_{obs} ) amidst noisy data, we fit mathematical functions to the data:

  • Gaussian: Models pure thermal broadening (a standard bell curve).
  • Lorentzian: Models pressure broadening (heavy wings, falling off slowly).
  • Voigt Profile: The gold standard. It is the convolution of both Gaussian and Lorentzian profiles, representing the complex physics of stellar atmospheres.

This fitting process is essentially an optimization problem. Just as we use gradient descent to train neural networks, we use non-linear least-squares fitting (like scipy.optimize.curve_fit) to minimize the difference between our mathematical model and the observed data, extracting the true λobs\lambda_{obs} .

Python Implementation: The Stellar Speedometer

Let’s put theory into practice. The following Python script acts as a "Stellar Speedometer." We will simulate observing the famous H-alpha emission line (Rest wavelength: 6563.06563.0 Å) from a distant galaxy and calculate its recession velocity.

import numpy as np

# 1. Define Universal Constants
# Speed of light (c) in kilometers per second (km/s).
C = 299792.458 

# 2. Define Rest Wavelength (The Theoretical Baseline)
# The H-alpha emission line wavelength (in Angstroms).
lambda_rest = 6563.0 

# 3. Define Observed Wavelength (The Simulated Data Input)
# Simulated observation of the H-alpha line from a distant source.
# Note: This observed value (7219.3 Å) is longer than the rest value, indicating redshift.
lambda_observed = 7219.3 

# 4. Calculate Redshift (z)
# The fundamental definition of redshift (z): 
# z = (lambda_observed - lambda_rest) / lambda_rest
redshift_z = (lambda_observed - lambda_rest) / lambda_rest

# 5. Calculate Velocity (v) using the Non-Relativistic Approximation
# For small redshifts (z < 0.1), the velocity (v) is approximated by v = c * z.
velocity_km_s = C * redshift_z

# 6. Output and Interpretation
print(f"--- Astrophysical Redshift Calculation ---")
print(f"Rest Wavelength (Hydrogen H-alpha): {lambda_rest:.2f} Å")
print(f"Observed Wavelength:                {lambda_observed:.2f} Å")
print("-" * 40)
print(f"Calculated Redshift (z):            {redshift_z:.4f}")
print(f"Inferred Recession Velocity (v):    {velocity_km_s:.2f} km/s")

# 7. Relativistic Check (Advanced Context)
# If velocity is > 10% of c, the non-relativistic approximation introduces error.
if velocity_km_s > 0.1 * C:
    print("\n[WARNING] Velocity exceeds 10% of speed of light. Using relativistic correction.")
    relativistic_factor = ((redshift_z + 1)**2 - 1) / ((redshift_z + 1)**2 + 1)
    velocity_relativistic = C * relativistic_factor
    print(f"Relativistic Velocity (v_rel):      {velocity_relativistic:.2f} km/s")

Code Breakdown

  1. Constants & Inputs: We define the speed of light and the H-alpha rest wavelength ( 6563.06563.0 Å). The lambda_observed represents our raw data point.
  2. The Redshift Calculation: We apply the formula z=(λobs−λrest)/λrestz = (\lambda_{obs} - \lambda_{rest}) / \lambda_{rest} . A positive zz confirms the galaxy is receding.
  3. Velocity Conversion: We multiply zz by cc to get a physical speed. In our example, the galaxy is moving away at roughly 30,00030,000 km/s.
  4. Relativistic Warning: The code checks if the velocity is significant. If we were observing a quasar with a redshift of z=1z=1 , the simple v=c⋅zv=c \cdot z formula would break down, and we would need the relativistic correction included in the script.

Conclusion

Spectroscopy is the bridge between raw starlight and physical understanding. By analyzing the shift in emission lines, we can measure the velocity of distant galaxies. By combining these velocities with Hubble's Law ( v=H0⋅Dv = H_0 \cdot D ), we can map the expansion of the universe itself.

Whether you are fitting a Gaussian curve to noisy data or calculating the relativistic velocity of a quasar, the combination of astrophysics and Python provides the tools to decode the universe's hidden messages.

Let's Discuss

  1. The Limits of Light: If we discovered a galaxy with a redshift of z=10z = 10 , why would our simple non-relativistic velocity calculation ( v=c⋅zv = c \cdot z ) be completely invalid? What does a redshift that high physically imply about the space between us and that galaxy?
  2. AI in Spectroscopy: Modern telescopes generate terabytes of spectral data every night. How do you think machine learning algorithms (like the ones used to fit the Voigt profiles mentioned in the text) could improve the speed or accuracy of detecting exoplanet atmospheres compared to manual analysis?

The concepts and code demonstrated here are drawn directly from the comprehensive roadmap laid out in the ebook
Astrophysics & AI: Building Research Agents for Astronomy, Cosmology, and SETI. You can find it here. Check all the other 50 Programming & AI ebooks with python, typescript, swift, c#: here