Skip to content

TrajectoryData

TrajFlag

Bases: int

Trajectory point classification flags for marking special trajectory events.

Provides enumeration values for identifying and filtering special points in ballistic trajectories. The flags can be combined using bitwise operations.

Flag Values
  • NONE (0): Standard trajectory point with no special events
  • ZERO_UP (1): Upward zero crossing (trajectory rising through sight line)
  • ZERO_DOWN (2): Downward zero crossing (trajectory falling through sight line)
  • ZERO (3): Any zero crossing (ZERO_UP | ZERO_DOWN)
  • MACH (4): Mach 1 transition point (sound barrier crossing)
  • RANGE (8): User requested point, typically by distance or time step
  • APEX (16): Trajectory apex (maximum height point)
  • ALL (31): All special points (combination of all above flags)
  • MRT (32): Mid-Range Trajectory/Maximum Ordinate (largest slant height) [PROPOSED]

Examples:

Basic flag usage:

from py_ballisticcalc.trajectory_data import TrajFlag

# Filter for zero crossings only
flags = TrajFlag.ZERO

# Filter for multiple event types
flags = TrajFlag.ZERO | TrajFlag.APEX | TrajFlag.MACH

# Filter for all special points
flags = TrajFlag.ALL

# Check if a trajectory point has specific flags
if point.flag & TrajFlag.APEX:
    print("Trajectory apex")

Trajectory calculation with flags:

# Calculate trajectory with zero crossings and apex
hit_result = calc.fire(shot, 1000, filter_flags=TrajFlag.ZERO | TrajFlag.APEX)

# Find all zero crossing points
zeros = [p for p in hit_result.trajectory if p.flag & TrajFlag.ZERO]

# Find apex point
apex = next((p for p in hit_result.trajectory if p.flag & TrajFlag.APEX), None)

Methods:

Name Description
name

Get the human-readable name for a trajectory flag value.

Functions

name staticmethod
name(value: Union[int, TrajFlag]) -> str

Get the human-readable name for a trajectory flag value.

Converts a numeric flag value to its corresponding string name for display, logging, or debugging purposes. Supports both individual flags and combined flag values with intelligent formatting.

Parameters:

Name Type Description Default
value Union[int, TrajFlag]

The TrajFlag enum value or integer flag to convert.

required

Returns:

Type Description
str

String name of the flag. For combined flags, returns names joined with "|". For unknown flags, returns "UNKNOWN". Special handling for ZERO flag combinations.

Examples:

# Individual flag names
print(TrajFlag.name(TrajFlag.ZERO))      # "ZERO"
print(TrajFlag.name(TrajFlag.APEX))      # "APEX"

# Combined flags
combined = TrajFlag.ZERO | TrajFlag.APEX
print(TrajFlag.name(combined))           # "ZERO|APEX"

# Unknown flags
print(TrajFlag.name(999))                # "UNKNOWN"
Source code in py_ballisticcalc/trajectory_data.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
@staticmethod
def name(value: Union[int, TrajFlag]) -> str:
    """Get the human-readable name for a trajectory flag value.

    Converts a numeric flag value to its corresponding string name for
    display, logging, or debugging purposes. Supports both individual
    flags and combined flag values with intelligent formatting.

    Args:
        value: The TrajFlag enum value or integer flag to convert.

    Returns:
        String name of the flag. For combined flags, returns names joined with "|".
            For unknown flags, returns "UNKNOWN". Special handling for ZERO flag combinations.

    Examples:
        ```python
        # Individual flag names
        print(TrajFlag.name(TrajFlag.ZERO))      # "ZERO"
        print(TrajFlag.name(TrajFlag.APEX))      # "APEX"

        # Combined flags
        combined = TrajFlag.ZERO | TrajFlag.APEX
        print(TrajFlag.name(combined))           # "ZERO|APEX"

        # Unknown flags
        print(TrajFlag.name(999))                # "UNKNOWN"
        ```
    """
    v = int(value)
    mapping = TrajFlag._value_to_name()
    if v in mapping:
        return mapping[v]
    parts = [mapping[bit] for bit in sorted(mapping) if bit and (v & bit) == bit]
    if "ZERO_UP" in parts and "ZERO_DOWN" in parts:
        parts.remove("ZERO_UP")
        parts.remove("ZERO_DOWN")
    return "|".join(parts) if parts else "UNKNOWN"

BaseTrajData

Bases: NamedTuple

Minimal ballistic trajectory point data.

Represents the minimum state information for a single point in a ballistic trajectory. The data are kept in basic units (seconds, feet) to avoid unit tracking and conversion overhead.

Attributes:

Name Type Description
time float

Time since projectile launch in seconds.

position Vector

3D position vector in feet (x=downrange, y=height, z=windage).

velocity Vector

3D velocity vector in feet per second.

mach float

Local speed of sound in feet per second.

Examples:

from py_ballisticcalc.vector import Vector

# Create trajectory point at launch
launch_pt = BaseTrajData(
    time=0.0,
    position=Vector(0.0, -0.1, 0.0),   # 0.1 ft scope height
    velocity=Vector(2640.0, 0.0, 0.0), # 800 m/s ≈ 2640 fps
    mach=1115.5                        # Standard conditions
)

# Interpolate between points
interpolated = BaseTrajData.interpolate('time', 1.25, launch_pt, mid_pt, end_pt)
Note

This class is designed for efficiency in calculation engines that may compute thousands of points over a trajectory. For detailed data with units and derived quantities, use TrajectoryData which can be constructed from BaseTrajData using from_base_data().

Methods:

Name Description
interpolate

Interpolate a BaseTrajData point using monotone PCHIP (default) or linear.

Functions

interpolate staticmethod
interpolate(
    key_attribute: str,
    key_value: float,
    p0: BaseTrajData,
    p1: BaseTrajData,
    p2: BaseTrajData,
    method: InterpolationMethod = "pchip",
) -> BaseTrajData

Interpolate a BaseTrajData point using monotone PCHIP (default) or linear.

Parameters:

Name Type Description Default
key_attribute str

Can be 'time', 'mach', or a vector component like 'position.x' or 'velocity.z'.

required
key_value float

The value to interpolate for.

required
p0 BaseTrajData

First bracketing point.

required
p1 BaseTrajData

Second (middle) bracketing point.

required
p2 BaseTrajData

Third bracketing point.

required
method InterpolationMethod

'pchip' (default, monotone cubic Hermite) or 'linear'.

'pchip'

Returns:

Type Description
BaseTrajData

The interpolated data point.

Raises:

Type Description
AttributeError

If the key_attribute is not a member of BaseTrajData.

ZeroDivisionError

If the interpolation fails due to zero division. (This will result if two of the points are identical).

ValueError

If method is not one of 'pchip' or 'linear'.

Source code in py_ballisticcalc/trajectory_data.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
@staticmethod
def interpolate(key_attribute: str, key_value: float,
                p0: BaseTrajData, p1: BaseTrajData, p2: BaseTrajData,
                method: InterpolationMethod = "pchip") -> BaseTrajData:
    """
    Interpolate a BaseTrajData point using monotone PCHIP (default) or linear.

    Args:
        key_attribute: Can be 'time', 'mach', or a vector component like 'position.x' or 'velocity.z'.
        key_value: The value to interpolate for.
        p0: First bracketing point.
        p1: Second (middle) bracketing point.
        p2: Third bracketing point.
        method: 'pchip' (default, monotone cubic Hermite) or 'linear'.

    Returns:
        The interpolated data point.

    Raises:
        AttributeError: If the key_attribute is not a member of BaseTrajData.
        ZeroDivisionError: If the interpolation fails due to zero division.
                           (This will result if two of the points are identical).
        ValueError: If method is not one of 'pchip' or 'linear'.
    """
    def get_key_val(td: "BaseTrajData", path: str) -> float:
        """Helper to get the key value from a BaseTrajData point."""
        if '.' in path:
            top, component = path.split('.', 1)
            obj = getattr(td, top)
            return getattr(obj, component)
        return getattr(td, path)

    # independent variable values
    x0 = get_key_val(p0, key_attribute)
    x1 = get_key_val(p1, key_attribute)
    x2 = get_key_val(p2, key_attribute)
    def _interp_scalar(y0, y1, y2):
        if method == "pchip":
            return interpolate_3_pt(key_value, x0, y0, x1, y1, x2, y2)
        elif method == "linear":
            pts = sorted(((x0, y0), (x1, y1), (x2, y2)), key=lambda p: p[0])
            (sx0, sy0), (sx1, sy1), (sx2, sy2) = pts
            if key_value <= sx1:
                return interpolate_2_pt(key_value, sx0, sy0, sx1, sy1)
            else:
                return interpolate_2_pt(key_value, sx1, sy1, sx2, sy2)
        else:
            raise ValueError("method must be 'pchip' or 'linear'")

    time = _interp_scalar(p0.time, p1.time, p2.time) if key_attribute != 'time' else key_value
    px = _interp_scalar(p0.position.x, p1.position.x, p2.position.x)
    py = _interp_scalar(p0.position.y, p1.position.y, p2.position.y)
    pz = _interp_scalar(p0.position.z, p1.position.z, p2.position.z)
    position = Vector(px, py, pz)
    vx = _interp_scalar(p0.velocity.x, p1.velocity.x, p2.velocity.x)
    vy = _interp_scalar(p0.velocity.y, p1.velocity.y, p2.velocity.y)
    vz = _interp_scalar(p0.velocity.z, p1.velocity.z, p2.velocity.z)
    velocity = Vector(vx, vy, vz)
    mach = _interp_scalar(p0.mach, p1.mach, p2.mach) if key_attribute != 'mach' else key_value

    return BaseTrajData(time=time, position=position, velocity=velocity, mach=mach)

TrajectoryData

Bases: NamedTuple

Data for one point in ballistic trajectory.

Attributes:

Name Type Description
time float

Flight time in seconds

distance Distance

Down-range (x-axis) coordinate of this point

velocity Velocity

Velocity vector at this point

mach float

Velocity in Mach terms

height Distance

Vertical (y-axis) coordinate of this point

slant_height Distance

Distance orthogonal to sight-line

drop_adj Angular

Sight adjustment to zero slant_height at this distance

windage Distance

Windage (z-axis) coordinate of this point

windage_adj Angular

Windage adjustment

slant_distance Distance

Distance along sight line that is closest to this point

angle Angular

Angle of velocity vector relative to x-axis

density_ratio float

Ratio of air density here to standard density

drag float

Standard Drag Factor at this point

energy Energy

Energy of bullet at this point

ogw Weight

Optimal game weight, given .energy

flag Union[TrajFlag, int]

Row type (TrajFlag)

Methods:

Name Description
look_distance

Synonym for slant_distance.

formatted

Return attributes as tuple of strings, formatted per PreferredUnits.

in_def_units

Return attributes as tuple of floats converting to PreferredUnits.

get_correction

Calculate the sight adjustment in radians.

calculate_energy

Calculate the kinetic energy of a projectile.

calculate_ogw

Calculate the optimal game weight for a projectile.

from_base_data

Create a TrajectoryData object from BaseTrajData.

from_props

Create a TrajectoryData object.

interpolate

Interpolate TrajectoryData where key_attribute==value using PCHIP (default) or linear.

Attributes

x property

Synonym for .distance.

y property

Synonym for .height.

z property

Synonym for .windage.

target_drop property
target_drop: Distance

Synonym for slant_height.

Functions

look_distance
look_distance() -> Distance

Synonym for slant_distance.

Source code in py_ballisticcalc/trajectory_data.py
357
358
359
360
@deprecated(reason="Use .slant_distance instead of .look_distance", version="2.2.0")
def look_distance(self) -> Distance:
    """Synonym for slant_distance."""
    return self.slant_distance
formatted
formatted() -> Tuple[str, ...]

Return attributes as tuple of strings, formatted per PreferredUnits.

Returns:

Type Description
Tuple[str, ...]

Tuple of formatted strings for this point, in PreferredUnits.

Source code in py_ballisticcalc/trajectory_data.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def formatted(self) -> Tuple[str, ...]:
    """Return attributes as tuple of strings, formatted per PreferredUnits.

    Returns:
        Tuple of formatted strings for this point, in PreferredUnits.
    """

    def _fmt(v: GenericDimension, u: Unit) -> str:
        """Format Dimension as a string."""
        return f"{v >> u:.{u.accuracy}f} {u.symbol}"

    return (
        f'{self.time:.3f} s',
        _fmt(self.distance, PreferredUnits.distance),
        _fmt(self.velocity, PreferredUnits.velocity),
        f'{self.mach:.2f} mach',
        _fmt(self.height, PreferredUnits.drop),
        _fmt(self.slant_height, PreferredUnits.drop),
        _fmt(self.drop_adj, PreferredUnits.adjustment),
        _fmt(self.windage, PreferredUnits.drop),
        _fmt(self.windage_adj, PreferredUnits.adjustment),
        _fmt(self.slant_distance, PreferredUnits.distance),
        _fmt(self.angle, PreferredUnits.angular),
        f'{self.density_ratio:.5e}',
        f'{self.drag:.3e}',
        _fmt(self.energy, PreferredUnits.energy),
        _fmt(self.ogw, PreferredUnits.ogw),
        TrajFlag.name(self.flag)
    )
in_def_units
in_def_units() -> Tuple[float, ...]

Return attributes as tuple of floats converting to PreferredUnits.

Returns:

Type Description
Tuple[float, ...]

Tuple of floats describing this point, in PreferredUnits.

Source code in py_ballisticcalc/trajectory_data.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
def in_def_units(self) -> Tuple[float, ...]:
    """Return attributes as tuple of floats converting to PreferredUnits.

    Returns:
        Tuple of floats describing this point, in PreferredUnits.
    """
    return (
        self.time,
        self.distance >> PreferredUnits.distance,
        self.velocity >> PreferredUnits.velocity,
        self.mach,
        self.height >> PreferredUnits.drop,
        self.slant_height >> PreferredUnits.drop,
        self.drop_adj >> PreferredUnits.adjustment,
        self.windage >> PreferredUnits.drop,
        self.windage_adj >> PreferredUnits.adjustment,
        self.slant_distance >> PreferredUnits.distance,
        self.angle >> PreferredUnits.angular,
        self.density_ratio,
        self.drag,
        self.energy >> PreferredUnits.energy,
        self.ogw >> PreferredUnits.ogw,
        self.flag
    )
get_correction staticmethod
get_correction(distance: float, offset: float) -> float

Calculate the sight adjustment in radians.

Parameters:

Name Type Description Default
distance float

The distance to the target in feet.

required
offset float

The offset from the target in feet.

required

Returns:

Type Description
float

The sight adjustment in radians.

Source code in py_ballisticcalc/trajectory_data.py
423
424
425
426
427
428
429
430
431
432
433
434
435
436
@staticmethod
def get_correction(distance: float, offset: float) -> float:
    """Calculate the sight adjustment in radians.

    Args:
        distance: The distance to the target in feet.
        offset: The offset from the target in feet.

    Returns:
        The sight adjustment in radians.
    """
    if distance != 0:
        return math.atan(offset / distance)
    return 0  # None
calculate_energy staticmethod
calculate_energy(
    bullet_weight: float, velocity: float
) -> float

Calculate the kinetic energy of a projectile.

Parameters:

Name Type Description Default
bullet_weight float

Projectile weight in grains.

required
velocity float

Projectile velocity in feet per second.

required

Returns:

Type Description
float

Kinetic energy in foot-pounds (ft·lbf).

Notes

Uses the standard small-arms approximation: E(ft·lbf) = weight(grains) * v(fps)^2 / 450400.

Source code in py_ballisticcalc/trajectory_data.py
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
@staticmethod
def calculate_energy(bullet_weight: float, velocity: float) -> float:
    """Calculate the kinetic energy of a projectile.

    Args:
        bullet_weight: Projectile weight in grains.
        velocity: Projectile velocity in feet per second.

    Returns:
        Kinetic energy in foot-pounds (ft·lbf).

    Notes:
        Uses the standard small-arms approximation:
        E(ft·lbf) = weight(grains) * v(fps)^2 / 450400.
    """
    return bullet_weight * math.pow(velocity, 2) / 450400
calculate_ogw staticmethod
calculate_ogw(
    bullet_weight: float, velocity: float
) -> float

Calculate the optimal game weight for a projectile.

Parameters:

Name Type Description Default
bullet_weight float

Bullet weight in grains (per common OGW formula).

required
velocity float

Projectile velocity in feet per second.

required

Returns:

Type Description
float

The optimal game weight in pounds.

Source code in py_ballisticcalc/trajectory_data.py
455
456
457
458
459
460
461
462
463
464
465
466
@staticmethod
def calculate_ogw(bullet_weight: float, velocity: float) -> float:
    """Calculate the optimal game weight for a projectile.

    Args:
        bullet_weight: Bullet weight in grains (per common OGW formula).
        velocity: Projectile velocity in feet per second.

    Returns:
        The optimal game weight in pounds.
    """
    return math.pow(bullet_weight, 2) * math.pow(velocity, 3) * 1.5e-12
from_base_data staticmethod
from_base_data(
    props: ShotProps,
    data: BaseTrajData,
    flag: Union[TrajFlag, int] = NONE,
) -> TrajectoryData

Create a TrajectoryData object from BaseTrajData.

Source code in py_ballisticcalc/trajectory_data.py
503
504
505
506
507
@staticmethod
def from_base_data(props: ShotProps, data: BaseTrajData,
                   flag: Union[TrajFlag, int] = TrajFlag.NONE) -> TrajectoryData:
    """Create a TrajectoryData object from BaseTrajData."""
    return TrajectoryData.from_props(props, data.time, data.position, data.velocity, data.mach, flag)
from_props staticmethod
from_props(
    props: ShotProps,
    time: float,
    range_vector: Vector,
    velocity_vector: Vector,
    mach: float,
    flag: Union[TrajFlag, int] = NONE,
) -> TrajectoryData

Create a TrajectoryData object.

Source code in py_ballisticcalc/trajectory_data.py
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
@staticmethod
def from_props(props: ShotProps,
                time: float,
                range_vector: Vector,
                velocity_vector: Vector,
                mach: float,
                flag: Union[TrajFlag, int] = TrajFlag.NONE) -> TrajectoryData:
    """Create a TrajectoryData object."""
    spin_drift = props.spin_drift(time)
    velocity = velocity_vector.magnitude()
    windage = range_vector.z + spin_drift
    drop_adjustment = TrajectoryData.get_correction(range_vector.x, range_vector.y)
    windage_adjustment = TrajectoryData.get_correction(range_vector.x, windage)
    trajectory_angle = math.atan2(velocity_vector.y, velocity_vector.x)
    look_angle_cos = math.cos(props.look_angle_rad)
    look_angle_sin = math.sin(props.look_angle_rad)
    density_ratio, _ = props.get_density_and_mach_for_altitude(range_vector.y)
    drag = props.drag_by_mach(velocity / mach)
    return TrajectoryData(
        time=time,
        distance=TrajectoryData._new_feet(range_vector.x),
        velocity=TrajectoryData._new_fps(velocity),
        mach=velocity / mach,
        height=TrajectoryData._new_feet(range_vector.y),
        slant_height=TrajectoryData._new_feet(range_vector.y * look_angle_cos - range_vector.x * look_angle_sin),
        drop_adj=TrajectoryData._new_rad(drop_adjustment - (props.look_angle_rad if range_vector.x else 0)),
        windage=TrajectoryData._new_feet(windage),
        windage_adj=TrajectoryData._new_rad(windage_adjustment),
        slant_distance=TrajectoryData._new_feet(range_vector.x * look_angle_cos + range_vector.y * look_angle_sin),
        angle=TrajectoryData._new_rad(trajectory_angle),
        density_ratio=density_ratio,
        drag=drag,
        energy=TrajectoryData._new_ft_lb(TrajectoryData.calculate_energy(props.weight_grains, velocity)),
        ogw=TrajectoryData._new_lb(TrajectoryData.calculate_ogw(props.weight_grains, velocity)),
        flag=flag
    )
interpolate staticmethod
interpolate(
    key_attribute: TRAJECTORY_DATA_ATTRIBUTES,
    value: Union[float, GenericDimension],
    p0: TrajectoryData,
    p1: TrajectoryData,
    p2: TrajectoryData,
    flag: Union[TrajFlag, int] = NONE,
    method: InterpolationMethod = "pchip",
) -> TrajectoryData

Interpolate TrajectoryData where key_attribute==value using PCHIP (default) or linear.

Parameters:

Name Type Description Default
key_attribute TRAJECTORY_DATA_ATTRIBUTES

Attribute to key on (e.g., 'time', 'distance').

required
value Union[float, GenericDimension]

Target value for the key attribute. A bare float is treated as raw value for dimensioned fields.

required
p0 TrajectoryData

First bracketing point.

required
p1 TrajectoryData

Second (middle) bracketing point.

required
p2 TrajectoryData

Third bracketing point.

required
flag Union[TrajFlag, int]

Flag to assign to the new point.

NONE
method InterpolationMethod

'pchip' (monotone cubic Hermite) or 'linear'.

'pchip'

Returns:

Type Description
TrajectoryData

Interpolated point with key_attribute==value.

Raises:

Type Description
AttributeError

If TrajectoryData doesn't have the specified attribute.

KeyError

If the key_attribute is 'flag'.

ZeroDivisionError

If interpolation fails due to zero division.

ValueError

If method is not one of 'pchip' or 'linear'.

Source code in py_ballisticcalc/trajectory_data.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
@staticmethod
def interpolate(key_attribute: TRAJECTORY_DATA_ATTRIBUTES, value: Union[float, GenericDimension],
                p0: TrajectoryData, p1: TrajectoryData, p2: TrajectoryData,
                flag: Union[TrajFlag, int]=TrajFlag.NONE,
                method: InterpolationMethod = "pchip") -> TrajectoryData:
    """
    Interpolate TrajectoryData where key_attribute==value using PCHIP (default) or linear.

    Args:
        key_attribute: Attribute to key on (e.g., 'time', 'distance').
        value: Target value for the key attribute. A bare float is treated as
            raw value for dimensioned fields.
        p0: First bracketing point.
        p1: Second (middle) bracketing point.
        p2: Third bracketing point.
        flag: Flag to assign to the new point.
        method: 'pchip' (monotone cubic Hermite) or 'linear'.

    Returns:
        Interpolated point with key_attribute==value.

    Raises:
        AttributeError: If TrajectoryData doesn't have the specified attribute.
        KeyError: If the key_attribute is 'flag'.
        ZeroDivisionError: If interpolation fails due to zero division.
        ValueError: If method is not one of 'pchip' or 'linear'.
    """
    key_attribute = TRAJECTORY_DATA_SYNONYMS.get(key_attribute, key_attribute)  # Resolve synonyms
    if not hasattr(TrajectoryData, key_attribute):
        raise AttributeError(f"TrajectoryData has no attribute '{key_attribute}'")
    if key_attribute == 'flag':
        raise KeyError("Cannot interpolate based on 'flag' attribute")
    key_value = value.raw_value if isinstance(value, GenericDimension) else value

    def get_key_val(td):
        """Helper to get the raw value of the key attribute from a TrajectoryData point."""
        val = getattr(td, key_attribute)
        return val.raw_value if hasattr(val, 'raw_value') else float(val)

    # The independent variable for interpolation (x-axis)
    x_val = key_value
    x0, x1, x2 = get_key_val(p0), get_key_val(p1), get_key_val(p2)

    # Use reflection to build the new TrajectoryData object
    interpolated_fields: typing.Dict[str, typing.Any] = {}
    for field_name in TrajectoryData._fields:
        if field_name == 'flag':
            continue

        p0_field = getattr(p0, field_name)

        if field_name == key_attribute:
            if isinstance(value, GenericDimension):
                interpolated_fields[field_name] = value
            else:  # value is a float, assume it's in the same unit as the original data
                if isinstance(p0_field, GenericDimension):
                    interpolated_fields[field_name] = type(p0_field).new_from_raw(float(value), p0_field.units)
                else:
                    interpolated_fields[field_name] = float(value)
            continue

        # Interpolate all other fields
        y0_val = p0_field
        y1_val = getattr(p1, field_name)
        y2_val = getattr(p2, field_name)

        if isinstance(y0_val, GenericDimension):
            y0, y1, y2 = y0_val.raw_value, y1_val.raw_value, y2_val.raw_value
            if method == "pchip":
                interpolated_raw = interpolate_3_pt(x_val, x0, y0, x1, y1, x2, y2)
            elif method == "linear":
                interpolated_raw = interpolate_2_pt(x_val, x0, y0, x1, y1) if x_val <= x1 else interpolate_2_pt(x_val, x1, y1, x2, y2)
            else:
                raise ValueError("method must be 'pchip' or 'linear'")
            interpolated_fields[field_name] = type(y0_val).new_from_raw(interpolated_raw, y0_val.units)
        elif isinstance(y0_val, (float, int)):
            fy0, fy1, fy2 = float(y0_val), float(y1_val), float(y2_val)
            if method == "pchip":
                interpolated_fields[field_name] = interpolate_3_pt(x_val, x0, fy0, x1, fy1, x2, fy2)
            elif method == "linear":
                interpolated_fields[field_name] = interpolate_2_pt(x_val, x0, fy0, x1, fy1) if x_val <= x1 else interpolate_2_pt(x_val, x1, fy1, x2, fy2)
            else:
                raise ValueError("method must be 'pchip' or 'linear'")
        else:
            raise TypeError(f"Cannot interpolate field '{field_name}' of type {type(y0_val)}")

    interpolated_fields['flag'] = flag
    return TrajectoryData(**interpolated_fields)