.txt reader

← Instruments

Reusable Python examples for loading numeric text files and making line plots or maps. Inspect the file format first: header length, delimiter, column meanings, units, and sweep order are part of the data. The examples below replace the executable path through the older placeholder template, which is retained at the bottom for reference.

Two-column numeric data

This example expects a whitespace-separated file with one numeric x column and one numeric y column. Set skiprows to the actual number of header lines; use delimiter=”,” for comma-separated data. Lines beginning with # are treated as comments.

from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt

path = Path("data/trace.txt")
data = np.loadtxt(path, comments="#", skiprows=0, ndmin=2)
if data.shape[1] != 2:
    raise ValueError(f"Expected two columns, got {data.shape}")
if not np.all(np.isfinite(data)):
    raise ValueError("Input contains non-finite values")

x, y = data.T
fig, ax = plt.subplots(layout="constrained")
ax.plot(x, y, linewidth=1.2)
ax.set(xlabel="x (specify unit)", ylabel="y (specify unit)")
plt.show()

A rectangular map with explicit axes

Use one axis file per dimension and a matrix whose rows follow y and columns follow x. The example checks shape and monotonicity. pcolormesh with shading=”nearest” treats coordinates as cell centers; shading=”auto” chooses a shading convention based on array dimensions, and does not mean that scientific data have been interpolated.

x = np.loadtxt("data/x_axis.txt", ndmin=1)
y = np.loadtxt("data/y_axis.txt", ndmin=1)
z = np.loadtxt("data/map.txt", ndmin=2)
if x.ndim != 1 or y.ndim != 1:
    raise ValueError("Axis files must contain one column")
if x.size < 2 or y.size < 2 or z.shape != (y.size, x.size):
    raise ValueError("Expected z.shape == (len(y), len(x)), both >= 2")
if not np.all(np.diff(x) > 0) or not np.all(np.diff(y) > 0):
    raise ValueError("Axes must be increasing; reorder the data with them")

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
cmap = plt.get_cmap("RdBu_r").copy()
cmap.set_bad("lightgray")
im = ax.pcolormesh(x, y, np.ma.masked_invalid(z),
                   shading="nearest", cmap=cmap)
ax.set(xlabel="x (specify unit)", ylabel="y (specify unit)")
fig.colorbar(im, ax=ax, label="Signal (specify unit)")
plt.show()

Common checks

  • Do not silently drop malformed rows or invent missing axis values. Report rejected records and preserve missing measurements as NaN when the grid is known.
  • Keep acquisition order for hysteresis or time-series plots. Sort only when the analysis requires it, and apply the same permutation to axes and data.
  • Convert voltage to resistance using the calibrated excitation current, not a hard-coded factor copied from another run.
  • For large custom formats, separate parsing, unit conversion, background correction, and plotting into independent functions.
  • Export axis values and processing settings with each processed map.

More examples: repeated VNA traces, lock-in conversion, optical spectra, and Jupyter setup

Original 2024 template (historical; contains non-executable placeholders)

The original sketch below uses ellipses inside function signatures and assignments and is not runnable as written. It also contains a massage_date/massage_data naming mismatch. Use the complete examples above for new scripts.

This snippet provides a standard format to read .txt files, then manipulate and convert the essential data into scientific plots.

import numpy as np
import scipy.constants as C
import matplotlib.pyplot as plt
import seaborn as sns

# Constants
A = ...
B = ...
...

# Function to read and parse the data file
def read_and_parse_data(filename):
    with open(filename, 'r') as file:
        lines = file.readlines()

    # Assuming the first row after the headers contains x-data
    x1_data = [float(x) for x in lines[3].split('\t')[0:]] # '3' should be replaced by actual line number
    x2_data = ... # More x-data if data is multidimensional
    ...

    # Collect all y-data, assuming they start from the third line
    y_data = []
    for line in lines[5:]: # '5' should be replaced by actual line number
        # Splitting each line on tab and converting each piece to float
        # z_data_points = [float(y) for i, y in enumerate(line.split('\t')) if i % 2 == 0]
        y_data_points = [float(y) for y in line.split('\t')[0:]]

        y_data.append(y_data_points)
    
    return x1_data, x2_data, ..., y_data

# Function to reform the read data
def massage_data(x1, x2, ..., y):

    x1_new_data = []
    for i in range(len(x1)):
        x1_new_data.append(2*x1[i]) # replace the manipulation by actual massage way
    x2_new_data = []
    ...
    
    y_new_data = []
    for i in range(len(y)):
        ydata = []
        for yy in y[i]:
            ydata.append((yy)*1e6)  # replace the manipulation by actual massage way
        y_new_data.append(ydata)
    
    return x1_new_data, x2_new_data, ..., y_new_data
        
# Example usage
filename1 = r'D:\···\···.txt'  # Change this to the path of your file
filename2 = ...  # More files
x1_data, x2_data, ..., y_data = read_and_parse_data(filename1)
x1_new_data, x2_new_data, ..., y_new_data = massage_date(x1_data, x2_data, ..., y_data)

# Line plot function
plt.figure(figsize=(10, 8))
plt.plot(x1_new_data, y_new_data)
plt.title('phase/°')
plt.xticks([], [], size=18,weight='bold')
plt.yticks([], [], size=18,weight='bold')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()

# Map plot function

# Create a meshgrid for plotting
x, y = np.meshgrid(x1_data, x2_data)

# Shift the heatmap
# For each row in y, we shift x left by the index of the row
# for i in range(y.shape[0]):
#     x[i, :] += 1.5*i

# Plotting the heatmap
plt.figure(figsize=(10, 8))
plt.pcolormesh(x, y, y_data, cmap='jet_r', shading='auto')  # 'auto' shading interpolates the values
plt.colorbar()  # adds a color bar to indicate the scale
plt.title('phase/°')
plt.xticks([], [], size=18,weight='bold')
plt.yticks([], [], size=18,weight='bold')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

Comments

一条对“.txt reader”的回复

  1. […] .txt Reader — numeric text loading, validation, line plots, and maps. […]

    赞

发表评论