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.events if p.flag & TrajFlag.ZERO]

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

Methods:

Name Description
name

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

Methods:

name staticmethod
name(value: 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 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
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
188
189
190
@staticmethod
def name(value: 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.

Methods:

interpolate staticmethod
interpolate(
    key_attribute: BaseTrajDataAttribute,
    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 BaseTrajDataAttribute

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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
@staticmethod
def interpolate(
    key_attribute: BaseTrajDataAttribute,
    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'")

    vp0 = p0.position
    vp1 = p1.position
    vp2 = p2.position
    vv0 = p0.velocity
    vv1 = p1.velocity
    vv2 = p2.velocity

    time = _interp_scalar(p0.time, p1.time, p2.time) if key_attribute != "time" else key_value
    position = Vector(
        _interp_scalar(vp0.x, vp1.x, vp2.x),
        _interp_scalar(vp0.y, vp1.y, vp2.y),
        _interp_scalar(vp0.z, vp1.z, vp2.z),
    )
    velocity = Vector(
        _interp_scalar(vv0.x, vv1.x, vv2.x),
        _interp_scalar(vv0.y, vv1.y, vv2.y),
        _interp_scalar(vv0.z, vv1.z, vv2.z),
    )
    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)

InterpolationMethod

InterpolationMethod = Literal['pchip', 'linear']

BaseTrajDataAttribute

BaseTrajDataAttribute = Literal[
    "time",
    "position.x",
    "position.y",
    "position.z",
    "velocity.x",
    "velocity.y",
    "velocity.z",
    "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

Scalar velocity (magnitude) 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_angle Angular

Slant_height in angular term

windage Distance

Windage (z-axis) coordinate of this point

windage_angle Angular

Windage in angular terms

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 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.

drop_adj property
drop_adj: Angular

Synonym for drop_angle.

windage_adj property
windage_adj: Angular

Synonym for windage_angle.

Methods:

look_distance
look_distance() -> Distance

Synonym for slant_distance.

Source code in py_ballisticcalc/trajectory_data.py
495
496
497
498
@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
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
545
546
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_angle, PreferredUnits.adjustment),
        _fmt(self.windage, PreferredUnits.drop),
        _fmt(self.windage_angle, 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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
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_angle >> PreferredUnits.adjustment,
        self.windage >> PreferredUnits.drop,
        self.windage_angle >> 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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
@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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
@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
605
606
607
608
609
610
611
612
613
614
615
616
@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: TrajFlag | int = NONE,
) -> TrajectoryData

Create a TrajectoryData object from BaseTrajData.

Source code in py_ballisticcalc/trajectory_data.py
653
654
655
656
@staticmethod
def from_base_data(props: ShotProps, data: BaseTrajData, flag: 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: TrajFlag | int = NONE,
) -> TrajectoryData

Create a TrajectoryData object.

Source code in py_ballisticcalc/trajectory_data.py
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
@staticmethod
def from_props(
    props: ShotProps,
    time: float,
    range_vector: Vector,
    velocity_vector: Vector,
    mach: float,
    flag: TrajFlag | int = TrajFlag.NONE,
) -> TrajectoryData:
    """Create a TrajectoryData object."""
    adjusted_range = props.adjust_range_for_coriolis(time, range_vector)
    spin_drift = props.spin_drift(time)
    velocity = velocity_vector.magnitude()
    windage = adjusted_range.z + spin_drift
    drop_angle = TrajectoryData.get_correction(adjusted_range.x, adjusted_range.y)
    windage_angle = TrajectoryData.get_correction(adjusted_range.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(adjusted_range.x),
        velocity=TrajectoryData._new_fps(velocity),
        mach=velocity / mach,
        height=TrajectoryData._new_feet(adjusted_range.y),
        slant_height=TrajectoryData._new_feet(
            adjusted_range.y * look_angle_cos - adjusted_range.x * look_angle_sin
        ),
        drop_angle=TrajectoryData._new_rad(drop_angle - (props.look_angle_rad if adjusted_range.x else 0)),
        windage=TrajectoryData._new_feet(windage),
        windage_angle=TrajectoryData._new_rad(windage_angle),
        slant_distance=TrajectoryData._new_feet(
            adjusted_range.x * look_angle_cos + adjusted_range.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: TrajectoryDataAttribute,
    value: float | GenericDimension,
    p0: TrajectoryData,
    p1: TrajectoryData,
    p2: TrajectoryData,
    flag: 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 TrajectoryDataAttribute

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

required
value 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 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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
@staticmethod
def interpolate(
    key_attribute: TrajectoryDataAttribute,
    value: float | GenericDimension,
    p0: TrajectoryData,
    p1: TrajectoryData,
    p2: TrajectoryData,
    flag: 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: dict[str, 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)

TrajectoryDataFilter

TrajectoryDataFilter(
    props: ShotProps,
    filter_flags: TrajFlag | int,
    range_limit: float = 0.0,
    range_step: float = 0.0,
    time_step: float = 0.0,
)

Emit requested rows and events from accepted trajectory intervals.

Integrators call :meth:record_initial once followed by :meth:record_step for every accepted interval. Every query is evaluated from the interval's endpoint Hermite model. Rows are intentionally not merged by a time tolerance: a scheduled sample and a physical event are distinct observations unless the caller explicitly gives them the same state and flags.

Methods:

Name Description
record_initial

Record the launch state before any accepted interval exists.

record_step

Emit all scheduled samples and one-shot events between start and end.

record

Compatibility adapter for callers that still provide endpoints.

Source code in py_ballisticcalc/engines/base_engine.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def __init__(
    self,
    props: ShotProps,
    filter_flags: TrajFlag | int,
    range_limit: float = 0.0,
    range_step: float = 0.0,
    time_step: float = 0.0,
):
    """If a time_step > 0, then we will record a row at least that often in the trajectory."""
    self.records = []
    self.props = props
    self.filter = filter_flags
    self.time_step = time_step
    self.range_step = range_step
    self.range_limit = range_limit
    self.time_of_last_record = 0.0
    self.next_record_distance = 0.0
    self.prev_data = None
    self.look_angle_tangent = math.tan(props.look_angle_rad)

Methods:

record_initial
record_initial(data: BaseTrajData) -> None

Record the launch state before any accepted interval exists.

Source code in py_ballisticcalc/engines/base_engine.py
271
272
273
274
275
276
277
def record_initial(self, data: BaseTrajData) -> None:
    """Record the launch state before any accepted interval exists."""
    if self.prev_data is not None:
        raise RuntimeError("TrajectoryDataFilter was initialized twice")
    self.init(data)
    self._append(data, TrajFlag.RANGE if (self.range_step > 0 or self.time_step > 0) else TrajFlag.NONE)
    self.prev_data = data
record_step
record_step(start: BaseTrajData, end: BaseTrajData) -> None

Emit all scheduled samples and one-shot events between start and end.

Source code in py_ballisticcalc/engines/base_engine.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
def record_step(self, start: BaseTrajData, end: BaseTrajData) -> None:
    """Emit all scheduled samples and one-shot events between *start* and *end*."""
    if self.prev_data is None:
        self.record_initial(start)
    elif start != self.prev_data:
        raise ValueError("Trajectory steps must be contiguous")

    step = TrajectoryStep(start, end)
    rows: list[tuple[BaseTrajData, TrajFlag | int]] = []

    def add(data: BaseTrajData, flag: TrajFlag | int) -> None:
        rows.append((data, flag))

    if self.range_step > 0:
        while self.next_record_distance + self.range_step <= end.position.x:
            distance = self.next_record_distance + self.range_step
            if distance > self.range_limit + self.EPSILON:
                self.range_step = -1
                break
            if distance >= start.position.x - self.EPSILON:
                sample = step.at_x(distance)
                add(sample, TrajFlag.RANGE)
                # RANGE and TIME samples share one "last record" clock:
                # a time schedule starts from the most recently emitted
                # RANGE row, matching the long-standing filter contract.
                self.time_of_last_record = sample.time
            self.next_record_distance = distance

    if self.time_step > 0:
        while self.time_of_last_record + self.time_step <= end.time:
            self.time_of_last_record += self.time_step
            if self.time_of_last_record >= start.time:
                add(step.at_time(self.time_of_last_record), TrajFlag.RANGE)

    if self.filter & TrajFlag.APEX and start.velocity.y > 0.0 >= end.velocity.y:
        add(step.at_value(lambda data: data.velocity.y, 0.0), TrajFlag.APEX)
        self.filter &= ~TrajFlag.APEX

    mach_ratio = lambda data: data.velocity.magnitude() / data.mach
    if self.filter & TrajFlag.MACH and mach_ratio(start) > 1.0 > mach_ratio(end):
        add(step.at_value(mach_ratio, 1.0), TrajFlag.MACH)
        self.filter &= ~TrajFlag.MACH

    sight_height = lambda data: data.position.y - data.position.x * self.look_angle_tangent
    if self.filter & TrajFlag.ZERO_UP and sight_height(start) < 0.0 < sight_height(end):
        add(step.at_value(sight_height, 0.0), TrajFlag.ZERO_UP)
        self.filter &= ~TrajFlag.ZERO_UP
    elif self.filter & TrajFlag.ZERO_DOWN and sight_height(start) > 0.0 > sight_height(end):
        add(step.at_value(sight_height, 0.0), TrajFlag.ZERO_DOWN)
        self.filter &= ~TrajFlag.ZERO_DOWN

    for data, flag in sorted(rows, key=lambda row: row[0].time):
        self._append(data, flag)
    self.prev_data = end
record
record(data: BaseTrajData) -> None

Compatibility adapter for callers that still provide endpoints.

Source code in py_ballisticcalc/engines/base_engine.py
351
352
353
354
355
356
def record(self, data: BaseTrajData) -> None:
    """Compatibility adapter for callers that still provide endpoints."""
    if self.prev_data is None:
        self.record_initial(data)
    else:
        self.record_step(self.prev_data, data)

TrajectoryDataAttribute

TrajectoryDataAttribute = Literal[
    "time",
    "distance",
    "velocity",
    "mach",
    "height",
    "slant_height",
    "drop_angle",
    "windage",
    "windage_angle",
    "slant_distance",
    "angle",
    "density_ratio",
    "drag",
    "energy",
    "ogw",
    "flag",
    "x",
    "y",
    "z",
]