NEC-81 in Python: Numerical Electromagnetics Code (NEC-2)

Mike Markowski, mike.ab3ap@gmail.com

This page is hosted at both University of Delaware and GitHub

NEC-81 PySide6 GUI and 3D radiation pattern
NEC-81 wire/patch geometry alongside 3D far-field pattern.

This is a complete Python and NumPy conversion of the classic NEC-81 (v2.2) implementation of the Numerical Electromagnetics Code (NEC-2). It preserves the full Method of Moments (MoM) solver for thin wires, surface patches, wire-to-patch junctions, reflection and rotational symmetry, transmission lines, two-port networks, lumped and distributed impedance loading, Sommerfeld/Norton ground, near-field grids, and Numerical Green's Functions (N.G.F.), while adding modern configuration files, 2D/3D Matplotlib plots, and an optional PySide6 GUI.

Background

Developed at Lawrence Livermore National Laboratory by Gerald Burke and Andrew Poggio in the late 1970s and early 1980s, NEC-2 became the standard antenna modeling engine for amateur radio operators, engineers, and researchers alike. The codebase converted here traces back to David J. Pinion's 1989 NEC-81 v2.2 distribution and OH3MCK's 1991 Sun-4 Unix port.

Original Fortran NEC decks are unforgiving with strict 80-column field alignments and terse two-letter cards. This Python port accepts both classic fixed-column decks and modern comma- or space-delimited decks, while also supporting self-documented configuration files and an interactive GUI.

Installation

Download the release archive, extract it, and install the wheel with pip. Only numpy is required for the core solver; optional extras enable 2D/3D plotting and the PySide6 GUI interface. (This will be updated with GitHub info.)

Download:
nec81-2.2.0-release.tar.gz (latest 15 Nov 2026).
examples.tar.bz2 (latest 15 Nov 2026).

$ tar jxf examples.tar.bz2   # Sample input files for NEC-81.
$ tar zxf nec81-2.2.0-release.tar.gz
$ cd nec81

# Core solver only (headless)
$ pip install nec81-2.2.0-py3-none-any.whl

# Core solver + 2D/3D Matplotlib plots
$ pip install "nec81-2.2.0-py3-none-any.whl[plots]"

# Everything: solver, plots, and PySide6 GUI
$ pip install "nec81-2.2.0-py3-none-any.whl[full]"

Note: Do not rename the .whl file before installing, as pip reads the filename to verify package version and Python compatibility. Once installed, you can launch the GUI or CLI directly from any directory using nec81 (or mainsa for batch runs).

1. Running NEC-81 (GUI by Default & Command-Line Options)

Running nec81 with no arguments or with a single .nec or .cfg file opens the PySide6 GUI interface directly. Passing an output report file, configuration flag, plotting flag, or --cli runs headlessly in command-line mode:

$ nec81                                   # Open GUI with a new deck
$ nec81 06_6m_5el_yagi.nec                     # Open deck in GUI
$ nec81 06_6m_5el_yagi.cfg                     # Open config in GUI
$ nec81 06_6m_5el_yagi.nec 06_6m_5el_yagi.out  # Run batch CLI mode
$ nec81 --config 06_6m_5el_yagi.cfg            # Run from config file
$ nec81 --write-config-template my_antenna.cfg # Generate starter .cfg
$ nec81 --cli                                  # Original Unit 23/24 prompt
Option Description
[inputFile] Open a .nec deck or .cfg file in the GUI (when given alone), or specify the input deck for batch CLI mode.
[outputFile] Destination path for the printed NEC report (implies headless CLI mode).
-o / --cli / --no-gui Run in command-line mode without opening the GUI (prompts interactively for Unit 23 and Unit 24 if no files are given).
-g / --gui [DECK_OR_CFG] Explicitly launch the PySide6 GUI interface, optionally preloading a .nec or .cfg file.
-c / --config FILE Load settings (and optional embedded model cards) from a .cfg file and run in CLI mode.
-t / --write-config-template [PATH] Generate a commented starter configuration file (default: nec81.cfg) and exit.
--plots3d / --no-plots3d Enable or disable Matplotlib plot generation in CLI mode.
-d / --plot-directory DIR Output directory for saved plot images (default: plots).
--show-sources / --no-show-sources Show or hide excitation source markers (magenta diamonds) on 3D geometry plots.
--show-loads / --no-show-loads Show or hide impedance load markers (green squares) on 3D geometry plots.
--show-plots / --no-show-plots Keep interactive Matplotlib windows open for rotation and zooming after completion.

2. Desktop GUI & Visualization Suite

Launching nec81 opens a six-tab PySide6 GUI:

Generated Plot Suite

Here are examples of plots from NEC-81. In this case, a 5-element Yagi for 6m is shown. You can open each image in another tab to see it in more detail.

6m 5-element Yagi 3D geometry and RF currents
3D geometry with RF current magnitude coloring and feedpoint marker.
6m 5-element Yagi 3D radiation pattern
3D gain-colored far-field wireframe pattern (35 dB dynamic range).
6m 5-element Yagi 2D polar azimuth and elevation cuts
2D polar Azimuth and Elevation cuts with F/B ratio and −3 dB beamwidth.

3. Modern Configuration Files

Configuration files use plain-text var val lines. Comments begin with #, and relative file paths are resolved from the directory containing the configuration file. Sample .nec card decks and .cfg configs are available in examples.tar.bz2. Many times examples are better than descriptions.

Setting Type Default Description
inputFile path "" Path to an external .nec deck (omit when using embedded card.* groups).
outputFile path "" Destination path for the standard NEC text report.
plots3d bool false Master switch (true/false) enabling plot generation.
plotGeometry bool true Generate 3D wire & patch geometry with RF current magnitude coloring.
plotPatterns bool true Generate 3D far-field pattern wireframes and 2D polar Azimuth/Elevation cuts.
plotFields bool true Generate 3D scalar scatter plots for NE / NH near-field grids.
showSources bool true Overlay excitation source locations (EX) on the 3D geometry plot.
showLoads bool false Overlay impedance-loaded segments (LD) on the 3D geometry plot.
plotDirectory path plots Directory where rendered plot images are saved.
plotFormat string png Image format passed to Matplotlib (png, svg, or pdf).
showPlots bool true Keep interactive Matplotlib windows open after saving images.

Self-Contained Models via Card Groups

Instead of referencing an external .nec file, an entire antenna model can be written inside a configuration file using card.<group>.<field> value lines. Groups are emitted in the order they first appear and accept either two-letter NEC card codes or descriptive names:

card.title.kind comment
card.title.text "Center-fed half-wave dipole at 299.79 MHz"
card.commentEnd.kind commentEnd

card.driven.kind wire
card.driven.tag 1
card.driven.segments 21
card.driven.x1_m -0.25
card.driven.y1_m 0
card.driven.z1_m 0
card.driven.x2_m 0.25
card.driven.y2_m 0
card.driven.z2_m 0
card.driven.radius_m 0.001

card.geometryEnd.kind geometryEnd
card.geometryEnd.groundFlag 0

card.frequency.kind frequency
card.frequency.stepType 0
card.frequency.count 1
card.frequency.start_MHz 299.792458

card.source.kind excitation
card.source.type 0
card.source.tag 1
card.source.segment 11
card.source.real_V 1
card.source.imag_V 0

card.pattern.kind radiationPattern
card.pattern.mode 0
card.pattern.thetaCount 19
card.pattern.phiCount 37
card.pattern.flags 1000
card.pattern.startTheta_deg 0
card.pattern.startPhi_deg 0
card.pattern.thetaStep_deg 10
card.pattern.phiStep_deg 10

card.execute.kind execute
card.end.kind end

outputFile dipole.out
plots3d true
showSources true
showLoads false
plotDirectory plots
plotFormat png
showPlots true

4. Supported NEC-2 Card Reference

The original NEC-81 documentation is recommended to fully understand options available. For those already familiar, here is a summary of supported cards in this python version of NEC-81.

Code Descriptive Name Parameters Purpose
CMcommentTextComment line in header section.
CEcommentEndTextEnds the initial comment header.
GWwireTag, Segments, X1_m, Y1_m, Z1_m, X2_m, Y2_m, Z2_m, Radius_mStraight wire divided into equal segments.
GCwireTaperUnused1, Unused2, SegmentLengthRatio, StartRadius_m, EndRadius_mTapers segment length and radius on preceding GW (when Radius=0).
GAarcTag, Segments, Radius_m, Start_deg, End_deg, WireRadius_mCircular wire arc in the X-Z plane.
GHhelixTag, Segments, TurnSpacing_m, Length_m, StartRadiusX_m, StartRadiusY_m, EndRadiusX_m, EndRadiusY_m, WireRadius_mUniform or tapered helix / spiral.
SPsurfacePatchTag, Shape, X1_m, Y1_m, Z1_m, X2_orTheta, Y2_orPhi, Z2_mDefines an arbitrary (0), rectangular (1), triangular (2), or quadrilateral (3) patch.
SCpatchContinuationUnused, Shape, X3_m, Y3_m, Z3_m, X4_m, Y4_m, Z4_mSupplies remaining corners for SP or SM patches.
SMmultiplePatchesCountX, CountY, X1_m, Y1_m, Z1_m, X2_m, Y2_m, Z2_mGenerates a rectangular CountX × CountY grid of surface patches.
GMmoveTagIncrement, Copies, RotateX_deg, RotateY_deg, RotateZ_deg, TranslateX_m, TranslateY_m, TranslateZ_m, StartTagRotates, translates, or duplicates structure elements.
GRrotateTagIncrement, CopiesGenerates cylindrical rotational copies about the Z axis.
GSscaleConversion, Unused, ScaleScales all structure coordinates and radii (1 = ft→m, 2 = in→m, 0 = factor).
GXreflectTagIncrement, AxesReflects structure across coordinate planes (100=X, 010=Y, 001=Z) and enables symmetry.
GFgreenFunctionReadPrintFlagReads a precomputed Numerical Green's Function file (must precede geometry).
GPsuppressGeometryPrint—NEC-81 extension: suppresses the printed segmentation table.
GEgeometryEndGroundFlag, PlotFlagEnds geometry input, builds connectivity, and checks junctions.
FRfrequencyStepType, Count, Unused1, Unused2, Start_MHz, Step_MHz_orRatioSets single frequency or linear (0) / multiplicative (1) frequency sweep.
EXexcitationType, Tag, Segment, Flags, Real_V, Imag_V, Param3..6Voltage source (0), incident plane wave (1–3), elementary current source (4), or voltage discontinuity (5).
GNgroundType, Radials, Unused1, Unused2, RelativePermittivity, Conductivity_Spm, RadialLength_m, RadialRadius_mFree space (-1), reflection-coefficient ground (0), perfect ground (1), or Sommerfeld/Norton ground (2).
GDsecondMediumUnused1..4, RelativePermittivity, Conductivity_Spm, BoundaryDistance_m, Depth_mCliff or radial ground screen second medium parameters for far fields.
LDloadType, Tag, FromSegment, ThroughSegment, Resistance_Ohm, Inductance_H, Capacitance_FSeries/parallel RLC (0–3), fixed Z (4), or finite wire conductivity/permeability (5).
NTnetworkTag1, Segment1, Tag2, Segment2, Y11Real_S, Y11Imag_S, Y12Real_S, Y12Imag_S, Y22Real_S, Y22Imag_SConnects a two-port short-circuit admittance network between two segments.
TLtransmissionLineTag1, Segment1, Tag2, Segment2, Z0_Ohm, Length_m, Y1Real_S, Y1Imag_S, Y2Real_S, Y2Imag_SConnects a transmission line (negative Z0 crosses line; Length=0 uses straight-line distance).
CPcouplingTag1, Segment1, Tag2, Segment2Computes maximum coupling between up to 5 specified segments.
EKextendedKernelOptionEnables (0) or disables (-1) the extended thin-wire kernel.
KHinteractionRangeUnused1..4, RangeSets the distance threshold (in wavelengths) for approximate matrix integration.
PTcurrentPrintControl, Tag, FromSegment, ThroughSegmentControls printed wire current tables or receiving pattern normalization.
PQchargePrintControl, Tag, FromSegment, ThroughSegmentControls printed segment charge density tables.
PLplotFlagsFlag1, Flag2, Flag3, Flag4Writes auxiliary plot data to fort.8.
NEnearElectricFieldCoordinates, CountX, CountY, CountZ, StartX_m, StartY_m, StartZ_m, StepX_m, StepY_m, StepZ_mEvaluates near electric field (Ex, Ey, Ez) on a rectangular (0) or spherical (1) grid.
NHnearMagneticFieldCoordinates, CountX, CountY, CountZ, StartX_m, StartY_m, StartZ_m, StepX_m, StepY_m, StepZ_mEvaluates near magnetic field (Hx, Hy, Hz) on a rectangular (0) or spherical (1) grid.
RPradiationPatternMode, ThetaCount, PhiCount, Flags, StartTheta_deg, StartPhi_deg, ThetaStep_deg, PhiStep_deg, Range_m, Normalization_dBEvaluates far-zone radiation pattern, power/directive gain, polarization, and axial ratio.
WGgreenFunctionWrite—Writes factored N.G.F. matrices to disk for reuse in subsequent runs.
XQexecuteOptionExecutes matrix fill, solve, and requested field calculations.
NXnextStructure—Resets structure state to process another deck in the same input stream.
ENend—Terminates execution and prints total run time.

NSMA WG16.99.050 Format

Many manufacturers provide antenna patterns in Antenna Systems – Standard Format for Digitized Antenna Patterns WG16.99.050 format. Link budget simulators designed for NSMA format files often cannot use NEC output. This version of NEC-81 provides the -a or GUI option to write output in an NSMA format .adf file. An example of a NEC-81 generated adf can be seen at NSMA viewer.

Software Architecture

The solver core was translated from the 15 Fortran source files of NEC-81 v2.2 into modular Python files sharing a unified NECState dataclass in place of Fortran COMMON blocks:

Dependencies: Only numpy is required to run the NEC-81 solver engine. matplotlib is required for 2D/3D plots, and PySide6 is required only when launching the GUI.