repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
python-diamond/Diamond | src/diamond/handler/sentry.py | SentryHandler.process | def process(self, metric):
"""
process a single metric
@type metric: diamond.metric.Metric
@param metric: metric to process
@rtype None
"""
for rule in self.rules:
rule.process(metric, self) | python | def process(self, metric):
"""
process a single metric
@type metric: diamond.metric.Metric
@param metric: metric to process
@rtype None
"""
for rule in self.rules:
rule.process(metric, self) | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"for",
"rule",
"in",
"self",
".",
"rules",
":",
"rule",
".",
"process",
"(",
"metric",
",",
"self",
")"
] | process a single metric
@type metric: diamond.metric.Metric
@param metric: metric to process
@rtype None | [
"process",
"a",
"single",
"metric"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/sentry.py#L349-L357 | train | 217,300 |
python-diamond/Diamond | src/collectors/network/network.py | NetworkCollector.collect | def collect(self):
"""
Collect network interface stats.
"""
# Initialize results
results = {}
if os.access(self.PROC, os.R_OK):
# Open File
file = open(self.PROC)
# Build Regular Expression
greed = ''
if str_to_bool(self.config['greedy']):
greed = '\S*'
exp = (('^(?:\s*)((?:%s)%s):(?:\s*)' +
'(?P<rx_bytes>\d+)(?:\s*)' +
'(?P<rx_packets>\w+)(?:\s*)' +
'(?P<rx_errors>\d+)(?:\s*)' +
'(?P<rx_drop>\d+)(?:\s*)' +
'(?P<rx_fifo>\d+)(?:\s*)' +
'(?P<rx_frame>\d+)(?:\s*)' +
'(?P<rx_compressed>\d+)(?:\s*)' +
'(?P<rx_multicast>\d+)(?:\s*)' +
'(?P<tx_bytes>\d+)(?:\s*)' +
'(?P<tx_packets>\w+)(?:\s*)' +
'(?P<tx_errors>\d+)(?:\s*)' +
'(?P<tx_drop>\d+)(?:\s*)' +
'(?P<tx_fifo>\d+)(?:\s*)' +
'(?P<tx_colls>\d+)(?:\s*)' +
'(?P<tx_carrier>\d+)(?:\s*)' +
'(?P<tx_compressed>\d+)(?:.*)$') %
(('|'.join(self.config['interfaces'])), greed))
reg = re.compile(exp)
# Match Interfaces
for line in file:
match = reg.match(line)
if match:
device = match.group(1)
results[device] = match.groupdict()
# Close File
file.close()
else:
if not psutil:
self.log.error('Unable to import psutil')
self.log.error('No network metrics retrieved')
return None
network_stats = psutil.network_io_counters(True)
for device in network_stats.keys():
network_stat = network_stats[device]
results[device] = {}
results[device]['rx_bytes'] = network_stat.bytes_recv
results[device]['tx_bytes'] = network_stat.bytes_sent
results[device]['rx_packets'] = network_stat.packets_recv
results[device]['tx_packets'] = network_stat.packets_sent
for device in results:
stats = results[device]
for s, v in stats.items():
# Get Metric Name
metric_name = '.'.join([device, s])
# Get Metric Value
metric_value = self.derivative(metric_name,
long(v),
diamond.collector.MAX_COUNTER)
# Convert rx_bytes and tx_bytes
if s == 'rx_bytes' or s == 'tx_bytes':
convertor = diamond.convertor.binary(value=metric_value,
unit='byte')
for u in self.config['byte_unit']:
# Public Converted Metric
self.publish(metric_name.replace('bytes', u),
convertor.get(unit=u), 2)
else:
# Publish Metric Derivative
self.publish(metric_name, metric_value)
return None | python | def collect(self):
"""
Collect network interface stats.
"""
# Initialize results
results = {}
if os.access(self.PROC, os.R_OK):
# Open File
file = open(self.PROC)
# Build Regular Expression
greed = ''
if str_to_bool(self.config['greedy']):
greed = '\S*'
exp = (('^(?:\s*)((?:%s)%s):(?:\s*)' +
'(?P<rx_bytes>\d+)(?:\s*)' +
'(?P<rx_packets>\w+)(?:\s*)' +
'(?P<rx_errors>\d+)(?:\s*)' +
'(?P<rx_drop>\d+)(?:\s*)' +
'(?P<rx_fifo>\d+)(?:\s*)' +
'(?P<rx_frame>\d+)(?:\s*)' +
'(?P<rx_compressed>\d+)(?:\s*)' +
'(?P<rx_multicast>\d+)(?:\s*)' +
'(?P<tx_bytes>\d+)(?:\s*)' +
'(?P<tx_packets>\w+)(?:\s*)' +
'(?P<tx_errors>\d+)(?:\s*)' +
'(?P<tx_drop>\d+)(?:\s*)' +
'(?P<tx_fifo>\d+)(?:\s*)' +
'(?P<tx_colls>\d+)(?:\s*)' +
'(?P<tx_carrier>\d+)(?:\s*)' +
'(?P<tx_compressed>\d+)(?:.*)$') %
(('|'.join(self.config['interfaces'])), greed))
reg = re.compile(exp)
# Match Interfaces
for line in file:
match = reg.match(line)
if match:
device = match.group(1)
results[device] = match.groupdict()
# Close File
file.close()
else:
if not psutil:
self.log.error('Unable to import psutil')
self.log.error('No network metrics retrieved')
return None
network_stats = psutil.network_io_counters(True)
for device in network_stats.keys():
network_stat = network_stats[device]
results[device] = {}
results[device]['rx_bytes'] = network_stat.bytes_recv
results[device]['tx_bytes'] = network_stat.bytes_sent
results[device]['rx_packets'] = network_stat.packets_recv
results[device]['tx_packets'] = network_stat.packets_sent
for device in results:
stats = results[device]
for s, v in stats.items():
# Get Metric Name
metric_name = '.'.join([device, s])
# Get Metric Value
metric_value = self.derivative(metric_name,
long(v),
diamond.collector.MAX_COUNTER)
# Convert rx_bytes and tx_bytes
if s == 'rx_bytes' or s == 'tx_bytes':
convertor = diamond.convertor.binary(value=metric_value,
unit='byte')
for u in self.config['byte_unit']:
# Public Converted Metric
self.publish(metric_name.replace('bytes', u),
convertor.get(unit=u), 2)
else:
# Publish Metric Derivative
self.publish(metric_name, metric_value)
return None | [
"def",
"collect",
"(",
"self",
")",
":",
"# Initialize results",
"results",
"=",
"{",
"}",
"if",
"os",
".",
"access",
"(",
"self",
".",
"PROC",
",",
"os",
".",
"R_OK",
")",
":",
"# Open File",
"file",
"=",
"open",
"(",
"self",
".",
"PROC",
")",
"# ... | Collect network interface stats. | [
"Collect",
"network",
"interface",
"stats",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/network/network.py#L51-L133 | train | 217,301 |
python-diamond/Diamond | src/collectors/conntrack/conntrack.py | ConnTrackCollector.get_default_config_help | def get_default_config_help(self):
"""
Return help text for collector configuration
"""
config_help = super(ConnTrackCollector, self).get_default_config_help()
config_help.update({
"dir": "Directories with files of interest, comma seperated",
"files": "List of files to collect statistics from",
})
return config_help | python | def get_default_config_help(self):
"""
Return help text for collector configuration
"""
config_help = super(ConnTrackCollector, self).get_default_config_help()
config_help.update({
"dir": "Directories with files of interest, comma seperated",
"files": "List of files to collect statistics from",
})
return config_help | [
"def",
"get_default_config_help",
"(",
"self",
")",
":",
"config_help",
"=",
"super",
"(",
"ConnTrackCollector",
",",
"self",
")",
".",
"get_default_config_help",
"(",
")",
"config_help",
".",
"update",
"(",
"{",
"\"dir\"",
":",
"\"Directories with files of interest... | Return help text for collector configuration | [
"Return",
"help",
"text",
"for",
"collector",
"configuration"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/conntrack/conntrack.py#L22-L31 | train | 217,302 |
python-diamond/Diamond | src/collectors/netapp/netapp.py | NetAppCollector._replace_and_publish | def _replace_and_publish(self, path, prettyname, value, device):
"""
Inputs a complete path for a metric and a value.
Replace the metric name and publish.
"""
if value is None:
return
newpath = path
# Change metric name before publish if needed.
newpath = ".".join([".".join(path.split(".")[:-1]), prettyname])
metric = Metric(newpath, value, precision=4, host=device)
self.publish_metric(metric) | python | def _replace_and_publish(self, path, prettyname, value, device):
"""
Inputs a complete path for a metric and a value.
Replace the metric name and publish.
"""
if value is None:
return
newpath = path
# Change metric name before publish if needed.
newpath = ".".join([".".join(path.split(".")[:-1]), prettyname])
metric = Metric(newpath, value, precision=4, host=device)
self.publish_metric(metric) | [
"def",
"_replace_and_publish",
"(",
"self",
",",
"path",
",",
"prettyname",
",",
"value",
",",
"device",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"newpath",
"=",
"path",
"# Change metric name before publish if needed.",
"newpath",
"=",
"\".\"",
".",... | Inputs a complete path for a metric and a value.
Replace the metric name and publish. | [
"Inputs",
"a",
"complete",
"path",
"for",
"a",
"metric",
"and",
"a",
"value",
".",
"Replace",
"the",
"metric",
"name",
"and",
"publish",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netapp.py#L204-L215 | train | 217,303 |
python-diamond/Diamond | src/collectors/netapp/netapp.py | NetAppCollector._gen_delta_depend | def _gen_delta_depend(self, path, derivative, multiplier, prettyname,
device):
"""
For some metrics we need to divide the delta for one metric
with the delta of another.
Publishes a metric if the convertion goes well.
"""
primary_delta = derivative[path]
shortpath = ".".join(path.split(".")[:-1])
basename = path.split(".")[-1]
secondary_delta = None
if basename in self.DIVIDERS.keys():
mateKey = ".".join([shortpath, self.DIVIDERS[basename]])
else:
return
if mateKey in derivative.keys():
secondary_delta = derivative[mateKey]
else:
return
# If we find a corresponding secondary_delta, publish a metric
if primary_delta > 0 and secondary_delta > 0:
value = (float(primary_delta) / secondary_delta) * multiplier
self._replace_and_publish(path, prettyname, value, device) | python | def _gen_delta_depend(self, path, derivative, multiplier, prettyname,
device):
"""
For some metrics we need to divide the delta for one metric
with the delta of another.
Publishes a metric if the convertion goes well.
"""
primary_delta = derivative[path]
shortpath = ".".join(path.split(".")[:-1])
basename = path.split(".")[-1]
secondary_delta = None
if basename in self.DIVIDERS.keys():
mateKey = ".".join([shortpath, self.DIVIDERS[basename]])
else:
return
if mateKey in derivative.keys():
secondary_delta = derivative[mateKey]
else:
return
# If we find a corresponding secondary_delta, publish a metric
if primary_delta > 0 and secondary_delta > 0:
value = (float(primary_delta) / secondary_delta) * multiplier
self._replace_and_publish(path, prettyname, value, device) | [
"def",
"_gen_delta_depend",
"(",
"self",
",",
"path",
",",
"derivative",
",",
"multiplier",
",",
"prettyname",
",",
"device",
")",
":",
"primary_delta",
"=",
"derivative",
"[",
"path",
"]",
"shortpath",
"=",
"\".\"",
".",
"join",
"(",
"path",
".",
"split",... | For some metrics we need to divide the delta for one metric
with the delta of another.
Publishes a metric if the convertion goes well. | [
"For",
"some",
"metrics",
"we",
"need",
"to",
"divide",
"the",
"delta",
"for",
"one",
"metric",
"with",
"the",
"delta",
"of",
"another",
".",
"Publishes",
"a",
"metric",
"if",
"the",
"convertion",
"goes",
"well",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netapp.py#L217-L240 | train | 217,304 |
python-diamond/Diamond | src/collectors/netapp/netapp.py | NetAppCollector._gen_delta_per_sec | def _gen_delta_per_sec(self, path, value_delta, time_delta, multiplier,
prettyname, device):
"""
Calulates the difference between to point, and scales is to per second.
"""
if time_delta < 0:
return
value = (value_delta / time_delta) * multiplier
# Only publish if there is any data.
# This helps keep unused metrics out of Graphite
if value > 0.0:
self._replace_and_publish(path, prettyname, value, device) | python | def _gen_delta_per_sec(self, path, value_delta, time_delta, multiplier,
prettyname, device):
"""
Calulates the difference between to point, and scales is to per second.
"""
if time_delta < 0:
return
value = (value_delta / time_delta) * multiplier
# Only publish if there is any data.
# This helps keep unused metrics out of Graphite
if value > 0.0:
self._replace_and_publish(path, prettyname, value, device) | [
"def",
"_gen_delta_per_sec",
"(",
"self",
",",
"path",
",",
"value_delta",
",",
"time_delta",
",",
"multiplier",
",",
"prettyname",
",",
"device",
")",
":",
"if",
"time_delta",
"<",
"0",
":",
"return",
"value",
"=",
"(",
"value_delta",
"/",
"time_delta",
"... | Calulates the difference between to point, and scales is to per second. | [
"Calulates",
"the",
"difference",
"between",
"to",
"point",
"and",
"scales",
"is",
"to",
"per",
"second",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netapp.py#L242-L253 | train | 217,305 |
python-diamond/Diamond | src/diamond/handler/datadog.py | DatadogHandler._send | def _send(self):
"""
Take metrics from queue and send it to Datadog API
"""
while len(self.queue) > 0:
metric = self.queue.popleft()
path = '%s.%s.%s' % (
metric.getPathPrefix(),
metric.getCollectorPath(),
metric.getMetricPath()
)
topic, value, timestamp = str(metric).split()
logging.debug(
"Sending.. topic[%s], value[%s], timestamp[%s]",
path,
value,
timestamp
)
self.api.metric(path, (timestamp, value), host=metric.host) | python | def _send(self):
"""
Take metrics from queue and send it to Datadog API
"""
while len(self.queue) > 0:
metric = self.queue.popleft()
path = '%s.%s.%s' % (
metric.getPathPrefix(),
metric.getCollectorPath(),
metric.getMetricPath()
)
topic, value, timestamp = str(metric).split()
logging.debug(
"Sending.. topic[%s], value[%s], timestamp[%s]",
path,
value,
timestamp
)
self.api.metric(path, (timestamp, value), host=metric.host) | [
"def",
"_send",
"(",
"self",
")",
":",
"while",
"len",
"(",
"self",
".",
"queue",
")",
">",
"0",
":",
"metric",
"=",
"self",
".",
"queue",
".",
"popleft",
"(",
")",
"path",
"=",
"'%s.%s.%s'",
"%",
"(",
"metric",
".",
"getPathPrefix",
"(",
")",
",... | Take metrics from queue and send it to Datadog API | [
"Take",
"metrics",
"from",
"queue",
"and",
"send",
"it",
"to",
"Datadog",
"API"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/datadog.py#L84-L106 | train | 217,306 |
python-diamond/Diamond | setup.py | get_version | def get_version():
"""
Read the version.txt file to get the new version string
Generate it if version.txt is not available. Generation
is required for pip installs
"""
try:
f = open('version.txt')
except IOError:
os.system("./version.sh > version.txt")
f = open('version.txt')
version = ''.join(f.readlines()).rstrip()
f.close()
return version | python | def get_version():
"""
Read the version.txt file to get the new version string
Generate it if version.txt is not available. Generation
is required for pip installs
"""
try:
f = open('version.txt')
except IOError:
os.system("./version.sh > version.txt")
f = open('version.txt')
version = ''.join(f.readlines()).rstrip()
f.close()
return version | [
"def",
"get_version",
"(",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"'version.txt'",
")",
"except",
"IOError",
":",
"os",
".",
"system",
"(",
"\"./version.sh > version.txt\"",
")",
"f",
"=",
"open",
"(",
"'version.txt'",
")",
"version",
"=",
"''",
".... | Read the version.txt file to get the new version string
Generate it if version.txt is not available. Generation
is required for pip installs | [
"Read",
"the",
"version",
".",
"txt",
"file",
"to",
"get",
"the",
"new",
"version",
"string",
"Generate",
"it",
"if",
"version",
".",
"txt",
"is",
"not",
"available",
".",
"Generation",
"is",
"required",
"for",
"pip",
"installs"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/setup.py#L98-L111 | train | 217,307 |
python-diamond/Diamond | setup.py | pkgPath | def pkgPath(root, path, rpath="/"):
"""
Package up a path recursively
"""
global data_files
if not os.path.exists(path):
return
files = []
for spath in os.listdir(path):
# Ignore test directories
if spath == 'test':
continue
subpath = os.path.join(path, spath)
spath = os.path.join(rpath, spath)
if os.path.isfile(subpath):
files.append(subpath)
if os.path.isdir(subpath):
pkgPath(root, subpath, spath)
data_files.append((root + rpath, files)) | python | def pkgPath(root, path, rpath="/"):
"""
Package up a path recursively
"""
global data_files
if not os.path.exists(path):
return
files = []
for spath in os.listdir(path):
# Ignore test directories
if spath == 'test':
continue
subpath = os.path.join(path, spath)
spath = os.path.join(rpath, spath)
if os.path.isfile(subpath):
files.append(subpath)
if os.path.isdir(subpath):
pkgPath(root, subpath, spath)
data_files.append((root + rpath, files)) | [
"def",
"pkgPath",
"(",
"root",
",",
"path",
",",
"rpath",
"=",
"\"/\"",
")",
":",
"global",
"data_files",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"files",
"=",
"[",
"]",
"for",
"spath",
"in",
"os",
".",
"li... | Package up a path recursively | [
"Package",
"up",
"a",
"path",
"recursively"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/setup.py#L114-L132 | train | 217,308 |
python-diamond/Diamond | src/diamond/handler/statsite.py | StatsiteHandler._send | def _send(self, data):
"""
Send data to statsite. Data that can not be sent will be queued.
"""
retry = self.RETRY
# Attempt to send any data in the queue
while retry > 0:
# Check socket
if not self.socket:
# Log Error
self.log.error("StatsiteHandler: Socket unavailable.")
# Attempt to restablish connection
self._connect()
# Decrement retry
retry -= 1
# Try again
continue
try:
# Send data to socket
data = data.split()
data = data[0] + ":" + data[1] + "|kv\n"
self.socket.sendall(data)
# Done
break
except socket.error as e:
# Log Error
self.log.error("StatsiteHandler: Failed sending data. %s.", e)
# Attempt to restablish connection
self._close()
# Decrement retry
retry -= 1
# try again
continue | python | def _send(self, data):
"""
Send data to statsite. Data that can not be sent will be queued.
"""
retry = self.RETRY
# Attempt to send any data in the queue
while retry > 0:
# Check socket
if not self.socket:
# Log Error
self.log.error("StatsiteHandler: Socket unavailable.")
# Attempt to restablish connection
self._connect()
# Decrement retry
retry -= 1
# Try again
continue
try:
# Send data to socket
data = data.split()
data = data[0] + ":" + data[1] + "|kv\n"
self.socket.sendall(data)
# Done
break
except socket.error as e:
# Log Error
self.log.error("StatsiteHandler: Failed sending data. %s.", e)
# Attempt to restablish connection
self._close()
# Decrement retry
retry -= 1
# try again
continue | [
"def",
"_send",
"(",
"self",
",",
"data",
")",
":",
"retry",
"=",
"self",
".",
"RETRY",
"# Attempt to send any data in the queue",
"while",
"retry",
">",
"0",
":",
"# Check socket",
"if",
"not",
"self",
".",
"socket",
":",
"# Log Error",
"self",
".",
"log",
... | Send data to statsite. Data that can not be sent will be queued. | [
"Send",
"data",
"to",
"statsite",
".",
"Data",
"that",
"can",
"not",
"be",
"sent",
"will",
"be",
"queued",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/statsite.py#L127-L159 | train | 217,309 |
python-diamond/Diamond | src/diamond/handler/statsite.py | StatsiteHandler._connect | def _connect(self):
"""
Connect to the statsite server
"""
# Create socket
if self.udpport > 0:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.port = self.udpport
elif self.tcpport > 0:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.port = self.tcpport
if socket is None:
# Log Error
self.log.error("StatsiteHandler: Unable to create socket.")
# Close Socket
self._close()
return
# Set socket timeout
self.socket.settimeout(self.timeout)
# Connect to statsite server
try:
self.socket.connect((self.host, self.port))
# Log
self.log.debug("Established connection to statsite server %s:%d",
self.host, self.port)
except Exception as ex:
# Log Error
self.log.error("StatsiteHandler: Failed to connect to %s:%i. %s",
self.host, self.port, ex)
# Close Socket
self._close()
return | python | def _connect(self):
"""
Connect to the statsite server
"""
# Create socket
if self.udpport > 0:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.port = self.udpport
elif self.tcpport > 0:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.port = self.tcpport
if socket is None:
# Log Error
self.log.error("StatsiteHandler: Unable to create socket.")
# Close Socket
self._close()
return
# Set socket timeout
self.socket.settimeout(self.timeout)
# Connect to statsite server
try:
self.socket.connect((self.host, self.port))
# Log
self.log.debug("Established connection to statsite server %s:%d",
self.host, self.port)
except Exception as ex:
# Log Error
self.log.error("StatsiteHandler: Failed to connect to %s:%i. %s",
self.host, self.port, ex)
# Close Socket
self._close()
return | [
"def",
"_connect",
"(",
"self",
")",
":",
"# Create socket",
"if",
"self",
".",
"udpport",
">",
"0",
":",
"self",
".",
"socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"self",
".",
"port",
... | Connect to the statsite server | [
"Connect",
"to",
"the",
"statsite",
"server"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/statsite.py#L161-L192 | train | 217,310 |
python-diamond/Diamond | src/diamond/utils/classes.py | load_include_path | def load_include_path(paths):
"""
Scan for and add paths to the include path
"""
for path in paths:
# Verify the path is valid
if not os.path.isdir(path):
continue
# Add path to the system path, to avoid name clashes
# with mysql-connector for example ...
if path not in sys.path:
sys.path.insert(1, path)
# Load all the files in path
for f in os.listdir(path):
# Are we a directory? If so process down the tree
fpath = os.path.join(path, f)
if os.path.isdir(fpath):
load_include_path([fpath]) | python | def load_include_path(paths):
"""
Scan for and add paths to the include path
"""
for path in paths:
# Verify the path is valid
if not os.path.isdir(path):
continue
# Add path to the system path, to avoid name clashes
# with mysql-connector for example ...
if path not in sys.path:
sys.path.insert(1, path)
# Load all the files in path
for f in os.listdir(path):
# Are we a directory? If so process down the tree
fpath = os.path.join(path, f)
if os.path.isdir(fpath):
load_include_path([fpath]) | [
"def",
"load_include_path",
"(",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"# Verify the path is valid",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"continue",
"# Add path to the system path, to avoid name clashes",
"# with mysq... | Scan for and add paths to the include path | [
"Scan",
"for",
"and",
"add",
"paths",
"to",
"the",
"include",
"path"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/classes.py#L19-L36 | train | 217,311 |
python-diamond/Diamond | src/diamond/utils/classes.py | load_dynamic_class | def load_dynamic_class(fqn, subclass):
"""
Dynamically load fqn class and verify it's a subclass of subclass
"""
if not isinstance(fqn, basestring):
return fqn
cls = load_class_from_name(fqn)
if cls == subclass or not issubclass(cls, subclass):
raise TypeError("%s is not a valid %s" % (fqn, subclass.__name__))
return cls | python | def load_dynamic_class(fqn, subclass):
"""
Dynamically load fqn class and verify it's a subclass of subclass
"""
if not isinstance(fqn, basestring):
return fqn
cls = load_class_from_name(fqn)
if cls == subclass or not issubclass(cls, subclass):
raise TypeError("%s is not a valid %s" % (fqn, subclass.__name__))
return cls | [
"def",
"load_dynamic_class",
"(",
"fqn",
",",
"subclass",
")",
":",
"if",
"not",
"isinstance",
"(",
"fqn",
",",
"basestring",
")",
":",
"return",
"fqn",
"cls",
"=",
"load_class_from_name",
"(",
"fqn",
")",
"if",
"cls",
"==",
"subclass",
"or",
"not",
"iss... | Dynamically load fqn class and verify it's a subclass of subclass | [
"Dynamically",
"load",
"fqn",
"class",
"and",
"verify",
"it",
"s",
"a",
"subclass",
"of",
"subclass"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/classes.py#L39-L51 | train | 217,312 |
python-diamond/Diamond | src/diamond/utils/classes.py | load_collectors_from_paths | def load_collectors_from_paths(paths):
"""
Scan for collectors to load from path
"""
# Initialize return value
collectors = {}
if paths is None:
return
if isinstance(paths, basestring):
paths = paths.split(',')
paths = map(str.strip, paths)
load_include_path(paths)
for path in paths:
# Get a list of files in the directory, if the directory exists
if not os.path.exists(path):
raise OSError("Directory does not exist: %s" % path)
if path.endswith('tests') or path.endswith('fixtures'):
return collectors
# Load all the files in path
for f in os.listdir(path):
# Are we a directory? If so process down the tree
fpath = os.path.join(path, f)
if os.path.isdir(fpath):
subcollectors = load_collectors_from_paths([fpath])
for key in subcollectors:
collectors[key] = subcollectors[key]
# Ignore anything that isn't a .py file
elif (os.path.isfile(fpath) and
len(f) > 3 and
f[-3:] == '.py' and
f[0:4] != 'test' and
f[0] != '.'):
modname = f[:-3]
fp, pathname, description = imp.find_module(modname, [path])
try:
# Import the module
mod = imp.load_module(modname, fp, pathname, description)
except (KeyboardInterrupt, SystemExit) as err:
logger.error(
"System or keyboard interrupt "
"while loading module %s"
% modname)
if isinstance(err, SystemExit):
sys.exit(err.code)
raise KeyboardInterrupt
except Exception:
# Log error
logger.error("Failed to import module: %s. %s",
modname,
traceback.format_exc())
else:
for name, cls in get_collectors_from_module(mod):
collectors[name] = cls
finally:
if fp:
fp.close()
# Return Collector classes
return collectors | python | def load_collectors_from_paths(paths):
"""
Scan for collectors to load from path
"""
# Initialize return value
collectors = {}
if paths is None:
return
if isinstance(paths, basestring):
paths = paths.split(',')
paths = map(str.strip, paths)
load_include_path(paths)
for path in paths:
# Get a list of files in the directory, if the directory exists
if not os.path.exists(path):
raise OSError("Directory does not exist: %s" % path)
if path.endswith('tests') or path.endswith('fixtures'):
return collectors
# Load all the files in path
for f in os.listdir(path):
# Are we a directory? If so process down the tree
fpath = os.path.join(path, f)
if os.path.isdir(fpath):
subcollectors = load_collectors_from_paths([fpath])
for key in subcollectors:
collectors[key] = subcollectors[key]
# Ignore anything that isn't a .py file
elif (os.path.isfile(fpath) and
len(f) > 3 and
f[-3:] == '.py' and
f[0:4] != 'test' and
f[0] != '.'):
modname = f[:-3]
fp, pathname, description = imp.find_module(modname, [path])
try:
# Import the module
mod = imp.load_module(modname, fp, pathname, description)
except (KeyboardInterrupt, SystemExit) as err:
logger.error(
"System or keyboard interrupt "
"while loading module %s"
% modname)
if isinstance(err, SystemExit):
sys.exit(err.code)
raise KeyboardInterrupt
except Exception:
# Log error
logger.error("Failed to import module: %s. %s",
modname,
traceback.format_exc())
else:
for name, cls in get_collectors_from_module(mod):
collectors[name] = cls
finally:
if fp:
fp.close()
# Return Collector classes
return collectors | [
"def",
"load_collectors_from_paths",
"(",
"paths",
")",
":",
"# Initialize return value",
"collectors",
"=",
"{",
"}",
"if",
"paths",
"is",
"None",
":",
"return",
"if",
"isinstance",
"(",
"paths",
",",
"basestring",
")",
":",
"paths",
"=",
"paths",
".",
"spl... | Scan for collectors to load from path | [
"Scan",
"for",
"collectors",
"to",
"load",
"from",
"path"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/classes.py#L112-L181 | train | 217,313 |
python-diamond/Diamond | src/diamond/utils/classes.py | load_collectors_from_entry_point | def load_collectors_from_entry_point(path):
"""
Load collectors that were installed into an entry_point.
"""
collectors = {}
for ep in pkg_resources.iter_entry_points(path):
try:
mod = ep.load()
except Exception:
logger.error('Failed to import entry_point: %s. %s',
ep.name,
traceback.format_exc())
else:
collectors.update(get_collectors_from_module(mod))
return collectors | python | def load_collectors_from_entry_point(path):
"""
Load collectors that were installed into an entry_point.
"""
collectors = {}
for ep in pkg_resources.iter_entry_points(path):
try:
mod = ep.load()
except Exception:
logger.error('Failed to import entry_point: %s. %s',
ep.name,
traceback.format_exc())
else:
collectors.update(get_collectors_from_module(mod))
return collectors | [
"def",
"load_collectors_from_entry_point",
"(",
"path",
")",
":",
"collectors",
"=",
"{",
"}",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"path",
")",
":",
"try",
":",
"mod",
"=",
"ep",
".",
"load",
"(",
")",
"except",
"Exception",
... | Load collectors that were installed into an entry_point. | [
"Load",
"collectors",
"that",
"were",
"installed",
"into",
"an",
"entry_point",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/classes.py#L184-L198 | train | 217,314 |
python-diamond/Diamond | src/diamond/utils/classes.py | get_collectors_from_module | def get_collectors_from_module(mod):
"""
Locate all of the collector classes within a given module
"""
for attrname in dir(mod):
attr = getattr(mod, attrname)
# Only attempt to load classes that are infact classes
# are Collectors but are not the base Collector class
if ((inspect.isclass(attr) and
issubclass(attr, Collector) and
attr != Collector)):
if attrname.startswith('parent_'):
continue
# Get class name
fqcn = '.'.join([mod.__name__, attrname])
try:
# Load Collector class
cls = load_dynamic_class(fqcn, Collector)
# Add Collector class
yield cls.__name__, cls
except Exception:
# Log error
logger.error(
"Failed to load Collector: %s. %s",
fqcn, traceback.format_exc())
continue | python | def get_collectors_from_module(mod):
"""
Locate all of the collector classes within a given module
"""
for attrname in dir(mod):
attr = getattr(mod, attrname)
# Only attempt to load classes that are infact classes
# are Collectors but are not the base Collector class
if ((inspect.isclass(attr) and
issubclass(attr, Collector) and
attr != Collector)):
if attrname.startswith('parent_'):
continue
# Get class name
fqcn = '.'.join([mod.__name__, attrname])
try:
# Load Collector class
cls = load_dynamic_class(fqcn, Collector)
# Add Collector class
yield cls.__name__, cls
except Exception:
# Log error
logger.error(
"Failed to load Collector: %s. %s",
fqcn, traceback.format_exc())
continue | [
"def",
"get_collectors_from_module",
"(",
"mod",
")",
":",
"for",
"attrname",
"in",
"dir",
"(",
"mod",
")",
":",
"attr",
"=",
"getattr",
"(",
"mod",
",",
"attrname",
")",
"# Only attempt to load classes that are infact classes",
"# are Collectors but are not the base Co... | Locate all of the collector classes within a given module | [
"Locate",
"all",
"of",
"the",
"collector",
"classes",
"within",
"a",
"given",
"module"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/classes.py#L201-L226 | train | 217,315 |
python-diamond/Diamond | src/diamond/handler/mysql.py | MySQLHandler._send | def _send(self, data):
"""
Insert the data
"""
data = data.strip().split(' ')
try:
cursor = self.conn.cursor()
cursor.execute("INSERT INTO %s (%s, %s, %s) VALUES(%%s, %%s, %%s)"
% (self.table, self.col_metric,
self.col_time, self.col_value),
(data[0], data[2], data[1]))
cursor.close()
self.conn.commit()
except BaseException as e:
# Log Error
self.log.error("MySQLHandler: Failed sending data. %s.", e)
# Attempt to restablish connection
self._connect() | python | def _send(self, data):
"""
Insert the data
"""
data = data.strip().split(' ')
try:
cursor = self.conn.cursor()
cursor.execute("INSERT INTO %s (%s, %s, %s) VALUES(%%s, %%s, %%s)"
% (self.table, self.col_metric,
self.col_time, self.col_value),
(data[0], data[2], data[1]))
cursor.close()
self.conn.commit()
except BaseException as e:
# Log Error
self.log.error("MySQLHandler: Failed sending data. %s.", e)
# Attempt to restablish connection
self._connect() | [
"def",
"_send",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
".",
"strip",
"(",
")",
".",
"split",
"(",
"' '",
")",
"try",
":",
"cursor",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"INSERT INTO... | Insert the data | [
"Insert",
"the",
"data"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/mysql.py#L73-L90 | train | 217,316 |
python-diamond/Diamond | src/diamond/handler/mysql.py | MySQLHandler._connect | def _connect(self):
"""
Connect to the MySQL server
"""
self._close()
self.conn = MySQLdb.Connect(host=self.hostname,
port=self.port,
user=self.username,
passwd=self.password,
db=self.database) | python | def _connect(self):
"""
Connect to the MySQL server
"""
self._close()
self.conn = MySQLdb.Connect(host=self.hostname,
port=self.port,
user=self.username,
passwd=self.password,
db=self.database) | [
"def",
"_connect",
"(",
"self",
")",
":",
"self",
".",
"_close",
"(",
")",
"self",
".",
"conn",
"=",
"MySQLdb",
".",
"Connect",
"(",
"host",
"=",
"self",
".",
"hostname",
",",
"port",
"=",
"self",
".",
"port",
",",
"user",
"=",
"self",
".",
"user... | Connect to the MySQL server | [
"Connect",
"to",
"the",
"MySQL",
"server"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/mysql.py#L92-L101 | train | 217,317 |
python-diamond/Diamond | src/collectors/nvidia_gpu/nvidia_gpu.py | NvidiaGPUCollector.collect | def collect(self):
"""
Collector GPU stats
"""
stats_config = self.config['stats']
if USE_PYTHON_BINDING:
collect_metrics = self.collect_via_pynvml
else:
collect_metrics = self.collect_via_nvidia_smi
collect_metrics(stats_config) | python | def collect(self):
"""
Collector GPU stats
"""
stats_config = self.config['stats']
if USE_PYTHON_BINDING:
collect_metrics = self.collect_via_pynvml
else:
collect_metrics = self.collect_via_nvidia_smi
collect_metrics(stats_config) | [
"def",
"collect",
"(",
"self",
")",
":",
"stats_config",
"=",
"self",
".",
"config",
"[",
"'stats'",
"]",
"if",
"USE_PYTHON_BINDING",
":",
"collect_metrics",
"=",
"self",
".",
"collect_via_pynvml",
"else",
":",
"collect_metrics",
"=",
"self",
".",
"collect_via... | Collector GPU stats | [
"Collector",
"GPU",
"stats"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nvidia_gpu/nvidia_gpu.py#L119-L129 | train | 217,318 |
python-diamond/Diamond | src/collectors/jcollectd/collectd_network.py | decode_network_values | def decode_network_values(ptype, plen, buf):
"""Decodes a list of DS values in collectd network format
"""
nvalues = short.unpack_from(buf, header.size)[0]
off = header.size + short.size + nvalues
valskip = double.size
# Check whether our expected packet size is the reported one
assert ((valskip + 1) * nvalues + short.size + header.size) == plen
assert double.size == number.size
result = []
for dstype in [ord(x) for x in buf[header.size + short.size:off]]:
if dstype == DS_TYPE_COUNTER:
result.append((dstype, number.unpack_from(buf, off)[0]))
off += valskip
elif dstype == DS_TYPE_GAUGE:
result.append((dstype, double.unpack_from(buf, off)[0]))
off += valskip
elif dstype == DS_TYPE_DERIVE:
result.append((dstype, number.unpack_from(buf, off)[0]))
off += valskip
elif dstype == DS_TYPE_ABSOLUTE:
result.append((dstype, number.unpack_from(buf, off)[0]))
off += valskip
else:
raise ValueError("DS type %i unsupported" % dstype)
return result | python | def decode_network_values(ptype, plen, buf):
"""Decodes a list of DS values in collectd network format
"""
nvalues = short.unpack_from(buf, header.size)[0]
off = header.size + short.size + nvalues
valskip = double.size
# Check whether our expected packet size is the reported one
assert ((valskip + 1) * nvalues + short.size + header.size) == plen
assert double.size == number.size
result = []
for dstype in [ord(x) for x in buf[header.size + short.size:off]]:
if dstype == DS_TYPE_COUNTER:
result.append((dstype, number.unpack_from(buf, off)[0]))
off += valskip
elif dstype == DS_TYPE_GAUGE:
result.append((dstype, double.unpack_from(buf, off)[0]))
off += valskip
elif dstype == DS_TYPE_DERIVE:
result.append((dstype, number.unpack_from(buf, off)[0]))
off += valskip
elif dstype == DS_TYPE_ABSOLUTE:
result.append((dstype, number.unpack_from(buf, off)[0]))
off += valskip
else:
raise ValueError("DS type %i unsupported" % dstype)
return result | [
"def",
"decode_network_values",
"(",
"ptype",
",",
"plen",
",",
"buf",
")",
":",
"nvalues",
"=",
"short",
".",
"unpack_from",
"(",
"buf",
",",
"header",
".",
"size",
")",
"[",
"0",
"]",
"off",
"=",
"header",
".",
"size",
"+",
"short",
".",
"size",
... | Decodes a list of DS values in collectd network format | [
"Decodes",
"a",
"list",
"of",
"DS",
"values",
"in",
"collectd",
"network",
"format"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/jcollectd/collectd_network.py#L83-L111 | train | 217,319 |
python-diamond/Diamond | src/collectors/jcollectd/collectd_network.py | decode_network_packet | def decode_network_packet(buf):
"""Decodes a network packet in collectd format.
"""
off = 0
blen = len(buf)
while off < blen:
ptype, plen = header.unpack_from(buf, off)
if plen > blen - off:
raise ValueError("Packet longer than amount of data in buffer")
if ptype not in _decoders:
raise ValueError("Message type %i not recognized" % ptype)
yield ptype, _decoders[ptype](ptype, plen, buf[off:])
off += plen | python | def decode_network_packet(buf):
"""Decodes a network packet in collectd format.
"""
off = 0
blen = len(buf)
while off < blen:
ptype, plen = header.unpack_from(buf, off)
if plen > blen - off:
raise ValueError("Packet longer than amount of data in buffer")
if ptype not in _decoders:
raise ValueError("Message type %i not recognized" % ptype)
yield ptype, _decoders[ptype](ptype, plen, buf[off:])
off += plen | [
"def",
"decode_network_packet",
"(",
"buf",
")",
":",
"off",
"=",
"0",
"blen",
"=",
"len",
"(",
"buf",
")",
"while",
"off",
"<",
"blen",
":",
"ptype",
",",
"plen",
"=",
"header",
".",
"unpack_from",
"(",
"buf",
",",
"off",
")",
"if",
"plen",
">",
... | Decodes a network packet in collectd format. | [
"Decodes",
"a",
"network",
"packet",
"in",
"collectd",
"format",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/jcollectd/collectd_network.py#L143-L159 | train | 217,320 |
python-diamond/Diamond | src/collectors/jcollectd/collectd_network.py | Reader.receive | def receive(self, poll_interval):
"""Receives a single raw collect network packet.
"""
readable, writeable, errored = select.select(self._readlist, [], [],
poll_interval)
for s in readable:
data, addr = s.recvfrom(self.BUFFER_SIZE)
if data:
return data
return None | python | def receive(self, poll_interval):
"""Receives a single raw collect network packet.
"""
readable, writeable, errored = select.select(self._readlist, [], [],
poll_interval)
for s in readable:
data, addr = s.recvfrom(self.BUFFER_SIZE)
if data:
return data
return None | [
"def",
"receive",
"(",
"self",
",",
"poll_interval",
")",
":",
"readable",
",",
"writeable",
",",
"errored",
"=",
"select",
".",
"select",
"(",
"self",
".",
"_readlist",
",",
"[",
"]",
",",
"[",
"]",
",",
"poll_interval",
")",
"for",
"s",
"in",
"read... | Receives a single raw collect network packet. | [
"Receives",
"a",
"single",
"raw",
"collect",
"network",
"packet",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/jcollectd/collectd_network.py#L341-L351 | train | 217,321 |
python-diamond/Diamond | src/collectors/jcollectd/collectd_network.py | Reader.decode | def decode(self, poll_interval, buf=None):
"""Decodes a given buffer or the next received packet.
"""
if buf is None:
buf = self.receive(poll_interval)
if buf is None:
return None
return decode_network_packet(buf) | python | def decode(self, poll_interval, buf=None):
"""Decodes a given buffer or the next received packet.
"""
if buf is None:
buf = self.receive(poll_interval)
if buf is None:
return None
return decode_network_packet(buf) | [
"def",
"decode",
"(",
"self",
",",
"poll_interval",
",",
"buf",
"=",
"None",
")",
":",
"if",
"buf",
"is",
"None",
":",
"buf",
"=",
"self",
".",
"receive",
"(",
"poll_interval",
")",
"if",
"buf",
"is",
"None",
":",
"return",
"None",
"return",
"decode_... | Decodes a given buffer or the next received packet. | [
"Decodes",
"a",
"given",
"buffer",
"or",
"the",
"next",
"received",
"packet",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/jcollectd/collectd_network.py#L353-L360 | train | 217,322 |
python-diamond/Diamond | src/collectors/jcollectd/collectd_network.py | Reader.interpret | def interpret(self, iterable=None, poll_interval=0.2):
"""Interprets a sequence
"""
if iterable is None:
iterable = self.decode(poll_interval)
if iterable is None:
return None
if isinstance(iterable, basestring):
iterable = self.decode(poll_interval, iterable)
return interpret_opcodes(iterable) | python | def interpret(self, iterable=None, poll_interval=0.2):
"""Interprets a sequence
"""
if iterable is None:
iterable = self.decode(poll_interval)
if iterable is None:
return None
if isinstance(iterable, basestring):
iterable = self.decode(poll_interval, iterable)
return interpret_opcodes(iterable) | [
"def",
"interpret",
"(",
"self",
",",
"iterable",
"=",
"None",
",",
"poll_interval",
"=",
"0.2",
")",
":",
"if",
"iterable",
"is",
"None",
":",
"iterable",
"=",
"self",
".",
"decode",
"(",
"poll_interval",
")",
"if",
"iterable",
"is",
"None",
":",
"ret... | Interprets a sequence | [
"Interprets",
"a",
"sequence"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/jcollectd/collectd_network.py#L362-L373 | train | 217,323 |
ncclient/ncclient | ncclient/manager.py | make_device_handler | def make_device_handler(device_params):
"""
Create a device handler object that provides device specific parameters and
functions, which are called in various places throughout our code.
If no device_params are defined or the "name" in the parameter dict is not
known then a default handler will be returned.
"""
if device_params is None:
device_params = {}
handler = device_params.get('handler', None)
if handler:
return handler(device_params)
device_name = device_params.get("name", "default")
# Attempt to import device handler class. All device handlers are
# in a module called "ncclient.devices.<devicename>" and in a class named
# "<devicename>DeviceHandler", with the first letter capitalized.
class_name = "%sDeviceHandler" % device_name.capitalize()
devices_module_name = "ncclient.devices.%s" % device_name
dev_module_obj = __import__(devices_module_name)
handler_module_obj = getattr(getattr(dev_module_obj, "devices"), device_name)
class_obj = getattr(handler_module_obj, class_name)
handler_obj = class_obj(device_params)
return handler_obj | python | def make_device_handler(device_params):
"""
Create a device handler object that provides device specific parameters and
functions, which are called in various places throughout our code.
If no device_params are defined or the "name" in the parameter dict is not
known then a default handler will be returned.
"""
if device_params is None:
device_params = {}
handler = device_params.get('handler', None)
if handler:
return handler(device_params)
device_name = device_params.get("name", "default")
# Attempt to import device handler class. All device handlers are
# in a module called "ncclient.devices.<devicename>" and in a class named
# "<devicename>DeviceHandler", with the first letter capitalized.
class_name = "%sDeviceHandler" % device_name.capitalize()
devices_module_name = "ncclient.devices.%s" % device_name
dev_module_obj = __import__(devices_module_name)
handler_module_obj = getattr(getattr(dev_module_obj, "devices"), device_name)
class_obj = getattr(handler_module_obj, class_name)
handler_obj = class_obj(device_params)
return handler_obj | [
"def",
"make_device_handler",
"(",
"device_params",
")",
":",
"if",
"device_params",
"is",
"None",
":",
"device_params",
"=",
"{",
"}",
"handler",
"=",
"device_params",
".",
"get",
"(",
"'handler'",
",",
"None",
")",
"if",
"handler",
":",
"return",
"handler"... | Create a device handler object that provides device specific parameters and
functions, which are called in various places throughout our code.
If no device_params are defined or the "name" in the parameter dict is not
known then a default handler will be returned. | [
"Create",
"a",
"device",
"handler",
"object",
"that",
"provides",
"device",
"specific",
"parameters",
"and",
"functions",
"which",
"are",
"called",
"in",
"various",
"places",
"throughout",
"our",
"code",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/manager.py#L63-L89 | train | 217,324 |
ncclient/ncclient | ncclient/manager.py | Manager.take_notification | def take_notification(self, block=True, timeout=None):
"""Attempt to retrieve one notification from the queue of received
notifications.
If block is True, the call will wait until a notification is
received.
If timeout is a number greater than 0, the call will wait that
many seconds to receive a notification before timing out.
If there is no notification available when block is False or
when the timeout has elapse, None will be returned.
Otherwise a :class:`~ncclient.operations.notify.Notification`
object will be returned.
"""
return self._session.take_notification(block, timeout) | python | def take_notification(self, block=True, timeout=None):
"""Attempt to retrieve one notification from the queue of received
notifications.
If block is True, the call will wait until a notification is
received.
If timeout is a number greater than 0, the call will wait that
many seconds to receive a notification before timing out.
If there is no notification available when block is False or
when the timeout has elapse, None will be returned.
Otherwise a :class:`~ncclient.operations.notify.Notification`
object will be returned.
"""
return self._session.take_notification(block, timeout) | [
"def",
"take_notification",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"_session",
".",
"take_notification",
"(",
"block",
",",
"timeout",
")"
] | Attempt to retrieve one notification from the queue of received
notifications.
If block is True, the call will wait until a notification is
received.
If timeout is a number greater than 0, the call will wait that
many seconds to receive a notification before timing out.
If there is no notification available when block is False or
when the timeout has elapse, None will be returned.
Otherwise a :class:`~ncclient.operations.notify.Notification`
object will be returned. | [
"Attempt",
"to",
"retrieve",
"one",
"notification",
"from",
"the",
"queue",
"of",
"received",
"notifications",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/manager.py#L258-L274 | train | 217,325 |
ncclient/ncclient | ncclient/operations/third_party/hpcomware/rpc.py | DisplayCommand.request | def request(self, cmds):
"""
Single Execution element is permitted.
cmds can be a list or single command
"""
if isinstance(cmds, list):
cmd = '\n'.join(cmds)
elif isinstance(cmds, str) or isinstance(cmds, unicode):
cmd = cmds
node = etree.Element(qualify('CLI', BASE_NS_1_0))
etree.SubElement(node, qualify('Execution',
BASE_NS_1_0)).text = cmd
return self._request(node) | python | def request(self, cmds):
"""
Single Execution element is permitted.
cmds can be a list or single command
"""
if isinstance(cmds, list):
cmd = '\n'.join(cmds)
elif isinstance(cmds, str) or isinstance(cmds, unicode):
cmd = cmds
node = etree.Element(qualify('CLI', BASE_NS_1_0))
etree.SubElement(node, qualify('Execution',
BASE_NS_1_0)).text = cmd
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"cmds",
")",
":",
"if",
"isinstance",
"(",
"cmds",
",",
"list",
")",
":",
"cmd",
"=",
"'\\n'",
".",
"join",
"(",
"cmds",
")",
"elif",
"isinstance",
"(",
"cmds",
",",
"str",
")",
"or",
"isinstance",
"(",
"cmds",
... | Single Execution element is permitted.
cmds can be a list or single command | [
"Single",
"Execution",
"element",
"is",
"permitted",
".",
"cmds",
"can",
"be",
"a",
"list",
"or",
"single",
"command"
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/third_party/hpcomware/rpc.py#L7-L22 | train | 217,326 |
ncclient/ncclient | ncclient/xml_.py | validated_element | def validated_element(x, tags=None, attrs=None):
"""Checks if the root element of an XML document or Element meets the supplied criteria.
*tags* if specified is either a single allowable tag name or sequence of allowable alternatives
*attrs* if specified is a sequence of required attributes, each of which may be a sequence of several allowable alternatives
Raises :exc:`XMLError` if the requirements are not met.
"""
ele = to_ele(x)
if tags:
if isinstance(tags, (str, bytes)):
tags = [tags]
if ele.tag not in tags:
raise XMLError("Element [%s] does not meet requirement" % ele.tag)
if attrs:
for req in attrs:
if isinstance(req, (str, bytes)): req = [req]
for alt in req:
if alt in ele.attrib:
break
else:
raise XMLError("Element [%s] does not have required attributes" % ele.tag)
return ele | python | def validated_element(x, tags=None, attrs=None):
"""Checks if the root element of an XML document or Element meets the supplied criteria.
*tags* if specified is either a single allowable tag name or sequence of allowable alternatives
*attrs* if specified is a sequence of required attributes, each of which may be a sequence of several allowable alternatives
Raises :exc:`XMLError` if the requirements are not met.
"""
ele = to_ele(x)
if tags:
if isinstance(tags, (str, bytes)):
tags = [tags]
if ele.tag not in tags:
raise XMLError("Element [%s] does not meet requirement" % ele.tag)
if attrs:
for req in attrs:
if isinstance(req, (str, bytes)): req = [req]
for alt in req:
if alt in ele.attrib:
break
else:
raise XMLError("Element [%s] does not have required attributes" % ele.tag)
return ele | [
"def",
"validated_element",
"(",
"x",
",",
"tags",
"=",
"None",
",",
"attrs",
"=",
"None",
")",
":",
"ele",
"=",
"to_ele",
"(",
"x",
")",
"if",
"tags",
":",
"if",
"isinstance",
"(",
"tags",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"tags",
... | Checks if the root element of an XML document or Element meets the supplied criteria.
*tags* if specified is either a single allowable tag name or sequence of allowable alternatives
*attrs* if specified is a sequence of required attributes, each of which may be a sequence of several allowable alternatives
Raises :exc:`XMLError` if the requirements are not met. | [
"Checks",
"if",
"the",
"root",
"element",
"of",
"an",
"XML",
"document",
"or",
"Element",
"meets",
"the",
"supplied",
"criteria",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/xml_.py#L125-L148 | train | 217,327 |
ncclient/ncclient | ncclient/xml_.py | NCElement.tostring | def tostring(self):
"""return a pretty-printed string output for rpc reply"""
parser = etree.XMLParser(remove_blank_text=True)
outputtree = etree.XML(etree.tostring(self.__doc), parser)
return etree.tostring(outputtree, pretty_print=True) | python | def tostring(self):
"""return a pretty-printed string output for rpc reply"""
parser = etree.XMLParser(remove_blank_text=True)
outputtree = etree.XML(etree.tostring(self.__doc), parser)
return etree.tostring(outputtree, pretty_print=True) | [
"def",
"tostring",
"(",
"self",
")",
":",
"parser",
"=",
"etree",
".",
"XMLParser",
"(",
"remove_blank_text",
"=",
"True",
")",
"outputtree",
"=",
"etree",
".",
"XML",
"(",
"etree",
".",
"tostring",
"(",
"self",
".",
"__doc",
")",
",",
"parser",
")",
... | return a pretty-printed string output for rpc reply | [
"return",
"a",
"pretty",
"-",
"printed",
"string",
"output",
"for",
"rpc",
"reply"
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/xml_.py#L192-L196 | train | 217,328 |
ncclient/ncclient | ncclient/xml_.py | NCElement.remove_namespaces | def remove_namespaces(self, rpc_reply):
"""remove xmlns attributes from rpc reply"""
self.__xslt=self.__transform_reply
self.__parser = etree.XMLParser(remove_blank_text=True)
self.__xslt_doc = etree.parse(io.BytesIO(self.__xslt), self.__parser)
self.__transform = etree.XSLT(self.__xslt_doc)
self.__root = etree.fromstring(str(self.__transform(etree.parse(StringIO(str(rpc_reply))))))
return self.__root | python | def remove_namespaces(self, rpc_reply):
"""remove xmlns attributes from rpc reply"""
self.__xslt=self.__transform_reply
self.__parser = etree.XMLParser(remove_blank_text=True)
self.__xslt_doc = etree.parse(io.BytesIO(self.__xslt), self.__parser)
self.__transform = etree.XSLT(self.__xslt_doc)
self.__root = etree.fromstring(str(self.__transform(etree.parse(StringIO(str(rpc_reply))))))
return self.__root | [
"def",
"remove_namespaces",
"(",
"self",
",",
"rpc_reply",
")",
":",
"self",
".",
"__xslt",
"=",
"self",
".",
"__transform_reply",
"self",
".",
"__parser",
"=",
"etree",
".",
"XMLParser",
"(",
"remove_blank_text",
"=",
"True",
")",
"self",
".",
"__xslt_doc",... | remove xmlns attributes from rpc reply | [
"remove",
"xmlns",
"attributes",
"from",
"rpc",
"reply"
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/xml_.py#L203-L210 | train | 217,329 |
ncclient/ncclient | ncclient/operations/retrieve.py | GetSchema.request | def request(self, identifier, version=None, format=None):
"""Retrieve a named schema, with optional revision and type.
*identifier* name of the schema to be retrieved
*version* version of schema to get
*format* format of the schema to be retrieved, yang is the default
:seealso: :ref:`filter_params`"""
node = etree.Element(qualify("get-schema",NETCONF_MONITORING_NS))
if identifier is not None:
elem = etree.Element(qualify("identifier",NETCONF_MONITORING_NS))
elem.text = identifier
node.append(elem)
if version is not None:
elem = etree.Element(qualify("version",NETCONF_MONITORING_NS))
elem.text = version
node.append(elem)
if format is not None:
elem = etree.Element(qualify("format",NETCONF_MONITORING_NS))
elem.text = format
node.append(elem)
return self._request(node) | python | def request(self, identifier, version=None, format=None):
"""Retrieve a named schema, with optional revision and type.
*identifier* name of the schema to be retrieved
*version* version of schema to get
*format* format of the schema to be retrieved, yang is the default
:seealso: :ref:`filter_params`"""
node = etree.Element(qualify("get-schema",NETCONF_MONITORING_NS))
if identifier is not None:
elem = etree.Element(qualify("identifier",NETCONF_MONITORING_NS))
elem.text = identifier
node.append(elem)
if version is not None:
elem = etree.Element(qualify("version",NETCONF_MONITORING_NS))
elem.text = version
node.append(elem)
if format is not None:
elem = etree.Element(qualify("format",NETCONF_MONITORING_NS))
elem.text = format
node.append(elem)
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"identifier",
",",
"version",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"node",
"=",
"etree",
".",
"Element",
"(",
"qualify",
"(",
"\"get-schema\"",
",",
"NETCONF_MONITORING_NS",
")",
")",
"if",
"identifier",
... | Retrieve a named schema, with optional revision and type.
*identifier* name of the schema to be retrieved
*version* version of schema to get
*format* format of the schema to be retrieved, yang is the default
:seealso: :ref:`filter_params` | [
"Retrieve",
"a",
"named",
"schema",
"with",
"optional",
"revision",
"and",
"type",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/retrieve.py#L175-L198 | train | 217,330 |
ncclient/ncclient | ncclient/devices/default.py | DefaultDeviceHandler.is_rpc_error_exempt | def is_rpc_error_exempt(self, error_text):
"""
Check whether an RPC error message is excempt, thus NOT causing an exception.
On some devices the RPC operations may indicate an error response, even though
the operation actually succeeded. This may be in cases where a warning would be
more appropriate. In that case, the client may be better advised to simply
ignore that error and not raise an exception.
Note that there is also the "raise_mode", set on session and manager, which
controls the exception-raising behaviour in case of returned errors. This error
filter here is independent of that: No matter what the raise_mode says, if the
error message matches one of the exempt errors returned here, an exception
will not be raised.
The exempt error messages are defined in the _EXEMPT_ERRORS field of the device
handler object and can be overwritten by child classes. Wild cards are
possible: Start and/or end with a '*' to indicate that the text can appear at
the start, the end or the middle of the error message to still match. All
comparisons are case insensitive.
Return True/False depending on found match.
"""
if error_text is not None:
error_text = error_text.lower().strip()
else:
error_text = 'no error given'
# Compare the error text against all the exempt errors.
for ex in self._exempt_errors_exact_match:
if error_text == ex:
return True
for ex in self._exempt_errors_startwith_wildcard_match:
if error_text.endswith(ex):
return True
for ex in self._exempt_errors_endwith_wildcard_match:
if error_text.startswith(ex):
return True
for ex in self._exempt_errors_full_wildcard_match:
if ex in error_text:
return True
return False | python | def is_rpc_error_exempt(self, error_text):
"""
Check whether an RPC error message is excempt, thus NOT causing an exception.
On some devices the RPC operations may indicate an error response, even though
the operation actually succeeded. This may be in cases where a warning would be
more appropriate. In that case, the client may be better advised to simply
ignore that error and not raise an exception.
Note that there is also the "raise_mode", set on session and manager, which
controls the exception-raising behaviour in case of returned errors. This error
filter here is independent of that: No matter what the raise_mode says, if the
error message matches one of the exempt errors returned here, an exception
will not be raised.
The exempt error messages are defined in the _EXEMPT_ERRORS field of the device
handler object and can be overwritten by child classes. Wild cards are
possible: Start and/or end with a '*' to indicate that the text can appear at
the start, the end or the middle of the error message to still match. All
comparisons are case insensitive.
Return True/False depending on found match.
"""
if error_text is not None:
error_text = error_text.lower().strip()
else:
error_text = 'no error given'
# Compare the error text against all the exempt errors.
for ex in self._exempt_errors_exact_match:
if error_text == ex:
return True
for ex in self._exempt_errors_startwith_wildcard_match:
if error_text.endswith(ex):
return True
for ex in self._exempt_errors_endwith_wildcard_match:
if error_text.startswith(ex):
return True
for ex in self._exempt_errors_full_wildcard_match:
if ex in error_text:
return True
return False | [
"def",
"is_rpc_error_exempt",
"(",
"self",
",",
"error_text",
")",
":",
"if",
"error_text",
"is",
"not",
"None",
":",
"error_text",
"=",
"error_text",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"else",
":",
"error_text",
"=",
"'no error given'",
"# Co... | Check whether an RPC error message is excempt, thus NOT causing an exception.
On some devices the RPC operations may indicate an error response, even though
the operation actually succeeded. This may be in cases where a warning would be
more appropriate. In that case, the client may be better advised to simply
ignore that error and not raise an exception.
Note that there is also the "raise_mode", set on session and manager, which
controls the exception-raising behaviour in case of returned errors. This error
filter here is independent of that: No matter what the raise_mode says, if the
error message matches one of the exempt errors returned here, an exception
will not be raised.
The exempt error messages are defined in the _EXEMPT_ERRORS field of the device
handler object and can be overwritten by child classes. Wild cards are
possible: Start and/or end with a '*' to indicate that the text can appear at
the start, the end or the middle of the error message to still match. All
comparisons are case insensitive.
Return True/False depending on found match. | [
"Check",
"whether",
"an",
"RPC",
"error",
"message",
"is",
"excempt",
"thus",
"NOT",
"causing",
"an",
"exception",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/devices/default.py#L146-L192 | train | 217,331 |
ncclient/ncclient | ncclient/devices/nexus.py | NexusDeviceHandler.get_ssh_subsystem_names | def get_ssh_subsystem_names(self):
"""
Return a list of possible SSH subsystem names.
Different NXOS versions use different SSH subsystem names for netconf.
Therefore, we return a list so that several can be tried, if necessary.
The Nexus device handler also accepts
"""
preferred_ssh_subsystem = self.device_params.get("ssh_subsystem_name")
name_list = [ "netconf", "xmlagent" ]
if preferred_ssh_subsystem:
return [ preferred_ssh_subsystem ] + \
[ n for n in name_list if n != preferred_ssh_subsystem ]
else:
return name_list | python | def get_ssh_subsystem_names(self):
"""
Return a list of possible SSH subsystem names.
Different NXOS versions use different SSH subsystem names for netconf.
Therefore, we return a list so that several can be tried, if necessary.
The Nexus device handler also accepts
"""
preferred_ssh_subsystem = self.device_params.get("ssh_subsystem_name")
name_list = [ "netconf", "xmlagent" ]
if preferred_ssh_subsystem:
return [ preferred_ssh_subsystem ] + \
[ n for n in name_list if n != preferred_ssh_subsystem ]
else:
return name_list | [
"def",
"get_ssh_subsystem_names",
"(",
"self",
")",
":",
"preferred_ssh_subsystem",
"=",
"self",
".",
"device_params",
".",
"get",
"(",
"\"ssh_subsystem_name\"",
")",
"name_list",
"=",
"[",
"\"netconf\"",
",",
"\"xmlagent\"",
"]",
"if",
"preferred_ssh_subsystem",
":... | Return a list of possible SSH subsystem names.
Different NXOS versions use different SSH subsystem names for netconf.
Therefore, we return a list so that several can be tried, if necessary.
The Nexus device handler also accepts | [
"Return",
"a",
"list",
"of",
"possible",
"SSH",
"subsystem",
"names",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/devices/nexus.py#L79-L95 | train | 217,332 |
ncclient/ncclient | ncclient/transport/session.py | Session.add_listener | def add_listener(self, listener):
"""Register a listener that will be notified of incoming messages and
errors.
:type listener: :class:`SessionListener`
"""
self.logger.debug('installing listener %r', listener)
if not isinstance(listener, SessionListener):
raise SessionError("Listener must be a SessionListener type")
with self._lock:
self._listeners.add(listener) | python | def add_listener(self, listener):
"""Register a listener that will be notified of incoming messages and
errors.
:type listener: :class:`SessionListener`
"""
self.logger.debug('installing listener %r', listener)
if not isinstance(listener, SessionListener):
raise SessionError("Listener must be a SessionListener type")
with self._lock:
self._listeners.add(listener) | [
"def",
"add_listener",
"(",
"self",
",",
"listener",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'installing listener %r'",
",",
"listener",
")",
"if",
"not",
"isinstance",
"(",
"listener",
",",
"SessionListener",
")",
":",
"raise",
"SessionError",
... | Register a listener that will be notified of incoming messages and
errors.
:type listener: :class:`SessionListener` | [
"Register",
"a",
"listener",
"that",
"will",
"be",
"notified",
"of",
"incoming",
"messages",
"and",
"errors",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/transport/session.py#L125-L135 | train | 217,333 |
ncclient/ncclient | ncclient/transport/session.py | Session.remove_listener | def remove_listener(self, listener):
"""Unregister some listener; ignore if the listener was never
registered.
:type listener: :class:`SessionListener`
"""
self.logger.debug('discarding listener %r', listener)
with self._lock:
self._listeners.discard(listener) | python | def remove_listener(self, listener):
"""Unregister some listener; ignore if the listener was never
registered.
:type listener: :class:`SessionListener`
"""
self.logger.debug('discarding listener %r', listener)
with self._lock:
self._listeners.discard(listener) | [
"def",
"remove_listener",
"(",
"self",
",",
"listener",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'discarding listener %r'",
",",
"listener",
")",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_listeners",
".",
"discard",
"(",
"listener",
")"... | Unregister some listener; ignore if the listener was never
registered.
:type listener: :class:`SessionListener` | [
"Unregister",
"some",
"listener",
";",
"ignore",
"if",
"the",
"listener",
"was",
"never",
"registered",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/transport/session.py#L137-L145 | train | 217,334 |
ncclient/ncclient | ncclient/transport/session.py | Session.get_listener_instance | def get_listener_instance(self, cls):
"""If a listener of the specified type is registered, returns the
instance.
:type cls: :class:`SessionListener`
"""
with self._lock:
for listener in self._listeners:
if isinstance(listener, cls):
return listener | python | def get_listener_instance(self, cls):
"""If a listener of the specified type is registered, returns the
instance.
:type cls: :class:`SessionListener`
"""
with self._lock:
for listener in self._listeners:
if isinstance(listener, cls):
return listener | [
"def",
"get_listener_instance",
"(",
"self",
",",
"cls",
")",
":",
"with",
"self",
".",
"_lock",
":",
"for",
"listener",
"in",
"self",
".",
"_listeners",
":",
"if",
"isinstance",
"(",
"listener",
",",
"cls",
")",
":",
"return",
"listener"
] | If a listener of the specified type is registered, returns the
instance.
:type cls: :class:`SessionListener` | [
"If",
"a",
"listener",
"of",
"the",
"specified",
"type",
"is",
"registered",
"returns",
"the",
"instance",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/transport/session.py#L147-L156 | train | 217,335 |
ncclient/ncclient | ncclient/operations/subscribe.py | CreateSubscription.request | def request(self, filter=None, stream_name=None, start_time=None, stop_time=None):
"""Creates a subscription for notifications from the server.
*filter* specifies the subset of notifications to receive (by
default all notificaitons are received)
:seealso: :ref:`filter_params`
*stream_name* specifies the notification stream name. The
default is None meaning all streams.
*start_time* triggers the notification replay feature to
replay notifications from the given time. The default is None,
meaning that this is not a replay subscription. The format is
an RFC 3339/ISO 8601 date and time.
*stop_time* indicates the end of the notifications of
interest. This parameter must be used with *start_time*. The
default is None, meaning that (if *start_time* is present) the
notifications will continue until the subscription is
terminated. The format is an RFC 3339/ISO 8601 date and time.
"""
node = new_ele_ns("create-subscription", NETCONF_NOTIFICATION_NS)
if filter is not None:
node.append(util.build_filter(filter))
if stream_name is not None:
sub_ele(node, "stream").text = stream_name
if start_time is not None:
sub_ele(node, "startTime").text = start_time
if stop_time is not None:
if start_time is None:
raise ValueError("You must provide start_time if you provide stop_time")
sub_ele(node, "stopTime").text = stop_time
return self._request(node) | python | def request(self, filter=None, stream_name=None, start_time=None, stop_time=None):
"""Creates a subscription for notifications from the server.
*filter* specifies the subset of notifications to receive (by
default all notificaitons are received)
:seealso: :ref:`filter_params`
*stream_name* specifies the notification stream name. The
default is None meaning all streams.
*start_time* triggers the notification replay feature to
replay notifications from the given time. The default is None,
meaning that this is not a replay subscription. The format is
an RFC 3339/ISO 8601 date and time.
*stop_time* indicates the end of the notifications of
interest. This parameter must be used with *start_time*. The
default is None, meaning that (if *start_time* is present) the
notifications will continue until the subscription is
terminated. The format is an RFC 3339/ISO 8601 date and time.
"""
node = new_ele_ns("create-subscription", NETCONF_NOTIFICATION_NS)
if filter is not None:
node.append(util.build_filter(filter))
if stream_name is not None:
sub_ele(node, "stream").text = stream_name
if start_time is not None:
sub_ele(node, "startTime").text = start_time
if stop_time is not None:
if start_time is None:
raise ValueError("You must provide start_time if you provide stop_time")
sub_ele(node, "stopTime").text = stop_time
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"stream_name",
"=",
"None",
",",
"start_time",
"=",
"None",
",",
"stop_time",
"=",
"None",
")",
":",
"node",
"=",
"new_ele_ns",
"(",
"\"create-subscription\"",
",",
"NETCONF_NOTIFICATION_NS",
")... | Creates a subscription for notifications from the server.
*filter* specifies the subset of notifications to receive (by
default all notificaitons are received)
:seealso: :ref:`filter_params`
*stream_name* specifies the notification stream name. The
default is None meaning all streams.
*start_time* triggers the notification replay feature to
replay notifications from the given time. The default is None,
meaning that this is not a replay subscription. The format is
an RFC 3339/ISO 8601 date and time.
*stop_time* indicates the end of the notifications of
interest. This parameter must be used with *start_time*. The
default is None, meaning that (if *start_time* is present) the
notifications will continue until the subscription is
terminated. The format is an RFC 3339/ISO 8601 date and time. | [
"Creates",
"a",
"subscription",
"for",
"notifications",
"from",
"the",
"server",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/subscribe.py#L27-L64 | train | 217,336 |
ncclient/ncclient | ncclient/operations/edit.py | DeleteConfig.request | def request(self, target):
"""Delete a configuration datastore.
*target* specifies the name or URL of configuration datastore to delete
:seealso: :ref:`srctarget_params`"""
node = new_ele("delete-config")
node.append(util.datastore_or_url("target", target, self._assert))
return self._request(node) | python | def request(self, target):
"""Delete a configuration datastore.
*target* specifies the name or URL of configuration datastore to delete
:seealso: :ref:`srctarget_params`"""
node = new_ele("delete-config")
node.append(util.datastore_or_url("target", target, self._assert))
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"target",
")",
":",
"node",
"=",
"new_ele",
"(",
"\"delete-config\"",
")",
"node",
".",
"append",
"(",
"util",
".",
"datastore_or_url",
"(",
"\"target\"",
",",
"target",
",",
"self",
".",
"_assert",
")",
")",
"return",... | Delete a configuration datastore.
*target* specifies the name or URL of configuration datastore to delete
:seealso: :ref:`srctarget_params` | [
"Delete",
"a",
"configuration",
"datastore",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/edit.py#L73-L81 | train | 217,337 |
ncclient/ncclient | ncclient/operations/edit.py | CopyConfig.request | def request(self, source, target):
"""Create or replace an entire configuration datastore with the contents of another complete
configuration datastore.
*source* is the name of the configuration datastore to use as the source of the copy operation or `config` element containing the configuration subtree to copy
*target* is the name of the configuration datastore to use as the destination of the copy operation
:seealso: :ref:`srctarget_params`"""
node = new_ele("copy-config")
node.append(util.datastore_or_url("target", target, self._assert))
try:
# datastore name or URL
node.append(util.datastore_or_url("source", source, self._assert))
except Exception:
# `source` with `config` element containing the configuration subtree to copy
node.append(validated_element(source, ("source", qualify("source"))))
return self._request(node) | python | def request(self, source, target):
"""Create or replace an entire configuration datastore with the contents of another complete
configuration datastore.
*source* is the name of the configuration datastore to use as the source of the copy operation or `config` element containing the configuration subtree to copy
*target* is the name of the configuration datastore to use as the destination of the copy operation
:seealso: :ref:`srctarget_params`"""
node = new_ele("copy-config")
node.append(util.datastore_or_url("target", target, self._assert))
try:
# datastore name or URL
node.append(util.datastore_or_url("source", source, self._assert))
except Exception:
# `source` with `config` element containing the configuration subtree to copy
node.append(validated_element(source, ("source", qualify("source"))))
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"source",
",",
"target",
")",
":",
"node",
"=",
"new_ele",
"(",
"\"copy-config\"",
")",
"node",
".",
"append",
"(",
"util",
".",
"datastore_or_url",
"(",
"\"target\"",
",",
"target",
",",
"self",
".",
"_assert",
")",
... | Create or replace an entire configuration datastore with the contents of another complete
configuration datastore.
*source* is the name of the configuration datastore to use as the source of the copy operation or `config` element containing the configuration subtree to copy
*target* is the name of the configuration datastore to use as the destination of the copy operation
:seealso: :ref:`srctarget_params` | [
"Create",
"or",
"replace",
"an",
"entire",
"configuration",
"datastore",
"with",
"the",
"contents",
"of",
"another",
"complete",
"configuration",
"datastore",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/edit.py#L87-L106 | train | 217,338 |
ncclient/ncclient | ncclient/operations/edit.py | Validate.request | def request(self, source="candidate"):
"""Validate the contents of the specified configuration.
*source* is the name of the configuration datastore being validated or `config` element containing the configuration subtree to be validated
:seealso: :ref:`srctarget_params`"""
node = new_ele("validate")
if type(source) is str:
src = util.datastore_or_url("source", source, self._assert)
else:
validated_element(source, ("config", qualify("config")))
src = new_ele("source")
src.append(source)
node.append(src)
return self._request(node) | python | def request(self, source="candidate"):
"""Validate the contents of the specified configuration.
*source* is the name of the configuration datastore being validated or `config` element containing the configuration subtree to be validated
:seealso: :ref:`srctarget_params`"""
node = new_ele("validate")
if type(source) is str:
src = util.datastore_or_url("source", source, self._assert)
else:
validated_element(source, ("config", qualify("config")))
src = new_ele("source")
src.append(source)
node.append(src)
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"source",
"=",
"\"candidate\"",
")",
":",
"node",
"=",
"new_ele",
"(",
"\"validate\"",
")",
"if",
"type",
"(",
"source",
")",
"is",
"str",
":",
"src",
"=",
"util",
".",
"datastore_or_url",
"(",
"\"source\"",
",",
"so... | Validate the contents of the specified configuration.
*source* is the name of the configuration datastore being validated or `config` element containing the configuration subtree to be validated
:seealso: :ref:`srctarget_params` | [
"Validate",
"the",
"contents",
"of",
"the",
"specified",
"configuration",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/edit.py#L114-L128 | train | 217,339 |
ncclient/ncclient | ncclient/operations/lock.py | Lock.request | def request(self, target="candidate"):
"""Allows the client to lock the configuration system of a device.
*target* is the name of the configuration datastore to lock
"""
node = new_ele("lock")
sub_ele(sub_ele(node, "target"), target)
return self._request(node) | python | def request(self, target="candidate"):
"""Allows the client to lock the configuration system of a device.
*target* is the name of the configuration datastore to lock
"""
node = new_ele("lock")
sub_ele(sub_ele(node, "target"), target)
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"target",
"=",
"\"candidate\"",
")",
":",
"node",
"=",
"new_ele",
"(",
"\"lock\"",
")",
"sub_ele",
"(",
"sub_ele",
"(",
"node",
",",
"\"target\"",
")",
",",
"target",
")",
"return",
"self",
".",
"_request",
"(",
"nod... | Allows the client to lock the configuration system of a device.
*target* is the name of the configuration datastore to lock | [
"Allows",
"the",
"client",
"to",
"lock",
"the",
"configuration",
"system",
"of",
"a",
"device",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/lock.py#L28-L35 | train | 217,340 |
ncclient/ncclient | ncclient/transport/ssh.py | SSHSession._parse10 | def _parse10(self):
"""Messages are delimited by MSG_DELIM. The buffer could have grown by
a maximum of BUF_SIZE bytes everytime this method is called. Retains
state across method calls and if a chunk has been read it will not be
considered again."""
self.logger.debug("parsing netconf v1.0")
buf = self._buffer
buf.seek(self._parsing_pos10)
if MSG_DELIM in buf.read().decode('UTF-8'):
buf.seek(0)
msg, _, remaining = buf.read().decode('UTF-8').partition(MSG_DELIM)
msg = msg.strip()
if sys.version < '3':
self._dispatch_message(msg.encode())
else:
self._dispatch_message(msg)
# create new buffer which contains remaining of old buffer
self._buffer = StringIO()
self._buffer.write(remaining.encode())
self._parsing_pos10 = 0
if len(remaining) > 0:
# There could be another entire message in the
# buffer, so we should try to parse again.
self.logger.debug('Trying another round of parsing since there is still data')
self._parse10()
else:
# handle case that MSG_DELIM is split over two chunks
self._parsing_pos10 = buf.tell() - MSG_DELIM_LEN
if self._parsing_pos10 < 0:
self._parsing_pos10 = 0 | python | def _parse10(self):
"""Messages are delimited by MSG_DELIM. The buffer could have grown by
a maximum of BUF_SIZE bytes everytime this method is called. Retains
state across method calls and if a chunk has been read it will not be
considered again."""
self.logger.debug("parsing netconf v1.0")
buf = self._buffer
buf.seek(self._parsing_pos10)
if MSG_DELIM in buf.read().decode('UTF-8'):
buf.seek(0)
msg, _, remaining = buf.read().decode('UTF-8').partition(MSG_DELIM)
msg = msg.strip()
if sys.version < '3':
self._dispatch_message(msg.encode())
else:
self._dispatch_message(msg)
# create new buffer which contains remaining of old buffer
self._buffer = StringIO()
self._buffer.write(remaining.encode())
self._parsing_pos10 = 0
if len(remaining) > 0:
# There could be another entire message in the
# buffer, so we should try to parse again.
self.logger.debug('Trying another round of parsing since there is still data')
self._parse10()
else:
# handle case that MSG_DELIM is split over two chunks
self._parsing_pos10 = buf.tell() - MSG_DELIM_LEN
if self._parsing_pos10 < 0:
self._parsing_pos10 = 0 | [
"def",
"_parse10",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"parsing netconf v1.0\"",
")",
"buf",
"=",
"self",
".",
"_buffer",
"buf",
".",
"seek",
"(",
"self",
".",
"_parsing_pos10",
")",
"if",
"MSG_DELIM",
"in",
"buf",
".",
"... | Messages are delimited by MSG_DELIM. The buffer could have grown by
a maximum of BUF_SIZE bytes everytime this method is called. Retains
state across method calls and if a chunk has been read it will not be
considered again. | [
"Messages",
"are",
"delimited",
"by",
"MSG_DELIM",
".",
"The",
"buffer",
"could",
"have",
"grown",
"by",
"a",
"maximum",
"of",
"BUF_SIZE",
"bytes",
"everytime",
"this",
"method",
"is",
"called",
".",
"Retains",
"state",
"across",
"method",
"calls",
"and",
"i... | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/transport/ssh.py#L139-L170 | train | 217,341 |
ncclient/ncclient | ncclient/operations/util.py | one_of | def one_of(*args):
"Verifies that only one of the arguments is not None"
for i, arg in enumerate(args):
if arg is not None:
for argh in args[i+1:]:
if argh is not None:
raise OperationError("Too many parameters")
else:
return
raise OperationError("Insufficient parameters") | python | def one_of(*args):
"Verifies that only one of the arguments is not None"
for i, arg in enumerate(args):
if arg is not None:
for argh in args[i+1:]:
if argh is not None:
raise OperationError("Too many parameters")
else:
return
raise OperationError("Insufficient parameters") | [
"def",
"one_of",
"(",
"*",
"args",
")",
":",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"arg",
"is",
"not",
"None",
":",
"for",
"argh",
"in",
"args",
"[",
"i",
"+",
"1",
":",
"]",
":",
"if",
"argh",
"is",
"not",
... | Verifies that only one of the arguments is not None | [
"Verifies",
"that",
"only",
"one",
"of",
"the",
"arguments",
"is",
"not",
"None"
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/util.py#L21-L30 | train | 217,342 |
RJT1990/pyflux | pyflux/arma/arimax.py | ARIMAX._get_scale_and_shape | def _get_scale_and_shape(self, transformed_lvs):
""" Obtains model scale, shape and skewness latent variables
Parameters
----------
transformed_lvs : np.array
Transformed latent variable vector
Returns
----------
- Tuple of model scale, model shape, model skewness
"""
if self.scale is True:
if self.shape is True:
model_shape = transformed_lvs[-1]
model_scale = transformed_lvs[-2]
else:
model_shape = 0
model_scale = transformed_lvs[-1]
else:
model_scale = 0
model_shape = 0
if self.skewness is True:
model_skewness = transformed_lvs[-3]
else:
model_skewness = 0
return model_scale, model_shape, model_skewness | python | def _get_scale_and_shape(self, transformed_lvs):
""" Obtains model scale, shape and skewness latent variables
Parameters
----------
transformed_lvs : np.array
Transformed latent variable vector
Returns
----------
- Tuple of model scale, model shape, model skewness
"""
if self.scale is True:
if self.shape is True:
model_shape = transformed_lvs[-1]
model_scale = transformed_lvs[-2]
else:
model_shape = 0
model_scale = transformed_lvs[-1]
else:
model_scale = 0
model_shape = 0
if self.skewness is True:
model_skewness = transformed_lvs[-3]
else:
model_skewness = 0
return model_scale, model_shape, model_skewness | [
"def",
"_get_scale_and_shape",
"(",
"self",
",",
"transformed_lvs",
")",
":",
"if",
"self",
".",
"scale",
"is",
"True",
":",
"if",
"self",
".",
"shape",
"is",
"True",
":",
"model_shape",
"=",
"transformed_lvs",
"[",
"-",
"1",
"]",
"model_scale",
"=",
"tr... | Obtains model scale, shape and skewness latent variables
Parameters
----------
transformed_lvs : np.array
Transformed latent variable vector
Returns
----------
- Tuple of model scale, model shape, model skewness | [
"Obtains",
"model",
"scale",
"shape",
"and",
"skewness",
"latent",
"variables"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/arimax.py#L152-L181 | train | 217,343 |
RJT1990/pyflux | pyflux/arma/arimax.py | ARIMAX._get_scale_and_shape_sim | def _get_scale_and_shape_sim(self, transformed_lvs):
""" Obtains model scale, shape, skewness latent variables for
a 2d array of simulations.
Parameters
----------
transformed_lvs : np.array
Transformed latent variable vector (2d - with draws of each variable)
Returns
----------
- Tuple of np.arrays (each being scale, shape and skewness draws)
"""
if self.scale is True:
if self.shape is True:
model_shape = self.latent_variables.z_list[-1].prior.transform(transformed_lvs[-1, :])
model_scale = self.latent_variables.z_list[-2].prior.transform(transformed_lvs[-2, :])
else:
model_shape = np.zeros(transformed_lvs.shape[1])
model_scale = self.latent_variables.z_list[-1].prior.transform(transformed_lvs[-1, :])
else:
model_scale = np.zeros(transformed_lvs.shape[1])
model_shape = np.zeros(transformed_lvs.shape[1])
if self.skewness is True:
model_skewness = self.latent_variables.z_list[-3].prior.transform(transformed_lvs[-3, :])
else:
model_skewness = np.zeros(transformed_lvs.shape[1])
return model_scale, model_shape, model_skewness | python | def _get_scale_and_shape_sim(self, transformed_lvs):
""" Obtains model scale, shape, skewness latent variables for
a 2d array of simulations.
Parameters
----------
transformed_lvs : np.array
Transformed latent variable vector (2d - with draws of each variable)
Returns
----------
- Tuple of np.arrays (each being scale, shape and skewness draws)
"""
if self.scale is True:
if self.shape is True:
model_shape = self.latent_variables.z_list[-1].prior.transform(transformed_lvs[-1, :])
model_scale = self.latent_variables.z_list[-2].prior.transform(transformed_lvs[-2, :])
else:
model_shape = np.zeros(transformed_lvs.shape[1])
model_scale = self.latent_variables.z_list[-1].prior.transform(transformed_lvs[-1, :])
else:
model_scale = np.zeros(transformed_lvs.shape[1])
model_shape = np.zeros(transformed_lvs.shape[1])
if self.skewness is True:
model_skewness = self.latent_variables.z_list[-3].prior.transform(transformed_lvs[-3, :])
else:
model_skewness = np.zeros(transformed_lvs.shape[1])
return model_scale, model_shape, model_skewness | [
"def",
"_get_scale_and_shape_sim",
"(",
"self",
",",
"transformed_lvs",
")",
":",
"if",
"self",
".",
"scale",
"is",
"True",
":",
"if",
"self",
".",
"shape",
"is",
"True",
":",
"model_shape",
"=",
"self",
".",
"latent_variables",
".",
"z_list",
"[",
"-",
... | Obtains model scale, shape, skewness latent variables for
a 2d array of simulations.
Parameters
----------
transformed_lvs : np.array
Transformed latent variable vector (2d - with draws of each variable)
Returns
----------
- Tuple of np.arrays (each being scale, shape and skewness draws) | [
"Obtains",
"model",
"scale",
"shape",
"skewness",
"latent",
"variables",
"for",
"a",
"2d",
"array",
"of",
"simulations",
"."
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/arimax.py#L183-L213 | train | 217,344 |
RJT1990/pyflux | pyflux/arma/arimax.py | ARIMAX._summarize_simulations | def _summarize_simulations(self, mean_values, sim_vector, date_index, h, past_values):
""" Produces forecasted values to plot, along with prediction intervals
This is a utility function that constructs the prediction intervals and other quantities
used for plot_predict() in particular.
Parameters
----------
mean_values : np.ndarray
Mean predictions for h-step ahead forecasts
sim_vector : np.ndarray
N simulation predictions for h-step ahead forecasts
date_index : pd.DateIndex or np.ndarray
Dates for the simulations
h : int
How many steps ahead are forecast
past_values : int
How many past observations to include in the forecast plot
"""
error_bars = []
for pre in range(5,100,5):
error_bars.append(np.insert([np.percentile(i,pre) for i in sim_vector], 0, mean_values[-h-1]))
if self.latent_variables.estimation_method in ['M-H']:
forecasted_values = np.insert([np.mean(i) for i in sim_vector], 0, mean_values[-h-1])
else:
forecasted_values = mean_values[-h-1:]
plot_values = mean_values[-h-past_values:]
plot_index = date_index[-h-past_values:]
return error_bars, forecasted_values, plot_values, plot_index | python | def _summarize_simulations(self, mean_values, sim_vector, date_index, h, past_values):
""" Produces forecasted values to plot, along with prediction intervals
This is a utility function that constructs the prediction intervals and other quantities
used for plot_predict() in particular.
Parameters
----------
mean_values : np.ndarray
Mean predictions for h-step ahead forecasts
sim_vector : np.ndarray
N simulation predictions for h-step ahead forecasts
date_index : pd.DateIndex or np.ndarray
Dates for the simulations
h : int
How many steps ahead are forecast
past_values : int
How many past observations to include in the forecast plot
"""
error_bars = []
for pre in range(5,100,5):
error_bars.append(np.insert([np.percentile(i,pre) for i in sim_vector], 0, mean_values[-h-1]))
if self.latent_variables.estimation_method in ['M-H']:
forecasted_values = np.insert([np.mean(i) for i in sim_vector], 0, mean_values[-h-1])
else:
forecasted_values = mean_values[-h-1:]
plot_values = mean_values[-h-past_values:]
plot_index = date_index[-h-past_values:]
return error_bars, forecasted_values, plot_values, plot_index | [
"def",
"_summarize_simulations",
"(",
"self",
",",
"mean_values",
",",
"sim_vector",
",",
"date_index",
",",
"h",
",",
"past_values",
")",
":",
"error_bars",
"=",
"[",
"]",
"for",
"pre",
"in",
"range",
"(",
"5",
",",
"100",
",",
"5",
")",
":",
"error_b... | Produces forecasted values to plot, along with prediction intervals
This is a utility function that constructs the prediction intervals and other quantities
used for plot_predict() in particular.
Parameters
----------
mean_values : np.ndarray
Mean predictions for h-step ahead forecasts
sim_vector : np.ndarray
N simulation predictions for h-step ahead forecasts
date_index : pd.DateIndex or np.ndarray
Dates for the simulations
h : int
How many steps ahead are forecast
past_values : int
How many past observations to include in the forecast plot | [
"Produces",
"forecasted",
"values",
"to",
"plot",
"along",
"with",
"prediction",
"intervals"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/arimax.py#L606-L639 | train | 217,345 |
RJT1990/pyflux | pyflux/arma/arimax.py | ARIMAX.normal_neg_loglik | def normal_neg_loglik(self, beta):
""" Calculates the negative log-likelihood of the model for Normal family
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model
"""
mu, Y = self._model(beta)
return -np.sum(ss.norm.logpdf(Y, loc=mu, scale=self.latent_variables.z_list[-1].prior.transform(beta[-1]))) | python | def normal_neg_loglik(self, beta):
""" Calculates the negative log-likelihood of the model for Normal family
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model
"""
mu, Y = self._model(beta)
return -np.sum(ss.norm.logpdf(Y, loc=mu, scale=self.latent_variables.z_list[-1].prior.transform(beta[-1]))) | [
"def",
"normal_neg_loglik",
"(",
"self",
",",
"beta",
")",
":",
"mu",
",",
"Y",
"=",
"self",
".",
"_model",
"(",
"beta",
")",
"return",
"-",
"np",
".",
"sum",
"(",
"ss",
".",
"norm",
".",
"logpdf",
"(",
"Y",
",",
"loc",
"=",
"mu",
",",
"scale",... | Calculates the negative log-likelihood of the model for Normal family
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model | [
"Calculates",
"the",
"negative",
"log",
"-",
"likelihood",
"of",
"the",
"model",
"for",
"Normal",
"family"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/arimax.py#L641-L654 | train | 217,346 |
RJT1990/pyflux | pyflux/arma/arimax.py | ARIMAX.normal_mb_neg_loglik | def normal_mb_neg_loglik(self, beta, mini_batch):
""" Calculates the negative log-likelihood of the Normal model for a minibatch
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
mini_batch : int
Size of each mini batch of data
Returns
----------
The negative logliklihood of the model
"""
mu, Y = self._mb_model(beta, mini_batch)
return -np.sum(ss.norm.logpdf(Y, loc=mu, scale=self.latent_variables.z_list[-1].prior.transform(beta[-1]))) | python | def normal_mb_neg_loglik(self, beta, mini_batch):
""" Calculates the negative log-likelihood of the Normal model for a minibatch
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
mini_batch : int
Size of each mini batch of data
Returns
----------
The negative logliklihood of the model
"""
mu, Y = self._mb_model(beta, mini_batch)
return -np.sum(ss.norm.logpdf(Y, loc=mu, scale=self.latent_variables.z_list[-1].prior.transform(beta[-1]))) | [
"def",
"normal_mb_neg_loglik",
"(",
"self",
",",
"beta",
",",
"mini_batch",
")",
":",
"mu",
",",
"Y",
"=",
"self",
".",
"_mb_model",
"(",
"beta",
",",
"mini_batch",
")",
"return",
"-",
"np",
".",
"sum",
"(",
"ss",
".",
"norm",
".",
"logpdf",
"(",
"... | Calculates the negative log-likelihood of the Normal model for a minibatch
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
mini_batch : int
Size of each mini batch of data
Returns
----------
The negative logliklihood of the model | [
"Calculates",
"the",
"negative",
"log",
"-",
"likelihood",
"of",
"the",
"Normal",
"model",
"for",
"a",
"minibatch"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/arimax.py#L656-L673 | train | 217,347 |
RJT1990/pyflux | pyflux/families/skewt.py | Skewt.draw_variable | def draw_variable(loc, scale, shape, skewness, nsims):
""" Draws random variables from Skew t distribution
Parameters
----------
loc : float
location parameter for the distribution
scale : float
scale parameter for the distribution
shape : float
tail thickness parameter for the distribution
skewness : float
skewness parameter for the distribution
nsims : int or list
number of draws to take from the distribution
Returns
----------
- Random draws from the distribution
"""
return loc + scale*Skewt.rvs(shape, skewness, nsims) | python | def draw_variable(loc, scale, shape, skewness, nsims):
""" Draws random variables from Skew t distribution
Parameters
----------
loc : float
location parameter for the distribution
scale : float
scale parameter for the distribution
shape : float
tail thickness parameter for the distribution
skewness : float
skewness parameter for the distribution
nsims : int or list
number of draws to take from the distribution
Returns
----------
- Random draws from the distribution
"""
return loc + scale*Skewt.rvs(shape, skewness, nsims) | [
"def",
"draw_variable",
"(",
"loc",
",",
"scale",
",",
"shape",
",",
"skewness",
",",
"nsims",
")",
":",
"return",
"loc",
"+",
"scale",
"*",
"Skewt",
".",
"rvs",
"(",
"shape",
",",
"skewness",
",",
"nsims",
")"
] | Draws random variables from Skew t distribution
Parameters
----------
loc : float
location parameter for the distribution
scale : float
scale parameter for the distribution
shape : float
tail thickness parameter for the distribution
skewness : float
skewness parameter for the distribution
nsims : int or list
number of draws to take from the distribution
Returns
----------
- Random draws from the distribution | [
"Draws",
"random",
"variables",
"from",
"Skew",
"t",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L138-L162 | train | 217,348 |
RJT1990/pyflux | pyflux/families/skewt.py | Skewt.first_order_score | def first_order_score(y, mean, scale, shape, skewness):
""" GAS Skew t Update term using gradient only - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Skew t distribution
scale : float
scale parameter for the Skew t distribution
shape : float
tail thickness parameter for the Skew t distribution
skewness : float
skewness parameter for the Skew t distribution
Returns
----------
- Score of the Skew t family
"""
m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))
mean = mean + (skewness - (1.0/skewness))*scale*m1
if (y-mean)>=0:
return ((shape+1)/shape)*(y-mean)/(np.power(skewness*scale,2) + (np.power(y-mean,2)/shape))
else:
return ((shape+1)/shape)*(y-mean)/(np.power(scale,2) + (np.power(skewness*(y-mean),2)/shape)) | python | def first_order_score(y, mean, scale, shape, skewness):
""" GAS Skew t Update term using gradient only - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Skew t distribution
scale : float
scale parameter for the Skew t distribution
shape : float
tail thickness parameter for the Skew t distribution
skewness : float
skewness parameter for the Skew t distribution
Returns
----------
- Score of the Skew t family
"""
m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))
mean = mean + (skewness - (1.0/skewness))*scale*m1
if (y-mean)>=0:
return ((shape+1)/shape)*(y-mean)/(np.power(skewness*scale,2) + (np.power(y-mean,2)/shape))
else:
return ((shape+1)/shape)*(y-mean)/(np.power(scale,2) + (np.power(skewness*(y-mean),2)/shape)) | [
"def",
"first_order_score",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"m1",
"=",
"(",
"np",
".",
"sqrt",
"(",
"shape",
")",
"*",
"sp",
".",
"gamma",
"(",
"(",
"shape",
"-",
"1.0",
")",
"/",
"2.0",
")",
")",
... | GAS Skew t Update term using gradient only - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Skew t distribution
scale : float
scale parameter for the Skew t distribution
shape : float
tail thickness parameter for the Skew t distribution
skewness : float
skewness parameter for the Skew t distribution
Returns
----------
- Score of the Skew t family | [
"GAS",
"Skew",
"t",
"Update",
"term",
"using",
"gradient",
"only",
"-",
"native",
"Python",
"function"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L165-L194 | train | 217,349 |
RJT1990/pyflux | pyflux/families/skewt.py | Skewt.rvs | def rvs(df, gamma, n):
""" Generates random variables from a Skew t distribution
Parameters
----------
df : float
degrees of freedom parameter
gamma : float
skewness parameter
n : int or list
Number of simulations to perform; if list input, produces array
"""
if type(n) == list:
u = np.random.uniform(size=n[0]*n[1])
result = Skewt.ppf(q=u, df=df, gamma=gamma)
result = np.split(result,n[0])
return np.array(result)
else:
u = np.random.uniform(size=n)
if isinstance(df, np.ndarray) or isinstance(gamma, np.ndarray):
return np.array([Skewt.ppf(q=np.array([u[i]]), df=df[i], gamma=gamma[i])[0] for i in range(n)])
else:
return Skewt.ppf(q=u, df=df, gamma=gamma) | python | def rvs(df, gamma, n):
""" Generates random variables from a Skew t distribution
Parameters
----------
df : float
degrees of freedom parameter
gamma : float
skewness parameter
n : int or list
Number of simulations to perform; if list input, produces array
"""
if type(n) == list:
u = np.random.uniform(size=n[0]*n[1])
result = Skewt.ppf(q=u, df=df, gamma=gamma)
result = np.split(result,n[0])
return np.array(result)
else:
u = np.random.uniform(size=n)
if isinstance(df, np.ndarray) or isinstance(gamma, np.ndarray):
return np.array([Skewt.ppf(q=np.array([u[i]]), df=df[i], gamma=gamma[i])[0] for i in range(n)])
else:
return Skewt.ppf(q=u, df=df, gamma=gamma) | [
"def",
"rvs",
"(",
"df",
",",
"gamma",
",",
"n",
")",
":",
"if",
"type",
"(",
"n",
")",
"==",
"list",
":",
"u",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"n",
"[",
"0",
"]",
"*",
"n",
"[",
"1",
"]",
")",
"result",
"=",
... | Generates random variables from a Skew t distribution
Parameters
----------
df : float
degrees of freedom parameter
gamma : float
skewness parameter
n : int or list
Number of simulations to perform; if list input, produces array | [
"Generates",
"random",
"variables",
"from",
"a",
"Skew",
"t",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L197-L223 | train | 217,350 |
RJT1990/pyflux | pyflux/families/skewt.py | Skewt.logpdf | def logpdf(self, mu):
"""
Log PDF for Skew t prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = self.transform(mu)
return self.logpdf_internal_prior(mu, df=self.df0, loc=self.loc0, scale=self.scale0, gamma=self.gamma0) | python | def logpdf(self, mu):
"""
Log PDF for Skew t prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = self.transform(mu)
return self.logpdf_internal_prior(mu, df=self.df0, loc=self.loc0, scale=self.scale0, gamma=self.gamma0) | [
"def",
"logpdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"self",
".",
"logpdf_internal_prior",
"(",
"mu",
",",
"df",
"=",
"self",
"."... | Log PDF for Skew t prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu)) | [
"Log",
"PDF",
"for",
"Skew",
"t",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L239-L254 | train | 217,351 |
RJT1990/pyflux | pyflux/families/skewt.py | Skewt.markov_blanket | def markov_blanket(y, mean, scale, shape, skewness):
""" Markov blanket for each likelihood term
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Skew t distribution
scale : float
scale parameter for the Skew t distribution
shape : float
tail thickness parameter for the Skew t distribution
skewness : float
skewness parameter for the Skew t distribution
Returns
----------
- Markov blanket of the Skew t family
"""
m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))
mean = mean + (skewness - (1.0/skewness))*scale*m1
return Skewt.logpdf_internal(x=y, df=shape, loc=mean, gamma=skewness, scale=scale) | python | def markov_blanket(y, mean, scale, shape, skewness):
""" Markov blanket for each likelihood term
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Skew t distribution
scale : float
scale parameter for the Skew t distribution
shape : float
tail thickness parameter for the Skew t distribution
skewness : float
skewness parameter for the Skew t distribution
Returns
----------
- Markov blanket of the Skew t family
"""
m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))
mean = mean + (skewness - (1.0/skewness))*scale*m1
return Skewt.logpdf_internal(x=y, df=shape, loc=mean, gamma=skewness, scale=scale) | [
"def",
"markov_blanket",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"m1",
"=",
"(",
"np",
".",
"sqrt",
"(",
"shape",
")",
"*",
"sp",
".",
"gamma",
"(",
"(",
"shape",
"-",
"1.0",
")",
"/",
"2.0",
")",
")",
"/... | Markov blanket for each likelihood term
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Skew t distribution
scale : float
scale parameter for the Skew t distribution
shape : float
tail thickness parameter for the Skew t distribution
skewness : float
skewness parameter for the Skew t distribution
Returns
----------
- Markov blanket of the Skew t family | [
"Markov",
"blanket",
"for",
"each",
"likelihood",
"term"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L257-L283 | train | 217,352 |
RJT1990/pyflux | pyflux/families/skewt.py | Skewt.pdf_internal | def pdf_internal(x, df, loc=0.0, scale=1.0, gamma = 1.0):
"""
Raw PDF function for the Skew t distribution
"""
result = np.zeros(x.shape[0])
result[x<0] = 2.0/(gamma + 1.0/gamma)*stats.t.pdf(x=gamma*x[(x-loc) < 0], loc=loc[(x-loc) < 0]*gamma,df=df, scale=scale)
result[x>=0] = 2.0/(gamma + 1.0/gamma)*stats.t.pdf(x=x[(x-loc) >= 0]/gamma, loc=loc[(x-loc) >= 0]/gamma,df=df, scale=scale)
return result | python | def pdf_internal(x, df, loc=0.0, scale=1.0, gamma = 1.0):
"""
Raw PDF function for the Skew t distribution
"""
result = np.zeros(x.shape[0])
result[x<0] = 2.0/(gamma + 1.0/gamma)*stats.t.pdf(x=gamma*x[(x-loc) < 0], loc=loc[(x-loc) < 0]*gamma,df=df, scale=scale)
result[x>=0] = 2.0/(gamma + 1.0/gamma)*stats.t.pdf(x=x[(x-loc) >= 0]/gamma, loc=loc[(x-loc) >= 0]/gamma,df=df, scale=scale)
return result | [
"def",
"pdf_internal",
"(",
"x",
",",
"df",
",",
"loc",
"=",
"0.0",
",",
"scale",
"=",
"1.0",
",",
"gamma",
"=",
"1.0",
")",
":",
"result",
"=",
"np",
".",
"zeros",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
")",
"result",
"[",
"x",
"<",
"0",
"... | Raw PDF function for the Skew t distribution | [
"Raw",
"PDF",
"function",
"for",
"the",
"Skew",
"t",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L340-L347 | train | 217,353 |
RJT1990/pyflux | pyflux/families/skewt.py | Skewt.pdf | def pdf(self, mu):
"""
PDF for Skew t prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu)
"""
if self.transform is not None:
mu = self.transform(mu)
return self.pdf_internal(mu, df=self.df0, loc=self.loc0, scale=self.scale0, gamma=self.gamma0) | python | def pdf(self, mu):
"""
PDF for Skew t prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu)
"""
if self.transform is not None:
mu = self.transform(mu)
return self.pdf_internal(mu, df=self.df0, loc=self.loc0, scale=self.scale0, gamma=self.gamma0) | [
"def",
"pdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"self",
".",
"pdf_internal",
"(",
"mu",
",",
"df",
"=",
"self",
".",
"df0",
... | PDF for Skew t prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu) | [
"PDF",
"for",
"Skew",
"t",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L349-L364 | train | 217,354 |
RJT1990/pyflux | pyflux/families/skewt.py | Skewt.cdf | def cdf(x, df, loc=0.0, scale=1.0, gamma = 1.0):
"""
CDF function for Skew t distribution
"""
result = np.zeros(x.shape[0])
result[x<0] = 2.0/(np.power(gamma,2) + 1.0)*ss.t.cdf(gamma*(x[x-loc < 0]-loc[x-loc < 0])/scale, df=df)
result[x>=0] = 1.0/(np.power(gamma,2) + 1.0) + 2.0/((1.0/np.power(gamma,2)) + 1.0)*(ss.t.cdf((x[x-loc >= 0]-loc[x-loc >= 0])/(gamma*scale), df=df)-0.5)
return result | python | def cdf(x, df, loc=0.0, scale=1.0, gamma = 1.0):
"""
CDF function for Skew t distribution
"""
result = np.zeros(x.shape[0])
result[x<0] = 2.0/(np.power(gamma,2) + 1.0)*ss.t.cdf(gamma*(x[x-loc < 0]-loc[x-loc < 0])/scale, df=df)
result[x>=0] = 1.0/(np.power(gamma,2) + 1.0) + 2.0/((1.0/np.power(gamma,2)) + 1.0)*(ss.t.cdf((x[x-loc >= 0]-loc[x-loc >= 0])/(gamma*scale), df=df)-0.5)
return result | [
"def",
"cdf",
"(",
"x",
",",
"df",
",",
"loc",
"=",
"0.0",
",",
"scale",
"=",
"1.0",
",",
"gamma",
"=",
"1.0",
")",
":",
"result",
"=",
"np",
".",
"zeros",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
")",
"result",
"[",
"x",
"<",
"0",
"]",
"="... | CDF function for Skew t distribution | [
"CDF",
"function",
"for",
"Skew",
"t",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L434-L441 | train | 217,355 |
RJT1990/pyflux | pyflux/families/skewt.py | Skewt.ppf | def ppf(q, df, loc=0.0, scale=1.0, gamma = 1.0):
"""
PPF function for Skew t distribution
"""
result = np.zeros(q.shape[0])
probzero = Skewt.cdf(x=np.zeros(1),loc=np.zeros(1),df=df,gamma=gamma)
result[q<probzero] = 1.0/gamma*ss.t.ppf(((np.power(gamma,2) + 1.0) * q[q<probzero])/2.0,df)
result[q>=probzero] = gamma*ss.t.ppf((1.0 + 1.0/np.power(gamma,2))/2.0*(q[q >= probzero] - probzero) + 0.5, df)
return result | python | def ppf(q, df, loc=0.0, scale=1.0, gamma = 1.0):
"""
PPF function for Skew t distribution
"""
result = np.zeros(q.shape[0])
probzero = Skewt.cdf(x=np.zeros(1),loc=np.zeros(1),df=df,gamma=gamma)
result[q<probzero] = 1.0/gamma*ss.t.ppf(((np.power(gamma,2) + 1.0) * q[q<probzero])/2.0,df)
result[q>=probzero] = gamma*ss.t.ppf((1.0 + 1.0/np.power(gamma,2))/2.0*(q[q >= probzero] - probzero) + 0.5, df)
return result | [
"def",
"ppf",
"(",
"q",
",",
"df",
",",
"loc",
"=",
"0.0",
",",
"scale",
"=",
"1.0",
",",
"gamma",
"=",
"1.0",
")",
":",
"result",
"=",
"np",
".",
"zeros",
"(",
"q",
".",
"shape",
"[",
"0",
"]",
")",
"probzero",
"=",
"Skewt",
".",
"cdf",
"(... | PPF function for Skew t distribution | [
"PPF",
"function",
"for",
"Skew",
"t",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L444-L452 | train | 217,356 |
RJT1990/pyflux | pyflux/families/family.py | Family.transform_define | def transform_define(transform):
"""
This function links the user's choice of transformation with the associated numpy function
"""
if transform == 'tanh':
return np.tanh
elif transform == 'exp':
return np.exp
elif transform == 'logit':
return Family.ilogit
elif transform is None:
return np.array
else:
return None | python | def transform_define(transform):
"""
This function links the user's choice of transformation with the associated numpy function
"""
if transform == 'tanh':
return np.tanh
elif transform == 'exp':
return np.exp
elif transform == 'logit':
return Family.ilogit
elif transform is None:
return np.array
else:
return None | [
"def",
"transform_define",
"(",
"transform",
")",
":",
"if",
"transform",
"==",
"'tanh'",
":",
"return",
"np",
".",
"tanh",
"elif",
"transform",
"==",
"'exp'",
":",
"return",
"np",
".",
"exp",
"elif",
"transform",
"==",
"'logit'",
":",
"return",
"Family",
... | This function links the user's choice of transformation with the associated numpy function | [
"This",
"function",
"links",
"the",
"user",
"s",
"choice",
"of",
"transformation",
"with",
"the",
"associated",
"numpy",
"function"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/family.py#L26-L39 | train | 217,357 |
RJT1990/pyflux | pyflux/families/family.py | Family.itransform_define | def itransform_define(transform):
"""
This function links the user's choice of transformation with its inverse
"""
if transform == 'tanh':
return np.arctanh
elif transform == 'exp':
return np.log
elif transform == 'logit':
return Family.logit
elif transform is None:
return np.array
else:
return None | python | def itransform_define(transform):
"""
This function links the user's choice of transformation with its inverse
"""
if transform == 'tanh':
return np.arctanh
elif transform == 'exp':
return np.log
elif transform == 'logit':
return Family.logit
elif transform is None:
return np.array
else:
return None | [
"def",
"itransform_define",
"(",
"transform",
")",
":",
"if",
"transform",
"==",
"'tanh'",
":",
"return",
"np",
".",
"arctanh",
"elif",
"transform",
"==",
"'exp'",
":",
"return",
"np",
".",
"log",
"elif",
"transform",
"==",
"'logit'",
":",
"return",
"Famil... | This function links the user's choice of transformation with its inverse | [
"This",
"function",
"links",
"the",
"user",
"s",
"choice",
"of",
"transformation",
"with",
"its",
"inverse"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/family.py#L42-L55 | train | 217,358 |
RJT1990/pyflux | pyflux/gpnarx/gpnarx.py | GPNARX._L | def _L(self, parm):
""" Creates cholesky decomposition of covariance matrix
Parameters
----------
parm : np.array
Contains transformed latent variables
Returns
----------
The cholesky decomposition (L) of K
"""
return np.linalg.cholesky(self.kernel.K(parm) + np.identity(self.X().shape[1])*parm[0]) | python | def _L(self, parm):
""" Creates cholesky decomposition of covariance matrix
Parameters
----------
parm : np.array
Contains transformed latent variables
Returns
----------
The cholesky decomposition (L) of K
"""
return np.linalg.cholesky(self.kernel.K(parm) + np.identity(self.X().shape[1])*parm[0]) | [
"def",
"_L",
"(",
"self",
",",
"parm",
")",
":",
"return",
"np",
".",
"linalg",
".",
"cholesky",
"(",
"self",
".",
"kernel",
".",
"K",
"(",
"parm",
")",
"+",
"np",
".",
"identity",
"(",
"self",
".",
"X",
"(",
")",
".",
"shape",
"[",
"1",
"]",... | Creates cholesky decomposition of covariance matrix
Parameters
----------
parm : np.array
Contains transformed latent variables
Returns
----------
The cholesky decomposition (L) of K | [
"Creates",
"cholesky",
"decomposition",
"of",
"covariance",
"matrix"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gpnarx/gpnarx.py#L176-L189 | train | 217,359 |
RJT1990/pyflux | pyflux/gpnarx/gpnarx.py | GPNARX.plot_fit | def plot_fit(self, intervals=True, **kwargs):
""" Plots the fit of the Gaussian process model to the data
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
intervals : Boolean
Whether to plot uncertainty intervals or not
Returns
----------
None (plots the fit of the function)
"""
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
date_index = self.index[self.max_lag:]
expectation = self.expected_values(self.latent_variables.get_z_values())
variance = self.variance_values(self.latent_variables.get_z_values())
upper = expectation + 1.98*np.power(np.diag(variance),0.5)
lower = expectation - 1.98*np.power(np.diag(variance),0.5)
plt.figure(figsize=figsize)
plt.subplot(2, 2, 1)
plt.title(self.data_name + " Raw")
plt.plot(date_index,self.data*self._norm_std + self._norm_mean,'k')
plt.subplot(2, 2, 2)
plt.title(self.data_name + " Raw and Expected")
plt.plot(date_index,self.data*self._norm_std + self._norm_mean,'k',alpha=0.2)
plt.plot(date_index,self.expected_values(self.latent_variables.get_z_values())*self._norm_std + self._norm_mean,'b')
plt.subplot(2, 2, 3)
plt.title(self.data_name + " Raw and Expected (with intervals)")
if intervals == True:
plt.fill_between(date_index, lower*self._norm_std + self._norm_mean, upper*self._norm_std + self._norm_mean, alpha=0.2)
plt.plot(date_index,self.data*self._norm_std + self._norm_mean,'k',alpha=0.2)
plt.plot(date_index,self.expected_values(self.latent_variables.get_z_values())*self._norm_std + self._norm_mean,'b')
plt.subplot(2, 2, 4)
plt.title("Expected " + self.data_name + " (with intervals)")
if intervals == True:
plt.fill_between(date_index, lower*self._norm_std + self._norm_mean, upper*self._norm_std + self._norm_mean, alpha=0.2)
plt.plot(date_index,self.expected_values(self.latent_variables.get_z_values())*self._norm_std + self._norm_mean,'b')
plt.show() | python | def plot_fit(self, intervals=True, **kwargs):
""" Plots the fit of the Gaussian process model to the data
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
intervals : Boolean
Whether to plot uncertainty intervals or not
Returns
----------
None (plots the fit of the function)
"""
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
date_index = self.index[self.max_lag:]
expectation = self.expected_values(self.latent_variables.get_z_values())
variance = self.variance_values(self.latent_variables.get_z_values())
upper = expectation + 1.98*np.power(np.diag(variance),0.5)
lower = expectation - 1.98*np.power(np.diag(variance),0.5)
plt.figure(figsize=figsize)
plt.subplot(2, 2, 1)
plt.title(self.data_name + " Raw")
plt.plot(date_index,self.data*self._norm_std + self._norm_mean,'k')
plt.subplot(2, 2, 2)
plt.title(self.data_name + " Raw and Expected")
plt.plot(date_index,self.data*self._norm_std + self._norm_mean,'k',alpha=0.2)
plt.plot(date_index,self.expected_values(self.latent_variables.get_z_values())*self._norm_std + self._norm_mean,'b')
plt.subplot(2, 2, 3)
plt.title(self.data_name + " Raw and Expected (with intervals)")
if intervals == True:
plt.fill_between(date_index, lower*self._norm_std + self._norm_mean, upper*self._norm_std + self._norm_mean, alpha=0.2)
plt.plot(date_index,self.data*self._norm_std + self._norm_mean,'k',alpha=0.2)
plt.plot(date_index,self.expected_values(self.latent_variables.get_z_values())*self._norm_std + self._norm_mean,'b')
plt.subplot(2, 2, 4)
plt.title("Expected " + self.data_name + " (with intervals)")
if intervals == True:
plt.fill_between(date_index, lower*self._norm_std + self._norm_mean, upper*self._norm_std + self._norm_mean, alpha=0.2)
plt.plot(date_index,self.expected_values(self.latent_variables.get_z_values())*self._norm_std + self._norm_mean,'b')
plt.show() | [
"def",
"plot_fit",
"(",
"self",
",",
"intervals",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"seaborn",
"as",
"sns",
"figsize",
"=",
"kwargs",
".",
"get",
"(",
"'figsize'",
",",
"(",
... | Plots the fit of the Gaussian process model to the data
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
intervals : Boolean
Whether to plot uncertainty intervals or not
Returns
----------
None (plots the fit of the function) | [
"Plots",
"the",
"fit",
"of",
"the",
"Gaussian",
"process",
"model",
"to",
"the",
"data"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gpnarx/gpnarx.py#L260-L315 | train | 217,360 |
RJT1990/pyflux | pyflux/gas/gas.py | GAS._get_scale_and_shape | def _get_scale_and_shape(self,parm):
""" Obtains appropriate model scale and shape latent variables
Parameters
----------
parm : np.array
Transformed latent variable vector
Returns
----------
None (changes model attributes)
"""
if self.scale is True:
if self.shape is True:
model_shape = parm[-1]
model_scale = parm[-2]
else:
model_shape = 0
model_scale = parm[-1]
else:
model_scale = 0
model_shape = 0
if self.skewness is True:
model_skewness = parm[-3]
else:
model_skewness = 0
return model_scale, model_shape, model_skewness | python | def _get_scale_and_shape(self,parm):
""" Obtains appropriate model scale and shape latent variables
Parameters
----------
parm : np.array
Transformed latent variable vector
Returns
----------
None (changes model attributes)
"""
if self.scale is True:
if self.shape is True:
model_shape = parm[-1]
model_scale = parm[-2]
else:
model_shape = 0
model_scale = parm[-1]
else:
model_scale = 0
model_shape = 0
if self.skewness is True:
model_skewness = parm[-3]
else:
model_skewness = 0
return model_scale, model_shape, model_skewness | [
"def",
"_get_scale_and_shape",
"(",
"self",
",",
"parm",
")",
":",
"if",
"self",
".",
"scale",
"is",
"True",
":",
"if",
"self",
".",
"shape",
"is",
"True",
":",
"model_shape",
"=",
"parm",
"[",
"-",
"1",
"]",
"model_scale",
"=",
"parm",
"[",
"-",
"... | Obtains appropriate model scale and shape latent variables
Parameters
----------
parm : np.array
Transformed latent variable vector
Returns
----------
None (changes model attributes) | [
"Obtains",
"appropriate",
"model",
"scale",
"and",
"shape",
"latent",
"variables"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gas/gas.py#L127-L156 | train | 217,361 |
RJT1990/pyflux | pyflux/gas/gas.py | GAS.plot_sample | def plot_sample(self, nsims=10, plot_data=True, **kwargs):
"""
Plots draws from the posterior predictive density against the data
Parameters
----------
nsims : int (default : 1000)
How many draws from the posterior predictive distribution
plot_data boolean
Whether to plot the data or not
"""
if self.latent_variables.estimation_method not in ['BBVI', 'M-H']:
raise Exception("No latent variables estimated!")
else:
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
plt.figure(figsize=figsize)
date_index = self.index[max(self.ar, self.sc):self.data_length]
mu, Y, scores = self._model(self.latent_variables.get_z_values())
draws = self.sample(nsims).T
plt.plot(date_index, draws, label='Posterior Draws', alpha=1.0)
if plot_data is True:
plt.plot(date_index, Y, label='Data', c='black', alpha=0.5, linestyle='', marker='s')
plt.title(self.data_name)
plt.show() | python | def plot_sample(self, nsims=10, plot_data=True, **kwargs):
"""
Plots draws from the posterior predictive density against the data
Parameters
----------
nsims : int (default : 1000)
How many draws from the posterior predictive distribution
plot_data boolean
Whether to plot the data or not
"""
if self.latent_variables.estimation_method not in ['BBVI', 'M-H']:
raise Exception("No latent variables estimated!")
else:
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
plt.figure(figsize=figsize)
date_index = self.index[max(self.ar, self.sc):self.data_length]
mu, Y, scores = self._model(self.latent_variables.get_z_values())
draws = self.sample(nsims).T
plt.plot(date_index, draws, label='Posterior Draws', alpha=1.0)
if plot_data is True:
plt.plot(date_index, Y, label='Data', c='black', alpha=0.5, linestyle='', marker='s')
plt.title(self.data_name)
plt.show() | [
"def",
"plot_sample",
"(",
"self",
",",
"nsims",
"=",
"10",
",",
"plot_data",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
"estimation_method",
"not",
"in",
"[",
"'BBVI'",
",",
"'M-H'",
"]",
":",
"raise",
... | Plots draws from the posterior predictive density against the data
Parameters
----------
nsims : int (default : 1000)
How many draws from the posterior predictive distribution
plot_data boolean
Whether to plot the data or not | [
"Plots",
"draws",
"from",
"the",
"posterior",
"predictive",
"density",
"against",
"the",
"data"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gas/gas.py#L939-L967 | train | 217,362 |
RJT1990/pyflux | pyflux/arma/arma.py | ARIMA._ar_matrix | def _ar_matrix(self):
""" Creates the Autoregressive matrix for the model
Returns
----------
X : np.ndarray
Autoregressive Matrix
"""
X = np.ones(self.data_length-self.max_lag)
if self.ar != 0:
for i in range(0, self.ar):
X = np.vstack((X,self.data[(self.max_lag-i-1):-i-1]))
return X | python | def _ar_matrix(self):
""" Creates the Autoregressive matrix for the model
Returns
----------
X : np.ndarray
Autoregressive Matrix
"""
X = np.ones(self.data_length-self.max_lag)
if self.ar != 0:
for i in range(0, self.ar):
X = np.vstack((X,self.data[(self.max_lag-i-1):-i-1]))
return X | [
"def",
"_ar_matrix",
"(",
"self",
")",
":",
"X",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"data_length",
"-",
"self",
".",
"max_lag",
")",
"if",
"self",
".",
"ar",
"!=",
"0",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"self",
".",
"ar",
... | Creates the Autoregressive matrix for the model
Returns
----------
X : np.ndarray
Autoregressive Matrix | [
"Creates",
"the",
"Autoregressive",
"matrix",
"for",
"the",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/arma.py#L109-L124 | train | 217,363 |
RJT1990/pyflux | pyflux/families/inverse_wishart.py | InverseWishart.logpdf | def logpdf(self, X):
"""
Log PDF for Inverse Wishart prior
Parameters
----------
X : float
Covariance matrix for which the prior is being formed over
Returns
----------
- log(p(X))
"""
return invwishart.logpdf(X, df=self.v, scale=self.Psi) | python | def logpdf(self, X):
"""
Log PDF for Inverse Wishart prior
Parameters
----------
X : float
Covariance matrix for which the prior is being formed over
Returns
----------
- log(p(X))
"""
return invwishart.logpdf(X, df=self.v, scale=self.Psi) | [
"def",
"logpdf",
"(",
"self",
",",
"X",
")",
":",
"return",
"invwishart",
".",
"logpdf",
"(",
"X",
",",
"df",
"=",
"self",
".",
"v",
",",
"scale",
"=",
"self",
".",
"Psi",
")"
] | Log PDF for Inverse Wishart prior
Parameters
----------
X : float
Covariance matrix for which the prior is being formed over
Returns
----------
- log(p(X)) | [
"Log",
"PDF",
"for",
"Inverse",
"Wishart",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/inverse_wishart.py#L38-L51 | train | 217,364 |
RJT1990/pyflux | pyflux/families/inverse_wishart.py | InverseWishart.pdf | def pdf(self, X):
"""
PDF for Inverse Wishart prior
Parameters
----------
x : float
Covariance matrix for which the prior is being formed over
Returns
----------
- p(x)
"""
return invwishart.pdf(X, df=self.v, scale=self.Psi) | python | def pdf(self, X):
"""
PDF for Inverse Wishart prior
Parameters
----------
x : float
Covariance matrix for which the prior is being formed over
Returns
----------
- p(x)
"""
return invwishart.pdf(X, df=self.v, scale=self.Psi) | [
"def",
"pdf",
"(",
"self",
",",
"X",
")",
":",
"return",
"invwishart",
".",
"pdf",
"(",
"X",
",",
"df",
"=",
"self",
".",
"v",
",",
"scale",
"=",
"self",
".",
"Psi",
")"
] | PDF for Inverse Wishart prior
Parameters
----------
x : float
Covariance matrix for which the prior is being formed over
Returns
----------
- p(x) | [
"PDF",
"for",
"Inverse",
"Wishart",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/inverse_wishart.py#L53-L66 | train | 217,365 |
RJT1990/pyflux | pyflux/ssm/nllt.py | NLLT.neg_loglik | def neg_loglik(self, beta):
""" Creates negative loglikelihood of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- Negative loglikelihood
"""
Z = np.zeros(2)
Z[0] = 1
states = np.zeros([self.state_no, self.data.shape[0]])
states[0,:] = beta[self.z_no:self.z_no+self.data.shape[0]]
states[1,:] = beta[self.z_no+self.data.shape[0]:]
parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(self.z_no)]) # transformed distribution parameters
scale, shape, skewness = self._get_scale_and_shape(parm)
return self.state_likelihood(beta, states) + self.family.neg_loglikelihood(self.data, self.link(np.dot(Z, states)), scale, shape, skewness) | python | def neg_loglik(self, beta):
""" Creates negative loglikelihood of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- Negative loglikelihood
"""
Z = np.zeros(2)
Z[0] = 1
states = np.zeros([self.state_no, self.data.shape[0]])
states[0,:] = beta[self.z_no:self.z_no+self.data.shape[0]]
states[1,:] = beta[self.z_no+self.data.shape[0]:]
parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(self.z_no)]) # transformed distribution parameters
scale, shape, skewness = self._get_scale_and_shape(parm)
return self.state_likelihood(beta, states) + self.family.neg_loglikelihood(self.data, self.link(np.dot(Z, states)), scale, shape, skewness) | [
"def",
"neg_loglik",
"(",
"self",
",",
"beta",
")",
":",
"Z",
"=",
"np",
".",
"zeros",
"(",
"2",
")",
"Z",
"[",
"0",
"]",
"=",
"1",
"states",
"=",
"np",
".",
"zeros",
"(",
"[",
"self",
".",
"state_no",
",",
"self",
".",
"data",
".",
"shape",
... | Creates negative loglikelihood of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- Negative loglikelihood | [
"Creates",
"negative",
"loglikelihood",
"of",
"the",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllt.py#L117-L136 | train | 217,366 |
RJT1990/pyflux | pyflux/ssm/nllt.py | NLLT.state_likelihood_markov_blanket | def state_likelihood_markov_blanket(self, beta, alpha, col_no):
""" Returns Markov blanket of the states given the variance latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
State matrix
Returns
----------
State likelihood
"""
_, _, _, Q = self._ss_matrices(beta)
blanket = np.append(0,ss.norm.logpdf(alpha[col_no][1:]-alpha[col_no][:-1],loc=0,scale=np.sqrt(Q[col_no][col_no])))
blanket[:-1] = blanket[:-1] + blanket[1:]
return blanket | python | def state_likelihood_markov_blanket(self, beta, alpha, col_no):
""" Returns Markov blanket of the states given the variance latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
State matrix
Returns
----------
State likelihood
"""
_, _, _, Q = self._ss_matrices(beta)
blanket = np.append(0,ss.norm.logpdf(alpha[col_no][1:]-alpha[col_no][:-1],loc=0,scale=np.sqrt(Q[col_no][col_no])))
blanket[:-1] = blanket[:-1] + blanket[1:]
return blanket | [
"def",
"state_likelihood_markov_blanket",
"(",
"self",
",",
"beta",
",",
"alpha",
",",
"col_no",
")",
":",
"_",
",",
"_",
",",
"_",
",",
"Q",
"=",
"self",
".",
"_ss_matrices",
"(",
"beta",
")",
"blanket",
"=",
"np",
".",
"append",
"(",
"0",
",",
"s... | Returns Markov blanket of the states given the variance latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
State matrix
Returns
----------
State likelihood | [
"Returns",
"Markov",
"blanket",
"of",
"the",
"states",
"given",
"the",
"variance",
"latent",
"variables"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllt.py#L181-L199 | train | 217,367 |
RJT1990/pyflux | pyflux/ssm/nllt.py | NLLT.markov_blanket | def markov_blanket(self, beta, alpha):
""" Creates total Markov blanket for states
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
A vector of states
Returns
----------
Markov blanket for states
"""
likelihood_blanket = self.likelihood_markov_blanket(beta)
state_blanket = self.state_likelihood_markov_blanket(beta,alpha,0)
for i in range(self.state_no-1):
likelihood_blanket = np.append(likelihood_blanket,self.likelihood_markov_blanket(beta))
state_blanket = np.append(state_blanket,self.state_likelihood_markov_blanket(beta,alpha,i+1))
return likelihood_blanket + state_blanket | python | def markov_blanket(self, beta, alpha):
""" Creates total Markov blanket for states
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
A vector of states
Returns
----------
Markov blanket for states
"""
likelihood_blanket = self.likelihood_markov_blanket(beta)
state_blanket = self.state_likelihood_markov_blanket(beta,alpha,0)
for i in range(self.state_no-1):
likelihood_blanket = np.append(likelihood_blanket,self.likelihood_markov_blanket(beta))
state_blanket = np.append(state_blanket,self.state_likelihood_markov_blanket(beta,alpha,i+1))
return likelihood_blanket + state_blanket | [
"def",
"markov_blanket",
"(",
"self",
",",
"beta",
",",
"alpha",
")",
":",
"likelihood_blanket",
"=",
"self",
".",
"likelihood_markov_blanket",
"(",
"beta",
")",
"state_blanket",
"=",
"self",
".",
"state_likelihood_markov_blanket",
"(",
"beta",
",",
"alpha",
","... | Creates total Markov blanket for states
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
A vector of states
Returns
----------
Markov blanket for states | [
"Creates",
"total",
"Markov",
"blanket",
"for",
"states"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllt.py#L221-L241 | train | 217,368 |
RJT1990/pyflux | pyflux/ssm/nllt.py | NLLT._general_approximating_model | def _general_approximating_model(self, beta, T, Z, R, Q, h_approx):
""" Creates simplest kind of approximating Gaussian model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
T, Z, R, Q : np.array
State space matrices used in KFS algorithm
h_approx : float
Value to use for the H matrix
Returns
----------
H : np.array
Approximating measurement variance matrix
mu : np.array
Approximating measurement constants
"""
H = np.ones(self.data_length)*h_approx
mu = np.zeros(self.data_length)
return H, mu | python | def _general_approximating_model(self, beta, T, Z, R, Q, h_approx):
""" Creates simplest kind of approximating Gaussian model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
T, Z, R, Q : np.array
State space matrices used in KFS algorithm
h_approx : float
Value to use for the H matrix
Returns
----------
H : np.array
Approximating measurement variance matrix
mu : np.array
Approximating measurement constants
"""
H = np.ones(self.data_length)*h_approx
mu = np.zeros(self.data_length)
return H, mu | [
"def",
"_general_approximating_model",
"(",
"self",
",",
"beta",
",",
"T",
",",
"Z",
",",
"R",
",",
"Q",
",",
"h_approx",
")",
":",
"H",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"data_length",
")",
"*",
"h_approx",
"mu",
"=",
"np",
".",
"zeros",
... | Creates simplest kind of approximating Gaussian model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
T, Z, R, Q : np.array
State space matrices used in KFS algorithm
h_approx : float
Value to use for the H matrix
Returns
----------
H : np.array
Approximating measurement variance matrix
mu : np.array
Approximating measurement constants | [
"Creates",
"simplest",
"kind",
"of",
"approximating",
"Gaussian",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllt.py#L403-L430 | train | 217,369 |
RJT1990/pyflux | pyflux/ssm/nllt.py | NLLT.fit | def fit(self, optimizer='RMSProp', iterations=1000, print_progress=True, start_diffuse=False, **kwargs):
""" Fits the model
Parameters
----------
optimizer : string
Stochastic optimizer: either RMSProp or ADAM.
iterations: int
How many iterations to run
print_progress : bool
Whether tp print the ELBO progress or not
start_diffuse : bool
Whether to start from diffuse values (if not: use approx Gaussian)
Returns
----------
BBVI fit object
"""
return self._bbvi_fit(optimizer=optimizer, print_progress=print_progress,
start_diffuse=start_diffuse, iterations=iterations, **kwargs) | python | def fit(self, optimizer='RMSProp', iterations=1000, print_progress=True, start_diffuse=False, **kwargs):
""" Fits the model
Parameters
----------
optimizer : string
Stochastic optimizer: either RMSProp or ADAM.
iterations: int
How many iterations to run
print_progress : bool
Whether tp print the ELBO progress or not
start_diffuse : bool
Whether to start from diffuse values (if not: use approx Gaussian)
Returns
----------
BBVI fit object
"""
return self._bbvi_fit(optimizer=optimizer, print_progress=print_progress,
start_diffuse=start_diffuse, iterations=iterations, **kwargs) | [
"def",
"fit",
"(",
"self",
",",
"optimizer",
"=",
"'RMSProp'",
",",
"iterations",
"=",
"1000",
",",
"print_progress",
"=",
"True",
",",
"start_diffuse",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_bbvi_fit",
"(",
"optimizer"... | Fits the model
Parameters
----------
optimizer : string
Stochastic optimizer: either RMSProp or ADAM.
iterations: int
How many iterations to run
print_progress : bool
Whether tp print the ELBO progress or not
start_diffuse : bool
Whether to start from diffuse values (if not: use approx Gaussian)
Returns
----------
BBVI fit object | [
"Fits",
"the",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllt.py#L432-L455 | train | 217,370 |
RJT1990/pyflux | pyflux/var/var.py | create_design_matrix_2 | def create_design_matrix_2(Z, data, Y_len, lag_no):
"""
For Python 2.7 - cythonized version only works for 3.5
"""
row_count = 1
for lag in range(1, lag_no+1):
for reg in range(Y_len):
Z[row_count, :] = data[reg][(lag_no-lag):-lag]
row_count += 1
return Z | python | def create_design_matrix_2(Z, data, Y_len, lag_no):
"""
For Python 2.7 - cythonized version only works for 3.5
"""
row_count = 1
for lag in range(1, lag_no+1):
for reg in range(Y_len):
Z[row_count, :] = data[reg][(lag_no-lag):-lag]
row_count += 1
return Z | [
"def",
"create_design_matrix_2",
"(",
"Z",
",",
"data",
",",
"Y_len",
",",
"lag_no",
")",
":",
"row_count",
"=",
"1",
"for",
"lag",
"in",
"range",
"(",
"1",
",",
"lag_no",
"+",
"1",
")",
":",
"for",
"reg",
"in",
"range",
"(",
"Y_len",
")",
":",
"... | For Python 2.7 - cythonized version only works for 3.5 | [
"For",
"Python",
"2",
".",
"7",
"-",
"cythonized",
"version",
"only",
"works",
"for",
"3",
".",
"5"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L18-L29 | train | 217,371 |
RJT1990/pyflux | pyflux/var/var.py | VAR._create_B | def _create_B(self,Y):
""" Creates OLS coefficient matrix
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The coefficient matrix B
"""
Z = self._create_Z(Y)
return np.dot(np.dot(Y,np.transpose(Z)),np.linalg.inv(np.dot(Z,np.transpose(Z)))) | python | def _create_B(self,Y):
""" Creates OLS coefficient matrix
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The coefficient matrix B
"""
Z = self._create_Z(Y)
return np.dot(np.dot(Y,np.transpose(Z)),np.linalg.inv(np.dot(Z,np.transpose(Z)))) | [
"def",
"_create_B",
"(",
"self",
",",
"Y",
")",
":",
"Z",
"=",
"self",
".",
"_create_Z",
"(",
"Y",
")",
"return",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"Y",
",",
"np",
".",
"transpose",
"(",
"Z",
")",
")",
",",
"np",
".",
"linalg",
... | Creates OLS coefficient matrix
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The coefficient matrix B | [
"Creates",
"OLS",
"coefficient",
"matrix"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L97-L111 | train | 217,372 |
RJT1990/pyflux | pyflux/var/var.py | VAR._create_Z | def _create_Z(self,Y):
""" Creates design matrix holding the lagged variables
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The design matrix Z
"""
Z = np.ones(((self.ylen*self.lags +1),Y[0].shape[0]))
return self.create_design_matrix(Z, self.data, Y.shape[0], self.lags) | python | def _create_Z(self,Y):
""" Creates design matrix holding the lagged variables
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The design matrix Z
"""
Z = np.ones(((self.ylen*self.lags +1),Y[0].shape[0]))
return self.create_design_matrix(Z, self.data, Y.shape[0], self.lags) | [
"def",
"_create_Z",
"(",
"self",
",",
"Y",
")",
":",
"Z",
"=",
"np",
".",
"ones",
"(",
"(",
"(",
"self",
".",
"ylen",
"*",
"self",
".",
"lags",
"+",
"1",
")",
",",
"Y",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
")",
")",
"return",
"self... | Creates design matrix holding the lagged variables
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The design matrix Z | [
"Creates",
"design",
"matrix",
"holding",
"the",
"lagged",
"variables"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L163-L177 | train | 217,373 |
RJT1990/pyflux | pyflux/var/var.py | VAR._forecast_mean | def _forecast_mean(self,h,t_params,Y,shock_type=None,shock_index=0,shock_value=None,shock_dir='positive',irf_intervals=False):
""" Function allows for mean prediction; also allows shock specification for simulations or impulse response effects
Parameters
----------
h : int
How many steps ahead to forecast
t_params : np.array
Transformed latent variables vector
Y : np.array
Data for series that is being forecast
shock_type : None or str
Type of shock; options include None, 'Cov' (simulate from covariance matrix), 'IRF' (impulse response shock)
shock_index : int
Which latent variable to apply the shock to if using an IRF.
shock_value : None or float
If specified, applies a custom-sized impulse response shock.
shock_dir : str
Direction of the IRF shock. One of 'positive' or 'negative'.
irf_intervals : Boolean
Whether to have intervals for the IRF plot or not
Returns
----------
A vector of forecasted data
"""
random = self._shock_create(h, shock_type, shock_index, shock_value, shock_dir,irf_intervals)
exp = [Y[variable] for variable in range(0,self.ylen)]
# Each forward projection
for t in range(0,h):
new_values = np.zeros(self.ylen)
# Each variable
for variable in range(0,self.ylen):
index_ref = variable*(1+self.ylen*self.lags)
new_values[variable] = t_params[index_ref] # constant
# VAR(p) terms
for lag in range(0,self.lags):
for lagged_var in range(0,self.ylen):
new_values[variable] += t_params[index_ref+lagged_var+(lag*self.ylen)+1]*exp[lagged_var][-1-lag]
# Random shock
new_values[variable] += random[t][variable]
# Add new values
for variable in range(0,self.ylen):
exp[variable] = np.append(exp[variable],new_values[variable])
return np.array(exp) | python | def _forecast_mean(self,h,t_params,Y,shock_type=None,shock_index=0,shock_value=None,shock_dir='positive',irf_intervals=False):
""" Function allows for mean prediction; also allows shock specification for simulations or impulse response effects
Parameters
----------
h : int
How many steps ahead to forecast
t_params : np.array
Transformed latent variables vector
Y : np.array
Data for series that is being forecast
shock_type : None or str
Type of shock; options include None, 'Cov' (simulate from covariance matrix), 'IRF' (impulse response shock)
shock_index : int
Which latent variable to apply the shock to if using an IRF.
shock_value : None or float
If specified, applies a custom-sized impulse response shock.
shock_dir : str
Direction of the IRF shock. One of 'positive' or 'negative'.
irf_intervals : Boolean
Whether to have intervals for the IRF plot or not
Returns
----------
A vector of forecasted data
"""
random = self._shock_create(h, shock_type, shock_index, shock_value, shock_dir,irf_intervals)
exp = [Y[variable] for variable in range(0,self.ylen)]
# Each forward projection
for t in range(0,h):
new_values = np.zeros(self.ylen)
# Each variable
for variable in range(0,self.ylen):
index_ref = variable*(1+self.ylen*self.lags)
new_values[variable] = t_params[index_ref] # constant
# VAR(p) terms
for lag in range(0,self.lags):
for lagged_var in range(0,self.ylen):
new_values[variable] += t_params[index_ref+lagged_var+(lag*self.ylen)+1]*exp[lagged_var][-1-lag]
# Random shock
new_values[variable] += random[t][variable]
# Add new values
for variable in range(0,self.ylen):
exp[variable] = np.append(exp[variable],new_values[variable])
return np.array(exp) | [
"def",
"_forecast_mean",
"(",
"self",
",",
"h",
",",
"t_params",
",",
"Y",
",",
"shock_type",
"=",
"None",
",",
"shock_index",
"=",
"0",
",",
"shock_value",
"=",
"None",
",",
"shock_dir",
"=",
"'positive'",
",",
"irf_intervals",
"=",
"False",
")",
":",
... | Function allows for mean prediction; also allows shock specification for simulations or impulse response effects
Parameters
----------
h : int
How many steps ahead to forecast
t_params : np.array
Transformed latent variables vector
Y : np.array
Data for series that is being forecast
shock_type : None or str
Type of shock; options include None, 'Cov' (simulate from covariance matrix), 'IRF' (impulse response shock)
shock_index : int
Which latent variable to apply the shock to if using an IRF.
shock_value : None or float
If specified, applies a custom-sized impulse response shock.
shock_dir : str
Direction of the IRF shock. One of 'positive' or 'negative'.
irf_intervals : Boolean
Whether to have intervals for the IRF plot or not
Returns
----------
A vector of forecasted data | [
"Function",
"allows",
"for",
"mean",
"prediction",
";",
"also",
"allows",
"shock",
"specification",
"for",
"simulations",
"or",
"impulse",
"response",
"effects"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L179-L237 | train | 217,374 |
RJT1990/pyflux | pyflux/var/var.py | VAR._shock_create | def _shock_create(self, h, shock_type, shock_index, shock_value, shock_dir, irf_intervals):
""" Function creates shocks based on desired specification
Parameters
----------
h : int
How many steps ahead to forecast
shock_type : None or str
Type of shock; options include None, 'Cov' (simulate from covariance matrix), 'IRF' (impulse response shock)
shock_index : int
Which latent variables to apply the shock to if using an IRF.
shock_value : None or float
If specified, applies a custom-sized impulse response shock.
shock_dir : str
Direction of the IRF shock. One of 'positive' or 'negative'.
irf_intervals : Boolean
Whether to have intervals for the IRF plot or not
Returns
----------
A h-length list which contains np.arrays containing shocks for each variable
"""
if shock_type is None:
random = [np.zeros(self.ylen) for i in range(0,h)]
elif shock_type == 'IRF':
if self.use_ols_covariance is False:
cov = self.custom_covariance(self.latent_variables.get_z_values())
else:
cov = self.ols_covariance()
post = ss.multivariate_normal(np.zeros(self.ylen),cov)
if irf_intervals is False:
random = [np.zeros(self.ylen) for i in range(0,h)]
else:
random = [post.rvs() for i in range(0,h)]
random[0] = np.zeros(self.ylen)
if shock_value is None:
if shock_dir=='positive':
random[0][shock_index] = cov[shock_index,shock_index]**0.5
elif shock_dir=='negative':
random[0][shock_index] = -cov[shock_index,shock_index]**0.5
else:
raise ValueError("Unknown shock direction!")
else:
random[0][shock_index] = shock_value
elif shock_type == 'Cov':
if self.use_ols_covariance is False:
cov = self.custom_covariance(self.latent_variables.get_z_values())
else:
cov = self.ols_covariance()
post = ss.multivariate_normal(np.zeros(self.ylen),cov)
random = [post.rvs() for i in range(0,h)]
return random | python | def _shock_create(self, h, shock_type, shock_index, shock_value, shock_dir, irf_intervals):
""" Function creates shocks based on desired specification
Parameters
----------
h : int
How many steps ahead to forecast
shock_type : None or str
Type of shock; options include None, 'Cov' (simulate from covariance matrix), 'IRF' (impulse response shock)
shock_index : int
Which latent variables to apply the shock to if using an IRF.
shock_value : None or float
If specified, applies a custom-sized impulse response shock.
shock_dir : str
Direction of the IRF shock. One of 'positive' or 'negative'.
irf_intervals : Boolean
Whether to have intervals for the IRF plot or not
Returns
----------
A h-length list which contains np.arrays containing shocks for each variable
"""
if shock_type is None:
random = [np.zeros(self.ylen) for i in range(0,h)]
elif shock_type == 'IRF':
if self.use_ols_covariance is False:
cov = self.custom_covariance(self.latent_variables.get_z_values())
else:
cov = self.ols_covariance()
post = ss.multivariate_normal(np.zeros(self.ylen),cov)
if irf_intervals is False:
random = [np.zeros(self.ylen) for i in range(0,h)]
else:
random = [post.rvs() for i in range(0,h)]
random[0] = np.zeros(self.ylen)
if shock_value is None:
if shock_dir=='positive':
random[0][shock_index] = cov[shock_index,shock_index]**0.5
elif shock_dir=='negative':
random[0][shock_index] = -cov[shock_index,shock_index]**0.5
else:
raise ValueError("Unknown shock direction!")
else:
random[0][shock_index] = shock_value
elif shock_type == 'Cov':
if self.use_ols_covariance is False:
cov = self.custom_covariance(self.latent_variables.get_z_values())
else:
cov = self.ols_covariance()
post = ss.multivariate_normal(np.zeros(self.ylen),cov)
random = [post.rvs() for i in range(0,h)]
return random | [
"def",
"_shock_create",
"(",
"self",
",",
"h",
",",
"shock_type",
",",
"shock_index",
",",
"shock_value",
",",
"shock_dir",
",",
"irf_intervals",
")",
":",
"if",
"shock_type",
"is",
"None",
":",
"random",
"=",
"[",
"np",
".",
"zeros",
"(",
"self",
".",
... | Function creates shocks based on desired specification
Parameters
----------
h : int
How many steps ahead to forecast
shock_type : None or str
Type of shock; options include None, 'Cov' (simulate from covariance matrix), 'IRF' (impulse response shock)
shock_index : int
Which latent variables to apply the shock to if using an IRF.
shock_value : None or float
If specified, applies a custom-sized impulse response shock.
shock_dir : str
Direction of the IRF shock. One of 'positive' or 'negative'.
irf_intervals : Boolean
Whether to have intervals for the IRF plot or not
Returns
----------
A h-length list which contains np.arrays containing shocks for each variable | [
"Function",
"creates",
"shocks",
"based",
"on",
"desired",
"specification"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L269-L336 | train | 217,375 |
RJT1990/pyflux | pyflux/var/var.py | VAR.estimator_cov | def estimator_cov(self,method):
""" Creates covariance matrix for the estimators
Parameters
----------
method : str
Estimation method
Returns
----------
A Covariance Matrix
"""
Y = np.array([reg[self.lags:] for reg in self.data])
Z = self._create_Z(Y)
if method == 'OLS':
sigma = self.ols_covariance()
else:
sigma = self.custom_covariance(self.latent_variables.get_z_values())
return np.kron(np.linalg.inv(np.dot(Z,np.transpose(Z))), sigma) | python | def estimator_cov(self,method):
""" Creates covariance matrix for the estimators
Parameters
----------
method : str
Estimation method
Returns
----------
A Covariance Matrix
"""
Y = np.array([reg[self.lags:] for reg in self.data])
Z = self._create_Z(Y)
if method == 'OLS':
sigma = self.ols_covariance()
else:
sigma = self.custom_covariance(self.latent_variables.get_z_values())
return np.kron(np.linalg.inv(np.dot(Z,np.transpose(Z))), sigma) | [
"def",
"estimator_cov",
"(",
"self",
",",
"method",
")",
":",
"Y",
"=",
"np",
".",
"array",
"(",
"[",
"reg",
"[",
"self",
".",
"lags",
":",
"]",
"for",
"reg",
"in",
"self",
".",
"data",
"]",
")",
"Z",
"=",
"self",
".",
"_create_Z",
"(",
"Y",
... | Creates covariance matrix for the estimators
Parameters
----------
method : str
Estimation method
Returns
----------
A Covariance Matrix | [
"Creates",
"covariance",
"matrix",
"for",
"the",
"estimators"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L388-L407 | train | 217,376 |
RJT1990/pyflux | pyflux/var/var.py | VAR.ols_covariance | def ols_covariance(self):
""" Creates OLS estimate of the covariance matrix
Returns
----------
The OLS estimate of the covariance matrix
"""
Y = np.array([reg[self.lags:reg.shape[0]] for reg in self.data])
return (1.0/(Y[0].shape[0]))*np.dot(self.residuals(Y),np.transpose(self.residuals(Y))) | python | def ols_covariance(self):
""" Creates OLS estimate of the covariance matrix
Returns
----------
The OLS estimate of the covariance matrix
"""
Y = np.array([reg[self.lags:reg.shape[0]] for reg in self.data])
return (1.0/(Y[0].shape[0]))*np.dot(self.residuals(Y),np.transpose(self.residuals(Y))) | [
"def",
"ols_covariance",
"(",
"self",
")",
":",
"Y",
"=",
"np",
".",
"array",
"(",
"[",
"reg",
"[",
"self",
".",
"lags",
":",
"reg",
".",
"shape",
"[",
"0",
"]",
"]",
"for",
"reg",
"in",
"self",
".",
"data",
"]",
")",
"return",
"(",
"1.0",
"/... | Creates OLS estimate of the covariance matrix
Returns
----------
The OLS estimate of the covariance matrix | [
"Creates",
"OLS",
"estimate",
"of",
"the",
"covariance",
"matrix"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L435-L444 | train | 217,377 |
RJT1990/pyflux | pyflux/var/var.py | VAR.residuals | def residuals(self,Y):
""" Creates the model residuals
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The model residuals
"""
return (Y-np.dot(self._create_B(Y),self._create_Z(Y))) | python | def residuals(self,Y):
""" Creates the model residuals
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The model residuals
"""
return (Y-np.dot(self._create_B(Y),self._create_Z(Y))) | [
"def",
"residuals",
"(",
"self",
",",
"Y",
")",
":",
"return",
"(",
"Y",
"-",
"np",
".",
"dot",
"(",
"self",
".",
"_create_B",
"(",
"Y",
")",
",",
"self",
".",
"_create_Z",
"(",
"Y",
")",
")",
")"
] | Creates the model residuals
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The model residuals | [
"Creates",
"the",
"model",
"residuals"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L648-L661 | train | 217,378 |
RJT1990/pyflux | pyflux/var/var.py | VAR.construct_wishart | def construct_wishart(self,v,X):
"""
Constructs a Wishart prior for the covariance matrix
"""
self.adjust_prior(list(range(int((len(self.latent_variables.z_list)-self.ylen-(self.ylen**2-self.ylen)/2)),
int(len(self.latent_variables.z_list)))), fam.InverseWishart(v,X)) | python | def construct_wishart(self,v,X):
"""
Constructs a Wishart prior for the covariance matrix
"""
self.adjust_prior(list(range(int((len(self.latent_variables.z_list)-self.ylen-(self.ylen**2-self.ylen)/2)),
int(len(self.latent_variables.z_list)))), fam.InverseWishart(v,X)) | [
"def",
"construct_wishart",
"(",
"self",
",",
"v",
",",
"X",
")",
":",
"self",
".",
"adjust_prior",
"(",
"list",
"(",
"range",
"(",
"int",
"(",
"(",
"len",
"(",
"self",
".",
"latent_variables",
".",
"z_list",
")",
"-",
"self",
".",
"ylen",
"-",
"("... | Constructs a Wishart prior for the covariance matrix | [
"Constructs",
"a",
"Wishart",
"prior",
"for",
"the",
"covariance",
"matrix"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L663-L668 | train | 217,379 |
RJT1990/pyflux | pyflux/ssm/llm.py | LLEV.simulation_smoother | def simulation_smoother(self,beta):
""" Koopman's simulation smoother - simulates from states given
model latent variables and observations
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- A simulated state evolution
"""
T, Z, R, Q, H = self._ss_matrices(beta)
# Generate e_t+ and n_t+
rnd_h = np.random.normal(0,np.sqrt(H),self.data.shape[0]+1)
q_dist = ss.multivariate_normal([0.0], Q)
rnd_q = q_dist.rvs(self.data.shape[0]+1)
# Generate a_t+ and y_t+
a_plus = np.zeros((T.shape[0],self.data.shape[0]+1))
a_plus[0,0] = np.mean(self.data[0:5])
y_plus = np.zeros(self.data.shape[0])
for t in range(0,self.data.shape[0]+1):
if t == 0:
a_plus[:,t] = np.dot(T,a_plus[:,t]) + rnd_q[t]
y_plus[t] = np.dot(Z,a_plus[:,t]) + rnd_h[t]
else:
if t != self.data.shape[0]:
a_plus[:,t] = np.dot(T,a_plus[:,t-1]) + rnd_q[t]
y_plus[t] = np.dot(Z,a_plus[:,t]) + rnd_h[t]
alpha_hat,_ = self.smoothed_state(self.data,beta)
alpha_hat_plus,_ = self.smoothed_state(y_plus,beta)
alpha_tilde = alpha_hat - alpha_hat_plus + a_plus
return alpha_tilde | python | def simulation_smoother(self,beta):
""" Koopman's simulation smoother - simulates from states given
model latent variables and observations
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- A simulated state evolution
"""
T, Z, R, Q, H = self._ss_matrices(beta)
# Generate e_t+ and n_t+
rnd_h = np.random.normal(0,np.sqrt(H),self.data.shape[0]+1)
q_dist = ss.multivariate_normal([0.0], Q)
rnd_q = q_dist.rvs(self.data.shape[0]+1)
# Generate a_t+ and y_t+
a_plus = np.zeros((T.shape[0],self.data.shape[0]+1))
a_plus[0,0] = np.mean(self.data[0:5])
y_plus = np.zeros(self.data.shape[0])
for t in range(0,self.data.shape[0]+1):
if t == 0:
a_plus[:,t] = np.dot(T,a_plus[:,t]) + rnd_q[t]
y_plus[t] = np.dot(Z,a_plus[:,t]) + rnd_h[t]
else:
if t != self.data.shape[0]:
a_plus[:,t] = np.dot(T,a_plus[:,t-1]) + rnd_q[t]
y_plus[t] = np.dot(Z,a_plus[:,t]) + rnd_h[t]
alpha_hat,_ = self.smoothed_state(self.data,beta)
alpha_hat_plus,_ = self.smoothed_state(y_plus,beta)
alpha_tilde = alpha_hat - alpha_hat_plus + a_plus
return alpha_tilde | [
"def",
"simulation_smoother",
"(",
"self",
",",
"beta",
")",
":",
"T",
",",
"Z",
",",
"R",
",",
"Q",
",",
"H",
"=",
"self",
".",
"_ss_matrices",
"(",
"beta",
")",
"# Generate e_t+ and n_t+",
"rnd_h",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",... | Koopman's simulation smoother - simulates from states given
model latent variables and observations
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- A simulated state evolution | [
"Koopman",
"s",
"simulation",
"smoother",
"-",
"simulates",
"from",
"states",
"given",
"model",
"latent",
"variables",
"and",
"observations"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/llm.py#L496-L536 | train | 217,380 |
RJT1990/pyflux | pyflux/ssm/llm.py | LLEV.smoothed_state | def smoothed_state(self,data,beta):
""" Creates the negative log marginal likelihood of the model
Parameters
----------
data : np.array
Data to be smoothed
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- Smoothed states
"""
T, Z, R, Q, H = self._ss_matrices(beta)
alpha, V = univariate_KFS(data,Z,H,T,Q,R,0.0)
return alpha, V | python | def smoothed_state(self,data,beta):
""" Creates the negative log marginal likelihood of the model
Parameters
----------
data : np.array
Data to be smoothed
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- Smoothed states
"""
T, Z, R, Q, H = self._ss_matrices(beta)
alpha, V = univariate_KFS(data,Z,H,T,Q,R,0.0)
return alpha, V | [
"def",
"smoothed_state",
"(",
"self",
",",
"data",
",",
"beta",
")",
":",
"T",
",",
"Z",
",",
"R",
",",
"Q",
",",
"H",
"=",
"self",
".",
"_ss_matrices",
"(",
"beta",
")",
"alpha",
",",
"V",
"=",
"univariate_KFS",
"(",
"data",
",",
"Z",
",",
"H"... | Creates the negative log marginal likelihood of the model
Parameters
----------
data : np.array
Data to be smoothed
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- Smoothed states | [
"Creates",
"the",
"negative",
"log",
"marginal",
"likelihood",
"of",
"the",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/llm.py#L538-L557 | train | 217,381 |
RJT1990/pyflux | pyflux/tsm.py | TSM._laplace_fit | def _laplace_fit(self,obj_type):
""" Performs a Laplace approximation to the posterior
Parameters
----------
obj_type : method
Whether a likelihood or a posterior
Returns
----------
None (plots posterior)
"""
# Get Mode and Inverse Hessian information
y = self.fit(method='PML',printer=False)
if y.ihessian is None:
raise Exception("No Hessian information - Laplace approximation cannot be performed")
else:
self.latent_variables.estimation_method = 'Laplace'
theta, Y, scores, states, states_var, X_names = self._categorize_model_output(self.latent_variables.get_z_values())
# Change this in future
try:
latent_variables_store = self.latent_variables.copy()
except:
latent_variables_store = self.latent_variables
return LaplaceResults(data_name=self.data_name,X_names=X_names,model_name=self.model_name,
model_type=self.model_type, latent_variables=latent_variables_store,data=Y,index=self.index,
multivariate_model=self.multivariate_model,objective_object=obj_type,
method='Laplace',ihessian=y.ihessian,signal=theta,scores=scores,
z_hide=self._z_hide,max_lag=self.max_lag,states=states,states_var=states_var) | python | def _laplace_fit(self,obj_type):
""" Performs a Laplace approximation to the posterior
Parameters
----------
obj_type : method
Whether a likelihood or a posterior
Returns
----------
None (plots posterior)
"""
# Get Mode and Inverse Hessian information
y = self.fit(method='PML',printer=False)
if y.ihessian is None:
raise Exception("No Hessian information - Laplace approximation cannot be performed")
else:
self.latent_variables.estimation_method = 'Laplace'
theta, Y, scores, states, states_var, X_names = self._categorize_model_output(self.latent_variables.get_z_values())
# Change this in future
try:
latent_variables_store = self.latent_variables.copy()
except:
latent_variables_store = self.latent_variables
return LaplaceResults(data_name=self.data_name,X_names=X_names,model_name=self.model_name,
model_type=self.model_type, latent_variables=latent_variables_store,data=Y,index=self.index,
multivariate_model=self.multivariate_model,objective_object=obj_type,
method='Laplace',ihessian=y.ihessian,signal=theta,scores=scores,
z_hide=self._z_hide,max_lag=self.max_lag,states=states,states_var=states_var) | [
"def",
"_laplace_fit",
"(",
"self",
",",
"obj_type",
")",
":",
"# Get Mode and Inverse Hessian information",
"y",
"=",
"self",
".",
"fit",
"(",
"method",
"=",
"'PML'",
",",
"printer",
"=",
"False",
")",
"if",
"y",
".",
"ihessian",
"is",
"None",
":",
"raise... | Performs a Laplace approximation to the posterior
Parameters
----------
obj_type : method
Whether a likelihood or a posterior
Returns
----------
None (plots posterior) | [
"Performs",
"a",
"Laplace",
"approximation",
"to",
"the",
"posterior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/tsm.py#L187-L221 | train | 217,382 |
RJT1990/pyflux | pyflux/tsm.py | TSM._optimize_fit | def _optimize_fit(self, obj_type=None, **kwargs):
"""
This function fits models using Maximum Likelihood or Penalized Maximum Likelihood
"""
preopt_search = kwargs.get('preopt_search', True) # If user supplied
if obj_type == self.neg_loglik:
method = 'MLE'
else:
method = 'PML'
# Starting values - check to see if model has preoptimize method, if not, simply use default starting values
if preopt_search is True:
try:
phi = self._preoptimize_model(self.latent_variables.get_z_starting_values(), method)
preoptimized = True
except:
phi = self.latent_variables.get_z_starting_values()
preoptimized = False
else:
preoptimized = False
phi = self.latent_variables.get_z_starting_values()
phi = kwargs.get('start',phi).copy() # If user supplied
# Optimize using L-BFGS-B
p = optimize.minimize(obj_type, phi, method='L-BFGS-B', options={'gtol': 1e-8})
if preoptimized is True:
p2 = optimize.minimize(obj_type, self.latent_variables.get_z_starting_values(), method='L-BFGS-B',
options={'gtol': 1e-8})
if self.neg_loglik(p2.x) < self.neg_loglik(p.x):
p = p2
theta, Y, scores, states, states_var, X_names = self._categorize_model_output(p.x)
# Check that matrix is non-singular; act accordingly
try:
ihessian = np.linalg.inv(nd.Hessian(obj_type)(p.x))
ses = np.power(np.abs(np.diag(ihessian)),0.5)
self.latent_variables.set_z_values(p.x,method,ses,None)
except:
ihessian = None
ses = None
self.latent_variables.set_z_values(p.x,method,None,None)
self.latent_variables.estimation_method = method
# Change this in future
try:
latent_variables_store = self.latent_variables.copy()
except:
latent_variables_store = self.latent_variables
return MLEResults(data_name=self.data_name,X_names=X_names,model_name=self.model_name,
model_type=self.model_type, latent_variables=latent_variables_store,results=p,data=Y, index=self.index,
multivariate_model=self.multivariate_model,objective_object=obj_type,
method=method,ihessian=ihessian,signal=theta,scores=scores,
z_hide=self._z_hide,max_lag=self.max_lag,states=states,states_var=states_var) | python | def _optimize_fit(self, obj_type=None, **kwargs):
"""
This function fits models using Maximum Likelihood or Penalized Maximum Likelihood
"""
preopt_search = kwargs.get('preopt_search', True) # If user supplied
if obj_type == self.neg_loglik:
method = 'MLE'
else:
method = 'PML'
# Starting values - check to see if model has preoptimize method, if not, simply use default starting values
if preopt_search is True:
try:
phi = self._preoptimize_model(self.latent_variables.get_z_starting_values(), method)
preoptimized = True
except:
phi = self.latent_variables.get_z_starting_values()
preoptimized = False
else:
preoptimized = False
phi = self.latent_variables.get_z_starting_values()
phi = kwargs.get('start',phi).copy() # If user supplied
# Optimize using L-BFGS-B
p = optimize.minimize(obj_type, phi, method='L-BFGS-B', options={'gtol': 1e-8})
if preoptimized is True:
p2 = optimize.minimize(obj_type, self.latent_variables.get_z_starting_values(), method='L-BFGS-B',
options={'gtol': 1e-8})
if self.neg_loglik(p2.x) < self.neg_loglik(p.x):
p = p2
theta, Y, scores, states, states_var, X_names = self._categorize_model_output(p.x)
# Check that matrix is non-singular; act accordingly
try:
ihessian = np.linalg.inv(nd.Hessian(obj_type)(p.x))
ses = np.power(np.abs(np.diag(ihessian)),0.5)
self.latent_variables.set_z_values(p.x,method,ses,None)
except:
ihessian = None
ses = None
self.latent_variables.set_z_values(p.x,method,None,None)
self.latent_variables.estimation_method = method
# Change this in future
try:
latent_variables_store = self.latent_variables.copy()
except:
latent_variables_store = self.latent_variables
return MLEResults(data_name=self.data_name,X_names=X_names,model_name=self.model_name,
model_type=self.model_type, latent_variables=latent_variables_store,results=p,data=Y, index=self.index,
multivariate_model=self.multivariate_model,objective_object=obj_type,
method=method,ihessian=ihessian,signal=theta,scores=scores,
z_hide=self._z_hide,max_lag=self.max_lag,states=states,states_var=states_var) | [
"def",
"_optimize_fit",
"(",
"self",
",",
"obj_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"preopt_search",
"=",
"kwargs",
".",
"get",
"(",
"'preopt_search'",
",",
"True",
")",
"# If user supplied",
"if",
"obj_type",
"==",
"self",
".",
"neg_logl... | This function fits models using Maximum Likelihood or Penalized Maximum Likelihood | [
"This",
"function",
"fits",
"models",
"using",
"Maximum",
"Likelihood",
"or",
"Penalized",
"Maximum",
"Likelihood"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/tsm.py#L347-L406 | train | 217,383 |
RJT1990/pyflux | pyflux/tsm.py | TSM.multivariate_neg_logposterior | def multivariate_neg_logposterior(self,beta):
""" Returns negative log posterior, for a model with a covariance matrix
Parameters
----------
beta : np.array
Contains untransformed starting values for latent_variables
Returns
----------
Negative log posterior
"""
post = self.neg_loglik(beta)
for k in range(0,self.z_no):
if self.latent_variables.z_list[k].prior.covariance_prior is True:
post += -self.latent_variables.z_list[k].prior.logpdf(self.custom_covariance(beta))
break
else:
post += -self.latent_variables.z_list[k].prior.logpdf(beta[k])
return post | python | def multivariate_neg_logposterior(self,beta):
""" Returns negative log posterior, for a model with a covariance matrix
Parameters
----------
beta : np.array
Contains untransformed starting values for latent_variables
Returns
----------
Negative log posterior
"""
post = self.neg_loglik(beta)
for k in range(0,self.z_no):
if self.latent_variables.z_list[k].prior.covariance_prior is True:
post += -self.latent_variables.z_list[k].prior.logpdf(self.custom_covariance(beta))
break
else:
post += -self.latent_variables.z_list[k].prior.logpdf(beta[k])
return post | [
"def",
"multivariate_neg_logposterior",
"(",
"self",
",",
"beta",
")",
":",
"post",
"=",
"self",
".",
"neg_loglik",
"(",
"beta",
")",
"for",
"k",
"in",
"range",
"(",
"0",
",",
"self",
".",
"z_no",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
... | Returns negative log posterior, for a model with a covariance matrix
Parameters
----------
beta : np.array
Contains untransformed starting values for latent_variables
Returns
----------
Negative log posterior | [
"Returns",
"negative",
"log",
"posterior",
"for",
"a",
"model",
"with",
"a",
"covariance",
"matrix"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/tsm.py#L496-L516 | train | 217,384 |
RJT1990/pyflux | pyflux/tsm.py | TSM.shift_dates | def shift_dates(self,h):
""" Auxiliary function for creating dates for forecasts
Parameters
----------
h : int
How many steps to forecast
Returns
----------
A transformed date_index object
"""
date_index = copy.deepcopy(self.index)
date_index = date_index[self.max_lag:len(date_index)]
if self.is_pandas is True:
if isinstance(date_index, pd.core.indexes.datetimes.DatetimeIndex):
if pd.infer_freq(date_index) in ['H', 'M', 'S']:
for t in range(h):
date_index += pd.DateOffset((date_index[len(date_index)-1] - date_index[len(date_index)-2]).seconds)
else: # Assume higher frequency (configured for days)
for t in range(h):
date_index += pd.DateOffset((date_index[len(date_index)-1] - date_index[len(date_index)-2]).days)
elif isinstance(date_index, pd.core.indexes.numeric.Int64Index):
for i in range(h):
new_value = date_index.values[len(date_index.values)-1] + (date_index.values[len(date_index.values)-1] - date_index.values[len(date_index.values)-2])
date_index = pd.Int64Index(np.append(date_index.values,new_value))
else:
for t in range(h):
date_index.append(date_index[len(date_index)-1]+1)
return date_index | python | def shift_dates(self,h):
""" Auxiliary function for creating dates for forecasts
Parameters
----------
h : int
How many steps to forecast
Returns
----------
A transformed date_index object
"""
date_index = copy.deepcopy(self.index)
date_index = date_index[self.max_lag:len(date_index)]
if self.is_pandas is True:
if isinstance(date_index, pd.core.indexes.datetimes.DatetimeIndex):
if pd.infer_freq(date_index) in ['H', 'M', 'S']:
for t in range(h):
date_index += pd.DateOffset((date_index[len(date_index)-1] - date_index[len(date_index)-2]).seconds)
else: # Assume higher frequency (configured for days)
for t in range(h):
date_index += pd.DateOffset((date_index[len(date_index)-1] - date_index[len(date_index)-2]).days)
elif isinstance(date_index, pd.core.indexes.numeric.Int64Index):
for i in range(h):
new_value = date_index.values[len(date_index.values)-1] + (date_index.values[len(date_index.values)-1] - date_index.values[len(date_index.values)-2])
date_index = pd.Int64Index(np.append(date_index.values,new_value))
else:
for t in range(h):
date_index.append(date_index[len(date_index)-1]+1)
return date_index | [
"def",
"shift_dates",
"(",
"self",
",",
"h",
")",
":",
"date_index",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"index",
")",
"date_index",
"=",
"date_index",
"[",
"self",
".",
"max_lag",
":",
"len",
"(",
"date_index",
")",
"]",
"if",
"self",
".... | Auxiliary function for creating dates for forecasts
Parameters
----------
h : int
How many steps to forecast
Returns
----------
A transformed date_index object | [
"Auxiliary",
"function",
"for",
"creating",
"dates",
"for",
"forecasts"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/tsm.py#L518-L559 | train | 217,385 |
RJT1990/pyflux | pyflux/tsm.py | TSM.plot_z | def plot_z(self, indices=None,figsize=(15,5),**kwargs):
""" Plots latent variables by calling latent parameters object
Returns
----------
Pretty plot
"""
self.latent_variables.plot_z(indices=indices,figsize=figsize,**kwargs) | python | def plot_z(self, indices=None,figsize=(15,5),**kwargs):
""" Plots latent variables by calling latent parameters object
Returns
----------
Pretty plot
"""
self.latent_variables.plot_z(indices=indices,figsize=figsize,**kwargs) | [
"def",
"plot_z",
"(",
"self",
",",
"indices",
"=",
"None",
",",
"figsize",
"=",
"(",
"15",
",",
"5",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"latent_variables",
".",
"plot_z",
"(",
"indices",
"=",
"indices",
",",
"figsize",
"=",
"figsi... | Plots latent variables by calling latent parameters object
Returns
----------
Pretty plot | [
"Plots",
"latent",
"variables",
"by",
"calling",
"latent",
"parameters",
"object"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/tsm.py#L579-L586 | train | 217,386 |
RJT1990/pyflux | pyflux/ssm/ndynlin.py | NDynReg.evo_blanket | def evo_blanket(self, beta, alpha):
""" Creates Markov blanket for the variance latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
A vector of states
Returns
----------
Markov blanket for variance latent variables
"""
# Markov blanket for each state
evo_blanket = np.zeros(self.state_no)
for i in range(evo_blanket.shape[0]):
evo_blanket[i] = self.state_likelihood_markov_blanket(beta, alpha, i).sum()
# If the family has additional parameters, add their markov blankets
if self.family_z_no > 0:
evo_blanket = np.append([self.likelihood_markov_blanket(beta).sum()]*(self.family_z_no),evo_blanket)
return evo_blanket | python | def evo_blanket(self, beta, alpha):
""" Creates Markov blanket for the variance latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
A vector of states
Returns
----------
Markov blanket for variance latent variables
"""
# Markov blanket for each state
evo_blanket = np.zeros(self.state_no)
for i in range(evo_blanket.shape[0]):
evo_blanket[i] = self.state_likelihood_markov_blanket(beta, alpha, i).sum()
# If the family has additional parameters, add their markov blankets
if self.family_z_no > 0:
evo_blanket = np.append([self.likelihood_markov_blanket(beta).sum()]*(self.family_z_no),evo_blanket)
return evo_blanket | [
"def",
"evo_blanket",
"(",
"self",
",",
"beta",
",",
"alpha",
")",
":",
"# Markov blanket for each state",
"evo_blanket",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"state_no",
")",
"for",
"i",
"in",
"range",
"(",
"evo_blanket",
".",
"shape",
"[",
"0",
"... | Creates Markov blanket for the variance latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
A vector of states
Returns
----------
Markov blanket for variance latent variables | [
"Creates",
"Markov",
"blanket",
"for",
"the",
"variance",
"latent",
"variables"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/ndynlin.py#L233-L258 | train | 217,387 |
RJT1990/pyflux | pyflux/ssm/ndynlin.py | NDynReg.log_p_blanket | def log_p_blanket(self, beta):
""" Creates complete Markov blanket for latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
Markov blanket for latent variables
"""
states = np.zeros([self.state_no, self.data.shape[0]])
for state_i in range(self.state_no):
states[state_i,:] = beta[(self.z_no + (self.data.shape[0]*state_i)):(self.z_no + (self.data.shape[0]*(state_i+1)))]
return np.append(self.evo_blanket(beta,states),self.markov_blanket(beta,states)) | python | def log_p_blanket(self, beta):
""" Creates complete Markov blanket for latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
Markov blanket for latent variables
"""
states = np.zeros([self.state_no, self.data.shape[0]])
for state_i in range(self.state_no):
states[state_i,:] = beta[(self.z_no + (self.data.shape[0]*state_i)):(self.z_no + (self.data.shape[0]*(state_i+1)))]
return np.append(self.evo_blanket(beta,states),self.markov_blanket(beta,states)) | [
"def",
"log_p_blanket",
"(",
"self",
",",
"beta",
")",
":",
"states",
"=",
"np",
".",
"zeros",
"(",
"[",
"self",
".",
"state_no",
",",
"self",
".",
"data",
".",
"shape",
"[",
"0",
"]",
"]",
")",
"for",
"state_i",
"in",
"range",
"(",
"self",
".",
... | Creates complete Markov blanket for latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
Markov blanket for latent variables | [
"Creates",
"complete",
"Markov",
"blanket",
"for",
"latent",
"variables"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/ndynlin.py#L260-L276 | train | 217,388 |
RJT1990/pyflux | pyflux/families/exponential.py | Exponential.logpdf | def logpdf(self, mu):
"""
Log PDF for Exponential prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = self.transform(mu)
return ss.expon.logpdf(mu, self.lmd0) | python | def logpdf(self, mu):
"""
Log PDF for Exponential prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = self.transform(mu)
return ss.expon.logpdf(mu, self.lmd0) | [
"def",
"logpdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"ss",
".",
"expon",
".",
"logpdf",
"(",
"mu",
",",
"self",
".",
"lmd0",
... | Log PDF for Exponential prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu)) | [
"Log",
"PDF",
"for",
"Exponential",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/exponential.py#L177-L192 | train | 217,389 |
RJT1990/pyflux | pyflux/families/exponential.py | Exponential.markov_blanket | def markov_blanket(y, mean, scale, shape, skewness):
""" Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential distribution
shape : float
tail thickness parameter for the Exponential distribution
skewness : float
skewness parameter for the Exponential distribution
Returns
----------
- Markov blanket of the Exponential family
"""
return ss.expon.logpdf(x=y, scale=1/mean) | python | def markov_blanket(y, mean, scale, shape, skewness):
""" Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential distribution
shape : float
tail thickness parameter for the Exponential distribution
skewness : float
skewness parameter for the Exponential distribution
Returns
----------
- Markov blanket of the Exponential family
"""
return ss.expon.logpdf(x=y, scale=1/mean) | [
"def",
"markov_blanket",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"ss",
".",
"expon",
".",
"logpdf",
"(",
"x",
"=",
"y",
",",
"scale",
"=",
"1",
"/",
"mean",
")"
] | Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential distribution
shape : float
tail thickness parameter for the Exponential distribution
skewness : float
skewness parameter for the Exponential distribution
Returns
----------
- Markov blanket of the Exponential family | [
"Markov",
"blanket",
"for",
"the",
"Exponential",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/exponential.py#L195-L219 | train | 217,390 |
RJT1990/pyflux | pyflux/families/exponential.py | Exponential.pdf | def pdf(self, mu):
"""
PDF for Exponential prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu)
"""
if self.transform is not None:
mu = self.transform(mu)
return ss.expon.pdf(mu, self.lmd0) | python | def pdf(self, mu):
"""
PDF for Exponential prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu)
"""
if self.transform is not None:
mu = self.transform(mu)
return ss.expon.pdf(mu, self.lmd0) | [
"def",
"pdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"ss",
".",
"expon",
".",
"pdf",
"(",
"mu",
",",
"self",
".",
"lmd0",
")"
] | PDF for Exponential prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu) | [
"PDF",
"for",
"Exponential",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/exponential.py#L277-L292 | train | 217,391 |
RJT1990/pyflux | pyflux/inference/bbvi.py | BBVI.change_parameters | def change_parameters(self,params):
"""
Utility function for changing the approximate distribution parameters
"""
no_of_params = 0
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
self.q[core_param].vi_change_param(approx_param, params[no_of_params])
no_of_params += 1 | python | def change_parameters(self,params):
"""
Utility function for changing the approximate distribution parameters
"""
no_of_params = 0
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
self.q[core_param].vi_change_param(approx_param, params[no_of_params])
no_of_params += 1 | [
"def",
"change_parameters",
"(",
"self",
",",
"params",
")",
":",
"no_of_params",
"=",
"0",
"for",
"core_param",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"q",
")",
")",
":",
"for",
"approx_param",
"in",
"range",
"(",
"self",
".",
"q",
"[",
"core_... | Utility function for changing the approximate distribution parameters | [
"Utility",
"function",
"for",
"changing",
"the",
"approximate",
"distribution",
"parameters"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L54-L62 | train | 217,392 |
RJT1990/pyflux | pyflux/inference/bbvi.py | BBVI.current_parameters | def current_parameters(self):
"""
Obtains an array with the current parameters
"""
current = []
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
current.append(self.q[core_param].vi_return_param(approx_param))
return np.array(current) | python | def current_parameters(self):
"""
Obtains an array with the current parameters
"""
current = []
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
current.append(self.q[core_param].vi_return_param(approx_param))
return np.array(current) | [
"def",
"current_parameters",
"(",
"self",
")",
":",
"current",
"=",
"[",
"]",
"for",
"core_param",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"q",
")",
")",
":",
"for",
"approx_param",
"in",
"range",
"(",
"self",
".",
"q",
"[",
"core_param",
"]",
... | Obtains an array with the current parameters | [
"Obtains",
"an",
"array",
"with",
"the",
"current",
"parameters"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L71-L79 | train | 217,393 |
RJT1990/pyflux | pyflux/inference/bbvi.py | BBVI.cv_gradient | def cv_gradient(self,z):
"""
The control variate augmented Monte Carlo gradient estimate
"""
gradient = np.zeros(np.sum(self.approx_param_no))
z_t = z.T
log_q = self.normal_log_q(z.T)
log_p = self.log_p(z.T)
grad_log_q = self.grad_log_q(z)
gradient = grad_log_q*(log_p-log_q)
alpha0 = alpha_recursion(np.zeros(np.sum(self.approx_param_no)), grad_log_q, gradient, np.sum(self.approx_param_no))
vectorized = gradient - ((alpha0/np.var(grad_log_q,axis=1))*grad_log_q.T).T
return np.mean(vectorized,axis=1) | python | def cv_gradient(self,z):
"""
The control variate augmented Monte Carlo gradient estimate
"""
gradient = np.zeros(np.sum(self.approx_param_no))
z_t = z.T
log_q = self.normal_log_q(z.T)
log_p = self.log_p(z.T)
grad_log_q = self.grad_log_q(z)
gradient = grad_log_q*(log_p-log_q)
alpha0 = alpha_recursion(np.zeros(np.sum(self.approx_param_no)), grad_log_q, gradient, np.sum(self.approx_param_no))
vectorized = gradient - ((alpha0/np.var(grad_log_q,axis=1))*grad_log_q.T).T
return np.mean(vectorized,axis=1) | [
"def",
"cv_gradient",
"(",
"self",
",",
"z",
")",
":",
"gradient",
"=",
"np",
".",
"zeros",
"(",
"np",
".",
"sum",
"(",
"self",
".",
"approx_param_no",
")",
")",
"z_t",
"=",
"z",
".",
"T",
"log_q",
"=",
"self",
".",
"normal_log_q",
"(",
"z",
".",... | The control variate augmented Monte Carlo gradient estimate | [
"The",
"control",
"variate",
"augmented",
"Monte",
"Carlo",
"gradient",
"estimate"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L81-L96 | train | 217,394 |
RJT1990/pyflux | pyflux/inference/bbvi.py | BBVI.draw_variables | def draw_variables(self):
"""
Draw parameters from the approximating distributions
"""
z = self.q[0].draw_variable_local(self.sims)
for i in range(1,len(self.q)):
z = np.vstack((z,self.q[i].draw_variable_local(self.sims)))
return z | python | def draw_variables(self):
"""
Draw parameters from the approximating distributions
"""
z = self.q[0].draw_variable_local(self.sims)
for i in range(1,len(self.q)):
z = np.vstack((z,self.q[i].draw_variable_local(self.sims)))
return z | [
"def",
"draw_variables",
"(",
"self",
")",
":",
"z",
"=",
"self",
".",
"q",
"[",
"0",
"]",
".",
"draw_variable_local",
"(",
"self",
".",
"sims",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"q",
")",
")",
":",
"z",
... | Draw parameters from the approximating distributions | [
"Draw",
"parameters",
"from",
"the",
"approximating",
"distributions"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L129-L136 | train | 217,395 |
RJT1990/pyflux | pyflux/inference/bbvi.py | BBVI.grad_log_q | def grad_log_q(self,z):
"""
The gradients of the approximating distributions
"""
param_count = 0
grad = np.zeros((np.sum(self.approx_param_no),self.sims))
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
grad[param_count] = self.q[core_param].vi_score(z[core_param],approx_param)
param_count += 1
return grad | python | def grad_log_q(self,z):
"""
The gradients of the approximating distributions
"""
param_count = 0
grad = np.zeros((np.sum(self.approx_param_no),self.sims))
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
grad[param_count] = self.q[core_param].vi_score(z[core_param],approx_param)
param_count += 1
return grad | [
"def",
"grad_log_q",
"(",
"self",
",",
"z",
")",
":",
"param_count",
"=",
"0",
"grad",
"=",
"np",
".",
"zeros",
"(",
"(",
"np",
".",
"sum",
"(",
"self",
".",
"approx_param_no",
")",
",",
"self",
".",
"sims",
")",
")",
"for",
"core_param",
"in",
"... | The gradients of the approximating distributions | [
"The",
"gradients",
"of",
"the",
"approximating",
"distributions"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L155-L165 | train | 217,396 |
RJT1990/pyflux | pyflux/inference/bbvi.py | BBVIM.print_progress | def print_progress(self, i, current_params):
"""
Prints the current ELBO at every decile of total iterations
"""
for split in range(1,11):
if i == (round(self.iterations/10*split)-1):
post = -self.full_neg_posterior(current_params)
approx = self.create_normal_logq(current_params)
diff = post - approx
if not self.quiet_progress:
print(str(split) + "0% done : ELBO is " + str(diff) + ", p(y,z) is " + str(post) + ", q(z) is " + str(approx)) | python | def print_progress(self, i, current_params):
"""
Prints the current ELBO at every decile of total iterations
"""
for split in range(1,11):
if i == (round(self.iterations/10*split)-1):
post = -self.full_neg_posterior(current_params)
approx = self.create_normal_logq(current_params)
diff = post - approx
if not self.quiet_progress:
print(str(split) + "0% done : ELBO is " + str(diff) + ", p(y,z) is " + str(post) + ", q(z) is " + str(approx)) | [
"def",
"print_progress",
"(",
"self",
",",
"i",
",",
"current_params",
")",
":",
"for",
"split",
"in",
"range",
"(",
"1",
",",
"11",
")",
":",
"if",
"i",
"==",
"(",
"round",
"(",
"self",
".",
"iterations",
"/",
"10",
"*",
"split",
")",
"-",
"1",
... | Prints the current ELBO at every decile of total iterations | [
"Prints",
"the",
"current",
"ELBO",
"at",
"every",
"decile",
"of",
"total",
"iterations"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L441-L451 | train | 217,397 |
RJT1990/pyflux | pyflux/inference/bbvi.py | BBVIM.run | def run(self):
"""
The core BBVI routine - draws Monte Carlo gradients and uses a stochastic optimizer.
"""
# Initialization assumptions
z = self.draw_normal_initial()
gradient = self.cv_gradient_initial(z)
gradient[np.isnan(gradient)] = 0
variance = np.power(gradient, 2)
final_parameters = self.current_parameters()
final_samples = 1
# Create optimizer
if self.optimizer == 'ADAM':
self.optim = ADAM(final_parameters, variance, self.learning_rate, 0.9, 0.999)
elif self.optimizer == 'RMSProp':
self.optim = RMSProp(final_parameters, variance, self.learning_rate, 0.99)
# Record elbo
if self.record_elbo is True:
elbo_records = np.zeros(self.iterations)
else:
elbo_records = None
for i in range(self.iterations):
x = self.draw_normal()
gradient = self.cv_gradient(x)
gradient[np.isnan(gradient)] = 0
self.change_parameters(self.optim.update(gradient))
if self.printer is True:
self.print_progress(i, self.optim.parameters[::2])
# Construct final parameters using final 10% of samples
if i > self.iterations-round(self.iterations/10):
final_samples += 1
final_parameters = final_parameters+self.optim.parameters
if self.record_elbo is True:
elbo_records[i] = self.get_elbo(self.optim.parameters[::2])
final_parameters = final_parameters/float(final_samples)
self.change_parameters(final_parameters)
final_means = np.array([final_parameters[el] for el in range(len(final_parameters)) if el%2==0])
final_ses = np.array([final_parameters[el] for el in range(len(final_parameters)) if el%2!=0])
if not self.quiet_progress:
print("")
print("Final model ELBO is " + str(-self.full_neg_posterior(final_means)-self.create_normal_logq(final_means)))
return self.q, final_means, final_ses, elbo_records | python | def run(self):
"""
The core BBVI routine - draws Monte Carlo gradients and uses a stochastic optimizer.
"""
# Initialization assumptions
z = self.draw_normal_initial()
gradient = self.cv_gradient_initial(z)
gradient[np.isnan(gradient)] = 0
variance = np.power(gradient, 2)
final_parameters = self.current_parameters()
final_samples = 1
# Create optimizer
if self.optimizer == 'ADAM':
self.optim = ADAM(final_parameters, variance, self.learning_rate, 0.9, 0.999)
elif self.optimizer == 'RMSProp':
self.optim = RMSProp(final_parameters, variance, self.learning_rate, 0.99)
# Record elbo
if self.record_elbo is True:
elbo_records = np.zeros(self.iterations)
else:
elbo_records = None
for i in range(self.iterations):
x = self.draw_normal()
gradient = self.cv_gradient(x)
gradient[np.isnan(gradient)] = 0
self.change_parameters(self.optim.update(gradient))
if self.printer is True:
self.print_progress(i, self.optim.parameters[::2])
# Construct final parameters using final 10% of samples
if i > self.iterations-round(self.iterations/10):
final_samples += 1
final_parameters = final_parameters+self.optim.parameters
if self.record_elbo is True:
elbo_records[i] = self.get_elbo(self.optim.parameters[::2])
final_parameters = final_parameters/float(final_samples)
self.change_parameters(final_parameters)
final_means = np.array([final_parameters[el] for el in range(len(final_parameters)) if el%2==0])
final_ses = np.array([final_parameters[el] for el in range(len(final_parameters)) if el%2!=0])
if not self.quiet_progress:
print("")
print("Final model ELBO is " + str(-self.full_neg_posterior(final_means)-self.create_normal_logq(final_means)))
return self.q, final_means, final_ses, elbo_records | [
"def",
"run",
"(",
"self",
")",
":",
"# Initialization assumptions",
"z",
"=",
"self",
".",
"draw_normal_initial",
"(",
")",
"gradient",
"=",
"self",
".",
"cv_gradient_initial",
"(",
"z",
")",
"gradient",
"[",
"np",
".",
"isnan",
"(",
"gradient",
")",
"]",... | The core BBVI routine - draws Monte Carlo gradients and uses a stochastic optimizer. | [
"The",
"core",
"BBVI",
"routine",
"-",
"draws",
"Monte",
"Carlo",
"gradients",
"and",
"uses",
"a",
"stochastic",
"optimizer",
"."
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L453-L502 | train | 217,398 |
RJT1990/pyflux | pyflux/garch/segarchm.py | logpdf | def logpdf(x, shape, loc=0.0, scale=1.0, skewness=1.0):
"""
Log PDF for the Skew-t distribution
Parameters
----------
x : np.array
random variables
shape : float
The degrees of freedom for the skew-t distribution
loc : np.array
The location parameter for the skew-t distribution
scale : float
The scale of the distribution
skewness : float
Skewness parameter (if 1, no skewness, if > 1, +ve skew, if < 1, -ve skew)
"""
m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))
loc = loc + (skewness - (1.0/skewness))*scale*m1
result = np.zeros(x.shape[0])
result[x-loc<0] = np.log(2.0) - np.log(skewness + 1.0/skewness) + ss.t.logpdf(x=skewness*x[(x-loc) < 0], loc=loc[(x-loc) < 0]*skewness,df=shape, scale=scale[(x-loc) < 0])
result[x-loc>=0] = np.log(2.0) - np.log(skewness + 1.0/skewness) + ss.t.logpdf(x=x[(x-loc) >= 0]/skewness, loc=loc[(x-loc) >= 0]/skewness,df=shape, scale=scale[(x-loc) >= 0])
return result | python | def logpdf(x, shape, loc=0.0, scale=1.0, skewness=1.0):
"""
Log PDF for the Skew-t distribution
Parameters
----------
x : np.array
random variables
shape : float
The degrees of freedom for the skew-t distribution
loc : np.array
The location parameter for the skew-t distribution
scale : float
The scale of the distribution
skewness : float
Skewness parameter (if 1, no skewness, if > 1, +ve skew, if < 1, -ve skew)
"""
m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))
loc = loc + (skewness - (1.0/skewness))*scale*m1
result = np.zeros(x.shape[0])
result[x-loc<0] = np.log(2.0) - np.log(skewness + 1.0/skewness) + ss.t.logpdf(x=skewness*x[(x-loc) < 0], loc=loc[(x-loc) < 0]*skewness,df=shape, scale=scale[(x-loc) < 0])
result[x-loc>=0] = np.log(2.0) - np.log(skewness + 1.0/skewness) + ss.t.logpdf(x=x[(x-loc) >= 0]/skewness, loc=loc[(x-loc) >= 0]/skewness,df=shape, scale=scale[(x-loc) >= 0])
return result | [
"def",
"logpdf",
"(",
"x",
",",
"shape",
",",
"loc",
"=",
"0.0",
",",
"scale",
"=",
"1.0",
",",
"skewness",
"=",
"1.0",
")",
":",
"m1",
"=",
"(",
"np",
".",
"sqrt",
"(",
"shape",
")",
"*",
"sp",
".",
"gamma",
"(",
"(",
"shape",
"-",
"1.0",
... | Log PDF for the Skew-t distribution
Parameters
----------
x : np.array
random variables
shape : float
The degrees of freedom for the skew-t distribution
loc : np.array
The location parameter for the skew-t distribution
scale : float
The scale of the distribution
skewness : float
Skewness parameter (if 1, no skewness, if > 1, +ve skew, if < 1, -ve skew) | [
"Log",
"PDF",
"for",
"the",
"Skew",
"-",
"t",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/garch/segarchm.py#L17-L44 | train | 217,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.