generated from StabilityNexus/Template-Repo
-
-
Notifications
You must be signed in to change notification settings - Fork 11
PID difficulty adjuster with pure integer arithmetic #63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
anshulchikhale30-p
wants to merge
10
commits into
StabilityNexus:main
Choose a base branch
from
anshulchikhale30-p:pid-app
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
b531c45
done
anshulchikhale30-p 34deb5d
Update minichain/chain.py
anshulchikhale30-p 25ee67d
Update minichain/chain.py
anshulchikhale30-p 0fde886
Update minichain/chain.py
anshulchikhale30-p 258342b
Update minichain/pid.py
anshulchikhale30-p 46ae32e
Update test_pid_integration.py
anshulchikhale30-p d911642
Update minichain/pow.py
anshulchikhale30-p af63105
Update tests/test_difficulty.py
anshulchikhale30-p 879a9c1
Update tests/test_difficulty.py
anshulchikhale30-p 08e1cb3
Update test_pid_integration.py
anshulchikhale30-p File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| """ | ||
| PID-based Difficulty Adjuster for MiniChain | ||
|
|
||
| Uses fixed-point integer arithmetic for deterministic behavior across all nodes. | ||
|
|
||
| Key Fix: Uses integer division (difficulty // 10) instead of float (difficulty * 0.1) | ||
| This prevents chain forks from CPU rounding differences. | ||
| """ | ||
|
|
||
| import time | ||
| from typing import Optional | ||
|
|
||
|
|
||
| class PIDDifficultyAdjuster: | ||
| """ | ||
| Adjusts blockchain difficulty using a PID controller to maintain target block time. | ||
|
|
||
| Uses fixed-point integer scaling (SCALE=1000) for deterministic behavior. | ||
| Ensures all nodes compute identical results regardless of CPU/platform. | ||
| """ | ||
|
|
||
| SCALE = 1000 # Fixed-point scaling factor | ||
|
|
||
| def __init__( | ||
| self, | ||
| target_block_time: float = 5.0, | ||
| kp: int = 500, | ||
| ki: int = 50, | ||
| kd: int = 100 | ||
| ): | ||
| """ | ||
| Initialize the PID difficulty adjuster. | ||
|
|
||
| Args: | ||
| target_block_time: Target time for block generation in seconds | ||
| kp: Proportional coefficient (pre-scaled by SCALE). Default 500 = 0.5 | ||
| ki: Integral coefficient (pre-scaled by SCALE). Default 50 = 0.05 | ||
| kd: Derivative coefficient (pre-scaled by SCALE). Default 100 = 0.1 | ||
| """ | ||
| self.target_block_time = target_block_time | ||
| self.kp = kp # Proportional | ||
| self.ki = ki # Integral | ||
| self.kd = kd # Derivative | ||
| self.integral = 0 | ||
| self.previous_error = 0 | ||
| self.last_block_time = time.monotonic() | ||
| self.integral_limit = 100 * self.SCALE | ||
|
|
||
| def adjust( | ||
| self, | ||
| current_difficulty: Optional[int] = None, | ||
| actual_block_time: Optional[float] = None | ||
| ) -> int: | ||
| """ | ||
| Calculate new difficulty based on actual block time. | ||
|
|
||
| Args: | ||
| current_difficulty: Current difficulty (default: 1000) | ||
| actual_block_time: Time to mine block in seconds | ||
| If None, calculated from time since last call | ||
|
|
||
| Returns: | ||
| New difficulty value (minimum 1) | ||
|
|
||
| Example: | ||
| adjuster = PIDDifficultyAdjuster(target_block_time=10) | ||
| new_difficulty = adjuster.adjust(current_difficulty=10000, actual_block_time=12.5) | ||
| """ | ||
|
|
||
| # Handle None difficulty | ||
| if current_difficulty is None: | ||
| current_difficulty = 1000 | ||
|
|
||
| # Calculate actual_block_time if not provided | ||
| if actual_block_time is None: | ||
| now = time.monotonic() | ||
| actual_block_time = now - self.last_block_time | ||
| self.last_block_time = now | ||
|
|
||
| # ===== Fixed-Point Integer Arithmetic ===== | ||
| # Convert times to scaled integers for precise calculation | ||
| actual_block_time_scaled = int(actual_block_time * self.SCALE) | ||
| target_time_scaled = int(self.target_block_time * self.SCALE) | ||
|
|
||
| # Calculate error: positive = too fast, negative = too slow | ||
| error = target_time_scaled - actual_block_time_scaled | ||
|
|
||
| # ===== Proportional Term ===== | ||
| p_term = self.kp * error | ||
|
|
||
| # ===== Integral Term with Anti-Windup ===== | ||
| self.integral += error | ||
| self.integral = max( | ||
| min(self.integral, self.integral_limit), | ||
| -self.integral_limit | ||
| ) | ||
| i_term = self.ki * self.integral | ||
|
|
||
| # ===== Derivative Term ===== | ||
| derivative = error - self.previous_error | ||
| self.previous_error = error | ||
| d_term = self.kd * derivative | ||
|
|
||
| # ===== PID Calculation ===== | ||
| # Combine all terms and scale back to normal units | ||
| adjustment = (p_term + i_term + d_term) // self.SCALE | ||
|
|
||
| # ===== Safety Constraint: Limit Change to 10% ===== | ||
| # ✅ FIXED: Use integer division instead of float multiplier | ||
| # Was: max_delta = max(1, int(current_difficulty * 0.1)) | ||
| # Now: max_delta = max(1, current_difficulty // 10) | ||
| max_delta = max(1, current_difficulty // 10) | ||
|
|
||
| # Clamp adjustment to safety bounds | ||
| clamped_adjustment = max( | ||
| min(adjustment, max_delta), | ||
| -max_delta | ||
| ) | ||
|
|
||
| # Ensure we move at least ±1 if adjustment is non-zero | ||
| delta = clamped_adjustment | ||
|
|
||
| # Calculate and return new difficulty | ||
| new_difficulty = current_difficulty + delta | ||
| return max(1, new_difficulty) | ||
|
|
||
| def reset(self) -> None: | ||
| """Reset PID state (integral and derivative history).""" | ||
| self.integral = 0 | ||
| self.previous_error = 0 | ||
| self.last_block_time = time.monotonic() | ||
|
|
||
| def get_state(self) -> dict: | ||
| """ | ||
| Get current PID state for debugging or persistence. | ||
|
|
||
| Returns: | ||
| Dictionary containing integral, previous_error, and last update time | ||
| """ | ||
| return { | ||
| "integral": self.integral, | ||
| "previous_error": self.previous_error, | ||
| "last_block_time": self.last_block_time | ||
| } | ||
|
|
||
| def set_state(self, state: dict) -> None: | ||
| """ | ||
| Restore PID state from a dictionary (for recovery/persistence). | ||
|
|
||
| Args: | ||
| state: Dictionary with keys 'integral', 'previous_error', 'last_block_time' | ||
| """ | ||
| self.integral = state.get("integral", 0) | ||
| self.previous_error = state.get("previous_error", 0) | ||
| self.last_block_time = state.get("last_block_time", time.monotonic()) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.