Skip to content

Commit

Permalink
Merge pull request #2310 from opentensor/btsdk-docs/roman/docstrings-…
Browse files Browse the repository at this point in the history
…improvement

Updating/improving/creating docstring codebase
  • Loading branch information
roman-opentensor authored Sep 18, 2024
2 parents e8ab3b9 + 44f7358 commit 87a923d
Show file tree
Hide file tree
Showing 54 changed files with 1,149 additions and 735 deletions.
12 changes: 12 additions & 0 deletions bittensor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,22 @@

# Logging helpers.
def trace(on: bool = True):
"""
Enables or disables trace logging.
Args:
on (bool): If True, enables trace logging. If False, disables trace logging.
"""
logging.set_trace(on)


def debug(on: bool = True):
"""
Enables or disables debug logging.
Args:
on (bool): If True, enables debug logging. If False, disables debug logging.
"""
logging.set_debug(on)


Expand Down
165 changes: 97 additions & 68 deletions bittensor/core/axon.py

Large diffs are not rendered by default.

29 changes: 20 additions & 9 deletions bittensor/core/chain_data/axon_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,6 @@
"""
This module defines the `AxonInfo` class, a data structure used to represent information about an axon endpoint
in the bittensor network.
The `AxonInfo` class includes attributes such as version, IP address, port, IP type, hotkey, coldkey, and protocol,
along with additional placeholders to accommodate future expansion. It provides various methods to facilitate handling
and interacting with axon information, including methods for converting to and from JSON strings, checking the
serving status, generating string representations, and creating instances from a dictionary or a parameter dictionary.
"""

import json
Expand All @@ -36,6 +31,22 @@

@dataclass
class AxonInfo:
"""
The `AxonInfo` class represents information about an axon endpoint in the bittensor network. This includes
properties such as IP address, ports, and relevant keys.
Attributes:
version (int): The version of the axon endpoint.
ip (str): The IP address of the axon endpoint.
port (int): The port number the axon endpoint uses.
ip_type (int): The type of IP protocol (e.g., IPv4 or IPv6).
hotkey (str): The hotkey associated with the axon endpoint.
coldkey (str): The coldkey associated with the axon endpoint.
protocol (int): The protocol version (default is 4).
placeholder1 (int): Reserved field (default is 0).
placeholder2 (int): Reserved field (default is 0).
"""

version: int
ip: str
port: int
Expand Down Expand Up @@ -78,7 +89,7 @@ def __repr__(self):
return self.__str__()

def to_string(self) -> str:
"""Converts the AxonInfo object to a string representation using JSON."""
"""Converts the `AxonInfo` object to a string representation using JSON."""
try:
return json.dumps(asdict(self))
except (TypeError, ValueError) as e:
Expand All @@ -88,13 +99,13 @@ def to_string(self) -> str:
@classmethod
def from_string(cls, json_string: str) -> "AxonInfo":
"""
Creates an AxonInfo object from its string representation using JSON.
Creates an `AxonInfo` object from its string representation using JSON.
Args:
json_string (str): The JSON string representation of the AxonInfo object.
Returns:
AxonInfo: An instance of AxonInfo created from the JSON string. If decoding fails, returns a default AxonInfo object with default values.
AxonInfo: An instance of AxonInfo created from the JSON string. If decoding fails, returns a default `AxonInfo` object with default values.
Raises:
json.JSONDecodeError: If there is an error in decoding the JSON string.
Expand All @@ -115,7 +126,7 @@ def from_string(cls, json_string: str) -> "AxonInfo":
@classmethod
def from_neuron_info(cls, neuron_info: dict) -> "AxonInfo":
"""
Converts a dictionary to an AxonInfo object.
Converts a dictionary to an `AxonInfo` object.
Args:
neuron_info (dict): A dictionary containing the neuron information.
Expand Down
22 changes: 11 additions & 11 deletions bittensor/core/chain_data/delegate_info.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from dataclasses import dataclass
from typing import List, Tuple, Optional, Any
from typing import Optional, Any

from scalecodec.utils.ss58 import ss58_encode

Expand All @@ -12,12 +12,12 @@
@dataclass
class DelegateInfo:
"""
Dataclass for delegate information. For a lighter version of this class, see :func:`DelegateInfoLite`.
Dataclass for delegate information. For a lighter version of this class, see ``DelegateInfoLite``.
Args:
hotkey_ss58 (str): Hotkey of the delegate for which the information is being fetched.
total_stake (int): Total stake of the delegate.
nominators (list[Tuple[str, int]]): List of nominators of the delegate and their stake.
nominators (list[tuple[str, int]]): List of nominators of the delegate and their stake.
take (float): Take of the delegate as a percentage.
owner_ss58 (str): Coldkey of the owner.
registrations (list[int]): List of subnets that the delegate is registered on.
Expand All @@ -29,15 +29,15 @@ class DelegateInfo:

hotkey_ss58: str # Hotkey of delegate
total_stake: Balance # Total stake of the delegate
nominators: List[
Tuple[str, Balance]
nominators: list[
tuple[str, Balance]
] # List of nominators of the delegate and their stake
owner_ss58: str # Coldkey of owner
take: float # Take of the delegate as a percentage
validator_permits: List[
validator_permits: list[
int
] # List of subnets that the delegate is allowed to validate on
registrations: List[int] # List of subnets that the delegate is registered on
registrations: tuple[int] # List of subnets that the delegate is registered on
return_per_1000: Balance # Return per 1000 tao of the delegate over a day
total_daily_return: Balance # Total daily return of the delegate

Expand Down Expand Up @@ -66,7 +66,7 @@ def fix_decoded_values(cls, decoded: Any) -> "DelegateInfo":
)

@classmethod
def from_vec_u8(cls, vec_u8: List[int]) -> Optional["DelegateInfo"]:
def from_vec_u8(cls, vec_u8: list[int]) -> Optional["DelegateInfo"]:
"""Returns a DelegateInfo object from a ``vec_u8``."""
if len(vec_u8) == 0:
return None
Expand All @@ -78,7 +78,7 @@ def from_vec_u8(cls, vec_u8: List[int]) -> Optional["DelegateInfo"]:
return DelegateInfo.fix_decoded_values(decoded)

@classmethod
def list_from_vec_u8(cls, vec_u8: List[int]) -> List["DelegateInfo"]:
def list_from_vec_u8(cls, vec_u8: list[int]) -> list["DelegateInfo"]:
"""Returns a list of DelegateInfo objects from a ``vec_u8``."""
decoded = from_scale_encoding(vec_u8, ChainDataType.DelegateInfo, is_vec=True)

Expand All @@ -89,8 +89,8 @@ def list_from_vec_u8(cls, vec_u8: List[int]) -> List["DelegateInfo"]:

@classmethod
def delegated_list_from_vec_u8(
cls, vec_u8: List[int]
) -> List[Tuple["DelegateInfo", "Balance"]]:
cls, vec_u8: list[int]
) -> list[tuple["DelegateInfo", "Balance"]]:
"""Returns a list of Tuples of DelegateInfo objects, and Balance, from a ``vec_u8``.
This is the list of delegates that the user has delegated to, and the amount of stake delegated.
Expand Down
7 changes: 3 additions & 4 deletions bittensor/core/chain_data/delegate_info_lite.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
from dataclasses import dataclass
from typing import List


@dataclass
class DelegateInfoLite:
"""
Dataclass for DelegateLiteInfo. This is a lighter version of :func:`DelegateInfo`.
Dataclass for `DelegateLiteInfo`. This is a lighter version of :func:``DelegateInfo``.
Args:
delegate_ss58 (str): Hotkey of the delegate for which the information is being fetched.
Expand All @@ -22,8 +21,8 @@ class DelegateInfoLite:
take: float # Take of the delegate as a percentage
nominators: int # Count of the nominators of the delegate.
owner_ss58: str # Coldkey of owner
registrations: List[int] # List of subnets that the delegate is registered on
validator_permits: List[
registrations: list[int] # List of subnets that the delegate is registered on
validator_permits: list[
int
] # List of subnets that the delegate is allowed to validate on
return_per_1000: int # Return per 1000 tao for the delegate over a day
Expand Down
19 changes: 13 additions & 6 deletions bittensor/core/chain_data/ip_info.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from dataclasses import dataclass
from typing import List, Dict, Optional, Any, Union
from typing import Optional, Any, Union

from bittensor.core.chain_data.utils import from_scale_encoding, ChainDataType
from bittensor.utils import networking as net
Expand All @@ -8,13 +8,20 @@

@dataclass
class IPInfo:
"""Dataclass for associated IP Info."""
"""
Dataclass representing IP information.
Attributes:
ip (str): The IP address as a string.
ip_type (int): The type of the IP address (e.g., IPv4, IPv6).
protocol (int): The protocol associated with the IP (e.g., TCP, UDP).
"""

ip: str
ip_type: int
protocol: int

def encode(self) -> Dict[str, Any]:
def encode(self) -> dict[str, Any]:
"""Returns a dictionary of the IPInfo object that can be encoded."""
return {
"ip": net.ip_to_int(
Expand All @@ -24,7 +31,7 @@ def encode(self) -> Dict[str, Any]:
}

@classmethod
def from_vec_u8(cls, vec_u8: List[int]) -> Optional["IPInfo"]:
def from_vec_u8(cls, vec_u8: list[int]) -> Optional["IPInfo"]:
"""Returns a IPInfo object from a ``vec_u8``."""
if len(vec_u8) == 0:
return None
Expand All @@ -36,7 +43,7 @@ def from_vec_u8(cls, vec_u8: List[int]) -> Optional["IPInfo"]:
return IPInfo.fix_decoded_values(decoded)

@classmethod
def list_from_vec_u8(cls, vec_u8: List[int]) -> List["IPInfo"]:
def list_from_vec_u8(cls, vec_u8: list[int]) -> list["IPInfo"]:
"""Returns a list of IPInfo objects from a ``vec_u8``."""
decoded = from_scale_encoding(vec_u8, ChainDataType.IPInfo, is_vec=True)

Expand All @@ -46,7 +53,7 @@ def list_from_vec_u8(cls, vec_u8: List[int]) -> List["IPInfo"]:
return [IPInfo.fix_decoded_values(d) for d in decoded]

@classmethod
def fix_decoded_values(cls, decoded: Dict) -> "IPInfo":
def fix_decoded_values(cls, decoded: dict) -> "IPInfo":
"""Returns a SubnetInfo object from a decoded IPInfo dictionary."""
return IPInfo(
ip=net.int_to_ip(decoded["ip"]),
Expand Down
50 changes: 45 additions & 5 deletions bittensor/core/chain_data/neuron_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,50 @@
from bittensor.utils import u16_normalized_float
from bittensor.utils.balance import Balance

# for annotation purposes
if TYPE_CHECKING:
from bittensor.core.chain_data.neuron_info_lite import NeuronInfoLite


@dataclass
class NeuronInfo:
"""Dataclass for neuron metadata."""
"""Represents the metadata of a neuron including keys, UID, stake, rankings, and other attributes.
Attributes:
hotkey (str): The hotkey associated with the neuron.
coldkey (str): The coldkey associated with the neuron.
uid (int): The unique identifier for the neuron.
netuid (int): The network unique identifier for the neuron.
active (int): The active status of the neuron.
stake (Balance): The balance staked to this neuron.
stake_dict (dict[str, Balance]): A dictionary mapping coldkey to the amount staked.
total_stake (Balance): The total amount of stake.
rank (float): The rank score of the neuron.
emission (float): The emission rate.
incentive (float): The incentive value.
consensus (float): The consensus score.
trust (float): The trust score.
validator_trust (float): The validation trust score.
dividends (float): The dividends value.
last_update (int): The timestamp of the last update.
validator_permit (bool): Validator permit status.
weights (list[list[int]]): List of weights associated with the neuron.
bonds (list[list[int]]): List of bonds associated with the neuron.
pruning_score (int): The pruning score of the neuron.
prometheus_info (Optional[PrometheusInfo]): Information related to Prometheus.
axon_info (Optional[AxonInfo]): Information related to Axon.
is_null (bool): Indicator if this is a null neuron.
"""

hotkey: str
coldkey: str
uid: int
netuid: int
active: int
stake: Balance
stake: "Balance"
# mapping of coldkey to amount staked to this Neuron
stake_dict: dict[str, Balance]
total_stake: Balance
stake_dict: dict[str, "Balance"]
total_stake: "Balance"
rank: float
emission: float
incentive: float
Expand All @@ -40,7 +67,7 @@ class NeuronInfo:
bonds: list[list[int]]
pruning_score: int
prometheus_info: Optional["PrometheusInfo"] = None
axon_info: Optional[AxonInfo] = None
axon_info: Optional["AxonInfo"] = None
is_null: bool = False

@classmethod
Expand All @@ -50,6 +77,17 @@ def from_weights_bonds_and_neuron_lite(
weights_as_dict: dict[int, list[tuple[int, int]]],
bonds_as_dict: dict[int, list[tuple[int, int]]],
) -> "NeuronInfo":
"""
Creates an instance of NeuronInfo from NeuronInfoLite and dictionaries of weights and bonds.
Args:
neuron_lite (NeuronInfoLite): A lite version of the neuron containing basic attributes.
weights_as_dict (dict[int, list[tuple[int, int]]]): A dictionary where the key is the UID and the value is a list of weight tuples associated with the neuron.
bonds_as_dict (dict[int, list[tuple[int, int]]]): A dictionary where the key is the UID and the value is a list of bond tuples associated with the neuron.
Returns:
NeuronInfo: An instance of NeuronInfo populated with the provided weights and bonds.
"""
n_dict = neuron_lite.__dict__
n_dict["weights"] = weights_as_dict.get(neuron_lite.uid, [])
n_dict["bonds"] = bonds_as_dict.get(neuron_lite.uid, [])
Expand All @@ -58,6 +96,7 @@ def from_weights_bonds_and_neuron_lite(

@staticmethod
def get_null_neuron() -> "NeuronInfo":
"""Returns a null NeuronInfo instance."""
neuron = NeuronInfo(
uid=0,
netuid=0,
Expand Down Expand Up @@ -87,6 +126,7 @@ def get_null_neuron() -> "NeuronInfo":

@classmethod
def from_vec_u8(cls, vec_u8: bytes) -> "NeuronInfo":
"""Instantiates NeuronInfo from a byte vector."""
n = bt_decode.NeuronInfo.decode(bytes(vec_u8))
stake_dict = process_stake_data(n.stake)
total_stake = sum(stake_dict.values()) if stake_dict else Balance(0)
Expand Down
Loading

0 comments on commit 87a923d

Please sign in to comment.