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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
pylp/pylp | pylp/utils/paths.py | make_readable_path | def make_readable_path(path):
"""Make a path more "readable"""
home = os.path.expanduser("~")
if path.startswith(home):
path = "~" + path[len(home):]
return path | python | def make_readable_path(path):
"""Make a path more "readable"""
home = os.path.expanduser("~")
if path.startswith(home):
path = "~" + path[len(home):]
return path | [
"def",
"make_readable_path",
"(",
"path",
")",
":",
"home",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
"if",
"path",
".",
"startswith",
"(",
"home",
")",
":",
"path",
"=",
"\"~\"",
"+",
"path",
"[",
"len",
"(",
"home",
")",
":",
"]",
"return",
"path"
] | Make a path more "readable | [
"Make",
"a",
"path",
"more",
"readable"
] | 7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4 | https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/utils/paths.py#L13-L19 | train |
xflr6/bitsets | bitsets/combos.py | shortlex | def shortlex(start, other, excludestart=False):
"""Yield all unions of start with other in shortlex order.
>>> ['{:03b}'.format(s) for s in shortlex(0, [0b100, 0b010, 0b001])]
['000', '100', '010', '001', '110', '101', '011', '111']
>>> ', '.join(''.join(sorted(s))
... for s in shortlex(set(), [{'a'}, {'b'}, {'c'}, {'d'}]))
', a, b, c, d, ab, ac, ad, bc, bd, cd, abc, abd, acd, bcd, abcd'
>>> assert list(shortlex(set(), [{1}, {2}], excludestart=True)) == \
[{1}, {2}, {1, 2}]
"""
if not excludestart:
yield start
queue = collections.deque([(start, other)])
while queue:
current, other = queue.popleft()
while other:
first, other = other[0], other[1:]
result = current | first
yield result
if other:
queue.append((result, other)) | python | def shortlex(start, other, excludestart=False):
"""Yield all unions of start with other in shortlex order.
>>> ['{:03b}'.format(s) for s in shortlex(0, [0b100, 0b010, 0b001])]
['000', '100', '010', '001', '110', '101', '011', '111']
>>> ', '.join(''.join(sorted(s))
... for s in shortlex(set(), [{'a'}, {'b'}, {'c'}, {'d'}]))
', a, b, c, d, ab, ac, ad, bc, bd, cd, abc, abd, acd, bcd, abcd'
>>> assert list(shortlex(set(), [{1}, {2}], excludestart=True)) == \
[{1}, {2}, {1, 2}]
"""
if not excludestart:
yield start
queue = collections.deque([(start, other)])
while queue:
current, other = queue.popleft()
while other:
first, other = other[0], other[1:]
result = current | first
yield result
if other:
queue.append((result, other)) | [
"def",
"shortlex",
"(",
"start",
",",
"other",
",",
"excludestart",
"=",
"False",
")",
":",
"if",
"not",
"excludestart",
":",
"yield",
"start",
"queue",
"=",
"collections",
".",
"deque",
"(",
"[",
"(",
"start",
",",
"other",
")",
"]",
")",
"while",
"queue",
":",
"current",
",",
"other",
"=",
"queue",
".",
"popleft",
"(",
")",
"while",
"other",
":",
"first",
",",
"other",
"=",
"other",
"[",
"0",
"]",
",",
"other",
"[",
"1",
":",
"]",
"result",
"=",
"current",
"|",
"first",
"yield",
"result",
"if",
"other",
":",
"queue",
".",
"append",
"(",
"(",
"result",
",",
"other",
")",
")"
] | Yield all unions of start with other in shortlex order.
>>> ['{:03b}'.format(s) for s in shortlex(0, [0b100, 0b010, 0b001])]
['000', '100', '010', '001', '110', '101', '011', '111']
>>> ', '.join(''.join(sorted(s))
... for s in shortlex(set(), [{'a'}, {'b'}, {'c'}, {'d'}]))
', a, b, c, d, ab, ac, ad, bc, bd, cd, abc, abd, acd, bcd, abcd'
>>> assert list(shortlex(set(), [{1}, {2}], excludestart=True)) == \
[{1}, {2}, {1, 2}] | [
"Yield",
"all",
"unions",
"of",
"start",
"with",
"other",
"in",
"shortlex",
"order",
"."
] | ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf | https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/combos.py#L10-L38 | train |
xflr6/bitsets | bitsets/combos.py | reverse_shortlex | def reverse_shortlex(end, other, excludeend=False):
"""Yield all intersections of end with other in reverse shortlex order.
>>> ['{:03b}'.format(s) for s in reverse_shortlex(0b111, [0b011, 0b101, 0b110])]
['111', '011', '101', '110', '001', '010', '100', '000']
>>> ', '.join(''.join(sorted(s))
... for s in reverse_shortlex({'a', 'b', 'c', 'd'},
... [{'b', 'c', 'd'}, {'a', 'c', 'd'}, {'a', 'b', 'd'}, {'a', 'b', 'c'}]))
'abcd, bcd, acd, abd, abc, cd, bd, bc, ad, ac, ab, d, c, b, a, '
>>> assert list(reverse_shortlex({1, 2}, [{1}, {2}], excludeend=True)) == \
[{1}, {2}, set()]
"""
if not excludeend:
yield end
queue = collections.deque([(end, other)])
while queue:
current, other = queue.popleft()
while other:
first, other = other[0], other[1:]
result = current & first
yield result
if other:
queue.append((result, other)) | python | def reverse_shortlex(end, other, excludeend=False):
"""Yield all intersections of end with other in reverse shortlex order.
>>> ['{:03b}'.format(s) for s in reverse_shortlex(0b111, [0b011, 0b101, 0b110])]
['111', '011', '101', '110', '001', '010', '100', '000']
>>> ', '.join(''.join(sorted(s))
... for s in reverse_shortlex({'a', 'b', 'c', 'd'},
... [{'b', 'c', 'd'}, {'a', 'c', 'd'}, {'a', 'b', 'd'}, {'a', 'b', 'c'}]))
'abcd, bcd, acd, abd, abc, cd, bd, bc, ad, ac, ab, d, c, b, a, '
>>> assert list(reverse_shortlex({1, 2}, [{1}, {2}], excludeend=True)) == \
[{1}, {2}, set()]
"""
if not excludeend:
yield end
queue = collections.deque([(end, other)])
while queue:
current, other = queue.popleft()
while other:
first, other = other[0], other[1:]
result = current & first
yield result
if other:
queue.append((result, other)) | [
"def",
"reverse_shortlex",
"(",
"end",
",",
"other",
",",
"excludeend",
"=",
"False",
")",
":",
"if",
"not",
"excludeend",
":",
"yield",
"end",
"queue",
"=",
"collections",
".",
"deque",
"(",
"[",
"(",
"end",
",",
"other",
")",
"]",
")",
"while",
"queue",
":",
"current",
",",
"other",
"=",
"queue",
".",
"popleft",
"(",
")",
"while",
"other",
":",
"first",
",",
"other",
"=",
"other",
"[",
"0",
"]",
",",
"other",
"[",
"1",
":",
"]",
"result",
"=",
"current",
"&",
"first",
"yield",
"result",
"if",
"other",
":",
"queue",
".",
"append",
"(",
"(",
"result",
",",
"other",
")",
")"
] | Yield all intersections of end with other in reverse shortlex order.
>>> ['{:03b}'.format(s) for s in reverse_shortlex(0b111, [0b011, 0b101, 0b110])]
['111', '011', '101', '110', '001', '010', '100', '000']
>>> ', '.join(''.join(sorted(s))
... for s in reverse_shortlex({'a', 'b', 'c', 'd'},
... [{'b', 'c', 'd'}, {'a', 'c', 'd'}, {'a', 'b', 'd'}, {'a', 'b', 'c'}]))
'abcd, bcd, acd, abd, abc, cd, bd, bc, ad, ac, ab, d, c, b, a, '
>>> assert list(reverse_shortlex({1, 2}, [{1}, {2}], excludeend=True)) == \
[{1}, {2}, set()] | [
"Yield",
"all",
"intersections",
"of",
"end",
"with",
"other",
"in",
"reverse",
"shortlex",
"order",
"."
] | ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf | https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/combos.py#L41-L70 | train |
druids/django-chamber | chamber/models/fields.py | RestrictedFileFieldMixin.generate_filename | def generate_filename(self, instance, filename):
"""
removes UTF chars from filename
"""
from unidecode import unidecode
return super().generate_filename(instance, unidecode(force_text(filename))) | python | def generate_filename(self, instance, filename):
"""
removes UTF chars from filename
"""
from unidecode import unidecode
return super().generate_filename(instance, unidecode(force_text(filename))) | [
"def",
"generate_filename",
"(",
"self",
",",
"instance",
",",
"filename",
")",
":",
"from",
"unidecode",
"import",
"unidecode",
"return",
"super",
"(",
")",
".",
"generate_filename",
"(",
"instance",
",",
"unidecode",
"(",
"force_text",
"(",
"filename",
")",
")",
")"
] | removes UTF chars from filename | [
"removes",
"UTF",
"chars",
"from",
"filename"
] | eef4169923557e96877a664fa254e8c0814f3f23 | https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/models/fields.py#L69-L75 | train |
PaulMcMillan/tasa | tasa/store.py | Queue.next | def next(self):
""" Retrieve the next item in the queue.
Returns deserialized value, or None if there were no entries
in the Queue.
"""
if self.blocking >= 0:
# returns queue name and item, we just need item
res = self.redis.blpop([self.name], timeout=self.blocking)
if res:
res = res[1]
else:
res = self.redis.lpop(self.name)
value = self.deserialize(res)
logger.debug('Popped from "%s": %s', self.name, repr(value))
return value | python | def next(self):
""" Retrieve the next item in the queue.
Returns deserialized value, or None if there were no entries
in the Queue.
"""
if self.blocking >= 0:
# returns queue name and item, we just need item
res = self.redis.blpop([self.name], timeout=self.blocking)
if res:
res = res[1]
else:
res = self.redis.lpop(self.name)
value = self.deserialize(res)
logger.debug('Popped from "%s": %s', self.name, repr(value))
return value | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"blocking",
">=",
"0",
":",
"# returns queue name and item, we just need item",
"res",
"=",
"self",
".",
"redis",
".",
"blpop",
"(",
"[",
"self",
".",
"name",
"]",
",",
"timeout",
"=",
"self",
".",
"blocking",
")",
"if",
"res",
":",
"res",
"=",
"res",
"[",
"1",
"]",
"else",
":",
"res",
"=",
"self",
".",
"redis",
".",
"lpop",
"(",
"self",
".",
"name",
")",
"value",
"=",
"self",
".",
"deserialize",
"(",
"res",
")",
"logger",
".",
"debug",
"(",
"'Popped from \"%s\": %s'",
",",
"self",
".",
"name",
",",
"repr",
"(",
"value",
")",
")",
"return",
"value"
] | Retrieve the next item in the queue.
Returns deserialized value, or None if there were no entries
in the Queue. | [
"Retrieve",
"the",
"next",
"item",
"in",
"the",
"queue",
"."
] | fd548d97fd08e61c0e71296b08ffedb7d949e06a | https://github.com/PaulMcMillan/tasa/blob/fd548d97fd08e61c0e71296b08ffedb7d949e06a/tasa/store.py#L58-L73 | train |
PaulMcMillan/tasa | tasa/store.py | Queue.send | def send(self, *args):
""" Send a value to this LIFO Queue.
Provided argument is serialized and pushed out. Don't send None.
"""
# this and the serializer could use some streamlining
if None in args:
raise TypeError('None is not a valid queue item.')
serialized_values = [self.serialize(value) for value in args]
logger.debug('Sending to "%s": %s', self.name, serialized_values)
return self.redis.rpush(self.name, *serialized_values) | python | def send(self, *args):
""" Send a value to this LIFO Queue.
Provided argument is serialized and pushed out. Don't send None.
"""
# this and the serializer could use some streamlining
if None in args:
raise TypeError('None is not a valid queue item.')
serialized_values = [self.serialize(value) for value in args]
logger.debug('Sending to "%s": %s', self.name, serialized_values)
return self.redis.rpush(self.name, *serialized_values) | [
"def",
"send",
"(",
"self",
",",
"*",
"args",
")",
":",
"# this and the serializer could use some streamlining",
"if",
"None",
"in",
"args",
":",
"raise",
"TypeError",
"(",
"'None is not a valid queue item.'",
")",
"serialized_values",
"=",
"[",
"self",
".",
"serialize",
"(",
"value",
")",
"for",
"value",
"in",
"args",
"]",
"logger",
".",
"debug",
"(",
"'Sending to \"%s\": %s'",
",",
"self",
".",
"name",
",",
"serialized_values",
")",
"return",
"self",
".",
"redis",
".",
"rpush",
"(",
"self",
".",
"name",
",",
"*",
"serialized_values",
")"
] | Send a value to this LIFO Queue.
Provided argument is serialized and pushed out. Don't send None. | [
"Send",
"a",
"value",
"to",
"this",
"LIFO",
"Queue",
"."
] | fd548d97fd08e61c0e71296b08ffedb7d949e06a | https://github.com/PaulMcMillan/tasa/blob/fd548d97fd08e61c0e71296b08ffedb7d949e06a/tasa/store.py#L75-L85 | train |
PaulMcMillan/tasa | tasa/store.py | Queue.clear | def clear(self):
""" Clear any existing values from this queue. """
logger.debug('Clearing queue: "%s"', self.name)
return self.redis.delete(self.name) | python | def clear(self):
""" Clear any existing values from this queue. """
logger.debug('Clearing queue: "%s"', self.name)
return self.redis.delete(self.name) | [
"def",
"clear",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Clearing queue: \"%s\"'",
",",
"self",
".",
"name",
")",
"return",
"self",
".",
"redis",
".",
"delete",
"(",
"self",
".",
"name",
")"
] | Clear any existing values from this queue. | [
"Clear",
"any",
"existing",
"values",
"from",
"this",
"queue",
"."
] | fd548d97fd08e61c0e71296b08ffedb7d949e06a | https://github.com/PaulMcMillan/tasa/blob/fd548d97fd08e61c0e71296b08ffedb7d949e06a/tasa/store.py#L99-L102 | train |
PierreRust/apigpio | apigpio/apigpio.py | u2i | def u2i(uint32):
"""
Converts a 32 bit unsigned number to signed.
uint32:= an unsigned 32 bit number
...
print(u2i(4294967272))
-24
print(u2i(37))
37
...
"""
mask = (2 ** 32) - 1
if uint32 & (1 << 31):
v = uint32 | ~mask
else:
v = uint32 & mask
return v | python | def u2i(uint32):
"""
Converts a 32 bit unsigned number to signed.
uint32:= an unsigned 32 bit number
...
print(u2i(4294967272))
-24
print(u2i(37))
37
...
"""
mask = (2 ** 32) - 1
if uint32 & (1 << 31):
v = uint32 | ~mask
else:
v = uint32 & mask
return v | [
"def",
"u2i",
"(",
"uint32",
")",
":",
"mask",
"=",
"(",
"2",
"**",
"32",
")",
"-",
"1",
"if",
"uint32",
"&",
"(",
"1",
"<<",
"31",
")",
":",
"v",
"=",
"uint32",
"|",
"~",
"mask",
"else",
":",
"v",
"=",
"uint32",
"&",
"mask",
"return",
"v"
] | Converts a 32 bit unsigned number to signed.
uint32:= an unsigned 32 bit number
...
print(u2i(4294967272))
-24
print(u2i(37))
37
... | [
"Converts",
"a",
"32",
"bit",
"unsigned",
"number",
"to",
"signed",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L301-L319 | train |
PierreRust/apigpio | apigpio/apigpio.py | _u2i | def _u2i(uint32):
"""
Converts a 32 bit unsigned number to signed. If the number
is negative it indicates an error. On error a pigpio
exception will be raised if exceptions is True.
"""
v = u2i(uint32)
if v < 0:
if exceptions:
raise ApigpioError(error_text(v))
return v | python | def _u2i(uint32):
"""
Converts a 32 bit unsigned number to signed. If the number
is negative it indicates an error. On error a pigpio
exception will be raised if exceptions is True.
"""
v = u2i(uint32)
if v < 0:
if exceptions:
raise ApigpioError(error_text(v))
return v | [
"def",
"_u2i",
"(",
"uint32",
")",
":",
"v",
"=",
"u2i",
"(",
"uint32",
")",
"if",
"v",
"<",
"0",
":",
"if",
"exceptions",
":",
"raise",
"ApigpioError",
"(",
"error_text",
"(",
"v",
")",
")",
"return",
"v"
] | Converts a 32 bit unsigned number to signed. If the number
is negative it indicates an error. On error a pigpio
exception will be raised if exceptions is True. | [
"Converts",
"a",
"32",
"bit",
"unsigned",
"number",
"to",
"signed",
".",
"If",
"the",
"number",
"is",
"negative",
"it",
"indicates",
"an",
"error",
".",
"On",
"error",
"a",
"pigpio",
"exception",
"will",
"be",
"raised",
"if",
"exceptions",
"is",
"True",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L322-L332 | train |
PierreRust/apigpio | apigpio/apigpio.py | _callback_handler.append | def append(self, cb):
"""Adds a callback."""
self.callbacks.append(cb.callb)
self.monitor = self.monitor | cb.callb.bit
yield from self.pi._pigpio_aio_command(_PI_CMD_NB, self.handle,
self.monitor) | python | def append(self, cb):
"""Adds a callback."""
self.callbacks.append(cb.callb)
self.monitor = self.monitor | cb.callb.bit
yield from self.pi._pigpio_aio_command(_PI_CMD_NB, self.handle,
self.monitor) | [
"def",
"append",
"(",
"self",
",",
"cb",
")",
":",
"self",
".",
"callbacks",
".",
"append",
"(",
"cb",
".",
"callb",
")",
"self",
".",
"monitor",
"=",
"self",
".",
"monitor",
"|",
"cb",
".",
"callb",
".",
"bit",
"yield",
"from",
"self",
".",
"pi",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_NB",
",",
"self",
".",
"handle",
",",
"self",
".",
"monitor",
")"
] | Adds a callback. | [
"Adds",
"a",
"callback",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L450-L456 | train |
PierreRust/apigpio | apigpio/apigpio.py | _callback_handler.remove | def remove(self, cb):
"""Removes a callback."""
if cb in self.callbacks:
self.callbacks.remove(cb)
new_monitor = 0
for c in self.callbacks:
new_monitor |= c.bit
if new_monitor != self.monitor:
self.monitor = new_monitor
yield from self.pi._pigpio_aio_command(
_PI_CMD_NB, self.handle, self.monitor) | python | def remove(self, cb):
"""Removes a callback."""
if cb in self.callbacks:
self.callbacks.remove(cb)
new_monitor = 0
for c in self.callbacks:
new_monitor |= c.bit
if new_monitor != self.monitor:
self.monitor = new_monitor
yield from self.pi._pigpio_aio_command(
_PI_CMD_NB, self.handle, self.monitor) | [
"def",
"remove",
"(",
"self",
",",
"cb",
")",
":",
"if",
"cb",
"in",
"self",
".",
"callbacks",
":",
"self",
".",
"callbacks",
".",
"remove",
"(",
"cb",
")",
"new_monitor",
"=",
"0",
"for",
"c",
"in",
"self",
".",
"callbacks",
":",
"new_monitor",
"|=",
"c",
".",
"bit",
"if",
"new_monitor",
"!=",
"self",
".",
"monitor",
":",
"self",
".",
"monitor",
"=",
"new_monitor",
"yield",
"from",
"self",
".",
"pi",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_NB",
",",
"self",
".",
"handle",
",",
"self",
".",
"monitor",
")"
] | Removes a callback. | [
"Removes",
"a",
"callback",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L459-L469 | train |
PierreRust/apigpio | apigpio/apigpio.py | Pi._pigpio_aio_command | def _pigpio_aio_command(self, cmd, p1, p2,):
"""
Runs a pigpio socket command.
sl:= command socket and lock.
cmd:= the command to be executed.
p1:= command parameter 1 (if applicable).
p2:= command parameter 2 (if applicable).
"""
with (yield from self._lock):
data = struct.pack('IIII', cmd, p1, p2, 0)
self._loop.sock_sendall(self.s, data)
response = yield from self._loop.sock_recv(self.s, 16)
_, res = struct.unpack('12sI', response)
return res | python | def _pigpio_aio_command(self, cmd, p1, p2,):
"""
Runs a pigpio socket command.
sl:= command socket and lock.
cmd:= the command to be executed.
p1:= command parameter 1 (if applicable).
p2:= command parameter 2 (if applicable).
"""
with (yield from self._lock):
data = struct.pack('IIII', cmd, p1, p2, 0)
self._loop.sock_sendall(self.s, data)
response = yield from self._loop.sock_recv(self.s, 16)
_, res = struct.unpack('12sI', response)
return res | [
"def",
"_pigpio_aio_command",
"(",
"self",
",",
"cmd",
",",
"p1",
",",
"p2",
",",
")",
":",
"with",
"(",
"yield",
"from",
"self",
".",
"_lock",
")",
":",
"data",
"=",
"struct",
".",
"pack",
"(",
"'IIII'",
",",
"cmd",
",",
"p1",
",",
"p2",
",",
"0",
")",
"self",
".",
"_loop",
".",
"sock_sendall",
"(",
"self",
".",
"s",
",",
"data",
")",
"response",
"=",
"yield",
"from",
"self",
".",
"_loop",
".",
"sock_recv",
"(",
"self",
".",
"s",
",",
"16",
")",
"_",
",",
"res",
"=",
"struct",
".",
"unpack",
"(",
"'12sI'",
",",
"response",
")",
"return",
"res"
] | Runs a pigpio socket command.
sl:= command socket and lock.
cmd:= the command to be executed.
p1:= command parameter 1 (if applicable).
p2:= command parameter 2 (if applicable). | [
"Runs",
"a",
"pigpio",
"socket",
"command",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L518-L532 | train |
PierreRust/apigpio | apigpio/apigpio.py | Pi._pigpio_aio_command_ext | def _pigpio_aio_command_ext(self, cmd, p1, p2, p3, extents, rl=True):
"""
Runs an extended pigpio socket command.
sl:= command socket and lock.
cmd:= the command to be executed.
p1:= command parameter 1 (if applicable).
p2:= command parameter 2 (if applicable).
p3:= total size in bytes of following extents
extents:= additional data blocks
"""
with (yield from self._lock):
ext = bytearray(struct.pack('IIII', cmd, p1, p2, p3))
for x in extents:
if isinstance(x, str):
ext.extend(_b(x))
else:
ext.extend(x)
self._loop.sock_sendall(self.s, ext)
response = yield from self._loop.sock_recv(self.s, 16)
_, res = struct.unpack('12sI', response)
return res | python | def _pigpio_aio_command_ext(self, cmd, p1, p2, p3, extents, rl=True):
"""
Runs an extended pigpio socket command.
sl:= command socket and lock.
cmd:= the command to be executed.
p1:= command parameter 1 (if applicable).
p2:= command parameter 2 (if applicable).
p3:= total size in bytes of following extents
extents:= additional data blocks
"""
with (yield from self._lock):
ext = bytearray(struct.pack('IIII', cmd, p1, p2, p3))
for x in extents:
if isinstance(x, str):
ext.extend(_b(x))
else:
ext.extend(x)
self._loop.sock_sendall(self.s, ext)
response = yield from self._loop.sock_recv(self.s, 16)
_, res = struct.unpack('12sI', response)
return res | [
"def",
"_pigpio_aio_command_ext",
"(",
"self",
",",
"cmd",
",",
"p1",
",",
"p2",
",",
"p3",
",",
"extents",
",",
"rl",
"=",
"True",
")",
":",
"with",
"(",
"yield",
"from",
"self",
".",
"_lock",
")",
":",
"ext",
"=",
"bytearray",
"(",
"struct",
".",
"pack",
"(",
"'IIII'",
",",
"cmd",
",",
"p1",
",",
"p2",
",",
"p3",
")",
")",
"for",
"x",
"in",
"extents",
":",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"ext",
".",
"extend",
"(",
"_b",
"(",
"x",
")",
")",
"else",
":",
"ext",
".",
"extend",
"(",
"x",
")",
"self",
".",
"_loop",
".",
"sock_sendall",
"(",
"self",
".",
"s",
",",
"ext",
")",
"response",
"=",
"yield",
"from",
"self",
".",
"_loop",
".",
"sock_recv",
"(",
"self",
".",
"s",
",",
"16",
")",
"_",
",",
"res",
"=",
"struct",
".",
"unpack",
"(",
"'12sI'",
",",
"response",
")",
"return",
"res"
] | Runs an extended pigpio socket command.
sl:= command socket and lock.
cmd:= the command to be executed.
p1:= command parameter 1 (if applicable).
p2:= command parameter 2 (if applicable).
p3:= total size in bytes of following extents
extents:= additional data blocks | [
"Runs",
"an",
"extended",
"pigpio",
"socket",
"command",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L535-L556 | train |
PierreRust/apigpio | apigpio/apigpio.py | Pi.store_script | def store_script(self, script):
"""
Store a script for later execution.
script:= the script text as a series of bytes.
Returns a >=0 script id if OK.
...
sid = pi.store_script(
b'tag 0 w 22 1 mils 100 w 22 0 mils 100 dcr p0 jp 0')
...
"""
if len(script):
res = yield from self._pigpio_aio_command_ext(_PI_CMD_PROC, 0, 0,
len(script),
[script])
return _u2i(res)
else:
return 0 | python | def store_script(self, script):
"""
Store a script for later execution.
script:= the script text as a series of bytes.
Returns a >=0 script id if OK.
...
sid = pi.store_script(
b'tag 0 w 22 1 mils 100 w 22 0 mils 100 dcr p0 jp 0')
...
"""
if len(script):
res = yield from self._pigpio_aio_command_ext(_PI_CMD_PROC, 0, 0,
len(script),
[script])
return _u2i(res)
else:
return 0 | [
"def",
"store_script",
"(",
"self",
",",
"script",
")",
":",
"if",
"len",
"(",
"script",
")",
":",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command_ext",
"(",
"_PI_CMD_PROC",
",",
"0",
",",
"0",
",",
"len",
"(",
"script",
")",
",",
"[",
"script",
"]",
")",
"return",
"_u2i",
"(",
"res",
")",
"else",
":",
"return",
"0"
] | Store a script for later execution.
script:= the script text as a series of bytes.
Returns a >=0 script id if OK.
...
sid = pi.store_script(
b'tag 0 w 22 1 mils 100 w 22 0 mils 100 dcr p0 jp 0')
... | [
"Store",
"a",
"script",
"for",
"later",
"execution",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L603-L622 | train |
PierreRust/apigpio | apigpio/apigpio.py | Pi.run_script | def run_script(self, script_id, params=None):
"""
Runs a stored script.
script_id:= id of stored script.
params:= up to 10 parameters required by the script.
...
s = pi.run_script(sid, [par1, par2])
s = pi.run_script(sid)
s = pi.run_script(sid, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
...
"""
# I p1 script id
# I p2 0
# I p3 params * 4 (0-10 params)
# (optional) extension
# I[] params
if params is not None:
ext = bytearray()
for p in params:
ext.extend(struct.pack("I", p))
nump = len(params)
extents = [ext]
else:
nump = 0
extents = []
res = yield from self._pigpio_aio_command_ext(_PI_CMD_PROCR, script_id,
0, nump * 4, extents)
return _u2i(res) | python | def run_script(self, script_id, params=None):
"""
Runs a stored script.
script_id:= id of stored script.
params:= up to 10 parameters required by the script.
...
s = pi.run_script(sid, [par1, par2])
s = pi.run_script(sid)
s = pi.run_script(sid, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
...
"""
# I p1 script id
# I p2 0
# I p3 params * 4 (0-10 params)
# (optional) extension
# I[] params
if params is not None:
ext = bytearray()
for p in params:
ext.extend(struct.pack("I", p))
nump = len(params)
extents = [ext]
else:
nump = 0
extents = []
res = yield from self._pigpio_aio_command_ext(_PI_CMD_PROCR, script_id,
0, nump * 4, extents)
return _u2i(res) | [
"def",
"run_script",
"(",
"self",
",",
"script_id",
",",
"params",
"=",
"None",
")",
":",
"# I p1 script id",
"# I p2 0",
"# I p3 params * 4 (0-10 params)",
"# (optional) extension",
"# I[] params",
"if",
"params",
"is",
"not",
"None",
":",
"ext",
"=",
"bytearray",
"(",
")",
"for",
"p",
"in",
"params",
":",
"ext",
".",
"extend",
"(",
"struct",
".",
"pack",
"(",
"\"I\"",
",",
"p",
")",
")",
"nump",
"=",
"len",
"(",
"params",
")",
"extents",
"=",
"[",
"ext",
"]",
"else",
":",
"nump",
"=",
"0",
"extents",
"=",
"[",
"]",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command_ext",
"(",
"_PI_CMD_PROCR",
",",
"script_id",
",",
"0",
",",
"nump",
"*",
"4",
",",
"extents",
")",
"return",
"_u2i",
"(",
"res",
")"
] | Runs a stored script.
script_id:= id of stored script.
params:= up to 10 parameters required by the script.
...
s = pi.run_script(sid, [par1, par2])
s = pi.run_script(sid)
s = pi.run_script(sid, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
... | [
"Runs",
"a",
"stored",
"script",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L625-L656 | train |
PierreRust/apigpio | apigpio/apigpio.py | Pi.script_status | def script_status(self, script_id):
"""
Returns the run status of a stored script as well as the
current values of parameters 0 to 9.
script_id:= id of stored script.
The run status may be
. .
PI_SCRIPT_INITING
PI_SCRIPT_HALTED
PI_SCRIPT_RUNNING
PI_SCRIPT_WAITING
PI_SCRIPT_FAILED
. .
The return value is a tuple of run status and a list of
the 10 parameters. On error the run status will be negative
and the parameter list will be empty.
...
(s, pars) = pi.script_status(sid)
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_PROCP, script_id, 0)
bytes = u2i(res)
if bytes > 0:
# Fixme : this sould be the same a _rxbuf
# data = self._rxbuf(bytes)
data = yield from self._loop.sock_recv(self.s, bytes)
while len(data) < bytes:
b = yield from self._loop.sock_recv(self.s, bytes-len(data))
data.extend(b)
pars = struct.unpack('11i', _str(data))
status = pars[0]
params = pars[1:]
else:
status = bytes
params = ()
return status, params | python | def script_status(self, script_id):
"""
Returns the run status of a stored script as well as the
current values of parameters 0 to 9.
script_id:= id of stored script.
The run status may be
. .
PI_SCRIPT_INITING
PI_SCRIPT_HALTED
PI_SCRIPT_RUNNING
PI_SCRIPT_WAITING
PI_SCRIPT_FAILED
. .
The return value is a tuple of run status and a list of
the 10 parameters. On error the run status will be negative
and the parameter list will be empty.
...
(s, pars) = pi.script_status(sid)
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_PROCP, script_id, 0)
bytes = u2i(res)
if bytes > 0:
# Fixme : this sould be the same a _rxbuf
# data = self._rxbuf(bytes)
data = yield from self._loop.sock_recv(self.s, bytes)
while len(data) < bytes:
b = yield from self._loop.sock_recv(self.s, bytes-len(data))
data.extend(b)
pars = struct.unpack('11i', _str(data))
status = pars[0]
params = pars[1:]
else:
status = bytes
params = ()
return status, params | [
"def",
"script_status",
"(",
"self",
",",
"script_id",
")",
":",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_PROCP",
",",
"script_id",
",",
"0",
")",
"bytes",
"=",
"u2i",
"(",
"res",
")",
"if",
"bytes",
">",
"0",
":",
"# Fixme : this sould be the same a _rxbuf",
"# data = self._rxbuf(bytes)",
"data",
"=",
"yield",
"from",
"self",
".",
"_loop",
".",
"sock_recv",
"(",
"self",
".",
"s",
",",
"bytes",
")",
"while",
"len",
"(",
"data",
")",
"<",
"bytes",
":",
"b",
"=",
"yield",
"from",
"self",
".",
"_loop",
".",
"sock_recv",
"(",
"self",
".",
"s",
",",
"bytes",
"-",
"len",
"(",
"data",
")",
")",
"data",
".",
"extend",
"(",
"b",
")",
"pars",
"=",
"struct",
".",
"unpack",
"(",
"'11i'",
",",
"_str",
"(",
"data",
")",
")",
"status",
"=",
"pars",
"[",
"0",
"]",
"params",
"=",
"pars",
"[",
"1",
":",
"]",
"else",
":",
"status",
"=",
"bytes",
"params",
"=",
"(",
")",
"return",
"status",
",",
"params"
] | Returns the run status of a stored script as well as the
current values of parameters 0 to 9.
script_id:= id of stored script.
The run status may be
. .
PI_SCRIPT_INITING
PI_SCRIPT_HALTED
PI_SCRIPT_RUNNING
PI_SCRIPT_WAITING
PI_SCRIPT_FAILED
. .
The return value is a tuple of run status and a list of
the 10 parameters. On error the run status will be negative
and the parameter list will be empty.
...
(s, pars) = pi.script_status(sid)
... | [
"Returns",
"the",
"run",
"status",
"of",
"a",
"stored",
"script",
"as",
"well",
"as",
"the",
"current",
"values",
"of",
"parameters",
"0",
"to",
"9",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L659-L702 | train |
PierreRust/apigpio | apigpio/apigpio.py | Pi.stop_script | def stop_script(self, script_id):
"""
Stops a running script.
script_id:= id of stored script.
...
status = pi.stop_script(sid)
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_PROCS, script_id, 0)
return _u2i(res) | python | def stop_script(self, script_id):
"""
Stops a running script.
script_id:= id of stored script.
...
status = pi.stop_script(sid)
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_PROCS, script_id, 0)
return _u2i(res) | [
"def",
"stop_script",
"(",
"self",
",",
"script_id",
")",
":",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_PROCS",
",",
"script_id",
",",
"0",
")",
"return",
"_u2i",
"(",
"res",
")"
] | Stops a running script.
script_id:= id of stored script.
...
status = pi.stop_script(sid)
... | [
"Stops",
"a",
"running",
"script",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L705-L716 | train |
PierreRust/apigpio | apigpio/apigpio.py | Pi.delete_script | def delete_script(self, script_id):
"""
Deletes a stored script.
script_id:= id of stored script.
...
status = pi.delete_script(sid)
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_PROCD, script_id, 0)
return _u2i(res) | python | def delete_script(self, script_id):
"""
Deletes a stored script.
script_id:= id of stored script.
...
status = pi.delete_script(sid)
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_PROCD, script_id, 0)
return _u2i(res) | [
"def",
"delete_script",
"(",
"self",
",",
"script_id",
")",
":",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_PROCD",
",",
"script_id",
",",
"0",
")",
"return",
"_u2i",
"(",
"res",
")"
] | Deletes a stored script.
script_id:= id of stored script.
...
status = pi.delete_script(sid)
... | [
"Deletes",
"a",
"stored",
"script",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L719-L730 | train |
PierreRust/apigpio | apigpio/apigpio.py | Pi.clear_bank_1 | def clear_bank_1(self, bits):
"""
Clears gpios 0-31 if the corresponding bit in bits is set.
bits:= a 32 bit mask with 1 set if the corresponding gpio is
to be cleared.
A returned status of PI_SOME_PERMITTED indicates that the user
is not allowed to write to one or more of the gpios.
...
pi.clear_bank_1(int("111110010000",2))
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_BC1, bits, 0)
return _u2i(res) | python | def clear_bank_1(self, bits):
"""
Clears gpios 0-31 if the corresponding bit in bits is set.
bits:= a 32 bit mask with 1 set if the corresponding gpio is
to be cleared.
A returned status of PI_SOME_PERMITTED indicates that the user
is not allowed to write to one or more of the gpios.
...
pi.clear_bank_1(int("111110010000",2))
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_BC1, bits, 0)
return _u2i(res) | [
"def",
"clear_bank_1",
"(",
"self",
",",
"bits",
")",
":",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_BC1",
",",
"bits",
",",
"0",
")",
"return",
"_u2i",
"(",
"res",
")"
] | Clears gpios 0-31 if the corresponding bit in bits is set.
bits:= a 32 bit mask with 1 set if the corresponding gpio is
to be cleared.
A returned status of PI_SOME_PERMITTED indicates that the user
is not allowed to write to one or more of the gpios.
...
pi.clear_bank_1(int("111110010000",2))
... | [
"Clears",
"gpios",
"0",
"-",
"31",
"if",
"the",
"corresponding",
"bit",
"in",
"bits",
"is",
"set",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L749-L764 | train |
PierreRust/apigpio | apigpio/apigpio.py | Pi.set_bank_1 | def set_bank_1(self, bits):
"""
Sets gpios 0-31 if the corresponding bit in bits is set.
bits:= a 32 bit mask with 1 set if the corresponding gpio is
to be set.
A returned status of PI_SOME_PERMITTED indicates that the user
is not allowed to write to one or more of the gpios.
...
pi.set_bank_1(int("111110010000",2))
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_BS1, bits, 0)
return _u2i(res) | python | def set_bank_1(self, bits):
"""
Sets gpios 0-31 if the corresponding bit in bits is set.
bits:= a 32 bit mask with 1 set if the corresponding gpio is
to be set.
A returned status of PI_SOME_PERMITTED indicates that the user
is not allowed to write to one or more of the gpios.
...
pi.set_bank_1(int("111110010000",2))
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_BS1, bits, 0)
return _u2i(res) | [
"def",
"set_bank_1",
"(",
"self",
",",
"bits",
")",
":",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_BS1",
",",
"bits",
",",
"0",
")",
"return",
"_u2i",
"(",
"res",
")"
] | Sets gpios 0-31 if the corresponding bit in bits is set.
bits:= a 32 bit mask with 1 set if the corresponding gpio is
to be set.
A returned status of PI_SOME_PERMITTED indicates that the user
is not allowed to write to one or more of the gpios.
...
pi.set_bank_1(int("111110010000",2))
... | [
"Sets",
"gpios",
"0",
"-",
"31",
"if",
"the",
"corresponding",
"bit",
"in",
"bits",
"is",
"set",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L767-L782 | train |
PierreRust/apigpio | apigpio/apigpio.py | Pi.set_mode | def set_mode(self, gpio, mode):
"""
Sets the gpio mode.
gpio:= 0-53.
mode:= INPUT, OUTPUT, ALT0, ALT1, ALT2, ALT3, ALT4, ALT5.
...
pi.set_mode( 4, apigpio.INPUT) # gpio 4 as input
pi.set_mode(17, apigpio.OUTPUT) # gpio 17 as output
pi.set_mode(24, apigpio.ALT2) # gpio 24 as ALT2
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_MODES, gpio, mode)
return _u2i(res) | python | def set_mode(self, gpio, mode):
"""
Sets the gpio mode.
gpio:= 0-53.
mode:= INPUT, OUTPUT, ALT0, ALT1, ALT2, ALT3, ALT4, ALT5.
...
pi.set_mode( 4, apigpio.INPUT) # gpio 4 as input
pi.set_mode(17, apigpio.OUTPUT) # gpio 17 as output
pi.set_mode(24, apigpio.ALT2) # gpio 24 as ALT2
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_MODES, gpio, mode)
return _u2i(res) | [
"def",
"set_mode",
"(",
"self",
",",
"gpio",
",",
"mode",
")",
":",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_MODES",
",",
"gpio",
",",
"mode",
")",
"return",
"_u2i",
"(",
"res",
")"
] | Sets the gpio mode.
gpio:= 0-53.
mode:= INPUT, OUTPUT, ALT0, ALT1, ALT2, ALT3, ALT4, ALT5.
...
pi.set_mode( 4, apigpio.INPUT) # gpio 4 as input
pi.set_mode(17, apigpio.OUTPUT) # gpio 17 as output
pi.set_mode(24, apigpio.ALT2) # gpio 24 as ALT2
... | [
"Sets",
"the",
"gpio",
"mode",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L785-L799 | train |
PierreRust/apigpio | apigpio/apigpio.py | Pi.get_mode | def get_mode(self, gpio):
"""
Returns the gpio mode.
gpio:= 0-53.
Returns a value as follows
. .
0 = INPUT
1 = OUTPUT
2 = ALT5
3 = ALT4
4 = ALT0
5 = ALT1
6 = ALT2
7 = ALT3
. .
...
print(pi.get_mode(0))
4
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_MODEG, gpio, 0)
return _u2i(res) | python | def get_mode(self, gpio):
"""
Returns the gpio mode.
gpio:= 0-53.
Returns a value as follows
. .
0 = INPUT
1 = OUTPUT
2 = ALT5
3 = ALT4
4 = ALT0
5 = ALT1
6 = ALT2
7 = ALT3
. .
...
print(pi.get_mode(0))
4
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_MODEG, gpio, 0)
return _u2i(res) | [
"def",
"get_mode",
"(",
"self",
",",
"gpio",
")",
":",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_MODEG",
",",
"gpio",
",",
"0",
")",
"return",
"_u2i",
"(",
"res",
")"
] | Returns the gpio mode.
gpio:= 0-53.
Returns a value as follows
. .
0 = INPUT
1 = OUTPUT
2 = ALT5
3 = ALT4
4 = ALT0
5 = ALT1
6 = ALT2
7 = ALT3
. .
...
print(pi.get_mode(0))
4
... | [
"Returns",
"the",
"gpio",
"mode",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L817-L842 | train |
PierreRust/apigpio | apigpio/apigpio.py | Pi.write | def write(self, gpio, level):
"""
Sets the gpio level.
gpio:= 0-53.
level:= 0, 1.
If PWM or servo pulses are active on the gpio they are
switched off.
...
pi.set_mode(17, pigpio.OUTPUT)
pi.write(17,0)
print(pi.read(17))
0
pi.write(17,1)
print(pi.read(17))
1
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_WRITE, gpio, level)
return _u2i(res) | python | def write(self, gpio, level):
"""
Sets the gpio level.
gpio:= 0-53.
level:= 0, 1.
If PWM or servo pulses are active on the gpio they are
switched off.
...
pi.set_mode(17, pigpio.OUTPUT)
pi.write(17,0)
print(pi.read(17))
0
pi.write(17,1)
print(pi.read(17))
1
...
"""
res = yield from self._pigpio_aio_command(_PI_CMD_WRITE, gpio, level)
return _u2i(res) | [
"def",
"write",
"(",
"self",
",",
"gpio",
",",
"level",
")",
":",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_WRITE",
",",
"gpio",
",",
"level",
")",
"return",
"_u2i",
"(",
"res",
")"
] | Sets the gpio level.
gpio:= 0-53.
level:= 0, 1.
If PWM or servo pulses are active on the gpio they are
switched off.
...
pi.set_mode(17, pigpio.OUTPUT)
pi.write(17,0)
print(pi.read(17))
0
pi.write(17,1)
print(pi.read(17))
1
... | [
"Sets",
"the",
"gpio",
"level",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L845-L868 | train |
kyzima-spb/flask-pony | flask_pony/utils.py | camelcase2list | def camelcase2list(s, lower=False):
"""Converts a camelcase string to a list."""
s = re.findall(r'([A-Z][a-z0-9]+)', s)
return [w.lower() for w in s] if lower else s | python | def camelcase2list(s, lower=False):
"""Converts a camelcase string to a list."""
s = re.findall(r'([A-Z][a-z0-9]+)', s)
return [w.lower() for w in s] if lower else s | [
"def",
"camelcase2list",
"(",
"s",
",",
"lower",
"=",
"False",
")",
":",
"s",
"=",
"re",
".",
"findall",
"(",
"r'([A-Z][a-z0-9]+)'",
",",
"s",
")",
"return",
"[",
"w",
".",
"lower",
"(",
")",
"for",
"w",
"in",
"s",
"]",
"if",
"lower",
"else",
"s"
] | Converts a camelcase string to a list. | [
"Converts",
"a",
"camelcase",
"string",
"to",
"a",
"list",
"."
] | 6cf28d70b7ebf415d58fa138fcc70b8dd57432c7 | https://github.com/kyzima-spb/flask-pony/blob/6cf28d70b7ebf415d58fa138fcc70b8dd57432c7/flask_pony/utils.py#L27-L30 | train |
kyzima-spb/flask-pony | flask_pony/utils.py | get_route_param_names | def get_route_param_names(endpoint):
"""Returns parameter names from the route."""
try:
g = current_app.url_map.iter_rules(endpoint)
return next(g).arguments
except KeyError:
return {} | python | def get_route_param_names(endpoint):
"""Returns parameter names from the route."""
try:
g = current_app.url_map.iter_rules(endpoint)
return next(g).arguments
except KeyError:
return {} | [
"def",
"get_route_param_names",
"(",
"endpoint",
")",
":",
"try",
":",
"g",
"=",
"current_app",
".",
"url_map",
".",
"iter_rules",
"(",
"endpoint",
")",
"return",
"next",
"(",
"g",
")",
".",
"arguments",
"except",
"KeyError",
":",
"return",
"{",
"}"
] | Returns parameter names from the route. | [
"Returns",
"parameter",
"names",
"from",
"the",
"route",
"."
] | 6cf28d70b7ebf415d58fa138fcc70b8dd57432c7 | https://github.com/kyzima-spb/flask-pony/blob/6cf28d70b7ebf415d58fa138fcc70b8dd57432c7/flask_pony/utils.py#L33-L39 | train |
guaix-ucm/numina | numina/types/structured.py | BaseStructuredCalibration.update_meta_info | def update_meta_info(self):
"""Extract metadata from myself"""
result = super(BaseStructuredCalibration, self).update_meta_info()
result['instrument'] = self.instrument
result['uuid'] = self.uuid
result['tags'] = self.tags
result['type'] = self.name()
minfo = self.meta_info
try:
result['mode'] = minfo['mode_name']
origin = minfo['origin']
date_obs = origin['date_obs']
except KeyError:
origin = {}
date_obs = "1970-01-01T00:00:00.00"
result['observation_date'] = conv.convert_date(date_obs)
result['origin'] = origin
return result | python | def update_meta_info(self):
"""Extract metadata from myself"""
result = super(BaseStructuredCalibration, self).update_meta_info()
result['instrument'] = self.instrument
result['uuid'] = self.uuid
result['tags'] = self.tags
result['type'] = self.name()
minfo = self.meta_info
try:
result['mode'] = minfo['mode_name']
origin = minfo['origin']
date_obs = origin['date_obs']
except KeyError:
origin = {}
date_obs = "1970-01-01T00:00:00.00"
result['observation_date'] = conv.convert_date(date_obs)
result['origin'] = origin
return result | [
"def",
"update_meta_info",
"(",
"self",
")",
":",
"result",
"=",
"super",
"(",
"BaseStructuredCalibration",
",",
"self",
")",
".",
"update_meta_info",
"(",
")",
"result",
"[",
"'instrument'",
"]",
"=",
"self",
".",
"instrument",
"result",
"[",
"'uuid'",
"]",
"=",
"self",
".",
"uuid",
"result",
"[",
"'tags'",
"]",
"=",
"self",
".",
"tags",
"result",
"[",
"'type'",
"]",
"=",
"self",
".",
"name",
"(",
")",
"minfo",
"=",
"self",
".",
"meta_info",
"try",
":",
"result",
"[",
"'mode'",
"]",
"=",
"minfo",
"[",
"'mode_name'",
"]",
"origin",
"=",
"minfo",
"[",
"'origin'",
"]",
"date_obs",
"=",
"origin",
"[",
"'date_obs'",
"]",
"except",
"KeyError",
":",
"origin",
"=",
"{",
"}",
"date_obs",
"=",
"\"1970-01-01T00:00:00.00\"",
"result",
"[",
"'observation_date'",
"]",
"=",
"conv",
".",
"convert_date",
"(",
"date_obs",
")",
"result",
"[",
"'origin'",
"]",
"=",
"origin",
"return",
"result"
] | Extract metadata from myself | [
"Extract",
"metadata",
"from",
"myself"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/types/structured.py#L197-L218 | train |
jtambasco/gnuplotpy | gnuplotpy/gnuplot.py | gnuplot | def gnuplot(script_name, args_dict={}, data=[], silent=True):
'''
Call a Gnuplot script, passing it arguments and
datasets.
Args:
scipt_name(str): The name of the Gnuplot script.
args_dict(dict): A dictionary of parameters to pass
to the script. The `key` is the name of the variable
that the `item` will be passed to the Gnuplot script
with.
data(list): A list of lists containing lists to be plotted.
The lists can be accessed by plotting the variable
`data` in the Gnuplot script. The first list in the
list of lists corresponds to the first column in data,
and so on.
silent (bool): `True` if Gnuplot stdout should be silenced,
`False` if not.
Returns:
str: The Gnuplot command used to call the script.
'''
gnuplot_command = 'gnuplot'
if data:
assert 'data' not in args_dict, \
'Can\'t use \'data\' variable twice.'
data_temp = _GnuplotDataTemp(*data)
args_dict['data'] = data_temp.name
if args_dict:
gnuplot_command += ' -e "'
for arg in args_dict.items():
gnuplot_command += arg[0] + '='
if isinstance(arg[1], str):
gnuplot_command += '\'' + arg[1] + '\''
elif isinstance(arg[1], bool):
if arg[1] is True:
gnuplot_command += '1'
else:
gnuplot_command += '0'
elif hasattr(arg[1], '__iter__'):
gnuplot_command += '\'' + ' '.join([str(v) for v in arg[1]]) + '\''
else:
gnuplot_command += str(arg[1])
gnuplot_command += '; '
gnuplot_command = gnuplot_command[:-1]
gnuplot_command += '"'
gnuplot_command += ' ' + script_name
if silent:
gnuplot_command += ' > /dev/null 2>&1'
os.system(gnuplot_command)
return gnuplot_command | python | def gnuplot(script_name, args_dict={}, data=[], silent=True):
'''
Call a Gnuplot script, passing it arguments and
datasets.
Args:
scipt_name(str): The name of the Gnuplot script.
args_dict(dict): A dictionary of parameters to pass
to the script. The `key` is the name of the variable
that the `item` will be passed to the Gnuplot script
with.
data(list): A list of lists containing lists to be plotted.
The lists can be accessed by plotting the variable
`data` in the Gnuplot script. The first list in the
list of lists corresponds to the first column in data,
and so on.
silent (bool): `True` if Gnuplot stdout should be silenced,
`False` if not.
Returns:
str: The Gnuplot command used to call the script.
'''
gnuplot_command = 'gnuplot'
if data:
assert 'data' not in args_dict, \
'Can\'t use \'data\' variable twice.'
data_temp = _GnuplotDataTemp(*data)
args_dict['data'] = data_temp.name
if args_dict:
gnuplot_command += ' -e "'
for arg in args_dict.items():
gnuplot_command += arg[0] + '='
if isinstance(arg[1], str):
gnuplot_command += '\'' + arg[1] + '\''
elif isinstance(arg[1], bool):
if arg[1] is True:
gnuplot_command += '1'
else:
gnuplot_command += '0'
elif hasattr(arg[1], '__iter__'):
gnuplot_command += '\'' + ' '.join([str(v) for v in arg[1]]) + '\''
else:
gnuplot_command += str(arg[1])
gnuplot_command += '; '
gnuplot_command = gnuplot_command[:-1]
gnuplot_command += '"'
gnuplot_command += ' ' + script_name
if silent:
gnuplot_command += ' > /dev/null 2>&1'
os.system(gnuplot_command)
return gnuplot_command | [
"def",
"gnuplot",
"(",
"script_name",
",",
"args_dict",
"=",
"{",
"}",
",",
"data",
"=",
"[",
"]",
",",
"silent",
"=",
"True",
")",
":",
"gnuplot_command",
"=",
"'gnuplot'",
"if",
"data",
":",
"assert",
"'data'",
"not",
"in",
"args_dict",
",",
"'Can\\'t use \\'data\\' variable twice.'",
"data_temp",
"=",
"_GnuplotDataTemp",
"(",
"*",
"data",
")",
"args_dict",
"[",
"'data'",
"]",
"=",
"data_temp",
".",
"name",
"if",
"args_dict",
":",
"gnuplot_command",
"+=",
"' -e \"'",
"for",
"arg",
"in",
"args_dict",
".",
"items",
"(",
")",
":",
"gnuplot_command",
"+=",
"arg",
"[",
"0",
"]",
"+",
"'='",
"if",
"isinstance",
"(",
"arg",
"[",
"1",
"]",
",",
"str",
")",
":",
"gnuplot_command",
"+=",
"'\\''",
"+",
"arg",
"[",
"1",
"]",
"+",
"'\\''",
"elif",
"isinstance",
"(",
"arg",
"[",
"1",
"]",
",",
"bool",
")",
":",
"if",
"arg",
"[",
"1",
"]",
"is",
"True",
":",
"gnuplot_command",
"+=",
"'1'",
"else",
":",
"gnuplot_command",
"+=",
"'0'",
"elif",
"hasattr",
"(",
"arg",
"[",
"1",
"]",
",",
"'__iter__'",
")",
":",
"gnuplot_command",
"+=",
"'\\''",
"+",
"' '",
".",
"join",
"(",
"[",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"arg",
"[",
"1",
"]",
"]",
")",
"+",
"'\\''",
"else",
":",
"gnuplot_command",
"+=",
"str",
"(",
"arg",
"[",
"1",
"]",
")",
"gnuplot_command",
"+=",
"'; '",
"gnuplot_command",
"=",
"gnuplot_command",
"[",
":",
"-",
"1",
"]",
"gnuplot_command",
"+=",
"'\"'",
"gnuplot_command",
"+=",
"' '",
"+",
"script_name",
"if",
"silent",
":",
"gnuplot_command",
"+=",
"' > /dev/null 2>&1'",
"os",
".",
"system",
"(",
"gnuplot_command",
")",
"return",
"gnuplot_command"
] | Call a Gnuplot script, passing it arguments and
datasets.
Args:
scipt_name(str): The name of the Gnuplot script.
args_dict(dict): A dictionary of parameters to pass
to the script. The `key` is the name of the variable
that the `item` will be passed to the Gnuplot script
with.
data(list): A list of lists containing lists to be plotted.
The lists can be accessed by plotting the variable
`data` in the Gnuplot script. The first list in the
list of lists corresponds to the first column in data,
and so on.
silent (bool): `True` if Gnuplot stdout should be silenced,
`False` if not.
Returns:
str: The Gnuplot command used to call the script. | [
"Call",
"a",
"Gnuplot",
"script",
"passing",
"it",
"arguments",
"and",
"datasets",
"."
] | 0e67fa0b839f94981f8e18dfd42c30f98b68f500 | https://github.com/jtambasco/gnuplotpy/blob/0e67fa0b839f94981f8e18dfd42c30f98b68f500/gnuplotpy/gnuplot.py#L39-L96 | train |
jtambasco/gnuplotpy | gnuplotpy/gnuplot.py | gnuplot_2d | def gnuplot_2d(x, y, filename, title='', x_label='', y_label=''):
'''
Function to produce a general 2D plot.
Args:
x (list): x points.
y (list): y points.
filename (str): Filename of the output image.
title (str): Title of the plot. Default is '' (no title).
x_label (str): x-axis label.
y_label (str): y-axis label.
'''
_, ext = os.path.splitext(filename)
if ext != '.png':
filename += '.png'
gnuplot_cmds = \
'''
set datafile separator ","
set term pngcairo size 30cm,25cm
set out filename
unset key
set border lw 1.5
set grid lt -1 lc rgb "gray80"
set title title
set xlabel x_label
set ylabel y_label
plot filename_data u 1:2 w lp pt 6 ps 0.5
'''
scr = _GnuplotScriptTemp(gnuplot_cmds)
data = _GnuplotDataTemp(x, y)
args_dict = {
'filename': filename,
'filename_data': data.name,
'title': title,
'x_label': x_label,
'y_label': y_label
}
gnuplot(scr.name, args_dict) | python | def gnuplot_2d(x, y, filename, title='', x_label='', y_label=''):
'''
Function to produce a general 2D plot.
Args:
x (list): x points.
y (list): y points.
filename (str): Filename of the output image.
title (str): Title of the plot. Default is '' (no title).
x_label (str): x-axis label.
y_label (str): y-axis label.
'''
_, ext = os.path.splitext(filename)
if ext != '.png':
filename += '.png'
gnuplot_cmds = \
'''
set datafile separator ","
set term pngcairo size 30cm,25cm
set out filename
unset key
set border lw 1.5
set grid lt -1 lc rgb "gray80"
set title title
set xlabel x_label
set ylabel y_label
plot filename_data u 1:2 w lp pt 6 ps 0.5
'''
scr = _GnuplotScriptTemp(gnuplot_cmds)
data = _GnuplotDataTemp(x, y)
args_dict = {
'filename': filename,
'filename_data': data.name,
'title': title,
'x_label': x_label,
'y_label': y_label
}
gnuplot(scr.name, args_dict) | [
"def",
"gnuplot_2d",
"(",
"x",
",",
"y",
",",
"filename",
",",
"title",
"=",
"''",
",",
"x_label",
"=",
"''",
",",
"y_label",
"=",
"''",
")",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"ext",
"!=",
"'.png'",
":",
"filename",
"+=",
"'.png'",
"gnuplot_cmds",
"=",
"'''\n set datafile separator \",\"\n set term pngcairo size 30cm,25cm\n set out filename\n\n unset key\n set border lw 1.5\n set grid lt -1 lc rgb \"gray80\"\n\n set title title\n set xlabel x_label\n set ylabel y_label\n\n plot filename_data u 1:2 w lp pt 6 ps 0.5\n '''",
"scr",
"=",
"_GnuplotScriptTemp",
"(",
"gnuplot_cmds",
")",
"data",
"=",
"_GnuplotDataTemp",
"(",
"x",
",",
"y",
")",
"args_dict",
"=",
"{",
"'filename'",
":",
"filename",
",",
"'filename_data'",
":",
"data",
".",
"name",
",",
"'title'",
":",
"title",
",",
"'x_label'",
":",
"x_label",
",",
"'y_label'",
":",
"y_label",
"}",
"gnuplot",
"(",
"scr",
".",
"name",
",",
"args_dict",
")"
] | Function to produce a general 2D plot.
Args:
x (list): x points.
y (list): y points.
filename (str): Filename of the output image.
title (str): Title of the plot. Default is '' (no title).
x_label (str): x-axis label.
y_label (str): y-axis label. | [
"Function",
"to",
"produce",
"a",
"general",
"2D",
"plot",
"."
] | 0e67fa0b839f94981f8e18dfd42c30f98b68f500 | https://github.com/jtambasco/gnuplotpy/blob/0e67fa0b839f94981f8e18dfd42c30f98b68f500/gnuplotpy/gnuplot.py#L98-L140 | train |
jtambasco/gnuplotpy | gnuplotpy/gnuplot.py | gnuplot_3d_matrix | def gnuplot_3d_matrix(z_matrix, filename, title='', x_label='', y_label=''):
'''
Function to produce a general 3D plot from a 2D matrix.
Args:
z_matrix (list): 2D matrix.
filename (str): Filename of the output image.
title (str): Title of the plot. Default is '' (no title).
x_label (str): x-axis label.
y_label (str): y-axis label.
'''
_, ext = os.path.splitext(filename)
if ext != '.png':
filename += '.png'
gnuplot_cmds = \
'''
set datafile separator ","
set term pngcairo size 30cm,25cm
set out filename
unset key
set border lw 1.5
set view map
set title title
set xlabel x_label
set ylabel y_label
splot filename_data matrix w pm3d
'''
scr = _GnuplotScriptTemp(gnuplot_cmds)
data = _GnuplotDataZMatrixTemp(z_matrix)
args_dict = {
'filename': filename,
'filename_data': data.name,
'title': title,
'x_label': x_label,
'y_label': y_label
}
gnuplot(scr.name, args_dict) | python | def gnuplot_3d_matrix(z_matrix, filename, title='', x_label='', y_label=''):
'''
Function to produce a general 3D plot from a 2D matrix.
Args:
z_matrix (list): 2D matrix.
filename (str): Filename of the output image.
title (str): Title of the plot. Default is '' (no title).
x_label (str): x-axis label.
y_label (str): y-axis label.
'''
_, ext = os.path.splitext(filename)
if ext != '.png':
filename += '.png'
gnuplot_cmds = \
'''
set datafile separator ","
set term pngcairo size 30cm,25cm
set out filename
unset key
set border lw 1.5
set view map
set title title
set xlabel x_label
set ylabel y_label
splot filename_data matrix w pm3d
'''
scr = _GnuplotScriptTemp(gnuplot_cmds)
data = _GnuplotDataZMatrixTemp(z_matrix)
args_dict = {
'filename': filename,
'filename_data': data.name,
'title': title,
'x_label': x_label,
'y_label': y_label
}
gnuplot(scr.name, args_dict) | [
"def",
"gnuplot_3d_matrix",
"(",
"z_matrix",
",",
"filename",
",",
"title",
"=",
"''",
",",
"x_label",
"=",
"''",
",",
"y_label",
"=",
"''",
")",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"ext",
"!=",
"'.png'",
":",
"filename",
"+=",
"'.png'",
"gnuplot_cmds",
"=",
"'''\n set datafile separator \",\"\n set term pngcairo size 30cm,25cm\n set out filename\n\n unset key\n set border lw 1.5\n set view map\n\n set title title\n set xlabel x_label\n set ylabel y_label\n\n splot filename_data matrix w pm3d\n '''",
"scr",
"=",
"_GnuplotScriptTemp",
"(",
"gnuplot_cmds",
")",
"data",
"=",
"_GnuplotDataZMatrixTemp",
"(",
"z_matrix",
")",
"args_dict",
"=",
"{",
"'filename'",
":",
"filename",
",",
"'filename_data'",
":",
"data",
".",
"name",
",",
"'title'",
":",
"title",
",",
"'x_label'",
":",
"x_label",
",",
"'y_label'",
":",
"y_label",
"}",
"gnuplot",
"(",
"scr",
".",
"name",
",",
"args_dict",
")"
] | Function to produce a general 3D plot from a 2D matrix.
Args:
z_matrix (list): 2D matrix.
filename (str): Filename of the output image.
title (str): Title of the plot. Default is '' (no title).
x_label (str): x-axis label.
y_label (str): y-axis label. | [
"Function",
"to",
"produce",
"a",
"general",
"3D",
"plot",
"from",
"a",
"2D",
"matrix",
"."
] | 0e67fa0b839f94981f8e18dfd42c30f98b68f500 | https://github.com/jtambasco/gnuplotpy/blob/0e67fa0b839f94981f8e18dfd42c30f98b68f500/gnuplotpy/gnuplot.py#L190-L231 | train |
SUNCAT-Center/CatHub | cathub/folderreader.py | FolderReader.read | def read(self, skip=[], goto_metal=None, goto_reaction=None):
"""
Get reactions from folders.
Parameters
----------
skip: list of str
list of folders not to read
goto_reaction: str
Skip ahead to this metal
goto_reaction:
Skip ahead to this reacion
"""
if len(skip) > 0:
for skip_f in skip:
self.omit_folders.append(skip_f)
""" If publication level is input"""
if os.path.isfile(self.data_base + '/publication.txt'):
self.user_base_level -= 1
self.stdout.write('---------------------- \n')
self.stdout.write('Starting folderreader! \n')
self.stdout.write('---------------------- \n')
found_reaction = False
for root, dirs, files in os.walk(self.user_base):
for omit_folder in self.omit_folders: # user specified omit_folder
if omit_folder in dirs:
dirs.remove(omit_folder)
level = len(root.split("/")) - self.user_base_level
if level == self.pub_level:
self.read_pub(root)
if level == self.DFT_level:
self.DFT_code = os.path.basename(root)
if level == self.XC_level:
self.DFT_functional = os.path.basename(root)
self.gas_folder = root + '/gas/'
self.read_gas()
if level == self.reference_level:
if 'gas' in os.path.basename(root):
continue
if goto_metal is not None:
if os.path.basename(root) == goto_metal:
goto_metal = None
else:
dirs[:] = [] # don't read any sub_dirs
continue
self.read_bulk(root)
if level == self.slab_level:
self.read_slab(root)
if level == self.reaction_level:
if goto_reaction is not None:
if os.path.basename(root) == goto_reaction:
goto_reaction = None
else:
dirs[:] = [] # don't read any sub_dirs
continue
self.read_reaction(root)
if level == self.final_level:
self.root = root
self.read_energies(root)
if self.key_value_pairs_reaction is not None:
yield self.key_value_pairs_reaction | python | def read(self, skip=[], goto_metal=None, goto_reaction=None):
"""
Get reactions from folders.
Parameters
----------
skip: list of str
list of folders not to read
goto_reaction: str
Skip ahead to this metal
goto_reaction:
Skip ahead to this reacion
"""
if len(skip) > 0:
for skip_f in skip:
self.omit_folders.append(skip_f)
""" If publication level is input"""
if os.path.isfile(self.data_base + '/publication.txt'):
self.user_base_level -= 1
self.stdout.write('---------------------- \n')
self.stdout.write('Starting folderreader! \n')
self.stdout.write('---------------------- \n')
found_reaction = False
for root, dirs, files in os.walk(self.user_base):
for omit_folder in self.omit_folders: # user specified omit_folder
if omit_folder in dirs:
dirs.remove(omit_folder)
level = len(root.split("/")) - self.user_base_level
if level == self.pub_level:
self.read_pub(root)
if level == self.DFT_level:
self.DFT_code = os.path.basename(root)
if level == self.XC_level:
self.DFT_functional = os.path.basename(root)
self.gas_folder = root + '/gas/'
self.read_gas()
if level == self.reference_level:
if 'gas' in os.path.basename(root):
continue
if goto_metal is not None:
if os.path.basename(root) == goto_metal:
goto_metal = None
else:
dirs[:] = [] # don't read any sub_dirs
continue
self.read_bulk(root)
if level == self.slab_level:
self.read_slab(root)
if level == self.reaction_level:
if goto_reaction is not None:
if os.path.basename(root) == goto_reaction:
goto_reaction = None
else:
dirs[:] = [] # don't read any sub_dirs
continue
self.read_reaction(root)
if level == self.final_level:
self.root = root
self.read_energies(root)
if self.key_value_pairs_reaction is not None:
yield self.key_value_pairs_reaction | [
"def",
"read",
"(",
"self",
",",
"skip",
"=",
"[",
"]",
",",
"goto_metal",
"=",
"None",
",",
"goto_reaction",
"=",
"None",
")",
":",
"if",
"len",
"(",
"skip",
")",
">",
"0",
":",
"for",
"skip_f",
"in",
"skip",
":",
"self",
".",
"omit_folders",
".",
"append",
"(",
"skip_f",
")",
"\"\"\" If publication level is input\"\"\"",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"data_base",
"+",
"'/publication.txt'",
")",
":",
"self",
".",
"user_base_level",
"-=",
"1",
"self",
".",
"stdout",
".",
"write",
"(",
"'---------------------- \\n'",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"'Starting folderreader! \\n'",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"'---------------------- \\n'",
")",
"found_reaction",
"=",
"False",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"self",
".",
"user_base",
")",
":",
"for",
"omit_folder",
"in",
"self",
".",
"omit_folders",
":",
"# user specified omit_folder",
"if",
"omit_folder",
"in",
"dirs",
":",
"dirs",
".",
"remove",
"(",
"omit_folder",
")",
"level",
"=",
"len",
"(",
"root",
".",
"split",
"(",
"\"/\"",
")",
")",
"-",
"self",
".",
"user_base_level",
"if",
"level",
"==",
"self",
".",
"pub_level",
":",
"self",
".",
"read_pub",
"(",
"root",
")",
"if",
"level",
"==",
"self",
".",
"DFT_level",
":",
"self",
".",
"DFT_code",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"root",
")",
"if",
"level",
"==",
"self",
".",
"XC_level",
":",
"self",
".",
"DFT_functional",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"root",
")",
"self",
".",
"gas_folder",
"=",
"root",
"+",
"'/gas/'",
"self",
".",
"read_gas",
"(",
")",
"if",
"level",
"==",
"self",
".",
"reference_level",
":",
"if",
"'gas'",
"in",
"os",
".",
"path",
".",
"basename",
"(",
"root",
")",
":",
"continue",
"if",
"goto_metal",
"is",
"not",
"None",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"root",
")",
"==",
"goto_metal",
":",
"goto_metal",
"=",
"None",
"else",
":",
"dirs",
"[",
":",
"]",
"=",
"[",
"]",
"# don't read any sub_dirs",
"continue",
"self",
".",
"read_bulk",
"(",
"root",
")",
"if",
"level",
"==",
"self",
".",
"slab_level",
":",
"self",
".",
"read_slab",
"(",
"root",
")",
"if",
"level",
"==",
"self",
".",
"reaction_level",
":",
"if",
"goto_reaction",
"is",
"not",
"None",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"root",
")",
"==",
"goto_reaction",
":",
"goto_reaction",
"=",
"None",
"else",
":",
"dirs",
"[",
":",
"]",
"=",
"[",
"]",
"# don't read any sub_dirs",
"continue",
"self",
".",
"read_reaction",
"(",
"root",
")",
"if",
"level",
"==",
"self",
".",
"final_level",
":",
"self",
".",
"root",
"=",
"root",
"self",
".",
"read_energies",
"(",
"root",
")",
"if",
"self",
".",
"key_value_pairs_reaction",
"is",
"not",
"None",
":",
"yield",
"self",
".",
"key_value_pairs_reaction"
] | Get reactions from folders.
Parameters
----------
skip: list of str
list of folders not to read
goto_reaction: str
Skip ahead to this metal
goto_reaction:
Skip ahead to this reacion | [
"Get",
"reactions",
"from",
"folders",
"."
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/folderreader.py#L79-L150 | train |
guaix-ucm/numina | numina/array/utils.py | slice_create | def slice_create(center, block, start=0, stop=None):
'''Return an slice with a symmetric region around center.'''
do = coor_to_pix_1d(center - block)
up = coor_to_pix_1d(center + block)
l = max(start, do)
if stop is not None:
h = min(up + 1, stop)
else:
h = up + 1
return slice(l, h, 1) | python | def slice_create(center, block, start=0, stop=None):
'''Return an slice with a symmetric region around center.'''
do = coor_to_pix_1d(center - block)
up = coor_to_pix_1d(center + block)
l = max(start, do)
if stop is not None:
h = min(up + 1, stop)
else:
h = up + 1
return slice(l, h, 1) | [
"def",
"slice_create",
"(",
"center",
",",
"block",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"None",
")",
":",
"do",
"=",
"coor_to_pix_1d",
"(",
"center",
"-",
"block",
")",
"up",
"=",
"coor_to_pix_1d",
"(",
"center",
"+",
"block",
")",
"l",
"=",
"max",
"(",
"start",
",",
"do",
")",
"if",
"stop",
"is",
"not",
"None",
":",
"h",
"=",
"min",
"(",
"up",
"+",
"1",
",",
"stop",
")",
"else",
":",
"h",
"=",
"up",
"+",
"1",
"return",
"slice",
"(",
"l",
",",
"h",
",",
"1",
")"
] | Return an slice with a symmetric region around center. | [
"Return",
"an",
"slice",
"with",
"a",
"symmetric",
"region",
"around",
"center",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/utils.py#L40-L53 | train |
guaix-ucm/numina | numina/array/utils.py | image_box | def image_box(center, shape, box):
'''Create a region of size box, around a center in a image of shape.'''
return tuple(slice_create(c, b, stop=s)
for c, s, b in zip(center, shape, box)) | python | def image_box(center, shape, box):
'''Create a region of size box, around a center in a image of shape.'''
return tuple(slice_create(c, b, stop=s)
for c, s, b in zip(center, shape, box)) | [
"def",
"image_box",
"(",
"center",
",",
"shape",
",",
"box",
")",
":",
"return",
"tuple",
"(",
"slice_create",
"(",
"c",
",",
"b",
",",
"stop",
"=",
"s",
")",
"for",
"c",
",",
"s",
",",
"b",
"in",
"zip",
"(",
"center",
",",
"shape",
",",
"box",
")",
")"
] | Create a region of size box, around a center in a image of shape. | [
"Create",
"a",
"region",
"of",
"size",
"box",
"around",
"a",
"center",
"in",
"a",
"image",
"of",
"shape",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/utils.py#L56-L59 | train |
guaix-ucm/numina | numina/array/utils.py | expand_region | def expand_region(tuple_of_s, a, b, start=0, stop=None):
'''Apply expend_slice on a tuple of slices'''
return tuple(expand_slice(s, a, b, start=start, stop=stop)
for s in tuple_of_s) | python | def expand_region(tuple_of_s, a, b, start=0, stop=None):
'''Apply expend_slice on a tuple of slices'''
return tuple(expand_slice(s, a, b, start=start, stop=stop)
for s in tuple_of_s) | [
"def",
"expand_region",
"(",
"tuple_of_s",
",",
"a",
",",
"b",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"None",
")",
":",
"return",
"tuple",
"(",
"expand_slice",
"(",
"s",
",",
"a",
",",
"b",
",",
"start",
"=",
"start",
",",
"stop",
"=",
"stop",
")",
"for",
"s",
"in",
"tuple_of_s",
")"
] | Apply expend_slice on a tuple of slices | [
"Apply",
"expend_slice",
"on",
"a",
"tuple",
"of",
"slices"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/utils.py#L81-L84 | train |
guaix-ucm/numina | numina/user/helpers.py | BaseWorkEnvironment.adapt_obsres | def adapt_obsres(self, obsres):
"""Adapt obsres after file copy"""
_logger.debug('adapt observation result for work dir')
for f in obsres.images:
# Remove path components
f.filename = os.path.basename(f.filename)
return obsres | python | def adapt_obsres(self, obsres):
"""Adapt obsres after file copy"""
_logger.debug('adapt observation result for work dir')
for f in obsres.images:
# Remove path components
f.filename = os.path.basename(f.filename)
return obsres | [
"def",
"adapt_obsres",
"(",
"self",
",",
"obsres",
")",
":",
"_logger",
".",
"debug",
"(",
"'adapt observation result for work dir'",
")",
"for",
"f",
"in",
"obsres",
".",
"images",
":",
"# Remove path components",
"f",
".",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"f",
".",
"filename",
")",
"return",
"obsres"
] | Adapt obsres after file copy | [
"Adapt",
"obsres",
"after",
"file",
"copy"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/user/helpers.py#L326-L333 | train |
guaix-ucm/numina | numina/user/helpers.py | DiskStorageBase.store | def store(self, completed_task, resultsdir):
"""Store the values of the completed task."""
with working_directory(resultsdir):
_logger.info('storing result')
return completed_task.store(self) | python | def store(self, completed_task, resultsdir):
"""Store the values of the completed task."""
with working_directory(resultsdir):
_logger.info('storing result')
return completed_task.store(self) | [
"def",
"store",
"(",
"self",
",",
"completed_task",
",",
"resultsdir",
")",
":",
"with",
"working_directory",
"(",
"resultsdir",
")",
":",
"_logger",
".",
"info",
"(",
"'storing result'",
")",
"return",
"completed_task",
".",
"store",
"(",
"self",
")"
] | Store the values of the completed task. | [
"Store",
"the",
"values",
"of",
"the",
"completed",
"task",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/user/helpers.py#L396-L401 | train |
guaix-ucm/numina | numina/types/datatype.py | DataType.validate | def validate(self, obj):
"""Validate convertibility to internal representation
Returns
-------
bool
True if 'obj' matches the data type
Raises
-------
ValidationError
If the validation fails
"""
if not isinstance(obj, self.internal_type):
raise ValidationError(obj, self.internal_type)
return True | python | def validate(self, obj):
"""Validate convertibility to internal representation
Returns
-------
bool
True if 'obj' matches the data type
Raises
-------
ValidationError
If the validation fails
"""
if not isinstance(obj, self.internal_type):
raise ValidationError(obj, self.internal_type)
return True | [
"def",
"validate",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"self",
".",
"internal_type",
")",
":",
"raise",
"ValidationError",
"(",
"obj",
",",
"self",
".",
"internal_type",
")",
"return",
"True"
] | Validate convertibility to internal representation
Returns
-------
bool
True if 'obj' matches the data type
Raises
-------
ValidationError
If the validation fails | [
"Validate",
"convertibility",
"to",
"internal",
"representation"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/types/datatype.py#L50-L66 | train |
SUNCAT-Center/CatHub | cathub/postgresql.py | CathubPostgreSQL.delete_user | def delete_user(self, user):
""" Delete user and all data"""
assert self.user == 'catroot' or self.user == 'postgres'
assert not user == 'public'
con = self.connection or self._connect()
cur = con.cursor()
cur.execute('DROP SCHEMA {user} CASCADE;'.format(user=user))
cur.execute('REVOKE USAGE ON SCHEMA public FROM {user};'
.format(user=user))
cur.execute(
'REVOKE SELECT ON ALL TABLES IN SCHEMA public FROM {user};'
.format(user=user))
cur.execute(
'DROP ROLE {user};'.format(user=user))
self.stdout.write(
'REMOVED USER {user}\n'.format(user=user))
if self.connection is None:
con.commit()
con.close()
return self | python | def delete_user(self, user):
""" Delete user and all data"""
assert self.user == 'catroot' or self.user == 'postgres'
assert not user == 'public'
con = self.connection or self._connect()
cur = con.cursor()
cur.execute('DROP SCHEMA {user} CASCADE;'.format(user=user))
cur.execute('REVOKE USAGE ON SCHEMA public FROM {user};'
.format(user=user))
cur.execute(
'REVOKE SELECT ON ALL TABLES IN SCHEMA public FROM {user};'
.format(user=user))
cur.execute(
'DROP ROLE {user};'.format(user=user))
self.stdout.write(
'REMOVED USER {user}\n'.format(user=user))
if self.connection is None:
con.commit()
con.close()
return self | [
"def",
"delete_user",
"(",
"self",
",",
"user",
")",
":",
"assert",
"self",
".",
"user",
"==",
"'catroot'",
"or",
"self",
".",
"user",
"==",
"'postgres'",
"assert",
"not",
"user",
"==",
"'public'",
"con",
"=",
"self",
".",
"connection",
"or",
"self",
".",
"_connect",
"(",
")",
"cur",
"=",
"con",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"'DROP SCHEMA {user} CASCADE;'",
".",
"format",
"(",
"user",
"=",
"user",
")",
")",
"cur",
".",
"execute",
"(",
"'REVOKE USAGE ON SCHEMA public FROM {user};'",
".",
"format",
"(",
"user",
"=",
"user",
")",
")",
"cur",
".",
"execute",
"(",
"'REVOKE SELECT ON ALL TABLES IN SCHEMA public FROM {user};'",
".",
"format",
"(",
"user",
"=",
"user",
")",
")",
"cur",
".",
"execute",
"(",
"'DROP ROLE {user};'",
".",
"format",
"(",
"user",
"=",
"user",
")",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"'REMOVED USER {user}\\n'",
".",
"format",
"(",
"user",
"=",
"user",
")",
")",
"if",
"self",
".",
"connection",
"is",
"None",
":",
"con",
".",
"commit",
"(",
")",
"con",
".",
"close",
"(",
")",
"return",
"self"
] | Delete user and all data | [
"Delete",
"user",
"and",
"all",
"data"
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/postgresql.py#L320-L341 | train |
SUNCAT-Center/CatHub | cathub/postgresql.py | CathubPostgreSQL.truncate_schema | def truncate_schema(self):
""" Will delete all data in schema. Only for test use!"""
assert self.server == 'localhost'
con = self.connection or self._connect()
self._initialize(con)
cur = con.cursor()
cur.execute('DELETE FROM publication;')
cur.execute('TRUNCATE systems CASCADE;')
con.commit()
con.close()
return | python | def truncate_schema(self):
""" Will delete all data in schema. Only for test use!"""
assert self.server == 'localhost'
con = self.connection or self._connect()
self._initialize(con)
cur = con.cursor()
cur.execute('DELETE FROM publication;')
cur.execute('TRUNCATE systems CASCADE;')
con.commit()
con.close()
return | [
"def",
"truncate_schema",
"(",
"self",
")",
":",
"assert",
"self",
".",
"server",
"==",
"'localhost'",
"con",
"=",
"self",
".",
"connection",
"or",
"self",
".",
"_connect",
"(",
")",
"self",
".",
"_initialize",
"(",
"con",
")",
"cur",
"=",
"con",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"'DELETE FROM publication;'",
")",
"cur",
".",
"execute",
"(",
"'TRUNCATE systems CASCADE;'",
")",
"con",
".",
"commit",
"(",
")",
"con",
".",
"close",
"(",
")",
"return"
] | Will delete all data in schema. Only for test use! | [
"Will",
"delete",
"all",
"data",
"in",
"schema",
".",
"Only",
"for",
"test",
"use!"
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/postgresql.py#L772-L786 | train |
druids/django-chamber | chamber/commands/__init__.py | ProgressBarStream.write | def write(self, *args, **kwargs):
"""
Call the stream's write method without linebreaks at line endings.
"""
return self.stream.write(ending="", *args, **kwargs) | python | def write(self, *args, **kwargs):
"""
Call the stream's write method without linebreaks at line endings.
"""
return self.stream.write(ending="", *args, **kwargs) | [
"def",
"write",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"stream",
".",
"write",
"(",
"ending",
"=",
"\"\"",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Call the stream's write method without linebreaks at line endings. | [
"Call",
"the",
"stream",
"s",
"write",
"method",
"without",
"linebreaks",
"at",
"line",
"endings",
"."
] | eef4169923557e96877a664fa254e8c0814f3f23 | https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/commands/__init__.py#L19-L23 | train |
arkottke/pysra | pysra/site.py | NonlinearProperty._update | def _update(self):
"""Initialize the 1D interpolation."""
if self.strains.size and self.strains.size == self.values.size:
x = np.log(self.strains)
y = self.values
if x.size < 4:
self._interpolater = interp1d(
x,
y,
'linear',
bounds_error=False,
fill_value=(y[0], y[-1]))
else:
self._interpolater = interp1d(
x,
y,
'cubic',
bounds_error=False,
fill_value=(y[0], y[-1])) | python | def _update(self):
"""Initialize the 1D interpolation."""
if self.strains.size and self.strains.size == self.values.size:
x = np.log(self.strains)
y = self.values
if x.size < 4:
self._interpolater = interp1d(
x,
y,
'linear',
bounds_error=False,
fill_value=(y[0], y[-1]))
else:
self._interpolater = interp1d(
x,
y,
'cubic',
bounds_error=False,
fill_value=(y[0], y[-1])) | [
"def",
"_update",
"(",
"self",
")",
":",
"if",
"self",
".",
"strains",
".",
"size",
"and",
"self",
".",
"strains",
".",
"size",
"==",
"self",
".",
"values",
".",
"size",
":",
"x",
"=",
"np",
".",
"log",
"(",
"self",
".",
"strains",
")",
"y",
"=",
"self",
".",
"values",
"if",
"x",
".",
"size",
"<",
"4",
":",
"self",
".",
"_interpolater",
"=",
"interp1d",
"(",
"x",
",",
"y",
",",
"'linear'",
",",
"bounds_error",
"=",
"False",
",",
"fill_value",
"=",
"(",
"y",
"[",
"0",
"]",
",",
"y",
"[",
"-",
"1",
"]",
")",
")",
"else",
":",
"self",
".",
"_interpolater",
"=",
"interp1d",
"(",
"x",
",",
"y",
",",
"'cubic'",
",",
"bounds_error",
"=",
"False",
",",
"fill_value",
"=",
"(",
"y",
"[",
"0",
"]",
",",
"y",
"[",
"-",
"1",
"]",
")",
")"
] | Initialize the 1D interpolation. | [
"Initialize",
"the",
"1D",
"interpolation",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L129-L149 | train |
arkottke/pysra | pysra/site.py | SoilType.is_nonlinear | def is_nonlinear(self):
"""If nonlinear properties are specified."""
return any(
isinstance(p, NonlinearProperty)
for p in [self.mod_reduc, self.damping]) | python | def is_nonlinear(self):
"""If nonlinear properties are specified."""
return any(
isinstance(p, NonlinearProperty)
for p in [self.mod_reduc, self.damping]) | [
"def",
"is_nonlinear",
"(",
"self",
")",
":",
"return",
"any",
"(",
"isinstance",
"(",
"p",
",",
"NonlinearProperty",
")",
"for",
"p",
"in",
"[",
"self",
".",
"mod_reduc",
",",
"self",
".",
"damping",
"]",
")"
] | If nonlinear properties are specified. | [
"If",
"nonlinear",
"properties",
"are",
"specified",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L194-L198 | train |
arkottke/pysra | pysra/site.py | IterativeValue.relative_error | def relative_error(self):
"""The relative error, in percent, between the two iterations.
"""
if self.previous is not None:
# FIXME
# Use the maximum strain value -- this is important for error
# calculation with frequency dependent properties
# prev = np.max(self.previous)
# value = np.max(self.value)
try:
err = 100. * np.max((self.previous - self.value) / self.value)
except ZeroDivisionError:
err = np.inf
else:
err = 0
return err | python | def relative_error(self):
"""The relative error, in percent, between the two iterations.
"""
if self.previous is not None:
# FIXME
# Use the maximum strain value -- this is important for error
# calculation with frequency dependent properties
# prev = np.max(self.previous)
# value = np.max(self.value)
try:
err = 100. * np.max((self.previous - self.value) / self.value)
except ZeroDivisionError:
err = np.inf
else:
err = 0
return err | [
"def",
"relative_error",
"(",
"self",
")",
":",
"if",
"self",
".",
"previous",
"is",
"not",
"None",
":",
"# FIXME",
"# Use the maximum strain value -- this is important for error",
"# calculation with frequency dependent properties",
"# prev = np.max(self.previous)",
"# value = np.max(self.value)",
"try",
":",
"err",
"=",
"100.",
"*",
"np",
".",
"max",
"(",
"(",
"self",
".",
"previous",
"-",
"self",
".",
"value",
")",
"/",
"self",
".",
"value",
")",
"except",
"ZeroDivisionError",
":",
"err",
"=",
"np",
".",
"inf",
"else",
":",
"err",
"=",
"0",
"return",
"err"
] | The relative error, in percent, between the two iterations. | [
"The",
"relative",
"error",
"in",
"percent",
"between",
"the",
"two",
"iterations",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L563-L578 | train |
arkottke/pysra | pysra/site.py | Layer.duplicate | def duplicate(cls, other):
"""Create a copy of the layer."""
return cls(other.soil_type, other.thickness, other.shear_vel) | python | def duplicate(cls, other):
"""Create a copy of the layer."""
return cls(other.soil_type, other.thickness, other.shear_vel) | [
"def",
"duplicate",
"(",
"cls",
",",
"other",
")",
":",
"return",
"cls",
"(",
"other",
".",
"soil_type",
",",
"other",
".",
"thickness",
",",
"other",
".",
"shear_vel",
")"
] | Create a copy of the layer. | [
"Create",
"a",
"copy",
"of",
"the",
"layer",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L630-L632 | train |
arkottke/pysra | pysra/site.py | Layer.damping | def damping(self):
"""Strain-compatible damping."""
try:
value = self._damping.value
except AttributeError:
value = self._damping
return value | python | def damping(self):
"""Strain-compatible damping."""
try:
value = self._damping.value
except AttributeError:
value = self._damping
return value | [
"def",
"damping",
"(",
"self",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"_damping",
".",
"value",
"except",
"AttributeError",
":",
"value",
"=",
"self",
".",
"_damping",
"return",
"value"
] | Strain-compatible damping. | [
"Strain",
"-",
"compatible",
"damping",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L640-L646 | train |
arkottke/pysra | pysra/site.py | Profile.auto_discretize | def auto_discretize(self, max_freq=50., wave_frac=0.2):
"""Subdivide the layers to capture strain variation.
Parameters
----------
max_freq: float
Maximum frequency of interest [Hz].
wave_frac: float
Fraction of wavelength required. Typically 1/3 to 1/5.
Returns
-------
profile: Profile
A new profile with modified layer thicknesses
"""
layers = []
for l in self:
if l.soil_type.is_nonlinear:
opt_thickness = l.shear_vel / max_freq * wave_frac
count = np.ceil(l.thickness / opt_thickness).astype(int)
thickness = l.thickness / count
for _ in range(count):
layers.append(Layer(l.soil_type, thickness, l.shear_vel))
else:
layers.append(l)
return Profile(layers, wt_depth=self.wt_depth) | python | def auto_discretize(self, max_freq=50., wave_frac=0.2):
"""Subdivide the layers to capture strain variation.
Parameters
----------
max_freq: float
Maximum frequency of interest [Hz].
wave_frac: float
Fraction of wavelength required. Typically 1/3 to 1/5.
Returns
-------
profile: Profile
A new profile with modified layer thicknesses
"""
layers = []
for l in self:
if l.soil_type.is_nonlinear:
opt_thickness = l.shear_vel / max_freq * wave_frac
count = np.ceil(l.thickness / opt_thickness).astype(int)
thickness = l.thickness / count
for _ in range(count):
layers.append(Layer(l.soil_type, thickness, l.shear_vel))
else:
layers.append(l)
return Profile(layers, wt_depth=self.wt_depth) | [
"def",
"auto_discretize",
"(",
"self",
",",
"max_freq",
"=",
"50.",
",",
"wave_frac",
"=",
"0.2",
")",
":",
"layers",
"=",
"[",
"]",
"for",
"l",
"in",
"self",
":",
"if",
"l",
".",
"soil_type",
".",
"is_nonlinear",
":",
"opt_thickness",
"=",
"l",
".",
"shear_vel",
"/",
"max_freq",
"*",
"wave_frac",
"count",
"=",
"np",
".",
"ceil",
"(",
"l",
".",
"thickness",
"/",
"opt_thickness",
")",
".",
"astype",
"(",
"int",
")",
"thickness",
"=",
"l",
".",
"thickness",
"/",
"count",
"for",
"_",
"in",
"range",
"(",
"count",
")",
":",
"layers",
".",
"append",
"(",
"Layer",
"(",
"l",
".",
"soil_type",
",",
"thickness",
",",
"l",
".",
"shear_vel",
")",
")",
"else",
":",
"layers",
".",
"append",
"(",
"l",
")",
"return",
"Profile",
"(",
"layers",
",",
"wt_depth",
"=",
"self",
".",
"wt_depth",
")"
] | Subdivide the layers to capture strain variation.
Parameters
----------
max_freq: float
Maximum frequency of interest [Hz].
wave_frac: float
Fraction of wavelength required. Typically 1/3 to 1/5.
Returns
-------
profile: Profile
A new profile with modified layer thicknesses | [
"Subdivide",
"the",
"layers",
"to",
"capture",
"strain",
"variation",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L866-L892 | train |
arkottke/pysra | pysra/site.py | Profile.location | def location(self, wave_field, depth=None, index=None):
"""Create a Location for a specific depth.
Parameters
----------
wave_field: str
Wave field. See :class:`Location` for possible values.
depth: float, optional
Depth corresponding to the :class`Location` of interest. If
provided, then index is ignored.
index: int, optional
Index corresponding to layer of interest in :class:`Profile`. If
provided, then depth is ignored and location is provided a top
of layer.
Returns
-------
Location
Corresponding :class:`Location` object.
"""
if not isinstance(wave_field, WaveField):
wave_field = WaveField[wave_field]
if index is None and depth is not None:
for i, layer in enumerate(self[:-1]):
if layer.depth <= depth < layer.depth_base:
depth_within = depth - layer.depth
break
else:
# Bedrock
i = len(self) - 1
layer = self[-1]
depth_within = 0
elif index is not None and depth is None:
layer = self[index]
i = self.index(layer)
depth_within = 0
else:
raise NotImplementedError
return Location(i, layer, wave_field, depth_within) | python | def location(self, wave_field, depth=None, index=None):
"""Create a Location for a specific depth.
Parameters
----------
wave_field: str
Wave field. See :class:`Location` for possible values.
depth: float, optional
Depth corresponding to the :class`Location` of interest. If
provided, then index is ignored.
index: int, optional
Index corresponding to layer of interest in :class:`Profile`. If
provided, then depth is ignored and location is provided a top
of layer.
Returns
-------
Location
Corresponding :class:`Location` object.
"""
if not isinstance(wave_field, WaveField):
wave_field = WaveField[wave_field]
if index is None and depth is not None:
for i, layer in enumerate(self[:-1]):
if layer.depth <= depth < layer.depth_base:
depth_within = depth - layer.depth
break
else:
# Bedrock
i = len(self) - 1
layer = self[-1]
depth_within = 0
elif index is not None and depth is None:
layer = self[index]
i = self.index(layer)
depth_within = 0
else:
raise NotImplementedError
return Location(i, layer, wave_field, depth_within) | [
"def",
"location",
"(",
"self",
",",
"wave_field",
",",
"depth",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"wave_field",
",",
"WaveField",
")",
":",
"wave_field",
"=",
"WaveField",
"[",
"wave_field",
"]",
"if",
"index",
"is",
"None",
"and",
"depth",
"is",
"not",
"None",
":",
"for",
"i",
",",
"layer",
"in",
"enumerate",
"(",
"self",
"[",
":",
"-",
"1",
"]",
")",
":",
"if",
"layer",
".",
"depth",
"<=",
"depth",
"<",
"layer",
".",
"depth_base",
":",
"depth_within",
"=",
"depth",
"-",
"layer",
".",
"depth",
"break",
"else",
":",
"# Bedrock",
"i",
"=",
"len",
"(",
"self",
")",
"-",
"1",
"layer",
"=",
"self",
"[",
"-",
"1",
"]",
"depth_within",
"=",
"0",
"elif",
"index",
"is",
"not",
"None",
"and",
"depth",
"is",
"None",
":",
"layer",
"=",
"self",
"[",
"index",
"]",
"i",
"=",
"self",
".",
"index",
"(",
"layer",
")",
"depth_within",
"=",
"0",
"else",
":",
"raise",
"NotImplementedError",
"return",
"Location",
"(",
"i",
",",
"layer",
",",
"wave_field",
",",
"depth_within",
")"
] | Create a Location for a specific depth.
Parameters
----------
wave_field: str
Wave field. See :class:`Location` for possible values.
depth: float, optional
Depth corresponding to the :class`Location` of interest. If
provided, then index is ignored.
index: int, optional
Index corresponding to layer of interest in :class:`Profile`. If
provided, then depth is ignored and location is provided a top
of layer.
Returns
-------
Location
Corresponding :class:`Location` object. | [
"Create",
"a",
"Location",
"for",
"a",
"specific",
"depth",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L910-L950 | train |
arkottke/pysra | pysra/site.py | Profile.time_average_vel | def time_average_vel(self, depth):
"""Calculate the time-average velocity.
Parameters
----------
depth: float
Depth over which the average velocity is computed.
Returns
-------
avg_vel: float
Time averaged velocity.
"""
depths = [l.depth for l in self]
# Final layer is infinite and is treated separately
travel_times = [0] + [l.travel_time for l in self[:-1]]
# If needed, add the final layer to the required depth
if depths[-1] < depth:
depths.append(depth)
travel_times.append((depth - self[-1].depth) / self[-1].shear_vel)
total_travel_times = np.cumsum(travel_times)
# Interpolate the travel time to the depth of interest
avg_shear_vel = depth / np.interp(depth, depths, total_travel_times)
return avg_shear_vel | python | def time_average_vel(self, depth):
"""Calculate the time-average velocity.
Parameters
----------
depth: float
Depth over which the average velocity is computed.
Returns
-------
avg_vel: float
Time averaged velocity.
"""
depths = [l.depth for l in self]
# Final layer is infinite and is treated separately
travel_times = [0] + [l.travel_time for l in self[:-1]]
# If needed, add the final layer to the required depth
if depths[-1] < depth:
depths.append(depth)
travel_times.append((depth - self[-1].depth) / self[-1].shear_vel)
total_travel_times = np.cumsum(travel_times)
# Interpolate the travel time to the depth of interest
avg_shear_vel = depth / np.interp(depth, depths, total_travel_times)
return avg_shear_vel | [
"def",
"time_average_vel",
"(",
"self",
",",
"depth",
")",
":",
"depths",
"=",
"[",
"l",
".",
"depth",
"for",
"l",
"in",
"self",
"]",
"# Final layer is infinite and is treated separately",
"travel_times",
"=",
"[",
"0",
"]",
"+",
"[",
"l",
".",
"travel_time",
"for",
"l",
"in",
"self",
"[",
":",
"-",
"1",
"]",
"]",
"# If needed, add the final layer to the required depth",
"if",
"depths",
"[",
"-",
"1",
"]",
"<",
"depth",
":",
"depths",
".",
"append",
"(",
"depth",
")",
"travel_times",
".",
"append",
"(",
"(",
"depth",
"-",
"self",
"[",
"-",
"1",
"]",
".",
"depth",
")",
"/",
"self",
"[",
"-",
"1",
"]",
".",
"shear_vel",
")",
"total_travel_times",
"=",
"np",
".",
"cumsum",
"(",
"travel_times",
")",
"# Interpolate the travel time to the depth of interest",
"avg_shear_vel",
"=",
"depth",
"/",
"np",
".",
"interp",
"(",
"depth",
",",
"depths",
",",
"total_travel_times",
")",
"return",
"avg_shear_vel"
] | Calculate the time-average velocity.
Parameters
----------
depth: float
Depth over which the average velocity is computed.
Returns
-------
avg_vel: float
Time averaged velocity. | [
"Calculate",
"the",
"time",
"-",
"average",
"velocity",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L952-L976 | train |
arkottke/pysra | pysra/site.py | Profile.simplified_rayliegh_vel | def simplified_rayliegh_vel(self):
"""Simplified Rayliegh velocity of the site.
This follows the simplifications proposed by Urzua et al. (2017)
Returns
-------
rayleigh_vel : float
Equivalent shear-wave velocity.
"""
# FIXME: What if last layer has no thickness?
thicks = np.array([l.thickness for l in self])
depths_mid = np.array([l.depth_mid for l in self])
shear_vels = np.array([l.shear_vel for l in self])
mode_incr = depths_mid * thicks / shear_vels ** 2
# Mode shape is computed as the sumation from the base of
# the profile. Need to append a 0 for the roll performed in the next
# step
shape = np.r_[np.cumsum(mode_incr[::-1])[::-1], 0]
freq_fund = np.sqrt(4 * np.sum(
thicks * depths_mid ** 2 / shear_vels ** 2
) / np.sum(
thicks *
# Roll is used to offset the mode_shape so that the sum
# can be calculated for two adjacent layers
np.sum(np.c_[shape, np.roll(shape, -1)], axis=1)[:-1] ** 2))
period_fun = 2 * np.pi / freq_fund
rayleigh_vel = 4 * thicks.sum() / period_fun
return rayleigh_vel | python | def simplified_rayliegh_vel(self):
"""Simplified Rayliegh velocity of the site.
This follows the simplifications proposed by Urzua et al. (2017)
Returns
-------
rayleigh_vel : float
Equivalent shear-wave velocity.
"""
# FIXME: What if last layer has no thickness?
thicks = np.array([l.thickness for l in self])
depths_mid = np.array([l.depth_mid for l in self])
shear_vels = np.array([l.shear_vel for l in self])
mode_incr = depths_mid * thicks / shear_vels ** 2
# Mode shape is computed as the sumation from the base of
# the profile. Need to append a 0 for the roll performed in the next
# step
shape = np.r_[np.cumsum(mode_incr[::-1])[::-1], 0]
freq_fund = np.sqrt(4 * np.sum(
thicks * depths_mid ** 2 / shear_vels ** 2
) / np.sum(
thicks *
# Roll is used to offset the mode_shape so that the sum
# can be calculated for two adjacent layers
np.sum(np.c_[shape, np.roll(shape, -1)], axis=1)[:-1] ** 2))
period_fun = 2 * np.pi / freq_fund
rayleigh_vel = 4 * thicks.sum() / period_fun
return rayleigh_vel | [
"def",
"simplified_rayliegh_vel",
"(",
"self",
")",
":",
"# FIXME: What if last layer has no thickness?",
"thicks",
"=",
"np",
".",
"array",
"(",
"[",
"l",
".",
"thickness",
"for",
"l",
"in",
"self",
"]",
")",
"depths_mid",
"=",
"np",
".",
"array",
"(",
"[",
"l",
".",
"depth_mid",
"for",
"l",
"in",
"self",
"]",
")",
"shear_vels",
"=",
"np",
".",
"array",
"(",
"[",
"l",
".",
"shear_vel",
"for",
"l",
"in",
"self",
"]",
")",
"mode_incr",
"=",
"depths_mid",
"*",
"thicks",
"/",
"shear_vels",
"**",
"2",
"# Mode shape is computed as the sumation from the base of",
"# the profile. Need to append a 0 for the roll performed in the next",
"# step",
"shape",
"=",
"np",
".",
"r_",
"[",
"np",
".",
"cumsum",
"(",
"mode_incr",
"[",
":",
":",
"-",
"1",
"]",
")",
"[",
":",
":",
"-",
"1",
"]",
",",
"0",
"]",
"freq_fund",
"=",
"np",
".",
"sqrt",
"(",
"4",
"*",
"np",
".",
"sum",
"(",
"thicks",
"*",
"depths_mid",
"**",
"2",
"/",
"shear_vels",
"**",
"2",
")",
"/",
"np",
".",
"sum",
"(",
"thicks",
"*",
"# Roll is used to offset the mode_shape so that the sum",
"# can be calculated for two adjacent layers",
"np",
".",
"sum",
"(",
"np",
".",
"c_",
"[",
"shape",
",",
"np",
".",
"roll",
"(",
"shape",
",",
"-",
"1",
")",
"]",
",",
"axis",
"=",
"1",
")",
"[",
":",
"-",
"1",
"]",
"**",
"2",
")",
")",
"period_fun",
"=",
"2",
"*",
"np",
".",
"pi",
"/",
"freq_fund",
"rayleigh_vel",
"=",
"4",
"*",
"thicks",
".",
"sum",
"(",
")",
"/",
"period_fun",
"return",
"rayleigh_vel"
] | Simplified Rayliegh velocity of the site.
This follows the simplifications proposed by Urzua et al. (2017)
Returns
-------
rayleigh_vel : float
Equivalent shear-wave velocity. | [
"Simplified",
"Rayliegh",
"velocity",
"of",
"the",
"site",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L978-L1008 | train |
arkottke/pysra | pysra/variation.py | ToroThicknessVariation.iter_thickness | def iter_thickness(self, depth_total):
"""Iterate over the varied thicknesses.
The layering is generated using a non-homogenous Poisson process. The
following routine is used to generate the layering. The rate
function, :math:`\lambda(t)`, is integrated from 0 to t to generate
cumulative rate function, :math:`\Lambda(t)`. This function is then
inverted producing :math:`\Lambda^{-1}(t)`. Random variables
are produced using the a exponential random variation with
:math:`\mu = 1` and converted to the nonhomogenous variables using
the inverted function.
Parameters
----------
depth_total: float
Total depth generated. Last thickness is truncated to achieve
this depth.
Yields
------
float
Varied thickness.
"""
total = 0
depth_prev = 0
while depth_prev < depth_total:
# Add a random exponential increment
total += np.random.exponential(1.0)
# Convert between x and depth using the inverse of \Lambda(t)
depth = np.power(
(self.c_2 * total) / self.c_3 + total / self.c_3 + np.power(
self.c_1, self.c_2 + 1), 1 / (self.c_2 + 1)) - self.c_1
thickness = depth - depth_prev
if depth > depth_total:
thickness = (depth_total - depth_prev)
depth = depth_prev + thickness
depth_mid = (depth_prev + depth) / 2
yield thickness, depth_mid
depth_prev = depth | python | def iter_thickness(self, depth_total):
"""Iterate over the varied thicknesses.
The layering is generated using a non-homogenous Poisson process. The
following routine is used to generate the layering. The rate
function, :math:`\lambda(t)`, is integrated from 0 to t to generate
cumulative rate function, :math:`\Lambda(t)`. This function is then
inverted producing :math:`\Lambda^{-1}(t)`. Random variables
are produced using the a exponential random variation with
:math:`\mu = 1` and converted to the nonhomogenous variables using
the inverted function.
Parameters
----------
depth_total: float
Total depth generated. Last thickness is truncated to achieve
this depth.
Yields
------
float
Varied thickness.
"""
total = 0
depth_prev = 0
while depth_prev < depth_total:
# Add a random exponential increment
total += np.random.exponential(1.0)
# Convert between x and depth using the inverse of \Lambda(t)
depth = np.power(
(self.c_2 * total) / self.c_3 + total / self.c_3 + np.power(
self.c_1, self.c_2 + 1), 1 / (self.c_2 + 1)) - self.c_1
thickness = depth - depth_prev
if depth > depth_total:
thickness = (depth_total - depth_prev)
depth = depth_prev + thickness
depth_mid = (depth_prev + depth) / 2
yield thickness, depth_mid
depth_prev = depth | [
"def",
"iter_thickness",
"(",
"self",
",",
"depth_total",
")",
":",
"total",
"=",
"0",
"depth_prev",
"=",
"0",
"while",
"depth_prev",
"<",
"depth_total",
":",
"# Add a random exponential increment",
"total",
"+=",
"np",
".",
"random",
".",
"exponential",
"(",
"1.0",
")",
"# Convert between x and depth using the inverse of \\Lambda(t)",
"depth",
"=",
"np",
".",
"power",
"(",
"(",
"self",
".",
"c_2",
"*",
"total",
")",
"/",
"self",
".",
"c_3",
"+",
"total",
"/",
"self",
".",
"c_3",
"+",
"np",
".",
"power",
"(",
"self",
".",
"c_1",
",",
"self",
".",
"c_2",
"+",
"1",
")",
",",
"1",
"/",
"(",
"self",
".",
"c_2",
"+",
"1",
")",
")",
"-",
"self",
".",
"c_1",
"thickness",
"=",
"depth",
"-",
"depth_prev",
"if",
"depth",
">",
"depth_total",
":",
"thickness",
"=",
"(",
"depth_total",
"-",
"depth_prev",
")",
"depth",
"=",
"depth_prev",
"+",
"thickness",
"depth_mid",
"=",
"(",
"depth_prev",
"+",
"depth",
")",
"/",
"2",
"yield",
"thickness",
",",
"depth_mid",
"depth_prev",
"=",
"depth"
] | Iterate over the varied thicknesses.
The layering is generated using a non-homogenous Poisson process. The
following routine is used to generate the layering. The rate
function, :math:`\lambda(t)`, is integrated from 0 to t to generate
cumulative rate function, :math:`\Lambda(t)`. This function is then
inverted producing :math:`\Lambda^{-1}(t)`. Random variables
are produced using the a exponential random variation with
:math:`\mu = 1` and converted to the nonhomogenous variables using
the inverted function.
Parameters
----------
depth_total: float
Total depth generated. Last thickness is truncated to achieve
this depth.
Yields
------
float
Varied thickness. | [
"Iterate",
"over",
"the",
"varied",
"thicknesses",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/variation.py#L149-L194 | train |
arkottke/pysra | pysra/variation.py | VelocityVariation._calc_covar_matrix | def _calc_covar_matrix(self, profile):
"""Calculate the covariance matrix.
Parameters
----------
profile : site.Profile
Input site profile
Yields
------
covar : `class`:numpy.array
Covariance matrix
"""
corr = self._calc_corr(profile)
std = self._calc_ln_std(profile)
# Modify the standard deviation by the truncated norm scale
std *= randnorm.scale
var = std ** 2
covar = corr * std[:-1] * std[1:]
# Main diagonal is the variance
mat = diags([covar, var, covar], [-1, 0, 1]).toarray()
return mat | python | def _calc_covar_matrix(self, profile):
"""Calculate the covariance matrix.
Parameters
----------
profile : site.Profile
Input site profile
Yields
------
covar : `class`:numpy.array
Covariance matrix
"""
corr = self._calc_corr(profile)
std = self._calc_ln_std(profile)
# Modify the standard deviation by the truncated norm scale
std *= randnorm.scale
var = std ** 2
covar = corr * std[:-1] * std[1:]
# Main diagonal is the variance
mat = diags([covar, var, covar], [-1, 0, 1]).toarray()
return mat | [
"def",
"_calc_covar_matrix",
"(",
"self",
",",
"profile",
")",
":",
"corr",
"=",
"self",
".",
"_calc_corr",
"(",
"profile",
")",
"std",
"=",
"self",
".",
"_calc_ln_std",
"(",
"profile",
")",
"# Modify the standard deviation by the truncated norm scale",
"std",
"*=",
"randnorm",
".",
"scale",
"var",
"=",
"std",
"**",
"2",
"covar",
"=",
"corr",
"*",
"std",
"[",
":",
"-",
"1",
"]",
"*",
"std",
"[",
"1",
":",
"]",
"# Main diagonal is the variance",
"mat",
"=",
"diags",
"(",
"[",
"covar",
",",
"var",
",",
"covar",
"]",
",",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
")",
".",
"toarray",
"(",
")",
"return",
"mat"
] | Calculate the covariance matrix.
Parameters
----------
profile : site.Profile
Input site profile
Yields
------
covar : `class`:numpy.array
Covariance matrix | [
"Calculate",
"the",
"covariance",
"matrix",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/variation.py#L265-L289 | train |
arkottke/pysra | pysra/variation.py | ToroVelocityVariation._calc_corr | def _calc_corr(self, profile):
"""Compute the adjacent-layer correlations
Parameters
----------
profile : :class:`site.Profile`
Input site profile
Yields
------
corr : :class:`numpy.array`
Adjacent-layer correlations
"""
depth = np.array([l.depth_mid for l in profile[:-1]])
thick = np.diff(depth)
depth = depth[1:]
# Depth dependent correlation
corr_depth = (self.rho_200 * np.power(
(depth + self.rho_0) / (200 + self.rho_0), self.b))
corr_depth[depth > 200] = self.rho_200
# Thickness dependent correlation
corr_thick = self.rho_0 * np.exp(-thick / self.delta)
# Final correlation
# Correlation coefficient
corr = (1 - corr_depth) * corr_thick + corr_depth
# Bedrock is perfectly correlated with layer above it
corr = np.r_[corr, 1]
return corr | python | def _calc_corr(self, profile):
"""Compute the adjacent-layer correlations
Parameters
----------
profile : :class:`site.Profile`
Input site profile
Yields
------
corr : :class:`numpy.array`
Adjacent-layer correlations
"""
depth = np.array([l.depth_mid for l in profile[:-1]])
thick = np.diff(depth)
depth = depth[1:]
# Depth dependent correlation
corr_depth = (self.rho_200 * np.power(
(depth + self.rho_0) / (200 + self.rho_0), self.b))
corr_depth[depth > 200] = self.rho_200
# Thickness dependent correlation
corr_thick = self.rho_0 * np.exp(-thick / self.delta)
# Final correlation
# Correlation coefficient
corr = (1 - corr_depth) * corr_thick + corr_depth
# Bedrock is perfectly correlated with layer above it
corr = np.r_[corr, 1]
return corr | [
"def",
"_calc_corr",
"(",
"self",
",",
"profile",
")",
":",
"depth",
"=",
"np",
".",
"array",
"(",
"[",
"l",
".",
"depth_mid",
"for",
"l",
"in",
"profile",
"[",
":",
"-",
"1",
"]",
"]",
")",
"thick",
"=",
"np",
".",
"diff",
"(",
"depth",
")",
"depth",
"=",
"depth",
"[",
"1",
":",
"]",
"# Depth dependent correlation",
"corr_depth",
"=",
"(",
"self",
".",
"rho_200",
"*",
"np",
".",
"power",
"(",
"(",
"depth",
"+",
"self",
".",
"rho_0",
")",
"/",
"(",
"200",
"+",
"self",
".",
"rho_0",
")",
",",
"self",
".",
"b",
")",
")",
"corr_depth",
"[",
"depth",
">",
"200",
"]",
"=",
"self",
".",
"rho_200",
"# Thickness dependent correlation",
"corr_thick",
"=",
"self",
".",
"rho_0",
"*",
"np",
".",
"exp",
"(",
"-",
"thick",
"/",
"self",
".",
"delta",
")",
"# Final correlation",
"# Correlation coefficient",
"corr",
"=",
"(",
"1",
"-",
"corr_depth",
")",
"*",
"corr_thick",
"+",
"corr_depth",
"# Bedrock is perfectly correlated with layer above it",
"corr",
"=",
"np",
".",
"r_",
"[",
"corr",
",",
"1",
"]",
"return",
"corr"
] | Compute the adjacent-layer correlations
Parameters
----------
profile : :class:`site.Profile`
Input site profile
Yields
------
corr : :class:`numpy.array`
Adjacent-layer correlations | [
"Compute",
"the",
"adjacent",
"-",
"layer",
"correlations"
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/variation.py#L419-L451 | train |
arkottke/pysra | pysra/variation.py | ToroVelocityVariation.generic_model | def generic_model(cls, site_class, **kwds):
"""Use generic model parameters based on site class.
Parameters
----------
site_class: str
Site classification. Possible options are:
* Geomatrix AB
* Geomatrix CD
* USGS AB
* USGS CD
* USGS A
* USGS B
* USGS C
* USGS D
See the report for definitions of the Geomatrix site
classication. USGS site classification is based on :math:`V_{s30}`:
=========== =====================
Site Class :math:`V_{s30}` (m/s)
=========== =====================
A >750 m/s
B 360 to 750 m/s
C 180 to 360 m/s
D <180 m/s
=========== =====================
Returns
-------
ToroVelocityVariation
Initialized :class:`ToroVelocityVariation` with generic parameters.
"""
p = dict(cls.PARAMS[site_class])
p.update(kwds)
return cls(**p) | python | def generic_model(cls, site_class, **kwds):
"""Use generic model parameters based on site class.
Parameters
----------
site_class: str
Site classification. Possible options are:
* Geomatrix AB
* Geomatrix CD
* USGS AB
* USGS CD
* USGS A
* USGS B
* USGS C
* USGS D
See the report for definitions of the Geomatrix site
classication. USGS site classification is based on :math:`V_{s30}`:
=========== =====================
Site Class :math:`V_{s30}` (m/s)
=========== =====================
A >750 m/s
B 360 to 750 m/s
C 180 to 360 m/s
D <180 m/s
=========== =====================
Returns
-------
ToroVelocityVariation
Initialized :class:`ToroVelocityVariation` with generic parameters.
"""
p = dict(cls.PARAMS[site_class])
p.update(kwds)
return cls(**p) | [
"def",
"generic_model",
"(",
"cls",
",",
"site_class",
",",
"*",
"*",
"kwds",
")",
":",
"p",
"=",
"dict",
"(",
"cls",
".",
"PARAMS",
"[",
"site_class",
"]",
")",
"p",
".",
"update",
"(",
"kwds",
")",
"return",
"cls",
"(",
"*",
"*",
"p",
")"
] | Use generic model parameters based on site class.
Parameters
----------
site_class: str
Site classification. Possible options are:
* Geomatrix AB
* Geomatrix CD
* USGS AB
* USGS CD
* USGS A
* USGS B
* USGS C
* USGS D
See the report for definitions of the Geomatrix site
classication. USGS site classification is based on :math:`V_{s30}`:
=========== =====================
Site Class :math:`V_{s30}` (m/s)
=========== =====================
A >750 m/s
B 360 to 750 m/s
C 180 to 360 m/s
D <180 m/s
=========== =====================
Returns
-------
ToroVelocityVariation
Initialized :class:`ToroVelocityVariation` with generic parameters. | [
"Use",
"generic",
"model",
"parameters",
"based",
"on",
"site",
"class",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/variation.py#L486-L521 | train |
arkottke/pysra | pysra/variation.py | DarendeliVariation.calc_std_damping | def calc_std_damping(damping):
"""Calculate the standard deviation as a function of damping in decimal.
Equation 7.30 from Darendeli (2001).
Parameters
----------
damping : array_like
Material damping values in decimal.
Returns
-------
std : :class:`numpy.ndarray`
Standard deviation.
"""
damping = np.asarray(damping).astype(float)
std = (np.exp(-5) + np.exp(-0.25) * np.sqrt(100 * damping)) / 100.
return std | python | def calc_std_damping(damping):
"""Calculate the standard deviation as a function of damping in decimal.
Equation 7.30 from Darendeli (2001).
Parameters
----------
damping : array_like
Material damping values in decimal.
Returns
-------
std : :class:`numpy.ndarray`
Standard deviation.
"""
damping = np.asarray(damping).astype(float)
std = (np.exp(-5) + np.exp(-0.25) * np.sqrt(100 * damping)) / 100.
return std | [
"def",
"calc_std_damping",
"(",
"damping",
")",
":",
"damping",
"=",
"np",
".",
"asarray",
"(",
"damping",
")",
".",
"astype",
"(",
"float",
")",
"std",
"=",
"(",
"np",
".",
"exp",
"(",
"-",
"5",
")",
"+",
"np",
".",
"exp",
"(",
"-",
"0.25",
")",
"*",
"np",
".",
"sqrt",
"(",
"100",
"*",
"damping",
")",
")",
"/",
"100.",
"return",
"std"
] | Calculate the standard deviation as a function of damping in decimal.
Equation 7.30 from Darendeli (2001).
Parameters
----------
damping : array_like
Material damping values in decimal.
Returns
-------
std : :class:`numpy.ndarray`
Standard deviation. | [
"Calculate",
"the",
"standard",
"deviation",
"as",
"a",
"function",
"of",
"damping",
"in",
"decimal",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/variation.py#L615-L632 | train |
inspirehep/inspire-schemas | inspire_schemas/builders/authors.py | AuthorBuilder._append_to | def _append_to(self, field, element):
"""Append the ``element`` to the ``field`` of the record.
This method is smart: it does nothing if ``element`` is empty and
creates ``field`` if it does not exit yet.
Args:
:param field: the name of the field of the record to append to
:type field: string
:param element: the element to append
"""
if element not in EMPTIES:
self.obj.setdefault(field, [])
self.obj.get(field).append(element) | python | def _append_to(self, field, element):
"""Append the ``element`` to the ``field`` of the record.
This method is smart: it does nothing if ``element`` is empty and
creates ``field`` if it does not exit yet.
Args:
:param field: the name of the field of the record to append to
:type field: string
:param element: the element to append
"""
if element not in EMPTIES:
self.obj.setdefault(field, [])
self.obj.get(field).append(element) | [
"def",
"_append_to",
"(",
"self",
",",
"field",
",",
"element",
")",
":",
"if",
"element",
"not",
"in",
"EMPTIES",
":",
"self",
".",
"obj",
".",
"setdefault",
"(",
"field",
",",
"[",
"]",
")",
"self",
".",
"obj",
".",
"get",
"(",
"field",
")",
".",
"append",
"(",
"element",
")"
] | Append the ``element`` to the ``field`` of the record.
This method is smart: it does nothing if ``element`` is empty and
creates ``field`` if it does not exit yet.
Args:
:param field: the name of the field of the record to append to
:type field: string
:param element: the element to append | [
"Append",
"the",
"element",
"to",
"the",
"field",
"of",
"the",
"record",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L64-L77 | train |
inspirehep/inspire-schemas | inspire_schemas/builders/authors.py | AuthorBuilder.add_name_variant | def add_name_variant(self, name):
"""Add name variant.
Args:
:param name: name variant for the current author.
:type name: string
"""
self._ensure_field('name', {})
self.obj['name'].setdefault('name_variants', []).append(name) | python | def add_name_variant(self, name):
"""Add name variant.
Args:
:param name: name variant for the current author.
:type name: string
"""
self._ensure_field('name', {})
self.obj['name'].setdefault('name_variants', []).append(name) | [
"def",
"add_name_variant",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_ensure_field",
"(",
"'name'",
",",
"{",
"}",
")",
"self",
".",
"obj",
"[",
"'name'",
"]",
".",
"setdefault",
"(",
"'name_variants'",
",",
"[",
"]",
")",
".",
"append",
"(",
"name",
")"
] | Add name variant.
Args:
:param name: name variant for the current author.
:type name: string | [
"Add",
"name",
"variant",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L102-L110 | train |
inspirehep/inspire-schemas | inspire_schemas/builders/authors.py | AuthorBuilder.add_native_name | def add_native_name(self, name):
"""Add native name.
Args:
:param name: native name for the current author.
:type name: string
"""
self._ensure_field('name', {})
self.obj['name'].setdefault('native_names', []).append(name) | python | def add_native_name(self, name):
"""Add native name.
Args:
:param name: native name for the current author.
:type name: string
"""
self._ensure_field('name', {})
self.obj['name'].setdefault('native_names', []).append(name) | [
"def",
"add_native_name",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_ensure_field",
"(",
"'name'",
",",
"{",
"}",
")",
"self",
".",
"obj",
"[",
"'name'",
"]",
".",
"setdefault",
"(",
"'native_names'",
",",
"[",
"]",
")",
".",
"append",
"(",
"name",
")"
] | Add native name.
Args:
:param name: native name for the current author.
:type name: string | [
"Add",
"native",
"name",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L113-L121 | train |
inspirehep/inspire-schemas | inspire_schemas/builders/authors.py | AuthorBuilder.add_previous_name | def add_previous_name(self, name):
"""Add previous name.
Args:
:param name: previous name for the current author.
:type name: string
"""
self._ensure_field('name', {})
self.obj['name'].setdefault('previous_names', []).append(name) | python | def add_previous_name(self, name):
"""Add previous name.
Args:
:param name: previous name for the current author.
:type name: string
"""
self._ensure_field('name', {})
self.obj['name'].setdefault('previous_names', []).append(name) | [
"def",
"add_previous_name",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_ensure_field",
"(",
"'name'",
",",
"{",
"}",
")",
"self",
".",
"obj",
"[",
"'name'",
"]",
".",
"setdefault",
"(",
"'previous_names'",
",",
"[",
"]",
")",
".",
"append",
"(",
"name",
")"
] | Add previous name.
Args:
:param name: previous name for the current author.
:type name: string | [
"Add",
"previous",
"name",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L124-L132 | train |
inspirehep/inspire-schemas | inspire_schemas/builders/authors.py | AuthorBuilder.add_email_address | def add_email_address(self, email, hidden=None):
"""Add email address.
Args:
:param email: email of the author.
:type email: string
:param hidden: if email is public or not.
:type hidden: boolean
"""
existing_emails = get_value(self.obj, 'email_addresses', [])
found_email = next(
(existing_email for existing_email in existing_emails if existing_email.get('value') == email),
None
)
if found_email is None:
new_email = {'value': email}
if hidden is not None:
new_email['hidden'] = hidden
self._append_to('email_addresses', new_email)
elif hidden is not None:
found_email['hidden'] = hidden | python | def add_email_address(self, email, hidden=None):
"""Add email address.
Args:
:param email: email of the author.
:type email: string
:param hidden: if email is public or not.
:type hidden: boolean
"""
existing_emails = get_value(self.obj, 'email_addresses', [])
found_email = next(
(existing_email for existing_email in existing_emails if existing_email.get('value') == email),
None
)
if found_email is None:
new_email = {'value': email}
if hidden is not None:
new_email['hidden'] = hidden
self._append_to('email_addresses', new_email)
elif hidden is not None:
found_email['hidden'] = hidden | [
"def",
"add_email_address",
"(",
"self",
",",
"email",
",",
"hidden",
"=",
"None",
")",
":",
"existing_emails",
"=",
"get_value",
"(",
"self",
".",
"obj",
",",
"'email_addresses'",
",",
"[",
"]",
")",
"found_email",
"=",
"next",
"(",
"(",
"existing_email",
"for",
"existing_email",
"in",
"existing_emails",
"if",
"existing_email",
".",
"get",
"(",
"'value'",
")",
"==",
"email",
")",
",",
"None",
")",
"if",
"found_email",
"is",
"None",
":",
"new_email",
"=",
"{",
"'value'",
":",
"email",
"}",
"if",
"hidden",
"is",
"not",
"None",
":",
"new_email",
"[",
"'hidden'",
"]",
"=",
"hidden",
"self",
".",
"_append_to",
"(",
"'email_addresses'",
",",
"new_email",
")",
"elif",
"hidden",
"is",
"not",
"None",
":",
"found_email",
"[",
"'hidden'",
"]",
"=",
"hidden"
] | Add email address.
Args:
:param email: email of the author.
:type email: string
:param hidden: if email is public or not.
:type hidden: boolean | [
"Add",
"email",
"address",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L135-L156 | train |
inspirehep/inspire-schemas | inspire_schemas/builders/authors.py | AuthorBuilder.add_url | def add_url(self, url, description=None):
"""Add a personal website.
Args:
:param url: url to the person's website.
:type url: string
:param description: short description of the website.
:type description: string
"""
url = {
'value': url,
}
if description:
url['description'] = description
self._append_to('urls', url) | python | def add_url(self, url, description=None):
"""Add a personal website.
Args:
:param url: url to the person's website.
:type url: string
:param description: short description of the website.
:type description: string
"""
url = {
'value': url,
}
if description:
url['description'] = description
self._append_to('urls', url) | [
"def",
"add_url",
"(",
"self",
",",
"url",
",",
"description",
"=",
"None",
")",
":",
"url",
"=",
"{",
"'value'",
":",
"url",
",",
"}",
"if",
"description",
":",
"url",
"[",
"'description'",
"]",
"=",
"description",
"self",
".",
"_append_to",
"(",
"'urls'",
",",
"url",
")"
] | Add a personal website.
Args:
:param url: url to the person's website.
:type url: string
:param description: short description of the website.
:type description: string | [
"Add",
"a",
"personal",
"website",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L169-L184 | train |
inspirehep/inspire-schemas | inspire_schemas/builders/authors.py | AuthorBuilder.add_project | def add_project(self, name, record=None, start_date=None, end_date=None, curated=False, current=False):
"""Add an experiment that the person worked on.
Args:
:param name: name of the experiment.
:type name: string
:param start_date: the date when the person started working on the experiment.
:type start_date: string
:param end_date: the date when the person stopped working on the experiment.
:type end_date: string
:param record: URI for the experiment record.
:type record: string
:param curated: if the experiment has been curated i.e. has been verified.
:type curated: boolean
:param current: if the person is currently working on this experiment.
:type current: boolean
"""
new_experiment = {}
new_experiment['name'] = name
if start_date:
new_experiment['start_date'] = normalize_date(start_date)
if end_date:
new_experiment['end_date'] = normalize_date(end_date)
if record:
new_experiment['record'] = record
new_experiment['curated_relation'] = curated
new_experiment['current'] = current
self._append_to('project_membership', new_experiment)
self.obj['project_membership'].sort(key=self._get_work_priority_tuple, reverse=True) | python | def add_project(self, name, record=None, start_date=None, end_date=None, curated=False, current=False):
"""Add an experiment that the person worked on.
Args:
:param name: name of the experiment.
:type name: string
:param start_date: the date when the person started working on the experiment.
:type start_date: string
:param end_date: the date when the person stopped working on the experiment.
:type end_date: string
:param record: URI for the experiment record.
:type record: string
:param curated: if the experiment has been curated i.e. has been verified.
:type curated: boolean
:param current: if the person is currently working on this experiment.
:type current: boolean
"""
new_experiment = {}
new_experiment['name'] = name
if start_date:
new_experiment['start_date'] = normalize_date(start_date)
if end_date:
new_experiment['end_date'] = normalize_date(end_date)
if record:
new_experiment['record'] = record
new_experiment['curated_relation'] = curated
new_experiment['current'] = current
self._append_to('project_membership', new_experiment)
self.obj['project_membership'].sort(key=self._get_work_priority_tuple, reverse=True) | [
"def",
"add_project",
"(",
"self",
",",
"name",
",",
"record",
"=",
"None",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"curated",
"=",
"False",
",",
"current",
"=",
"False",
")",
":",
"new_experiment",
"=",
"{",
"}",
"new_experiment",
"[",
"'name'",
"]",
"=",
"name",
"if",
"start_date",
":",
"new_experiment",
"[",
"'start_date'",
"]",
"=",
"normalize_date",
"(",
"start_date",
")",
"if",
"end_date",
":",
"new_experiment",
"[",
"'end_date'",
"]",
"=",
"normalize_date",
"(",
"end_date",
")",
"if",
"record",
":",
"new_experiment",
"[",
"'record'",
"]",
"=",
"record",
"new_experiment",
"[",
"'curated_relation'",
"]",
"=",
"curated",
"new_experiment",
"[",
"'current'",
"]",
"=",
"current",
"self",
".",
"_append_to",
"(",
"'project_membership'",
",",
"new_experiment",
")",
"self",
".",
"obj",
"[",
"'project_membership'",
"]",
".",
"sort",
"(",
"key",
"=",
"self",
".",
"_get_work_priority_tuple",
",",
"reverse",
"=",
"True",
")"
] | Add an experiment that the person worked on.
Args:
:param name: name of the experiment.
:type name: string
:param start_date: the date when the person started working on the experiment.
:type start_date: string
:param end_date: the date when the person stopped working on the experiment.
:type end_date: string
:param record: URI for the experiment record.
:type record: string
:param curated: if the experiment has been curated i.e. has been verified.
:type curated: boolean
:param current: if the person is currently working on this experiment.
:type current: boolean | [
"Add",
"an",
"experiment",
"that",
"the",
"person",
"worked",
"on",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L306-L339 | train |
inspirehep/inspire-schemas | inspire_schemas/builders/authors.py | AuthorBuilder.add_advisor | def add_advisor(self, name, ids=None, degree_type=None, record=None, curated=False):
"""Add an advisor.
Args:
:param name: full name of the advisor.
:type name: string
:param ids: list with the IDs of the advisor.
:type ids: list
:param degree_type: one of the allowed types of degree the advisor helped with.
:type degree_type: string
:param record: URI for the advisor.
:type record: string
:param curated: if the advisor relation has been curated i.e. has been verified.
:type curated: boolean
"""
new_advisor = {}
new_advisor['name'] = normalize_name(name)
if ids:
new_advisor['ids'] = force_list(ids)
if degree_type:
new_advisor['degree_type'] = degree_type
if record:
new_advisor['record'] = record
new_advisor['curated_relation'] = curated
self._append_to('advisors', new_advisor) | python | def add_advisor(self, name, ids=None, degree_type=None, record=None, curated=False):
"""Add an advisor.
Args:
:param name: full name of the advisor.
:type name: string
:param ids: list with the IDs of the advisor.
:type ids: list
:param degree_type: one of the allowed types of degree the advisor helped with.
:type degree_type: string
:param record: URI for the advisor.
:type record: string
:param curated: if the advisor relation has been curated i.e. has been verified.
:type curated: boolean
"""
new_advisor = {}
new_advisor['name'] = normalize_name(name)
if ids:
new_advisor['ids'] = force_list(ids)
if degree_type:
new_advisor['degree_type'] = degree_type
if record:
new_advisor['record'] = record
new_advisor['curated_relation'] = curated
self._append_to('advisors', new_advisor) | [
"def",
"add_advisor",
"(",
"self",
",",
"name",
",",
"ids",
"=",
"None",
",",
"degree_type",
"=",
"None",
",",
"record",
"=",
"None",
",",
"curated",
"=",
"False",
")",
":",
"new_advisor",
"=",
"{",
"}",
"new_advisor",
"[",
"'name'",
"]",
"=",
"normalize_name",
"(",
"name",
")",
"if",
"ids",
":",
"new_advisor",
"[",
"'ids'",
"]",
"=",
"force_list",
"(",
"ids",
")",
"if",
"degree_type",
":",
"new_advisor",
"[",
"'degree_type'",
"]",
"=",
"degree_type",
"if",
"record",
":",
"new_advisor",
"[",
"'record'",
"]",
"=",
"record",
"new_advisor",
"[",
"'curated_relation'",
"]",
"=",
"curated",
"self",
".",
"_append_to",
"(",
"'advisors'",
",",
"new_advisor",
")"
] | Add an advisor.
Args:
:param name: full name of the advisor.
:type name: string
:param ids: list with the IDs of the advisor.
:type ids: list
:param degree_type: one of the allowed types of degree the advisor helped with.
:type degree_type: string
:param record: URI for the advisor.
:type record: string
:param curated: if the advisor relation has been curated i.e. has been verified.
:type curated: boolean | [
"Add",
"an",
"advisor",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L350-L378 | train |
inspirehep/inspire-schemas | inspire_schemas/builders/authors.py | AuthorBuilder.add_private_note | def add_private_note(self, note, source=None):
"""Add a private note.
Args:
:param comment: comment about the author.
:type comment: string
:param source: the source of the comment.
:type source: string
"""
note = {
'value': note,
}
if source:
note['source'] = source
self._append_to('_private_notes', note) | python | def add_private_note(self, note, source=None):
"""Add a private note.
Args:
:param comment: comment about the author.
:type comment: string
:param source: the source of the comment.
:type source: string
"""
note = {
'value': note,
}
if source:
note['source'] = source
self._append_to('_private_notes', note) | [
"def",
"add_private_note",
"(",
"self",
",",
"note",
",",
"source",
"=",
"None",
")",
":",
"note",
"=",
"{",
"'value'",
":",
"note",
",",
"}",
"if",
"source",
":",
"note",
"[",
"'source'",
"]",
"=",
"source",
"self",
".",
"_append_to",
"(",
"'_private_notes'",
",",
"note",
")"
] | Add a private note.
Args:
:param comment: comment about the author.
:type comment: string
:param source: the source of the comment.
:type source: string | [
"Add",
"a",
"private",
"note",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L381-L396 | train |
guaix-ucm/numina | numina/array/imsurfit.py | _compute_value | def _compute_value(power, wg):
"""Return the weight corresponding to single power."""
if power not in wg:
p1, p2 = power
# y power
if p1 == 0:
yy = wg[(0, -1)]
wg[power] = numpy.power(yy, p2 / 2).sum() / len(yy)
# x power
else:
xx = wg[(-1, 0)]
wg[power] = numpy.power(xx, p1 / 2).sum() / len(xx)
return wg[power] | python | def _compute_value(power, wg):
"""Return the weight corresponding to single power."""
if power not in wg:
p1, p2 = power
# y power
if p1 == 0:
yy = wg[(0, -1)]
wg[power] = numpy.power(yy, p2 / 2).sum() / len(yy)
# x power
else:
xx = wg[(-1, 0)]
wg[power] = numpy.power(xx, p1 / 2).sum() / len(xx)
return wg[power] | [
"def",
"_compute_value",
"(",
"power",
",",
"wg",
")",
":",
"if",
"power",
"not",
"in",
"wg",
":",
"p1",
",",
"p2",
"=",
"power",
"# y power",
"if",
"p1",
"==",
"0",
":",
"yy",
"=",
"wg",
"[",
"(",
"0",
",",
"-",
"1",
")",
"]",
"wg",
"[",
"power",
"]",
"=",
"numpy",
".",
"power",
"(",
"yy",
",",
"p2",
"/",
"2",
")",
".",
"sum",
"(",
")",
"/",
"len",
"(",
"yy",
")",
"# x power",
"else",
":",
"xx",
"=",
"wg",
"[",
"(",
"-",
"1",
",",
"0",
")",
"]",
"wg",
"[",
"power",
"]",
"=",
"numpy",
".",
"power",
"(",
"xx",
",",
"p1",
"/",
"2",
")",
".",
"sum",
"(",
")",
"/",
"len",
"(",
"xx",
")",
"return",
"wg",
"[",
"power",
"]"
] | Return the weight corresponding to single power. | [
"Return",
"the",
"weight",
"corresponding",
"to",
"single",
"power",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/imsurfit.py#L25-L37 | train |
guaix-ucm/numina | numina/array/imsurfit.py | _compute_weight | def _compute_weight(powers, wg):
"""Return the weight corresponding to given powers."""
# split
pow1 = (powers[0], 0)
pow2 = (0, powers[1])
cal1 = _compute_value(pow1, wg)
cal2 = _compute_value(pow2, wg)
return cal1 * cal2 | python | def _compute_weight(powers, wg):
"""Return the weight corresponding to given powers."""
# split
pow1 = (powers[0], 0)
pow2 = (0, powers[1])
cal1 = _compute_value(pow1, wg)
cal2 = _compute_value(pow2, wg)
return cal1 * cal2 | [
"def",
"_compute_weight",
"(",
"powers",
",",
"wg",
")",
":",
"# split",
"pow1",
"=",
"(",
"powers",
"[",
"0",
"]",
",",
"0",
")",
"pow2",
"=",
"(",
"0",
",",
"powers",
"[",
"1",
"]",
")",
"cal1",
"=",
"_compute_value",
"(",
"pow1",
",",
"wg",
")",
"cal2",
"=",
"_compute_value",
"(",
"pow2",
",",
"wg",
")",
"return",
"cal1",
"*",
"cal2"
] | Return the weight corresponding to given powers. | [
"Return",
"the",
"weight",
"corresponding",
"to",
"given",
"powers",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/imsurfit.py#L40-L49 | train |
guaix-ucm/numina | numina/array/imsurfit.py | imsurfit | def imsurfit(data, order, output_fit=False):
"""Fit a bidimensional polynomial to an image.
:param data: a bidimensional array
:param integer order: order of the polynomial
:param bool output_fit: return the fitted image
:returns: a tuple with an array with the coefficients of the polynomial terms
>>> import numpy
>>> xx, yy = numpy.mgrid[-1:1:100j,-1:1:100j]
>>> z = 456.0 + 0.3 * xx - 0.9* yy
>>> imsurfit(z, order=1) #doctest: +NORMALIZE_WHITESPACE
(array([ 4.56000000e+02, 3.00000000e-01, -9.00000000e-01]),)
"""
# we create a grid with the same number of points
# between -1 and 1
c0 = complex(0, data.shape[0])
c1 = complex(0, data.shape[1])
xx, yy = numpy.ogrid[-1:1:c0, -1:1:c1]
ncoeff = (order + 1) * (order + 2) // 2
powerlist = list(_powers(order))
# Array with ncoff x,y moments of the data
bb = numpy.zeros(ncoeff)
# Moments
for idx, powers in enumerate(powerlist):
p1, p2 = powers
bb[idx] = (data * xx ** p1 * yy ** p2).sum() / data.size
# Now computing aa matrix
# it contains \sum x^a y^b
# most of the terms are zero
# only those with a and b even remain
# aa is symmetric
x = xx[:, 0]
y = yy[0]
# weights are stored so we compute them only once
wg = {(0, 0): 1, (-1, 0): x**2, (0, -1): y**2}
# wg[(2,0)] = wg[(-1,0)].sum() / len(x)
# wg[(0,2)] = wg[(0,-1)].sum() / len(y)
aa = numpy.zeros((ncoeff, ncoeff))
for j, ci in enumerate(powerlist):
for i, ri in enumerate(powerlist[j:]):
p1 = ci[0] + ri[0]
p2 = ci[1] + ri[1]
if p1 % 2 == 0 and p2 % 2 == 0:
# val = (x ** p1).sum() / len(x) * (y ** p2).sum() / len(y)
val = _compute_weight((p1, p2), wg)
aa[j, i+j] = val
# Making symmetric the array
aa += numpy.triu(aa, k=1).T
polycoeff = numpy.linalg.solve(aa, bb)
if output_fit:
index = 0
result = 0
for o in range(order + 1):
for b in range(o + 1):
a = o - b
result += polycoeff[index] * (xx ** a) * (yy ** b)
index += 1
return polycoeff, result
return (polycoeff,) | python | def imsurfit(data, order, output_fit=False):
"""Fit a bidimensional polynomial to an image.
:param data: a bidimensional array
:param integer order: order of the polynomial
:param bool output_fit: return the fitted image
:returns: a tuple with an array with the coefficients of the polynomial terms
>>> import numpy
>>> xx, yy = numpy.mgrid[-1:1:100j,-1:1:100j]
>>> z = 456.0 + 0.3 * xx - 0.9* yy
>>> imsurfit(z, order=1) #doctest: +NORMALIZE_WHITESPACE
(array([ 4.56000000e+02, 3.00000000e-01, -9.00000000e-01]),)
"""
# we create a grid with the same number of points
# between -1 and 1
c0 = complex(0, data.shape[0])
c1 = complex(0, data.shape[1])
xx, yy = numpy.ogrid[-1:1:c0, -1:1:c1]
ncoeff = (order + 1) * (order + 2) // 2
powerlist = list(_powers(order))
# Array with ncoff x,y moments of the data
bb = numpy.zeros(ncoeff)
# Moments
for idx, powers in enumerate(powerlist):
p1, p2 = powers
bb[idx] = (data * xx ** p1 * yy ** p2).sum() / data.size
# Now computing aa matrix
# it contains \sum x^a y^b
# most of the terms are zero
# only those with a and b even remain
# aa is symmetric
x = xx[:, 0]
y = yy[0]
# weights are stored so we compute them only once
wg = {(0, 0): 1, (-1, 0): x**2, (0, -1): y**2}
# wg[(2,0)] = wg[(-1,0)].sum() / len(x)
# wg[(0,2)] = wg[(0,-1)].sum() / len(y)
aa = numpy.zeros((ncoeff, ncoeff))
for j, ci in enumerate(powerlist):
for i, ri in enumerate(powerlist[j:]):
p1 = ci[0] + ri[0]
p2 = ci[1] + ri[1]
if p1 % 2 == 0 and p2 % 2 == 0:
# val = (x ** p1).sum() / len(x) * (y ** p2).sum() / len(y)
val = _compute_weight((p1, p2), wg)
aa[j, i+j] = val
# Making symmetric the array
aa += numpy.triu(aa, k=1).T
polycoeff = numpy.linalg.solve(aa, bb)
if output_fit:
index = 0
result = 0
for o in range(order + 1):
for b in range(o + 1):
a = o - b
result += polycoeff[index] * (xx ** a) * (yy ** b)
index += 1
return polycoeff, result
return (polycoeff,) | [
"def",
"imsurfit",
"(",
"data",
",",
"order",
",",
"output_fit",
"=",
"False",
")",
":",
"# we create a grid with the same number of points",
"# between -1 and 1",
"c0",
"=",
"complex",
"(",
"0",
",",
"data",
".",
"shape",
"[",
"0",
"]",
")",
"c1",
"=",
"complex",
"(",
"0",
",",
"data",
".",
"shape",
"[",
"1",
"]",
")",
"xx",
",",
"yy",
"=",
"numpy",
".",
"ogrid",
"[",
"-",
"1",
":",
"1",
":",
"c0",
",",
"-",
"1",
":",
"1",
":",
"c1",
"]",
"ncoeff",
"=",
"(",
"order",
"+",
"1",
")",
"*",
"(",
"order",
"+",
"2",
")",
"//",
"2",
"powerlist",
"=",
"list",
"(",
"_powers",
"(",
"order",
")",
")",
"# Array with ncoff x,y moments of the data",
"bb",
"=",
"numpy",
".",
"zeros",
"(",
"ncoeff",
")",
"# Moments",
"for",
"idx",
",",
"powers",
"in",
"enumerate",
"(",
"powerlist",
")",
":",
"p1",
",",
"p2",
"=",
"powers",
"bb",
"[",
"idx",
"]",
"=",
"(",
"data",
"*",
"xx",
"**",
"p1",
"*",
"yy",
"**",
"p2",
")",
".",
"sum",
"(",
")",
"/",
"data",
".",
"size",
"# Now computing aa matrix",
"# it contains \\sum x^a y^b",
"# most of the terms are zero",
"# only those with a and b even remain",
"# aa is symmetric",
"x",
"=",
"xx",
"[",
":",
",",
"0",
"]",
"y",
"=",
"yy",
"[",
"0",
"]",
"# weights are stored so we compute them only once",
"wg",
"=",
"{",
"(",
"0",
",",
"0",
")",
":",
"1",
",",
"(",
"-",
"1",
",",
"0",
")",
":",
"x",
"**",
"2",
",",
"(",
"0",
",",
"-",
"1",
")",
":",
"y",
"**",
"2",
"}",
"# wg[(2,0)] = wg[(-1,0)].sum() / len(x)",
"# wg[(0,2)] = wg[(0,-1)].sum() / len(y)",
"aa",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"ncoeff",
",",
"ncoeff",
")",
")",
"for",
"j",
",",
"ci",
"in",
"enumerate",
"(",
"powerlist",
")",
":",
"for",
"i",
",",
"ri",
"in",
"enumerate",
"(",
"powerlist",
"[",
"j",
":",
"]",
")",
":",
"p1",
"=",
"ci",
"[",
"0",
"]",
"+",
"ri",
"[",
"0",
"]",
"p2",
"=",
"ci",
"[",
"1",
"]",
"+",
"ri",
"[",
"1",
"]",
"if",
"p1",
"%",
"2",
"==",
"0",
"and",
"p2",
"%",
"2",
"==",
"0",
":",
"# val = (x ** p1).sum() / len(x) * (y ** p2).sum() / len(y)",
"val",
"=",
"_compute_weight",
"(",
"(",
"p1",
",",
"p2",
")",
",",
"wg",
")",
"aa",
"[",
"j",
",",
"i",
"+",
"j",
"]",
"=",
"val",
"# Making symmetric the array",
"aa",
"+=",
"numpy",
".",
"triu",
"(",
"aa",
",",
"k",
"=",
"1",
")",
".",
"T",
"polycoeff",
"=",
"numpy",
".",
"linalg",
".",
"solve",
"(",
"aa",
",",
"bb",
")",
"if",
"output_fit",
":",
"index",
"=",
"0",
"result",
"=",
"0",
"for",
"o",
"in",
"range",
"(",
"order",
"+",
"1",
")",
":",
"for",
"b",
"in",
"range",
"(",
"o",
"+",
"1",
")",
":",
"a",
"=",
"o",
"-",
"b",
"result",
"+=",
"polycoeff",
"[",
"index",
"]",
"*",
"(",
"xx",
"**",
"a",
")",
"*",
"(",
"yy",
"**",
"b",
")",
"index",
"+=",
"1",
"return",
"polycoeff",
",",
"result",
"return",
"(",
"polycoeff",
",",
")"
] | Fit a bidimensional polynomial to an image.
:param data: a bidimensional array
:param integer order: order of the polynomial
:param bool output_fit: return the fitted image
:returns: a tuple with an array with the coefficients of the polynomial terms
>>> import numpy
>>> xx, yy = numpy.mgrid[-1:1:100j,-1:1:100j]
>>> z = 456.0 + 0.3 * xx - 0.9* yy
>>> imsurfit(z, order=1) #doctest: +NORMALIZE_WHITESPACE
(array([ 4.56000000e+02, 3.00000000e-01, -9.00000000e-01]),) | [
"Fit",
"a",
"bidimensional",
"polynomial",
"to",
"an",
"image",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/imsurfit.py#L52-L125 | train |
pvizeli/yahooweather | yahooweather.py | _yql_query | def _yql_query(yql):
"""Fetch data from Yahoo! Return a dict if successfull or None."""
url = _YAHOO_BASE_URL.format(urlencode({'q': yql}))
# send request
_LOGGER.debug("Send request to url: %s", url)
try:
request = urlopen(url)
rawData = request.read()
# parse jason
data = json.loads(rawData.decode("utf-8"))
_LOGGER.debug("Query data from yahoo: %s", str(data))
return data.get("query", {}).get("results", {})
except (urllib.error.HTTPError, urllib.error.URLError):
_LOGGER.info("Can't fetch data from Yahoo!")
return None | python | def _yql_query(yql):
"""Fetch data from Yahoo! Return a dict if successfull or None."""
url = _YAHOO_BASE_URL.format(urlencode({'q': yql}))
# send request
_LOGGER.debug("Send request to url: %s", url)
try:
request = urlopen(url)
rawData = request.read()
# parse jason
data = json.loads(rawData.decode("utf-8"))
_LOGGER.debug("Query data from yahoo: %s", str(data))
return data.get("query", {}).get("results", {})
except (urllib.error.HTTPError, urllib.error.URLError):
_LOGGER.info("Can't fetch data from Yahoo!")
return None | [
"def",
"_yql_query",
"(",
"yql",
")",
":",
"url",
"=",
"_YAHOO_BASE_URL",
".",
"format",
"(",
"urlencode",
"(",
"{",
"'q'",
":",
"yql",
"}",
")",
")",
"# send request",
"_LOGGER",
".",
"debug",
"(",
"\"Send request to url: %s\"",
",",
"url",
")",
"try",
":",
"request",
"=",
"urlopen",
"(",
"url",
")",
"rawData",
"=",
"request",
".",
"read",
"(",
")",
"# parse jason",
"data",
"=",
"json",
".",
"loads",
"(",
"rawData",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Query data from yahoo: %s\"",
",",
"str",
"(",
"data",
")",
")",
"return",
"data",
".",
"get",
"(",
"\"query\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"results\"",
",",
"{",
"}",
")",
"except",
"(",
"urllib",
".",
"error",
".",
"HTTPError",
",",
"urllib",
".",
"error",
".",
"URLError",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Can't fetch data from Yahoo!\"",
")",
"return",
"None"
] | Fetch data from Yahoo! Return a dict if successfull or None. | [
"Fetch",
"data",
"from",
"Yahoo!",
"Return",
"a",
"dict",
"if",
"successfull",
"or",
"None",
"."
] | 42e59510fc20b84afc8efadfbc3a30c15675b327 | https://github.com/pvizeli/yahooweather/blob/42e59510fc20b84afc8efadfbc3a30c15675b327/yahooweather.py#L22-L41 | train |
pvizeli/yahooweather | yahooweather.py | get_woeid | def get_woeid(lat, lon):
"""Ask Yahoo! who is the woeid from GPS position."""
yql = _YQL_WOEID.format(lat, lon)
# send request
tmpData = _yql_query(yql)
if tmpData is None:
_LOGGER.error("No woid is received!")
return None
# found woid?
return tmpData.get("place", {}).get("woeid", None) | python | def get_woeid(lat, lon):
"""Ask Yahoo! who is the woeid from GPS position."""
yql = _YQL_WOEID.format(lat, lon)
# send request
tmpData = _yql_query(yql)
if tmpData is None:
_LOGGER.error("No woid is received!")
return None
# found woid?
return tmpData.get("place", {}).get("woeid", None) | [
"def",
"get_woeid",
"(",
"lat",
",",
"lon",
")",
":",
"yql",
"=",
"_YQL_WOEID",
".",
"format",
"(",
"lat",
",",
"lon",
")",
"# send request",
"tmpData",
"=",
"_yql_query",
"(",
"yql",
")",
"if",
"tmpData",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"No woid is received!\"",
")",
"return",
"None",
"# found woid?",
"return",
"tmpData",
".",
"get",
"(",
"\"place\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"woeid\"",
",",
"None",
")"
] | Ask Yahoo! who is the woeid from GPS position. | [
"Ask",
"Yahoo!",
"who",
"is",
"the",
"woeid",
"from",
"GPS",
"position",
"."
] | 42e59510fc20b84afc8efadfbc3a30c15675b327 | https://github.com/pvizeli/yahooweather/blob/42e59510fc20b84afc8efadfbc3a30c15675b327/yahooweather.py#L44-L56 | train |
pvizeli/yahooweather | yahooweather.py | YahooWeather.updateWeather | def updateWeather(self):
"""Fetch weather data from Yahoo! True if success."""
yql = _YQL_WEATHER.format(self._woeid, self._unit)
# send request
tmpData = _yql_query(yql)
# data exists
if tmpData is not None and "channel" in tmpData:
self._data = tmpData["channel"]
return True
_LOGGER.error("Fetch no weather data Yahoo!")
self._data = {}
return False | python | def updateWeather(self):
"""Fetch weather data from Yahoo! True if success."""
yql = _YQL_WEATHER.format(self._woeid, self._unit)
# send request
tmpData = _yql_query(yql)
# data exists
if tmpData is not None and "channel" in tmpData:
self._data = tmpData["channel"]
return True
_LOGGER.error("Fetch no weather data Yahoo!")
self._data = {}
return False | [
"def",
"updateWeather",
"(",
"self",
")",
":",
"yql",
"=",
"_YQL_WEATHER",
".",
"format",
"(",
"self",
".",
"_woeid",
",",
"self",
".",
"_unit",
")",
"# send request",
"tmpData",
"=",
"_yql_query",
"(",
"yql",
")",
"# data exists",
"if",
"tmpData",
"is",
"not",
"None",
"and",
"\"channel\"",
"in",
"tmpData",
":",
"self",
".",
"_data",
"=",
"tmpData",
"[",
"\"channel\"",
"]",
"return",
"True",
"_LOGGER",
".",
"error",
"(",
"\"Fetch no weather data Yahoo!\"",
")",
"self",
".",
"_data",
"=",
"{",
"}",
"return",
"False"
] | Fetch weather data from Yahoo! True if success. | [
"Fetch",
"weather",
"data",
"from",
"Yahoo!",
"True",
"if",
"success",
"."
] | 42e59510fc20b84afc8efadfbc3a30c15675b327 | https://github.com/pvizeli/yahooweather/blob/42e59510fc20b84afc8efadfbc3a30c15675b327/yahooweather.py#L68-L82 | train |
SUNCAT-Center/CatHub | cathub/ase_tools/__init__.py | get_energies | def get_energies(atoms_list):
""" Potential energy for a list of atoms objects"""
if len(atoms_list) == 1:
return atoms_list[0].get_potential_energy()
elif len(atoms_list) > 1:
energies = []
for atoms in atoms_list:
energies.append(atoms.get_potential_energy())
return energies | python | def get_energies(atoms_list):
""" Potential energy for a list of atoms objects"""
if len(atoms_list) == 1:
return atoms_list[0].get_potential_energy()
elif len(atoms_list) > 1:
energies = []
for atoms in atoms_list:
energies.append(atoms.get_potential_energy())
return energies | [
"def",
"get_energies",
"(",
"atoms_list",
")",
":",
"if",
"len",
"(",
"atoms_list",
")",
"==",
"1",
":",
"return",
"atoms_list",
"[",
"0",
"]",
".",
"get_potential_energy",
"(",
")",
"elif",
"len",
"(",
"atoms_list",
")",
">",
"1",
":",
"energies",
"=",
"[",
"]",
"for",
"atoms",
"in",
"atoms_list",
":",
"energies",
".",
"append",
"(",
"atoms",
".",
"get_potential_energy",
"(",
")",
")",
"return",
"energies"
] | Potential energy for a list of atoms objects | [
"Potential",
"energy",
"for",
"a",
"list",
"of",
"atoms",
"objects"
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/ase_tools/__init__.py#L174-L182 | train |
SUNCAT-Center/CatHub | cathub/ase_tools/__init__.py | check_in_ase | def check_in_ase(atoms, ase_db, energy=None):
"""Check if entry is allready in ASE db"""
db_ase = ase.db.connect(ase_db)
if energy is None:
energy = atoms.get_potential_energy()
formula = get_chemical_formula(atoms)
rows = db_ase.select(energy=energy)
n = 0
ids = []
for row in rows:
if formula == row.formula:
n += 1
ids.append(row.id)
if n > 0:
id = ids[0]
unique_id = db_ase.get(id)['unique_id']
return id, unique_id
else:
return None, None | python | def check_in_ase(atoms, ase_db, energy=None):
"""Check if entry is allready in ASE db"""
db_ase = ase.db.connect(ase_db)
if energy is None:
energy = atoms.get_potential_energy()
formula = get_chemical_formula(atoms)
rows = db_ase.select(energy=energy)
n = 0
ids = []
for row in rows:
if formula == row.formula:
n += 1
ids.append(row.id)
if n > 0:
id = ids[0]
unique_id = db_ase.get(id)['unique_id']
return id, unique_id
else:
return None, None | [
"def",
"check_in_ase",
"(",
"atoms",
",",
"ase_db",
",",
"energy",
"=",
"None",
")",
":",
"db_ase",
"=",
"ase",
".",
"db",
".",
"connect",
"(",
"ase_db",
")",
"if",
"energy",
"is",
"None",
":",
"energy",
"=",
"atoms",
".",
"get_potential_energy",
"(",
")",
"formula",
"=",
"get_chemical_formula",
"(",
"atoms",
")",
"rows",
"=",
"db_ase",
".",
"select",
"(",
"energy",
"=",
"energy",
")",
"n",
"=",
"0",
"ids",
"=",
"[",
"]",
"for",
"row",
"in",
"rows",
":",
"if",
"formula",
"==",
"row",
".",
"formula",
":",
"n",
"+=",
"1",
"ids",
".",
"append",
"(",
"row",
".",
"id",
")",
"if",
"n",
">",
"0",
":",
"id",
"=",
"ids",
"[",
"0",
"]",
"unique_id",
"=",
"db_ase",
".",
"get",
"(",
"id",
")",
"[",
"'unique_id'",
"]",
"return",
"id",
",",
"unique_id",
"else",
":",
"return",
"None",
",",
"None"
] | Check if entry is allready in ASE db | [
"Check",
"if",
"entry",
"is",
"allready",
"in",
"ASE",
"db"
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/ase_tools/__init__.py#L322-L341 | train |
pylp/pylp | pylp/lib/tasks.py | task | def task(name, deps = None, fn = None):
"""Define a new task."""
if callable(deps):
fn = deps
deps = None
if not deps and not fn:
logger.log(logger.red("The task '%s' is empty" % name))
else:
tasks[name] = [fn, deps] | python | def task(name, deps = None, fn = None):
"""Define a new task."""
if callable(deps):
fn = deps
deps = None
if not deps and not fn:
logger.log(logger.red("The task '%s' is empty" % name))
else:
tasks[name] = [fn, deps] | [
"def",
"task",
"(",
"name",
",",
"deps",
"=",
"None",
",",
"fn",
"=",
"None",
")",
":",
"if",
"callable",
"(",
"deps",
")",
":",
"fn",
"=",
"deps",
"deps",
"=",
"None",
"if",
"not",
"deps",
"and",
"not",
"fn",
":",
"logger",
".",
"log",
"(",
"logger",
".",
"red",
"(",
"\"The task '%s' is empty\"",
"%",
"name",
")",
")",
"else",
":",
"tasks",
"[",
"name",
"]",
"=",
"[",
"fn",
",",
"deps",
"]"
] | Define a new task. | [
"Define",
"a",
"new",
"task",
"."
] | 7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4 | https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/tasks.py#L18-L27 | train |
guaix-ucm/numina | numina/modeling/sumofgauss.py | sum_of_gaussian_factory | def sum_of_gaussian_factory(N):
"""Return a model of the sum of N Gaussians and a constant background."""
name = "SumNGauss%d" % N
attr = {}
# parameters
for i in range(N):
key = "amplitude_%d" % i
attr[key] = Parameter(key)
key = "center_%d" % i
attr[key] = Parameter(key)
key = "stddev_%d" % i
attr[key] = Parameter(key)
attr['background'] = Parameter('background', default=0.0)
def fit_eval(self, x, *args):
result = x * 0 + args[-1]
for i in range(N):
result += args[3 * i] * \
np.exp(- 0.5 * (x - args[3 * i + 1])
** 2 / args[3 * i + 2] ** 2)
return result
attr['evaluate'] = fit_eval
def deriv(self, x, *args):
d_result = np.ones(((3 * N + 1), len(x)))
for i in range(N):
d_result[3 * i] = (np.exp(-0.5 / args[3 * i + 2] ** 2 *
(x - args[3 * i + 1]) ** 2))
d_result[3 * i + 1] = args[3 * i] * d_result[3 * i] * \
(x - args[3 * i + 1]) / args[3 * i + 2] ** 2
d_result[3 * i + 2] = args[3 * i] * d_result[3 * i] * \
(x - args[3 * i + 1]) ** 2 / args[3 * i + 2] ** 3
return d_result
attr['fit_deriv'] = deriv
klass = type(name, (Fittable1DModel, ), attr)
return klass | python | def sum_of_gaussian_factory(N):
"""Return a model of the sum of N Gaussians and a constant background."""
name = "SumNGauss%d" % N
attr = {}
# parameters
for i in range(N):
key = "amplitude_%d" % i
attr[key] = Parameter(key)
key = "center_%d" % i
attr[key] = Parameter(key)
key = "stddev_%d" % i
attr[key] = Parameter(key)
attr['background'] = Parameter('background', default=0.0)
def fit_eval(self, x, *args):
result = x * 0 + args[-1]
for i in range(N):
result += args[3 * i] * \
np.exp(- 0.5 * (x - args[3 * i + 1])
** 2 / args[3 * i + 2] ** 2)
return result
attr['evaluate'] = fit_eval
def deriv(self, x, *args):
d_result = np.ones(((3 * N + 1), len(x)))
for i in range(N):
d_result[3 * i] = (np.exp(-0.5 / args[3 * i + 2] ** 2 *
(x - args[3 * i + 1]) ** 2))
d_result[3 * i + 1] = args[3 * i] * d_result[3 * i] * \
(x - args[3 * i + 1]) / args[3 * i + 2] ** 2
d_result[3 * i + 2] = args[3 * i] * d_result[3 * i] * \
(x - args[3 * i + 1]) ** 2 / args[3 * i + 2] ** 3
return d_result
attr['fit_deriv'] = deriv
klass = type(name, (Fittable1DModel, ), attr)
return klass | [
"def",
"sum_of_gaussian_factory",
"(",
"N",
")",
":",
"name",
"=",
"\"SumNGauss%d\"",
"%",
"N",
"attr",
"=",
"{",
"}",
"# parameters",
"for",
"i",
"in",
"range",
"(",
"N",
")",
":",
"key",
"=",
"\"amplitude_%d\"",
"%",
"i",
"attr",
"[",
"key",
"]",
"=",
"Parameter",
"(",
"key",
")",
"key",
"=",
"\"center_%d\"",
"%",
"i",
"attr",
"[",
"key",
"]",
"=",
"Parameter",
"(",
"key",
")",
"key",
"=",
"\"stddev_%d\"",
"%",
"i",
"attr",
"[",
"key",
"]",
"=",
"Parameter",
"(",
"key",
")",
"attr",
"[",
"'background'",
"]",
"=",
"Parameter",
"(",
"'background'",
",",
"default",
"=",
"0.0",
")",
"def",
"fit_eval",
"(",
"self",
",",
"x",
",",
"*",
"args",
")",
":",
"result",
"=",
"x",
"*",
"0",
"+",
"args",
"[",
"-",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"N",
")",
":",
"result",
"+=",
"args",
"[",
"3",
"*",
"i",
"]",
"*",
"np",
".",
"exp",
"(",
"-",
"0.5",
"*",
"(",
"x",
"-",
"args",
"[",
"3",
"*",
"i",
"+",
"1",
"]",
")",
"**",
"2",
"/",
"args",
"[",
"3",
"*",
"i",
"+",
"2",
"]",
"**",
"2",
")",
"return",
"result",
"attr",
"[",
"'evaluate'",
"]",
"=",
"fit_eval",
"def",
"deriv",
"(",
"self",
",",
"x",
",",
"*",
"args",
")",
":",
"d_result",
"=",
"np",
".",
"ones",
"(",
"(",
"(",
"3",
"*",
"N",
"+",
"1",
")",
",",
"len",
"(",
"x",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"N",
")",
":",
"d_result",
"[",
"3",
"*",
"i",
"]",
"=",
"(",
"np",
".",
"exp",
"(",
"-",
"0.5",
"/",
"args",
"[",
"3",
"*",
"i",
"+",
"2",
"]",
"**",
"2",
"*",
"(",
"x",
"-",
"args",
"[",
"3",
"*",
"i",
"+",
"1",
"]",
")",
"**",
"2",
")",
")",
"d_result",
"[",
"3",
"*",
"i",
"+",
"1",
"]",
"=",
"args",
"[",
"3",
"*",
"i",
"]",
"*",
"d_result",
"[",
"3",
"*",
"i",
"]",
"*",
"(",
"x",
"-",
"args",
"[",
"3",
"*",
"i",
"+",
"1",
"]",
")",
"/",
"args",
"[",
"3",
"*",
"i",
"+",
"2",
"]",
"**",
"2",
"d_result",
"[",
"3",
"*",
"i",
"+",
"2",
"]",
"=",
"args",
"[",
"3",
"*",
"i",
"]",
"*",
"d_result",
"[",
"3",
"*",
"i",
"]",
"*",
"(",
"x",
"-",
"args",
"[",
"3",
"*",
"i",
"+",
"1",
"]",
")",
"**",
"2",
"/",
"args",
"[",
"3",
"*",
"i",
"+",
"2",
"]",
"**",
"3",
"return",
"d_result",
"attr",
"[",
"'fit_deriv'",
"]",
"=",
"deriv",
"klass",
"=",
"type",
"(",
"name",
",",
"(",
"Fittable1DModel",
",",
")",
",",
"attr",
")",
"return",
"klass"
] | Return a model of the sum of N Gaussians and a constant background. | [
"Return",
"a",
"model",
"of",
"the",
"sum",
"of",
"N",
"Gaussians",
"and",
"a",
"constant",
"background",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/modeling/sumofgauss.py#L14-L56 | train |
PierreRust/apigpio | apigpio/utils.py | Debounce | def Debounce(threshold=100):
"""
Simple debouncing decorator for apigpio callbacks.
Example:
`@Debouncer()
def my_cb(gpio, level, tick)
print('gpio cb: {} {} {}'.format(gpio, level, tick))
`
The threshold can be given to the decorator as an argument (in millisec).
This decorator can be used both on function and object's methods.
Warning: as the debouncer uses the tick from pigpio, which wraps around
after approximately 1 hour 12 minutes, you could theoretically miss one
call if your callback is called twice with that interval.
"""
threshold *= 1000
max_tick = 0xFFFFFFFF
class _decorated(object):
def __init__(self, pigpio_cb):
self._fn = pigpio_cb
self.last = 0
self.is_method = False
def __call__(self, *args, **kwargs):
if self.is_method:
tick = args[3]
else:
tick = args[2]
if self.last > tick:
delay = max_tick-self.last + tick
else:
delay = tick - self.last
if delay > threshold:
self._fn(*args, **kwargs)
print('call passed by debouncer {} {} {}'
.format(tick, self.last, threshold))
self.last = tick
else:
print('call filtered out by debouncer {} {} {}'
.format(tick, self.last, threshold))
def __get__(self, instance, type=None):
# with is called when an instance of `_decorated` is used as a class
# attribute, which is the case when decorating a method in a class
self.is_method = True
return functools.partial(self, instance)
return _decorated | python | def Debounce(threshold=100):
"""
Simple debouncing decorator for apigpio callbacks.
Example:
`@Debouncer()
def my_cb(gpio, level, tick)
print('gpio cb: {} {} {}'.format(gpio, level, tick))
`
The threshold can be given to the decorator as an argument (in millisec).
This decorator can be used both on function and object's methods.
Warning: as the debouncer uses the tick from pigpio, which wraps around
after approximately 1 hour 12 minutes, you could theoretically miss one
call if your callback is called twice with that interval.
"""
threshold *= 1000
max_tick = 0xFFFFFFFF
class _decorated(object):
def __init__(self, pigpio_cb):
self._fn = pigpio_cb
self.last = 0
self.is_method = False
def __call__(self, *args, **kwargs):
if self.is_method:
tick = args[3]
else:
tick = args[2]
if self.last > tick:
delay = max_tick-self.last + tick
else:
delay = tick - self.last
if delay > threshold:
self._fn(*args, **kwargs)
print('call passed by debouncer {} {} {}'
.format(tick, self.last, threshold))
self.last = tick
else:
print('call filtered out by debouncer {} {} {}'
.format(tick, self.last, threshold))
def __get__(self, instance, type=None):
# with is called when an instance of `_decorated` is used as a class
# attribute, which is the case when decorating a method in a class
self.is_method = True
return functools.partial(self, instance)
return _decorated | [
"def",
"Debounce",
"(",
"threshold",
"=",
"100",
")",
":",
"threshold",
"*=",
"1000",
"max_tick",
"=",
"0xFFFFFFFF",
"class",
"_decorated",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"pigpio_cb",
")",
":",
"self",
".",
"_fn",
"=",
"pigpio_cb",
"self",
".",
"last",
"=",
"0",
"self",
".",
"is_method",
"=",
"False",
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"is_method",
":",
"tick",
"=",
"args",
"[",
"3",
"]",
"else",
":",
"tick",
"=",
"args",
"[",
"2",
"]",
"if",
"self",
".",
"last",
">",
"tick",
":",
"delay",
"=",
"max_tick",
"-",
"self",
".",
"last",
"+",
"tick",
"else",
":",
"delay",
"=",
"tick",
"-",
"self",
".",
"last",
"if",
"delay",
">",
"threshold",
":",
"self",
".",
"_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"print",
"(",
"'call passed by debouncer {} {} {}'",
".",
"format",
"(",
"tick",
",",
"self",
".",
"last",
",",
"threshold",
")",
")",
"self",
".",
"last",
"=",
"tick",
"else",
":",
"print",
"(",
"'call filtered out by debouncer {} {} {}'",
".",
"format",
"(",
"tick",
",",
"self",
".",
"last",
",",
"threshold",
")",
")",
"def",
"__get__",
"(",
"self",
",",
"instance",
",",
"type",
"=",
"None",
")",
":",
"# with is called when an instance of `_decorated` is used as a class",
"# attribute, which is the case when decorating a method in a class",
"self",
".",
"is_method",
"=",
"True",
"return",
"functools",
".",
"partial",
"(",
"self",
",",
"instance",
")",
"return",
"_decorated"
] | Simple debouncing decorator for apigpio callbacks.
Example:
`@Debouncer()
def my_cb(gpio, level, tick)
print('gpio cb: {} {} {}'.format(gpio, level, tick))
`
The threshold can be given to the decorator as an argument (in millisec).
This decorator can be used both on function and object's methods.
Warning: as the debouncer uses the tick from pigpio, which wraps around
after approximately 1 hour 12 minutes, you could theoretically miss one
call if your callback is called twice with that interval. | [
"Simple",
"debouncing",
"decorator",
"for",
"apigpio",
"callbacks",
"."
] | 2b969f40e06219b43a43498d8baf87f5935ceab2 | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/utils.py#L4-L56 | train |
morepath/more.jwtauth | more/jwtauth/refresh.py | verify_refresh_request | def verify_refresh_request(request):
"""
Wrapper around JWTIdentityPolicy.verify_refresh which verify
if the request to refresh the token is valid.
If valid it returns the userid which can be used to create to
create an updated identity with ``remember_identity``.
Otherwise it raises an exception based on InvalidTokenError.
:param request: request object
:type request: :class:`morepath.Request`
:returns: userid
:raises: InvalidTokenError, ExpiredSignatureError, DecodeError,
MissingRequiredClaimError
"""
jwtauth_settings = request.app.settings.jwtauth.__dict__.copy()
identity_policy = JWTIdentityPolicy(**jwtauth_settings)
return identity_policy.verify_refresh(request) | python | def verify_refresh_request(request):
"""
Wrapper around JWTIdentityPolicy.verify_refresh which verify
if the request to refresh the token is valid.
If valid it returns the userid which can be used to create to
create an updated identity with ``remember_identity``.
Otherwise it raises an exception based on InvalidTokenError.
:param request: request object
:type request: :class:`morepath.Request`
:returns: userid
:raises: InvalidTokenError, ExpiredSignatureError, DecodeError,
MissingRequiredClaimError
"""
jwtauth_settings = request.app.settings.jwtauth.__dict__.copy()
identity_policy = JWTIdentityPolicy(**jwtauth_settings)
return identity_policy.verify_refresh(request) | [
"def",
"verify_refresh_request",
"(",
"request",
")",
":",
"jwtauth_settings",
"=",
"request",
".",
"app",
".",
"settings",
".",
"jwtauth",
".",
"__dict__",
".",
"copy",
"(",
")",
"identity_policy",
"=",
"JWTIdentityPolicy",
"(",
"*",
"*",
"jwtauth_settings",
")",
"return",
"identity_policy",
".",
"verify_refresh",
"(",
"request",
")"
] | Wrapper around JWTIdentityPolicy.verify_refresh which verify
if the request to refresh the token is valid.
If valid it returns the userid which can be used to create to
create an updated identity with ``remember_identity``.
Otherwise it raises an exception based on InvalidTokenError.
:param request: request object
:type request: :class:`morepath.Request`
:returns: userid
:raises: InvalidTokenError, ExpiredSignatureError, DecodeError,
MissingRequiredClaimError | [
"Wrapper",
"around",
"JWTIdentityPolicy",
".",
"verify_refresh",
"which",
"verify",
"if",
"the",
"request",
"to",
"refresh",
"the",
"token",
"is",
"valid",
".",
"If",
"valid",
"it",
"returns",
"the",
"userid",
"which",
"can",
"be",
"used",
"to",
"create",
"to",
"create",
"an",
"updated",
"identity",
"with",
"remember_identity",
".",
"Otherwise",
"it",
"raises",
"an",
"exception",
"based",
"on",
"InvalidTokenError",
"."
] | 1c3c5731612069a092e44cf612641c05edf1f083 | https://github.com/morepath/more.jwtauth/blob/1c3c5731612069a092e44cf612641c05edf1f083/more/jwtauth/refresh.py#L4-L21 | train |
guaix-ucm/numina | numina/array/peaks/detrend.py | detrend | def detrend(arr, x=None, deg=5, tol=1e-3, maxloop=10):
"""Compute a baseline trend of a signal"""
xx = numpy.arange(len(arr)) if x is None else x
base = arr.copy()
trend = base
pol = numpy.ones((deg + 1,))
for _ in range(maxloop):
pol_new = numpy.polyfit(xx, base, deg)
pol_norm = numpy.linalg.norm(pol)
diff_pol_norm = numpy.linalg.norm(pol - pol_new)
if diff_pol_norm / pol_norm < tol:
break
pol = pol_new
trend = numpy.polyval(pol, xx)
base = numpy.minimum(base, trend)
return trend | python | def detrend(arr, x=None, deg=5, tol=1e-3, maxloop=10):
"""Compute a baseline trend of a signal"""
xx = numpy.arange(len(arr)) if x is None else x
base = arr.copy()
trend = base
pol = numpy.ones((deg + 1,))
for _ in range(maxloop):
pol_new = numpy.polyfit(xx, base, deg)
pol_norm = numpy.linalg.norm(pol)
diff_pol_norm = numpy.linalg.norm(pol - pol_new)
if diff_pol_norm / pol_norm < tol:
break
pol = pol_new
trend = numpy.polyval(pol, xx)
base = numpy.minimum(base, trend)
return trend | [
"def",
"detrend",
"(",
"arr",
",",
"x",
"=",
"None",
",",
"deg",
"=",
"5",
",",
"tol",
"=",
"1e-3",
",",
"maxloop",
"=",
"10",
")",
":",
"xx",
"=",
"numpy",
".",
"arange",
"(",
"len",
"(",
"arr",
")",
")",
"if",
"x",
"is",
"None",
"else",
"x",
"base",
"=",
"arr",
".",
"copy",
"(",
")",
"trend",
"=",
"base",
"pol",
"=",
"numpy",
".",
"ones",
"(",
"(",
"deg",
"+",
"1",
",",
")",
")",
"for",
"_",
"in",
"range",
"(",
"maxloop",
")",
":",
"pol_new",
"=",
"numpy",
".",
"polyfit",
"(",
"xx",
",",
"base",
",",
"deg",
")",
"pol_norm",
"=",
"numpy",
".",
"linalg",
".",
"norm",
"(",
"pol",
")",
"diff_pol_norm",
"=",
"numpy",
".",
"linalg",
".",
"norm",
"(",
"pol",
"-",
"pol_new",
")",
"if",
"diff_pol_norm",
"/",
"pol_norm",
"<",
"tol",
":",
"break",
"pol",
"=",
"pol_new",
"trend",
"=",
"numpy",
".",
"polyval",
"(",
"pol",
",",
"xx",
")",
"base",
"=",
"numpy",
".",
"minimum",
"(",
"base",
",",
"trend",
")",
"return",
"trend"
] | Compute a baseline trend of a signal | [
"Compute",
"a",
"baseline",
"trend",
"of",
"a",
"signal"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/peaks/detrend.py#L13-L29 | train |
arkottke/pysra | pysra/motion.py | TimeSeriesMotion.calc_osc_accels | def calc_osc_accels(self, osc_freqs, osc_damping=0.05, tf=None):
"""Compute the pseudo-acceleration spectral response of an oscillator
with a specific frequency and damping.
Parameters
----------
osc_freq : float
Frequency of the oscillator (Hz).
osc_damping : float
Fractional damping of the oscillator (dec). For example, 0.05 for a
damping ratio of 5%.
tf : array_like, optional
Transfer function to be applied to motion prior calculation of the
oscillator response.
Returns
-------
spec_accels : :class:`numpy.ndarray`
Peak pseudo-spectral acceleration of the oscillator
"""
if tf is None:
tf = np.ones_like(self.freqs)
else:
tf = np.asarray(tf).astype(complex)
resp = np.array([
self.calc_peak(tf * self._calc_sdof_tf(of, osc_damping))
for of in osc_freqs
])
return resp | python | def calc_osc_accels(self, osc_freqs, osc_damping=0.05, tf=None):
"""Compute the pseudo-acceleration spectral response of an oscillator
with a specific frequency and damping.
Parameters
----------
osc_freq : float
Frequency of the oscillator (Hz).
osc_damping : float
Fractional damping of the oscillator (dec). For example, 0.05 for a
damping ratio of 5%.
tf : array_like, optional
Transfer function to be applied to motion prior calculation of the
oscillator response.
Returns
-------
spec_accels : :class:`numpy.ndarray`
Peak pseudo-spectral acceleration of the oscillator
"""
if tf is None:
tf = np.ones_like(self.freqs)
else:
tf = np.asarray(tf).astype(complex)
resp = np.array([
self.calc_peak(tf * self._calc_sdof_tf(of, osc_damping))
for of in osc_freqs
])
return resp | [
"def",
"calc_osc_accels",
"(",
"self",
",",
"osc_freqs",
",",
"osc_damping",
"=",
"0.05",
",",
"tf",
"=",
"None",
")",
":",
"if",
"tf",
"is",
"None",
":",
"tf",
"=",
"np",
".",
"ones_like",
"(",
"self",
".",
"freqs",
")",
"else",
":",
"tf",
"=",
"np",
".",
"asarray",
"(",
"tf",
")",
".",
"astype",
"(",
"complex",
")",
"resp",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"calc_peak",
"(",
"tf",
"*",
"self",
".",
"_calc_sdof_tf",
"(",
"of",
",",
"osc_damping",
")",
")",
"for",
"of",
"in",
"osc_freqs",
"]",
")",
"return",
"resp"
] | Compute the pseudo-acceleration spectral response of an oscillator
with a specific frequency and damping.
Parameters
----------
osc_freq : float
Frequency of the oscillator (Hz).
osc_damping : float
Fractional damping of the oscillator (dec). For example, 0.05 for a
damping ratio of 5%.
tf : array_like, optional
Transfer function to be applied to motion prior calculation of the
oscillator response.
Returns
-------
spec_accels : :class:`numpy.ndarray`
Peak pseudo-spectral acceleration of the oscillator | [
"Compute",
"the",
"pseudo",
"-",
"acceleration",
"spectral",
"response",
"of",
"an",
"oscillator",
"with",
"a",
"specific",
"frequency",
"and",
"damping",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/motion.py#L141-L170 | train |
arkottke/pysra | pysra/motion.py | TimeSeriesMotion._calc_fourier_spectrum | def _calc_fourier_spectrum(self, fa_length=None):
"""Compute the Fourier Amplitude Spectrum of the time series."""
if fa_length is None:
# Use the next power of 2 for the length
n = 1
while n < self.accels.size:
n <<= 1
else:
n = fa_length
self._fourier_amps = np.fft.rfft(self._accels, n)
freq_step = 1. / (2 * self._time_step * (n / 2))
self._freqs = freq_step * np.arange(1 + n / 2) | python | def _calc_fourier_spectrum(self, fa_length=None):
"""Compute the Fourier Amplitude Spectrum of the time series."""
if fa_length is None:
# Use the next power of 2 for the length
n = 1
while n < self.accels.size:
n <<= 1
else:
n = fa_length
self._fourier_amps = np.fft.rfft(self._accels, n)
freq_step = 1. / (2 * self._time_step * (n / 2))
self._freqs = freq_step * np.arange(1 + n / 2) | [
"def",
"_calc_fourier_spectrum",
"(",
"self",
",",
"fa_length",
"=",
"None",
")",
":",
"if",
"fa_length",
"is",
"None",
":",
"# Use the next power of 2 for the length",
"n",
"=",
"1",
"while",
"n",
"<",
"self",
".",
"accels",
".",
"size",
":",
"n",
"<<=",
"1",
"else",
":",
"n",
"=",
"fa_length",
"self",
".",
"_fourier_amps",
"=",
"np",
".",
"fft",
".",
"rfft",
"(",
"self",
".",
"_accels",
",",
"n",
")",
"freq_step",
"=",
"1.",
"/",
"(",
"2",
"*",
"self",
".",
"_time_step",
"*",
"(",
"n",
"/",
"2",
")",
")",
"self",
".",
"_freqs",
"=",
"freq_step",
"*",
"np",
".",
"arange",
"(",
"1",
"+",
"n",
"/",
"2",
")"
] | Compute the Fourier Amplitude Spectrum of the time series. | [
"Compute",
"the",
"Fourier",
"Amplitude",
"Spectrum",
"of",
"the",
"time",
"series",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/motion.py#L172-L186 | train |
arkottke/pysra | pysra/motion.py | TimeSeriesMotion._calc_sdof_tf | def _calc_sdof_tf(self, osc_freq, damping=0.05):
"""Compute the transfer function for a single-degree-of-freedom
oscillator.
The transfer function computes the pseudo-spectral acceleration.
Parameters
----------
osc_freq : float
natural frequency of the oscillator [Hz]
damping : float, optional
damping ratio of the oscillator in decimal. Default value is
0.05, or 5%.
Returns
-------
tf : :class:`numpy.ndarray`
Complex-valued transfer function with length equal to `self.freq`.
"""
return (-osc_freq ** 2. / (np.square(self.freqs) - np.square(osc_freq)
- 2.j * damping * osc_freq * self.freqs)) | python | def _calc_sdof_tf(self, osc_freq, damping=0.05):
"""Compute the transfer function for a single-degree-of-freedom
oscillator.
The transfer function computes the pseudo-spectral acceleration.
Parameters
----------
osc_freq : float
natural frequency of the oscillator [Hz]
damping : float, optional
damping ratio of the oscillator in decimal. Default value is
0.05, or 5%.
Returns
-------
tf : :class:`numpy.ndarray`
Complex-valued transfer function with length equal to `self.freq`.
"""
return (-osc_freq ** 2. / (np.square(self.freqs) - np.square(osc_freq)
- 2.j * damping * osc_freq * self.freqs)) | [
"def",
"_calc_sdof_tf",
"(",
"self",
",",
"osc_freq",
",",
"damping",
"=",
"0.05",
")",
":",
"return",
"(",
"-",
"osc_freq",
"**",
"2.",
"/",
"(",
"np",
".",
"square",
"(",
"self",
".",
"freqs",
")",
"-",
"np",
".",
"square",
"(",
"osc_freq",
")",
"-",
"2.j",
"*",
"damping",
"*",
"osc_freq",
"*",
"self",
".",
"freqs",
")",
")"
] | Compute the transfer function for a single-degree-of-freedom
oscillator.
The transfer function computes the pseudo-spectral acceleration.
Parameters
----------
osc_freq : float
natural frequency of the oscillator [Hz]
damping : float, optional
damping ratio of the oscillator in decimal. Default value is
0.05, or 5%.
Returns
-------
tf : :class:`numpy.ndarray`
Complex-valued transfer function with length equal to `self.freq`. | [
"Compute",
"the",
"transfer",
"function",
"for",
"a",
"single",
"-",
"degree",
"-",
"of",
"-",
"freedom",
"oscillator",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/motion.py#L188-L208 | train |
arkottke/pysra | pysra/motion.py | TimeSeriesMotion.load_at2_file | def load_at2_file(cls, filename):
"""Read an AT2 formatted time series.
Parameters
----------
filename: str
Filename to open.
"""
with open(filename) as fp:
next(fp)
description = next(fp).strip()
next(fp)
parts = next(fp).split()
time_step = float(parts[1])
accels = [float(p) for l in fp for p in l.split()]
return cls(filename, description, time_step, accels) | python | def load_at2_file(cls, filename):
"""Read an AT2 formatted time series.
Parameters
----------
filename: str
Filename to open.
"""
with open(filename) as fp:
next(fp)
description = next(fp).strip()
next(fp)
parts = next(fp).split()
time_step = float(parts[1])
accels = [float(p) for l in fp for p in l.split()]
return cls(filename, description, time_step, accels) | [
"def",
"load_at2_file",
"(",
"cls",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fp",
":",
"next",
"(",
"fp",
")",
"description",
"=",
"next",
"(",
"fp",
")",
".",
"strip",
"(",
")",
"next",
"(",
"fp",
")",
"parts",
"=",
"next",
"(",
"fp",
")",
".",
"split",
"(",
")",
"time_step",
"=",
"float",
"(",
"parts",
"[",
"1",
"]",
")",
"accels",
"=",
"[",
"float",
"(",
"p",
")",
"for",
"l",
"in",
"fp",
"for",
"p",
"in",
"l",
".",
"split",
"(",
")",
"]",
"return",
"cls",
"(",
"filename",
",",
"description",
",",
"time_step",
",",
"accels",
")"
] | Read an AT2 formatted time series.
Parameters
----------
filename: str
Filename to open. | [
"Read",
"an",
"AT2",
"formatted",
"time",
"series",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/motion.py#L211-L229 | train |
arkottke/pysra | pysra/motion.py | TimeSeriesMotion.load_smc_file | def load_smc_file(cls, filename):
"""Read an SMC formatted time series.
Format of the time series is provided by:
https://escweb.wr.usgs.gov/nsmp-data/smcfmt.html
Parameters
----------
filename: str
Filename to open.
"""
from .tools import parse_fixed_width
with open(filename) as fp:
lines = list(fp)
# 11 lines of strings
lines_str = [lines.pop(0) for _ in range(11)]
if lines_str[0].strip() != '2 CORRECTED ACCELEROGRAM':
raise RuntimeWarning("Loading uncorrected SMC file.")
m = re.search('station =(.+)component=(.+)', lines_str[5])
description = '; '.join([g.strip() for g in m.groups()])
# 6 lines of (8i10) formatted integers
values_int = parse_fixed_width(48 * [(10, int)],
[lines.pop(0) for _ in range(6)])
count_comment = values_int[15]
count = values_int[16]
# 10 lines of (5e15.7) formatted floats
values_float = parse_fixed_width(50 * [(15, float)],
[lines.pop(0) for _ in range(10)])
time_step = 1 / values_float[1]
# Skip comments
lines = lines[count_comment:]
accels = np.array(parse_fixed_width(count * [
(10, float),
], lines))
return TimeSeriesMotion(filename, description, time_step, accels) | python | def load_smc_file(cls, filename):
"""Read an SMC formatted time series.
Format of the time series is provided by:
https://escweb.wr.usgs.gov/nsmp-data/smcfmt.html
Parameters
----------
filename: str
Filename to open.
"""
from .tools import parse_fixed_width
with open(filename) as fp:
lines = list(fp)
# 11 lines of strings
lines_str = [lines.pop(0) for _ in range(11)]
if lines_str[0].strip() != '2 CORRECTED ACCELEROGRAM':
raise RuntimeWarning("Loading uncorrected SMC file.")
m = re.search('station =(.+)component=(.+)', lines_str[5])
description = '; '.join([g.strip() for g in m.groups()])
# 6 lines of (8i10) formatted integers
values_int = parse_fixed_width(48 * [(10, int)],
[lines.pop(0) for _ in range(6)])
count_comment = values_int[15]
count = values_int[16]
# 10 lines of (5e15.7) formatted floats
values_float = parse_fixed_width(50 * [(15, float)],
[lines.pop(0) for _ in range(10)])
time_step = 1 / values_float[1]
# Skip comments
lines = lines[count_comment:]
accels = np.array(parse_fixed_width(count * [
(10, float),
], lines))
return TimeSeriesMotion(filename, description, time_step, accels) | [
"def",
"load_smc_file",
"(",
"cls",
",",
"filename",
")",
":",
"from",
".",
"tools",
"import",
"parse_fixed_width",
"with",
"open",
"(",
"filename",
")",
"as",
"fp",
":",
"lines",
"=",
"list",
"(",
"fp",
")",
"# 11 lines of strings",
"lines_str",
"=",
"[",
"lines",
".",
"pop",
"(",
"0",
")",
"for",
"_",
"in",
"range",
"(",
"11",
")",
"]",
"if",
"lines_str",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"!=",
"'2 CORRECTED ACCELEROGRAM'",
":",
"raise",
"RuntimeWarning",
"(",
"\"Loading uncorrected SMC file.\"",
")",
"m",
"=",
"re",
".",
"search",
"(",
"'station =(.+)component=(.+)'",
",",
"lines_str",
"[",
"5",
"]",
")",
"description",
"=",
"'; '",
".",
"join",
"(",
"[",
"g",
".",
"strip",
"(",
")",
"for",
"g",
"in",
"m",
".",
"groups",
"(",
")",
"]",
")",
"# 6 lines of (8i10) formatted integers",
"values_int",
"=",
"parse_fixed_width",
"(",
"48",
"*",
"[",
"(",
"10",
",",
"int",
")",
"]",
",",
"[",
"lines",
".",
"pop",
"(",
"0",
")",
"for",
"_",
"in",
"range",
"(",
"6",
")",
"]",
")",
"count_comment",
"=",
"values_int",
"[",
"15",
"]",
"count",
"=",
"values_int",
"[",
"16",
"]",
"# 10 lines of (5e15.7) formatted floats",
"values_float",
"=",
"parse_fixed_width",
"(",
"50",
"*",
"[",
"(",
"15",
",",
"float",
")",
"]",
",",
"[",
"lines",
".",
"pop",
"(",
"0",
")",
"for",
"_",
"in",
"range",
"(",
"10",
")",
"]",
")",
"time_step",
"=",
"1",
"/",
"values_float",
"[",
"1",
"]",
"# Skip comments",
"lines",
"=",
"lines",
"[",
"count_comment",
":",
"]",
"accels",
"=",
"np",
".",
"array",
"(",
"parse_fixed_width",
"(",
"count",
"*",
"[",
"(",
"10",
",",
"float",
")",
",",
"]",
",",
"lines",
")",
")",
"return",
"TimeSeriesMotion",
"(",
"filename",
",",
"description",
",",
"time_step",
",",
"accels",
")"
] | Read an SMC formatted time series.
Format of the time series is provided by:
https://escweb.wr.usgs.gov/nsmp-data/smcfmt.html
Parameters
----------
filename: str
Filename to open. | [
"Read",
"an",
"SMC",
"formatted",
"time",
"series",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/motion.py#L232-L276 | train |
SUNCAT-Center/CatHub | cathub/classification.py | SiteClassification.get_info | def get_info(self):
"""Return surface reconstruction as well as primary and
secondary adsorption site labels"""
reconstructed = self.is_reconstructed()
site, site_type = self.get_site()
return reconstructed, site, site_type | python | def get_info(self):
"""Return surface reconstruction as well as primary and
secondary adsorption site labels"""
reconstructed = self.is_reconstructed()
site, site_type = self.get_site()
return reconstructed, site, site_type | [
"def",
"get_info",
"(",
"self",
")",
":",
"reconstructed",
"=",
"self",
".",
"is_reconstructed",
"(",
")",
"site",
",",
"site_type",
"=",
"self",
".",
"get_site",
"(",
")",
"return",
"reconstructed",
",",
"site",
",",
"site_type"
] | Return surface reconstruction as well as primary and
secondary adsorption site labels | [
"Return",
"surface",
"reconstruction",
"as",
"well",
"as",
"primary",
"and",
"secondary",
"adsorption",
"site",
"labels"
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/classification.py#L48-L56 | train |
SUNCAT-Center/CatHub | cathub/classification.py | SiteClassification.check_dissociated | def check_dissociated(self, cutoff=1.2):
"""Check if adsorbate dissociates"""
dissociated = False
if not len(self.B) > self.nslab + 1: # only one adsorbate
return dissociated
adsatoms = [atom for atom in self.B[self.nslab:]]
ads0, ads1 = set(atom.symbol for atom in adsatoms)
bond_dist = get_ads_dist(self.B, ads0, ads1)
Cradii = [cradii[atom.number]
for atom in [ase.Atom(ads0), ase.Atom(ads1)]]
bond_dist0 = sum(Cradii)
if bond_dist > cutoff * bond_dist0:
print('DISSOCIATED: {} Ang > 1.2 * {} Ang'
.format(bond_dist, bond_dist0))
dissociated = True
return dissociated | python | def check_dissociated(self, cutoff=1.2):
"""Check if adsorbate dissociates"""
dissociated = False
if not len(self.B) > self.nslab + 1: # only one adsorbate
return dissociated
adsatoms = [atom for atom in self.B[self.nslab:]]
ads0, ads1 = set(atom.symbol for atom in adsatoms)
bond_dist = get_ads_dist(self.B, ads0, ads1)
Cradii = [cradii[atom.number]
for atom in [ase.Atom(ads0), ase.Atom(ads1)]]
bond_dist0 = sum(Cradii)
if bond_dist > cutoff * bond_dist0:
print('DISSOCIATED: {} Ang > 1.2 * {} Ang'
.format(bond_dist, bond_dist0))
dissociated = True
return dissociated | [
"def",
"check_dissociated",
"(",
"self",
",",
"cutoff",
"=",
"1.2",
")",
":",
"dissociated",
"=",
"False",
"if",
"not",
"len",
"(",
"self",
".",
"B",
")",
">",
"self",
".",
"nslab",
"+",
"1",
":",
"# only one adsorbate",
"return",
"dissociated",
"adsatoms",
"=",
"[",
"atom",
"for",
"atom",
"in",
"self",
".",
"B",
"[",
"self",
".",
"nslab",
":",
"]",
"]",
"ads0",
",",
"ads1",
"=",
"set",
"(",
"atom",
".",
"symbol",
"for",
"atom",
"in",
"adsatoms",
")",
"bond_dist",
"=",
"get_ads_dist",
"(",
"self",
".",
"B",
",",
"ads0",
",",
"ads1",
")",
"Cradii",
"=",
"[",
"cradii",
"[",
"atom",
".",
"number",
"]",
"for",
"atom",
"in",
"[",
"ase",
".",
"Atom",
"(",
"ads0",
")",
",",
"ase",
".",
"Atom",
"(",
"ads1",
")",
"]",
"]",
"bond_dist0",
"=",
"sum",
"(",
"Cradii",
")",
"if",
"bond_dist",
">",
"cutoff",
"*",
"bond_dist0",
":",
"print",
"(",
"'DISSOCIATED: {} Ang > 1.2 * {} Ang'",
".",
"format",
"(",
"bond_dist",
",",
"bond_dist0",
")",
")",
"dissociated",
"=",
"True",
"return",
"dissociated"
] | Check if adsorbate dissociates | [
"Check",
"if",
"adsorbate",
"dissociates"
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/classification.py#L58-L77 | train |
SUNCAT-Center/CatHub | cathub/classification.py | SiteClassification.is_reconstructed | def is_reconstructed(self, xy_cutoff=0.3, z_cutoff=0.4):
"""Compare initial and final slab configuration
to determine if slab reconstructs during relaxation
xy_cutoff: Allowed xy-movement is determined from
the covalent radii as:
xy_cutoff * np.mean(cradii)
z_cutoff: Allowed z-movement is determined as
z_cutoff * cradii_i
"""
assert self.A, \
'Initial slab geometry needed to classify reconstruction'
# remove adsorbate
A = self.A[:-1].copy()
B = self.B[:-1].copy()
# Order wrt x-positions
x_indices = np.argsort(A.positions[:, 0])
A = A[x_indices]
B = B[x_indices]
a = A.positions
b = B.positions
allowed_z_movement = z_cutoff * cradii[A.get_atomic_numbers()]
allowed_xy_movement = \
xy_cutoff * np.mean(cradii[A.get_atomic_numbers()])
D, D_len = get_distances(p1=a, p2=b, cell=A.cell, pbc=True)
d_xy = np.linalg.norm(np.diagonal(D)[:2], axis=0)
d_z = np.diagonal(D)[2:][0]
cond1 = np.all(d_xy < allowed_xy_movement)
cond2 = np.all([d_z[i] < allowed_z_movement[i]
for i in range(len(a))])
if cond1 and cond2: # not reconstructed
return False
else:
return True | python | def is_reconstructed(self, xy_cutoff=0.3, z_cutoff=0.4):
"""Compare initial and final slab configuration
to determine if slab reconstructs during relaxation
xy_cutoff: Allowed xy-movement is determined from
the covalent radii as:
xy_cutoff * np.mean(cradii)
z_cutoff: Allowed z-movement is determined as
z_cutoff * cradii_i
"""
assert self.A, \
'Initial slab geometry needed to classify reconstruction'
# remove adsorbate
A = self.A[:-1].copy()
B = self.B[:-1].copy()
# Order wrt x-positions
x_indices = np.argsort(A.positions[:, 0])
A = A[x_indices]
B = B[x_indices]
a = A.positions
b = B.positions
allowed_z_movement = z_cutoff * cradii[A.get_atomic_numbers()]
allowed_xy_movement = \
xy_cutoff * np.mean(cradii[A.get_atomic_numbers()])
D, D_len = get_distances(p1=a, p2=b, cell=A.cell, pbc=True)
d_xy = np.linalg.norm(np.diagonal(D)[:2], axis=0)
d_z = np.diagonal(D)[2:][0]
cond1 = np.all(d_xy < allowed_xy_movement)
cond2 = np.all([d_z[i] < allowed_z_movement[i]
for i in range(len(a))])
if cond1 and cond2: # not reconstructed
return False
else:
return True | [
"def",
"is_reconstructed",
"(",
"self",
",",
"xy_cutoff",
"=",
"0.3",
",",
"z_cutoff",
"=",
"0.4",
")",
":",
"assert",
"self",
".",
"A",
",",
"'Initial slab geometry needed to classify reconstruction'",
"# remove adsorbate",
"A",
"=",
"self",
".",
"A",
"[",
":",
"-",
"1",
"]",
".",
"copy",
"(",
")",
"B",
"=",
"self",
".",
"B",
"[",
":",
"-",
"1",
"]",
".",
"copy",
"(",
")",
"# Order wrt x-positions",
"x_indices",
"=",
"np",
".",
"argsort",
"(",
"A",
".",
"positions",
"[",
":",
",",
"0",
"]",
")",
"A",
"=",
"A",
"[",
"x_indices",
"]",
"B",
"=",
"B",
"[",
"x_indices",
"]",
"a",
"=",
"A",
".",
"positions",
"b",
"=",
"B",
".",
"positions",
"allowed_z_movement",
"=",
"z_cutoff",
"*",
"cradii",
"[",
"A",
".",
"get_atomic_numbers",
"(",
")",
"]",
"allowed_xy_movement",
"=",
"xy_cutoff",
"*",
"np",
".",
"mean",
"(",
"cradii",
"[",
"A",
".",
"get_atomic_numbers",
"(",
")",
"]",
")",
"D",
",",
"D_len",
"=",
"get_distances",
"(",
"p1",
"=",
"a",
",",
"p2",
"=",
"b",
",",
"cell",
"=",
"A",
".",
"cell",
",",
"pbc",
"=",
"True",
")",
"d_xy",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"np",
".",
"diagonal",
"(",
"D",
")",
"[",
":",
"2",
"]",
",",
"axis",
"=",
"0",
")",
"d_z",
"=",
"np",
".",
"diagonal",
"(",
"D",
")",
"[",
"2",
":",
"]",
"[",
"0",
"]",
"cond1",
"=",
"np",
".",
"all",
"(",
"d_xy",
"<",
"allowed_xy_movement",
")",
"cond2",
"=",
"np",
".",
"all",
"(",
"[",
"d_z",
"[",
"i",
"]",
"<",
"allowed_z_movement",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
")",
"]",
")",
"if",
"cond1",
"and",
"cond2",
":",
"# not reconstructed",
"return",
"False",
"else",
":",
"return",
"True"
] | Compare initial and final slab configuration
to determine if slab reconstructs during relaxation
xy_cutoff: Allowed xy-movement is determined from
the covalent radii as:
xy_cutoff * np.mean(cradii)
z_cutoff: Allowed z-movement is determined as
z_cutoff * cradii_i | [
"Compare",
"initial",
"and",
"final",
"slab",
"configuration",
"to",
"determine",
"if",
"slab",
"reconstructs",
"during",
"relaxation"
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/classification.py#L105-L145 | train |
SUNCAT-Center/CatHub | cathub/classification.py | SiteClassification.get_under_bridge | def get_under_bridge(self):
"""Return element closest to the adsorbate in the subsurface layer"""
C0 = self.B[-1:] * (3, 3, 1)
ads_pos = C0.positions[4]
C = self.get_subsurface_layer() * (3, 3, 1)
dis = self.B.cell[0][0] * 2
ret = None
for ele in C:
new_dis = np.linalg.norm(ads_pos - ele.position)
if new_dis < dis:
dis = new_dis
ret = ele.symbol
return ret | python | def get_under_bridge(self):
"""Return element closest to the adsorbate in the subsurface layer"""
C0 = self.B[-1:] * (3, 3, 1)
ads_pos = C0.positions[4]
C = self.get_subsurface_layer() * (3, 3, 1)
dis = self.B.cell[0][0] * 2
ret = None
for ele in C:
new_dis = np.linalg.norm(ads_pos - ele.position)
if new_dis < dis:
dis = new_dis
ret = ele.symbol
return ret | [
"def",
"get_under_bridge",
"(",
"self",
")",
":",
"C0",
"=",
"self",
".",
"B",
"[",
"-",
"1",
":",
"]",
"*",
"(",
"3",
",",
"3",
",",
"1",
")",
"ads_pos",
"=",
"C0",
".",
"positions",
"[",
"4",
"]",
"C",
"=",
"self",
".",
"get_subsurface_layer",
"(",
")",
"*",
"(",
"3",
",",
"3",
",",
"1",
")",
"dis",
"=",
"self",
".",
"B",
".",
"cell",
"[",
"0",
"]",
"[",
"0",
"]",
"*",
"2",
"ret",
"=",
"None",
"for",
"ele",
"in",
"C",
":",
"new_dis",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"ads_pos",
"-",
"ele",
".",
"position",
")",
"if",
"new_dis",
"<",
"dis",
":",
"dis",
"=",
"new_dis",
"ret",
"=",
"ele",
".",
"symbol",
"return",
"ret"
] | Return element closest to the adsorbate in the subsurface layer | [
"Return",
"element",
"closest",
"to",
"the",
"adsorbate",
"in",
"the",
"subsurface",
"layer"
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/classification.py#L260-L276 | train |
SUNCAT-Center/CatHub | cathub/classification.py | SiteClassification.get_under_hollow | def get_under_hollow(self):
""" Return HCP if an atom is present below the adsorbate in the
subsurface layer and FCC if not"""
C0 = self.B[-1:] * (3, 3, 1)
ads_pos = C0.positions[4]
C = self.get_subsurface_layer() * (3, 3, 1)
ret = 'FCC'
if np.any([np.linalg.norm(ads_pos[:2] - ele.position[:2]) < 0.5 *
cradii[ele.number] for ele in C]):
ret = 'HCP'
return ret | python | def get_under_hollow(self):
""" Return HCP if an atom is present below the adsorbate in the
subsurface layer and FCC if not"""
C0 = self.B[-1:] * (3, 3, 1)
ads_pos = C0.positions[4]
C = self.get_subsurface_layer() * (3, 3, 1)
ret = 'FCC'
if np.any([np.linalg.norm(ads_pos[:2] - ele.position[:2]) < 0.5 *
cradii[ele.number] for ele in C]):
ret = 'HCP'
return ret | [
"def",
"get_under_hollow",
"(",
"self",
")",
":",
"C0",
"=",
"self",
".",
"B",
"[",
"-",
"1",
":",
"]",
"*",
"(",
"3",
",",
"3",
",",
"1",
")",
"ads_pos",
"=",
"C0",
".",
"positions",
"[",
"4",
"]",
"C",
"=",
"self",
".",
"get_subsurface_layer",
"(",
")",
"*",
"(",
"3",
",",
"3",
",",
"1",
")",
"ret",
"=",
"'FCC'",
"if",
"np",
".",
"any",
"(",
"[",
"np",
".",
"linalg",
".",
"norm",
"(",
"ads_pos",
"[",
":",
"2",
"]",
"-",
"ele",
".",
"position",
"[",
":",
"2",
"]",
")",
"<",
"0.5",
"*",
"cradii",
"[",
"ele",
".",
"number",
"]",
"for",
"ele",
"in",
"C",
"]",
")",
":",
"ret",
"=",
"'HCP'",
"return",
"ret"
] | Return HCP if an atom is present below the adsorbate in the
subsurface layer and FCC if not | [
"Return",
"HCP",
"if",
"an",
"atom",
"is",
"present",
"below",
"the",
"adsorbate",
"in",
"the",
"subsurface",
"layer",
"and",
"FCC",
"if",
"not"
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/classification.py#L278-L291 | train |
guaix-ucm/numina | numina/array/distortion.py | fmap | def fmap(order, aij, bij, x, y):
"""Evaluate the 2D polynomial transformation.
u = sum[i=0:order]( sum[j=0:j]( a_ij * x**(i - j) * y**j ))
v = sum[i=0:order]( sum[j=0:j]( b_ij * x**(i - j) * y**j ))
Parameters
----------
order : int
Order of the polynomial transformation.
aij : numpy array
Polynomial coefficents corresponding to a_ij.
bij : numpy array
Polynomial coefficents corresponding to b_ij.
x : numpy array or float
X coordinate values where the transformation is computed. Note
that these values correspond to array indices.
y : numpy array or float
Y coordinate values where the transformation is computed. Note
that these values correspond to array indices.
Returns
-------
u : numpy array or float
U coordinate values.
v : numpy array or float
V coordinate values.
"""
u = np.zeros_like(x)
v = np.zeros_like(y)
k = 0
for i in range(order + 1):
for j in range(i + 1):
u += aij[k] * (x ** (i - j)) * (y ** j)
v += bij[k] * (x ** (i - j)) * (y ** j)
k += 1
return u, v | python | def fmap(order, aij, bij, x, y):
"""Evaluate the 2D polynomial transformation.
u = sum[i=0:order]( sum[j=0:j]( a_ij * x**(i - j) * y**j ))
v = sum[i=0:order]( sum[j=0:j]( b_ij * x**(i - j) * y**j ))
Parameters
----------
order : int
Order of the polynomial transformation.
aij : numpy array
Polynomial coefficents corresponding to a_ij.
bij : numpy array
Polynomial coefficents corresponding to b_ij.
x : numpy array or float
X coordinate values where the transformation is computed. Note
that these values correspond to array indices.
y : numpy array or float
Y coordinate values where the transformation is computed. Note
that these values correspond to array indices.
Returns
-------
u : numpy array or float
U coordinate values.
v : numpy array or float
V coordinate values.
"""
u = np.zeros_like(x)
v = np.zeros_like(y)
k = 0
for i in range(order + 1):
for j in range(i + 1):
u += aij[k] * (x ** (i - j)) * (y ** j)
v += bij[k] * (x ** (i - j)) * (y ** j)
k += 1
return u, v | [
"def",
"fmap",
"(",
"order",
",",
"aij",
",",
"bij",
",",
"x",
",",
"y",
")",
":",
"u",
"=",
"np",
".",
"zeros_like",
"(",
"x",
")",
"v",
"=",
"np",
".",
"zeros_like",
"(",
"y",
")",
"k",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"order",
"+",
"1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
")",
":",
"u",
"+=",
"aij",
"[",
"k",
"]",
"*",
"(",
"x",
"**",
"(",
"i",
"-",
"j",
")",
")",
"*",
"(",
"y",
"**",
"j",
")",
"v",
"+=",
"bij",
"[",
"k",
"]",
"*",
"(",
"x",
"**",
"(",
"i",
"-",
"j",
")",
")",
"*",
"(",
"y",
"**",
"j",
")",
"k",
"+=",
"1",
"return",
"u",
",",
"v"
] | Evaluate the 2D polynomial transformation.
u = sum[i=0:order]( sum[j=0:j]( a_ij * x**(i - j) * y**j ))
v = sum[i=0:order]( sum[j=0:j]( b_ij * x**(i - j) * y**j ))
Parameters
----------
order : int
Order of the polynomial transformation.
aij : numpy array
Polynomial coefficents corresponding to a_ij.
bij : numpy array
Polynomial coefficents corresponding to b_ij.
x : numpy array or float
X coordinate values where the transformation is computed. Note
that these values correspond to array indices.
y : numpy array or float
Y coordinate values where the transformation is computed. Note
that these values correspond to array indices.
Returns
-------
u : numpy array or float
U coordinate values.
v : numpy array or float
V coordinate values. | [
"Evaluate",
"the",
"2D",
"polynomial",
"transformation",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/distortion.py#L184-L224 | train |
guaix-ucm/numina | numina/array/distortion.py | ncoef_fmap | def ncoef_fmap(order):
"""Expected number of coefficients in a 2D transformation of a given order.
Parameters
----------
order : int
Order of the 2D polynomial transformation.
Returns
-------
ncoef : int
Expected number of coefficients.
"""
ncoef = 0
for i in range(order + 1):
for j in range(i + 1):
ncoef += 1
return ncoef | python | def ncoef_fmap(order):
"""Expected number of coefficients in a 2D transformation of a given order.
Parameters
----------
order : int
Order of the 2D polynomial transformation.
Returns
-------
ncoef : int
Expected number of coefficients.
"""
ncoef = 0
for i in range(order + 1):
for j in range(i + 1):
ncoef += 1
return ncoef | [
"def",
"ncoef_fmap",
"(",
"order",
")",
":",
"ncoef",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"order",
"+",
"1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
")",
":",
"ncoef",
"+=",
"1",
"return",
"ncoef"
] | Expected number of coefficients in a 2D transformation of a given order.
Parameters
----------
order : int
Order of the 2D polynomial transformation.
Returns
-------
ncoef : int
Expected number of coefficients. | [
"Expected",
"number",
"of",
"coefficients",
"in",
"a",
"2D",
"transformation",
"of",
"a",
"given",
"order",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/distortion.py#L227-L246 | train |
guaix-ucm/numina | numina/array/distortion.py | order_fmap | def order_fmap(ncoef):
"""Compute order corresponding to a given number of coefficients.
Parameters
----------
ncoef : int
Number of coefficients.
Returns
-------
order : int
Order corresponding to the provided number of coefficients.
"""
loop = True
order = 1
while loop:
loop = not (ncoef == ncoef_fmap(order))
if loop:
order += 1
if order > NMAX_ORDER:
print('No. of coefficients: ', ncoef)
raise ValueError("order > " + str(NMAX_ORDER) +
" not implemented")
return order | python | def order_fmap(ncoef):
"""Compute order corresponding to a given number of coefficients.
Parameters
----------
ncoef : int
Number of coefficients.
Returns
-------
order : int
Order corresponding to the provided number of coefficients.
"""
loop = True
order = 1
while loop:
loop = not (ncoef == ncoef_fmap(order))
if loop:
order += 1
if order > NMAX_ORDER:
print('No. of coefficients: ', ncoef)
raise ValueError("order > " + str(NMAX_ORDER) +
" not implemented")
return order | [
"def",
"order_fmap",
"(",
"ncoef",
")",
":",
"loop",
"=",
"True",
"order",
"=",
"1",
"while",
"loop",
":",
"loop",
"=",
"not",
"(",
"ncoef",
"==",
"ncoef_fmap",
"(",
"order",
")",
")",
"if",
"loop",
":",
"order",
"+=",
"1",
"if",
"order",
">",
"NMAX_ORDER",
":",
"print",
"(",
"'No. of coefficients: '",
",",
"ncoef",
")",
"raise",
"ValueError",
"(",
"\"order > \"",
"+",
"str",
"(",
"NMAX_ORDER",
")",
"+",
"\" not implemented\"",
")",
"return",
"order"
] | Compute order corresponding to a given number of coefficients.
Parameters
----------
ncoef : int
Number of coefficients.
Returns
-------
order : int
Order corresponding to the provided number of coefficients. | [
"Compute",
"order",
"corresponding",
"to",
"a",
"given",
"number",
"of",
"coefficients",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/distortion.py#L249-L274 | train |
kyzima-spb/flask-pony | flask_pony/views.py | BaseView.get_template_name | def get_template_name(self):
"""
Returns the name of the template.
If the template_name property is not set, the value will be generated automatically based on the class name.
Example:
>>> class MyEntityAction(BaseView): pass
>>> view = MyEntityAction()
>>> view.get_template_name()
"my_entity/action.html"
"""
if self.template_name is None:
name = camelcase2list(self.__class__.__name__)
name = '{}/{}.html'.format(name.pop(0), '_'.join(name))
self.template_name = name.lower()
return self.template_name | python | def get_template_name(self):
"""
Returns the name of the template.
If the template_name property is not set, the value will be generated automatically based on the class name.
Example:
>>> class MyEntityAction(BaseView): pass
>>> view = MyEntityAction()
>>> view.get_template_name()
"my_entity/action.html"
"""
if self.template_name is None:
name = camelcase2list(self.__class__.__name__)
name = '{}/{}.html'.format(name.pop(0), '_'.join(name))
self.template_name = name.lower()
return self.template_name | [
"def",
"get_template_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"template_name",
"is",
"None",
":",
"name",
"=",
"camelcase2list",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
"name",
"=",
"'{}/{}.html'",
".",
"format",
"(",
"name",
".",
"pop",
"(",
"0",
")",
",",
"'_'",
".",
"join",
"(",
"name",
")",
")",
"self",
".",
"template_name",
"=",
"name",
".",
"lower",
"(",
")",
"return",
"self",
".",
"template_name"
] | Returns the name of the template.
If the template_name property is not set, the value will be generated automatically based on the class name.
Example:
>>> class MyEntityAction(BaseView): pass
>>> view = MyEntityAction()
>>> view.get_template_name()
"my_entity/action.html" | [
"Returns",
"the",
"name",
"of",
"the",
"template",
"."
] | 6cf28d70b7ebf415d58fa138fcc70b8dd57432c7 | https://github.com/kyzima-spb/flask-pony/blob/6cf28d70b7ebf415d58fa138fcc70b8dd57432c7/flask_pony/views.py#L131-L148 | train |
pylp/pylp | pylp/lib/stream.py | Stream.append_file | def append_file(self, file):
"""Append a new file in the stream."""
self.files.append(file)
if self.transformer:
future = asyncio.ensure_future(self.transformer.transform(file))
future.add_done_callback(self.handle_transform) | python | def append_file(self, file):
"""Append a new file in the stream."""
self.files.append(file)
if self.transformer:
future = asyncio.ensure_future(self.transformer.transform(file))
future.add_done_callback(self.handle_transform) | [
"def",
"append_file",
"(",
"self",
",",
"file",
")",
":",
"self",
".",
"files",
".",
"append",
"(",
"file",
")",
"if",
"self",
".",
"transformer",
":",
"future",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"transformer",
".",
"transform",
"(",
"file",
")",
")",
"future",
".",
"add_done_callback",
"(",
"self",
".",
"handle_transform",
")"
] | Append a new file in the stream. | [
"Append",
"a",
"new",
"file",
"in",
"the",
"stream",
"."
] | 7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4 | https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/stream.py#L33-L39 | train |
pylp/pylp | pylp/lib/stream.py | Stream.flush_if_ended | def flush_if_ended(self):
"""Call 'flush' function if all files have been transformed."""
if self.ended and self.next and len(self.files) == self.transformed:
future = asyncio.ensure_future(self.transformer.flush())
future.add_done_callback(lambda x: self.next.end_of_stream()) | python | def flush_if_ended(self):
"""Call 'flush' function if all files have been transformed."""
if self.ended and self.next and len(self.files) == self.transformed:
future = asyncio.ensure_future(self.transformer.flush())
future.add_done_callback(lambda x: self.next.end_of_stream()) | [
"def",
"flush_if_ended",
"(",
"self",
")",
":",
"if",
"self",
".",
"ended",
"and",
"self",
".",
"next",
"and",
"len",
"(",
"self",
".",
"files",
")",
"==",
"self",
".",
"transformed",
":",
"future",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"transformer",
".",
"flush",
"(",
")",
")",
"future",
".",
"add_done_callback",
"(",
"lambda",
"x",
":",
"self",
".",
"next",
".",
"end_of_stream",
"(",
")",
")"
] | Call 'flush' function if all files have been transformed. | [
"Call",
"flush",
"function",
"if",
"all",
"files",
"have",
"been",
"transformed",
"."
] | 7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4 | https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/stream.py#L42-L46 | train |
pylp/pylp | pylp/lib/stream.py | Stream.handle_transform | def handle_transform(self, task):
"""Handle a 'transform' callback."""
self.transformed += 1
file = task.result()
if file:
self.next.append_file(file)
self.flush_if_ended() | python | def handle_transform(self, task):
"""Handle a 'transform' callback."""
self.transformed += 1
file = task.result()
if file:
self.next.append_file(file)
self.flush_if_ended() | [
"def",
"handle_transform",
"(",
"self",
",",
"task",
")",
":",
"self",
".",
"transformed",
"+=",
"1",
"file",
"=",
"task",
".",
"result",
"(",
")",
"if",
"file",
":",
"self",
".",
"next",
".",
"append_file",
"(",
"file",
")",
"self",
".",
"flush_if_ended",
"(",
")"
] | Handle a 'transform' callback. | [
"Handle",
"a",
"transform",
"callback",
"."
] | 7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4 | https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/stream.py#L49-L57 | train |
pylp/pylp | pylp/lib/stream.py | Stream.pipe | def pipe(self, transformer):
"""Pipe this stream to another."""
if self.next:
return
stream = Stream()
self.next = stream
stream.prev = self
self.transformer = transformer
transformer.stream = self
transformer.piped()
for file in self.files:
future = asyncio.ensure_future(self.transformer.transform(file))
future.add_done_callback(self.handle_transform)
self.onpiped.set_result(None)
self.flush_if_ended()
return stream | python | def pipe(self, transformer):
"""Pipe this stream to another."""
if self.next:
return
stream = Stream()
self.next = stream
stream.prev = self
self.transformer = transformer
transformer.stream = self
transformer.piped()
for file in self.files:
future = asyncio.ensure_future(self.transformer.transform(file))
future.add_done_callback(self.handle_transform)
self.onpiped.set_result(None)
self.flush_if_ended()
return stream | [
"def",
"pipe",
"(",
"self",
",",
"transformer",
")",
":",
"if",
"self",
".",
"next",
":",
"return",
"stream",
"=",
"Stream",
"(",
")",
"self",
".",
"next",
"=",
"stream",
"stream",
".",
"prev",
"=",
"self",
"self",
".",
"transformer",
"=",
"transformer",
"transformer",
".",
"stream",
"=",
"self",
"transformer",
".",
"piped",
"(",
")",
"for",
"file",
"in",
"self",
".",
"files",
":",
"future",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"transformer",
".",
"transform",
"(",
"file",
")",
")",
"future",
".",
"add_done_callback",
"(",
"self",
".",
"handle_transform",
")",
"self",
".",
"onpiped",
".",
"set_result",
"(",
"None",
")",
"self",
".",
"flush_if_ended",
"(",
")",
"return",
"stream"
] | Pipe this stream to another. | [
"Pipe",
"this",
"stream",
"to",
"another",
"."
] | 7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4 | https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/stream.py#L66-L86 | train |
pylp/pylp | pylp/utils/pipes.py | pipes | def pipes(stream, *transformers):
"""Pipe several transformers end to end."""
for transformer in transformers:
stream = stream.pipe(transformer)
return stream | python | def pipes(stream, *transformers):
"""Pipe several transformers end to end."""
for transformer in transformers:
stream = stream.pipe(transformer)
return stream | [
"def",
"pipes",
"(",
"stream",
",",
"*",
"transformers",
")",
":",
"for",
"transformer",
"in",
"transformers",
":",
"stream",
"=",
"stream",
".",
"pipe",
"(",
"transformer",
")",
"return",
"stream"
] | Pipe several transformers end to end. | [
"Pipe",
"several",
"transformers",
"end",
"to",
"end",
"."
] | 7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4 | https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/utils/pipes.py#L11-L15 | train |
guaix-ucm/numina | numina/core/dataholders.py | Parameter.convert | def convert(self, val):
"""Convert input values to type values."""
pre = super(Parameter, self).convert(val)
if self.custom_validator is not None:
post = self.custom_validator(pre)
else:
post = pre
return post | python | def convert(self, val):
"""Convert input values to type values."""
pre = super(Parameter, self).convert(val)
if self.custom_validator is not None:
post = self.custom_validator(pre)
else:
post = pre
return post | [
"def",
"convert",
"(",
"self",
",",
"val",
")",
":",
"pre",
"=",
"super",
"(",
"Parameter",
",",
"self",
")",
".",
"convert",
"(",
"val",
")",
"if",
"self",
".",
"custom_validator",
"is",
"not",
"None",
":",
"post",
"=",
"self",
".",
"custom_validator",
"(",
"pre",
")",
"else",
":",
"post",
"=",
"pre",
"return",
"post"
] | Convert input values to type values. | [
"Convert",
"input",
"values",
"to",
"type",
"values",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/dataholders.py#L342-L350 | train |
guaix-ucm/numina | numina/core/dataholders.py | Parameter.validate | def validate(self, val):
"""Validate values according to the requirement"""
if self.validation:
self.type.validate(val)
if self.custom_validator is not None:
self.custom_validator(val)
return True | python | def validate(self, val):
"""Validate values according to the requirement"""
if self.validation:
self.type.validate(val)
if self.custom_validator is not None:
self.custom_validator(val)
return True | [
"def",
"validate",
"(",
"self",
",",
"val",
")",
":",
"if",
"self",
".",
"validation",
":",
"self",
".",
"type",
".",
"validate",
"(",
"val",
")",
"if",
"self",
".",
"custom_validator",
"is",
"not",
"None",
":",
"self",
".",
"custom_validator",
"(",
"val",
")",
"return",
"True"
] | Validate values according to the requirement | [
"Validate",
"values",
"according",
"to",
"the",
"requirement"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/dataholders.py#L352-L360 | train |
kyzima-spb/flask-pony | flask_pony/decorators.py | route | def route(obj, rule, *args, **kwargs):
"""Decorator for the View classes."""
def decorator(cls):
endpoint = kwargs.get('endpoint', camel_to_snake(cls.__name__))
kwargs['view_func'] = cls.as_view(endpoint)
obj.add_url_rule(rule, *args, **kwargs)
return cls
return decorator | python | def route(obj, rule, *args, **kwargs):
"""Decorator for the View classes."""
def decorator(cls):
endpoint = kwargs.get('endpoint', camel_to_snake(cls.__name__))
kwargs['view_func'] = cls.as_view(endpoint)
obj.add_url_rule(rule, *args, **kwargs)
return cls
return decorator | [
"def",
"route",
"(",
"obj",
",",
"rule",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"endpoint",
"=",
"kwargs",
".",
"get",
"(",
"'endpoint'",
",",
"camel_to_snake",
"(",
"cls",
".",
"__name__",
")",
")",
"kwargs",
"[",
"'view_func'",
"]",
"=",
"cls",
".",
"as_view",
"(",
"endpoint",
")",
"obj",
".",
"add_url_rule",
"(",
"rule",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"cls",
"return",
"decorator"
] | Decorator for the View classes. | [
"Decorator",
"for",
"the",
"View",
"classes",
"."
] | 6cf28d70b7ebf415d58fa138fcc70b8dd57432c7 | https://github.com/kyzima-spb/flask-pony/blob/6cf28d70b7ebf415d58fa138fcc70b8dd57432c7/flask_pony/decorators.py#L20-L27 | train |
arkottke/pysra | pysra/propagation.py | QuarterWaveLenCalculator.fit | def fit(self,
target_type,
target,
adjust_thickness=False,
adjust_site_atten=False,
adjust_source_vel=False):
"""
Fit to a target crustal amplification or site term.
The fitting process adjusts the velocity, site attenuation, and layer
thickness (if enabled) to fit a target values. The frequency range is
specified by the input motion.
Parameters
----------
target_type: str
Options are 'crustal_amp' to only fit to the crustal amplification,
or 'site_term' to fit both the velocity and the site attenuation
parameter.
target: `array_like`
Target values.
adjust_thickness: bool (optional)
If the thickness of the layers is adjusted as well, default: False.
adjust_site_atten: bool (optional)
If the site attenuation is adjusted as well, default: False.
adjust_source_vel: bool (optional)
If the source velocity should be adjusted, default: False.
Returns
-------
profile: `pyrsa.site.Profile`
profile optimized to fit a target amplification.
"""
density = self.profile.density
nl = len(density)
# Slowness bounds
slowness = self.profile.slowness
thickness = self.profile.thickness
site_atten = self._site_atten
# Slowness
initial = slowness
bounds = 1 / np.tile((4000, 100), (nl, 1))
if not adjust_source_vel:
bounds[-1] = (initial[-1], initial[-1])
# Thickness bounds
if adjust_thickness:
bounds = np.r_[bounds, [[t / 2, 2 * t] for t in thickness]]
initial = np.r_[initial, thickness]
# Site attenuation bounds
if adjust_site_atten:
bounds = np.r_[bounds, [[0.0001, 0.200]]]
initial = np.r_[initial, self.site_atten]
def calc_rmse(this, that):
return np.mean(((this - that) / that) ** 2)
def err(x):
_slowness = x[0:nl]
if adjust_thickness:
_thickness = x[nl:(2 * nl)]
else:
_thickness = thickness
if adjust_site_atten:
self._site_atten = x[-1]
crustal_amp, site_term = self._calc_amp(density, _thickness,
_slowness)
calc = crustal_amp if target_type == 'crustal_amp' else site_term
err = 10 * calc_rmse(target, calc)
# Prefer the original values so add the difference to the error
err += calc_rmse(slowness, _slowness)
if adjust_thickness:
err += calc_rmse(thickness, _thickness)
if adjust_site_atten:
err += calc_rmse(self._site_atten, site_atten)
return err
res = minimize(err, initial, method='L-BFGS-B', bounds=bounds)
slowness = res.x[0:nl]
if adjust_thickness:
thickness = res.x[nl:(2 * nl)]
profile = Profile([
Layer(l.soil_type, t, 1 / s)
for l, t, s in zip(self.profile, thickness, slowness)
], self.profile.wt_depth)
# Update the calculated amplificaiton
return (self.motion, profile, self.loc_input) | python | def fit(self,
target_type,
target,
adjust_thickness=False,
adjust_site_atten=False,
adjust_source_vel=False):
"""
Fit to a target crustal amplification or site term.
The fitting process adjusts the velocity, site attenuation, and layer
thickness (if enabled) to fit a target values. The frequency range is
specified by the input motion.
Parameters
----------
target_type: str
Options are 'crustal_amp' to only fit to the crustal amplification,
or 'site_term' to fit both the velocity and the site attenuation
parameter.
target: `array_like`
Target values.
adjust_thickness: bool (optional)
If the thickness of the layers is adjusted as well, default: False.
adjust_site_atten: bool (optional)
If the site attenuation is adjusted as well, default: False.
adjust_source_vel: bool (optional)
If the source velocity should be adjusted, default: False.
Returns
-------
profile: `pyrsa.site.Profile`
profile optimized to fit a target amplification.
"""
density = self.profile.density
nl = len(density)
# Slowness bounds
slowness = self.profile.slowness
thickness = self.profile.thickness
site_atten = self._site_atten
# Slowness
initial = slowness
bounds = 1 / np.tile((4000, 100), (nl, 1))
if not adjust_source_vel:
bounds[-1] = (initial[-1], initial[-1])
# Thickness bounds
if adjust_thickness:
bounds = np.r_[bounds, [[t / 2, 2 * t] for t in thickness]]
initial = np.r_[initial, thickness]
# Site attenuation bounds
if adjust_site_atten:
bounds = np.r_[bounds, [[0.0001, 0.200]]]
initial = np.r_[initial, self.site_atten]
def calc_rmse(this, that):
return np.mean(((this - that) / that) ** 2)
def err(x):
_slowness = x[0:nl]
if adjust_thickness:
_thickness = x[nl:(2 * nl)]
else:
_thickness = thickness
if adjust_site_atten:
self._site_atten = x[-1]
crustal_amp, site_term = self._calc_amp(density, _thickness,
_slowness)
calc = crustal_amp if target_type == 'crustal_amp' else site_term
err = 10 * calc_rmse(target, calc)
# Prefer the original values so add the difference to the error
err += calc_rmse(slowness, _slowness)
if adjust_thickness:
err += calc_rmse(thickness, _thickness)
if adjust_site_atten:
err += calc_rmse(self._site_atten, site_atten)
return err
res = minimize(err, initial, method='L-BFGS-B', bounds=bounds)
slowness = res.x[0:nl]
if adjust_thickness:
thickness = res.x[nl:(2 * nl)]
profile = Profile([
Layer(l.soil_type, t, 1 / s)
for l, t, s in zip(self.profile, thickness, slowness)
], self.profile.wt_depth)
# Update the calculated amplificaiton
return (self.motion, profile, self.loc_input) | [
"def",
"fit",
"(",
"self",
",",
"target_type",
",",
"target",
",",
"adjust_thickness",
"=",
"False",
",",
"adjust_site_atten",
"=",
"False",
",",
"adjust_source_vel",
"=",
"False",
")",
":",
"density",
"=",
"self",
".",
"profile",
".",
"density",
"nl",
"=",
"len",
"(",
"density",
")",
"# Slowness bounds",
"slowness",
"=",
"self",
".",
"profile",
".",
"slowness",
"thickness",
"=",
"self",
".",
"profile",
".",
"thickness",
"site_atten",
"=",
"self",
".",
"_site_atten",
"# Slowness",
"initial",
"=",
"slowness",
"bounds",
"=",
"1",
"/",
"np",
".",
"tile",
"(",
"(",
"4000",
",",
"100",
")",
",",
"(",
"nl",
",",
"1",
")",
")",
"if",
"not",
"adjust_source_vel",
":",
"bounds",
"[",
"-",
"1",
"]",
"=",
"(",
"initial",
"[",
"-",
"1",
"]",
",",
"initial",
"[",
"-",
"1",
"]",
")",
"# Thickness bounds",
"if",
"adjust_thickness",
":",
"bounds",
"=",
"np",
".",
"r_",
"[",
"bounds",
",",
"[",
"[",
"t",
"/",
"2",
",",
"2",
"*",
"t",
"]",
"for",
"t",
"in",
"thickness",
"]",
"]",
"initial",
"=",
"np",
".",
"r_",
"[",
"initial",
",",
"thickness",
"]",
"# Site attenuation bounds",
"if",
"adjust_site_atten",
":",
"bounds",
"=",
"np",
".",
"r_",
"[",
"bounds",
",",
"[",
"[",
"0.0001",
",",
"0.200",
"]",
"]",
"]",
"initial",
"=",
"np",
".",
"r_",
"[",
"initial",
",",
"self",
".",
"site_atten",
"]",
"def",
"calc_rmse",
"(",
"this",
",",
"that",
")",
":",
"return",
"np",
".",
"mean",
"(",
"(",
"(",
"this",
"-",
"that",
")",
"/",
"that",
")",
"**",
"2",
")",
"def",
"err",
"(",
"x",
")",
":",
"_slowness",
"=",
"x",
"[",
"0",
":",
"nl",
"]",
"if",
"adjust_thickness",
":",
"_thickness",
"=",
"x",
"[",
"nl",
":",
"(",
"2",
"*",
"nl",
")",
"]",
"else",
":",
"_thickness",
"=",
"thickness",
"if",
"adjust_site_atten",
":",
"self",
".",
"_site_atten",
"=",
"x",
"[",
"-",
"1",
"]",
"crustal_amp",
",",
"site_term",
"=",
"self",
".",
"_calc_amp",
"(",
"density",
",",
"_thickness",
",",
"_slowness",
")",
"calc",
"=",
"crustal_amp",
"if",
"target_type",
"==",
"'crustal_amp'",
"else",
"site_term",
"err",
"=",
"10",
"*",
"calc_rmse",
"(",
"target",
",",
"calc",
")",
"# Prefer the original values so add the difference to the error",
"err",
"+=",
"calc_rmse",
"(",
"slowness",
",",
"_slowness",
")",
"if",
"adjust_thickness",
":",
"err",
"+=",
"calc_rmse",
"(",
"thickness",
",",
"_thickness",
")",
"if",
"adjust_site_atten",
":",
"err",
"+=",
"calc_rmse",
"(",
"self",
".",
"_site_atten",
",",
"site_atten",
")",
"return",
"err",
"res",
"=",
"minimize",
"(",
"err",
",",
"initial",
",",
"method",
"=",
"'L-BFGS-B'",
",",
"bounds",
"=",
"bounds",
")",
"slowness",
"=",
"res",
".",
"x",
"[",
"0",
":",
"nl",
"]",
"if",
"adjust_thickness",
":",
"thickness",
"=",
"res",
".",
"x",
"[",
"nl",
":",
"(",
"2",
"*",
"nl",
")",
"]",
"profile",
"=",
"Profile",
"(",
"[",
"Layer",
"(",
"l",
".",
"soil_type",
",",
"t",
",",
"1",
"/",
"s",
")",
"for",
"l",
",",
"t",
",",
"s",
"in",
"zip",
"(",
"self",
".",
"profile",
",",
"thickness",
",",
"slowness",
")",
"]",
",",
"self",
".",
"profile",
".",
"wt_depth",
")",
"# Update the calculated amplificaiton",
"return",
"(",
"self",
".",
"motion",
",",
"profile",
",",
"self",
".",
"loc_input",
")"
] | Fit to a target crustal amplification or site term.
The fitting process adjusts the velocity, site attenuation, and layer
thickness (if enabled) to fit a target values. The frequency range is
specified by the input motion.
Parameters
----------
target_type: str
Options are 'crustal_amp' to only fit to the crustal amplification,
or 'site_term' to fit both the velocity and the site attenuation
parameter.
target: `array_like`
Target values.
adjust_thickness: bool (optional)
If the thickness of the layers is adjusted as well, default: False.
adjust_site_atten: bool (optional)
If the site attenuation is adjusted as well, default: False.
adjust_source_vel: bool (optional)
If the source velocity should be adjusted, default: False.
Returns
-------
profile: `pyrsa.site.Profile`
profile optimized to fit a target amplification. | [
"Fit",
"to",
"a",
"target",
"crustal",
"amplification",
"or",
"site",
"term",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/propagation.py#L153-L247 | train |
arkottke/pysra | pysra/propagation.py | LinearElasticCalculator.wave_at_location | def wave_at_location(self, l):
"""Compute the wave field at specific location.
Parameters
----------
l : site.Location
:class:`site.Location` of the input
Returns
-------
`np.ndarray`
Amplitude and phase of waves
"""
cterm = 1j * self._wave_nums[l.index] * l.depth_within
if l.wave_field == WaveField.within:
return (self._waves_a[l.index] * np.exp(cterm) +
self._waves_b[l.index] * np.exp(-cterm))
elif l.wave_field == WaveField.outcrop:
return 2 * self._waves_a[l.index] * np.exp(cterm)
elif l.wave_field == WaveField.incoming_only:
return self._waves_a[l.index] * np.exp(cterm)
else:
raise NotImplementedError | python | def wave_at_location(self, l):
"""Compute the wave field at specific location.
Parameters
----------
l : site.Location
:class:`site.Location` of the input
Returns
-------
`np.ndarray`
Amplitude and phase of waves
"""
cterm = 1j * self._wave_nums[l.index] * l.depth_within
if l.wave_field == WaveField.within:
return (self._waves_a[l.index] * np.exp(cterm) +
self._waves_b[l.index] * np.exp(-cterm))
elif l.wave_field == WaveField.outcrop:
return 2 * self._waves_a[l.index] * np.exp(cterm)
elif l.wave_field == WaveField.incoming_only:
return self._waves_a[l.index] * np.exp(cterm)
else:
raise NotImplementedError | [
"def",
"wave_at_location",
"(",
"self",
",",
"l",
")",
":",
"cterm",
"=",
"1j",
"*",
"self",
".",
"_wave_nums",
"[",
"l",
".",
"index",
"]",
"*",
"l",
".",
"depth_within",
"if",
"l",
".",
"wave_field",
"==",
"WaveField",
".",
"within",
":",
"return",
"(",
"self",
".",
"_waves_a",
"[",
"l",
".",
"index",
"]",
"*",
"np",
".",
"exp",
"(",
"cterm",
")",
"+",
"self",
".",
"_waves_b",
"[",
"l",
".",
"index",
"]",
"*",
"np",
".",
"exp",
"(",
"-",
"cterm",
")",
")",
"elif",
"l",
".",
"wave_field",
"==",
"WaveField",
".",
"outcrop",
":",
"return",
"2",
"*",
"self",
".",
"_waves_a",
"[",
"l",
".",
"index",
"]",
"*",
"np",
".",
"exp",
"(",
"cterm",
")",
"elif",
"l",
".",
"wave_field",
"==",
"WaveField",
".",
"incoming_only",
":",
"return",
"self",
".",
"_waves_a",
"[",
"l",
".",
"index",
"]",
"*",
"np",
".",
"exp",
"(",
"cterm",
")",
"else",
":",
"raise",
"NotImplementedError"
] | Compute the wave field at specific location.
Parameters
----------
l : site.Location
:class:`site.Location` of the input
Returns
-------
`np.ndarray`
Amplitude and phase of waves | [
"Compute",
"the",
"wave",
"field",
"at",
"specific",
"location",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/propagation.py#L340-L363 | train |
arkottke/pysra | pysra/propagation.py | LinearElasticCalculator.calc_accel_tf | def calc_accel_tf(self, lin, lout):
"""Compute the acceleration transfer function.
Parameters
----------
lin : :class:`~site.Location`
Location of input
lout : :class:`~site.Location`
Location of output. Note that this would typically be midheight
of the layer.
"""
tf = self.wave_at_location(lout) / self.wave_at_location(lin)
return tf | python | def calc_accel_tf(self, lin, lout):
"""Compute the acceleration transfer function.
Parameters
----------
lin : :class:`~site.Location`
Location of input
lout : :class:`~site.Location`
Location of output. Note that this would typically be midheight
of the layer.
"""
tf = self.wave_at_location(lout) / self.wave_at_location(lin)
return tf | [
"def",
"calc_accel_tf",
"(",
"self",
",",
"lin",
",",
"lout",
")",
":",
"tf",
"=",
"self",
".",
"wave_at_location",
"(",
"lout",
")",
"/",
"self",
".",
"wave_at_location",
"(",
"lin",
")",
"return",
"tf"
] | Compute the acceleration transfer function.
Parameters
----------
lin : :class:`~site.Location`
Location of input
lout : :class:`~site.Location`
Location of output. Note that this would typically be midheight
of the layer. | [
"Compute",
"the",
"acceleration",
"transfer",
"function",
"."
] | c72fd389d6c15203c0c00728ac00f101bae6369d | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/propagation.py#L365-L378 | train |
Subsets and Splits