Token导航 LogoToken导航

Agent Skill · 研究检索

numpy-numerical-analysis(numpy 数值分析)

numpy-numerical-analysis 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

numpy-numerical-analysis 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为权限未标注;许可证为 MIT,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 49,433。

总安装 652周安装 28GitHub Stars 8下载 228核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
MIT

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:numpy-numerical-analysis(numpy 数值分析)
来源仓库:https://github.com/vamseeachanta/workspace-hub
仓库路径:skills/numpy-numerical-analysis
安装命令:
npx skills add https://github.com/vamseeachanta/workspace-hub --skill numpy-numerical-analysis
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/vamseeachanta/workspace-hub --skill numpy-numerical-analysis

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

numpy-numerical-analysis 用于查找、检索和筛选相关信息,适合在主流 Agent 宿主中快速定位候选结果。适用于围绕 NumPy 数值分析功能进行信息检索。通过 npx skills add 命令安装,需结合原始 README 确认具体用法。

安装前建议确认权限范围、维护状态及是否触发联网或文件读写操作。可结合来源仓库进一步核验功能细节和使用限制。

来源仓库内路径:skills/numpy-numerical-analysis

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/vamseeachanta/workspace-hub --skill numpy-nume…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    权限没有明确标注,第一次使用时只给一个无关紧要的任务,观察它到底读了哪些文件和网络。

常见问题

6 条

numpy-numerical-analysis 怎么安装?

在终端执行 npx skills add https://github.com/vamseeachanta/workspace-hub --skill numpy-numerical-anal…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

numpy-numerical-analysis 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

numpy-numerical-analysis 需要什么权限?

权限级别没有明确标注。第一次使用时建议只给无关紧要的任务,观察它实际读写了哪些内容。

numpy-numerical-analysis 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

numpy-numerical-analysis 用的人多吗?

公开数据是累计安装 652 次,近一周安装 28 次,下载 228 次,GitHub 8 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

numpy-numerical-analysis 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 3 个目录同时收录,说明这个 Skill 流传比较广。
  • 许可证明确为 MIT,商用和分发边界好判断。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。
  • 需要许可证清楚、并且有第三方扫描结果的团队项目。

不太适合

  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
numpy-numerical-analysis

numpy 数值分析 · 本页

6528权限未标注MIT通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

NumPy Numerical Analysis Skill

Master NumPy for efficient numerical computations, matrix operations, FFT analysis, and linear algebra in marine and offshore engineering applications.

When to Use This Skill

Use NumPy numerical analysis when you need:

  • Matrix operations - 6DOF equations of motion, mass matrices, stiffness matrices
  • FFT analysis - Frequency domain analysis, spectral density, response spectra
  • Linear algebra - Solve linear systems, eigenvalue analysis, matrix decomposition
  • Array operations - Efficient computations on large datasets
  • Numerical integration - Time-stepping, ODE solvers
  • Signal processing - Filtering, windowing, convolution

Avoid when:

  • Symbolic mathematics needed (use SymPy)
  • Sparse matrices dominate (use SciPy sparse)
  • GPU acceleration required (use CuPy or JAX)
  • Distributed computing needed (use Dask)

Core Capabilities

1. Array Creation and Operations

Array Creation:

import numpy as np

# Create arrays
zeros = np.zeros((3, 3))
ones = np.ones((3, 3))
identity = np.eye(3)
arange = np.arange(0, 10, 0.1)  # 0 to 10 with step 0.1
linspace = np.linspace(0, 10, 100)  # 100 points from 0 to 10

# From list
arr = np.array([1, 2, 3, 4, 5])

# Multi-dimensional
matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

# Random arrays
random_uniform = np.random.rand(3, 3)  # Uniform [0, 1)
random_normal = np.random.randn(3, 3)  # Standard normal
random_int = np.random.randint(0, 100, size=(3, 3))

Array Operations:

# Element-wise operations
a = np.array([1, 2, 3, 4, 5])
b = np.array([10, 20, 30, 40, 50])

c = a + b  # [11, 22, 33, 44, 55]
d = a * b  # [10, 40, 90, 160, 250]
e = a ** 2  # [1, 4, 9, 16, 25]

# Mathematical functions
sin_a = np.sin(a)
cos_a = np.cos(a)
exp_a = np.exp(a)
log_a = np.log(a)
sqrt_a = np.sqrt(a)

# Statistical operations
mean = np.mean(a)
std = np.std(a)
var = np.var(a)
min_val = np.min(a)
max_val = np.max(a)

2. Matrix Operations

Matrix Multiplication:

def compute_force_response(
    mass_matrix: np.ndarray,
    stiffness_matrix: np.ndarray,
    force_vector: np.ndarray
) -> np.ndarray:
    """
    Compute structural response: F = K * x
    Solve for displacement: x = K^-1 * F

    Args:
        mass_matrix: Mass matrix [M]
        stiffness_matrix: Stiffness matrix [K]
        force_vector: Applied force vector {F}

    Returns:
        Displacement vector {x}
    """
    # Static response (ignoring mass for now)
    displacement = np.linalg.solve(stiffness_matrix, force_vector)

    return displacement

# Example: 3DOF spring-mass system
K = np.array([
    [200, -100, 0],
    [-100, 200, -100],
    [0, -100, 100]
])  # Stiffness matrix (N/m)

F = np.array([1000, 0, 0])  # Force at first node (N)

x = compute_force_response(None, K, F)
print(f"Displacements: {x} m")

Matrix Properties:

def analyze_matrix_properties(matrix: np.ndarray) -> dict:
    """
    Analyze matrix properties for structural analysis.

    Args:
        matrix: Input matrix (mass or stiffness)

    Returns:
        Dictionary with matrix properties
    """
    properties = {}

    # Determinant
    properties['determinant'] = np.linalg.det(matrix)

    # Condition number (numerical stability indicator)
    properties['condition_number'] = np.linalg.cond(matrix)

    # Rank
    properties['rank'] = np.linalg.matrix_rank(matrix)

    # Eigenvalues and eigenvectors
    eigenvalues, eigenvectors = np.linalg.eig(matrix)
    properties['eigenvalues'] = eigenvalues
    properties['eigenvectors'] = eigenvectors

    # Is symmetric?
    properties['is_symmetric'] = np.allclose(matrix, matrix.T)

    # Is positive definite? (all eigenvalues > 0)
    properties['is_positive_definite'] = np.all(eigenvalues > 0)

    return properties

# Example: Check stiffness matrix properties
K = np.array([
    [200, -100, 0],
    [-100, 200, -100],
    [0, -100, 100]
])

props = analyze_matrix_properties(K)
print(f"Determinant: {props['determinant']:.2f}")
print(f"Condition number: {props['condition_number']:.2f}")
print(f"Eigenvalues: {props['eigenvalues']}")
print(f"Positive definite: {props['is_positive_definite']}")

3. 6DOF Equations of Motion

6DOF Dynamics:

def solve_6dof_equation_of_motion(
    mass_matrix: np.ndarray,
    damping_matrix: np.ndarray,
    stiffness_matrix: np.ndarray,
    force_vector: np.ndarray,
    displacement: np.ndarray,
    velocity: np.ndarray,
    dt: float
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Solve 6DOF equation of motion using Newmark-Beta method.

    [M]{ẍ} + [C]{ẋ} + [K]{x} = {F}

    Args:
        mass_matrix: 6x6 mass matrix [M]
        damping_matrix: 6x6 damping matrix [C]
        stiffness_matrix: 6x6 stiffness matrix [K]
        force_vector: 6x1 force vector {F}
        displacement: Current displacement {x_n}
        velocity: Current velocity {ẋ_n}
        dt: Time step

    Returns:
        (acceleration, velocity, displacement) at next time step
    """
    # Newmark-Beta parameters
    beta = 0.25  # Constant average acceleration
    gamma = 0.5

    # Effective stiffness
    K_eff = (
        mass_matrix / (beta * dt**2) +
        damping_matrix * gamma / (beta * dt) +
        stiffness_matrix
    )

    # Effective force at next time step
    F_eff = (
        force_vector +
        mass_matrix @ (
            displacement / (beta * dt**2) +
            velocity / (beta * dt)
        ) +
        damping_matrix @ (
            displacement * gamma / (beta * dt) -
            velocity * (1 - gamma / beta)
        )
    )

    # Solve for displacement at next time step
    displacement_next = np.linalg.solve(K_eff, F_eff)

    # Calculate velocity at next time step
    velocity_next = (
        gamma / (beta * dt) * (displacement_next - displacement) +
        (1 - gamma / beta) * velocity
    )

    # Calculate acceleration at next time step
    acceleration_next = (
        (displacement_next - displacement) / (beta * dt**2) -
        velocity / (beta * dt)
    )

    return acceleration_next, velocity_next, displacement_next

# Example: Single time step for floating vessel
M = np.diag([100000, 100000, 100000, 5e6, 5e6, 5e6])  # Mass matrix
C = np.diag([50000, 50000, 50000, 2e5, 2e5, 2e5])    # Damping
K = np.diag([1000, 1000, 2000, 5e4, 5e4, 1e4])       # Restoring

F = np.array([1e6, 0, 0, 0, 0, 0])  # Surge force 1 MN
x = np.zeros(6)  # Initial displacement
v = np.zeros(6)  # Initial velocity

a, v_new, x_new = solve_6dof_equation_of_motion(M, C, K, F, x, v, dt=0.01)

print(f"Acceleration: {a}")
print(f"Velocity: {v_new}")
print(f"Displacement: {x_new}")

4. FFT and Frequency Analysis

FFT for Spectral Analysis:

def compute_fft_spectrum(
    time_series: np.ndarray,
    dt: float,
    window: str = 'hann'
) -> tuple[np.ndarray, np.ndarray]:
    """
    Compute FFT spectrum of time series.

    Args:
        time_series: Time series data
        dt: Time step
        window: Window function ('hann', 'hamming', 'blackman')

    Returns:
        (frequencies, amplitude_spectrum)
    """
    n = len(time_series)

    # Apply window
    if window == 'hann':
        windowed = time_series * np.hanning(n)
    elif window == 'hamming':
        windowed = time_series * np.hamming(n)
    elif window == 'blackman':
        windowed = time_series * np.blackman(n)
    else:
        windowed = time_series

    # Compute FFT
    fft_result = np.fft.fft(windowed)

    # Compute frequencies
    frequencies = np.fft.fftfreq(n, d=dt)

    # Amplitude spectrum (single-sided)
    amplitude = np.abs(fft_result)[:n//2] * 2 / n
    frequencies_positive = frequencies[:n//2]

    return frequencies_positive, amplitude

# Example: Analyze wave elevation time series
import numpy as np

# Generate sample wave elevation (3 components)
t = np.linspace(0, 100, 10000)  # 100 seconds, 10000 points
dt = t[1] - t[0]

# Wave components: 6s, 8s, 10s periods
wave = (
    2.0 * np.sin(2*np.pi*t / 6) +
    1.5 * np.sin(2*np.pi*t / 8) +
    1.0 * np.sin(2*np.pi*t / 10)
)

# Add noise
wave += 0.2 * np.random.randn(len(t))

# Compute spectrum
freq, amplitude = compute_fft_spectrum(wave, dt, window='hann')

# Find peaks
peak_indices = np.argsort(amplitude)[-3:]  # Top 3 peaks
peak_frequencies = freq[peak_indices]
peak_periods = 1 / peak_frequencies

print("Detected wave periods:")
for period in sorted(peak_periods, reverse=True):
    print(f"  T = {period:.2f} s")

Power Spectral Density:

def compute_power_spectral_density(
    time_series: np.ndarray,
    dt: float,
    nfft: int = None
) -> tuple[np.ndarray, np.ndarray]:
    """
    Compute power spectral density using Welch's method.

    Args:
        time_series: Time series data
        dt: Time step
        nfft: FFT length (None = length of time series)

    Returns:
        (frequencies, PSD)
    """
    from scipy import signal

    # Compute PSD using Welch's method
    frequencies, psd = signal.welch(
        time_series,
        fs=1/dt,
        nperseg=nfft or len(time_series)//8,
        window='hann'
    )

    return frequencies, psd

# Example: Wave spectral analysis
t = np.linspace(0, 3600, 36000)  # 1 hour, 10 Hz sampling
dt = t[1] - t[0]

# JONSWAP spectrum simulation (simplified)
wave_elevation = np.random.randn(len(t)) * 2.0  # Simplified

freq, psd = compute_power_spectral_density(wave_elevation, dt)

# Calculate Hs from PSD
m0 = np.trapz(psd, freq)  # Zero-order moment
Hs = 4 * np.sqrt(m0)

print(f"Significant wave height: {Hs:.2f} m")

5. Linear Algebra Operations

Eigenvalue Analysis:

def natural_frequency_analysis(
    mass_matrix: np.ndarray,
    stiffness_matrix: np.ndarray
) -> dict:
    """
    Perform eigenvalue analysis to find natural frequencies and mode shapes.

    [K]{ϕ} = ω²[M]{ϕ}

    Args:
        mass_matrix: Mass matrix [M]
        stiffness_matrix: Stiffness matrix [K]

    Returns:
        Dictionary with natural frequencies and mode shapes
    """
    # Solve generalized eigenvalue problem
    eigenvalues, eigenvectors = np.linalg.eig(
        np.linalg.solve(mass_matrix, stiffness_matrix)
    )

    # Natural frequencies (rad/s)
    natural_frequencies_rad = np.sqrt(eigenvalues)

    # Natural frequencies (Hz)
    natural_frequencies_hz = natural_frequencies_rad / (2 * np.pi)

    # Sort by frequency
    sort_indices = np.argsort(natural_frequencies_hz)
    natural_frequencies_hz = natural_frequencies_hz[sort_indices]
    eigenvectors = eigenvectors[:, sort_indices]

    # Periods
    periods = 1 / natural_frequencies_hz

    return {
        'frequencies_hz': natural_frequencies_hz,
        'frequencies_rad_s': natural_frequencies_rad[sort_indices],
        'periods_s': periods,
        'mode_shapes': eigenvectors
    }

# Example: FPSO natural frequencies
# 6DOF system
M = np.diag([150000, 150000, 150000, 1e7, 1e7, 5e6])  # Mass matrix (tonnes, tonne-m²)
K = np.diag([500, 500, 3000, 5e5, 5e5, 1e5])          # Stiffness (kN/m, kN-m/rad)

results = natural_frequency_analysis(M, K)

print("Natural Frequencies:")
for i, (freq, period) in enumerate(zip(results['frequencies_hz'], results['periods_s'])):
    dof_names = ['Surge', 'Sway', 'Heave', 'Roll', 'Pitch', 'Yaw']
    print(f"  Mode {i+1} ({dof_names[i]}): f = {freq:.4f} Hz, T = {period:.2f} s")

Matrix Decomposition:

def lu_decomposition_solve(A: np.ndarray, b: np.ndarray) -> np.ndarray:
    """
    Solve linear system using LU decomposition.

    Args:
        A: Coefficient matrix
        b: Right-hand side vector

    Returns:
        Solution vector x
    """
    from scipy.linalg import lu

    # LU decomposition
    P, L, U = lu(A)

    # Solve Ly = Pb
    y = np.linalg.solve(L, P @ b)

    # Solve Ux = y
    x = np.linalg.solve(U, y)

    return x

# Example
A = np.array([[4, -1, 0],
              [-1, 4, -1],
              [0, -1, 3]])
b = np.array([15, 10, 10])

x = lu_decomposition_solve(A, b)
print(f"Solution: {x}")

6. Numerical Integration

Time-Stepping Integration:

def runge_kutta_4th_order(
    derivative_func,
    y0: np.ndarray,
    t: np.ndarray
) -> np.ndarray:
    """
    4th-order Runge-Kutta integration.

    Args:
        derivative_func: Function dy/dt = f(t, y)
        y0: Initial conditions
        t: Time array

    Returns:
        Solution array
    """
    n = len(t)
    y = np.zeros((n, len(y0)))
    y[0] = y0

    for i in range(n - 1):
        dt = t[i+1] - t[i]

        k1 = derivative_func(t[i], y[i])
        k2 = derivative_func(t[i] + dt/2, y[i] + k1*dt/2)
        k3 = derivative_func(t[i] + dt/2, y[i] + k2*dt/2)
        k4 = derivative_func(t[i] + dt, y[i] + k3*dt)

        y[i+1] = y[i] + (dt/6) * (k1 + 2*k2 + 2*k3 + k4)

    return y

# Example: Simple harmonic oscillator
# m*x'' + k*x = 0
# y = [x, v], dy/dt = [v, -k/m*x]

def oscillator_derivatives(t, y):
    """Simple harmonic oscillator."""
    m = 1.0  # Mass
    k = 4.0  # Stiffness (omega = 2 rad/s, T = pi s)

    x, v = y
    dxdt = v
    dvdt = -k/m * x

    return np.array([dxdt, dvdt])

# Initial conditions
y0 = np.array([1.0, 0.0])  # x = 1, v = 0

# Time array
t = np.linspace(0, 10, 1000)

# Solve
solution = runge_kutta_4th_order(oscillator_derivatives, y0, t)

print(f"Final position: {solution[-1, 0]:.4f}")
print(f"Final velocity: {solution[-1, 1]:.4f}")

Trapezoidal Integration:

def integrate_spectrum(
    frequencies: np.ndarray,
    spectral_density: np.ndarray
) -> float:
    """
    Integrate spectral density to get variance.

    m_0 = ∫ S(f) df

    Args:
        frequencies: Frequency array
        spectral_density: Spectral density array

    Returns:
        Integral (variance)
    """
    variance = np.trapz(spectral_density, frequencies)

    return variance

# Example: Calculate significant wave height from spectrum
freq = np.linspace(0.05, 0.5, 100)  # Hz
S = 10 * freq**(-5)  # Simplified spectrum

m0 = integrate_spectrum(freq, S)
Hs = 4 * np.sqrt(m0)

print(f"Significant wave height: {Hs:.2f} m")

Complete Examples

Example 1: 6DOF Time-Domain Simulation

import numpy as np
import plotly.graph_objects as go

def simulate_6dof_vessel_motion(
    mass_matrix: np.ndarray,
    damping_matrix: np.ndarray,
    stiffness_matrix: np.ndarray,
    force_time_series: np.ndarray,
    time: np.ndarray
) -> dict:
    """
    Complete 6DOF time-domain simulation of vessel motion.

    Args:
        mass_matrix: 6x6 mass matrix
        damping_matrix: 6x6 damping matrix
        stiffness_matrix: 6x6 stiffness matrix
        force_time_series: Force time series (n_steps x 6)
        time: Time array

    Returns:
        Dictionary with motion time series
    """
    n_steps = len(time)
    dt = time[1] - time[0]

    # Initialize arrays
    displacement = np.zeros((n_steps, 6))
    velocity = np.zeros((n_steps, 6))
    acceleration = np.zeros((n_steps, 6))

    # Initial conditions (at rest)
    displacement[0] = np.zeros(6)
    velocity[0] = np.zeros(6)

    # Time-stepping loop
    for i in range(n_steps - 1):
        a, v, d = solve_6dof_equation_of_motion(
            mass_matrix,
            damping_matrix,
            stiffness_matrix,
            force_time_series[i],
            displacement[i],
            velocity[i],
            dt
        )

        acceleration[i+1] = a
        velocity[i+1] = v
        displacement[i+1] = d

    return {
        'time': time,
        'displacement': displacement,
        'velocity': velocity,
        'acceleration': acceleration
    }

# Define FPSO properties
M = np.diag([150000, 150000, 150000, 1e7, 1e7, 5e6])  # Mass
C = np.diag([50000, 50000, 100000, 5e5, 5e5, 2e5])    # Damping
K = np.diag([500, 500, 3000, 5e4, 5e4, 1e4])          # Stiffness

# Simulate wave forces (simplified)
time = np.linspace(0, 100, 10000)
dt = time[1] - time[0]

# Wave force in surge (1 MN amplitude, 10s period)
F = np.zeros((len(time), 6))
F[:, 0] = 1e6 * np.sin(2*np.pi*time / 10)

# Simulate
results = simulate_6dof_vessel_motion(M, C, K, F, time)

# Plot results
fig = go.Figure()

dof_names = ['Surge', 'Sway', 'Heave', 'Roll', 'Pitch', 'Yaw']
for i in range(3):  # Plot first 3 DOFs
    fig.add_trace(go.Scatter(
        x=results['time'],
        y=results['displacement'][:, i],
        name=dof_names[i],
        mode='lines'
    ))

fig.update_layout(
    title='Vessel Motion - Translation DOFs',
    xaxis_title='Time (s)',
    yaxis_title='Displacement (m)',
    hovermode='x unified'
)

fig.write_html('reports/vessel_motion_6dof.html')

# Print statistics
print("Motion Statistics:")
for i, name in enumerate(dof_names):
    print(f"{name}:")
    print(f"  Max: {np.max(np.abs(results['displacement'][:, i])):.3f}")
    print(f"  Std: {np.std(results['displacement'][:, i]):.3f}")

Example 2: RAO Calculation from FFT

def calculate_rao_from_time_series(
    wave_elevation: np.ndarray,
    vessel_response: np.ndarray,
    dt: float
) -> tuple[np.ndarray, np.ndarray]:
    """
    Calculate Response Amplitude Operator (RAO) from time series.

    RAO(ω) = |Response(ω)| / |Wave(ω)|

    Args:
        wave_elevation: Wave elevation time series
        vessel_response: Vessel response time series
        dt: Time step

    Returns:
        (frequencies, RAO)
    """
    # FFT of wave and response
    freq_wave, amplitude_wave = compute_fft_spectrum(wave_elevation, dt)
    freq_response, amplitude_response = compute_fft_spectrum(vessel_response, dt)

    # Calculate RAO
    # Avoid division by zero
    rao = np.where(
        amplitude_wave > 1e-6,
        amplitude_response / amplitude_wave,
        0
    )

    return freq_wave, rao

# Example: Calculate heave RAO
time = np.linspace(0, 100, 10000)
dt = time[1] - time[0]

# Regular wave (Hs = 2m, T = 8s)
wave = 1.0 * np.sin(2*np.pi*time / 8)

# Vessel heave response (with RAO ~1.5)
heave = 1.5 * np.sin(2*np.pi*time / 8 - np.pi/6)  # 30° phase lag

# Calculate RAO
freq, rao = calculate_rao_from_time_series(wave, heave, dt)

# Plot
fig = go.Figure()
fig.add_trace(go.Scatter(
    x=freq,
    y=rao,
    name='Heave RAO',
    mode='lines'
))

fig.update_layout(
    title='Heave Response Amplitude Operator',
    xaxis_title='Frequency (Hz)',
    yaxis_title='RAO (m/m)',
    xaxis_range=[0, 0.5]
)

fig.write_html('reports/heave_rao.html')

# Find peak
peak_idx = np.argmax(rao[freq < 0.5])
peak_freq = freq[peak_idx]
peak_period = 1 / peak_freq

print(f"Peak RAO: {rao[peak_idx]:.2f} at T = {peak_period:.2f} s")

Example 3: Mooring Stiffness Matrix

def calculate_mooring_stiffness_matrix(
    num_lines: int,
    pretension: float,
    fairlead_radius: float,
    fairlead_depth: float,
    line_azimuth: np.ndarray,
    weight_per_length: float
) -> np.ndarray:
    """
    Calculate mooring system stiffness matrix.

    Args:
        num_lines: Number of mooring lines
        pretension: Pretension per line (kN)
        fairlead_radius: Horizontal distance from center to fairlead (m)
        fairlead_depth: Depth of fairlead below waterline (m)
        line_azimuth: Azimuth angle of each line (degrees)
        weight_per_length: Line weight per unit length (kN/m)

    Returns:
        6x6 mooring stiffness matrix
    """
    K_mooring = np.zeros((6, 6))

    # Individual line stiffness
    # Simplified: K_line = w * T / d
    k_line = weight_per_length * pretension / fairlead_depth

    for i in range(num_lines):
        theta = np.radians(line_azimuth[i])

        # Direction cosines
        cx = np.cos(theta)
        cy = np.sin(theta)

        # Surge-surge
        K_mooring[0, 0] += k_line * cx**2

        # Sway-sway
        K_mooring[1, 1] += k_line * cy**2

        # Surge-sway coupling
        K_mooring[0, 1] += k_line * cx * cy
        K_mooring[1, 0] += k_line * cx * cy

        # Yaw-yaw (moment = force * lever arm)
        K_mooring[5, 5] += k_line * fairlead_radius**2

        # Surge-yaw coupling
        K_mooring[0, 5] += k_line * fairlead_radius * cy
        K_mooring[5, 0] += k_line * fairlead_radius * cy

        # Sway-yaw coupling
        K_mooring[1, 5] -= k_line * fairlead_radius * cx
        K_mooring[5, 1] -= k_line * fairlead_radius * cx

    return K_mooring

# Example: 12-line spread mooring
num_lines = 12
azimuths = np.array([0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330])

K = calculate_mooring_stiffness_matrix(
    num_lines=12,
    pretension=2000,  # kN
    fairlead_radius=100,  # m
    fairlead_depth=25,  # m
    line_azimuth=azimuths,
    weight_per_length=1.2  # kN/m
)

print("Mooring Stiffness Matrix:")
print(K)

# Check symmetry
print(f"\nIs symmetric: {np.allclose(K, K.T)}")

Example 4: Statistical Analysis of Extremes

def extreme_value_statistics(
    data: np.ndarray,
    method: str = '3hr_max'
) -> dict:
    """
    Perform extreme value statistical analysis.

    Args:
        data: Time series data
        method: '3hr_max' or 'annual_max'

    Returns:
        Statistical parameters
    """
    if method == '3hr_max':
        # Extract 3-hour maxima
        chunk_size = int(3 * 3600 / 0.1)  # Assuming 0.1s time step
        n_chunks = len(data) // chunk_size

        maxima = np.array([
            np.max(data[i*chunk_size:(i+1)*chunk_size])
            for i in range(n_chunks)
        ])

    elif method == 'annual_max':
        maxima = data  # Assume already annual maxima

    # Fit Gumbel distribution
    # μ = mean, σ = std
    mu = np.mean(maxima)
    sigma = np.std(maxima)

    # Gumbel parameters
    beta = sigma * np.sqrt(6) / np.pi
    mu_gumbel = mu - 0.5772 * beta

    # Extreme values for different return periods
    return_periods = np.array([1, 10, 100, 10000])  # years
    extreme_values = mu_gumbel - beta * np.log(-np.log(1 - 1/return_periods))

    return {
        'mean': mu,
        'std': sigma,
        'gumbel_location': mu_gumbel,
        'gumbel_scale': beta,
        'return_periods': return_periods,
        'extreme_values': extreme_values
    }

# Example
# Generate sample tension data
time = np.linspace(0, 86400, 864000)  # 24 hours, 0.1s timestep
tension = 2000 + 500 * np.random.rayleigh(scale=1.0, size=len(time))

stats = extreme_value_statistics(tension, method='3hr_max')

print("Extreme Value Statistics:")
print(f"Mean: {stats['mean']:.1f} kN")
print(f"Std: {stats['std']:.1f} kN")
print("\nExtreme Values:")
for T, val in zip(stats['return_periods'], stats['extreme_values']):
    print(f"  {T:>5} year: {val:.1f} kN")

Example 5: Convolution for Impulse Response

def convolve_impulse_response(
    impulse_response: np.ndarray,
    force_time_series: np.ndarray,
    dt: float
) -> np.ndarray:
    """
    Convolve impulse response with force time series.

    Response(t) = ∫ h(τ) * F(t-τ) dτ

    Args:
        impulse_response: Impulse response function
        force_time_series: Force time series
        dt: Time step

    Returns:
        Response time series
    """
    # Convolution
    response = np.convolve(impulse_response, force_time_series, mode='same') * dt

    return response

# Example: System response to random force
t = np.linspace(0, 10, 1000)
dt = t[1] - t[0]

# Impulse response (damped oscillator)
omega = 2 * np.pi  # 1 Hz natural frequency
zeta = 0.1  # 10% damping
h = np.exp(-zeta * omega * t) * np.sin(omega * np.sqrt(1 - zeta**2) * t)

# Random force
F = np.random.randn(len(t))

# Compute response
response = convolve_impulse_response(h, F, dt)

print(f"Max response: {np.max(np.abs(response)):.3f}")
print(f"Std response: {np.std(response):.3f}")

Best Practices

1. Use Vectorization

# ❌ Bad: Loop
result = np.zeros(len(x))
for i in range(len(x)):
    result[i] = x[i]**2 + y[i]**2

# ✅ Good: Vectorized
result = x**2 + y**2

2. Avoid Unnecessary Copies

# ❌ Bad: Creates copies
a = np.array([1, 2, 3])
b = a
b[0] = 10  # Modifies original

# ✅ Good: Explicit copy when needed
a = np.array([1, 2, 3])
b = a.copy()
b[0] = 10  # Original unchanged

3. Use In-Place Operations

# ❌ Bad: Creates new array
a = a + 1

# ✅ Good: In-place
a += 1

4. Choose Appropriate Data Types

# Use float32 for large arrays when precision allows
large_array = np.zeros((10000, 10000), dtype=np.float32)  # 400 MB instead of 800 MB

Resources


Use this skill for all numerical computations in DigitalModel!

平台分布

Claude Code

26.36%
按下载量换算60

OpenCode

23.15%
按下载量换算53

Cursor

17.99%
按下载量换算41

Codex

13.16%
按下载量换算30

windsurf

7.28%
按下载量换算17

trae

3.59%
按下载量换算8

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

权限未标注

当前来源未能明确判断权限范围,默认进入异常复核队列。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

继续浏览同类 Skills