function
stringlengths 11
56k
| repo_name
stringlengths 5
60
| features
sequence |
---|---|---|
def execute_sql(self, *a, **kw):
try:
return super(SQLInsertCompiler, self).execute_sql(*a, **kw)
except InvalidGaeKey:
raise DatabaseError("Ivalid value for a key filter on GAE.") | potatolondon/djangoappengine-1-4 | [
3,
2,
3,
1,
1358943676
] |
def insert(self, data_list, return_id=False):
opts = self.query.get_meta()
unindexed_fields = get_model_indexes(self.query.model)['unindexed']
unindexed_cols = [opts.get_field(name).column
for name in unindexed_fields]
entity_list = []
ancestor_keys = []
for data in data_list:
properties = {}
kwds = {'unindexed_properties': unindexed_cols}
for column, value in data.items():
# The value will already be a db.Key, but the Entity
# constructor takes a name or id of the key, and will
# automatically create a new key if neither is given.
if column == opts.pk.column:
if value is not None:
if isinstance(value, AncestorKey):
ancestor_keys.append(value)
kwds['id'] = value.id()
kwds['name'] = value.name()
kwds['parent'] = value.parent()
# GAE does not store empty lists (and even does not allow
# passing empty lists to Entity.update) so skip them.
elif isinstance(value, (tuple, list)) and not len(value):
continue
# Use column names as property names.
else:
properties[column] = value
entity = Entity(opts.db_table, **kwds)
entity.update(properties)
entity_list.append(entity)
keys = Put(entity_list)
if ancestor_keys and len(ancestor_keys) == len(keys):
for ancestor_key, key in zip(ancestor_keys, keys):
ancestor_key.key_id = key.id_or_name()
return keys[0] if isinstance(keys, list) else keys | potatolondon/djangoappengine-1-4 | [
3,
2,
3,
1,
1358943676
] |
def execute_sql(self, result_type=MULTI):
# Modify query to fetch pks only and then execute the query
# to get all pks.
pk_field = self.query.model._meta.pk
self.query.add_immediate_loading([pk_field.name])
pks = [row for row in self.results_iter()]
self.update_entities(pks, pk_field)
return len(pks) | potatolondon/djangoappengine-1-4 | [
3,
2,
3,
1,
1358943676
] |
def update_entity(self, pk, pk_field):
gae_query = self.build_query()
entity = Get(self.ops.value_for_db(pk, pk_field))
if not gae_query.matches_filters(entity):
return
for field, _, value in self.query.values:
if hasattr(value, 'prepare_database_save'):
value = value.prepare_database_save(field)
else:
value = field.get_db_prep_save(value,
connection=self.connection)
if hasattr(value, 'evaluate'):
assert not value.negated
assert not value.subtree_parents
value = ExpressionEvaluator(value, self.query, entity,
allow_joins=False)
if hasattr(value, 'as_sql'):
value = value.as_sql(lambda n: n, self.connection)
entity[field.column] = self.ops.value_for_db(value, field)
Put(entity) | potatolondon/djangoappengine-1-4 | [
3,
2,
3,
1,
1358943676
] |
def _af_rmul(a, b):
"""
Return the product b*a; input and output are array forms. The ith value
is a[b[i]].
Examples
========
>>> Permutation.print_cyclic = False
>>> a, b = [1, 0, 2], [0, 2, 1]
>>> _af_rmul(a, b)
[1, 2, 0]
>>> [a[b[i]] for i in range(3)]
[1, 2, 0]
This handles the operands in reverse order compared to the ``*`` operator:
>>> a = Permutation(a)
>>> b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]
See Also
========
rmul, _af_rmuln
"""
return [a[i] for i in b] | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def _af_parity(pi):
"""
Computes the parity of a permutation in array form.
The parity of a permutation reflects the parity of the
number of inversions in the permutation, i.e., the
number of pairs of x and y such that x > y but p[x] < p[y].
Examples
========
>>> _af_parity([0, 1, 2, 3])
0
>>> _af_parity([3, 2, 0, 1])
1
See Also
========
Permutation
"""
n = len(pi)
a = [0] * n
c = 0
for j in range(n):
if a[j] == 0:
c += 1
a[j] = 1
i = j
while pi[i] != j:
i = pi[i]
a[i] = 1
return (n - c) % 2 | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def _af_pow(a, n):
"""
Routine for finding powers of a permutation.
Examples
========
>>> Permutation.print_cyclic = False
>>> p = Permutation([2, 0, 3, 1])
>>> p.order()
4
>>> _af_pow(p._array_form, 4)
[0, 1, 2, 3]
"""
if n == 0:
return list(range(len(a)))
if n < 0:
return _af_pow(_af_invert(a), -n)
if n == 1:
return a[:]
elif n == 2:
b = [a[i] for i in a]
elif n == 3:
b = [a[a[i]] for i in a]
elif n == 4:
b = [a[a[a[i]]] for i in a]
else:
# use binary multiplication
b = list(range(len(a)))
while 1:
if n & 1:
b = [b[i] for i in a]
n -= 1
if not n:
break
if n % 4 == 0:
a = [a[a[a[i]]] for i in a]
n = n // 4
elif n % 2 == 0:
a = [a[i] for i in a]
n = n // 2
return b | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def __missing__(self, arg):
"""Enter arg into dictionary and return arg."""
arg = as_int(arg)
self[arg] = arg
return arg | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def __call__(self, *other):
"""Return product of cycles processed from R to L.
Examples
========
>>> Cycle(1, 2)(2, 3)
Cycle(1, 3, 2)
An instance of a Cycle will automatically parse list-like
objects and Permutations that are on the right. It is more
flexible than the Permutation in that all elements need not
be present:
>>> a = Cycle(1, 2)
>>> a(2, 3)
Cycle(1, 3, 2)
>>> a(2, 3)(4, 5)
Cycle(1, 3, 2)(4, 5)
"""
rv = Cycle(*other)
for k, v in zip(list(self.keys()), [rv[v] for v in self.values()]):
rv[k] = v
return rv | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def __repr__(self):
"""We want it to print as a Cycle, not as a dict.
Examples
========
>>> Cycle(1, 2)
Cycle(1, 2)
>>> print(_)
Cycle(1, 2)
>>> list(Cycle(1, 2).items())
[(1, 2), (2, 1)]
"""
if not self:
return 'Cycle()'
cycles = Permutation(self).cyclic_form
s = ''.join(str(tuple(c)) for c in cycles)
big = self.size - 1
if not any(i == big for c in cycles for i in c):
s += f'({big})'
return f'Cycle{s}' | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def size(self):
if not self:
return 0
return max(self.keys()) + 1 | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def __new__(cls, *args, **kwargs):
"""
Constructor for the Permutation object from a list or a
list of lists in which all elements of the permutation may
appear only once.
Examples
========
>>> Permutation.print_cyclic = False
Permutations entered in array-form are left unaltered:
>>> Permutation([0, 2, 1])
Permutation([0, 2, 1])
Permutations entered in cyclic form are converted to array form;
singletons need not be entered, but can be entered to indicate the
largest element:
>>> Permutation([[4, 5, 6], [0, 1]])
Permutation([1, 0, 2, 3, 5, 6, 4])
>>> Permutation([[4, 5, 6], [0, 1], [19]])
Permutation([1, 0, 2, 3, 5, 6, 4], size=20)
All manipulation of permutations assumes that the smallest element
is 0 (in keeping with 0-based indexing in Python) so if the 0 is
missing when entering a permutation in array form, an error will be
raised:
>>> Permutation([2, 1])
Traceback (most recent call last):
...
ValueError: Integers 0 through 2 must be present.
If a permutation is entered in cyclic form, it can be entered without
singletons and the ``size`` specified so those values can be filled
in, otherwise the array form will only extend to the maximum value
in the cycles:
>>> Permutation([[1, 4], [3, 5, 2]], size=10)
Permutation([0, 4, 3, 5, 1, 2], size=10)
>>> _.array_form
[0, 4, 3, 5, 1, 2, 6, 7, 8, 9]
"""
size = kwargs.pop('size', None)
if size is not None:
size = int(size)
# a) ()
# b) (1) = identity
# c) (1, 2) = cycle
# d) ([1, 2, 3]) = array form
# e) ([[1, 2]]) = cyclic form
# f) (Cycle) = conversion to permutation
# g) (Permutation) = adjust size or return copy
ok = True
if not args: # a
return _af_new(list(range(size or 0)))
elif len(args) > 1: # c
return _af_new(Cycle(*args).list(size))
if len(args) == 1:
a = args[0]
if isinstance(a, Perm): # g
if size is None or size == a.size:
return a
return Perm(a.array_form, size=size)
if isinstance(a, Cycle): # f
return _af_new(a.list(size))
if not is_sequence(a): # b
return _af_new(list(range(a + 1)))
if has_variety(is_sequence(ai) for ai in a):
ok = False
else:
ok = False
if not ok:
raise ValueError('Permutation argument must be a list of ints, '
'a list of lists, Permutation or Cycle.')
# safe to assume args are valid; this also makes a copy
# of the args
args = list(args[0])
is_cycle = args and is_sequence(args[0])
if is_cycle: # e
args = [[int(i) for i in c] for c in args]
else: # d
args = [int(i) for i in args]
# if there are n elements present, 0, 1, ..., n-1 should be present
# unless a cycle notation has been provided. A 0 will be added
# for convenience in case one wants to enter permutations where
# counting starts from 1.
temp = flatten(args)
if has_dups(temp):
if is_cycle:
raise ValueError('there were repeated elements; to resolve '
f"cycles use Cycle{''.join([str(tuple(c)) for c in args])}.")
raise ValueError('there were repeated elements.')
temp = set(temp)
if not is_cycle and \
any(i not in temp for i in range(len(temp))):
raise ValueError(f'Integers 0 through {max(temp)} must be present.')
if is_cycle:
# it's not necessarily canonical so we won't store
# it -- use the array form instead
c = Cycle()
for ci in args:
c = c(*ci)
aform = c.list()
else:
aform = list(args)
if size and size > len(aform):
# don't allow for truncation of permutation which
# might split a cycle and lead to an invalid aform
# but do allow the permutation size to be increased
aform.extend(list(range(len(aform), size)))
size = len(aform)
args = Tuple(*[sympify(_) for _ in aform])
obj = Basic.__new__(cls, args)
obj._array_form = aform
obj._size = size
return obj | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def _af_new(perm):
"""A method to produce a Permutation object from a list;
the list is bound to the _array_form attribute, so it must
not be modified; this method is meant for internal use only;
the list ``a`` is supposed to be generated as a temporary value
in a method, so p = Perm._af_new(a) is the only object
to hold a reference to ``a``::
Examples
========
>>> Permutation.print_cyclic = False
>>> a = [2, 1, 3, 0]
>>> p = Permutation._af_new(a)
>>> p
Permutation([2, 1, 3, 0])
"""
p = Basic.__new__(Perm, Tuple(perm))
p._array_form = perm
p._size = len(perm)
return p | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def array_form(self):
"""
Return a copy of the attribute _array_form
Examples
========
>>> Permutation.print_cyclic = False
>>> p = Permutation([[2, 0], [3, 1]])
>>> p.array_form
[2, 3, 0, 1]
>>> Permutation([[2, 0, 3, 1]]).array_form
[3, 2, 0, 1]
>>> Permutation([2, 0, 3, 1]).array_form
[2, 0, 3, 1]
>>> Permutation([[1, 2], [4, 5]]).array_form
[0, 2, 1, 3, 5, 4]
"""
return self._array_form[:] | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def cyclic_form(self):
"""
This is used to convert to the cyclic notation
from the canonical notation. Singletons are omitted.
Examples
========
>>> Permutation.print_cyclic = False
>>> p = Permutation([0, 3, 1, 2])
>>> p.cyclic_form
[[1, 3, 2]]
>>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form
[[0, 1], [3, 4]]
See Also
========
array_form, full_cyclic_form
"""
if self._cyclic_form is not None:
return list(self._cyclic_form)
array_form = self.array_form
unchecked = [True] * len(array_form)
cyclic_form = []
for i in range(len(array_form)):
if unchecked[i]:
cycle = []
cycle.append(i)
unchecked[i] = False
j = i
while unchecked[array_form[j]]:
j = array_form[j]
cycle.append(j)
unchecked[j] = False
if len(cycle) > 1:
cyclic_form.append(cycle)
assert cycle == list(minlex(cycle, is_set=True))
cyclic_form.sort()
self._cyclic_form = cyclic_form[:]
return cyclic_form | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def full_cyclic_form(self):
"""Return permutation in cyclic form including singletons.
Examples
========
>>> Permutation([0, 2, 1]).full_cyclic_form
[[0], [1, 2]]
"""
need = set(range(self.size)) - set(flatten(self.cyclic_form))
rv = self.cyclic_form
rv.extend([[i] for i in need])
rv.sort()
return rv | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def size(self):
"""
Returns the number of elements in the permutation.
Examples
========
>>> Permutation([[3, 2], [0, 1]]).size
4
See Also
========
cardinality, length, order, rank
"""
return self._size | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def __add__(self, other):
"""Return permutation that is other higher in rank than self.
The rank is the lexicographical rank, with the identity permutation
having rank of 0.
Examples
========
>>> Permutation.print_cyclic = False
>>> I = Permutation([0, 1, 2, 3])
>>> a = Permutation([2, 1, 3, 0])
>>> I + a.rank() == a
True
See Also
========
__sub__, inversion_vector
"""
rank = (self.rank() + other) % self.cardinality
rv = Perm.unrank_lex(self.size, rank)
rv._rank = rank
return rv | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def rmul(*args):
"""
Return product of Permutations [a, b, c, ...] as the Permutation whose
ith value is a(b(c(i))).
a, b, c, ... can be Permutation objects or tuples.
Examples
========
>>> Permutation.print_cyclic = False
>>> a, b = [1, 0, 2], [0, 2, 1]
>>> a = Permutation(a)
>>> b = Permutation(b)
>>> list(Permutation.rmul(a, b))
[1, 2, 0]
>>> [a(b(i)) for i in range(3)]
[1, 2, 0]
This handles the operands in reverse order compared to the ``*`` operator:
>>> a = Permutation(a)
>>> b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]
Notes
=====
All items in the sequence will be parsed by Permutation as
necessary as long as the first item is a Permutation:
>>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b)
True
The reverse order of arguments will raise a TypeError.
"""
rv = args[0]
for i in range(1, len(args)):
rv = args[i]*rv
return rv | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def rmul_with_af(*args):
"""
Same as rmul, but the elements of args are Permutation objects
which have _array_form.
"""
a = [x._array_form for x in args]
rv = _af_new(_af_rmuln(*a))
return rv | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def __rmul__(self, other):
"""This is needed to coerse other to Permutation in rmul."""
return Perm(other)*self | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def commutes_with(self, other):
"""
Checks if the elements are commuting.
Examples
========
>>> a = Permutation([1, 4, 3, 0, 2, 5])
>>> b = Permutation([0, 1, 2, 3, 4, 5])
>>> a.commutes_with(b)
True
>>> b = Permutation([2, 3, 5, 4, 1, 0])
>>> a.commutes_with(b)
False
"""
a = self.array_form
b = other.array_form
return _af_commutes_with(a, b) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def __rxor__(self, i):
"""Return self(i) when ``i`` is an int.
Examples
========
>>> p = Permutation(1, 2, 9)
>>> 2 ^ p == p(2) == 9
True
"""
if int(i) == i:
return self(i)
else:
raise NotImplementedError(
f'i^p = p(i) when i is an integer, not {i}.') | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def transpositions(self):
"""
Return the permutation decomposed into a list of transpositions.
It is always possible to express a permutation as the product of
transpositions, see [1]
Examples
========
>>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]])
>>> t = p.transpositions()
>>> t
[(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)]
>>> print(''.join(str(c) for c in t))
(0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2)
>>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p
True
References
==========
1. https://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties
"""
a = self.cyclic_form
res = []
for x in a:
nx = len(x)
if nx == 2:
res.append(tuple(x))
elif nx > 2:
first = x[0]
for y in x[nx - 1:0:-1]:
res.append((first, y))
return res | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def from_sequence(cls, i, key=None):
"""Return the permutation needed to obtain ``i`` from the sorted
elements of ``i``. If custom sorting is desired, a key can be given.
Examples
========
>>> Permutation.print_cyclic = True
>>> Permutation.from_sequence('SymPy')
Permutation(4)(0, 1, 3)
>>> _(sorted('SymPy'))
['S', 'y', 'm', 'P', 'y']
>>> Permutation.from_sequence('SymPy', key=lambda x: x.lower())
Permutation(4)(0, 2)(1, 3)
"""
ic = list(zip(i, range(len(i))))
if key:
ic.sort(key=lambda x: key(x[0]))
else:
ic.sort()
return ~Permutation([i[1] for i in ic]) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def __iter__(self):
"""Yield elements from array form.
Examples
========
>>> list(Permutation(range(3)))
[0, 1, 2]
"""
for i in self.array_form:
yield i | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def atoms(self):
"""
Returns all the elements of a permutation
Examples
========
>>> Permutation([0, 1, 2, 3, 4, 5]).atoms()
{0, 1, 2, 3, 4, 5}
>>> Permutation([[0, 1], [2, 3], [4, 5]]).atoms()
{0, 1, 2, 3, 4, 5}
"""
return set(self.array_form) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def unrank_nonlex(cls, n, r):
"""
This is a linear time unranking algorithm that does not
respect lexicographic order [3].
Examples
========
>>> Permutation.print_cyclic = False
>>> Permutation.unrank_nonlex(4, 5)
Permutation([2, 0, 3, 1])
>>> Permutation.unrank_nonlex(4, -1)
Permutation([0, 1, 2, 3])
See Also
========
next_nonlex, rank_nonlex
"""
def _unrank1(n, r, a):
if n > 0:
a[n - 1], a[r % n] = a[r % n], a[n - 1]
_unrank1(n - 1, r//n, a)
id_perm = list(range(n))
n = int(n)
r = r % ifac(n)
_unrank1(n, r, id_perm)
return _af_new(id_perm) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def _rank1(n, perm, inv_perm):
if n == 1:
return 0
s = perm[n - 1]
t = inv_perm[n - 1]
perm[n - 1], perm[t] = perm[t], s
inv_perm[n - 1], inv_perm[s] = inv_perm[s], t
return s + n*_rank1(n - 1, perm, inv_perm) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def next_nonlex(self):
"""
Returns the next permutation in nonlex order [3].
If self is the last permutation in this order it returns None.
Examples
========
>>> Permutation.print_cyclic = False
>>> p = Permutation([2, 0, 3, 1])
>>> p.rank_nonlex()
5
>>> p = p.next_nonlex()
>>> p
Permutation([3, 0, 1, 2])
>>> p.rank_nonlex()
6
See Also
========
rank_nonlex, unrank_nonlex
"""
r = self.rank_nonlex()
if r != ifac(self.size) - 1:
return Perm.unrank_nonlex(self.size, r + 1) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def cardinality(self):
"""
Returns the number of all possible permutations.
Examples
========
>>> p = Permutation([0, 1, 2, 3])
>>> p.cardinality
24
See Also
========
length, order, rank, size
"""
return int(ifac(self.size)) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def is_even(self):
"""
Checks if a permutation is even.
Examples
========
>>> p = Permutation([0, 1, 2, 3])
>>> p.is_even
True
>>> p = Permutation([3, 2, 1, 0])
>>> p.is_even
True
See Also
========
is_odd
"""
return not self.is_odd | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def is_odd(self):
"""
Checks if a permutation is odd.
Examples
========
>>> p = Permutation([0, 1, 2, 3])
>>> p.is_odd
False
>>> p = Permutation([3, 2, 0, 1])
>>> p.is_odd
True
See Also
========
is_even
"""
return bool(self.parity() % 2) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def is_Singleton(self):
"""
Checks to see if the permutation contains only one number and is
thus the only possible permutation of this set of numbers
Examples
========
>>> Permutation([0]).is_Singleton
True
>>> Permutation([0, 1]).is_Singleton
False
See Also
========
is_Empty
"""
return self.size == 1 | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def is_Empty(self):
"""
Checks to see if the permutation is a set with zero elements
Examples
========
>>> Permutation([]).is_Empty
True
>>> Permutation([0]).is_Empty
False
See Also
========
is_Singleton
"""
return self.size == 0 | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def is_Identity(self):
"""
Returns True if the Permutation is an identity permutation.
Examples
========
>>> p = Permutation([])
>>> p.is_Identity
True
>>> p = Permutation([[0], [1], [2]])
>>> p.is_Identity
True
>>> p = Permutation([0, 1, 2])
>>> p.is_Identity
True
>>> p = Permutation([0, 2, 1])
>>> p.is_Identity
False
See Also
========
order
"""
af = self.array_form
return not af or all(i == af[i] for i in range(self.size)) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def descents(self):
"""
Returns the positions of descents in a permutation, ie, the location
where p[i] > p[i+1]
Examples
========
>>> p = Permutation([4, 0, 1, 3, 2])
>>> p.descents()
[0, 3]
See Also
========
ascents, inversions, min, max
"""
a = self.array_form
pos = [i for i in range(len(a) - 1) if a[i] > a[i + 1]]
return pos | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def min(self):
"""
The minimum element moved by the permutation.
Examples
========
>>> p = Permutation([0, 1, 4, 3, 2])
>>> p.min()
2
See Also
========
max, descents, ascents, inversions
"""
a = self.array_form
min = len(a)
for i, ai in enumerate(a):
if ai != i and ai < min:
min = ai
return min | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def commutator(self, x):
"""Return the commutator of self and x: ``~x*~self*x*self``
If f and g are part of a group, G, then the commutator of f and g
is the group identity iff f and g commute, i.e. fg == gf.
Examples
========
>>> Permutation.print_cyclic = False
>>> p = Permutation([0, 2, 3, 1])
>>> x = Permutation([2, 0, 3, 1])
>>> c = p.commutator(x)
>>> c
Permutation([2, 1, 3, 0])
>>> c == ~x*~p*x*p
True
>>> I = Permutation(3)
>>> p = [I + i for i in range(6)]
>>> for i in range(len(p)):
... for j in range(len(p)):
... c = p[i].commutator(p[j])
... if p[i]*p[j] == p[j]*p[i]:
... assert c == I
... else:
... assert c != I
...
References
==========
https://en.wikipedia.org/wiki/Commutator
"""
a = self.array_form
b = x.array_form
n = len(a)
if len(b) != n:
raise ValueError('The permutations must be of equal size.')
inva = [None]*n
for i in range(n):
inva[a[i]] = i
invb = [None]*n
for i in range(n):
invb[b[i]] = i
return _af_new([a[b[inva[i]]] for i in invb]) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def order(self):
"""
Computes the order of a permutation.
When the permutation is raised to the power of its
order it equals the identity permutation.
Examples
========
>>> Permutation.print_cyclic = False
>>> p = Permutation([3, 1, 5, 2, 4, 0])
>>> p.order()
4
>>> (p**(p.order()))
Permutation([], size=6)
See Also
========
is_Identity, cardinality, length, rank, size
"""
return functools.reduce(lcm, [len(cycle) for cycle in self.cyclic_form], 1) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def cycle_structure(self):
"""Return the cycle structure of the permutation as a dictionary
indicating the multiplicity of each cycle length.
Examples
========
>>> Permutation.print_cyclic = True
>>> Permutation(3).cycle_structure
{1: 4}
>>> Permutation(0, 4, 3)(1, 2)(5, 6).cycle_structure
{2: 2, 3: 1}
"""
if self._cycle_structure:
rv = self._cycle_structure
else:
rv = defaultdict(int)
singletons = self.size
for c in self.cyclic_form:
rv[len(c)] += 1
singletons -= len(c)
if singletons:
rv[1] = singletons
self._cycle_structure = rv
return dict(rv) # make a copy | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def cycles(self):
"""
Returns the number of cycles contained in the permutation
(including singletons).
Examples
========
>>> Permutation([0, 1, 2]).cycles
3
>>> Permutation([0, 1, 2]).full_cyclic_form
[[0], [1], [2]]
>>> Permutation(0, 1)(2, 3).cycles
2
See Also
========
diofant.functions.combinatorial.numbers.stirling
"""
return len(self.full_cyclic_form) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def runs(self):
"""
Returns the runs of a permutation.
An ascending sequence in a permutation is called a run [5].
Examples
========
>>> p = Permutation([2, 5, 7, 3, 6, 0, 1, 4, 8])
>>> p.runs()
[[2, 5, 7], [3, 6], [0, 1, 4, 8]]
>>> q = Permutation([1, 3, 2, 0])
>>> q.runs()
[[1, 3], [2], [0]]
"""
return runs(self.array_form) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def rank_trotterjohnson(self):
"""
Returns the Trotter Johnson rank, which we get from the minimal
change algorithm. See [4] section 2.4.
Examples
========
>>> p = Permutation([0, 1, 2, 3])
>>> p.rank_trotterjohnson()
0
>>> p = Permutation([0, 2, 1, 3])
>>> p.rank_trotterjohnson()
7
See Also
========
unrank_trotterjohnson, next_trotterjohnson
"""
if self.array_form == [] or self.is_Identity:
return 0
if self.array_form == [1, 0]:
return 1
perm = self.array_form
n = self.size
rank = 0
for j in range(1, n):
k = 1
i = 0
while perm[i] != j:
if perm[i] < j:
k += 1
i += 1
j1 = j + 1
if rank % 2 == 0:
rank = j1*rank + j1 - k
else:
rank = j1*rank + k - 1
return rank | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def unrank_trotterjohnson(cls, size, rank):
"""
Trotter Johnson permutation unranking. See [4] section 2.4.
Examples
========
>>> Permutation.unrank_trotterjohnson(5, 10)
Permutation([0, 3, 1, 2, 4])
See Also
========
rank_trotterjohnson, next_trotterjohnson
"""
perm = [0]*size
r2 = 0
n = ifac(size)
pj = 1
for j in range(2, size + 1):
pj *= j
r1 = (rank * pj) // n
k = r1 - j*r2
if r2 % 2 == 0:
for i in range(j - 1, j - k - 1, -1):
perm[i] = perm[i - 1]
perm[j - k - 1] = j - 1
else:
for i in range(j - 1, k, -1):
perm[i] = perm[i - 1]
perm[k] = j - 1
r2 = r1
return _af_new(perm) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def get_precedence_matrix(self):
"""
Gets the precedence matrix. This is used for computing the
distance between two permutations.
Examples
========
>>> p = Permutation.josephus(3, 6, 1)
>>> Permutation.print_cyclic = False
>>> p
Permutation([2, 5, 3, 1, 4, 0])
>>> p.get_precedence_matrix()
Matrix([
[0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 1, 0],
[1, 1, 0, 1, 1, 1],
[1, 1, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0],
[1, 1, 0, 1, 1, 0]])
See Also
========
get_precedence_distance, get_adjacency_matrix, get_adjacency_distance
"""
m = zeros(self.size)
perm = self.array_form
for i in range(m.rows):
for j in range(i + 1, m.cols):
m[perm[i], perm[j]] = 1
return m | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def get_adjacency_matrix(self):
"""
Computes the adjacency matrix of a permutation.
If job i is adjacent to job j in a permutation p
then we set m[i, j] = 1 where m is the adjacency
matrix of p.
Examples
========
>>> p = Permutation.josephus(3, 6, 1)
>>> p.get_adjacency_matrix()
Matrix([
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0]])
>>> q = Permutation([0, 1, 2, 3])
>>> q.get_adjacency_matrix()
Matrix([
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]])
See Also
========
get_precedence_matrix, get_precedence_distance, get_adjacency_distance
"""
m = zeros(self.size)
perm = self.array_form
for i in range(self.size - 1):
m[perm[i], perm[i + 1]] = 1
return m | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def get_positional_distance(self, other):
"""
Computes the positional distance between two permutations.
Examples
========
>>> p = Permutation([0, 3, 1, 2, 4])
>>> q = Permutation.josephus(4, 5, 2)
>>> r = Permutation([3, 1, 4, 0, 2])
>>> p.get_positional_distance(q)
12
>>> p.get_positional_distance(r)
12
See Also
========
get_precedence_distance, get_adjacency_distance
"""
a = self.array_form
b = other.array_form
if len(a) != len(b):
raise ValueError('The permutations must be of the same size.')
return sum(abs(a[i] - b[i]) for i in range(len(a))) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def josephus(cls, m, n, s=1):
"""Return as a permutation the shuffling of range(n) using the Josephus
scheme in which every m-th item is selected until all have been chosen.
The returned permutation has elements listed by the order in which they
were selected.
The parameter ``s`` stops the selection process when there are ``s``
items remaining and these are selected by continuing the selection,
counting by 1 rather than by ``m``.
Consider selecting every 3rd item from 6 until only 2 remain::
choices chosen
======== ======
012345
01 345 2
01 34 25
01 4 253
0 4 2531
0 25314
253140
Examples
========
>>> Permutation.josephus(3, 6, 2).array_form
[2, 5, 3, 1, 4, 0]
References
==========
* https://en.wikipedia.org/wiki/Flavius_Josephus
* https://en.wikipedia.org/wiki/Josephus_problem
"""
from collections import deque
m -= 1
Q = deque(list(range(n)))
perm = []
while len(Q) > max(s, 1):
for _ in range(m):
Q.append(Q.popleft())
perm.append(Q.popleft())
perm.extend(list(Q))
return Perm(perm) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def from_inversion_vector(cls, inversion):
"""
Calculates the permutation from the inversion vector.
Examples
========
>>> Permutation.print_cyclic = False
>>> Permutation.from_inversion_vector([3, 2, 1, 0, 0])
Permutation([3, 2, 1, 0, 4, 5])
"""
size = len(inversion)
N = list(range(size + 1))
perm = []
try:
for k in range(size):
val = N[inversion[k]]
perm.append(val)
N.remove(val)
except IndexError as exc:
raise ValueError('The inversion vector is not valid.') from exc
perm.extend(N)
return _af_new(perm) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def random(cls, n):
"""
Generates a random permutation of length ``n``.
Uses the underlying Python pseudo-random number generator.
Examples
========
>>> Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1]))
True
"""
perm_array = list(range(n))
random.shuffle(perm_array)
return _af_new(perm_array) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def unrank_lex(cls, size, rank):
"""
Lexicographic permutation unranking.
Examples
========
>>> Permutation.print_cyclic = False
>>> a = Permutation.unrank_lex(5, 10)
>>> a.rank()
10
>>> a
Permutation([0, 2, 4, 1, 3])
See Also
========
rank, next_lex
"""
perm_array = [0] * size
psize = 1
for i in range(size):
new_psize = psize*(i + 1)
d = (rank % new_psize) // psize
rank -= d*psize
perm_array[size - i - 1] = d
for j in range(size - i, size):
if perm_array[j] > d - 1:
perm_array[j] += 1
psize = new_psize
return _af_new(perm_array) | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def _merge(arr, temp, left, mid, right):
"""
Merges two sorted arrays and calculates the inversion count.
Helper function for calculating inversions. This method is
for internal use only.
"""
i = k = left
j = mid
inv_count = 0
while i < mid and j <= right:
if arr[i] < arr[j]:
temp[k] = arr[i]
k += 1
i += 1
else:
temp[k] = arr[j]
k += 1
j += 1
inv_count += (mid - i)
while i < mid:
temp[k] = arr[i]
k += 1
i += 1
if j <= right:
k += right - j + 1
j += right - j + 1
arr[left:k + 1] = temp[left:k + 1]
else:
arr[left:right + 1] = temp[left:right + 1]
return inv_count | diofant/diofant | [
61,
16,
61,
107,
1424619203
] |
def __init__(self, filename, problem, arg):
self.filename = filename
self.problem = problem
self.arg = arg | DecisionSystemsGroup/DSGos | [
2,
1,
2,
1,
1427035979
] |
def pacman_conf_enumerator(path):
filestack = []
current_section = None
filestack.append(open(path))
while len(filestack) > 0:
f = filestack[-1]
line = f.readline()
if len(line) == 0:
# end of file
f.close()
filestack.pop()
continue
line = line.strip()
if len(line) == 0:
continue
if line[0] == '#':
continue
if line[0] == '[' and line[-1] == ']':
current_section = line[1:-1]
continue
if current_section is None:
raise InvalidSyntax(f.name, 'statement outside of a section', line)
# read key, value
key, equal, value = [x.strip() for x in line.partition('=')]
# include files
if equal == '=' and key == 'Include':
filestack.extend(open(f) for f in glob.glob(value))
continue
if current_section != 'options':
# repos only have the Server, SigLevel, Usage options
if key in ('Server', 'SigLevel', 'Usage') and equal == '=':
yield (current_section, key, value)
else:
raise InvalidSyntax(f.name, 'invalid key for repository configuration', line)
continue
if equal == '=':
if key in LIST_OPTIONS:
for val in value.split():
yield (current_section, key, val)
elif key in SINGLE_OPTIONS:
yield (current_section, key, value)
else:
warnings.warn(InvalidSyntax(f.name, 'unrecognized option', key))
else:
if key in BOOLEAN_OPTIONS:
yield (current_section, key, True)
else:
warnings.warn(InvalidSyntax(f.name, 'unrecognized option', key)) | DecisionSystemsGroup/DSGos | [
2,
1,
2,
1,
1427035979
] |
def __init__(self, conf=None, options=None):
super(PacmanConfig, self).__init__()
self['options'] = collections.OrderedDict()
self.options = self['options']
self.repos = collections.OrderedDict()
self.options["RootDir"] = "/"
self.options["DBPath"] = "/var/lib/pacman"
self.options["GPGDir"] = "/etc/pacman.d/gnupg/"
self.options["LogFile"] = "/var/log/pacman.log"
self.options["Architecture"] = os.uname()[-1]
if conf is not None:
self.load_from_file(conf)
if options is not None:
self.load_from_options(options) | DecisionSystemsGroup/DSGos | [
2,
1,
2,
1,
1427035979
] |
def load_from_options(self, options):
global _logmask
if options.root is not None:
self.options["RootDir"] = options.root
if options.dbpath is not None:
self.options["DBPath"] = options.dbpath
if options.gpgdir is not None:
self.options["GPGDir"] = options.gpgdir
if options.arch is not None:
self.options["Architecture"] = options.arch
if options.logfile is not None:
self.options["LogFile"] = options.logfile
if options.cachedir is not None:
self.options["CacheDir"] = [options.cachedir]
if options.debug:
_logmask = 0xffff | DecisionSystemsGroup/DSGos | [
2,
1,
2,
1,
1427035979
] |
def create(kernel):
result = Tangible()
result.template = "object/tangible/gambling/table/shared_table_base.iff"
result.attribute_template_id = -1
result.stfName("item_n","gambling_table") | anhstudios/swganh | [
62,
37,
62,
37,
1297996365
] |
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_mynock.iff"
result.attribute_template_id = 9
result.stfName("monster_name","mynock") | anhstudios/swganh | [
62,
37,
62,
37,
1297996365
] |
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/components/armor/shared_arm_mandal_enhanced_heavy_composite.iff"
result.attribute_template_id = 8
result.stfName("space/space_item","arm_mandal_enhanced_heavy_composite_n") | anhstudios/swganh | [
62,
37,
62,
37,
1297996365
] |
def __init__(self, **kwargs):
"""Initialize module."""
super(RProcess, self).__init__(**kwargs)
self._wants_dense = True
barnes_v = np.asarray([0.1, 0.2, 0.3])
barnes_M = np.asarray([1.e-3, 5.e-3, 1.e-2, 5.e-2])
barnes_a = np.asarray([[2.01, 4.52, 8.16], [0.81, 1.9, 3.2], [
0.56, 1.31, 2.19], [.27, .55, .95]])
barnes_b = np.asarray([[0.28, 0.62, 1.19], [0.19, 0.28, 0.45], [
0.17, 0.21, 0.31], [0.10, 0.13, 0.15]])
barnes_d = np.asarray([[1.12, 1.39, 1.52], [0.86, 1.21, 1.39], [
0.74, 1.13, 1.32], [0.6, 0.9, 1.13]])
self.therm_func_a = RegularGridInterpolator(
(barnes_M, barnes_v), barnes_a, bounds_error=False, fill_value=None)
self.therm_func_b = RegularGridInterpolator(
(barnes_M, barnes_v), barnes_b, bounds_error=False, fill_value=None)
self.therm_func_d = RegularGridInterpolator(
(barnes_M, barnes_v), barnes_d, bounds_error=False, fill_value=None) | guillochon/FriendlyFit | [
33,
47,
33,
38,
1473435475
] |
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_tanc_mite_hue.iff"
result.attribute_template_id = 9
result.stfName("monster_name","tanc_mite") | anhstudios/swganh | [
62,
37,
62,
37,
1297996365
] |
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_deathstar_debris_cultist_hum_m_02.iff"
result.attribute_template_id = 9
result.stfName("obj_n","unknown_creature") | anhstudios/swganh | [
62,
37,
62,
37,
1297996365
] |
def my_append(self, a):
self.append(a) | chrivers/pyjaco | [
142,
18,
142,
42,
1298974725
] |
def resolve(url):
try:
try:
referer = urlparse.parse_qs(urlparse.urlparse(url).query)['referer'][0]
except:
referer=url | azumimuo/family-xbmc-addon | [
1,
3,
1,
2,
1456692116
] |
def __init__(self, a):
self.args = a
self.configfile = self.args['config']
self.fullscreen = self.args['fullscreen']
self.resolution = self.args['resolution']
self.theme = self.args['theme']
self.config = self.load_config(self.configfile)
# Lysdestic - Allow support for manipulating fullscreen via CLI
if self.fullscreen is not None:
Config.set("video", "fullscreen", self.fullscreen)
# Lysdestic - Change resolution from CLI
if self.resolution is not None:
Config.set("video", "resolution", self.resolution)
# Lysdestic - Alter theme from CLI
if self.theme is not None:
Config.set("coffee", "themename", self.theme)
self.engine = GameEngine(self.config)
self.videoLayer = False
self.restartRequested = False | fofix/fofix | [
379,
88,
379,
66,
1341600969
] |
def load_config(configPath):
''' Load the configuration file. '''
if configPath is not None:
if configPath.lower() == "reset":
# Get os specific location of config file, and remove it.
fileName = os.path.join(VFS.getWritableResourcePath(), Version.PROGRAM_UNIXSTYLE_NAME + ".ini")
os.remove(fileName)
# Recreate it
config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini", setAsDefault=True)
else:
# Load specified config file
config = Config.load(configPath, setAsDefault=True)
else:
# Use default configuration file
config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini", setAsDefault=True)
return config | fofix/fofix | [
379,
88,
379,
66,
1341600969
] |
def __init__(self, name, bases, nmspc):
super(RegisterClasses, self).__init__(name, bases, nmspc)
if not hasattr(self, 'registry'):
self.registry = set()
self.registry.add(self)
self.registry -= set(bases) | DinoTools/dionaea | [
628,
172,
628,
57,
1450728831
] |
def start(cls, addr, iface=None):
raise NotImplementedError("do it") | DinoTools/dionaea | [
628,
172,
628,
57,
1450728831
] |
def stop(cls, daemon):
daemon.close() | DinoTools/dionaea | [
628,
172,
628,
57,
1450728831
] |
def start(cls):
raise NotImplementedError("do it") | DinoTools/dionaea | [
628,
172,
628,
57,
1450728831
] |
def stop(cls, ihandler):
ihandler.stop() | DinoTools/dionaea | [
628,
172,
628,
57,
1450728831
] |
def __init__(self, interval: float, function: Callable, delay: Optional[float] = None, repeat=False,
args: Optional[list] = None, kwargs: Optional[dict] = None):
Thread.__init__(self)
self.interval = interval
self.function = function
self.delay = delay
if self.delay is None:
self.delay = self.interval
self.repeat = repeat
self.args = args if args is not None else []
self.kwargs = kwargs if kwargs is not None else {}
self.finished = Event() | DinoTools/dionaea | [
628,
172,
628,
57,
1450728831
] |
def run(self) -> None:
self.finished.wait(self.delay)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
while self.repeat and not self.finished.wait(self.interval):
if not self.finished.is_set():
self.function(*self.args, **self.kwargs) | DinoTools/dionaea | [
628,
172,
628,
57,
1450728831
] |
def __init__(self, interval: float, function: Callable, delay: Optional[float] = None, repeat=False,
args: Optional[list] = None, kwargs: Optional[dict] = None):
self.interval = interval
self.function = function
self.delay = delay
if self.delay is None:
self.delay = self.interval
self.repeat = repeat
self.args = args if args is not None else []
self.kwargs = kwargs if kwargs is not None else {}
self._timer: Optional[SubTimer] = None | DinoTools/dionaea | [
628,
172,
628,
57,
1450728831
] |
def cancel(self) -> None:
"""Cancel the Timer"""
if self._timer:
self._timer.cancel() | DinoTools/dionaea | [
628,
172,
628,
57,
1450728831
] |
def load_submodules(base_pkg=None):
if base_pkg is None:
import dionaea as base_pkg
prefix = base_pkg.__name__ + "."
for importer, modname, ispkg in pkgutil.iter_modules(base_pkg.__path__, prefix):
if modname in loaded_submodules:
continue
logger.info("Import module %s", modname)
try:
__import__(modname, fromlist="dummy")
except Exception as e:
logger.warning("Error loading module: {}".format(str(e)))
for msg in traceback.format_exc().split("\n"):
logger.warning(msg.rstrip())
loaded_submodules.append(modname) | DinoTools/dionaea | [
628,
172,
628,
57,
1450728831
] |
def to_xmlrpc(cls, query={}):
"""
Convert the query set for XMLRPC
"""
s = XMLRPCSerializer(queryset=cls.objects.filter(**query).order_by("pk"))
return s.serialize_queryset() | Nitrate/Nitrate | [
222,
99,
222,
60,
1413958586
] |
def log(self):
log = TCMSLog(model=self)
return log.list() | Nitrate/Nitrate | [
222,
99,
222,
60,
1413958586
] |
def connect(self,host,port):
raise NotImplementedError("Not implemented by subclass") | gromacs/copernicus | [
14,
4,
14,
4,
1421754399
] |
def prepareHeaders(self,request):
"""
Creates and adds necessary headers for this connection type
inputs:
request:ServerRequest
returns:
ServerRequest
"""
raise NotImplementedError("not implemented by subclass") | gromacs/copernicus | [
14,
4,
14,
4,
1421754399
] |
def check_output_config(config):
""" Check that the configuration is valid"""
ok = True
if config['output']['sort_column'] not in config['output']['columns']:
print("Sort column not in output columns list")
ok = False
return ok | BjerknesClimateDataCentre/QuinCe | [
5,
6,
5,
484,
1428402948
] |
def __init__(self, local_error = 0.001, dz = 1e-5,
disable_Raman = False, disable_self_steepening = False,
suppress_iteration = True, USE_SIMPLE_RAMAN = False,
f_R = 0.18, f_R0 = 0.18, tau_1 = 0.0122, tau_2 = 0.0320):
"""
This initialization function sets up the parameters of the SSFM.
"""
self.iter = 0
self.last_h = -1.0
self.last_dir = 0.0
self.eta = 5
self.local_error = local_error
self.method = SSFM.METHOD_RK4IP
self.disable_Raman = disable_Raman
self.disable_self_steepening = disable_self_steepening
self.USE_SIMPLE_RAMAN = USE_SIMPLE_RAMAN
# Raman fraction; may change depending upon which calculation method
# is used
self.f_R = f_R
# The value for the old-style Raman response
self.f_R0 = f_R0 | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def load_fiber_parameters(self, pulse_in, fiber, output_power, z=0):
"""
This funciton loads the fiber parameters into class variables.
"""
self.betas[:] = fiber.get_betas(pulse_in, z=z)
# self.alpha[:] = -fiber.get_gain(pulse_in, output_power) # currently alpha cannot change with z
self.gamma = fiber.get_gamma(z=z) | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def setup_fftw(self, pulse_in, fiber, output_power, raman_plots = False):
''' Call immediately before starting Propagate. This function does two
things:\n
1) it sets up byte aligned arrays for fftw\n
2) it fftshifts betas, omegas, and the Raman response so that no further\n
shifts are required during integration. This saves lots of time.''' | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def CalculateRamanResponseFT(self, pulse):
"""
Calculate Raman response in frequency domain. Two versions are
available: the first is the LaserFOAM one, which directly calculates
R[w]. The second is Dudley-style, which calculates R[t] and then
FFTs. Note that the use of fftshifts is critical here (FFT_t_shift)
as is the factor of pulse_width.
""" | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def integrate_over_dz(self,delta_z, direction=1): | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def Advance(self,A,dz,direction):
if self.method == SSFM.METHOD_SSFM:
if direction==1:
A[:] = self.LinearStep(A,dz,direction)
return np.exp(dz*direction*self.NonlinearOperator(A))*A
else:
A[:] = np.exp(dz*direction*self.NonlinearOperator(A))*A
return self.LinearStep(A,dz,direction)
elif self.method == SSFM.METHOD_RK4IP:
return self.RK4IP(A,dz,direction) | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def Deriv(self,Aw):
"""Calculate the temporal derivative using FFT. \n\n MODIFIED from
LaserFOAM original code, now input is in frequency space, output is
temporal derivative. This should save a few FFTs per iteration."""
return self.IFFT_t(-1.0j*self.omegas * Aw) | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def RK4IP(self,A,h,direction):
"""Fourth-order Runge-Kutta in the interaction picture.
J. Hult, J. Lightwave Tech. 25, 3770 (2007)."""
self.A_I[:] = self.LinearStep(A,h,direction) #Side effect: Rely on LinearStep to recalculate self.exp_D for h/2 and direction dir
self.k1[:] = self.IFFT_t_2(self.exp_D*self.FFT_t_2(h*direction*self.NonlinearOperator(A)*A))
self.k2[:] = h * direction * self.NonlinearOperator(self.A_I + self.k1/2.0)*\
(self.A_I + self.k1/2.0)
self.k3[:] = h * direction * self.NonlinearOperator(self.A_I + self.k2/2.0)*\
(self.A_I + self.k2/2.0)
self.temp[:] = self.IFFT_t_2(self.exp_D*self.FFT_t_2(self.A_I+self.k3))
self.k4[:] = h * direction * self.NonlinearOperator(self.temp)*self.temp
if not self.suppress_iteration:
print ( "ks: ",np.sum(np.abs(self.k1)),np.sum(np.abs(self.k2)),\
np.sum(np.abs(self.k3)),np.sum(np.abs(self.k2)) )
return self.IFFT_t_2(self.exp_D * self.FFT_t_2(self.A_I + self.k1/6.0 +\
self.k2/3.0 + self.k3/3.0)) + self.k4/6.0 | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def propagate(self, pulse_in, fiber, n_steps, output_power=None, reload_fiber_each_step=False):
"""
This is the main user-facing function that allows a pulse to be
propagated along a fiber (or other nonlinear medium). | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def calculate_coherence(self, pulse_in, fiber,
num_trials=5, random_seed=None, noise_type='one_photon_freq',
n_steps=50, output_power=None, reload_fiber_each_step=False):
"""
This function runs :func:`pynlo.interactions.FourWaveMixing.SSFM.propagate` several times (given by num_trials),
each time adding random noise to the pulse. By comparing the electric fields of the different pulses,
and estimate of the coherence can be made. | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def propagate_to_gain_goal(self, pulse_in, fiber, n_steps, power_goal = 1,
scalefactor_guess = None, powertol = 0.05):
"""
Integrate over length of gain fiber such that the average output
power is power_goal [W]. For this to work, fiber must have spectroscopic
gain data from an amplifier model or measurement. If the approximate
scalefactor needed to adjust the gain is known it can be passed as
scalefactor_guess.\n This function returns a tuple of tuples:\n
((ys,AWs,ATs,pulse_out), scale_factor)
"""
if scalefactor_guess is not None:
scalefactor = scalefactor_guess
else:
scalefactor = 1
y, AW, AT, pulse_out = self.propagate(pulse_in,
fiber,
1,
output_power = scalefactor *\
power_goal)
scalefactor_revised = (power_goal / (pulse_out.calc_epp()*pulse_out.frep))
modeled_avg_power = pulse_out.calc_epp()*pulse_out.frep
output_scale = scalefactor
while abs(modeled_avg_power - power_goal) / power_goal > powertol:
y, AW, AT, pulse_out = self.propagate(pulse_in, fiber,
1, output_power =
power_goal * scalefactor_revised)
modeled_avg_power_prev = modeled_avg_power
modeled_avg_power = pulse_out.calc_epp()*pulse_out.frep
slope = (modeled_avg_power - modeled_avg_power_prev) /\
(scalefactor_revised - scalefactor)
yint = modeled_avg_power_prev - slope*scalefactor
# Before updating the scale factor, see if the new or old modeled
# power is closer to the goal. When the loop ends, whichever is more
# accurate is used for final iteration. This makes maximum use of
# each (computationally expensive) numeric integration
if abs(modeled_avg_power-power_goal) < \
abs(modeled_avg_power_prev-power_goal):
output_scale = scalefactor_revised
else:
output_scale = scalefactor
# Update scalefactor and go to top of loop
scalefactor = scalefactor_revised
scalefactor_revised = (power_goal - yint)/slope
print ('Updated final power:',modeled_avg_power,'W' )
return (self.propagate(pulse_in, fiber,
n_steps,
output_power = power_goal * output_scale),
output_scale) | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def FFT_t(self, A):
if PYFFTW_AVAILABLE:
if global_variables.PRE_FFTSHIFT:
self.fft_input[:] = A
return self.fft()
else:
self.fft_input[:] = fftshift(A)
return ifftshift(self.fft())
else:
if global_variables.PRE_FFTSHIFT:
return scipy.fftpack.ifft(A)
else:
return ifftshift(scipy.fftpack.ifft(fftshift(A))) | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def FFT_t_shift(self, A):
if PYFFTW_AVAILABLE:
self.fft_input[:] = fftshift(A)
return ifftshift(self.fft())
else:
return ifftshift(scipy.fftpack.ifft(fftshift(A))) | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def FFT_t_2(self, A):
if PYFFTW_AVAILABLE:
if global_variables.PRE_FFTSHIFT:
self.fft_input_2[:] = A
return self.fft_2()
else:
self.fft_input_2[:] = fftshift(A)
return ifftshift(self.fft_2())
else:
if global_variables.PRE_FFTSHIFT:
return scipy.fftpack.ifft(A)
else:
return ifftshift(scipy.fftpack.ifft(fftshift(A))) | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def IFFT_t_3(self, A):
if PYFFTW_AVAILABLE:
if global_variables.PRE_FFTSHIFT:
self.ifft_input_3[:] = A
return self.ifft_3()
else:
self.ifft_input_3[:] = fftshift(A)
return ifftshift(self.ifft_3())
else:
if global_variables.PRE_FFTSHIFT:
return scipy.fftpack.fft(A)
else:
return ifftshift(scipy.fftpack.fft(fftshift(A))) | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def CalculateLocalError(self):
denom = np.linalg.norm(self.Af)
if denom != 0.0:
return np.linalg.norm(self.Af-self.Ac)/np.linalg.norm(self.Af)
else:
return np.linalg.norm(self.Af-self.Ac) | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def conditional_fftshift(self, x):
if global_variables.PRE_FFTSHIFT:
x[:] = fftshift(x)
return x
else:
return x | pyNLO/PyNLO | [
72,
43,
72,
14,
1451323162
] |
def stubo_path():
# Find folder that this module is contained in
module = sys.modules[__name__]
return os.path.dirname(os.path.abspath(module.__file__)) | rusenask/mirage | [
1,
9,
1,
1,
1442829462
] |
Subsets and Splits