Using PyMCNP with AI Agents¶
PyMCNP ships a skill file, SKILL.md, for AI coding agents such as
Claude Code. It is a short Markdown file that tells an agent how to use PyMCNP well:
the parsing contract: every parser returns
(object, remainder), and a non-empty remainder means part of the file was not read;the API for building, scanning, checking and running inputs, and for reading OUTP, MESHTAL and PTRAC files;
the common pitfalls, e.g., PTRAC files that do not fit in memory, PTRAC options that leave out the values you need, and OUTP tallies PyMCNP cannot parse yet;
what to do when PyMCNP fails on a valid MCNP file: draft a GitHub issue with a minimal input instead of working around it.
With the skill installed, an agent can write, scan, run and plot MCNP models from a short description. The automation example, 441 iron discs over a rough concrete floor with a flux plot, was created this way from a short prompt.
Installing the Skill for Claude Code¶
Claude Code looks for skills in a folder named after the skill that holds a SKILL.md file:
Scope |
Location |
Used in |
|---|---|---|
Personal |
|
all your projects on this machine |
Project |
|
sessions in that project; commit it to share it with your team |
SKILL.md is not part of the installed Python package, so download it from GitHub. It exists from PyMCNP 1.0.0 on: for an older version the download fails with a 404, so upgrade first. Take the version that matches your
installed PyMCNP, since the skill describes that version’s API; pymcnp --version prints it, also for uv tool and
pipx installs. For a personal install:
v=$(pymcnp --version | cut -d' ' -f2)
mkdir -p ~/.claude/skills/pymcnp
curl -fsSL "https://raw.githubusercontent.com/FSIBT/PyMCNP/v$v/SKILL.md" -o ~/.claude/skills/pymcnp/SKILL.md
For a project install, run the same commands from the project’s root directory with .claude/skills/pymcnp in place of
~/.claude/skills/pymcnp. If you installed PyMCNP from GitHub rather than from a release, the version has no tag: use
main in place of v$v, or copy SKILL.md from your clone of the repository.
To check that Claude Code found the skill, run /skills in a session, or ask “What does the pymcnp skill say about
PTRAC files?”. Claude Code picks up a new skill in a running session; if it does not show up, run /reload-skills or
start a new session. The skill loads by itself when a task involves MCNP files, and /pymcnp loads it explicitly.
When you upgrade PyMCNP, download the skill again with the same commands, so that the agent does not use a stale API.
Other Agents¶
SKILL.md is plain Markdown with a short YAML header (name and description), so any agent can use it:
Agents that support the Agent Skills format read the same
pymcnp/SKILL.mdfolder; see your agent’s documentation for where it looks for skills.Agents that read an
AGENTS.mdfile (or a similar rules file) in the project: saveSKILL.mdin the project, e.g., asdocs/pymcnp-skill.md, and add a line such as “Before writing code that uses PyMCNP or MCNP files, readdocs/pymcnp-skill.mdand follow it.”Otherwise, attach the file or paste its text into the conversation before you ask for MCNP work.
What to Ask¶
Describe the goal, the files, and what you want back. For example:
“Read
model.inp, scan the radius of surface 99 from 500 to 700 cm in steps of 50, and write one input per radius. Run them withmcnp6four at a time and plot tally 1 of every run in one figure.”“
ptracis a 20 GB PTRAC file from a run withEVENT=SRC,BNK,SUR,COL,TER. Write the photons entering cell 3 through surface 3 to a parquet file, with the nuclide each photon came from.”“Check
deck.inpwithpymcnp check, fix the lines that are too long, and tell me about any card PyMCNP cannot parse.”
Reviewing the Results¶
An agent can make mistakes that still give a valid MCNP input, so check its work:
Look at the geometry (
pymcnp visualize, orVisualize().to_show_cells(inp)) before running a model.Check
outp.summary.okandoutp.summary.checks_passedbefore trusting a tally, and read the warnings PyMCNP issues.Do not send export-controlled or otherwise sensitive inputs to a hosted model, and follow your MCNP licence.
The Skill File¶
Python API and CLI for MCNP inputs and outputs (pip install pymcnp, Python 3.11-3.15). Working scripts live in examples/ of the repository (create_*.py, read_*.py, do_*.py; https://github.com/FSIBT/PyMCNP/tree/main/examples, not installed by pip); copy from them.
Parsing contract¶
X.from_mcnp(text) and X.from_file(path) return (obj, remainder). Parsing stops silently at the first card it cannot parse; that card and everything after it is the remainder. Always check remainder == '', otherwise part of the file was dropped. The same holds for a single card, e.g., card.Data.from_mcnp('E14 0.1 3i 10'), which expands the shorthands as Inp does; a card that parses only in part leaves the rest of its expanded text as the remainder (e.g., 2r there comes back written out). For Inp this holds for the data block, including a data card that parses only in part (e.g., f4:n 1 [1]): that card and every card after it are the remainder, as Inp writes them, with shorthands expanded. A cell or surface card PyMCNP cannot parse raises pymcnp.abc.Error instead, since the blocks after it would be missing; pymcnp check names its line. Unparseable input with nothing parseable raises pymcnp.abc.Error. For OUTP files an empty remainder is not enough: tally blocks in a layout PyMCNP cannot parse yet (e.g., F8, and some F1/F2/F4/F5 layouts) are kept as unparsed text, so they leave no remainder; each one issues a pymcnp.abc.Warning (“Tally not parsed.”, with the tally number and type), is missing from outp.tallies() and outp.to_dataframe(), and outp.tally(n) raises abc.Error “Tally not parsed.”. Do not silence these warnings; report the missing tally type (see “d) Missing feature or parse failure”).
obj.to_mcnp() writes MCNP text. For OUTP, PTRAC and MESHTAL, obj.to_mcnp() + remainder is the original text. Inp.to_mcnp() writes equivalent input, not the same text: it expands the shorthands nR, nI, nILOG/nLOG, nJ and xM of cards (not comments) into explicit entries (e1 0.1 511i 10 becomes 512 numbers, with float noise such as 0.17734375000000002), may pad a card with trailing Js, and wraps card lines longer than 80 columns with & (MCNP rejects data past column 80). So compare inputs by parsing both, not by diffing text. obj.to_file(path) writes.
a) Create inputs, scan, run¶
import pymcnp
from pymcnp.inp import card
from pymcnp.inp.card import surface, data
s = surface.So(j=1, r=10)
mat = data.M.from_formula(suffix=1, formulas={'H2O': 1}, is_weight=False) # default is weight fractions
cell = card.Cell_0(j=1, m=1, d=1.0, geom=-s, options=['imp:n=1']) # -s, +s build senses; & is intersection ('1 2'), | is union ('(1:2)')
outside = card.Cell_1(j=2, m=0, geom=+s, options=['imp:n=0']) # Cell_1 = void (no density)
inp = pymcnp.Inp(title='Sphere\n', cells=[cell, outside], surfaces=[s], data=[mat, data.Sdef(options=['ERG=14'])])
inp.nps = 1000 # setters add the card if missing
inp.seed = 42
Import the subpackages (from pymcnp.inp import card, from pymcnp.inp.card import surface, data) instead of spelling out pymcnp.inp.card.surface. each time; scripts read much better. Cards also accept strings (geom='#(99:3)', options=['imp:n=1.0']). Field names follow the class, not the manual: Nps(npp=...), Rcc has h1 h2 h3 for the height vector. M.from_formula(..., library='80c') appends a library suffix to every ZAID (without it MCNP needs a default library); fractions are weight (negative) or atom (positive) fractions per element and isotope. from_formula drops the isotopes of an element whose fraction is below cutoff (default 0.01), e.g., H-2 and O-17/O-18 of water or Ca-42/43/46/48 of calcium, and does not renormalise the rest, so pass cutoff=0 to keep every isotope. See examples/create_inp.py for tallies and multi-surface geometry.
Scan: read a file, then inp.scan(nps=[...], seed=[...]) yields independent deep copies for every combination of the values of fields or settable properties such as nps, seed or title (the last one varies fastest; a title value gets the trailing newline of the title card if it has none, e.g., title=['Case A', 'Case B'], as in Inp(title='Sphere', ...) and inp.title = 'Sphere'). A key may also be a path to a nested field, inp.scan(**{'surfaces[99].r': [9, 10, 11]}) (attributes with .name, list items with [i]; the index into cells or surfaces is the card number, so surfaces[99] is surface 99 and cells[3] is cell 3, not a list position, and a number no card has raises abc.Error; the index into data is the list position, as in inp.data[i], comment cards included; values become the field’s literal type, e.g., inp.literal.Real, which compares and computes as a number, and a value that does not parse whole, e.g., '7 8' for a radius, raises abc.Error (whitespace around it is dropped; a float such as 10.0 for an integer field raises, use int); inp.message = 'outp=run.o' gets the message: keyword if it has none; abc.Error if the path does not exist). For changes that need code (several fields, computed values) use inp.scan_with(values, apply), which deep-copies per value and calls apply(copy, value) (examples/do_parameter_scan.py). Use list(...) to pass the copies to Run:
base, rest = pymcnp.Inp.from_file('model.inp')
assert rest == ''
# surface_cards(n) finds cards by number; inp.surfaces[i] also counts comment cards; fields are named by the class (`So.r`), see its docstring
inps = list(base.scan_with((9, 10, 11), lambda inp, r: setattr(inp.surface_cards(1)[0], 'r', r)))
inps += list(base.scan(nps=[10**4, 10**5]))
(copy.deepcopy(inp) also works; never reuse one mutated Inp for several runs.)
Lookups: inp.cell_cards(number=None, material=None, density=None, kind=Cell), inp.surface_cards(number=None, kind=Surface) and inp.data_cards(kind=Data) return a tuple of the cards themselves, so edits change the input (inp.surface_cards(1)[0].r = 5); assigning a name that is not a field of the card, e.g., r on an RPP box or a misspelt field, raises AttributeError listing the card’s fields, so check type(card) first; the tuple is empty if nothing matches, and the filters combine (inp.cell_cards(material=2) lists the cells with material 2, following LIKE n BUT; material=0 lists void cells). kind restricts the card class: inp.data_cards(data.M) returns the material cards, inp.data_cards(data.Fmesh) the mesh tallies. inp.cells, inp.surfaces and inp.data are the indexable card lists, whose filter(kind, field=value) skips items without that field. Warnings use Python’s standard warnings module (PyMCNP installs no hook).
Run: results = pymcnp.Run(inps, command='mcnp6', max_workers=4, names='case-{index}').run(directory) runs each input in its own directory directory/pymcnp-<timestamp>/<name>/ (default names run-00000, …; a name may not hold & | < > ^ % ! "; run.directory holds the batch path after run; batch=False skips the timestamp directory and uses directory/<name>/, which must not exist yet; MCNP refuses to reuse output files, so never share one directory), at most max_workers at a time (default: CPU count). It returns one Result per input, in order, with .inp, .outp, .ptrac, .runtpe (paths, None if not written), .log, .returncode, .fatal_errors and .ok. It waits for all runs, then raises abc.Error listing the failed ones (non-zero exit code or fatal error in the output), unless check=False; then test result.ok. Run(...) raises abc.Error if command is not on PATH. To dry-run, use command='echo', check=False (on Windows, which has no echo program, command='where') (echo writes no output file, so with the default check=True the run fails with exit code 0, no output file). Subclass Run and override prehook_file(path, index), posthook_file(result) (runs in the worker thread, so heavy post-processing such as PTRAC to parquet runs in parallel without your own pool; skipped for failed runs unless check=False), prehook_batch(path), posthook_batch(path) (examples/do_run.py). Outp.fatal_errors lists the fatal errors of any parsed output. CLI: pymcnp run [-c CMD] [-p DIR] a.inp b.inp (runs nothing and exits 3 if PyMCNP cannot parse an input; exits 1 if a run failed).
b) Read outputs¶
outp, rest = pymcnp.Outp.from_file(p);outp.to_dataframe()returns all tallies in onepandas.DataFramewith anumbercolumn (numberandnpsareint,bins,countsanderrorsfloats, the other columns strings); preferoutp.tally(n)below.outp.activity('photon')/outp.activity('neutron')returns the activity table (print table 126) as a dataframe, one row per cell (cell,tracksentering,population,collisions, …) plus a final totals row withcellmissing; use it to cross-check counts from a PTRAC file, e.g., photon tracks entering a cell.outp.fatal_errorslists MCNP’s fatal errors.outp.summarygives the headline results without regexes:.version,.nps(histories run),.run_time(minutes),.terminated('histories','cycles'or'fatal errors'),.ok,.keff/.keff_sd(final combined,KCODEproblems only, elseNone),.warnings(unique),.fatal_errors, and.checks(tally number toTallyCheck(number, passed, failed, message), e.g.,TallyCheck(number=1, passed=False, failed=1, message='...'):passedis whether all of MCNP’s 10 statistical checks of the tally fluctuation bin passed,failedhow many did not, andmessagethe first failed one) with.checks_passed(Noneif no checks are printed). Always checksummary.okandsummary.checks_passedbefore trusting results.outp.tallies()returns the parsed tally blocks (outp.block.Tally, not a dataframe;outp.tallies(n)picks one number;tally.tally_numberis anint, while the raw fields of the blocks, e.g.,tally.number, are the padded text of the file) andoutp.activities()the activity blocks;outp.tally(n)returns one tally as a dataframe with typed columns:bins, counts, errors, then where presentangle_from/angle_to(float) andcellorsurface/facet(Int64), thennumber(int),quantity,particles,nps(int).outp.to_file_csv(path)/outp.to_file_parquet(path)write all tallies (MeshtalandPtrachave the same methods; for one tally useoutp.tally(n).to_csv(path));pymcnp.Plot().to_pdf(outp, '1', path)/pymcnp.Plot().to_show(outp, '1')(the tally number may be anintor astr). CLI:pymcnp convert outp --csv f.outp(alsoptrac,meshtal; writesf.outp.csv, the whole file name plus.csv; nothing and exit 1 if there is nothing to convert, 3 if that is because the tallies did not parse; formeshtalevery mesh tally, with anumbercolumn),pymcnp plot --pdf f.outp 1; both write or plot the parsed part and exit 3 if PyMCNP cannot parse all of the file.PTRAC files can be huge: stream them, parse once.
pymcnp.Ptrac.stream(path)reads the file history by history and yields oneptrac.Eventat a time with flat memory (about 300 MB for a 345 MB file);Ptrac.tracks(path)yields oneptrac.Trackper particle;Ptrac.iter_histories(path)yieldsHistoryobjects (orptrac.block.HistoryTruncated, see below).pymcnp.PtracProcessor(overrideprocess_source/bank/surface/collision/terminal;.runreturns the non-Noneresults) andpymcnp.PtracFilter(overridecheck_*;.runyields accepted events; everycheck_*returnsTrueby default, so overriding onlycheck_collisionstill keeps all source, bank, surface and terminal events: override the others withreturn Falseto drop them) accept the path directly:.run(path). Do not callPtrac.from_fileon anything large: it builds the whole object tree, about 35x the file size in RAM (10 GB for 345 MB), and the file is parsed again for every extra pass. Do all the work in one pass over the generator. A PTRAC file cut short, e.g., by a killed MCNP run, keeps its truncated last history:stream,tracks,to_parquetanditer_histories(which yields it asHistoryTruncated) read it and issue anabc.Warning, while damage anywhere before the final event still raisesabc.Error.Ptrac.from_fileon such a file leaves the partial last history inrest, so use the streaming functions for files that may be truncated.Ptrac.from_file(p)(returns(ptrac, rest),ptrac.historiesis a list) is fine for small files and for inspecting the structure.ptrac.Event(fromstream) has the type and meaning already worked out, so do not read rawJ-line slots:event.nps,event.type(pymcnp.ptrac.EventType, anIntEnum:SOURCE,BANK,SURFACE,COLLISION,TERMINAL,END; compare with the enum,event.type == pymcnp.ptrac.EventType.BANK, orevent.type.name == 'BANK':event.type == 'BANK'is alwaysFalse, whileevent.to_dict()['type']is the name'BANK'; for banked particlesevent.creation_codekeeps the2xxxcode),event.particle(pymcnp.ptrac.Particle, likewise anIntEnum, e.g.,Particle.PHOTON,to_dict()['particle']is'PHOTON'; a plainintfor rare ones),event.cell,event.material.event.surface(ptrac.Surfacewith.numberand.facet, e.g.,3.1is surface 3 facet 1; surface crossings only),event.cell_entered(surface crossings only),event.zaid(collisions: the nuclide hit; bank events: the nuclide of the collision that made the particle,Noneif it is 0, e.g., photons made by photon interactions).event.position, and withPTRAC ... WRITE=ALLalsoevent.direction,event.energy,event.weight,event.time. WithoutWRITE=ALLthese areNone: they are not in the file, so rerun MCNP rather than guess.event.rawis the text as written,event.blockis the parsed event block,event.to_dict()is a flat row of plain values,pymcnp.ptrac.to_dataframe(rows)gives proper dtypes (nullableInt64,string).TYPE=Prestricts what MCNP writes to photons,CELL=/SURFACE=(macrobody facets like3.1work) restrict events inside MCNP,EVENT=chooses event types: addCOLfor collisions andBNKfor bank events, otherwise the originating nuclide is unknowable (say so and ask for a rerun). Separate several values with commas, e.g.,PTRAC FILE=ASC WRITE=ALL TYPE=P EVENT=SRC,BNK,SUR,COL,TER CELL=3,4 SURFACE=3.1,4; PyMCNP reads only ASCII PTRAC files, so always writeFILE=ASC.
Originating isotope of a photon: use
Ptrac.tracks(path, particle=None, entered=None). ATrackis one particle (itseventsstart with the source or bank event);track.parentis the track it was banked from (Nonefor source particles or if not found) andtrack.parent_zaidis the nuclide of the collision that started its chain (inherited from the parent when the bank event has ZAID 0;Noneif unknown, never 0).particle=pymcnp.ptrac.Particle.PHOTONandentered=<cell>drop other tracks early (parents are still resolved);track.entries(cell=99, surface=999)yields a track’s matching surface crossings (any facet). NeedsEVENT=withBNK(andCOL). Gammas entering a detector cell, one pass (cell 99 through surface 999 gives rows forexamples/example_02.ptrac; use your own cell and surface numbers):import pandas, pymcnp rows = [] for track in pymcnp.Ptrac.tracks('ptrac', particle=pymcnp.ptrac.Particle.PHOTON, entered=99): for e in track.entries(cell=99, surface=999): rows.append({**e.to_dict(), 'parent_zaid': track.parent_zaid}) assert rows, 'no photons entered the detector (or EVENT= lacks SUR)' pandas.DataFrame(rows).to_parquet('out.parquet')
For big files or many rows write straight to parquet in chunks instead (flat memory; columns of
Event.to_dictplustrackandparent_zaid, typedInt64/string/float64; returns the row count):pymcnp.Ptrac.to_parquet('ptrac', 'out.parquet', particle=pymcnp.ptrac.Particle.PHOTON, cell_entered=99, surface=999). Withcell_entered/surfaceonly matching surface crossings are written;types={pymcnp.ptrac.EventType.SURFACE}restricts event types.Object model behind it (
from_file,iter_histories; checkrest == ''andlen(ptrac.histories) > 0, a header-only file gives zero histories):history.nps,history.event_type;history.eventsis a list of event blocks (pymcnp.ptrac.block.EventSource_1, …,EventTermination_4, named after the variables of the MCNP manual, e.g.,pbl_r_x,ncl_pbl_i_icl), all fixed-width strings. Thetypeon an event’sJline is the type of the NEXT event; an event’s own type is the previous event’stype(for the first eventhistory.event_type), which PyMCNP uses to pick the event block class.Ptrac.streamgives the values by meaning, whatever the PTRAC options.pymcnp.Meshtal.from_file(p)parses only the FIRST mesh tally of a file (the others come back as the non-emptyrest, check it): for files with severalFMESHtallies usefor tally in pymcnp.Meshtal.iter_tallies(p), which yields oneMeshtalper tally withtally.tally_number(int),tally.nps(histories,int) andtally.particle_name(plainstr); raw fields such astally.historiesare the padded text of the file. AMeshtalparses header, title, histories, tally number, particle, bin boundaries and every data row (.rows).meshtal.names(list ofstr) lists the columns (Energy/Timeonly if present, thenX Y Z Result Rel Error);meshtal.to_dataframe()returns apandas.DataFramewith float columns (one frame per tally;Energy/Timestay strings if a bin isTotal).Parsing time is linear in file size: about 0.01 ms per PTRAC event with
Ptrac.from_file(a 1.1 MB file with 10,000 events takes about a tenth of a second; at that rate a file with 1.7 million events, e.g., 345 MB, takes roughly 20 seconds). Older versions (before the offset-based parser) were quadratic, so upgrade before parsing large PTRAC or OUTP files. To save time, restrict what MCNP writes (PTRAC ... EVENT=,CELL=,SURFACE=,TYPE=,MAX=) rather than filtering afterwards. PyMCNP cannot parse theFILTER=keyword yet, so an input using it leaves a remainder; avoid it, or tell the user. An F5 point detector withoutND, e.g.,F5:p 0 0 0 1, parses asF_0with its coordinates read as cells (writeF5:p 0 0 0 1 ND, or checktype(card)isF_1), and+F6 1does not parse.
c) Check and modify existing files¶
CLI pymcnp check [--diff] [--fix] f.inp:
Exit |
Meaning |
|---|---|
0 |
clean (or |
1 |
lines over 80 columns (error); with |
2 |
usage error, or the file does not exist or cannot be read as text |
3 |
PyMCNP cannot parse a card, or the file, e.g., two cells with one number (warning; MCNP may still accept a card PyMCNP cannot parse). Checking stops at the first such card, so recheck after fixing |
Every pymcnp command uses the same exit codes, and a file gets the same code from every command that reads it (but an OUTP tally PyMCNP cannot parse yet is only a warning: convert, and plot of a parsed tally, exit 0; plot of that tally exits 3): 0 success; 1 the input or output has problems or the command failed (a line over 80 columns, a run failed, the MCNP command is not found, a PTRAC file without events to convert); 2 usage error (unknown option or command, a cell, surface or tally not in the file) or a file that does not exist, is a directory, or is not a text file (e.g., binary PTRAC, or UTF-16 text, which must be saved as UTF-8; text that is not UTF-8 is read as Latin-1 with a warning); 3 PyMCNP cannot parse all of a file (the warning names the line; a cell or surface card PyMCNP cannot parse, or an input that is not valid, e.g., two cells with one number, leaves nothing to work with; also a file of another kind, an OUTP tally in a layout PyMCNP cannot parse yet given to plot (“Tally not parsed.”), or nothing to convert because the tallies did not parse).
--diff shows what --fix would change; --fix rewrites the file in place (re-wrapping to 80 columns) and refuses on exit-3 files. Work on a copy if the original matters.
Python: c = pymcnp.Check(path); c.problems() returns Problem(line, kind, message) (kind is 'error' or 'warning'); c.check() yields a unified diff; c.fix() rewrites in place and returns the problems left (e.g., comments still over 80 columns); on a file PyMCNP cannot parse completely it raises abc.Error, naming the line, and leaves the file as it is.
Edit loop: inp, rest = Inp.from_file(p); assert rest == ''; change fields or use inp.nps / inp.seed; inp.to_file(p2). Visualize geometry: pymcnp.Visualize().to_show_surfaces(inp) (pyvista; also to_show_cells, to_show_cell(inp, n), and to_pdf_surfaces(inp, path) / to_pdf_cells).
d) Missing feature or parse failure¶
PyMCNP does not cover all MCNP options. If a valid MCNP file fails (abc.Error, non-empty remainder, check exit 3) or a card/feature is missing, or MCNP rejects a PyMCNP round trip, do not work around it silently. Draft a GitHub issue for https://github.com/FSIBT/PyMCNP/issues (CONTRIBUTING.md asks for exactly this) and show it to the user before posting:
a minimal input: trim to the few cards that trigger it,
the full traceback or
remainder/ unexpected output,PyMCNP version (
pip show pymcnp), Python version, MCNP version (PyMCNP supports 6.1 to 6.3),nothing export-controlled or sensitive.
Failing inputs are explicitly welcome, so say what you were trying to do.