请求将IDL二进制数据读取器转换为Python代码
Python Equivalent of IDL NC_vlf Data Reader
Here's the Python implementation matching your IDL code, including proper handling of signed 24-bit data and little-endian binary format:
import numpy as np import os def NC_vlf(file, t0m, t0s, dus): fs = 78125.0 # Sampling frequency in Hz (78.125 kHz) # Get file size and calculate number of 8-byte blocks file_size = os.path.getsize(file) np_blocks = file_size // 8 # Each block contains two 32-bit integers # Read binary data as little-endian 32-bit signed integers # Data is stored as WE, NS, WE, NS... so reshape to (2, np_blocks) where: # d[0] = all WE channel samples, d[1] = all NS channel samples data = np.fromfile(file, dtype='<i4') d = data.reshape((np_blocks, 2)).T # Define channel indices (adjust to [0,1] if NS comes first in your file) nswe = [1, 0] # nswe[0] = NS channel index, nswe[1] = WE channel index # Calculate start and end indices for the selected interval start_time = t0m * 60 + t0s i0 = int(fs * start_time) i1 = i0 + int(np.ceil(fs * dus)) # Ensure indices stay within array bounds i0 = max(0, i0) i1 = min(d.shape[1] - 1, i1) # Generate time axis (seconds since start of the hour) num_samples = i1 - i0 + 1 t = np.arange(num_samples) / fs + t0s # Extract 24-bit data (discard lower 8 control bits) and convert to nanoTesla # Integer division by 256 shifts right 8 bits, preserving sign for signed 24-bit values B_NS_nT = (d[nswe[0], i0:i1+1] // 256) / 1e7 B_WE_nT = (d[nswe[1], i0:i1+1] // 256) / 1e7 return t, B_NS_nT, B_WE_nT
Key Details:
- Binary Format: Uses
<i4dtype to read little-endian 32-bit signed integers, matching IDL's/Swap_If_Big_Endianbehavior. - 24-bit Data Handling: Integer division by 256 removes the 8-bit control word. Since we use signed integers, negative 24-bit values are correctly sign-extended.
- Channel Order: Adjust the
nswelist if your file stores NS samples before WE samples. - Large File Optimization: For files over 2GB, use
np.memmapto avoid loading the entire file into memory:# Alternative for large files with np.memmap(file, dtype='<i4', mode='r') as data: d = data.reshape((np_blocks, 2)).T # Rest of the code remains identical
Usage Example:
t, B_NS, B_WE = NC_vlf('CH1_2_20170103_060000', 42.0, 3.547, 0.008)
内容的提问来源于stack exchange,提问作者Richard Ferranti
相关产品推荐
相关产品推荐

