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 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
13,900
|
persephone-tools/persephone
|
persephone/datasets/na.py
|
get_story_prefixes
|
def get_story_prefixes(label_type, label_dir=LABEL_DIR):
""" Gets the Na text prefixes. """
prefixes = [prefix for prefix in os.listdir(os.path.join(label_dir, "TEXT"))
if prefix.endswith(".%s" % label_type)]
prefixes = [os.path.splitext(os.path.join("TEXT", prefix))[0]
for prefix in prefixes]
return prefixes
|
python
|
def get_story_prefixes(label_type, label_dir=LABEL_DIR):
""" Gets the Na text prefixes. """
prefixes = [prefix for prefix in os.listdir(os.path.join(label_dir, "TEXT"))
if prefix.endswith(".%s" % label_type)]
prefixes = [os.path.splitext(os.path.join("TEXT", prefix))[0]
for prefix in prefixes]
return prefixes
|
[
"def",
"get_story_prefixes",
"(",
"label_type",
",",
"label_dir",
"=",
"LABEL_DIR",
")",
":",
"prefixes",
"=",
"[",
"prefix",
"for",
"prefix",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"label_dir",
",",
"\"TEXT\"",
")",
")",
"if",
"prefix",
".",
"endswith",
"(",
"\".%s\"",
"%",
"label_type",
")",
"]",
"prefixes",
"=",
"[",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"TEXT\"",
",",
"prefix",
")",
")",
"[",
"0",
"]",
"for",
"prefix",
"in",
"prefixes",
"]",
"return",
"prefixes"
] |
Gets the Na text prefixes.
|
[
"Gets",
"the",
"Na",
"text",
"prefixes",
"."
] |
f94c63e4d5fe719fb1deba449b177bb299d225fb
|
https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L404-L410
|
13,901
|
persephone-tools/persephone
|
persephone/datasets/na.py
|
get_stories
|
def get_stories(label_type):
""" Returns a list of the stories in the Na corpus. """
prefixes = get_story_prefixes(label_type)
texts = list(set([prefix.split(".")[0].split("/")[1] for prefix in prefixes]))
return texts
|
python
|
def get_stories(label_type):
""" Returns a list of the stories in the Na corpus. """
prefixes = get_story_prefixes(label_type)
texts = list(set([prefix.split(".")[0].split("/")[1] for prefix in prefixes]))
return texts
|
[
"def",
"get_stories",
"(",
"label_type",
")",
":",
"prefixes",
"=",
"get_story_prefixes",
"(",
"label_type",
")",
"texts",
"=",
"list",
"(",
"set",
"(",
"[",
"prefix",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
".",
"split",
"(",
"\"/\"",
")",
"[",
"1",
"]",
"for",
"prefix",
"in",
"prefixes",
"]",
")",
")",
"return",
"texts"
] |
Returns a list of the stories in the Na corpus.
|
[
"Returns",
"a",
"list",
"of",
"the",
"stories",
"in",
"the",
"Na",
"corpus",
"."
] |
f94c63e4d5fe719fb1deba449b177bb299d225fb
|
https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L456-L461
|
13,902
|
persephone-tools/persephone
|
persephone/datasets/na.py
|
Corpus.make_data_splits
|
def make_data_splits(self, max_samples, valid_story=None, test_story=None):
"""Split data into train, valid and test groups"""
# TODO Make this also work with wordlists.
if valid_story or test_story:
if not (valid_story and test_story):
raise PersephoneException(
"We need a valid story if we specify a test story "
"and vice versa. This shouldn't be required but for "
"now it is.")
train, valid, test = make_story_splits(valid_story, test_story,
max_samples,
self.label_type,
tgt_dir=str(self.tgt_dir))
else:
train, valid, test = make_data_splits(self.label_type,
train_rec_type=self.train_rec_type,
max_samples=max_samples,
tgt_dir=str(self.tgt_dir))
self.train_prefixes = train
self.valid_prefixes = valid
self.test_prefixes = test
|
python
|
def make_data_splits(self, max_samples, valid_story=None, test_story=None):
"""Split data into train, valid and test groups"""
# TODO Make this also work with wordlists.
if valid_story or test_story:
if not (valid_story and test_story):
raise PersephoneException(
"We need a valid story if we specify a test story "
"and vice versa. This shouldn't be required but for "
"now it is.")
train, valid, test = make_story_splits(valid_story, test_story,
max_samples,
self.label_type,
tgt_dir=str(self.tgt_dir))
else:
train, valid, test = make_data_splits(self.label_type,
train_rec_type=self.train_rec_type,
max_samples=max_samples,
tgt_dir=str(self.tgt_dir))
self.train_prefixes = train
self.valid_prefixes = valid
self.test_prefixes = test
|
[
"def",
"make_data_splits",
"(",
"self",
",",
"max_samples",
",",
"valid_story",
"=",
"None",
",",
"test_story",
"=",
"None",
")",
":",
"# TODO Make this also work with wordlists.",
"if",
"valid_story",
"or",
"test_story",
":",
"if",
"not",
"(",
"valid_story",
"and",
"test_story",
")",
":",
"raise",
"PersephoneException",
"(",
"\"We need a valid story if we specify a test story \"",
"\"and vice versa. This shouldn't be required but for \"",
"\"now it is.\"",
")",
"train",
",",
"valid",
",",
"test",
"=",
"make_story_splits",
"(",
"valid_story",
",",
"test_story",
",",
"max_samples",
",",
"self",
".",
"label_type",
",",
"tgt_dir",
"=",
"str",
"(",
"self",
".",
"tgt_dir",
")",
")",
"else",
":",
"train",
",",
"valid",
",",
"test",
"=",
"make_data_splits",
"(",
"self",
".",
"label_type",
",",
"train_rec_type",
"=",
"self",
".",
"train_rec_type",
",",
"max_samples",
"=",
"max_samples",
",",
"tgt_dir",
"=",
"str",
"(",
"self",
".",
"tgt_dir",
")",
")",
"self",
".",
"train_prefixes",
"=",
"train",
"self",
".",
"valid_prefixes",
"=",
"valid",
"self",
".",
"test_prefixes",
"=",
"test"
] |
Split data into train, valid and test groups
|
[
"Split",
"data",
"into",
"train",
"valid",
"and",
"test",
"groups"
] |
f94c63e4d5fe719fb1deba449b177bb299d225fb
|
https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L537-L558
|
13,903
|
persephone-tools/persephone
|
persephone/datasets/na.py
|
Corpus.output_story_prefixes
|
def output_story_prefixes(self):
""" Writes the set of prefixes to a file this is useful for pretty
printing in results.latex_output. """
if not self.test_story:
raise NotImplementedError(
"I want to write the prefixes to a file"
"called <test_story>_prefixes.txt, but there's no test_story.")
fn = os.path.join(TGT_DIR, "%s_prefixes.txt" % self.test_story)
with open(fn, "w") as f:
for utter_id in self.test_prefixes:
print(utter_id.split("/")[1], file=f)
|
python
|
def output_story_prefixes(self):
""" Writes the set of prefixes to a file this is useful for pretty
printing in results.latex_output. """
if not self.test_story:
raise NotImplementedError(
"I want to write the prefixes to a file"
"called <test_story>_prefixes.txt, but there's no test_story.")
fn = os.path.join(TGT_DIR, "%s_prefixes.txt" % self.test_story)
with open(fn, "w") as f:
for utter_id in self.test_prefixes:
print(utter_id.split("/")[1], file=f)
|
[
"def",
"output_story_prefixes",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"test_story",
":",
"raise",
"NotImplementedError",
"(",
"\"I want to write the prefixes to a file\"",
"\"called <test_story>_prefixes.txt, but there's no test_story.\"",
")",
"fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"TGT_DIR",
",",
"\"%s_prefixes.txt\"",
"%",
"self",
".",
"test_story",
")",
"with",
"open",
"(",
"fn",
",",
"\"w\"",
")",
"as",
"f",
":",
"for",
"utter_id",
"in",
"self",
".",
"test_prefixes",
":",
"print",
"(",
"utter_id",
".",
"split",
"(",
"\"/\"",
")",
"[",
"1",
"]",
",",
"file",
"=",
"f",
")"
] |
Writes the set of prefixes to a file this is useful for pretty
printing in results.latex_output.
|
[
"Writes",
"the",
"set",
"of",
"prefixes",
"to",
"a",
"file",
"this",
"is",
"useful",
"for",
"pretty",
"printing",
"in",
"results",
".",
"latex_output",
"."
] |
f94c63e4d5fe719fb1deba449b177bb299d225fb
|
https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L560-L572
|
13,904
|
KxSystems/pyq
|
setup.py
|
add_data_file
|
def add_data_file(data_files, target, source):
"""Add an entry to data_files"""
for t, f in data_files:
if t == target:
break
else:
data_files.append((target, []))
f = data_files[-1][1]
if source not in f:
f.append(source)
|
python
|
def add_data_file(data_files, target, source):
"""Add an entry to data_files"""
for t, f in data_files:
if t == target:
break
else:
data_files.append((target, []))
f = data_files[-1][1]
if source not in f:
f.append(source)
|
[
"def",
"add_data_file",
"(",
"data_files",
",",
"target",
",",
"source",
")",
":",
"for",
"t",
",",
"f",
"in",
"data_files",
":",
"if",
"t",
"==",
"target",
":",
"break",
"else",
":",
"data_files",
".",
"append",
"(",
"(",
"target",
",",
"[",
"]",
")",
")",
"f",
"=",
"data_files",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"if",
"source",
"not",
"in",
"f",
":",
"f",
".",
"append",
"(",
"source",
")"
] |
Add an entry to data_files
|
[
"Add",
"an",
"entry",
"to",
"data_files"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/setup.py#L145-L154
|
13,905
|
KxSystems/pyq
|
setup.py
|
get_q_home
|
def get_q_home(env):
"""Derive q home from the environment"""
q_home = env.get('QHOME')
if q_home:
return q_home
for v in ['VIRTUAL_ENV', 'HOME']:
prefix = env.get(v)
if prefix:
q_home = os.path.join(prefix, 'q')
if os.path.isdir(q_home):
return q_home
if WINDOWS:
q_home = os.path.join(env['SystemDrive'], r'\q')
if os.path.isdir(q_home):
return q_home
raise RuntimeError('No suitable QHOME.')
|
python
|
def get_q_home(env):
"""Derive q home from the environment"""
q_home = env.get('QHOME')
if q_home:
return q_home
for v in ['VIRTUAL_ENV', 'HOME']:
prefix = env.get(v)
if prefix:
q_home = os.path.join(prefix, 'q')
if os.path.isdir(q_home):
return q_home
if WINDOWS:
q_home = os.path.join(env['SystemDrive'], r'\q')
if os.path.isdir(q_home):
return q_home
raise RuntimeError('No suitable QHOME.')
|
[
"def",
"get_q_home",
"(",
"env",
")",
":",
"q_home",
"=",
"env",
".",
"get",
"(",
"'QHOME'",
")",
"if",
"q_home",
":",
"return",
"q_home",
"for",
"v",
"in",
"[",
"'VIRTUAL_ENV'",
",",
"'HOME'",
"]",
":",
"prefix",
"=",
"env",
".",
"get",
"(",
"v",
")",
"if",
"prefix",
":",
"q_home",
"=",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"'q'",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"q_home",
")",
":",
"return",
"q_home",
"if",
"WINDOWS",
":",
"q_home",
"=",
"os",
".",
"path",
".",
"join",
"(",
"env",
"[",
"'SystemDrive'",
"]",
",",
"r'\\q'",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"q_home",
")",
":",
"return",
"q_home",
"raise",
"RuntimeError",
"(",
"'No suitable QHOME.'",
")"
] |
Derive q home from the environment
|
[
"Derive",
"q",
"home",
"from",
"the",
"environment"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/setup.py#L185-L200
|
13,906
|
KxSystems/pyq
|
setup.py
|
get_q_version
|
def get_q_version(q_home):
"""Return version of q installed at q_home"""
with open(os.path.join(q_home, 'q.k')) as f:
for line in f:
if line.startswith('k:'):
return line[2:5]
return '2.2'
|
python
|
def get_q_version(q_home):
"""Return version of q installed at q_home"""
with open(os.path.join(q_home, 'q.k')) as f:
for line in f:
if line.startswith('k:'):
return line[2:5]
return '2.2'
|
[
"def",
"get_q_version",
"(",
"q_home",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"q_home",
",",
"'q.k'",
")",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"line",
".",
"startswith",
"(",
"'k:'",
")",
":",
"return",
"line",
"[",
"2",
":",
"5",
"]",
"return",
"'2.2'"
] |
Return version of q installed at q_home
|
[
"Return",
"version",
"of",
"q",
"installed",
"at",
"q_home"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/setup.py#L230-L236
|
13,907
|
KxSystems/pyq
|
src/pyq/cmd.py
|
Cmd.precmd
|
def precmd(self, line):
"""Support for help"""
if line.startswith('help'):
if not q("`help in key`.q"):
try:
q("\\l help.q")
except kerr:
return '-1"no help available - install help.q"'
if line == 'help':
line += "`"
return line
|
python
|
def precmd(self, line):
"""Support for help"""
if line.startswith('help'):
if not q("`help in key`.q"):
try:
q("\\l help.q")
except kerr:
return '-1"no help available - install help.q"'
if line == 'help':
line += "`"
return line
|
[
"def",
"precmd",
"(",
"self",
",",
"line",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'help'",
")",
":",
"if",
"not",
"q",
"(",
"\"`help in key`.q\"",
")",
":",
"try",
":",
"q",
"(",
"\"\\\\l help.q\"",
")",
"except",
"kerr",
":",
"return",
"'-1\"no help available - install help.q\"'",
"if",
"line",
"==",
"'help'",
":",
"line",
"+=",
"\"`\"",
"return",
"line"
] |
Support for help
|
[
"Support",
"for",
"help"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/cmd.py#L35-L45
|
13,908
|
KxSystems/pyq
|
src/pyq/cmd.py
|
Cmd.onecmd
|
def onecmd(self, line):
"""Interpret the line"""
if line == '\\':
return True
elif line == 'EOF':
print('\r', end='')
return True
else:
try:
v = q(line)
except kerr as e:
print("'%s" % e.args[0])
else:
if v != q('::'):
v.show()
return False
|
python
|
def onecmd(self, line):
"""Interpret the line"""
if line == '\\':
return True
elif line == 'EOF':
print('\r', end='')
return True
else:
try:
v = q(line)
except kerr as e:
print("'%s" % e.args[0])
else:
if v != q('::'):
v.show()
return False
|
[
"def",
"onecmd",
"(",
"self",
",",
"line",
")",
":",
"if",
"line",
"==",
"'\\\\'",
":",
"return",
"True",
"elif",
"line",
"==",
"'EOF'",
":",
"print",
"(",
"'\\r'",
",",
"end",
"=",
"''",
")",
"return",
"True",
"else",
":",
"try",
":",
"v",
"=",
"q",
"(",
"line",
")",
"except",
"kerr",
"as",
"e",
":",
"print",
"(",
"\"'%s\"",
"%",
"e",
".",
"args",
"[",
"0",
"]",
")",
"else",
":",
"if",
"v",
"!=",
"q",
"(",
"'::'",
")",
":",
"v",
".",
"show",
"(",
")",
"return",
"False"
] |
Interpret the line
|
[
"Interpret",
"the",
"line"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/cmd.py#L47-L62
|
13,909
|
KxSystems/pyq
|
src/pyq/_pt_run.py
|
run
|
def run(q_prompt=False):
"""Run a prompt-toolkit based REPL"""
lines, columns = console_size()
q(r'\c %d %d' % (lines, columns))
if len(sys.argv) > 1:
try:
q(r'\l %s' % sys.argv[1])
except kerr as e:
print(e)
raise SystemExit(1)
else:
del sys.argv[1]
if q_prompt:
q()
ptp.run()
|
python
|
def run(q_prompt=False):
"""Run a prompt-toolkit based REPL"""
lines, columns = console_size()
q(r'\c %d %d' % (lines, columns))
if len(sys.argv) > 1:
try:
q(r'\l %s' % sys.argv[1])
except kerr as e:
print(e)
raise SystemExit(1)
else:
del sys.argv[1]
if q_prompt:
q()
ptp.run()
|
[
"def",
"run",
"(",
"q_prompt",
"=",
"False",
")",
":",
"lines",
",",
"columns",
"=",
"console_size",
"(",
")",
"q",
"(",
"r'\\c %d %d'",
"%",
"(",
"lines",
",",
"columns",
")",
")",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"1",
":",
"try",
":",
"q",
"(",
"r'\\l %s'",
"%",
"sys",
".",
"argv",
"[",
"1",
"]",
")",
"except",
"kerr",
"as",
"e",
":",
"print",
"(",
"e",
")",
"raise",
"SystemExit",
"(",
"1",
")",
"else",
":",
"del",
"sys",
".",
"argv",
"[",
"1",
"]",
"if",
"q_prompt",
":",
"q",
"(",
")",
"ptp",
".",
"run",
"(",
")"
] |
Run a prompt-toolkit based REPL
|
[
"Run",
"a",
"prompt",
"-",
"toolkit",
"based",
"REPL"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/_pt_run.py#L32-L46
|
13,910
|
KxSystems/pyq
|
src/pyq/_n.py
|
get_unit
|
def get_unit(a):
"""Extract the time unit from array's dtype"""
typestr = a.dtype.str
i = typestr.find('[')
if i == -1:
raise TypeError("Expected a datetime64 array, not %s", a.dtype)
return typestr[i + 1: -1]
|
python
|
def get_unit(a):
"""Extract the time unit from array's dtype"""
typestr = a.dtype.str
i = typestr.find('[')
if i == -1:
raise TypeError("Expected a datetime64 array, not %s", a.dtype)
return typestr[i + 1: -1]
|
[
"def",
"get_unit",
"(",
"a",
")",
":",
"typestr",
"=",
"a",
".",
"dtype",
".",
"str",
"i",
"=",
"typestr",
".",
"find",
"(",
"'['",
")",
"if",
"i",
"==",
"-",
"1",
":",
"raise",
"TypeError",
"(",
"\"Expected a datetime64 array, not %s\"",
",",
"a",
".",
"dtype",
")",
"return",
"typestr",
"[",
"i",
"+",
"1",
":",
"-",
"1",
"]"
] |
Extract the time unit from array's dtype
|
[
"Extract",
"the",
"time",
"unit",
"from",
"array",
"s",
"dtype"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/_n.py#L50-L56
|
13,911
|
KxSystems/pyq
|
src/pyq/_n.py
|
k2a
|
def k2a(a, x):
"""Rescale data from a K object x to array a.
"""
func, scale = None, 1
t = abs(x._t)
# timestamp (12), month (13), date (14) or datetime (15)
if 12 <= t <= 15:
unit = get_unit(a)
attr, shift, func, scale = _UNIT[unit]
a[:] = getattr(x, attr).data
a += shift
# timespan (16), minute (17), second (18) or time (19)
elif 16 <= t <= 19:
unit = get_unit(a)
func, scale = _SCALE[unit]
a[:] = x.timespan.data
else:
a[:] = list(x)
if func is not None:
func = getattr(numpy, func)
a[:] = func(a.view(dtype='i8'), scale)
if a.dtype.char in 'mM':
n = x.null
if n.any:
a[n] = None
|
python
|
def k2a(a, x):
"""Rescale data from a K object x to array a.
"""
func, scale = None, 1
t = abs(x._t)
# timestamp (12), month (13), date (14) or datetime (15)
if 12 <= t <= 15:
unit = get_unit(a)
attr, shift, func, scale = _UNIT[unit]
a[:] = getattr(x, attr).data
a += shift
# timespan (16), minute (17), second (18) or time (19)
elif 16 <= t <= 19:
unit = get_unit(a)
func, scale = _SCALE[unit]
a[:] = x.timespan.data
else:
a[:] = list(x)
if func is not None:
func = getattr(numpy, func)
a[:] = func(a.view(dtype='i8'), scale)
if a.dtype.char in 'mM':
n = x.null
if n.any:
a[n] = None
|
[
"def",
"k2a",
"(",
"a",
",",
"x",
")",
":",
"func",
",",
"scale",
"=",
"None",
",",
"1",
"t",
"=",
"abs",
"(",
"x",
".",
"_t",
")",
"# timestamp (12), month (13), date (14) or datetime (15)",
"if",
"12",
"<=",
"t",
"<=",
"15",
":",
"unit",
"=",
"get_unit",
"(",
"a",
")",
"attr",
",",
"shift",
",",
"func",
",",
"scale",
"=",
"_UNIT",
"[",
"unit",
"]",
"a",
"[",
":",
"]",
"=",
"getattr",
"(",
"x",
",",
"attr",
")",
".",
"data",
"a",
"+=",
"shift",
"# timespan (16), minute (17), second (18) or time (19)",
"elif",
"16",
"<=",
"t",
"<=",
"19",
":",
"unit",
"=",
"get_unit",
"(",
"a",
")",
"func",
",",
"scale",
"=",
"_SCALE",
"[",
"unit",
"]",
"a",
"[",
":",
"]",
"=",
"x",
".",
"timespan",
".",
"data",
"else",
":",
"a",
"[",
":",
"]",
"=",
"list",
"(",
"x",
")",
"if",
"func",
"is",
"not",
"None",
":",
"func",
"=",
"getattr",
"(",
"numpy",
",",
"func",
")",
"a",
"[",
":",
"]",
"=",
"func",
"(",
"a",
".",
"view",
"(",
"dtype",
"=",
"'i8'",
")",
",",
"scale",
")",
"if",
"a",
".",
"dtype",
".",
"char",
"in",
"'mM'",
":",
"n",
"=",
"x",
".",
"null",
"if",
"n",
".",
"any",
":",
"a",
"[",
"n",
"]",
"=",
"None"
] |
Rescale data from a K object x to array a.
|
[
"Rescale",
"data",
"from",
"a",
"K",
"object",
"x",
"to",
"array",
"a",
"."
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/_n.py#L118-L145
|
13,912
|
KxSystems/pyq
|
src/pyq/__init__.py
|
K.show
|
def show(self, start=0, geometry=None, output=None):
"""pretty-print data to the console
(similar to q.show, but uses python stdout by default)
>>> x = q('([k:`x`y`z]a:1 2 3;b:10 20 30)')
>>> x.show() # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
x| 1 10
y| 2 20
z| 3 30
the first optional argument, 'start' specifies the first row to be
printed (negative means from the end)
>>> x.show(2) # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
z| 3 30
>>> x.show(-2) # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
y| 2 20
z| 3 30
the geometry is the height and width of the console
>>> x.show(geometry=[4, 6])
k| a..
-| -..
x| 1..
..
"""
if output is None:
output = sys.stdout
if geometry is None:
geometry = q.value(kp("\\c"))
else:
geometry = self._I(geometry)
if start < 0:
start += q.count(self)
# Make sure nil is not passed to a q function
if self._id() != nil._id():
r = self._show(geometry, start)
else:
r = '::\n'
if isinstance(output, type):
return output(r)
try:
output.write(r)
except TypeError:
output.write(str(r))
|
python
|
def show(self, start=0, geometry=None, output=None):
"""pretty-print data to the console
(similar to q.show, but uses python stdout by default)
>>> x = q('([k:`x`y`z]a:1 2 3;b:10 20 30)')
>>> x.show() # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
x| 1 10
y| 2 20
z| 3 30
the first optional argument, 'start' specifies the first row to be
printed (negative means from the end)
>>> x.show(2) # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
z| 3 30
>>> x.show(-2) # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
y| 2 20
z| 3 30
the geometry is the height and width of the console
>>> x.show(geometry=[4, 6])
k| a..
-| -..
x| 1..
..
"""
if output is None:
output = sys.stdout
if geometry is None:
geometry = q.value(kp("\\c"))
else:
geometry = self._I(geometry)
if start < 0:
start += q.count(self)
# Make sure nil is not passed to a q function
if self._id() != nil._id():
r = self._show(geometry, start)
else:
r = '::\n'
if isinstance(output, type):
return output(r)
try:
output.write(r)
except TypeError:
output.write(str(r))
|
[
"def",
"show",
"(",
"self",
",",
"start",
"=",
"0",
",",
"geometry",
"=",
"None",
",",
"output",
"=",
"None",
")",
":",
"if",
"output",
"is",
"None",
":",
"output",
"=",
"sys",
".",
"stdout",
"if",
"geometry",
"is",
"None",
":",
"geometry",
"=",
"q",
".",
"value",
"(",
"kp",
"(",
"\"\\\\c\"",
")",
")",
"else",
":",
"geometry",
"=",
"self",
".",
"_I",
"(",
"geometry",
")",
"if",
"start",
"<",
"0",
":",
"start",
"+=",
"q",
".",
"count",
"(",
"self",
")",
"# Make sure nil is not passed to a q function",
"if",
"self",
".",
"_id",
"(",
")",
"!=",
"nil",
".",
"_id",
"(",
")",
":",
"r",
"=",
"self",
".",
"_show",
"(",
"geometry",
",",
"start",
")",
"else",
":",
"r",
"=",
"'::\\n'",
"if",
"isinstance",
"(",
"output",
",",
"type",
")",
":",
"return",
"output",
"(",
"r",
")",
"try",
":",
"output",
".",
"write",
"(",
"r",
")",
"except",
"TypeError",
":",
"output",
".",
"write",
"(",
"str",
"(",
"r",
")",
")"
] |
pretty-print data to the console
(similar to q.show, but uses python stdout by default)
>>> x = q('([k:`x`y`z]a:1 2 3;b:10 20 30)')
>>> x.show() # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
x| 1 10
y| 2 20
z| 3 30
the first optional argument, 'start' specifies the first row to be
printed (negative means from the end)
>>> x.show(2) # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
z| 3 30
>>> x.show(-2) # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
y| 2 20
z| 3 30
the geometry is the height and width of the console
>>> x.show(geometry=[4, 6])
k| a..
-| -..
x| 1..
..
|
[
"pretty",
"-",
"print",
"data",
"to",
"the",
"console"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/__init__.py#L377-L435
|
13,913
|
KxSystems/pyq
|
src/pyq/__init__.py
|
K.select
|
def select(self, columns=(), by=(), where=(), **kwds):
"""select from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.select('a', where='b > 20').show()
a
-
3
"""
return self._seu('select', columns, by, where, kwds)
|
python
|
def select(self, columns=(), by=(), where=(), **kwds):
"""select from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.select('a', where='b > 20').show()
a
-
3
"""
return self._seu('select', columns, by, where, kwds)
|
[
"def",
"select",
"(",
"self",
",",
"columns",
"=",
"(",
")",
",",
"by",
"=",
"(",
")",
",",
"where",
"=",
"(",
")",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
".",
"_seu",
"(",
"'select'",
",",
"columns",
",",
"by",
",",
"where",
",",
"kwds",
")"
] |
select from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.select('a', where='b > 20').show()
a
-
3
|
[
"select",
"from",
"self"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/__init__.py#L465-L474
|
13,914
|
KxSystems/pyq
|
src/pyq/__init__.py
|
K.exec_
|
def exec_(self, columns=(), by=(), where=(), **kwds):
"""exec from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.exec_('a', where='b > 10').show()
2 3
"""
return self._seu('exec', columns, by, where, kwds)
|
python
|
def exec_(self, columns=(), by=(), where=(), **kwds):
"""exec from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.exec_('a', where='b > 10').show()
2 3
"""
return self._seu('exec', columns, by, where, kwds)
|
[
"def",
"exec_",
"(",
"self",
",",
"columns",
"=",
"(",
")",
",",
"by",
"=",
"(",
")",
",",
"where",
"=",
"(",
")",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
".",
"_seu",
"(",
"'exec'",
",",
"columns",
",",
"by",
",",
"where",
",",
"kwds",
")"
] |
exec from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.exec_('a', where='b > 10').show()
2 3
|
[
"exec",
"from",
"self"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/__init__.py#L476-L483
|
13,915
|
KxSystems/pyq
|
src/pyq/__init__.py
|
K.update
|
def update(self, columns=(), by=(), where=(), **kwds):
"""update from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.update('a*2',
... where='b > 20').show() # doctest: +NORMALIZE_WHITESPACE
a b
----
1 10
2 20
6 30
"""
return self._seu('update', columns, by, where, kwds)
|
python
|
def update(self, columns=(), by=(), where=(), **kwds):
"""update from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.update('a*2',
... where='b > 20').show() # doctest: +NORMALIZE_WHITESPACE
a b
----
1 10
2 20
6 30
"""
return self._seu('update', columns, by, where, kwds)
|
[
"def",
"update",
"(",
"self",
",",
"columns",
"=",
"(",
")",
",",
"by",
"=",
"(",
")",
",",
"where",
"=",
"(",
")",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
".",
"_seu",
"(",
"'update'",
",",
"columns",
",",
"by",
",",
"where",
",",
"kwds",
")"
] |
update from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.update('a*2',
... where='b > 20').show() # doctest: +NORMALIZE_WHITESPACE
a b
----
1 10
2 20
6 30
|
[
"update",
"from",
"self"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/__init__.py#L485-L497
|
13,916
|
KxSystems/pyq
|
src/pyq/__init__.py
|
K.dict
|
def dict(cls, *args, **kwds):
"""Construct a q dictionary
K.dict() -> new empty q dictionary (q('()!()')
K.dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
K.dict(iterable) -> new dictionary initialized from an iterable
yielding (key, value) pairs
K.dict(**kwargs) -> new dictionary initialized with the name=value
pairs in the keyword argument list.
For example: K.dict(one=1, two=2)
"""
if args:
if len(args) > 1:
raise TypeError("Too many positional arguments")
x = args[0]
keys = []
vals = []
try:
x_keys = x.keys
except AttributeError:
for k, v in x:
keys.append(k)
vals.append(v)
else:
keys = x_keys()
vals = [x[k] for k in keys]
return q('!', keys, vals)
else:
if kwds:
keys = []
vals = []
for k, v in kwds.items():
keys.append(k)
vals.append(v)
return q('!', keys, vals)
else:
return q('()!()')
|
python
|
def dict(cls, *args, **kwds):
"""Construct a q dictionary
K.dict() -> new empty q dictionary (q('()!()')
K.dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
K.dict(iterable) -> new dictionary initialized from an iterable
yielding (key, value) pairs
K.dict(**kwargs) -> new dictionary initialized with the name=value
pairs in the keyword argument list.
For example: K.dict(one=1, two=2)
"""
if args:
if len(args) > 1:
raise TypeError("Too many positional arguments")
x = args[0]
keys = []
vals = []
try:
x_keys = x.keys
except AttributeError:
for k, v in x:
keys.append(k)
vals.append(v)
else:
keys = x_keys()
vals = [x[k] for k in keys]
return q('!', keys, vals)
else:
if kwds:
keys = []
vals = []
for k, v in kwds.items():
keys.append(k)
vals.append(v)
return q('!', keys, vals)
else:
return q('()!()')
|
[
"def",
"dict",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"args",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"\"Too many positional arguments\"",
")",
"x",
"=",
"args",
"[",
"0",
"]",
"keys",
"=",
"[",
"]",
"vals",
"=",
"[",
"]",
"try",
":",
"x_keys",
"=",
"x",
".",
"keys",
"except",
"AttributeError",
":",
"for",
"k",
",",
"v",
"in",
"x",
":",
"keys",
".",
"append",
"(",
"k",
")",
"vals",
".",
"append",
"(",
"v",
")",
"else",
":",
"keys",
"=",
"x_keys",
"(",
")",
"vals",
"=",
"[",
"x",
"[",
"k",
"]",
"for",
"k",
"in",
"keys",
"]",
"return",
"q",
"(",
"'!'",
",",
"keys",
",",
"vals",
")",
"else",
":",
"if",
"kwds",
":",
"keys",
"=",
"[",
"]",
"vals",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"kwds",
".",
"items",
"(",
")",
":",
"keys",
".",
"append",
"(",
"k",
")",
"vals",
".",
"append",
"(",
"v",
")",
"return",
"q",
"(",
"'!'",
",",
"keys",
",",
"vals",
")",
"else",
":",
"return",
"q",
"(",
"'()!()'",
")"
] |
Construct a q dictionary
K.dict() -> new empty q dictionary (q('()!()')
K.dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
K.dict(iterable) -> new dictionary initialized from an iterable
yielding (key, value) pairs
K.dict(**kwargs) -> new dictionary initialized with the name=value
pairs in the keyword argument list.
For example: K.dict(one=1, two=2)
|
[
"Construct",
"a",
"q",
"dictionary"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/__init__.py#L558-L595
|
13,917
|
KxSystems/pyq
|
src/pyq/magic.py
|
logical_lines
|
def logical_lines(lines):
"""Merge lines into chunks according to q rules"""
if isinstance(lines, string_types):
lines = StringIO(lines)
buf = []
for line in lines:
if buf and not line.startswith(' '):
chunk = ''.join(buf).strip()
if chunk:
yield chunk
buf[:] = []
buf.append(line)
chunk = ''.join(buf).strip()
if chunk:
yield chunk
|
python
|
def logical_lines(lines):
"""Merge lines into chunks according to q rules"""
if isinstance(lines, string_types):
lines = StringIO(lines)
buf = []
for line in lines:
if buf and not line.startswith(' '):
chunk = ''.join(buf).strip()
if chunk:
yield chunk
buf[:] = []
buf.append(line)
chunk = ''.join(buf).strip()
if chunk:
yield chunk
|
[
"def",
"logical_lines",
"(",
"lines",
")",
":",
"if",
"isinstance",
"(",
"lines",
",",
"string_types",
")",
":",
"lines",
"=",
"StringIO",
"(",
"lines",
")",
"buf",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"buf",
"and",
"not",
"line",
".",
"startswith",
"(",
"' '",
")",
":",
"chunk",
"=",
"''",
".",
"join",
"(",
"buf",
")",
".",
"strip",
"(",
")",
"if",
"chunk",
":",
"yield",
"chunk",
"buf",
"[",
":",
"]",
"=",
"[",
"]",
"buf",
".",
"append",
"(",
"line",
")",
"chunk",
"=",
"''",
".",
"join",
"(",
"buf",
")",
".",
"strip",
"(",
")",
"if",
"chunk",
":",
"yield",
"chunk"
] |
Merge lines into chunks according to q rules
|
[
"Merge",
"lines",
"into",
"chunks",
"according",
"to",
"q",
"rules"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/magic.py#L23-L38
|
13,918
|
KxSystems/pyq
|
src/pyq/magic.py
|
q
|
def q(line, cell=None, _ns=None):
"""Run q code.
Options:
-l (dir|script) - pre-load database or script
-h host:port - execute on the given host
-o var - send output to a variable named var.
-i var1,..,varN - input variables
-1/-2 - redirect stdout/stderr
"""
if cell is None:
return pyq.q(line)
if _ns is None:
_ns = vars(sys.modules['__main__'])
input = output = None
preload = []
outs = {}
try:
h = pyq.q('0i')
if line:
for opt, value in getopt(line.split(), "h:l:o:i:12")[0]:
if opt == '-l':
preload.append(value)
elif opt == '-h':
h = pyq.K(str(':' + value))
elif opt == '-o':
output = str(value) # (see #673)
elif opt == '-i':
input = str(value).split(',')
elif opt in ('-1', '-2'):
outs[int(opt[1])] = None
if outs:
if int(h) != 0:
raise ValueError("Cannot redirect remote std stream")
for fd in outs:
tmpfd, tmpfile = mkstemp()
try:
pyq.q(r'\%d %s' % (fd, tmpfile))
finally:
os.unlink(tmpfile)
os.close(tmpfd)
r = None
for script in preload:
h(pyq.kp(r"\l " + script))
if input is not None:
for chunk in logical_lines(cell):
func = "{[%s]%s}" % (';'.join(input), chunk)
args = tuple(_ns[i] for i in input)
if r != Q_NONE:
r.show()
r = h((pyq.kp(func),) + args)
if outs:
_forward_outputs(outs)
else:
for chunk in logical_lines(cell):
if r != Q_NONE:
r.show()
r = h(pyq.kp(chunk))
if outs:
_forward_outputs(outs)
except pyq.kerr as e:
print("'%s" % e)
else:
if output is not None:
if output.startswith('q.'):
pyq.q('@[`.;;:;]', output[2:], r)
else:
_ns[output] = r
else:
if r != Q_NONE:
return r
|
python
|
def q(line, cell=None, _ns=None):
"""Run q code.
Options:
-l (dir|script) - pre-load database or script
-h host:port - execute on the given host
-o var - send output to a variable named var.
-i var1,..,varN - input variables
-1/-2 - redirect stdout/stderr
"""
if cell is None:
return pyq.q(line)
if _ns is None:
_ns = vars(sys.modules['__main__'])
input = output = None
preload = []
outs = {}
try:
h = pyq.q('0i')
if line:
for opt, value in getopt(line.split(), "h:l:o:i:12")[0]:
if opt == '-l':
preload.append(value)
elif opt == '-h':
h = pyq.K(str(':' + value))
elif opt == '-o':
output = str(value) # (see #673)
elif opt == '-i':
input = str(value).split(',')
elif opt in ('-1', '-2'):
outs[int(opt[1])] = None
if outs:
if int(h) != 0:
raise ValueError("Cannot redirect remote std stream")
for fd in outs:
tmpfd, tmpfile = mkstemp()
try:
pyq.q(r'\%d %s' % (fd, tmpfile))
finally:
os.unlink(tmpfile)
os.close(tmpfd)
r = None
for script in preload:
h(pyq.kp(r"\l " + script))
if input is not None:
for chunk in logical_lines(cell):
func = "{[%s]%s}" % (';'.join(input), chunk)
args = tuple(_ns[i] for i in input)
if r != Q_NONE:
r.show()
r = h((pyq.kp(func),) + args)
if outs:
_forward_outputs(outs)
else:
for chunk in logical_lines(cell):
if r != Q_NONE:
r.show()
r = h(pyq.kp(chunk))
if outs:
_forward_outputs(outs)
except pyq.kerr as e:
print("'%s" % e)
else:
if output is not None:
if output.startswith('q.'):
pyq.q('@[`.;;:;]', output[2:], r)
else:
_ns[output] = r
else:
if r != Q_NONE:
return r
|
[
"def",
"q",
"(",
"line",
",",
"cell",
"=",
"None",
",",
"_ns",
"=",
"None",
")",
":",
"if",
"cell",
"is",
"None",
":",
"return",
"pyq",
".",
"q",
"(",
"line",
")",
"if",
"_ns",
"is",
"None",
":",
"_ns",
"=",
"vars",
"(",
"sys",
".",
"modules",
"[",
"'__main__'",
"]",
")",
"input",
"=",
"output",
"=",
"None",
"preload",
"=",
"[",
"]",
"outs",
"=",
"{",
"}",
"try",
":",
"h",
"=",
"pyq",
".",
"q",
"(",
"'0i'",
")",
"if",
"line",
":",
"for",
"opt",
",",
"value",
"in",
"getopt",
"(",
"line",
".",
"split",
"(",
")",
",",
"\"h:l:o:i:12\"",
")",
"[",
"0",
"]",
":",
"if",
"opt",
"==",
"'-l'",
":",
"preload",
".",
"append",
"(",
"value",
")",
"elif",
"opt",
"==",
"'-h'",
":",
"h",
"=",
"pyq",
".",
"K",
"(",
"str",
"(",
"':'",
"+",
"value",
")",
")",
"elif",
"opt",
"==",
"'-o'",
":",
"output",
"=",
"str",
"(",
"value",
")",
"# (see #673)",
"elif",
"opt",
"==",
"'-i'",
":",
"input",
"=",
"str",
"(",
"value",
")",
".",
"split",
"(",
"','",
")",
"elif",
"opt",
"in",
"(",
"'-1'",
",",
"'-2'",
")",
":",
"outs",
"[",
"int",
"(",
"opt",
"[",
"1",
"]",
")",
"]",
"=",
"None",
"if",
"outs",
":",
"if",
"int",
"(",
"h",
")",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Cannot redirect remote std stream\"",
")",
"for",
"fd",
"in",
"outs",
":",
"tmpfd",
",",
"tmpfile",
"=",
"mkstemp",
"(",
")",
"try",
":",
"pyq",
".",
"q",
"(",
"r'\\%d %s'",
"%",
"(",
"fd",
",",
"tmpfile",
")",
")",
"finally",
":",
"os",
".",
"unlink",
"(",
"tmpfile",
")",
"os",
".",
"close",
"(",
"tmpfd",
")",
"r",
"=",
"None",
"for",
"script",
"in",
"preload",
":",
"h",
"(",
"pyq",
".",
"kp",
"(",
"r\"\\l \"",
"+",
"script",
")",
")",
"if",
"input",
"is",
"not",
"None",
":",
"for",
"chunk",
"in",
"logical_lines",
"(",
"cell",
")",
":",
"func",
"=",
"\"{[%s]%s}\"",
"%",
"(",
"';'",
".",
"join",
"(",
"input",
")",
",",
"chunk",
")",
"args",
"=",
"tuple",
"(",
"_ns",
"[",
"i",
"]",
"for",
"i",
"in",
"input",
")",
"if",
"r",
"!=",
"Q_NONE",
":",
"r",
".",
"show",
"(",
")",
"r",
"=",
"h",
"(",
"(",
"pyq",
".",
"kp",
"(",
"func",
")",
",",
")",
"+",
"args",
")",
"if",
"outs",
":",
"_forward_outputs",
"(",
"outs",
")",
"else",
":",
"for",
"chunk",
"in",
"logical_lines",
"(",
"cell",
")",
":",
"if",
"r",
"!=",
"Q_NONE",
":",
"r",
".",
"show",
"(",
")",
"r",
"=",
"h",
"(",
"pyq",
".",
"kp",
"(",
"chunk",
")",
")",
"if",
"outs",
":",
"_forward_outputs",
"(",
"outs",
")",
"except",
"pyq",
".",
"kerr",
"as",
"e",
":",
"print",
"(",
"\"'%s\"",
"%",
"e",
")",
"else",
":",
"if",
"output",
"is",
"not",
"None",
":",
"if",
"output",
".",
"startswith",
"(",
"'q.'",
")",
":",
"pyq",
".",
"q",
"(",
"'@[`.;;:;]'",
",",
"output",
"[",
"2",
":",
"]",
",",
"r",
")",
"else",
":",
"_ns",
"[",
"output",
"]",
"=",
"r",
"else",
":",
"if",
"r",
"!=",
"Q_NONE",
":",
"return",
"r"
] |
Run q code.
Options:
-l (dir|script) - pre-load database or script
-h host:port - execute on the given host
-o var - send output to a variable named var.
-i var1,..,varN - input variables
-1/-2 - redirect stdout/stderr
|
[
"Run",
"q",
"code",
"."
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/magic.py#L50-L121
|
13,919
|
KxSystems/pyq
|
src/pyq/magic.py
|
load_ipython_extension
|
def load_ipython_extension(ipython):
"""Register %q and %%q magics and pretty display for K objects"""
ipython.register_magic_function(q, 'line_cell')
fmr = ipython.display_formatter.formatters['text/plain']
fmr.for_type(pyq.K, _q_formatter)
|
python
|
def load_ipython_extension(ipython):
"""Register %q and %%q magics and pretty display for K objects"""
ipython.register_magic_function(q, 'line_cell')
fmr = ipython.display_formatter.formatters['text/plain']
fmr.for_type(pyq.K, _q_formatter)
|
[
"def",
"load_ipython_extension",
"(",
"ipython",
")",
":",
"ipython",
".",
"register_magic_function",
"(",
"q",
",",
"'line_cell'",
")",
"fmr",
"=",
"ipython",
".",
"display_formatter",
".",
"formatters",
"[",
"'text/plain'",
"]",
"fmr",
".",
"for_type",
"(",
"pyq",
".",
"K",
",",
"_q_formatter",
")"
] |
Register %q and %%q magics and pretty display for K objects
|
[
"Register",
"%q",
"and",
"%%q",
"magics",
"and",
"pretty",
"display",
"for",
"K",
"objects"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/magic.py#L129-L133
|
13,920
|
KxSystems/pyq
|
src/pyq/ptk.py
|
get_prompt_tokens
|
def get_prompt_tokens(_):
"""Return a list of tokens for the prompt"""
namespace = q(r'\d')
if namespace == '.':
namespace = ''
return [(Token.Generic.Prompt, 'q%s)' % namespace)]
|
python
|
def get_prompt_tokens(_):
"""Return a list of tokens for the prompt"""
namespace = q(r'\d')
if namespace == '.':
namespace = ''
return [(Token.Generic.Prompt, 'q%s)' % namespace)]
|
[
"def",
"get_prompt_tokens",
"(",
"_",
")",
":",
"namespace",
"=",
"q",
"(",
"r'\\d'",
")",
"if",
"namespace",
"==",
"'.'",
":",
"namespace",
"=",
"''",
"return",
"[",
"(",
"Token",
".",
"Generic",
".",
"Prompt",
",",
"'q%s)'",
"%",
"namespace",
")",
"]"
] |
Return a list of tokens for the prompt
|
[
"Return",
"a",
"list",
"of",
"tokens",
"for",
"the",
"prompt"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/ptk.py#L48-L53
|
13,921
|
KxSystems/pyq
|
src/pyq/ptk.py
|
cmdloop
|
def cmdloop(self, intro=None):
"""A Cmd.cmdloop implementation"""
style = style_from_pygments(BasicStyle, style_dict)
self.preloop()
stop = None
while not stop:
line = prompt(get_prompt_tokens=get_prompt_tokens, lexer=lexer,
get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
history=history, style=style, true_color=True,
on_exit='return-none', on_abort='return-none',
completer=QCompleter())
if line is None or line.strip() == r'\\':
raise SystemExit
else:
line = self.precmd(line)
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
self.postloop()
|
python
|
def cmdloop(self, intro=None):
"""A Cmd.cmdloop implementation"""
style = style_from_pygments(BasicStyle, style_dict)
self.preloop()
stop = None
while not stop:
line = prompt(get_prompt_tokens=get_prompt_tokens, lexer=lexer,
get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
history=history, style=style, true_color=True,
on_exit='return-none', on_abort='return-none',
completer=QCompleter())
if line is None or line.strip() == r'\\':
raise SystemExit
else:
line = self.precmd(line)
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
self.postloop()
|
[
"def",
"cmdloop",
"(",
"self",
",",
"intro",
"=",
"None",
")",
":",
"style",
"=",
"style_from_pygments",
"(",
"BasicStyle",
",",
"style_dict",
")",
"self",
".",
"preloop",
"(",
")",
"stop",
"=",
"None",
"while",
"not",
"stop",
":",
"line",
"=",
"prompt",
"(",
"get_prompt_tokens",
"=",
"get_prompt_tokens",
",",
"lexer",
"=",
"lexer",
",",
"get_bottom_toolbar_tokens",
"=",
"get_bottom_toolbar_tokens",
",",
"history",
"=",
"history",
",",
"style",
"=",
"style",
",",
"true_color",
"=",
"True",
",",
"on_exit",
"=",
"'return-none'",
",",
"on_abort",
"=",
"'return-none'",
",",
"completer",
"=",
"QCompleter",
"(",
")",
")",
"if",
"line",
"is",
"None",
"or",
"line",
".",
"strip",
"(",
")",
"==",
"r'\\\\'",
":",
"raise",
"SystemExit",
"else",
":",
"line",
"=",
"self",
".",
"precmd",
"(",
"line",
")",
"stop",
"=",
"self",
".",
"onecmd",
"(",
"line",
")",
"stop",
"=",
"self",
".",
"postcmd",
"(",
"stop",
",",
"line",
")",
"self",
".",
"postloop",
"(",
")"
] |
A Cmd.cmdloop implementation
|
[
"A",
"Cmd",
".",
"cmdloop",
"implementation"
] |
ad7b807abde94615a7344aaa930bb01fb1552cc5
|
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/ptk.py#L90-L107
|
13,922
|
mapbox/snuggs
|
snuggs/__init__.py
|
eval
|
def eval(source, kwd_dict=None, **kwds):
"""Evaluate a snuggs expression.
Parameters
----------
source : str
Expression source.
kwd_dict : dict
A dict of items that form the evaluation context. Deprecated.
kwds : dict
A dict of items that form the valuation context.
Returns
-------
object
"""
kwd_dict = kwd_dict or kwds
with ctx(kwd_dict):
return handleLine(source)
|
python
|
def eval(source, kwd_dict=None, **kwds):
"""Evaluate a snuggs expression.
Parameters
----------
source : str
Expression source.
kwd_dict : dict
A dict of items that form the evaluation context. Deprecated.
kwds : dict
A dict of items that form the valuation context.
Returns
-------
object
"""
kwd_dict = kwd_dict or kwds
with ctx(kwd_dict):
return handleLine(source)
|
[
"def",
"eval",
"(",
"source",
",",
"kwd_dict",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"kwd_dict",
"=",
"kwd_dict",
"or",
"kwds",
"with",
"ctx",
"(",
"kwd_dict",
")",
":",
"return",
"handleLine",
"(",
"source",
")"
] |
Evaluate a snuggs expression.
Parameters
----------
source : str
Expression source.
kwd_dict : dict
A dict of items that form the evaluation context. Deprecated.
kwds : dict
A dict of items that form the valuation context.
Returns
-------
object
|
[
"Evaluate",
"a",
"snuggs",
"expression",
"."
] |
7517839178accf78ae9624b7186d03b77f837e02
|
https://github.com/mapbox/snuggs/blob/7517839178accf78ae9624b7186d03b77f837e02/snuggs/__init__.py#L208-L227
|
13,923
|
josiahcarlson/parse-crontab
|
crontab/_crontab.py
|
CronTab._make_matchers
|
def _make_matchers(self, crontab):
'''
This constructs the full matcher struct.
'''
crontab = _aliases.get(crontab, crontab)
ct = crontab.split()
if len(ct) == 5:
ct.insert(0, '0')
ct.append('*')
elif len(ct) == 6:
ct.insert(0, '0')
_assert(len(ct) == 7,
"improper number of cron entries specified; got %i need 5 to 7"%(len(ct,)))
matchers = [_Matcher(which, entry) for which, entry in enumerate(ct)]
return Matcher(*matchers)
|
python
|
def _make_matchers(self, crontab):
'''
This constructs the full matcher struct.
'''
crontab = _aliases.get(crontab, crontab)
ct = crontab.split()
if len(ct) == 5:
ct.insert(0, '0')
ct.append('*')
elif len(ct) == 6:
ct.insert(0, '0')
_assert(len(ct) == 7,
"improper number of cron entries specified; got %i need 5 to 7"%(len(ct,)))
matchers = [_Matcher(which, entry) for which, entry in enumerate(ct)]
return Matcher(*matchers)
|
[
"def",
"_make_matchers",
"(",
"self",
",",
"crontab",
")",
":",
"crontab",
"=",
"_aliases",
".",
"get",
"(",
"crontab",
",",
"crontab",
")",
"ct",
"=",
"crontab",
".",
"split",
"(",
")",
"if",
"len",
"(",
"ct",
")",
"==",
"5",
":",
"ct",
".",
"insert",
"(",
"0",
",",
"'0'",
")",
"ct",
".",
"append",
"(",
"'*'",
")",
"elif",
"len",
"(",
"ct",
")",
"==",
"6",
":",
"ct",
".",
"insert",
"(",
"0",
",",
"'0'",
")",
"_assert",
"(",
"len",
"(",
"ct",
")",
"==",
"7",
",",
"\"improper number of cron entries specified; got %i need 5 to 7\"",
"%",
"(",
"len",
"(",
"ct",
",",
")",
")",
")",
"matchers",
"=",
"[",
"_Matcher",
"(",
"which",
",",
"entry",
")",
"for",
"which",
",",
"entry",
"in",
"enumerate",
"(",
"ct",
")",
"]",
"return",
"Matcher",
"(",
"*",
"matchers",
")"
] |
This constructs the full matcher struct.
|
[
"This",
"constructs",
"the",
"full",
"matcher",
"struct",
"."
] |
b2bd254cf14e8c83e502615851b0d4b62f73ab15
|
https://github.com/josiahcarlson/parse-crontab/blob/b2bd254cf14e8c83e502615851b0d4b62f73ab15/crontab/_crontab.py#L361-L377
|
13,924
|
josiahcarlson/parse-crontab
|
crontab/_crontab.py
|
CronTab.next
|
def next(self, now=None, increments=_increments, delta=True, default_utc=WARN_CHANGE):
'''
How long to wait in seconds before this crontab entry can next be
executed.
'''
if default_utc is WARN_CHANGE and (isinstance(now, _number_types) or (now and not now.tzinfo) or now is None):
warnings.warn(WARNING_CHANGE_MESSAGE, FutureWarning, 2)
default_utc = False
now = now or (datetime.utcnow() if default_utc and default_utc is not WARN_CHANGE else datetime.now())
if isinstance(now, _number_types):
now = datetime.utcfromtimestamp(now) if default_utc else datetime.fromtimestamp(now)
# handle timezones if the datetime object has a timezone and get a
# reasonable future/past start time
onow, now = now, now.replace(tzinfo=None)
tz = onow.tzinfo
future = now.replace(microsecond=0) + increments[0]()
if future < now:
# we are going backwards...
_test = lambda: future.year < self.matchers.year
if now.microsecond:
future = now.replace(microsecond=0)
else:
# we are going forwards
_test = lambda: self.matchers.year < future.year
# Start from the year and work our way down. Any time we increment a
# higher-magnitude value, we reset all lower-magnitude values. This
# gets us performance without sacrificing correctness. Still more
# complicated than a brute-force approach, but also orders of
# magnitude faster in basically all cases.
to_test = ENTRIES - 1
while to_test >= 0:
if not self._test_match(to_test, future):
inc = increments[to_test](future, self.matchers)
future += inc
for i in xrange(0, to_test):
future = increments[ENTRIES+i](future, inc)
try:
if _test():
return None
except:
print(future, type(future), type(inc))
raise
to_test = ENTRIES-1
continue
to_test -= 1
# verify the match
match = [self._test_match(i, future) for i in xrange(ENTRIES)]
_assert(all(match),
"\nYou have discovered a bug with crontab, please notify the\n" \
"author with the following information:\n" \
"crontab: %r\n" \
"now: %r", ' '.join(m.input for m in self.matchers), now)
if not delta:
onow = now = datetime(1970, 1, 1)
delay = future - now
if tz:
delay += _fix_none(onow.utcoffset())
if hasattr(tz, 'localize'):
delay -= _fix_none(tz.localize(future).utcoffset())
else:
delay -= _fix_none(future.replace(tzinfo=tz).utcoffset())
return delay.days * 86400 + delay.seconds + delay.microseconds / 1000000.
|
python
|
def next(self, now=None, increments=_increments, delta=True, default_utc=WARN_CHANGE):
'''
How long to wait in seconds before this crontab entry can next be
executed.
'''
if default_utc is WARN_CHANGE and (isinstance(now, _number_types) or (now and not now.tzinfo) or now is None):
warnings.warn(WARNING_CHANGE_MESSAGE, FutureWarning, 2)
default_utc = False
now = now or (datetime.utcnow() if default_utc and default_utc is not WARN_CHANGE else datetime.now())
if isinstance(now, _number_types):
now = datetime.utcfromtimestamp(now) if default_utc else datetime.fromtimestamp(now)
# handle timezones if the datetime object has a timezone and get a
# reasonable future/past start time
onow, now = now, now.replace(tzinfo=None)
tz = onow.tzinfo
future = now.replace(microsecond=0) + increments[0]()
if future < now:
# we are going backwards...
_test = lambda: future.year < self.matchers.year
if now.microsecond:
future = now.replace(microsecond=0)
else:
# we are going forwards
_test = lambda: self.matchers.year < future.year
# Start from the year and work our way down. Any time we increment a
# higher-magnitude value, we reset all lower-magnitude values. This
# gets us performance without sacrificing correctness. Still more
# complicated than a brute-force approach, but also orders of
# magnitude faster in basically all cases.
to_test = ENTRIES - 1
while to_test >= 0:
if not self._test_match(to_test, future):
inc = increments[to_test](future, self.matchers)
future += inc
for i in xrange(0, to_test):
future = increments[ENTRIES+i](future, inc)
try:
if _test():
return None
except:
print(future, type(future), type(inc))
raise
to_test = ENTRIES-1
continue
to_test -= 1
# verify the match
match = [self._test_match(i, future) for i in xrange(ENTRIES)]
_assert(all(match),
"\nYou have discovered a bug with crontab, please notify the\n" \
"author with the following information:\n" \
"crontab: %r\n" \
"now: %r", ' '.join(m.input for m in self.matchers), now)
if not delta:
onow = now = datetime(1970, 1, 1)
delay = future - now
if tz:
delay += _fix_none(onow.utcoffset())
if hasattr(tz, 'localize'):
delay -= _fix_none(tz.localize(future).utcoffset())
else:
delay -= _fix_none(future.replace(tzinfo=tz).utcoffset())
return delay.days * 86400 + delay.seconds + delay.microseconds / 1000000.
|
[
"def",
"next",
"(",
"self",
",",
"now",
"=",
"None",
",",
"increments",
"=",
"_increments",
",",
"delta",
"=",
"True",
",",
"default_utc",
"=",
"WARN_CHANGE",
")",
":",
"if",
"default_utc",
"is",
"WARN_CHANGE",
"and",
"(",
"isinstance",
"(",
"now",
",",
"_number_types",
")",
"or",
"(",
"now",
"and",
"not",
"now",
".",
"tzinfo",
")",
"or",
"now",
"is",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"WARNING_CHANGE_MESSAGE",
",",
"FutureWarning",
",",
"2",
")",
"default_utc",
"=",
"False",
"now",
"=",
"now",
"or",
"(",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"default_utc",
"and",
"default_utc",
"is",
"not",
"WARN_CHANGE",
"else",
"datetime",
".",
"now",
"(",
")",
")",
"if",
"isinstance",
"(",
"now",
",",
"_number_types",
")",
":",
"now",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"now",
")",
"if",
"default_utc",
"else",
"datetime",
".",
"fromtimestamp",
"(",
"now",
")",
"# handle timezones if the datetime object has a timezone and get a",
"# reasonable future/past start time",
"onow",
",",
"now",
"=",
"now",
",",
"now",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"tz",
"=",
"onow",
".",
"tzinfo",
"future",
"=",
"now",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
"+",
"increments",
"[",
"0",
"]",
"(",
")",
"if",
"future",
"<",
"now",
":",
"# we are going backwards...",
"_test",
"=",
"lambda",
":",
"future",
".",
"year",
"<",
"self",
".",
"matchers",
".",
"year",
"if",
"now",
".",
"microsecond",
":",
"future",
"=",
"now",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
"else",
":",
"# we are going forwards",
"_test",
"=",
"lambda",
":",
"self",
".",
"matchers",
".",
"year",
"<",
"future",
".",
"year",
"# Start from the year and work our way down. Any time we increment a",
"# higher-magnitude value, we reset all lower-magnitude values. This",
"# gets us performance without sacrificing correctness. Still more",
"# complicated than a brute-force approach, but also orders of",
"# magnitude faster in basically all cases.",
"to_test",
"=",
"ENTRIES",
"-",
"1",
"while",
"to_test",
">=",
"0",
":",
"if",
"not",
"self",
".",
"_test_match",
"(",
"to_test",
",",
"future",
")",
":",
"inc",
"=",
"increments",
"[",
"to_test",
"]",
"(",
"future",
",",
"self",
".",
"matchers",
")",
"future",
"+=",
"inc",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"to_test",
")",
":",
"future",
"=",
"increments",
"[",
"ENTRIES",
"+",
"i",
"]",
"(",
"future",
",",
"inc",
")",
"try",
":",
"if",
"_test",
"(",
")",
":",
"return",
"None",
"except",
":",
"print",
"(",
"future",
",",
"type",
"(",
"future",
")",
",",
"type",
"(",
"inc",
")",
")",
"raise",
"to_test",
"=",
"ENTRIES",
"-",
"1",
"continue",
"to_test",
"-=",
"1",
"# verify the match",
"match",
"=",
"[",
"self",
".",
"_test_match",
"(",
"i",
",",
"future",
")",
"for",
"i",
"in",
"xrange",
"(",
"ENTRIES",
")",
"]",
"_assert",
"(",
"all",
"(",
"match",
")",
",",
"\"\\nYou have discovered a bug with crontab, please notify the\\n\"",
"\"author with the following information:\\n\"",
"\"crontab: %r\\n\"",
"\"now: %r\"",
",",
"' '",
".",
"join",
"(",
"m",
".",
"input",
"for",
"m",
"in",
"self",
".",
"matchers",
")",
",",
"now",
")",
"if",
"not",
"delta",
":",
"onow",
"=",
"now",
"=",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
"delay",
"=",
"future",
"-",
"now",
"if",
"tz",
":",
"delay",
"+=",
"_fix_none",
"(",
"onow",
".",
"utcoffset",
"(",
")",
")",
"if",
"hasattr",
"(",
"tz",
",",
"'localize'",
")",
":",
"delay",
"-=",
"_fix_none",
"(",
"tz",
".",
"localize",
"(",
"future",
")",
".",
"utcoffset",
"(",
")",
")",
"else",
":",
"delay",
"-=",
"_fix_none",
"(",
"future",
".",
"replace",
"(",
"tzinfo",
"=",
"tz",
")",
".",
"utcoffset",
"(",
")",
")",
"return",
"delay",
".",
"days",
"*",
"86400",
"+",
"delay",
".",
"seconds",
"+",
"delay",
".",
"microseconds",
"/",
"1000000."
] |
How long to wait in seconds before this crontab entry can next be
executed.
|
[
"How",
"long",
"to",
"wait",
"in",
"seconds",
"before",
"this",
"crontab",
"entry",
"can",
"next",
"be",
"executed",
"."
] |
b2bd254cf14e8c83e502615851b0d4b62f73ab15
|
https://github.com/josiahcarlson/parse-crontab/blob/b2bd254cf14e8c83e502615851b0d4b62f73ab15/crontab/_crontab.py#L390-L458
|
13,925
|
sanand0/xmljson
|
xmljson/__init__.py
|
XMLData._tostring
|
def _tostring(value):
'''Convert value to XML compatible string'''
if value is True:
value = 'true'
elif value is False:
value = 'false'
elif value is None:
value = ''
return unicode(value)
|
python
|
def _tostring(value):
'''Convert value to XML compatible string'''
if value is True:
value = 'true'
elif value is False:
value = 'false'
elif value is None:
value = ''
return unicode(value)
|
[
"def",
"_tostring",
"(",
"value",
")",
":",
"if",
"value",
"is",
"True",
":",
"value",
"=",
"'true'",
"elif",
"value",
"is",
"False",
":",
"value",
"=",
"'false'",
"elif",
"value",
"is",
"None",
":",
"value",
"=",
"''",
"return",
"unicode",
"(",
"value",
")"
] |
Convert value to XML compatible string
|
[
"Convert",
"value",
"to",
"XML",
"compatible",
"string"
] |
2ecc2065fe7c87b3d282d362289927f13ce7f8b0
|
https://github.com/sanand0/xmljson/blob/2ecc2065fe7c87b3d282d362289927f13ce7f8b0/xmljson/__init__.py#L61-L69
|
13,926
|
sanand0/xmljson
|
xmljson/__init__.py
|
XMLData._fromstring
|
def _fromstring(value):
'''Convert XML string value to None, boolean, int or float'''
# NOTE: Is this even possible ?
if value is None:
return None
# FIXME: In XML, booleans are either 0/false or 1/true (lower-case !)
if value.lower() == 'true':
return True
elif value.lower() == 'false':
return False
# FIXME: Using int() or float() is eating whitespaces unintendedly here
try:
return int(value)
except ValueError:
pass
try:
# Test for infinity and NaN values
if float('-inf') < float(value) < float('inf'):
return float(value)
except ValueError:
pass
return value
|
python
|
def _fromstring(value):
'''Convert XML string value to None, boolean, int or float'''
# NOTE: Is this even possible ?
if value is None:
return None
# FIXME: In XML, booleans are either 0/false or 1/true (lower-case !)
if value.lower() == 'true':
return True
elif value.lower() == 'false':
return False
# FIXME: Using int() or float() is eating whitespaces unintendedly here
try:
return int(value)
except ValueError:
pass
try:
# Test for infinity and NaN values
if float('-inf') < float(value) < float('inf'):
return float(value)
except ValueError:
pass
return value
|
[
"def",
"_fromstring",
"(",
"value",
")",
":",
"# NOTE: Is this even possible ?",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"# FIXME: In XML, booleans are either 0/false or 1/true (lower-case !)",
"if",
"value",
".",
"lower",
"(",
")",
"==",
"'true'",
":",
"return",
"True",
"elif",
"value",
".",
"lower",
"(",
")",
"==",
"'false'",
":",
"return",
"False",
"# FIXME: Using int() or float() is eating whitespaces unintendedly here",
"try",
":",
"return",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"pass",
"try",
":",
"# Test for infinity and NaN values",
"if",
"float",
"(",
"'-inf'",
")",
"<",
"float",
"(",
"value",
")",
"<",
"float",
"(",
"'inf'",
")",
":",
"return",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"pass",
"return",
"value"
] |
Convert XML string value to None, boolean, int or float
|
[
"Convert",
"XML",
"string",
"value",
"to",
"None",
"boolean",
"int",
"or",
"float"
] |
2ecc2065fe7c87b3d282d362289927f13ce7f8b0
|
https://github.com/sanand0/xmljson/blob/2ecc2065fe7c87b3d282d362289927f13ce7f8b0/xmljson/__init__.py#L72-L97
|
13,927
|
pysal/esda
|
esda/join_counts.py
|
Join_Counts.by_col
|
def by_col(cls, df, cols, w=None, inplace=False, pvalue='sim', outvals=None, **stat_kws):
"""
Function to compute a Join_Count statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
cols : string or list of string
name or list of names of columns to use to compute the statistic
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_join_count'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Join_Count statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Join_Count statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Join_Count statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Join_Count class in pysal.esda
"""
if outvals is None:
outvals = []
outvals.extend(['bb', 'p_sim_bw', 'p_sim_bb'])
pvalue = ''
return _univariate_handler(df, cols, w=w, inplace=inplace, pvalue=pvalue,
outvals=outvals, stat=cls,
swapname='bw', **stat_kws)
|
python
|
def by_col(cls, df, cols, w=None, inplace=False, pvalue='sim', outvals=None, **stat_kws):
"""
Function to compute a Join_Count statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
cols : string or list of string
name or list of names of columns to use to compute the statistic
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_join_count'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Join_Count statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Join_Count statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Join_Count statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Join_Count class in pysal.esda
"""
if outvals is None:
outvals = []
outvals.extend(['bb', 'p_sim_bw', 'p_sim_bb'])
pvalue = ''
return _univariate_handler(df, cols, w=w, inplace=inplace, pvalue=pvalue,
outvals=outvals, stat=cls,
swapname='bw', **stat_kws)
|
[
"def",
"by_col",
"(",
"cls",
",",
"df",
",",
"cols",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"pvalue",
"=",
"'sim'",
",",
"outvals",
"=",
"None",
",",
"*",
"*",
"stat_kws",
")",
":",
"if",
"outvals",
"is",
"None",
":",
"outvals",
"=",
"[",
"]",
"outvals",
".",
"extend",
"(",
"[",
"'bb'",
",",
"'p_sim_bw'",
",",
"'p_sim_bb'",
"]",
")",
"pvalue",
"=",
"''",
"return",
"_univariate_handler",
"(",
"df",
",",
"cols",
",",
"w",
"=",
"w",
",",
"inplace",
"=",
"inplace",
",",
"pvalue",
"=",
"pvalue",
",",
"outvals",
"=",
"outvals",
",",
"stat",
"=",
"cls",
",",
"swapname",
"=",
"'bw'",
",",
"*",
"*",
"stat_kws",
")"
] |
Function to compute a Join_Count statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
cols : string or list of string
name or list of names of columns to use to compute the statistic
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_join_count'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Join_Count statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Join_Count statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Join_Count statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Join_Count class in pysal.esda
|
[
"Function",
"to",
"compute",
"a",
"Join_Count",
"statistic",
"on",
"a",
"dataframe"
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/join_counts.py#L171-L214
|
13,928
|
pysal/esda
|
esda/moran.py
|
Moran_BV_matrix
|
def Moran_BV_matrix(variables, w, permutations=0, varnames=None):
"""
Bivariate Moran Matrix
Calculates bivariate Moran between all pairs of a set of variables.
Parameters
----------
variables : array or pandas.DataFrame
sequence of variables to be assessed
w : W
a spatial weights object
permutations : int
number of permutations
varnames : list, optional if variables is an array
Strings for variable names. Will add an
attribute to `Moran_BV` objects in results needed for plotting
in `splot` or `.plot()`. Default =None.
Note: If variables is a `pandas.DataFrame` varnames
will automatically be generated
Returns
-------
results : dictionary
(i, j) is the key for the pair of variables, values are
the Moran_BV objects.
Examples
--------
open dbf
>>> import libpysal
>>> f = libpysal.io.open(libpysal.examples.get_path("sids2.dbf"))
pull of selected variables from dbf and create numpy arrays for each
>>> varnames = ['SIDR74', 'SIDR79', 'NWR74', 'NWR79']
>>> vars = [np.array(f.by_col[var]) for var in varnames]
create a contiguity matrix from an external gal file
>>> w = libpysal.io.open(libpysal.examples.get_path("sids2.gal")).read()
create an instance of Moran_BV_matrix
>>> from esda.moran import Moran_BV_matrix
>>> res = Moran_BV_matrix(vars, w, varnames = varnames)
check values
>>> round(res[(0, 1)].I,7)
0.1936261
>>> round(res[(3, 0)].I,7)
0.3770138
"""
try:
# check if pandas is installed
import pandas
if isinstance(variables, pandas.DataFrame):
# if yes use variables as df and convert to numpy_array
varnames = pandas.Index.tolist(variables.columns)
variables_n = []
for var in varnames:
variables_n.append(variables[str(var)].values)
else:
variables_n = variables
except ImportError:
variables_n = variables
results = _Moran_BV_Matrix_array(variables=variables_n, w=w,
permutations=permutations,
varnames=varnames)
return results
|
python
|
def Moran_BV_matrix(variables, w, permutations=0, varnames=None):
"""
Bivariate Moran Matrix
Calculates bivariate Moran between all pairs of a set of variables.
Parameters
----------
variables : array or pandas.DataFrame
sequence of variables to be assessed
w : W
a spatial weights object
permutations : int
number of permutations
varnames : list, optional if variables is an array
Strings for variable names. Will add an
attribute to `Moran_BV` objects in results needed for plotting
in `splot` or `.plot()`. Default =None.
Note: If variables is a `pandas.DataFrame` varnames
will automatically be generated
Returns
-------
results : dictionary
(i, j) is the key for the pair of variables, values are
the Moran_BV objects.
Examples
--------
open dbf
>>> import libpysal
>>> f = libpysal.io.open(libpysal.examples.get_path("sids2.dbf"))
pull of selected variables from dbf and create numpy arrays for each
>>> varnames = ['SIDR74', 'SIDR79', 'NWR74', 'NWR79']
>>> vars = [np.array(f.by_col[var]) for var in varnames]
create a contiguity matrix from an external gal file
>>> w = libpysal.io.open(libpysal.examples.get_path("sids2.gal")).read()
create an instance of Moran_BV_matrix
>>> from esda.moran import Moran_BV_matrix
>>> res = Moran_BV_matrix(vars, w, varnames = varnames)
check values
>>> round(res[(0, 1)].I,7)
0.1936261
>>> round(res[(3, 0)].I,7)
0.3770138
"""
try:
# check if pandas is installed
import pandas
if isinstance(variables, pandas.DataFrame):
# if yes use variables as df and convert to numpy_array
varnames = pandas.Index.tolist(variables.columns)
variables_n = []
for var in varnames:
variables_n.append(variables[str(var)].values)
else:
variables_n = variables
except ImportError:
variables_n = variables
results = _Moran_BV_Matrix_array(variables=variables_n, w=w,
permutations=permutations,
varnames=varnames)
return results
|
[
"def",
"Moran_BV_matrix",
"(",
"variables",
",",
"w",
",",
"permutations",
"=",
"0",
",",
"varnames",
"=",
"None",
")",
":",
"try",
":",
"# check if pandas is installed",
"import",
"pandas",
"if",
"isinstance",
"(",
"variables",
",",
"pandas",
".",
"DataFrame",
")",
":",
"# if yes use variables as df and convert to numpy_array",
"varnames",
"=",
"pandas",
".",
"Index",
".",
"tolist",
"(",
"variables",
".",
"columns",
")",
"variables_n",
"=",
"[",
"]",
"for",
"var",
"in",
"varnames",
":",
"variables_n",
".",
"append",
"(",
"variables",
"[",
"str",
"(",
"var",
")",
"]",
".",
"values",
")",
"else",
":",
"variables_n",
"=",
"variables",
"except",
"ImportError",
":",
"variables_n",
"=",
"variables",
"results",
"=",
"_Moran_BV_Matrix_array",
"(",
"variables",
"=",
"variables_n",
",",
"w",
"=",
"w",
",",
"permutations",
"=",
"permutations",
",",
"varnames",
"=",
"varnames",
")",
"return",
"results"
] |
Bivariate Moran Matrix
Calculates bivariate Moran between all pairs of a set of variables.
Parameters
----------
variables : array or pandas.DataFrame
sequence of variables to be assessed
w : W
a spatial weights object
permutations : int
number of permutations
varnames : list, optional if variables is an array
Strings for variable names. Will add an
attribute to `Moran_BV` objects in results needed for plotting
in `splot` or `.plot()`. Default =None.
Note: If variables is a `pandas.DataFrame` varnames
will automatically be generated
Returns
-------
results : dictionary
(i, j) is the key for the pair of variables, values are
the Moran_BV objects.
Examples
--------
open dbf
>>> import libpysal
>>> f = libpysal.io.open(libpysal.examples.get_path("sids2.dbf"))
pull of selected variables from dbf and create numpy arrays for each
>>> varnames = ['SIDR74', 'SIDR79', 'NWR74', 'NWR79']
>>> vars = [np.array(f.by_col[var]) for var in varnames]
create a contiguity matrix from an external gal file
>>> w = libpysal.io.open(libpysal.examples.get_path("sids2.gal")).read()
create an instance of Moran_BV_matrix
>>> from esda.moran import Moran_BV_matrix
>>> res = Moran_BV_matrix(vars, w, varnames = varnames)
check values
>>> round(res[(0, 1)].I,7)
0.1936261
>>> round(res[(3, 0)].I,7)
0.3770138
|
[
"Bivariate",
"Moran",
"Matrix"
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/moran.py#L464-L537
|
13,929
|
pysal/esda
|
esda/moran.py
|
_Moran_BV_Matrix_array
|
def _Moran_BV_Matrix_array(variables, w, permutations=0, varnames=None):
"""
Base calculation for MORAN_BV_Matrix
"""
if varnames is None:
varnames = ['x{}'.format(i) for i in range(k)]
k = len(variables)
rk = list(range(0, k - 1))
results = {}
for i in rk:
for j in range(i + 1, k):
y1 = variables[i]
y2 = variables[j]
results[i, j] = Moran_BV(y1, y2, w, permutations=permutations)
results[j, i] = Moran_BV(y2, y1, w, permutations=permutations)
results[i, j].varnames = {'x': varnames[i], 'y': varnames[j]}
results[j, i].varnames = {'x': varnames[j], 'y': varnames[i]}
return results
|
python
|
def _Moran_BV_Matrix_array(variables, w, permutations=0, varnames=None):
"""
Base calculation for MORAN_BV_Matrix
"""
if varnames is None:
varnames = ['x{}'.format(i) for i in range(k)]
k = len(variables)
rk = list(range(0, k - 1))
results = {}
for i in rk:
for j in range(i + 1, k):
y1 = variables[i]
y2 = variables[j]
results[i, j] = Moran_BV(y1, y2, w, permutations=permutations)
results[j, i] = Moran_BV(y2, y1, w, permutations=permutations)
results[i, j].varnames = {'x': varnames[i], 'y': varnames[j]}
results[j, i].varnames = {'x': varnames[j], 'y': varnames[i]}
return results
|
[
"def",
"_Moran_BV_Matrix_array",
"(",
"variables",
",",
"w",
",",
"permutations",
"=",
"0",
",",
"varnames",
"=",
"None",
")",
":",
"if",
"varnames",
"is",
"None",
":",
"varnames",
"=",
"[",
"'x{}'",
".",
"format",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"k",
")",
"]",
"k",
"=",
"len",
"(",
"variables",
")",
"rk",
"=",
"list",
"(",
"range",
"(",
"0",
",",
"k",
"-",
"1",
")",
")",
"results",
"=",
"{",
"}",
"for",
"i",
"in",
"rk",
":",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"k",
")",
":",
"y1",
"=",
"variables",
"[",
"i",
"]",
"y2",
"=",
"variables",
"[",
"j",
"]",
"results",
"[",
"i",
",",
"j",
"]",
"=",
"Moran_BV",
"(",
"y1",
",",
"y2",
",",
"w",
",",
"permutations",
"=",
"permutations",
")",
"results",
"[",
"j",
",",
"i",
"]",
"=",
"Moran_BV",
"(",
"y2",
",",
"y1",
",",
"w",
",",
"permutations",
"=",
"permutations",
")",
"results",
"[",
"i",
",",
"j",
"]",
".",
"varnames",
"=",
"{",
"'x'",
":",
"varnames",
"[",
"i",
"]",
",",
"'y'",
":",
"varnames",
"[",
"j",
"]",
"}",
"results",
"[",
"j",
",",
"i",
"]",
".",
"varnames",
"=",
"{",
"'x'",
":",
"varnames",
"[",
"j",
"]",
",",
"'y'",
":",
"varnames",
"[",
"i",
"]",
"}",
"return",
"results"
] |
Base calculation for MORAN_BV_Matrix
|
[
"Base",
"calculation",
"for",
"MORAN_BV_Matrix"
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/moran.py#L540-L558
|
13,930
|
pysal/esda
|
esda/moran.py
|
Moran_BV.by_col
|
def by_col(cls, df, x, y=None, w=None, inplace=False, pvalue='sim', outvals=None, **stat_kws):
"""
Function to compute a Moran_BV statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
X : list of strings
column name or list of column names to use as X values to compute
the bivariate statistic. If no Y is provided, pairwise comparisons
among these variates are used instead.
Y : list of strings
column name or list of column names to use as Y values to compute
the bivariate statistic. if no Y is provided, pariwise comparisons
among the X variates are used instead.
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_moran_local'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Moran_BV statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Moran_BV statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Moran_BV statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Moran_BV class in pysal.esda
"""
return _bivariate_handler(df, x, y=y, w=w, inplace=inplace,
pvalue = pvalue, outvals = outvals,
swapname=cls.__name__.lower(), stat=cls,**stat_kws)
|
python
|
def by_col(cls, df, x, y=None, w=None, inplace=False, pvalue='sim', outvals=None, **stat_kws):
"""
Function to compute a Moran_BV statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
X : list of strings
column name or list of column names to use as X values to compute
the bivariate statistic. If no Y is provided, pairwise comparisons
among these variates are used instead.
Y : list of strings
column name or list of column names to use as Y values to compute
the bivariate statistic. if no Y is provided, pariwise comparisons
among the X variates are used instead.
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_moran_local'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Moran_BV statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Moran_BV statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Moran_BV statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Moran_BV class in pysal.esda
"""
return _bivariate_handler(df, x, y=y, w=w, inplace=inplace,
pvalue = pvalue, outvals = outvals,
swapname=cls.__name__.lower(), stat=cls,**stat_kws)
|
[
"def",
"by_col",
"(",
"cls",
",",
"df",
",",
"x",
",",
"y",
"=",
"None",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"pvalue",
"=",
"'sim'",
",",
"outvals",
"=",
"None",
",",
"*",
"*",
"stat_kws",
")",
":",
"return",
"_bivariate_handler",
"(",
"df",
",",
"x",
",",
"y",
"=",
"y",
",",
"w",
"=",
"w",
",",
"inplace",
"=",
"inplace",
",",
"pvalue",
"=",
"pvalue",
",",
"outvals",
"=",
"outvals",
",",
"swapname",
"=",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
",",
"stat",
"=",
"cls",
",",
"*",
"*",
"stat_kws",
")"
] |
Function to compute a Moran_BV statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
X : list of strings
column name or list of column names to use as X values to compute
the bivariate statistic. If no Y is provided, pairwise comparisons
among these variates are used instead.
Y : list of strings
column name or list of column names to use as Y values to compute
the bivariate statistic. if no Y is provided, pariwise comparisons
among the X variates are used instead.
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_moran_local'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Moran_BV statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Moran_BV statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Moran_BV statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Moran_BV class in pysal.esda
|
[
"Function",
"to",
"compute",
"a",
"Moran_BV",
"statistic",
"on",
"a",
"dataframe"
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/moran.py#L415-L461
|
13,931
|
pysal/esda
|
esda/moran.py
|
Moran_Rate.by_col
|
def by_col(cls, df, events, populations, w=None, inplace=False,
pvalue='sim', outvals=None, swapname='', **stat_kws):
"""
Function to compute a Moran_Rate statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
events : string or list of strings
one or more names where events are stored
populations : string or list of strings
one or more names where the populations corresponding to the
events are stored. If one population column is provided, it is
used for all event columns. If more than one population column
is provided but there is not a population for every event
column, an exception will be raised.
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_moran_rate'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Moran_Rate statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Moran_Rate statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Moran_Rate statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Moran_Rate class in pysal.esda
"""
if not inplace:
new = df.copy()
cls.by_col(new, events, populations, w=w, inplace=True,
pvalue=pvalue, outvals=outvals, swapname=swapname,
**stat_kws)
return new
if isinstance(events, str):
events = [events]
if isinstance(populations, str):
populations = [populations]
if len(populations) < len(events):
populations = populations * len(events)
if len(events) != len(populations):
raise ValueError('There is not a one-to-one matching between events and '
'populations!\nEvents: {}\n\nPopulations:'
' {}'.format(events, populations))
adjusted = stat_kws.pop('adjusted', True)
if isinstance(adjusted, bool):
adjusted = [adjusted] * len(events)
if swapname is '':
swapname = cls.__name__.lower()
rates = [assuncao_rate(df[e], df[pop]) if adj
else df[e].astype(float) / df[pop]
for e,pop,adj in zip(events, populations, adjusted)]
names = ['-'.join((e,p)) for e,p in zip(events, populations)]
out_df = df.copy()
rate_df = out_df.from_items(list(zip(names, rates))) #trick to avoid importing pandas
stat_df = _univariate_handler(rate_df, names, w=w, inplace=False,
pvalue = pvalue, outvals = outvals,
swapname=swapname,
stat=Moran, #how would this get done w/super?
**stat_kws)
for col in stat_df.columns:
df[col] = stat_df[col]
|
python
|
def by_col(cls, df, events, populations, w=None, inplace=False,
pvalue='sim', outvals=None, swapname='', **stat_kws):
"""
Function to compute a Moran_Rate statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
events : string or list of strings
one or more names where events are stored
populations : string or list of strings
one or more names where the populations corresponding to the
events are stored. If one population column is provided, it is
used for all event columns. If more than one population column
is provided but there is not a population for every event
column, an exception will be raised.
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_moran_rate'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Moran_Rate statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Moran_Rate statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Moran_Rate statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Moran_Rate class in pysal.esda
"""
if not inplace:
new = df.copy()
cls.by_col(new, events, populations, w=w, inplace=True,
pvalue=pvalue, outvals=outvals, swapname=swapname,
**stat_kws)
return new
if isinstance(events, str):
events = [events]
if isinstance(populations, str):
populations = [populations]
if len(populations) < len(events):
populations = populations * len(events)
if len(events) != len(populations):
raise ValueError('There is not a one-to-one matching between events and '
'populations!\nEvents: {}\n\nPopulations:'
' {}'.format(events, populations))
adjusted = stat_kws.pop('adjusted', True)
if isinstance(adjusted, bool):
adjusted = [adjusted] * len(events)
if swapname is '':
swapname = cls.__name__.lower()
rates = [assuncao_rate(df[e], df[pop]) if adj
else df[e].astype(float) / df[pop]
for e,pop,adj in zip(events, populations, adjusted)]
names = ['-'.join((e,p)) for e,p in zip(events, populations)]
out_df = df.copy()
rate_df = out_df.from_items(list(zip(names, rates))) #trick to avoid importing pandas
stat_df = _univariate_handler(rate_df, names, w=w, inplace=False,
pvalue = pvalue, outvals = outvals,
swapname=swapname,
stat=Moran, #how would this get done w/super?
**stat_kws)
for col in stat_df.columns:
df[col] = stat_df[col]
|
[
"def",
"by_col",
"(",
"cls",
",",
"df",
",",
"events",
",",
"populations",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"pvalue",
"=",
"'sim'",
",",
"outvals",
"=",
"None",
",",
"swapname",
"=",
"''",
",",
"*",
"*",
"stat_kws",
")",
":",
"if",
"not",
"inplace",
":",
"new",
"=",
"df",
".",
"copy",
"(",
")",
"cls",
".",
"by_col",
"(",
"new",
",",
"events",
",",
"populations",
",",
"w",
"=",
"w",
",",
"inplace",
"=",
"True",
",",
"pvalue",
"=",
"pvalue",
",",
"outvals",
"=",
"outvals",
",",
"swapname",
"=",
"swapname",
",",
"*",
"*",
"stat_kws",
")",
"return",
"new",
"if",
"isinstance",
"(",
"events",
",",
"str",
")",
":",
"events",
"=",
"[",
"events",
"]",
"if",
"isinstance",
"(",
"populations",
",",
"str",
")",
":",
"populations",
"=",
"[",
"populations",
"]",
"if",
"len",
"(",
"populations",
")",
"<",
"len",
"(",
"events",
")",
":",
"populations",
"=",
"populations",
"*",
"len",
"(",
"events",
")",
"if",
"len",
"(",
"events",
")",
"!=",
"len",
"(",
"populations",
")",
":",
"raise",
"ValueError",
"(",
"'There is not a one-to-one matching between events and '",
"'populations!\\nEvents: {}\\n\\nPopulations:'",
"' {}'",
".",
"format",
"(",
"events",
",",
"populations",
")",
")",
"adjusted",
"=",
"stat_kws",
".",
"pop",
"(",
"'adjusted'",
",",
"True",
")",
"if",
"isinstance",
"(",
"adjusted",
",",
"bool",
")",
":",
"adjusted",
"=",
"[",
"adjusted",
"]",
"*",
"len",
"(",
"events",
")",
"if",
"swapname",
"is",
"''",
":",
"swapname",
"=",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
"rates",
"=",
"[",
"assuncao_rate",
"(",
"df",
"[",
"e",
"]",
",",
"df",
"[",
"pop",
"]",
")",
"if",
"adj",
"else",
"df",
"[",
"e",
"]",
".",
"astype",
"(",
"float",
")",
"/",
"df",
"[",
"pop",
"]",
"for",
"e",
",",
"pop",
",",
"adj",
"in",
"zip",
"(",
"events",
",",
"populations",
",",
"adjusted",
")",
"]",
"names",
"=",
"[",
"'-'",
".",
"join",
"(",
"(",
"e",
",",
"p",
")",
")",
"for",
"e",
",",
"p",
"in",
"zip",
"(",
"events",
",",
"populations",
")",
"]",
"out_df",
"=",
"df",
".",
"copy",
"(",
")",
"rate_df",
"=",
"out_df",
".",
"from_items",
"(",
"list",
"(",
"zip",
"(",
"names",
",",
"rates",
")",
")",
")",
"#trick to avoid importing pandas",
"stat_df",
"=",
"_univariate_handler",
"(",
"rate_df",
",",
"names",
",",
"w",
"=",
"w",
",",
"inplace",
"=",
"False",
",",
"pvalue",
"=",
"pvalue",
",",
"outvals",
"=",
"outvals",
",",
"swapname",
"=",
"swapname",
",",
"stat",
"=",
"Moran",
",",
"#how would this get done w/super?",
"*",
"*",
"stat_kws",
")",
"for",
"col",
"in",
"stat_df",
".",
"columns",
":",
"df",
"[",
"col",
"]",
"=",
"stat_df",
"[",
"col",
"]"
] |
Function to compute a Moran_Rate statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
events : string or list of strings
one or more names where events are stored
populations : string or list of strings
one or more names where the populations corresponding to the
events are stored. If one population column is provided, it is
used for all event columns. If more than one population column
is provided but there is not a population for every event
column, an exception will be raised.
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_moran_rate'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Moran_Rate statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Moran_Rate statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Moran_Rate statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Moran_Rate class in pysal.esda
|
[
"Function",
"to",
"compute",
"a",
"Moran_Rate",
"statistic",
"on",
"a",
"dataframe"
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/moran.py#L679-L758
|
13,932
|
pysal/esda
|
esda/smoothing.py
|
flatten
|
def flatten(l, unique=True):
"""flatten a list of lists
Parameters
----------
l : list
of lists
unique : boolean
whether or not only unique items are wanted (default=True)
Returns
-------
list
of single items
Examples
--------
Creating a sample list whose elements are lists of integers
>>> l = [[1, 2], [3, 4, ], [5, 6]]
Applying flatten function
>>> flatten(l)
[1, 2, 3, 4, 5, 6]
"""
l = reduce(lambda x, y: x + y, l)
if not unique:
return list(l)
return list(set(l))
|
python
|
def flatten(l, unique=True):
"""flatten a list of lists
Parameters
----------
l : list
of lists
unique : boolean
whether or not only unique items are wanted (default=True)
Returns
-------
list
of single items
Examples
--------
Creating a sample list whose elements are lists of integers
>>> l = [[1, 2], [3, 4, ], [5, 6]]
Applying flatten function
>>> flatten(l)
[1, 2, 3, 4, 5, 6]
"""
l = reduce(lambda x, y: x + y, l)
if not unique:
return list(l)
return list(set(l))
|
[
"def",
"flatten",
"(",
"l",
",",
"unique",
"=",
"True",
")",
":",
"l",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"y",
",",
"l",
")",
"if",
"not",
"unique",
":",
"return",
"list",
"(",
"l",
")",
"return",
"list",
"(",
"set",
"(",
"l",
")",
")"
] |
flatten a list of lists
Parameters
----------
l : list
of lists
unique : boolean
whether or not only unique items are wanted (default=True)
Returns
-------
list
of single items
Examples
--------
Creating a sample list whose elements are lists of integers
>>> l = [[1, 2], [3, 4, ], [5, 6]]
Applying flatten function
>>> flatten(l)
[1, 2, 3, 4, 5, 6]
|
[
"flatten",
"a",
"list",
"of",
"lists"
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L32-L63
|
13,933
|
pysal/esda
|
esda/smoothing.py
|
weighted_median
|
def weighted_median(d, w):
"""A utility function to find a median of d based on w
Parameters
----------
d : array
(n, 1), variable for which median will be found
w : array
(n, 1), variable on which d's median will be decided
Notes
-----
d and w are arranged in the same order
Returns
-------
float
median of d
Examples
--------
Creating an array including five integers.
We will get the median of these integers.
>>> d = np.array([5,4,3,1,2])
Creating another array including weight values for the above integers.
The median of d will be decided with a consideration to these weight
values.
>>> w = np.array([10, 22, 9, 2, 5])
Applying weighted_median function
>>> weighted_median(d, w)
4
"""
dtype = [('w', '%s' % w.dtype), ('v', '%s' % d.dtype)]
d_w = np.array(list(zip(w, d)), dtype=dtype)
d_w.sort(order='v')
reordered_w = d_w['w'].cumsum()
cumsum_threshold = reordered_w[-1] * 1.0 / 2
median_inx = (reordered_w >= cumsum_threshold).nonzero()[0][0]
if reordered_w[median_inx] == cumsum_threshold and len(d) - 1 > median_inx:
return np.sort(d)[median_inx:median_inx + 2].mean()
return np.sort(d)[median_inx]
|
python
|
def weighted_median(d, w):
"""A utility function to find a median of d based on w
Parameters
----------
d : array
(n, 1), variable for which median will be found
w : array
(n, 1), variable on which d's median will be decided
Notes
-----
d and w are arranged in the same order
Returns
-------
float
median of d
Examples
--------
Creating an array including five integers.
We will get the median of these integers.
>>> d = np.array([5,4,3,1,2])
Creating another array including weight values for the above integers.
The median of d will be decided with a consideration to these weight
values.
>>> w = np.array([10, 22, 9, 2, 5])
Applying weighted_median function
>>> weighted_median(d, w)
4
"""
dtype = [('w', '%s' % w.dtype), ('v', '%s' % d.dtype)]
d_w = np.array(list(zip(w, d)), dtype=dtype)
d_w.sort(order='v')
reordered_w = d_w['w'].cumsum()
cumsum_threshold = reordered_w[-1] * 1.0 / 2
median_inx = (reordered_w >= cumsum_threshold).nonzero()[0][0]
if reordered_w[median_inx] == cumsum_threshold and len(d) - 1 > median_inx:
return np.sort(d)[median_inx:median_inx + 2].mean()
return np.sort(d)[median_inx]
|
[
"def",
"weighted_median",
"(",
"d",
",",
"w",
")",
":",
"dtype",
"=",
"[",
"(",
"'w'",
",",
"'%s'",
"%",
"w",
".",
"dtype",
")",
",",
"(",
"'v'",
",",
"'%s'",
"%",
"d",
".",
"dtype",
")",
"]",
"d_w",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"zip",
"(",
"w",
",",
"d",
")",
")",
",",
"dtype",
"=",
"dtype",
")",
"d_w",
".",
"sort",
"(",
"order",
"=",
"'v'",
")",
"reordered_w",
"=",
"d_w",
"[",
"'w'",
"]",
".",
"cumsum",
"(",
")",
"cumsum_threshold",
"=",
"reordered_w",
"[",
"-",
"1",
"]",
"*",
"1.0",
"/",
"2",
"median_inx",
"=",
"(",
"reordered_w",
">=",
"cumsum_threshold",
")",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"if",
"reordered_w",
"[",
"median_inx",
"]",
"==",
"cumsum_threshold",
"and",
"len",
"(",
"d",
")",
"-",
"1",
">",
"median_inx",
":",
"return",
"np",
".",
"sort",
"(",
"d",
")",
"[",
"median_inx",
":",
"median_inx",
"+",
"2",
"]",
".",
"mean",
"(",
")",
"return",
"np",
".",
"sort",
"(",
"d",
")",
"[",
"median_inx",
"]"
] |
A utility function to find a median of d based on w
Parameters
----------
d : array
(n, 1), variable for which median will be found
w : array
(n, 1), variable on which d's median will be decided
Notes
-----
d and w are arranged in the same order
Returns
-------
float
median of d
Examples
--------
Creating an array including five integers.
We will get the median of these integers.
>>> d = np.array([5,4,3,1,2])
Creating another array including weight values for the above integers.
The median of d will be decided with a consideration to these weight
values.
>>> w = np.array([10, 22, 9, 2, 5])
Applying weighted_median function
>>> weighted_median(d, w)
4
|
[
"A",
"utility",
"function",
"to",
"find",
"a",
"median",
"of",
"d",
"based",
"on",
"w"
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L66-L113
|
13,934
|
pysal/esda
|
esda/smoothing.py
|
sum_by_n
|
def sum_by_n(d, w, n):
"""A utility function to summarize a data array into n values
after weighting the array with another weight array w
Parameters
----------
d : array
(t, 1), numerical values
w : array
(t, 1), numerical values for weighting
n : integer
the number of groups
t = c*n (c is a constant)
Returns
-------
: array
(n, 1), an array with summarized values
Examples
--------
Creating an array including four integers.
We will compute weighted means for every two elements.
>>> d = np.array([10, 9, 20, 30])
Here is another array with the weight values for d's elements.
>>> w = np.array([0.5, 0.1, 0.3, 0.8])
We specify the number of groups for which the weighted mean is computed.
>>> n = 2
Applying sum_by_n function
>>> sum_by_n(d, w, n)
array([ 5.9, 30. ])
"""
t = len(d)
h = t // n #must be floor!
d = d * w
return np.array([sum(d[i: i + h]) for i in range(0, t, h)])
|
python
|
def sum_by_n(d, w, n):
"""A utility function to summarize a data array into n values
after weighting the array with another weight array w
Parameters
----------
d : array
(t, 1), numerical values
w : array
(t, 1), numerical values for weighting
n : integer
the number of groups
t = c*n (c is a constant)
Returns
-------
: array
(n, 1), an array with summarized values
Examples
--------
Creating an array including four integers.
We will compute weighted means for every two elements.
>>> d = np.array([10, 9, 20, 30])
Here is another array with the weight values for d's elements.
>>> w = np.array([0.5, 0.1, 0.3, 0.8])
We specify the number of groups for which the weighted mean is computed.
>>> n = 2
Applying sum_by_n function
>>> sum_by_n(d, w, n)
array([ 5.9, 30. ])
"""
t = len(d)
h = t // n #must be floor!
d = d * w
return np.array([sum(d[i: i + h]) for i in range(0, t, h)])
|
[
"def",
"sum_by_n",
"(",
"d",
",",
"w",
",",
"n",
")",
":",
"t",
"=",
"len",
"(",
"d",
")",
"h",
"=",
"t",
"//",
"n",
"#must be floor!",
"d",
"=",
"d",
"*",
"w",
"return",
"np",
".",
"array",
"(",
"[",
"sum",
"(",
"d",
"[",
"i",
":",
"i",
"+",
"h",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"t",
",",
"h",
")",
"]",
")"
] |
A utility function to summarize a data array into n values
after weighting the array with another weight array w
Parameters
----------
d : array
(t, 1), numerical values
w : array
(t, 1), numerical values for weighting
n : integer
the number of groups
t = c*n (c is a constant)
Returns
-------
: array
(n, 1), an array with summarized values
Examples
--------
Creating an array including four integers.
We will compute weighted means for every two elements.
>>> d = np.array([10, 9, 20, 30])
Here is another array with the weight values for d's elements.
>>> w = np.array([0.5, 0.1, 0.3, 0.8])
We specify the number of groups for which the weighted mean is computed.
>>> n = 2
Applying sum_by_n function
>>> sum_by_n(d, w, n)
array([ 5.9, 30. ])
|
[
"A",
"utility",
"function",
"to",
"summarize",
"a",
"data",
"array",
"into",
"n",
"values",
"after",
"weighting",
"the",
"array",
"with",
"another",
"weight",
"array",
"w"
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L116-L160
|
13,935
|
pysal/esda
|
esda/smoothing.py
|
crude_age_standardization
|
def crude_age_standardization(e, b, n):
"""A utility function to compute rate through crude age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
n : integer
the number of spatial units
Notes
-----
e and b are arranged in the same order
Returns
-------
: array
(n, 1), age standardized rate
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([100, 100, 110, 90, 100, 90, 110, 90])
Specifying the number of regions.
>>> n = 2
Applying crude_age_standardization function to e and b
>>> crude_age_standardization(e, b, n)
array([0.2375 , 0.26666667])
"""
r = e * 1.0 / b
b_by_n = sum_by_n(b, 1.0, n)
age_weight = b * 1.0 / b_by_n.repeat(len(e) // n)
return sum_by_n(r, age_weight, n)
|
python
|
def crude_age_standardization(e, b, n):
"""A utility function to compute rate through crude age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
n : integer
the number of spatial units
Notes
-----
e and b are arranged in the same order
Returns
-------
: array
(n, 1), age standardized rate
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([100, 100, 110, 90, 100, 90, 110, 90])
Specifying the number of regions.
>>> n = 2
Applying crude_age_standardization function to e and b
>>> crude_age_standardization(e, b, n)
array([0.2375 , 0.26666667])
"""
r = e * 1.0 / b
b_by_n = sum_by_n(b, 1.0, n)
age_weight = b * 1.0 / b_by_n.repeat(len(e) // n)
return sum_by_n(r, age_weight, n)
|
[
"def",
"crude_age_standardization",
"(",
"e",
",",
"b",
",",
"n",
")",
":",
"r",
"=",
"e",
"*",
"1.0",
"/",
"b",
"b_by_n",
"=",
"sum_by_n",
"(",
"b",
",",
"1.0",
",",
"n",
")",
"age_weight",
"=",
"b",
"*",
"1.0",
"/",
"b_by_n",
".",
"repeat",
"(",
"len",
"(",
"e",
")",
"//",
"n",
")",
"return",
"sum_by_n",
"(",
"r",
",",
"age_weight",
",",
"n",
")"
] |
A utility function to compute rate through crude age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
n : integer
the number of spatial units
Notes
-----
e and b are arranged in the same order
Returns
-------
: array
(n, 1), age standardized rate
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([100, 100, 110, 90, 100, 90, 110, 90])
Specifying the number of regions.
>>> n = 2
Applying crude_age_standardization function to e and b
>>> crude_age_standardization(e, b, n)
array([0.2375 , 0.26666667])
|
[
"A",
"utility",
"function",
"to",
"compute",
"rate",
"through",
"crude",
"age",
"standardization"
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L163-L213
|
13,936
|
pysal/esda
|
esda/smoothing.py
|
direct_age_standardization
|
def direct_age_standardization(e, b, s, n, alpha=0.05):
"""A utility function to compute rate through direct age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
s : array
(n*h, 1), standard population for each age group across n spatial units
n : integer
the number of spatial units
alpha : float
significance level for confidence interval
Notes
-----
e, b, and s are arranged in the same order
Returns
-------
list
a list of n tuples; a tuple has a rate and its lower and upper limits
age standardized rates and confidence intervals
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([1000, 1000, 1100, 900, 1000, 900, 1100, 900])
For direct age standardization, we also need the data for standard population.
Standard population is a reference population-at-risk (e.g., population distribution for the U.S.)
whose age distribution can be used as a benchmarking point for comparing age distributions
across regions (e.g., population distribution for Arizona and California).
Another array including standard population is created.
>>> s = np.array([1000, 900, 1000, 900, 1000, 900, 1000, 900])
Specifying the number of regions.
>>> n = 2
Applying direct_age_standardization function to e and b
>>> a, b = [i[0] for i in direct_age_standardization(e, b, s, n)]
>>> round(a, 4)
0.0237
>>> round(b, 4)
0.0267
"""
age_weight = (1.0 / b) * (s * 1.0 / sum_by_n(s, 1.0, n).repeat(len(s) // n))
adjusted_r = sum_by_n(e, age_weight, n)
var_estimate = sum_by_n(e, np.square(age_weight), n)
g_a = np.square(adjusted_r) / var_estimate
g_b = var_estimate / adjusted_r
k = [age_weight[i:i + len(b) // n].max() for i in range(0, len(b),
len(b) // n)]
g_a_k = np.square(adjusted_r + k) / (var_estimate + np.square(k))
g_b_k = (var_estimate + np.square(k)) / (adjusted_r + k)
summed_b = sum_by_n(b, 1.0, n)
res = []
for i in range(len(adjusted_r)):
if adjusted_r[i] == 0:
upper = 0.5 * chi2.ppf(1 - 0.5 * alpha)
lower = 0.0
else:
lower = gamma.ppf(0.5 * alpha, g_a[i], scale=g_b[i])
upper = gamma.ppf(1 - 0.5 * alpha, g_a_k[i], scale=g_b_k[i])
res.append((adjusted_r[i], lower, upper))
return res
|
python
|
def direct_age_standardization(e, b, s, n, alpha=0.05):
"""A utility function to compute rate through direct age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
s : array
(n*h, 1), standard population for each age group across n spatial units
n : integer
the number of spatial units
alpha : float
significance level for confidence interval
Notes
-----
e, b, and s are arranged in the same order
Returns
-------
list
a list of n tuples; a tuple has a rate and its lower and upper limits
age standardized rates and confidence intervals
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([1000, 1000, 1100, 900, 1000, 900, 1100, 900])
For direct age standardization, we also need the data for standard population.
Standard population is a reference population-at-risk (e.g., population distribution for the U.S.)
whose age distribution can be used as a benchmarking point for comparing age distributions
across regions (e.g., population distribution for Arizona and California).
Another array including standard population is created.
>>> s = np.array([1000, 900, 1000, 900, 1000, 900, 1000, 900])
Specifying the number of regions.
>>> n = 2
Applying direct_age_standardization function to e and b
>>> a, b = [i[0] for i in direct_age_standardization(e, b, s, n)]
>>> round(a, 4)
0.0237
>>> round(b, 4)
0.0267
"""
age_weight = (1.0 / b) * (s * 1.0 / sum_by_n(s, 1.0, n).repeat(len(s) // n))
adjusted_r = sum_by_n(e, age_weight, n)
var_estimate = sum_by_n(e, np.square(age_weight), n)
g_a = np.square(adjusted_r) / var_estimate
g_b = var_estimate / adjusted_r
k = [age_weight[i:i + len(b) // n].max() for i in range(0, len(b),
len(b) // n)]
g_a_k = np.square(adjusted_r + k) / (var_estimate + np.square(k))
g_b_k = (var_estimate + np.square(k)) / (adjusted_r + k)
summed_b = sum_by_n(b, 1.0, n)
res = []
for i in range(len(adjusted_r)):
if adjusted_r[i] == 0:
upper = 0.5 * chi2.ppf(1 - 0.5 * alpha)
lower = 0.0
else:
lower = gamma.ppf(0.5 * alpha, g_a[i], scale=g_b[i])
upper = gamma.ppf(1 - 0.5 * alpha, g_a_k[i], scale=g_b_k[i])
res.append((adjusted_r[i], lower, upper))
return res
|
[
"def",
"direct_age_standardization",
"(",
"e",
",",
"b",
",",
"s",
",",
"n",
",",
"alpha",
"=",
"0.05",
")",
":",
"age_weight",
"=",
"(",
"1.0",
"/",
"b",
")",
"*",
"(",
"s",
"*",
"1.0",
"/",
"sum_by_n",
"(",
"s",
",",
"1.0",
",",
"n",
")",
".",
"repeat",
"(",
"len",
"(",
"s",
")",
"//",
"n",
")",
")",
"adjusted_r",
"=",
"sum_by_n",
"(",
"e",
",",
"age_weight",
",",
"n",
")",
"var_estimate",
"=",
"sum_by_n",
"(",
"e",
",",
"np",
".",
"square",
"(",
"age_weight",
")",
",",
"n",
")",
"g_a",
"=",
"np",
".",
"square",
"(",
"adjusted_r",
")",
"/",
"var_estimate",
"g_b",
"=",
"var_estimate",
"/",
"adjusted_r",
"k",
"=",
"[",
"age_weight",
"[",
"i",
":",
"i",
"+",
"len",
"(",
"b",
")",
"//",
"n",
"]",
".",
"max",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"b",
")",
",",
"len",
"(",
"b",
")",
"//",
"n",
")",
"]",
"g_a_k",
"=",
"np",
".",
"square",
"(",
"adjusted_r",
"+",
"k",
")",
"/",
"(",
"var_estimate",
"+",
"np",
".",
"square",
"(",
"k",
")",
")",
"g_b_k",
"=",
"(",
"var_estimate",
"+",
"np",
".",
"square",
"(",
"k",
")",
")",
"/",
"(",
"adjusted_r",
"+",
"k",
")",
"summed_b",
"=",
"sum_by_n",
"(",
"b",
",",
"1.0",
",",
"n",
")",
"res",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"adjusted_r",
")",
")",
":",
"if",
"adjusted_r",
"[",
"i",
"]",
"==",
"0",
":",
"upper",
"=",
"0.5",
"*",
"chi2",
".",
"ppf",
"(",
"1",
"-",
"0.5",
"*",
"alpha",
")",
"lower",
"=",
"0.0",
"else",
":",
"lower",
"=",
"gamma",
".",
"ppf",
"(",
"0.5",
"*",
"alpha",
",",
"g_a",
"[",
"i",
"]",
",",
"scale",
"=",
"g_b",
"[",
"i",
"]",
")",
"upper",
"=",
"gamma",
".",
"ppf",
"(",
"1",
"-",
"0.5",
"*",
"alpha",
",",
"g_a_k",
"[",
"i",
"]",
",",
"scale",
"=",
"g_b_k",
"[",
"i",
"]",
")",
"res",
".",
"append",
"(",
"(",
"adjusted_r",
"[",
"i",
"]",
",",
"lower",
",",
"upper",
")",
")",
"return",
"res"
] |
A utility function to compute rate through direct age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
s : array
(n*h, 1), standard population for each age group across n spatial units
n : integer
the number of spatial units
alpha : float
significance level for confidence interval
Notes
-----
e, b, and s are arranged in the same order
Returns
-------
list
a list of n tuples; a tuple has a rate and its lower and upper limits
age standardized rates and confidence intervals
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([1000, 1000, 1100, 900, 1000, 900, 1100, 900])
For direct age standardization, we also need the data for standard population.
Standard population is a reference population-at-risk (e.g., population distribution for the U.S.)
whose age distribution can be used as a benchmarking point for comparing age distributions
across regions (e.g., population distribution for Arizona and California).
Another array including standard population is created.
>>> s = np.array([1000, 900, 1000, 900, 1000, 900, 1000, 900])
Specifying the number of regions.
>>> n = 2
Applying direct_age_standardization function to e and b
>>> a, b = [i[0] for i in direct_age_standardization(e, b, s, n)]
>>> round(a, 4)
0.0237
>>> round(b, 4)
0.0267
|
[
"A",
"utility",
"function",
"to",
"compute",
"rate",
"through",
"direct",
"age",
"standardization"
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L216-L298
|
13,937
|
pysal/esda
|
esda/smoothing.py
|
indirect_age_standardization
|
def indirect_age_standardization(e, b, s_e, s_b, n, alpha=0.05):
"""A utility function to compute rate through indirect age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
s_e : array
(n*h, 1), event variable measured for each age group across n spatial units in a standard population
s_b : array
(n*h, 1), population variable measured for each age group across n spatial units in a standard population
n : integer
the number of spatial units
alpha : float
significance level for confidence interval
Notes
-----
e, b, s_e, and s_b are arranged in the same order
Returns
-------
list
a list of n tuples; a tuple has a rate and its lower and upper limits
age standardized rate
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([100, 100, 110, 90, 100, 90, 110, 90])
For indirect age standardization, we also need the data for standard population and event.
Standard population is a reference population-at-risk (e.g., population distribution for the U.S.)
whose age distribution can be used as a benchmarking point for comparing age distributions
across regions (e.g., popoulation distribution for Arizona and California).
When the same concept is applied to the event variable,
we call it standard event (e.g., the number of cancer patients in the U.S.).
Two additional arrays including standard population and event are created.
>>> s_e = np.array([100, 45, 120, 100, 50, 30, 200, 80])
>>> s_b = np.array([1000, 900, 1000, 900, 1000, 900, 1000, 900])
Specifying the number of regions.
>>> n = 2
Applying indirect_age_standardization function to e and b
>>> [i[0] for i in indirect_age_standardization(e, b, s_e, s_b, n)]
[0.23723821989528798, 0.2610803324099723]
"""
smr = standardized_mortality_ratio(e, b, s_e, s_b, n)
s_r_all = sum(s_e * 1.0) / sum(s_b * 1.0)
adjusted_r = s_r_all * smr
e_by_n = sum_by_n(e, 1.0, n)
log_smr = np.log(smr)
log_smr_sd = 1.0 / np.sqrt(e_by_n)
norm_thres = norm.ppf(1 - 0.5 * alpha)
log_smr_lower = log_smr - norm_thres * log_smr_sd
log_smr_upper = log_smr + norm_thres * log_smr_sd
smr_lower = np.exp(log_smr_lower) * s_r_all
smr_upper = np.exp(log_smr_upper) * s_r_all
res = list(zip(adjusted_r, smr_lower, smr_upper))
return res
|
python
|
def indirect_age_standardization(e, b, s_e, s_b, n, alpha=0.05):
"""A utility function to compute rate through indirect age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
s_e : array
(n*h, 1), event variable measured for each age group across n spatial units in a standard population
s_b : array
(n*h, 1), population variable measured for each age group across n spatial units in a standard population
n : integer
the number of spatial units
alpha : float
significance level for confidence interval
Notes
-----
e, b, s_e, and s_b are arranged in the same order
Returns
-------
list
a list of n tuples; a tuple has a rate and its lower and upper limits
age standardized rate
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([100, 100, 110, 90, 100, 90, 110, 90])
For indirect age standardization, we also need the data for standard population and event.
Standard population is a reference population-at-risk (e.g., population distribution for the U.S.)
whose age distribution can be used as a benchmarking point for comparing age distributions
across regions (e.g., popoulation distribution for Arizona and California).
When the same concept is applied to the event variable,
we call it standard event (e.g., the number of cancer patients in the U.S.).
Two additional arrays including standard population and event are created.
>>> s_e = np.array([100, 45, 120, 100, 50, 30, 200, 80])
>>> s_b = np.array([1000, 900, 1000, 900, 1000, 900, 1000, 900])
Specifying the number of regions.
>>> n = 2
Applying indirect_age_standardization function to e and b
>>> [i[0] for i in indirect_age_standardization(e, b, s_e, s_b, n)]
[0.23723821989528798, 0.2610803324099723]
"""
smr = standardized_mortality_ratio(e, b, s_e, s_b, n)
s_r_all = sum(s_e * 1.0) / sum(s_b * 1.0)
adjusted_r = s_r_all * smr
e_by_n = sum_by_n(e, 1.0, n)
log_smr = np.log(smr)
log_smr_sd = 1.0 / np.sqrt(e_by_n)
norm_thres = norm.ppf(1 - 0.5 * alpha)
log_smr_lower = log_smr - norm_thres * log_smr_sd
log_smr_upper = log_smr + norm_thres * log_smr_sd
smr_lower = np.exp(log_smr_lower) * s_r_all
smr_upper = np.exp(log_smr_upper) * s_r_all
res = list(zip(adjusted_r, smr_lower, smr_upper))
return res
|
[
"def",
"indirect_age_standardization",
"(",
"e",
",",
"b",
",",
"s_e",
",",
"s_b",
",",
"n",
",",
"alpha",
"=",
"0.05",
")",
":",
"smr",
"=",
"standardized_mortality_ratio",
"(",
"e",
",",
"b",
",",
"s_e",
",",
"s_b",
",",
"n",
")",
"s_r_all",
"=",
"sum",
"(",
"s_e",
"*",
"1.0",
")",
"/",
"sum",
"(",
"s_b",
"*",
"1.0",
")",
"adjusted_r",
"=",
"s_r_all",
"*",
"smr",
"e_by_n",
"=",
"sum_by_n",
"(",
"e",
",",
"1.0",
",",
"n",
")",
"log_smr",
"=",
"np",
".",
"log",
"(",
"smr",
")",
"log_smr_sd",
"=",
"1.0",
"/",
"np",
".",
"sqrt",
"(",
"e_by_n",
")",
"norm_thres",
"=",
"norm",
".",
"ppf",
"(",
"1",
"-",
"0.5",
"*",
"alpha",
")",
"log_smr_lower",
"=",
"log_smr",
"-",
"norm_thres",
"*",
"log_smr_sd",
"log_smr_upper",
"=",
"log_smr",
"+",
"norm_thres",
"*",
"log_smr_sd",
"smr_lower",
"=",
"np",
".",
"exp",
"(",
"log_smr_lower",
")",
"*",
"s_r_all",
"smr_upper",
"=",
"np",
".",
"exp",
"(",
"log_smr_upper",
")",
"*",
"s_r_all",
"res",
"=",
"list",
"(",
"zip",
"(",
"adjusted_r",
",",
"smr_lower",
",",
"smr_upper",
")",
")",
"return",
"res"
] |
A utility function to compute rate through indirect age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
s_e : array
(n*h, 1), event variable measured for each age group across n spatial units in a standard population
s_b : array
(n*h, 1), population variable measured for each age group across n spatial units in a standard population
n : integer
the number of spatial units
alpha : float
significance level for confidence interval
Notes
-----
e, b, s_e, and s_b are arranged in the same order
Returns
-------
list
a list of n tuples; a tuple has a rate and its lower and upper limits
age standardized rate
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([100, 100, 110, 90, 100, 90, 110, 90])
For indirect age standardization, we also need the data for standard population and event.
Standard population is a reference population-at-risk (e.g., population distribution for the U.S.)
whose age distribution can be used as a benchmarking point for comparing age distributions
across regions (e.g., popoulation distribution for Arizona and California).
When the same concept is applied to the event variable,
we call it standard event (e.g., the number of cancer patients in the U.S.).
Two additional arrays including standard population and event are created.
>>> s_e = np.array([100, 45, 120, 100, 50, 30, 200, 80])
>>> s_b = np.array([1000, 900, 1000, 900, 1000, 900, 1000, 900])
Specifying the number of regions.
>>> n = 2
Applying indirect_age_standardization function to e and b
>>> [i[0] for i in indirect_age_standardization(e, b, s_e, s_b, n)]
[0.23723821989528798, 0.2610803324099723]
|
[
"A",
"utility",
"function",
"to",
"compute",
"rate",
"through",
"indirect",
"age",
"standardization"
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L301-L379
|
13,938
|
pysal/esda
|
esda/tabular.py
|
_univariate_handler
|
def _univariate_handler(df, cols, stat=None, w=None, inplace=True,
pvalue = 'sim', outvals = None, swapname='', **kwargs):
"""
Compute a univariate descriptive statistic `stat` over columns `cols` in
`df`.
Parameters
----------
df : pandas.DataFrame
the dataframe containing columns to compute the descriptive
statistics
cols : string or list of strings
one or more names of columns in `df` to use to compute
exploratory descriptive statistics.
stat : callable
a function that takes data as a first argument and any number
of configuration keyword arguments and returns an object
encapsulating the exploratory statistic results
w : pysal.weights.W
the spatial weights object corresponding to the dataframe
inplace : bool
a flag denoting whether to add the statistic to the dataframe
in memory, or to construct a copy of the dataframe and append
the results to the copy
pvalue : string
the name of the pvalue on the results object wanted
outvals : list of strings
names of attributes of the dataframe to attempt to flatten
into a column
swapname : string
suffix to replace generic identifier with. Each caller of this
function should set this to a unique column suffix
**kwargs : optional keyword arguments
options that are passed directly to the statistic
"""
### Preprocess
if not inplace:
new_df = df.copy()
_univariate_handler(new_df, cols, stat=stat, w=w, pvalue=pvalue,
inplace=True, outvals=outvals,
swapname=swapname, **kwargs)
return new_df
if w is None:
for name in df._metadata:
this_obj = df.__dict__.get(name)
if isinstance(this_obj, W):
w = this_obj
if w is None:
raise Exception('Weights not provided and no weights attached to frame!'
' Please provide a weight or attach a weight to the'
' dataframe')
### Prep indexes
if outvals is None:
outvals = []
outvals.insert(0,'_statistic')
if pvalue.lower() in ['all', 'both', '*']:
raise NotImplementedError("If you want more than one type of PValue,add"
" the targeted pvalue type to outvals. For example:"
" Geary(df, cols=['HOVAL'], w=w, outvals=['p_z_sim', "
"'p_rand']")
# this is nontrivial, since we
# can't know which p_value types are on the object without computing it.
# This is because we don't flag them with @properties, so they're just
# arbitrarily assigned post-facto. One solution might be to post-process the
# objects, determine which pvalue types are available, and then grab them
# all if needed.
if pvalue is not '':
outvals.append('p_'+pvalue.lower())
if isinstance(cols, str):
cols = [cols]
### Make closure around weights & apply columnwise
def column_stat(column):
return stat(column.values, w=w, **kwargs)
stat_objs = df[cols].apply(column_stat)
### Assign into dataframe
for col in cols:
stat_obj = stat_objs[col]
y = kwargs.get('y')
if y is not None:
col += '-' + y.name
outcols = ['_'.join((col, val)) for val in outvals]
for colname, attname in zip(outcols, outvals):
df[colname] = stat_obj.__getattribute__(attname)
if swapname is not '':
df.columns = [_swap_ending(col, swapname) if col.endswith('_statistic') else col
for col in df.columns]
|
python
|
def _univariate_handler(df, cols, stat=None, w=None, inplace=True,
pvalue = 'sim', outvals = None, swapname='', **kwargs):
"""
Compute a univariate descriptive statistic `stat` over columns `cols` in
`df`.
Parameters
----------
df : pandas.DataFrame
the dataframe containing columns to compute the descriptive
statistics
cols : string or list of strings
one or more names of columns in `df` to use to compute
exploratory descriptive statistics.
stat : callable
a function that takes data as a first argument and any number
of configuration keyword arguments and returns an object
encapsulating the exploratory statistic results
w : pysal.weights.W
the spatial weights object corresponding to the dataframe
inplace : bool
a flag denoting whether to add the statistic to the dataframe
in memory, or to construct a copy of the dataframe and append
the results to the copy
pvalue : string
the name of the pvalue on the results object wanted
outvals : list of strings
names of attributes of the dataframe to attempt to flatten
into a column
swapname : string
suffix to replace generic identifier with. Each caller of this
function should set this to a unique column suffix
**kwargs : optional keyword arguments
options that are passed directly to the statistic
"""
### Preprocess
if not inplace:
new_df = df.copy()
_univariate_handler(new_df, cols, stat=stat, w=w, pvalue=pvalue,
inplace=True, outvals=outvals,
swapname=swapname, **kwargs)
return new_df
if w is None:
for name in df._metadata:
this_obj = df.__dict__.get(name)
if isinstance(this_obj, W):
w = this_obj
if w is None:
raise Exception('Weights not provided and no weights attached to frame!'
' Please provide a weight or attach a weight to the'
' dataframe')
### Prep indexes
if outvals is None:
outvals = []
outvals.insert(0,'_statistic')
if pvalue.lower() in ['all', 'both', '*']:
raise NotImplementedError("If you want more than one type of PValue,add"
" the targeted pvalue type to outvals. For example:"
" Geary(df, cols=['HOVAL'], w=w, outvals=['p_z_sim', "
"'p_rand']")
# this is nontrivial, since we
# can't know which p_value types are on the object without computing it.
# This is because we don't flag them with @properties, so they're just
# arbitrarily assigned post-facto. One solution might be to post-process the
# objects, determine which pvalue types are available, and then grab them
# all if needed.
if pvalue is not '':
outvals.append('p_'+pvalue.lower())
if isinstance(cols, str):
cols = [cols]
### Make closure around weights & apply columnwise
def column_stat(column):
return stat(column.values, w=w, **kwargs)
stat_objs = df[cols].apply(column_stat)
### Assign into dataframe
for col in cols:
stat_obj = stat_objs[col]
y = kwargs.get('y')
if y is not None:
col += '-' + y.name
outcols = ['_'.join((col, val)) for val in outvals]
for colname, attname in zip(outcols, outvals):
df[colname] = stat_obj.__getattribute__(attname)
if swapname is not '':
df.columns = [_swap_ending(col, swapname) if col.endswith('_statistic') else col
for col in df.columns]
|
[
"def",
"_univariate_handler",
"(",
"df",
",",
"cols",
",",
"stat",
"=",
"None",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"True",
",",
"pvalue",
"=",
"'sim'",
",",
"outvals",
"=",
"None",
",",
"swapname",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"### Preprocess",
"if",
"not",
"inplace",
":",
"new_df",
"=",
"df",
".",
"copy",
"(",
")",
"_univariate_handler",
"(",
"new_df",
",",
"cols",
",",
"stat",
"=",
"stat",
",",
"w",
"=",
"w",
",",
"pvalue",
"=",
"pvalue",
",",
"inplace",
"=",
"True",
",",
"outvals",
"=",
"outvals",
",",
"swapname",
"=",
"swapname",
",",
"*",
"*",
"kwargs",
")",
"return",
"new_df",
"if",
"w",
"is",
"None",
":",
"for",
"name",
"in",
"df",
".",
"_metadata",
":",
"this_obj",
"=",
"df",
".",
"__dict__",
".",
"get",
"(",
"name",
")",
"if",
"isinstance",
"(",
"this_obj",
",",
"W",
")",
":",
"w",
"=",
"this_obj",
"if",
"w",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'Weights not provided and no weights attached to frame!'",
"' Please provide a weight or attach a weight to the'",
"' dataframe'",
")",
"### Prep indexes",
"if",
"outvals",
"is",
"None",
":",
"outvals",
"=",
"[",
"]",
"outvals",
".",
"insert",
"(",
"0",
",",
"'_statistic'",
")",
"if",
"pvalue",
".",
"lower",
"(",
")",
"in",
"[",
"'all'",
",",
"'both'",
",",
"'*'",
"]",
":",
"raise",
"NotImplementedError",
"(",
"\"If you want more than one type of PValue,add\"",
"\" the targeted pvalue type to outvals. For example:\"",
"\" Geary(df, cols=['HOVAL'], w=w, outvals=['p_z_sim', \"",
"\"'p_rand']\"",
")",
"# this is nontrivial, since we",
"# can't know which p_value types are on the object without computing it.",
"# This is because we don't flag them with @properties, so they're just",
"# arbitrarily assigned post-facto. One solution might be to post-process the",
"# objects, determine which pvalue types are available, and then grab them",
"# all if needed.",
"if",
"pvalue",
"is",
"not",
"''",
":",
"outvals",
".",
"append",
"(",
"'p_'",
"+",
"pvalue",
".",
"lower",
"(",
")",
")",
"if",
"isinstance",
"(",
"cols",
",",
"str",
")",
":",
"cols",
"=",
"[",
"cols",
"]",
"### Make closure around weights & apply columnwise",
"def",
"column_stat",
"(",
"column",
")",
":",
"return",
"stat",
"(",
"column",
".",
"values",
",",
"w",
"=",
"w",
",",
"*",
"*",
"kwargs",
")",
"stat_objs",
"=",
"df",
"[",
"cols",
"]",
".",
"apply",
"(",
"column_stat",
")",
"### Assign into dataframe",
"for",
"col",
"in",
"cols",
":",
"stat_obj",
"=",
"stat_objs",
"[",
"col",
"]",
"y",
"=",
"kwargs",
".",
"get",
"(",
"'y'",
")",
"if",
"y",
"is",
"not",
"None",
":",
"col",
"+=",
"'-'",
"+",
"y",
".",
"name",
"outcols",
"=",
"[",
"'_'",
".",
"join",
"(",
"(",
"col",
",",
"val",
")",
")",
"for",
"val",
"in",
"outvals",
"]",
"for",
"colname",
",",
"attname",
"in",
"zip",
"(",
"outcols",
",",
"outvals",
")",
":",
"df",
"[",
"colname",
"]",
"=",
"stat_obj",
".",
"__getattribute__",
"(",
"attname",
")",
"if",
"swapname",
"is",
"not",
"''",
":",
"df",
".",
"columns",
"=",
"[",
"_swap_ending",
"(",
"col",
",",
"swapname",
")",
"if",
"col",
".",
"endswith",
"(",
"'_statistic'",
")",
"else",
"col",
"for",
"col",
"in",
"df",
".",
"columns",
"]"
] |
Compute a univariate descriptive statistic `stat` over columns `cols` in
`df`.
Parameters
----------
df : pandas.DataFrame
the dataframe containing columns to compute the descriptive
statistics
cols : string or list of strings
one or more names of columns in `df` to use to compute
exploratory descriptive statistics.
stat : callable
a function that takes data as a first argument and any number
of configuration keyword arguments and returns an object
encapsulating the exploratory statistic results
w : pysal.weights.W
the spatial weights object corresponding to the dataframe
inplace : bool
a flag denoting whether to add the statistic to the dataframe
in memory, or to construct a copy of the dataframe and append
the results to the copy
pvalue : string
the name of the pvalue on the results object wanted
outvals : list of strings
names of attributes of the dataframe to attempt to flatten
into a column
swapname : string
suffix to replace generic identifier with. Each caller of this
function should set this to a unique column suffix
**kwargs : optional keyword arguments
options that are passed directly to the statistic
|
[
"Compute",
"a",
"univariate",
"descriptive",
"statistic",
"stat",
"over",
"columns",
"cols",
"in",
"df",
"."
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/tabular.py#L10-L98
|
13,939
|
pysal/esda
|
esda/tabular.py
|
_bivariate_handler
|
def _bivariate_handler(df, x, y=None, w=None, inplace=True, pvalue='sim',
outvals=None, **kwargs):
"""
Compute a descriptive bivariate statistic over two sets of columns, `x` and
`y`, contained in `df`.
Parameters
----------
df : pandas.DataFrame
dataframe in which columns `x` and `y` are contained
x : string or list of strings
one or more column names to use as variates in the bivariate
statistics
y : string or list of strings
one or more column names to use as variates in the bivariate
statistics
w : pysal.weights.W
spatial weights object corresponding to the dataframe `df`
inplace : bool
a flag denoting whether to add the statistic to the dataframe
in memory, or to construct a copy of the dataframe and append
the results to the copy
pvalue : string
the name of the pvalue on the results object wanted
outvals : list of strings
names of attributes of the dataframe to attempt to flatten
into a column
swapname : string
suffix to replace generic identifier with. Each caller of this
function should set this to a unique column suffix
**kwargs : optional keyword arguments
options that are passed directly to the statistic
"""
real_swapname = kwargs.pop('swapname', '')
if isinstance(y, str):
y = [y]
if isinstance(x, str):
x = [x]
if not inplace:
new_df = df.copy()
_bivariate_handler(new_df, x, y=y, w=w, inplace=True,
swapname=real_swapname,
pvalue=pvalue, outvals=outvals, **kwargs)
return new_df
if y is None:
y = x
for xi,yi in _it.product(x,y):
if xi == yi:
continue
_univariate_handler(df, cols=xi, w=w, y=df[yi], inplace=True,
pvalue=pvalue, outvals=outvals, swapname='', **kwargs)
if real_swapname is not '':
df.columns = [_swap_ending(col, real_swapname)
if col.endswith('_statistic')
else col for col in df.columns]
|
python
|
def _bivariate_handler(df, x, y=None, w=None, inplace=True, pvalue='sim',
outvals=None, **kwargs):
"""
Compute a descriptive bivariate statistic over two sets of columns, `x` and
`y`, contained in `df`.
Parameters
----------
df : pandas.DataFrame
dataframe in which columns `x` and `y` are contained
x : string or list of strings
one or more column names to use as variates in the bivariate
statistics
y : string or list of strings
one or more column names to use as variates in the bivariate
statistics
w : pysal.weights.W
spatial weights object corresponding to the dataframe `df`
inplace : bool
a flag denoting whether to add the statistic to the dataframe
in memory, or to construct a copy of the dataframe and append
the results to the copy
pvalue : string
the name of the pvalue on the results object wanted
outvals : list of strings
names of attributes of the dataframe to attempt to flatten
into a column
swapname : string
suffix to replace generic identifier with. Each caller of this
function should set this to a unique column suffix
**kwargs : optional keyword arguments
options that are passed directly to the statistic
"""
real_swapname = kwargs.pop('swapname', '')
if isinstance(y, str):
y = [y]
if isinstance(x, str):
x = [x]
if not inplace:
new_df = df.copy()
_bivariate_handler(new_df, x, y=y, w=w, inplace=True,
swapname=real_swapname,
pvalue=pvalue, outvals=outvals, **kwargs)
return new_df
if y is None:
y = x
for xi,yi in _it.product(x,y):
if xi == yi:
continue
_univariate_handler(df, cols=xi, w=w, y=df[yi], inplace=True,
pvalue=pvalue, outvals=outvals, swapname='', **kwargs)
if real_swapname is not '':
df.columns = [_swap_ending(col, real_swapname)
if col.endswith('_statistic')
else col for col in df.columns]
|
[
"def",
"_bivariate_handler",
"(",
"df",
",",
"x",
",",
"y",
"=",
"None",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"True",
",",
"pvalue",
"=",
"'sim'",
",",
"outvals",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"real_swapname",
"=",
"kwargs",
".",
"pop",
"(",
"'swapname'",
",",
"''",
")",
"if",
"isinstance",
"(",
"y",
",",
"str",
")",
":",
"y",
"=",
"[",
"y",
"]",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"x",
"=",
"[",
"x",
"]",
"if",
"not",
"inplace",
":",
"new_df",
"=",
"df",
".",
"copy",
"(",
")",
"_bivariate_handler",
"(",
"new_df",
",",
"x",
",",
"y",
"=",
"y",
",",
"w",
"=",
"w",
",",
"inplace",
"=",
"True",
",",
"swapname",
"=",
"real_swapname",
",",
"pvalue",
"=",
"pvalue",
",",
"outvals",
"=",
"outvals",
",",
"*",
"*",
"kwargs",
")",
"return",
"new_df",
"if",
"y",
"is",
"None",
":",
"y",
"=",
"x",
"for",
"xi",
",",
"yi",
"in",
"_it",
".",
"product",
"(",
"x",
",",
"y",
")",
":",
"if",
"xi",
"==",
"yi",
":",
"continue",
"_univariate_handler",
"(",
"df",
",",
"cols",
"=",
"xi",
",",
"w",
"=",
"w",
",",
"y",
"=",
"df",
"[",
"yi",
"]",
",",
"inplace",
"=",
"True",
",",
"pvalue",
"=",
"pvalue",
",",
"outvals",
"=",
"outvals",
",",
"swapname",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"if",
"real_swapname",
"is",
"not",
"''",
":",
"df",
".",
"columns",
"=",
"[",
"_swap_ending",
"(",
"col",
",",
"real_swapname",
")",
"if",
"col",
".",
"endswith",
"(",
"'_statistic'",
")",
"else",
"col",
"for",
"col",
"in",
"df",
".",
"columns",
"]"
] |
Compute a descriptive bivariate statistic over two sets of columns, `x` and
`y`, contained in `df`.
Parameters
----------
df : pandas.DataFrame
dataframe in which columns `x` and `y` are contained
x : string or list of strings
one or more column names to use as variates in the bivariate
statistics
y : string or list of strings
one or more column names to use as variates in the bivariate
statistics
w : pysal.weights.W
spatial weights object corresponding to the dataframe `df`
inplace : bool
a flag denoting whether to add the statistic to the dataframe
in memory, or to construct a copy of the dataframe and append
the results to the copy
pvalue : string
the name of the pvalue on the results object wanted
outvals : list of strings
names of attributes of the dataframe to attempt to flatten
into a column
swapname : string
suffix to replace generic identifier with. Each caller of this
function should set this to a unique column suffix
**kwargs : optional keyword arguments
options that are passed directly to the statistic
|
[
"Compute",
"a",
"descriptive",
"bivariate",
"statistic",
"over",
"two",
"sets",
"of",
"columns",
"x",
"and",
"y",
"contained",
"in",
"df",
"."
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/tabular.py#L100-L154
|
13,940
|
pysal/esda
|
esda/tabular.py
|
_swap_ending
|
def _swap_ending(s, ending, delim='_'):
"""
Replace the ending of a string, delimited into an arbitrary
number of chunks by `delim`, with the ending provided
Parameters
----------
s : string
string to replace endings
ending : string
string used to replace ending of `s`
delim : string
string that splits s into one or more parts
Returns
-------
new string where the final chunk of `s`, delimited by `delim`, is replaced
with `ending`.
"""
parts = [x for x in s.split(delim)[:-1] if x != '']
parts.append(ending)
return delim.join(parts)
|
python
|
def _swap_ending(s, ending, delim='_'):
"""
Replace the ending of a string, delimited into an arbitrary
number of chunks by `delim`, with the ending provided
Parameters
----------
s : string
string to replace endings
ending : string
string used to replace ending of `s`
delim : string
string that splits s into one or more parts
Returns
-------
new string where the final chunk of `s`, delimited by `delim`, is replaced
with `ending`.
"""
parts = [x for x in s.split(delim)[:-1] if x != '']
parts.append(ending)
return delim.join(parts)
|
[
"def",
"_swap_ending",
"(",
"s",
",",
"ending",
",",
"delim",
"=",
"'_'",
")",
":",
"parts",
"=",
"[",
"x",
"for",
"x",
"in",
"s",
".",
"split",
"(",
"delim",
")",
"[",
":",
"-",
"1",
"]",
"if",
"x",
"!=",
"''",
"]",
"parts",
".",
"append",
"(",
"ending",
")",
"return",
"delim",
".",
"join",
"(",
"parts",
")"
] |
Replace the ending of a string, delimited into an arbitrary
number of chunks by `delim`, with the ending provided
Parameters
----------
s : string
string to replace endings
ending : string
string used to replace ending of `s`
delim : string
string that splits s into one or more parts
Returns
-------
new string where the final chunk of `s`, delimited by `delim`, is replaced
with `ending`.
|
[
"Replace",
"the",
"ending",
"of",
"a",
"string",
"delimited",
"into",
"an",
"arbitrary",
"number",
"of",
"chunks",
"by",
"delim",
"with",
"the",
"ending",
"provided"
] |
2fafc6ec505e153152a86601d3e0fba080610c20
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/tabular.py#L156-L177
|
13,941
|
symengine/symengine.py
|
symengine/compatibility.py
|
is_sequence
|
def is_sequence(i, include=None):
"""
Return a boolean indicating whether ``i`` is a sequence in the SymPy
sense. If anything that fails the test below should be included as
being a sequence for your application, set 'include' to that object's
type; multiple types should be passed as a tuple of types.
Note: although generators can generate a sequence, they often need special
handling to make sure their elements are captured before the generator is
exhausted, so these are not included by default in the definition of a
sequence.
See also: iterable
Examples
========
>>> from sympy.utilities.iterables import is_sequence
>>> from types import GeneratorType
>>> is_sequence([])
True
>>> is_sequence(set())
False
>>> is_sequence('abc')
False
>>> is_sequence('abc', include=str)
True
>>> generator = (c for c in 'abc')
>>> is_sequence(generator)
False
>>> is_sequence(generator, include=(str, GeneratorType))
True
"""
return (hasattr(i, '__getitem__') and
iterable(i) or
bool(include) and
isinstance(i, include))
|
python
|
def is_sequence(i, include=None):
"""
Return a boolean indicating whether ``i`` is a sequence in the SymPy
sense. If anything that fails the test below should be included as
being a sequence for your application, set 'include' to that object's
type; multiple types should be passed as a tuple of types.
Note: although generators can generate a sequence, they often need special
handling to make sure their elements are captured before the generator is
exhausted, so these are not included by default in the definition of a
sequence.
See also: iterable
Examples
========
>>> from sympy.utilities.iterables import is_sequence
>>> from types import GeneratorType
>>> is_sequence([])
True
>>> is_sequence(set())
False
>>> is_sequence('abc')
False
>>> is_sequence('abc', include=str)
True
>>> generator = (c for c in 'abc')
>>> is_sequence(generator)
False
>>> is_sequence(generator, include=(str, GeneratorType))
True
"""
return (hasattr(i, '__getitem__') and
iterable(i) or
bool(include) and
isinstance(i, include))
|
[
"def",
"is_sequence",
"(",
"i",
",",
"include",
"=",
"None",
")",
":",
"return",
"(",
"hasattr",
"(",
"i",
",",
"'__getitem__'",
")",
"and",
"iterable",
"(",
"i",
")",
"or",
"bool",
"(",
"include",
")",
"and",
"isinstance",
"(",
"i",
",",
"include",
")",
")"
] |
Return a boolean indicating whether ``i`` is a sequence in the SymPy
sense. If anything that fails the test below should be included as
being a sequence for your application, set 'include' to that object's
type; multiple types should be passed as a tuple of types.
Note: although generators can generate a sequence, they often need special
handling to make sure their elements are captured before the generator is
exhausted, so these are not included by default in the definition of a
sequence.
See also: iterable
Examples
========
>>> from sympy.utilities.iterables import is_sequence
>>> from types import GeneratorType
>>> is_sequence([])
True
>>> is_sequence(set())
False
>>> is_sequence('abc')
False
>>> is_sequence('abc', include=str)
True
>>> generator = (c for c in 'abc')
>>> is_sequence(generator)
False
>>> is_sequence(generator, include=(str, GeneratorType))
True
|
[
"Return",
"a",
"boolean",
"indicating",
"whether",
"i",
"is",
"a",
"sequence",
"in",
"the",
"SymPy",
"sense",
".",
"If",
"anything",
"that",
"fails",
"the",
"test",
"below",
"should",
"be",
"included",
"as",
"being",
"a",
"sequence",
"for",
"your",
"application",
"set",
"include",
"to",
"that",
"object",
"s",
"type",
";",
"multiple",
"types",
"should",
"be",
"passed",
"as",
"a",
"tuple",
"of",
"types",
"."
] |
1366cf98ceaade339c5dd24ae3381a0e63ea9dad
|
https://github.com/symengine/symengine.py/blob/1366cf98ceaade339c5dd24ae3381a0e63ea9dad/symengine/compatibility.py#L245-L282
|
13,942
|
symengine/symengine.py
|
symengine/compatibility.py
|
as_int
|
def as_int(n):
"""
Convert the argument to a builtin integer.
The return value is guaranteed to be equal to the input. ValueError is
raised if the input has a non-integral value.
Examples
========
>>> from sympy.core.compatibility import as_int
>>> from sympy import sqrt
>>> 3.0
3.0
>>> as_int(3.0) # convert to int and test for equality
3
>>> int(sqrt(10))
3
>>> as_int(sqrt(10))
Traceback (most recent call last):
...
ValueError: ... is not an integer
"""
try:
result = int(n)
if result != n:
raise TypeError
except TypeError:
raise ValueError('%s is not an integer' % n)
return result
|
python
|
def as_int(n):
"""
Convert the argument to a builtin integer.
The return value is guaranteed to be equal to the input. ValueError is
raised if the input has a non-integral value.
Examples
========
>>> from sympy.core.compatibility import as_int
>>> from sympy import sqrt
>>> 3.0
3.0
>>> as_int(3.0) # convert to int and test for equality
3
>>> int(sqrt(10))
3
>>> as_int(sqrt(10))
Traceback (most recent call last):
...
ValueError: ... is not an integer
"""
try:
result = int(n)
if result != n:
raise TypeError
except TypeError:
raise ValueError('%s is not an integer' % n)
return result
|
[
"def",
"as_int",
"(",
"n",
")",
":",
"try",
":",
"result",
"=",
"int",
"(",
"n",
")",
"if",
"result",
"!=",
"n",
":",
"raise",
"TypeError",
"except",
"TypeError",
":",
"raise",
"ValueError",
"(",
"'%s is not an integer'",
"%",
"n",
")",
"return",
"result"
] |
Convert the argument to a builtin integer.
The return value is guaranteed to be equal to the input. ValueError is
raised if the input has a non-integral value.
Examples
========
>>> from sympy.core.compatibility import as_int
>>> from sympy import sqrt
>>> 3.0
3.0
>>> as_int(3.0) # convert to int and test for equality
3
>>> int(sqrt(10))
3
>>> as_int(sqrt(10))
Traceback (most recent call last):
...
ValueError: ... is not an integer
|
[
"Convert",
"the",
"argument",
"to",
"a",
"builtin",
"integer",
"."
] |
1366cf98ceaade339c5dd24ae3381a0e63ea9dad
|
https://github.com/symengine/symengine.py/blob/1366cf98ceaade339c5dd24ae3381a0e63ea9dad/symengine/compatibility.py#L359-L389
|
13,943
|
symengine/symengine.py
|
symengine/compatibility.py
|
default_sort_key
|
def default_sort_key(item, order=None):
"""Return a key that can be used for sorting.
The key has the structure:
(class_key, (len(args), args), exponent.sort_key(), coefficient)
This key is supplied by the sort_key routine of Basic objects when
``item`` is a Basic object or an object (other than a string) that
sympifies to a Basic object. Otherwise, this function produces the
key.
The ``order`` argument is passed along to the sort_key routine and is
used to determine how the terms *within* an expression are ordered.
(See examples below) ``order`` options are: 'lex', 'grlex', 'grevlex',
and reversed values of the same (e.g. 'rev-lex'). The default order
value is None (which translates to 'lex').
Examples
========
>>> from sympy import S, I, default_sort_key
>>> from sympy.core.function import UndefinedFunction
>>> from sympy.abc import x
The following are equivalent ways of getting the key for an object:
>>> x.sort_key() == default_sort_key(x)
True
Here are some examples of the key that is produced:
>>> default_sort_key(UndefinedFunction('f'))
((0, 0, 'UndefinedFunction'), (1, ('f',)), ((1, 0, 'Number'),
(0, ()), (), 1), 1)
>>> default_sort_key('1')
((0, 0, 'str'), (1, ('1',)), ((1, 0, 'Number'), (0, ()), (), 1), 1)
>>> default_sort_key(S.One)
((1, 0, 'Number'), (0, ()), (), 1)
>>> default_sort_key(2)
((1, 0, 'Number'), (0, ()), (), 2)
While sort_key is a method only defined for SymPy objects,
default_sort_key will accept anything as an argument so it is
more robust as a sorting key. For the following, using key=
lambda i: i.sort_key() would fail because 2 doesn't have a sort_key
method; that's why default_sort_key is used. Note, that it also
handles sympification of non-string items likes ints:
>>> a = [2, I, -I]
>>> sorted(a, key=default_sort_key)
[2, -I, I]
The returned key can be used anywhere that a key can be specified for
a function, e.g. sort, min, max, etc...:
>>> a.sort(key=default_sort_key); a[0]
2
>>> min(a, key=default_sort_key)
2
Note
----
The key returned is useful for getting items into a canonical order
that will be the same across platforms. It is not directly useful for
sorting lists of expressions:
>>> a, b = x, 1/x
Since ``a`` has only 1 term, its value of sort_key is unaffected by
``order``:
>>> a.sort_key() == a.sort_key('rev-lex')
True
If ``a`` and ``b`` are combined then the key will differ because there
are terms that can be ordered:
>>> eq = a + b
>>> eq.sort_key() == eq.sort_key('rev-lex')
False
>>> eq.as_ordered_terms()
[x, 1/x]
>>> eq.as_ordered_terms('rev-lex')
[1/x, x]
But since the keys for each of these terms are independent of ``order``'s
value, they don't sort differently when they appear separately in a list:
>>> sorted(eq.args, key=default_sort_key)
[1/x, x]
>>> sorted(eq.args, key=lambda i: default_sort_key(i, order='rev-lex'))
[1/x, x]
The order of terms obtained when using these keys is the order that would
be obtained if those terms were *factors* in a product.
See Also
========
sympy.core.expr.as_ordered_factors, sympy.core.expr.as_ordered_terms
"""
from sympy.core import S, Basic
from sympy.core.sympify import sympify, SympifyError
from sympy.core.compatibility import iterable
if isinstance(item, Basic):
return item.sort_key(order=order)
if iterable(item, exclude=string_types):
if isinstance(item, dict):
args = item.items()
unordered = True
elif isinstance(item, set):
args = item
unordered = True
else:
# e.g. tuple, list
args = list(item)
unordered = False
args = [default_sort_key(arg, order=order) for arg in args]
if unordered:
# e.g. dict, set
args = sorted(args)
cls_index, args = 10, (len(args), tuple(args))
else:
if not isinstance(item, string_types):
try:
item = sympify(item)
except SympifyError:
# e.g. lambda x: x
pass
else:
if isinstance(item, Basic):
# e.g int -> Integer
return default_sort_key(item)
# e.g. UndefinedFunction
# e.g. str
cls_index, args = 0, (1, (str(item),))
return (cls_index, 0, item.__class__.__name__
), args, S.One.sort_key(), S.One
|
python
|
def default_sort_key(item, order=None):
"""Return a key that can be used for sorting.
The key has the structure:
(class_key, (len(args), args), exponent.sort_key(), coefficient)
This key is supplied by the sort_key routine of Basic objects when
``item`` is a Basic object or an object (other than a string) that
sympifies to a Basic object. Otherwise, this function produces the
key.
The ``order`` argument is passed along to the sort_key routine and is
used to determine how the terms *within* an expression are ordered.
(See examples below) ``order`` options are: 'lex', 'grlex', 'grevlex',
and reversed values of the same (e.g. 'rev-lex'). The default order
value is None (which translates to 'lex').
Examples
========
>>> from sympy import S, I, default_sort_key
>>> from sympy.core.function import UndefinedFunction
>>> from sympy.abc import x
The following are equivalent ways of getting the key for an object:
>>> x.sort_key() == default_sort_key(x)
True
Here are some examples of the key that is produced:
>>> default_sort_key(UndefinedFunction('f'))
((0, 0, 'UndefinedFunction'), (1, ('f',)), ((1, 0, 'Number'),
(0, ()), (), 1), 1)
>>> default_sort_key('1')
((0, 0, 'str'), (1, ('1',)), ((1, 0, 'Number'), (0, ()), (), 1), 1)
>>> default_sort_key(S.One)
((1, 0, 'Number'), (0, ()), (), 1)
>>> default_sort_key(2)
((1, 0, 'Number'), (0, ()), (), 2)
While sort_key is a method only defined for SymPy objects,
default_sort_key will accept anything as an argument so it is
more robust as a sorting key. For the following, using key=
lambda i: i.sort_key() would fail because 2 doesn't have a sort_key
method; that's why default_sort_key is used. Note, that it also
handles sympification of non-string items likes ints:
>>> a = [2, I, -I]
>>> sorted(a, key=default_sort_key)
[2, -I, I]
The returned key can be used anywhere that a key can be specified for
a function, e.g. sort, min, max, etc...:
>>> a.sort(key=default_sort_key); a[0]
2
>>> min(a, key=default_sort_key)
2
Note
----
The key returned is useful for getting items into a canonical order
that will be the same across platforms. It is not directly useful for
sorting lists of expressions:
>>> a, b = x, 1/x
Since ``a`` has only 1 term, its value of sort_key is unaffected by
``order``:
>>> a.sort_key() == a.sort_key('rev-lex')
True
If ``a`` and ``b`` are combined then the key will differ because there
are terms that can be ordered:
>>> eq = a + b
>>> eq.sort_key() == eq.sort_key('rev-lex')
False
>>> eq.as_ordered_terms()
[x, 1/x]
>>> eq.as_ordered_terms('rev-lex')
[1/x, x]
But since the keys for each of these terms are independent of ``order``'s
value, they don't sort differently when they appear separately in a list:
>>> sorted(eq.args, key=default_sort_key)
[1/x, x]
>>> sorted(eq.args, key=lambda i: default_sort_key(i, order='rev-lex'))
[1/x, x]
The order of terms obtained when using these keys is the order that would
be obtained if those terms were *factors* in a product.
See Also
========
sympy.core.expr.as_ordered_factors, sympy.core.expr.as_ordered_terms
"""
from sympy.core import S, Basic
from sympy.core.sympify import sympify, SympifyError
from sympy.core.compatibility import iterable
if isinstance(item, Basic):
return item.sort_key(order=order)
if iterable(item, exclude=string_types):
if isinstance(item, dict):
args = item.items()
unordered = True
elif isinstance(item, set):
args = item
unordered = True
else:
# e.g. tuple, list
args = list(item)
unordered = False
args = [default_sort_key(arg, order=order) for arg in args]
if unordered:
# e.g. dict, set
args = sorted(args)
cls_index, args = 10, (len(args), tuple(args))
else:
if not isinstance(item, string_types):
try:
item = sympify(item)
except SympifyError:
# e.g. lambda x: x
pass
else:
if isinstance(item, Basic):
# e.g int -> Integer
return default_sort_key(item)
# e.g. UndefinedFunction
# e.g. str
cls_index, args = 0, (1, (str(item),))
return (cls_index, 0, item.__class__.__name__
), args, S.One.sort_key(), S.One
|
[
"def",
"default_sort_key",
"(",
"item",
",",
"order",
"=",
"None",
")",
":",
"from",
"sympy",
".",
"core",
"import",
"S",
",",
"Basic",
"from",
"sympy",
".",
"core",
".",
"sympify",
"import",
"sympify",
",",
"SympifyError",
"from",
"sympy",
".",
"core",
".",
"compatibility",
"import",
"iterable",
"if",
"isinstance",
"(",
"item",
",",
"Basic",
")",
":",
"return",
"item",
".",
"sort_key",
"(",
"order",
"=",
"order",
")",
"if",
"iterable",
"(",
"item",
",",
"exclude",
"=",
"string_types",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"args",
"=",
"item",
".",
"items",
"(",
")",
"unordered",
"=",
"True",
"elif",
"isinstance",
"(",
"item",
",",
"set",
")",
":",
"args",
"=",
"item",
"unordered",
"=",
"True",
"else",
":",
"# e.g. tuple, list",
"args",
"=",
"list",
"(",
"item",
")",
"unordered",
"=",
"False",
"args",
"=",
"[",
"default_sort_key",
"(",
"arg",
",",
"order",
"=",
"order",
")",
"for",
"arg",
"in",
"args",
"]",
"if",
"unordered",
":",
"# e.g. dict, set",
"args",
"=",
"sorted",
"(",
"args",
")",
"cls_index",
",",
"args",
"=",
"10",
",",
"(",
"len",
"(",
"args",
")",
",",
"tuple",
"(",
"args",
")",
")",
"else",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"string_types",
")",
":",
"try",
":",
"item",
"=",
"sympify",
"(",
"item",
")",
"except",
"SympifyError",
":",
"# e.g. lambda x: x",
"pass",
"else",
":",
"if",
"isinstance",
"(",
"item",
",",
"Basic",
")",
":",
"# e.g int -> Integer",
"return",
"default_sort_key",
"(",
"item",
")",
"# e.g. UndefinedFunction",
"# e.g. str",
"cls_index",
",",
"args",
"=",
"0",
",",
"(",
"1",
",",
"(",
"str",
"(",
"item",
")",
",",
")",
")",
"return",
"(",
"cls_index",
",",
"0",
",",
"item",
".",
"__class__",
".",
"__name__",
")",
",",
"args",
",",
"S",
".",
"One",
".",
"sort_key",
"(",
")",
",",
"S",
".",
"One"
] |
Return a key that can be used for sorting.
The key has the structure:
(class_key, (len(args), args), exponent.sort_key(), coefficient)
This key is supplied by the sort_key routine of Basic objects when
``item`` is a Basic object or an object (other than a string) that
sympifies to a Basic object. Otherwise, this function produces the
key.
The ``order`` argument is passed along to the sort_key routine and is
used to determine how the terms *within* an expression are ordered.
(See examples below) ``order`` options are: 'lex', 'grlex', 'grevlex',
and reversed values of the same (e.g. 'rev-lex'). The default order
value is None (which translates to 'lex').
Examples
========
>>> from sympy import S, I, default_sort_key
>>> from sympy.core.function import UndefinedFunction
>>> from sympy.abc import x
The following are equivalent ways of getting the key for an object:
>>> x.sort_key() == default_sort_key(x)
True
Here are some examples of the key that is produced:
>>> default_sort_key(UndefinedFunction('f'))
((0, 0, 'UndefinedFunction'), (1, ('f',)), ((1, 0, 'Number'),
(0, ()), (), 1), 1)
>>> default_sort_key('1')
((0, 0, 'str'), (1, ('1',)), ((1, 0, 'Number'), (0, ()), (), 1), 1)
>>> default_sort_key(S.One)
((1, 0, 'Number'), (0, ()), (), 1)
>>> default_sort_key(2)
((1, 0, 'Number'), (0, ()), (), 2)
While sort_key is a method only defined for SymPy objects,
default_sort_key will accept anything as an argument so it is
more robust as a sorting key. For the following, using key=
lambda i: i.sort_key() would fail because 2 doesn't have a sort_key
method; that's why default_sort_key is used. Note, that it also
handles sympification of non-string items likes ints:
>>> a = [2, I, -I]
>>> sorted(a, key=default_sort_key)
[2, -I, I]
The returned key can be used anywhere that a key can be specified for
a function, e.g. sort, min, max, etc...:
>>> a.sort(key=default_sort_key); a[0]
2
>>> min(a, key=default_sort_key)
2
Note
----
The key returned is useful for getting items into a canonical order
that will be the same across platforms. It is not directly useful for
sorting lists of expressions:
>>> a, b = x, 1/x
Since ``a`` has only 1 term, its value of sort_key is unaffected by
``order``:
>>> a.sort_key() == a.sort_key('rev-lex')
True
If ``a`` and ``b`` are combined then the key will differ because there
are terms that can be ordered:
>>> eq = a + b
>>> eq.sort_key() == eq.sort_key('rev-lex')
False
>>> eq.as_ordered_terms()
[x, 1/x]
>>> eq.as_ordered_terms('rev-lex')
[1/x, x]
But since the keys for each of these terms are independent of ``order``'s
value, they don't sort differently when they appear separately in a list:
>>> sorted(eq.args, key=default_sort_key)
[1/x, x]
>>> sorted(eq.args, key=lambda i: default_sort_key(i, order='rev-lex'))
[1/x, x]
The order of terms obtained when using these keys is the order that would
be obtained if those terms were *factors* in a product.
See Also
========
sympy.core.expr.as_ordered_factors, sympy.core.expr.as_ordered_terms
|
[
"Return",
"a",
"key",
"that",
"can",
"be",
"used",
"for",
"sorting",
"."
] |
1366cf98ceaade339c5dd24ae3381a0e63ea9dad
|
https://github.com/symengine/symengine.py/blob/1366cf98ceaade339c5dd24ae3381a0e63ea9dad/symengine/compatibility.py#L392-L541
|
13,944
|
symengine/symengine.py
|
symengine/utilities.py
|
var
|
def var(names, **args):
"""
Create symbols and inject them into the global namespace.
INPUT:
- s -- a string, either a single variable name, or
- a space separated list of variable names, or
- a list of variable names.
This calls :func:`symbols` with the same arguments and puts the results
into the *global* namespace. It's recommended not to use :func:`var` in
library code, where :func:`symbols` has to be used::
Examples
========
>>> from symengine import var
>>> var('x')
x
>>> x
x
>>> var('a,ab,abc')
(a, ab, abc)
>>> abc
abc
See :func:`symbols` documentation for more details on what kinds of
arguments can be passed to :func:`var`.
"""
def traverse(symbols, frame):
"""Recursively inject symbols to the global namespace. """
for symbol in symbols:
if isinstance(symbol, Basic):
frame.f_globals[symbol.__str__()] = symbol
# Once we hace an undefined function class
# implemented, put a check for function here
else:
traverse(symbol, frame)
from inspect import currentframe
frame = currentframe().f_back
try:
syms = symbols(names, **args)
if syms is not None:
if isinstance(syms, Basic):
frame.f_globals[syms.__str__()] = syms
# Once we hace an undefined function class
# implemented, put a check for function here
else:
traverse(syms, frame)
finally:
del frame # break cyclic dependencies as stated in inspect docs
return syms
|
python
|
def var(names, **args):
"""
Create symbols and inject them into the global namespace.
INPUT:
- s -- a string, either a single variable name, or
- a space separated list of variable names, or
- a list of variable names.
This calls :func:`symbols` with the same arguments and puts the results
into the *global* namespace. It's recommended not to use :func:`var` in
library code, where :func:`symbols` has to be used::
Examples
========
>>> from symengine import var
>>> var('x')
x
>>> x
x
>>> var('a,ab,abc')
(a, ab, abc)
>>> abc
abc
See :func:`symbols` documentation for more details on what kinds of
arguments can be passed to :func:`var`.
"""
def traverse(symbols, frame):
"""Recursively inject symbols to the global namespace. """
for symbol in symbols:
if isinstance(symbol, Basic):
frame.f_globals[symbol.__str__()] = symbol
# Once we hace an undefined function class
# implemented, put a check for function here
else:
traverse(symbol, frame)
from inspect import currentframe
frame = currentframe().f_back
try:
syms = symbols(names, **args)
if syms is not None:
if isinstance(syms, Basic):
frame.f_globals[syms.__str__()] = syms
# Once we hace an undefined function class
# implemented, put a check for function here
else:
traverse(syms, frame)
finally:
del frame # break cyclic dependencies as stated in inspect docs
return syms
|
[
"def",
"var",
"(",
"names",
",",
"*",
"*",
"args",
")",
":",
"def",
"traverse",
"(",
"symbols",
",",
"frame",
")",
":",
"\"\"\"Recursively inject symbols to the global namespace. \"\"\"",
"for",
"symbol",
"in",
"symbols",
":",
"if",
"isinstance",
"(",
"symbol",
",",
"Basic",
")",
":",
"frame",
".",
"f_globals",
"[",
"symbol",
".",
"__str__",
"(",
")",
"]",
"=",
"symbol",
"# Once we hace an undefined function class",
"# implemented, put a check for function here",
"else",
":",
"traverse",
"(",
"symbol",
",",
"frame",
")",
"from",
"inspect",
"import",
"currentframe",
"frame",
"=",
"currentframe",
"(",
")",
".",
"f_back",
"try",
":",
"syms",
"=",
"symbols",
"(",
"names",
",",
"*",
"*",
"args",
")",
"if",
"syms",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"syms",
",",
"Basic",
")",
":",
"frame",
".",
"f_globals",
"[",
"syms",
".",
"__str__",
"(",
")",
"]",
"=",
"syms",
"# Once we hace an undefined function class",
"# implemented, put a check for function here",
"else",
":",
"traverse",
"(",
"syms",
",",
"frame",
")",
"finally",
":",
"del",
"frame",
"# break cyclic dependencies as stated in inspect docs",
"return",
"syms"
] |
Create symbols and inject them into the global namespace.
INPUT:
- s -- a string, either a single variable name, or
- a space separated list of variable names, or
- a list of variable names.
This calls :func:`symbols` with the same arguments and puts the results
into the *global* namespace. It's recommended not to use :func:`var` in
library code, where :func:`symbols` has to be used::
Examples
========
>>> from symengine import var
>>> var('x')
x
>>> x
x
>>> var('a,ab,abc')
(a, ab, abc)
>>> abc
abc
See :func:`symbols` documentation for more details on what kinds of
arguments can be passed to :func:`var`.
|
[
"Create",
"symbols",
"and",
"inject",
"them",
"into",
"the",
"global",
"namespace",
"."
] |
1366cf98ceaade339c5dd24ae3381a0e63ea9dad
|
https://github.com/symengine/symengine.py/blob/1366cf98ceaade339c5dd24ae3381a0e63ea9dad/symengine/utilities.py#L184-L242
|
13,945
|
Murali-group/halp
|
halp/undirected_hypergraph.py
|
UndirectedHypergraph._combine_attribute_arguments
|
def _combine_attribute_arguments(self, attr_dict, attr):
# Note: Code & comments unchanged from DirectedHypergraph
"""Combines attr_dict and attr dictionaries, by updating attr_dict
with attr.
:param attr_dict: dictionary of attributes of the node.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
:returns: dict -- single dictionary of [combined] attributes.
:raises: AttributeError -- attr_dict argument must be a dictionary.
"""
# If no attribute dict was passed, treat the keyword
# arguments as the dict
if attr_dict is None:
attr_dict = attr
# Otherwise, combine the passed attribute dict with
# the keyword arguments
else:
try:
attr_dict.update(attr)
except AttributeError:
raise AttributeError("attr_dict argument \
must be a dictionary.")
return attr_dict
|
python
|
def _combine_attribute_arguments(self, attr_dict, attr):
# Note: Code & comments unchanged from DirectedHypergraph
"""Combines attr_dict and attr dictionaries, by updating attr_dict
with attr.
:param attr_dict: dictionary of attributes of the node.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
:returns: dict -- single dictionary of [combined] attributes.
:raises: AttributeError -- attr_dict argument must be a dictionary.
"""
# If no attribute dict was passed, treat the keyword
# arguments as the dict
if attr_dict is None:
attr_dict = attr
# Otherwise, combine the passed attribute dict with
# the keyword arguments
else:
try:
attr_dict.update(attr)
except AttributeError:
raise AttributeError("attr_dict argument \
must be a dictionary.")
return attr_dict
|
[
"def",
"_combine_attribute_arguments",
"(",
"self",
",",
"attr_dict",
",",
"attr",
")",
":",
"# Note: Code & comments unchanged from DirectedHypergraph",
"# If no attribute dict was passed, treat the keyword",
"# arguments as the dict",
"if",
"attr_dict",
"is",
"None",
":",
"attr_dict",
"=",
"attr",
"# Otherwise, combine the passed attribute dict with",
"# the keyword arguments",
"else",
":",
"try",
":",
"attr_dict",
".",
"update",
"(",
"attr",
")",
"except",
"AttributeError",
":",
"raise",
"AttributeError",
"(",
"\"attr_dict argument \\\n must be a dictionary.\"",
")",
"return",
"attr_dict"
] |
Combines attr_dict and attr dictionaries, by updating attr_dict
with attr.
:param attr_dict: dictionary of attributes of the node.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
:returns: dict -- single dictionary of [combined] attributes.
:raises: AttributeError -- attr_dict argument must be a dictionary.
|
[
"Combines",
"attr_dict",
"and",
"attr",
"dictionaries",
"by",
"updating",
"attr_dict",
"with",
"attr",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/undirected_hypergraph.py#L137-L162
|
13,946
|
Murali-group/halp
|
halp/undirected_hypergraph.py
|
UndirectedHypergraph.remove_node
|
def remove_node(self, node):
"""Removes a node and its attributes from the hypergraph. Removes
every hyperedge that contains this node.
:param node: reference to the node being added.
:raises: ValueError -- No such node exists.
Examples:
::
>>> H = UndirectedHypergraph()
>>> H.add_node("A", label="positive")
>>> H.remove_node("A")
"""
if not self.has_node(node):
raise ValueError("No such node exists.")
# Loop over every hyperedge in the star of the node;
# i.e., over every hyperedge that contains the node
for hyperedge_id in self._star[node]:
frozen_nodes = \
self._hyperedge_attributes[hyperedge_id]["__frozen_nodes"]
# Remove the node set composing the hyperedge
del self._node_set_to_hyperedge[frozen_nodes]
# Remove this hyperedge's attributes
del self._hyperedge_attributes[hyperedge_id]
# Remove node's star
del self._star[node]
# Remove node's attributes dictionary
del self._node_attributes[node]
|
python
|
def remove_node(self, node):
"""Removes a node and its attributes from the hypergraph. Removes
every hyperedge that contains this node.
:param node: reference to the node being added.
:raises: ValueError -- No such node exists.
Examples:
::
>>> H = UndirectedHypergraph()
>>> H.add_node("A", label="positive")
>>> H.remove_node("A")
"""
if not self.has_node(node):
raise ValueError("No such node exists.")
# Loop over every hyperedge in the star of the node;
# i.e., over every hyperedge that contains the node
for hyperedge_id in self._star[node]:
frozen_nodes = \
self._hyperedge_attributes[hyperedge_id]["__frozen_nodes"]
# Remove the node set composing the hyperedge
del self._node_set_to_hyperedge[frozen_nodes]
# Remove this hyperedge's attributes
del self._hyperedge_attributes[hyperedge_id]
# Remove node's star
del self._star[node]
# Remove node's attributes dictionary
del self._node_attributes[node]
|
[
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"self",
".",
"has_node",
"(",
"node",
")",
":",
"raise",
"ValueError",
"(",
"\"No such node exists.\"",
")",
"# Loop over every hyperedge in the star of the node;",
"# i.e., over every hyperedge that contains the node",
"for",
"hyperedge_id",
"in",
"self",
".",
"_star",
"[",
"node",
"]",
":",
"frozen_nodes",
"=",
"self",
".",
"_hyperedge_attributes",
"[",
"hyperedge_id",
"]",
"[",
"\"__frozen_nodes\"",
"]",
"# Remove the node set composing the hyperedge",
"del",
"self",
".",
"_node_set_to_hyperedge",
"[",
"frozen_nodes",
"]",
"# Remove this hyperedge's attributes",
"del",
"self",
".",
"_hyperedge_attributes",
"[",
"hyperedge_id",
"]",
"# Remove node's star",
"del",
"self",
".",
"_star",
"[",
"node",
"]",
"# Remove node's attributes dictionary",
"del",
"self",
".",
"_node_attributes",
"[",
"node",
"]"
] |
Removes a node and its attributes from the hypergraph. Removes
every hyperedge that contains this node.
:param node: reference to the node being added.
:raises: ValueError -- No such node exists.
Examples:
::
>>> H = UndirectedHypergraph()
>>> H.add_node("A", label="positive")
>>> H.remove_node("A")
|
[
"Removes",
"a",
"node",
"and",
"its",
"attributes",
"from",
"the",
"hypergraph",
".",
"Removes",
"every",
"hyperedge",
"that",
"contains",
"this",
"node",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/undirected_hypergraph.py#L256-L288
|
13,947
|
Murali-group/halp
|
halp/undirected_hypergraph.py
|
UndirectedHypergraph.add_hyperedge
|
def add_hyperedge(self, nodes, attr_dict=None, **attr):
"""Adds a hyperedge to the hypergraph, along with any related
attributes of the hyperedge.
This method will automatically add any node from the node set
that was not in the hypergraph.
A hyperedge without a "weight" attribute specified will be
assigned the default value of 1.
:param nodes: iterable container of references to nodes in the
hyperedge to be added.
:param attr_dict: dictionary of attributes of the hyperedge being
added.
:param attr: keyword arguments of attributes of the hyperedge;
attr's values will override attr_dict's values
if both are provided.
:returns: str -- the ID of the hyperedge that was added.
:raises: ValueError -- nodes arguments cannot be empty.
Examples:
::
>>> H = UndirectedHypergraph()
>>> x = H.add_hyperedge(["A", "B", "C"])
>>> y = H.add_hyperedge(("A", "D"), weight=2)
>>> z = H.add_hyperedge(set(["B", "D"]), {color: "red"})
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# Don't allow empty node set (invalid hyperedge)
if not nodes:
raise ValueError("nodes argument cannot be empty.")
# Use frozensets for node sets to allow for hashable keys
frozen_nodes = frozenset(nodes)
is_new_hyperedge = not self.has_hyperedge(frozen_nodes)
if is_new_hyperedge:
# Add nodes to graph (if not already present)
self.add_nodes(frozen_nodes)
# Create new hyperedge name to use as reference for that hyperedge
hyperedge_id = self._assign_next_hyperedge_id()
# For each node in the node set, add hyperedge to the node's star
for node in frozen_nodes:
self._star[node].add(hyperedge_id)
# Add the hyperedge ID as the hyperedge that the node set composes
self._node_set_to_hyperedge[frozen_nodes] = hyperedge_id
# Assign some special attributes to this hyperedge. We assign
# a default weight of 1 to the hyperedge. We also store the
# original node set in order to return them exactly as the
# user passed them into add_hyperedge.
self._hyperedge_attributes[hyperedge_id] = \
{"nodes": nodes, "__frozen_nodes": frozen_nodes, "weight": 1}
else:
# If its not a new hyperedge, just get its ID to update attributes
hyperedge_id = self._node_set_to_hyperedge[frozen_nodes]
# Set attributes and return hyperedge ID
self._hyperedge_attributes[hyperedge_id].update(attr_dict)
return hyperedge_id
|
python
|
def add_hyperedge(self, nodes, attr_dict=None, **attr):
"""Adds a hyperedge to the hypergraph, along with any related
attributes of the hyperedge.
This method will automatically add any node from the node set
that was not in the hypergraph.
A hyperedge without a "weight" attribute specified will be
assigned the default value of 1.
:param nodes: iterable container of references to nodes in the
hyperedge to be added.
:param attr_dict: dictionary of attributes of the hyperedge being
added.
:param attr: keyword arguments of attributes of the hyperedge;
attr's values will override attr_dict's values
if both are provided.
:returns: str -- the ID of the hyperedge that was added.
:raises: ValueError -- nodes arguments cannot be empty.
Examples:
::
>>> H = UndirectedHypergraph()
>>> x = H.add_hyperedge(["A", "B", "C"])
>>> y = H.add_hyperedge(("A", "D"), weight=2)
>>> z = H.add_hyperedge(set(["B", "D"]), {color: "red"})
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# Don't allow empty node set (invalid hyperedge)
if not nodes:
raise ValueError("nodes argument cannot be empty.")
# Use frozensets for node sets to allow for hashable keys
frozen_nodes = frozenset(nodes)
is_new_hyperedge = not self.has_hyperedge(frozen_nodes)
if is_new_hyperedge:
# Add nodes to graph (if not already present)
self.add_nodes(frozen_nodes)
# Create new hyperedge name to use as reference for that hyperedge
hyperedge_id = self._assign_next_hyperedge_id()
# For each node in the node set, add hyperedge to the node's star
for node in frozen_nodes:
self._star[node].add(hyperedge_id)
# Add the hyperedge ID as the hyperedge that the node set composes
self._node_set_to_hyperedge[frozen_nodes] = hyperedge_id
# Assign some special attributes to this hyperedge. We assign
# a default weight of 1 to the hyperedge. We also store the
# original node set in order to return them exactly as the
# user passed them into add_hyperedge.
self._hyperedge_attributes[hyperedge_id] = \
{"nodes": nodes, "__frozen_nodes": frozen_nodes, "weight": 1}
else:
# If its not a new hyperedge, just get its ID to update attributes
hyperedge_id = self._node_set_to_hyperedge[frozen_nodes]
# Set attributes and return hyperedge ID
self._hyperedge_attributes[hyperedge_id].update(attr_dict)
return hyperedge_id
|
[
"def",
"add_hyperedge",
"(",
"self",
",",
"nodes",
",",
"attr_dict",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"attr_dict",
"=",
"self",
".",
"_combine_attribute_arguments",
"(",
"attr_dict",
",",
"attr",
")",
"# Don't allow empty node set (invalid hyperedge)",
"if",
"not",
"nodes",
":",
"raise",
"ValueError",
"(",
"\"nodes argument cannot be empty.\"",
")",
"# Use frozensets for node sets to allow for hashable keys",
"frozen_nodes",
"=",
"frozenset",
"(",
"nodes",
")",
"is_new_hyperedge",
"=",
"not",
"self",
".",
"has_hyperedge",
"(",
"frozen_nodes",
")",
"if",
"is_new_hyperedge",
":",
"# Add nodes to graph (if not already present)",
"self",
".",
"add_nodes",
"(",
"frozen_nodes",
")",
"# Create new hyperedge name to use as reference for that hyperedge",
"hyperedge_id",
"=",
"self",
".",
"_assign_next_hyperedge_id",
"(",
")",
"# For each node in the node set, add hyperedge to the node's star",
"for",
"node",
"in",
"frozen_nodes",
":",
"self",
".",
"_star",
"[",
"node",
"]",
".",
"add",
"(",
"hyperedge_id",
")",
"# Add the hyperedge ID as the hyperedge that the node set composes",
"self",
".",
"_node_set_to_hyperedge",
"[",
"frozen_nodes",
"]",
"=",
"hyperedge_id",
"# Assign some special attributes to this hyperedge. We assign",
"# a default weight of 1 to the hyperedge. We also store the",
"# original node set in order to return them exactly as the",
"# user passed them into add_hyperedge.",
"self",
".",
"_hyperedge_attributes",
"[",
"hyperedge_id",
"]",
"=",
"{",
"\"nodes\"",
":",
"nodes",
",",
"\"__frozen_nodes\"",
":",
"frozen_nodes",
",",
"\"weight\"",
":",
"1",
"}",
"else",
":",
"# If its not a new hyperedge, just get its ID to update attributes",
"hyperedge_id",
"=",
"self",
".",
"_node_set_to_hyperedge",
"[",
"frozen_nodes",
"]",
"# Set attributes and return hyperedge ID",
"self",
".",
"_hyperedge_attributes",
"[",
"hyperedge_id",
"]",
".",
"update",
"(",
"attr_dict",
")",
"return",
"hyperedge_id"
] |
Adds a hyperedge to the hypergraph, along with any related
attributes of the hyperedge.
This method will automatically add any node from the node set
that was not in the hypergraph.
A hyperedge without a "weight" attribute specified will be
assigned the default value of 1.
:param nodes: iterable container of references to nodes in the
hyperedge to be added.
:param attr_dict: dictionary of attributes of the hyperedge being
added.
:param attr: keyword arguments of attributes of the hyperedge;
attr's values will override attr_dict's values
if both are provided.
:returns: str -- the ID of the hyperedge that was added.
:raises: ValueError -- nodes arguments cannot be empty.
Examples:
::
>>> H = UndirectedHypergraph()
>>> x = H.add_hyperedge(["A", "B", "C"])
>>> y = H.add_hyperedge(("A", "D"), weight=2)
>>> z = H.add_hyperedge(set(["B", "D"]), {color: "red"})
|
[
"Adds",
"a",
"hyperedge",
"to",
"the",
"hypergraph",
"along",
"with",
"any",
"related",
"attributes",
"of",
"the",
"hyperedge",
".",
"This",
"method",
"will",
"automatically",
"add",
"any",
"node",
"from",
"the",
"node",
"set",
"that",
"was",
"not",
"in",
"the",
"hypergraph",
".",
"A",
"hyperedge",
"without",
"a",
"weight",
"attribute",
"specified",
"will",
"be",
"assigned",
"the",
"default",
"value",
"of",
"1",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/undirected_hypergraph.py#L384-L447
|
13,948
|
Murali-group/halp
|
halp/undirected_hypergraph.py
|
UndirectedHypergraph.add_hyperedges
|
def add_hyperedges(self, hyperedges, attr_dict=None, **attr):
"""Adds multiple hyperedges to the graph, along with any related
attributes of the hyperedges.
If any node of a hyperedge has not previously been added to the
hypergraph, it will automatically be added here.
Hyperedges without a "weight" attribute specified will be
assigned the default value of 1.
:param hyperedges: iterable container to references of the node sets
:param attr_dict: dictionary of attributes shared by all
the hyperedges being added.
:param attr: keyword arguments of attributes of the hyperedges;
attr's values will override attr_dict's values
if both are provided.
:returns: list -- the IDs of the hyperedges added in the order
specified by the hyperedges container's iterator.
See also:
add_hyperedge
Examples:
::
>>> H = UndirectedHypergraph()
>>> hyperedge_list = (["A", "B", "C"],
("A", "D"),
set(["B", "D"]))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
hyperedge_ids = []
for nodes in hyperedges:
hyperedge_id = self.add_hyperedge(nodes, attr_dict.copy())
hyperedge_ids.append(hyperedge_id)
return hyperedge_ids
|
python
|
def add_hyperedges(self, hyperedges, attr_dict=None, **attr):
"""Adds multiple hyperedges to the graph, along with any related
attributes of the hyperedges.
If any node of a hyperedge has not previously been added to the
hypergraph, it will automatically be added here.
Hyperedges without a "weight" attribute specified will be
assigned the default value of 1.
:param hyperedges: iterable container to references of the node sets
:param attr_dict: dictionary of attributes shared by all
the hyperedges being added.
:param attr: keyword arguments of attributes of the hyperedges;
attr's values will override attr_dict's values
if both are provided.
:returns: list -- the IDs of the hyperedges added in the order
specified by the hyperedges container's iterator.
See also:
add_hyperedge
Examples:
::
>>> H = UndirectedHypergraph()
>>> hyperedge_list = (["A", "B", "C"],
("A", "D"),
set(["B", "D"]))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
hyperedge_ids = []
for nodes in hyperedges:
hyperedge_id = self.add_hyperedge(nodes, attr_dict.copy())
hyperedge_ids.append(hyperedge_id)
return hyperedge_ids
|
[
"def",
"add_hyperedges",
"(",
"self",
",",
"hyperedges",
",",
"attr_dict",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"attr_dict",
"=",
"self",
".",
"_combine_attribute_arguments",
"(",
"attr_dict",
",",
"attr",
")",
"hyperedge_ids",
"=",
"[",
"]",
"for",
"nodes",
"in",
"hyperedges",
":",
"hyperedge_id",
"=",
"self",
".",
"add_hyperedge",
"(",
"nodes",
",",
"attr_dict",
".",
"copy",
"(",
")",
")",
"hyperedge_ids",
".",
"append",
"(",
"hyperedge_id",
")",
"return",
"hyperedge_ids"
] |
Adds multiple hyperedges to the graph, along with any related
attributes of the hyperedges.
If any node of a hyperedge has not previously been added to the
hypergraph, it will automatically be added here.
Hyperedges without a "weight" attribute specified will be
assigned the default value of 1.
:param hyperedges: iterable container to references of the node sets
:param attr_dict: dictionary of attributes shared by all
the hyperedges being added.
:param attr: keyword arguments of attributes of the hyperedges;
attr's values will override attr_dict's values
if both are provided.
:returns: list -- the IDs of the hyperedges added in the order
specified by the hyperedges container's iterator.
See also:
add_hyperedge
Examples:
::
>>> H = UndirectedHypergraph()
>>> hyperedge_list = (["A", "B", "C"],
("A", "D"),
set(["B", "D"]))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
|
[
"Adds",
"multiple",
"hyperedges",
"to",
"the",
"graph",
"along",
"with",
"any",
"related",
"attributes",
"of",
"the",
"hyperedges",
".",
"If",
"any",
"node",
"of",
"a",
"hyperedge",
"has",
"not",
"previously",
"been",
"added",
"to",
"the",
"hypergraph",
"it",
"will",
"automatically",
"be",
"added",
"here",
".",
"Hyperedges",
"without",
"a",
"weight",
"attribute",
"specified",
"will",
"be",
"assigned",
"the",
"default",
"value",
"of",
"1",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/undirected_hypergraph.py#L449-L487
|
13,949
|
Murali-group/halp
|
halp/undirected_hypergraph.py
|
UndirectedHypergraph.get_hyperedge_id
|
def get_hyperedge_id(self, nodes):
"""From a set of nodes, returns the ID of the hyperedge that this
set comprises.
:param nodes: iterable container of references to nodes in the
the hyperedge to be added
:returns: str -- ID of the hyperedge that has that the specified
node set comprises.
:raises: ValueError -- No such hyperedge exists.
Examples:
::
>>> H = UndirectedHypergraph()
>>> hyperedge_list = (["A", "B", "C"],
("A", "D"),
set(["B", "D"]))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
>>> x = H.get_hyperedge_id(["A", "B", "C"])
"""
frozen_nodes = frozenset(nodes)
if not self.has_hyperedge(frozen_nodes):
raise ValueError("No such hyperedge exists.")
return self._node_set_to_hyperedge[frozen_nodes]
|
python
|
def get_hyperedge_id(self, nodes):
"""From a set of nodes, returns the ID of the hyperedge that this
set comprises.
:param nodes: iterable container of references to nodes in the
the hyperedge to be added
:returns: str -- ID of the hyperedge that has that the specified
node set comprises.
:raises: ValueError -- No such hyperedge exists.
Examples:
::
>>> H = UndirectedHypergraph()
>>> hyperedge_list = (["A", "B", "C"],
("A", "D"),
set(["B", "D"]))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
>>> x = H.get_hyperedge_id(["A", "B", "C"])
"""
frozen_nodes = frozenset(nodes)
if not self.has_hyperedge(frozen_nodes):
raise ValueError("No such hyperedge exists.")
return self._node_set_to_hyperedge[frozen_nodes]
|
[
"def",
"get_hyperedge_id",
"(",
"self",
",",
"nodes",
")",
":",
"frozen_nodes",
"=",
"frozenset",
"(",
"nodes",
")",
"if",
"not",
"self",
".",
"has_hyperedge",
"(",
"frozen_nodes",
")",
":",
"raise",
"ValueError",
"(",
"\"No such hyperedge exists.\"",
")",
"return",
"self",
".",
"_node_set_to_hyperedge",
"[",
"frozen_nodes",
"]"
] |
From a set of nodes, returns the ID of the hyperedge that this
set comprises.
:param nodes: iterable container of references to nodes in the
the hyperedge to be added
:returns: str -- ID of the hyperedge that has that the specified
node set comprises.
:raises: ValueError -- No such hyperedge exists.
Examples:
::
>>> H = UndirectedHypergraph()
>>> hyperedge_list = (["A", "B", "C"],
("A", "D"),
set(["B", "D"]))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
>>> x = H.get_hyperedge_id(["A", "B", "C"])
|
[
"From",
"a",
"set",
"of",
"nodes",
"returns",
"the",
"ID",
"of",
"the",
"hyperedge",
"that",
"this",
"set",
"comprises",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/undirected_hypergraph.py#L592-L618
|
13,950
|
Murali-group/halp
|
halp/undirected_hypergraph.py
|
UndirectedHypergraph.get_hyperedge_attribute
|
def get_hyperedge_attribute(self, hyperedge_id, attribute_name):
# Note: Code unchanged from DirectedHypergraph
"""Given a hyperedge ID and the name of an attribute, get a copy
of that hyperedge's attribute.
:param hyperedge_id: ID of the hyperedge to retrieve the attribute of.
:param attribute_name: name of the attribute to retrieve.
:returns: attribute value of the attribute_name key for the
specified hyperedge.
:raises: ValueError -- No such hyperedge exists.
:raises: ValueError -- No such attribute exists.
Examples:
::
>>> H = UndirectedHypergraph()
>>> hyperedge_list = (["A", "B", "C"],
("A", "D"),
set(["B", "D"]))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
>>> attribute = H.get_hyperedge_attribute(hyperedge_ids[0])
"""
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
elif attribute_name not in self._hyperedge_attributes[hyperedge_id]:
raise ValueError("No such attribute exists.")
else:
return copy.\
copy(self._hyperedge_attributes[hyperedge_id][attribute_name])
|
python
|
def get_hyperedge_attribute(self, hyperedge_id, attribute_name):
# Note: Code unchanged from DirectedHypergraph
"""Given a hyperedge ID and the name of an attribute, get a copy
of that hyperedge's attribute.
:param hyperedge_id: ID of the hyperedge to retrieve the attribute of.
:param attribute_name: name of the attribute to retrieve.
:returns: attribute value of the attribute_name key for the
specified hyperedge.
:raises: ValueError -- No such hyperedge exists.
:raises: ValueError -- No such attribute exists.
Examples:
::
>>> H = UndirectedHypergraph()
>>> hyperedge_list = (["A", "B", "C"],
("A", "D"),
set(["B", "D"]))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
>>> attribute = H.get_hyperedge_attribute(hyperedge_ids[0])
"""
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
elif attribute_name not in self._hyperedge_attributes[hyperedge_id]:
raise ValueError("No such attribute exists.")
else:
return copy.\
copy(self._hyperedge_attributes[hyperedge_id][attribute_name])
|
[
"def",
"get_hyperedge_attribute",
"(",
"self",
",",
"hyperedge_id",
",",
"attribute_name",
")",
":",
"# Note: Code unchanged from DirectedHypergraph",
"if",
"not",
"self",
".",
"has_hyperedge_id",
"(",
"hyperedge_id",
")",
":",
"raise",
"ValueError",
"(",
"\"No such hyperedge exists.\"",
")",
"elif",
"attribute_name",
"not",
"in",
"self",
".",
"_hyperedge_attributes",
"[",
"hyperedge_id",
"]",
":",
"raise",
"ValueError",
"(",
"\"No such attribute exists.\"",
")",
"else",
":",
"return",
"copy",
".",
"copy",
"(",
"self",
".",
"_hyperedge_attributes",
"[",
"hyperedge_id",
"]",
"[",
"attribute_name",
"]",
")"
] |
Given a hyperedge ID and the name of an attribute, get a copy
of that hyperedge's attribute.
:param hyperedge_id: ID of the hyperedge to retrieve the attribute of.
:param attribute_name: name of the attribute to retrieve.
:returns: attribute value of the attribute_name key for the
specified hyperedge.
:raises: ValueError -- No such hyperedge exists.
:raises: ValueError -- No such attribute exists.
Examples:
::
>>> H = UndirectedHypergraph()
>>> hyperedge_list = (["A", "B", "C"],
("A", "D"),
set(["B", "D"]))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
>>> attribute = H.get_hyperedge_attribute(hyperedge_ids[0])
|
[
"Given",
"a",
"hyperedge",
"ID",
"and",
"the",
"name",
"of",
"an",
"attribute",
"get",
"a",
"copy",
"of",
"that",
"hyperedge",
"s",
"attribute",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/undirected_hypergraph.py#L620-L649
|
13,951
|
Murali-group/halp
|
halp/undirected_hypergraph.py
|
UndirectedHypergraph.get_hyperedge_attributes
|
def get_hyperedge_attributes(self, hyperedge_id):
"""Given a hyperedge ID, get a dictionary of copies of that hyperedge's
attributes.
:param hyperedge_id: ID of the hyperedge to retrieve the attributes of.
:returns: dict -- copy of each attribute of the specified hyperedge_id
(except the private __frozen_nodes entry).
:raises: ValueError -- No such hyperedge exists.
"""
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
dict_to_copy = self._hyperedge_attributes[hyperedge_id].items()
attributes = {}
for attr_name, attr_value in dict_to_copy:
if attr_name != "__frozen_nodes":
attributes[attr_name] = copy.copy(attr_value)
return attributes
|
python
|
def get_hyperedge_attributes(self, hyperedge_id):
"""Given a hyperedge ID, get a dictionary of copies of that hyperedge's
attributes.
:param hyperedge_id: ID of the hyperedge to retrieve the attributes of.
:returns: dict -- copy of each attribute of the specified hyperedge_id
(except the private __frozen_nodes entry).
:raises: ValueError -- No such hyperedge exists.
"""
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
dict_to_copy = self._hyperedge_attributes[hyperedge_id].items()
attributes = {}
for attr_name, attr_value in dict_to_copy:
if attr_name != "__frozen_nodes":
attributes[attr_name] = copy.copy(attr_value)
return attributes
|
[
"def",
"get_hyperedge_attributes",
"(",
"self",
",",
"hyperedge_id",
")",
":",
"if",
"not",
"self",
".",
"has_hyperedge_id",
"(",
"hyperedge_id",
")",
":",
"raise",
"ValueError",
"(",
"\"No such hyperedge exists.\"",
")",
"dict_to_copy",
"=",
"self",
".",
"_hyperedge_attributes",
"[",
"hyperedge_id",
"]",
".",
"items",
"(",
")",
"attributes",
"=",
"{",
"}",
"for",
"attr_name",
",",
"attr_value",
"in",
"dict_to_copy",
":",
"if",
"attr_name",
"!=",
"\"__frozen_nodes\"",
":",
"attributes",
"[",
"attr_name",
"]",
"=",
"copy",
".",
"copy",
"(",
"attr_value",
")",
"return",
"attributes"
] |
Given a hyperedge ID, get a dictionary of copies of that hyperedge's
attributes.
:param hyperedge_id: ID of the hyperedge to retrieve the attributes of.
:returns: dict -- copy of each attribute of the specified hyperedge_id
(except the private __frozen_nodes entry).
:raises: ValueError -- No such hyperedge exists.
|
[
"Given",
"a",
"hyperedge",
"ID",
"get",
"a",
"dictionary",
"of",
"copies",
"of",
"that",
"hyperedge",
"s",
"attributes",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/undirected_hypergraph.py#L651-L668
|
13,952
|
Murali-group/halp
|
halp/undirected_hypergraph.py
|
UndirectedHypergraph.get_star
|
def get_star(self, node):
"""Given a node, get a copy of that node's star, that is, the set of
hyperedges that the node belongs to.
:param node: node to retrieve the star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's star.
:raises: ValueError -- No such node exists.
"""
if node not in self._node_attributes:
raise ValueError("No such node exists.")
return self._star[node].copy()
|
python
|
def get_star(self, node):
"""Given a node, get a copy of that node's star, that is, the set of
hyperedges that the node belongs to.
:param node: node to retrieve the star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's star.
:raises: ValueError -- No such node exists.
"""
if node not in self._node_attributes:
raise ValueError("No such node exists.")
return self._star[node].copy()
|
[
"def",
"get_star",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"not",
"in",
"self",
".",
"_node_attributes",
":",
"raise",
"ValueError",
"(",
"\"No such node exists.\"",
")",
"return",
"self",
".",
"_star",
"[",
"node",
"]",
".",
"copy",
"(",
")"
] |
Given a node, get a copy of that node's star, that is, the set of
hyperedges that the node belongs to.
:param node: node to retrieve the star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's star.
:raises: ValueError -- No such node exists.
|
[
"Given",
"a",
"node",
"get",
"a",
"copy",
"of",
"that",
"node",
"s",
"star",
"that",
"is",
"the",
"set",
"of",
"hyperedges",
"that",
"the",
"node",
"belongs",
"to",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/undirected_hypergraph.py#L691-L703
|
13,953
|
Murali-group/halp
|
halp/utilities/directed_statistics.py
|
_F_outdegree
|
def _F_outdegree(H, F):
"""Returns the result of a function F applied to the set of outdegrees in
in the hypergraph.
:param H: the hypergraph whose outdegrees will be operated on.
:param F: function to execute on the list of outdegrees in the hypergraph.
:returns: result of the given function F.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
"""
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return F([len(H.get_forward_star(node))
for node in H.get_node_set()])
|
python
|
def _F_outdegree(H, F):
"""Returns the result of a function F applied to the set of outdegrees in
in the hypergraph.
:param H: the hypergraph whose outdegrees will be operated on.
:param F: function to execute on the list of outdegrees in the hypergraph.
:returns: result of the given function F.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
"""
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return F([len(H.get_forward_star(node))
for node in H.get_node_set()])
|
[
"def",
"_F_outdegree",
"(",
"H",
",",
"F",
")",
":",
"if",
"not",
"isinstance",
"(",
"H",
",",
"DirectedHypergraph",
")",
":",
"raise",
"TypeError",
"(",
"\"Algorithm only applicable to directed hypergraphs\"",
")",
"return",
"F",
"(",
"[",
"len",
"(",
"H",
".",
"get_forward_star",
"(",
"node",
")",
")",
"for",
"node",
"in",
"H",
".",
"get_node_set",
"(",
")",
"]",
")"
] |
Returns the result of a function F applied to the set of outdegrees in
in the hypergraph.
:param H: the hypergraph whose outdegrees will be operated on.
:param F: function to execute on the list of outdegrees in the hypergraph.
:returns: result of the given function F.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
|
[
"Returns",
"the",
"result",
"of",
"a",
"function",
"F",
"applied",
"to",
"the",
"set",
"of",
"outdegrees",
"in",
"in",
"the",
"hypergraph",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/directed_statistics.py#L40-L54
|
13,954
|
Murali-group/halp
|
halp/utilities/directed_statistics.py
|
_F_indegree
|
def _F_indegree(H, F):
"""Returns the result of a function F applied to the list of indegrees in
in the hypergraph.
:param H: the hypergraph whose indegrees will be operated on.
:param F: function to execute on the list of indegrees in the hypergraph.
:returns: result of the given function F.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
"""
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return F([len(H.get_backward_star(node))
for node in H.get_node_set()])
|
python
|
def _F_indegree(H, F):
"""Returns the result of a function F applied to the list of indegrees in
in the hypergraph.
:param H: the hypergraph whose indegrees will be operated on.
:param F: function to execute on the list of indegrees in the hypergraph.
:returns: result of the given function F.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
"""
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return F([len(H.get_backward_star(node))
for node in H.get_node_set()])
|
[
"def",
"_F_indegree",
"(",
"H",
",",
"F",
")",
":",
"if",
"not",
"isinstance",
"(",
"H",
",",
"DirectedHypergraph",
")",
":",
"raise",
"TypeError",
"(",
"\"Algorithm only applicable to directed hypergraphs\"",
")",
"return",
"F",
"(",
"[",
"len",
"(",
"H",
".",
"get_backward_star",
"(",
"node",
")",
")",
"for",
"node",
"in",
"H",
".",
"get_node_set",
"(",
")",
"]",
")"
] |
Returns the result of a function F applied to the list of indegrees in
in the hypergraph.
:param H: the hypergraph whose indegrees will be operated on.
:param F: function to execute on the list of indegrees in the hypergraph.
:returns: result of the given function F.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
|
[
"Returns",
"the",
"result",
"of",
"a",
"function",
"F",
"applied",
"to",
"the",
"list",
"of",
"indegrees",
"in",
"in",
"the",
"hypergraph",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/directed_statistics.py#L105-L119
|
13,955
|
Murali-group/halp
|
halp/utilities/directed_statistics.py
|
_F_hyperedge_tail_cardinality
|
def _F_hyperedge_tail_cardinality(H, F):
"""Returns the result of a function F applied to the set of cardinalities
of hyperedge tails in the hypergraph.
:param H: the hypergraph whose tail cardinalities will be
operated on.
:param F: function to execute on the set of cardinalities in the
hypergraph.
:returns: result of the given function F.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
"""
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return F([len(H.get_hyperedge_tail(hyperedge_id))
for hyperedge_id in H.get_hyperedge_id_set()])
|
python
|
def _F_hyperedge_tail_cardinality(H, F):
"""Returns the result of a function F applied to the set of cardinalities
of hyperedge tails in the hypergraph.
:param H: the hypergraph whose tail cardinalities will be
operated on.
:param F: function to execute on the set of cardinalities in the
hypergraph.
:returns: result of the given function F.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
"""
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return F([len(H.get_hyperedge_tail(hyperedge_id))
for hyperedge_id in H.get_hyperedge_id_set()])
|
[
"def",
"_F_hyperedge_tail_cardinality",
"(",
"H",
",",
"F",
")",
":",
"if",
"not",
"isinstance",
"(",
"H",
",",
"DirectedHypergraph",
")",
":",
"raise",
"TypeError",
"(",
"\"Algorithm only applicable to directed hypergraphs\"",
")",
"return",
"F",
"(",
"[",
"len",
"(",
"H",
".",
"get_hyperedge_tail",
"(",
"hyperedge_id",
")",
")",
"for",
"hyperedge_id",
"in",
"H",
".",
"get_hyperedge_id_set",
"(",
")",
"]",
")"
] |
Returns the result of a function F applied to the set of cardinalities
of hyperedge tails in the hypergraph.
:param H: the hypergraph whose tail cardinalities will be
operated on.
:param F: function to execute on the set of cardinalities in the
hypergraph.
:returns: result of the given function F.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
|
[
"Returns",
"the",
"result",
"of",
"a",
"function",
"F",
"applied",
"to",
"the",
"set",
"of",
"cardinalities",
"of",
"hyperedge",
"tails",
"in",
"the",
"hypergraph",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/directed_statistics.py#L170-L186
|
13,956
|
Murali-group/halp
|
halp/utilities/directed_statistics.py
|
_F_hyperedge_head_cardinality
|
def _F_hyperedge_head_cardinality(H, F):
"""Returns the result of a function F applied to the set of cardinalities
of hyperedge heads in the hypergraph.
:param H: the hypergraph whose head cardinalities will be
operated on.
:param F: function to execute on the set of cardinalities in the
hypergraph.
:returns: result of the given function F.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
"""
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return F([len(H.get_hyperedge_head(hyperedge_id))
for hyperedge_id in H.get_hyperedge_id_set()])
|
python
|
def _F_hyperedge_head_cardinality(H, F):
"""Returns the result of a function F applied to the set of cardinalities
of hyperedge heads in the hypergraph.
:param H: the hypergraph whose head cardinalities will be
operated on.
:param F: function to execute on the set of cardinalities in the
hypergraph.
:returns: result of the given function F.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
"""
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return F([len(H.get_hyperedge_head(hyperedge_id))
for hyperedge_id in H.get_hyperedge_id_set()])
|
[
"def",
"_F_hyperedge_head_cardinality",
"(",
"H",
",",
"F",
")",
":",
"if",
"not",
"isinstance",
"(",
"H",
",",
"DirectedHypergraph",
")",
":",
"raise",
"TypeError",
"(",
"\"Algorithm only applicable to directed hypergraphs\"",
")",
"return",
"F",
"(",
"[",
"len",
"(",
"H",
".",
"get_hyperedge_head",
"(",
"hyperedge_id",
")",
")",
"for",
"hyperedge_id",
"in",
"H",
".",
"get_hyperedge_id_set",
"(",
")",
"]",
")"
] |
Returns the result of a function F applied to the set of cardinalities
of hyperedge heads in the hypergraph.
:param H: the hypergraph whose head cardinalities will be
operated on.
:param F: function to execute on the set of cardinalities in the
hypergraph.
:returns: result of the given function F.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
|
[
"Returns",
"the",
"result",
"of",
"a",
"function",
"F",
"applied",
"to",
"the",
"set",
"of",
"cardinalities",
"of",
"hyperedge",
"heads",
"in",
"the",
"hypergraph",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/directed_statistics.py#L240-L256
|
13,957
|
Murali-group/halp
|
halp/utilities/undirected_matrices.py
|
get_hyperedge_weight_matrix
|
def get_hyperedge_weight_matrix(H, hyperedge_ids_to_indices):
"""Creates the diagonal matrix W of hyperedge weights as a sparse matrix.
:param H: the hypergraph to find the weights.
:param hyperedge_weights: the mapping from the indices of hyperedge IDs to
the corresponding hyperedge weights.
:returns: sparse.csc_matrix -- the diagonal edge weight matrix as a
sparse matrix.
"""
# Combined 2 methods into 1; this could be written better
hyperedge_weights = {}
for hyperedge_id in H.hyperedge_id_iterator():
hyperedge_weights.update({hyperedge_ids_to_indices[hyperedge_id]:
H.get_hyperedge_weight(hyperedge_id)})
hyperedge_weight_vector = []
for i in range(len(hyperedge_weights.keys())):
hyperedge_weight_vector.append(hyperedge_weights.get(i))
return sparse.diags([hyperedge_weight_vector], [0])
|
python
|
def get_hyperedge_weight_matrix(H, hyperedge_ids_to_indices):
"""Creates the diagonal matrix W of hyperedge weights as a sparse matrix.
:param H: the hypergraph to find the weights.
:param hyperedge_weights: the mapping from the indices of hyperedge IDs to
the corresponding hyperedge weights.
:returns: sparse.csc_matrix -- the diagonal edge weight matrix as a
sparse matrix.
"""
# Combined 2 methods into 1; this could be written better
hyperedge_weights = {}
for hyperedge_id in H.hyperedge_id_iterator():
hyperedge_weights.update({hyperedge_ids_to_indices[hyperedge_id]:
H.get_hyperedge_weight(hyperedge_id)})
hyperedge_weight_vector = []
for i in range(len(hyperedge_weights.keys())):
hyperedge_weight_vector.append(hyperedge_weights.get(i))
return sparse.diags([hyperedge_weight_vector], [0])
|
[
"def",
"get_hyperedge_weight_matrix",
"(",
"H",
",",
"hyperedge_ids_to_indices",
")",
":",
"# Combined 2 methods into 1; this could be written better",
"hyperedge_weights",
"=",
"{",
"}",
"for",
"hyperedge_id",
"in",
"H",
".",
"hyperedge_id_iterator",
"(",
")",
":",
"hyperedge_weights",
".",
"update",
"(",
"{",
"hyperedge_ids_to_indices",
"[",
"hyperedge_id",
"]",
":",
"H",
".",
"get_hyperedge_weight",
"(",
"hyperedge_id",
")",
"}",
")",
"hyperedge_weight_vector",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"hyperedge_weights",
".",
"keys",
"(",
")",
")",
")",
":",
"hyperedge_weight_vector",
".",
"append",
"(",
"hyperedge_weights",
".",
"get",
"(",
"i",
")",
")",
"return",
"sparse",
".",
"diags",
"(",
"[",
"hyperedge_weight_vector",
"]",
",",
"[",
"0",
"]",
")"
] |
Creates the diagonal matrix W of hyperedge weights as a sparse matrix.
:param H: the hypergraph to find the weights.
:param hyperedge_weights: the mapping from the indices of hyperedge IDs to
the corresponding hyperedge weights.
:returns: sparse.csc_matrix -- the diagonal edge weight matrix as a
sparse matrix.
|
[
"Creates",
"the",
"diagonal",
"matrix",
"W",
"of",
"hyperedge",
"weights",
"as",
"a",
"sparse",
"matrix",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/undirected_matrices.py#L103-L123
|
13,958
|
Murali-group/halp
|
halp/utilities/undirected_matrices.py
|
get_hyperedge_degree_matrix
|
def get_hyperedge_degree_matrix(M):
"""Creates the diagonal matrix of hyperedge degrees D_e as a sparse matrix,
where a hyperedge degree is the cardinality of the hyperedge.
:param M: the incidence matrix of the hypergraph to find the D_e matrix on.
:returns: sparse.csc_matrix -- the diagonal hyperedge degree matrix as a
sparse matrix.
"""
degrees = M.sum(0).transpose()
new_degree = []
for degree in degrees:
new_degree.append(int(degree[0:]))
return sparse.diags([new_degree], [0])
|
python
|
def get_hyperedge_degree_matrix(M):
"""Creates the diagonal matrix of hyperedge degrees D_e as a sparse matrix,
where a hyperedge degree is the cardinality of the hyperedge.
:param M: the incidence matrix of the hypergraph to find the D_e matrix on.
:returns: sparse.csc_matrix -- the diagonal hyperedge degree matrix as a
sparse matrix.
"""
degrees = M.sum(0).transpose()
new_degree = []
for degree in degrees:
new_degree.append(int(degree[0:]))
return sparse.diags([new_degree], [0])
|
[
"def",
"get_hyperedge_degree_matrix",
"(",
"M",
")",
":",
"degrees",
"=",
"M",
".",
"sum",
"(",
"0",
")",
".",
"transpose",
"(",
")",
"new_degree",
"=",
"[",
"]",
"for",
"degree",
"in",
"degrees",
":",
"new_degree",
".",
"append",
"(",
"int",
"(",
"degree",
"[",
"0",
":",
"]",
")",
")",
"return",
"sparse",
".",
"diags",
"(",
"[",
"new_degree",
"]",
",",
"[",
"0",
"]",
")"
] |
Creates the diagonal matrix of hyperedge degrees D_e as a sparse matrix,
where a hyperedge degree is the cardinality of the hyperedge.
:param M: the incidence matrix of the hypergraph to find the D_e matrix on.
:returns: sparse.csc_matrix -- the diagonal hyperedge degree matrix as a
sparse matrix.
|
[
"Creates",
"the",
"diagonal",
"matrix",
"of",
"hyperedge",
"degrees",
"D_e",
"as",
"a",
"sparse",
"matrix",
"where",
"a",
"hyperedge",
"degree",
"is",
"the",
"cardinality",
"of",
"the",
"hyperedge",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/undirected_matrices.py#L126-L140
|
13,959
|
Murali-group/halp
|
halp/utilities/undirected_matrices.py
|
fast_inverse
|
def fast_inverse(M):
"""Computes the inverse of a diagonal matrix.
:param H: the diagonal matrix to find the inverse of.
:returns: sparse.csc_matrix -- the inverse of the input matrix as a
sparse matrix.
"""
diags = M.diagonal()
new_diag = []
for value in diags:
new_diag.append(1.0/value)
return sparse.diags([new_diag], [0])
|
python
|
def fast_inverse(M):
"""Computes the inverse of a diagonal matrix.
:param H: the diagonal matrix to find the inverse of.
:returns: sparse.csc_matrix -- the inverse of the input matrix as a
sparse matrix.
"""
diags = M.diagonal()
new_diag = []
for value in diags:
new_diag.append(1.0/value)
return sparse.diags([new_diag], [0])
|
[
"def",
"fast_inverse",
"(",
"M",
")",
":",
"diags",
"=",
"M",
".",
"diagonal",
"(",
")",
"new_diag",
"=",
"[",
"]",
"for",
"value",
"in",
"diags",
":",
"new_diag",
".",
"append",
"(",
"1.0",
"/",
"value",
")",
"return",
"sparse",
".",
"diags",
"(",
"[",
"new_diag",
"]",
",",
"[",
"0",
"]",
")"
] |
Computes the inverse of a diagonal matrix.
:param H: the diagonal matrix to find the inverse of.
:returns: sparse.csc_matrix -- the inverse of the input matrix as a
sparse matrix.
|
[
"Computes",
"the",
"inverse",
"of",
"a",
"diagonal",
"matrix",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/undirected_matrices.py#L143-L156
|
13,960
|
Murali-group/halp
|
halp/signaling_hypergraph.py
|
node_iterator
|
def node_iterator(self):
"""Provides an iterator over the nodes.
"""
return iter(self._node_attributes)
def has_hypernode(self, hypernode):
"""Determines if a specific hypernode is present in the hypergraph.
:param node: reference to hypernode whose presence is being checked.
:returns: bool -- true iff the node exists in the hypergraph.
"""
return hypernode in self._hypernode_attributes
|
python
|
def node_iterator(self):
"""Provides an iterator over the nodes.
"""
return iter(self._node_attributes)
def has_hypernode(self, hypernode):
"""Determines if a specific hypernode is present in the hypergraph.
:param node: reference to hypernode whose presence is being checked.
:returns: bool -- true iff the node exists in the hypergraph.
"""
return hypernode in self._hypernode_attributes
|
[
"def",
"node_iterator",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"self",
".",
"_node_attributes",
")",
"def",
"has_hypernode",
"(",
"self",
",",
"hypernode",
")",
":",
"\"\"\"Determines if a specific hypernode is present in the hypergraph.\n\n :param node: reference to hypernode whose presence is being checked.\n :returns: bool -- true iff the node exists in the hypergraph.\n\n \"\"\"",
"return",
"hypernode",
"in",
"self",
".",
"_hypernode_attributes"
] |
Provides an iterator over the nodes.
|
[
"Provides",
"an",
"iterator",
"over",
"the",
"nodes",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/signaling_hypergraph.py#L243-L256
|
13,961
|
Murali-group/halp
|
halp/signaling_hypergraph.py
|
add_hypernode
|
def add_hypernode(self, hypernode, composing_nodes=set(), attr_dict=None, **attr):
"""Adds a hypernode to the graph, along with any related attributes
of the hypernode.
:param hypernode: reference to the hypernode being added.
:param nodes: reference to the set of nodes that compose
the hypernode.
:param in_hypernodes: set of references to the hypernodes that the
node being added is a member of.
:param attr_dict: dictionary of attributes of the node.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# If the hypernode hasn't previously been added, add it along
# with its attributes
if not self.has_hypernode(hypernode):
attr_dict["__composing_nodes"] = composing_nodes
added_nodes = composing_nodes
removed_nodes = set()
self._hypernode_attributes[hypernode] = attr_dict
# Otherwise, just update the hypernode's attributes
else:
self._hypernode_attributes[hypernode].update(attr_dict)
added_nodes = composing_nodes - self._hypernode_attributes\
[hypernode]["__composing_nodes"]
removed_nodes = self._hypernode_attributes\
[hypernode]["__composing_nodes"] - composing_nodes
# For every "composing node" added to this hypernode, update
# those nodes attributes to be members of this hypernode
for node in added_nodes:
_add_hypernode_membership(node, hypernode)
# For every "composing node" added to this hypernode, update
# those nodes attributes to no longer be members of this hypernode
for node in remove_nodes:
_remove_hypernode_membership(node, hypernode)
|
python
|
def add_hypernode(self, hypernode, composing_nodes=set(), attr_dict=None, **attr):
"""Adds a hypernode to the graph, along with any related attributes
of the hypernode.
:param hypernode: reference to the hypernode being added.
:param nodes: reference to the set of nodes that compose
the hypernode.
:param in_hypernodes: set of references to the hypernodes that the
node being added is a member of.
:param attr_dict: dictionary of attributes of the node.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# If the hypernode hasn't previously been added, add it along
# with its attributes
if not self.has_hypernode(hypernode):
attr_dict["__composing_nodes"] = composing_nodes
added_nodes = composing_nodes
removed_nodes = set()
self._hypernode_attributes[hypernode] = attr_dict
# Otherwise, just update the hypernode's attributes
else:
self._hypernode_attributes[hypernode].update(attr_dict)
added_nodes = composing_nodes - self._hypernode_attributes\
[hypernode]["__composing_nodes"]
removed_nodes = self._hypernode_attributes\
[hypernode]["__composing_nodes"] - composing_nodes
# For every "composing node" added to this hypernode, update
# those nodes attributes to be members of this hypernode
for node in added_nodes:
_add_hypernode_membership(node, hypernode)
# For every "composing node" added to this hypernode, update
# those nodes attributes to no longer be members of this hypernode
for node in remove_nodes:
_remove_hypernode_membership(node, hypernode)
|
[
"def",
"add_hypernode",
"(",
"self",
",",
"hypernode",
",",
"composing_nodes",
"=",
"set",
"(",
")",
",",
"attr_dict",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"attr_dict",
"=",
"self",
".",
"_combine_attribute_arguments",
"(",
"attr_dict",
",",
"attr",
")",
"# If the hypernode hasn't previously been added, add it along",
"# with its attributes",
"if",
"not",
"self",
".",
"has_hypernode",
"(",
"hypernode",
")",
":",
"attr_dict",
"[",
"\"__composing_nodes\"",
"]",
"=",
"composing_nodes",
"added_nodes",
"=",
"composing_nodes",
"removed_nodes",
"=",
"set",
"(",
")",
"self",
".",
"_hypernode_attributes",
"[",
"hypernode",
"]",
"=",
"attr_dict",
"# Otherwise, just update the hypernode's attributes",
"else",
":",
"self",
".",
"_hypernode_attributes",
"[",
"hypernode",
"]",
".",
"update",
"(",
"attr_dict",
")",
"added_nodes",
"=",
"composing_nodes",
"-",
"self",
".",
"_hypernode_attributes",
"[",
"hypernode",
"]",
"[",
"\"__composing_nodes\"",
"]",
"removed_nodes",
"=",
"self",
".",
"_hypernode_attributes",
"[",
"hypernode",
"]",
"[",
"\"__composing_nodes\"",
"]",
"-",
"composing_nodes",
"# For every \"composing node\" added to this hypernode, update",
"# those nodes attributes to be members of this hypernode",
"for",
"node",
"in",
"added_nodes",
":",
"_add_hypernode_membership",
"(",
"node",
",",
"hypernode",
")",
"# For every \"composing node\" added to this hypernode, update",
"# those nodes attributes to no longer be members of this hypernode",
"for",
"node",
"in",
"remove_nodes",
":",
"_remove_hypernode_membership",
"(",
"node",
",",
"hypernode",
")"
] |
Adds a hypernode to the graph, along with any related attributes
of the hypernode.
:param hypernode: reference to the hypernode being added.
:param nodes: reference to the set of nodes that compose
the hypernode.
:param in_hypernodes: set of references to the hypernodes that the
node being added is a member of.
:param attr_dict: dictionary of attributes of the node.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
|
[
"Adds",
"a",
"hypernode",
"to",
"the",
"graph",
"along",
"with",
"any",
"related",
"attributes",
"of",
"the",
"hypernode",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/signaling_hypergraph.py#L305-L344
|
13,962
|
Murali-group/halp
|
halp/algorithms/undirected_partitioning.py
|
_create_random_starter
|
def _create_random_starter(node_count):
"""Creates the random starter for the random walk.
:param node_count: number of nodes to create the random vector.
:returns: list -- list of starting probabilities for each node.
"""
pi = np.zeros(node_count, dtype=float)
for i in range(node_count):
pi[i] = random.random()
summation = np.sum(pi)
for i in range(node_count):
pi[i] = pi[i] / summation
return pi
|
python
|
def _create_random_starter(node_count):
"""Creates the random starter for the random walk.
:param node_count: number of nodes to create the random vector.
:returns: list -- list of starting probabilities for each node.
"""
pi = np.zeros(node_count, dtype=float)
for i in range(node_count):
pi[i] = random.random()
summation = np.sum(pi)
for i in range(node_count):
pi[i] = pi[i] / summation
return pi
|
[
"def",
"_create_random_starter",
"(",
"node_count",
")",
":",
"pi",
"=",
"np",
".",
"zeros",
"(",
"node_count",
",",
"dtype",
"=",
"float",
")",
"for",
"i",
"in",
"range",
"(",
"node_count",
")",
":",
"pi",
"[",
"i",
"]",
"=",
"random",
".",
"random",
"(",
")",
"summation",
"=",
"np",
".",
"sum",
"(",
"pi",
")",
"for",
"i",
"in",
"range",
"(",
"node_count",
")",
":",
"pi",
"[",
"i",
"]",
"=",
"pi",
"[",
"i",
"]",
"/",
"summation",
"return",
"pi"
] |
Creates the random starter for the random walk.
:param node_count: number of nodes to create the random vector.
:returns: list -- list of starting probabilities for each node.
|
[
"Creates",
"the",
"random",
"starter",
"for",
"the",
"random",
"walk",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/algorithms/undirected_partitioning.py#L188-L202
|
13,963
|
Murali-group/halp
|
halp/algorithms/undirected_partitioning.py
|
_has_converged
|
def _has_converged(pi_star, pi):
"""Checks if the random walk has converged.
:param pi_star: the new vector
:param pi: the old vector
:returns: bool-- True iff pi has converged.
"""
node_count = pi.shape[0]
EPS = 10e-6
for i in range(node_count):
if pi[i] - pi_star[i] > EPS:
return False
return True
|
python
|
def _has_converged(pi_star, pi):
"""Checks if the random walk has converged.
:param pi_star: the new vector
:param pi: the old vector
:returns: bool-- True iff pi has converged.
"""
node_count = pi.shape[0]
EPS = 10e-6
for i in range(node_count):
if pi[i] - pi_star[i] > EPS:
return False
return True
|
[
"def",
"_has_converged",
"(",
"pi_star",
",",
"pi",
")",
":",
"node_count",
"=",
"pi",
".",
"shape",
"[",
"0",
"]",
"EPS",
"=",
"10e-6",
"for",
"i",
"in",
"range",
"(",
"node_count",
")",
":",
"if",
"pi",
"[",
"i",
"]",
"-",
"pi_star",
"[",
"i",
"]",
">",
"EPS",
":",
"return",
"False",
"return",
"True"
] |
Checks if the random walk has converged.
:param pi_star: the new vector
:param pi: the old vector
:returns: bool-- True iff pi has converged.
|
[
"Checks",
"if",
"the",
"random",
"walk",
"has",
"converged",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/algorithms/undirected_partitioning.py#L205-L219
|
13,964
|
Murali-group/halp
|
halp/utilities/priority_queue.py
|
PriorityQueue.add_element
|
def add_element(self, priority, element, count=None):
"""Adds an element with a specific priority.
:param priority: priority of the element.
:param element: element to add.
"""
if count is None:
count = next(self.counter)
entry = [priority, count, element]
self.element_finder[element] = entry
heapq.heappush(self.pq, entry)
|
python
|
def add_element(self, priority, element, count=None):
"""Adds an element with a specific priority.
:param priority: priority of the element.
:param element: element to add.
"""
if count is None:
count = next(self.counter)
entry = [priority, count, element]
self.element_finder[element] = entry
heapq.heappush(self.pq, entry)
|
[
"def",
"add_element",
"(",
"self",
",",
"priority",
",",
"element",
",",
"count",
"=",
"None",
")",
":",
"if",
"count",
"is",
"None",
":",
"count",
"=",
"next",
"(",
"self",
".",
"counter",
")",
"entry",
"=",
"[",
"priority",
",",
"count",
",",
"element",
"]",
"self",
".",
"element_finder",
"[",
"element",
"]",
"=",
"entry",
"heapq",
".",
"heappush",
"(",
"self",
".",
"pq",
",",
"entry",
")"
] |
Adds an element with a specific priority.
:param priority: priority of the element.
:param element: element to add.
|
[
"Adds",
"an",
"element",
"with",
"a",
"specific",
"priority",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/priority_queue.py#L41-L52
|
13,965
|
Murali-group/halp
|
halp/utilities/priority_queue.py
|
PriorityQueue.reprioritize
|
def reprioritize(self, priority, element):
"""Updates the priority of an element.
:raises: ValueError -- No such element in the priority queue.
"""
if element not in self.element_finder:
raise ValueError("No such element in the priority queue.")
entry = self.element_finder[element]
self.add_element(priority, element, entry[1])
entry[1] = self.INVALID
|
python
|
def reprioritize(self, priority, element):
"""Updates the priority of an element.
:raises: ValueError -- No such element in the priority queue.
"""
if element not in self.element_finder:
raise ValueError("No such element in the priority queue.")
entry = self.element_finder[element]
self.add_element(priority, element, entry[1])
entry[1] = self.INVALID
|
[
"def",
"reprioritize",
"(",
"self",
",",
"priority",
",",
"element",
")",
":",
"if",
"element",
"not",
"in",
"self",
".",
"element_finder",
":",
"raise",
"ValueError",
"(",
"\"No such element in the priority queue.\"",
")",
"entry",
"=",
"self",
".",
"element_finder",
"[",
"element",
"]",
"self",
".",
"add_element",
"(",
"priority",
",",
"element",
",",
"entry",
"[",
"1",
"]",
")",
"entry",
"[",
"1",
"]",
"=",
"self",
".",
"INVALID"
] |
Updates the priority of an element.
:raises: ValueError -- No such element in the priority queue.
|
[
"Updates",
"the",
"priority",
"of",
"an",
"element",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/priority_queue.py#L79-L89
|
13,966
|
Murali-group/halp
|
halp/utilities/priority_queue.py
|
PriorityQueue.contains_element
|
def contains_element(self, element):
"""Determines if an element is contained in the priority queue."
:returns: bool -- true iff element is in the priority queue.
"""
return (element in self.element_finder) and \
(self.element_finder[element][1] != self.INVALID)
|
python
|
def contains_element(self, element):
"""Determines if an element is contained in the priority queue."
:returns: bool -- true iff element is in the priority queue.
"""
return (element in self.element_finder) and \
(self.element_finder[element][1] != self.INVALID)
|
[
"def",
"contains_element",
"(",
"self",
",",
"element",
")",
":",
"return",
"(",
"element",
"in",
"self",
".",
"element_finder",
")",
"and",
"(",
"self",
".",
"element_finder",
"[",
"element",
"]",
"[",
"1",
"]",
"!=",
"self",
".",
"INVALID",
")"
] |
Determines if an element is contained in the priority queue."
:returns: bool -- true iff element is in the priority queue.
|
[
"Determines",
"if",
"an",
"element",
"is",
"contained",
"in",
"the",
"priority",
"queue",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/priority_queue.py#L102-L109
|
13,967
|
Murali-group/halp
|
halp/utilities/priority_queue.py
|
PriorityQueue.is_empty
|
def is_empty(self):
"""Determines if the priority queue has any elements.
Performs removal of any elements that were "marked-as-invalid".
:returns: true iff the priority queue has no elements.
"""
while self.pq:
if self.pq[0][1] != self.INVALID:
return False
else:
_, _, element = heapq.heappop(self.pq)
if element in self.element_finder:
del self.element_finder[element]
return True
|
python
|
def is_empty(self):
"""Determines if the priority queue has any elements.
Performs removal of any elements that were "marked-as-invalid".
:returns: true iff the priority queue has no elements.
"""
while self.pq:
if self.pq[0][1] != self.INVALID:
return False
else:
_, _, element = heapq.heappop(self.pq)
if element in self.element_finder:
del self.element_finder[element]
return True
|
[
"def",
"is_empty",
"(",
"self",
")",
":",
"while",
"self",
".",
"pq",
":",
"if",
"self",
".",
"pq",
"[",
"0",
"]",
"[",
"1",
"]",
"!=",
"self",
".",
"INVALID",
":",
"return",
"False",
"else",
":",
"_",
",",
"_",
",",
"element",
"=",
"heapq",
".",
"heappop",
"(",
"self",
".",
"pq",
")",
"if",
"element",
"in",
"self",
".",
"element_finder",
":",
"del",
"self",
".",
"element_finder",
"[",
"element",
"]",
"return",
"True"
] |
Determines if the priority queue has any elements.
Performs removal of any elements that were "marked-as-invalid".
:returns: true iff the priority queue has no elements.
|
[
"Determines",
"if",
"the",
"priority",
"queue",
"has",
"any",
"elements",
".",
"Performs",
"removal",
"of",
"any",
"elements",
"that",
"were",
"marked",
"-",
"as",
"-",
"invalid",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/priority_queue.py#L111-L125
|
13,968
|
Murali-group/halp
|
halp/algorithms/directed_paths.py
|
is_connected
|
def is_connected(H, source_node, target_node):
"""Checks if a target node is connected to a source node. That is,
this method determines if a target node can be visited from the source
node in the sense of the 'Visit' algorithm.
Refer to 'visit's documentation for more details.
:param H: the hypergraph to check connectedness on.
:param source_node: the node to check connectedness to.
:param target_node: the node to check connectedness of.
:returns: bool -- whether target_node can be visited from source_node.
"""
visited_nodes, Pv, Pe = visit(H, source_node)
return target_node in visited_nodes
|
python
|
def is_connected(H, source_node, target_node):
"""Checks if a target node is connected to a source node. That is,
this method determines if a target node can be visited from the source
node in the sense of the 'Visit' algorithm.
Refer to 'visit's documentation for more details.
:param H: the hypergraph to check connectedness on.
:param source_node: the node to check connectedness to.
:param target_node: the node to check connectedness of.
:returns: bool -- whether target_node can be visited from source_node.
"""
visited_nodes, Pv, Pe = visit(H, source_node)
return target_node in visited_nodes
|
[
"def",
"is_connected",
"(",
"H",
",",
"source_node",
",",
"target_node",
")",
":",
"visited_nodes",
",",
"Pv",
",",
"Pe",
"=",
"visit",
"(",
"H",
",",
"source_node",
")",
"return",
"target_node",
"in",
"visited_nodes"
] |
Checks if a target node is connected to a source node. That is,
this method determines if a target node can be visited from the source
node in the sense of the 'Visit' algorithm.
Refer to 'visit's documentation for more details.
:param H: the hypergraph to check connectedness on.
:param source_node: the node to check connectedness to.
:param target_node: the node to check connectedness of.
:returns: bool -- whether target_node can be visited from source_node.
|
[
"Checks",
"if",
"a",
"target",
"node",
"is",
"connected",
"to",
"a",
"source",
"node",
".",
"That",
"is",
"this",
"method",
"determines",
"if",
"a",
"target",
"node",
"can",
"be",
"visited",
"from",
"the",
"source",
"node",
"in",
"the",
"sense",
"of",
"the",
"Visit",
"algorithm",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/algorithms/directed_paths.py#L84-L98
|
13,969
|
Murali-group/halp
|
halp/algorithms/directed_paths.py
|
is_b_connected
|
def is_b_connected(H, source_node, target_node):
"""Checks if a target node is B-connected to a source node.
A node t is B-connected to a node s iff:
- t is s, or
- there exists an edge in the backward star of t such that all nodes in
the tail of that edge are B-connected to s
In other words, this method determines if a target node can be B-visited
from the source node in the sense of the 'B-Visit' algorithm. Refer to
'b_visit's documentation for more details.
:param H: the hypergraph to check B-connectedness on.
:param source_node: the node to check B-connectedness to.
:param target_node: the node to check B-connectedness of.
:returns: bool -- whether target_node can be visited from source_node.
"""
b_visited_nodes, Pv, Pe, v = b_visit(H, source_node)
return target_node in b_visited_nodes
|
python
|
def is_b_connected(H, source_node, target_node):
"""Checks if a target node is B-connected to a source node.
A node t is B-connected to a node s iff:
- t is s, or
- there exists an edge in the backward star of t such that all nodes in
the tail of that edge are B-connected to s
In other words, this method determines if a target node can be B-visited
from the source node in the sense of the 'B-Visit' algorithm. Refer to
'b_visit's documentation for more details.
:param H: the hypergraph to check B-connectedness on.
:param source_node: the node to check B-connectedness to.
:param target_node: the node to check B-connectedness of.
:returns: bool -- whether target_node can be visited from source_node.
"""
b_visited_nodes, Pv, Pe, v = b_visit(H, source_node)
return target_node in b_visited_nodes
|
[
"def",
"is_b_connected",
"(",
"H",
",",
"source_node",
",",
"target_node",
")",
":",
"b_visited_nodes",
",",
"Pv",
",",
"Pe",
",",
"v",
"=",
"b_visit",
"(",
"H",
",",
"source_node",
")",
"return",
"target_node",
"in",
"b_visited_nodes"
] |
Checks if a target node is B-connected to a source node.
A node t is B-connected to a node s iff:
- t is s, or
- there exists an edge in the backward star of t such that all nodes in
the tail of that edge are B-connected to s
In other words, this method determines if a target node can be B-visited
from the source node in the sense of the 'B-Visit' algorithm. Refer to
'b_visit's documentation for more details.
:param H: the hypergraph to check B-connectedness on.
:param source_node: the node to check B-connectedness to.
:param target_node: the node to check B-connectedness of.
:returns: bool -- whether target_node can be visited from source_node.
|
[
"Checks",
"if",
"a",
"target",
"node",
"is",
"B",
"-",
"connected",
"to",
"a",
"source",
"node",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/algorithms/directed_paths.py#L215-L234
|
13,970
|
Murali-group/halp
|
halp/algorithms/directed_paths.py
|
is_f_connected
|
def is_f_connected(H, source_node, target_node):
"""Checks if a target node is F-connected to a source node.
A node t is F-connected to a node s iff s if B-connected to t.
Refer to 'f_visit's or 'is_b_connected's documentation for more details.
:param H: the hypergraph to check F-connectedness on.
:param source_node: the node to check F-connectedness to.
:param target_node: the node to check F-connectedness of.
:returns: bool -- whether target_node can be visited from source_node.
"""
f_visited_nodes, Pv, Pe, v = f_visit(H, source_node)
return target_node in f_visited_nodes
|
python
|
def is_f_connected(H, source_node, target_node):
"""Checks if a target node is F-connected to a source node.
A node t is F-connected to a node s iff s if B-connected to t.
Refer to 'f_visit's or 'is_b_connected's documentation for more details.
:param H: the hypergraph to check F-connectedness on.
:param source_node: the node to check F-connectedness to.
:param target_node: the node to check F-connectedness of.
:returns: bool -- whether target_node can be visited from source_node.
"""
f_visited_nodes, Pv, Pe, v = f_visit(H, source_node)
return target_node in f_visited_nodes
|
[
"def",
"is_f_connected",
"(",
"H",
",",
"source_node",
",",
"target_node",
")",
":",
"f_visited_nodes",
",",
"Pv",
",",
"Pe",
",",
"v",
"=",
"f_visit",
"(",
"H",
",",
"source_node",
")",
"return",
"target_node",
"in",
"f_visited_nodes"
] |
Checks if a target node is F-connected to a source node.
A node t is F-connected to a node s iff s if B-connected to t.
Refer to 'f_visit's or 'is_b_connected's documentation for more details.
:param H: the hypergraph to check F-connectedness on.
:param source_node: the node to check F-connectedness to.
:param target_node: the node to check F-connectedness of.
:returns: bool -- whether target_node can be visited from source_node.
|
[
"Checks",
"if",
"a",
"target",
"node",
"is",
"F",
"-",
"connected",
"to",
"a",
"source",
"node",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/algorithms/directed_paths.py#L263-L276
|
13,971
|
Murali-group/halp
|
halp/utilities/undirected_graph_transformations.py
|
from_networkx_graph
|
def from_networkx_graph(nx_graph):
"""Returns an UndirectedHypergraph object that is the graph equivalent of
the given NetworkX Graph object.
:param nx_graph: the NetworkX undirected graph object to transform.
:returns: UndirectedHypergraph -- H object equivalent to the
NetworkX undirected graph.
:raises: TypeError -- Transformation only applicable to undirected
NetworkX graphs
"""
import networkx as nx
if not isinstance(nx_graph, nx.Graph):
raise TypeError("Transformation only applicable to undirected \
NetworkX graphs")
G = UndirectedHypergraph()
for node in nx_graph.nodes_iter():
G.add_node(node, copy.copy(nx_graph.node[node]))
for edge in nx_graph.edges_iter():
G.add_hyperedge([edge[0], edge[1]],
copy.copy(nx_graph[edge[0]][edge[1]]))
return G
|
python
|
def from_networkx_graph(nx_graph):
"""Returns an UndirectedHypergraph object that is the graph equivalent of
the given NetworkX Graph object.
:param nx_graph: the NetworkX undirected graph object to transform.
:returns: UndirectedHypergraph -- H object equivalent to the
NetworkX undirected graph.
:raises: TypeError -- Transformation only applicable to undirected
NetworkX graphs
"""
import networkx as nx
if not isinstance(nx_graph, nx.Graph):
raise TypeError("Transformation only applicable to undirected \
NetworkX graphs")
G = UndirectedHypergraph()
for node in nx_graph.nodes_iter():
G.add_node(node, copy.copy(nx_graph.node[node]))
for edge in nx_graph.edges_iter():
G.add_hyperedge([edge[0], edge[1]],
copy.copy(nx_graph[edge[0]][edge[1]]))
return G
|
[
"def",
"from_networkx_graph",
"(",
"nx_graph",
")",
":",
"import",
"networkx",
"as",
"nx",
"if",
"not",
"isinstance",
"(",
"nx_graph",
",",
"nx",
".",
"Graph",
")",
":",
"raise",
"TypeError",
"(",
"\"Transformation only applicable to undirected \\\n NetworkX graphs\"",
")",
"G",
"=",
"UndirectedHypergraph",
"(",
")",
"for",
"node",
"in",
"nx_graph",
".",
"nodes_iter",
"(",
")",
":",
"G",
".",
"add_node",
"(",
"node",
",",
"copy",
".",
"copy",
"(",
"nx_graph",
".",
"node",
"[",
"node",
"]",
")",
")",
"for",
"edge",
"in",
"nx_graph",
".",
"edges_iter",
"(",
")",
":",
"G",
".",
"add_hyperedge",
"(",
"[",
"edge",
"[",
"0",
"]",
",",
"edge",
"[",
"1",
"]",
"]",
",",
"copy",
".",
"copy",
"(",
"nx_graph",
"[",
"edge",
"[",
"0",
"]",
"]",
"[",
"edge",
"[",
"1",
"]",
"]",
")",
")",
"return",
"G"
] |
Returns an UndirectedHypergraph object that is the graph equivalent of
the given NetworkX Graph object.
:param nx_graph: the NetworkX undirected graph object to transform.
:returns: UndirectedHypergraph -- H object equivalent to the
NetworkX undirected graph.
:raises: TypeError -- Transformation only applicable to undirected
NetworkX graphs
|
[
"Returns",
"an",
"UndirectedHypergraph",
"object",
"that",
"is",
"the",
"graph",
"equivalent",
"of",
"the",
"given",
"NetworkX",
"Graph",
"object",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/undirected_graph_transformations.py#L81-L107
|
13,972
|
Murali-group/halp
|
halp/utilities/directed_graph_transformations.py
|
from_networkx_digraph
|
def from_networkx_digraph(nx_digraph):
"""Returns a DirectedHypergraph object that is the graph equivalent of the
given NetworkX DiGraph object.
:param nx_digraph: the NetworkX directed graph object to transform.
:returns: DirectedHypergraph -- hypergraph object equivalent to the
NetworkX directed graph.
:raises: TypeError -- Transformation only applicable to directed
NetworkX graphs
"""
import networkx as nx
if not isinstance(nx_digraph, nx.DiGraph):
raise TypeError("Transformation only applicable to directed \
NetworkX graphs")
G = DirectedHypergraph()
for node in nx_digraph.nodes_iter():
G.add_node(node, copy.copy(nx_digraph.node[node]))
for edge in nx_digraph.edges_iter():
tail_node = edge[0]
head_node = edge[1]
G.add_hyperedge(tail_node,
head_node,
copy.copy(nx_digraph[tail_node][head_node]))
return G
|
python
|
def from_networkx_digraph(nx_digraph):
"""Returns a DirectedHypergraph object that is the graph equivalent of the
given NetworkX DiGraph object.
:param nx_digraph: the NetworkX directed graph object to transform.
:returns: DirectedHypergraph -- hypergraph object equivalent to the
NetworkX directed graph.
:raises: TypeError -- Transformation only applicable to directed
NetworkX graphs
"""
import networkx as nx
if not isinstance(nx_digraph, nx.DiGraph):
raise TypeError("Transformation only applicable to directed \
NetworkX graphs")
G = DirectedHypergraph()
for node in nx_digraph.nodes_iter():
G.add_node(node, copy.copy(nx_digraph.node[node]))
for edge in nx_digraph.edges_iter():
tail_node = edge[0]
head_node = edge[1]
G.add_hyperedge(tail_node,
head_node,
copy.copy(nx_digraph[tail_node][head_node]))
return G
|
[
"def",
"from_networkx_digraph",
"(",
"nx_digraph",
")",
":",
"import",
"networkx",
"as",
"nx",
"if",
"not",
"isinstance",
"(",
"nx_digraph",
",",
"nx",
".",
"DiGraph",
")",
":",
"raise",
"TypeError",
"(",
"\"Transformation only applicable to directed \\\n NetworkX graphs\"",
")",
"G",
"=",
"DirectedHypergraph",
"(",
")",
"for",
"node",
"in",
"nx_digraph",
".",
"nodes_iter",
"(",
")",
":",
"G",
".",
"add_node",
"(",
"node",
",",
"copy",
".",
"copy",
"(",
"nx_digraph",
".",
"node",
"[",
"node",
"]",
")",
")",
"for",
"edge",
"in",
"nx_digraph",
".",
"edges_iter",
"(",
")",
":",
"tail_node",
"=",
"edge",
"[",
"0",
"]",
"head_node",
"=",
"edge",
"[",
"1",
"]",
"G",
".",
"add_hyperedge",
"(",
"tail_node",
",",
"head_node",
",",
"copy",
".",
"copy",
"(",
"nx_digraph",
"[",
"tail_node",
"]",
"[",
"head_node",
"]",
")",
")",
"return",
"G"
] |
Returns a DirectedHypergraph object that is the graph equivalent of the
given NetworkX DiGraph object.
:param nx_digraph: the NetworkX directed graph object to transform.
:returns: DirectedHypergraph -- hypergraph object equivalent to the
NetworkX directed graph.
:raises: TypeError -- Transformation only applicable to directed
NetworkX graphs
|
[
"Returns",
"a",
"DirectedHypergraph",
"object",
"that",
"is",
"the",
"graph",
"equivalent",
"of",
"the",
"given",
"NetworkX",
"DiGraph",
"object",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/directed_graph_transformations.py#L81-L110
|
13,973
|
Murali-group/halp
|
halp/utilities/directed_matrices.py
|
get_tail_incidence_matrix
|
def get_tail_incidence_matrix(H, nodes_to_indices, hyperedge_ids_to_indices):
"""Creates the incidence matrix of the tail nodes of the given
hypergraph as a sparse matrix.
:param H: the hypergraph for which to create the incidence matrix of.
:param nodes_to_indices: for each node, maps the node to its
corresponding integer index.
:param hyperedge_ids_to_indices: for each hyperedge ID, maps the hyperedge
ID to its corresponding integer index.
:returns: sparse.csc_matrix -- the incidence matrix as a sparse matrix.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
"""
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
rows, cols = [], []
for hyperedge_id, hyperedge_index in hyperedge_ids_to_indices.items():
for node in H.get_hyperedge_tail(hyperedge_id):
# get the mapping between the node and its ID
rows.append(nodes_to_indices.get(node))
cols.append(hyperedge_index)
values = np.ones(len(rows), dtype=int)
node_count = len(H.get_node_set())
hyperedge_count = len(H.get_hyperedge_id_set())
return sparse.csc_matrix((values, (rows, cols)),
shape=(node_count, hyperedge_count))
|
python
|
def get_tail_incidence_matrix(H, nodes_to_indices, hyperedge_ids_to_indices):
"""Creates the incidence matrix of the tail nodes of the given
hypergraph as a sparse matrix.
:param H: the hypergraph for which to create the incidence matrix of.
:param nodes_to_indices: for each node, maps the node to its
corresponding integer index.
:param hyperedge_ids_to_indices: for each hyperedge ID, maps the hyperedge
ID to its corresponding integer index.
:returns: sparse.csc_matrix -- the incidence matrix as a sparse matrix.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
"""
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
rows, cols = [], []
for hyperedge_id, hyperedge_index in hyperedge_ids_to_indices.items():
for node in H.get_hyperedge_tail(hyperedge_id):
# get the mapping between the node and its ID
rows.append(nodes_to_indices.get(node))
cols.append(hyperedge_index)
values = np.ones(len(rows), dtype=int)
node_count = len(H.get_node_set())
hyperedge_count = len(H.get_hyperedge_id_set())
return sparse.csc_matrix((values, (rows, cols)),
shape=(node_count, hyperedge_count))
|
[
"def",
"get_tail_incidence_matrix",
"(",
"H",
",",
"nodes_to_indices",
",",
"hyperedge_ids_to_indices",
")",
":",
"if",
"not",
"isinstance",
"(",
"H",
",",
"DirectedHypergraph",
")",
":",
"raise",
"TypeError",
"(",
"\"Algorithm only applicable to directed hypergraphs\"",
")",
"rows",
",",
"cols",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"hyperedge_id",
",",
"hyperedge_index",
"in",
"hyperedge_ids_to_indices",
".",
"items",
"(",
")",
":",
"for",
"node",
"in",
"H",
".",
"get_hyperedge_tail",
"(",
"hyperedge_id",
")",
":",
"# get the mapping between the node and its ID",
"rows",
".",
"append",
"(",
"nodes_to_indices",
".",
"get",
"(",
"node",
")",
")",
"cols",
".",
"append",
"(",
"hyperedge_index",
")",
"values",
"=",
"np",
".",
"ones",
"(",
"len",
"(",
"rows",
")",
",",
"dtype",
"=",
"int",
")",
"node_count",
"=",
"len",
"(",
"H",
".",
"get_node_set",
"(",
")",
")",
"hyperedge_count",
"=",
"len",
"(",
"H",
".",
"get_hyperedge_id_set",
"(",
")",
")",
"return",
"sparse",
".",
"csc_matrix",
"(",
"(",
"values",
",",
"(",
"rows",
",",
"cols",
")",
")",
",",
"shape",
"=",
"(",
"node_count",
",",
"hyperedge_count",
")",
")"
] |
Creates the incidence matrix of the tail nodes of the given
hypergraph as a sparse matrix.
:param H: the hypergraph for which to create the incidence matrix of.
:param nodes_to_indices: for each node, maps the node to its
corresponding integer index.
:param hyperedge_ids_to_indices: for each hyperedge ID, maps the hyperedge
ID to its corresponding integer index.
:returns: sparse.csc_matrix -- the incidence matrix as a sparse matrix.
:raises: TypeError -- Algorithm only applicable to directed hypergraphs
|
[
"Creates",
"the",
"incidence",
"matrix",
"of",
"the",
"tail",
"nodes",
"of",
"the",
"given",
"hypergraph",
"as",
"a",
"sparse",
"matrix",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/directed_matrices.py#L59-L87
|
13,974
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.add_node
|
def add_node(self, node, attr_dict=None, **attr):
"""Adds a node to the graph, along with any related attributes
of the node.
:param node: reference to the node being added.
:param attr_dict: dictionary of attributes of the node.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
Examples:
::
>>> H = DirectedHypergraph()
>>> attributes = {label: "positive"}
>>> H.add_node("A", attributes)
>>> H.add_node("B", label="negative")
>>> H.add_node("C", attributes, root=True)
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# If the node hasn't previously been added, add it along
# with its attributes
if not self.has_node(node):
self._node_attributes[node] = attr_dict
self._forward_star[node] = set()
self._backward_star[node] = set()
# Otherwise, just update the node's attributes
else:
self._node_attributes[node].update(attr_dict)
|
python
|
def add_node(self, node, attr_dict=None, **attr):
"""Adds a node to the graph, along with any related attributes
of the node.
:param node: reference to the node being added.
:param attr_dict: dictionary of attributes of the node.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
Examples:
::
>>> H = DirectedHypergraph()
>>> attributes = {label: "positive"}
>>> H.add_node("A", attributes)
>>> H.add_node("B", label="negative")
>>> H.add_node("C", attributes, root=True)
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# If the node hasn't previously been added, add it along
# with its attributes
if not self.has_node(node):
self._node_attributes[node] = attr_dict
self._forward_star[node] = set()
self._backward_star[node] = set()
# Otherwise, just update the node's attributes
else:
self._node_attributes[node].update(attr_dict)
|
[
"def",
"add_node",
"(",
"self",
",",
"node",
",",
"attr_dict",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"attr_dict",
"=",
"self",
".",
"_combine_attribute_arguments",
"(",
"attr_dict",
",",
"attr",
")",
"# If the node hasn't previously been added, add it along",
"# with its attributes",
"if",
"not",
"self",
".",
"has_node",
"(",
"node",
")",
":",
"self",
".",
"_node_attributes",
"[",
"node",
"]",
"=",
"attr_dict",
"self",
".",
"_forward_star",
"[",
"node",
"]",
"=",
"set",
"(",
")",
"self",
".",
"_backward_star",
"[",
"node",
"]",
"=",
"set",
"(",
")",
"# Otherwise, just update the node's attributes",
"else",
":",
"self",
".",
"_node_attributes",
"[",
"node",
"]",
".",
"update",
"(",
"attr_dict",
")"
] |
Adds a node to the graph, along with any related attributes
of the node.
:param node: reference to the node being added.
:param attr_dict: dictionary of attributes of the node.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
Examples:
::
>>> H = DirectedHypergraph()
>>> attributes = {label: "positive"}
>>> H.add_node("A", attributes)
>>> H.add_node("B", label="negative")
>>> H.add_node("C", attributes, root=True)
|
[
"Adds",
"a",
"node",
"to",
"the",
"graph",
"along",
"with",
"any",
"related",
"attributes",
"of",
"the",
"node",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L204-L234
|
13,975
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.add_nodes
|
def add_nodes(self, nodes, attr_dict=None, **attr):
"""Adds multiple nodes to the graph, along with any related attributes
of the nodes.
:param nodes: iterable container to either references of the nodes
OR tuples of (node reference, attribute dictionary);
if an attribute dictionary is provided in the tuple,
its values will override both attr_dict's and attr's
values.
:param attr_dict: dictionary of attributes shared by all the nodes.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
See also:
add_node
Examples:
::
>>> H = DirectedHypergraph()
>>> attributes = {label: "positive"}
>>> node_list = ["A",
("B", {label="negative"}),
("C", {root=True})]
>>> H.add_nodes(node_list, attributes)
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
for node in nodes:
# Note: This won't behave properly if the node is actually a tuple
if type(node) is tuple:
# See ("B", {label="negative"}) in the documentation example
new_node, node_attr_dict = node
# Create a new dictionary and load it with node_attr_dict and
# attr_dict, with the former (node_attr_dict) taking precedence
new_dict = attr_dict.copy()
new_dict.update(node_attr_dict)
self.add_node(new_node, new_dict)
else:
# See "A" in the documentation example
self.add_node(node, attr_dict.copy())
|
python
|
def add_nodes(self, nodes, attr_dict=None, **attr):
"""Adds multiple nodes to the graph, along with any related attributes
of the nodes.
:param nodes: iterable container to either references of the nodes
OR tuples of (node reference, attribute dictionary);
if an attribute dictionary is provided in the tuple,
its values will override both attr_dict's and attr's
values.
:param attr_dict: dictionary of attributes shared by all the nodes.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
See also:
add_node
Examples:
::
>>> H = DirectedHypergraph()
>>> attributes = {label: "positive"}
>>> node_list = ["A",
("B", {label="negative"}),
("C", {root=True})]
>>> H.add_nodes(node_list, attributes)
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
for node in nodes:
# Note: This won't behave properly if the node is actually a tuple
if type(node) is tuple:
# See ("B", {label="negative"}) in the documentation example
new_node, node_attr_dict = node
# Create a new dictionary and load it with node_attr_dict and
# attr_dict, with the former (node_attr_dict) taking precedence
new_dict = attr_dict.copy()
new_dict.update(node_attr_dict)
self.add_node(new_node, new_dict)
else:
# See "A" in the documentation example
self.add_node(node, attr_dict.copy())
|
[
"def",
"add_nodes",
"(",
"self",
",",
"nodes",
",",
"attr_dict",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"attr_dict",
"=",
"self",
".",
"_combine_attribute_arguments",
"(",
"attr_dict",
",",
"attr",
")",
"for",
"node",
"in",
"nodes",
":",
"# Note: This won't behave properly if the node is actually a tuple",
"if",
"type",
"(",
"node",
")",
"is",
"tuple",
":",
"# See (\"B\", {label=\"negative\"}) in the documentation example",
"new_node",
",",
"node_attr_dict",
"=",
"node",
"# Create a new dictionary and load it with node_attr_dict and",
"# attr_dict, with the former (node_attr_dict) taking precedence",
"new_dict",
"=",
"attr_dict",
".",
"copy",
"(",
")",
"new_dict",
".",
"update",
"(",
"node_attr_dict",
")",
"self",
".",
"add_node",
"(",
"new_node",
",",
"new_dict",
")",
"else",
":",
"# See \"A\" in the documentation example",
"self",
".",
"add_node",
"(",
"node",
",",
"attr_dict",
".",
"copy",
"(",
")",
")"
] |
Adds multiple nodes to the graph, along with any related attributes
of the nodes.
:param nodes: iterable container to either references of the nodes
OR tuples of (node reference, attribute dictionary);
if an attribute dictionary is provided in the tuple,
its values will override both attr_dict's and attr's
values.
:param attr_dict: dictionary of attributes shared by all the nodes.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
See also:
add_node
Examples:
::
>>> H = DirectedHypergraph()
>>> attributes = {label: "positive"}
>>> node_list = ["A",
("B", {label="negative"}),
("C", {root=True})]
>>> H.add_nodes(node_list, attributes)
|
[
"Adds",
"multiple",
"nodes",
"to",
"the",
"graph",
"along",
"with",
"any",
"related",
"attributes",
"of",
"the",
"nodes",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L236-L278
|
13,976
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.remove_node
|
def remove_node(self, node):
"""Removes a node and its attributes from the hypergraph. Removes
every hyperedge that contains this node in either the head or the tail.
:param node: reference to the node being added.
:raises: ValueError -- No such node exists.
Examples:
::
>>> H = DirectedHypergraph()
>>> H.add_node("A", label="positive")
>>> H.remove_node("A")
"""
if not self.has_node(node):
raise ValueError("No such node exists.")
# Remove every hyperedge which is in the forward star of the node
forward_star = self.get_forward_star(node)
for hyperedge_id in forward_star:
self.remove_hyperedge(hyperedge_id)
# Remove every hyperedge which is in the backward star of the node
# but that is not also in the forward start of the node (to handle
# overlapping hyperedges)
backward_star = self.get_backward_star(node)
for hyperedge_id in backward_star - forward_star:
self.remove_hyperedge(hyperedge_id)
# Remove node's forward and backward star
del self._forward_star[node]
del self._backward_star[node]
# Remove node's attributes dictionary
del self._node_attributes[node]
|
python
|
def remove_node(self, node):
"""Removes a node and its attributes from the hypergraph. Removes
every hyperedge that contains this node in either the head or the tail.
:param node: reference to the node being added.
:raises: ValueError -- No such node exists.
Examples:
::
>>> H = DirectedHypergraph()
>>> H.add_node("A", label="positive")
>>> H.remove_node("A")
"""
if not self.has_node(node):
raise ValueError("No such node exists.")
# Remove every hyperedge which is in the forward star of the node
forward_star = self.get_forward_star(node)
for hyperedge_id in forward_star:
self.remove_hyperedge(hyperedge_id)
# Remove every hyperedge which is in the backward star of the node
# but that is not also in the forward start of the node (to handle
# overlapping hyperedges)
backward_star = self.get_backward_star(node)
for hyperedge_id in backward_star - forward_star:
self.remove_hyperedge(hyperedge_id)
# Remove node's forward and backward star
del self._forward_star[node]
del self._backward_star[node]
# Remove node's attributes dictionary
del self._node_attributes[node]
|
[
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"self",
".",
"has_node",
"(",
"node",
")",
":",
"raise",
"ValueError",
"(",
"\"No such node exists.\"",
")",
"# Remove every hyperedge which is in the forward star of the node",
"forward_star",
"=",
"self",
".",
"get_forward_star",
"(",
"node",
")",
"for",
"hyperedge_id",
"in",
"forward_star",
":",
"self",
".",
"remove_hyperedge",
"(",
"hyperedge_id",
")",
"# Remove every hyperedge which is in the backward star of the node",
"# but that is not also in the forward start of the node (to handle",
"# overlapping hyperedges)",
"backward_star",
"=",
"self",
".",
"get_backward_star",
"(",
"node",
")",
"for",
"hyperedge_id",
"in",
"backward_star",
"-",
"forward_star",
":",
"self",
".",
"remove_hyperedge",
"(",
"hyperedge_id",
")",
"# Remove node's forward and backward star",
"del",
"self",
".",
"_forward_star",
"[",
"node",
"]",
"del",
"self",
".",
"_backward_star",
"[",
"node",
"]",
"# Remove node's attributes dictionary",
"del",
"self",
".",
"_node_attributes",
"[",
"node",
"]"
] |
Removes a node and its attributes from the hypergraph. Removes
every hyperedge that contains this node in either the head or the tail.
:param node: reference to the node being added.
:raises: ValueError -- No such node exists.
Examples:
::
>>> H = DirectedHypergraph()
>>> H.add_node("A", label="positive")
>>> H.remove_node("A")
|
[
"Removes",
"a",
"node",
"and",
"its",
"attributes",
"from",
"the",
"hypergraph",
".",
"Removes",
"every",
"hyperedge",
"that",
"contains",
"this",
"node",
"in",
"either",
"the",
"head",
"or",
"the",
"tail",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L280-L315
|
13,977
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.get_node_attribute
|
def get_node_attribute(self, node, attribute_name):
"""Given a node and the name of an attribute, get a copy
of that node's attribute.
:param node: reference to the node to retrieve the attribute of.
:param attribute_name: name of the attribute to retrieve.
:returns: attribute value of the attribute_name key for the
specified node.
:raises: ValueError -- No such node exists.
:raises: ValueError -- No such attribute exists.
"""
if not self.has_node(node):
raise ValueError("No such node exists.")
elif attribute_name not in self._node_attributes[node]:
raise ValueError("No such attribute exists.")
else:
return copy.\
copy(self._node_attributes[node][attribute_name])
|
python
|
def get_node_attribute(self, node, attribute_name):
"""Given a node and the name of an attribute, get a copy
of that node's attribute.
:param node: reference to the node to retrieve the attribute of.
:param attribute_name: name of the attribute to retrieve.
:returns: attribute value of the attribute_name key for the
specified node.
:raises: ValueError -- No such node exists.
:raises: ValueError -- No such attribute exists.
"""
if not self.has_node(node):
raise ValueError("No such node exists.")
elif attribute_name not in self._node_attributes[node]:
raise ValueError("No such attribute exists.")
else:
return copy.\
copy(self._node_attributes[node][attribute_name])
|
[
"def",
"get_node_attribute",
"(",
"self",
",",
"node",
",",
"attribute_name",
")",
":",
"if",
"not",
"self",
".",
"has_node",
"(",
"node",
")",
":",
"raise",
"ValueError",
"(",
"\"No such node exists.\"",
")",
"elif",
"attribute_name",
"not",
"in",
"self",
".",
"_node_attributes",
"[",
"node",
"]",
":",
"raise",
"ValueError",
"(",
"\"No such attribute exists.\"",
")",
"else",
":",
"return",
"copy",
".",
"copy",
"(",
"self",
".",
"_node_attributes",
"[",
"node",
"]",
"[",
"attribute_name",
"]",
")"
] |
Given a node and the name of an attribute, get a copy
of that node's attribute.
:param node: reference to the node to retrieve the attribute of.
:param attribute_name: name of the attribute to retrieve.
:returns: attribute value of the attribute_name key for the
specified node.
:raises: ValueError -- No such node exists.
:raises: ValueError -- No such attribute exists.
|
[
"Given",
"a",
"node",
"and",
"the",
"name",
"of",
"an",
"attribute",
"get",
"a",
"copy",
"of",
"that",
"node",
"s",
"attribute",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L420-L438
|
13,978
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.get_node_attributes
|
def get_node_attributes(self, node):
"""Given a node, get a dictionary with copies of that node's
attributes.
:param node: reference to the node to retrieve the attributes of.
:returns: dict -- copy of each attribute of the specified node.
:raises: ValueError -- No such node exists.
"""
if not self.has_node(node):
raise ValueError("No such node exists.")
attributes = {}
for attr_name, attr_value in self._node_attributes[node].items():
attributes[attr_name] = copy.copy(attr_value)
return attributes
|
python
|
def get_node_attributes(self, node):
"""Given a node, get a dictionary with copies of that node's
attributes.
:param node: reference to the node to retrieve the attributes of.
:returns: dict -- copy of each attribute of the specified node.
:raises: ValueError -- No such node exists.
"""
if not self.has_node(node):
raise ValueError("No such node exists.")
attributes = {}
for attr_name, attr_value in self._node_attributes[node].items():
attributes[attr_name] = copy.copy(attr_value)
return attributes
|
[
"def",
"get_node_attributes",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"self",
".",
"has_node",
"(",
"node",
")",
":",
"raise",
"ValueError",
"(",
"\"No such node exists.\"",
")",
"attributes",
"=",
"{",
"}",
"for",
"attr_name",
",",
"attr_value",
"in",
"self",
".",
"_node_attributes",
"[",
"node",
"]",
".",
"items",
"(",
")",
":",
"attributes",
"[",
"attr_name",
"]",
"=",
"copy",
".",
"copy",
"(",
"attr_value",
")",
"return",
"attributes"
] |
Given a node, get a dictionary with copies of that node's
attributes.
:param node: reference to the node to retrieve the attributes of.
:returns: dict -- copy of each attribute of the specified node.
:raises: ValueError -- No such node exists.
|
[
"Given",
"a",
"node",
"get",
"a",
"dictionary",
"with",
"copies",
"of",
"that",
"node",
"s",
"attributes",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L440-L454
|
13,979
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.add_hyperedge
|
def add_hyperedge(self, tail, head, attr_dict=None, **attr):
"""Adds a hyperedge to the hypergraph, along with any related
attributes of the hyperedge.
This method will automatically add any node from the tail and
head that was not in the hypergraph.
A hyperedge without a "weight" attribute specified will be
assigned the default value of 1.
:param tail: iterable container of references to nodes in the
tail of the hyperedge to be added.
:param head: iterable container of references to nodes in the
head of the hyperedge to be added.
:param attr_dict: dictionary of attributes shared by all
the hyperedges.
:param attr: keyword arguments of attributes of the hyperedge;
attr's values will override attr_dict's values
if both are provided.
:returns: str -- the ID of the hyperedge that was added.
:raises: ValueError -- tail and head arguments cannot both be empty.
Examples:
::
>>> H = DirectedHypergraph()
>>> x = H.add_hyperedge(["A", "B"], ["C", "D"])
>>> y = H.add_hyperedge(("A", "C"), ("B"), 'weight'=2)
>>> z = H.add_hyperedge(set(["D"]),
set(["A", "C"]),
{color: "red"})
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# Don't allow both empty tail and head containers (invalid hyperedge)
if not tail and not head:
raise ValueError("tail and head arguments \
cannot both be empty.")
# Use frozensets for tail and head sets to allow for hashable keys
frozen_tail = frozenset(tail)
frozen_head = frozenset(head)
# Initialize a successor dictionary for the tail and head, respectively
if frozen_tail not in self._successors:
self._successors[frozen_tail] = {}
if frozen_head not in self._predecessors:
self._predecessors[frozen_head] = {}
is_new_hyperedge = not self.has_hyperedge(frozen_tail, frozen_head)
if is_new_hyperedge:
# Add tail and head nodes to graph (if not already present)
self.add_nodes(frozen_head)
self.add_nodes(frozen_tail)
# Create new hyperedge name to use as reference for that hyperedge
hyperedge_id = self._assign_next_hyperedge_id()
# Add hyperedge to the forward-star and to the backward-star
# for each node in the tail and head sets, respectively
for node in frozen_tail:
self._forward_star[node].add(hyperedge_id)
for node in frozen_head:
self._backward_star[node].add(hyperedge_id)
# Add the hyperedge as the successors and predecessors
# of the tail set and head set, respectively
self._successors[frozen_tail][frozen_head] = hyperedge_id
self._predecessors[frozen_head][frozen_tail] = hyperedge_id
# Assign some special attributes to this hyperedge. We assign
# a default weight of 1 to the hyperedge. We also store the
# original tail and head sets in order to return them exactly
# as the user passed them into add_hyperedge.
self._hyperedge_attributes[hyperedge_id] = \
{"tail": tail, "__frozen_tail": frozen_tail,
"head": head, "__frozen_head": frozen_head,
"weight": 1}
else:
# If its not a new hyperedge, just get its ID to update attributes
hyperedge_id = self._successors[frozen_tail][frozen_head]
# Set attributes and return hyperedge ID
self._hyperedge_attributes[hyperedge_id].update(attr_dict)
return hyperedge_id
|
python
|
def add_hyperedge(self, tail, head, attr_dict=None, **attr):
"""Adds a hyperedge to the hypergraph, along with any related
attributes of the hyperedge.
This method will automatically add any node from the tail and
head that was not in the hypergraph.
A hyperedge without a "weight" attribute specified will be
assigned the default value of 1.
:param tail: iterable container of references to nodes in the
tail of the hyperedge to be added.
:param head: iterable container of references to nodes in the
head of the hyperedge to be added.
:param attr_dict: dictionary of attributes shared by all
the hyperedges.
:param attr: keyword arguments of attributes of the hyperedge;
attr's values will override attr_dict's values
if both are provided.
:returns: str -- the ID of the hyperedge that was added.
:raises: ValueError -- tail and head arguments cannot both be empty.
Examples:
::
>>> H = DirectedHypergraph()
>>> x = H.add_hyperedge(["A", "B"], ["C", "D"])
>>> y = H.add_hyperedge(("A", "C"), ("B"), 'weight'=2)
>>> z = H.add_hyperedge(set(["D"]),
set(["A", "C"]),
{color: "red"})
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# Don't allow both empty tail and head containers (invalid hyperedge)
if not tail and not head:
raise ValueError("tail and head arguments \
cannot both be empty.")
# Use frozensets for tail and head sets to allow for hashable keys
frozen_tail = frozenset(tail)
frozen_head = frozenset(head)
# Initialize a successor dictionary for the tail and head, respectively
if frozen_tail not in self._successors:
self._successors[frozen_tail] = {}
if frozen_head not in self._predecessors:
self._predecessors[frozen_head] = {}
is_new_hyperedge = not self.has_hyperedge(frozen_tail, frozen_head)
if is_new_hyperedge:
# Add tail and head nodes to graph (if not already present)
self.add_nodes(frozen_head)
self.add_nodes(frozen_tail)
# Create new hyperedge name to use as reference for that hyperedge
hyperedge_id = self._assign_next_hyperedge_id()
# Add hyperedge to the forward-star and to the backward-star
# for each node in the tail and head sets, respectively
for node in frozen_tail:
self._forward_star[node].add(hyperedge_id)
for node in frozen_head:
self._backward_star[node].add(hyperedge_id)
# Add the hyperedge as the successors and predecessors
# of the tail set and head set, respectively
self._successors[frozen_tail][frozen_head] = hyperedge_id
self._predecessors[frozen_head][frozen_tail] = hyperedge_id
# Assign some special attributes to this hyperedge. We assign
# a default weight of 1 to the hyperedge. We also store the
# original tail and head sets in order to return them exactly
# as the user passed them into add_hyperedge.
self._hyperedge_attributes[hyperedge_id] = \
{"tail": tail, "__frozen_tail": frozen_tail,
"head": head, "__frozen_head": frozen_head,
"weight": 1}
else:
# If its not a new hyperedge, just get its ID to update attributes
hyperedge_id = self._successors[frozen_tail][frozen_head]
# Set attributes and return hyperedge ID
self._hyperedge_attributes[hyperedge_id].update(attr_dict)
return hyperedge_id
|
[
"def",
"add_hyperedge",
"(",
"self",
",",
"tail",
",",
"head",
",",
"attr_dict",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"attr_dict",
"=",
"self",
".",
"_combine_attribute_arguments",
"(",
"attr_dict",
",",
"attr",
")",
"# Don't allow both empty tail and head containers (invalid hyperedge)",
"if",
"not",
"tail",
"and",
"not",
"head",
":",
"raise",
"ValueError",
"(",
"\"tail and head arguments \\\n cannot both be empty.\"",
")",
"# Use frozensets for tail and head sets to allow for hashable keys",
"frozen_tail",
"=",
"frozenset",
"(",
"tail",
")",
"frozen_head",
"=",
"frozenset",
"(",
"head",
")",
"# Initialize a successor dictionary for the tail and head, respectively",
"if",
"frozen_tail",
"not",
"in",
"self",
".",
"_successors",
":",
"self",
".",
"_successors",
"[",
"frozen_tail",
"]",
"=",
"{",
"}",
"if",
"frozen_head",
"not",
"in",
"self",
".",
"_predecessors",
":",
"self",
".",
"_predecessors",
"[",
"frozen_head",
"]",
"=",
"{",
"}",
"is_new_hyperedge",
"=",
"not",
"self",
".",
"has_hyperedge",
"(",
"frozen_tail",
",",
"frozen_head",
")",
"if",
"is_new_hyperedge",
":",
"# Add tail and head nodes to graph (if not already present)",
"self",
".",
"add_nodes",
"(",
"frozen_head",
")",
"self",
".",
"add_nodes",
"(",
"frozen_tail",
")",
"# Create new hyperedge name to use as reference for that hyperedge",
"hyperedge_id",
"=",
"self",
".",
"_assign_next_hyperedge_id",
"(",
")",
"# Add hyperedge to the forward-star and to the backward-star",
"# for each node in the tail and head sets, respectively",
"for",
"node",
"in",
"frozen_tail",
":",
"self",
".",
"_forward_star",
"[",
"node",
"]",
".",
"add",
"(",
"hyperedge_id",
")",
"for",
"node",
"in",
"frozen_head",
":",
"self",
".",
"_backward_star",
"[",
"node",
"]",
".",
"add",
"(",
"hyperedge_id",
")",
"# Add the hyperedge as the successors and predecessors",
"# of the tail set and head set, respectively",
"self",
".",
"_successors",
"[",
"frozen_tail",
"]",
"[",
"frozen_head",
"]",
"=",
"hyperedge_id",
"self",
".",
"_predecessors",
"[",
"frozen_head",
"]",
"[",
"frozen_tail",
"]",
"=",
"hyperedge_id",
"# Assign some special attributes to this hyperedge. We assign",
"# a default weight of 1 to the hyperedge. We also store the",
"# original tail and head sets in order to return them exactly",
"# as the user passed them into add_hyperedge.",
"self",
".",
"_hyperedge_attributes",
"[",
"hyperedge_id",
"]",
"=",
"{",
"\"tail\"",
":",
"tail",
",",
"\"__frozen_tail\"",
":",
"frozen_tail",
",",
"\"head\"",
":",
"head",
",",
"\"__frozen_head\"",
":",
"frozen_head",
",",
"\"weight\"",
":",
"1",
"}",
"else",
":",
"# If its not a new hyperedge, just get its ID to update attributes",
"hyperedge_id",
"=",
"self",
".",
"_successors",
"[",
"frozen_tail",
"]",
"[",
"frozen_head",
"]",
"# Set attributes and return hyperedge ID",
"self",
".",
"_hyperedge_attributes",
"[",
"hyperedge_id",
"]",
".",
"update",
"(",
"attr_dict",
")",
"return",
"hyperedge_id"
] |
Adds a hyperedge to the hypergraph, along with any related
attributes of the hyperedge.
This method will automatically add any node from the tail and
head that was not in the hypergraph.
A hyperedge without a "weight" attribute specified will be
assigned the default value of 1.
:param tail: iterable container of references to nodes in the
tail of the hyperedge to be added.
:param head: iterable container of references to nodes in the
head of the hyperedge to be added.
:param attr_dict: dictionary of attributes shared by all
the hyperedges.
:param attr: keyword arguments of attributes of the hyperedge;
attr's values will override attr_dict's values
if both are provided.
:returns: str -- the ID of the hyperedge that was added.
:raises: ValueError -- tail and head arguments cannot both be empty.
Examples:
::
>>> H = DirectedHypergraph()
>>> x = H.add_hyperedge(["A", "B"], ["C", "D"])
>>> y = H.add_hyperedge(("A", "C"), ("B"), 'weight'=2)
>>> z = H.add_hyperedge(set(["D"]),
set(["A", "C"]),
{color: "red"})
|
[
"Adds",
"a",
"hyperedge",
"to",
"the",
"hypergraph",
"along",
"with",
"any",
"related",
"attributes",
"of",
"the",
"hyperedge",
".",
"This",
"method",
"will",
"automatically",
"add",
"any",
"node",
"from",
"the",
"tail",
"and",
"head",
"that",
"was",
"not",
"in",
"the",
"hypergraph",
".",
"A",
"hyperedge",
"without",
"a",
"weight",
"attribute",
"specified",
"will",
"be",
"assigned",
"the",
"default",
"value",
"of",
"1",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L465-L548
|
13,980
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.add_hyperedges
|
def add_hyperedges(self, hyperedges, attr_dict=None, **attr):
"""Adds multiple hyperedges to the graph, along with any related
attributes of the hyperedges.
If any node in the tail or head of any hyperedge has not
previously been added to the hypergraph, it will automatically
be added here. Hyperedges without a "weight" attribute specified
will be assigned the default value of 1.
:param hyperedges: iterable container to either tuples of
(tail reference, head reference) OR tuples of
(tail reference, head reference, attribute dictionary);
if an attribute dictionary is provided in the tuple,
its values will override both attr_dict's and attr's
values.
:param attr_dict: dictionary of attributes shared by all
the hyperedges.
:param attr: keyword arguments of attributes of the hyperedges;
attr's values will override attr_dict's values
if both are provided.
:returns: list -- the IDs of the hyperedges added in the order
specified by the hyperedges container's iterator.
See also:
add_hyperedge
Examples:
::
>>> H = DirectedHypergraph()
>>> xyz = hyperedge_list = ((["A", "B"], ["C", "D"]),
(("A", "C"), ("B"), {'weight': 2}),
(set(["D"]), set(["A", "C"])))
>>> H.add_hyperedges(hyperedge_list)
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
hyperedge_ids = []
for hyperedge in hyperedges:
if len(hyperedge) == 3:
# See ("A", "C"), ("B"), {weight: 2}) in the
# documentation example
tail, head, hyperedge_attr_dict = hyperedge
# Create a new dictionary and load it with node_attr_dict and
# attr_dict, with the former (node_attr_dict) taking precedence
new_dict = attr_dict.copy()
new_dict.update(hyperedge_attr_dict)
hyperedge_id = self.add_hyperedge(tail, head, new_dict)
else:
# See (["A", "B"], ["C", "D"]) in the documentation example
tail, head = hyperedge
hyperedge_id = \
self.add_hyperedge(tail, head, attr_dict.copy())
hyperedge_ids.append(hyperedge_id)
return hyperedge_ids
|
python
|
def add_hyperedges(self, hyperedges, attr_dict=None, **attr):
"""Adds multiple hyperedges to the graph, along with any related
attributes of the hyperedges.
If any node in the tail or head of any hyperedge has not
previously been added to the hypergraph, it will automatically
be added here. Hyperedges without a "weight" attribute specified
will be assigned the default value of 1.
:param hyperedges: iterable container to either tuples of
(tail reference, head reference) OR tuples of
(tail reference, head reference, attribute dictionary);
if an attribute dictionary is provided in the tuple,
its values will override both attr_dict's and attr's
values.
:param attr_dict: dictionary of attributes shared by all
the hyperedges.
:param attr: keyword arguments of attributes of the hyperedges;
attr's values will override attr_dict's values
if both are provided.
:returns: list -- the IDs of the hyperedges added in the order
specified by the hyperedges container's iterator.
See also:
add_hyperedge
Examples:
::
>>> H = DirectedHypergraph()
>>> xyz = hyperedge_list = ((["A", "B"], ["C", "D"]),
(("A", "C"), ("B"), {'weight': 2}),
(set(["D"]), set(["A", "C"])))
>>> H.add_hyperedges(hyperedge_list)
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
hyperedge_ids = []
for hyperedge in hyperedges:
if len(hyperedge) == 3:
# See ("A", "C"), ("B"), {weight: 2}) in the
# documentation example
tail, head, hyperedge_attr_dict = hyperedge
# Create a new dictionary and load it with node_attr_dict and
# attr_dict, with the former (node_attr_dict) taking precedence
new_dict = attr_dict.copy()
new_dict.update(hyperedge_attr_dict)
hyperedge_id = self.add_hyperedge(tail, head, new_dict)
else:
# See (["A", "B"], ["C", "D"]) in the documentation example
tail, head = hyperedge
hyperedge_id = \
self.add_hyperedge(tail, head, attr_dict.copy())
hyperedge_ids.append(hyperedge_id)
return hyperedge_ids
|
[
"def",
"add_hyperedges",
"(",
"self",
",",
"hyperedges",
",",
"attr_dict",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"attr_dict",
"=",
"self",
".",
"_combine_attribute_arguments",
"(",
"attr_dict",
",",
"attr",
")",
"hyperedge_ids",
"=",
"[",
"]",
"for",
"hyperedge",
"in",
"hyperedges",
":",
"if",
"len",
"(",
"hyperedge",
")",
"==",
"3",
":",
"# See (\"A\", \"C\"), (\"B\"), {weight: 2}) in the",
"# documentation example",
"tail",
",",
"head",
",",
"hyperedge_attr_dict",
"=",
"hyperedge",
"# Create a new dictionary and load it with node_attr_dict and",
"# attr_dict, with the former (node_attr_dict) taking precedence",
"new_dict",
"=",
"attr_dict",
".",
"copy",
"(",
")",
"new_dict",
".",
"update",
"(",
"hyperedge_attr_dict",
")",
"hyperedge_id",
"=",
"self",
".",
"add_hyperedge",
"(",
"tail",
",",
"head",
",",
"new_dict",
")",
"else",
":",
"# See ([\"A\", \"B\"], [\"C\", \"D\"]) in the documentation example",
"tail",
",",
"head",
"=",
"hyperedge",
"hyperedge_id",
"=",
"self",
".",
"add_hyperedge",
"(",
"tail",
",",
"head",
",",
"attr_dict",
".",
"copy",
"(",
")",
")",
"hyperedge_ids",
".",
"append",
"(",
"hyperedge_id",
")",
"return",
"hyperedge_ids"
] |
Adds multiple hyperedges to the graph, along with any related
attributes of the hyperedges.
If any node in the tail or head of any hyperedge has not
previously been added to the hypergraph, it will automatically
be added here. Hyperedges without a "weight" attribute specified
will be assigned the default value of 1.
:param hyperedges: iterable container to either tuples of
(tail reference, head reference) OR tuples of
(tail reference, head reference, attribute dictionary);
if an attribute dictionary is provided in the tuple,
its values will override both attr_dict's and attr's
values.
:param attr_dict: dictionary of attributes shared by all
the hyperedges.
:param attr: keyword arguments of attributes of the hyperedges;
attr's values will override attr_dict's values
if both are provided.
:returns: list -- the IDs of the hyperedges added in the order
specified by the hyperedges container's iterator.
See also:
add_hyperedge
Examples:
::
>>> H = DirectedHypergraph()
>>> xyz = hyperedge_list = ((["A", "B"], ["C", "D"]),
(("A", "C"), ("B"), {'weight': 2}),
(set(["D"]), set(["A", "C"])))
>>> H.add_hyperedges(hyperedge_list)
|
[
"Adds",
"multiple",
"hyperedges",
"to",
"the",
"graph",
"along",
"with",
"any",
"related",
"attributes",
"of",
"the",
"hyperedges",
".",
"If",
"any",
"node",
"in",
"the",
"tail",
"or",
"head",
"of",
"any",
"hyperedge",
"has",
"not",
"previously",
"been",
"added",
"to",
"the",
"hypergraph",
"it",
"will",
"automatically",
"be",
"added",
"here",
".",
"Hyperedges",
"without",
"a",
"weight",
"attribute",
"specified",
"will",
"be",
"assigned",
"the",
"default",
"value",
"of",
"1",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L550-L606
|
13,981
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.get_hyperedge_id
|
def get_hyperedge_id(self, tail, head):
"""From a tail and head set of nodes, returns the ID of the hyperedge
that these sets comprise.
:param tail: iterable container of references to nodes in the
tail of the hyperedge to be added
:param head: iterable container of references to nodes in the
head of the hyperedge to be added
:returns: str -- ID of the hyperedge that has that the specified
tail and head sets comprise.
:raises: ValueError -- No such hyperedge exists.
Examples:
::
>>> H = DirectedHypergraph()
>>> hyperedge_list = (["A"], ["B", "C"]),
(("A", "B"), ("C"), {weight: 2}),
(set(["B"]), set(["A", "C"])))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
>>> x = H.get_hyperedge_id(["A"], ["B", "C"])
"""
frozen_tail = frozenset(tail)
frozen_head = frozenset(head)
if not self.has_hyperedge(frozen_tail, frozen_head):
raise ValueError("No such hyperedge exists.")
return self._successors[frozen_tail][frozen_head]
|
python
|
def get_hyperedge_id(self, tail, head):
"""From a tail and head set of nodes, returns the ID of the hyperedge
that these sets comprise.
:param tail: iterable container of references to nodes in the
tail of the hyperedge to be added
:param head: iterable container of references to nodes in the
head of the hyperedge to be added
:returns: str -- ID of the hyperedge that has that the specified
tail and head sets comprise.
:raises: ValueError -- No such hyperedge exists.
Examples:
::
>>> H = DirectedHypergraph()
>>> hyperedge_list = (["A"], ["B", "C"]),
(("A", "B"), ("C"), {weight: 2}),
(set(["B"]), set(["A", "C"])))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
>>> x = H.get_hyperedge_id(["A"], ["B", "C"])
"""
frozen_tail = frozenset(tail)
frozen_head = frozenset(head)
if not self.has_hyperedge(frozen_tail, frozen_head):
raise ValueError("No such hyperedge exists.")
return self._successors[frozen_tail][frozen_head]
|
[
"def",
"get_hyperedge_id",
"(",
"self",
",",
"tail",
",",
"head",
")",
":",
"frozen_tail",
"=",
"frozenset",
"(",
"tail",
")",
"frozen_head",
"=",
"frozenset",
"(",
"head",
")",
"if",
"not",
"self",
".",
"has_hyperedge",
"(",
"frozen_tail",
",",
"frozen_head",
")",
":",
"raise",
"ValueError",
"(",
"\"No such hyperedge exists.\"",
")",
"return",
"self",
".",
"_successors",
"[",
"frozen_tail",
"]",
"[",
"frozen_head",
"]"
] |
From a tail and head set of nodes, returns the ID of the hyperedge
that these sets comprise.
:param tail: iterable container of references to nodes in the
tail of the hyperedge to be added
:param head: iterable container of references to nodes in the
head of the hyperedge to be added
:returns: str -- ID of the hyperedge that has that the specified
tail and head sets comprise.
:raises: ValueError -- No such hyperedge exists.
Examples:
::
>>> H = DirectedHypergraph()
>>> hyperedge_list = (["A"], ["B", "C"]),
(("A", "B"), ("C"), {weight: 2}),
(set(["B"]), set(["A", "C"])))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
>>> x = H.get_hyperedge_id(["A"], ["B", "C"])
|
[
"From",
"a",
"tail",
"and",
"head",
"set",
"of",
"nodes",
"returns",
"the",
"ID",
"of",
"the",
"hyperedge",
"that",
"these",
"sets",
"comprise",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L724-L753
|
13,982
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.get_forward_star
|
def get_forward_star(self, node):
"""Given a node, get a copy of that node's forward star.
:param node: node to retrieve the forward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's forward star.
:raises: ValueError -- No such node exists.
"""
if node not in self._node_attributes:
raise ValueError("No such node exists.")
return self._forward_star[node].copy()
|
python
|
def get_forward_star(self, node):
"""Given a node, get a copy of that node's forward star.
:param node: node to retrieve the forward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's forward star.
:raises: ValueError -- No such node exists.
"""
if node not in self._node_attributes:
raise ValueError("No such node exists.")
return self._forward_star[node].copy()
|
[
"def",
"get_forward_star",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"not",
"in",
"self",
".",
"_node_attributes",
":",
"raise",
"ValueError",
"(",
"\"No such node exists.\"",
")",
"return",
"self",
".",
"_forward_star",
"[",
"node",
"]",
".",
"copy",
"(",
")"
] |
Given a node, get a copy of that node's forward star.
:param node: node to retrieve the forward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's forward star.
:raises: ValueError -- No such node exists.
|
[
"Given",
"a",
"node",
"get",
"a",
"copy",
"of",
"that",
"node",
"s",
"forward",
"star",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L833-L844
|
13,983
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.get_backward_star
|
def get_backward_star(self, node):
"""Given a node, get a copy of that node's backward star.
:param node: node to retrieve the backward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's backward star.
:raises: ValueError -- No such node exists.
"""
if node not in self._node_attributes:
raise ValueError("No such node exists.")
return self._backward_star[node].copy()
|
python
|
def get_backward_star(self, node):
"""Given a node, get a copy of that node's backward star.
:param node: node to retrieve the backward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's backward star.
:raises: ValueError -- No such node exists.
"""
if node not in self._node_attributes:
raise ValueError("No such node exists.")
return self._backward_star[node].copy()
|
[
"def",
"get_backward_star",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"not",
"in",
"self",
".",
"_node_attributes",
":",
"raise",
"ValueError",
"(",
"\"No such node exists.\"",
")",
"return",
"self",
".",
"_backward_star",
"[",
"node",
"]",
".",
"copy",
"(",
")"
] |
Given a node, get a copy of that node's backward star.
:param node: node to retrieve the backward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's backward star.
:raises: ValueError -- No such node exists.
|
[
"Given",
"a",
"node",
"get",
"a",
"copy",
"of",
"that",
"node",
"s",
"backward",
"star",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L846-L857
|
13,984
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.get_successors
|
def get_successors(self, tail):
"""Given a tail set of nodes, get a list of edges of which the node
set is the tail of each edge.
:param tail: set of nodes that correspond to the tails of some
(possibly empty) set of edges.
:returns: set -- hyperedge_ids of the hyperedges that have tail
in the tail.
"""
frozen_tail = frozenset(tail)
# If this node set isn't any tail in the hypergraph, then it has
# no successors; thus, return an empty list
if frozen_tail not in self._successors:
return set()
return set(self._successors[frozen_tail].values())
|
python
|
def get_successors(self, tail):
"""Given a tail set of nodes, get a list of edges of which the node
set is the tail of each edge.
:param tail: set of nodes that correspond to the tails of some
(possibly empty) set of edges.
:returns: set -- hyperedge_ids of the hyperedges that have tail
in the tail.
"""
frozen_tail = frozenset(tail)
# If this node set isn't any tail in the hypergraph, then it has
# no successors; thus, return an empty list
if frozen_tail not in self._successors:
return set()
return set(self._successors[frozen_tail].values())
|
[
"def",
"get_successors",
"(",
"self",
",",
"tail",
")",
":",
"frozen_tail",
"=",
"frozenset",
"(",
"tail",
")",
"# If this node set isn't any tail in the hypergraph, then it has",
"# no successors; thus, return an empty list",
"if",
"frozen_tail",
"not",
"in",
"self",
".",
"_successors",
":",
"return",
"set",
"(",
")",
"return",
"set",
"(",
"self",
".",
"_successors",
"[",
"frozen_tail",
"]",
".",
"values",
"(",
")",
")"
] |
Given a tail set of nodes, get a list of edges of which the node
set is the tail of each edge.
:param tail: set of nodes that correspond to the tails of some
(possibly empty) set of edges.
:returns: set -- hyperedge_ids of the hyperedges that have tail
in the tail.
|
[
"Given",
"a",
"tail",
"set",
"of",
"nodes",
"get",
"a",
"list",
"of",
"edges",
"of",
"which",
"the",
"node",
"set",
"is",
"the",
"tail",
"of",
"each",
"edge",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L859-L875
|
13,985
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.get_predecessors
|
def get_predecessors(self, head):
"""Given a head set of nodes, get a list of edges of which the node set
is the head of each edge.
:param head: set of nodes that correspond to the heads of some
(possibly empty) set of edges.
:returns: set -- hyperedge_ids of the hyperedges that have head
in the head.
"""
frozen_head = frozenset(head)
# If this node set isn't any head in the hypergraph, then it has
# no predecessors; thus, return an empty list
if frozen_head not in self._predecessors:
return set()
return set(self._predecessors[frozen_head].values())
|
python
|
def get_predecessors(self, head):
"""Given a head set of nodes, get a list of edges of which the node set
is the head of each edge.
:param head: set of nodes that correspond to the heads of some
(possibly empty) set of edges.
:returns: set -- hyperedge_ids of the hyperedges that have head
in the head.
"""
frozen_head = frozenset(head)
# If this node set isn't any head in the hypergraph, then it has
# no predecessors; thus, return an empty list
if frozen_head not in self._predecessors:
return set()
return set(self._predecessors[frozen_head].values())
|
[
"def",
"get_predecessors",
"(",
"self",
",",
"head",
")",
":",
"frozen_head",
"=",
"frozenset",
"(",
"head",
")",
"# If this node set isn't any head in the hypergraph, then it has",
"# no predecessors; thus, return an empty list",
"if",
"frozen_head",
"not",
"in",
"self",
".",
"_predecessors",
":",
"return",
"set",
"(",
")",
"return",
"set",
"(",
"self",
".",
"_predecessors",
"[",
"frozen_head",
"]",
".",
"values",
"(",
")",
")"
] |
Given a head set of nodes, get a list of edges of which the node set
is the head of each edge.
:param head: set of nodes that correspond to the heads of some
(possibly empty) set of edges.
:returns: set -- hyperedge_ids of the hyperedges that have head
in the head.
|
[
"Given",
"a",
"head",
"set",
"of",
"nodes",
"get",
"a",
"list",
"of",
"edges",
"of",
"which",
"the",
"node",
"set",
"is",
"the",
"head",
"of",
"each",
"edge",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L877-L892
|
13,986
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.is_BF_hypergraph
|
def is_BF_hypergraph(self):
"""Indicates whether the hypergraph is a BF-hypergraph.
A BF-hypergraph consists of only B-hyperedges and F-hyperedges.
See "is_B_hypergraph" or "is_F_hypergraph" for more details.
:returns: bool -- True iff the hypergraph is an F-hypergraph.
"""
for hyperedge_id in self._hyperedge_attributes:
tail = self.get_hyperedge_tail(hyperedge_id)
head = self.get_hyperedge_head(hyperedge_id)
if len(tail) > 1 and len(head) > 1:
return False
return True
|
python
|
def is_BF_hypergraph(self):
"""Indicates whether the hypergraph is a BF-hypergraph.
A BF-hypergraph consists of only B-hyperedges and F-hyperedges.
See "is_B_hypergraph" or "is_F_hypergraph" for more details.
:returns: bool -- True iff the hypergraph is an F-hypergraph.
"""
for hyperedge_id in self._hyperedge_attributes:
tail = self.get_hyperedge_tail(hyperedge_id)
head = self.get_hyperedge_head(hyperedge_id)
if len(tail) > 1 and len(head) > 1:
return False
return True
|
[
"def",
"is_BF_hypergraph",
"(",
"self",
")",
":",
"for",
"hyperedge_id",
"in",
"self",
".",
"_hyperedge_attributes",
":",
"tail",
"=",
"self",
".",
"get_hyperedge_tail",
"(",
"hyperedge_id",
")",
"head",
"=",
"self",
".",
"get_hyperedge_head",
"(",
"hyperedge_id",
")",
"if",
"len",
"(",
"tail",
")",
">",
"1",
"and",
"len",
"(",
"head",
")",
">",
"1",
":",
"return",
"False",
"return",
"True"
] |
Indicates whether the hypergraph is a BF-hypergraph.
A BF-hypergraph consists of only B-hyperedges and F-hyperedges.
See "is_B_hypergraph" or "is_F_hypergraph" for more details.
:returns: bool -- True iff the hypergraph is an F-hypergraph.
|
[
"Indicates",
"whether",
"the",
"hypergraph",
"is",
"a",
"BF",
"-",
"hypergraph",
".",
"A",
"BF",
"-",
"hypergraph",
"consists",
"of",
"only",
"B",
"-",
"hyperedges",
"and",
"F",
"-",
"hyperedges",
".",
"See",
"is_B_hypergraph",
"or",
"is_F_hypergraph",
"for",
"more",
"details",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L928-L941
|
13,987
|
Murali-group/halp
|
halp/directed_hypergraph.py
|
DirectedHypergraph.get_induced_subhypergraph
|
def get_induced_subhypergraph(self, nodes):
"""Gives a new hypergraph that is the subhypergraph of the current
hypergraph induced by the provided set of nodes. That is, the induced
subhypergraph's node set corresponds precisely to the nodes provided,
and the coressponding hyperedges in the subhypergraph are only those
from the original graph consist of tail and head sets that are subsets
of the provided nodes.
:param nodes: the set of nodes to find the induced subhypergraph of.
:returns: DirectedHypergraph -- the subhypergraph induced on the
provided nodes.
"""
sub_H = self.copy()
sub_H.remove_nodes(sub_H.get_node_set() - set(nodes))
return sub_H
|
python
|
def get_induced_subhypergraph(self, nodes):
"""Gives a new hypergraph that is the subhypergraph of the current
hypergraph induced by the provided set of nodes. That is, the induced
subhypergraph's node set corresponds precisely to the nodes provided,
and the coressponding hyperedges in the subhypergraph are only those
from the original graph consist of tail and head sets that are subsets
of the provided nodes.
:param nodes: the set of nodes to find the induced subhypergraph of.
:returns: DirectedHypergraph -- the subhypergraph induced on the
provided nodes.
"""
sub_H = self.copy()
sub_H.remove_nodes(sub_H.get_node_set() - set(nodes))
return sub_H
|
[
"def",
"get_induced_subhypergraph",
"(",
"self",
",",
"nodes",
")",
":",
"sub_H",
"=",
"self",
".",
"copy",
"(",
")",
"sub_H",
".",
"remove_nodes",
"(",
"sub_H",
".",
"get_node_set",
"(",
")",
"-",
"set",
"(",
"nodes",
")",
")",
"return",
"sub_H"
] |
Gives a new hypergraph that is the subhypergraph of the current
hypergraph induced by the provided set of nodes. That is, the induced
subhypergraph's node set corresponds precisely to the nodes provided,
and the coressponding hyperedges in the subhypergraph are only those
from the original graph consist of tail and head sets that are subsets
of the provided nodes.
:param nodes: the set of nodes to find the induced subhypergraph of.
:returns: DirectedHypergraph -- the subhypergraph induced on the
provided nodes.
|
[
"Gives",
"a",
"new",
"hypergraph",
"that",
"is",
"the",
"subhypergraph",
"of",
"the",
"current",
"hypergraph",
"induced",
"by",
"the",
"provided",
"set",
"of",
"nodes",
".",
"That",
"is",
"the",
"induced",
"subhypergraph",
"s",
"node",
"set",
"corresponds",
"precisely",
"to",
"the",
"nodes",
"provided",
"and",
"the",
"coressponding",
"hyperedges",
"in",
"the",
"subhypergraph",
"are",
"only",
"those",
"from",
"the",
"original",
"graph",
"consist",
"of",
"tail",
"and",
"head",
"sets",
"that",
"are",
"subsets",
"of",
"the",
"provided",
"nodes",
"."
] |
6eb27466ba84e2281e18f93b62aae5efb21ef8b3
|
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L1046-L1061
|
13,988
|
aio-libs/multidict
|
multidict/_multidict_py.py
|
_Base.getall
|
def getall(self, key, default=_marker):
"""Return a list of all values matching the key."""
identity = self._title(key)
res = [v for i, k, v in self._impl._items if i == identity]
if res:
return res
if not res and default is not _marker:
return default
raise KeyError('Key not found: %r' % key)
|
python
|
def getall(self, key, default=_marker):
"""Return a list of all values matching the key."""
identity = self._title(key)
res = [v for i, k, v in self._impl._items if i == identity]
if res:
return res
if not res and default is not _marker:
return default
raise KeyError('Key not found: %r' % key)
|
[
"def",
"getall",
"(",
"self",
",",
"key",
",",
"default",
"=",
"_marker",
")",
":",
"identity",
"=",
"self",
".",
"_title",
"(",
"key",
")",
"res",
"=",
"[",
"v",
"for",
"i",
",",
"k",
",",
"v",
"in",
"self",
".",
"_impl",
".",
"_items",
"if",
"i",
"==",
"identity",
"]",
"if",
"res",
":",
"return",
"res",
"if",
"not",
"res",
"and",
"default",
"is",
"not",
"_marker",
":",
"return",
"default",
"raise",
"KeyError",
"(",
"'Key not found: %r'",
"%",
"key",
")"
] |
Return a list of all values matching the key.
|
[
"Return",
"a",
"list",
"of",
"all",
"values",
"matching",
"the",
"key",
"."
] |
1ecfa942cf6ae79727711a109e1f46ed24fae07f
|
https://github.com/aio-libs/multidict/blob/1ecfa942cf6ae79727711a109e1f46ed24fae07f/multidict/_multidict_py.py#L64-L72
|
13,989
|
aio-libs/multidict
|
multidict/_multidict_py.py
|
MultiDict.extend
|
def extend(self, *args, **kwargs):
"""Extend current MultiDict with more values.
This method must be used instead of update.
"""
self._extend(args, kwargs, 'extend', self._extend_items)
|
python
|
def extend(self, *args, **kwargs):
"""Extend current MultiDict with more values.
This method must be used instead of update.
"""
self._extend(args, kwargs, 'extend', self._extend_items)
|
[
"def",
"extend",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_extend",
"(",
"args",
",",
"kwargs",
",",
"'extend'",
",",
"self",
".",
"_extend_items",
")"
] |
Extend current MultiDict with more values.
This method must be used instead of update.
|
[
"Extend",
"current",
"MultiDict",
"with",
"more",
"values",
"."
] |
1ecfa942cf6ae79727711a109e1f46ed24fae07f
|
https://github.com/aio-libs/multidict/blob/1ecfa942cf6ae79727711a109e1f46ed24fae07f/multidict/_multidict_py.py#L218-L223
|
13,990
|
aio-libs/multidict
|
multidict/_multidict_py.py
|
MultiDict.setdefault
|
def setdefault(self, key, default=None):
"""Return value for key, set value to default if key is not present."""
identity = self._title(key)
for i, k, v in self._impl._items:
if i == identity:
return v
self.add(key, default)
return default
|
python
|
def setdefault(self, key, default=None):
"""Return value for key, set value to default if key is not present."""
identity = self._title(key)
for i, k, v in self._impl._items:
if i == identity:
return v
self.add(key, default)
return default
|
[
"def",
"setdefault",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"identity",
"=",
"self",
".",
"_title",
"(",
"key",
")",
"for",
"i",
",",
"k",
",",
"v",
"in",
"self",
".",
"_impl",
".",
"_items",
":",
"if",
"i",
"==",
"identity",
":",
"return",
"v",
"self",
".",
"add",
"(",
"key",
",",
"default",
")",
"return",
"default"
] |
Return value for key, set value to default if key is not present.
|
[
"Return",
"value",
"for",
"key",
"set",
"value",
"to",
"default",
"if",
"key",
"is",
"not",
"present",
"."
] |
1ecfa942cf6ae79727711a109e1f46ed24fae07f
|
https://github.com/aio-libs/multidict/blob/1ecfa942cf6ae79727711a109e1f46ed24fae07f/multidict/_multidict_py.py#L281-L288
|
13,991
|
aio-libs/multidict
|
multidict/_multidict_py.py
|
MultiDict.popall
|
def popall(self, key, default=_marker):
"""Remove all occurrences of key and return the list of corresponding
values.
If key is not found, default is returned if given, otherwise
KeyError is raised.
"""
found = False
identity = self._title(key)
ret = []
for i in range(len(self._impl._items)-1, -1, -1):
item = self._impl._items[i]
if item[0] == identity:
ret.append(item[2])
del self._impl._items[i]
self._impl.incr_version()
found = True
if not found:
if default is _marker:
raise KeyError(key)
else:
return default
else:
ret.reverse()
return ret
|
python
|
def popall(self, key, default=_marker):
"""Remove all occurrences of key and return the list of corresponding
values.
If key is not found, default is returned if given, otherwise
KeyError is raised.
"""
found = False
identity = self._title(key)
ret = []
for i in range(len(self._impl._items)-1, -1, -1):
item = self._impl._items[i]
if item[0] == identity:
ret.append(item[2])
del self._impl._items[i]
self._impl.incr_version()
found = True
if not found:
if default is _marker:
raise KeyError(key)
else:
return default
else:
ret.reverse()
return ret
|
[
"def",
"popall",
"(",
"self",
",",
"key",
",",
"default",
"=",
"_marker",
")",
":",
"found",
"=",
"False",
"identity",
"=",
"self",
".",
"_title",
"(",
"key",
")",
"ret",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_impl",
".",
"_items",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"item",
"=",
"self",
".",
"_impl",
".",
"_items",
"[",
"i",
"]",
"if",
"item",
"[",
"0",
"]",
"==",
"identity",
":",
"ret",
".",
"append",
"(",
"item",
"[",
"2",
"]",
")",
"del",
"self",
".",
"_impl",
".",
"_items",
"[",
"i",
"]",
"self",
".",
"_impl",
".",
"incr_version",
"(",
")",
"found",
"=",
"True",
"if",
"not",
"found",
":",
"if",
"default",
"is",
"_marker",
":",
"raise",
"KeyError",
"(",
"key",
")",
"else",
":",
"return",
"default",
"else",
":",
"ret",
".",
"reverse",
"(",
")",
"return",
"ret"
] |
Remove all occurrences of key and return the list of corresponding
values.
If key is not found, default is returned if given, otherwise
KeyError is raised.
|
[
"Remove",
"all",
"occurrences",
"of",
"key",
"and",
"return",
"the",
"list",
"of",
"corresponding",
"values",
"."
] |
1ecfa942cf6ae79727711a109e1f46ed24fae07f
|
https://github.com/aio-libs/multidict/blob/1ecfa942cf6ae79727711a109e1f46ed24fae07f/multidict/_multidict_py.py#L311-L336
|
13,992
|
rootpy/rootpy
|
rootpy/stats/histfactory/histfactory.py
|
Data.total
|
def total(self, xbin1=1, xbin2=-2):
"""
Return the total yield and its associated statistical uncertainty.
"""
return self.hist.integral(xbin1=xbin1, xbin2=xbin2, error=True)
|
python
|
def total(self, xbin1=1, xbin2=-2):
"""
Return the total yield and its associated statistical uncertainty.
"""
return self.hist.integral(xbin1=xbin1, xbin2=xbin2, error=True)
|
[
"def",
"total",
"(",
"self",
",",
"xbin1",
"=",
"1",
",",
"xbin2",
"=",
"-",
"2",
")",
":",
"return",
"self",
".",
"hist",
".",
"integral",
"(",
"xbin1",
"=",
"xbin1",
",",
"xbin2",
"=",
"xbin2",
",",
"error",
"=",
"True",
")"
] |
Return the total yield and its associated statistical uncertainty.
|
[
"Return",
"the",
"total",
"yield",
"and",
"its",
"associated",
"statistical",
"uncertainty",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/stats/histfactory/histfactory.py#L133-L137
|
13,993
|
rootpy/rootpy
|
rootpy/stats/histfactory/histfactory.py
|
Sample.iter_sys
|
def iter_sys(self):
"""
Iterate over sys_name, overall_sys, histo_sys.
overall_sys or histo_sys may be None for any given sys_name.
"""
names = self.sys_names()
for name in names:
osys = self.GetOverallSys(name)
hsys = self.GetHistoSys(name)
yield name, osys, hsys
|
python
|
def iter_sys(self):
"""
Iterate over sys_name, overall_sys, histo_sys.
overall_sys or histo_sys may be None for any given sys_name.
"""
names = self.sys_names()
for name in names:
osys = self.GetOverallSys(name)
hsys = self.GetHistoSys(name)
yield name, osys, hsys
|
[
"def",
"iter_sys",
"(",
"self",
")",
":",
"names",
"=",
"self",
".",
"sys_names",
"(",
")",
"for",
"name",
"in",
"names",
":",
"osys",
"=",
"self",
".",
"GetOverallSys",
"(",
"name",
")",
"hsys",
"=",
"self",
".",
"GetHistoSys",
"(",
"name",
")",
"yield",
"name",
",",
"osys",
",",
"hsys"
] |
Iterate over sys_name, overall_sys, histo_sys.
overall_sys or histo_sys may be None for any given sys_name.
|
[
"Iterate",
"over",
"sys_name",
"overall_sys",
"histo_sys",
".",
"overall_sys",
"or",
"histo_sys",
"may",
"be",
"None",
"for",
"any",
"given",
"sys_name",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/stats/histfactory/histfactory.py#L260-L269
|
13,994
|
rootpy/rootpy
|
rootpy/stats/histfactory/histfactory.py
|
Sample.sys_hist
|
def sys_hist(self, name=None):
"""
Return the effective low and high histogram for a given systematic.
If this sample does not contain the named systematic then return
the nominal histogram for both low and high variations.
"""
if name is None:
low = self.hist.Clone(shallow=True)
high = self.hist.Clone(shallow=True)
return low, high
osys = self.GetOverallSys(name)
hsys = self.GetHistoSys(name)
if osys is None:
osys_high, osys_low = 1., 1.
else:
osys_high, osys_low = osys.high, osys.low
if hsys is None:
hsys_high = self.hist.Clone(shallow=True)
hsys_low = self.hist.Clone(shallow=True)
else:
hsys_high = hsys.high.Clone(shallow=True)
hsys_low = hsys.low.Clone(shallow=True)
return hsys_low * osys_low, hsys_high * osys_high
|
python
|
def sys_hist(self, name=None):
"""
Return the effective low and high histogram for a given systematic.
If this sample does not contain the named systematic then return
the nominal histogram for both low and high variations.
"""
if name is None:
low = self.hist.Clone(shallow=True)
high = self.hist.Clone(shallow=True)
return low, high
osys = self.GetOverallSys(name)
hsys = self.GetHistoSys(name)
if osys is None:
osys_high, osys_low = 1., 1.
else:
osys_high, osys_low = osys.high, osys.low
if hsys is None:
hsys_high = self.hist.Clone(shallow=True)
hsys_low = self.hist.Clone(shallow=True)
else:
hsys_high = hsys.high.Clone(shallow=True)
hsys_low = hsys.low.Clone(shallow=True)
return hsys_low * osys_low, hsys_high * osys_high
|
[
"def",
"sys_hist",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"low",
"=",
"self",
".",
"hist",
".",
"Clone",
"(",
"shallow",
"=",
"True",
")",
"high",
"=",
"self",
".",
"hist",
".",
"Clone",
"(",
"shallow",
"=",
"True",
")",
"return",
"low",
",",
"high",
"osys",
"=",
"self",
".",
"GetOverallSys",
"(",
"name",
")",
"hsys",
"=",
"self",
".",
"GetHistoSys",
"(",
"name",
")",
"if",
"osys",
"is",
"None",
":",
"osys_high",
",",
"osys_low",
"=",
"1.",
",",
"1.",
"else",
":",
"osys_high",
",",
"osys_low",
"=",
"osys",
".",
"high",
",",
"osys",
".",
"low",
"if",
"hsys",
"is",
"None",
":",
"hsys_high",
"=",
"self",
".",
"hist",
".",
"Clone",
"(",
"shallow",
"=",
"True",
")",
"hsys_low",
"=",
"self",
".",
"hist",
".",
"Clone",
"(",
"shallow",
"=",
"True",
")",
"else",
":",
"hsys_high",
"=",
"hsys",
".",
"high",
".",
"Clone",
"(",
"shallow",
"=",
"True",
")",
"hsys_low",
"=",
"hsys",
".",
"low",
".",
"Clone",
"(",
"shallow",
"=",
"True",
")",
"return",
"hsys_low",
"*",
"osys_low",
",",
"hsys_high",
"*",
"osys_high"
] |
Return the effective low and high histogram for a given systematic.
If this sample does not contain the named systematic then return
the nominal histogram for both low and high variations.
|
[
"Return",
"the",
"effective",
"low",
"and",
"high",
"histogram",
"for",
"a",
"given",
"systematic",
".",
"If",
"this",
"sample",
"does",
"not",
"contain",
"the",
"named",
"systematic",
"then",
"return",
"the",
"nominal",
"histogram",
"for",
"both",
"low",
"and",
"high",
"variations",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/stats/histfactory/histfactory.py#L271-L293
|
13,995
|
rootpy/rootpy
|
rootpy/stats/histfactory/histfactory.py
|
Channel.sys_hist
|
def sys_hist(self, name=None, where=None):
"""
Return the effective total low and high histogram for a given
systematic over samples in this channel.
If a sample does not contain the named systematic then its nominal
histogram is used for both low and high variations.
Parameters
----------
name : string, optional (default=None)
The systematic name otherwise nominal if None
where : callable, optional (default=None)
A callable taking one argument: the sample, and returns True if
this sample should be included in the total.
Returns
-------
total_low, total_high : histograms
The total low and high histograms for this systematic
"""
total_low, total_high = None, None
for sample in self.samples:
if where is not None and not where(sample):
continue
low, high = sample.sys_hist(name)
if total_low is None:
total_low = low.Clone(shallow=True)
else:
total_low += low
if total_high is None:
total_high = high.Clone(shallow=True)
else:
total_high += high
return total_low, total_high
|
python
|
def sys_hist(self, name=None, where=None):
"""
Return the effective total low and high histogram for a given
systematic over samples in this channel.
If a sample does not contain the named systematic then its nominal
histogram is used for both low and high variations.
Parameters
----------
name : string, optional (default=None)
The systematic name otherwise nominal if None
where : callable, optional (default=None)
A callable taking one argument: the sample, and returns True if
this sample should be included in the total.
Returns
-------
total_low, total_high : histograms
The total low and high histograms for this systematic
"""
total_low, total_high = None, None
for sample in self.samples:
if where is not None and not where(sample):
continue
low, high = sample.sys_hist(name)
if total_low is None:
total_low = low.Clone(shallow=True)
else:
total_low += low
if total_high is None:
total_high = high.Clone(shallow=True)
else:
total_high += high
return total_low, total_high
|
[
"def",
"sys_hist",
"(",
"self",
",",
"name",
"=",
"None",
",",
"where",
"=",
"None",
")",
":",
"total_low",
",",
"total_high",
"=",
"None",
",",
"None",
"for",
"sample",
"in",
"self",
".",
"samples",
":",
"if",
"where",
"is",
"not",
"None",
"and",
"not",
"where",
"(",
"sample",
")",
":",
"continue",
"low",
",",
"high",
"=",
"sample",
".",
"sys_hist",
"(",
"name",
")",
"if",
"total_low",
"is",
"None",
":",
"total_low",
"=",
"low",
".",
"Clone",
"(",
"shallow",
"=",
"True",
")",
"else",
":",
"total_low",
"+=",
"low",
"if",
"total_high",
"is",
"None",
":",
"total_high",
"=",
"high",
".",
"Clone",
"(",
"shallow",
"=",
"True",
")",
"else",
":",
"total_high",
"+=",
"high",
"return",
"total_low",
",",
"total_high"
] |
Return the effective total low and high histogram for a given
systematic over samples in this channel.
If a sample does not contain the named systematic then its nominal
histogram is used for both low and high variations.
Parameters
----------
name : string, optional (default=None)
The systematic name otherwise nominal if None
where : callable, optional (default=None)
A callable taking one argument: the sample, and returns True if
this sample should be included in the total.
Returns
-------
total_low, total_high : histograms
The total low and high histograms for this systematic
|
[
"Return",
"the",
"effective",
"total",
"low",
"and",
"high",
"histogram",
"for",
"a",
"given",
"systematic",
"over",
"samples",
"in",
"this",
"channel",
".",
"If",
"a",
"sample",
"does",
"not",
"contain",
"the",
"named",
"systematic",
"then",
"its",
"nominal",
"histogram",
"is",
"used",
"for",
"both",
"low",
"and",
"high",
"variations",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/stats/histfactory/histfactory.py#L894-L931
|
13,996
|
rootpy/rootpy
|
rootpy/stats/histfactory/histfactory.py
|
Channel.apply_snapshot
|
def apply_snapshot(self, argset):
"""
Create a clone of this Channel where histograms are modified according
to the values of the nuisance parameters in the snapshot. This is
useful when creating post-fit distribution plots.
Parameters
----------
argset : RooArtSet
A RooArgSet of RooRealVar nuisance parameters
Returns
-------
channel : Channel
The modified channel
"""
clone = self.Clone()
args = [var for var in argset if not (
var.name.startswith('binWidth_obs_x_') or
var.name.startswith('gamma_stat') or
var.name.startswith('nom_'))]
# handle NormFactors first
nargs = []
for var in args:
is_norm = False
name = var.name.replace('alpha_', '')
for sample in clone.samples:
if sample.GetNormFactor(name) is not None:
log.info("applying snapshot of {0} on sample {1}".format(
name, sample.name))
is_norm = True
# scale the entire sample
sample *= var.value
# add an OverallSys for the error
osys = OverallSys(name,
low=1. - var.error / var.value,
high=1. + var.error / var.value)
sample.AddOverallSys(osys)
# remove the NormFactor
sample.RemoveNormFactor(name)
if not is_norm:
nargs.append(var)
# modify the nominal shape and systematics
for sample in clone.samples:
# check that hist is not NULL
if sample.hist is None:
raise RuntimeError(
"sample {0} does not have a "
"nominal histogram".format(sample.name))
nominal = sample.hist.Clone(shallow=True)
for var in nargs:
name = var.name.replace('alpha_', '')
if not sample.has_sys(name):
continue
log.info("applying snapshot of {0} on sample {1}".format(
name, sample.name))
low, high = sample.sys_hist(name)
# modify nominal
val = var.value
if val > 0:
sample.hist += (high - nominal) * val
elif val < 0:
sample.hist += (nominal - low) * val
# TODO:
# modify OverallSys
# modify HistoSys
return clone
|
python
|
def apply_snapshot(self, argset):
"""
Create a clone of this Channel where histograms are modified according
to the values of the nuisance parameters in the snapshot. This is
useful when creating post-fit distribution plots.
Parameters
----------
argset : RooArtSet
A RooArgSet of RooRealVar nuisance parameters
Returns
-------
channel : Channel
The modified channel
"""
clone = self.Clone()
args = [var for var in argset if not (
var.name.startswith('binWidth_obs_x_') or
var.name.startswith('gamma_stat') or
var.name.startswith('nom_'))]
# handle NormFactors first
nargs = []
for var in args:
is_norm = False
name = var.name.replace('alpha_', '')
for sample in clone.samples:
if sample.GetNormFactor(name) is not None:
log.info("applying snapshot of {0} on sample {1}".format(
name, sample.name))
is_norm = True
# scale the entire sample
sample *= var.value
# add an OverallSys for the error
osys = OverallSys(name,
low=1. - var.error / var.value,
high=1. + var.error / var.value)
sample.AddOverallSys(osys)
# remove the NormFactor
sample.RemoveNormFactor(name)
if not is_norm:
nargs.append(var)
# modify the nominal shape and systematics
for sample in clone.samples:
# check that hist is not NULL
if sample.hist is None:
raise RuntimeError(
"sample {0} does not have a "
"nominal histogram".format(sample.name))
nominal = sample.hist.Clone(shallow=True)
for var in nargs:
name = var.name.replace('alpha_', '')
if not sample.has_sys(name):
continue
log.info("applying snapshot of {0} on sample {1}".format(
name, sample.name))
low, high = sample.sys_hist(name)
# modify nominal
val = var.value
if val > 0:
sample.hist += (high - nominal) * val
elif val < 0:
sample.hist += (nominal - low) * val
# TODO:
# modify OverallSys
# modify HistoSys
return clone
|
[
"def",
"apply_snapshot",
"(",
"self",
",",
"argset",
")",
":",
"clone",
"=",
"self",
".",
"Clone",
"(",
")",
"args",
"=",
"[",
"var",
"for",
"var",
"in",
"argset",
"if",
"not",
"(",
"var",
".",
"name",
".",
"startswith",
"(",
"'binWidth_obs_x_'",
")",
"or",
"var",
".",
"name",
".",
"startswith",
"(",
"'gamma_stat'",
")",
"or",
"var",
".",
"name",
".",
"startswith",
"(",
"'nom_'",
")",
")",
"]",
"# handle NormFactors first",
"nargs",
"=",
"[",
"]",
"for",
"var",
"in",
"args",
":",
"is_norm",
"=",
"False",
"name",
"=",
"var",
".",
"name",
".",
"replace",
"(",
"'alpha_'",
",",
"''",
")",
"for",
"sample",
"in",
"clone",
".",
"samples",
":",
"if",
"sample",
".",
"GetNormFactor",
"(",
"name",
")",
"is",
"not",
"None",
":",
"log",
".",
"info",
"(",
"\"applying snapshot of {0} on sample {1}\"",
".",
"format",
"(",
"name",
",",
"sample",
".",
"name",
")",
")",
"is_norm",
"=",
"True",
"# scale the entire sample",
"sample",
"*=",
"var",
".",
"value",
"# add an OverallSys for the error",
"osys",
"=",
"OverallSys",
"(",
"name",
",",
"low",
"=",
"1.",
"-",
"var",
".",
"error",
"/",
"var",
".",
"value",
",",
"high",
"=",
"1.",
"+",
"var",
".",
"error",
"/",
"var",
".",
"value",
")",
"sample",
".",
"AddOverallSys",
"(",
"osys",
")",
"# remove the NormFactor",
"sample",
".",
"RemoveNormFactor",
"(",
"name",
")",
"if",
"not",
"is_norm",
":",
"nargs",
".",
"append",
"(",
"var",
")",
"# modify the nominal shape and systematics",
"for",
"sample",
"in",
"clone",
".",
"samples",
":",
"# check that hist is not NULL",
"if",
"sample",
".",
"hist",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"sample {0} does not have a \"",
"\"nominal histogram\"",
".",
"format",
"(",
"sample",
".",
"name",
")",
")",
"nominal",
"=",
"sample",
".",
"hist",
".",
"Clone",
"(",
"shallow",
"=",
"True",
")",
"for",
"var",
"in",
"nargs",
":",
"name",
"=",
"var",
".",
"name",
".",
"replace",
"(",
"'alpha_'",
",",
"''",
")",
"if",
"not",
"sample",
".",
"has_sys",
"(",
"name",
")",
":",
"continue",
"log",
".",
"info",
"(",
"\"applying snapshot of {0} on sample {1}\"",
".",
"format",
"(",
"name",
",",
"sample",
".",
"name",
")",
")",
"low",
",",
"high",
"=",
"sample",
".",
"sys_hist",
"(",
"name",
")",
"# modify nominal",
"val",
"=",
"var",
".",
"value",
"if",
"val",
">",
"0",
":",
"sample",
".",
"hist",
"+=",
"(",
"high",
"-",
"nominal",
")",
"*",
"val",
"elif",
"val",
"<",
"0",
":",
"sample",
".",
"hist",
"+=",
"(",
"nominal",
"-",
"low",
")",
"*",
"val",
"# TODO:",
"# modify OverallSys",
"# modify HistoSys",
"return",
"clone"
] |
Create a clone of this Channel where histograms are modified according
to the values of the nuisance parameters in the snapshot. This is
useful when creating post-fit distribution plots.
Parameters
----------
argset : RooArtSet
A RooArgSet of RooRealVar nuisance parameters
Returns
-------
channel : Channel
The modified channel
|
[
"Create",
"a",
"clone",
"of",
"this",
"Channel",
"where",
"histograms",
"are",
"modified",
"according",
"to",
"the",
"values",
"of",
"the",
"nuisance",
"parameters",
"in",
"the",
"snapshot",
".",
"This",
"is",
"useful",
"when",
"creating",
"post",
"-",
"fit",
"distribution",
"plots",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/stats/histfactory/histfactory.py#L1040-L1109
|
13,997
|
rootpy/rootpy
|
rootpy/extern/byteplay2/__init__.py
|
printcodelist
|
def printcodelist(codelist, to=sys.stdout):
"""Get a code list. Print it nicely."""
labeldict = {}
pendinglabels = []
for i, (op, arg) in enumerate(codelist):
if isinstance(op, Label):
pendinglabels.append(op)
elif op is SetLineno:
pass
else:
while pendinglabels:
labeldict[pendinglabels.pop()] = i
lineno = None
islabel = False
for i, (op, arg) in enumerate(codelist):
if op is SetLineno:
lineno = arg
print >> to
continue
if isinstance(op, Label):
islabel = True
continue
if lineno is None:
linenostr = ''
else:
linenostr = str(lineno)
lineno = None
if islabel:
islabelstr = '>>'
islabel = False
else:
islabelstr = ''
if op in hasconst:
argstr = repr(arg)
elif op in hasjump:
try:
argstr = 'to ' + str(labeldict[arg])
except KeyError:
argstr = repr(arg)
elif op in hasarg:
argstr = str(arg)
else:
argstr = ''
print >> to, '%3s %2s %4d %-20s %s' % (
linenostr,
islabelstr,
i,
op,
argstr)
|
python
|
def printcodelist(codelist, to=sys.stdout):
"""Get a code list. Print it nicely."""
labeldict = {}
pendinglabels = []
for i, (op, arg) in enumerate(codelist):
if isinstance(op, Label):
pendinglabels.append(op)
elif op is SetLineno:
pass
else:
while pendinglabels:
labeldict[pendinglabels.pop()] = i
lineno = None
islabel = False
for i, (op, arg) in enumerate(codelist):
if op is SetLineno:
lineno = arg
print >> to
continue
if isinstance(op, Label):
islabel = True
continue
if lineno is None:
linenostr = ''
else:
linenostr = str(lineno)
lineno = None
if islabel:
islabelstr = '>>'
islabel = False
else:
islabelstr = ''
if op in hasconst:
argstr = repr(arg)
elif op in hasjump:
try:
argstr = 'to ' + str(labeldict[arg])
except KeyError:
argstr = repr(arg)
elif op in hasarg:
argstr = str(arg)
else:
argstr = ''
print >> to, '%3s %2s %4d %-20s %s' % (
linenostr,
islabelstr,
i,
op,
argstr)
|
[
"def",
"printcodelist",
"(",
"codelist",
",",
"to",
"=",
"sys",
".",
"stdout",
")",
":",
"labeldict",
"=",
"{",
"}",
"pendinglabels",
"=",
"[",
"]",
"for",
"i",
",",
"(",
"op",
",",
"arg",
")",
"in",
"enumerate",
"(",
"codelist",
")",
":",
"if",
"isinstance",
"(",
"op",
",",
"Label",
")",
":",
"pendinglabels",
".",
"append",
"(",
"op",
")",
"elif",
"op",
"is",
"SetLineno",
":",
"pass",
"else",
":",
"while",
"pendinglabels",
":",
"labeldict",
"[",
"pendinglabels",
".",
"pop",
"(",
")",
"]",
"=",
"i",
"lineno",
"=",
"None",
"islabel",
"=",
"False",
"for",
"i",
",",
"(",
"op",
",",
"arg",
")",
"in",
"enumerate",
"(",
"codelist",
")",
":",
"if",
"op",
"is",
"SetLineno",
":",
"lineno",
"=",
"arg",
"print",
">>",
"to",
"continue",
"if",
"isinstance",
"(",
"op",
",",
"Label",
")",
":",
"islabel",
"=",
"True",
"continue",
"if",
"lineno",
"is",
"None",
":",
"linenostr",
"=",
"''",
"else",
":",
"linenostr",
"=",
"str",
"(",
"lineno",
")",
"lineno",
"=",
"None",
"if",
"islabel",
":",
"islabelstr",
"=",
"'>>'",
"islabel",
"=",
"False",
"else",
":",
"islabelstr",
"=",
"''",
"if",
"op",
"in",
"hasconst",
":",
"argstr",
"=",
"repr",
"(",
"arg",
")",
"elif",
"op",
"in",
"hasjump",
":",
"try",
":",
"argstr",
"=",
"'to '",
"+",
"str",
"(",
"labeldict",
"[",
"arg",
"]",
")",
"except",
"KeyError",
":",
"argstr",
"=",
"repr",
"(",
"arg",
")",
"elif",
"op",
"in",
"hasarg",
":",
"argstr",
"=",
"str",
"(",
"arg",
")",
"else",
":",
"argstr",
"=",
"''",
"print",
">>",
"to",
",",
"'%3s %2s %4d %-20s %s'",
"%",
"(",
"linenostr",
",",
"islabelstr",
",",
"i",
",",
"op",
",",
"argstr",
")"
] |
Get a code list. Print it nicely.
|
[
"Get",
"a",
"code",
"list",
".",
"Print",
"it",
"nicely",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/byteplay2/__init__.py#L785-L840
|
13,998
|
rootpy/rootpy
|
rootpy/extern/byteplay2/__init__.py
|
recompile
|
def recompile(filename):
"""Create a .pyc by disassembling the file and assembling it again, printing
a message that the reassembled file was loaded."""
# Most of the code here based on the compile.py module.
import os
import imp
import marshal
import struct
f = open(filename, 'U')
try:
timestamp = long(os.fstat(f.fileno()).st_mtime)
except AttributeError:
timestamp = long(os.stat(filename).st_mtime)
codestring = f.read()
f.close()
if codestring and codestring[-1] != '\n':
codestring = codestring + '\n'
try:
codeobject = compile(codestring, filename, 'exec')
except SyntaxError:
print >> sys.stderr, "Skipping %s - syntax error." % filename
return
cod = Code.from_code(codeobject)
message = "reassembled %r imported.\n" % filename
cod.code[:0] = [ # __import__('sys').stderr.write(message)
(LOAD_GLOBAL, '__import__'),
(LOAD_CONST, 'sys'),
(CALL_FUNCTION, 1),
(LOAD_ATTR, 'stderr'),
(LOAD_ATTR, 'write'),
(LOAD_CONST, message),
(CALL_FUNCTION, 1),
(POP_TOP, None),
]
codeobject2 = cod.to_code()
fc = open(filename+'c', 'wb')
fc.write('\0\0\0\0')
fc.write(struct.pack('<l', timestamp))
marshal.dump(codeobject2, fc)
fc.flush()
fc.seek(0, 0)
fc.write(imp.get_magic())
fc.close()
|
python
|
def recompile(filename):
"""Create a .pyc by disassembling the file and assembling it again, printing
a message that the reassembled file was loaded."""
# Most of the code here based on the compile.py module.
import os
import imp
import marshal
import struct
f = open(filename, 'U')
try:
timestamp = long(os.fstat(f.fileno()).st_mtime)
except AttributeError:
timestamp = long(os.stat(filename).st_mtime)
codestring = f.read()
f.close()
if codestring and codestring[-1] != '\n':
codestring = codestring + '\n'
try:
codeobject = compile(codestring, filename, 'exec')
except SyntaxError:
print >> sys.stderr, "Skipping %s - syntax error." % filename
return
cod = Code.from_code(codeobject)
message = "reassembled %r imported.\n" % filename
cod.code[:0] = [ # __import__('sys').stderr.write(message)
(LOAD_GLOBAL, '__import__'),
(LOAD_CONST, 'sys'),
(CALL_FUNCTION, 1),
(LOAD_ATTR, 'stderr'),
(LOAD_ATTR, 'write'),
(LOAD_CONST, message),
(CALL_FUNCTION, 1),
(POP_TOP, None),
]
codeobject2 = cod.to_code()
fc = open(filename+'c', 'wb')
fc.write('\0\0\0\0')
fc.write(struct.pack('<l', timestamp))
marshal.dump(codeobject2, fc)
fc.flush()
fc.seek(0, 0)
fc.write(imp.get_magic())
fc.close()
|
[
"def",
"recompile",
"(",
"filename",
")",
":",
"# Most of the code here based on the compile.py module.",
"import",
"os",
"import",
"imp",
"import",
"marshal",
"import",
"struct",
"f",
"=",
"open",
"(",
"filename",
",",
"'U'",
")",
"try",
":",
"timestamp",
"=",
"long",
"(",
"os",
".",
"fstat",
"(",
"f",
".",
"fileno",
"(",
")",
")",
".",
"st_mtime",
")",
"except",
"AttributeError",
":",
"timestamp",
"=",
"long",
"(",
"os",
".",
"stat",
"(",
"filename",
")",
".",
"st_mtime",
")",
"codestring",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"if",
"codestring",
"and",
"codestring",
"[",
"-",
"1",
"]",
"!=",
"'\\n'",
":",
"codestring",
"=",
"codestring",
"+",
"'\\n'",
"try",
":",
"codeobject",
"=",
"compile",
"(",
"codestring",
",",
"filename",
",",
"'exec'",
")",
"except",
"SyntaxError",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"Skipping %s - syntax error.\"",
"%",
"filename",
"return",
"cod",
"=",
"Code",
".",
"from_code",
"(",
"codeobject",
")",
"message",
"=",
"\"reassembled %r imported.\\n\"",
"%",
"filename",
"cod",
".",
"code",
"[",
":",
"0",
"]",
"=",
"[",
"# __import__('sys').stderr.write(message)",
"(",
"LOAD_GLOBAL",
",",
"'__import__'",
")",
",",
"(",
"LOAD_CONST",
",",
"'sys'",
")",
",",
"(",
"CALL_FUNCTION",
",",
"1",
")",
",",
"(",
"LOAD_ATTR",
",",
"'stderr'",
")",
",",
"(",
"LOAD_ATTR",
",",
"'write'",
")",
",",
"(",
"LOAD_CONST",
",",
"message",
")",
",",
"(",
"CALL_FUNCTION",
",",
"1",
")",
",",
"(",
"POP_TOP",
",",
"None",
")",
",",
"]",
"codeobject2",
"=",
"cod",
".",
"to_code",
"(",
")",
"fc",
"=",
"open",
"(",
"filename",
"+",
"'c'",
",",
"'wb'",
")",
"fc",
".",
"write",
"(",
"'\\0\\0\\0\\0'",
")",
"fc",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<l'",
",",
"timestamp",
")",
")",
"marshal",
".",
"dump",
"(",
"codeobject2",
",",
"fc",
")",
"fc",
".",
"flush",
"(",
")",
"fc",
".",
"seek",
"(",
"0",
",",
"0",
")",
"fc",
".",
"write",
"(",
"imp",
".",
"get_magic",
"(",
")",
")",
"fc",
".",
"close",
"(",
")"
] |
Create a .pyc by disassembling the file and assembling it again, printing
a message that the reassembled file was loaded.
|
[
"Create",
"a",
".",
"pyc",
"by",
"disassembling",
"the",
"file",
"and",
"assembling",
"it",
"again",
"printing",
"a",
"message",
"that",
"the",
"reassembled",
"file",
"was",
"loaded",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/byteplay2/__init__.py#L842-L885
|
13,999
|
rootpy/rootpy
|
rootpy/extern/byteplay2/__init__.py
|
recompile_all
|
def recompile_all(path):
"""recursively recompile all .py files in the directory"""
import os
if os.path.isdir(path):
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith('.py'):
filename = os.path.abspath(os.path.join(root, name))
print >> sys.stderr, filename
recompile(filename)
else:
filename = os.path.abspath(path)
recompile(filename)
|
python
|
def recompile_all(path):
"""recursively recompile all .py files in the directory"""
import os
if os.path.isdir(path):
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith('.py'):
filename = os.path.abspath(os.path.join(root, name))
print >> sys.stderr, filename
recompile(filename)
else:
filename = os.path.abspath(path)
recompile(filename)
|
[
"def",
"recompile_all",
"(",
"path",
")",
":",
"import",
"os",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"name",
"in",
"files",
":",
"if",
"name",
".",
"endswith",
"(",
"'.py'",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"name",
")",
")",
"print",
">>",
"sys",
".",
"stderr",
",",
"filename",
"recompile",
"(",
"filename",
")",
"else",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"recompile",
"(",
"filename",
")"
] |
recursively recompile all .py files in the directory
|
[
"recursively",
"recompile",
"all",
".",
"py",
"files",
"in",
"the",
"directory"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/byteplay2/__init__.py#L887-L899
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.