North is one direction even when the numbers straddle zero

A satellite-derived elevation model can support terrain-aspect analysis, but summarizing its directions requires different arithmetic from summarizing height. Two slopes facing 350 and 10 degrees both point close to north under a compass convention. Their ordinary numerical average is 180 degrees, which points south. The calculation has treated the ends of a circular scale as far apart on a line, creating a direction opposite to the cluster the analyst intended to describe.

This tutorial computes a circular mean and a mean resultant length with a small standard-library Python function. It uses invented compass aspects, exposes the coordinate convention and returns no mean direction when opposing vectors cancel within a declared numerical tolerance. The code summarizes already prepared angles; it does not derive terrain gradients or process a real elevation raster. Its purpose is to make a directional summary inspectable before it is attached to a watershed, habitat unit or other remote-sensing reporting area.

1. Declare the aspect convention and preserve undefined terrain

Here zero degrees means north, ninety means east, one hundred eighty means south and two hundred seventy means west, with angles increasing clockwise. GDAL's aspect documentation describes this azimuth convention as well as an alternative trigonometric convention. A numeric angle without its convention can therefore refer to a different physical direction in another workflow. Convert deliberately when needed, retain the source definition and do not assume that a familiar field name makes all aspect products interchangeable.

Flat terrain has no downslope aspect to average. GDAL documents a nodata representation for undefined flat-area aspect and an option that instead writes zero. In a compass dataset, zero is also a valid northward direction. If flat areas have been encoded that way, preserve a separate mask or other adequate source information before summarizing. This function cannot recover the distinction from the number alone. It rejects out-of-range and missing values rather than turning a nodata code into a plausible direction through automatic angle wrapping. [1]

2. Average the direction vectors instead of the degree labels

Represent each valid compass angle as a unit direction vector. Its east component is the sine of the angle and its north component is the cosine, after conversion from degrees to radians. Average those components using the declared positive weights, then recover the compass direction with the two-argument arctangent of east and north. SciPy's circular-mean documentation gives the equivalent unweighted idea through the argument of a mean complex unit vector. The weighted function here is an explicit teaching implementation, not a call to SciPy.

Also calculate the length of the averaged vector. With positive weights this resultant length ranges from zero to one: aligned directions reinforce one another, while opposed directions can cancel. The length is useful context for the mean but is not a confidence level or the percentage of terrain facing a particular direction. It describes the concentration of the supplied directional vectors under their weights. Keep the original distribution available because one mean and one length cannot preserve every feature of a complicated aspect pattern. [2]

3. Check a northward pair and an opposing pair

For the invented 350- and 10-degree pair with equal weights, the east components cancel and the north components reinforce. The circular mean is north, represented as zero degrees, and the resultant length is approximately 0.9848. The ordinary arithmetic mean of the degree labels is still 180, demonstrating why the linear calculation is inappropriate at the wraparound. No actual slope or vegetation condition has been inferred from these two invented observations; the example checks the geometry of the summary.

Now consider equal weights at ninety and two hundred seventy degrees. East and west cancel, leaving no preferred mean direction. Floating-point arithmetic may leave a tiny residual, so the code returns null for direction when the resultant length is at most one trillionth. This is a numerical cancellation policy for the example, not an ecological acceptance threshold. SciPy documents its own implementation-dependent zero-resultant behavior; the explicit null choice here should not be confused with reproducing every detail of that library's API. [2]

Two compass plots compare 350 and 10 degree samples with a northward circular mean against opposing east and west samples whose mean direction is undefined
Synthetic compass-angle examples: zero is north and angles increase clockwise. Resultant length describes directional concentration, not terrain slope, uncertainty or a probability. Original artwork: iT Sensing Editorial / TechnoGIS.

4. Choose weights that match the reporting question

Equal weights give every supplied direction the same contribution. If the question concerns planimetric area and the valid cells have different ground areas, appropriate area weights may be needed. For a deliberately simple weighted example, give north a weight of three and east a weight of one. The mean points about 18.435 degrees clockwise from north, with a resultant length of approximately 0.7906. That result follows from the declared vectors and weights, not from an estimated proportion of solar energy or vegetation response.

A collection of field points, raster cells and generalized terrain polygons can have different sampling support. Do not interchange their weights without deciding what population the summary represents. The function requires strictly positive finite weights; remove zero-support observations through an explicit preparation step. Keep the valid area or sample count beside the result, especially when different dates, masks or elevation products supply different subsets. Directional averaging does not correct an unrepresentative sample simply because its trigonometric arithmetic is sound.

5. Run the implementation and inspect the components

Save the code as aspect_mean.py and the invented input as aspects.json. Run the self-test and then the JSON example. The output includes count, total weight, mean east and north components, resultant length and circular mean in compass degrees. The self-test checks the north-wrap example, the opposing pair and the weighted north-east pair. Examine the components as well as the final angle so that a cancellation or an unexpected convention remains visible in the delivered record.

The function accepts degrees from zero inclusive to three hundred sixty exclusive. It checks array lengths, finite numeric values and positive weights. It does not choose a terrain mask, read a coordinate reference system or calculate a raster derivative. For a real project, prepare those inputs using the actual elevation product and a documented terrain method, then verify several known slope orientations. A north-up display is useful context but should not replace checking the quantitative aspect convention and valid-data definition.

"""Circular summary of prepared compass aspects, with 0 north and 90 east."""
import json
import math
import sys


def finite_number(value):
    return type(value) in (int, float) and math.isfinite(value)


def summarize(angles, weights=None):
    if not isinstance(angles, list) or not angles:
        raise ValueError('Provide a nonempty list of compass angles')
    if not all(finite_number(a) and 0 <= a < 360 for a in angles):
        raise ValueError('Angles must be finite degrees in [0, 360)')
    if weights is None:
        weights = [1.0] * len(angles)
    if not isinstance(weights, list) or len(weights) != len(angles):
        raise ValueError('Weights must match the angle list')
    if not all(finite_number(w) and w > 0 for w in weights):
        raise ValueError('Weights must be positive and finite')
    total = math.fsum(weights)
    if not math.isfinite(total):
        raise ValueError('Total weight must be finite')
    radians = [math.radians(a) for a in angles]
    east = math.fsum((w / total) * math.sin(a)
                     for w, a in zip(weights, radians))
    north = math.fsum((w / total) * math.cos(a)
                      for w, a in zip(weights, radians))
    length = min(1.0, math.hypot(east, north))
    tolerance = 1e-12  # Numerical cancellation, not a scientific QA threshold.
    direction = None
    if length > tolerance:
        direction = math.degrees(math.atan2(east, north)) % 360
        if min(direction, 360 - direction) < 1e-10:
            direction = 0.0
    return {'count': len(angles), 'total_weight': total,
            'mean_east': east, 'mean_north': north,
            'resultant_length': length, 'mean_compass_degrees': direction,
            'cancellation_tolerance': tolerance}


EXAMPLE = {'angles': [350, 10], 'weights': [1, 1]}


def self_test():
    north = summarize(**EXAMPLE)
    opposite = summarize([90, 270])
    weighted = summarize([0, 90], [3, 1])
    assert north['mean_compass_degrees'] == 0
    assert math.isclose(north['resultant_length'], math.cos(math.radians(10)))
    assert opposite['mean_compass_degrees'] is None
    assert math.isclose(weighted['mean_compass_degrees'],
                        math.degrees(math.atan2(1, 3)))
    return {'passed': True, 'north_pair': north, 'opposing_pair': opposite,
            'weighted_north_east': weighted}


if __name__ == '__main__':
    if len(sys.argv) != 2:
        raise SystemExit('Usage: python aspect_mean.py --self-test | aspects.json')
    if sys.argv[1] == '--self-test':
        output = self_test()
    else:
        with open(sys.argv[1], encoding='utf-8') as stream:
            output = summarize(**json.load(stream))
    print(json.dumps(output, indent=2, allow_nan=False))

Commands and inventory structure (replace every example input):

python aspect_mean.py --self-test
python aspect_mean.py aspects.json

aspects.json contains invented compass aspects and positive weights:
{"angles":[350,10],"weights":[1,1]}

6. Interpret a mean direction without inventing a mean landform

A directional mean can help summarize aspect patterns, but it does not reconstruct the slope of an average terrain surface. The calculation uses unit directions and discards slope magnitude. A set of steep and gentle north-facing cells can have the same directional concentration despite very different gradients. If the question concerns a mean gradient, illumination or another physical process, define the appropriate variables and model rather than assuming that an average aspect alone supplies the needed terrain description.

Deliver the convention, valid-data policy, weights, count and resultant length with the mean, and retain a directional distribution when it helps interpretation. Distinct opposing groups can be scientifically meaningful even when their resultant vanishes; null then describes the absence of one preferred summary direction, not the absence of terrain information. Treat the result as a compact descriptor of the supplied observations. That preserves the usefulness of circular statistics while keeping the remote-sensing interpretation attached to the terrain measurements and question that generated it.

Sources and technical reading