Skip to content

Statistical Adaptive SNR Thresholds - #3302

Merged
mha1 merged 18 commits into
ExpressLRS:masterfrom
SunjunKim:statistical-snr-dp
Nov 22, 2025
Merged

mha1 merged 18 commits into
ExpressLRS:masterfrom
SunjunKim:statistical-snr-dp

Conversation

@SunjunKim

@SunjunKim SunjunKim commented Aug 13, 2025 •

Copy link
Copy Markdown
Contributor

Idea

The current dynamic power management system uses fixed SNR thresholds for power adjustments, which is not working optimal especially on LR1121 RX. This PR introduces statistical SNR threshold calculation that adapts to actual signal quality conditions.

Instead of using predetermined thresholds, the system now:

  • Collects SNR samples when link quality is excellent (LQ ≥ 99)
  • Calculates statistical thresholds based on mean and standard deviation

How it works

StdevAccumulator Implementation

  • 32-sample circular buffer: Maintains a moving window of SNR values
  • Incremental mean and stdev calculation: Instead of looping through the entire buffer each time, O(1) logic is applied to each function to deal only with the added/removed values from the buffer.
  • Fixed-point arithmetic: Uses Q8.8 format (16-bit with 8 fractional bits) for precision without floating-point calculation overhead
  • Fast integer square root: Binary search algorithm for efficient standard deviation calculation

Dynamic Threshold Calculation

  • Upper threshold: mean - 3.5*stdev (for power increase when SNR is low). When LQ is less than 100, for earlier power up, the scale factor (3.5 by default) goes lower linearly, all the way down to 0.5 when LQ = 85.
  • Lower threshold: mean + 1.5*stdev (for power decrease when SNR is high)
  • Safety margin: Ensures minimum 1.5dB separation between thresholds (when the stdev is very low)
  • The SNR buffer is being reset when RF air rate is changed.

Performance

  • The algorithm was tested with an LR1121 RX on every SNR-based DP modes in my initial flight tests, and I found it works reasonably.
  • -4stdev -- +1.5stdev is my current go-to setting, but feel free to test other values.
  • Initialisation period takes ~10 seconds (which fills the buffer fully). Until that point, the default values (defined in common.cpp) will be used as a backup.

Remark

@SunjunKim

SunjunKim commented Aug 17, 2025 •

Copy link
Copy Markdown
Contributor Author

Uploading ELRS Quad-2025-08-17-175240.csv…
I found that the current logic reacts slowly during an LR test flight. During this time, the SNR gradually decreases with distance. This resulted in the LQ dropping by around 85 (the LQ-based safety net) before powering up.

In order to address the slowly degrading SNR, the power-up threshold has been made more (linearly) sensitive when the LQ drops below 100.

@deadbytefpv

Copy link
Copy Markdown
Contributor

@SunjunKim
would it be best for this to target master (4.0) instead of 3.x so we can get more testing for it via Release Candidates?

@SunjunKim

Copy link
Copy Markdown
Contributor Author

@SunjunKim would it be best for this to target master (4.0) instead of 3.x so we can get more testing for it via Release Candidates?

I still want on 3.x because it'll solve LR1121 power adjustment problem which is already deployed quite a lot.
Of course enough testing is needed so I want no rush to merge.

@pitts-mo

pitts-mo commented Oct 8, 2025

Copy link
Copy Markdown
Contributor

No news is good news?
Has anyone hit a condition where questionable behavior came up?

Should I update my RX too or can I test this by just updating my TX?
My RX are recently flashed with a PR off 3.x.x-maintenance 07b1627

@pitts-mo

pitts-mo commented Oct 9, 2025 •

Copy link
Copy Markdown
Contributor

Initial testing with this PR on TX and 3.6.0 release on RX seems OK. However, when flying the one brief spot that causes my TX to ramp up from from 10mw I noticed my TX did not consistently back off/reduce output power. Sometimes it would ramp back down a few power levels in a quick burst but not typically all the way back to 10mw other times it would stay at a much higher power level than expected for a much longer period than expected.

RadioMaster Nomad TX with antenna mode switch with this PR
HappyModel CrazyF405HD Mob8 with ELRS 3.6.0 release.

EdgeTX log sample stripped to include the link related columns.
TX-Log-2025-10-09-205157-cut.csv

I intend to test tomorrow with Nomad TX in single antenna mode.

@pitts-mo

Copy link
Copy Markdown
Contributor

@SunjunKim Can you suggest the correct way for me to adjust sensitivity? I would like to reduce sensitivity to SNR/RSSI changes and rely more heavily on LQ.

observations:
Testing the default settings of this PR appears to give changes in SNR/RSSI too much influence in setting / maintaining higher output power levels. I find TX output power steps to be excessively aggressive/conservative. Typically jumping up multiple power levels and then frequently taking more than 20 seconds to drop one power level and much longer to return to 10mw. I have never had a fail safe with ELRS and with prior builds my TX would rarely increase output power from 10mw for more than a couple seconds at a time and I almost never see >=250mw.

extra detail:
Nomad TX and HappyModel EP1/EP2 type RXs. Nomad antenna mode 1, 2, or switch did not change behavior. TX antenna mode switch appears to receive on both antennas and just switch the antenna used for RX/TX when the prior RX/TX antenna failed to receive a packet but the other antenna did.

@CapnBry

CapnBry commented Oct 19, 2025

Copy link
Copy Markdown
Member

I haven't commented on this because I've just looked at the code and have some changes I think are needed, but was waiting until I had a chance to use the code in action.

I'd like to apply myself as a blocker 😆 to prevent this getting merged until I have time for it, but it seems like pitts-mo has possible things we might need to address as well

@pitts-mo

Copy link
Copy Markdown
Contributor

This dynamic power implementation still feels too defensive for me but it did feel much better during my flights today.

details:
I flew several flights with this PR on TX and v3.6.0 on antenna diversity RX (Matek R24-D). These flights occurred over farm fields in very low RF environments on both a wing and quad up to ~4km out.

In these cases I found the behavior of dynamic TX power much more predictable. It was still bumping up to higher power levels than needed but still <250mw and staying up at those higher output powers longer than needed. However, power output levels were reducing in a much more predictable/desirable way than my previous single antenna RX tests in a thickly settled area.

@CapnBry
CapnBry changed the base branch from 3.x.x-maintenance to master November 17, 2025 17:02
@CapnBry

CapnBry commented Nov 17, 2025 •

Copy link
Copy Markdown
Member

@SunjunKim I've retargetted this to master and made a couple changes. We can consider this as a backport for a 3.7.0 but let's work on master first where all the new features go and there's a ton of testing coming up for.

  • Removed DynamicPower_SnrThresholdUpdate(), as why does it need to do this calculation at ISR time instead of right before doing the rest of the math?
  • Removed IRAM from all the functions. The ones that don't run in the ISR don't need it, and the other one I do not believe this code needs the speed to warrant using it.

However, can we not do float operations? The result of mean and standardDeviation is like divided by 256, turned into a float, multiplied by 16, then converted back to an int. Can we just use the raw fixed value and scale it to the same integer value?

diff --git a/src/lib/MeanAccumulator/StdevAccumulator.h b/src/lib/MeanAccumulator/StdevAccumulator.h
index 08027c1f..bdb05e47 100644
--- a/src/lib/MeanAccumulator/StdevAccumulator.h
+++ b/src/lib/MeanAccumulator/StdevAccumulator.h
@@ -3,12 +3,6 @@
 #include <cstdint>
 #include <cmath>

-// Fixed-point arithmetic constants
-// Using 16-bit fixed-point with 8 fractional bits (Q8.8 format)
-#define FIXED_POINT_SHIFT 8
-#define FIXED_POINT_SCALE (1 << FIXED_POINT_SHIFT)
-#define FIXED_POINT_MASK (FIXED_POINT_SCALE - 1)
-
 // Fast integer square root using binary search
 // algorithm adopted from https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2
)
 uint16_t fast_sqrt_uint(uint32_t x)
@@ -43,7 +37,12 @@ uint16_t fast_sqrt_uint(uint32_t x)
 class StdevAccumulator
 {
 public:
-    static const size_t WINDOW_SIZE = 48;
+    static constexpr size_t WINDOW_SIZE = 48;
+    // Fixed-point arithmetic constants
+    // Using 16-bit fixed-point with 8 fractional bits (Q8.8 format)
+    static constexpr uint32_t FIXED_POINT_SHIFT = 8;
+    static constexpr uint32_t FIXED_POINT_SCALE = 1 << FIXED_POINT_SHIFT;
+    static constexpr uint32_t FIXED_POINT_MASK = FIXED_POINT_SCALE - 1;

     StdevAccumulator()
     {
@@ -80,35 +79,45 @@ public:
     /// @brief Computes and returns the mean of the current buffer contents.
     /// @return Mean as float, or 0.0f if no data
     float mean()
+    {
+        return static_cast<float>(meanRaw()) / FIXED_POINT_SCALE;
+    }
+
+    int32_t meanRaw()
     {
         if (_count == 0)
         {
-            return 0.0f;
+            return 0;
         }

         if (!_dirty)
         {
-            return static_cast<float>(_lastMeanFixed) / FIXED_POINT_SCALE;
+            return _lastMeanFixed;
         }

         // Fixed-point division using bit shifting
         _lastMeanFixed = (_sum << FIXED_POINT_SHIFT) / _count;
         // Don't clear _dirty here, as stdev may still need update
-        return static_cast<float>(_lastMeanFixed) / FIXED_POINT_SCALE;
+        return _lastMeanFixed;
     }

     /// @brief Computes and returns the standard deviation of the current buffer contents.
     /// @return Standard deviation as float, or 0.0f if not enough data
     float standardDeviation()
+    {
+        return static_cast<float>(standardDeviationRaw()) / FIXED_POINT_SCALE;
+    }
+
+    int32_t standardDeviationRaw()
     {
         if (_count < 2)
         {
-            return 0.0f;
+            return 0;
         }

         if (!_dirty)
         {
-            return static_cast<float>(_lastStdevFixed) / FIXED_POINT_SCALE;
+            return _lastStdevFixed;
         }

         // Calculate mean in fixed-point
@@ -136,7 +145,7 @@ public:
         // Note: sqrt(variance * 256) = sqrt(variance) * 16, so we need to scale back to 256
         _lastStdevFixed = fast_sqrt_uint(varianceFixed) << 4;
         _dirty = false;
-        return static_cast<float>(_lastStdevFixed) / FIXED_POINT_SCALE;
+        return _lastStdevFixed;
     }

     /// @brief Returns the number of valid entries (up to WINDOW_SIZE)
diff --git a/src/src/dynpower.cpp b/src/src/dynpower.cpp
index 6bab1ad8..24c1c06c 100644
--- a/src/src/dynpower.cpp
+++ b/src/src/dynpower.cpp
@@ -148,10 +148,6 @@ void DynamicPower_Update(uint32_t now)
   // the calculation could exceed 100% during a rate change or initial connect when the LQs are not synced
   lq_current = std::min(lq_current * 100 / std::max((uint32_t)LBTSuccessCalc.getLQ(), (uint32_t)1U), (uint32_t)100U);
 #endif
-  if (lq_current >= 99)
-  {
-      dynpower_stat_snr.add(snrScaled);
-  }
   uint32_t lq_avg = dynpower_mavg_lq;
   int32_t lq_diff = lq_avg - lq_current;
   dynpower_mavg_lq.add(lq_current);
@@ -195,11 +191,17 @@ void DynamicPower_Update(uint32_t now)
     int8_t snr_stat_threshold_up = ExpressLRS_currAirRate_RFperfParams->DynpowerSnrThreshUp;
     int8_t snr_stat_threshold_dn = ExpressLRS_currAirRate_RFperfParams->DynpowerSnrThreshDn;

+    // Incorporate the current value if LQ is meets the desired LQ standard
+    if (lq_current >= 99)
+    {
+        dynpower_stat_snr.add(snrScaled);
+    }
     // is SNR stat ready? = is the buffer fully stuffed?
     if(dynpower_stat_snr.getCount() >= dynpower_stat_snr.WINDOW_SIZE)
     {
-      int32_t snr_stat_mean = static_cast<int32_t>(dynpower_stat_snr.mean()*16);
-      int32_t snr_stat_stdev = static_cast<int32_t>(dynpower_stat_snr.standardDeviation()*16);
+      static_assert(dynpower_stat_snr.FIXED_POINT_SHIFT >= 4, "StdDevAccumulator must be at least 4 bits of decimal fixed point");
+      int32_t snr_stat_mean = dynpower_stat_snr.meanRaw() >> (dynpower_stat_snr.FIXED_POINT_SHIFT - 4);
+      int32_t snr_stat_stdev = dynpower_stat_snr.standardDeviationRaw() >> (dynpower_stat_snr.FIXED_POINT_SHIFT - 4);

       // Fuzzy logic: reduce scale factor when LQ is getting low for more conservative power management
       // Base scale factor is 13/4 (3.25), reduce it proportionally when LQ < 100
@@ -213,6 +215,7 @@ void DynamicPower_Update(uint32_t now)
       int8_t snr_thre_dn_scaled = static_cast<int8_t>((snr_stat_mean + snr_stat_stdev*3/2)/16); // +1.5 sd
       int8_t snr_thre_up_limit = static_cast<int8_t>((snr_stat_mean)/16)-SNR_SCALE(1.0); // to ensure at least -1.0 dB split between thresholds

+      //DBGLN("cur=%d tup=%d tdn=%d lim=%d mean=%d sd=%d", snrScaled, snr_thre_up_scaled, snr_thre_dn_scaled, snr_thre_up_limit, snr_stat_mean, snr_stat_stdev);
       snr_stat_threshold_up = std::min(snr_thre_up_scaled, snr_thre_up_limit);
       snr_stat_threshold_dn = snr_thre_dn_scaled;
     }

@pkendall64

Copy link
Copy Markdown
Collaborator

@CapnBry we want to avoid float math as, much as possible as the 8285 & C3 does NOT have an FPU

@CapnBry

CapnBry commented Nov 17, 2025 •

Copy link
Copy Markdown
Member

@CapnBry we want to avoid float math as, much as possible as the 8285 & C3 does NOT have an FPU

Absolutely! That's why I was asking sunjun if it was ok (and if it would preserve the correct value) to skip the intermediate floating point step and just use raw values and shifts. It seems to work just fine but I didn't want to change any of the math without checking first.

@CapnBry

CapnBry commented Nov 20, 2025 •

Copy link
Copy Markdown
Member

I've pushed the changes that use only fixed point math as per my diff above.

TL;DR - Uses more power to achieve largely similar results to fixed values. Does not ever underestimate the power need.

Regarding performance, I've been testing this on and off for a couple of months now, and done some walk testing and a lot of flying this week. Overall, it seems to not be underestimating the power needed or getting wedged with too-low power in any situation I've tried to throw at it. It definitely appears more adaptive instead of using fixed values, which means the LR1121 is working a lot better without having to compile in any new fixed values. Fantastic. Here are some sort of typical graphs from the EdgeTX logs

SX1280 250Hz 40m

dynpower-sx1280-noamp-250hz-40m-master dynpower-sx1280-noamp-250hz-40m-sunjun

SX1280 50Hz 40m

dynpower-sx1280-noamp-50hz-40m-master dynpower-sx1280-noamp-50hz-40m-sunjun

In both, the first is standard dynamic power, the second is this PR. Running some stats on the logs, this PR always uses more power than the existing dynamic power, but also shows a slightly higher average LQ. It does seem to sort of get stuck on higher power though, not because there's anything wrong in the code, but just because the statistics suggest it for the chosen target LQ (99-100%). Take for example this longer flight at distances mostly <1km with some clear LOS and some obscured by trees, SX1280 333Hz on this PR

image

There's so many times here where the TSNR is above the static power down threshold (9.5) but the power just stays locked at max (500mW) after an event that caused it to go up where the static limits would have dropped the power in a much more reasonable time. I am wondering if maybe the requirement that the LQ be 99 or 100 for the statistics is a bit too tight? It also seems like the SNR is not correlated with the TX power at all in that graph because the SNR is almost always very good. I feel like in this log the existing system would have used far less power and maintained similar LQ. Is it possible the isSignalBad test added is there because it is always overestimating the required power and therefore needed an additional check to rein it in? 🤔

I'm not saying that it is doing anything wrong, and does follow a more natural reaction to changes, but it does seem to overestimate the power required and then stick with it for a longer time. That's not harmful per-se and the conservative nature is definitely better than the alternative.

@mha1
mha1 merged commit 2775774 into ExpressLRS:master Nov 22, 2025
@pitts-mo

pitts-mo commented Dec 6, 2025

Copy link
Copy Markdown
Contributor

This appears to work well in Master ac862ac .

The new dynamic power is still bumping up to higher power levels than I am familiar with but I have not hit an instance that feels absurdly excessive. I think all my flights so far have remained >=100mw (1w dynamic). Power ramp down is also much quicker and more predictable than the last time I tested this.

I plan to keep an eye on my TX power outputs for a while especially when my RX does not have a PA.
Thank you @SunjunKim @CapnBry @pkendall64 and group, -p

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants