Skip to content

[Code scan] RDF helpers mutate sel_type and poison later default calls #987

Description

@njzjz

This issue is part of a Codex global repository code scan.

The RDF functions use mutable sel_type=[None, None] defaults and _compute_rdf_1frame() rewrites the list in place. A default call can therefore change compute_rdf.__defaults__, causing later default calls on a different system to reuse stale atom types and return invalid values.

Affected code:

dpdata/dpdata/md/rdf.py

Lines 43 to 50 in a7a50bf

def compute_rdf(box, posis, atype, sel_type=[None, None], max_r=5, nbins=100):
nframes = box.shape[0]
xx = None
all_rdf = []
all_cod = []
for ii in range(nframes):
xx, rdf, cod = _compute_rdf_1frame(
box[ii], posis[ii], atype, sel_type, max_r, nbins

dpdata/dpdata/md/rdf.py

Lines 61 to 70 in a7a50bf

def _compute_rdf_1frame(box, posis, atype, sel_type=[None, None], max_r=5, nbins=100):
all_types = list(set(list(np.sort(atype, kind="stable"))))
if sel_type[0] is None:
sel_type[0] = all_types
if sel_type[1] is None:
sel_type[1] = all_types
if not isinstance(sel_type[0], list):
sel_type[0] = [sel_type[0]]
if not isinstance(sel_type[1], list):
sel_type[1] = [sel_type[1]]

Minimal reproducer:

import numpy as np
from dpdata.md import rdf as rdfmod

box = np.eye(3).reshape(1, 3, 3) * 10
pos = np.array([[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]])

rdfmod.compute_rdf(box, pos, np.array([0, 1]))
print(rdfmod.compute_rdf.__defaults__)

_, stat, _ = rdfmod.compute_rdf(box, pos, np.array([2, 2]))
print(np.isfinite(stat).all(), stat[:3])

Current behavior:

([[np.int64(0), np.int64(1)], [np.int64(0), np.int64(1)]], 5, 100)
False [nan nan nan]

The function should not mutate either its default object or a caller-provided sel_type list. A common fix is to default to None and construct a local normalized selection list per call/frame.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    Status
    In Progress

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions