id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
225,200 | DataBiosphere/toil | src/toil/lib/ec2nodes.py | updateStaticEC2Instances | def updateStaticEC2Instances():
"""
Generates a new python file of fetchable EC2 Instances by region with current prices and specs.
Takes a few (~3+) minutes to run (you'll need decent internet).
:return: Nothing. Writes a new 'generatedEC2Lists.py' file.
"""
logger.info("Updating Toil's EC2 lists to the most current version from AWS's bulk API. "
"This may take a while, depending on your internet connection.")
dirname = os.path.dirname(__file__)
# the file Toil uses to get info about EC2 instance types
origFile = os.path.join(dirname, 'generatedEC2Lists.py')
assert os.path.exists(origFile)
# use a temporary file until all info is fetched
genFile = os.path.join(dirname, 'generatedEC2Lists_tmp.py')
assert not os.path.exists(genFile)
# will be used to save a copy of the original when finished
oldFile = os.path.join(dirname, 'generatedEC2Lists_old.py')
# provenance note, copyright and imports
with open(genFile, 'w') as f:
f.write(textwrap.dedent('''
# !!! AUTOGENERATED FILE !!!
# Update with: src/toil/utils/toilUpdateEC2Instances.py
#
# Copyright (C) 2015-{year} UCSC Computational Genomics Lab
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from six import iteritems
from toil.lib.ec2nodes import InstanceType\n\n\n''').format(year=datetime.date.today().strftime("%Y"))[1:])
currentEC2List = []
instancesByRegion = {}
for regionNickname, _ in iteritems(EC2Regions):
currentEC2Dict = fetchEC2InstanceDict(regionNickname=regionNickname)
for instanceName, instanceTypeObj in iteritems(currentEC2Dict):
if instanceTypeObj not in currentEC2List:
currentEC2List.append(instanceTypeObj)
instancesByRegion.setdefault(regionNickname, []).append(instanceName)
# write header of total EC2 instance type list
genString = "# {num} Instance Types. Generated {date}.\n".format(
num=str(len(currentEC2List)), date=str(datetime.datetime.now()))
genString = genString + "E2Instances = {\n"
sortedCurrentEC2List = sorted(currentEC2List, key=lambda x: x.name)
# write the list of all instances types
for i in sortedCurrentEC2List:
z = " '{name}': InstanceType(name='{name}', cores={cores}, memory={memory}, disks={disks}, disk_capacity={disk_capacity})," \
"\n".format(name=i.name, cores=i.cores, memory=i.memory, disks=i.disks, disk_capacity=i.disk_capacity)
genString = genString + z
genString = genString + '}\n\n'
genString = genString + 'regionDict = {\n'
for regionName, instanceList in iteritems(instancesByRegion):
genString = genString + " '{regionName}': [".format(regionName=regionName)
for instance in sorted(instanceList):
genString = genString + "'{instance}', ".format(instance=instance)
if genString.endswith(', '):
genString = genString[:-2]
genString = genString + '],\n'
if genString.endswith(',\n'):
genString = genString[:-len(',\n')]
genString = genString + '}\n'
with open(genFile, 'a+') as f:
f.write(genString)
# append key for fetching at the end
regionKey = '\nec2InstancesByRegion = dict((region, [E2Instances[i] for i in instances]) for region, instances in iteritems(regionDict))\n'
with open(genFile, 'a+') as f:
f.write(regionKey)
# preserve the original file unless it already exists
if not os.path.exists(oldFile):
os.rename(origFile, oldFile)
# delete the original file if it's still there
if os.path.exists(origFile):
os.remove(origFile)
# replace the instance list with a current list
os.rename(genFile, origFile) | python | def updateStaticEC2Instances():
logger.info("Updating Toil's EC2 lists to the most current version from AWS's bulk API. "
"This may take a while, depending on your internet connection.")
dirname = os.path.dirname(__file__)
# the file Toil uses to get info about EC2 instance types
origFile = os.path.join(dirname, 'generatedEC2Lists.py')
assert os.path.exists(origFile)
# use a temporary file until all info is fetched
genFile = os.path.join(dirname, 'generatedEC2Lists_tmp.py')
assert not os.path.exists(genFile)
# will be used to save a copy of the original when finished
oldFile = os.path.join(dirname, 'generatedEC2Lists_old.py')
# provenance note, copyright and imports
with open(genFile, 'w') as f:
f.write(textwrap.dedent('''
# !!! AUTOGENERATED FILE !!!
# Update with: src/toil/utils/toilUpdateEC2Instances.py
#
# Copyright (C) 2015-{year} UCSC Computational Genomics Lab
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from six import iteritems
from toil.lib.ec2nodes import InstanceType\n\n\n''').format(year=datetime.date.today().strftime("%Y"))[1:])
currentEC2List = []
instancesByRegion = {}
for regionNickname, _ in iteritems(EC2Regions):
currentEC2Dict = fetchEC2InstanceDict(regionNickname=regionNickname)
for instanceName, instanceTypeObj in iteritems(currentEC2Dict):
if instanceTypeObj not in currentEC2List:
currentEC2List.append(instanceTypeObj)
instancesByRegion.setdefault(regionNickname, []).append(instanceName)
# write header of total EC2 instance type list
genString = "# {num} Instance Types. Generated {date}.\n".format(
num=str(len(currentEC2List)), date=str(datetime.datetime.now()))
genString = genString + "E2Instances = {\n"
sortedCurrentEC2List = sorted(currentEC2List, key=lambda x: x.name)
# write the list of all instances types
for i in sortedCurrentEC2List:
z = " '{name}': InstanceType(name='{name}', cores={cores}, memory={memory}, disks={disks}, disk_capacity={disk_capacity})," \
"\n".format(name=i.name, cores=i.cores, memory=i.memory, disks=i.disks, disk_capacity=i.disk_capacity)
genString = genString + z
genString = genString + '}\n\n'
genString = genString + 'regionDict = {\n'
for regionName, instanceList in iteritems(instancesByRegion):
genString = genString + " '{regionName}': [".format(regionName=regionName)
for instance in sorted(instanceList):
genString = genString + "'{instance}', ".format(instance=instance)
if genString.endswith(', '):
genString = genString[:-2]
genString = genString + '],\n'
if genString.endswith(',\n'):
genString = genString[:-len(',\n')]
genString = genString + '}\n'
with open(genFile, 'a+') as f:
f.write(genString)
# append key for fetching at the end
regionKey = '\nec2InstancesByRegion = dict((region, [E2Instances[i] for i in instances]) for region, instances in iteritems(regionDict))\n'
with open(genFile, 'a+') as f:
f.write(regionKey)
# preserve the original file unless it already exists
if not os.path.exists(oldFile):
os.rename(origFile, oldFile)
# delete the original file if it's still there
if os.path.exists(origFile):
os.remove(origFile)
# replace the instance list with a current list
os.rename(genFile, origFile) | [
"def",
"updateStaticEC2Instances",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"Updating Toil's EC2 lists to the most current version from AWS's bulk API. \"",
"\"This may take a while, depending on your internet connection.\"",
")",
"dirname",
"=",
"os",
".",
"path",
".",
"dir... | Generates a new python file of fetchable EC2 Instances by region with current prices and specs.
Takes a few (~3+) minutes to run (you'll need decent internet).
:return: Nothing. Writes a new 'generatedEC2Lists.py' file. | [
"Generates",
"a",
"new",
"python",
"file",
"of",
"fetchable",
"EC2",
"Instances",
"by",
"region",
"with",
"current",
"prices",
"and",
"specs",
"."
] | a8252277ff814e7bee0971139c2344f88e44b644 | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/lib/ec2nodes.py#L208-L299 |
225,201 | DataBiosphere/toil | src/toil/batchSystems/singleMachine.py | SingleMachineBatchSystem._runWorker | def _runWorker(self, jobCommand, jobID, environment):
"""
Run the jobCommand using the worker and wait for it to finish.
The worker is forked unless it is a '_toil_worker' job and
debugWorker is True.
"""
startTime = time.time() # Time job is started
if self.debugWorker and "_toil_worker" in jobCommand:
# Run the worker without forking
jobName, jobStoreLocator, jobStoreID = jobCommand.split()[1:] # Parse command
jobStore = Toil.resumeJobStore(jobStoreLocator)
# TODO: The following does not yet properly populate self.runningJobs so it is not possible to kill
# running jobs in forkless mode - see the "None" value in place of popen
info = Info(time.time(), None, killIntended=False)
try:
self.runningJobs[jobID] = info
try:
toil_worker.workerScript(jobStore, jobStore.config, jobName, jobStoreID,
redirectOutputToLogFile=not self.debugWorker) # Call the worker
finally:
self.runningJobs.pop(jobID)
finally:
if not info.killIntended:
self.outputQueue.put((jobID, 0, time.time() - startTime))
else:
with self.popenLock:
popen = subprocess.Popen(jobCommand,
shell=True,
env=dict(os.environ, **environment))
info = Info(time.time(), popen, killIntended=False)
try:
self.runningJobs[jobID] = info
try:
statusCode = popen.wait()
if statusCode != 0 and not info.killIntended:
log.error("Got exit code %i (indicating failure) "
"from job %s.", statusCode, self.jobs[jobID])
finally:
self.runningJobs.pop(jobID)
finally:
if not info.killIntended:
self.outputQueue.put((jobID, statusCode, time.time() - startTime)) | python | def _runWorker(self, jobCommand, jobID, environment):
startTime = time.time() # Time job is started
if self.debugWorker and "_toil_worker" in jobCommand:
# Run the worker without forking
jobName, jobStoreLocator, jobStoreID = jobCommand.split()[1:] # Parse command
jobStore = Toil.resumeJobStore(jobStoreLocator)
# TODO: The following does not yet properly populate self.runningJobs so it is not possible to kill
# running jobs in forkless mode - see the "None" value in place of popen
info = Info(time.time(), None, killIntended=False)
try:
self.runningJobs[jobID] = info
try:
toil_worker.workerScript(jobStore, jobStore.config, jobName, jobStoreID,
redirectOutputToLogFile=not self.debugWorker) # Call the worker
finally:
self.runningJobs.pop(jobID)
finally:
if not info.killIntended:
self.outputQueue.put((jobID, 0, time.time() - startTime))
else:
with self.popenLock:
popen = subprocess.Popen(jobCommand,
shell=True,
env=dict(os.environ, **environment))
info = Info(time.time(), popen, killIntended=False)
try:
self.runningJobs[jobID] = info
try:
statusCode = popen.wait()
if statusCode != 0 and not info.killIntended:
log.error("Got exit code %i (indicating failure) "
"from job %s.", statusCode, self.jobs[jobID])
finally:
self.runningJobs.pop(jobID)
finally:
if not info.killIntended:
self.outputQueue.put((jobID, statusCode, time.time() - startTime)) | [
"def",
"_runWorker",
"(",
"self",
",",
"jobCommand",
",",
"jobID",
",",
"environment",
")",
":",
"startTime",
"=",
"time",
".",
"time",
"(",
")",
"# Time job is started",
"if",
"self",
".",
"debugWorker",
"and",
"\"_toil_worker\"",
"in",
"jobCommand",
":",
"... | Run the jobCommand using the worker and wait for it to finish.
The worker is forked unless it is a '_toil_worker' job and
debugWorker is True. | [
"Run",
"the",
"jobCommand",
"using",
"the",
"worker",
"and",
"wait",
"for",
"it",
"to",
"finish",
".",
"The",
"worker",
"is",
"forked",
"unless",
"it",
"is",
"a",
"_toil_worker",
"job",
"and",
"debugWorker",
"is",
"True",
"."
] | a8252277ff814e7bee0971139c2344f88e44b644 | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/batchSystems/singleMachine.py#L136-L177 |
225,202 | DataBiosphere/toil | src/toil/batchSystems/singleMachine.py | SingleMachineBatchSystem.issueBatchJob | def issueBatchJob(self, jobNode):
"""Adds the command and resources to a queue to be run."""
# Round cores to minCores and apply scale
cores = math.ceil(jobNode.cores * self.scale / self.minCores) * self.minCores
assert cores <= self.maxCores, ('The job {} is requesting {} cores, more than the maximum of '
'{} cores this batch system was configured with. Scale is '
'set to {}.'.format(jobNode.jobName, cores, self.maxCores, self.scale))
assert cores >= self.minCores
assert jobNode.memory <= self.maxMemory, ('The job {} is requesting {} bytes of memory, more than '
'the maximum of {} this batch system was configured '
'with.'.format(jobNode.jobName, jobNode.memory, self.maxMemory))
self.checkResourceRequest(jobNode.memory, cores, jobNode.disk)
log.debug("Issuing the command: %s with memory: %i, cores: %i, disk: %i" % (
jobNode.command, jobNode.memory, cores, jobNode.disk))
with self.jobIndexLock:
jobID = self.jobIndex
self.jobIndex += 1
self.jobs[jobID] = jobNode.command
self.inputQueue.put((jobNode.command, jobID, cores, jobNode.memory,
jobNode.disk, self.environment.copy()))
if self.debugWorker: # then run immediately, blocking for return
self.worker(self.inputQueue)
return jobID | python | def issueBatchJob(self, jobNode):
# Round cores to minCores and apply scale
cores = math.ceil(jobNode.cores * self.scale / self.minCores) * self.minCores
assert cores <= self.maxCores, ('The job {} is requesting {} cores, more than the maximum of '
'{} cores this batch system was configured with. Scale is '
'set to {}.'.format(jobNode.jobName, cores, self.maxCores, self.scale))
assert cores >= self.minCores
assert jobNode.memory <= self.maxMemory, ('The job {} is requesting {} bytes of memory, more than '
'the maximum of {} this batch system was configured '
'with.'.format(jobNode.jobName, jobNode.memory, self.maxMemory))
self.checkResourceRequest(jobNode.memory, cores, jobNode.disk)
log.debug("Issuing the command: %s with memory: %i, cores: %i, disk: %i" % (
jobNode.command, jobNode.memory, cores, jobNode.disk))
with self.jobIndexLock:
jobID = self.jobIndex
self.jobIndex += 1
self.jobs[jobID] = jobNode.command
self.inputQueue.put((jobNode.command, jobID, cores, jobNode.memory,
jobNode.disk, self.environment.copy()))
if self.debugWorker: # then run immediately, blocking for return
self.worker(self.inputQueue)
return jobID | [
"def",
"issueBatchJob",
"(",
"self",
",",
"jobNode",
")",
":",
"# Round cores to minCores and apply scale",
"cores",
"=",
"math",
".",
"ceil",
"(",
"jobNode",
".",
"cores",
"*",
"self",
".",
"scale",
"/",
"self",
".",
"minCores",
")",
"*",
"self",
".",
"mi... | Adds the command and resources to a queue to be run. | [
"Adds",
"the",
"command",
"and",
"resources",
"to",
"a",
"queue",
"to",
"be",
"run",
"."
] | a8252277ff814e7bee0971139c2344f88e44b644 | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/batchSystems/singleMachine.py#L220-L243 |
225,203 | DataBiosphere/toil | src/toil/batchSystems/singleMachine.py | SingleMachineBatchSystem.killBatchJobs | def killBatchJobs(self, jobIDs):
"""Kills jobs by ID."""
log.debug('Killing jobs: {}'.format(jobIDs))
for jobID in jobIDs:
if jobID in self.runningJobs:
info = self.runningJobs[jobID]
info.killIntended = True
if info.popen != None:
os.kill(info.popen.pid, 9)
else:
# No popen if running in forkless mode currently
assert self.debugWorker
log.critical("Can't kill job: %s in debug mode" % jobID)
while jobID in self.runningJobs:
pass | python | def killBatchJobs(self, jobIDs):
log.debug('Killing jobs: {}'.format(jobIDs))
for jobID in jobIDs:
if jobID in self.runningJobs:
info = self.runningJobs[jobID]
info.killIntended = True
if info.popen != None:
os.kill(info.popen.pid, 9)
else:
# No popen if running in forkless mode currently
assert self.debugWorker
log.critical("Can't kill job: %s in debug mode" % jobID)
while jobID in self.runningJobs:
pass | [
"def",
"killBatchJobs",
"(",
"self",
",",
"jobIDs",
")",
":",
"log",
".",
"debug",
"(",
"'Killing jobs: {}'",
".",
"format",
"(",
"jobIDs",
")",
")",
"for",
"jobID",
"in",
"jobIDs",
":",
"if",
"jobID",
"in",
"self",
".",
"runningJobs",
":",
"info",
"="... | Kills jobs by ID. | [
"Kills",
"jobs",
"by",
"ID",
"."
] | a8252277ff814e7bee0971139c2344f88e44b644 | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/batchSystems/singleMachine.py#L245-L259 |
225,204 | DataBiosphere/toil | src/toil/batchSystems/singleMachine.py | SingleMachineBatchSystem.shutdown | def shutdown(self):
"""
Cleanly terminate worker threads. Add sentinels to inputQueue equal to maxThreads. Join
all worker threads.
"""
# Remove reference to inputQueue (raises exception if inputQueue is used after method call)
inputQueue = self.inputQueue
self.inputQueue = None
for i in range(self.numWorkers):
inputQueue.put(None)
for thread in self.workerThreads:
thread.join()
BatchSystemSupport.workerCleanup(self.workerCleanupInfo) | python | def shutdown(self):
# Remove reference to inputQueue (raises exception if inputQueue is used after method call)
inputQueue = self.inputQueue
self.inputQueue = None
for i in range(self.numWorkers):
inputQueue.put(None)
for thread in self.workerThreads:
thread.join()
BatchSystemSupport.workerCleanup(self.workerCleanupInfo) | [
"def",
"shutdown",
"(",
"self",
")",
":",
"# Remove reference to inputQueue (raises exception if inputQueue is used after method call)",
"inputQueue",
"=",
"self",
".",
"inputQueue",
"self",
".",
"inputQueue",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"self",
".",
... | Cleanly terminate worker threads. Add sentinels to inputQueue equal to maxThreads. Join
all worker threads. | [
"Cleanly",
"terminate",
"worker",
"threads",
".",
"Add",
"sentinels",
"to",
"inputQueue",
"equal",
"to",
"maxThreads",
".",
"Join",
"all",
"worker",
"threads",
"."
] | a8252277ff814e7bee0971139c2344f88e44b644 | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/batchSystems/singleMachine.py#L269-L281 |
225,205 | DataBiosphere/toil | src/toil/batchSystems/singleMachine.py | SingleMachineBatchSystem.getUpdatedBatchJob | def getUpdatedBatchJob(self, maxWait):
"""Returns a map of the run jobs and the return value of their processes."""
try:
item = self.outputQueue.get(timeout=maxWait)
except Empty:
return None
jobID, exitValue, wallTime = item
jobCommand = self.jobs.pop(jobID)
log.debug("Ran jobID: %s with exit value: %i", jobID, exitValue)
return jobID, exitValue, wallTime | python | def getUpdatedBatchJob(self, maxWait):
try:
item = self.outputQueue.get(timeout=maxWait)
except Empty:
return None
jobID, exitValue, wallTime = item
jobCommand = self.jobs.pop(jobID)
log.debug("Ran jobID: %s with exit value: %i", jobID, exitValue)
return jobID, exitValue, wallTime | [
"def",
"getUpdatedBatchJob",
"(",
"self",
",",
"maxWait",
")",
":",
"try",
":",
"item",
"=",
"self",
".",
"outputQueue",
".",
"get",
"(",
"timeout",
"=",
"maxWait",
")",
"except",
"Empty",
":",
"return",
"None",
"jobID",
",",
"exitValue",
",",
"wallTime"... | Returns a map of the run jobs and the return value of their processes. | [
"Returns",
"a",
"map",
"of",
"the",
"run",
"jobs",
"and",
"the",
"return",
"value",
"of",
"their",
"processes",
"."
] | a8252277ff814e7bee0971139c2344f88e44b644 | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/batchSystems/singleMachine.py#L283-L292 |
225,206 | DataBiosphere/toil | src/toil/batchSystems/mesos/executor.py | MesosExecutor.registered | def registered(self, driver, executorInfo, frameworkInfo, agentInfo):
"""
Invoked once the executor driver has been able to successfully connect with Mesos.
"""
# Get the ID we have been assigned, if we have it
self.id = executorInfo.executor_id.get('value', None)
log.debug("Registered executor %s with framework", self.id)
self.address = socket.gethostbyname(agentInfo.hostname)
nodeInfoThread = threading.Thread(target=self._sendFrameworkMessage, args=[driver])
nodeInfoThread.daemon = True
nodeInfoThread.start() | python | def registered(self, driver, executorInfo, frameworkInfo, agentInfo):
# Get the ID we have been assigned, if we have it
self.id = executorInfo.executor_id.get('value', None)
log.debug("Registered executor %s with framework", self.id)
self.address = socket.gethostbyname(agentInfo.hostname)
nodeInfoThread = threading.Thread(target=self._sendFrameworkMessage, args=[driver])
nodeInfoThread.daemon = True
nodeInfoThread.start() | [
"def",
"registered",
"(",
"self",
",",
"driver",
",",
"executorInfo",
",",
"frameworkInfo",
",",
"agentInfo",
")",
":",
"# Get the ID we have been assigned, if we have it",
"self",
".",
"id",
"=",
"executorInfo",
".",
"executor_id",
".",
"get",
"(",
"'value'",
","... | Invoked once the executor driver has been able to successfully connect with Mesos. | [
"Invoked",
"once",
"the",
"executor",
"driver",
"has",
"been",
"able",
"to",
"successfully",
"connect",
"with",
"Mesos",
"."
] | a8252277ff814e7bee0971139c2344f88e44b644 | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/batchSystems/mesos/executor.py#L69-L81 |
225,207 | DataBiosphere/toil | src/toil/batchSystems/mesos/executor.py | MesosExecutor.killTask | def killTask(self, driver, taskId):
"""
Kill parent task process and all its spawned children
"""
try:
pid = self.runningTasks[taskId]
pgid = os.getpgid(pid)
except KeyError:
pass
else:
os.killpg(pgid, signal.SIGKILL) | python | def killTask(self, driver, taskId):
try:
pid = self.runningTasks[taskId]
pgid = os.getpgid(pid)
except KeyError:
pass
else:
os.killpg(pgid, signal.SIGKILL) | [
"def",
"killTask",
"(",
"self",
",",
"driver",
",",
"taskId",
")",
":",
"try",
":",
"pid",
"=",
"self",
".",
"runningTasks",
"[",
"taskId",
"]",
"pgid",
"=",
"os",
".",
"getpgid",
"(",
"pid",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"os... | Kill parent task process and all its spawned children | [
"Kill",
"parent",
"task",
"process",
"and",
"all",
"its",
"spawned",
"children"
] | a8252277ff814e7bee0971139c2344f88e44b644 | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/batchSystems/mesos/executor.py#L96-L106 |
225,208 | DataBiosphere/toil | src/toil/lib/retry.py | retry | def retry( delays=(0, 1, 1, 4, 16, 64), timeout=300, predicate=never ):
"""
Retry an operation while the failure matches a given predicate and until a given timeout
expires, waiting a given amount of time in between attempts. This function is a generator
that yields contextmanagers. See doctests below for example usage.
:param Iterable[float] delays: an interable yielding the time in seconds to wait before each
retried attempt, the last element of the iterable will be repeated.
:param float timeout: a overall timeout that should not be exceeded for all attempts together.
This is a best-effort mechanism only and it won't abort an ongoing attempt, even if the
timeout expires during that attempt.
:param Callable[[Exception],bool] predicate: a unary callable returning True if another
attempt should be made to recover from the given exception. The default value for this
parameter will prevent any retries!
:return: a generator yielding context managers, one per attempt
:rtype: Iterator
Retry for a limited amount of time:
>>> true = lambda _:True
>>> false = lambda _:False
>>> i = 0
>>> for attempt in retry( delays=[0], timeout=.1, predicate=true ):
... with attempt:
... i += 1
... raise RuntimeError('foo')
Traceback (most recent call last):
...
RuntimeError: foo
>>> i > 1
True
If timeout is 0, do exactly one attempt:
>>> i = 0
>>> for attempt in retry( timeout=0 ):
... with attempt:
... i += 1
... raise RuntimeError( 'foo' )
Traceback (most recent call last):
...
RuntimeError: foo
>>> i
1
Don't retry on success:
>>> i = 0
>>> for attempt in retry( delays=[0], timeout=.1, predicate=true ):
... with attempt:
... i += 1
>>> i
1
Don't retry on unless predicate returns True:
>>> i = 0
>>> for attempt in retry( delays=[0], timeout=.1, predicate=false):
... with attempt:
... i += 1
... raise RuntimeError( 'foo' )
Traceback (most recent call last):
...
RuntimeError: foo
>>> i
1
"""
if timeout > 0:
go = [ None ]
@contextmanager
def repeated_attempt( delay ):
try:
yield
except Exception as e:
if time.time( ) + delay < expiration and predicate( e ):
log.info( 'Got %s, trying again in %is.', e, delay )
time.sleep( delay )
else:
raise
else:
go.pop( )
delays = iter( delays )
expiration = time.time( ) + timeout
delay = next( delays )
while go:
yield repeated_attempt( delay )
delay = next( delays, delay )
else:
@contextmanager
def single_attempt( ):
yield
yield single_attempt( ) | python | def retry( delays=(0, 1, 1, 4, 16, 64), timeout=300, predicate=never ):
if timeout > 0:
go = [ None ]
@contextmanager
def repeated_attempt( delay ):
try:
yield
except Exception as e:
if time.time( ) + delay < expiration and predicate( e ):
log.info( 'Got %s, trying again in %is.', e, delay )
time.sleep( delay )
else:
raise
else:
go.pop( )
delays = iter( delays )
expiration = time.time( ) + timeout
delay = next( delays )
while go:
yield repeated_attempt( delay )
delay = next( delays, delay )
else:
@contextmanager
def single_attempt( ):
yield
yield single_attempt( ) | [
"def",
"retry",
"(",
"delays",
"=",
"(",
"0",
",",
"1",
",",
"1",
",",
"4",
",",
"16",
",",
"64",
")",
",",
"timeout",
"=",
"300",
",",
"predicate",
"=",
"never",
")",
":",
"if",
"timeout",
">",
"0",
":",
"go",
"=",
"[",
"None",
"]",
"@",
... | Retry an operation while the failure matches a given predicate and until a given timeout
expires, waiting a given amount of time in between attempts. This function is a generator
that yields contextmanagers. See doctests below for example usage.
:param Iterable[float] delays: an interable yielding the time in seconds to wait before each
retried attempt, the last element of the iterable will be repeated.
:param float timeout: a overall timeout that should not be exceeded for all attempts together.
This is a best-effort mechanism only and it won't abort an ongoing attempt, even if the
timeout expires during that attempt.
:param Callable[[Exception],bool] predicate: a unary callable returning True if another
attempt should be made to recover from the given exception. The default value for this
parameter will prevent any retries!
:return: a generator yielding context managers, one per attempt
:rtype: Iterator
Retry for a limited amount of time:
>>> true = lambda _:True
>>> false = lambda _:False
>>> i = 0
>>> for attempt in retry( delays=[0], timeout=.1, predicate=true ):
... with attempt:
... i += 1
... raise RuntimeError('foo')
Traceback (most recent call last):
...
RuntimeError: foo
>>> i > 1
True
If timeout is 0, do exactly one attempt:
>>> i = 0
>>> for attempt in retry( timeout=0 ):
... with attempt:
... i += 1
... raise RuntimeError( 'foo' )
Traceback (most recent call last):
...
RuntimeError: foo
>>> i
1
Don't retry on success:
>>> i = 0
>>> for attempt in retry( delays=[0], timeout=.1, predicate=true ):
... with attempt:
... i += 1
>>> i
1
Don't retry on unless predicate returns True:
>>> i = 0
>>> for attempt in retry( delays=[0], timeout=.1, predicate=false):
... with attempt:
... i += 1
... raise RuntimeError( 'foo' )
Traceback (most recent call last):
...
RuntimeError: foo
>>> i
1 | [
"Retry",
"an",
"operation",
"while",
"the",
"failure",
"matches",
"a",
"given",
"predicate",
"and",
"until",
"a",
"given",
"timeout",
"expires",
"waiting",
"a",
"given",
"amount",
"of",
"time",
"in",
"between",
"attempts",
".",
"This",
"function",
"is",
"a",... | a8252277ff814e7bee0971139c2344f88e44b644 | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/lib/retry.py#L40-L137 |
225,209 | DataBiosphere/toil | src/toil/lib/retry.py | retryable_http_error | def retryable_http_error( e ):
"""
Determine if an error encountered during an HTTP download is likely to go away if we try again.
"""
if isinstance( e, urllib.error.HTTPError ) and e.code in ('503', '408', '500'):
# The server returned one of:
# 503 Service Unavailable
# 408 Request Timeout
# 500 Internal Server Error
return True
if isinstance( e, BadStatusLine ):
# The server didn't return a valid response at all
return True
return False | python | def retryable_http_error( e ):
if isinstance( e, urllib.error.HTTPError ) and e.code in ('503', '408', '500'):
# The server returned one of:
# 503 Service Unavailable
# 408 Request Timeout
# 500 Internal Server Error
return True
if isinstance( e, BadStatusLine ):
# The server didn't return a valid response at all
return True
return False | [
"def",
"retryable_http_error",
"(",
"e",
")",
":",
"if",
"isinstance",
"(",
"e",
",",
"urllib",
".",
"error",
".",
"HTTPError",
")",
"and",
"e",
".",
"code",
"in",
"(",
"'503'",
",",
"'408'",
",",
"'500'",
")",
":",
"# The server returned one of:",
"# 50... | Determine if an error encountered during an HTTP download is likely to go away if we try again. | [
"Determine",
"if",
"an",
"error",
"encountered",
"during",
"an",
"HTTP",
"download",
"is",
"likely",
"to",
"go",
"away",
"if",
"we",
"try",
"again",
"."
] | a8252277ff814e7bee0971139c2344f88e44b644 | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/lib/retry.py#L144-L157 |
225,210 | DataBiosphere/toil | src/toil/batchSystems/abstractGridEngineBatchSystem.py | AbstractGridEngineBatchSystem.getRunningBatchJobIDs | def getRunningBatchJobIDs(self):
"""
Retrieve running job IDs from local and batch scheduler.
Respects statePollingWait and will return cached results if not within
time period to talk with the scheduler.
"""
if (self._getRunningBatchJobIDsTimestamp and (
datetime.now() -
self._getRunningBatchJobIDsTimestamp).total_seconds() <
self.config.statePollingWait):
batchIds = self._getRunningBatchJobIDsCache
else:
batchIds = with_retries(self.worker.getRunningJobIDs)
self._getRunningBatchJobIDsCache = batchIds
self._getRunningBatchJobIDsTimestamp = datetime.now()
batchIds.update(self.getRunningLocalJobIDs())
return batchIds | python | def getRunningBatchJobIDs(self):
if (self._getRunningBatchJobIDsTimestamp and (
datetime.now() -
self._getRunningBatchJobIDsTimestamp).total_seconds() <
self.config.statePollingWait):
batchIds = self._getRunningBatchJobIDsCache
else:
batchIds = with_retries(self.worker.getRunningJobIDs)
self._getRunningBatchJobIDsCache = batchIds
self._getRunningBatchJobIDsTimestamp = datetime.now()
batchIds.update(self.getRunningLocalJobIDs())
return batchIds | [
"def",
"getRunningBatchJobIDs",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_getRunningBatchJobIDsTimestamp",
"and",
"(",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"_getRunningBatchJobIDsTimestamp",
")",
".",
"total_seconds",
"(",
")",
"<",
"self... | Retrieve running job IDs from local and batch scheduler.
Respects statePollingWait and will return cached results if not within
time period to talk with the scheduler. | [
"Retrieve",
"running",
"job",
"IDs",
"from",
"local",
"and",
"batch",
"scheduler",
"."
] | a8252277ff814e7bee0971139c2344f88e44b644 | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/batchSystems/abstractGridEngineBatchSystem.py#L368-L385 |
225,211 | DAI-Lab/Copulas | copulas/multivariate/gaussian.py | GaussianMultivariate.get_lower_bound | def get_lower_bound(self):
"""Compute the lower bound to integrate cumulative density.
Returns:
float: lower bound for cumulative density integral.
"""
lower_bounds = []
for distribution in self.distribs.values():
lower_bound = distribution.percent_point(distribution.mean / 10000)
if not pd.isnull(lower_bound):
lower_bounds.append(lower_bound)
return min(lower_bounds) | python | def get_lower_bound(self):
lower_bounds = []
for distribution in self.distribs.values():
lower_bound = distribution.percent_point(distribution.mean / 10000)
if not pd.isnull(lower_bound):
lower_bounds.append(lower_bound)
return min(lower_bounds) | [
"def",
"get_lower_bound",
"(",
"self",
")",
":",
"lower_bounds",
"=",
"[",
"]",
"for",
"distribution",
"in",
"self",
".",
"distribs",
".",
"values",
"(",
")",
":",
"lower_bound",
"=",
"distribution",
".",
"percent_point",
"(",
"distribution",
".",
"mean",
... | Compute the lower bound to integrate cumulative density.
Returns:
float: lower bound for cumulative density integral. | [
"Compute",
"the",
"lower",
"bound",
"to",
"integrate",
"cumulative",
"density",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/gaussian.py#L42-L55 |
225,212 | DAI-Lab/Copulas | copulas/multivariate/gaussian.py | GaussianMultivariate.get_column_names | def get_column_names(self, X):
"""Return iterable containing columns for the given array X.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
Returns:
iterable: columns for the given matrix.
"""
if isinstance(X, pd.DataFrame):
return X.columns
return range(X.shape[1]) | python | def get_column_names(self, X):
if isinstance(X, pd.DataFrame):
return X.columns
return range(X.shape[1]) | [
"def",
"get_column_names",
"(",
"self",
",",
"X",
")",
":",
"if",
"isinstance",
"(",
"X",
",",
"pd",
".",
"DataFrame",
")",
":",
"return",
"X",
".",
"columns",
"return",
"range",
"(",
"X",
".",
"shape",
"[",
"1",
"]",
")"
] | Return iterable containing columns for the given array X.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
Returns:
iterable: columns for the given matrix. | [
"Return",
"iterable",
"containing",
"columns",
"for",
"the",
"given",
"array",
"X",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/gaussian.py#L57-L69 |
225,213 | DAI-Lab/Copulas | copulas/multivariate/gaussian.py | GaussianMultivariate.get_column | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] | python | def get_column(self, X, column):
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] | [
"def",
"get_column",
"(",
"self",
",",
"X",
",",
"column",
")",
":",
"if",
"isinstance",
"(",
"X",
",",
"pd",
".",
"DataFrame",
")",
":",
"return",
"X",
"[",
"column",
"]",
".",
"values",
"return",
"X",
"[",
":",
",",
"column",
"]"
] | Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column. | [
"Return",
"a",
"column",
"of",
"the",
"given",
"matrix",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/gaussian.py#L71-L84 |
225,214 | DAI-Lab/Copulas | copulas/multivariate/gaussian.py | GaussianMultivariate.set_column | def set_column(self, X, column, value):
"""Sets a column on the matrix X with the given value.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
value: `np.ndarray` with shape (1,)
Returns:
`np.ndarray` or `pandas.DataFrame` with the inserted column.
"""
if isinstance(X, pd.DataFrame):
X.loc[:, column] = value
else:
X[:, column] = value
return X | python | def set_column(self, X, column, value):
if isinstance(X, pd.DataFrame):
X.loc[:, column] = value
else:
X[:, column] = value
return X | [
"def",
"set_column",
"(",
"self",
",",
"X",
",",
"column",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"X",
",",
"pd",
".",
"DataFrame",
")",
":",
"X",
".",
"loc",
"[",
":",
",",
"column",
"]",
"=",
"value",
"else",
":",
"X",
"[",
":",
"... | Sets a column on the matrix X with the given value.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
value: `np.ndarray` with shape (1,)
Returns:
`np.ndarray` or `pandas.DataFrame` with the inserted column. | [
"Sets",
"a",
"column",
"on",
"the",
"matrix",
"X",
"with",
"the",
"given",
"value",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/gaussian.py#L86-L105 |
225,215 | DAI-Lab/Copulas | copulas/multivariate/gaussian.py | GaussianMultivariate._get_covariance | def _get_covariance(self, X):
"""Compute covariance matrix with transformed data.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
Returns:
np.ndarray
"""
result = pd.DataFrame(index=range(len(X)))
column_names = self.get_column_names(X)
for column_name in column_names:
column = self.get_column(X, column_name)
distrib = self.distribs[column_name]
# get original distrib's cdf of the column
cdf = distrib.cumulative_distribution(column)
if distrib.constant_value is not None:
# This is to avoid np.inf in the case the column is constant.
cdf = np.ones(column.shape) - EPSILON
# get inverse cdf using standard normal
result = self.set_column(result, column_name, stats.norm.ppf(cdf))
# remove any rows that have infinite values
result = result[(result != np.inf).all(axis=1)]
return pd.DataFrame(data=result).cov().values | python | def _get_covariance(self, X):
result = pd.DataFrame(index=range(len(X)))
column_names = self.get_column_names(X)
for column_name in column_names:
column = self.get_column(X, column_name)
distrib = self.distribs[column_name]
# get original distrib's cdf of the column
cdf = distrib.cumulative_distribution(column)
if distrib.constant_value is not None:
# This is to avoid np.inf in the case the column is constant.
cdf = np.ones(column.shape) - EPSILON
# get inverse cdf using standard normal
result = self.set_column(result, column_name, stats.norm.ppf(cdf))
# remove any rows that have infinite values
result = result[(result != np.inf).all(axis=1)]
return pd.DataFrame(data=result).cov().values | [
"def",
"_get_covariance",
"(",
"self",
",",
"X",
")",
":",
"result",
"=",
"pd",
".",
"DataFrame",
"(",
"index",
"=",
"range",
"(",
"len",
"(",
"X",
")",
")",
")",
"column_names",
"=",
"self",
".",
"get_column_names",
"(",
"X",
")",
"for",
"column_nam... | Compute covariance matrix with transformed data.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
Returns:
np.ndarray | [
"Compute",
"covariance",
"matrix",
"with",
"transformed",
"data",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/gaussian.py#L107-L135 |
225,216 | DAI-Lab/Copulas | copulas/multivariate/gaussian.py | GaussianMultivariate.fit | def fit(self, X):
"""Compute the distribution for each variable and then its covariance matrix.
Args:
X(numpy.ndarray or pandas.DataFrame): Data to model.
Returns:
None
"""
LOGGER.debug('Fitting Gaussian Copula')
column_names = self.get_column_names(X)
distribution_class = import_object(self.distribution)
for column_name in column_names:
self.distribs[column_name] = distribution_class()
column = self.get_column(X, column_name)
self.distribs[column_name].fit(column)
self.covariance = self._get_covariance(X)
self.fitted = True | python | def fit(self, X):
LOGGER.debug('Fitting Gaussian Copula')
column_names = self.get_column_names(X)
distribution_class = import_object(self.distribution)
for column_name in column_names:
self.distribs[column_name] = distribution_class()
column = self.get_column(X, column_name)
self.distribs[column_name].fit(column)
self.covariance = self._get_covariance(X)
self.fitted = True | [
"def",
"fit",
"(",
"self",
",",
"X",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Fitting Gaussian Copula'",
")",
"column_names",
"=",
"self",
".",
"get_column_names",
"(",
"X",
")",
"distribution_class",
"=",
"import_object",
"(",
"self",
".",
"distribution",
"... | Compute the distribution for each variable and then its covariance matrix.
Args:
X(numpy.ndarray or pandas.DataFrame): Data to model.
Returns:
None | [
"Compute",
"the",
"distribution",
"for",
"each",
"variable",
"and",
"then",
"its",
"covariance",
"matrix",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/gaussian.py#L138-L157 |
225,217 | DAI-Lab/Copulas | copulas/multivariate/gaussian.py | GaussianMultivariate.cumulative_distribution | def cumulative_distribution(self, X):
"""Computes the cumulative distribution function for the copula
Args:
X: `numpy.ndarray` or `pandas.DataFrame`
Returns:
np.array: cumulative probability
"""
self.check_fit()
# Wrapper for pdf to accept vector as args
def func(*args):
return self.probability_density(list(args))
# Lower bound for integral, to split significant part from tail
lower_bound = self.get_lower_bound()
ranges = [[lower_bound, val] for val in X]
return integrate.nquad(func, ranges)[0] | python | def cumulative_distribution(self, X):
self.check_fit()
# Wrapper for pdf to accept vector as args
def func(*args):
return self.probability_density(list(args))
# Lower bound for integral, to split significant part from tail
lower_bound = self.get_lower_bound()
ranges = [[lower_bound, val] for val in X]
return integrate.nquad(func, ranges)[0] | [
"def",
"cumulative_distribution",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"# Wrapper for pdf to accept vector as args",
"def",
"func",
"(",
"*",
"args",
")",
":",
"return",
"self",
".",
"probability_density",
"(",
"list",
"(",
"arg... | Computes the cumulative distribution function for the copula
Args:
X: `numpy.ndarray` or `pandas.DataFrame`
Returns:
np.array: cumulative probability | [
"Computes",
"the",
"cumulative",
"distribution",
"function",
"for",
"the",
"copula"
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/gaussian.py#L174-L193 |
225,218 | DAI-Lab/Copulas | copulas/multivariate/gaussian.py | GaussianMultivariate.sample | def sample(self, num_rows=1):
"""Creates sintentic values stadistically similar to the original dataset.
Args:
num_rows: `int` amount of samples to generate.
Returns:
np.ndarray: Sampled data.
"""
self.check_fit()
res = {}
means = np.zeros(self.covariance.shape[0])
size = (num_rows,)
clean_cov = np.nan_to_num(self.covariance)
samples = np.random.multivariate_normal(means, clean_cov, size=size)
for i, (label, distrib) in enumerate(self.distribs.items()):
cdf = stats.norm.cdf(samples[:, i])
res[label] = distrib.percent_point(cdf)
return pd.DataFrame(data=res) | python | def sample(self, num_rows=1):
self.check_fit()
res = {}
means = np.zeros(self.covariance.shape[0])
size = (num_rows,)
clean_cov = np.nan_to_num(self.covariance)
samples = np.random.multivariate_normal(means, clean_cov, size=size)
for i, (label, distrib) in enumerate(self.distribs.items()):
cdf = stats.norm.cdf(samples[:, i])
res[label] = distrib.percent_point(cdf)
return pd.DataFrame(data=res) | [
"def",
"sample",
"(",
"self",
",",
"num_rows",
"=",
"1",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"res",
"=",
"{",
"}",
"means",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"covariance",
".",
"shape",
"[",
"0",
"]",
")",
"size",
"=",
"(",
... | Creates sintentic values stadistically similar to the original dataset.
Args:
num_rows: `int` amount of samples to generate.
Returns:
np.ndarray: Sampled data. | [
"Creates",
"sintentic",
"values",
"stadistically",
"similar",
"to",
"the",
"original",
"dataset",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/gaussian.py#L196-L219 |
225,219 | DAI-Lab/Copulas | copulas/univariate/gaussian.py | GaussianUnivariate.probability_density | def probability_density(self, X):
"""Compute probability density.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
np.ndarray
"""
self.check_fit()
return norm.pdf(X, loc=self.mean, scale=self.std) | python | def probability_density(self, X):
self.check_fit()
return norm.pdf(X, loc=self.mean, scale=self.std) | [
"def",
"probability_density",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"return",
"norm",
".",
"pdf",
"(",
"X",
",",
"loc",
"=",
"self",
".",
"mean",
",",
"scale",
"=",
"self",
".",
"std",
")"
] | Compute probability density.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
np.ndarray | [
"Compute",
"probability",
"density",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/gaussian.py#L57-L67 |
225,220 | DAI-Lab/Copulas | copulas/univariate/gaussian.py | GaussianUnivariate.cumulative_distribution | def cumulative_distribution(self, X):
"""Cumulative distribution function for gaussian distribution.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
np.ndarray: Cumulative density for X.
"""
self.check_fit()
return norm.cdf(X, loc=self.mean, scale=self.std) | python | def cumulative_distribution(self, X):
self.check_fit()
return norm.cdf(X, loc=self.mean, scale=self.std) | [
"def",
"cumulative_distribution",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"return",
"norm",
".",
"cdf",
"(",
"X",
",",
"loc",
"=",
"self",
".",
"mean",
",",
"scale",
"=",
"self",
".",
"std",
")"
] | Cumulative distribution function for gaussian distribution.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
np.ndarray: Cumulative density for X. | [
"Cumulative",
"distribution",
"function",
"for",
"gaussian",
"distribution",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/gaussian.py#L69-L79 |
225,221 | DAI-Lab/Copulas | copulas/univariate/gaussian.py | GaussianUnivariate.percent_point | def percent_point(self, U):
"""Given a cumulated distribution value, returns a value in original space.
Arguments:
U: `np.ndarray` of shape (n, 1) and values in [0,1]
Returns:
`np.ndarray`: Estimated values in original space.
"""
self.check_fit()
return norm.ppf(U, loc=self.mean, scale=self.std) | python | def percent_point(self, U):
self.check_fit()
return norm.ppf(U, loc=self.mean, scale=self.std) | [
"def",
"percent_point",
"(",
"self",
",",
"U",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"return",
"norm",
".",
"ppf",
"(",
"U",
",",
"loc",
"=",
"self",
".",
"mean",
",",
"scale",
"=",
"self",
".",
"std",
")"
] | Given a cumulated distribution value, returns a value in original space.
Arguments:
U: `np.ndarray` of shape (n, 1) and values in [0,1]
Returns:
`np.ndarray`: Estimated values in original space. | [
"Given",
"a",
"cumulated",
"distribution",
"value",
"returns",
"a",
"value",
"in",
"original",
"space",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/gaussian.py#L81-L91 |
225,222 | DAI-Lab/Copulas | copulas/univariate/gaussian.py | GaussianUnivariate.sample | def sample(self, num_samples=1):
"""Returns new data point based on model.
Arguments:
n_samples: `int`
Returns:
np.ndarray: Generated samples
"""
self.check_fit()
return np.random.normal(self.mean, self.std, num_samples) | python | def sample(self, num_samples=1):
self.check_fit()
return np.random.normal(self.mean, self.std, num_samples) | [
"def",
"sample",
"(",
"self",
",",
"num_samples",
"=",
"1",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"return",
"np",
".",
"random",
".",
"normal",
"(",
"self",
".",
"mean",
",",
"self",
".",
"std",
",",
"num_samples",
")"
] | Returns new data point based on model.
Arguments:
n_samples: `int`
Returns:
np.ndarray: Generated samples | [
"Returns",
"new",
"data",
"point",
"based",
"on",
"model",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/gaussian.py#L94-L104 |
225,223 | DAI-Lab/Copulas | copulas/bivariate/base.py | Bivariate.fit | def fit(self, X):
"""Fit a model to the data updating the parameters.
Args:
X: `np.ndarray` of shape (,2).
Return:
None
"""
U, V = self.split_matrix(X)
self.tau = stats.kendalltau(U, V)[0]
self.theta = self.compute_theta()
self.check_theta() | python | def fit(self, X):
U, V = self.split_matrix(X)
self.tau = stats.kendalltau(U, V)[0]
self.theta = self.compute_theta()
self.check_theta() | [
"def",
"fit",
"(",
"self",
",",
"X",
")",
":",
"U",
",",
"V",
"=",
"self",
".",
"split_matrix",
"(",
"X",
")",
"self",
".",
"tau",
"=",
"stats",
".",
"kendalltau",
"(",
"U",
",",
"V",
")",
"[",
"0",
"]",
"self",
".",
"theta",
"=",
"self",
"... | Fit a model to the data updating the parameters.
Args:
X: `np.ndarray` of shape (,2).
Return:
None | [
"Fit",
"a",
"model",
"to",
"the",
"data",
"updating",
"the",
"parameters",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/bivariate/base.py#L74-L86 |
225,224 | DAI-Lab/Copulas | copulas/bivariate/base.py | Bivariate.from_dict | def from_dict(cls, copula_dict):
"""Create a new instance from the given parameters.
Args:
copula_dict: `dict` with the parameters to replicate the copula.
Like the output of `Bivariate.to_dict`
Returns:
Bivariate: Instance of the copula defined on the parameters.
"""
instance = cls(copula_dict['copula_type'])
instance.theta = copula_dict['theta']
instance.tau = copula_dict['tau']
return instance | python | def from_dict(cls, copula_dict):
instance = cls(copula_dict['copula_type'])
instance.theta = copula_dict['theta']
instance.tau = copula_dict['tau']
return instance | [
"def",
"from_dict",
"(",
"cls",
",",
"copula_dict",
")",
":",
"instance",
"=",
"cls",
"(",
"copula_dict",
"[",
"'copula_type'",
"]",
")",
"instance",
".",
"theta",
"=",
"copula_dict",
"[",
"'theta'",
"]",
"instance",
".",
"tau",
"=",
"copula_dict",
"[",
... | Create a new instance from the given parameters.
Args:
copula_dict: `dict` with the parameters to replicate the copula.
Like the output of `Bivariate.to_dict`
Returns:
Bivariate: Instance of the copula defined on the parameters. | [
"Create",
"a",
"new",
"instance",
"from",
"the",
"given",
"parameters",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/bivariate/base.py#L104-L117 |
225,225 | DAI-Lab/Copulas | copulas/bivariate/base.py | Bivariate.check_theta | def check_theta(self):
"""Validate the computed theta against the copula specification.
This method is used to assert the computed theta is in the valid range for the copula."""
lower, upper = self.theta_interval
if (not lower <= self.theta <= upper) or (self.theta in self.invalid_thetas):
message = 'The computed theta value {} is out of limits for the given {} copula.'
raise ValueError(message.format(self.theta, self.copula_type.name)) | python | def check_theta(self):
lower, upper = self.theta_interval
if (not lower <= self.theta <= upper) or (self.theta in self.invalid_thetas):
message = 'The computed theta value {} is out of limits for the given {} copula.'
raise ValueError(message.format(self.theta, self.copula_type.name)) | [
"def",
"check_theta",
"(",
"self",
")",
":",
"lower",
",",
"upper",
"=",
"self",
".",
"theta_interval",
"if",
"(",
"not",
"lower",
"<=",
"self",
".",
"theta",
"<=",
"upper",
")",
"or",
"(",
"self",
".",
"theta",
"in",
"self",
".",
"invalid_thetas",
"... | Validate the computed theta against the copula specification.
This method is used to assert the computed theta is in the valid range for the copula. | [
"Validate",
"the",
"computed",
"theta",
"against",
"the",
"copula",
"specification",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/bivariate/base.py#L213-L220 |
225,226 | DAI-Lab/Copulas | copulas/bivariate/base.py | Bivariate.compute_empirical | def compute_empirical(cls, X):
"""Compute empirical distribution."""
z_left = []
z_right = []
L = []
R = []
U, V = cls.split_matrix(X)
N = len(U)
base = np.linspace(EPSILON, 1.0 - EPSILON, COMPUTE_EMPIRICAL_STEPS)
# See https://github.com/DAI-Lab/Copulas/issues/45
for k in range(COMPUTE_EMPIRICAL_STEPS):
left = sum(np.logical_and(U <= base[k], V <= base[k])) / N
right = sum(np.logical_and(U >= base[k], V >= base[k])) / N
if left > 0:
z_left.append(base[k])
L.append(left / base[k] ** 2)
if right > 0:
z_right.append(base[k])
R.append(right / (1 - z_right[k]) ** 2)
return z_left, L, z_right, R | python | def compute_empirical(cls, X):
z_left = []
z_right = []
L = []
R = []
U, V = cls.split_matrix(X)
N = len(U)
base = np.linspace(EPSILON, 1.0 - EPSILON, COMPUTE_EMPIRICAL_STEPS)
# See https://github.com/DAI-Lab/Copulas/issues/45
for k in range(COMPUTE_EMPIRICAL_STEPS):
left = sum(np.logical_and(U <= base[k], V <= base[k])) / N
right = sum(np.logical_and(U >= base[k], V >= base[k])) / N
if left > 0:
z_left.append(base[k])
L.append(left / base[k] ** 2)
if right > 0:
z_right.append(base[k])
R.append(right / (1 - z_right[k]) ** 2)
return z_left, L, z_right, R | [
"def",
"compute_empirical",
"(",
"cls",
",",
"X",
")",
":",
"z_left",
"=",
"[",
"]",
"z_right",
"=",
"[",
"]",
"L",
"=",
"[",
"]",
"R",
"=",
"[",
"]",
"U",
",",
"V",
"=",
"cls",
".",
"split_matrix",
"(",
"X",
")",
"N",
"=",
"len",
"(",
"U",... | Compute empirical distribution. | [
"Compute",
"empirical",
"distribution",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/bivariate/base.py#L240-L265 |
225,227 | DAI-Lab/Copulas | copulas/bivariate/base.py | Bivariate.select_copula | def select_copula(cls, X):
"""Select best copula function based on likelihood.
Args:
X: 2-dimensional `np.ndarray`
Returns:
tuple: `tuple(CopulaType, float)` best fit and model param.
"""
frank = Bivariate(CopulaTypes.FRANK)
frank.fit(X)
if frank.tau <= 0:
selected_theta = frank.theta
selected_copula = CopulaTypes.FRANK
return selected_copula, selected_theta
copula_candidates = [frank]
theta_candidates = [frank.theta]
try:
clayton = Bivariate(CopulaTypes.CLAYTON)
clayton.fit(X)
copula_candidates.append(clayton)
theta_candidates.append(clayton.theta)
except ValueError:
# Invalid theta, copula ignored
pass
try:
gumbel = Bivariate(CopulaTypes.GUMBEL)
gumbel.fit(X)
copula_candidates.append(gumbel)
theta_candidates.append(gumbel.theta)
except ValueError:
# Invalid theta, copula ignored
pass
z_left, L, z_right, R = cls.compute_empirical(X)
left_dependence, right_dependence = cls.get_dependencies(
copula_candidates, z_left, z_right)
# compute L2 distance from empirical distribution
cost_L = [np.sum((L - l) ** 2) for l in left_dependence]
cost_R = [np.sum((R - r) ** 2) for r in right_dependence]
cost_LR = np.add(cost_L, cost_R)
selected_copula = np.argmax(cost_LR)
selected_theta = theta_candidates[selected_copula]
return CopulaTypes(selected_copula), selected_theta | python | def select_copula(cls, X):
frank = Bivariate(CopulaTypes.FRANK)
frank.fit(X)
if frank.tau <= 0:
selected_theta = frank.theta
selected_copula = CopulaTypes.FRANK
return selected_copula, selected_theta
copula_candidates = [frank]
theta_candidates = [frank.theta]
try:
clayton = Bivariate(CopulaTypes.CLAYTON)
clayton.fit(X)
copula_candidates.append(clayton)
theta_candidates.append(clayton.theta)
except ValueError:
# Invalid theta, copula ignored
pass
try:
gumbel = Bivariate(CopulaTypes.GUMBEL)
gumbel.fit(X)
copula_candidates.append(gumbel)
theta_candidates.append(gumbel.theta)
except ValueError:
# Invalid theta, copula ignored
pass
z_left, L, z_right, R = cls.compute_empirical(X)
left_dependence, right_dependence = cls.get_dependencies(
copula_candidates, z_left, z_right)
# compute L2 distance from empirical distribution
cost_L = [np.sum((L - l) ** 2) for l in left_dependence]
cost_R = [np.sum((R - r) ** 2) for r in right_dependence]
cost_LR = np.add(cost_L, cost_R)
selected_copula = np.argmax(cost_LR)
selected_theta = theta_candidates[selected_copula]
return CopulaTypes(selected_copula), selected_theta | [
"def",
"select_copula",
"(",
"cls",
",",
"X",
")",
":",
"frank",
"=",
"Bivariate",
"(",
"CopulaTypes",
".",
"FRANK",
")",
"frank",
".",
"fit",
"(",
"X",
")",
"if",
"frank",
".",
"tau",
"<=",
"0",
":",
"selected_theta",
"=",
"frank",
".",
"theta",
"... | Select best copula function based on likelihood.
Args:
X: 2-dimensional `np.ndarray`
Returns:
tuple: `tuple(CopulaType, float)` best fit and model param. | [
"Select",
"best",
"copula",
"function",
"based",
"on",
"likelihood",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/bivariate/base.py#L287-L336 |
225,228 | DAI-Lab/Copulas | copulas/__init__.py | import_object | def import_object(object_name):
"""Import an object from its Fully Qualified Name."""
package, name = object_name.rsplit('.', 1)
return getattr(importlib.import_module(package), name) | python | def import_object(object_name):
package, name = object_name.rsplit('.', 1)
return getattr(importlib.import_module(package), name) | [
"def",
"import_object",
"(",
"object_name",
")",
":",
"package",
",",
"name",
"=",
"object_name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"return",
"getattr",
"(",
"importlib",
".",
"import_module",
"(",
"package",
")",
",",
"name",
")"
] | Import an object from its Fully Qualified Name. | [
"Import",
"an",
"object",
"from",
"its",
"Fully",
"Qualified",
"Name",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/__init__.py#L38-L41 |
225,229 | DAI-Lab/Copulas | copulas/__init__.py | get_qualified_name | def get_qualified_name(_object):
"""Return the Fully Qualified Name from an instance or class."""
module = _object.__module__
if hasattr(_object, '__name__'):
_class = _object.__name__
else:
_class = _object.__class__.__name__
return module + '.' + _class | python | def get_qualified_name(_object):
module = _object.__module__
if hasattr(_object, '__name__'):
_class = _object.__name__
else:
_class = _object.__class__.__name__
return module + '.' + _class | [
"def",
"get_qualified_name",
"(",
"_object",
")",
":",
"module",
"=",
"_object",
".",
"__module__",
"if",
"hasattr",
"(",
"_object",
",",
"'__name__'",
")",
":",
"_class",
"=",
"_object",
".",
"__name__",
"else",
":",
"_class",
"=",
"_object",
".",
"__clas... | Return the Fully Qualified Name from an instance or class. | [
"Return",
"the",
"Fully",
"Qualified",
"Name",
"from",
"an",
"instance",
"or",
"class",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/__init__.py#L44-L53 |
225,230 | DAI-Lab/Copulas | copulas/__init__.py | vectorize | def vectorize(function):
"""Allow a method that only accepts scalars to accept vectors too.
This decorator has two different behaviors depending on the dimensionality of the
array passed as an argument:
**1-d array**
It will work under the assumption that the `function` argument is a callable
with signature::
function(self, X, *args, **kwargs)
where X is an scalar magnitude.
In this case the arguments of the input array will be given one at a time, and
both the input and output of the decorated function will have shape (n,).
**2-d array**
It will work under the assumption that the `function` argument is a callable with signature::
function(self, X0, ..., Xj, *args, **kwargs)
where `Xi` are scalar magnitudes.
It will pass the contents of each row unpacked on each call. The input is espected to have
shape (n, j), the output a shape of (n,)
It will return a function that is guaranteed to return a `numpy.array`.
Args:
function(callable): Function that only accept and return scalars.
Returns:
callable: Decorated function that can accept and return :attr:`numpy.array`.
"""
def decorated(self, X, *args, **kwargs):
if not isinstance(X, np.ndarray):
return function(self, X, *args, **kwargs)
if len(X.shape) == 1:
X = X.reshape([-1, 1])
if len(X.shape) == 2:
return np.fromiter(
(function(self, *x, *args, **kwargs) for x in X),
np.dtype('float64')
)
else:
raise ValueError('Arrays of dimensionality higher than 2 are not supported.')
decorated.__doc__ = function.__doc__
return decorated | python | def vectorize(function):
def decorated(self, X, *args, **kwargs):
if not isinstance(X, np.ndarray):
return function(self, X, *args, **kwargs)
if len(X.shape) == 1:
X = X.reshape([-1, 1])
if len(X.shape) == 2:
return np.fromiter(
(function(self, *x, *args, **kwargs) for x in X),
np.dtype('float64')
)
else:
raise ValueError('Arrays of dimensionality higher than 2 are not supported.')
decorated.__doc__ = function.__doc__
return decorated | [
"def",
"vectorize",
"(",
"function",
")",
":",
"def",
"decorated",
"(",
"self",
",",
"X",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"X",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"function",
"(",
"s... | Allow a method that only accepts scalars to accept vectors too.
This decorator has two different behaviors depending on the dimensionality of the
array passed as an argument:
**1-d array**
It will work under the assumption that the `function` argument is a callable
with signature::
function(self, X, *args, **kwargs)
where X is an scalar magnitude.
In this case the arguments of the input array will be given one at a time, and
both the input and output of the decorated function will have shape (n,).
**2-d array**
It will work under the assumption that the `function` argument is a callable with signature::
function(self, X0, ..., Xj, *args, **kwargs)
where `Xi` are scalar magnitudes.
It will pass the contents of each row unpacked on each call. The input is espected to have
shape (n, j), the output a shape of (n,)
It will return a function that is guaranteed to return a `numpy.array`.
Args:
function(callable): Function that only accept and return scalars.
Returns:
callable: Decorated function that can accept and return :attr:`numpy.array`. | [
"Allow",
"a",
"method",
"that",
"only",
"accepts",
"scalars",
"to",
"accept",
"vectors",
"too",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/__init__.py#L56-L112 |
225,231 | DAI-Lab/Copulas | copulas/__init__.py | scalarize | def scalarize(function):
"""Allow methods that only accepts 1-d vectors to work with scalars.
Args:
function(callable): Function that accepts and returns vectors.
Returns:
callable: Decorated function that accepts and returns scalars.
"""
def decorated(self, X, *args, **kwargs):
scalar = not isinstance(X, np.ndarray)
if scalar:
X = np.array([X])
result = function(self, X, *args, **kwargs)
if scalar:
result = result[0]
return result
decorated.__doc__ = function.__doc__
return decorated | python | def scalarize(function):
def decorated(self, X, *args, **kwargs):
scalar = not isinstance(X, np.ndarray)
if scalar:
X = np.array([X])
result = function(self, X, *args, **kwargs)
if scalar:
result = result[0]
return result
decorated.__doc__ = function.__doc__
return decorated | [
"def",
"scalarize",
"(",
"function",
")",
":",
"def",
"decorated",
"(",
"self",
",",
"X",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"scalar",
"=",
"not",
"isinstance",
"(",
"X",
",",
"np",
".",
"ndarray",
")",
"if",
"scalar",
":",
"X",... | Allow methods that only accepts 1-d vectors to work with scalars.
Args:
function(callable): Function that accepts and returns vectors.
Returns:
callable: Decorated function that accepts and returns scalars. | [
"Allow",
"methods",
"that",
"only",
"accepts",
"1",
"-",
"d",
"vectors",
"to",
"work",
"with",
"scalars",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/__init__.py#L115-L137 |
225,232 | DAI-Lab/Copulas | copulas/__init__.py | check_valid_values | def check_valid_values(function):
"""Raises an exception if the given values are not supported.
Args:
function(callable): Method whose unique argument is a numpy.array-like object.
Returns:
callable: Decorated function
Raises:
ValueError: If there are missing or invalid values or if the dataset is empty.
"""
def decorated(self, X, *args, **kwargs):
if isinstance(X, pd.DataFrame):
W = X.values
else:
W = X
if not len(W):
raise ValueError('Your dataset is empty.')
if W.dtype not in [np.dtype('float64'), np.dtype('int64')]:
raise ValueError('There are non-numerical values in your data.')
if np.isnan(W).any().any():
raise ValueError('There are nan values in your data.')
return function(self, X, *args, **kwargs)
return decorated | python | def check_valid_values(function):
def decorated(self, X, *args, **kwargs):
if isinstance(X, pd.DataFrame):
W = X.values
else:
W = X
if not len(W):
raise ValueError('Your dataset is empty.')
if W.dtype not in [np.dtype('float64'), np.dtype('int64')]:
raise ValueError('There are non-numerical values in your data.')
if np.isnan(W).any().any():
raise ValueError('There are nan values in your data.')
return function(self, X, *args, **kwargs)
return decorated | [
"def",
"check_valid_values",
"(",
"function",
")",
":",
"def",
"decorated",
"(",
"self",
",",
"X",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"X",
",",
"pd",
".",
"DataFrame",
")",
":",
"W",
"=",
"X",
".",
"valu... | Raises an exception if the given values are not supported.
Args:
function(callable): Method whose unique argument is a numpy.array-like object.
Returns:
callable: Decorated function
Raises:
ValueError: If there are missing or invalid values or if the dataset is empty. | [
"Raises",
"an",
"exception",
"if",
"the",
"given",
"values",
"are",
"not",
"supported",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/__init__.py#L140-L171 |
225,233 | DAI-Lab/Copulas | copulas/__init__.py | missing_method_scipy_wrapper | def missing_method_scipy_wrapper(function):
"""Raises a detailed exception when a method is not available."""
def decorated(self, *args, **kwargs):
message = (
'Your tried to access `{method_name}` from {class_name}, but its not available.\n '
'There can be multiple factors causing this, please feel free to open an issue in '
'https://github.com/DAI-Lab/Copulas/issues/new'
)
params = {
'method_name': function.__name__,
'class_name': get_qualified_name(function.__self__.__class__)
}
raise NotImplementedError(message.format(**params))
return decorated | python | def missing_method_scipy_wrapper(function):
def decorated(self, *args, **kwargs):
message = (
'Your tried to access `{method_name}` from {class_name}, but its not available.\n '
'There can be multiple factors causing this, please feel free to open an issue in '
'https://github.com/DAI-Lab/Copulas/issues/new'
)
params = {
'method_name': function.__name__,
'class_name': get_qualified_name(function.__self__.__class__)
}
raise NotImplementedError(message.format(**params))
return decorated | [
"def",
"missing_method_scipy_wrapper",
"(",
"function",
")",
":",
"def",
"decorated",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"message",
"=",
"(",
"'Your tried to access `{method_name}` from {class_name}, but its not available.\\n '",
"'There c... | Raises a detailed exception when a method is not available. | [
"Raises",
"a",
"detailed",
"exception",
"when",
"a",
"method",
"is",
"not",
"available",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/__init__.py#L174-L190 |
225,234 | DAI-Lab/Copulas | copulas/bivariate/frank.py | Frank._g | def _g(self, z):
"""Helper function to solve Frank copula.
This functions encapsulates :math:`g_z = e^{-\\theta z} - 1` used on Frank copulas.
Argument:
z: np.ndarray
Returns:
np.ndarray
"""
return np.exp(np.multiply(-self.theta, z)) - 1 | python | def _g(self, z):
return np.exp(np.multiply(-self.theta, z)) - 1 | [
"def",
"_g",
"(",
"self",
",",
"z",
")",
":",
"return",
"np",
".",
"exp",
"(",
"np",
".",
"multiply",
"(",
"-",
"self",
".",
"theta",
",",
"z",
")",
")",
"-",
"1"
] | Helper function to solve Frank copula.
This functions encapsulates :math:`g_z = e^{-\\theta z} - 1` used on Frank copulas.
Argument:
z: np.ndarray
Returns:
np.ndarray | [
"Helper",
"function",
"to",
"solve",
"Frank",
"copula",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/bivariate/frank.py#L22-L33 |
225,235 | DAI-Lab/Copulas | copulas/bivariate/frank.py | Frank._frank_help | def _frank_help(alpha, tau):
"""Compute first order debye function to estimate theta."""
def debye(t):
return t / (np.exp(t) - 1)
debye_value = integrate.quad(debye, EPSILON, alpha)[0] / alpha
return 4 * (debye_value - 1) / alpha + 1 - tau | python | def _frank_help(alpha, tau):
def debye(t):
return t / (np.exp(t) - 1)
debye_value = integrate.quad(debye, EPSILON, alpha)[0] / alpha
return 4 * (debye_value - 1) / alpha + 1 - tau | [
"def",
"_frank_help",
"(",
"alpha",
",",
"tau",
")",
":",
"def",
"debye",
"(",
"t",
")",
":",
"return",
"t",
"/",
"(",
"np",
".",
"exp",
"(",
"t",
")",
"-",
"1",
")",
"debye_value",
"=",
"integrate",
".",
"quad",
"(",
"debye",
",",
"EPSILON",
"... | Compute first order debye function to estimate theta. | [
"Compute",
"first",
"order",
"debye",
"function",
"to",
"estimate",
"theta",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/bivariate/frank.py#L134-L141 |
225,236 | DAI-Lab/Copulas | copulas/univariate/base.py | Univariate.to_dict | def to_dict(self):
"""Returns parameters to replicate the distribution."""
result = {
'type': get_qualified_name(self),
'fitted': self.fitted,
'constant_value': self.constant_value
}
if not self.fitted:
return result
result.update(self._fit_params())
return result | python | def to_dict(self):
result = {
'type': get_qualified_name(self),
'fitted': self.fitted,
'constant_value': self.constant_value
}
if not self.fitted:
return result
result.update(self._fit_params())
return result | [
"def",
"to_dict",
"(",
"self",
")",
":",
"result",
"=",
"{",
"'type'",
":",
"get_qualified_name",
"(",
"self",
")",
",",
"'fitted'",
":",
"self",
".",
"fitted",
",",
"'constant_value'",
":",
"self",
".",
"constant_value",
"}",
"if",
"not",
"self",
".",
... | Returns parameters to replicate the distribution. | [
"Returns",
"parameters",
"to",
"replicate",
"the",
"distribution",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/base.py#L81-L93 |
225,237 | DAI-Lab/Copulas | copulas/univariate/base.py | Univariate._constant_cumulative_distribution | def _constant_cumulative_distribution(self, X):
"""Cumulative distribution for the degenerate case of constant distribution.
Note that the output of this method will be an array whose unique values are 0 and 1.
More information can be found here: https://en.wikipedia.org/wiki/Degenerate_distribution
Args:
X (numpy.ndarray): Values to compute cdf to.
Returns:
numpy.ndarray: Cumulative distribution for the given values.
"""
result = np.ones(X.shape)
result[np.nonzero(X < self.constant_value)] = 0
return result | python | def _constant_cumulative_distribution(self, X):
result = np.ones(X.shape)
result[np.nonzero(X < self.constant_value)] = 0
return result | [
"def",
"_constant_cumulative_distribution",
"(",
"self",
",",
"X",
")",
":",
"result",
"=",
"np",
".",
"ones",
"(",
"X",
".",
"shape",
")",
"result",
"[",
"np",
".",
"nonzero",
"(",
"X",
"<",
"self",
".",
"constant_value",
")",
"]",
"=",
"0",
"return... | Cumulative distribution for the degenerate case of constant distribution.
Note that the output of this method will be an array whose unique values are 0 and 1.
More information can be found here: https://en.wikipedia.org/wiki/Degenerate_distribution
Args:
X (numpy.ndarray): Values to compute cdf to.
Returns:
numpy.ndarray: Cumulative distribution for the given values. | [
"Cumulative",
"distribution",
"for",
"the",
"degenerate",
"case",
"of",
"constant",
"distribution",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/base.py#L142-L157 |
225,238 | DAI-Lab/Copulas | copulas/univariate/base.py | Univariate._constant_probability_density | def _constant_probability_density(self, X):
"""Probability density for the degenerate case of constant distribution.
Note that the output of this method will be an array whose unique values are 0 and 1.
More information can be found here: https://en.wikipedia.org/wiki/Degenerate_distribution
Args:
X(numpy.ndarray): Values to compute pdf.
Returns:
numpy.ndarray: Probability densisty for the given values
"""
result = np.zeros(X.shape)
result[np.nonzero(X == self.constant_value)] = 1
return result | python | def _constant_probability_density(self, X):
result = np.zeros(X.shape)
result[np.nonzero(X == self.constant_value)] = 1
return result | [
"def",
"_constant_probability_density",
"(",
"self",
",",
"X",
")",
":",
"result",
"=",
"np",
".",
"zeros",
"(",
"X",
".",
"shape",
")",
"result",
"[",
"np",
".",
"nonzero",
"(",
"X",
"==",
"self",
".",
"constant_value",
")",
"]",
"=",
"1",
"return",... | Probability density for the degenerate case of constant distribution.
Note that the output of this method will be an array whose unique values are 0 and 1.
More information can be found here: https://en.wikipedia.org/wiki/Degenerate_distribution
Args:
X(numpy.ndarray): Values to compute pdf.
Returns:
numpy.ndarray: Probability densisty for the given values | [
"Probability",
"density",
"for",
"the",
"degenerate",
"case",
"of",
"constant",
"distribution",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/base.py#L159-L174 |
225,239 | DAI-Lab/Copulas | copulas/univariate/base.py | Univariate._replace_constant_methods | def _replace_constant_methods(self):
"""Replaces conventional distribution methods by its constant counterparts."""
self.cumulative_distribution = self._constant_cumulative_distribution
self.percent_point = self._constant_percent_point
self.probability_density = self._constant_probability_density
self.sample = self._constant_sample | python | def _replace_constant_methods(self):
self.cumulative_distribution = self._constant_cumulative_distribution
self.percent_point = self._constant_percent_point
self.probability_density = self._constant_probability_density
self.sample = self._constant_sample | [
"def",
"_replace_constant_methods",
"(",
"self",
")",
":",
"self",
".",
"cumulative_distribution",
"=",
"self",
".",
"_constant_cumulative_distribution",
"self",
".",
"percent_point",
"=",
"self",
".",
"_constant_percent_point",
"self",
".",
"probability_density",
"=",
... | Replaces conventional distribution methods by its constant counterparts. | [
"Replaces",
"conventional",
"distribution",
"methods",
"by",
"its",
"constant",
"counterparts",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/base.py#L192-L197 |
225,240 | DAI-Lab/Copulas | copulas/univariate/base.py | ScipyWrapper.fit | def fit(self, X, *args, **kwargs):
"""Fit scipy model to an array of values.
Args:
X(`np.ndarray` or `pd.DataFrame`): Datapoints to be estimated from. Must be 1-d
Returns:
None
"""
self.constant_value = self._get_constant_value(X)
if self.constant_value is None:
if self.unfittable_model:
self.model = getattr(scipy.stats, self.model_class)(*args, **kwargs)
else:
self.model = getattr(scipy.stats, self.model_class)(X, *args, **kwargs)
for name in self.METHOD_NAMES:
attribute = getattr(self.__class__, name)
if isinstance(attribute, str):
setattr(self, name, getattr(self.model, attribute))
elif attribute is None:
setattr(self, name, missing_method_scipy_wrapper(lambda x: x))
else:
self._replace_constant_methods()
self.fitted = True | python | def fit(self, X, *args, **kwargs):
self.constant_value = self._get_constant_value(X)
if self.constant_value is None:
if self.unfittable_model:
self.model = getattr(scipy.stats, self.model_class)(*args, **kwargs)
else:
self.model = getattr(scipy.stats, self.model_class)(X, *args, **kwargs)
for name in self.METHOD_NAMES:
attribute = getattr(self.__class__, name)
if isinstance(attribute, str):
setattr(self, name, getattr(self.model, attribute))
elif attribute is None:
setattr(self, name, missing_method_scipy_wrapper(lambda x: x))
else:
self._replace_constant_methods()
self.fitted = True | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"constant_value",
"=",
"self",
".",
"_get_constant_value",
"(",
"X",
")",
"if",
"self",
".",
"constant_value",
"is",
"None",
":",
"if",
"self",
"... | Fit scipy model to an array of values.
Args:
X(`np.ndarray` or `pd.DataFrame`): Datapoints to be estimated from. Must be 1-d
Returns:
None | [
"Fit",
"scipy",
"model",
"to",
"an",
"array",
"of",
"values",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/base.py#L267-L296 |
225,241 | DAI-Lab/Copulas | examples/copulas_example.py | main | def main(data, utype, ctype):
"""Create a Vine from the data, utype and ctype"""
copula = CopulaModel(data, utype, ctype)
print(copula.sampling(1, plot=True))
print(copula.model.vine_model[-1].tree_data) | python | def main(data, utype, ctype):
copula = CopulaModel(data, utype, ctype)
print(copula.sampling(1, plot=True))
print(copula.model.vine_model[-1].tree_data) | [
"def",
"main",
"(",
"data",
",",
"utype",
",",
"ctype",
")",
":",
"copula",
"=",
"CopulaModel",
"(",
"data",
",",
"utype",
",",
"ctype",
")",
"print",
"(",
"copula",
".",
"sampling",
"(",
"1",
",",
"plot",
"=",
"True",
")",
")",
"print",
"(",
"co... | Create a Vine from the data, utype and ctype | [
"Create",
"a",
"Vine",
"from",
"the",
"data",
"utype",
"and",
"ctype"
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/examples/copulas_example.py#L9-L13 |
225,242 | DAI-Lab/Copulas | copulas/bivariate/clayton.py | Clayton.compute_theta | def compute_theta(self):
"""Compute theta parameter using Kendall's tau.
On Clayton copula this is :math:`τ = θ/(θ + 2) \\implies θ = 2τ/(1-τ)` with
:math:`θ ∈ (0, ∞)`.
On the corner case of :math:`τ = 1`, a big enough number is returned instead of infinity.
"""
if self.tau == 1:
theta = 10000
else:
theta = 2 * self.tau / (1 - self.tau)
return theta | python | def compute_theta(self):
if self.tau == 1:
theta = 10000
else:
theta = 2 * self.tau / (1 - self.tau)
return theta | [
"def",
"compute_theta",
"(",
"self",
")",
":",
"if",
"self",
".",
"tau",
"==",
"1",
":",
"theta",
"=",
"10000",
"else",
":",
"theta",
"=",
"2",
"*",
"self",
".",
"tau",
"/",
"(",
"1",
"-",
"self",
".",
"tau",
")",
"return",
"theta"
] | Compute theta parameter using Kendall's tau.
On Clayton copula this is :math:`τ = θ/(θ + 2) \\implies θ = 2τ/(1-τ)` with
:math:`θ ∈ (0, ∞)`.
On the corner case of :math:`τ = 1`, a big enough number is returned instead of infinity. | [
"Compute",
"theta",
"parameter",
"using",
"Kendall",
"s",
"tau",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/bivariate/clayton.py#L106-L120 |
225,243 | DAI-Lab/Copulas | copulas/multivariate/vine.py | VineCopula.fit | def fit(self, X, truncated=3):
"""Fit a vine model to the data.
Args:
X(numpy.ndarray): data to be fitted.
truncated(int): max level to build the vine.
"""
self.n_sample, self.n_var = X.shape
self.columns = X.columns
self.tau_mat = X.corr(method='kendall').values
self.u_matrix = np.empty([self.n_sample, self.n_var])
self.truncated = truncated
self.depth = self.n_var - 1
self.trees = []
self.unis, self.ppfs = [], []
for i, col in enumerate(X):
uni = self.model()
uni.fit(X[col])
self.u_matrix[:, i] = uni.cumulative_distribution(X[col])
self.unis.append(uni)
self.ppfs.append(uni.percent_point)
self.train_vine(self.vine_type)
self.fitted = True | python | def fit(self, X, truncated=3):
self.n_sample, self.n_var = X.shape
self.columns = X.columns
self.tau_mat = X.corr(method='kendall').values
self.u_matrix = np.empty([self.n_sample, self.n_var])
self.truncated = truncated
self.depth = self.n_var - 1
self.trees = []
self.unis, self.ppfs = [], []
for i, col in enumerate(X):
uni = self.model()
uni.fit(X[col])
self.u_matrix[:, i] = uni.cumulative_distribution(X[col])
self.unis.append(uni)
self.ppfs.append(uni.percent_point)
self.train_vine(self.vine_type)
self.fitted = True | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"truncated",
"=",
"3",
")",
":",
"self",
".",
"n_sample",
",",
"self",
".",
"n_var",
"=",
"X",
".",
"shape",
"self",
".",
"columns",
"=",
"X",
".",
"columns",
"self",
".",
"tau_mat",
"=",
"X",
".",
"cor... | Fit a vine model to the data.
Args:
X(numpy.ndarray): data to be fitted.
truncated(int): max level to build the vine. | [
"Fit",
"a",
"vine",
"model",
"to",
"the",
"data",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/vine.py#L82-L107 |
225,244 | DAI-Lab/Copulas | copulas/multivariate/vine.py | VineCopula.train_vine | def train_vine(self, tree_type):
"""Train vine."""
LOGGER.debug('start building tree : 0')
tree_1 = Tree(tree_type)
tree_1.fit(0, self.n_var, self.tau_mat, self.u_matrix)
self.trees.append(tree_1)
LOGGER.debug('finish building tree : 0')
for k in range(1, min(self.n_var - 1, self.truncated)):
# get constraints from previous tree
self.trees[k - 1]._get_constraints()
tau = self.trees[k - 1].get_tau_matrix()
LOGGER.debug('start building tree: {0}'.format(k))
tree_k = Tree(tree_type)
tree_k.fit(k, self.n_var - k, tau, self.trees[k - 1])
self.trees.append(tree_k)
LOGGER.debug('finish building tree: {0}'.format(k)) | python | def train_vine(self, tree_type):
LOGGER.debug('start building tree : 0')
tree_1 = Tree(tree_type)
tree_1.fit(0, self.n_var, self.tau_mat, self.u_matrix)
self.trees.append(tree_1)
LOGGER.debug('finish building tree : 0')
for k in range(1, min(self.n_var - 1, self.truncated)):
# get constraints from previous tree
self.trees[k - 1]._get_constraints()
tau = self.trees[k - 1].get_tau_matrix()
LOGGER.debug('start building tree: {0}'.format(k))
tree_k = Tree(tree_type)
tree_k.fit(k, self.n_var - k, tau, self.trees[k - 1])
self.trees.append(tree_k)
LOGGER.debug('finish building tree: {0}'.format(k)) | [
"def",
"train_vine",
"(",
"self",
",",
"tree_type",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'start building tree : 0'",
")",
"tree_1",
"=",
"Tree",
"(",
"tree_type",
")",
"tree_1",
".",
"fit",
"(",
"0",
",",
"self",
".",
"n_var",
",",
"self",
".",
"tau... | Train vine. | [
"Train",
"vine",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/vine.py#L109-L125 |
225,245 | DAI-Lab/Copulas | copulas/multivariate/vine.py | VineCopula.get_likelihood | def get_likelihood(self, uni_matrix):
"""Compute likelihood of the vine."""
num_tree = len(self.trees)
values = np.empty([1, num_tree])
for i in range(num_tree):
value, new_uni_matrix = self.trees[i].get_likelihood(uni_matrix)
uni_matrix = new_uni_matrix
values[0, i] = value
return np.sum(values) | python | def get_likelihood(self, uni_matrix):
num_tree = len(self.trees)
values = np.empty([1, num_tree])
for i in range(num_tree):
value, new_uni_matrix = self.trees[i].get_likelihood(uni_matrix)
uni_matrix = new_uni_matrix
values[0, i] = value
return np.sum(values) | [
"def",
"get_likelihood",
"(",
"self",
",",
"uni_matrix",
")",
":",
"num_tree",
"=",
"len",
"(",
"self",
".",
"trees",
")",
"values",
"=",
"np",
".",
"empty",
"(",
"[",
"1",
",",
"num_tree",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"num_tree",
")",... | Compute likelihood of the vine. | [
"Compute",
"likelihood",
"of",
"the",
"vine",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/vine.py#L127-L137 |
225,246 | DAI-Lab/Copulas | copulas/multivariate/vine.py | VineCopula._sample_row | def _sample_row(self):
"""Generate a single sampled row from vine model.
Returns:
numpy.ndarray
"""
unis = np.random.uniform(0, 1, self.n_var)
# randomly select a node to start with
first_ind = np.random.randint(0, self.n_var)
adj = self.trees[0].get_adjacent_matrix()
visited = []
explore = [first_ind]
sampled = np.zeros(self.n_var)
itr = 0
while explore:
current = explore.pop(0)
neighbors = np.where(adj[current, :] == 1)[0].tolist()
if itr == 0:
new_x = self.ppfs[current](unis[current])
else:
for i in range(itr - 1, -1, -1):
current_ind = -1
if i >= self.truncated:
continue
current_tree = self.trees[i].edges
# get index of edge to retrieve
for edge in current_tree:
if i == 0:
if (edge.L == current and edge.R == visited[0]) or\
(edge.R == current and edge.L == visited[0]):
current_ind = edge.index
break
else:
if edge.L == current or edge.R == current:
condition = set(edge.D)
condition.add(edge.L)
condition.add(edge.R)
visit_set = set(visited)
visit_set.add(current)
if condition.issubset(visit_set):
current_ind = edge.index
break
if current_ind != -1:
# the node is not indepedent contional on visited node
copula_type = current_tree[current_ind].name
copula = Bivariate(CopulaTypes(copula_type))
copula.theta = current_tree[current_ind].theta
derivative = copula.partial_derivative_scalar
if i == itr - 1:
tmp = optimize.fminbound(
derivative, EPSILON, 1.0,
args=(unis[visited[0]], unis[current])
)
else:
tmp = optimize.fminbound(
derivative, EPSILON, 1.0,
args=(unis[visited[0]], tmp)
)
tmp = min(max(tmp, EPSILON), 0.99)
new_x = self.ppfs[current](tmp)
sampled[current] = new_x
for s in neighbors:
if s not in visited:
explore.insert(0, s)
itr += 1
visited.insert(0, current)
return sampled | python | def _sample_row(self):
unis = np.random.uniform(0, 1, self.n_var)
# randomly select a node to start with
first_ind = np.random.randint(0, self.n_var)
adj = self.trees[0].get_adjacent_matrix()
visited = []
explore = [first_ind]
sampled = np.zeros(self.n_var)
itr = 0
while explore:
current = explore.pop(0)
neighbors = np.where(adj[current, :] == 1)[0].tolist()
if itr == 0:
new_x = self.ppfs[current](unis[current])
else:
for i in range(itr - 1, -1, -1):
current_ind = -1
if i >= self.truncated:
continue
current_tree = self.trees[i].edges
# get index of edge to retrieve
for edge in current_tree:
if i == 0:
if (edge.L == current and edge.R == visited[0]) or\
(edge.R == current and edge.L == visited[0]):
current_ind = edge.index
break
else:
if edge.L == current or edge.R == current:
condition = set(edge.D)
condition.add(edge.L)
condition.add(edge.R)
visit_set = set(visited)
visit_set.add(current)
if condition.issubset(visit_set):
current_ind = edge.index
break
if current_ind != -1:
# the node is not indepedent contional on visited node
copula_type = current_tree[current_ind].name
copula = Bivariate(CopulaTypes(copula_type))
copula.theta = current_tree[current_ind].theta
derivative = copula.partial_derivative_scalar
if i == itr - 1:
tmp = optimize.fminbound(
derivative, EPSILON, 1.0,
args=(unis[visited[0]], unis[current])
)
else:
tmp = optimize.fminbound(
derivative, EPSILON, 1.0,
args=(unis[visited[0]], tmp)
)
tmp = min(max(tmp, EPSILON), 0.99)
new_x = self.ppfs[current](tmp)
sampled[current] = new_x
for s in neighbors:
if s not in visited:
explore.insert(0, s)
itr += 1
visited.insert(0, current)
return sampled | [
"def",
"_sample_row",
"(",
"self",
")",
":",
"unis",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"1",
",",
"self",
".",
"n_var",
")",
"# randomly select a node to start with",
"first_ind",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
... | Generate a single sampled row from vine model.
Returns:
numpy.ndarray | [
"Generate",
"a",
"single",
"sampled",
"row",
"from",
"vine",
"model",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/vine.py#L139-L219 |
225,247 | DAI-Lab/Copulas | copulas/multivariate/vine.py | VineCopula.sample | def sample(self, num_rows):
"""Sample new rows.
Args:
num_rows(int): Number of rows to sample
Returns:
pandas.DataFrame
"""
sampled_values = []
for i in range(num_rows):
sampled_values.append(self._sample_row())
return pd.DataFrame(sampled_values, columns=self.columns) | python | def sample(self, num_rows):
sampled_values = []
for i in range(num_rows):
sampled_values.append(self._sample_row())
return pd.DataFrame(sampled_values, columns=self.columns) | [
"def",
"sample",
"(",
"self",
",",
"num_rows",
")",
":",
"sampled_values",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"num_rows",
")",
":",
"sampled_values",
".",
"append",
"(",
"self",
".",
"_sample_row",
"(",
")",
")",
"return",
"pd",
".",
"Dat... | Sample new rows.
Args:
num_rows(int): Number of rows to sample
Returns:
pandas.DataFrame | [
"Sample",
"new",
"rows",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/vine.py#L222-L236 |
225,248 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Tree.fit | def fit(self, index, n_nodes, tau_matrix, previous_tree, edges=None):
"""Fits tree object.
Args:
:param index: index of the tree
:param n_nodes: number of nodes in the tree
:tau_matrix: kendall's tau matrix of the data
:previous_tree: tree object of previous level
:type index: int
:type n_nodes: int
:type tau_matrix: np.ndarray of size n_nodes*n_nodes
"""
self.level = index + 1
self.n_nodes = n_nodes
self.tau_matrix = tau_matrix
self.previous_tree = previous_tree
self.edges = edges or []
if not self.edges:
if self.level == 1:
self.u_matrix = previous_tree
self._build_first_tree()
else:
self._build_kth_tree()
self.prepare_next_tree()
self.fitted = True | python | def fit(self, index, n_nodes, tau_matrix, previous_tree, edges=None):
self.level = index + 1
self.n_nodes = n_nodes
self.tau_matrix = tau_matrix
self.previous_tree = previous_tree
self.edges = edges or []
if not self.edges:
if self.level == 1:
self.u_matrix = previous_tree
self._build_first_tree()
else:
self._build_kth_tree()
self.prepare_next_tree()
self.fitted = True | [
"def",
"fit",
"(",
"self",
",",
"index",
",",
"n_nodes",
",",
"tau_matrix",
",",
"previous_tree",
",",
"edges",
"=",
"None",
")",
":",
"self",
".",
"level",
"=",
"index",
"+",
"1",
"self",
".",
"n_nodes",
"=",
"n_nodes",
"self",
".",
"tau_matrix",
"=... | Fits tree object.
Args:
:param index: index of the tree
:param n_nodes: number of nodes in the tree
:tau_matrix: kendall's tau matrix of the data
:previous_tree: tree object of previous level
:type index: int
:type n_nodes: int
:type tau_matrix: np.ndarray of size n_nodes*n_nodes | [
"Fits",
"tree",
"object",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L64-L92 |
225,249 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Tree._check_contraint | def _check_contraint(self, edge1, edge2):
"""Check if two edges satisfy vine constraint.
Args:
:param edge1: edge object representing edge1
:param edge2: edge object representing edge2
:type edge1: Edge object
:type edge2: Edge object
Returns:
Boolean True if the two edges satisfy vine constraints
"""
full_node = set([edge1.L, edge1.R, edge2.L, edge2.R])
full_node.update(edge1.D)
full_node.update(edge2.D)
return len(full_node) == (self.level + 1) | python | def _check_contraint(self, edge1, edge2):
full_node = set([edge1.L, edge1.R, edge2.L, edge2.R])
full_node.update(edge1.D)
full_node.update(edge2.D)
return len(full_node) == (self.level + 1) | [
"def",
"_check_contraint",
"(",
"self",
",",
"edge1",
",",
"edge2",
")",
":",
"full_node",
"=",
"set",
"(",
"[",
"edge1",
".",
"L",
",",
"edge1",
".",
"R",
",",
"edge2",
".",
"L",
",",
"edge2",
".",
"R",
"]",
")",
"full_node",
".",
"update",
"(",... | Check if two edges satisfy vine constraint.
Args:
:param edge1: edge object representing edge1
:param edge2: edge object representing edge2
:type edge1: Edge object
:type edge2: Edge object
Returns:
Boolean True if the two edges satisfy vine constraints | [
"Check",
"if",
"two",
"edges",
"satisfy",
"vine",
"constraint",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L94-L109 |
225,250 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Tree._get_constraints | def _get_constraints(self):
"""Get neighboring edges for each edge in the edges."""
num_edges = len(self.edges)
for k in range(num_edges):
for i in range(num_edges):
# add to constraints if i shared an edge with k
if k != i and self.edges[k].is_adjacent(self.edges[i]):
self.edges[k].neighbors.append(i) | python | def _get_constraints(self):
num_edges = len(self.edges)
for k in range(num_edges):
for i in range(num_edges):
# add to constraints if i shared an edge with k
if k != i and self.edges[k].is_adjacent(self.edges[i]):
self.edges[k].neighbors.append(i) | [
"def",
"_get_constraints",
"(",
"self",
")",
":",
"num_edges",
"=",
"len",
"(",
"self",
".",
"edges",
")",
"for",
"k",
"in",
"range",
"(",
"num_edges",
")",
":",
"for",
"i",
"in",
"range",
"(",
"num_edges",
")",
":",
"# add to constraints if i shared an ed... | Get neighboring edges for each edge in the edges. | [
"Get",
"neighboring",
"edges",
"for",
"each",
"edge",
"in",
"the",
"edges",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L111-L118 |
225,251 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Tree._sort_tau_by_y | def _sort_tau_by_y(self, y):
"""Sort tau matrix by dependece with variable y.
Args:
:param y: index of variable of intrest
:type y: int
"""
# first column is the variable of interest
tau_y = self.tau_matrix[:, y]
tau_y[y] = np.NaN
temp = np.empty([self.n_nodes, 3])
temp[:, 0] = np.arange(self.n_nodes)
temp[:, 1] = tau_y
temp[:, 2] = abs(tau_y)
temp[np.isnan(temp)] = -10
tau_sorted = temp[temp[:, 2].argsort()[::-1]]
return tau_sorted | python | def _sort_tau_by_y(self, y):
# first column is the variable of interest
tau_y = self.tau_matrix[:, y]
tau_y[y] = np.NaN
temp = np.empty([self.n_nodes, 3])
temp[:, 0] = np.arange(self.n_nodes)
temp[:, 1] = tau_y
temp[:, 2] = abs(tau_y)
temp[np.isnan(temp)] = -10
tau_sorted = temp[temp[:, 2].argsort()[::-1]]
return tau_sorted | [
"def",
"_sort_tau_by_y",
"(",
"self",
",",
"y",
")",
":",
"# first column is the variable of interest",
"tau_y",
"=",
"self",
".",
"tau_matrix",
"[",
":",
",",
"y",
"]",
"tau_y",
"[",
"y",
"]",
"=",
"np",
".",
"NaN",
"temp",
"=",
"np",
".",
"empty",
"(... | Sort tau matrix by dependece with variable y.
Args:
:param y: index of variable of intrest
:type y: int | [
"Sort",
"tau",
"matrix",
"by",
"dependece",
"with",
"variable",
"y",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L120-L138 |
225,252 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Tree.get_tau_matrix | def get_tau_matrix(self):
"""Get tau matrix for adjacent pairs.
Returns:
:param tau: tau matrix for the current tree
:type tau: np.ndarray
"""
num_edges = len(self.edges)
tau = np.empty([num_edges, num_edges])
for i in range(num_edges):
edge = self.edges[i]
for j in edge.neighbors:
if self.level == 1:
left_u = self.u_matrix[:, edge.L]
right_u = self.u_matrix[:, edge.R]
else:
left_parent, right_parent = edge.parents
left_u, right_u = Edge.get_conditional_uni(left_parent, right_parent)
tau[i, j], pvalue = scipy.stats.kendalltau(left_u, right_u)
return tau | python | def get_tau_matrix(self):
num_edges = len(self.edges)
tau = np.empty([num_edges, num_edges])
for i in range(num_edges):
edge = self.edges[i]
for j in edge.neighbors:
if self.level == 1:
left_u = self.u_matrix[:, edge.L]
right_u = self.u_matrix[:, edge.R]
else:
left_parent, right_parent = edge.parents
left_u, right_u = Edge.get_conditional_uni(left_parent, right_parent)
tau[i, j], pvalue = scipy.stats.kendalltau(left_u, right_u)
return tau | [
"def",
"get_tau_matrix",
"(",
"self",
")",
":",
"num_edges",
"=",
"len",
"(",
"self",
".",
"edges",
")",
"tau",
"=",
"np",
".",
"empty",
"(",
"[",
"num_edges",
",",
"num_edges",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"num_edges",
")",
":",
"edge... | Get tau matrix for adjacent pairs.
Returns:
:param tau: tau matrix for the current tree
:type tau: np.ndarray | [
"Get",
"tau",
"matrix",
"for",
"adjacent",
"pairs",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L140-L163 |
225,253 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Tree.get_adjacent_matrix | def get_adjacent_matrix(self):
"""Get adjacency matrix.
Returns:
:param adj: adjacency matrix
:type adj: np.ndarray
"""
edges = self.edges
num_edges = len(edges) + 1
adj = np.zeros([num_edges, num_edges])
for k in range(num_edges - 1):
adj[edges[k].L, edges[k].R] = 1
adj[edges[k].R, edges[k].L] = 1
return adj | python | def get_adjacent_matrix(self):
edges = self.edges
num_edges = len(edges) + 1
adj = np.zeros([num_edges, num_edges])
for k in range(num_edges - 1):
adj[edges[k].L, edges[k].R] = 1
adj[edges[k].R, edges[k].L] = 1
return adj | [
"def",
"get_adjacent_matrix",
"(",
"self",
")",
":",
"edges",
"=",
"self",
".",
"edges",
"num_edges",
"=",
"len",
"(",
"edges",
")",
"+",
"1",
"adj",
"=",
"np",
".",
"zeros",
"(",
"[",
"num_edges",
",",
"num_edges",
"]",
")",
"for",
"k",
"in",
"ran... | Get adjacency matrix.
Returns:
:param adj: adjacency matrix
:type adj: np.ndarray | [
"Get",
"adjacency",
"matrix",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L165-L180 |
225,254 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Tree.prepare_next_tree | def prepare_next_tree(self):
"""Prepare conditional U matrix for next tree."""
for edge in self.edges:
copula_theta = edge.theta
if self.level == 1:
left_u = self.u_matrix[:, edge.L]
right_u = self.u_matrix[:, edge.R]
else:
left_parent, right_parent = edge.parents
left_u, right_u = Edge.get_conditional_uni(left_parent, right_parent)
# compute conditional cdfs C(i|j) = dC(i,j)/duj and dC(i,j)/du
left_u = [x for x in left_u if x is not None]
right_u = [x for x in right_u if x is not None]
X_left_right = np.array([[x, y] for x, y in zip(left_u, right_u)])
X_right_left = np.array([[x, y] for x, y in zip(right_u, left_u)])
copula = Bivariate(edge.name)
copula.theta = copula_theta
left_given_right = copula.partial_derivative(X_left_right)
right_given_left = copula.partial_derivative(X_right_left)
# correction of 0 or 1
left_given_right[left_given_right == 0] = EPSILON
right_given_left[right_given_left == 0] = EPSILON
left_given_right[left_given_right == 1] = 1 - EPSILON
right_given_left[right_given_left == 1] = 1 - EPSILON
edge.U = np.array([left_given_right, right_given_left]) | python | def prepare_next_tree(self):
for edge in self.edges:
copula_theta = edge.theta
if self.level == 1:
left_u = self.u_matrix[:, edge.L]
right_u = self.u_matrix[:, edge.R]
else:
left_parent, right_parent = edge.parents
left_u, right_u = Edge.get_conditional_uni(left_parent, right_parent)
# compute conditional cdfs C(i|j) = dC(i,j)/duj and dC(i,j)/du
left_u = [x for x in left_u if x is not None]
right_u = [x for x in right_u if x is not None]
X_left_right = np.array([[x, y] for x, y in zip(left_u, right_u)])
X_right_left = np.array([[x, y] for x, y in zip(right_u, left_u)])
copula = Bivariate(edge.name)
copula.theta = copula_theta
left_given_right = copula.partial_derivative(X_left_right)
right_given_left = copula.partial_derivative(X_right_left)
# correction of 0 or 1
left_given_right[left_given_right == 0] = EPSILON
right_given_left[right_given_left == 0] = EPSILON
left_given_right[left_given_right == 1] = 1 - EPSILON
right_given_left[right_given_left == 1] = 1 - EPSILON
edge.U = np.array([left_given_right, right_given_left]) | [
"def",
"prepare_next_tree",
"(",
"self",
")",
":",
"for",
"edge",
"in",
"self",
".",
"edges",
":",
"copula_theta",
"=",
"edge",
".",
"theta",
"if",
"self",
".",
"level",
"==",
"1",
":",
"left_u",
"=",
"self",
".",
"u_matrix",
"[",
":",
",",
"edge",
... | Prepare conditional U matrix for next tree. | [
"Prepare",
"conditional",
"U",
"matrix",
"for",
"next",
"tree",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L182-L211 |
225,255 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Tree.get_likelihood | def get_likelihood(self, uni_matrix):
"""Compute likelihood of the tree given an U matrix.
Args:
uni_matrix(numpy.array): univariate matrix to evaluate likelihood on.
Returns:
tuple[float, numpy.array]:
likelihood of the current tree, next level conditional univariate matrix
"""
uni_dim = uni_matrix.shape[1]
num_edge = len(self.edges)
values = np.zeros([1, num_edge])
new_uni_matrix = np.empty([uni_dim, uni_dim])
for i in range(num_edge):
edge = self.edges[i]
value, left_u, right_u = edge.get_likelihood(uni_matrix)
new_uni_matrix[edge.L, edge.R] = left_u
new_uni_matrix[edge.R, edge.L] = right_u
values[0, i] = np.log(value)
return np.sum(values), new_uni_matrix | python | def get_likelihood(self, uni_matrix):
uni_dim = uni_matrix.shape[1]
num_edge = len(self.edges)
values = np.zeros([1, num_edge])
new_uni_matrix = np.empty([uni_dim, uni_dim])
for i in range(num_edge):
edge = self.edges[i]
value, left_u, right_u = edge.get_likelihood(uni_matrix)
new_uni_matrix[edge.L, edge.R] = left_u
new_uni_matrix[edge.R, edge.L] = right_u
values[0, i] = np.log(value)
return np.sum(values), new_uni_matrix | [
"def",
"get_likelihood",
"(",
"self",
",",
"uni_matrix",
")",
":",
"uni_dim",
"=",
"uni_matrix",
".",
"shape",
"[",
"1",
"]",
"num_edge",
"=",
"len",
"(",
"self",
".",
"edges",
")",
"values",
"=",
"np",
".",
"zeros",
"(",
"[",
"1",
",",
"num_edge",
... | Compute likelihood of the tree given an U matrix.
Args:
uni_matrix(numpy.array): univariate matrix to evaluate likelihood on.
Returns:
tuple[float, numpy.array]:
likelihood of the current tree, next level conditional univariate matrix | [
"Compute",
"likelihood",
"of",
"the",
"tree",
"given",
"an",
"U",
"matrix",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L213-L235 |
225,256 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Tree.from_dict | def from_dict(cls, tree_dict, previous=None):
"""Create a new instance from a dictionary."""
instance = cls(tree_dict['tree_type'])
fitted = tree_dict['fitted']
instance.fitted = fitted
if fitted:
instance.level = tree_dict['level']
instance.n_nodes = tree_dict['n_nodes']
instance.tau_matrix = np.array(tree_dict['tau_matrix'])
instance.previous_tree = cls._deserialize_previous_tree(tree_dict, previous)
instance.edges = [Edge.from_dict(edge) for edge in tree_dict['edges']]
return instance | python | def from_dict(cls, tree_dict, previous=None):
instance = cls(tree_dict['tree_type'])
fitted = tree_dict['fitted']
instance.fitted = fitted
if fitted:
instance.level = tree_dict['level']
instance.n_nodes = tree_dict['n_nodes']
instance.tau_matrix = np.array(tree_dict['tau_matrix'])
instance.previous_tree = cls._deserialize_previous_tree(tree_dict, previous)
instance.edges = [Edge.from_dict(edge) for edge in tree_dict['edges']]
return instance | [
"def",
"from_dict",
"(",
"cls",
",",
"tree_dict",
",",
"previous",
"=",
"None",
")",
":",
"instance",
"=",
"cls",
"(",
"tree_dict",
"[",
"'tree_type'",
"]",
")",
"fitted",
"=",
"tree_dict",
"[",
"'fitted'",
"]",
"instance",
".",
"fitted",
"=",
"fitted",
... | Create a new instance from a dictionary. | [
"Create",
"a",
"new",
"instance",
"from",
"a",
"dictionary",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L277-L290 |
225,257 | DAI-Lab/Copulas | copulas/multivariate/tree.py | CenterTree._build_first_tree | def _build_first_tree(self):
"""Build first level tree."""
tau_sorted = self._sort_tau_by_y(0)
for itr in range(self.n_nodes - 1):
ind = int(tau_sorted[itr, 0])
name, theta = Bivariate.select_copula(self.u_matrix[:, (0, ind)])
new_edge = Edge(itr, 0, ind, name, theta)
new_edge.tau = self.tau_matrix[0, ind]
self.edges.append(new_edge) | python | def _build_first_tree(self):
tau_sorted = self._sort_tau_by_y(0)
for itr in range(self.n_nodes - 1):
ind = int(tau_sorted[itr, 0])
name, theta = Bivariate.select_copula(self.u_matrix[:, (0, ind)])
new_edge = Edge(itr, 0, ind, name, theta)
new_edge.tau = self.tau_matrix[0, ind]
self.edges.append(new_edge) | [
"def",
"_build_first_tree",
"(",
"self",
")",
":",
"tau_sorted",
"=",
"self",
".",
"_sort_tau_by_y",
"(",
"0",
")",
"for",
"itr",
"in",
"range",
"(",
"self",
".",
"n_nodes",
"-",
"1",
")",
":",
"ind",
"=",
"int",
"(",
"tau_sorted",
"[",
"itr",
",",
... | Build first level tree. | [
"Build",
"first",
"level",
"tree",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L312-L321 |
225,258 | DAI-Lab/Copulas | copulas/multivariate/tree.py | CenterTree._build_kth_tree | def _build_kth_tree(self):
"""Build k-th level tree."""
anchor = self.get_anchor()
aux_sorted = self._sort_tau_by_y(anchor)
edges = self.previous_tree.edges
for itr in range(self.n_nodes - 1):
right = int(aux_sorted[itr, 0])
left_parent, right_parent = Edge.sort_edge([edges[anchor], edges[right]])
new_edge = Edge.get_child_edge(itr, left_parent, right_parent)
new_edge.tau = aux_sorted[itr, 1]
self.edges.append(new_edge) | python | def _build_kth_tree(self):
anchor = self.get_anchor()
aux_sorted = self._sort_tau_by_y(anchor)
edges = self.previous_tree.edges
for itr in range(self.n_nodes - 1):
right = int(aux_sorted[itr, 0])
left_parent, right_parent = Edge.sort_edge([edges[anchor], edges[right]])
new_edge = Edge.get_child_edge(itr, left_parent, right_parent)
new_edge.tau = aux_sorted[itr, 1]
self.edges.append(new_edge) | [
"def",
"_build_kth_tree",
"(",
"self",
")",
":",
"anchor",
"=",
"self",
".",
"get_anchor",
"(",
")",
"aux_sorted",
"=",
"self",
".",
"_sort_tau_by_y",
"(",
"anchor",
")",
"edges",
"=",
"self",
".",
"previous_tree",
".",
"edges",
"for",
"itr",
"in",
"rang... | Build k-th level tree. | [
"Build",
"k",
"-",
"th",
"level",
"tree",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L323-L334 |
225,259 | DAI-Lab/Copulas | copulas/multivariate/tree.py | CenterTree.get_anchor | def get_anchor(self):
"""Find anchor variable with highest sum of dependence with the rest."""
temp = np.empty([self.n_nodes, 2])
temp[:, 0] = np.arange(self.n_nodes, dtype=int)
temp[:, 1] = np.sum(abs(self.tau_matrix), 1)
anchor = int(temp[0, 0])
return anchor | python | def get_anchor(self):
temp = np.empty([self.n_nodes, 2])
temp[:, 0] = np.arange(self.n_nodes, dtype=int)
temp[:, 1] = np.sum(abs(self.tau_matrix), 1)
anchor = int(temp[0, 0])
return anchor | [
"def",
"get_anchor",
"(",
"self",
")",
":",
"temp",
"=",
"np",
".",
"empty",
"(",
"[",
"self",
".",
"n_nodes",
",",
"2",
"]",
")",
"temp",
"[",
":",
",",
"0",
"]",
"=",
"np",
".",
"arange",
"(",
"self",
".",
"n_nodes",
",",
"dtype",
"=",
"int... | Find anchor variable with highest sum of dependence with the rest. | [
"Find",
"anchor",
"variable",
"with",
"highest",
"sum",
"of",
"dependence",
"with",
"the",
"rest",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L336-L342 |
225,260 | DAI-Lab/Copulas | copulas/multivariate/tree.py | RegularTree._build_first_tree | def _build_first_tree(self):
"""Build the first tree with n-1 variable."""
# Prim's algorithm
neg_tau = -1.0 * abs(self.tau_matrix)
X = {0}
while len(X) != self.n_nodes:
adj_set = set()
for x in X:
for k in range(self.n_nodes):
if k not in X and k != x:
adj_set.add((x, k))
# find edge with maximum
edge = sorted(adj_set, key=lambda e: neg_tau[e[0]][e[1]])[0]
name, theta = Bivariate.select_copula(self.u_matrix[:, (edge[0], edge[1])])
left, right = sorted([edge[0], edge[1]])
new_edge = Edge(len(X) - 1, left, right, name, theta)
new_edge.tau = self.tau_matrix[edge[0], edge[1]]
self.edges.append(new_edge)
X.add(edge[1]) | python | def _build_first_tree(self):
# Prim's algorithm
neg_tau = -1.0 * abs(self.tau_matrix)
X = {0}
while len(X) != self.n_nodes:
adj_set = set()
for x in X:
for k in range(self.n_nodes):
if k not in X and k != x:
adj_set.add((x, k))
# find edge with maximum
edge = sorted(adj_set, key=lambda e: neg_tau[e[0]][e[1]])[0]
name, theta = Bivariate.select_copula(self.u_matrix[:, (edge[0], edge[1])])
left, right = sorted([edge[0], edge[1]])
new_edge = Edge(len(X) - 1, left, right, name, theta)
new_edge.tau = self.tau_matrix[edge[0], edge[1]]
self.edges.append(new_edge)
X.add(edge[1]) | [
"def",
"_build_first_tree",
"(",
"self",
")",
":",
"# Prim's algorithm",
"neg_tau",
"=",
"-",
"1.0",
"*",
"abs",
"(",
"self",
".",
"tau_matrix",
")",
"X",
"=",
"{",
"0",
"}",
"while",
"len",
"(",
"X",
")",
"!=",
"self",
".",
"n_nodes",
":",
"adj_set"... | Build the first tree with n-1 variable. | [
"Build",
"the",
"first",
"tree",
"with",
"n",
"-",
"1",
"variable",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L401-L422 |
225,261 | DAI-Lab/Copulas | copulas/multivariate/tree.py | RegularTree._build_kth_tree | def _build_kth_tree(self):
"""Build tree for level k."""
neg_tau = -1.0 * abs(self.tau_matrix)
edges = self.previous_tree.edges
visited = set([0])
unvisited = set(range(self.n_nodes))
while len(visited) != self.n_nodes:
adj_set = set()
for x in visited:
for k in range(self.n_nodes):
# check if (x,k) is a valid edge in the vine
if k not in visited and k != x and self._check_contraint(edges[x], edges[k]):
adj_set.add((x, k))
# find edge with maximum tau
if len(adj_set) == 0:
visited.add(list(unvisited)[0])
continue
pairs = sorted(adj_set, key=lambda e: neg_tau[e[0]][e[1]])[0]
left_parent, right_parent = Edge.sort_edge([edges[pairs[0]], edges[pairs[1]]])
new_edge = Edge.get_child_edge(len(visited) - 1, left_parent, right_parent)
new_edge.tau = self.tau_matrix[pairs[0], pairs[1]]
self.edges.append(new_edge)
visited.add(pairs[1])
unvisited.remove(pairs[1]) | python | def _build_kth_tree(self):
neg_tau = -1.0 * abs(self.tau_matrix)
edges = self.previous_tree.edges
visited = set([0])
unvisited = set(range(self.n_nodes))
while len(visited) != self.n_nodes:
adj_set = set()
for x in visited:
for k in range(self.n_nodes):
# check if (x,k) is a valid edge in the vine
if k not in visited and k != x and self._check_contraint(edges[x], edges[k]):
adj_set.add((x, k))
# find edge with maximum tau
if len(adj_set) == 0:
visited.add(list(unvisited)[0])
continue
pairs = sorted(adj_set, key=lambda e: neg_tau[e[0]][e[1]])[0]
left_parent, right_parent = Edge.sort_edge([edges[pairs[0]], edges[pairs[1]]])
new_edge = Edge.get_child_edge(len(visited) - 1, left_parent, right_parent)
new_edge.tau = self.tau_matrix[pairs[0], pairs[1]]
self.edges.append(new_edge)
visited.add(pairs[1])
unvisited.remove(pairs[1]) | [
"def",
"_build_kth_tree",
"(",
"self",
")",
":",
"neg_tau",
"=",
"-",
"1.0",
"*",
"abs",
"(",
"self",
".",
"tau_matrix",
")",
"edges",
"=",
"self",
".",
"previous_tree",
".",
"edges",
"visited",
"=",
"set",
"(",
"[",
"0",
"]",
")",
"unvisited",
"=",
... | Build tree for level k. | [
"Build",
"tree",
"for",
"level",
"k",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L424-L452 |
225,262 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Edge._identify_eds_ing | def _identify_eds_ing(first, second):
"""Find nodes connecting adjacent edges.
Args:
first(Edge): Edge object representing the first edge.
second(Edge): Edge object representing the second edge.
Returns:
tuple[int, int, set[int]]: The first two values represent left and right node
indicies of the new edge. The third value is the new dependence set.
"""
A = set([first.L, first.R])
A.update(first.D)
B = set([second.L, second.R])
B.update(second.D)
depend_set = A & B
left, right = sorted(list(A ^ B))
return left, right, depend_set | python | def _identify_eds_ing(first, second):
A = set([first.L, first.R])
A.update(first.D)
B = set([second.L, second.R])
B.update(second.D)
depend_set = A & B
left, right = sorted(list(A ^ B))
return left, right, depend_set | [
"def",
"_identify_eds_ing",
"(",
"first",
",",
"second",
")",
":",
"A",
"=",
"set",
"(",
"[",
"first",
".",
"L",
",",
"first",
".",
"R",
"]",
")",
"A",
".",
"update",
"(",
"first",
".",
"D",
")",
"B",
"=",
"set",
"(",
"[",
"second",
".",
"L",... | Find nodes connecting adjacent edges.
Args:
first(Edge): Edge object representing the first edge.
second(Edge): Edge object representing the second edge.
Returns:
tuple[int, int, set[int]]: The first two values represent left and right node
indicies of the new edge. The third value is the new dependence set. | [
"Find",
"nodes",
"connecting",
"adjacent",
"edges",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L480-L500 |
225,263 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Edge.is_adjacent | def is_adjacent(self, another_edge):
"""Check if two edges are adjacent.
Args:
:param another_edge: edge object of another edge
:type another_edge: edge object
This function will return true if the two edges are adjacent.
"""
return (
self.L == another_edge.L
or self.L == another_edge.R
or self.R == another_edge.L
or self.R == another_edge.R
) | python | def is_adjacent(self, another_edge):
return (
self.L == another_edge.L
or self.L == another_edge.R
or self.R == another_edge.L
or self.R == another_edge.R
) | [
"def",
"is_adjacent",
"(",
"self",
",",
"another_edge",
")",
":",
"return",
"(",
"self",
".",
"L",
"==",
"another_edge",
".",
"L",
"or",
"self",
".",
"L",
"==",
"another_edge",
".",
"R",
"or",
"self",
".",
"R",
"==",
"another_edge",
".",
"L",
"or",
... | Check if two edges are adjacent.
Args:
:param another_edge: edge object of another edge
:type another_edge: edge object
This function will return true if the two edges are adjacent. | [
"Check",
"if",
"two",
"edges",
"are",
"adjacent",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L502-L516 |
225,264 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Edge.sort_edge | def sort_edge(edges):
"""Sort iterable of edges first by left node indices then right.
Args:
edges(list[Edge]): List of edges to be sorted.
Returns:
list[Edge]: Sorted list by left and right node indices.
"""
return sorted(edges, key=lambda x: (x.L, x.R)) | python | def sort_edge(edges):
return sorted(edges, key=lambda x: (x.L, x.R)) | [
"def",
"sort_edge",
"(",
"edges",
")",
":",
"return",
"sorted",
"(",
"edges",
",",
"key",
"=",
"lambda",
"x",
":",
"(",
"x",
".",
"L",
",",
"x",
".",
"R",
")",
")"
] | Sort iterable of edges first by left node indices then right.
Args:
edges(list[Edge]): List of edges to be sorted.
Returns:
list[Edge]: Sorted list by left and right node indices. | [
"Sort",
"iterable",
"of",
"edges",
"first",
"by",
"left",
"node",
"indices",
"then",
"right",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L519-L528 |
225,265 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Edge.get_conditional_uni | def get_conditional_uni(cls, left_parent, right_parent):
"""Identify pair univariate value from parents.
Args:
left_parent(Edge): left parent
right_parent(Edge): right parent
Returns:
tuple[np.ndarray, np.ndarray]: left and right parents univariate.
"""
left, right, _ = cls._identify_eds_ing(left_parent, right_parent)
left_u = left_parent.U[0] if left_parent.L == left else left_parent.U[1]
right_u = right_parent.U[0] if right_parent.L == right else right_parent.U[1]
return left_u, right_u | python | def get_conditional_uni(cls, left_parent, right_parent):
left, right, _ = cls._identify_eds_ing(left_parent, right_parent)
left_u = left_parent.U[0] if left_parent.L == left else left_parent.U[1]
right_u = right_parent.U[0] if right_parent.L == right else right_parent.U[1]
return left_u, right_u | [
"def",
"get_conditional_uni",
"(",
"cls",
",",
"left_parent",
",",
"right_parent",
")",
":",
"left",
",",
"right",
",",
"_",
"=",
"cls",
".",
"_identify_eds_ing",
"(",
"left_parent",
",",
"right_parent",
")",
"left_u",
"=",
"left_parent",
".",
"U",
"[",
"0... | Identify pair univariate value from parents.
Args:
left_parent(Edge): left parent
right_parent(Edge): right parent
Returns:
tuple[np.ndarray, np.ndarray]: left and right parents univariate. | [
"Identify",
"pair",
"univariate",
"value",
"from",
"parents",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L531-L546 |
225,266 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Edge.get_child_edge | def get_child_edge(cls, index, left_parent, right_parent):
"""Construct a child edge from two parent edges."""
[ed1, ed2, depend_set] = cls._identify_eds_ing(left_parent, right_parent)
left_u, right_u = cls.get_conditional_uni(left_parent, right_parent)
X = np.array([[x, y] for x, y in zip(left_u, right_u)])
name, theta = Bivariate.select_copula(X)
new_edge = Edge(index, ed1, ed2, name, theta)
new_edge.D = depend_set
new_edge.parents = [left_parent, right_parent]
return new_edge | python | def get_child_edge(cls, index, left_parent, right_parent):
[ed1, ed2, depend_set] = cls._identify_eds_ing(left_parent, right_parent)
left_u, right_u = cls.get_conditional_uni(left_parent, right_parent)
X = np.array([[x, y] for x, y in zip(left_u, right_u)])
name, theta = Bivariate.select_copula(X)
new_edge = Edge(index, ed1, ed2, name, theta)
new_edge.D = depend_set
new_edge.parents = [left_parent, right_parent]
return new_edge | [
"def",
"get_child_edge",
"(",
"cls",
",",
"index",
",",
"left_parent",
",",
"right_parent",
")",
":",
"[",
"ed1",
",",
"ed2",
",",
"depend_set",
"]",
"=",
"cls",
".",
"_identify_eds_ing",
"(",
"left_parent",
",",
"right_parent",
")",
"left_u",
",",
"right_... | Construct a child edge from two parent edges. | [
"Construct",
"a",
"child",
"edge",
"from",
"two",
"parent",
"edges",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L549-L558 |
225,267 | DAI-Lab/Copulas | copulas/multivariate/tree.py | Edge.get_likelihood | def get_likelihood(self, uni_matrix):
"""Compute likelihood given a U matrix.
Args:
uni_matrix(numpy.array): Matrix to compute the likelihood.
Return:
tuple(np.ndarray, np.ndarray, np.array): likelihood and conditional values.
"""
if self.parents is None:
left_u = uni_matrix[:, self.L]
right_u = uni_matrix[:, self.R]
else:
left_ing = list(self.D - self.parents[0].D)[0]
right_ing = list(self.D - self.parents[1].D)[0]
left_u = uni_matrix[self.L, left_ing]
right_u = uni_matrix[self.R, right_ing]
copula = Bivariate(self.name)
copula.theta = self.theta
X_left_right = np.array([[left_u, right_u]])
X_right_left = np.array([[right_u, left_u]])
value = np.sum(copula.probability_density(X_left_right))
left_given_right = copula.partial_derivative(X_left_right)
right_given_left = copula.partial_derivative(X_right_left)
return value, left_given_right, right_given_left | python | def get_likelihood(self, uni_matrix):
if self.parents is None:
left_u = uni_matrix[:, self.L]
right_u = uni_matrix[:, self.R]
else:
left_ing = list(self.D - self.parents[0].D)[0]
right_ing = list(self.D - self.parents[1].D)[0]
left_u = uni_matrix[self.L, left_ing]
right_u = uni_matrix[self.R, right_ing]
copula = Bivariate(self.name)
copula.theta = self.theta
X_left_right = np.array([[left_u, right_u]])
X_right_left = np.array([[right_u, left_u]])
value = np.sum(copula.probability_density(X_left_right))
left_given_right = copula.partial_derivative(X_left_right)
right_given_left = copula.partial_derivative(X_right_left)
return value, left_given_right, right_given_left | [
"def",
"get_likelihood",
"(",
"self",
",",
"uni_matrix",
")",
":",
"if",
"self",
".",
"parents",
"is",
"None",
":",
"left_u",
"=",
"uni_matrix",
"[",
":",
",",
"self",
".",
"L",
"]",
"right_u",
"=",
"uni_matrix",
"[",
":",
",",
"self",
".",
"R",
"]... | Compute likelihood given a U matrix.
Args:
uni_matrix(numpy.array): Matrix to compute the likelihood.
Return:
tuple(np.ndarray, np.ndarray, np.array): likelihood and conditional values. | [
"Compute",
"likelihood",
"given",
"a",
"U",
"matrix",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/multivariate/tree.py#L560-L589 |
225,268 | DAI-Lab/Copulas | copulas/univariate/kde.py | KDEUnivariate.fit | def fit(self, X):
"""Fit Kernel density estimation to an list of values.
Args:
X: 1-d `np.ndarray` or `pd.Series` or `list` datapoints to be estimated from.
This function will fit a gaussian_kde model to a list of datapoints
and store it as a class attribute.
"""
self.constant_value = self._get_constant_value(X)
if self.constant_value is None:
self.model = scipy.stats.gaussian_kde(X)
else:
self._replace_constant_methods()
self.fitted = True | python | def fit(self, X):
self.constant_value = self._get_constant_value(X)
if self.constant_value is None:
self.model = scipy.stats.gaussian_kde(X)
else:
self._replace_constant_methods()
self.fitted = True | [
"def",
"fit",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"constant_value",
"=",
"self",
".",
"_get_constant_value",
"(",
"X",
")",
"if",
"self",
".",
"constant_value",
"is",
"None",
":",
"self",
".",
"model",
"=",
"scipy",
".",
"stats",
".",
"gaus... | Fit Kernel density estimation to an list of values.
Args:
X: 1-d `np.ndarray` or `pd.Series` or `list` datapoints to be estimated from.
This function will fit a gaussian_kde model to a list of datapoints
and store it as a class attribute. | [
"Fit",
"Kernel",
"density",
"estimation",
"to",
"an",
"list",
"of",
"values",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/kde.py#L19-L37 |
225,269 | DAI-Lab/Copulas | copulas/univariate/kde.py | KDEUnivariate.probability_density | def probability_density(self, X):
"""Evaluate the estimated pdf on a point.
Args:
X: `float` a datapoint.
:type X: float
Returns:
pdf: int or float with the value of estimated pdf
"""
self.check_fit()
if type(X) not in (int, float):
raise ValueError('x must be int or float')
return self.model.evaluate(X)[0] | python | def probability_density(self, X):
self.check_fit()
if type(X) not in (int, float):
raise ValueError('x must be int or float')
return self.model.evaluate(X)[0] | [
"def",
"probability_density",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"if",
"type",
"(",
"X",
")",
"not",
"in",
"(",
"int",
",",
"float",
")",
":",
"raise",
"ValueError",
"(",
"'x must be int or float'",
")",
"return",
"sel... | Evaluate the estimated pdf on a point.
Args:
X: `float` a datapoint.
:type X: float
Returns:
pdf: int or float with the value of estimated pdf | [
"Evaluate",
"the",
"estimated",
"pdf",
"on",
"a",
"point",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/kde.py#L39-L54 |
225,270 | DAI-Lab/Copulas | copulas/univariate/gaussian_kde.py | GaussianKDE._brentq_cdf | def _brentq_cdf(self, value):
"""Helper function to compute percent_point.
As scipy.stats.gaussian_kde doesn't provide this functionality out of the box we need
to make a numerical approach:
- First we scalarize and bound cumulative_distribution.
- Then we define a function `f(x) = cdf(x) - value`, where value is the given argument.
- As value will be called from ppf we can assume value = cdf(z) for some z that is the
value we are searching for. Therefore the zeros of the function will be x such that:
cdf(x) - cdf(z) = 0 => (becasue cdf is monotonous and continous) x = z
Args:
value(float): cdf value, that is, in [0,1]
Returns:
callable: function whose zero is the ppf of value.
"""
# The decorator expects an instance method, but usually are decorated before being bounded
bound_cdf = partial(scalarize(GaussianKDE.cumulative_distribution), self)
def f(x):
return bound_cdf(x) - value
return f | python | def _brentq_cdf(self, value):
# The decorator expects an instance method, but usually are decorated before being bounded
bound_cdf = partial(scalarize(GaussianKDE.cumulative_distribution), self)
def f(x):
return bound_cdf(x) - value
return f | [
"def",
"_brentq_cdf",
"(",
"self",
",",
"value",
")",
":",
"# The decorator expects an instance method, but usually are decorated before being bounded",
"bound_cdf",
"=",
"partial",
"(",
"scalarize",
"(",
"GaussianKDE",
".",
"cumulative_distribution",
")",
",",
"self",
")",... | Helper function to compute percent_point.
As scipy.stats.gaussian_kde doesn't provide this functionality out of the box we need
to make a numerical approach:
- First we scalarize and bound cumulative_distribution.
- Then we define a function `f(x) = cdf(x) - value`, where value is the given argument.
- As value will be called from ppf we can assume value = cdf(z) for some z that is the
value we are searching for. Therefore the zeros of the function will be x such that:
cdf(x) - cdf(z) = 0 => (becasue cdf is monotonous and continous) x = z
Args:
value(float): cdf value, that is, in [0,1]
Returns:
callable: function whose zero is the ppf of value. | [
"Helper",
"function",
"to",
"compute",
"percent_point",
"."
] | 821df61c3d36a6b81ef2883935f935c2eaaa862c | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/gaussian_kde.py#L39-L63 |
225,271 | mjg59/python-broadlink | broadlink/__init__.py | mp1.check_power_raw | def check_power_raw(self):
"""Returns the power state of the smart power strip in raw format."""
packet = bytearray(16)
packet[0x00] = 0x0a
packet[0x02] = 0xa5
packet[0x03] = 0xa5
packet[0x04] = 0x5a
packet[0x05] = 0x5a
packet[0x06] = 0xae
packet[0x07] = 0xc0
packet[0x08] = 0x01
response = self.send_packet(0x6a, packet)
err = response[0x22] | (response[0x23] << 8)
if err == 0:
payload = self.decrypt(bytes(response[0x38:]))
if type(payload[0x4]) == int:
state = payload[0x0e]
else:
state = ord(payload[0x0e])
return state | python | def check_power_raw(self):
packet = bytearray(16)
packet[0x00] = 0x0a
packet[0x02] = 0xa5
packet[0x03] = 0xa5
packet[0x04] = 0x5a
packet[0x05] = 0x5a
packet[0x06] = 0xae
packet[0x07] = 0xc0
packet[0x08] = 0x01
response = self.send_packet(0x6a, packet)
err = response[0x22] | (response[0x23] << 8)
if err == 0:
payload = self.decrypt(bytes(response[0x38:]))
if type(payload[0x4]) == int:
state = payload[0x0e]
else:
state = ord(payload[0x0e])
return state | [
"def",
"check_power_raw",
"(",
"self",
")",
":",
"packet",
"=",
"bytearray",
"(",
"16",
")",
"packet",
"[",
"0x00",
"]",
"=",
"0x0a",
"packet",
"[",
"0x02",
"]",
"=",
"0xa5",
"packet",
"[",
"0x03",
"]",
"=",
"0xa5",
"packet",
"[",
"0x04",
"]",
"=",... | Returns the power state of the smart power strip in raw format. | [
"Returns",
"the",
"power",
"state",
"of",
"the",
"smart",
"power",
"strip",
"in",
"raw",
"format",
"."
] | 1d6d8d2aee6e221aa3383e4078b19b7b95397f43 | https://github.com/mjg59/python-broadlink/blob/1d6d8d2aee6e221aa3383e4078b19b7b95397f43/broadlink/__init__.py#L325-L345 |
225,272 | mjg59/python-broadlink | broadlink/__init__.py | mp1.check_power | def check_power(self):
"""Returns the power state of the smart power strip."""
state = self.check_power_raw()
data = {}
data['s1'] = bool(state & 0x01)
data['s2'] = bool(state & 0x02)
data['s3'] = bool(state & 0x04)
data['s4'] = bool(state & 0x08)
return data | python | def check_power(self):
state = self.check_power_raw()
data = {}
data['s1'] = bool(state & 0x01)
data['s2'] = bool(state & 0x02)
data['s3'] = bool(state & 0x04)
data['s4'] = bool(state & 0x08)
return data | [
"def",
"check_power",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"check_power_raw",
"(",
")",
"data",
"=",
"{",
"}",
"data",
"[",
"'s1'",
"]",
"=",
"bool",
"(",
"state",
"&",
"0x01",
")",
"data",
"[",
"'s2'",
"]",
"=",
"bool",
"(",
"state"... | Returns the power state of the smart power strip. | [
"Returns",
"the",
"power",
"state",
"of",
"the",
"smart",
"power",
"strip",
"."
] | 1d6d8d2aee6e221aa3383e4078b19b7b95397f43 | https://github.com/mjg59/python-broadlink/blob/1d6d8d2aee6e221aa3383e4078b19b7b95397f43/broadlink/__init__.py#L347-L355 |
225,273 | mjg59/python-broadlink | broadlink/__init__.py | sp2.set_power | def set_power(self, state):
"""Sets the power state of the smart plug."""
packet = bytearray(16)
packet[0] = 2
if self.check_nightlight():
packet[4] = 3 if state else 2
else:
packet[4] = 1 if state else 0
self.send_packet(0x6a, packet) | python | def set_power(self, state):
packet = bytearray(16)
packet[0] = 2
if self.check_nightlight():
packet[4] = 3 if state else 2
else:
packet[4] = 1 if state else 0
self.send_packet(0x6a, packet) | [
"def",
"set_power",
"(",
"self",
",",
"state",
")",
":",
"packet",
"=",
"bytearray",
"(",
"16",
")",
"packet",
"[",
"0",
"]",
"=",
"2",
"if",
"self",
".",
"check_nightlight",
"(",
")",
":",
"packet",
"[",
"4",
"]",
"=",
"3",
"if",
"state",
"else"... | Sets the power state of the smart plug. | [
"Sets",
"the",
"power",
"state",
"of",
"the",
"smart",
"plug",
"."
] | 1d6d8d2aee6e221aa3383e4078b19b7b95397f43 | https://github.com/mjg59/python-broadlink/blob/1d6d8d2aee6e221aa3383e4078b19b7b95397f43/broadlink/__init__.py#L374-L382 |
225,274 | mjg59/python-broadlink | broadlink/__init__.py | sp2.set_nightlight | def set_nightlight(self, state):
"""Sets the night light state of the smart plug"""
packet = bytearray(16)
packet[0] = 2
if self.check_power():
packet[4] = 3 if state else 1
else:
packet[4] = 2 if state else 0
self.send_packet(0x6a, packet) | python | def set_nightlight(self, state):
packet = bytearray(16)
packet[0] = 2
if self.check_power():
packet[4] = 3 if state else 1
else:
packet[4] = 2 if state else 0
self.send_packet(0x6a, packet) | [
"def",
"set_nightlight",
"(",
"self",
",",
"state",
")",
":",
"packet",
"=",
"bytearray",
"(",
"16",
")",
"packet",
"[",
"0",
"]",
"=",
"2",
"if",
"self",
".",
"check_power",
"(",
")",
":",
"packet",
"[",
"4",
"]",
"=",
"3",
"if",
"state",
"else"... | Sets the night light state of the smart plug | [
"Sets",
"the",
"night",
"light",
"state",
"of",
"the",
"smart",
"plug"
] | 1d6d8d2aee6e221aa3383e4078b19b7b95397f43 | https://github.com/mjg59/python-broadlink/blob/1d6d8d2aee6e221aa3383e4078b19b7b95397f43/broadlink/__init__.py#L384-L392 |
225,275 | mjg59/python-broadlink | broadlink/__init__.py | sp2.check_power | def check_power(self):
"""Returns the power state of the smart plug."""
packet = bytearray(16)
packet[0] = 1
response = self.send_packet(0x6a, packet)
err = response[0x22] | (response[0x23] << 8)
if err == 0:
payload = self.decrypt(bytes(response[0x38:]))
if type(payload[0x4]) == int:
if payload[0x4] == 1 or payload[0x4] == 3 or payload[0x4] == 0xFD:
state = True
else:
state = False
else:
if ord(payload[0x4]) == 1 or ord(payload[0x4]) == 3 or ord(payload[0x4]) == 0xFD:
state = True
else:
state = False
return state | python | def check_power(self):
packet = bytearray(16)
packet[0] = 1
response = self.send_packet(0x6a, packet)
err = response[0x22] | (response[0x23] << 8)
if err == 0:
payload = self.decrypt(bytes(response[0x38:]))
if type(payload[0x4]) == int:
if payload[0x4] == 1 or payload[0x4] == 3 or payload[0x4] == 0xFD:
state = True
else:
state = False
else:
if ord(payload[0x4]) == 1 or ord(payload[0x4]) == 3 or ord(payload[0x4]) == 0xFD:
state = True
else:
state = False
return state | [
"def",
"check_power",
"(",
"self",
")",
":",
"packet",
"=",
"bytearray",
"(",
"16",
")",
"packet",
"[",
"0",
"]",
"=",
"1",
"response",
"=",
"self",
".",
"send_packet",
"(",
"0x6a",
",",
"packet",
")",
"err",
"=",
"response",
"[",
"0x22",
"]",
"|",... | Returns the power state of the smart plug. | [
"Returns",
"the",
"power",
"state",
"of",
"the",
"smart",
"plug",
"."
] | 1d6d8d2aee6e221aa3383e4078b19b7b95397f43 | https://github.com/mjg59/python-broadlink/blob/1d6d8d2aee6e221aa3383e4078b19b7b95397f43/broadlink/__init__.py#L394-L412 |
225,276 | twilio/twilio-python | twilio/rest/authy/v1/service/entity/factor/challenge.py | ChallengeList.create | def create(self, expiration_date=values.unset, details=values.unset,
hidden_details=values.unset):
"""
Create a new ChallengeInstance
:param datetime expiration_date: The future date in which this Challenge will expire
:param unicode details: Public details provided to contextualize the Challenge
:param unicode hidden_details: Hidden details provided to contextualize the Challenge
:returns: Newly created ChallengeInstance
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance
"""
data = values.of({
'ExpirationDate': serialize.iso8601_datetime(expiration_date),
'Details': details,
'HiddenDetails': hidden_details,
})
payload = self._version.create(
'POST',
self._uri,
data=data,
)
return ChallengeInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
identity=self._solution['identity'],
factor_sid=self._solution['factor_sid'],
) | python | def create(self, expiration_date=values.unset, details=values.unset,
hidden_details=values.unset):
data = values.of({
'ExpirationDate': serialize.iso8601_datetime(expiration_date),
'Details': details,
'HiddenDetails': hidden_details,
})
payload = self._version.create(
'POST',
self._uri,
data=data,
)
return ChallengeInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
identity=self._solution['identity'],
factor_sid=self._solution['factor_sid'],
) | [
"def",
"create",
"(",
"self",
",",
"expiration_date",
"=",
"values",
".",
"unset",
",",
"details",
"=",
"values",
".",
"unset",
",",
"hidden_details",
"=",
"values",
".",
"unset",
")",
":",
"data",
"=",
"values",
".",
"of",
"(",
"{",
"'ExpirationDate'",
... | Create a new ChallengeInstance
:param datetime expiration_date: The future date in which this Challenge will expire
:param unicode details: Public details provided to contextualize the Challenge
:param unicode hidden_details: Hidden details provided to contextualize the Challenge
:returns: Newly created ChallengeInstance
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance | [
"Create",
"a",
"new",
"ChallengeInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/authy/v1/service/entity/factor/challenge.py#L41-L71 |
225,277 | twilio/twilio-python | twilio/rest/authy/v1/service/entity/factor/challenge.py | ChallengeList.get | def get(self, sid):
"""
Constructs a ChallengeContext
:param sid: A string that uniquely identifies this Challenge, or `latest`.
:returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext
"""
return ChallengeContext(
self._version,
service_sid=self._solution['service_sid'],
identity=self._solution['identity'],
factor_sid=self._solution['factor_sid'],
sid=sid,
) | python | def get(self, sid):
return ChallengeContext(
self._version,
service_sid=self._solution['service_sid'],
identity=self._solution['identity'],
factor_sid=self._solution['factor_sid'],
sid=sid,
) | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"ChallengeContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"identity",
"=",
"self",
".",
"_solution",
"[",
"'identity'",
... | Constructs a ChallengeContext
:param sid: A string that uniquely identifies this Challenge, or `latest`.
:returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext | [
"Constructs",
"a",
"ChallengeContext"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/authy/v1/service/entity/factor/challenge.py#L73-L88 |
225,278 | twilio/twilio-python | twilio/rest/authy/v1/service/entity/factor/challenge.py | ChallengePage.get_instance | def get_instance(self, payload):
"""
Build an instance of ChallengeInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance
"""
return ChallengeInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
identity=self._solution['identity'],
factor_sid=self._solution['factor_sid'],
) | python | def get_instance(self, payload):
return ChallengeInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
identity=self._solution['identity'],
factor_sid=self._solution['factor_sid'],
) | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"ChallengeInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"identity",
"=",
"self",
".",
"_so... | Build an instance of ChallengeInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance | [
"Build",
"an",
"instance",
"of",
"ChallengeInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/authy/v1/service/entity/factor/challenge.py#L140-L155 |
225,279 | twilio/twilio-python | twilio/rest/authy/v1/service/entity/factor/challenge.py | ChallengeContext.fetch | def fetch(self):
"""
Fetch a ChallengeInstance
:returns: Fetched ChallengeInstance
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
return ChallengeInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
identity=self._solution['identity'],
factor_sid=self._solution['factor_sid'],
sid=self._solution['sid'],
) | python | def fetch(self):
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
return ChallengeInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
identity=self._solution['identity'],
factor_sid=self._solution['factor_sid'],
sid=self._solution['sid'],
) | [
"def",
"fetch",
"(",
"self",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"fetch",
"(",
"'GET'",
",",
"self",
".",
"_uri",
",",
"params",
"=",
"params",
",",
")",
"return",
"Chall... | Fetch a ChallengeInstance
:returns: Fetched ChallengeInstance
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance | [
"Fetch",
"a",
"ChallengeInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/authy/v1/service/entity/factor/challenge.py#L205-L227 |
225,280 | twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/task_channel.py | TaskChannelList.create | def create(self, friendly_name, unique_name):
"""
Create a new TaskChannelInstance
:param unicode friendly_name: String representing user-friendly name for the TaskChannel
:param unicode unique_name: String representing unique name for the TaskChannel
:returns: Newly created TaskChannelInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance
"""
data = values.of({'FriendlyName': friendly_name, 'UniqueName': unique_name, })
payload = self._version.create(
'POST',
self._uri,
data=data,
)
return TaskChannelInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) | python | def create(self, friendly_name, unique_name):
data = values.of({'FriendlyName': friendly_name, 'UniqueName': unique_name, })
payload = self._version.create(
'POST',
self._uri,
data=data,
)
return TaskChannelInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) | [
"def",
"create",
"(",
"self",
",",
"friendly_name",
",",
"unique_name",
")",
":",
"data",
"=",
"values",
".",
"of",
"(",
"{",
"'FriendlyName'",
":",
"friendly_name",
",",
"'UniqueName'",
":",
"unique_name",
",",
"}",
")",
"payload",
"=",
"self",
".",
"_v... | Create a new TaskChannelInstance
:param unicode friendly_name: String representing user-friendly name for the TaskChannel
:param unicode unique_name: String representing unique name for the TaskChannel
:returns: Newly created TaskChannelInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance | [
"Create",
"a",
"new",
"TaskChannelInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/task_channel.py#L117-L135 |
225,281 | twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/task_channel.py | TaskChannelList.get | def get(self, sid):
"""
Constructs a TaskChannelContext
:param sid: The sid
:returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext
:rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext
"""
return TaskChannelContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) | python | def get(self, sid):
return TaskChannelContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"TaskChannelContext",
"(",
"self",
".",
"_version",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | Constructs a TaskChannelContext
:param sid: The sid
:returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext
:rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext | [
"Constructs",
"a",
"TaskChannelContext"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/task_channel.py#L137-L146 |
225,282 | twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/task_channel.py | TaskChannelPage.get_instance | def get_instance(self, payload):
"""
Build an instance of TaskChannelInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance
"""
return TaskChannelInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) | python | def get_instance(self, payload):
return TaskChannelInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"TaskChannelInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_sid'",
"]",
",",
")"
] | Build an instance of TaskChannelInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance | [
"Build",
"an",
"instance",
"of",
"TaskChannelInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/task_channel.py#L188-L197 |
225,283 | twilio/twilio-python | twilio/rest/serverless/v1/service/environment/variable.py | VariableList.create | def create(self, key, value):
"""
Create a new VariableInstance
:param unicode key: The key
:param unicode value: The value
:returns: Newly created VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
"""
data = values.of({'Key': key, 'Value': value, })
payload = self._version.create(
'POST',
self._uri,
data=data,
)
return VariableInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
) | python | def create(self, key, value):
data = values.of({'Key': key, 'Value': value, })
payload = self._version.create(
'POST',
self._uri,
data=data,
)
return VariableInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
) | [
"def",
"create",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"data",
"=",
"values",
".",
"of",
"(",
"{",
"'Key'",
":",
"key",
",",
"'Value'",
":",
"value",
",",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"create",
"(",
"'POST'",... | Create a new VariableInstance
:param unicode key: The key
:param unicode value: The value
:returns: Newly created VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance | [
"Create",
"a",
"new",
"VariableInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/serverless/v1/service/environment/variable.py#L120-L143 |
225,284 | twilio/twilio-python | twilio/rest/serverless/v1/service/environment/variable.py | VariableList.get | def get(self, sid):
"""
Constructs a VariableContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.environment.variable.VariableContext
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext
"""
return VariableContext(
self._version,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=sid,
) | python | def get(self, sid):
return VariableContext(
self._version,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=sid,
) | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"VariableContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"environment_sid",
"=",
"self",
".",
"_solution",
"[",
"'environm... | Constructs a VariableContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.environment.variable.VariableContext
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext | [
"Constructs",
"a",
"VariableContext"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/serverless/v1/service/environment/variable.py#L145-L159 |
225,285 | twilio/twilio-python | twilio/rest/serverless/v1/service/environment/variable.py | VariablePage.get_instance | def get_instance(self, payload):
"""
Build an instance of VariableInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
"""
return VariableInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
) | python | def get_instance(self, payload):
return VariableInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
) | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"VariableInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"environment_sid",
"=",
"self",
".",
... | Build an instance of VariableInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance | [
"Build",
"an",
"instance",
"of",
"VariableInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/serverless/v1/service/environment/variable.py#L209-L223 |
225,286 | twilio/twilio-python | twilio/rest/serverless/v1/service/environment/variable.py | VariableContext.fetch | def fetch(self):
"""
Fetch a VariableInstance
:returns: Fetched VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
return VariableInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=self._solution['sid'],
) | python | def fetch(self):
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
return VariableInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
environment_sid=self._solution['environment_sid'],
sid=self._solution['sid'],
) | [
"def",
"fetch",
"(",
"self",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"fetch",
"(",
"'GET'",
",",
"self",
".",
"_uri",
",",
"params",
"=",
"params",
",",
")",
"return",
"Varia... | Fetch a VariableInstance
:returns: Fetched VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance | [
"Fetch",
"a",
"VariableInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/serverless/v1/service/environment/variable.py#L258-L279 |
225,287 | twilio/twilio-python | twilio/rest/api/v2010/account/usage/record/__init__.py | RecordList.all_time | def all_time(self):
"""
Access the all_time
:returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList
:rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList
"""
if self._all_time is None:
self._all_time = AllTimeList(self._version, account_sid=self._solution['account_sid'], )
return self._all_time | python | def all_time(self):
if self._all_time is None:
self._all_time = AllTimeList(self._version, account_sid=self._solution['account_sid'], )
return self._all_time | [
"def",
"all_time",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_time",
"is",
"None",
":",
"self",
".",
"_all_time",
"=",
"AllTimeList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
... | Access the all_time
:returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList
:rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList | [
"Access",
"the",
"all_time"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/record/__init__.py#L175-L184 |
225,288 | twilio/twilio-python | twilio/rest/api/v2010/account/usage/record/__init__.py | RecordList.daily | def daily(self):
"""
Access the daily
:returns: twilio.rest.api.v2010.account.usage.record.daily.DailyList
:rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyList
"""
if self._daily is None:
self._daily = DailyList(self._version, account_sid=self._solution['account_sid'], )
return self._daily | python | def daily(self):
if self._daily is None:
self._daily = DailyList(self._version, account_sid=self._solution['account_sid'], )
return self._daily | [
"def",
"daily",
"(",
"self",
")",
":",
"if",
"self",
".",
"_daily",
"is",
"None",
":",
"self",
".",
"_daily",
"=",
"DailyList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")",
"ret... | Access the daily
:returns: twilio.rest.api.v2010.account.usage.record.daily.DailyList
:rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyList | [
"Access",
"the",
"daily"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/record/__init__.py#L187-L196 |
225,289 | twilio/twilio-python | twilio/rest/api/v2010/account/usage/record/__init__.py | RecordList.last_month | def last_month(self):
"""
Access the last_month
:returns: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList
:rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList
"""
if self._last_month is None:
self._last_month = LastMonthList(self._version, account_sid=self._solution['account_sid'], )
return self._last_month | python | def last_month(self):
if self._last_month is None:
self._last_month = LastMonthList(self._version, account_sid=self._solution['account_sid'], )
return self._last_month | [
"def",
"last_month",
"(",
"self",
")",
":",
"if",
"self",
".",
"_last_month",
"is",
"None",
":",
"self",
".",
"_last_month",
"=",
"LastMonthList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
... | Access the last_month
:returns: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList
:rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList | [
"Access",
"the",
"last_month"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/record/__init__.py#L199-L208 |
225,290 | twilio/twilio-python | twilio/rest/api/v2010/account/usage/record/__init__.py | RecordList.monthly | def monthly(self):
"""
Access the monthly
:returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList
:rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList
"""
if self._monthly is None:
self._monthly = MonthlyList(self._version, account_sid=self._solution['account_sid'], )
return self._monthly | python | def monthly(self):
if self._monthly is None:
self._monthly = MonthlyList(self._version, account_sid=self._solution['account_sid'], )
return self._monthly | [
"def",
"monthly",
"(",
"self",
")",
":",
"if",
"self",
".",
"_monthly",
"is",
"None",
":",
"self",
".",
"_monthly",
"=",
"MonthlyList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")"... | Access the monthly
:returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList
:rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList | [
"Access",
"the",
"monthly"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/record/__init__.py#L211-L220 |
225,291 | twilio/twilio-python | twilio/rest/api/v2010/account/usage/record/__init__.py | RecordList.this_month | def this_month(self):
"""
Access the this_month
:returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList
:rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList
"""
if self._this_month is None:
self._this_month = ThisMonthList(self._version, account_sid=self._solution['account_sid'], )
return self._this_month | python | def this_month(self):
if self._this_month is None:
self._this_month = ThisMonthList(self._version, account_sid=self._solution['account_sid'], )
return self._this_month | [
"def",
"this_month",
"(",
"self",
")",
":",
"if",
"self",
".",
"_this_month",
"is",
"None",
":",
"self",
".",
"_this_month",
"=",
"ThisMonthList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
... | Access the this_month
:returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList
:rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList | [
"Access",
"the",
"this_month"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/record/__init__.py#L223-L232 |
225,292 | twilio/twilio-python | twilio/rest/api/v2010/account/usage/record/__init__.py | RecordList.today | def today(self):
"""
Access the today
:returns: twilio.rest.api.v2010.account.usage.record.today.TodayList
:rtype: twilio.rest.api.v2010.account.usage.record.today.TodayList
"""
if self._today is None:
self._today = TodayList(self._version, account_sid=self._solution['account_sid'], )
return self._today | python | def today(self):
if self._today is None:
self._today = TodayList(self._version, account_sid=self._solution['account_sid'], )
return self._today | [
"def",
"today",
"(",
"self",
")",
":",
"if",
"self",
".",
"_today",
"is",
"None",
":",
"self",
".",
"_today",
"=",
"TodayList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")",
"ret... | Access the today
:returns: twilio.rest.api.v2010.account.usage.record.today.TodayList
:rtype: twilio.rest.api.v2010.account.usage.record.today.TodayList | [
"Access",
"the",
"today"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/record/__init__.py#L235-L244 |
225,293 | twilio/twilio-python | twilio/rest/api/v2010/account/usage/record/__init__.py | RecordList.yearly | def yearly(self):
"""
Access the yearly
:returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList
:rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList
"""
if self._yearly is None:
self._yearly = YearlyList(self._version, account_sid=self._solution['account_sid'], )
return self._yearly | python | def yearly(self):
if self._yearly is None:
self._yearly = YearlyList(self._version, account_sid=self._solution['account_sid'], )
return self._yearly | [
"def",
"yearly",
"(",
"self",
")",
":",
"if",
"self",
".",
"_yearly",
"is",
"None",
":",
"self",
".",
"_yearly",
"=",
"YearlyList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")",
... | Access the yearly
:returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList
:rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList | [
"Access",
"the",
"yearly"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/record/__init__.py#L247-L256 |
225,294 | twilio/twilio-python | twilio/rest/api/v2010/account/usage/record/__init__.py | RecordList.yesterday | def yesterday(self):
"""
Access the yesterday
:returns: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList
:rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList
"""
if self._yesterday is None:
self._yesterday = YesterdayList(self._version, account_sid=self._solution['account_sid'], )
return self._yesterday | python | def yesterday(self):
if self._yesterday is None:
self._yesterday = YesterdayList(self._version, account_sid=self._solution['account_sid'], )
return self._yesterday | [
"def",
"yesterday",
"(",
"self",
")",
":",
"if",
"self",
".",
"_yesterday",
"is",
"None",
":",
"self",
".",
"_yesterday",
"=",
"YesterdayList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",... | Access the yesterday
:returns: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList
:rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList | [
"Access",
"the",
"yesterday"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/record/__init__.py#L259-L268 |
225,295 | twilio/twilio-python | twilio/rest/api/v2010/account/usage/record/__init__.py | RecordPage.get_instance | def get_instance(self, payload):
"""
Build an instance of RecordInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.RecordInstance
:rtype: twilio.rest.api.v2010.account.usage.record.RecordInstance
"""
return RecordInstance(self._version, payload, account_sid=self._solution['account_sid'], ) | python | def get_instance(self, payload):
return RecordInstance(self._version, payload, account_sid=self._solution['account_sid'], ) | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"RecordInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")"
] | Build an instance of RecordInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.RecordInstance
:rtype: twilio.rest.api.v2010.account.usage.record.RecordInstance | [
"Build",
"an",
"instance",
"of",
"RecordInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/record/__init__.py#L299-L308 |
225,296 | twilio/twilio-python | twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py | BulkCountryUpdateList.create | def create(self, update_request):
"""
Create a new BulkCountryUpdateInstance
:param unicode update_request: URL encoded JSON array of update objects
:returns: Newly created BulkCountryUpdateInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateInstance
"""
data = values.of({'UpdateRequest': update_request, })
payload = self._version.create(
'POST',
self._uri,
data=data,
)
return BulkCountryUpdateInstance(self._version, payload, ) | python | def create(self, update_request):
data = values.of({'UpdateRequest': update_request, })
payload = self._version.create(
'POST',
self._uri,
data=data,
)
return BulkCountryUpdateInstance(self._version, payload, ) | [
"def",
"create",
"(",
"self",
",",
"update_request",
")",
":",
"data",
"=",
"values",
".",
"of",
"(",
"{",
"'UpdateRequest'",
":",
"update_request",
",",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"create",
"(",
"'POST'",
",",
"self",
".",... | Create a new BulkCountryUpdateInstance
:param unicode update_request: URL encoded JSON array of update objects
:returns: Newly created BulkCountryUpdateInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateInstance | [
"Create",
"a",
"new",
"BulkCountryUpdateInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py#L36-L53 |
225,297 | twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py | WorkersCumulativeStatisticsPage.get_instance | def get_instance(self, payload):
"""
Build an instance of WorkersCumulativeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance
"""
return WorkersCumulativeStatisticsInstance(
self._version,
payload,
workspace_sid=self._solution['workspace_sid'],
) | python | def get_instance(self, payload):
return WorkersCumulativeStatisticsInstance(
self._version,
payload,
workspace_sid=self._solution['workspace_sid'],
) | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"WorkersCumulativeStatisticsInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_sid'",
"]",
",",
")"
] | Build an instance of WorkersCumulativeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance | [
"Build",
"an",
"instance",
"of",
"WorkersCumulativeStatisticsInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py#L89-L102 |
225,298 | twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py | WorkersCumulativeStatisticsContext.fetch | def fetch(self, end_date=values.unset, minutes=values.unset,
start_date=values.unset, task_channel=values.unset):
"""
Fetch a WorkersCumulativeStatisticsInstance
:param datetime end_date: Filter cumulative statistics by a end date.
:param unicode minutes: Filter cumulative statistics by up to 'x' minutes in the past.
:param datetime start_date: Filter cumulative statistics by a start date.
:param unicode task_channel: Filter cumulative statistics by TaskChannel.
:returns: Fetched WorkersCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance
"""
params = values.of({
'EndDate': serialize.iso8601_datetime(end_date),
'Minutes': minutes,
'StartDate': serialize.iso8601_datetime(start_date),
'TaskChannel': task_channel,
})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
return WorkersCumulativeStatisticsInstance(
self._version,
payload,
workspace_sid=self._solution['workspace_sid'],
) | python | def fetch(self, end_date=values.unset, minutes=values.unset,
start_date=values.unset, task_channel=values.unset):
params = values.of({
'EndDate': serialize.iso8601_datetime(end_date),
'Minutes': minutes,
'StartDate': serialize.iso8601_datetime(start_date),
'TaskChannel': task_channel,
})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
return WorkersCumulativeStatisticsInstance(
self._version,
payload,
workspace_sid=self._solution['workspace_sid'],
) | [
"def",
"fetch",
"(",
"self",
",",
"end_date",
"=",
"values",
".",
"unset",
",",
"minutes",
"=",
"values",
".",
"unset",
",",
"start_date",
"=",
"values",
".",
"unset",
",",
"task_channel",
"=",
"values",
".",
"unset",
")",
":",
"params",
"=",
"values",... | Fetch a WorkersCumulativeStatisticsInstance
:param datetime end_date: Filter cumulative statistics by a end date.
:param unicode minutes: Filter cumulative statistics by up to 'x' minutes in the past.
:param datetime start_date: Filter cumulative statistics by a start date.
:param unicode task_channel: Filter cumulative statistics by TaskChannel.
:returns: Fetched WorkersCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance | [
"Fetch",
"a",
"WorkersCumulativeStatisticsInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py#L133-L163 |
225,299 | twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py | WorkspaceRealTimeStatisticsPage.get_instance | def get_instance(self, payload):
"""
Build an instance of WorkspaceRealTimeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance
"""
return WorkspaceRealTimeStatisticsInstance(
self._version,
payload,
workspace_sid=self._solution['workspace_sid'],
) | python | def get_instance(self, payload):
return WorkspaceRealTimeStatisticsInstance(
self._version,
payload,
workspace_sid=self._solution['workspace_sid'],
) | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"WorkspaceRealTimeStatisticsInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_sid'",
"]",
",",
")"
] | Build an instance of WorkspaceRealTimeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance | [
"Build",
"an",
"instance",
"of",
"WorkspaceRealTimeStatisticsInstance"
] | c867895f55dcc29f522e6e8b8868d0d18483132f | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py#L88-L101 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.