INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Read MAC from OTP ROM
def read_mac(self): """ Read MAC from OTP ROM """ mac0 = self.read_reg(self.ESP_OTP_MAC0) mac1 = self.read_reg(self.ESP_OTP_MAC1) mac3 = self.read_reg(self.ESP_OTP_MAC3) if (mac3 != 0): oui = ((mac3 >> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff) elif ((mac1 >...
Calculate an erase size given a specific size in bytes. Provides a workaround for the bootloader erase bug.
def get_erase_size(self, offset, size): """ Calculate an erase size given a specific size in bytes. Provides a workaround for the bootloader erase bug.""" sectors_per_block = 16 sector_size = self.FLASH_SECTOR_SIZE num_sectors = (size + sector_size - 1) // sector_size s...
Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1 this bit is at position 16 in EFUSE_BLK0_RDATA0_REG
def is_flash_encryption_key_valid(self): """ Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1 this bit is at position 16 in EFUSE_BLK0_RDATA0_REG """ word0 = self.read_efuse(0) rd_disable = (word0 >> 16) & 0x1 # reading of BLOCK1 is NOT ALLOWED so we assume valid key is progr...
bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config this bit is at position 19 in EFUSE_BLK0_RDATA0_REG
def get_flash_crypt_config(self): """ bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config this bit is at position 19 in EFUSE_BLK0_RDATA0_REG """ word0 = self.read_efuse(0) rd_disable = (word0 >> 19) & 0x1 if rd_disable == 0: """ we can read the flash_cryp...
Read MAC from EFUSE region
def read_mac(self): """ Read MAC from EFUSE region """ words = [self.read_efuse(2), self.read_efuse(1)] bitstring = struct.pack(">II", *words) bitstring = bitstring[2:8] # trim the 2 byte CRC try: return tuple(ord(b) for b in bitstring) except TypeError: # P...
Return a new ImageSegment which splits "split_len" bytes from the beginning of the data. Remaining bytes are kept in this segment object (and the start address is adjusted to match.)
def split_image(self, split_len): """ Return a new ImageSegment which splits "split_len" bytes from the beginning of the data. Remaining bytes are kept in this segment object (and the start address is adjusted to match.) """ result = copy.copy(self) result.data = self.data[:split...
Load the next segment from the image file
def load_segment(self, f, is_irom_segment=False): """ Load the next segment from the image file """ file_offs = f.tell() (offset, size) = struct.unpack('<II', f.read(8)) self.warn_if_unusual_segment(offset, size, is_irom_segment) segment_data = f.read(size) if len(segment...
Save the next segment to the image file, return next checksum value if provided
def save_segment(self, f, segment, checksum=None): """ Save the next segment to the image file, return next checksum value if provided """ segment_data = self.maybe_patch_segment_data(f, segment.data) f.write(struct.pack('<II', segment.addr, len(segment_data))) f.write(segment_data) ...
If SHA256 digest of the ELF file needs to be inserted into this segment, do so. Returns segment data.
def maybe_patch_segment_data(self, f, segment_data): """If SHA256 digest of the ELF file needs to be inserted into this segment, do so. Returns segment data.""" segment_len = len(segment_data) file_pos = f.tell() # file_pos is position in the .bin file if self.elf_sha256_offset >= file_...
Calculate checksum of loaded image, based on segments in segment array.
def calculate_checksum(self): """ Calculate checksum of loaded image, based on segments in segment array. """ checksum = ESPLoader.ESP_CHECKSUM_MAGIC for seg in self.segments: if seg.include_in_checksum: checksum = ESPLoader.checksum(seg.data, checksum...
Append ESPLoader checksum to the just-written image
def append_checksum(self, f, checksum): """ Append ESPLoader checksum to the just-written image """ align_file_position(f, 16) f.write(struct.pack(b'B', checksum))
Save a set of V1 images for flashing. Parameter is a base filename.
def save(self, basename): """ Save a set of V1 images for flashing. Parameter is a base filename. """ # IROM data goes in its own plain binary file irom_segment = self.get_irom_segment() if irom_segment is not None: with open("%s0x%05x.bin" % (basename, irom_segment.addr - ES...
Derive a default output name from the ELF name.
def default_output_name(self, input_file): """ Derive a default output name from the ELF name. """ irom_segment = self.get_irom_segment() if irom_segment is not None: irom_offs = irom_segment.addr - ESP8266ROM.IROM_MAP_START else: irom_offs = 0 return "%s-...
Save the next segment to the image file, return next checksum value if provided
def save_flash_segment(self, f, segment, checksum=None): """ Save the next segment to the image file, return next checksum value if provided """ segment_end_pos = f.tell() + len(segment.data) + self.SEG_HEADER_LEN segment_len_remainder = segment_end_pos % self.IROM_ALIGN if segment_len_r...
Calculates 'k' from data itself, removing the need for strong random generator and producing deterministic (reproducible) signatures. See RFC 6979 for more details.
def sign_digest_deterministic(self, digest, hashfunc=None, sigencode=sigencode_string): """ Calculates 'k' from data itself, removing the need for strong random generator and producing deterministic (reproducible) signatures. See RFC 6979 for more details. """ secexp = se...
hashfunc= should behave like hashlib.sha1 . The output length of the hash (in bytes) must not be longer than the length of the curve order (rounded up to the nearest byte), so using SHA256 with nist256p is ok, but SHA256 with nist192p is not. (In the 2**-96ish unlikely event of a hash ou...
def sign(self, data, entropy=None, hashfunc=None, sigencode=sigencode_string, k=None): """ hashfunc= should behave like hashlib.sha1 . The output length of the hash (in bytes) must not be longer than the length of the curve order (rounded up to the nearest byte), so using SHA256 with nis...
Wrap an ELF file into a stub 'dict'
def wrap_stub(elf_file): """ Wrap an ELF file into a stub 'dict' """ print('Wrapping ELF file %s...' % elf_file) e = esptool.ELFFile(elf_file) text_section = e.get_section('.text') try: data_section = e.get_section('.data') except ValueError: data_section = None stub = { ...
order - order of the DSA generator used in the signature secexp - secure exponent (private key) in numeric form hash_func - reference to the same hash function used for generating hash data - hash in binary form of the signing data
def generate_k(order, secexp, hash_func, data): ''' order - order of the DSA generator used in the signature secexp - secure exponent (private key) in numeric form hash_func - reference to the same hash function used for generating hash data - hash in binary form of the signing data ...
Returns an iterator over 'chunk_len' chunks of 'source'
def get_chunks(source, chunk_len): """ Returns an iterator over 'chunk_len' chunks of 'source' """ return (source[i: i + chunk_len] for i in range(0, len(source), chunk_len))
Endian-swap each word in 'source' bitstring
def endian_swap_words(source): """ Endian-swap each word in 'source' bitstring """ assert len(source) % 4 == 0 words = "I" * (len(source) // 4) return struct.pack("<" + words, *struct.unpack(">" + words, source))
Swap the order of the words in 'source' bitstring
def swap_word_order(source): """ Swap the order of the words in 'source' bitstring """ assert len(source) % 4 == 0 words = "I" * (len(source) // 4) return struct.pack(words, *reversed(struct.unpack(words, source)))
Load a 256-bit key, similar to stored in efuse, from a file 192-bit keys will be extended to 256-bit using the same algorithm used by hardware if 3/4 Coding Scheme is set.
def _load_hardware_key(keyfile): """ Load a 256-bit key, similar to stored in efuse, from a file 192-bit keys will be extended to 256-bit using the same algorithm used by hardware if 3/4 Coding Scheme is set. """ key = keyfile.read() if len(key) not in [24, 32]: raise esptool.FatalError...
Calculate the digest of a bootloader image, in the same way the hardware secure boot engine would do so. Can be used with a pre-loaded key to update a secure bootloader.
def digest_secure_bootloader(args): """ Calculate the digest of a bootloader image, in the same way the hardware secure boot engine would do so. Can be used with a pre-loaded key to update a secure bootloader. """ if args.iv is not None: print("WARNING: --iv argument is for TESTING PURPOSES ONLY...
Sign a data file with a ECDSA private key, append binary signature to file contents
def sign_data(args): """ Sign a data file with a ECDSA private key, append binary signature to file contents """ sk = _load_ecdsa_signing_key(args) # calculate signature of binary data binary_content = args.datafile.read() signature = sk.sign_deterministic(binary_content, hashlib.sha256) # bac...
Generate an ECDSA signing key for signing secure boot images (post-bootloader)
def generate_signing_key(args): """ Generate an ECDSA signing key for signing secure boot images (post-bootloader) """ if os.path.exists(args.keyfile): raise esptool.FatalError("ERROR: Key file %s already exists" % args.keyfile) sk = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p) with open(args...
Verify a previously signed binary image, using the ECDSA public key
def verify_signature(args): """ Verify a previously signed binary image, using the ECDSA public key """ key_data = args.keyfile.read() if b"-BEGIN EC PRIVATE KEY" in key_data: sk = ecdsa.SigningKey.from_pem(key_data) vk = sk.get_verifying_key() elif b"-BEGIN PUBLIC KEY" in key_data: ...
Load an ECDSA private key and extract the embedded public key as raw binary data.
def extract_public_key(args): """ Load an ECDSA private key and extract the embedded public key as raw binary data. """ sk = _load_ecdsa_signing_key(args) vk = sk.get_verifying_key() args.public_keyfile.write(vk.to_string()) print("%s public key extracted to %s" % (args.keyfile.name, args.public_key...
Return a list of the bit indexes that the "key tweak" applies to, as determined by the FLASH_CRYPT_CONFIG 4 bit efuse value.
def _flash_encryption_tweak_range(flash_crypt_config=0xF): """ Return a list of the bit indexes that the "key tweak" applies to, as determined by the FLASH_CRYPT_CONFIG 4 bit efuse value. """ tweak_range = [] if (flash_crypt_config & 1) != 0: tweak_range += range(67) if (flash_crypt_conf...
Apply XOR "tweak" values to the key, derived from flash offset 'offset'. This matches the ESP32 hardware flash encryption. tweak_range is a list of bit indexes to apply the tweak to, as generated by _flash_encryption_tweak_range() from the FLASH_CRYPT_CONFIG efuse value. Return tweaked key
def _flash_encryption_tweak_key(key, offset, tweak_range): """Apply XOR "tweak" values to the key, derived from flash offset 'offset'. This matches the ESP32 hardware flash encryption. tweak_range is a list of bit indexes to apply the tweak to, as generated by _flash_encryption_tweak_range() from the ...
Convert integer x into a string of bytes, as per X9.62.
def int_to_string( x ): """Convert integer x into a string of bytes, as per X9.62.""" assert x >= 0 if x == 0: return b('\0') result = [] while x: ordinal = x & 0xFF result.append(int2byte(ordinal)) x >>= 8 result.reverse() return b('').join(result)
Convert a string of bytes into an integer, as per X9.62.
def string_to_int( s ): """Convert a string of bytes into an integer, as per X9.62.""" result = 0 for c in s: if not isinstance(c, int): c = ord( c ) result = 256 * result + c return result
Is (x,y) a valid public key based on the specified generator?
def point_is_valid( generator, x, y ): """Is (x,y) a valid public key based on the specified generator?""" # These are the tests specified in X9.62. n = generator.order() curve = generator.curve() if x < 0 or n <= x or y < 0 or n <= y: return False if not curve.contains_point( x, y ): return False...
Verify that signature is a valid signature of hash. Return True if the signature is valid.
def verifies( self, hash, signature ): """Verify that signature is a valid signature of hash. Return True if the signature is valid. """ # From X9.62 J.3.1. G = self.generator n = G.order() r = signature.r s = signature.s if r < 1 or r > n-1: return False if s < 1 or s > n-1: r...
Return a signature for the provided hash, using the provided random nonce. It is absolutely vital that random_k be an unpredictable number in the range [1, self.public_key.point.order()-1]. If an attacker can guess random_k, he can compute our private key from a single signature. Also, if an attacker...
def sign( self, hash, random_k ): """Return a signature for the provided hash, using the provided random nonce. It is absolutely vital that random_k be an unpredictable number in the range [1, self.public_key.point.order()-1]. If an attacker can guess random_k, he can compute our private key from a ...
Raise base to exponent, reducing by modulus
def modular_exp( base, exponent, modulus ): "Raise base to exponent, reducing by modulus" if exponent < 0: raise NegativeExponentError( "Negative exponents (%d) not allowed" \ % exponent ) return pow( base, exponent, modulus )
Reduce poly by polymod, integer arithmetic modulo p. Polynomials are represented as lists of coefficients of increasing powers of x.
def polynomial_reduce_mod( poly, polymod, p ): """Reduce poly by polymod, integer arithmetic modulo p. Polynomials are represented as lists of coefficients of increasing powers of x.""" # This module has been tested only by extensive use # in calculating modular square roots. # Just to make this easy, re...
Polynomial multiplication modulo a polynomial over ints mod p. Polynomials are represented as lists of coefficients of increasing powers of x.
def polynomial_multiply_mod( m1, m2, polymod, p ): """Polynomial multiplication modulo a polynomial over ints mod p. Polynomials are represented as lists of coefficients of increasing powers of x.""" # This is just a seat-of-the-pants implementation. # This module has been tested only by extensive use # ...
Polynomial exponentiation modulo a polynomial over ints mod p. Polynomials are represented as lists of coefficients of increasing powers of x.
def polynomial_exp_mod( base, exponent, polymod, p ): """Polynomial exponentiation modulo a polynomial over ints mod p. Polynomials are represented as lists of coefficients of increasing powers of x.""" # Based on the Handbook of Applied Cryptography, algorithm 2.227. # This module has been tested only by ...
Jacobi symbol
def jacobi( a, n ): """Jacobi symbol""" # Based on the Handbook of Applied Cryptography (HAC), algorithm 2.149. # This function has been tested by comparison with a small # table printed in HAC, and by extensive use in calculating # modular square roots. assert n >= 3 assert n%2 == 1 a = a % n if a...
Modular square root of a, mod p, p prime.
def square_root_mod_prime( a, p ): """Modular square root of a, mod p, p prime.""" # Based on the Handbook of Applied Cryptography, algorithms 3.34 to 3.39. # This module has been tested for all values in [0,p-1] for # every prime p from 3 to 1229. assert 0 <= a < p assert 1 < p if a == 0: return 0 ...
Inverse of a mod m.
def inverse_mod( a, m ): """Inverse of a mod m.""" if a < 0 or m <= a: a = a % m # From Ferguson and Schneier, roughly: c, d = a, m uc, vc, ud, vd = 1, 0, 0, 1 while c != 0: q, c, d = divmod( d, c ) + ( c, ) uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc # At this point, d is the GCD, and ud*a+...
Greatest common divisor using Euclid's algorithm.
def gcd2(a, b): """Greatest common divisor using Euclid's algorithm.""" while a: a, b = b%a, a return b
Greatest common divisor. Usage: gcd( [ 2, 4, 6 ] ) or: gcd( 2, 4, 6 )
def gcd( *a ): """Greatest common divisor. Usage: gcd( [ 2, 4, 6 ] ) or: gcd( 2, 4, 6 ) """ if len( a ) > 1: return reduce( gcd2, a ) if hasattr( a[0], "__iter__" ): return reduce( gcd2, a[0] ) return a[0]
Least common multiple. Usage: lcm( [ 3, 4, 5 ] ) or: lcm( 3, 4, 5 )
def lcm( *a ): """Least common multiple. Usage: lcm( [ 3, 4, 5 ] ) or: lcm( 3, 4, 5 ) """ if len( a ) > 1: return reduce( lcm2, a ) if hasattr( a[0], "__iter__" ): return reduce( lcm2, a[0] ) return a[0]
Decompose n into a list of (prime,exponent) pairs.
def factorization( n ): """Decompose n into a list of (prime,exponent) pairs.""" assert isinstance( n, integer_types ) if n < 2: return [] result = [] d = 2 # Test the small primes: for d in smallprimes: if d > n: break q, r = divmod( n, d ) if r == 0: count = 1 while d <= n: ...
Return the Carmichael function of a number that is represented as a list of (prime,exponent) pairs.
def carmichael_of_factorized( f_list ): """Return the Carmichael function of a number that is represented as a list of (prime,exponent) pairs. """ if len( f_list ) < 1: return 1 result = carmichael_of_ppower( f_list[0] ) for i in range( 1, len( f_list ) ): result = lcm( result, carmichael_of_ppower( f...
Return the Euler totient function of n.
def phi( n ): """Return the Euler totient function of n.""" assert isinstance( n, integer_types ) if n < 3: return 1 result = 1 ff = factorization( n ) for f in ff: e = f[1] if e > 1: result = result * f[0] ** (e-1) * ( f[0] - 1 ) else: result = result * ( f[0] - 1 ) return resu...
Return the order of x in the multiplicative group mod m.
def order_mod( x, m ): """Return the order of x in the multiplicative group mod m. """ # Warning: this implementation is not very clever, and will # take a long time if m is very large. if m <= 1: return 0 assert gcd( x, m ) == 1 z = x result = 1 while z != 1: z = ( z * x ) % m result = re...
Carmichael function of the given power of the given prime.
def carmichael_of_ppower( pp ): """Carmichael function of the given power of the given prime. """ p, a = pp if p == 2 and a > 2: return 2**(a-2) else: return (p-1) * p**(a-1)
Return the largest factor of a relatively prime to b.
def largest_factor_relatively_prime( a, b ): """Return the largest factor of a relatively prime to b. """ while 1: d = gcd( a, b ) if d <= 1: break b = d while 1: q, r = divmod( a, d ) if r > 0: break a = q return a
Return True if x is prime, False otherwise. We use the Miller-Rabin test, as given in Menezes et al. p. 138. This test is not exact: there are composite values n for which it returns True. In testing the odd numbers from 10000001 to 19999999, about 66 composites got past the first test, 5 got past the sec...
def is_prime( n ): """Return True if x is prime, False otherwise. We use the Miller-Rabin test, as given in Menezes et al. p. 138. This test is not exact: there are composite values n for which it returns True. In testing the odd numbers from 10000001 to 19999999, about 66 composites got past the first te...
Return the smallest prime larger than the starting value.
def next_prime( starting_value ): "Return the smallest prime larger than the starting value." if starting_value < 2: return 2 result = ( starting_value + 1 ) | 1 while not is_prime( result ): result = result + 2 return result
Uses feeder to read and convert from in_stream and write to out_stream.
def _feed_stream(feeder, in_stream, out_stream, block_size = BLOCK_SIZE): 'Uses feeder to read and convert from in_stream and write to out_stream.' while True: chunk = in_stream.read(block_size) if not chunk: break converted = feeder.feed(chunk) out_stream.write(conv...
Encrypts a stream of bytes from in_stream to out_stream using mode.
def encrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT): 'Encrypts a stream of bytes from in_stream to out_stream using mode.' encrypter = Encrypter(mode, padding = padding) _feed_stream(encrypter, in_stream, out_stream, block_size)
Decrypts a stream of bytes from in_stream to out_stream using mode.
def decrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT): 'Decrypts a stream of bytes from in_stream to out_stream using mode.' decrypter = Decrypter(mode, padding = padding) _feed_stream(decrypter, in_stream, out_stream, block_size)
Provide bytes to encrypt (or decrypt), returning any bytes possible from this or any previous calls to feed. Call with None or an empty string to flush the mode of operation and return any final bytes; no further calls to feed may be made.
def feed(self, data = None): '''Provide bytes to encrypt (or decrypt), returning any bytes possible from this or any previous calls to feed. Call with None or an empty string to flush the mode of operation and return any final bytes; no further calls to feed may be m...
Return a random integer k such that 1 <= k < order, uniformly distributed across that range. For simplicity, this only behaves well if 'order' is fairly close (but below) a power of 256. The try-try-again algorithm we use takes longer and longer time (on average) to complete as 'order' falls, rising to ...
def randrange(order, entropy=None): """Return a random integer k such that 1 <= k < order, uniformly distributed across that range. For simplicity, this only behaves well if 'order' is fairly close (but below) a power of 256. The try-try-again algorithm we use takes longer and longer time (on average) t...
Create AUTHORS file using git commits.
def generate_authors(git_dir): """Create AUTHORS file using git commits.""" authors = [] emails = [] git_log_cmd = ['git', 'log', '--format=%aN|%aE'] tmp_authors = _run_shell_command(git_log_cmd, git_dir).split('\n') for author_str in tmp_authors: author, email = author_str.split('|') ...
Initalizes root node of the tree, i.e depth = 0
def _initalize_tree(self, position, momentum, slice_var, stepsize): """ Initalizes root node of the tree, i.e depth = 0 """ position_bar, momentum_bar, _ = self.simulate_dynamics(self.model, position, momentum, stepsize, sel...
Returns a sample using a single iteration of NUTS
def _sample(self, position, stepsize): """ Returns a sample using a single iteration of NUTS """ # Re-sampling momentum momentum = np.random.normal(0, 1, len(position)) # Initializations depth = 0 position_backward, position_forward = position, position ...
Recursively builds a tree for proposing new position and momentum
def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize): """ Recursively builds a tree for proposing new position and momentum """ # Parameter names in algorithm (here -> representation in algorithm) # position -> theta, momentum -> r, slice_var -> u, di...
Returns a generator type object whose each iteration yields a sample Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, the starting state in markov chain. num_samples: int Number of samples to...
def generate_sample(self, initial_pos, num_samples, stepsize=None): """ Returns a generator type object whose each iteration yields a sample Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, the starting ...
Method to return samples using No U Turn Sampler Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, the starting state in markov chain. num_samples: int Number of samples to be generated ...
def sample(self, initial_pos, num_samples, stepsize=None, return_type='dataframe'): """ Method to return samples using No U Turn Sampler Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, the starting ...
Recursively builds a tree for proposing new position and momentum
def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize, position0, momentum0): """ Recursively builds a tree for proposing new position and momentum """ if depth == 0: position_bar, momentum_bar, candidate_set_size, accept_set_bool =\ ...
Returns samples using No U Turn Sampler with dual averaging Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, the starting state in markov chain. num_adapt: int The number of interations to ru...
def sample(self, initial_pos, num_adapt, num_samples, stepsize=None, return_type='dataframe'): """ Returns samples using No U Turn Sampler with dual averaging Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, ...
Returns a generator type object whose each iteration yields a sample Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, the starting state in markov chain. num_adapt: int The number of interati...
def generate_sample(self, initial_pos, num_adapt, num_samples, stepsize=None): """ Returns a generator type object whose each iteration yields a sample Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, the sta...
Discretizes the continuous distribution into discrete probability masses using various methods. Parameters ---------- method : A Discretizer Class from pgmpy.discretize *args, **kwargs: The parameters to be given to the Discretizer Class. Returns --...
def discretize(self, method, *args, **kwargs): """ Discretizes the continuous distribution into discrete probability masses using various methods. Parameters ---------- method : A Discretizer Class from pgmpy.discretize *args, **kwargs: The parameter...
Reduces the factor to the context of the given variable values. Parameters ---------- values: list, array-like A list of tuples of the form (variable_name, variable_value). inplace: boolean If inplace=True it will modify the factor itself, else would return ...
def reduce(self, values, inplace=True): """ Reduces the factor to the context of the given variable values. Parameters ---------- values: list, array-like A list of tuples of the form (variable_name, variable_value). inplace: boolean If inplace=T...
Marginalize the factor with respect to the given variables. Parameters ---------- variables: list, array-like List of variables with respect to which factor is to be maximized. inplace: boolean If inplace=True it will modify the factor itself, else would return ...
def marginalize(self, variables, inplace=True): """ Marginalize the factor with respect to the given variables. Parameters ---------- variables: list, array-like List of variables with respect to which factor is to be maximized. inplace: boolean ...
Normalizes the pdf of the continuous factor so that it integrates to 1 over all the variables. Parameters ---------- inplace: boolean If inplace=True it will modify the factor itself, else would return a new factor. Returns ------- Contin...
def normalize(self, inplace=True): """ Normalizes the pdf of the continuous factor so that it integrates to 1 over all the variables. Parameters ---------- inplace: boolean If inplace=True it will modify the factor itself, else would return a new ...
Gives the ContinuousFactor operation (product or divide) with the other factor. Parameters ---------- other: ContinuousFactor The ContinuousFactor to be multiplied. operation: String 'product' for multiplication operation and 'divide' for div...
def _operate(self, other, operation, inplace=True): """ Gives the ContinuousFactor operation (product or divide) with the other factor. Parameters ---------- other: ContinuousFactor The ContinuousFactor to be multiplied. operation: String ...
Gives the ContinuousFactor divide with the other factor. Parameters ---------- other: ContinuousFactor The ContinuousFactor to be divided. Returns ------- ContinuousFactor or None: if inplace=True (default) returns None ...
def divide(self, other, inplace=True): """ Gives the ContinuousFactor divide with the other factor. Parameters ---------- other: ContinuousFactor The ContinuousFactor to be divided. Returns ------- ContinuousFactor or None: ...
Returns factor product over `args`. Parameters ---------- args: `BaseFactor` instances. factors to be multiplied Returns ------- BaseFactor: `BaseFactor` representing factor product over all the `BaseFactor` instances in args. Examples -------- >>> from pgmpy.factors.discr...
def factor_product(*args): """ Returns factor product over `args`. Parameters ---------- args: `BaseFactor` instances. factors to be multiplied Returns ------- BaseFactor: `BaseFactor` representing factor product over all the `BaseFactor` instances in args. Examples --...
Returns `DiscreteFactor` representing `phi1 / phi2`. Parameters ---------- phi1: Factor The Dividend. phi2: Factor The Divisor. Returns ------- DiscreteFactor: `DiscreteFactor` representing factor division `phi1 / phi2`. Examples -------- >>> from pgmpy.factor...
def factor_divide(phi1, phi2): """ Returns `DiscreteFactor` representing `phi1 / phi2`. Parameters ---------- phi1: Factor The Dividend. phi2: Factor The Divisor. Returns ------- DiscreteFactor: `DiscreteFactor` representing factor division `phi1 / phi2`. Exam...
Method to estimate the model parameters (CPDs). Parameters ---------- prior_type: 'dirichlet', 'BDeu', or 'K2' string indicting which type of prior to use for the model parameters. - If 'prior_type' is 'dirichlet', the following must be provided: 'pseudo_...
def get_parameters(self, prior_type='BDeu', equivalent_sample_size=5, pseudo_counts=None): """ Method to estimate the model parameters (CPDs). Parameters ---------- prior_type: 'dirichlet', 'BDeu', or 'K2' string indicting which type of prior to use for the model par...
Method to estimate the CPD for a given variable. Parameters ---------- node: int, string (any hashable python object) The name of the variable for which the CPD is to be estimated. prior_type: 'dirichlet', 'BDeu', 'K2', string indicting which type of prior to us...
def estimate_cpd(self, node, prior_type='BDeu', pseudo_counts=[], equivalent_sample_size=5): """ Method to estimate the CPD for a given variable. Parameters ---------- node: int, string (any hashable python object) The name of the variable for which the CPD is to be ...
Generates sample(s) from joint distribution of the bayesian network. Parameters ---------- size: int size of sample to be generated return_type: string (dataframe | recarray) Return type for samples, either of 'dataframe' or 'recarray'. Defaults to '...
def forward_sample(self, size=1, return_type='dataframe'): """ Generates sample(s) from joint distribution of the bayesian network. Parameters ---------- size: int size of sample to be generated return_type: string (dataframe | recarray) Return t...
Generates sample(s) from joint distribution of the bayesian network, given the evidence. Parameters ---------- evidence: list of `pgmpy.factor.State` namedtuples None if no evidence size: int size of sample to be generated return_type: string (dat...
def rejection_sample(self, evidence=None, size=1, return_type="dataframe"): """ Generates sample(s) from joint distribution of the bayesian network, given the evidence. Parameters ---------- evidence: list of `pgmpy.factor.State` namedtuples None if no eviden...
Generates weighted sample(s) from joint distribution of the bayesian network, that comply with the given evidence. 'Probabilistic Graphical Model Principles and Techniques', Koller and Friedman, Algorithm 12.2 pp 493. Parameters ---------- evidence: list of `pgmpy.factor...
def likelihood_weighted_sample(self, evidence=None, size=1, return_type="dataframe"): """ Generates weighted sample(s) from joint distribution of the bayesian network, that comply with the given evidence. 'Probabilistic Graphical Model Principles and Techniques', Koller and Fried...
Computes the Gibbs transition models from a Markov Network. 'Probabilistic Graphical Model Principles and Techniques', Koller and Friedman, Section 12.3.3 pp 512-513. Parameters: ----------- model: MarkovModel The model from which probabilities will be computed.
def _get_kernel_from_markov_model(self, model): """ Computes the Gibbs transition models from a Markov Network. 'Probabilistic Graphical Model Principles and Techniques', Koller and Friedman, Section 12.3.3 pp 512-513. Parameters: ----------- model: MarkovModel ...
Computes the Gibbs transition models from a Bayesian Network. 'Probabilistic Graphical Model Principles and Techniques', Koller and Friedman, Section 12.3.3 pp 512-513. Parameters: ----------- model: BayesianModel The model from which probabilities will be computed.
def _get_kernel_from_bayesian_model(self, model): """ Computes the Gibbs transition models from a Bayesian Network. 'Probabilistic Graphical Model Principles and Techniques', Koller and Friedman, Section 12.3.3 pp 512-513. Parameters: ----------- model: BayesianM...
Generator version of self.sample Return Type: ------------ List of State namedtuples, representing the assignment to all variables of the model. Examples: --------- >>> from pgmpy.factors.discrete import DiscreteFactor >>> from pgmpy.sampling import GibbsSamplin...
def generate_sample(self, start_state=None, size=1): """ Generator version of self.sample Return Type: ------------ List of State namedtuples, representing the assignment to all variables of the model. Examples: --------- >>> from pgmpy.factors.discrete ...
Sample from the Markov Chain. Parameters: ----------- start_state: dict or array-like iterable Representing the starting states of the variables. If None is passed, a random start_state is chosen. size: int Number of samples to be generated. return_type: ...
def sample(self, start_state=None, size=1, return_type="dataframe"): """ Sample from the Markov Chain. Parameters: ----------- start_state: dict or array-like iterable Representing the starting states of the variables. If None is passed, a random start_state is chose...
Return a list of states that the variable takes in the data
def _collect_state_names(self, variable): "Return a list of states that the variable takes in the data" states = sorted(list(self.data.ix[:, variable].dropna().unique())) return states
Return counts how often each state of 'variable' occured in the data. If the variable has parents, counting is done conditionally for each state configuration of the parents. Parameters ---------- variable: string Name of the variable for which the state count is to ...
def state_counts(self, variable, **kwargs): """ Return counts how often each state of 'variable' occured in the data. If the variable has parents, counting is done conditionally for each state configuration of the parents. Parameters ---------- variable: string ...
Add a single node to the cluster graph. Parameters ---------- node: node A node should be a collection of nodes forming a clique. It can be a list, set or tuple of nodes Examples -------- >>> from pgmpy.models import ClusterGraph >>> G = ...
def add_node(self, node, **kwargs): """ Add a single node to the cluster graph. Parameters ---------- node: node A node should be a collection of nodes forming a clique. It can be a list, set or tuple of nodes Examples -------- >>...
Add multiple nodes to the cluster graph. Parameters ---------- nodes: iterable container A container of nodes (list, dict, set, etc.). Examples -------- >>> from pgmpy.models import ClusterGraph >>> G = ClusterGraph() >>> G.add_nodes_from([('...
def add_nodes_from(self, nodes, **kwargs): """ Add multiple nodes to the cluster graph. Parameters ---------- nodes: iterable container A container of nodes (list, dict, set, etc.). Examples -------- >>> from pgmpy.models import ClusterGraph ...
Add an edge between two clique nodes. Parameters ---------- u, v: nodes Nodes can be any list or set or tuple of nodes forming a clique. Examples -------- >>> from pgmpy.models import ClusterGraph >>> G = ClusterGraph() >>> G.add_nodes_from([...
def add_edge(self, u, v, **kwargs): """ Add an edge between two clique nodes. Parameters ---------- u, v: nodes Nodes can be any list or set or tuple of nodes forming a clique. Examples -------- >>> from pgmpy.models import ClusterGraph ...
Associate a factor to the graph. See factors class for the order of potential values Parameters ---------- *factor: pgmpy.factors.factors object A factor object on any subset of the variables of the model which is to be associated with the model. Returns...
def add_factors(self, *factors): """ Associate a factor to the graph. See factors class for the order of potential values Parameters ---------- *factor: pgmpy.factors.factors object A factor object on any subset of the variables of the model which ...
Returns the cardinality of the node Parameters ---------- node: any hashable python object (optional) The node whose cardinality we want. If node is not specified returns a dictionary with the given variable as keys and their respective cardinality as values....
def get_cardinality(self, node=None): """ Returns the cardinality of the node Parameters ---------- node: any hashable python object (optional) The node whose cardinality we want. If node is not specified returns a dictionary with the given variable as ke...
r""" Returns the partition function for a given undirected graph. A partition function is defined as .. math:: \sum_{X}(\prod_{i=1}^{m} \phi_i) where m is the number of factors present in the graph and X are all the random variables present. Examples -------- ...
def get_partition_function(self): r""" Returns the partition function for a given undirected graph. A partition function is defined as .. math:: \sum_{X}(\prod_{i=1}^{m} \phi_i) where m is the number of factors present in the graph and X are all the random variables pr...
Check the model for various errors. This method checks for the following errors. * Checks if factors are defined for all the cliques or not. * Check for running intersection property is not done explicitly over here as it done in the add_edges method. * Checks if cardinality i...
def check_model(self): """ Check the model for various errors. This method checks for the following errors. * Checks if factors are defined for all the cliques or not. * Check for running intersection property is not done explicitly over here as it done in the add_edge...
This is the message-update method. Parameters ---------- sending_cluster: The resulting messages are lambda_{c-->s} from the given cluster 'c' to all of its intersection_sets 's'. Here 's' are the elements of intersection_sets_for_cluster_c. Reference --...
def _update_message(self, sending_cluster): """ This is the message-update method. Parameters ---------- sending_cluster: The resulting messages are lambda_{c-->s} from the given cluster 'c' to all of its intersection_sets 's'. Here 's' are the elements ...
Finds the index of the maximum values for all the single node dual objectives. Reference: code presented by Sontag in 2012 here: http://cs.nyu.edu/~dsontag/code/README_v2.html
def _local_decode(self): """ Finds the index of the maximum values for all the single node dual objectives. Reference: code presented by Sontag in 2012 here: http://cs.nyu.edu/~dsontag/code/README_v2.html """ # The current assignment of the single node factors is stored ...
Finds all the triangles present in the given model Examples -------- >>> from pgmpy.models import MarkovModel >>> from pgmpy.factors.discrete import DiscreteFactor >>> from pgmpy.inference import Mplp >>> mm = MarkovModel() >>> mm.add_nodes_from(['x1', 'x2', 'x3'...
def find_triangles(self): """ Finds all the triangles present in the given model Examples -------- >>> from pgmpy.models import MarkovModel >>> from pgmpy.factors.discrete import DiscreteFactor >>> from pgmpy.inference import Mplp >>> mm = MarkovModel() ...
This method checks the integrality gap to ensure either: * we have found a near to exact solution or * stuck on a local minima. Parameters ---------- dual_threshold: double This sets the minimum width between the dual objective decrements. If the ...
def _is_converged(self, dual_threshold=None, integrality_gap_threshold=None): """ This method checks the integrality gap to ensure either: * we have found a near to exact solution or * stuck on a local minima. Parameters ---------- dual_threshold: double ...
From a set of variables forming a triangle in the model, we form the corresponding Clusters. These clusters are then appended to the code. Parameters ---------- triangle_list : list The list of variables forming the triangles to be updated. It is of the form of ...
def _update_triangles(self, triangles_list): """ From a set of variables forming a triangle in the model, we form the corresponding Clusters. These clusters are then appended to the code. Parameters ---------- triangle_list : list The list of vari...
Returns the score of each of the triplets found in the current model Parameters --------- triangles_list: list The list of variables forming the triangles to be updated. It is of the form of [['var_5', 'var_8', 'var_7'], ['var_4', 'var_5', 'var_7'...
def _get_triplet_scores(self, triangles_list): """ Returns the score of each of the triplets found in the current model Parameters --------- triangles_list: list The list of variables forming the triangles to be updated. It is of the form of ...
Updates messages until either Mplp converges or if doesn't converges; halts after no_iterations. Parameters -------- no_iterations: integer Number of maximum iterations that we want MPLP to run.
def _run_mplp(self, no_iterations): """ Updates messages until either Mplp converges or if doesn't converges; halts after no_iterations. Parameters -------- no_iterations: integer Number of maximum iterations that we want MPLP to run. """ ...
This method finds all the triplets that are eligible and adds them iteratively in the bunch of max_triplets Parameters ---------- max_iterations: integer Maximum number of times we tighten the relaxation later_iter: integer Number of maximum ...
def _tighten_triplet(self, max_iterations, later_iter, max_triplets, prolong): """ This method finds all the triplets that are eligible and adds them iteratively in the bunch of max_triplets Parameters ---------- max_iterations: integer Maximum number of ...