id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
26,000 | datastore/datastore | datastore/core/query.py | Filter.filter | def filter(cls, filters, iterable):
'''Returns the elements in `iterable` that pass given `filters`'''
if isinstance(filters, Filter):
filters = [filters]
for filter in filters:
iterable = filter.generator(iterable)
return iterable | python | def filter(cls, filters, iterable):
'''Returns the elements in `iterable` that pass given `filters`'''
if isinstance(filters, Filter):
filters = [filters]
for filter in filters:
iterable = filter.generator(iterable)
return iterable | [
"def",
"filter",
"(",
"cls",
",",
"filters",
",",
"iterable",
")",
":",
"if",
"isinstance",
"(",
"filters",
",",
"Filter",
")",
":",
"filters",
"=",
"[",
"filters",
"]",
"for",
"filter",
"in",
"filters",
":",
"iterable",
"=",
"filter",
".",
"generator"... | Returns the elements in `iterable` that pass given `filters` | [
"Returns",
"the",
"elements",
"in",
"iterable",
"that",
"pass",
"given",
"filters"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L182-L190 |
26,001 | datastore/datastore | datastore/core/query.py | Order.multipleOrderComparison | def multipleOrderComparison(cls, orders):
'''Returns a function that will compare two items according to `orders`'''
comparers = [ (o.keyfn, 1 if o.isAscending() else -1) for o in orders]
def cmpfn(a, b):
for keyfn, ascOrDesc in comparers:
comparison = cmp(keyfn(a), keyfn(b)) * ascOrDesc
if comparison is not 0:
return comparison
return 0
return cmpfn | python | def multipleOrderComparison(cls, orders):
'''Returns a function that will compare two items according to `orders`'''
comparers = [ (o.keyfn, 1 if o.isAscending() else -1) for o in orders]
def cmpfn(a, b):
for keyfn, ascOrDesc in comparers:
comparison = cmp(keyfn(a), keyfn(b)) * ascOrDesc
if comparison is not 0:
return comparison
return 0
return cmpfn | [
"def",
"multipleOrderComparison",
"(",
"cls",
",",
"orders",
")",
":",
"comparers",
"=",
"[",
"(",
"o",
".",
"keyfn",
",",
"1",
"if",
"o",
".",
"isAscending",
"(",
")",
"else",
"-",
"1",
")",
"for",
"o",
"in",
"orders",
"]",
"def",
"cmpfn",
"(",
... | Returns a function that will compare two items according to `orders` | [
"Returns",
"a",
"function",
"that",
"will",
"compare",
"two",
"items",
"according",
"to",
"orders"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L267-L278 |
26,002 | datastore/datastore | datastore/core/query.py | Order.sorted | def sorted(cls, items, orders):
'''Returns the elements in `items` sorted according to `orders`'''
return sorted(items, cmp=cls.multipleOrderComparison(orders)) | python | def sorted(cls, items, orders):
'''Returns the elements in `items` sorted according to `orders`'''
return sorted(items, cmp=cls.multipleOrderComparison(orders)) | [
"def",
"sorted",
"(",
"cls",
",",
"items",
",",
"orders",
")",
":",
"return",
"sorted",
"(",
"items",
",",
"cmp",
"=",
"cls",
".",
"multipleOrderComparison",
"(",
"orders",
")",
")"
] | Returns the elements in `items` sorted according to `orders` | [
"Returns",
"the",
"elements",
"in",
"items",
"sorted",
"according",
"to",
"orders"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L281-L283 |
26,003 | datastore/datastore | datastore/core/query.py | Query.order | def order(self, order):
'''Adds an Order to this query.
Args:
see :py:class:`Order <datastore.query.Order>` constructor
Returns self for JS-like method chaining::
query.order('+age').order('-home')
'''
order = order if isinstance(order, Order) else Order(order)
# ensure order gets attr values the same way the rest of the query does.
order.object_getattr = self.object_getattr
self.orders.append(order)
return self | python | def order(self, order):
'''Adds an Order to this query.
Args:
see :py:class:`Order <datastore.query.Order>` constructor
Returns self for JS-like method chaining::
query.order('+age').order('-home')
'''
order = order if isinstance(order, Order) else Order(order)
# ensure order gets attr values the same way the rest of the query does.
order.object_getattr = self.object_getattr
self.orders.append(order)
return self | [
"def",
"order",
"(",
"self",
",",
"order",
")",
":",
"order",
"=",
"order",
"if",
"isinstance",
"(",
"order",
",",
"Order",
")",
"else",
"Order",
"(",
"order",
")",
"# ensure order gets attr values the same way the rest of the query does.",
"order",
".",
"object_g... | Adds an Order to this query.
Args:
see :py:class:`Order <datastore.query.Order>` constructor
Returns self for JS-like method chaining::
query.order('+age').order('-home') | [
"Adds",
"an",
"Order",
"to",
"this",
"query",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L365-L381 |
26,004 | datastore/datastore | datastore/core/query.py | Query.filter | def filter(self, *args):
'''Adds a Filter to this query.
Args:
see :py:class:`Filter <datastore.query.Filter>` constructor
Returns self for JS-like method chaining::
query.filter('age', '>', 18).filter('sex', '=', 'Female')
'''
if len(args) == 1 and isinstance(args[0], Filter):
filter = args[0]
else:
filter = Filter(*args)
# ensure filter gets attr values the same way the rest of the query does.
filter.object_getattr = self.object_getattr
self.filters.append(filter)
return self | python | def filter(self, *args):
'''Adds a Filter to this query.
Args:
see :py:class:`Filter <datastore.query.Filter>` constructor
Returns self for JS-like method chaining::
query.filter('age', '>', 18).filter('sex', '=', 'Female')
'''
if len(args) == 1 and isinstance(args[0], Filter):
filter = args[0]
else:
filter = Filter(*args)
# ensure filter gets attr values the same way the rest of the query does.
filter.object_getattr = self.object_getattr
self.filters.append(filter)
return self | [
"def",
"filter",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"Filter",
")",
":",
"filter",
"=",
"args",
"[",
"0",
"]",
"else",
":",
"filter",
"=",
"F... | Adds a Filter to this query.
Args:
see :py:class:`Filter <datastore.query.Filter>` constructor
Returns self for JS-like method chaining::
query.filter('age', '>', 18).filter('sex', '=', 'Female') | [
"Adds",
"a",
"Filter",
"to",
"this",
"query",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L384-L403 |
26,005 | datastore/datastore | datastore/core/query.py | Query.copy | def copy(self):
'''Returns a copy of this query.'''
if self.object_getattr is Query.object_getattr:
other = Query(self.key)
else:
other = Query(self.key, object_getattr=self.object_getattr)
other.limit = self.limit
other.offset = self.offset
other.offset_key = self.offset_key
other.filters = self.filters
other.orders = self.orders
return other | python | def copy(self):
'''Returns a copy of this query.'''
if self.object_getattr is Query.object_getattr:
other = Query(self.key)
else:
other = Query(self.key, object_getattr=self.object_getattr)
other.limit = self.limit
other.offset = self.offset
other.offset_key = self.offset_key
other.filters = self.filters
other.orders = self.orders
return other | [
"def",
"copy",
"(",
"self",
")",
":",
"if",
"self",
".",
"object_getattr",
"is",
"Query",
".",
"object_getattr",
":",
"other",
"=",
"Query",
"(",
"self",
".",
"key",
")",
"else",
":",
"other",
"=",
"Query",
"(",
"self",
".",
"key",
",",
"object_getat... | Returns a copy of this query. | [
"Returns",
"a",
"copy",
"of",
"this",
"query",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L412-L423 |
26,006 | datastore/datastore | datastore/core/query.py | Query.dict | def dict(self):
'''Returns a dictionary representing this query.'''
d = dict()
d['key'] = str(self.key)
if self.limit is not None:
d['limit'] = self.limit
if self.offset > 0:
d['offset'] = self.offset
if self.offset_key:
d['offset_key'] = str(self.offset_key)
if len(self.filters) > 0:
d['filter'] = [[f.field, f.op, f.value] for f in self.filters]
if len(self.orders) > 0:
d['order'] = [str(o) for o in self.orders]
return d | python | def dict(self):
'''Returns a dictionary representing this query.'''
d = dict()
d['key'] = str(self.key)
if self.limit is not None:
d['limit'] = self.limit
if self.offset > 0:
d['offset'] = self.offset
if self.offset_key:
d['offset_key'] = str(self.offset_key)
if len(self.filters) > 0:
d['filter'] = [[f.field, f.op, f.value] for f in self.filters]
if len(self.orders) > 0:
d['order'] = [str(o) for o in self.orders]
return d | [
"def",
"dict",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
")",
"d",
"[",
"'key'",
"]",
"=",
"str",
"(",
"self",
".",
"key",
")",
"if",
"self",
".",
"limit",
"is",
"not",
"None",
":",
"d",
"[",
"'limit'",
"]",
"=",
"self",
".",
"limit",
"... | Returns a dictionary representing this query. | [
"Returns",
"a",
"dictionary",
"representing",
"this",
"query",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L425-L441 |
26,007 | datastore/datastore | datastore/core/query.py | Query.from_dict | def from_dict(cls, dictionary):
'''Constructs a query from a dictionary.'''
query = cls(Key(dictionary['key']))
for key, value in dictionary.items():
if key == 'order':
for order in value:
query.order(order)
elif key == 'filter':
for filter in value:
if not isinstance(filter, Filter):
filter = Filter(*filter)
query.filter(filter)
elif key in ['limit', 'offset', 'offset_key']:
setattr(query, key, value)
return query | python | def from_dict(cls, dictionary):
'''Constructs a query from a dictionary.'''
query = cls(Key(dictionary['key']))
for key, value in dictionary.items():
if key == 'order':
for order in value:
query.order(order)
elif key == 'filter':
for filter in value:
if not isinstance(filter, Filter):
filter = Filter(*filter)
query.filter(filter)
elif key in ['limit', 'offset', 'offset_key']:
setattr(query, key, value)
return query | [
"def",
"from_dict",
"(",
"cls",
",",
"dictionary",
")",
":",
"query",
"=",
"cls",
"(",
"Key",
"(",
"dictionary",
"[",
"'key'",
"]",
")",
")",
"for",
"key",
",",
"value",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"'order'",... | Constructs a query from a dictionary. | [
"Constructs",
"a",
"query",
"from",
"a",
"dictionary",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L444-L462 |
26,008 | datastore/datastore | datastore/core/query.py | Cursor.next | def next(self):
'''Iterator next. Build up count of returned elements during iteration.'''
# if iteration has not begun, begin it.
if not self._iterator:
self.__iter__()
next = self._iterator.next()
if next is not StopIteration:
self._returned_inc(next)
return next | python | def next(self):
'''Iterator next. Build up count of returned elements during iteration.'''
# if iteration has not begun, begin it.
if not self._iterator:
self.__iter__()
next = self._iterator.next()
if next is not StopIteration:
self._returned_inc(next)
return next | [
"def",
"next",
"(",
"self",
")",
":",
"# if iteration has not begun, begin it.",
"if",
"not",
"self",
".",
"_iterator",
":",
"self",
".",
"__iter__",
"(",
")",
"next",
"=",
"self",
".",
"_iterator",
".",
"next",
"(",
")",
"if",
"next",
"is",
"not",
"Stop... | Iterator next. Build up count of returned elements during iteration. | [
"Iterator",
"next",
".",
"Build",
"up",
"count",
"of",
"returned",
"elements",
"during",
"iteration",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L499-L509 |
26,009 | datastore/datastore | datastore/core/query.py | Cursor.apply_filter | def apply_filter(self):
'''Naively apply query filters.'''
self._ensure_modification_is_safe()
if len(self.query.filters) > 0:
self._iterable = Filter.filter(self.query.filters, self._iterable) | python | def apply_filter(self):
'''Naively apply query filters.'''
self._ensure_modification_is_safe()
if len(self.query.filters) > 0:
self._iterable = Filter.filter(self.query.filters, self._iterable) | [
"def",
"apply_filter",
"(",
"self",
")",
":",
"self",
".",
"_ensure_modification_is_safe",
"(",
")",
"if",
"len",
"(",
"self",
".",
"query",
".",
"filters",
")",
">",
"0",
":",
"self",
".",
"_iterable",
"=",
"Filter",
".",
"filter",
"(",
"self",
".",
... | Naively apply query filters. | [
"Naively",
"apply",
"query",
"filters",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L528-L533 |
26,010 | datastore/datastore | datastore/core/query.py | Cursor.apply_order | def apply_order(self):
'''Naively apply query orders.'''
self._ensure_modification_is_safe()
if len(self.query.orders) > 0:
self._iterable = Order.sorted(self._iterable, self.query.orders) | python | def apply_order(self):
'''Naively apply query orders.'''
self._ensure_modification_is_safe()
if len(self.query.orders) > 0:
self._iterable = Order.sorted(self._iterable, self.query.orders) | [
"def",
"apply_order",
"(",
"self",
")",
":",
"self",
".",
"_ensure_modification_is_safe",
"(",
")",
"if",
"len",
"(",
"self",
".",
"query",
".",
"orders",
")",
">",
"0",
":",
"self",
".",
"_iterable",
"=",
"Order",
".",
"sorted",
"(",
"self",
".",
"_... | Naively apply query orders. | [
"Naively",
"apply",
"query",
"orders",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L535-L540 |
26,011 | datastore/datastore | datastore/core/query.py | Cursor.apply_offset | def apply_offset(self):
'''Naively apply query offset.'''
self._ensure_modification_is_safe()
if self.query.offset != 0:
self._iterable = \
offset_gen(self.query.offset, self._iterable, self._skipped_inc) | python | def apply_offset(self):
'''Naively apply query offset.'''
self._ensure_modification_is_safe()
if self.query.offset != 0:
self._iterable = \
offset_gen(self.query.offset, self._iterable, self._skipped_inc) | [
"def",
"apply_offset",
"(",
"self",
")",
":",
"self",
".",
"_ensure_modification_is_safe",
"(",
")",
"if",
"self",
".",
"query",
".",
"offset",
"!=",
"0",
":",
"self",
".",
"_iterable",
"=",
"offset_gen",
"(",
"self",
".",
"query",
".",
"offset",
",",
... | Naively apply query offset. | [
"Naively",
"apply",
"query",
"offset",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L543-L549 |
26,012 | datastore/datastore | datastore/core/query.py | Cursor.apply_limit | def apply_limit(self):
'''Naively apply query limit.'''
self._ensure_modification_is_safe()
if self.query.limit is not None:
self._iterable = limit_gen(self.query.limit, self._iterable) | python | def apply_limit(self):
'''Naively apply query limit.'''
self._ensure_modification_is_safe()
if self.query.limit is not None:
self._iterable = limit_gen(self.query.limit, self._iterable) | [
"def",
"apply_limit",
"(",
"self",
")",
":",
"self",
".",
"_ensure_modification_is_safe",
"(",
")",
"if",
"self",
".",
"query",
".",
"limit",
"is",
"not",
"None",
":",
"self",
".",
"_iterable",
"=",
"limit_gen",
"(",
"self",
".",
"query",
".",
"limit",
... | Naively apply query limit. | [
"Naively",
"apply",
"query",
"limit",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L552-L557 |
26,013 | cockroachdb/cockroachdb-python | cockroachdb/sqlalchemy/transaction.py | run_transaction | def run_transaction(transactor, callback):
"""Run a transaction with retries.
``callback()`` will be called with one argument to execute the
transaction. ``callback`` may be called more than once; it should have
no side effects other than writes to the database on the given
connection. ``callback`` should not call ``commit()` or ``rollback()``;
these will be called automatically.
The ``transactor`` argument may be one of the following types:
* `sqlalchemy.engine.Connection`: the same connection is passed to the callback.
* `sqlalchemy.engine.Engine`: a connection is created and passed to the callback.
* `sqlalchemy.orm.sessionmaker`: a session is created and passed to the callback.
"""
if isinstance(transactor, sqlalchemy.engine.Connection):
return _txn_retry_loop(transactor, callback)
elif isinstance(transactor, sqlalchemy.engine.Engine):
with transactor.connect() as connection:
return _txn_retry_loop(connection, callback)
elif isinstance(transactor, sqlalchemy.orm.sessionmaker):
session = transactor(autocommit=True)
return _txn_retry_loop(session, callback)
else:
raise TypeError("don't know how to run a transaction on %s", type(transactor)) | python | def run_transaction(transactor, callback):
if isinstance(transactor, sqlalchemy.engine.Connection):
return _txn_retry_loop(transactor, callback)
elif isinstance(transactor, sqlalchemy.engine.Engine):
with transactor.connect() as connection:
return _txn_retry_loop(connection, callback)
elif isinstance(transactor, sqlalchemy.orm.sessionmaker):
session = transactor(autocommit=True)
return _txn_retry_loop(session, callback)
else:
raise TypeError("don't know how to run a transaction on %s", type(transactor)) | [
"def",
"run_transaction",
"(",
"transactor",
",",
"callback",
")",
":",
"if",
"isinstance",
"(",
"transactor",
",",
"sqlalchemy",
".",
"engine",
".",
"Connection",
")",
":",
"return",
"_txn_retry_loop",
"(",
"transactor",
",",
"callback",
")",
"elif",
"isinsta... | Run a transaction with retries.
``callback()`` will be called with one argument to execute the
transaction. ``callback`` may be called more than once; it should have
no side effects other than writes to the database on the given
connection. ``callback`` should not call ``commit()` or ``rollback()``;
these will be called automatically.
The ``transactor`` argument may be one of the following types:
* `sqlalchemy.engine.Connection`: the same connection is passed to the callback.
* `sqlalchemy.engine.Engine`: a connection is created and passed to the callback.
* `sqlalchemy.orm.sessionmaker`: a session is created and passed to the callback. | [
"Run",
"a",
"transaction",
"with",
"retries",
"."
] | 5a23e5fb4dc4386828fd147155becba58f0a7c4f | https://github.com/cockroachdb/cockroachdb-python/blob/5a23e5fb4dc4386828fd147155becba58f0a7c4f/cockroachdb/sqlalchemy/transaction.py#L10-L33 |
26,014 | cockroachdb/cockroachdb-python | cockroachdb/sqlalchemy/transaction.py | _txn_retry_loop | def _txn_retry_loop(conn, callback):
"""Inner transaction retry loop.
``conn`` may be either a Connection or a Session, but they both
have compatible ``begin()`` and ``begin_nested()`` methods.
"""
with conn.begin():
while True:
try:
with _NestedTransaction(conn):
ret = callback(conn)
return ret
except sqlalchemy.exc.DatabaseError as e:
if isinstance(e.orig, psycopg2.OperationalError):
if e.orig.pgcode == psycopg2.errorcodes.SERIALIZATION_FAILURE:
continue
raise | python | def _txn_retry_loop(conn, callback):
with conn.begin():
while True:
try:
with _NestedTransaction(conn):
ret = callback(conn)
return ret
except sqlalchemy.exc.DatabaseError as e:
if isinstance(e.orig, psycopg2.OperationalError):
if e.orig.pgcode == psycopg2.errorcodes.SERIALIZATION_FAILURE:
continue
raise | [
"def",
"_txn_retry_loop",
"(",
"conn",
",",
"callback",
")",
":",
"with",
"conn",
".",
"begin",
"(",
")",
":",
"while",
"True",
":",
"try",
":",
"with",
"_NestedTransaction",
"(",
"conn",
")",
":",
"ret",
"=",
"callback",
"(",
"conn",
")",
"return",
... | Inner transaction retry loop.
``conn`` may be either a Connection or a Session, but they both
have compatible ``begin()`` and ``begin_nested()`` methods. | [
"Inner",
"transaction",
"retry",
"loop",
"."
] | 5a23e5fb4dc4386828fd147155becba58f0a7c4f | https://github.com/cockroachdb/cockroachdb-python/blob/5a23e5fb4dc4386828fd147155becba58f0a7c4f/cockroachdb/sqlalchemy/transaction.py#L65-L81 |
26,015 | pazz/urwidtrees | urwidtrees/tree.py | Tree._get | def _get(self, pos):
"""loads widget at given position; handling invalid arguments"""
res = None, None
if pos is not None:
try:
res = self[pos], pos
except (IndexError, KeyError):
pass
return res | python | def _get(self, pos):
res = None, None
if pos is not None:
try:
res = self[pos], pos
except (IndexError, KeyError):
pass
return res | [
"def",
"_get",
"(",
"self",
",",
"pos",
")",
":",
"res",
"=",
"None",
",",
"None",
"if",
"pos",
"is",
"not",
"None",
":",
"try",
":",
"res",
"=",
"self",
"[",
"pos",
"]",
",",
"pos",
"except",
"(",
"IndexError",
",",
"KeyError",
")",
":",
"pass... | loads widget at given position; handling invalid arguments | [
"loads",
"widget",
"at",
"given",
"position",
";",
"handling",
"invalid",
"arguments"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L32-L40 |
26,016 | pazz/urwidtrees | urwidtrees/tree.py | Tree._next_of_kin | def _next_of_kin(self, pos):
"""
looks up the next sibling of the closest ancestor with not-None next
siblings.
"""
candidate = None
parent = self.parent_position(pos)
if parent is not None:
candidate = self.next_sibling_position(parent)
if candidate is None:
candidate = self._next_of_kin(parent)
return candidate | python | def _next_of_kin(self, pos):
candidate = None
parent = self.parent_position(pos)
if parent is not None:
candidate = self.next_sibling_position(parent)
if candidate is None:
candidate = self._next_of_kin(parent)
return candidate | [
"def",
"_next_of_kin",
"(",
"self",
",",
"pos",
")",
":",
"candidate",
"=",
"None",
"parent",
"=",
"self",
".",
"parent_position",
"(",
"pos",
")",
"if",
"parent",
"is",
"not",
"None",
":",
"candidate",
"=",
"self",
".",
"next_sibling_position",
"(",
"pa... | looks up the next sibling of the closest ancestor with not-None next
siblings. | [
"looks",
"up",
"the",
"next",
"sibling",
"of",
"the",
"closest",
"ancestor",
"with",
"not",
"-",
"None",
"next",
"siblings",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L42-L53 |
26,017 | pazz/urwidtrees | urwidtrees/tree.py | Tree._last_in_direction | def _last_in_direction(starting_pos, direction):
"""
move in the tree in given direction and return the last position.
:param starting_pos: position to start at
:param direction: callable that transforms a position into a position.
"""
cur_pos = None
next_pos = starting_pos
while next_pos is not None:
cur_pos = next_pos
next_pos = direction(cur_pos)
return cur_pos | python | def _last_in_direction(starting_pos, direction):
cur_pos = None
next_pos = starting_pos
while next_pos is not None:
cur_pos = next_pos
next_pos = direction(cur_pos)
return cur_pos | [
"def",
"_last_in_direction",
"(",
"starting_pos",
",",
"direction",
")",
":",
"cur_pos",
"=",
"None",
"next_pos",
"=",
"starting_pos",
"while",
"next_pos",
"is",
"not",
"None",
":",
"cur_pos",
"=",
"next_pos",
"next_pos",
"=",
"direction",
"(",
"cur_pos",
")",... | move in the tree in given direction and return the last position.
:param starting_pos: position to start at
:param direction: callable that transforms a position into a position. | [
"move",
"in",
"the",
"tree",
"in",
"given",
"direction",
"and",
"return",
"the",
"last",
"position",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L56-L68 |
26,018 | pazz/urwidtrees | urwidtrees/tree.py | Tree.depth | def depth(self, pos):
"""determine depth of node at pos"""
parent = self.parent_position(pos)
if parent is None:
return 0
else:
return self.depth(parent) + 1 | python | def depth(self, pos):
parent = self.parent_position(pos)
if parent is None:
return 0
else:
return self.depth(parent) + 1 | [
"def",
"depth",
"(",
"self",
",",
"pos",
")",
":",
"parent",
"=",
"self",
".",
"parent_position",
"(",
"pos",
")",
"if",
"parent",
"is",
"None",
":",
"return",
"0",
"else",
":",
"return",
"self",
".",
"depth",
"(",
"parent",
")",
"+",
"1"
] | determine depth of node at pos | [
"determine",
"depth",
"of",
"node",
"at",
"pos"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L70-L76 |
26,019 | pazz/urwidtrees | urwidtrees/tree.py | Tree.next_position | def next_position(self, pos):
"""returns the next position in depth-first order"""
candidate = None
if pos is not None:
candidate = self.first_child_position(pos)
if candidate is None:
candidate = self.next_sibling_position(pos)
if candidate is None:
candidate = self._next_of_kin(pos)
return candidate | python | def next_position(self, pos):
candidate = None
if pos is not None:
candidate = self.first_child_position(pos)
if candidate is None:
candidate = self.next_sibling_position(pos)
if candidate is None:
candidate = self._next_of_kin(pos)
return candidate | [
"def",
"next_position",
"(",
"self",
",",
"pos",
")",
":",
"candidate",
"=",
"None",
"if",
"pos",
"is",
"not",
"None",
":",
"candidate",
"=",
"self",
".",
"first_child_position",
"(",
"pos",
")",
"if",
"candidate",
"is",
"None",
":",
"candidate",
"=",
... | returns the next position in depth-first order | [
"returns",
"the",
"next",
"position",
"in",
"depth",
"-",
"first",
"order"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L102-L111 |
26,020 | pazz/urwidtrees | urwidtrees/tree.py | Tree.prev_position | def prev_position(self, pos):
"""returns the previous position in depth-first order"""
candidate = None
if pos is not None:
prevsib = self.prev_sibling_position(pos) # is None if first
if prevsib is not None:
candidate = self.last_decendant(prevsib)
else:
parent = self.parent_position(pos)
if parent is not None:
candidate = parent
return candidate | python | def prev_position(self, pos):
candidate = None
if pos is not None:
prevsib = self.prev_sibling_position(pos) # is None if first
if prevsib is not None:
candidate = self.last_decendant(prevsib)
else:
parent = self.parent_position(pos)
if parent is not None:
candidate = parent
return candidate | [
"def",
"prev_position",
"(",
"self",
",",
"pos",
")",
":",
"candidate",
"=",
"None",
"if",
"pos",
"is",
"not",
"None",
":",
"prevsib",
"=",
"self",
".",
"prev_sibling_position",
"(",
"pos",
")",
"# is None if first",
"if",
"prevsib",
"is",
"not",
"None",
... | returns the previous position in depth-first order | [
"returns",
"the",
"previous",
"position",
"in",
"depth",
"-",
"first",
"order"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L113-L124 |
26,021 | pazz/urwidtrees | urwidtrees/tree.py | Tree.positions | def positions(self, reverse=False):
"""returns a generator that walks the positions of this tree in DFO"""
def Posgen(reverse):
if reverse:
lastrootsib = self.last_sibling_position(self.root)
current = self.last_decendant(lastrootsib)
while current is not None:
yield current
current = self.prev_position(current)
else:
current = self.root
while current is not None:
yield current
current = self.next_position(current)
return Posgen(reverse) | python | def positions(self, reverse=False):
def Posgen(reverse):
if reverse:
lastrootsib = self.last_sibling_position(self.root)
current = self.last_decendant(lastrootsib)
while current is not None:
yield current
current = self.prev_position(current)
else:
current = self.root
while current is not None:
yield current
current = self.next_position(current)
return Posgen(reverse) | [
"def",
"positions",
"(",
"self",
",",
"reverse",
"=",
"False",
")",
":",
"def",
"Posgen",
"(",
"reverse",
")",
":",
"if",
"reverse",
":",
"lastrootsib",
"=",
"self",
".",
"last_sibling_position",
"(",
"self",
".",
"root",
")",
"current",
"=",
"self",
"... | returns a generator that walks the positions of this tree in DFO | [
"returns",
"a",
"generator",
"that",
"walks",
"the",
"positions",
"of",
"this",
"tree",
"in",
"DFO"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L126-L140 |
26,022 | pazz/urwidtrees | urwidtrees/tree.py | SimpleTree._get_substructure | def _get_substructure(self, treelist, pos):
"""recursive helper to look up node-tuple for `pos` in `treelist`"""
subtree = None
if len(pos) > 1:
subtree = self._get_substructure(treelist[pos[0]][1], pos[1:])
else:
try:
subtree = treelist[pos[0]]
except (IndexError, TypeError):
pass
return subtree | python | def _get_substructure(self, treelist, pos):
subtree = None
if len(pos) > 1:
subtree = self._get_substructure(treelist[pos[0]][1], pos[1:])
else:
try:
subtree = treelist[pos[0]]
except (IndexError, TypeError):
pass
return subtree | [
"def",
"_get_substructure",
"(",
"self",
",",
"treelist",
",",
"pos",
")",
":",
"subtree",
"=",
"None",
"if",
"len",
"(",
"pos",
")",
">",
"1",
":",
"subtree",
"=",
"self",
".",
"_get_substructure",
"(",
"treelist",
"[",
"pos",
"[",
"0",
"]",
"]",
... | recursive helper to look up node-tuple for `pos` in `treelist` | [
"recursive",
"helper",
"to",
"look",
"up",
"node",
"-",
"tuple",
"for",
"pos",
"in",
"treelist"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L188-L198 |
26,023 | pazz/urwidtrees | urwidtrees/tree.py | SimpleTree._get_node | def _get_node(self, treelist, pos):
"""
look up widget at `pos` of `treelist`; default to None if
nonexistent.
"""
node = None
if pos is not None:
subtree = self._get_substructure(treelist, pos)
if subtree is not None:
node = subtree[0]
return node | python | def _get_node(self, treelist, pos):
node = None
if pos is not None:
subtree = self._get_substructure(treelist, pos)
if subtree is not None:
node = subtree[0]
return node | [
"def",
"_get_node",
"(",
"self",
",",
"treelist",
",",
"pos",
")",
":",
"node",
"=",
"None",
"if",
"pos",
"is",
"not",
"None",
":",
"subtree",
"=",
"self",
".",
"_get_substructure",
"(",
"treelist",
",",
"pos",
")",
"if",
"subtree",
"is",
"not",
"Non... | look up widget at `pos` of `treelist`; default to None if
nonexistent. | [
"look",
"up",
"widget",
"at",
"pos",
"of",
"treelist",
";",
"default",
"to",
"None",
"if",
"nonexistent",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L200-L210 |
26,024 | pazz/urwidtrees | urwidtrees/tree.py | SimpleTree._confirm_pos | def _confirm_pos(self, pos):
"""look up widget for pos and default to None"""
candidate = None
if self._get_node(self._treelist, pos) is not None:
candidate = pos
return candidate | python | def _confirm_pos(self, pos):
candidate = None
if self._get_node(self._treelist, pos) is not None:
candidate = pos
return candidate | [
"def",
"_confirm_pos",
"(",
"self",
",",
"pos",
")",
":",
"candidate",
"=",
"None",
"if",
"self",
".",
"_get_node",
"(",
"self",
".",
"_treelist",
",",
"pos",
")",
"is",
"not",
"None",
":",
"candidate",
"=",
"pos",
"return",
"candidate"
] | look up widget for pos and default to None | [
"look",
"up",
"widget",
"for",
"pos",
"and",
"default",
"to",
"None"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L212-L217 |
26,025 | pazz/urwidtrees | docs/examples/example4.filesystem.py | DirectoryTree._list_dir | def _list_dir(self, path):
"""returns absolute paths for all entries in a directory"""
try:
elements = [
os.path.join(path, x) for x in os.listdir(path)
] if os.path.isdir(path) else []
elements.sort()
except OSError:
elements = None
return elements | python | def _list_dir(self, path):
try:
elements = [
os.path.join(path, x) for x in os.listdir(path)
] if os.path.isdir(path) else []
elements.sort()
except OSError:
elements = None
return elements | [
"def",
"_list_dir",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"elements",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"x",
")",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
"]",
"if",
"os",
".",
"path",
".",... | returns absolute paths for all entries in a directory | [
"returns",
"absolute",
"paths",
"for",
"all",
"entries",
"in",
"a",
"directory"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/docs/examples/example4.filesystem.py#L50-L59 |
26,026 | pazz/urwidtrees | docs/examples/example4.filesystem.py | DirectoryTree._get_siblings | def _get_siblings(self, pos):
"""lists the parent directory of pos """
parent = self.parent_position(pos)
siblings = [pos]
if parent is not None:
siblings = self._list_dir(parent)
return siblings | python | def _get_siblings(self, pos):
parent = self.parent_position(pos)
siblings = [pos]
if parent is not None:
siblings = self._list_dir(parent)
return siblings | [
"def",
"_get_siblings",
"(",
"self",
",",
"pos",
")",
":",
"parent",
"=",
"self",
".",
"parent_position",
"(",
"pos",
")",
"siblings",
"=",
"[",
"pos",
"]",
"if",
"parent",
"is",
"not",
"None",
":",
"siblings",
"=",
"self",
".",
"_list_dir",
"(",
"pa... | lists the parent directory of pos | [
"lists",
"the",
"parent",
"directory",
"of",
"pos"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/docs/examples/example4.filesystem.py#L61-L67 |
26,027 | incuna/django-orderable | orderable/admin.py | OrderableAdmin.reorder_view | def reorder_view(self, request):
"""The 'reorder' admin view for this model."""
model = self.model
if not self.has_change_permission(request):
raise PermissionDenied
if request.method == "POST":
object_pks = request.POST.getlist('neworder[]')
model.objects.set_orders(object_pks)
return HttpResponse("OK") | python | def reorder_view(self, request):
model = self.model
if not self.has_change_permission(request):
raise PermissionDenied
if request.method == "POST":
object_pks = request.POST.getlist('neworder[]')
model.objects.set_orders(object_pks)
return HttpResponse("OK") | [
"def",
"reorder_view",
"(",
"self",
",",
"request",
")",
":",
"model",
"=",
"self",
".",
"model",
"if",
"not",
"self",
".",
"has_change_permission",
"(",
"request",
")",
":",
"raise",
"PermissionDenied",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":... | The 'reorder' admin view for this model. | [
"The",
"reorder",
"admin",
"view",
"for",
"this",
"model",
"."
] | 88da9c762ef0500725f95988c8f18d9b304e6951 | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/admin.py#L50-L61 |
26,028 | pazz/urwidtrees | urwidtrees/decoration.py | CollapseMixin.is_collapsed | def is_collapsed(self, pos):
"""checks if given position is currently collapsed"""
collapsed = self._initially_collapsed(pos)
if pos in self._divergent_positions:
collapsed = not collapsed
return collapsed | python | def is_collapsed(self, pos):
collapsed = self._initially_collapsed(pos)
if pos in self._divergent_positions:
collapsed = not collapsed
return collapsed | [
"def",
"is_collapsed",
"(",
"self",
",",
"pos",
")",
":",
"collapsed",
"=",
"self",
".",
"_initially_collapsed",
"(",
"pos",
")",
"if",
"pos",
"in",
"self",
".",
"_divergent_positions",
":",
"collapsed",
"=",
"not",
"collapsed",
"return",
"collapsed"
] | checks if given position is currently collapsed | [
"checks",
"if",
"given",
"position",
"is",
"currently",
"collapsed"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/decoration.py#L76-L81 |
26,029 | pazz/urwidtrees | urwidtrees/decoration.py | ArrowTree._construct_spacer | def _construct_spacer(self, pos, acc):
"""
build a spacer that occupies the horizontally indented space between
pos's parent and the root node. It will return a list of tuples to be
fed into a Columns widget.
"""
parent = self._tree.parent_position(pos)
if parent is not None:
grandparent = self._tree.parent_position(parent)
if self._indent > 0 and grandparent is not None:
parent_sib = self._tree.next_sibling_position(parent)
draw_vbar = parent_sib is not None and \
self._arrow_vbar_char is not None
space_width = self._indent - 1 * (draw_vbar) - self._childbar_offset
if space_width > 0:
void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att)
acc.insert(0, ((space_width, void)))
if draw_vbar:
barw = urwid.SolidFill(self._arrow_vbar_char)
bar = urwid.AttrMap(barw, self._arrow_vbar_att or
self._arrow_att)
acc.insert(0, ((1, bar)))
return self._construct_spacer(parent, acc)
else:
return acc | python | def _construct_spacer(self, pos, acc):
parent = self._tree.parent_position(pos)
if parent is not None:
grandparent = self._tree.parent_position(parent)
if self._indent > 0 and grandparent is not None:
parent_sib = self._tree.next_sibling_position(parent)
draw_vbar = parent_sib is not None and \
self._arrow_vbar_char is not None
space_width = self._indent - 1 * (draw_vbar) - self._childbar_offset
if space_width > 0:
void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att)
acc.insert(0, ((space_width, void)))
if draw_vbar:
barw = urwid.SolidFill(self._arrow_vbar_char)
bar = urwid.AttrMap(barw, self._arrow_vbar_att or
self._arrow_att)
acc.insert(0, ((1, bar)))
return self._construct_spacer(parent, acc)
else:
return acc | [
"def",
"_construct_spacer",
"(",
"self",
",",
"pos",
",",
"acc",
")",
":",
"parent",
"=",
"self",
".",
"_tree",
".",
"parent_position",
"(",
"pos",
")",
"if",
"parent",
"is",
"not",
"None",
":",
"grandparent",
"=",
"self",
".",
"_tree",
".",
"parent_po... | build a spacer that occupies the horizontally indented space between
pos's parent and the root node. It will return a list of tuples to be
fed into a Columns widget. | [
"build",
"a",
"spacer",
"that",
"occupies",
"the",
"horizontally",
"indented",
"space",
"between",
"pos",
"s",
"parent",
"and",
"the",
"root",
"node",
".",
"It",
"will",
"return",
"a",
"list",
"of",
"tuples",
"to",
"be",
"fed",
"into",
"a",
"Columns",
"w... | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/decoration.py#L329-L353 |
26,030 | pazz/urwidtrees | urwidtrees/decoration.py | ArrowTree._construct_connector | def _construct_connector(self, pos):
"""
build widget to be used as "connector" bit between the vertical bar
between siblings and their respective horizontal bars leading to the
arrow tip
"""
# connector symbol, either L or |- shaped.
connectorw = None
connector = None
if self._tree.next_sibling_position(pos) is not None: # |- shaped
if self._arrow_connector_tchar is not None:
connectorw = urwid.Text(self._arrow_connector_tchar)
else: # L shaped
if self._arrow_connector_lchar is not None:
connectorw = urwid.Text(self._arrow_connector_lchar)
if connectorw is not None:
att = self._arrow_connector_att or self._arrow_att
connector = urwid.AttrMap(connectorw, att)
return connector | python | def _construct_connector(self, pos):
# connector symbol, either L or |- shaped.
connectorw = None
connector = None
if self._tree.next_sibling_position(pos) is not None: # |- shaped
if self._arrow_connector_tchar is not None:
connectorw = urwid.Text(self._arrow_connector_tchar)
else: # L shaped
if self._arrow_connector_lchar is not None:
connectorw = urwid.Text(self._arrow_connector_lchar)
if connectorw is not None:
att = self._arrow_connector_att or self._arrow_att
connector = urwid.AttrMap(connectorw, att)
return connector | [
"def",
"_construct_connector",
"(",
"self",
",",
"pos",
")",
":",
"# connector symbol, either L or |- shaped.",
"connectorw",
"=",
"None",
"connector",
"=",
"None",
"if",
"self",
".",
"_tree",
".",
"next_sibling_position",
"(",
"pos",
")",
"is",
"not",
"None",
"... | build widget to be used as "connector" bit between the vertical bar
between siblings and their respective horizontal bars leading to the
arrow tip | [
"build",
"widget",
"to",
"be",
"used",
"as",
"connector",
"bit",
"between",
"the",
"vertical",
"bar",
"between",
"siblings",
"and",
"their",
"respective",
"horizontal",
"bars",
"leading",
"to",
"the",
"arrow",
"tip"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/decoration.py#L355-L373 |
26,031 | pazz/urwidtrees | urwidtrees/decoration.py | ArrowTree._construct_first_indent | def _construct_first_indent(self, pos):
"""
build spacer to occupy the first indentation level from pos to the
left. This is separate as it adds arrowtip and sibling connector.
"""
cols = []
void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att)
available_width = self._indent
if self._tree.depth(pos) > 0:
connector = self._construct_connector(pos)
if connector is not None:
width = connector.pack()[0]
if width > available_width:
raise NoSpaceError()
available_width -= width
if self._tree.next_sibling_position(pos) is not None:
barw = urwid.SolidFill(self._arrow_vbar_char)
below = urwid.AttrMap(barw, self._arrow_vbar_att or
self._arrow_att)
else:
below = void
# pile up connector and bar
spacer = urwid.Pile([('pack', connector), below])
cols.append((width, spacer))
#arrow tip
awidth, at = self._construct_arrow_tip(pos)
if at is not None:
if awidth > available_width:
raise NoSpaceError()
available_width -= awidth
at_spacer = urwid.Pile([('pack', at), void])
cols.append((awidth, at_spacer))
# bar between connector and arrow tip
if available_width > 0:
barw = urwid.SolidFill(self._arrow_hbar_char)
bar = urwid.AttrMap(
barw, self._arrow_hbar_att or self._arrow_att)
hb_spacer = urwid.Pile([(1, bar), void])
cols.insert(1, (available_width, hb_spacer))
return cols | python | def _construct_first_indent(self, pos):
cols = []
void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att)
available_width = self._indent
if self._tree.depth(pos) > 0:
connector = self._construct_connector(pos)
if connector is not None:
width = connector.pack()[0]
if width > available_width:
raise NoSpaceError()
available_width -= width
if self._tree.next_sibling_position(pos) is not None:
barw = urwid.SolidFill(self._arrow_vbar_char)
below = urwid.AttrMap(barw, self._arrow_vbar_att or
self._arrow_att)
else:
below = void
# pile up connector and bar
spacer = urwid.Pile([('pack', connector), below])
cols.append((width, spacer))
#arrow tip
awidth, at = self._construct_arrow_tip(pos)
if at is not None:
if awidth > available_width:
raise NoSpaceError()
available_width -= awidth
at_spacer = urwid.Pile([('pack', at), void])
cols.append((awidth, at_spacer))
# bar between connector and arrow tip
if available_width > 0:
barw = urwid.SolidFill(self._arrow_hbar_char)
bar = urwid.AttrMap(
barw, self._arrow_hbar_att or self._arrow_att)
hb_spacer = urwid.Pile([(1, bar), void])
cols.insert(1, (available_width, hb_spacer))
return cols | [
"def",
"_construct_first_indent",
"(",
"self",
",",
"pos",
")",
":",
"cols",
"=",
"[",
"]",
"void",
"=",
"urwid",
".",
"AttrMap",
"(",
"urwid",
".",
"SolidFill",
"(",
"' '",
")",
",",
"self",
".",
"_arrow_att",
")",
"available_width",
"=",
"self",
".",... | build spacer to occupy the first indentation level from pos to the
left. This is separate as it adds arrowtip and sibling connector. | [
"build",
"spacer",
"to",
"occupy",
"the",
"first",
"indentation",
"level",
"from",
"pos",
"to",
"the",
"left",
".",
"This",
"is",
"separate",
"as",
"it",
"adds",
"arrowtip",
"and",
"sibling",
"connector",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/decoration.py#L386-L428 |
26,032 | pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.collapse_focussed | def collapse_focussed(self):
"""
Collapse currently focussed position; works only if the underlying
tree allows it.
"""
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.collapse(focuspos)
self._walker.clear_cache()
self.refresh() | python | def collapse_focussed(self):
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.collapse(focuspos)
self._walker.clear_cache()
self.refresh() | [
"def",
"collapse_focussed",
"(",
"self",
")",
":",
"if",
"implementsCollapseAPI",
"(",
"self",
".",
"_tree",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"self",
".",
"_tree",
".",
"collapse",
"(",
"focuspos",
")",
"self",
"... | Collapse currently focussed position; works only if the underlying
tree allows it. | [
"Collapse",
"currently",
"focussed",
"position",
";",
"works",
"only",
"if",
"the",
"underlying",
"tree",
"allows",
"it",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L156-L165 |
26,033 | pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.expand_focussed | def expand_focussed(self):
"""
Expand currently focussed position; works only if the underlying
tree allows it.
"""
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.expand(focuspos)
self._walker.clear_cache()
self.refresh() | python | def expand_focussed(self):
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.expand(focuspos)
self._walker.clear_cache()
self.refresh() | [
"def",
"expand_focussed",
"(",
"self",
")",
":",
"if",
"implementsCollapseAPI",
"(",
"self",
".",
"_tree",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"self",
".",
"_tree",
".",
"expand",
"(",
"focuspos",
")",
"self",
".",
... | Expand currently focussed position; works only if the underlying
tree allows it. | [
"Expand",
"currently",
"focussed",
"position",
";",
"works",
"only",
"if",
"the",
"underlying",
"tree",
"allows",
"it",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L167-L176 |
26,034 | pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.collapse_all | def collapse_all(self):
"""
Collapse all positions; works only if the underlying tree allows it.
"""
if implementsCollapseAPI(self._tree):
self._tree.collapse_all()
self.set_focus(self._tree.root)
self._walker.clear_cache()
self.refresh() | python | def collapse_all(self):
if implementsCollapseAPI(self._tree):
self._tree.collapse_all()
self.set_focus(self._tree.root)
self._walker.clear_cache()
self.refresh() | [
"def",
"collapse_all",
"(",
"self",
")",
":",
"if",
"implementsCollapseAPI",
"(",
"self",
".",
"_tree",
")",
":",
"self",
".",
"_tree",
".",
"collapse_all",
"(",
")",
"self",
".",
"set_focus",
"(",
"self",
".",
"_tree",
".",
"root",
")",
"self",
".",
... | Collapse all positions; works only if the underlying tree allows it. | [
"Collapse",
"all",
"positions",
";",
"works",
"only",
"if",
"the",
"underlying",
"tree",
"allows",
"it",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L178-L186 |
26,035 | pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.expand_all | def expand_all(self):
"""
Expand all positions; works only if the underlying tree allows it.
"""
if implementsCollapseAPI(self._tree):
self._tree.expand_all()
self._walker.clear_cache()
self.refresh() | python | def expand_all(self):
if implementsCollapseAPI(self._tree):
self._tree.expand_all()
self._walker.clear_cache()
self.refresh() | [
"def",
"expand_all",
"(",
"self",
")",
":",
"if",
"implementsCollapseAPI",
"(",
"self",
".",
"_tree",
")",
":",
"self",
".",
"_tree",
".",
"expand_all",
"(",
")",
"self",
".",
"_walker",
".",
"clear_cache",
"(",
")",
"self",
".",
"refresh",
"(",
")"
] | Expand all positions; works only if the underlying tree allows it. | [
"Expand",
"all",
"positions",
";",
"works",
"only",
"if",
"the",
"underlying",
"tree",
"allows",
"it",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L188-L195 |
26,036 | pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.focus_parent | def focus_parent(self):
"""move focus to parent node of currently focussed one"""
w, focuspos = self.get_focus()
parent = self._tree.parent_position(focuspos)
if parent is not None:
self.set_focus(parent) | python | def focus_parent(self):
w, focuspos = self.get_focus()
parent = self._tree.parent_position(focuspos)
if parent is not None:
self.set_focus(parent) | [
"def",
"focus_parent",
"(",
"self",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"parent",
"=",
"self",
".",
"_tree",
".",
"parent_position",
"(",
"focuspos",
")",
"if",
"parent",
"is",
"not",
"None",
":",
"self",
".",
"se... | move focus to parent node of currently focussed one | [
"move",
"focus",
"to",
"parent",
"node",
"of",
"currently",
"focussed",
"one"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L198-L203 |
26,037 | pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.focus_first_child | def focus_first_child(self):
"""move focus to first child of currently focussed one"""
w, focuspos = self.get_focus()
child = self._tree.first_child_position(focuspos)
if child is not None:
self.set_focus(child) | python | def focus_first_child(self):
w, focuspos = self.get_focus()
child = self._tree.first_child_position(focuspos)
if child is not None:
self.set_focus(child) | [
"def",
"focus_first_child",
"(",
"self",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"child",
"=",
"self",
".",
"_tree",
".",
"first_child_position",
"(",
"focuspos",
")",
"if",
"child",
"is",
"not",
"None",
":",
"self",
".... | move focus to first child of currently focussed one | [
"move",
"focus",
"to",
"first",
"child",
"of",
"currently",
"focussed",
"one"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L205-L210 |
26,038 | pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.focus_last_child | def focus_last_child(self):
"""move focus to last child of currently focussed one"""
w, focuspos = self.get_focus()
child = self._tree.last_child_position(focuspos)
if child is not None:
self.set_focus(child) | python | def focus_last_child(self):
w, focuspos = self.get_focus()
child = self._tree.last_child_position(focuspos)
if child is not None:
self.set_focus(child) | [
"def",
"focus_last_child",
"(",
"self",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"child",
"=",
"self",
".",
"_tree",
".",
"last_child_position",
"(",
"focuspos",
")",
"if",
"child",
"is",
"not",
"None",
":",
"self",
".",... | move focus to last child of currently focussed one | [
"move",
"focus",
"to",
"last",
"child",
"of",
"currently",
"focussed",
"one"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L212-L217 |
26,039 | pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.focus_next_sibling | def focus_next_sibling(self):
"""move focus to next sibling of currently focussed one"""
w, focuspos = self.get_focus()
sib = self._tree.next_sibling_position(focuspos)
if sib is not None:
self.set_focus(sib) | python | def focus_next_sibling(self):
w, focuspos = self.get_focus()
sib = self._tree.next_sibling_position(focuspos)
if sib is not None:
self.set_focus(sib) | [
"def",
"focus_next_sibling",
"(",
"self",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"sib",
"=",
"self",
".",
"_tree",
".",
"next_sibling_position",
"(",
"focuspos",
")",
"if",
"sib",
"is",
"not",
"None",
":",
"self",
".",... | move focus to next sibling of currently focussed one | [
"move",
"focus",
"to",
"next",
"sibling",
"of",
"currently",
"focussed",
"one"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L219-L224 |
26,040 | pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.focus_prev_sibling | def focus_prev_sibling(self):
"""move focus to previous sibling of currently focussed one"""
w, focuspos = self.get_focus()
sib = self._tree.prev_sibling_position(focuspos)
if sib is not None:
self.set_focus(sib) | python | def focus_prev_sibling(self):
w, focuspos = self.get_focus()
sib = self._tree.prev_sibling_position(focuspos)
if sib is not None:
self.set_focus(sib) | [
"def",
"focus_prev_sibling",
"(",
"self",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"sib",
"=",
"self",
".",
"_tree",
".",
"prev_sibling_position",
"(",
"focuspos",
")",
"if",
"sib",
"is",
"not",
"None",
":",
"self",
".",... | move focus to previous sibling of currently focussed one | [
"move",
"focus",
"to",
"previous",
"sibling",
"of",
"currently",
"focussed",
"one"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L226-L231 |
26,041 | incuna/django-orderable | orderable/models.py | Orderable.get_unique_fields | def get_unique_fields(self):
"""List field names that are unique_together with `sort_order`."""
for unique_together in self._meta.unique_together:
if 'sort_order' in unique_together:
unique_fields = list(unique_together)
unique_fields.remove('sort_order')
return ['%s_id' % f for f in unique_fields]
return [] | python | def get_unique_fields(self):
for unique_together in self._meta.unique_together:
if 'sort_order' in unique_together:
unique_fields = list(unique_together)
unique_fields.remove('sort_order')
return ['%s_id' % f for f in unique_fields]
return [] | [
"def",
"get_unique_fields",
"(",
"self",
")",
":",
"for",
"unique_together",
"in",
"self",
".",
"_meta",
".",
"unique_together",
":",
"if",
"'sort_order'",
"in",
"unique_together",
":",
"unique_fields",
"=",
"list",
"(",
"unique_together",
")",
"unique_fields",
... | List field names that are unique_together with `sort_order`. | [
"List",
"field",
"names",
"that",
"are",
"unique_together",
"with",
"sort_order",
"."
] | 88da9c762ef0500725f95988c8f18d9b304e6951 | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/models.py#L29-L36 |
26,042 | incuna/django-orderable | orderable/models.py | Orderable._is_sort_order_unique_together_with_something | def _is_sort_order_unique_together_with_something(self):
"""
Is the sort_order field unique_together with something
"""
unique_together = self._meta.unique_together
for fields in unique_together:
if 'sort_order' in fields and len(fields) > 1:
return True
return False | python | def _is_sort_order_unique_together_with_something(self):
unique_together = self._meta.unique_together
for fields in unique_together:
if 'sort_order' in fields and len(fields) > 1:
return True
return False | [
"def",
"_is_sort_order_unique_together_with_something",
"(",
"self",
")",
":",
"unique_together",
"=",
"self",
".",
"_meta",
".",
"unique_together",
"for",
"fields",
"in",
"unique_together",
":",
"if",
"'sort_order'",
"in",
"fields",
"and",
"len",
"(",
"fields",
"... | Is the sort_order field unique_together with something | [
"Is",
"the",
"sort_order",
"field",
"unique_together",
"with",
"something"
] | 88da9c762ef0500725f95988c8f18d9b304e6951 | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/models.py#L62-L70 |
26,043 | incuna/django-orderable | orderable/models.py | Orderable._update | def _update(qs):
"""
Increment the sort_order in a queryset.
Handle IntegrityErrors caused by unique constraints.
"""
try:
with transaction.atomic():
qs.update(sort_order=models.F('sort_order') + 1)
except IntegrityError:
for obj in qs.order_by('-sort_order'):
qs.filter(pk=obj.pk).update(sort_order=models.F('sort_order') + 1) | python | def _update(qs):
try:
with transaction.atomic():
qs.update(sort_order=models.F('sort_order') + 1)
except IntegrityError:
for obj in qs.order_by('-sort_order'):
qs.filter(pk=obj.pk).update(sort_order=models.F('sort_order') + 1) | [
"def",
"_update",
"(",
"qs",
")",
":",
"try",
":",
"with",
"transaction",
".",
"atomic",
"(",
")",
":",
"qs",
".",
"update",
"(",
"sort_order",
"=",
"models",
".",
"F",
"(",
"'sort_order'",
")",
"+",
"1",
")",
"except",
"IntegrityError",
":",
"for",
... | Increment the sort_order in a queryset.
Handle IntegrityErrors caused by unique constraints. | [
"Increment",
"the",
"sort_order",
"in",
"a",
"queryset",
"."
] | 88da9c762ef0500725f95988c8f18d9b304e6951 | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/models.py#L73-L84 |
26,044 | incuna/django-orderable | orderable/models.py | Orderable.save | def save(self, *args, **kwargs):
"""Keep the unique order in sync."""
objects = self.get_filtered_manager()
old_pos = getattr(self, '_original_sort_order', None)
new_pos = self.sort_order
if old_pos is None and self._unique_togethers_changed():
self.sort_order = None
new_pos = None
try:
with transaction.atomic():
self._save(objects, old_pos, new_pos)
except IntegrityError:
with transaction.atomic():
old_pos = objects.filter(pk=self.pk).values_list(
'sort_order', flat=True)[0]
self._save(objects, old_pos, new_pos)
# Call the "real" save() method.
super(Orderable, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
objects = self.get_filtered_manager()
old_pos = getattr(self, '_original_sort_order', None)
new_pos = self.sort_order
if old_pos is None and self._unique_togethers_changed():
self.sort_order = None
new_pos = None
try:
with transaction.atomic():
self._save(objects, old_pos, new_pos)
except IntegrityError:
with transaction.atomic():
old_pos = objects.filter(pk=self.pk).values_list(
'sort_order', flat=True)[0]
self._save(objects, old_pos, new_pos)
# Call the "real" save() method.
super(Orderable, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"objects",
"=",
"self",
".",
"get_filtered_manager",
"(",
")",
"old_pos",
"=",
"getattr",
"(",
"self",
",",
"'_original_sort_order'",
",",
"None",
")",
"new_pos",
"=",
"se... | Keep the unique order in sync. | [
"Keep",
"the",
"unique",
"order",
"in",
"sync",
"."
] | 88da9c762ef0500725f95988c8f18d9b304e6951 | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/models.py#L133-L153 |
26,045 | incuna/django-orderable | orderable/querysets.py | OrderableQueryset.set_orders | def set_orders(self, object_pks):
"""
Perform a mass update of sort_orders across the full queryset.
Accepts a list, object_pks, of the intended order for the objects.
Works as follows:
- Compile a list of all sort orders in the queryset. Leave out anything that
isn't in the object_pks list - this deals with pagination and any
inconsistencies.
- Get the maximum among all model object sort orders. Update the queryset to add
it to all the existing sort order values. This lifts them 'out of the way' of
unique_together clashes when setting the intended sort orders.
- Set the sort order on each object. Use only sort_order values that the objects
had before calling this method, so they get rearranged in place.
Performs O(n) queries.
"""
objects_to_sort = self.filter(pk__in=object_pks)
max_value = self.model.objects.all().aggregate(
models.Max('sort_order')
)['sort_order__max']
# Call list() on the values right away, so they don't get affected by the
# update() later (since values_list() is lazy).
orders = list(objects_to_sort.values_list('sort_order', flat=True))
# Check there are no unrecognised entries in the object_pks list. If so,
# throw an error. We only have to check that they're the same length because
# orders is built using only entries in object_pks, and all the pks are unique,
# so if their lengths are the same, the elements must match up exactly.
if len(orders) != len(object_pks):
pks = set(objects_to_sort.values_list('pk', flat=True))
message = 'The following object_pks are not in this queryset: {}'.format(
[pk for pk in object_pks if pk not in pks]
)
raise TypeError(message)
with transaction.atomic():
objects_to_sort.update(sort_order=models.F('sort_order') + max_value)
for pk, order in zip(object_pks, orders):
# Use update() to save a query per item and dodge the insertion sort
# code in save().
self.filter(pk=pk).update(sort_order=order)
# Return the operated-on queryset for convenience.
return objects_to_sort | python | def set_orders(self, object_pks):
objects_to_sort = self.filter(pk__in=object_pks)
max_value = self.model.objects.all().aggregate(
models.Max('sort_order')
)['sort_order__max']
# Call list() on the values right away, so they don't get affected by the
# update() later (since values_list() is lazy).
orders = list(objects_to_sort.values_list('sort_order', flat=True))
# Check there are no unrecognised entries in the object_pks list. If so,
# throw an error. We only have to check that they're the same length because
# orders is built using only entries in object_pks, and all the pks are unique,
# so if their lengths are the same, the elements must match up exactly.
if len(orders) != len(object_pks):
pks = set(objects_to_sort.values_list('pk', flat=True))
message = 'The following object_pks are not in this queryset: {}'.format(
[pk for pk in object_pks if pk not in pks]
)
raise TypeError(message)
with transaction.atomic():
objects_to_sort.update(sort_order=models.F('sort_order') + max_value)
for pk, order in zip(object_pks, orders):
# Use update() to save a query per item and dodge the insertion sort
# code in save().
self.filter(pk=pk).update(sort_order=order)
# Return the operated-on queryset for convenience.
return objects_to_sort | [
"def",
"set_orders",
"(",
"self",
",",
"object_pks",
")",
":",
"objects_to_sort",
"=",
"self",
".",
"filter",
"(",
"pk__in",
"=",
"object_pks",
")",
"max_value",
"=",
"self",
".",
"model",
".",
"objects",
".",
"all",
"(",
")",
".",
"aggregate",
"(",
"m... | Perform a mass update of sort_orders across the full queryset.
Accepts a list, object_pks, of the intended order for the objects.
Works as follows:
- Compile a list of all sort orders in the queryset. Leave out anything that
isn't in the object_pks list - this deals with pagination and any
inconsistencies.
- Get the maximum among all model object sort orders. Update the queryset to add
it to all the existing sort order values. This lifts them 'out of the way' of
unique_together clashes when setting the intended sort orders.
- Set the sort order on each object. Use only sort_order values that the objects
had before calling this method, so they get rearranged in place.
Performs O(n) queries. | [
"Perform",
"a",
"mass",
"update",
"of",
"sort_orders",
"across",
"the",
"full",
"queryset",
".",
"Accepts",
"a",
"list",
"object_pks",
"of",
"the",
"intended",
"order",
"for",
"the",
"objects",
"."
] | 88da9c762ef0500725f95988c8f18d9b304e6951 | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/querysets.py#L18-L62 |
26,046 | tatterdemalion/django-nece | nece/managers.py | TranslationQuerySet.order_by_json_path | def order_by_json_path(self, json_path, language_code=None, order='asc'):
"""
Orders a queryset by the value of the specified `json_path`.
More about the `#>>` operator and the `json_path` arg syntax:
https://www.postgresql.org/docs/current/static/functions-json.html
More about Raw SQL expressions:
https://docs.djangoproject.com/en/dev/ref/models/expressions/#raw-sql-expressions
Usage example:
MyModel.objects.language('en_us').filter(is_active=True).order_by_json_path('title')
"""
language_code = (language_code
or self._language_code
or self.get_language_key(language_code))
json_path = '{%s,%s}' % (language_code, json_path)
# Our jsonb field is named `translations`.
raw_sql_expression = RawSQL("translations#>>%s", (json_path,))
if order == 'desc':
raw_sql_expression = raw_sql_expression.desc()
return self.order_by(raw_sql_expression) | python | def order_by_json_path(self, json_path, language_code=None, order='asc'):
language_code = (language_code
or self._language_code
or self.get_language_key(language_code))
json_path = '{%s,%s}' % (language_code, json_path)
# Our jsonb field is named `translations`.
raw_sql_expression = RawSQL("translations#>>%s", (json_path,))
if order == 'desc':
raw_sql_expression = raw_sql_expression.desc()
return self.order_by(raw_sql_expression) | [
"def",
"order_by_json_path",
"(",
"self",
",",
"json_path",
",",
"language_code",
"=",
"None",
",",
"order",
"=",
"'asc'",
")",
":",
"language_code",
"=",
"(",
"language_code",
"or",
"self",
".",
"_language_code",
"or",
"self",
".",
"get_language_key",
"(",
... | Orders a queryset by the value of the specified `json_path`.
More about the `#>>` operator and the `json_path` arg syntax:
https://www.postgresql.org/docs/current/static/functions-json.html
More about Raw SQL expressions:
https://docs.djangoproject.com/en/dev/ref/models/expressions/#raw-sql-expressions
Usage example:
MyModel.objects.language('en_us').filter(is_active=True).order_by_json_path('title') | [
"Orders",
"a",
"queryset",
"by",
"the",
"value",
"of",
"the",
"specified",
"json_path",
"."
] | 44a6f7a303270709b1a8877138b50ecc1e99074a | https://github.com/tatterdemalion/django-nece/blob/44a6f7a303270709b1a8877138b50ecc1e99074a/nece/managers.py#L64-L85 |
26,047 | dcramer/django-ratings | djangoratings/managers.py | VoteQuerySet.delete | def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
model_class = ContentType.objects.get(pk=content_type).model_class()
if model_class:
to_update.extend(list(model_class.objects.filter(pk__in=list(objects)[0])))
retval = super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update(commit=False)
obj.save()
return retval | python | def delete(self, *args, **kwargs):
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
model_class = ContentType.objects.get(pk=content_type).model_class()
if model_class:
to_update.extend(list(model_class.objects.filter(pk__in=list(objects)[0])))
retval = super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update(commit=False)
obj.save()
return retval | [
"def",
"delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# XXX: circular import",
"from",
"fields",
"import",
"RatingField",
"qs",
"=",
"self",
".",
"distinct",
"(",
")",
".",
"values_list",
"(",
"'content_type'",
",",
"'object_i... | Handles updating the related `votes` and `score` fields attached to the model. | [
"Handles",
"updating",
"the",
"related",
"votes",
"and",
"score",
"fields",
"attached",
"to",
"the",
"model",
"."
] | 4d00dedc920a4e32d650dc12d5f480c51fc6216c | https://github.com/dcramer/django-ratings/blob/4d00dedc920a4e32d650dc12d5f480c51fc6216c/djangoratings/managers.py#L8-L29 |
26,048 | adafruit/Adafruit_CircuitPython_Motor | adafruit_motor/servo.py | _BaseServo.set_pulse_width_range | def set_pulse_width_range(self, min_pulse=750, max_pulse=2250):
"""Change min and max pulse widths."""
self._min_duty = int((min_pulse * self._pwm_out.frequency) / 1000000 * 0xffff)
max_duty = (max_pulse * self._pwm_out.frequency) / 1000000 * 0xffff
self._duty_range = int(max_duty - self._min_duty) | python | def set_pulse_width_range(self, min_pulse=750, max_pulse=2250):
self._min_duty = int((min_pulse * self._pwm_out.frequency) / 1000000 * 0xffff)
max_duty = (max_pulse * self._pwm_out.frequency) / 1000000 * 0xffff
self._duty_range = int(max_duty - self._min_duty) | [
"def",
"set_pulse_width_range",
"(",
"self",
",",
"min_pulse",
"=",
"750",
",",
"max_pulse",
"=",
"2250",
")",
":",
"self",
".",
"_min_duty",
"=",
"int",
"(",
"(",
"min_pulse",
"*",
"self",
".",
"_pwm_out",
".",
"frequency",
")",
"/",
"1000000",
"*",
"... | Change min and max pulse widths. | [
"Change",
"min",
"and",
"max",
"pulse",
"widths",
"."
] | 98563ab65800aac6464f671c0d005df56ecaa6c6 | https://github.com/adafruit/Adafruit_CircuitPython_Motor/blob/98563ab65800aac6464f671c0d005df56ecaa6c6/adafruit_motor/servo.py#L47-L51 |
26,049 | adafruit/Adafruit_CircuitPython_Motor | adafruit_motor/stepper.py | StepperMotor.onestep | def onestep(self, *, direction=FORWARD, style=SINGLE):
"""Performs one step of a particular style. The actual rotation amount will vary by style.
`SINGLE` and `DOUBLE` will normal cause a full step rotation. `INTERLEAVE` will normally
do a half step rotation. `MICROSTEP` will perform the smallest configured step.
When step styles are mixed, subsequent `SINGLE`, `DOUBLE` or `INTERLEAVE` steps may be
less than normal in order to align to the desired style's pattern.
:param int direction: Either `FORWARD` or `BACKWARD`
:param int style: `SINGLE`, `DOUBLE`, `INTERLEAVE`"""
# Adjust current steps based on the direction and type of step.
step_size = 0
if style == MICROSTEP:
step_size = 1
else:
half_step = self._microsteps // 2
full_step = self._microsteps
# Its possible the previous steps were MICROSTEPS so first align with the interleave
# pattern.
additional_microsteps = self._current_microstep % half_step
if additional_microsteps != 0:
# We set _current_microstep directly because our step size varies depending on the
# direction.
if direction == FORWARD:
self._current_microstep += half_step - additional_microsteps
else:
self._current_microstep -= additional_microsteps
step_size = 0
elif style == INTERLEAVE:
step_size = half_step
current_interleave = self._current_microstep // half_step
if ((style == SINGLE and current_interleave % 2 == 1) or
(style == DOUBLE and current_interleave % 2 == 0)):
step_size = half_step
elif style in (SINGLE, DOUBLE):
step_size = full_step
if direction == FORWARD:
self._current_microstep += step_size
else:
self._current_microstep -= step_size
# Now that we know our target microstep we can determine how to energize the four coils.
self._update_coils(microstepping=style == MICROSTEP)
return self._current_microstep | python | def onestep(self, *, direction=FORWARD, style=SINGLE):
# Adjust current steps based on the direction and type of step.
step_size = 0
if style == MICROSTEP:
step_size = 1
else:
half_step = self._microsteps // 2
full_step = self._microsteps
# Its possible the previous steps were MICROSTEPS so first align with the interleave
# pattern.
additional_microsteps = self._current_microstep % half_step
if additional_microsteps != 0:
# We set _current_microstep directly because our step size varies depending on the
# direction.
if direction == FORWARD:
self._current_microstep += half_step - additional_microsteps
else:
self._current_microstep -= additional_microsteps
step_size = 0
elif style == INTERLEAVE:
step_size = half_step
current_interleave = self._current_microstep // half_step
if ((style == SINGLE and current_interleave % 2 == 1) or
(style == DOUBLE and current_interleave % 2 == 0)):
step_size = half_step
elif style in (SINGLE, DOUBLE):
step_size = full_step
if direction == FORWARD:
self._current_microstep += step_size
else:
self._current_microstep -= step_size
# Now that we know our target microstep we can determine how to energize the four coils.
self._update_coils(microstepping=style == MICROSTEP)
return self._current_microstep | [
"def",
"onestep",
"(",
"self",
",",
"*",
",",
"direction",
"=",
"FORWARD",
",",
"style",
"=",
"SINGLE",
")",
":",
"# Adjust current steps based on the direction and type of step.",
"step_size",
"=",
"0",
"if",
"style",
"==",
"MICROSTEP",
":",
"step_size",
"=",
"... | Performs one step of a particular style. The actual rotation amount will vary by style.
`SINGLE` and `DOUBLE` will normal cause a full step rotation. `INTERLEAVE` will normally
do a half step rotation. `MICROSTEP` will perform the smallest configured step.
When step styles are mixed, subsequent `SINGLE`, `DOUBLE` or `INTERLEAVE` steps may be
less than normal in order to align to the desired style's pattern.
:param int direction: Either `FORWARD` or `BACKWARD`
:param int style: `SINGLE`, `DOUBLE`, `INTERLEAVE` | [
"Performs",
"one",
"step",
"of",
"a",
"particular",
"style",
".",
"The",
"actual",
"rotation",
"amount",
"will",
"vary",
"by",
"style",
".",
"SINGLE",
"and",
"DOUBLE",
"will",
"normal",
"cause",
"a",
"full",
"step",
"rotation",
".",
"INTERLEAVE",
"will",
"... | 98563ab65800aac6464f671c0d005df56ecaa6c6 | https://github.com/adafruit/Adafruit_CircuitPython_Motor/blob/98563ab65800aac6464f671c0d005df56ecaa6c6/adafruit_motor/stepper.py#L116-L162 |
26,050 | OCA/openupgradelib | openupgradelib/openupgrade_merge_records.py | merge_records | def merge_records(env, model_name, record_ids, target_record_id,
field_spec=None, method='orm', delete=True,
exclude_columns=None):
"""Merge several records into the target one.
NOTE: This should be executed in end migration scripts for assuring that
all the possible relations are loaded and changed. Tested on v10/v11.
:param env: Environment variable
:param model_name: Name of the model of the records to merge
:param record_ids: List of IDS of records that are going to be merged.
:param target_record_id: ID of the record where the rest records are going
to be merge in.
:param field_spec: Dictionary with field names as keys and forced operation
to perform as values. If a field is not present here, default operation
will be performed. See _adjust_merged_values_orm method doc for all the
available operators.
:param method: Specify how to perform operations. By default or specifying
'orm', operations will be performed with ORM, maybe slower, but safer, as
related and computed fields will be recomputed on changes, and all
constraints will be checked.
:param delete: If set, the source ids will be unlinked.
:exclude_columns: list of tuples (table, column) that will be ignored.
"""
if exclude_columns is None:
exclude_columns = []
if field_spec is None:
field_spec = {}
if isinstance(record_ids, list):
record_ids = tuple(record_ids)
args0 = (env, model_name, record_ids, target_record_id)
args = args0 + (exclude_columns, )
args2 = args0 + (field_spec, )
if target_record_id in record_ids:
raise Exception("You can't put the target record in the list or "
"records to be merged.")
# Check which records to be merged exist
record_ids = env[model_name].browse(record_ids).exists().ids
if not record_ids:
return
_change_generic(*args, method=method)
if method == 'orm':
_change_many2one_refs_orm(*args)
_change_many2many_refs_orm(*args)
_change_reference_refs_orm(*args)
_change_translations_orm(*args)
# TODO: serialized fields
with env.norecompute():
_adjust_merged_values_orm(*args2)
env[model_name].recompute()
if delete:
_delete_records_orm(env, model_name, record_ids, target_record_id)
else:
_change_foreign_key_refs(*args)
_change_reference_refs_sql(*args)
_change_translations_sql(*args)
# TODO: Adjust values of the merged records through SQL
if delete:
_delete_records_sql(env, model_name, record_ids, target_record_id) | python | def merge_records(env, model_name, record_ids, target_record_id,
field_spec=None, method='orm', delete=True,
exclude_columns=None):
if exclude_columns is None:
exclude_columns = []
if field_spec is None:
field_spec = {}
if isinstance(record_ids, list):
record_ids = tuple(record_ids)
args0 = (env, model_name, record_ids, target_record_id)
args = args0 + (exclude_columns, )
args2 = args0 + (field_spec, )
if target_record_id in record_ids:
raise Exception("You can't put the target record in the list or "
"records to be merged.")
# Check which records to be merged exist
record_ids = env[model_name].browse(record_ids).exists().ids
if not record_ids:
return
_change_generic(*args, method=method)
if method == 'orm':
_change_many2one_refs_orm(*args)
_change_many2many_refs_orm(*args)
_change_reference_refs_orm(*args)
_change_translations_orm(*args)
# TODO: serialized fields
with env.norecompute():
_adjust_merged_values_orm(*args2)
env[model_name].recompute()
if delete:
_delete_records_orm(env, model_name, record_ids, target_record_id)
else:
_change_foreign_key_refs(*args)
_change_reference_refs_sql(*args)
_change_translations_sql(*args)
# TODO: Adjust values of the merged records through SQL
if delete:
_delete_records_sql(env, model_name, record_ids, target_record_id) | [
"def",
"merge_records",
"(",
"env",
",",
"model_name",
",",
"record_ids",
",",
"target_record_id",
",",
"field_spec",
"=",
"None",
",",
"method",
"=",
"'orm'",
",",
"delete",
"=",
"True",
",",
"exclude_columns",
"=",
"None",
")",
":",
"if",
"exclude_columns"... | Merge several records into the target one.
NOTE: This should be executed in end migration scripts for assuring that
all the possible relations are loaded and changed. Tested on v10/v11.
:param env: Environment variable
:param model_name: Name of the model of the records to merge
:param record_ids: List of IDS of records that are going to be merged.
:param target_record_id: ID of the record where the rest records are going
to be merge in.
:param field_spec: Dictionary with field names as keys and forced operation
to perform as values. If a field is not present here, default operation
will be performed. See _adjust_merged_values_orm method doc for all the
available operators.
:param method: Specify how to perform operations. By default or specifying
'orm', operations will be performed with ORM, maybe slower, but safer, as
related and computed fields will be recomputed on changes, and all
constraints will be checked.
:param delete: If set, the source ids will be unlinked.
:exclude_columns: list of tuples (table, column) that will be ignored. | [
"Merge",
"several",
"records",
"into",
"the",
"target",
"one",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade_merge_records.py#L465-L523 |
26,051 | OCA/openupgradelib | openupgradelib/openupgrade.py | allow_pgcodes | def allow_pgcodes(cr, *codes):
"""Context manager that will omit specified error codes.
E.g., suppose you expect a migration to produce unique constraint
violations and you want to ignore them. Then you could just do::
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.execute("INSERT INTO me (name) SELECT name FROM you")
.. warning::
**All** sentences inside this context will be rolled back if **a single
error** is raised, so the above example would insert **nothing** if a
single row violates a unique constraint.
This would ignore duplicate files but insert the others::
cr.execute("SELECT name FROM you")
for row in cr.fetchall():
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.execute("INSERT INTO me (name) VALUES (%s)", row[0])
:param *str codes:
Undefined amount of error codes found in :mod:`psycopg2.errorcodes`
that are allowed. Codes can have either 2 characters (indicating an
error class) or 5 (indicating a concrete error). Any other errors
will be raised.
"""
try:
with cr.savepoint():
with core.tools.mute_logger('odoo.sql_db'):
yield
except (ProgrammingError, IntegrityError) as error:
msg = "Code: {code}. Class: {class_}. Error: {error}.".format(
code=error.pgcode,
class_=errorcodes.lookup(error.pgcode[:2]),
error=errorcodes.lookup(error.pgcode))
if error.pgcode in codes or error.pgcode[:2] in codes:
logger.info(msg)
else:
logger.exception(msg)
raise | python | def allow_pgcodes(cr, *codes):
try:
with cr.savepoint():
with core.tools.mute_logger('odoo.sql_db'):
yield
except (ProgrammingError, IntegrityError) as error:
msg = "Code: {code}. Class: {class_}. Error: {error}.".format(
code=error.pgcode,
class_=errorcodes.lookup(error.pgcode[:2]),
error=errorcodes.lookup(error.pgcode))
if error.pgcode in codes or error.pgcode[:2] in codes:
logger.info(msg)
else:
logger.exception(msg)
raise | [
"def",
"allow_pgcodes",
"(",
"cr",
",",
"*",
"codes",
")",
":",
"try",
":",
"with",
"cr",
".",
"savepoint",
"(",
")",
":",
"with",
"core",
".",
"tools",
".",
"mute_logger",
"(",
"'odoo.sql_db'",
")",
":",
"yield",
"except",
"(",
"ProgrammingError",
","... | Context manager that will omit specified error codes.
E.g., suppose you expect a migration to produce unique constraint
violations and you want to ignore them. Then you could just do::
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.execute("INSERT INTO me (name) SELECT name FROM you")
.. warning::
**All** sentences inside this context will be rolled back if **a single
error** is raised, so the above example would insert **nothing** if a
single row violates a unique constraint.
This would ignore duplicate files but insert the others::
cr.execute("SELECT name FROM you")
for row in cr.fetchall():
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.execute("INSERT INTO me (name) VALUES (%s)", row[0])
:param *str codes:
Undefined amount of error codes found in :mod:`psycopg2.errorcodes`
that are allowed. Codes can have either 2 characters (indicating an
error class) or 5 (indicating a concrete error). Any other errors
will be raised. | [
"Context",
"manager",
"that",
"will",
"omit",
"specified",
"error",
"codes",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L180-L220 |
26,052 | OCA/openupgradelib | openupgradelib/openupgrade.py | check_values_selection_field | def check_values_selection_field(cr, table_name, field_name, allowed_values):
"""
check if the field selection 'field_name' of the table 'table_name'
has only the values 'allowed_values'.
If not return False and log an error.
If yes, return True.
.. versionadded:: 8.0
"""
res = True
cr.execute("SELECT %s, count(*) FROM %s GROUP BY %s;" %
(field_name, table_name, field_name))
for row in cr.fetchall():
if row[0] not in allowed_values:
logger.error(
"Invalid value '%s' in the table '%s' "
"for the field '%s'. (%s rows).",
row[0], table_name, field_name, row[1])
res = False
return res | python | def check_values_selection_field(cr, table_name, field_name, allowed_values):
res = True
cr.execute("SELECT %s, count(*) FROM %s GROUP BY %s;" %
(field_name, table_name, field_name))
for row in cr.fetchall():
if row[0] not in allowed_values:
logger.error(
"Invalid value '%s' in the table '%s' "
"for the field '%s'. (%s rows).",
row[0], table_name, field_name, row[1])
res = False
return res | [
"def",
"check_values_selection_field",
"(",
"cr",
",",
"table_name",
",",
"field_name",
",",
"allowed_values",
")",
":",
"res",
"=",
"True",
"cr",
".",
"execute",
"(",
"\"SELECT %s, count(*) FROM %s GROUP BY %s;\"",
"%",
"(",
"field_name",
",",
"table_name",
",",
... | check if the field selection 'field_name' of the table 'table_name'
has only the values 'allowed_values'.
If not return False and log an error.
If yes, return True.
.. versionadded:: 8.0 | [
"check",
"if",
"the",
"field",
"selection",
"field_name",
"of",
"the",
"table",
"table_name",
"has",
"only",
"the",
"values",
"allowed_values",
".",
"If",
"not",
"return",
"False",
"and",
"log",
"an",
"error",
".",
"If",
"yes",
"return",
"True",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L223-L242 |
26,053 | OCA/openupgradelib | openupgradelib/openupgrade.py | load_data | def load_data(cr, module_name, filename, idref=None, mode='init'):
"""
Load an xml, csv or yml data file from your post script. The usual case for
this is the
occurrence of newly added essential or useful data in the module that is
marked with "noupdate='1'" and without "forcecreate='1'" so that it will
not be loaded by the usual upgrade mechanism. Leaving the 'mode' argument
to its default 'init' will load the data from your migration script.
Theoretically, you could simply load a stock file from the module, but be
careful not to reinitialize any data that could have been customized.
Preferably, select only the newly added items. Copy these to a file
in your migrations directory and load that file.
Leave it to the user to actually delete existing resources that are
marked with 'noupdate' (other named items will be deleted
automatically).
:param module_name: the name of the module
:param filename: the path to the filename, relative to the module \
directory.
:param idref: optional hash with ?id mapping cache?
:param mode:
one of 'init', 'update', 'demo', 'init_no_create'.
Always use 'init' for adding new items from files that are marked with
'noupdate'. Defaults to 'init'.
'init_no_create' is a hack to load data for records which have
forcecreate=False set. As those records won't be recreated during the
update, standard Odoo would recreate the record if it was deleted,
but this will fail in cases where there are required fields to be
filled which are not contained in the data file.
"""
if idref is None:
idref = {}
logger.info('%s: loading %s' % (module_name, filename))
_, ext = os.path.splitext(filename)
pathname = os.path.join(module_name, filename)
fp = tools.file_open(pathname)
try:
if ext == '.csv':
noupdate = True
tools.convert_csv_import(
cr, module_name, pathname, fp.read(), idref, mode, noupdate)
elif ext == '.yml':
yaml_import(cr, module_name, fp, None, idref=idref, mode=mode)
elif mode == 'init_no_create':
for fp2 in _get_existing_records(cr, fp, module_name):
tools.convert_xml_import(
cr, module_name, fp2, idref, mode='init',
)
else:
tools.convert_xml_import(cr, module_name, fp, idref, mode=mode)
finally:
fp.close() | python | def load_data(cr, module_name, filename, idref=None, mode='init'):
if idref is None:
idref = {}
logger.info('%s: loading %s' % (module_name, filename))
_, ext = os.path.splitext(filename)
pathname = os.path.join(module_name, filename)
fp = tools.file_open(pathname)
try:
if ext == '.csv':
noupdate = True
tools.convert_csv_import(
cr, module_name, pathname, fp.read(), idref, mode, noupdate)
elif ext == '.yml':
yaml_import(cr, module_name, fp, None, idref=idref, mode=mode)
elif mode == 'init_no_create':
for fp2 in _get_existing_records(cr, fp, module_name):
tools.convert_xml_import(
cr, module_name, fp2, idref, mode='init',
)
else:
tools.convert_xml_import(cr, module_name, fp, idref, mode=mode)
finally:
fp.close() | [
"def",
"load_data",
"(",
"cr",
",",
"module_name",
",",
"filename",
",",
"idref",
"=",
"None",
",",
"mode",
"=",
"'init'",
")",
":",
"if",
"idref",
"is",
"None",
":",
"idref",
"=",
"{",
"}",
"logger",
".",
"info",
"(",
"'%s: loading %s'",
"%",
"(",
... | Load an xml, csv or yml data file from your post script. The usual case for
this is the
occurrence of newly added essential or useful data in the module that is
marked with "noupdate='1'" and without "forcecreate='1'" so that it will
not be loaded by the usual upgrade mechanism. Leaving the 'mode' argument
to its default 'init' will load the data from your migration script.
Theoretically, you could simply load a stock file from the module, but be
careful not to reinitialize any data that could have been customized.
Preferably, select only the newly added items. Copy these to a file
in your migrations directory and load that file.
Leave it to the user to actually delete existing resources that are
marked with 'noupdate' (other named items will be deleted
automatically).
:param module_name: the name of the module
:param filename: the path to the filename, relative to the module \
directory.
:param idref: optional hash with ?id mapping cache?
:param mode:
one of 'init', 'update', 'demo', 'init_no_create'.
Always use 'init' for adding new items from files that are marked with
'noupdate'. Defaults to 'init'.
'init_no_create' is a hack to load data for records which have
forcecreate=False set. As those records won't be recreated during the
update, standard Odoo would recreate the record if it was deleted,
but this will fail in cases where there are required fields to be
filled which are not contained in the data file. | [
"Load",
"an",
"xml",
"csv",
"or",
"yml",
"data",
"file",
"from",
"your",
"post",
"script",
".",
"The",
"usual",
"case",
"for",
"this",
"is",
"the",
"occurrence",
"of",
"newly",
"added",
"essential",
"or",
"useful",
"data",
"in",
"the",
"module",
"that",
... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L245-L300 |
26,054 | OCA/openupgradelib | openupgradelib/openupgrade.py | _get_existing_records | def _get_existing_records(cr, fp, module_name):
"""yield file like objects per 'leaf' node in the xml file that exists.
This is for not trying to create a record with partial data in case the
record was removed in the database."""
def yield_element(node, path=None):
if node.tag not in ['openerp', 'odoo', 'data']:
if node.tag == 'record':
xmlid = node.attrib['id']
if '.' not in xmlid:
module = module_name
else:
module, xmlid = xmlid.split('.', 1)
cr.execute(
'select id from ir_model_data where module=%s and name=%s',
(module, xmlid)
)
if not cr.rowcount:
return
result = StringIO(etree.tostring(path, encoding='unicode'))
result.name = None
yield result
else:
for child in node:
for value in yield_element(
child,
etree.SubElement(path, node.tag, node.attrib)
if path else etree.Element(node.tag, node.attrib)
):
yield value
return yield_element(etree.parse(fp).getroot()) | python | def _get_existing_records(cr, fp, module_name):
def yield_element(node, path=None):
if node.tag not in ['openerp', 'odoo', 'data']:
if node.tag == 'record':
xmlid = node.attrib['id']
if '.' not in xmlid:
module = module_name
else:
module, xmlid = xmlid.split('.', 1)
cr.execute(
'select id from ir_model_data where module=%s and name=%s',
(module, xmlid)
)
if not cr.rowcount:
return
result = StringIO(etree.tostring(path, encoding='unicode'))
result.name = None
yield result
else:
for child in node:
for value in yield_element(
child,
etree.SubElement(path, node.tag, node.attrib)
if path else etree.Element(node.tag, node.attrib)
):
yield value
return yield_element(etree.parse(fp).getroot()) | [
"def",
"_get_existing_records",
"(",
"cr",
",",
"fp",
",",
"module_name",
")",
":",
"def",
"yield_element",
"(",
"node",
",",
"path",
"=",
"None",
")",
":",
"if",
"node",
".",
"tag",
"not",
"in",
"[",
"'openerp'",
",",
"'odoo'",
",",
"'data'",
"]",
"... | yield file like objects per 'leaf' node in the xml file that exists.
This is for not trying to create a record with partial data in case the
record was removed in the database. | [
"yield",
"file",
"like",
"objects",
"per",
"leaf",
"node",
"in",
"the",
"xml",
"file",
"that",
"exists",
".",
"This",
"is",
"for",
"not",
"trying",
"to",
"create",
"a",
"record",
"with",
"partial",
"data",
"in",
"case",
"the",
"record",
"was",
"removed",... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L303-L332 |
26,055 | OCA/openupgradelib | openupgradelib/openupgrade.py | rename_columns | def rename_columns(cr, column_spec):
"""
Rename table columns. Typically called in the pre script.
:param column_spec: a hash with table keys, with lists of tuples as \
values. Tuples consist of (old_name, new_name). Use None for new_name \
to trigger a conversion of old_name using get_legacy_name()
"""
for table in column_spec.keys():
for (old, new) in column_spec[table]:
if new is None:
new = get_legacy_name(old)
logger.info("table %s, column %s: renaming to %s",
table, old, new)
cr.execute(
'ALTER TABLE "%s" RENAME "%s" TO "%s"' % (table, old, new,))
cr.execute('DROP INDEX IF EXISTS "%s_%s_index"' % (table, old)) | python | def rename_columns(cr, column_spec):
for table in column_spec.keys():
for (old, new) in column_spec[table]:
if new is None:
new = get_legacy_name(old)
logger.info("table %s, column %s: renaming to %s",
table, old, new)
cr.execute(
'ALTER TABLE "%s" RENAME "%s" TO "%s"' % (table, old, new,))
cr.execute('DROP INDEX IF EXISTS "%s_%s_index"' % (table, old)) | [
"def",
"rename_columns",
"(",
"cr",
",",
"column_spec",
")",
":",
"for",
"table",
"in",
"column_spec",
".",
"keys",
"(",
")",
":",
"for",
"(",
"old",
",",
"new",
")",
"in",
"column_spec",
"[",
"table",
"]",
":",
"if",
"new",
"is",
"None",
":",
"new... | Rename table columns. Typically called in the pre script.
:param column_spec: a hash with table keys, with lists of tuples as \
values. Tuples consist of (old_name, new_name). Use None for new_name \
to trigger a conversion of old_name using get_legacy_name() | [
"Rename",
"table",
"columns",
".",
"Typically",
"called",
"in",
"the",
"pre",
"script",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L378-L394 |
26,056 | OCA/openupgradelib | openupgradelib/openupgrade.py | rename_tables | def rename_tables(cr, table_spec):
"""
Rename tables. Typically called in the pre script.
This function also renames the id sequence if it exists and if it is
not modified in the same run.
:param table_spec: a list of tuples (old table name, new table name). Use \
None for new_name to trigger a conversion of old_name to the result of \
get_legacy_name()
"""
# Append id sequences
to_rename = [x[0] for x in table_spec]
for old, new in list(table_spec):
if new is None:
new = get_legacy_name(old)
if (table_exists(cr, old + '_id_seq') and
old + '_id_seq' not in to_rename):
table_spec.append((old + '_id_seq', new + '_id_seq'))
for (old, new) in table_spec:
if new is None:
new = get_legacy_name(old)
logger.info("table %s: renaming to %s",
old, new)
cr.execute('ALTER TABLE "%s" RENAME TO "%s"' % (old, new,)) | python | def rename_tables(cr, table_spec):
# Append id sequences
to_rename = [x[0] for x in table_spec]
for old, new in list(table_spec):
if new is None:
new = get_legacy_name(old)
if (table_exists(cr, old + '_id_seq') and
old + '_id_seq' not in to_rename):
table_spec.append((old + '_id_seq', new + '_id_seq'))
for (old, new) in table_spec:
if new is None:
new = get_legacy_name(old)
logger.info("table %s: renaming to %s",
old, new)
cr.execute('ALTER TABLE "%s" RENAME TO "%s"' % (old, new,)) | [
"def",
"rename_tables",
"(",
"cr",
",",
"table_spec",
")",
":",
"# Append id sequences",
"to_rename",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"table_spec",
"]",
"for",
"old",
",",
"new",
"in",
"list",
"(",
"table_spec",
")",
":",
"if",
"new",
... | Rename tables. Typically called in the pre script.
This function also renames the id sequence if it exists and if it is
not modified in the same run.
:param table_spec: a list of tuples (old table name, new table name). Use \
None for new_name to trigger a conversion of old_name to the result of \
get_legacy_name() | [
"Rename",
"tables",
".",
"Typically",
"called",
"in",
"the",
"pre",
"script",
".",
"This",
"function",
"also",
"renames",
"the",
"id",
"sequence",
"if",
"it",
"exists",
"and",
"if",
"it",
"is",
"not",
"modified",
"in",
"the",
"same",
"run",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L505-L528 |
26,057 | OCA/openupgradelib | openupgradelib/openupgrade.py | update_workflow_workitems | def update_workflow_workitems(cr, pool, ref_spec_actions):
"""Find all the workflow items from the target state to set them to
the wanted state.
When a workflow action is removed, from model, the objects whose states
are in these actions need to be set to another to be able to continue the
workflow properly.
Run in pre-migration
:param ref_spec_actions: list of tuples with couple of workflow.action's
external ids. The first id is replaced with the second.
:return: None
.. versionadded:: 7.0
"""
workflow_workitems = pool['workflow.workitem']
ir_model_data_model = pool['ir.model.data']
for (target_external_id, fallback_external_id) in ref_spec_actions:
target_activity = ir_model_data_model.get_object(
cr, SUPERUSER_ID,
target_external_id.split(".")[0],
target_external_id.split(".")[1],
)
fallback_activity = ir_model_data_model.get_object(
cr, SUPERUSER_ID,
fallback_external_id.split(".")[0],
fallback_external_id.split(".")[1],
)
ids = workflow_workitems.search(
cr, SUPERUSER_ID, [('act_id', '=', target_activity.id)]
)
if ids:
logger.info(
"Moving %d items in the removed workflow action (%s) to a "
"fallback action (%s): %s",
len(ids), target_activity.name, fallback_activity.name, ids
)
workflow_workitems.write(
cr, SUPERUSER_ID, ids, {'act_id': fallback_activity.id}
) | python | def update_workflow_workitems(cr, pool, ref_spec_actions):
workflow_workitems = pool['workflow.workitem']
ir_model_data_model = pool['ir.model.data']
for (target_external_id, fallback_external_id) in ref_spec_actions:
target_activity = ir_model_data_model.get_object(
cr, SUPERUSER_ID,
target_external_id.split(".")[0],
target_external_id.split(".")[1],
)
fallback_activity = ir_model_data_model.get_object(
cr, SUPERUSER_ID,
fallback_external_id.split(".")[0],
fallback_external_id.split(".")[1],
)
ids = workflow_workitems.search(
cr, SUPERUSER_ID, [('act_id', '=', target_activity.id)]
)
if ids:
logger.info(
"Moving %d items in the removed workflow action (%s) to a "
"fallback action (%s): %s",
len(ids), target_activity.name, fallback_activity.name, ids
)
workflow_workitems.write(
cr, SUPERUSER_ID, ids, {'act_id': fallback_activity.id}
) | [
"def",
"update_workflow_workitems",
"(",
"cr",
",",
"pool",
",",
"ref_spec_actions",
")",
":",
"workflow_workitems",
"=",
"pool",
"[",
"'workflow.workitem'",
"]",
"ir_model_data_model",
"=",
"pool",
"[",
"'ir.model.data'",
"]",
"for",
"(",
"target_external_id",
",",... | Find all the workflow items from the target state to set them to
the wanted state.
When a workflow action is removed, from model, the objects whose states
are in these actions need to be set to another to be able to continue the
workflow properly.
Run in pre-migration
:param ref_spec_actions: list of tuples with couple of workflow.action's
external ids. The first id is replaced with the second.
:return: None
.. versionadded:: 7.0 | [
"Find",
"all",
"the",
"workflow",
"items",
"from",
"the",
"target",
"state",
"to",
"set",
"them",
"to",
"the",
"wanted",
"state",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L726-L767 |
26,058 | OCA/openupgradelib | openupgradelib/openupgrade.py | logged_query | def logged_query(cr, query, args=None, skip_no_result=False):
"""
Logs query and affected rows at level DEBUG.
:param query: a query string suitable to pass to cursor.execute()
:param args: a list, tuple or dictionary passed as substitution values
to cursor.execute().
:param skip_no_result: If True, then logging details are only shown
if there are affected records.
"""
if args is None:
args = ()
args = tuple(args) if type(args) == list else args
try:
cr.execute(query, args)
except (ProgrammingError, IntegrityError):
logger.error('Error running %s' % cr.mogrify(query, args))
raise
if not skip_no_result or cr.rowcount:
logger.debug('Running %s', query % args)
logger.debug('%s rows affected', cr.rowcount)
return cr.rowcount | python | def logged_query(cr, query, args=None, skip_no_result=False):
if args is None:
args = ()
args = tuple(args) if type(args) == list else args
try:
cr.execute(query, args)
except (ProgrammingError, IntegrityError):
logger.error('Error running %s' % cr.mogrify(query, args))
raise
if not skip_no_result or cr.rowcount:
logger.debug('Running %s', query % args)
logger.debug('%s rows affected', cr.rowcount)
return cr.rowcount | [
"def",
"logged_query",
"(",
"cr",
",",
"query",
",",
"args",
"=",
"None",
",",
"skip_no_result",
"=",
"False",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"(",
")",
"args",
"=",
"tuple",
"(",
"args",
")",
"if",
"type",
"(",
"args",
")... | Logs query and affected rows at level DEBUG.
:param query: a query string suitable to pass to cursor.execute()
:param args: a list, tuple or dictionary passed as substitution values
to cursor.execute().
:param skip_no_result: If True, then logging details are only shown
if there are affected records. | [
"Logs",
"query",
"and",
"affected",
"rows",
"at",
"level",
"DEBUG",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L959-L980 |
26,059 | OCA/openupgradelib | openupgradelib/openupgrade.py | update_module_names | def update_module_names(cr, namespec, merge_modules=False):
"""Deal with changed module names, making all the needed changes on the
related tables, like XML-IDs, translations, and so on.
:param namespec: list of tuples of (old name, new name)
:param merge_modules: Specify if the operation should be a merge instead
of just a renaming.
"""
for (old_name, new_name) in namespec:
if merge_modules:
# Delete meta entries, that will avoid the entry removal
# They will be recreated by the new module anyhow.
query = "SELECT id FROM ir_module_module WHERE name = %s"
cr.execute(query, [old_name])
row = cr.fetchone()
if row:
old_id = row[0]
query = "DELETE FROM ir_model_constraint WHERE module = %s"
logged_query(cr, query, [old_id])
query = "DELETE FROM ir_model_relation WHERE module = %s"
logged_query(cr, query, [old_id])
else:
query = "UPDATE ir_module_module SET name = %s WHERE name = %s"
logged_query(cr, query, (new_name, old_name))
query = ("UPDATE ir_model_data SET name = %s "
"WHERE name = %s AND module = 'base' AND "
"model='ir.module.module' ")
logged_query(cr, query,
("module_%s" % new_name, "module_%s" % old_name))
# The subselect allows to avoid duplicated XML-IDs
query = ("UPDATE ir_model_data SET module = %s "
"WHERE module = %s AND name NOT IN "
"(SELECT name FROM ir_model_data WHERE module = %s)")
logged_query(cr, query, (new_name, old_name, new_name))
# Rename the remaining occurrences for let Odoo's update process
# to auto-remove related resources
query = ("UPDATE ir_model_data "
"SET name = name || '_openupgrade_' || id, "
"module = %s "
"WHERE module = %s")
logged_query(cr, query, (new_name, old_name))
query = ("UPDATE ir_module_module_dependency SET name = %s "
"WHERE name = %s")
logged_query(cr, query, (new_name, old_name))
if version_info[0] > 7:
query = ("UPDATE ir_translation SET module = %s "
"WHERE module = %s")
logged_query(cr, query, (new_name, old_name))
if merge_modules:
# Conserve old_name's state if new_name is uninstalled
logged_query(
cr,
"UPDATE ir_module_module m1 SET state=m2.state "
"FROM ir_module_module m2 WHERE m1.name=%s AND "
"m2.name=%s AND m1.state='uninstalled'",
(new_name, old_name),
)
query = "DELETE FROM ir_module_module WHERE name = %s"
logged_query(cr, query, [old_name])
logged_query(
cr,
"DELETE FROM ir_model_data WHERE module = 'base' "
"AND model='ir.module.module' AND name = %s",
('module_%s' % old_name,),
) | python | def update_module_names(cr, namespec, merge_modules=False):
for (old_name, new_name) in namespec:
if merge_modules:
# Delete meta entries, that will avoid the entry removal
# They will be recreated by the new module anyhow.
query = "SELECT id FROM ir_module_module WHERE name = %s"
cr.execute(query, [old_name])
row = cr.fetchone()
if row:
old_id = row[0]
query = "DELETE FROM ir_model_constraint WHERE module = %s"
logged_query(cr, query, [old_id])
query = "DELETE FROM ir_model_relation WHERE module = %s"
logged_query(cr, query, [old_id])
else:
query = "UPDATE ir_module_module SET name = %s WHERE name = %s"
logged_query(cr, query, (new_name, old_name))
query = ("UPDATE ir_model_data SET name = %s "
"WHERE name = %s AND module = 'base' AND "
"model='ir.module.module' ")
logged_query(cr, query,
("module_%s" % new_name, "module_%s" % old_name))
# The subselect allows to avoid duplicated XML-IDs
query = ("UPDATE ir_model_data SET module = %s "
"WHERE module = %s AND name NOT IN "
"(SELECT name FROM ir_model_data WHERE module = %s)")
logged_query(cr, query, (new_name, old_name, new_name))
# Rename the remaining occurrences for let Odoo's update process
# to auto-remove related resources
query = ("UPDATE ir_model_data "
"SET name = name || '_openupgrade_' || id, "
"module = %s "
"WHERE module = %s")
logged_query(cr, query, (new_name, old_name))
query = ("UPDATE ir_module_module_dependency SET name = %s "
"WHERE name = %s")
logged_query(cr, query, (new_name, old_name))
if version_info[0] > 7:
query = ("UPDATE ir_translation SET module = %s "
"WHERE module = %s")
logged_query(cr, query, (new_name, old_name))
if merge_modules:
# Conserve old_name's state if new_name is uninstalled
logged_query(
cr,
"UPDATE ir_module_module m1 SET state=m2.state "
"FROM ir_module_module m2 WHERE m1.name=%s AND "
"m2.name=%s AND m1.state='uninstalled'",
(new_name, old_name),
)
query = "DELETE FROM ir_module_module WHERE name = %s"
logged_query(cr, query, [old_name])
logged_query(
cr,
"DELETE FROM ir_model_data WHERE module = 'base' "
"AND model='ir.module.module' AND name = %s",
('module_%s' % old_name,),
) | [
"def",
"update_module_names",
"(",
"cr",
",",
"namespec",
",",
"merge_modules",
"=",
"False",
")",
":",
"for",
"(",
"old_name",
",",
"new_name",
")",
"in",
"namespec",
":",
"if",
"merge_modules",
":",
"# Delete meta entries, that will avoid the entry removal",
"# Th... | Deal with changed module names, making all the needed changes on the
related tables, like XML-IDs, translations, and so on.
:param namespec: list of tuples of (old name, new name)
:param merge_modules: Specify if the operation should be a merge instead
of just a renaming. | [
"Deal",
"with",
"changed",
"module",
"names",
"making",
"all",
"the",
"needed",
"changes",
"on",
"the",
"related",
"tables",
"like",
"XML",
"-",
"IDs",
"translations",
"and",
"so",
"on",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L983-L1047 |
26,060 | OCA/openupgradelib | openupgradelib/openupgrade.py | add_ir_model_fields | def add_ir_model_fields(cr, columnspec):
"""
Typically, new columns on ir_model_fields need to be added in a very
early stage in the upgrade process of the base module, in raw sql
as they need to be in place before any model gets initialized.
Do not use for fields with additional SQL constraints, such as a
reference to another table or the cascade constraint, but craft your
own statement taking them into account.
:param columnspec: tuple of (column name, column type)
"""
for column in columnspec:
query = 'ALTER TABLE ir_model_fields ADD COLUMN %s %s' % (
column)
logged_query(cr, query, []) | python | def add_ir_model_fields(cr, columnspec):
for column in columnspec:
query = 'ALTER TABLE ir_model_fields ADD COLUMN %s %s' % (
column)
logged_query(cr, query, []) | [
"def",
"add_ir_model_fields",
"(",
"cr",
",",
"columnspec",
")",
":",
"for",
"column",
"in",
"columnspec",
":",
"query",
"=",
"'ALTER TABLE ir_model_fields ADD COLUMN %s %s'",
"%",
"(",
"column",
")",
"logged_query",
"(",
"cr",
",",
"query",
",",
"[",
"]",
")"... | Typically, new columns on ir_model_fields need to be added in a very
early stage in the upgrade process of the base module, in raw sql
as they need to be in place before any model gets initialized.
Do not use for fields with additional SQL constraints, such as a
reference to another table or the cascade constraint, but craft your
own statement taking them into account.
:param columnspec: tuple of (column name, column type) | [
"Typically",
"new",
"columns",
"on",
"ir_model_fields",
"need",
"to",
"be",
"added",
"in",
"a",
"very",
"early",
"stage",
"in",
"the",
"upgrade",
"process",
"of",
"the",
"base",
"module",
"in",
"raw",
"sql",
"as",
"they",
"need",
"to",
"be",
"in",
"place... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1050-L1064 |
26,061 | OCA/openupgradelib | openupgradelib/openupgrade.py | m2o_to_m2m | def m2o_to_m2m(cr, model, table, field, source_field):
"""
Recreate relations in many2many fields that were formerly
many2one fields. Use rename_columns in your pre-migrate
script to retain the column's old value, then call m2o_to_m2m
in your post-migrate script.
:param model: The target model registry object
:param table: The source table
:param field: The field name of the target model
:param source_field: the many2one column on the source table.
.. versionadded:: 7.0
.. deprecated:: 8.0
Use :func:`m2o_to_x2m` instead.
"""
return m2o_to_x2m(cr, model, table, field, source_field) | python | def m2o_to_m2m(cr, model, table, field, source_field):
return m2o_to_x2m(cr, model, table, field, source_field) | [
"def",
"m2o_to_m2m",
"(",
"cr",
",",
"model",
",",
"table",
",",
"field",
",",
"source_field",
")",
":",
"return",
"m2o_to_x2m",
"(",
"cr",
",",
"model",
",",
"table",
",",
"field",
",",
"source_field",
")"
] | Recreate relations in many2many fields that were formerly
many2one fields. Use rename_columns in your pre-migrate
script to retain the column's old value, then call m2o_to_m2m
in your post-migrate script.
:param model: The target model registry object
:param table: The source table
:param field: The field name of the target model
:param source_field: the many2one column on the source table.
.. versionadded:: 7.0
.. deprecated:: 8.0
Use :func:`m2o_to_x2m` instead. | [
"Recreate",
"relations",
"in",
"many2many",
"fields",
"that",
"were",
"formerly",
"many2one",
"fields",
".",
"Use",
"rename_columns",
"in",
"your",
"pre",
"-",
"migrate",
"script",
"to",
"retain",
"the",
"column",
"s",
"old",
"value",
"then",
"call",
"m2o_to_m... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1154-L1170 |
26,062 | OCA/openupgradelib | openupgradelib/openupgrade.py | message | def message(cr, module, table, column,
message, *args, **kwargs):
"""
Log handler for non-critical notifications about the upgrade.
To be extended with logging to a table for reporting purposes.
:param module: the module name that the message concerns
:param table: the model that this message concerns (may be False, \
but preferably not if 'column' is defined)
:param column: the column that this message concerns (may be False)
.. versionadded:: 7.0
"""
argslist = list(args or [])
prefix = ': '
if column:
argslist.insert(0, column)
prefix = ', column %s' + prefix
if table:
argslist.insert(0, table)
prefix = ', table %s' + prefix
argslist.insert(0, module)
prefix = 'Module %s' + prefix
logger.warn(prefix + message, *argslist, **kwargs) | python | def message(cr, module, table, column,
message, *args, **kwargs):
argslist = list(args or [])
prefix = ': '
if column:
argslist.insert(0, column)
prefix = ', column %s' + prefix
if table:
argslist.insert(0, table)
prefix = ', table %s' + prefix
argslist.insert(0, module)
prefix = 'Module %s' + prefix
logger.warn(prefix + message, *argslist, **kwargs) | [
"def",
"message",
"(",
"cr",
",",
"module",
",",
"table",
",",
"column",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"argslist",
"=",
"list",
"(",
"args",
"or",
"[",
"]",
")",
"prefix",
"=",
"': '",
"if",
"column",
":",
... | Log handler for non-critical notifications about the upgrade.
To be extended with logging to a table for reporting purposes.
:param module: the module name that the message concerns
:param table: the model that this message concerns (may be False, \
but preferably not if 'column' is defined)
:param column: the column that this message concerns (may be False)
.. versionadded:: 7.0 | [
"Log",
"handler",
"for",
"non",
"-",
"critical",
"notifications",
"about",
"the",
"upgrade",
".",
"To",
"be",
"extended",
"with",
"logging",
"to",
"a",
"table",
"for",
"reporting",
"purposes",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1271-L1295 |
26,063 | OCA/openupgradelib | openupgradelib/openupgrade.py | reactivate_workflow_transitions | def reactivate_workflow_transitions(cr, transition_conditions):
"""
Reactivate workflow transition previously deactivated by
deactivate_workflow_transitions.
:param transition_conditions: a dictionary returned by \
deactivate_workflow_transitions
.. versionadded:: 7.0
.. deprecated:: 11.0
Workflows were removed from Odoo as of version 11.0
"""
for transition_id, condition in transition_conditions.iteritems():
cr.execute(
'update wkf_transition set condition = %s where id = %s',
(condition, transition_id)) | python | def reactivate_workflow_transitions(cr, transition_conditions):
for transition_id, condition in transition_conditions.iteritems():
cr.execute(
'update wkf_transition set condition = %s where id = %s',
(condition, transition_id)) | [
"def",
"reactivate_workflow_transitions",
"(",
"cr",
",",
"transition_conditions",
")",
":",
"for",
"transition_id",
",",
"condition",
"in",
"transition_conditions",
".",
"iteritems",
"(",
")",
":",
"cr",
".",
"execute",
"(",
"'update wkf_transition set condition = %s w... | Reactivate workflow transition previously deactivated by
deactivate_workflow_transitions.
:param transition_conditions: a dictionary returned by \
deactivate_workflow_transitions
.. versionadded:: 7.0
.. deprecated:: 11.0
Workflows were removed from Odoo as of version 11.0 | [
"Reactivate",
"workflow",
"transition",
"previously",
"deactivated",
"by",
"deactivate_workflow_transitions",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1342-L1357 |
26,064 | OCA/openupgradelib | openupgradelib/openupgrade.py | convert_field_to_html | def convert_field_to_html(cr, table, field_name, html_field_name):
"""
Convert field value to HTML value.
.. versionadded:: 7.0
"""
if version_info[0] < 7:
logger.error("You cannot use this method in an OpenUpgrade version "
"prior to 7.0.")
return
cr.execute(
"SELECT id, %(field)s FROM %(table)s WHERE %(field)s IS NOT NULL" % {
'field': field_name,
'table': table,
}
)
for row in cr.fetchall():
logged_query(
cr, "UPDATE %(table)s SET %(field)s = %%s WHERE id = %%s" % {
'field': html_field_name,
'table': table,
}, (plaintext2html(row[1]), row[0])
) | python | def convert_field_to_html(cr, table, field_name, html_field_name):
if version_info[0] < 7:
logger.error("You cannot use this method in an OpenUpgrade version "
"prior to 7.0.")
return
cr.execute(
"SELECT id, %(field)s FROM %(table)s WHERE %(field)s IS NOT NULL" % {
'field': field_name,
'table': table,
}
)
for row in cr.fetchall():
logged_query(
cr, "UPDATE %(table)s SET %(field)s = %%s WHERE id = %%s" % {
'field': html_field_name,
'table': table,
}, (plaintext2html(row[1]), row[0])
) | [
"def",
"convert_field_to_html",
"(",
"cr",
",",
"table",
",",
"field_name",
",",
"html_field_name",
")",
":",
"if",
"version_info",
"[",
"0",
"]",
"<",
"7",
":",
"logger",
".",
"error",
"(",
"\"You cannot use this method in an OpenUpgrade version \"",
"\"prior to 7.... | Convert field value to HTML value.
.. versionadded:: 7.0 | [
"Convert",
"field",
"value",
"to",
"HTML",
"value",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1623-L1645 |
26,065 | OCA/openupgradelib | openupgradelib/openupgrade.py | lift_constraints | def lift_constraints(cr, table, column):
"""Lift all constraints on column in table.
Typically, you use this in a pre-migrate script where you adapt references
for many2one fields with changed target objects.
If everything went right, the constraints will be recreated"""
cr.execute(
'select relname, array_agg(conname) from '
'(select t1.relname, c.conname '
'from pg_constraint c '
'join pg_attribute a '
'on c.confrelid=a.attrelid and a.attnum=any(c.conkey) '
'join pg_class t on t.oid=a.attrelid '
'join pg_class t1 on t1.oid=c.conrelid '
'where t.relname=%(table)s and attname=%(column)s '
'union select t.relname, c.conname '
'from pg_constraint c '
'join pg_attribute a '
'on c.conrelid=a.attrelid and a.attnum=any(c.conkey) '
'join pg_class t on t.oid=a.attrelid '
'where relname=%(table)s and attname=%(column)s) in_out '
'group by relname',
{
'table': table,
'column': column,
})
for table, constraints in cr.fetchall():
cr.execute(
'alter table %s drop constraint %s',
(AsIs(table), AsIs(', drop constraint '.join(constraints)))
) | python | def lift_constraints(cr, table, column):
cr.execute(
'select relname, array_agg(conname) from '
'(select t1.relname, c.conname '
'from pg_constraint c '
'join pg_attribute a '
'on c.confrelid=a.attrelid and a.attnum=any(c.conkey) '
'join pg_class t on t.oid=a.attrelid '
'join pg_class t1 on t1.oid=c.conrelid '
'where t.relname=%(table)s and attname=%(column)s '
'union select t.relname, c.conname '
'from pg_constraint c '
'join pg_attribute a '
'on c.conrelid=a.attrelid and a.attnum=any(c.conkey) '
'join pg_class t on t.oid=a.attrelid '
'where relname=%(table)s and attname=%(column)s) in_out '
'group by relname',
{
'table': table,
'column': column,
})
for table, constraints in cr.fetchall():
cr.execute(
'alter table %s drop constraint %s',
(AsIs(table), AsIs(', drop constraint '.join(constraints)))
) | [
"def",
"lift_constraints",
"(",
"cr",
",",
"table",
",",
"column",
")",
":",
"cr",
".",
"execute",
"(",
"'select relname, array_agg(conname) from '",
"'(select t1.relname, c.conname '",
"'from pg_constraint c '",
"'join pg_attribute a '",
"'on c.confrelid=a.attrelid and a.attnum=... | Lift all constraints on column in table.
Typically, you use this in a pre-migrate script where you adapt references
for many2one fields with changed target objects.
If everything went right, the constraints will be recreated | [
"Lift",
"all",
"constraints",
"on",
"column",
"in",
"table",
".",
"Typically",
"you",
"use",
"this",
"in",
"a",
"pre",
"-",
"migrate",
"script",
"where",
"you",
"adapt",
"references",
"for",
"many2one",
"fields",
"with",
"changed",
"target",
"objects",
".",
... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1704-L1733 |
26,066 | OCA/openupgradelib | openupgradelib/openupgrade.py | savepoint | def savepoint(cr):
"""return a context manager wrapping postgres savepoints"""
if hasattr(cr, 'savepoint'):
with cr.savepoint():
yield
else:
name = uuid.uuid1().hex
cr.execute('SAVEPOINT "%s"' % name)
try:
yield
cr.execute('RELEASE SAVEPOINT "%s"' % name)
except:
cr.execute('ROLLBACK TO SAVEPOINT "%s"' % name) | python | def savepoint(cr):
if hasattr(cr, 'savepoint'):
with cr.savepoint():
yield
else:
name = uuid.uuid1().hex
cr.execute('SAVEPOINT "%s"' % name)
try:
yield
cr.execute('RELEASE SAVEPOINT "%s"' % name)
except:
cr.execute('ROLLBACK TO SAVEPOINT "%s"' % name) | [
"def",
"savepoint",
"(",
"cr",
")",
":",
"if",
"hasattr",
"(",
"cr",
",",
"'savepoint'",
")",
":",
"with",
"cr",
".",
"savepoint",
"(",
")",
":",
"yield",
"else",
":",
"name",
"=",
"uuid",
".",
"uuid1",
"(",
")",
".",
"hex",
"cr",
".",
"execute",... | return a context manager wrapping postgres savepoints | [
"return",
"a",
"context",
"manager",
"wrapping",
"postgres",
"savepoints"
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1737-L1749 |
26,067 | OCA/openupgradelib | openupgradelib/openupgrade.py | rename_property | def rename_property(cr, model, old_name, new_name):
"""Rename property old_name owned by model to new_name. This should happen
in a pre-migration script."""
cr.execute(
"update ir_model_fields f set name=%s "
"from ir_model m "
"where m.id=f.model_id and m.model=%s and f.name=%s "
"returning f.id",
(new_name, model, old_name))
field_ids = tuple(i for i, in cr.fetchall())
cr.execute(
"update ir_model_data set name=%s where model='ir.model.fields' and "
"res_id in %s",
('%s,%s' % (model, new_name), field_ids))
cr.execute(
"update ir_property set name=%s where fields_id in %s",
(new_name, field_ids)) | python | def rename_property(cr, model, old_name, new_name):
cr.execute(
"update ir_model_fields f set name=%s "
"from ir_model m "
"where m.id=f.model_id and m.model=%s and f.name=%s "
"returning f.id",
(new_name, model, old_name))
field_ids = tuple(i for i, in cr.fetchall())
cr.execute(
"update ir_model_data set name=%s where model='ir.model.fields' and "
"res_id in %s",
('%s,%s' % (model, new_name), field_ids))
cr.execute(
"update ir_property set name=%s where fields_id in %s",
(new_name, field_ids)) | [
"def",
"rename_property",
"(",
"cr",
",",
"model",
",",
"old_name",
",",
"new_name",
")",
":",
"cr",
".",
"execute",
"(",
"\"update ir_model_fields f set name=%s \"",
"\"from ir_model m \"",
"\"where m.id=f.model_id and m.model=%s and f.name=%s \"",
"\"returning f.id\"",
",",... | Rename property old_name owned by model to new_name. This should happen
in a pre-migration script. | [
"Rename",
"property",
"old_name",
"owned",
"by",
"model",
"to",
"new_name",
".",
"This",
"should",
"happen",
"in",
"a",
"pre",
"-",
"migration",
"script",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1752-L1768 |
26,068 | OCA/openupgradelib | openupgradelib/openupgrade.py | delete_records_safely_by_xml_id | def delete_records_safely_by_xml_id(env, xml_ids):
"""This removes in the safest possible way the records whose XML-IDs are
passed as argument.
:param xml_ids: List of XML-ID string identifiers of the records to remove.
"""
for xml_id in xml_ids:
logger.debug('Deleting record for XML-ID %s', xml_id)
try:
with env.cr.savepoint():
env.ref(xml_id).exists().unlink()
except Exception as e:
logger.error('Error deleting XML-ID %s: %s', xml_id, repr(e)) | python | def delete_records_safely_by_xml_id(env, xml_ids):
for xml_id in xml_ids:
logger.debug('Deleting record for XML-ID %s', xml_id)
try:
with env.cr.savepoint():
env.ref(xml_id).exists().unlink()
except Exception as e:
logger.error('Error deleting XML-ID %s: %s', xml_id, repr(e)) | [
"def",
"delete_records_safely_by_xml_id",
"(",
"env",
",",
"xml_ids",
")",
":",
"for",
"xml_id",
"in",
"xml_ids",
":",
"logger",
".",
"debug",
"(",
"'Deleting record for XML-ID %s'",
",",
"xml_id",
")",
"try",
":",
"with",
"env",
".",
"cr",
".",
"savepoint",
... | This removes in the safest possible way the records whose XML-IDs are
passed as argument.
:param xml_ids: List of XML-ID string identifiers of the records to remove. | [
"This",
"removes",
"in",
"the",
"safest",
"possible",
"way",
"the",
"records",
"whose",
"XML",
"-",
"IDs",
"are",
"passed",
"as",
"argument",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L2034-L2046 |
26,069 | OCA/openupgradelib | openupgradelib/openupgrade.py | chunked | def chunked(records, single=True):
""" Memory and performance friendly method to iterate over a potentially
large number of records. Yields either a whole chunk or a single record
at the time. Don't nest calls to this method. """
if version_info[0] > 10:
invalidate = records.env.cache.invalidate
elif version_info[0] > 7:
invalidate = records.env.invalidate_all
else:
raise Exception('Not supported Odoo version for this method.')
size = core.models.PREFETCH_MAX
model = records._name
ids = records.with_context(prefetch_fields=False).ids
for i in range(0, len(ids), size):
invalidate()
chunk = records.env[model].browse(ids[i:i + size])
if single:
for record in chunk:
yield record
continue
yield chunk | python | def chunked(records, single=True):
if version_info[0] > 10:
invalidate = records.env.cache.invalidate
elif version_info[0] > 7:
invalidate = records.env.invalidate_all
else:
raise Exception('Not supported Odoo version for this method.')
size = core.models.PREFETCH_MAX
model = records._name
ids = records.with_context(prefetch_fields=False).ids
for i in range(0, len(ids), size):
invalidate()
chunk = records.env[model].browse(ids[i:i + size])
if single:
for record in chunk:
yield record
continue
yield chunk | [
"def",
"chunked",
"(",
"records",
",",
"single",
"=",
"True",
")",
":",
"if",
"version_info",
"[",
"0",
"]",
">",
"10",
":",
"invalidate",
"=",
"records",
".",
"env",
".",
"cache",
".",
"invalidate",
"elif",
"version_info",
"[",
"0",
"]",
">",
"7",
... | Memory and performance friendly method to iterate over a potentially
large number of records. Yields either a whole chunk or a single record
at the time. Don't nest calls to this method. | [
"Memory",
"and",
"performance",
"friendly",
"method",
"to",
"iterate",
"over",
"a",
"potentially",
"large",
"number",
"of",
"records",
".",
"Yields",
"either",
"a",
"whole",
"chunk",
"or",
"a",
"single",
"record",
"at",
"the",
"time",
".",
"Don",
"t",
"nes... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L2049-L2069 |
26,070 | OCA/openupgradelib | openupgradelib/openupgrade_80.py | get_last_post_for_model | def get_last_post_for_model(cr, uid, ids, model_pool):
"""
Given a set of ids and a model pool, return a dict of each object ids with
their latest message date as a value.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param ids: ids of the model in question to retrieve ids
:param model_pool: orm model pool, assumed to be from pool.get()
:return: a dict with ids as keys and with dates as values
"""
if type(ids) is not list:
ids = [ids]
res = {}
for obj in model_pool.browse(cr, uid, ids):
message_ids = obj.message_ids
if message_ids:
res[obj.id] = sorted(
message_ids, key=lambda x: x.date, reverse=True)[0].date
else:
res[obj.id] = False
return res | python | def get_last_post_for_model(cr, uid, ids, model_pool):
if type(ids) is not list:
ids = [ids]
res = {}
for obj in model_pool.browse(cr, uid, ids):
message_ids = obj.message_ids
if message_ids:
res[obj.id] = sorted(
message_ids, key=lambda x: x.date, reverse=True)[0].date
else:
res[obj.id] = False
return res | [
"def",
"get_last_post_for_model",
"(",
"cr",
",",
"uid",
",",
"ids",
",",
"model_pool",
")",
":",
"if",
"type",
"(",
"ids",
")",
"is",
"not",
"list",
":",
"ids",
"=",
"[",
"ids",
"]",
"res",
"=",
"{",
"}",
"for",
"obj",
"in",
"model_pool",
".",
"... | Given a set of ids and a model pool, return a dict of each object ids with
their latest message date as a value.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param ids: ids of the model in question to retrieve ids
:param model_pool: orm model pool, assumed to be from pool.get()
:return: a dict with ids as keys and with dates as values | [
"Given",
"a",
"set",
"of",
"ids",
"and",
"a",
"model",
"pool",
"return",
"a",
"dict",
"of",
"each",
"object",
"ids",
"with",
"their",
"latest",
"message",
"date",
"as",
"a",
"value",
".",
"To",
"be",
"called",
"in",
"post",
"-",
"migration",
"scripts"
... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade_80.py#L34-L56 |
26,071 | OCA/openupgradelib | openupgradelib/openupgrade_80.py | set_message_last_post | def set_message_last_post(cr, uid, pool, models):
"""
Given a list of models, set their 'message_last_post' fields to an
estimated last post datetime.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param pool: orm pool, assumed to be openerp.pooler.get_pool(cr.dbname)
:param models: a list of model names for which 'message_last_post' needs \
to be filled
:return:
"""
if type(models) is not list:
models = [models]
for model in models:
model_pool = pool[model]
cr.execute(
"UPDATE {table} "
"SET message_last_post=(SELECT max(mm.date) "
"FROM mail_message mm "
"WHERE mm.model=%s "
"AND mm.date IS NOT NULL "
"AND mm.res_id={table}.id)".format(
table=model_pool._table), (model,)
) | python | def set_message_last_post(cr, uid, pool, models):
if type(models) is not list:
models = [models]
for model in models:
model_pool = pool[model]
cr.execute(
"UPDATE {table} "
"SET message_last_post=(SELECT max(mm.date) "
"FROM mail_message mm "
"WHERE mm.model=%s "
"AND mm.date IS NOT NULL "
"AND mm.res_id={table}.id)".format(
table=model_pool._table), (model,)
) | [
"def",
"set_message_last_post",
"(",
"cr",
",",
"uid",
",",
"pool",
",",
"models",
")",
":",
"if",
"type",
"(",
"models",
")",
"is",
"not",
"list",
":",
"models",
"=",
"[",
"models",
"]",
"for",
"model",
"in",
"models",
":",
"model_pool",
"=",
"pool"... | Given a list of models, set their 'message_last_post' fields to an
estimated last post datetime.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param pool: orm pool, assumed to be openerp.pooler.get_pool(cr.dbname)
:param models: a list of model names for which 'message_last_post' needs \
to be filled
:return: | [
"Given",
"a",
"list",
"of",
"models",
"set",
"their",
"message_last_post",
"fields",
"to",
"an",
"estimated",
"last",
"post",
"datetime",
".",
"To",
"be",
"called",
"in",
"post",
"-",
"migration",
"scripts"
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade_80.py#L59-L84 |
26,072 | OCA/openupgradelib | openupgradelib/openupgrade_tools.py | column_exists | def column_exists(cr, table, column):
""" Check whether a certain column exists """
cr.execute(
'SELECT count(attname) FROM pg_attribute '
'WHERE attrelid = '
'( SELECT oid FROM pg_class WHERE relname = %s ) '
'AND attname = %s',
(table, column))
return cr.fetchone()[0] == 1 | python | def column_exists(cr, table, column):
cr.execute(
'SELECT count(attname) FROM pg_attribute '
'WHERE attrelid = '
'( SELECT oid FROM pg_class WHERE relname = %s ) '
'AND attname = %s',
(table, column))
return cr.fetchone()[0] == 1 | [
"def",
"column_exists",
"(",
"cr",
",",
"table",
",",
"column",
")",
":",
"cr",
".",
"execute",
"(",
"'SELECT count(attname) FROM pg_attribute '",
"'WHERE attrelid = '",
"'( SELECT oid FROM pg_class WHERE relname = %s ) '",
"'AND attname = %s'",
",",
"(",
"table",
",",
"c... | Check whether a certain column exists | [
"Check",
"whether",
"a",
"certain",
"column",
"exists"
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade_tools.py#L32-L40 |
26,073 | crossbario/txaio | txaio/aio.py | start_logging | def start_logging(out=_stdout, level='info'):
"""
Begin logging.
:param out: if provided, a file-like object to log to. By default, this is
stdout.
:param level: the maximum log-level to emit (a string)
"""
global _log_level, _loggers, _started_logging
if level not in log_levels:
raise RuntimeError(
"Invalid log level '{0}'; valid are: {1}".format(
level, ', '.join(log_levels)
)
)
if _started_logging:
return
_started_logging = True
_log_level = level
handler = _TxaioFileHandler(out)
logging.getLogger().addHandler(handler)
# note: Don't need to call basicConfig() or similar, because we've
# now added at least one handler to the root logger
logging.raiseExceptions = True # FIXME
level_to_stdlib = {
'critical': logging.CRITICAL,
'error': logging.ERROR,
'warn': logging.WARNING,
'info': logging.INFO,
'debug': logging.DEBUG,
'trace': logging.DEBUG,
}
logging.getLogger().setLevel(level_to_stdlib[level])
# make sure any loggers we created before now have their log-level
# set (any created after now will get it from _log_level
for logger in _loggers:
logger._set_log_level(level) | python | def start_logging(out=_stdout, level='info'):
global _log_level, _loggers, _started_logging
if level not in log_levels:
raise RuntimeError(
"Invalid log level '{0}'; valid are: {1}".format(
level, ', '.join(log_levels)
)
)
if _started_logging:
return
_started_logging = True
_log_level = level
handler = _TxaioFileHandler(out)
logging.getLogger().addHandler(handler)
# note: Don't need to call basicConfig() or similar, because we've
# now added at least one handler to the root logger
logging.raiseExceptions = True # FIXME
level_to_stdlib = {
'critical': logging.CRITICAL,
'error': logging.ERROR,
'warn': logging.WARNING,
'info': logging.INFO,
'debug': logging.DEBUG,
'trace': logging.DEBUG,
}
logging.getLogger().setLevel(level_to_stdlib[level])
# make sure any loggers we created before now have their log-level
# set (any created after now will get it from _log_level
for logger in _loggers:
logger._set_log_level(level) | [
"def",
"start_logging",
"(",
"out",
"=",
"_stdout",
",",
"level",
"=",
"'info'",
")",
":",
"global",
"_log_level",
",",
"_loggers",
",",
"_started_logging",
"if",
"level",
"not",
"in",
"log_levels",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid log level '{0}'; ... | Begin logging.
:param out: if provided, a file-like object to log to. By default, this is
stdout.
:param level: the maximum log-level to emit (a string) | [
"Begin",
"logging",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/aio.py#L283-L322 |
26,074 | crossbario/txaio | txaio/aio.py | _AsyncioApi.create_failure | def create_failure(self, exception=None):
"""
This returns an object implementing IFailedFuture.
If exception is None (the default) we MUST be called within an
"except" block (such that sys.exc_info() returns useful
information).
"""
if exception:
return FailedFuture(type(exception), exception, None)
return FailedFuture(*sys.exc_info()) | python | def create_failure(self, exception=None):
if exception:
return FailedFuture(type(exception), exception, None)
return FailedFuture(*sys.exc_info()) | [
"def",
"create_failure",
"(",
"self",
",",
"exception",
"=",
"None",
")",
":",
"if",
"exception",
":",
"return",
"FailedFuture",
"(",
"type",
"(",
"exception",
")",
",",
"exception",
",",
"None",
")",
"return",
"FailedFuture",
"(",
"*",
"sys",
".",
"exc_... | This returns an object implementing IFailedFuture.
If exception is None (the default) we MUST be called within an
"except" block (such that sys.exc_info() returns useful
information). | [
"This",
"returns",
"an",
"object",
"implementing",
"IFailedFuture",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/aio.py#L495-L505 |
26,075 | crossbario/txaio | txaio/aio.py | _AsyncioApi.gather | def gather(self, futures, consume_exceptions=True):
"""
This returns a Future that waits for all the Futures in the list
``futures``
:param futures: a list of Futures (or coroutines?)
:param consume_exceptions: if True, any errors are eaten and
returned in the result list.
"""
# from the asyncio docs: "If return_exceptions is True, exceptions
# in the tasks are treated the same as successful results, and
# gathered in the result list; otherwise, the first raised
# exception will be immediately propagated to the returned
# future."
return asyncio.gather(*futures, return_exceptions=consume_exceptions) | python | def gather(self, futures, consume_exceptions=True):
# from the asyncio docs: "If return_exceptions is True, exceptions
# in the tasks are treated the same as successful results, and
# gathered in the result list; otherwise, the first raised
# exception will be immediately propagated to the returned
# future."
return asyncio.gather(*futures, return_exceptions=consume_exceptions) | [
"def",
"gather",
"(",
"self",
",",
"futures",
",",
"consume_exceptions",
"=",
"True",
")",
":",
"# from the asyncio docs: \"If return_exceptions is True, exceptions",
"# in the tasks are treated the same as successful results, and",
"# gathered in the result list; otherwise, the first ra... | This returns a Future that waits for all the Futures in the list
``futures``
:param futures: a list of Futures (or coroutines?)
:param consume_exceptions: if True, any errors are eaten and
returned in the result list. | [
"This",
"returns",
"a",
"Future",
"that",
"waits",
"for",
"all",
"the",
"Futures",
"in",
"the",
"list",
"futures"
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/aio.py#L522-L538 |
26,076 | crossbario/txaio | txaio/__init__.py | _use_framework | def _use_framework(module):
"""
Internal helper, to set this modules methods to a specified
framework helper-methods.
"""
import txaio
for method_name in __all__:
if method_name in ['use_twisted', 'use_asyncio']:
continue
setattr(txaio, method_name,
getattr(module, method_name)) | python | def _use_framework(module):
import txaio
for method_name in __all__:
if method_name in ['use_twisted', 'use_asyncio']:
continue
setattr(txaio, method_name,
getattr(module, method_name)) | [
"def",
"_use_framework",
"(",
"module",
")",
":",
"import",
"txaio",
"for",
"method_name",
"in",
"__all__",
":",
"if",
"method_name",
"in",
"[",
"'use_twisted'",
",",
"'use_asyncio'",
"]",
":",
"continue",
"setattr",
"(",
"txaio",
",",
"method_name",
",",
"g... | Internal helper, to set this modules methods to a specified
framework helper-methods. | [
"Internal",
"helper",
"to",
"set",
"this",
"modules",
"methods",
"to",
"a",
"specified",
"framework",
"helper",
"-",
"methods",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/__init__.py#L130-L140 |
26,077 | crossbario/txaio | txaio/tx.py | start_logging | def start_logging(out=_stdout, level='info'):
"""
Start logging to the file-like object in ``out``. By default, this
is stdout.
"""
global _loggers, _observer, _log_level, _started_logging
if level not in log_levels:
raise RuntimeError(
"Invalid log level '{0}'; valid are: {1}".format(
level, ', '.join(log_levels)
)
)
if _started_logging:
return
_started_logging = True
_log_level = level
set_global_log_level(_log_level)
if out:
_observer = _LogObserver(out)
if _NEW_LOGGER:
_observers = []
if _observer:
_observers.append(_observer)
globalLogBeginner.beginLoggingTo(_observers)
else:
assert out, "out needs to be given a value if using Twisteds before 15.2"
from twisted.python import log
log.startLogging(out) | python | def start_logging(out=_stdout, level='info'):
global _loggers, _observer, _log_level, _started_logging
if level not in log_levels:
raise RuntimeError(
"Invalid log level '{0}'; valid are: {1}".format(
level, ', '.join(log_levels)
)
)
if _started_logging:
return
_started_logging = True
_log_level = level
set_global_log_level(_log_level)
if out:
_observer = _LogObserver(out)
if _NEW_LOGGER:
_observers = []
if _observer:
_observers.append(_observer)
globalLogBeginner.beginLoggingTo(_observers)
else:
assert out, "out needs to be given a value if using Twisteds before 15.2"
from twisted.python import log
log.startLogging(out) | [
"def",
"start_logging",
"(",
"out",
"=",
"_stdout",
",",
"level",
"=",
"'info'",
")",
":",
"global",
"_loggers",
",",
"_observer",
",",
"_log_level",
",",
"_started_logging",
"if",
"level",
"not",
"in",
"log_levels",
":",
"raise",
"RuntimeError",
"(",
"\"Inv... | Start logging to the file-like object in ``out``. By default, this
is stdout. | [
"Start",
"logging",
"to",
"the",
"file",
"-",
"like",
"object",
"in",
"out",
".",
"By",
"default",
"this",
"is",
"stdout",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/tx.py#L332-L365 |
26,078 | crossbario/txaio | txaio/tx.py | Logger.set_log_level | def set_log_level(self, level, keep=True):
"""
Set the log level. If keep is True, then it will not change along with
global log changes.
"""
self._set_log_level(level)
self._log_level_set_explicitly = keep | python | def set_log_level(self, level, keep=True):
self._set_log_level(level)
self._log_level_set_explicitly = keep | [
"def",
"set_log_level",
"(",
"self",
",",
"level",
",",
"keep",
"=",
"True",
")",
":",
"self",
".",
"_set_log_level",
"(",
"level",
")",
"self",
".",
"_log_level_set_explicitly",
"=",
"keep"
] | Set the log level. If keep is True, then it will not change along with
global log changes. | [
"Set",
"the",
"log",
"level",
".",
"If",
"keep",
"is",
"True",
"then",
"it",
"will",
"not",
"change",
"along",
"with",
"global",
"log",
"changes",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/tx.py#L203-L209 |
26,079 | crossbario/txaio | txaio/tx.py | _TxApi.sleep | def sleep(self, delay):
"""
Inline sleep for use in co-routines.
:param delay: Time to sleep in seconds.
:type delay: float
"""
d = Deferred()
self._get_loop().callLater(delay, d.callback, None)
return d | python | def sleep(self, delay):
d = Deferred()
self._get_loop().callLater(delay, d.callback, None)
return d | [
"def",
"sleep",
"(",
"self",
",",
"delay",
")",
":",
"d",
"=",
"Deferred",
"(",
")",
"self",
".",
"_get_loop",
"(",
")",
".",
"callLater",
"(",
"delay",
",",
"d",
".",
"callback",
",",
"None",
")",
"return",
"d"
] | Inline sleep for use in co-routines.
:param delay: Time to sleep in seconds.
:type delay: float | [
"Inline",
"sleep",
"for",
"use",
"in",
"co",
"-",
"routines",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/tx.py#L530-L539 |
26,080 | crossbario/txaio | txaio/_common.py | _BatchedTimer._notify_bucket | def _notify_bucket(self, real_time):
"""
Internal helper. This 'does' the callbacks in a particular bucket.
:param real_time: the bucket to do callbacks on
"""
(delayed_call, calls) = self._buckets[real_time]
del self._buckets[real_time]
errors = []
def notify_one_chunk(calls, chunk_size, chunk_delay_ms):
for call in calls[:chunk_size]:
try:
call()
except Exception as e:
errors.append(e)
calls = calls[chunk_size:]
if calls:
self._create_delayed_call(
chunk_delay_ms / 1000.0,
notify_one_chunk, calls, chunk_size, chunk_delay_ms,
)
else:
# done all calls; make sure there were no errors
if len(errors):
msg = u"Error(s) processing call_later bucket:\n"
for e in errors:
msg += u"{}\n".format(e)
raise RuntimeError(msg)
# ceil()ing because we want the number of chunks, and a
# partial chunk is still a chunk
delay_ms = self._bucket_milliseconds / math.ceil(float(len(calls)) / self._chunk_size)
# I can't imagine any scenario in which chunk_delay_ms is
# actually less than zero, but just being safe here
notify_one_chunk(calls, self._chunk_size, max(0.0, delay_ms)) | python | def _notify_bucket(self, real_time):
(delayed_call, calls) = self._buckets[real_time]
del self._buckets[real_time]
errors = []
def notify_one_chunk(calls, chunk_size, chunk_delay_ms):
for call in calls[:chunk_size]:
try:
call()
except Exception as e:
errors.append(e)
calls = calls[chunk_size:]
if calls:
self._create_delayed_call(
chunk_delay_ms / 1000.0,
notify_one_chunk, calls, chunk_size, chunk_delay_ms,
)
else:
# done all calls; make sure there were no errors
if len(errors):
msg = u"Error(s) processing call_later bucket:\n"
for e in errors:
msg += u"{}\n".format(e)
raise RuntimeError(msg)
# ceil()ing because we want the number of chunks, and a
# partial chunk is still a chunk
delay_ms = self._bucket_milliseconds / math.ceil(float(len(calls)) / self._chunk_size)
# I can't imagine any scenario in which chunk_delay_ms is
# actually less than zero, but just being safe here
notify_one_chunk(calls, self._chunk_size, max(0.0, delay_ms)) | [
"def",
"_notify_bucket",
"(",
"self",
",",
"real_time",
")",
":",
"(",
"delayed_call",
",",
"calls",
")",
"=",
"self",
".",
"_buckets",
"[",
"real_time",
"]",
"del",
"self",
".",
"_buckets",
"[",
"real_time",
"]",
"errors",
"=",
"[",
"]",
"def",
"notif... | Internal helper. This 'does' the callbacks in a particular bucket.
:param real_time: the bucket to do callbacks on | [
"Internal",
"helper",
".",
"This",
"does",
"the",
"callbacks",
"in",
"a",
"particular",
"bucket",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/_common.py#L77-L111 |
26,081 | empymod/empymod | empymod/utils.py | check_ab | def check_ab(ab, verb):
r"""Check source-receiver configuration.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
ab_calc : int
Adjusted source-receiver configuration using reciprocity.
msrc, mrec : bool
If True, src/rec is magnetic; if False, src/rec is electric.
"""
# Try to cast ab into an integer
try:
ab = int(ab)
except VariableCatch:
print('* ERROR :: <ab> must be an integer')
raise
# Check src and rec orientation (<ab> for alpha-beta)
# pab: all possible values that <ab> can take
pab = [11, 12, 13, 14, 15, 16, 21, 22, 23, 24, 25, 26,
31, 32, 33, 34, 35, 36, 41, 42, 43, 44, 45, 46,
51, 52, 53, 54, 55, 56, 61, 62, 63, 64, 65, 66]
if ab not in pab:
print('* ERROR :: <ab> must be one of: ' + str(pab) + ';' +
' <ab> provided: ' + str(ab))
raise ValueError('ab')
# Print input <ab>
if verb > 2:
print(" Input ab : ", ab)
# Check if src and rec are magnetic or electric
msrc = ab % 10 > 3 # If True: magnetic src
mrec = ab // 10 > 3 # If True: magnetic rec
# If rec is magnetic, switch <ab> using reciprocity.
if mrec:
if msrc:
# G^mm_ab(s, r, e, z) = -G^ee_ab(s, r, -z, -e)
ab_calc = ab - 33 # -30 : mrec->erec; -3: msrc->esrc
else:
# G^me_ab(s, r, e, z) = -G^em_ba(r, s, e, z)
ab_calc = ab % 10*10 + ab // 10 # Swap alpha/beta
else:
ab_calc = ab
# Print actual calculated <ab>
if verb > 2:
if ab in [36, 63]:
print("\n> <ab> IS "+str(ab)+" WHICH IS ZERO; returning")
else:
print(" Calculated ab : ", ab_calc)
return ab_calc, msrc, mrec | python | def check_ab(ab, verb):
r"""Check source-receiver configuration.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
ab_calc : int
Adjusted source-receiver configuration using reciprocity.
msrc, mrec : bool
If True, src/rec is magnetic; if False, src/rec is electric.
"""
# Try to cast ab into an integer
try:
ab = int(ab)
except VariableCatch:
print('* ERROR :: <ab> must be an integer')
raise
# Check src and rec orientation (<ab> for alpha-beta)
# pab: all possible values that <ab> can take
pab = [11, 12, 13, 14, 15, 16, 21, 22, 23, 24, 25, 26,
31, 32, 33, 34, 35, 36, 41, 42, 43, 44, 45, 46,
51, 52, 53, 54, 55, 56, 61, 62, 63, 64, 65, 66]
if ab not in pab:
print('* ERROR :: <ab> must be one of: ' + str(pab) + ';' +
' <ab> provided: ' + str(ab))
raise ValueError('ab')
# Print input <ab>
if verb > 2:
print(" Input ab : ", ab)
# Check if src and rec are magnetic or electric
msrc = ab % 10 > 3 # If True: magnetic src
mrec = ab // 10 > 3 # If True: magnetic rec
# If rec is magnetic, switch <ab> using reciprocity.
if mrec:
if msrc:
# G^mm_ab(s, r, e, z) = -G^ee_ab(s, r, -z, -e)
ab_calc = ab - 33 # -30 : mrec->erec; -3: msrc->esrc
else:
# G^me_ab(s, r, e, z) = -G^em_ba(r, s, e, z)
ab_calc = ab % 10*10 + ab // 10 # Swap alpha/beta
else:
ab_calc = ab
# Print actual calculated <ab>
if verb > 2:
if ab in [36, 63]:
print("\n> <ab> IS "+str(ab)+" WHICH IS ZERO; returning")
else:
print(" Calculated ab : ", ab_calc)
return ab_calc, msrc, mrec | [
"def",
"check_ab",
"(",
"ab",
",",
"verb",
")",
":",
"# Try to cast ab into an integer",
"try",
":",
"ab",
"=",
"int",
"(",
"ab",
")",
"except",
"VariableCatch",
":",
"print",
"(",
"'* ERROR :: <ab> must be an integer'",
")",
"raise",
"# Check src and rec orientat... | r"""Check source-receiver configuration.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
ab_calc : int
Adjusted source-receiver configuration using reciprocity.
msrc, mrec : bool
If True, src/rec is magnetic; if False, src/rec is electric. | [
"r",
"Check",
"source",
"-",
"receiver",
"configuration",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L142-L211 |
26,082 | empymod/empymod | empymod/utils.py | check_dipole | def check_dipole(inp, name, verb):
r"""Check dipole parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
Pole coordinates (m): [pole-x, pole-y, pole-z].
name : str, {'src', 'rec'}
Pole-type.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
inp : list
List of pole coordinates [x, y, z].
ninp : int
Number of inp-elements
"""
# Check inp for x, y, and z; x & y must have same length, z is a float
_check_shape(np.squeeze(inp), name, (3,))
inp[0] = _check_var(inp[0], float, 1, name+'-x')
inp[1] = _check_var(inp[1], float, 1, name+'-y', inp[0].shape)
inp[2] = _check_var(inp[2], float, 1, name+'-z', (1,))
# Print spatial parameters
if verb > 2:
# Pole-type: src or rec
if name == 'src':
longname = ' Source(s) : '
else:
longname = ' Receiver(s) : '
print(longname, str(inp[0].size), 'dipole(s)')
tname = ['x ', 'y ', 'z ']
for i in range(3):
text = " > " + tname[i] + " [m] : "
_prnt_min_max_val(inp[i], text, verb)
return inp, inp[0].size | python | def check_dipole(inp, name, verb):
r"""Check dipole parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
Pole coordinates (m): [pole-x, pole-y, pole-z].
name : str, {'src', 'rec'}
Pole-type.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
inp : list
List of pole coordinates [x, y, z].
ninp : int
Number of inp-elements
"""
# Check inp for x, y, and z; x & y must have same length, z is a float
_check_shape(np.squeeze(inp), name, (3,))
inp[0] = _check_var(inp[0], float, 1, name+'-x')
inp[1] = _check_var(inp[1], float, 1, name+'-y', inp[0].shape)
inp[2] = _check_var(inp[2], float, 1, name+'-z', (1,))
# Print spatial parameters
if verb > 2:
# Pole-type: src or rec
if name == 'src':
longname = ' Source(s) : '
else:
longname = ' Receiver(s) : '
print(longname, str(inp[0].size), 'dipole(s)')
tname = ['x ', 'y ', 'z ']
for i in range(3):
text = " > " + tname[i] + " [m] : "
_prnt_min_max_val(inp[i], text, verb)
return inp, inp[0].size | [
"def",
"check_dipole",
"(",
"inp",
",",
"name",
",",
"verb",
")",
":",
"# Check inp for x, y, and z; x & y must have same length, z is a float",
"_check_shape",
"(",
"np",
".",
"squeeze",
"(",
"inp",
")",
",",
"name",
",",
"(",
"3",
",",
")",
")",
"inp",
"[",
... | r"""Check dipole parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
Pole coordinates (m): [pole-x, pole-y, pole-z].
name : str, {'src', 'rec'}
Pole-type.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
inp : list
List of pole coordinates [x, y, z].
ninp : int
Number of inp-elements | [
"r",
"Check",
"dipole",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L317-L365 |
26,083 | empymod/empymod | empymod/utils.py | check_frequency | def check_frequency(freq, res, aniso, epermH, epermV, mpermH, mpermV, verb):
r"""Calculate frequency-dependent parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
freq : array_like
Frequencies f (Hz).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
aniso : array_like
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
epermH, epermV : array_like
Relative horizontal/vertical electric permittivities
epsilon_h/epsilon_v (-);
#epermH = #epermV = #res.
mpermH, mpermV : array_like
Relative horizontal/vertical magnetic permeabilities mu_h/mu_v (-);
#mpermH = #mpermV = #res.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
freq : float
Frequency, checked for size and assured min_freq.
etaH, etaV : array
Parameters etaH/etaV, same size as provided resistivity.
zetaH, zetaV : array
Parameters zetaH/zetaV, same size as provided resistivity.
"""
global _min_freq
# Check if the user provided a model for etaH/etaV/zetaH/zetaV
if isinstance(res, dict):
res = res['res']
# Check frequency
freq = _check_var(freq, float, 1, 'freq')
# Minimum frequency to avoid division by zero at freq = 0 Hz.
# => min_freq can be set with utils.set_min
freq = _check_min(freq, _min_freq, 'Frequencies', 'Hz', verb)
if verb > 2:
_prnt_min_max_val(freq, " frequency [Hz] : ", verb)
# Calculate eta and zeta (horizontal and vertical)
c = 299792458 # Speed of light m/s
mu_0 = 4e-7*np.pi # Magn. permeability of free space [H/m]
epsilon_0 = 1./(mu_0*c*c) # Elec. permittivity of free space [F/m]
etaH = 1/res + np.outer(2j*np.pi*freq, epermH*epsilon_0)
etaV = 1/(res*aniso*aniso) + np.outer(2j*np.pi*freq, epermV*epsilon_0)
zetaH = np.outer(2j*np.pi*freq, mpermH*mu_0)
zetaV = np.outer(2j*np.pi*freq, mpermV*mu_0)
return freq, etaH, etaV, zetaH, zetaV | python | def check_frequency(freq, res, aniso, epermH, epermV, mpermH, mpermV, verb):
r"""Calculate frequency-dependent parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
freq : array_like
Frequencies f (Hz).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
aniso : array_like
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
epermH, epermV : array_like
Relative horizontal/vertical electric permittivities
epsilon_h/epsilon_v (-);
#epermH = #epermV = #res.
mpermH, mpermV : array_like
Relative horizontal/vertical magnetic permeabilities mu_h/mu_v (-);
#mpermH = #mpermV = #res.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
freq : float
Frequency, checked for size and assured min_freq.
etaH, etaV : array
Parameters etaH/etaV, same size as provided resistivity.
zetaH, zetaV : array
Parameters zetaH/zetaV, same size as provided resistivity.
"""
global _min_freq
# Check if the user provided a model for etaH/etaV/zetaH/zetaV
if isinstance(res, dict):
res = res['res']
# Check frequency
freq = _check_var(freq, float, 1, 'freq')
# Minimum frequency to avoid division by zero at freq = 0 Hz.
# => min_freq can be set with utils.set_min
freq = _check_min(freq, _min_freq, 'Frequencies', 'Hz', verb)
if verb > 2:
_prnt_min_max_val(freq, " frequency [Hz] : ", verb)
# Calculate eta and zeta (horizontal and vertical)
c = 299792458 # Speed of light m/s
mu_0 = 4e-7*np.pi # Magn. permeability of free space [H/m]
epsilon_0 = 1./(mu_0*c*c) # Elec. permittivity of free space [F/m]
etaH = 1/res + np.outer(2j*np.pi*freq, epermH*epsilon_0)
etaV = 1/(res*aniso*aniso) + np.outer(2j*np.pi*freq, epermV*epsilon_0)
zetaH = np.outer(2j*np.pi*freq, mpermH*mu_0)
zetaV = np.outer(2j*np.pi*freq, mpermV*mu_0)
return freq, etaH, etaV, zetaH, zetaV | [
"def",
"check_frequency",
"(",
"freq",
",",
"res",
",",
"aniso",
",",
"epermH",
",",
"epermV",
",",
"mpermH",
",",
"mpermV",
",",
"verb",
")",
":",
"global",
"_min_freq",
"# Check if the user provided a model for etaH/etaV/zetaH/zetaV",
"if",
"isinstance",
"(",
"r... | r"""Calculate frequency-dependent parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
freq : array_like
Frequencies f (Hz).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
aniso : array_like
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
epermH, epermV : array_like
Relative horizontal/vertical electric permittivities
epsilon_h/epsilon_v (-);
#epermH = #epermV = #res.
mpermH, mpermV : array_like
Relative horizontal/vertical magnetic permeabilities mu_h/mu_v (-);
#mpermH = #mpermV = #res.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
freq : float
Frequency, checked for size and assured min_freq.
etaH, etaV : array
Parameters etaH/etaV, same size as provided resistivity.
zetaH, zetaV : array
Parameters zetaH/zetaV, same size as provided resistivity. | [
"r",
"Calculate",
"frequency",
"-",
"dependent",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L368-L436 |
26,084 | empymod/empymod | empymod/utils.py | check_opt | def check_opt(opt, loop, ht, htarg, verb):
r"""Check optimization parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
opt : {None, 'parallel'}
Optimization flag; use ``numexpr`` or not.
loop : {None, 'freq', 'off'}
Loop flag.
ht : str
Flag to choose the Hankel transform.
htarg : array_like,
Depends on the value for ``ht``.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
use_ne_eval : bool
Boolean if to use ``numexpr``.
loop_freq : bool
Boolean if to loop over frequencies.
loop_off : bool
Boolean if to loop over offsets.
"""
# Check optimization flag
use_ne_eval = False
if opt == 'parallel':
if numexpr:
use_ne_eval = numexpr.evaluate
elif verb > 0:
print(numexpr_msg)
# Define if to loop over frequencies or over offsets
lagged_splined_fht = False
if ht == 'fht':
if htarg[1] != 0:
lagged_splined_fht = True
if ht in ['hqwe', 'hquad'] or lagged_splined_fht:
loop_freq = True
loop_off = False
else:
loop_off = loop == 'off'
loop_freq = loop == 'freq'
# If verbose, print optimization information
if verb > 2:
if use_ne_eval:
print(" Kernel Opt. : Use parallel")
else:
print(" Kernel Opt. : None")
if loop_off:
print(" Loop over : Offsets")
elif loop_freq:
print(" Loop over : Frequencies")
else:
print(" Loop over : None (all vectorized)")
return use_ne_eval, loop_freq, loop_off | python | def check_opt(opt, loop, ht, htarg, verb):
r"""Check optimization parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
opt : {None, 'parallel'}
Optimization flag; use ``numexpr`` or not.
loop : {None, 'freq', 'off'}
Loop flag.
ht : str
Flag to choose the Hankel transform.
htarg : array_like,
Depends on the value for ``ht``.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
use_ne_eval : bool
Boolean if to use ``numexpr``.
loop_freq : bool
Boolean if to loop over frequencies.
loop_off : bool
Boolean if to loop over offsets.
"""
# Check optimization flag
use_ne_eval = False
if opt == 'parallel':
if numexpr:
use_ne_eval = numexpr.evaluate
elif verb > 0:
print(numexpr_msg)
# Define if to loop over frequencies or over offsets
lagged_splined_fht = False
if ht == 'fht':
if htarg[1] != 0:
lagged_splined_fht = True
if ht in ['hqwe', 'hquad'] or lagged_splined_fht:
loop_freq = True
loop_off = False
else:
loop_off = loop == 'off'
loop_freq = loop == 'freq'
# If verbose, print optimization information
if verb > 2:
if use_ne_eval:
print(" Kernel Opt. : Use parallel")
else:
print(" Kernel Opt. : None")
if loop_off:
print(" Loop over : Offsets")
elif loop_freq:
print(" Loop over : Frequencies")
else:
print(" Loop over : None (all vectorized)")
return use_ne_eval, loop_freq, loop_off | [
"def",
"check_opt",
"(",
"opt",
",",
"loop",
",",
"ht",
",",
"htarg",
",",
"verb",
")",
":",
"# Check optimization flag",
"use_ne_eval",
"=",
"False",
"if",
"opt",
"==",
"'parallel'",
":",
"if",
"numexpr",
":",
"use_ne_eval",
"=",
"numexpr",
".",
"evaluate... | r"""Check optimization parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
opt : {None, 'parallel'}
Optimization flag; use ``numexpr`` or not.
loop : {None, 'freq', 'off'}
Loop flag.
ht : str
Flag to choose the Hankel transform.
htarg : array_like,
Depends on the value for ``ht``.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
use_ne_eval : bool
Boolean if to use ``numexpr``.
loop_freq : bool
Boolean if to loop over frequencies.
loop_off : bool
Boolean if to loop over offsets. | [
"r",
"Check",
"optimization",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L824-L897 |
26,085 | empymod/empymod | empymod/utils.py | check_time_only | def check_time_only(time, signal, verb):
r"""Check time and signal parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
time : array_like
Times t (s).
signal : {None, 0, 1, -1}
Source signal:
- None: Frequency-domain response
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
time : float
Time, checked for size and assured min_time.
"""
global _min_time
# Check input signal
if int(signal) not in [-1, 0, 1]:
print("* ERROR :: <signal> must be one of: [None, -1, 0, 1]; " +
"<signal> provided: "+str(signal))
raise ValueError('signal')
# Check time
time = _check_var(time, float, 1, 'time')
# Minimum time to avoid division by zero at time = 0 s.
# => min_time can be set with utils.set_min
time = _check_min(time, _min_time, 'Times', 's', verb)
if verb > 2:
_prnt_min_max_val(time, " time [s] : ", verb)
return time | python | def check_time_only(time, signal, verb):
r"""Check time and signal parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
time : array_like
Times t (s).
signal : {None, 0, 1, -1}
Source signal:
- None: Frequency-domain response
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
time : float
Time, checked for size and assured min_time.
"""
global _min_time
# Check input signal
if int(signal) not in [-1, 0, 1]:
print("* ERROR :: <signal> must be one of: [None, -1, 0, 1]; " +
"<signal> provided: "+str(signal))
raise ValueError('signal')
# Check time
time = _check_var(time, float, 1, 'time')
# Minimum time to avoid division by zero at time = 0 s.
# => min_time can be set with utils.set_min
time = _check_min(time, _min_time, 'Times', 's', verb)
if verb > 2:
_prnt_min_max_val(time, " time [s] : ", verb)
return time | [
"def",
"check_time_only",
"(",
"time",
",",
"signal",
",",
"verb",
")",
":",
"global",
"_min_time",
"# Check input signal",
"if",
"int",
"(",
"signal",
")",
"not",
"in",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
":",
"print",
"(",
"\"* ERROR :: <signal> ... | r"""Check time and signal parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
time : array_like
Times t (s).
signal : {None, 0, 1, -1}
Source signal:
- None: Frequency-domain response
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
time : float
Time, checked for size and assured min_time. | [
"r",
"Check",
"time",
"and",
"signal",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1221-L1267 |
26,086 | empymod/empymod | empymod/utils.py | check_solution | def check_solution(solution, signal, ab, msrc, mrec):
r"""Check required solution with parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
solution : str
String to define analytical solution.
signal : {None, 0, 1, -1}
Source signal:
- None: Frequency-domain response
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
msrc, mrec : bool
True if src/rec is magnetic, else False.
"""
# Ensure valid solution.
if solution not in ['fs', 'dfs', 'dhs', 'dsplit', 'dtetm']:
print("* ERROR :: Solution must be one of ['fs', 'dfs', 'dhs', " +
"'dsplit', 'dtetm']; <solution> provided: " + solution)
raise ValueError('solution')
# If diffusive solution is required, ensure EE-field.
if solution[0] == 'd' and (msrc or mrec):
print('* ERROR :: Diffusive solution is only implemented for ' +
'electric sources and electric receivers, <ab> provided: ' +
str(ab))
raise ValueError('ab')
# If full solution is required, ensure frequency-domain.
if solution == 'fs' and signal is not None:
print('* ERROR :: Full fullspace solution is only implemented for ' +
'the frequency domain, <signal> provided: ' + str(signal))
raise ValueError('signal') | python | def check_solution(solution, signal, ab, msrc, mrec):
r"""Check required solution with parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
solution : str
String to define analytical solution.
signal : {None, 0, 1, -1}
Source signal:
- None: Frequency-domain response
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
msrc, mrec : bool
True if src/rec is magnetic, else False.
"""
# Ensure valid solution.
if solution not in ['fs', 'dfs', 'dhs', 'dsplit', 'dtetm']:
print("* ERROR :: Solution must be one of ['fs', 'dfs', 'dhs', " +
"'dsplit', 'dtetm']; <solution> provided: " + solution)
raise ValueError('solution')
# If diffusive solution is required, ensure EE-field.
if solution[0] == 'd' and (msrc or mrec):
print('* ERROR :: Diffusive solution is only implemented for ' +
'electric sources and electric receivers, <ab> provided: ' +
str(ab))
raise ValueError('ab')
# If full solution is required, ensure frequency-domain.
if solution == 'fs' and signal is not None:
print('* ERROR :: Full fullspace solution is only implemented for ' +
'the frequency domain, <signal> provided: ' + str(signal))
raise ValueError('signal') | [
"def",
"check_solution",
"(",
"solution",
",",
"signal",
",",
"ab",
",",
"msrc",
",",
"mrec",
")",
":",
"# Ensure valid solution.",
"if",
"solution",
"not",
"in",
"[",
"'fs'",
",",
"'dfs'",
",",
"'dhs'",
",",
"'dsplit'",
",",
"'dtetm'",
"]",
":",
"print"... | r"""Check required solution with parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
solution : str
String to define analytical solution.
signal : {None, 0, 1, -1}
Source signal:
- None: Frequency-domain response
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
msrc, mrec : bool
True if src/rec is magnetic, else False. | [
"r",
"Check",
"required",
"solution",
"with",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1270-L1311 |
26,087 | empymod/empymod | empymod/utils.py | get_abs | def get_abs(msrc, mrec, srcazm, srcdip, recazm, recdip, verb):
r"""Get required ab's for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
msrc, mrec : bool
True if src/rec is magnetic, else False.
srcazm, recazm : float
Horizontal source/receiver angle (azimuth).
srcdip, recdip : float
Vertical source/receiver angle (dip).
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
ab_calc : array of int
ab's to calculate for this bipole.
"""
# Get required ab's (9 at most)
ab_calc = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]])
if msrc:
ab_calc += 3
if mrec:
ab_calc += 30
# Switch <ab> using reciprocity.
if msrc:
# G^mm_ab(s, r, e, z) = -G^ee_ab(s, r, -z, -e)
ab_calc -= 33 # -30 : mrec->erec; -3: msrc->esrc
else:
# G^me_ab(s, r, e, z) = -G^em_ba(r, s, e, z)
ab_calc = ab_calc % 10*10 + ab_calc // 10 # Swap alpha/beta
# Remove unnecessary ab's
bab = np.asarray(ab_calc*0+1, dtype=bool)
# Remove if source is x- or y-directed
check = np.atleast_1d(srcazm)[0]
if np.allclose(srcazm % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[:, 1] *= False # x-directed source, remove y
else: # Multiples of pi/2 (90)
bab[:, 0] *= False # y-directed source, remove x
# Remove if source is vertical
check = np.atleast_1d(srcdip)[0]
if np.allclose(srcdip % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[:, 2] *= False # Horizontal, remove z
else: # Multiples of pi/2 (90)
bab[:, :2] *= False # Vertical, remove x/y
# Remove if receiver is x- or y-directed
check = np.atleast_1d(recazm)[0]
if np.allclose(recazm % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[1, :] *= False # x-directed receiver, remove y
else: # Multiples of pi/2 (90)
bab[0, :] *= False # y-directed receiver, remove x
# Remove if receiver is vertical
check = np.atleast_1d(recdip)[0]
if np.allclose(recdip % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[2, :] *= False # Horizontal, remove z
else: # Multiples of pi/2 (90)
bab[:2, :] *= False # Vertical, remove x/y
# Reduce
ab_calc = ab_calc[bab].ravel()
# Print actual calculated <ab>
if verb > 2:
print(" Required ab's : ", _strvar(ab_calc))
return ab_calc | python | def get_abs(msrc, mrec, srcazm, srcdip, recazm, recdip, verb):
r"""Get required ab's for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
msrc, mrec : bool
True if src/rec is magnetic, else False.
srcazm, recazm : float
Horizontal source/receiver angle (azimuth).
srcdip, recdip : float
Vertical source/receiver angle (dip).
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
ab_calc : array of int
ab's to calculate for this bipole.
"""
# Get required ab's (9 at most)
ab_calc = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]])
if msrc:
ab_calc += 3
if mrec:
ab_calc += 30
# Switch <ab> using reciprocity.
if msrc:
# G^mm_ab(s, r, e, z) = -G^ee_ab(s, r, -z, -e)
ab_calc -= 33 # -30 : mrec->erec; -3: msrc->esrc
else:
# G^me_ab(s, r, e, z) = -G^em_ba(r, s, e, z)
ab_calc = ab_calc % 10*10 + ab_calc // 10 # Swap alpha/beta
# Remove unnecessary ab's
bab = np.asarray(ab_calc*0+1, dtype=bool)
# Remove if source is x- or y-directed
check = np.atleast_1d(srcazm)[0]
if np.allclose(srcazm % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[:, 1] *= False # x-directed source, remove y
else: # Multiples of pi/2 (90)
bab[:, 0] *= False # y-directed source, remove x
# Remove if source is vertical
check = np.atleast_1d(srcdip)[0]
if np.allclose(srcdip % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[:, 2] *= False # Horizontal, remove z
else: # Multiples of pi/2 (90)
bab[:, :2] *= False # Vertical, remove x/y
# Remove if receiver is x- or y-directed
check = np.atleast_1d(recazm)[0]
if np.allclose(recazm % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[1, :] *= False # x-directed receiver, remove y
else: # Multiples of pi/2 (90)
bab[0, :] *= False # y-directed receiver, remove x
# Remove if receiver is vertical
check = np.atleast_1d(recdip)[0]
if np.allclose(recdip % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[2, :] *= False # Horizontal, remove z
else: # Multiples of pi/2 (90)
bab[:2, :] *= False # Vertical, remove x/y
# Reduce
ab_calc = ab_calc[bab].ravel()
# Print actual calculated <ab>
if verb > 2:
print(" Required ab's : ", _strvar(ab_calc))
return ab_calc | [
"def",
"get_abs",
"(",
"msrc",
",",
"mrec",
",",
"srcazm",
",",
"srcdip",
",",
"recazm",
",",
"recdip",
",",
"verb",
")",
":",
"# Get required ab's (9 at most)",
"ab_calc",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"11",
",",
"12",
",",
"13",
"]",
",",... | r"""Get required ab's for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
msrc, mrec : bool
True if src/rec is magnetic, else False.
srcazm, recazm : float
Horizontal source/receiver angle (azimuth).
srcdip, recdip : float
Vertical source/receiver angle (dip).
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
ab_calc : array of int
ab's to calculate for this bipole. | [
"r",
"Get",
"required",
"ab",
"s",
"for",
"given",
"angles",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1316-L1402 |
26,088 | empymod/empymod | empymod/utils.py | get_geo_fact | def get_geo_fact(ab, srcazm, srcdip, recazm, recdip, msrc, mrec):
r"""Get required geometrical scaling factor for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
srcazm, recazm : float
Horizontal source/receiver angle.
srcdip, recdip : float
Vertical source/receiver angle.
Returns
-------
fact : float
Geometrical scaling factor.
"""
global _min_angle
# Get current direction for source and receiver
fis = ab % 10
fir = ab // 10
# If rec is magnetic and src not, swap directions (reciprocity).
# (They have been swapped in get_abs, but the original scaling applies.)
if mrec and not msrc:
fis, fir = fir, fis
def gfact(bp, azm, dip):
r"""Geometrical factor of source or receiver."""
if bp in [1, 4]: # x-directed
return np.cos(azm)*np.cos(dip)
elif bp in [2, 5]: # y-directed
return np.sin(azm)*np.cos(dip)
else: # z-directed
return np.sin(dip)
# Calculate src-rec-factor
fsrc = gfact(fis, srcazm, srcdip)
frec = gfact(fir, recazm, recdip)
fact = np.outer(fsrc, frec).ravel()
# Set very small angles to proper zero (because e.g. sin(pi/2) != exact 0)
# => min_angle can be set with utils.set_min
fact[np.abs(fact) < _min_angle] = 0
return fact | python | def get_geo_fact(ab, srcazm, srcdip, recazm, recdip, msrc, mrec):
r"""Get required geometrical scaling factor for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
srcazm, recazm : float
Horizontal source/receiver angle.
srcdip, recdip : float
Vertical source/receiver angle.
Returns
-------
fact : float
Geometrical scaling factor.
"""
global _min_angle
# Get current direction for source and receiver
fis = ab % 10
fir = ab // 10
# If rec is magnetic and src not, swap directions (reciprocity).
# (They have been swapped in get_abs, but the original scaling applies.)
if mrec and not msrc:
fis, fir = fir, fis
def gfact(bp, azm, dip):
r"""Geometrical factor of source or receiver."""
if bp in [1, 4]: # x-directed
return np.cos(azm)*np.cos(dip)
elif bp in [2, 5]: # y-directed
return np.sin(azm)*np.cos(dip)
else: # z-directed
return np.sin(dip)
# Calculate src-rec-factor
fsrc = gfact(fis, srcazm, srcdip)
frec = gfact(fir, recazm, recdip)
fact = np.outer(fsrc, frec).ravel()
# Set very small angles to proper zero (because e.g. sin(pi/2) != exact 0)
# => min_angle can be set with utils.set_min
fact[np.abs(fact) < _min_angle] = 0
return fact | [
"def",
"get_geo_fact",
"(",
"ab",
",",
"srcazm",
",",
"srcdip",
",",
"recazm",
",",
"recdip",
",",
"msrc",
",",
"mrec",
")",
":",
"global",
"_min_angle",
"# Get current direction for source and receiver",
"fis",
"=",
"ab",
"%",
"10",
"fir",
"=",
"ab",
"//",
... | r"""Get required geometrical scaling factor for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
srcazm, recazm : float
Horizontal source/receiver angle.
srcdip, recdip : float
Vertical source/receiver angle.
Returns
-------
fact : float
Geometrical scaling factor. | [
"r",
"Get",
"required",
"geometrical",
"scaling",
"factor",
"for",
"given",
"angles",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1405-L1459 |
26,089 | empymod/empymod | empymod/utils.py | get_layer_nr | def get_layer_nr(inp, depth):
r"""Get number of layer in which inp resides.
Note:
If zinp is on a layer interface, the layer above the interface is chosen.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
Dipole coordinates (m)
depth : array
Depths of layer interfaces.
Returns
-------
linp : int or array_like of int
Layer number(s) in which inp resides (plural only if bipole).
zinp : float or array
inp[2] (depths).
"""
zinp = inp[2]
# depth = [-infty : last interface]; create additional depth-array
# pdepth = [fist interface : +infty]
pdepth = np.concatenate((depth[1:], np.array([np.infty])))
# Broadcast arrays
b_zinp = np.atleast_1d(zinp)[:, None]
# Get layers
linp = np.where((depth[None, :] < b_zinp)*(pdepth[None, :] >= b_zinp))[1]
# Return; squeeze in case of only one inp-depth
return np.squeeze(linp), zinp | python | def get_layer_nr(inp, depth):
r"""Get number of layer in which inp resides.
Note:
If zinp is on a layer interface, the layer above the interface is chosen.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
Dipole coordinates (m)
depth : array
Depths of layer interfaces.
Returns
-------
linp : int or array_like of int
Layer number(s) in which inp resides (plural only if bipole).
zinp : float or array
inp[2] (depths).
"""
zinp = inp[2]
# depth = [-infty : last interface]; create additional depth-array
# pdepth = [fist interface : +infty]
pdepth = np.concatenate((depth[1:], np.array([np.infty])))
# Broadcast arrays
b_zinp = np.atleast_1d(zinp)[:, None]
# Get layers
linp = np.where((depth[None, :] < b_zinp)*(pdepth[None, :] >= b_zinp))[1]
# Return; squeeze in case of only one inp-depth
return np.squeeze(linp), zinp | [
"def",
"get_layer_nr",
"(",
"inp",
",",
"depth",
")",
":",
"zinp",
"=",
"inp",
"[",
"2",
"]",
"# depth = [-infty : last interface]; create additional depth-array",
"# pdepth = [fist interface : +infty]",
"pdepth",
"=",
"np",
".",
"concatenate",
"(",
"(",
"depth",
"["... | r"""Get number of layer in which inp resides.
Note:
If zinp is on a layer interface, the layer above the interface is chosen.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
Dipole coordinates (m)
depth : array
Depths of layer interfaces.
Returns
-------
linp : int or array_like of int
Layer number(s) in which inp resides (plural only if bipole).
zinp : float or array
inp[2] (depths). | [
"r",
"Get",
"number",
"of",
"layer",
"in",
"which",
"inp",
"resides",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1462-L1503 |
26,090 | empymod/empymod | empymod/utils.py | get_off_ang | def get_off_ang(src, rec, nsrc, nrec, verb):
r"""Get depths, offsets, angles, hence spatial input parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
src, rec : list of floats or arrays
Source/receiver dipole coordinates x, y, and z (m).
nsrc, nrec : int
Number of sources/receivers (-).
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
off : array of floats
Offsets
angle : array of floats
Angles
"""
global _min_off
# Pre-allocate off and angle
off = np.empty((nrec*nsrc,))
angle = np.empty((nrec*nsrc,))
# Coordinates
# Loop over sources, append them one after another.
for i in range(nsrc):
xco = rec[0] - src[0][i] # X-coordinates [m]
yco = rec[1] - src[1][i] # Y-coordinates [m]
off[i*nrec:(i+1)*nrec] = np.sqrt(xco*xco + yco*yco) # Offset [m]
angle[i*nrec:(i+1)*nrec] = np.arctan2(yco, xco) # Angle [rad]
# Note: One could achieve a potential speed-up using np.unique to sort out
# src-rec configurations that have the same offset and angle. Very unlikely
# for real data.
# Minimum offset to avoid singularities at off = 0 m.
# => min_off can be set with utils.set_min
angle[np.where(off < _min_off)] = np.nan
off = _check_min(off, _min_off, 'Offsets', 'm', verb)
return off, angle | python | def get_off_ang(src, rec, nsrc, nrec, verb):
r"""Get depths, offsets, angles, hence spatial input parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
src, rec : list of floats or arrays
Source/receiver dipole coordinates x, y, and z (m).
nsrc, nrec : int
Number of sources/receivers (-).
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
off : array of floats
Offsets
angle : array of floats
Angles
"""
global _min_off
# Pre-allocate off and angle
off = np.empty((nrec*nsrc,))
angle = np.empty((nrec*nsrc,))
# Coordinates
# Loop over sources, append them one after another.
for i in range(nsrc):
xco = rec[0] - src[0][i] # X-coordinates [m]
yco = rec[1] - src[1][i] # Y-coordinates [m]
off[i*nrec:(i+1)*nrec] = np.sqrt(xco*xco + yco*yco) # Offset [m]
angle[i*nrec:(i+1)*nrec] = np.arctan2(yco, xco) # Angle [rad]
# Note: One could achieve a potential speed-up using np.unique to sort out
# src-rec configurations that have the same offset and angle. Very unlikely
# for real data.
# Minimum offset to avoid singularities at off = 0 m.
# => min_off can be set with utils.set_min
angle[np.where(off < _min_off)] = np.nan
off = _check_min(off, _min_off, 'Offsets', 'm', verb)
return off, angle | [
"def",
"get_off_ang",
"(",
"src",
",",
"rec",
",",
"nsrc",
",",
"nrec",
",",
"verb",
")",
":",
"global",
"_min_off",
"# Pre-allocate off and angle",
"off",
"=",
"np",
".",
"empty",
"(",
"(",
"nrec",
"*",
"nsrc",
",",
")",
")",
"angle",
"=",
"np",
"."... | r"""Get depths, offsets, angles, hence spatial input parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
src, rec : list of floats or arrays
Source/receiver dipole coordinates x, y, and z (m).
nsrc, nrec : int
Number of sources/receivers (-).
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
off : array of floats
Offsets
angle : array of floats
Angles | [
"r",
"Get",
"depths",
"offsets",
"angles",
"hence",
"spatial",
"input",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1506-L1557 |
26,091 | empymod/empymod | empymod/utils.py | printstartfinish | def printstartfinish(verb, inp=None, kcount=None):
r"""Print start and finish with time measure and kernel count."""
if inp:
if verb > 1:
ttxt = str(timedelta(seconds=default_timer() - inp))
ktxt = ' '
if kcount:
ktxt += str(kcount) + ' kernel call(s)'
print('\n:: empymod END; runtime = ' + ttxt + ' ::' + ktxt + '\n')
else:
t0 = default_timer()
if verb > 2:
print("\n:: empymod START ::\n")
return t0 | python | def printstartfinish(verb, inp=None, kcount=None):
r"""Print start and finish with time measure and kernel count."""
if inp:
if verb > 1:
ttxt = str(timedelta(seconds=default_timer() - inp))
ktxt = ' '
if kcount:
ktxt += str(kcount) + ' kernel call(s)'
print('\n:: empymod END; runtime = ' + ttxt + ' ::' + ktxt + '\n')
else:
t0 = default_timer()
if verb > 2:
print("\n:: empymod START ::\n")
return t0 | [
"def",
"printstartfinish",
"(",
"verb",
",",
"inp",
"=",
"None",
",",
"kcount",
"=",
"None",
")",
":",
"if",
"inp",
":",
"if",
"verb",
">",
"1",
":",
"ttxt",
"=",
"str",
"(",
"timedelta",
"(",
"seconds",
"=",
"default_timer",
"(",
")",
"-",
"inp",
... | r"""Print start and finish with time measure and kernel count. | [
"r",
"Print",
"start",
"and",
"finish",
"with",
"time",
"measure",
"and",
"kernel",
"count",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1763-L1776 |
26,092 | empymod/empymod | empymod/utils.py | set_minimum | def set_minimum(min_freq=None, min_time=None, min_off=None, min_res=None,
min_angle=None):
r"""
Set minimum values of parameters.
The given parameters are set to its minimum value if they are smaller.
Parameters
----------
min_freq : float, optional
Minimum frequency [Hz] (default 1e-20 Hz).
min_time : float, optional
Minimum time [s] (default 1e-20 s).
min_off : float, optional
Minimum offset [m] (default 1e-3 m).
Also used to round src- & rec-coordinates.
min_res : float, optional
Minimum horizontal and vertical resistivity [Ohm.m] (default 1e-20).
min_angle : float, optional
Minimum angle [-] (default 1e-10).
Note
----
set_minimum and get_minimum are derived after set_printoptions and
get_printoptions from arrayprint.py in numpy.
"""
global _min_freq, _min_time, _min_off, _min_res, _min_angle
if min_freq is not None:
_min_freq = min_freq
if min_time is not None:
_min_time = min_time
if min_off is not None:
_min_off = min_off
if min_res is not None:
_min_res = min_res
if min_angle is not None:
_min_angle = min_angle | python | def set_minimum(min_freq=None, min_time=None, min_off=None, min_res=None,
min_angle=None):
r"""
Set minimum values of parameters.
The given parameters are set to its minimum value if they are smaller.
Parameters
----------
min_freq : float, optional
Minimum frequency [Hz] (default 1e-20 Hz).
min_time : float, optional
Minimum time [s] (default 1e-20 s).
min_off : float, optional
Minimum offset [m] (default 1e-3 m).
Also used to round src- & rec-coordinates.
min_res : float, optional
Minimum horizontal and vertical resistivity [Ohm.m] (default 1e-20).
min_angle : float, optional
Minimum angle [-] (default 1e-10).
Note
----
set_minimum and get_minimum are derived after set_printoptions and
get_printoptions from arrayprint.py in numpy.
"""
global _min_freq, _min_time, _min_off, _min_res, _min_angle
if min_freq is not None:
_min_freq = min_freq
if min_time is not None:
_min_time = min_time
if min_off is not None:
_min_off = min_off
if min_res is not None:
_min_res = min_res
if min_angle is not None:
_min_angle = min_angle | [
"def",
"set_minimum",
"(",
"min_freq",
"=",
"None",
",",
"min_time",
"=",
"None",
",",
"min_off",
"=",
"None",
",",
"min_res",
"=",
"None",
",",
"min_angle",
"=",
"None",
")",
":",
"global",
"_min_freq",
",",
"_min_time",
",",
"_min_off",
",",
"_min_res"... | r"""
Set minimum values of parameters.
The given parameters are set to its minimum value if they are smaller.
Parameters
----------
min_freq : float, optional
Minimum frequency [Hz] (default 1e-20 Hz).
min_time : float, optional
Minimum time [s] (default 1e-20 s).
min_off : float, optional
Minimum offset [m] (default 1e-3 m).
Also used to round src- & rec-coordinates.
min_res : float, optional
Minimum horizontal and vertical resistivity [Ohm.m] (default 1e-20).
min_angle : float, optional
Minimum angle [-] (default 1e-10).
Note
----
set_minimum and get_minimum are derived after set_printoptions and
get_printoptions from arrayprint.py in numpy. | [
"r",
"Set",
"minimum",
"values",
"of",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1789-L1828 |
26,093 | empymod/empymod | empymod/utils.py | get_minimum | def get_minimum():
r"""
Return the current minimum values.
Returns
-------
min_vals : dict
Dictionary of current minimum values with keys
- min_freq : float
- min_time : float
- min_off : float
- min_res : float
- min_angle : float
For a full description of these options, see `set_minimum`.
Note
----
set_minimum and get_minimum are derived after set_printoptions and
get_printoptions from arrayprint.py in numpy.
"""
d = dict(min_freq=_min_freq,
min_time=_min_time,
min_off=_min_off,
min_res=_min_res,
min_angle=_min_angle)
return d | python | def get_minimum():
r"""
Return the current minimum values.
Returns
-------
min_vals : dict
Dictionary of current minimum values with keys
- min_freq : float
- min_time : float
- min_off : float
- min_res : float
- min_angle : float
For a full description of these options, see `set_minimum`.
Note
----
set_minimum and get_minimum are derived after set_printoptions and
get_printoptions from arrayprint.py in numpy.
"""
d = dict(min_freq=_min_freq,
min_time=_min_time,
min_off=_min_off,
min_res=_min_res,
min_angle=_min_angle)
return d | [
"def",
"get_minimum",
"(",
")",
":",
"d",
"=",
"dict",
"(",
"min_freq",
"=",
"_min_freq",
",",
"min_time",
"=",
"_min_time",
",",
"min_off",
"=",
"_min_off",
",",
"min_res",
"=",
"_min_res",
",",
"min_angle",
"=",
"_min_angle",
")",
"return",
"d"
] | r"""
Return the current minimum values.
Returns
-------
min_vals : dict
Dictionary of current minimum values with keys
- min_freq : float
- min_time : float
- min_off : float
- min_res : float
- min_angle : float
For a full description of these options, see `set_minimum`.
Note
----
set_minimum and get_minimum are derived after set_printoptions and
get_printoptions from arrayprint.py in numpy. | [
"r",
"Return",
"the",
"current",
"minimum",
"values",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1831-L1859 |
26,094 | empymod/empymod | empymod/utils.py | _check_var | def _check_var(var, dtype, ndmin, name, shape=None, shape2=None):
r"""Return variable as array of dtype, ndmin; shape-checked."""
if var is None:
raise ValueError
var = np.array(var, dtype=dtype, copy=True, ndmin=ndmin)
if shape:
_check_shape(var, name, shape, shape2)
return var | python | def _check_var(var, dtype, ndmin, name, shape=None, shape2=None):
r"""Return variable as array of dtype, ndmin; shape-checked."""
if var is None:
raise ValueError
var = np.array(var, dtype=dtype, copy=True, ndmin=ndmin)
if shape:
_check_shape(var, name, shape, shape2)
return var | [
"def",
"_check_var",
"(",
"var",
",",
"dtype",
",",
"ndmin",
",",
"name",
",",
"shape",
"=",
"None",
",",
"shape2",
"=",
"None",
")",
":",
"if",
"var",
"is",
"None",
":",
"raise",
"ValueError",
"var",
"=",
"np",
".",
"array",
"(",
"var",
",",
"dt... | r"""Return variable as array of dtype, ndmin; shape-checked. | [
"r",
"Return",
"variable",
"as",
"array",
"of",
"dtype",
"ndmin",
";",
"shape",
"-",
"checked",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1880-L1887 |
26,095 | empymod/empymod | empymod/utils.py | _strvar | def _strvar(a, prec='{:G}'):
r"""Return variable as a string to print, with given precision."""
return ' '.join([prec.format(i) for i in np.atleast_1d(a)]) | python | def _strvar(a, prec='{:G}'):
r"""Return variable as a string to print, with given precision."""
return ' '.join([prec.format(i) for i in np.atleast_1d(a)]) | [
"def",
"_strvar",
"(",
"a",
",",
"prec",
"=",
"'{:G}'",
")",
":",
"return",
"' '",
".",
"join",
"(",
"[",
"prec",
".",
"format",
"(",
"i",
")",
"for",
"i",
"in",
"np",
".",
"atleast_1d",
"(",
"a",
")",
"]",
")"
] | r"""Return variable as a string to print, with given precision. | [
"r",
"Return",
"variable",
"as",
"a",
"string",
"to",
"print",
"with",
"given",
"precision",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1890-L1892 |
26,096 | empymod/empymod | empymod/utils.py | _check_min | def _check_min(par, minval, name, unit, verb):
r"""Check minimum value of parameter."""
scalar = False
if par.shape == ():
scalar = True
par = np.atleast_1d(par)
if minval is not None:
ipar = np.where(par < minval)
par[ipar] = minval
if verb > 0 and np.size(ipar) != 0:
print('* WARNING :: ' + name + ' < ' + str(minval) + ' ' + unit +
' are set to ' + str(minval) + ' ' + unit + '!')
if scalar:
return np.squeeze(par)
else:
return par | python | def _check_min(par, minval, name, unit, verb):
r"""Check minimum value of parameter."""
scalar = False
if par.shape == ():
scalar = True
par = np.atleast_1d(par)
if minval is not None:
ipar = np.where(par < minval)
par[ipar] = minval
if verb > 0 and np.size(ipar) != 0:
print('* WARNING :: ' + name + ' < ' + str(minval) + ' ' + unit +
' are set to ' + str(minval) + ' ' + unit + '!')
if scalar:
return np.squeeze(par)
else:
return par | [
"def",
"_check_min",
"(",
"par",
",",
"minval",
",",
"name",
",",
"unit",
",",
"verb",
")",
":",
"scalar",
"=",
"False",
"if",
"par",
".",
"shape",
"==",
"(",
")",
":",
"scalar",
"=",
"True",
"par",
"=",
"np",
".",
"atleast_1d",
"(",
"par",
")",
... | r"""Check minimum value of parameter. | [
"r",
"Check",
"minimum",
"value",
"of",
"parameter",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1906-L1921 |
26,097 | empymod/empymod | empymod/utils.py | spline_backwards_hankel | def spline_backwards_hankel(ht, htarg, opt):
r"""Check opt if deprecated 'spline' is used.
Returns corrected htarg, opt.
r"""
# Ensure ht is all lowercase
ht = ht.lower()
# Only relevant for 'fht' and 'hqwe', not for 'quad'
if ht in ['fht', 'qwe', 'hqwe']:
# Get corresponding htarg
if ht == 'fht':
htarg = _check_targ(htarg, ['fhtfilt', 'pts_per_dec'])
elif ht in ['qwe', 'hqwe']:
htarg = _check_targ(htarg, ['rtol', 'atol', 'nquad', 'maxint',
'pts_per_dec', 'diff_quad', 'a', 'b', 'limit'])
# If spline (qwe, fht) or lagged (fht)
if opt == 'spline':
# Issue warning
mesg = ("\n The use of `opt='spline'` is deprecated and will " +
"be removed\n in v2.0.0; use the corresponding " +
"setting in `htarg`.")
warnings.warn(mesg, DeprecationWarning)
# Reset opt
opt = None
# Check pts_per_dec; set to old default values if not given
if 'pts_per_dec' not in htarg:
if ht == 'fht':
htarg['pts_per_dec'] = -1 # Lagged Convolution DLF
elif ht in ['qwe', 'hqwe']:
htarg['pts_per_dec'] = 80 # Splined QWE; old default value
return htarg, opt | python | def spline_backwards_hankel(ht, htarg, opt):
r"""Check opt if deprecated 'spline' is used.
Returns corrected htarg, opt.
r"""
# Ensure ht is all lowercase
ht = ht.lower()
# Only relevant for 'fht' and 'hqwe', not for 'quad'
if ht in ['fht', 'qwe', 'hqwe']:
# Get corresponding htarg
if ht == 'fht':
htarg = _check_targ(htarg, ['fhtfilt', 'pts_per_dec'])
elif ht in ['qwe', 'hqwe']:
htarg = _check_targ(htarg, ['rtol', 'atol', 'nquad', 'maxint',
'pts_per_dec', 'diff_quad', 'a', 'b', 'limit'])
# If spline (qwe, fht) or lagged (fht)
if opt == 'spline':
# Issue warning
mesg = ("\n The use of `opt='spline'` is deprecated and will " +
"be removed\n in v2.0.0; use the corresponding " +
"setting in `htarg`.")
warnings.warn(mesg, DeprecationWarning)
# Reset opt
opt = None
# Check pts_per_dec; set to old default values if not given
if 'pts_per_dec' not in htarg:
if ht == 'fht':
htarg['pts_per_dec'] = -1 # Lagged Convolution DLF
elif ht in ['qwe', 'hqwe']:
htarg['pts_per_dec'] = 80 # Splined QWE; old default value
return htarg, opt | [
"def",
"spline_backwards_hankel",
"(",
"ht",
",",
"htarg",
",",
"opt",
")",
":",
"# Ensure ht is all lowercase",
"ht",
"=",
"ht",
".",
"lower",
"(",
")",
"# Only relevant for 'fht' and 'hqwe', not for 'quad'",
"if",
"ht",
"in",
"[",
"'fht'",
",",
"'qwe'",
",",
"... | r"""Check opt if deprecated 'spline' is used.
Returns corrected htarg, opt.
r | [
"r",
"Check",
"opt",
"if",
"deprecated",
"spline",
"is",
"used",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1937-L1975 |
26,098 | empymod/empymod | empymod/model.py | gpr | def gpr(src, rec, depth, res, freqtime, cf, gain=None, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, xdirect=False,
ht='quad', htarg=None, ft='fft', ftarg=None, opt=None, loop=None,
verb=2):
r"""Return the Ground-Penetrating Radar signal.
THIS FUNCTION IS EXPERIMENTAL, USE WITH CAUTION.
It is rather an example how you can calculate GPR responses; however, DO
NOT RELY ON IT! It works only well with QUAD or QWE (``quad``, ``qwe``) for
the Hankel transform, and with FFT (``fft``) for the Fourier transform.
It calls internally ``dipole`` for the frequency-domain calculation. It
subsequently convolves the response with a Ricker wavelet with central
frequency ``cf``. If signal!=None, it carries out the Fourier transform and
applies a gain to the response.
For input parameters see the function ``dipole``, except for:
Parameters
----------
cf : float
Centre frequency of GPR-signal, in Hz. Sensible values are between
10 MHz and 3000 MHz.
gain : float
Power of gain function. If None, no gain is applied. Only used if
signal!=None.
Returns
-------
EM : ndarray
GPR response
"""
if verb > 2:
print(" GPR : EXPERIMENTAL, USE WITH CAUTION")
print(" > centre freq : " + str(cf))
print(" > gain : " + str(gain))
# === 1. CHECK TIME ============
# Check times and Fourier Transform arguments, get required frequencies
time, freq, ft, ftarg = check_time(freqtime, 0, ft, ftarg, verb)
# === 2. CALL DIPOLE ============
EM = dipole(src, rec, depth, res, freq, None, ab, aniso, epermH, epermV,
mpermH, mpermV, xdirect, ht, htarg, ft, ftarg, opt, loop, verb)
# === 3. GPR STUFF
# Get required parameters
src, nsrc = check_dipole(src, 'src', 0)
rec, nrec = check_dipole(rec, 'rec', 0)
off, _ = get_off_ang(src, rec, nsrc, nrec, 0)
# Reshape output from dipole
EM = EM.reshape((-1, nrec*nsrc), order='F')
# Multiply with ricker wavelet
cfc = -(np.r_[0, freq[:-1]]/cf)**2
fwave = cfc*np.exp(cfc)
EM *= fwave[:, None]
# Do f->t transform
EM, conv = tem(EM, off, freq, time, 0, ft, ftarg)
# In case of QWE/QUAD, print Warning if not converged
conv_warning(conv, ftarg, 'Fourier', verb)
# Apply gain; make pure real
EM *= (1 + np.abs((time*10**9)**gain))[:, None]
EM = EM.real
# Reshape for number of sources
EM = np.squeeze(EM.reshape((-1, nrec, nsrc), order='F'))
return EM | python | def gpr(src, rec, depth, res, freqtime, cf, gain=None, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, xdirect=False,
ht='quad', htarg=None, ft='fft', ftarg=None, opt=None, loop=None,
verb=2):
r"""Return the Ground-Penetrating Radar signal.
THIS FUNCTION IS EXPERIMENTAL, USE WITH CAUTION.
It is rather an example how you can calculate GPR responses; however, DO
NOT RELY ON IT! It works only well with QUAD or QWE (``quad``, ``qwe``) for
the Hankel transform, and with FFT (``fft``) for the Fourier transform.
It calls internally ``dipole`` for the frequency-domain calculation. It
subsequently convolves the response with a Ricker wavelet with central
frequency ``cf``. If signal!=None, it carries out the Fourier transform and
applies a gain to the response.
For input parameters see the function ``dipole``, except for:
Parameters
----------
cf : float
Centre frequency of GPR-signal, in Hz. Sensible values are between
10 MHz and 3000 MHz.
gain : float
Power of gain function. If None, no gain is applied. Only used if
signal!=None.
Returns
-------
EM : ndarray
GPR response
"""
if verb > 2:
print(" GPR : EXPERIMENTAL, USE WITH CAUTION")
print(" > centre freq : " + str(cf))
print(" > gain : " + str(gain))
# === 1. CHECK TIME ============
# Check times and Fourier Transform arguments, get required frequencies
time, freq, ft, ftarg = check_time(freqtime, 0, ft, ftarg, verb)
# === 2. CALL DIPOLE ============
EM = dipole(src, rec, depth, res, freq, None, ab, aniso, epermH, epermV,
mpermH, mpermV, xdirect, ht, htarg, ft, ftarg, opt, loop, verb)
# === 3. GPR STUFF
# Get required parameters
src, nsrc = check_dipole(src, 'src', 0)
rec, nrec = check_dipole(rec, 'rec', 0)
off, _ = get_off_ang(src, rec, nsrc, nrec, 0)
# Reshape output from dipole
EM = EM.reshape((-1, nrec*nsrc), order='F')
# Multiply with ricker wavelet
cfc = -(np.r_[0, freq[:-1]]/cf)**2
fwave = cfc*np.exp(cfc)
EM *= fwave[:, None]
# Do f->t transform
EM, conv = tem(EM, off, freq, time, 0, ft, ftarg)
# In case of QWE/QUAD, print Warning if not converged
conv_warning(conv, ftarg, 'Fourier', verb)
# Apply gain; make pure real
EM *= (1 + np.abs((time*10**9)**gain))[:, None]
EM = EM.real
# Reshape for number of sources
EM = np.squeeze(EM.reshape((-1, nrec, nsrc), order='F'))
return EM | [
"def",
"gpr",
"(",
"src",
",",
"rec",
",",
"depth",
",",
"res",
",",
"freqtime",
",",
"cf",
",",
"gain",
"=",
"None",
",",
"ab",
"=",
"11",
",",
"aniso",
"=",
"None",
",",
"epermH",
"=",
"None",
",",
"epermV",
"=",
"None",
",",
"mpermH",
"=",
... | r"""Return the Ground-Penetrating Radar signal.
THIS FUNCTION IS EXPERIMENTAL, USE WITH CAUTION.
It is rather an example how you can calculate GPR responses; however, DO
NOT RELY ON IT! It works only well with QUAD or QWE (``quad``, ``qwe``) for
the Hankel transform, and with FFT (``fft``) for the Fourier transform.
It calls internally ``dipole`` for the frequency-domain calculation. It
subsequently convolves the response with a Ricker wavelet with central
frequency ``cf``. If signal!=None, it carries out the Fourier transform and
applies a gain to the response.
For input parameters see the function ``dipole``, except for:
Parameters
----------
cf : float
Centre frequency of GPR-signal, in Hz. Sensible values are between
10 MHz and 3000 MHz.
gain : float
Power of gain function. If None, no gain is applied. Only used if
signal!=None.
Returns
-------
EM : ndarray
GPR response | [
"r",
"Return",
"the",
"Ground",
"-",
"Penetrating",
"Radar",
"signal",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/model.py#L1187-L1266 |
26,099 | empymod/empymod | empymod/model.py | dipole_k | def dipole_k(src, rec, depth, res, freq, wavenumber, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, verb=2):
r"""Return the electromagnetic wavenumber-domain field.
Calculate the electromagnetic wavenumber-domain field due to infinitesimal
small electric or magnetic dipole source(s), measured by infinitesimal
small electric or magnetic dipole receiver(s); sources and receivers are
directed along the principal directions x, y, or z, and all sources are at
the same depth, as well as all receivers are at the same depth.
See Also
--------
dipole : Electromagnetic field due to an electromagnetic source (dipoles).
bipole : Electromagnetic field due to an electromagnetic source (bipoles).
fem : Electromagnetic frequency-domain response.
tem : Electromagnetic time-domain response.
Parameters
----------
src, rec : list of floats or arrays
Source and receiver coordinates (m): [x, y, z].
The x- and y-coordinates can be arrays, z is a single value.
The x- and y-coordinates must have the same dimension.
The x- and y-coordinates only matter for the angle-dependent factor.
Sources or receivers placed on a layer interface are considered in the
upper layer.
depth : list
Absolute layer interfaces z (m); #depth = #res - 1
(excluding +/- infinity).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
freq : array_like
Frequencies f (Hz), used to calculate etaH/V and zetaH/V.
wavenumber : array
Wavenumbers lambda (1/m)
ab : int, optional
Source-receiver configuration, defaults to 11.
+---------------+-------+------+------+------+------+------+------+
| | electric source | magnetic source |
+===============+=======+======+======+======+======+======+======+
| | **x**| **y**| **z**| **x**| **y**| **z**|
+---------------+-------+------+------+------+------+------+------+
| | **x** | 11 | 12 | 13 | 14 | 15 | 16 |
+ **electric** +-------+------+------+------+------+------+------+
| | **y** | 21 | 22 | 23 | 24 | 25 | 26 |
+ **receiver** +-------+------+------+------+------+------+------+
| | **z** | 31 | 32 | 33 | 34 | 35 | 36 |
+---------------+-------+------+------+------+------+------+------+
| | **x** | 41 | 42 | 43 | 44 | 45 | 46 |
+ **magnetic** +-------+------+------+------+------+------+------+
| | **y** | 51 | 52 | 53 | 54 | 55 | 56 |
+ **receiver** +-------+------+------+------+------+------+------+
| | **z** | 61 | 62 | 63 | 64 | 65 | 66 |
+---------------+-------+------+------+------+------+------+------+
aniso : array_like, optional
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
Defaults to ones.
epermH, epermV : array_like, optional
Relative horizontal/vertical electric permittivities
epsilon_h/epsilon_v (-);
#epermH = #epermV = #res. Default is ones.
mpermH, mpermV : array_like, optional
Relative horizontal/vertical magnetic permeabilities mu_h/mu_v (-);
#mpermH = #mpermV = #res. Default is ones.
verb : {0, 1, 2, 3, 4}, optional
Level of verbosity, default is 2:
- 0: Print nothing.
- 1: Print warnings.
- 2: Print additional runtime and kernel calls
- 3: Print additional start/stop, condensed parameter information.
- 4: Print additional full parameter information
Returns
-------
PJ0, PJ1 : array
Wavenumber-domain EM responses:
- PJ0: Wavenumber-domain solution for the kernel with a Bessel
function of the first kind of order zero.
- PJ1: Wavenumber-domain solution for the kernel with a Bessel
function of the first kind of order one.
Examples
--------
>>> import numpy as np
>>> from empymod.model import dipole_k
>>> src = [0, 0, 100]
>>> rec = [5000, 0, 200]
>>> depth = [0, 300, 1000, 1050]
>>> res = [1e20, .3, 1, 50, 1]
>>> freq = 1
>>> wavenrs = np.logspace(-3.7, -3.6, 10)
>>> PJ0, PJ1 = dipole_k(src, rec, depth, res, freq, wavenrs, verb=0)
>>> print(PJ0)
[ -1.02638329e-08 +4.91531529e-09j -1.05289724e-08 +5.04222413e-09j
-1.08009148e-08 +5.17238608e-09j -1.10798310e-08 +5.30588284e-09j
-1.13658957e-08 +5.44279805e-09j -1.16592877e-08 +5.58321732e-09j
-1.19601897e-08 +5.72722830e-09j -1.22687889e-08 +5.87492067e-09j
-1.25852765e-08 +6.02638626e-09j -1.29098481e-08 +6.18171904e-09j]
>>> print(PJ1)
[ 1.79483705e-10 -6.59235332e-10j 1.88672497e-10 -6.93749344e-10j
1.98325814e-10 -7.30068377e-10j 2.08466693e-10 -7.68286748e-10j
2.19119282e-10 -8.08503709e-10j 2.30308887e-10 -8.50823701e-10j
2.42062030e-10 -8.95356636e-10j 2.54406501e-10 -9.42218177e-10j
2.67371420e-10 -9.91530051e-10j 2.80987292e-10 -1.04342036e-09j]
"""
# === 1. LET'S START ============
t0 = printstartfinish(verb)
# === 2. CHECK INPUT ============
# Check layer parameters (isfullspace not required)
modl = check_model(depth, res, aniso, epermH, epermV, mpermH, mpermV,
False, verb)
depth, res, aniso, epermH, epermV, mpermH, mpermV, _ = modl
# Check frequency => get etaH, etaV, zetaH, and zetaV
f = check_frequency(freq, res, aniso, epermH, epermV, mpermH, mpermV, verb)
freq, etaH, etaV, zetaH, zetaV = f
# Check src-rec configuration
# => Get flags if src or rec or both are magnetic (msrc, mrec)
ab_calc, msrc, mrec = check_ab(ab, verb)
# Check src and rec
src, nsrc = check_dipole(src, 'src', verb)
rec, nrec = check_dipole(rec, 'rec', verb)
# Get angle-dependent factor
off, angle = get_off_ang(src, rec, nsrc, nrec, verb)
factAng = kernel.angle_factor(angle, ab, msrc, mrec)
# Get layer number in which src and rec reside (lsrc/lrec)
lsrc, zsrc = get_layer_nr(src, depth)
lrec, zrec = get_layer_nr(rec, depth)
# === 3. EM-FIELD CALCULATION ============
# Pre-allocate
if off.size == 1 and np.ndim(wavenumber) == 2:
PJ0 = np.zeros((freq.size, wavenumber.shape[0], wavenumber.shape[1]),
dtype=complex)
PJ1 = np.zeros((freq.size, wavenumber.shape[0], wavenumber.shape[1]),
dtype=complex)
else:
PJ0 = np.zeros((freq.size, off.size, wavenumber.size), dtype=complex)
PJ1 = np.zeros((freq.size, off.size, wavenumber.size), dtype=complex)
# If <ab> = 36 (or 63), field is zero
# In `bipole` and in `dipole`, this is taken care of in `fem`. Here we
# have to take care of it separately
if ab_calc not in [36, ]:
# Calculate wavenumber response
J0, J1, J0b = kernel.wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH,
etaV, zetaH, zetaV,
np.atleast_2d(wavenumber), ab_calc,
False, msrc, mrec, False)
# Collect output
if J1 is not None:
PJ1 += factAng[:, np.newaxis]*J1
if ab in [11, 12, 21, 22, 14, 24, 15, 25]: # Because of J2
# J2(kr) = 2/(kr)*J1(kr) - J0(kr)
PJ1 /= off[:, None]
if J0 is not None:
PJ0 += J0
if J0b is not None:
PJ0 += factAng[:, np.newaxis]*J0b
# === 4. FINISHED ============
printstartfinish(verb, t0, 1)
return np.squeeze(PJ0), np.squeeze(PJ1) | python | def dipole_k(src, rec, depth, res, freq, wavenumber, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, verb=2):
r"""Return the electromagnetic wavenumber-domain field.
Calculate the electromagnetic wavenumber-domain field due to infinitesimal
small electric or magnetic dipole source(s), measured by infinitesimal
small electric or magnetic dipole receiver(s); sources and receivers are
directed along the principal directions x, y, or z, and all sources are at
the same depth, as well as all receivers are at the same depth.
See Also
--------
dipole : Electromagnetic field due to an electromagnetic source (dipoles).
bipole : Electromagnetic field due to an electromagnetic source (bipoles).
fem : Electromagnetic frequency-domain response.
tem : Electromagnetic time-domain response.
Parameters
----------
src, rec : list of floats or arrays
Source and receiver coordinates (m): [x, y, z].
The x- and y-coordinates can be arrays, z is a single value.
The x- and y-coordinates must have the same dimension.
The x- and y-coordinates only matter for the angle-dependent factor.
Sources or receivers placed on a layer interface are considered in the
upper layer.
depth : list
Absolute layer interfaces z (m); #depth = #res - 1
(excluding +/- infinity).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
freq : array_like
Frequencies f (Hz), used to calculate etaH/V and zetaH/V.
wavenumber : array
Wavenumbers lambda (1/m)
ab : int, optional
Source-receiver configuration, defaults to 11.
+---------------+-------+------+------+------+------+------+------+
| | electric source | magnetic source |
+===============+=======+======+======+======+======+======+======+
| | **x**| **y**| **z**| **x**| **y**| **z**|
+---------------+-------+------+------+------+------+------+------+
| | **x** | 11 | 12 | 13 | 14 | 15 | 16 |
+ **electric** +-------+------+------+------+------+------+------+
| | **y** | 21 | 22 | 23 | 24 | 25 | 26 |
+ **receiver** +-------+------+------+------+------+------+------+
| | **z** | 31 | 32 | 33 | 34 | 35 | 36 |
+---------------+-------+------+------+------+------+------+------+
| | **x** | 41 | 42 | 43 | 44 | 45 | 46 |
+ **magnetic** +-------+------+------+------+------+------+------+
| | **y** | 51 | 52 | 53 | 54 | 55 | 56 |
+ **receiver** +-------+------+------+------+------+------+------+
| | **z** | 61 | 62 | 63 | 64 | 65 | 66 |
+---------------+-------+------+------+------+------+------+------+
aniso : array_like, optional
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
Defaults to ones.
epermH, epermV : array_like, optional
Relative horizontal/vertical electric permittivities
epsilon_h/epsilon_v (-);
#epermH = #epermV = #res. Default is ones.
mpermH, mpermV : array_like, optional
Relative horizontal/vertical magnetic permeabilities mu_h/mu_v (-);
#mpermH = #mpermV = #res. Default is ones.
verb : {0, 1, 2, 3, 4}, optional
Level of verbosity, default is 2:
- 0: Print nothing.
- 1: Print warnings.
- 2: Print additional runtime and kernel calls
- 3: Print additional start/stop, condensed parameter information.
- 4: Print additional full parameter information
Returns
-------
PJ0, PJ1 : array
Wavenumber-domain EM responses:
- PJ0: Wavenumber-domain solution for the kernel with a Bessel
function of the first kind of order zero.
- PJ1: Wavenumber-domain solution for the kernel with a Bessel
function of the first kind of order one.
Examples
--------
>>> import numpy as np
>>> from empymod.model import dipole_k
>>> src = [0, 0, 100]
>>> rec = [5000, 0, 200]
>>> depth = [0, 300, 1000, 1050]
>>> res = [1e20, .3, 1, 50, 1]
>>> freq = 1
>>> wavenrs = np.logspace(-3.7, -3.6, 10)
>>> PJ0, PJ1 = dipole_k(src, rec, depth, res, freq, wavenrs, verb=0)
>>> print(PJ0)
[ -1.02638329e-08 +4.91531529e-09j -1.05289724e-08 +5.04222413e-09j
-1.08009148e-08 +5.17238608e-09j -1.10798310e-08 +5.30588284e-09j
-1.13658957e-08 +5.44279805e-09j -1.16592877e-08 +5.58321732e-09j
-1.19601897e-08 +5.72722830e-09j -1.22687889e-08 +5.87492067e-09j
-1.25852765e-08 +6.02638626e-09j -1.29098481e-08 +6.18171904e-09j]
>>> print(PJ1)
[ 1.79483705e-10 -6.59235332e-10j 1.88672497e-10 -6.93749344e-10j
1.98325814e-10 -7.30068377e-10j 2.08466693e-10 -7.68286748e-10j
2.19119282e-10 -8.08503709e-10j 2.30308887e-10 -8.50823701e-10j
2.42062030e-10 -8.95356636e-10j 2.54406501e-10 -9.42218177e-10j
2.67371420e-10 -9.91530051e-10j 2.80987292e-10 -1.04342036e-09j]
"""
# === 1. LET'S START ============
t0 = printstartfinish(verb)
# === 2. CHECK INPUT ============
# Check layer parameters (isfullspace not required)
modl = check_model(depth, res, aniso, epermH, epermV, mpermH, mpermV,
False, verb)
depth, res, aniso, epermH, epermV, mpermH, mpermV, _ = modl
# Check frequency => get etaH, etaV, zetaH, and zetaV
f = check_frequency(freq, res, aniso, epermH, epermV, mpermH, mpermV, verb)
freq, etaH, etaV, zetaH, zetaV = f
# Check src-rec configuration
# => Get flags if src or rec or both are magnetic (msrc, mrec)
ab_calc, msrc, mrec = check_ab(ab, verb)
# Check src and rec
src, nsrc = check_dipole(src, 'src', verb)
rec, nrec = check_dipole(rec, 'rec', verb)
# Get angle-dependent factor
off, angle = get_off_ang(src, rec, nsrc, nrec, verb)
factAng = kernel.angle_factor(angle, ab, msrc, mrec)
# Get layer number in which src and rec reside (lsrc/lrec)
lsrc, zsrc = get_layer_nr(src, depth)
lrec, zrec = get_layer_nr(rec, depth)
# === 3. EM-FIELD CALCULATION ============
# Pre-allocate
if off.size == 1 and np.ndim(wavenumber) == 2:
PJ0 = np.zeros((freq.size, wavenumber.shape[0], wavenumber.shape[1]),
dtype=complex)
PJ1 = np.zeros((freq.size, wavenumber.shape[0], wavenumber.shape[1]),
dtype=complex)
else:
PJ0 = np.zeros((freq.size, off.size, wavenumber.size), dtype=complex)
PJ1 = np.zeros((freq.size, off.size, wavenumber.size), dtype=complex)
# If <ab> = 36 (or 63), field is zero
# In `bipole` and in `dipole`, this is taken care of in `fem`. Here we
# have to take care of it separately
if ab_calc not in [36, ]:
# Calculate wavenumber response
J0, J1, J0b = kernel.wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH,
etaV, zetaH, zetaV,
np.atleast_2d(wavenumber), ab_calc,
False, msrc, mrec, False)
# Collect output
if J1 is not None:
PJ1 += factAng[:, np.newaxis]*J1
if ab in [11, 12, 21, 22, 14, 24, 15, 25]: # Because of J2
# J2(kr) = 2/(kr)*J1(kr) - J0(kr)
PJ1 /= off[:, None]
if J0 is not None:
PJ0 += J0
if J0b is not None:
PJ0 += factAng[:, np.newaxis]*J0b
# === 4. FINISHED ============
printstartfinish(verb, t0, 1)
return np.squeeze(PJ0), np.squeeze(PJ1) | [
"def",
"dipole_k",
"(",
"src",
",",
"rec",
",",
"depth",
",",
"res",
",",
"freq",
",",
"wavenumber",
",",
"ab",
"=",
"11",
",",
"aniso",
"=",
"None",
",",
"epermH",
"=",
"None",
",",
"epermV",
"=",
"None",
",",
"mpermH",
"=",
"None",
",",
"mpermV... | r"""Return the electromagnetic wavenumber-domain field.
Calculate the electromagnetic wavenumber-domain field due to infinitesimal
small electric or magnetic dipole source(s), measured by infinitesimal
small electric or magnetic dipole receiver(s); sources and receivers are
directed along the principal directions x, y, or z, and all sources are at
the same depth, as well as all receivers are at the same depth.
See Also
--------
dipole : Electromagnetic field due to an electromagnetic source (dipoles).
bipole : Electromagnetic field due to an electromagnetic source (bipoles).
fem : Electromagnetic frequency-domain response.
tem : Electromagnetic time-domain response.
Parameters
----------
src, rec : list of floats or arrays
Source and receiver coordinates (m): [x, y, z].
The x- and y-coordinates can be arrays, z is a single value.
The x- and y-coordinates must have the same dimension.
The x- and y-coordinates only matter for the angle-dependent factor.
Sources or receivers placed on a layer interface are considered in the
upper layer.
depth : list
Absolute layer interfaces z (m); #depth = #res - 1
(excluding +/- infinity).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
freq : array_like
Frequencies f (Hz), used to calculate etaH/V and zetaH/V.
wavenumber : array
Wavenumbers lambda (1/m)
ab : int, optional
Source-receiver configuration, defaults to 11.
+---------------+-------+------+------+------+------+------+------+
| | electric source | magnetic source |
+===============+=======+======+======+======+======+======+======+
| | **x**| **y**| **z**| **x**| **y**| **z**|
+---------------+-------+------+------+------+------+------+------+
| | **x** | 11 | 12 | 13 | 14 | 15 | 16 |
+ **electric** +-------+------+------+------+------+------+------+
| | **y** | 21 | 22 | 23 | 24 | 25 | 26 |
+ **receiver** +-------+------+------+------+------+------+------+
| | **z** | 31 | 32 | 33 | 34 | 35 | 36 |
+---------------+-------+------+------+------+------+------+------+
| | **x** | 41 | 42 | 43 | 44 | 45 | 46 |
+ **magnetic** +-------+------+------+------+------+------+------+
| | **y** | 51 | 52 | 53 | 54 | 55 | 56 |
+ **receiver** +-------+------+------+------+------+------+------+
| | **z** | 61 | 62 | 63 | 64 | 65 | 66 |
+---------------+-------+------+------+------+------+------+------+
aniso : array_like, optional
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
Defaults to ones.
epermH, epermV : array_like, optional
Relative horizontal/vertical electric permittivities
epsilon_h/epsilon_v (-);
#epermH = #epermV = #res. Default is ones.
mpermH, mpermV : array_like, optional
Relative horizontal/vertical magnetic permeabilities mu_h/mu_v (-);
#mpermH = #mpermV = #res. Default is ones.
verb : {0, 1, 2, 3, 4}, optional
Level of verbosity, default is 2:
- 0: Print nothing.
- 1: Print warnings.
- 2: Print additional runtime and kernel calls
- 3: Print additional start/stop, condensed parameter information.
- 4: Print additional full parameter information
Returns
-------
PJ0, PJ1 : array
Wavenumber-domain EM responses:
- PJ0: Wavenumber-domain solution for the kernel with a Bessel
function of the first kind of order zero.
- PJ1: Wavenumber-domain solution for the kernel with a Bessel
function of the first kind of order one.
Examples
--------
>>> import numpy as np
>>> from empymod.model import dipole_k
>>> src = [0, 0, 100]
>>> rec = [5000, 0, 200]
>>> depth = [0, 300, 1000, 1050]
>>> res = [1e20, .3, 1, 50, 1]
>>> freq = 1
>>> wavenrs = np.logspace(-3.7, -3.6, 10)
>>> PJ0, PJ1 = dipole_k(src, rec, depth, res, freq, wavenrs, verb=0)
>>> print(PJ0)
[ -1.02638329e-08 +4.91531529e-09j -1.05289724e-08 +5.04222413e-09j
-1.08009148e-08 +5.17238608e-09j -1.10798310e-08 +5.30588284e-09j
-1.13658957e-08 +5.44279805e-09j -1.16592877e-08 +5.58321732e-09j
-1.19601897e-08 +5.72722830e-09j -1.22687889e-08 +5.87492067e-09j
-1.25852765e-08 +6.02638626e-09j -1.29098481e-08 +6.18171904e-09j]
>>> print(PJ1)
[ 1.79483705e-10 -6.59235332e-10j 1.88672497e-10 -6.93749344e-10j
1.98325814e-10 -7.30068377e-10j 2.08466693e-10 -7.68286748e-10j
2.19119282e-10 -8.08503709e-10j 2.30308887e-10 -8.50823701e-10j
2.42062030e-10 -8.95356636e-10j 2.54406501e-10 -9.42218177e-10j
2.67371420e-10 -9.91530051e-10j 2.80987292e-10 -1.04342036e-09j] | [
"r",
"Return",
"the",
"electromagnetic",
"wavenumber",
"-",
"domain",
"field",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/model.py#L1269-L1457 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.