code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# -*- coding: utf-8 -*-
# Copyright 2018 <NAME> & <NAME>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -*- coding: utf-8 -*-
import numpy as np
from ..utils import to_categorical
from .activations import softmax, sigmoid
# softmax交叉熵
def softmax_cross_entropy(out, label):
# out:神经元的输出值
# label:实际类别或one-hot编码
out, label = np.array(out), np.array(label)
assert len(out.shape) == 2 # 输出形状错误
assert len(label.shape) == 1 or len(label.shape) == 2 # 标签形状错误
if len(label.shape) == 1: # 转化为one-hot编码
y = to_categorical(label, num_classes=out.shape[1])
else:
if label.shape[1] == 1:
y = to_categorical(label.squeeze(), num_classes=out.shape[1])
else:
assert label.max() == 1 and label.sum(1).mean() == 1 # 标签one-hot编码错误
y = label
yhat = softmax(out)
return -np.mean(y * np.log(yhat))
# 交叉熵
def cross_entropy(out, label):
# out:神经元的输出值
# label:实际类别或one-hot编码
yhat, label = np.array(out), np.array(label)
assert len(out.shape) == 2 # 输出形状错误
assert len(label.shape) == 1 or len(label.shape) == 2 # 标签形状错误
if len(label.shape) == 1: # 转化为one-hot编码
y = to_categorical(label, num_classes=out.shape[1])
else:
if label.shape[1] == 1:
y = to_categorical(label.squeeze(), num_classes=out.shape[1])
else:
assert label.max() == 1 and label.sum(1).mean() == 1 # 标签one-hot编码错误
y = label
return -np.mean(y * np.log(yhat))
# 二分类
def sigmoid_binary_cross_entropy(out, label):
# out:神经元的输出值
# label:实际类别或one-hot编码
out, y = np.array(out), np.array(label)
assert len(out.shape) == 2 and out.shape[1] == 1 # 输出形状错误
assert len(y.shape) == 1 # 标签形状错误
yhat = sigmoid(out)
return -np.mean(y * np.log(yhat) + (1 - y) * np.log(1 - yhat))
# 二分类
def binary_cross_entropy(out, label):
# out:神经元的输出值
# label:实际类别或one-hot编码
yhat, y = np.array(out), np.array(label)
assert len(yhat.shape) == 2 and out.shape[1] == 1 # 输出形状错误
assert len(y.shape) == 1 # 标签形状错误
return -np.mean(y * np.log(yhat) + (1 - y) * np.log(1 - yhat))
# 最小二乘损失
def square_loss(prediction, y):
# prediction:预测值
# y:实际值
prediction, y = np.array(prediction), np.array(y)
assert (len(prediction.shape) == 2 and prediction.shape[1] == 1) or len(prediction.shape) == 1 # 输出形状错误
assert len(y.shape) == 1 or (len(y.shape) == 2 and y.shape[1] == 1) # 真实值形状错误
return np.sum(np.sum(np.square(prediction.reshape(-1, 1) - y.reshape(-1, 1)), 1))
# 均方误差
def mse(prediction, y):
# prediction:预测值
# y:实际值
prediction, y = np.array(prediction), np.array(y)
assert (len(prediction.shape) == 2 and prediction.shape[1] == 1) or len(prediction.shape) == 1 # 输出形状错误
assert len(y.shape) == 1 or (len(y.shape) == 2 and y.shape[1] == 1) # 真实值形状错误
return np.mean(np.sum(np.square(prediction.reshape(-1, 1) - y.reshape(-1, 1)), 1))
| [
"numpy.array",
"numpy.log"
] | [((888, 901), 'numpy.array', 'np.array', (['out'], {}), '(out)\n', (896, 901), True, 'import numpy as np\n'), ((903, 918), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (911, 918), True, 'import numpy as np\n'), ((1551, 1564), 'numpy.array', 'np.array', (['out'], {}), '(out)\n', (1559, 1564), True, 'import numpy as np\n'), ((1566, 1581), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (1574, 1581), True, 'import numpy as np\n'), ((2199, 2212), 'numpy.array', 'np.array', (['out'], {}), '(out)\n', (2207, 2212), True, 'import numpy as np\n'), ((2214, 2229), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (2222, 2229), True, 'import numpy as np\n'), ((2539, 2552), 'numpy.array', 'np.array', (['out'], {}), '(out)\n', (2547, 2552), True, 'import numpy as np\n'), ((2554, 2569), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (2562, 2569), True, 'import numpy as np\n'), ((2846, 2866), 'numpy.array', 'np.array', (['prediction'], {}), '(prediction)\n', (2854, 2866), True, 'import numpy as np\n'), ((2868, 2879), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (2876, 2879), True, 'import numpy as np\n'), ((3254, 3274), 'numpy.array', 'np.array', (['prediction'], {}), '(prediction)\n', (3262, 3274), True, 'import numpy as np\n'), ((3276, 3287), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (3284, 3287), True, 'import numpy as np\n'), ((1428, 1440), 'numpy.log', 'np.log', (['yhat'], {}), '(yhat)\n', (1434, 1440), True, 'import numpy as np\n'), ((2066, 2078), 'numpy.log', 'np.log', (['yhat'], {}), '(yhat)\n', (2072, 2078), True, 'import numpy as np\n'), ((2384, 2396), 'numpy.log', 'np.log', (['yhat'], {}), '(yhat)\n', (2390, 2396), True, 'import numpy as np\n'), ((2409, 2425), 'numpy.log', 'np.log', (['(1 - yhat)'], {}), '(1 - yhat)\n', (2415, 2425), True, 'import numpy as np\n'), ((2700, 2712), 'numpy.log', 'np.log', (['yhat'], {}), '(yhat)\n', (2706, 2712), True, 'import numpy as np\n'), ((2725, 2741), 'numpy.log', 'np.log', (['(1 - yhat)'], {}), '(1 - yhat)\n', (2731, 2741), True, 'import numpy as np\n')] |
import unittest
import prody
import numpy as np
import pytest
import itertools
from path import Path
from ..mhc_peptide import BasePDB
from ..sampling.generate_peptides import PeptideSampler
from .. import utils
from ..helpers import isolate, isolated_filesystem
@pytest.fixture()
def default_mhc():
return utils.load_gdomains_mhc('1ao7')
@pytest.fixture()
def default_pep():
return utils.load_gdomains_peptide('1ao7')
@isolate
def test_instantiate_with_seq():
sampler = PeptideSampler('ADCHTRTAC')
assert sampler.pep.numAtoms() > 10
@isolate
def test_instantiate_with_short_seq():
with pytest.raises(RuntimeError):
PeptideSampler('ADCH')
@isolate
def test_instantiate_with_long_seq():
with pytest.raises(RuntimeError):
PeptideSampler('ADCHLKKKKKKKKKKKK')
@isolate
def test_instantiate_with_wrong_letters_seq():
with pytest.raises(RuntimeError):
PeptideSampler('ADCHLBBKK')
@isolate
def test_instantiate_with_pdb():
prody.writePDB('pep.pdb', utils.load_gdomains_peptide('1ao7'))
sampler = PeptideSampler(pep='pep.pdb')
assert sampler.pep.numAtoms() > 10
@isolate
def test_instantiate_with_pep_and_mhc():
prody.writePDB('pep.pdb', utils.load_gdomains_peptide('1ao7'))
prody.writePDB('mhc.pdb', utils.load_gdomains_mhc('1ao7'))
sampler = PeptideSampler(pep='pep.pdb', rec='mhc.pdb')
assert sampler.pep.numAtoms() > 10
assert sampler.rec.numAtoms() > 100
@isolate
def test_instantiate_with_seq_and_custom_template():
prody.writePDB('template.pdb', utils.load_gdomains_peptide('1ao7'))
sampler = PeptideSampler('ADCHTRTAC', custom_template='template.pdb')
assert sampler.pep.numAtoms() > 10
@pytest.mark.parametrize('nsamples', [1, 10, 100, 1000, 15000])
def test_generate_simple(nsamples):
with isolated_filesystem():
sampler = PeptideSampler(pep=utils.load_gdomains_peptide('1ao7'))
sampler.generate_peptides(nsamples, 1, 0.3, 123)
assert sampler.brikard.numCoordsets() == nsamples
@isolate
def test_generate_with_template():
prody.writePDB('template.pdb', utils.load_gdomains_peptide('1ao7'))
sampler = PeptideSampler('ADCHTRTAC', custom_template='template.pdb')
sampler.generate_peptides(10, 1, 0.2, 123)
assert sampler.brikard.numCoordsets() == 10
@pytest.mark.parametrize('pep,rec', itertools.product(['1a1m', '1t22', '2bvo'], ['1a1m', '1t22', '2bvo']))
def test_generate_with_rec(pep, rec):
with isolated_filesystem():
sampler = PeptideSampler(pep=utils.load_gdomains_peptide(pep), rec=utils.load_gdomains_mhc(rec))
sampler.generate_peptides(10, 1, 0.2, 123)
assert sampler.brikard.numCoordsets() == 10
# check that receptor is fixed by default during sampling
def test_generate_receptor_fixed(default_mhc, default_pep):
with isolated_filesystem():
sampler = PeptideSampler(pep=default_pep, rec=default_mhc)
sampler.generate_peptides(10, 1, 0.2, 123)
assert sampler.brikard.numCoordsets() == 10
rec_fixed = sampler.brikard.select('chain A')
assert np.all(rec_fixed.getCoordsets(0) == rec_fixed.getCoordsets(1))
# check that receptor is flexible with sample_resi_within parameter set
def test_generate_receptor_flexible(default_mhc, default_pep):
with isolated_filesystem():
sampler = PeptideSampler(pep=default_pep, rec=default_mhc)
sampler.generate_peptides(10, 1, 0.2, 123, sample_resi_within=7)
assert sampler.brikard.numCoordsets() == 10
rec_flex = sampler.brikard.select('chain A')
assert np.any(rec_flex.getCoordsets(0) != rec_flex.getCoordsets(1))
@pytest.mark.parametrize('radius', range(1, 7, 2))
def test_generate_receptor_variable_radius(default_mhc, default_pep, radius):
with isolated_filesystem():
sampler = PeptideSampler(pep=default_pep, rec=default_mhc)
sampler.generate_peptides(10, 1, 0.2, 123, sample_resi_within=radius)
assert sampler.brikard.numCoordsets() == 10
| [
"pytest.fixture",
"pytest.mark.parametrize",
"itertools.product",
"pytest.raises"
] | [((268, 284), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (282, 284), False, 'import pytest\n'), ((350, 366), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (364, 366), False, 'import pytest\n'), ((1706, 1768), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""nsamples"""', '[1, 10, 100, 1000, 15000]'], {}), "('nsamples', [1, 10, 100, 1000, 15000])\n", (1729, 1768), False, 'import pytest\n'), ((2351, 2420), 'itertools.product', 'itertools.product', (["['1a1m', '1t22', '2bvo']", "['1a1m', '1t22', '2bvo']"], {}), "(['1a1m', '1t22', '2bvo'], ['1a1m', '1t22', '2bvo'])\n", (2368, 2420), False, 'import itertools\n'), ((617, 644), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (630, 644), False, 'import pytest\n'), ((735, 762), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (748, 762), False, 'import pytest\n'), ((875, 902), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (888, 902), False, 'import pytest\n')] |
#!/usr/bin/env python
from __future__ import division, print_function
try:
range = xrange
except NameError:
pass
import os
import sys
import h5py
import json
import time
import numpy
import ctypes
import signal
import logging
import argparse
import threading
from functools import reduce
from datetime import datetime, timedelta
from mnc.common import *
from mnc.mcs import ImageMonitorPoint, MultiMonitorPoint, Client
from station import ovro
from reductions import *
from operations import FileOperationsQueue
from monitoring import GlobalLogger
from control import VisibilityCommandProcessor
from lwams import get_zenith_uvw
from bifrost.address import Address
from bifrost.udp_socket import UDPSocket
from bifrost.packet_capture import PacketCaptureCallback, UDPCapture, DiskReader
from bifrost.ring import Ring
import bifrost.affinity as cpu_affinity
import bifrost.ndarray as BFArray
from bifrost.ndarray import copy_array
from bifrost.libbifrost import bf
from bifrost.proclog import ProcLog
from bifrost.memory import memcpy as BFMemCopy, memset as BFMemSet
from bifrost import asarray as BFAsArray
import PIL.Image, PIL.ImageDraw, PIL.ImageFont
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
QUEUE = FileOperationsQueue()
class CaptureOp(object):
def __init__(self, log, sock, oring, nbl, ntime_gulp=1,
slot_ntime=6, fast=False, shutdown_event=None, core=None):
self.log = log
self.sock = sock
self.oring = oring
self.nbl = nbl
self.ntime_gulp = ntime_gulp
self.slot_ntime = slot_ntime
self.fast = fast
if shutdown_event is None:
shutdown_event = threading.Event()
self.shutdown_event = shutdown_event
self.core = core
def shutdown(self):
self.shutdown_event.set()
def seq_callback(self, seq0, time_tag, chan0, nchan, navg, nsrc, hdr_ptr, hdr_size_ptr):
print("++++++++++++++++ seq0 =", seq0)
print(" time_tag =", time_tag)
hdr = {'time_tag': time_tag,
'seq0': seq0,
'chan0': chan0,
'cfreq': chan0*CHAN_BW,
'nchan': nchan,
'bw': nchan*CHAN_BW*(4 if self.fast else 1),
'navg': navg,
'nstand': int(numpy.sqrt(8*nsrc+1)-1)//2,
'npol': 4,
'nbl': nsrc,
'complex': True,
'nbit': 32}
print("******** CFREQ:", hdr['cfreq'])
hdr_str = json.dumps(hdr).encode()
# TODO: Can't pad with NULL because returned as C-string
#hdr_str = json.dumps(hdr).ljust(4096, '\0')
#hdr_str = json.dumps(hdr).ljust(4096, ' ')
header_buf = ctypes.create_string_buffer(hdr_str)
hdr_ptr[0] = ctypes.cast(header_buf, ctypes.c_void_p)
hdr_size_ptr[0] = len(hdr_str)
return 0
def main(self):
seq_callback = PacketCaptureCallback()
seq_callback.set_cor(self.seq_callback)
with UDPCapture("cor", self.sock, self.oring, self.nbl, 1, 9000,
self.ntime_gulp, self.slot_ntime,
sequence_callback=seq_callback, core=self.core) as capture:
while not self.shutdown_event.is_set():
status = capture.recv()
if status in (1,4,5,6):
break
del capture
class DummyOp(object):
def __init__(self, log, sock, oring, nbl, ntime_gulp=1,
slot_ntime=6, fast=False, shutdown_event=None, core=None):
self.log = log
self.sock = sock
self.oring = oring
self.nbl = nbl
self.ntime_gulp = ntime_gulp
self.slot_ntime = slot_ntime
self.fast = fast
if shutdown_event is None:
shutdown_event = threading.Event()
self.shutdown_event = shutdown_event
self.core = core
self.bind_proclog = ProcLog(type(self).__name__+"/bind")
self.out_proclog = ProcLog(type(self).__name__+"/out")
self.size_proclog = ProcLog(type(self).__name__+"/size")
self.perf_proclog = ProcLog(type(self).__name__+"/perf")
self.out_proclog.update( {'nring':1, 'ring0':self.oring.name})
self.size_proclog.update({'nseq_per_gulp': self.ntime_gulp})
def shutdown(self):
self.shutdown_event.set()
def main(self):
with self.oring.begin_writing() as oring:
navg = 2400 if self.fast else 240000
tint = navg / CHAN_BW
tgulp = tint * self.ntime_gulp
nsrc = self.nbl
nbl = self.nbl
chan0 = 1234
nchan = 192 // (4 if self.fast else 1)
npol = 4
# Try to load model visibilities
try:
vis_base = numpy.load('utils/sky.npy')
except:
self.log.warn("Could not load model visibilities from utils/sky.py, using random data")
vis_base = numpy.zeros((nbl, nchan, npol), dtype=numpy.complex64)
assert(vis_base.shape[0] >= nbl)
assert(vis_base.shape[1] >= nchan)
assert(vis_base.shape[2] == npol)
vis_base = vis_base[:self.nbl,::(4 if self.fast else 1),:]
vis_base_r = (vis_base.real*1000).astype(numpy.int32)
vis_base_i = (vis_base.imag*1000).astype(numpy.int32)
vis_base = numpy.zeros((nbl, nchan, npol, 2), dtype=numpy.int32)
vis_base[...,0] = vis_base_r
vis_base[...,1] = vis_base_i
ohdr = {'time_tag': int(int(time.time())*FS),
'seq0': 0,
'chan0': chan0,
'cfreq': chan0*CHAN_BW,
'nchan': nchan,
'bw': nchan*CHAN_BW*(4 if self.fast else 1),
'navg': navg*8192,
'nstand': int(numpy.sqrt(8*nsrc+1)-1)//2,
'npol': npol,
'nbl': nbl,
'complex': True,
'nbit': 32}
ohdr_str = json.dumps(ohdr)
ogulp_size = self.ntime_gulp*nbl*nchan*npol*8 # ci32
oshape = (self.ntime_gulp,nbl,nchan,npol)
self.oring.resize(ogulp_size)
prev_time = time.time()
with oring.begin_sequence(time_tag=ohdr['time_tag'], header=ohdr_str) as oseq:
while not self.shutdown_event.is_set():
with oseq.reserve(ogulp_size) as ospan:
curr_time = time.time()
reserve_time = curr_time - prev_time
prev_time = curr_time
odata = ospan.data_view(numpy.int32).reshape(oshape+(2,))
temp = vis_base + (1000*0.01*numpy.random.randn(*odata.shape)).astype(numpy.int32)
odata[...] = temp
curr_time = time.time()
while curr_time - prev_time < tgulp:
time.sleep(0.01)
curr_time = time.time()
curr_time = time.time()
process_time = curr_time - prev_time
prev_time = curr_time
self.perf_proclog.update({'acquire_time': -1,
'reserve_time': reserve_time,
'process_time': process_time,})
class SpectraOp(object):
def __init__(self, log, id, iring, ntime_gulp=1, guarantee=True, core=-1):
self.log = log
self.iring = iring
self.ntime_gulp = ntime_gulp
self.guarantee = guarantee
self.core = core
self.client = Client(id)
self.bind_proclog = ProcLog(type(self).__name__+"/bind")
self.in_proclog = ProcLog(type(self).__name__+"/in")
self.size_proclog = ProcLog(type(self).__name__+"/size")
self.sequence_proclog = ProcLog(type(self).__name__+"/sequence0")
self.perf_proclog = ProcLog(type(self).__name__+"/perf")
self.in_proclog.update({'nring':1, 'ring0':self.iring.name})
def _plot_spectra(self, time_tag, freq, specs):
# Plotting setup
nchan = freq.size
nstand = specs.shape[0]
try:
minval = numpy.min(specs[numpy.where(numpy.isfinite(specs))])
maxval = numpy.max(specs[numpy.where(numpy.isfinite(specs))])
except ValueError:
minval = 0.0
maxval = 1.0
# Image setup
width = 20
height = 18
im = PIL.Image.new('RGB', (width * 65 + 1, height * 65 + 21), '#FFFFFF')
draw = PIL.ImageDraw.Draw(im)
font = PIL.ImageFont.load(os.path.join(BASE_PATH, 'fonts', 'helvB10.pil'))
# Axes boxes
for i in range(width + 1):
draw.line([i * 65, 0, i * 65, height * 65], fill = '#000000')
for i in range(height + 1):
draw.line([(0, i * 65), (im.size[0], i * 65)], fill = '#000000')
# Power as a function of frequency for all antennas
x = numpy.arange(nchan) * 64 // nchan
for s in range(nstand):
if s >= height * width:
break
x0, y0 = (s % width) * 65 + 1, (s // width + 1) * 65
draw.text((x0 + 5, y0 - 60), str(s+1), font=font, fill='#000000')
## XX
c = '#1F77B4'
y = ((54.0 / (maxval - minval)) * (specs[s,:,0] - minval)).clip(0, 54)
draw.point(list(zip(x0 + x, y0 - y)), fill=c)
## YY
c = '#FF7F0E'
y = ((54.0 / (maxval - minval)) * (specs[s,:,1] - minval)).clip(0, 54)
draw.point(list(zip(x0 + x, y0 - y)), fill=c)
# Summary
ySummary = height * 65 + 2
timeStr = datetime.utcfromtimestamp(time_tag / FS)
timeStr = timeStr.strftime("%Y/%m/%d %H:%M:%S UTC")
draw.text((5, ySummary), timeStr, font = font, fill = '#000000')
rangeStr = 'range shown: %.3f to %.3f dB' % (minval, maxval)
draw.text((210, ySummary), rangeStr, font = font, fill = '#000000')
x = im.size[0] + 15
for label, c in reversed(list(zip(('XX', 'YY'),
('#1F77B4','#FF7F0E')))):
x -= draw.textsize(label, font = font)[0] + 20
draw.text((x, ySummary), label, font = font, fill = c)
return im
def main(self):
cpu_affinity.set_core(self.core)
self.bind_proclog.update({'ncore': 1,
'core0': cpu_affinity.get_core(),})
for iseq in self.iring.read(guarantee=self.guarantee):
ihdr = json.loads(iseq.header.tostring())
self.sequence_proclog.update(ihdr)
self.log.info("Spectra: Start of new sequence: %s", str(ihdr))
# Setup the ring metadata and gulp sizes
time_tag = ihdr['time_tag']
navg = ihdr['navg']
nbl = ihdr['nbl']
nstand = ihdr['nstand']
chan0 = ihdr['chan0']
nchan = ihdr['nchan']
chan_bw = ihdr['bw'] / nchan
npol = ihdr['npol']
igulp_size = self.ntime_gulp*nbl*nchan*npol*8 # ci32
ishape = (self.ntime_gulp,nbl,nchan,npol)
# Setup the arrays for the frequencies and auto-correlations
freq = chan0*chan_bw + numpy.arange(nchan)*chan_bw
autos = [i*(2*(nstand-1)+1-i)//2 + i for i in range(nstand)]
last_save = 0.0
prev_time = time.time()
for ispan in iseq.read(igulp_size):
if ispan.size < igulp_size:
continue # Ignore final gulp
curr_time = time.time()
acquire_time = curr_time - prev_time
prev_time = curr_time
## Setup and load
idata = ispan.data_view('ci32').reshape(ishape)
if time.time() - last_save > 60:
## Timestamp
tt = LWATime(time_tag, format='timetag')
ts = tt.unix
## Pull out the auto-correlations
adata = idata.view(numpy.int32)
adata = adata.reshape(ishape+(2,))
adata = adata[0,autos,:,:,0]
adata = adata[:,:,[0,3]]
## Plot
im = self._plot_spectra(time_tag, freq, 10*numpy.log10(adata))
## Save
mp = ImageMonitorPoint.from_image(im)
self.client.write_monitor_point('diagnostics/spectra',
mp, timestamp=ts)
if True:
## Save again, this time to disk
mjd, dt = tt.mjd, tt.datetime
mjd = int(mjd)
h, m, s = dt.hour, dt.minute, dt.second
filename = '%06i_%02i%02i%02i_spectra.png' % (mjd, h, m, s)
mp.to_file(filename)
### Save the raw spectra for comparison purposes
#filename = '%06i_%02i%02i%02i_spectra.npy' % (mjd, h, m, s)
#numpy.save(filename, adata)
#
### Save everything for comparison purposes
#odata = idata.view(numpy.int32)
#odata = odata.reshape(ishape+(2,))
#filename = '%06i_%02i%02i%02i_everything.npy' % (mjd, h, m, s)
#numpy.save(filename, odata)
last_save = time.time()
time_tag += navg * self.ntime_gulp
curr_time = time.time()
process_time = curr_time - prev_time
prev_time = curr_time
self.perf_proclog.update({'acquire_time': acquire_time,
'reserve_time': 0.0,
'process_time': process_time,})
self.log.info("SpectraOp - Done")
class BaselineOp(object):
def __init__(self, log, id, station, iring, ntime_gulp=1, guarantee=True, core=-1):
self.log = log
self.station = station
self.iring = iring
self.ntime_gulp = ntime_gulp
self.guarantee = guarantee
self.core = core
self.client = Client(id)
self.bind_proclog = ProcLog(type(self).__name__+"/bind")
self.in_proclog = ProcLog(type(self).__name__+"/in")
self.size_proclog = ProcLog(type(self).__name__+"/size")
self.sequence_proclog = ProcLog(type(self).__name__+"/sequence0")
self.perf_proclog = ProcLog(type(self).__name__+"/perf")
self.in_proclog.update({'nring':1, 'ring0':self.iring.name})
def _plot_baselines(self, time_tag, freq, dist, baselines, valid):
# Plotting setup
nchan = freq.size
nbl = baselines.shape[0]
freq = freq[nchan//2]
baselines = baselines[valid,nchan//2,:]
baselines = numpy.abs(baselines[:,[0,1,3]])
minval = numpy.min(baselines)
maxval = numpy.max(baselines)
if minval == maxval:
maxval = minval + 1.0
mindst = 0.0
maxdst = numpy.max(dist)
# Image setup
im = PIL.Image.new('RGB', (601, 421), '#FFFFFF')
draw = PIL.ImageDraw.Draw(im)
font = PIL.ImageFont.load(os.path.join(BASE_PATH, 'fonts', 'helvB10.pil'))
# Axes boxes
for i in range(2):
draw.line([i * 600, 0, i * 600, 400], fill = '#000000')
for i in range(2):
draw.line([(0, i * 400), (im.size[0], i * 400)], fill = '#000000')
# Visiblity amplitudes as a function of (u,v) distance
x0, y0 = 1, 400
draw.text((x0 + 500, y0 - 395), '%.3f MHz' % (freq/1e6,), font=font, fill='#000000')
## (u,v) distance
x = ((599.0 / (maxdst - mindst)) * (dist - mindst)).clip(0, 599)
## XX
y = ((399.0 / (maxval - minval)) * (baselines[:,0] - minval)).clip(0, 399)
draw.point(list(zip(x0 + x, y0 - y)), fill='#1F77B4')
## YY
y = ((399.0 / (maxval - minval)) * (baselines[:,2] - minval)).clip(0, 399)
draw.point(list(zip(x0 + x, y0 - y)), fill='#FF7F0E')
### XY
#y = ((399.0 / (maxval - minval)) * (baselines[:,1] - minval)).clip(0, 399)
#draw.point(list(zip(x0 + x, y0 - y)), fill='#A00000')
# Details and labels
ySummary = 402
timeStr = datetime.utcfromtimestamp(time_tag / FS)
timeStr = timeStr.strftime("%Y/%m/%d %H:%M:%S UTC")
draw.text((5, ySummary), timeStr, font = font, fill = '#000000')
rangeStr = 'range shown: %.6f - %.6f' % (minval, maxval)
draw.text((210, ySummary), rangeStr, font = font, fill = '#000000')
x = im.size[0] + 15
#for label, c in reversed(list(zip(('XX','XY','YY'), ('#1F77B4','#A00000','#FF7F0E')))):
for label, c in reversed(list(zip(('XX','YY'), ('#1F77B4','#FF7F0E')))):
x -= draw.textsize(label, font = font)[0] + 20
draw.text((x, ySummary), label, font = font, fill = c)
return im
def main(self):
cpu_affinity.set_core(self.core)
self.bind_proclog.update({'ncore': 1,
'core0': cpu_affinity.get_core(),})
for iseq in self.iring.read(guarantee=self.guarantee):
ihdr = json.loads(iseq.header.tostring())
self.sequence_proclog.update(ihdr)
self.log.info("Baseline: Start of new sequence: %s", str(ihdr))
# Setup the ring metadata and gulp sizes
time_tag = ihdr['time_tag']
navg = ihdr['navg']
nbl = ihdr['nbl']
nstand = ihdr['nstand']
chan0 = ihdr['chan0']
nchan = ihdr['nchan']
chan_bw = ihdr['bw'] / nchan
npol = ihdr['npol']
igulp_size = self.ntime_gulp*nbl*nchan*npol*8
ishape = (self.ntime_gulp,nbl,nchan,npol)
self.iring.resize(igulp_size)
# Setup the arrays for the frequencies and baseline lenghts
freq = chan0*chan_bw + numpy.arange(nchan)*chan_bw
uvw = get_zenith_uvw(self.station, LWATime(time_tag, format='timetag'))
uvw[:,2] = 0
dist = numpy.sqrt((uvw**2).sum(axis=1))
valid = numpy.where(dist > 0.1)[0]
last_save = 0.0
prev_time = time.time()
for ispan in iseq.read(igulp_size):
if ispan.size < igulp_size:
continue # Ignore final gulp
curr_time = time.time()
acquire_time = curr_time - prev_time
prev_time = curr_time
## Setup and load
idata = ispan.data_view('ci32').reshape(ishape)
if time.time() - last_save > 60:
## Timestamp
tt = LWATime(time_tag, format='timetag')
ts = tt.unix
## Plot
bdata = idata[0,...]
bdata = bdata.view(numpy.int32)
bdata = bdata.reshape(ishape+(2,))
bdata = bdata[0,:,:,:,0] + 1j*bdata[0,:,:,:,1]
bdata = bdata.astype(numpy.complex64)
im = self._plot_baselines(time_tag, freq, dist, bdata, valid)
## Save
mp = ImageMonitorPoint.from_image(im)
self.client.write_monitor_point('diagnostics/baselines',
mp, timestamp=ts)
if True:
## Save again, this time to disk
mjd, dt = tt.mjd, tt.datetime
mjd = int(mjd)
h, m, s = dt.hour, dt.minute, dt.second
filename = '%06i_%02i%02i%02i_baselines.png' % (mjd, h, m, s)
mp.to_file(filename)
last_save = time.time()
time_tag += navg * self.ntime_gulp
curr_time = time.time()
process_time = curr_time - prev_time
prev_time = curr_time
self.perf_proclog.update({'acquire_time': acquire_time,
'reserve_time': 0.0,
'process_time': process_time,})
self.log.info("BaselineOp - Done")
class StatisticsOp(object):
def __init__(self, log, id, iring, ntime_gulp=1, guarantee=True, core=None):
self.log = log
self.iring = iring
self.ntime_gulp = ntime_gulp
self.guarantee = guarantee
self.core = core
self.client = Client(id)
self.bind_proclog = ProcLog(type(self).__name__+"/bind")
self.in_proclog = ProcLog(type(self).__name__+"/in")
self.size_proclog = ProcLog(type(self).__name__+"/size")
self.sequence_proclog = ProcLog(type(self).__name__+"/sequence0")
self.perf_proclog = ProcLog(type(self).__name__+"/perf")
self.in_proclog.update( {'nring':1, 'ring0':self.iring.name})
self.size_proclog.update({'nseq_per_gulp': self.ntime_gulp})
def main(self):
if self.core is not None:
cpu_affinity.set_core(self.core)
self.bind_proclog.update({'ncore': 1,
'core0': cpu_affinity.get_core(),})
for iseq in self.iring.read(guarantee=self.guarantee):
ihdr = json.loads(iseq.header.tostring())
self.sequence_proclog.update(ihdr)
self.log.info("Statistics: Start of new sequence: %s", str(ihdr))
# Setup the ring metadata and gulp sizes
time_tag = ihdr['time_tag']
navg = ihdr['navg']
nbl = ihdr['nbl']
nstand = ihdr['nstand']
chan0 = ihdr['chan0']
nchan = ihdr['nchan']
chan_bw = ihdr['bw'] / nchan
npol = ihdr['npol']
igulp_size = self.ntime_gulp*nbl*nchan*npol*8 # ci32
ishape = (self.ntime_gulp,nbl,nchan,npol)
autos = [i*(2*(nstand-1)+1-i)//2 + i for i in range(nstand)]
data_pols = ['XX', 'YY']
last_save = 0.0
prev_time = time.time()
iseq_spans = iseq.read(igulp_size)
for ispan in iseq_spans:
if ispan.size < igulp_size:
continue # Ignore final gulp
curr_time = time.time()
acquire_time = curr_time - prev_time
prev_time = curr_time
## Setup and load
idata = ispan.data_view('ci32').reshape(ishape)
if time.time() - last_save > 60:
## Timestamp
tt = LWATime(time_tag, format='timetag')
ts = tt.unix
## Pull out the auto-correlations
adata = idata.view(numpy.int32)
adata = adata.reshape(ishape+(2,))
adata = adata[0,autos,:,:,0]
adata = adata[:,:,[0,3]]
## Run the statistics over all times/channels
## * only really works for ntime_gulp=1
data_min = numpy.min(adata, axis=1)
data_max = numpy.max(adata, axis=1)
data_avg = numpy.mean(adata, axis=1)
## Save
for data,name in zip((data_min,data_avg,data_max), ('min','avg','max')):
value = MultiMonitorPoint([data[:,i].tolist() for i in range(data.shape[1])],
timestamp=ts, field=data_pols)
self.client.write_monitor_point('statistics/%s' % name, value)
last_save = time.time()
time_tag += navg * self.ntime_gulp
curr_time = time.time()
process_time = curr_time - prev_time
prev_time = curr_time
self.perf_proclog.update({'acquire_time': acquire_time,
'reserve_time': -1,
'process_time': process_time,})
self.log.info("StatisticsOp - Done")
class WriterOp(object):
def __init__(self, log, station, iring, ntime_gulp=1, fast=False, guarantee=True, core=None):
self.log = log
self.station = station
self.iring = iring
self.ntime_gulp = ntime_gulp
self.fast = fast
self.guarantee = guarantee
self.core = core
self.bind_proclog = ProcLog(type(self).__name__+"/bind")
self.in_proclog = ProcLog(type(self).__name__+"/in")
self.size_proclog = ProcLog(type(self).__name__+"/size")
self.sequence_proclog = ProcLog(type(self).__name__+"/sequence0")
self.perf_proclog = ProcLog(type(self).__name__+"/perf")
self.in_proclog.update( {'nring':1, 'ring0':self.iring.name})
self.size_proclog.update({'nseq_per_gulp': self.ntime_gulp})
def main(self):
global QUEUE
if self.core is not None:
cpu_affinity.set_core(self.core)
self.bind_proclog.update({'ncore': 1,
'core0': cpu_affinity.get_core(),})
for iseq in self.iring.read(guarantee=self.guarantee):
ihdr = json.loads(iseq.header.tostring())
self.sequence_proclog.update(ihdr)
self.log.info("Writer: Start of new sequence: %s", str(ihdr))
# Setup the ring metadata and gulp sizes
time_tag = ihdr['time_tag']
navg = ihdr['navg']
nbl = ihdr['nbl']
chan0 = ihdr['chan0']
nchan = ihdr['nchan']
chan_bw = ihdr['bw'] / nchan
npol = ihdr['npol']
pols = ['XX','XY','YX','YY']
igulp_size = self.ntime_gulp*nbl*nchan*npol*8 # ci32
ishape = (self.ntime_gulp,nbl,nchan,npol)
self.iring.resize(igulp_size, 10*igulp_size*(4 if self.fast else 1))
norm_factor = navg // (2*NCHAN)
first_gulp = True
was_active = False
prev_time = time.time()
iseq_spans = iseq.read(igulp_size)
for ispan in iseq_spans:
if ispan.size < igulp_size:
continue # Ignore final gulp
curr_time = time.time()
acquire_time = curr_time - prev_time
prev_time = curr_time
## On our first span, update the pipeline lag for the queue
## so that we start recording at the right times
if first_gulp:
QUEUE.update_lag(LWATime(time_tag, format='timetag').datetime)
self.log.info("Current pipeline lag is %s", QUEUE.lag)
first_gulp = False
## Setup and load
idata = ispan.data_view('ci32').reshape(ishape)
idata = idata.view(numpy.int32)
idata = idata.reshape(ishape+(2,))
idata = idata[...,0] + 1j*idata[...,1]
idata /= norm_factor
idata = idata.astype(numpy.complex64)
## Determine what to do
if QUEUE.active is not None:
### Recording active - write
if not QUEUE.active.is_started:
self.log.info("Started operation - %s", QUEUE.active)
QUEUE.active.start(self.station, chan0, navg, nchan, chan_bw, npol, pols)
was_active = True
QUEUE.active.write(time_tag, idata)
elif was_active:
### Recording just finished
#### Clean
was_active = False
QUEUE.clean()
#### Close
self.log.info("Ended operation - %s", QUEUE.previous)
QUEUE.previous.stop()
time_tag += navg
curr_time = time.time()
process_time = curr_time - prev_time
prev_time = curr_time
self.perf_proclog.update({'acquire_time': acquire_time,
'reserve_time': -1,
'process_time': process_time,})
self.log.info("WriterOp - Done")
def main(argv):
global QUEUE
parser = argparse.ArgumentParser(
description="Data recorder for slow/fast visibility data"
)
parser.add_argument('-a', '--address', type=str, default='127.0.0.1',
help='IP address to listen to')
parser.add_argument('-p', '--port', type=int, default=10000,
help='UDP port to receive data on')
parser.add_argument('-o', '--offline', action='store_true',
help='run in offline using the specified file to read from')
parser.add_argument('-c', '--cores', type=str, default='0,1,2,3,4,5',
help='comma separated list of cores to bind to')
parser.add_argument('-g', '--gulp-size', type=int, default=1,
help='gulp size for ring buffers')
parser.add_argument('-l', '--logfile', type=str,
help='file to write logging to')
parser.add_argument('-r', '--record-directory', type=str, default=os.path.abspath('.'),
help='directory to save recorded files to')
parser.add_argument('-t', '--record-directory-quota', type=quota_size, default=0,
help='quota for the recording directory, 0 disables the quota')
parser.add_argument('-q', '--quick', action='store_true',
help='run in fast visibiltiy mode')
parser.add_argument('-i', '--nint-per-file', type=int, default=1,
help='number of integrations to write per measurement set')
parser.add_argument('-n', '--no-tar', action='store_true',
help='do not store the measurement sets inside a tar file')
parser.add_argument('-f', '--fork', action='store_true',
help='fork and run in the background')
args = parser.parse_args()
# Process the -q/--quick option
station = ovro
if args.quick:
args.nint_per_file = max([10, args.nint_per_file])
station = ovro.select_subset(list(range(1, 48+1)))
# Fork, if requested
if args.fork:
stderr = '/tmp/%s_%i.stderr' % (os.path.splitext(os.path.basename(__file__))[0], args.port)
daemonize(stdin='/dev/null', stdout='/dev/null', stderr=stderr)
# Setup logging
log = logging.getLogger(__name__)
logFormat = logging.Formatter('%(asctime)s [%(levelname)-8s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
logFormat.converter = time.gmtime
if args.logfile is None:
logHandler = logging.StreamHandler(sys.stdout)
else:
logHandler = LogFileHandler(args.logfile)
logHandler.setFormatter(logFormat)
log.addHandler(logHandler)
log.setLevel(logging.DEBUG)
log.info("Starting %s with PID %i", os.path.basename(__file__), os.getpid())
log.info("Cmdline args:")
for arg in vars(args):
log.info(" %s: %s", arg, getattr(args, arg))
# Setup the subsystem ID
mcs_id = 'drv'
if args.quick:
mcs_id += 'f'
else:
mcs_id += 's'
base_ip = int(args.address.split('.')[-1], 10)
base_port = args.port % 100
mcs_id += str(base_ip*100 + base_port)
# Setup the cores and GPUs to use
cores = [int(v, 10) for v in args.cores.split(',')]
log.info("CPUs: %s", ' '.join([str(v) for v in cores]))
# Setup the socket, if needed
isock = None
if not args.offline:
iaddr = Address(args.address, args.port)
isock = UDPSocket()
isock.bind(iaddr)
# Setup the rings
capture_ring = Ring(name="capture")
# Setup antennas
nant = len(station.antennas)
nbl = nant*(nant+1)//2
# Setup the recording directory, if needed
if not os.path.exists(args.record_directory):
status = os.system('mkdir -p %s' % args.record_directory)
if status != 0:
raise RuntimeError("Unable to create directory: %s" % args.record_directory)
else:
if not os.path.isdir(os.path.realpath(args.record_directory)):
raise RuntimeError("Cannot record to a non-directory: %s" % args.record_directory)
# Setup the blocks
ops = []
if args.offline:
ops.append(DummyOp(log, isock, capture_ring, (NPIPELINE//16)*nbl,
ntime_gulp=args.gulp_size, slot_ntime=(10 if args.quick else 6),
fast=args.quick, core=cores.pop(0)))
else:
ops.append(CaptureOp(log, isock, capture_ring, (NPIPELINE//16)*nbl, # two pipelines/recorder
ntime_gulp=args.gulp_size, slot_ntime=(10 if args.quick else 6),
fast=args.quick, core=cores.pop(0)))
if not args.quick:
ops.append(SpectraOp(log, mcs_id, capture_ring,
ntime_gulp=args.gulp_size, core=cores.pop(0)))
ops.append(BaselineOp(log, mcs_id, station, capture_ring,
ntime_gulp=args.gulp_size, core=cores.pop(0)))
ops.append(StatisticsOp(log, mcs_id, capture_ring,
ntime_gulp=args.gulp_size, core=cores.pop(0)))
ops.append(WriterOp(log, station, capture_ring,
ntime_gulp=args.gulp_size, fast=args.quick, core=cores.pop(0)))
ops.append(GlobalLogger(log, mcs_id, args, QUEUE, quota=args.record_directory_quota))
ops.append(VisibilityCommandProcessor(log, mcs_id, args.record_directory, QUEUE,
nint_per_file=args.nint_per_file,
is_tarred=not args.no_tar))
# Setup the threads
threads = [threading.Thread(target=op.main) for op in ops]
# Setup signal handling
shutdown_event = setup_signal_handling(ops)
ops[0].shutdown_event = shutdown_event
ops[-2].shutdown_event = shutdown_event
ops[-1].shutdown_event = shutdown_event
# Launch!
log.info("Launching %i thread(s)", len(threads))
for thread in threads:
#thread.daemon = True
thread.start()
t_now = LWATime(datetime.utcnow() + timedelta(seconds=15), format='datetime', scale='utc')
mjd_now = int(t_now.mjd)
mpm_now = int((t_now.mjd - mjd_now)*86400.0*1000.0)
c = Client()
r = c.send_command(mcs_id, 'start',
start_mjd=mjd_now, start_mpm=mpm_now)
print('III', r)
t_now = LWATime(datetime.utcnow() + timedelta(seconds=75), format='datetime', scale='utc')
mjd_now = int(t_now.mjd)
mpm_now = int((t_now.mjd - mjd_now)*86400.0*1000.0)
r = c.send_command(mcs_id, 'stop',
stop_mjd=mjd_now, stop_mpm=mpm_now)
print('III', r)
while not shutdown_event.is_set():
signal.pause()
log.info("Shutdown, waiting for threads to join")
for thread in threads:
thread.join()
log.info("All done")
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
| [
"logging.getLogger",
"datetime.datetime.utcfromtimestamp",
"logging.StreamHandler",
"numpy.sqrt",
"bifrost.packet_capture.PacketCaptureCallback",
"numpy.log10",
"bifrost.affinity.get_core",
"ctypes.create_string_buffer",
"time.sleep",
"numpy.isfinite",
"datetime.timedelta",
"mnc.mcs.Client",
... | [((1240, 1261), 'operations.FileOperationsQueue', 'FileOperationsQueue', ([], {}), '()\n', (1259, 1261), False, 'from operations import FileOperationsQueue\n'), ((1203, 1228), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (1218, 1228), False, 'import os\n'), ((30595, 30682), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Data recorder for slow/fast visibility data"""'}), "(description=\n 'Data recorder for slow/fast visibility data')\n", (30618, 30682), False, 'import argparse\n'), ((32872, 32899), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (32889, 32899), False, 'import logging\n'), ((32916, 33012), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s [%(levelname)-8s] %(message)s"""'], {'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "('%(asctime)s [%(levelname)-8s] %(message)s', datefmt=\n '%Y-%m-%d %H:%M:%S')\n", (32933, 33012), False, 'import logging\n'), ((34180, 34200), 'bifrost.ring.Ring', 'Ring', ([], {'name': '"""capture"""'}), "(name='capture')\n", (34184, 34200), False, 'from bifrost.ring import Ring\n'), ((36859, 36867), 'mnc.mcs.Client', 'Client', ([], {}), '()\n', (36865, 36867), False, 'from mnc.mcs import ImageMonitorPoint, MultiMonitorPoint, Client\n'), ((2815, 2851), 'ctypes.create_string_buffer', 'ctypes.create_string_buffer', (['hdr_str'], {}), '(hdr_str)\n', (2842, 2851), False, 'import ctypes\n'), ((2878, 2918), 'ctypes.cast', 'ctypes.cast', (['header_buf', 'ctypes.c_void_p'], {}), '(header_buf, ctypes.c_void_p)\n', (2889, 2918), False, 'import ctypes\n'), ((3028, 3051), 'bifrost.packet_capture.PacketCaptureCallback', 'PacketCaptureCallback', ([], {}), '()\n', (3049, 3051), False, 'from bifrost.packet_capture import PacketCaptureCallback, UDPCapture, DiskReader\n'), ((8103, 8113), 'mnc.mcs.Client', 'Client', (['id'], {}), '(id)\n', (8109, 8113), False, 'from mnc.mcs import ImageMonitorPoint, MultiMonitorPoint, Client\n'), ((10274, 10314), 'datetime.datetime.utcfromtimestamp', 'datetime.utcfromtimestamp', (['(time_tag / FS)'], {}), '(time_tag / FS)\n', (10299, 10314), False, 'from datetime import datetime, timedelta\n'), ((10943, 10975), 'bifrost.affinity.set_core', 'cpu_affinity.set_core', (['self.core'], {}), '(self.core)\n', (10964, 10975), True, 'import bifrost.affinity as cpu_affinity\n'), ((15294, 15304), 'mnc.mcs.Client', 'Client', (['id'], {}), '(id)\n', (15300, 15304), False, 'from mnc.mcs import ImageMonitorPoint, MultiMonitorPoint, Client\n'), ((15986, 16020), 'numpy.abs', 'numpy.abs', (['baselines[:, [0, 1, 3]]'], {}), '(baselines[:, [0, 1, 3]])\n', (15995, 16020), False, 'import numpy\n'), ((16035, 16055), 'numpy.min', 'numpy.min', (['baselines'], {}), '(baselines)\n', (16044, 16055), False, 'import numpy\n'), ((16073, 16093), 'numpy.max', 'numpy.max', (['baselines'], {}), '(baselines)\n', (16082, 16093), False, 'import numpy\n'), ((16208, 16223), 'numpy.max', 'numpy.max', (['dist'], {}), '(dist)\n', (16217, 16223), False, 'import numpy\n'), ((17551, 17591), 'datetime.datetime.utcfromtimestamp', 'datetime.utcfromtimestamp', (['(time_tag / FS)'], {}), '(time_tag / FS)\n', (17576, 17591), False, 'from datetime import datetime, timedelta\n'), ((18266, 18298), 'bifrost.affinity.set_core', 'cpu_affinity.set_core', (['self.core'], {}), '(self.core)\n', (18287, 18298), True, 'import bifrost.affinity as cpu_affinity\n'), ((22159, 22169), 'mnc.mcs.Client', 'Client', (['id'], {}), '(id)\n', (22165, 22169), False, 'from mnc.mcs import ImageMonitorPoint, MultiMonitorPoint, Client\n'), ((33130, 33163), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (33151, 33163), False, 'import logging\n'), ((33371, 33397), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (33387, 33397), False, 'import os\n'), ((33399, 33410), 'os.getpid', 'os.getpid', ([], {}), '()\n', (33408, 33410), False, 'import os\n'), ((34043, 34075), 'bifrost.address.Address', 'Address', (['args.address', 'args.port'], {}), '(args.address, args.port)\n', (34050, 34075), False, 'from bifrost.address import Address\n'), ((34092, 34103), 'bifrost.udp_socket.UDPSocket', 'UDPSocket', ([], {}), '()\n', (34101, 34103), False, 'from bifrost.udp_socket import UDPSocket\n'), ((34350, 34387), 'os.path.exists', 'os.path.exists', (['args.record_directory'], {}), '(args.record_directory)\n', (34364, 34387), False, 'import os\n'), ((34406, 34454), 'os.system', 'os.system', (["('mkdir -p %s' % args.record_directory)"], {}), "('mkdir -p %s' % args.record_directory)\n", (34415, 34454), False, 'import os\n'), ((35900, 35973), 'monitoring.GlobalLogger', 'GlobalLogger', (['log', 'mcs_id', 'args', 'QUEUE'], {'quota': 'args.record_directory_quota'}), '(log, mcs_id, args, QUEUE, quota=args.record_directory_quota)\n', (35912, 35973), False, 'from monitoring import GlobalLogger\n'), ((35990, 36124), 'control.VisibilityCommandProcessor', 'VisibilityCommandProcessor', (['log', 'mcs_id', 'args.record_directory', 'QUEUE'], {'nint_per_file': 'args.nint_per_file', 'is_tarred': '(not args.no_tar)'}), '(log, mcs_id, args.record_directory, QUEUE,\n nint_per_file=args.nint_per_file, is_tarred=not args.no_tar)\n', (36016, 36124), False, 'from control import VisibilityCommandProcessor\n'), ((36250, 36282), 'threading.Thread', 'threading.Thread', ([], {'target': 'op.main'}), '(target=op.main)\n', (36266, 36282), False, 'import threading\n'), ((37344, 37358), 'signal.pause', 'signal.pause', ([], {}), '()\n', (37356, 37358), False, 'import signal\n'), ((1702, 1719), 'threading.Event', 'threading.Event', ([], {}), '()\n', (1717, 1719), False, 'import threading\n'), ((3122, 3267), 'bifrost.packet_capture.UDPCapture', 'UDPCapture', (['"""cor"""', 'self.sock', 'self.oring', 'self.nbl', '(1)', '(9000)', 'self.ntime_gulp', 'self.slot_ntime'], {'sequence_callback': 'seq_callback', 'core': 'self.core'}), "('cor', self.sock, self.oring, self.nbl, 1, 9000, self.ntime_gulp,\n self.slot_ntime, sequence_callback=seq_callback, core=self.core)\n", (3132, 3267), False, 'from bifrost.packet_capture import PacketCaptureCallback, UDPCapture, DiskReader\n'), ((3941, 3958), 'threading.Event', 'threading.Event', ([], {}), '()\n', (3956, 3958), False, 'import threading\n'), ((5594, 5647), 'numpy.zeros', 'numpy.zeros', (['(nbl, nchan, npol, 2)'], {'dtype': 'numpy.int32'}), '((nbl, nchan, npol, 2), dtype=numpy.int32)\n', (5605, 5647), False, 'import numpy\n'), ((6312, 6328), 'json.dumps', 'json.dumps', (['ohdr'], {}), '(ohdr)\n', (6322, 6328), False, 'import json\n'), ((6545, 6556), 'time.time', 'time.time', ([], {}), '()\n', (6554, 6556), False, 'import time\n'), ((9142, 9189), 'os.path.join', 'os.path.join', (['BASE_PATH', '"""fonts"""', '"""helvB10.pil"""'], {}), "(BASE_PATH, 'fonts', 'helvB10.pil')\n", (9154, 9189), False, 'import os\n'), ((12155, 12166), 'time.time', 'time.time', ([], {}), '()\n', (12164, 12166), False, 'import time\n'), ((16384, 16431), 'os.path.join', 'os.path.join', (['BASE_PATH', '"""fonts"""', '"""helvB10.pil"""'], {}), "(BASE_PATH, 'fonts', 'helvB10.pil')\n", (16396, 16431), False, 'import os\n'), ((19646, 19657), 'time.time', 'time.time', ([], {}), '()\n', (19655, 19657), False, 'import time\n'), ((22735, 22767), 'bifrost.affinity.set_core', 'cpu_affinity.set_core', (['self.core'], {}), '(self.core)\n', (22756, 22767), True, 'import bifrost.affinity as cpu_affinity\n'), ((23856, 23867), 'time.time', 'time.time', ([], {}), '()\n', (23865, 23867), False, 'import time\n'), ((27000, 27032), 'bifrost.affinity.set_core', 'cpu_affinity.set_core', (['self.core'], {}), '(self.core)\n', (27021, 27032), True, 'import bifrost.affinity as cpu_affinity\n'), ((28172, 28183), 'time.time', 'time.time', ([], {}), '()\n', (28181, 28183), False, 'import time\n'), ((31570, 31590), 'os.path.abspath', 'os.path.abspath', (['"""."""'], {}), "('.')\n", (31585, 31590), False, 'import os\n'), ((36691, 36708), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (36706, 36708), False, 'from datetime import datetime, timedelta\n'), ((36711, 36732), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(15)'}), '(seconds=15)\n', (36720, 36732), False, 'from datetime import datetime, timedelta\n'), ((37014, 37031), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (37029, 37031), False, 'from datetime import datetime, timedelta\n'), ((37034, 37055), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(75)'}), '(seconds=75)\n', (37043, 37055), False, 'from datetime import datetime, timedelta\n'), ((2599, 2614), 'json.dumps', 'json.dumps', (['hdr'], {}), '(hdr)\n', (2609, 2614), False, 'import json\n'), ((4983, 5010), 'numpy.load', 'numpy.load', (['"""utils/sky.npy"""'], {}), "('utils/sky.npy')\n", (4993, 5010), False, 'import numpy\n'), ((9527, 9546), 'numpy.arange', 'numpy.arange', (['nchan'], {}), '(nchan)\n', (9539, 9546), False, 'import numpy\n'), ((11066, 11089), 'bifrost.affinity.get_core', 'cpu_affinity.get_core', ([], {}), '()\n', (11087, 11089), True, 'import bifrost.affinity as cpu_affinity\n'), ((12336, 12347), 'time.time', 'time.time', ([], {}), '()\n', (12345, 12347), False, 'import time\n'), ((14574, 14585), 'time.time', 'time.time', ([], {}), '()\n', (14583, 14585), False, 'import time\n'), ((18389, 18412), 'bifrost.affinity.get_core', 'cpu_affinity.get_core', ([], {}), '()\n', (18410, 18412), True, 'import bifrost.affinity as cpu_affinity\n'), ((19554, 19577), 'numpy.where', 'numpy.where', (['(dist > 0.1)'], {}), '(dist > 0.1)\n', (19565, 19577), False, 'import numpy\n'), ((19827, 19838), 'time.time', 'time.time', ([], {}), '()\n', (19836, 19838), False, 'import time\n'), ((21477, 21488), 'time.time', 'time.time', ([], {}), '()\n', (21486, 21488), False, 'import time\n'), ((22858, 22881), 'bifrost.affinity.get_core', 'cpu_affinity.get_core', ([], {}), '()\n', (22879, 22881), True, 'import bifrost.affinity as cpu_affinity\n'), ((24073, 24084), 'time.time', 'time.time', ([], {}), '()\n', (24082, 24084), False, 'import time\n'), ((25675, 25686), 'time.time', 'time.time', ([], {}), '()\n', (25684, 25686), False, 'import time\n'), ((27123, 27146), 'bifrost.affinity.get_core', 'cpu_affinity.get_core', ([], {}), '()\n', (27144, 27146), True, 'import bifrost.affinity as cpu_affinity\n'), ((28389, 28400), 'time.time', 'time.time', ([], {}), '()\n', (28398, 28400), False, 'import time\n'), ((30171, 30182), 'time.time', 'time.time', ([], {}), '()\n', (30180, 30182), False, 'import time\n'), ((34607, 34646), 'os.path.realpath', 'os.path.realpath', (['args.record_directory'], {}), '(args.record_directory)\n', (34623, 34646), False, 'import os\n'), ((5162, 5216), 'numpy.zeros', 'numpy.zeros', (['(nbl, nchan, npol)'], {'dtype': 'numpy.complex64'}), '((nbl, nchan, npol), dtype=numpy.complex64)\n', (5173, 5216), False, 'import numpy\n'), ((7467, 7478), 'time.time', 'time.time', ([], {}), '()\n', (7476, 7478), False, 'import time\n'), ((11989, 12008), 'numpy.arange', 'numpy.arange', (['nchan'], {}), '(nchan)\n', (12001, 12008), False, 'import numpy\n'), ((13229, 13261), 'mnc.mcs.ImageMonitorPoint.from_image', 'ImageMonitorPoint.from_image', (['im'], {}), '(im)\n', (13257, 13261), False, 'from mnc.mcs import ImageMonitorPoint, MultiMonitorPoint, Client\n'), ((14445, 14456), 'time.time', 'time.time', ([], {}), '()\n', (14454, 14456), False, 'import time\n'), ((19345, 19364), 'numpy.arange', 'numpy.arange', (['nchan'], {}), '(nchan)\n', (19357, 19364), False, 'import numpy\n'), ((20716, 20748), 'mnc.mcs.ImageMonitorPoint.from_image', 'ImageMonitorPoint.from_image', (['im'], {}), '(im)\n', (20744, 20748), False, 'from mnc.mcs import ImageMonitorPoint, MultiMonitorPoint, Client\n'), ((21348, 21359), 'time.time', 'time.time', ([], {}), '()\n', (21357, 21359), False, 'import time\n'), ((24939, 24963), 'numpy.min', 'numpy.min', (['adata'], {'axis': '(1)'}), '(adata, axis=1)\n', (24948, 24963), False, 'import numpy\n'), ((24995, 25019), 'numpy.max', 'numpy.max', (['adata'], {'axis': '(1)'}), '(adata, axis=1)\n', (25004, 25019), False, 'import numpy\n'), ((25051, 25076), 'numpy.mean', 'numpy.mean', (['adata'], {'axis': '(1)'}), '(adata, axis=1)\n', (25061, 25076), False, 'import numpy\n'), ((25546, 25557), 'time.time', 'time.time', ([], {}), '()\n', (25555, 25557), False, 'import time\n'), ((2379, 2403), 'numpy.sqrt', 'numpy.sqrt', (['(8 * nsrc + 1)'], {}), '(8 * nsrc + 1)\n', (2389, 2403), False, 'import numpy\n'), ((6800, 6811), 'time.time', 'time.time', ([], {}), '()\n', (6809, 6811), False, 'import time\n'), ((7236, 7247), 'time.time', 'time.time', ([], {}), '()\n', (7245, 7247), False, 'import time\n'), ((8739, 8760), 'numpy.isfinite', 'numpy.isfinite', (['specs'], {}), '(specs)\n', (8753, 8760), False, 'import numpy\n'), ((8813, 8834), 'numpy.isfinite', 'numpy.isfinite', (['specs'], {}), '(specs)\n', (8827, 8834), False, 'import numpy\n'), ((12590, 12601), 'time.time', 'time.time', ([], {}), '()\n', (12599, 12601), False, 'import time\n'), ((20081, 20092), 'time.time', 'time.time', ([], {}), '()\n', (20090, 20092), False, 'import time\n'), ((24327, 24338), 'time.time', 'time.time', ([], {}), '()\n', (24336, 24338), False, 'import time\n'), ((32718, 32744), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (32734, 32744), False, 'import os\n'), ((5783, 5794), 'time.time', 'time.time', ([], {}), '()\n', (5792, 5794), False, 'import time\n'), ((6112, 6136), 'numpy.sqrt', 'numpy.sqrt', (['(8 * nsrc + 1)'], {}), '(8 * nsrc + 1)\n', (6122, 6136), False, 'import numpy\n'), ((7337, 7353), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (7347, 7353), False, 'import time\n'), ((7394, 7405), 'time.time', 'time.time', ([], {}), '()\n', (7403, 7405), False, 'import time\n'), ((13135, 13153), 'numpy.log10', 'numpy.log10', (['adata'], {}), '(adata)\n', (13146, 13153), False, 'import numpy\n'), ((7079, 7111), 'numpy.random.randn', 'numpy.random.randn', (['*odata.shape'], {}), '(*odata.shape)\n', (7097, 7111), False, 'import numpy\n')] |
# Copyright 2017, <NAME>, All rights reserved.
import json
from common import overrides, Constants, Persist, PersistError
class ControllerPersist(Persist):
"""
Persisting state for controller
"""
# Keys
__KEY_DOWNLOADED_FILE_NAMES = "downloaded"
__KEY_EXTRACTED_FILE_NAMES = "extracted"
def __init__(self):
self.downloaded_file_names = set()
self.extracted_file_names = set()
@classmethod
@overrides(Persist)
def from_str(cls: "ControllerPersist", content: str) -> "ControllerPersist":
persist = ControllerPersist()
try:
dct = json.loads(content)
persist.downloaded_file_names = set(dct[ControllerPersist.__KEY_DOWNLOADED_FILE_NAMES])
persist.extracted_file_names = set(dct[ControllerPersist.__KEY_EXTRACTED_FILE_NAMES])
return persist
except (json.decoder.JSONDecodeError, KeyError) as e:
raise PersistError("Error parsing AutoQueuePersist - {}: {}".format(
type(e).__name__, str(e))
)
@overrides(Persist)
def to_str(self) -> str:
dct = dict()
dct[ControllerPersist.__KEY_DOWNLOADED_FILE_NAMES] = list(self.downloaded_file_names)
dct[ControllerPersist.__KEY_EXTRACTED_FILE_NAMES] = list(self.extracted_file_names)
return json.dumps(dct, indent=Constants.JSON_PRETTY_PRINT_INDENT)
| [
"json.loads",
"json.dumps",
"common.overrides"
] | [((449, 467), 'common.overrides', 'overrides', (['Persist'], {}), '(Persist)\n', (458, 467), False, 'from common import overrides, Constants, Persist, PersistError\n'), ((1068, 1086), 'common.overrides', 'overrides', (['Persist'], {}), '(Persist)\n', (1077, 1086), False, 'from common import overrides, Constants, Persist, PersistError\n'), ((1338, 1396), 'json.dumps', 'json.dumps', (['dct'], {'indent': 'Constants.JSON_PRETTY_PRINT_INDENT'}), '(dct, indent=Constants.JSON_PRETTY_PRINT_INDENT)\n', (1348, 1396), False, 'import json\n'), ((618, 637), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (628, 637), False, 'import json\n')] |
import copy
import numpy as np
import pandas as pd
import os
import contextlib
from sklearn.metrics import f1_score, accuracy_score
from sklearn.model_selection import StratifiedKFold
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
SEED = 0
NFOLDS = 4
KFOLD = StratifiedKFold(n_splits=NFOLDS, shuffle=True, random_state=SEED)
def skl_macro_f1(y_true, y_hat):
"""Early stopping by macro F1-score, callback function for LightGBM sklearn API."""
y_hat = np.where(y_hat > 0.5, 1, 0)
return 'f1', f1_score(y_true, y_hat, average='macro'), True
class SklearnWrapper(object):
"""Wapper object for Sklearn classifiers."""
def __init__(self, clf, seed=SEED, params=None, scale=False):
if scale:
if params is None:
self.clf = make_pipeline(StandardScaler(), clf)
else:
self.clf = make_pipeline(StandardScaler(), clf(**params))
else:
if params is None:
self.clf = clf
else:
self.clf = clf(**params)
self.clftype = type(clf)
def train(self, x_train, y_train, x_val=None, y_val=None):
self.clf.fit(X=x_train, y=y_train)
def predict(self, x):
return self.clf.predict_proba(x)[:, 1]
def __str__(self):
return str(self.clftype).split(".")[-1][:-2]
class LightGBMWrapper(object):
"""Wrapper object for LightGBMClassifier."""
def __init__(self, clf, seed=SEED, params=None):
params['feature_fraction_seed'] = seed
params['bagging_seed'] = seed
self.params = params
self.clf = clf(**params, n_estimators=10000)
def train(self, x_train, y_train, x_val, y_val):
self.clf.fit(X=x_train, y=y_train, eval_set=(x_val, y_val), verbose=0, early_stopping_rounds=250,
eval_metric=skl_macro_f1)
def predict(self, x):
return self.clf.predict_proba(x)[:, 1]
def __str__(self):
return str(type(self.clf)).split(".")[-1][:-2]
def get_oof(clf, x_train, y_train, x_test, y_test):
"""Get stacked out-of-fold predictions on training data and save classifiers
for future predictions."""
oof_train = np.zeros((x_train.shape[0],))
oof_test = np.zeros((x_test.shape[0],))
oof_test_skf = np.empty((NFOLDS, x_test.shape[0]))
models = []
for i, (train_index, val_index) in enumerate(KFOLD.split(x_train, y_train)):
x_train_fold = x_train[train_index, :]
y_train_fold = y_train[train_index]
x_val_fold = x_train[val_index, :]
y_val_fold = y_train[val_index]
clf.train(x_train_fold, y_train_fold, x_val_fold, y_val_fold)
train_pred = clf.predict(x_train_fold)
oof_pred = clf.predict(x_val_fold)
test_pred = clf.predict(x_test)
oof_train[val_index] = oof_pred
oof_test_skf[i, :] = test_pred
with open(os.devnull, "w") as f, contextlib.redirect_stdout(f):
models.append(copy.deepcopy(clf))
train_f1 = f1_score(y_train_fold, np.round(train_pred), average='macro')
val_f1 = f1_score(y_val_fold, np.round(oof_pred), average='macro')
test_f1 = f1_score(y_test, np.round(test_pred), average='macro')
print(f'Fold {i + 1}/{NFOLDS}, {clf}, train macro-F1: {train_f1:.3f}, oof macro-F1: {val_f1:.3f}, '
f'macro-F1: {test_f1:.3f}')
oof_test[:] = oof_test_skf.mean(axis=0)
return oof_train.reshape(-1, 1).ravel(), oof_test.reshape(-1, 1).ravel(), models
class StackingEnsemble:
"""Stacking ensemble classifier.
To add classifiers, call 'add_to_ensemble' and provide a list of wrappers, a training set for oof predictions,
and test set for validation. The feature set needs a name when training parts of the ensemble on different sets.
After adding classifiers, 'train_meta_learner' needs to be called to train on out-of-fold training predictions.
Predictions can be made on new data provided a list of the same features that was used during training classifiers.
"""
def __init__(self):
self.initialised = False
self.ready_for_meta_learning = False
self.oof_train = pd.DataFrame()
self.oof_test = pd.DataFrame()
self.y_train = None
self.y_test = None
self.clf_count = 0
self.feature_set_count = 0
self.clf_feature_set_ids = []
self.feature_sets = dict()
self.models = []
self.metalearner = None
def add_to_ensemble(self, clf_wrapper_list, x_train, y_train, x_test, y_test, feature_set_name):
"""Train classifiers on provided feature set, add and save to ensemble object."""
print(f"\nAdding to ensemble, {len(clf_wrapper_list)} classifiers trained on input {x_train.shape}:\n")
if feature_set_name in self.feature_sets:
feature_set_id = self.feature_sets['feature_set_name']
else:
feature_set_id = self.feature_set_count
self.feature_sets['feature_set_name'] = self.feature_set_count
self.feature_set_count += 1
if self.initialised:
assert (self.y_train == y_train).all() and (self.y_test == y_test).all(), "provided dataset is different to previously fitted set"
else:
self.initialised = True
self.y_train = y_train
self.y_test = y_test
for clf in clf_wrapper_list:
oof_train, oof_test, models = get_oof(clf, x_train, y_train, x_test, y_test)
self.oof_train[f'{self.feature_set_count}_{self.clf_count}'] = oof_train
self.oof_test[f'{self.feature_set_count}_{self.clf_count}'] = oof_test
self.models.append(models)
self.clf_count += 1
self.clf_feature_set_ids.append(feature_set_id)
self.ready_for_meta_learning = True
def train_meta_learner(self):
"""Train meta-learner on out-of-fold predictions.
Can only be called after having called 'add_to_ensemble'."""
assert self.ready_for_meta_learning is True
print(f"\nTraining meta-learner on ensemble of {self.clf_count} classifiers:")
self.metalearner = LogisticRegression()
self.metalearner.fit(self.oof_train, self.y_train)
preds = self.metalearner.predict(self.oof_train)
ac = accuracy_score(self.y_train, preds)
f1 = f1_score(self.y_train, preds, average='macro')
print(f"Train: accuracy {ac:0.3f}, macro-F1 {f1:0.3f}")
preds = self.metalearner.predict(self.oof_test)
ac = accuracy_score(self.y_test, preds)
f1 = f1_score(self.y_test, preds, average='macro')
print(f"Valid: accuracy {ac:0.3f}, macro-F1 {f1:0.3f} ")
def predict_proba(self, fs_list):
"""Predict probabilities on a list of feature sets, the same used when training the ensemble."""
assert self.metalearner is not None
basepreds = pd.DataFrame()
for i, clf_models in enumerate(self.models):
fs_id = self.clf_feature_set_ids[i]
clf_preds = np.zeros((fs_list[fs_id].shape[0],))
preds_skf = np.empty((NFOLDS, fs_list[fs_id].shape[0]))
for j, clf in enumerate(clf_models):
pred = clf.predict(fs_list[fs_id])
preds_skf[j, :] = pred
clf_preds[:] = preds_skf.mean(axis=0)
basepreds[i] = clf_preds
preds_prob = self.metalearner.predict_proba(basepreds)[:, 1]
return preds_prob
def predict(self, fs_list):
"""Predict binary classes for a list of feature sets, the same used when training the ensemble."""
assert self.metalearner is not None
basepreds = pd.DataFrame()
for i, clf_models in enumerate(self.models):
fs_id = self.clf_feature_set_ids[i]
clf_preds = np.zeros((fs_list[fs_id].shape[0],))
preds_skf = np.empty((NFOLDS, fs_list[fs_id].shape[0]))
for j, clf in enumerate(clf_models):
pred = clf.predict(fs_list[fs_id])
preds_skf[j, :] = pred
clf_preds[:] = preds_skf.mean(axis=0)
basepreds[i] = clf_preds
preds = self.metalearner.predict(basepreds)
return preds
def evaluate(self, fs_list, y):
"""Evaluate ensemble given a list of feature sets and labels."""
preds = self.predict(fs_list)
ac = accuracy_score(y, preds)
f1 = f1_score(y, preds, average='macro')
print(f"Evaluation: accuracy {ac:0.4f}, macro-F1 {f1:0.4f}")
| [
"contextlib.redirect_stdout",
"sklearn.metrics.f1_score",
"numpy.where",
"sklearn.linear_model.LogisticRegression",
"sklearn.model_selection.StratifiedKFold",
"sklearn.preprocessing.StandardScaler",
"numpy.zeros",
"numpy.empty",
"copy.deepcopy",
"pandas.DataFrame",
"sklearn.metrics.accuracy_scor... | [((358, 423), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'NFOLDS', 'shuffle': '(True)', 'random_state': 'SEED'}), '(n_splits=NFOLDS, shuffle=True, random_state=SEED)\n', (373, 423), False, 'from sklearn.model_selection import StratifiedKFold\n'), ((559, 586), 'numpy.where', 'np.where', (['(y_hat > 0.5)', '(1)', '(0)'], {}), '(y_hat > 0.5, 1, 0)\n', (567, 586), True, 'import numpy as np\n'), ((2278, 2307), 'numpy.zeros', 'np.zeros', (['(x_train.shape[0],)'], {}), '((x_train.shape[0],))\n', (2286, 2307), True, 'import numpy as np\n'), ((2323, 2351), 'numpy.zeros', 'np.zeros', (['(x_test.shape[0],)'], {}), '((x_test.shape[0],))\n', (2331, 2351), True, 'import numpy as np\n'), ((2371, 2406), 'numpy.empty', 'np.empty', (['(NFOLDS, x_test.shape[0])'], {}), '((NFOLDS, x_test.shape[0]))\n', (2379, 2406), True, 'import numpy as np\n'), ((604, 644), 'sklearn.metrics.f1_score', 'f1_score', (['y_true', 'y_hat'], {'average': '"""macro"""'}), "(y_true, y_hat, average='macro')\n", (612, 644), False, 'from sklearn.metrics import f1_score, accuracy_score\n'), ((4263, 4277), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4275, 4277), True, 'import pandas as pd\n'), ((4302, 4316), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4314, 4316), True, 'import pandas as pd\n'), ((6262, 6282), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (6280, 6282), False, 'from sklearn.linear_model import LogisticRegression\n'), ((6413, 6448), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['self.y_train', 'preds'], {}), '(self.y_train, preds)\n', (6427, 6448), False, 'from sklearn.metrics import f1_score, accuracy_score\n'), ((6462, 6508), 'sklearn.metrics.f1_score', 'f1_score', (['self.y_train', 'preds'], {'average': '"""macro"""'}), "(self.y_train, preds, average='macro')\n", (6470, 6508), False, 'from sklearn.metrics import f1_score, accuracy_score\n'), ((6643, 6677), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['self.y_test', 'preds'], {}), '(self.y_test, preds)\n', (6657, 6677), False, 'from sklearn.metrics import f1_score, accuracy_score\n'), ((6691, 6736), 'sklearn.metrics.f1_score', 'f1_score', (['self.y_test', 'preds'], {'average': '"""macro"""'}), "(self.y_test, preds, average='macro')\n", (6699, 6736), False, 'from sklearn.metrics import f1_score, accuracy_score\n'), ((7011, 7025), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7023, 7025), True, 'import pandas as pd\n'), ((7788, 7802), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7800, 7802), True, 'import pandas as pd\n'), ((8500, 8524), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y', 'preds'], {}), '(y, preds)\n', (8514, 8524), False, 'from sklearn.metrics import f1_score, accuracy_score\n'), ((8538, 8573), 'sklearn.metrics.f1_score', 'f1_score', (['y', 'preds'], {'average': '"""macro"""'}), "(y, preds, average='macro')\n", (8546, 8573), False, 'from sklearn.metrics import f1_score, accuracy_score\n'), ((3004, 3033), 'contextlib.redirect_stdout', 'contextlib.redirect_stdout', (['f'], {}), '(f)\n', (3030, 3033), False, 'import contextlib\n'), ((3124, 3144), 'numpy.round', 'np.round', (['train_pred'], {}), '(train_pred)\n', (3132, 3144), True, 'import numpy as np\n'), ((3201, 3219), 'numpy.round', 'np.round', (['oof_pred'], {}), '(oof_pred)\n', (3209, 3219), True, 'import numpy as np\n'), ((3273, 3292), 'numpy.round', 'np.round', (['test_pred'], {}), '(test_pred)\n', (3281, 3292), True, 'import numpy as np\n'), ((7154, 7190), 'numpy.zeros', 'np.zeros', (['(fs_list[fs_id].shape[0],)'], {}), '((fs_list[fs_id].shape[0],))\n', (7162, 7190), True, 'import numpy as np\n'), ((7215, 7258), 'numpy.empty', 'np.empty', (['(NFOLDS, fs_list[fs_id].shape[0])'], {}), '((NFOLDS, fs_list[fs_id].shape[0]))\n', (7223, 7258), True, 'import numpy as np\n'), ((7931, 7967), 'numpy.zeros', 'np.zeros', (['(fs_list[fs_id].shape[0],)'], {}), '((fs_list[fs_id].shape[0],))\n', (7939, 7967), True, 'import numpy as np\n'), ((7992, 8035), 'numpy.empty', 'np.empty', (['(NFOLDS, fs_list[fs_id].shape[0])'], {}), '((NFOLDS, fs_list[fs_id].shape[0]))\n', (8000, 8035), True, 'import numpy as np\n'), ((3061, 3079), 'copy.deepcopy', 'copy.deepcopy', (['clf'], {}), '(clf)\n', (3074, 3079), False, 'import copy\n'), ((890, 906), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (904, 906), False, 'from sklearn.preprocessing import StandardScaler\n'), ((972, 988), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (986, 988), False, 'from sklearn.preprocessing import StandardScaler\n')] |
import cv2
import sys
import json
import numpy as np
from matplotlib import pyplot as plt
shape='n/aaaa'
imgPath="C:\\xampp\\htdocs\\projektmunka\\python\\haromszog.png"
#imgPath=sys.argv[1]
img = cv2.imread(imgPath, cv2.IMREAD_GRAYSCALE)
_, threshold = cv2.threshold(img, 240, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True)
cv2.drawContours(img, [approx], 0, (0), 5)
x = approx.ravel()[0]
y = approx.ravel()[1]
if len(approx) == 3:
shape="triangle"
elif len(approx) == 4:
shape="square"
elif len(approx) == 5:
shape="otszog"
elif 6 < len(approx) < 15:
shape="sokszog"
else:
shape="circle"
print(shape)
| [
"cv2.drawContours",
"cv2.threshold",
"cv2.arcLength",
"cv2.findContours",
"cv2.imread"
] | [((198, 239), 'cv2.imread', 'cv2.imread', (['imgPath', 'cv2.IMREAD_GRAYSCALE'], {}), '(imgPath, cv2.IMREAD_GRAYSCALE)\n', (208, 239), False, 'import cv2\n'), ((255, 302), 'cv2.threshold', 'cv2.threshold', (['img', '(240)', '(255)', 'cv2.THRESH_BINARY'], {}), '(img, 240, 255, cv2.THRESH_BINARY)\n', (268, 302), False, 'import cv2\n'), ((317, 384), 'cv2.findContours', 'cv2.findContours', (['threshold', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (333, 384), False, 'import cv2\n'), ((483, 523), 'cv2.drawContours', 'cv2.drawContours', (['img', '[approx]', '(0)', '(0)', '(5)'], {}), '(img, [approx], 0, 0, 5)\n', (499, 523), False, 'import cv2\n'), ((447, 471), 'cv2.arcLength', 'cv2.arcLength', (['cnt', '(True)'], {}), '(cnt, True)\n', (460, 471), False, 'import cv2\n')] |
import aoareader as reader
import torch
import time
import argparse
import os
from preprocess import get_stories, vectorize_stories
parser = argparse.ArgumentParser(description="test.py")
parser.add_argument('-testdata', default='data/test.txt.pt',
help='Path to the test.txt.pt, test.txt.pt will be used if exists.')
parser.add_argument('-dict', default="data/dict.pt",
help='Path to the dictionary file, default value: data/dict.pt')
parser.add_argument('-out', default='data/result.txt',
help='output file name.')
parser.add_argument('-model', required=True, help='path to the saved model.')
testopt = parser.parse_args()
print(testopt)
def load_testdata(testfile, vocab_dict, with_answer=True):
if os.path.exists(testfile + '.pt'):
return torch.load(testfile + '.pt')
else:
testd = {}
with open(testfile, 'r') as tf:
tlines = tf.readlines()
test_stories = get_stories(tlines, with_answer=with_answer)
testd['documents'], testd['querys'], testd['answers'], testd['candidates'] = vectorize_stories(test_stories, vocab_dict)
torch.save(testd, testfile + '.pt')
return testd
def evalulate(model, data, vocab_dict):
def acc(answers, pred_answers):
num_correct = (answers == pred_answers).sum().squeeze().data[0]
return num_correct
model.eval()
answers = []
total_correct = 0
total = 0
for i in range(len(data)):
(batch_docs, batch_docs_len, doc_mask), (batch_querys, batch_querys_len, query_mask), batch_answers , candidates = data[i]
pred_answers, _ = model(batch_docs, batch_docs_len, doc_mask,
batch_querys, batch_querys_len, query_mask,
candidates=candidates, answers=batch_answers)
answers.extend(pred_answers.data)
num_correct = acc(batch_answers, pred_answers)
total_in_minibatch = batch_answers.size(0)
total_correct += num_correct
total += total_in_minibatch
del pred_answers
print("Evaluating on test set:\nAccurary {:.2%}".format(total_correct / total))
return vocab_dict.convert2word(answers)
def main():
print("Loading dict", testopt.dict)
vocab_dict = torch.load(testopt.dict)
print("Loading test data")
test_data = torch.load(testopt.testdata)
print("Loading model from ", testopt.model)
ckp = torch.load(testopt.model)
opt = ckp['opt']
model_state = ckp['model']
if opt.gpu:
torch.cuda.set_device(opt.gpu)
test_dataset = reader.Dataset(test_data, opt.batch_size, True, volatile=True)
print(' * vocabulary size = %d' %
(vocab_dict.size()))
print(' * number of test samples. %d' %
len(test_data['candidates']))
print(' * maximum batch size. %d' % opt.batch_size)
print('Building model...')
model = reader.AoAReader(vocab_dict, dropout_rate=opt.dropout, embed_dim=opt.embed_size, hidden_dim=opt.gru_size)
# no way on CPU
model.cuda()
# load state
model.load_state_dict(model_state)
print('Evaluate on test data')
answers = evalulate(model, test_dataset, vocab_dict)
with open(testopt.out, 'w') as out:
print('\n'.join(answers), file=out)
if __name__ == '__main__':
main()
| [
"os.path.exists",
"argparse.ArgumentParser",
"aoareader.Dataset",
"torch.load",
"preprocess.vectorize_stories",
"aoareader.AoAReader",
"torch.save",
"preprocess.get_stories",
"torch.cuda.set_device"
] | [((144, 190), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""test.py"""'}), "(description='test.py')\n", (167, 190), False, 'import argparse\n'), ((777, 809), 'os.path.exists', 'os.path.exists', (["(testfile + '.pt')"], {}), "(testfile + '.pt')\n", (791, 809), False, 'import os\n'), ((2320, 2344), 'torch.load', 'torch.load', (['testopt.dict'], {}), '(testopt.dict)\n', (2330, 2344), False, 'import torch\n'), ((2393, 2421), 'torch.load', 'torch.load', (['testopt.testdata'], {}), '(testopt.testdata)\n', (2403, 2421), False, 'import torch\n'), ((2481, 2506), 'torch.load', 'torch.load', (['testopt.model'], {}), '(testopt.model)\n', (2491, 2506), False, 'import torch\n'), ((2636, 2698), 'aoareader.Dataset', 'reader.Dataset', (['test_data', 'opt.batch_size', '(True)'], {'volatile': '(True)'}), '(test_data, opt.batch_size, True, volatile=True)\n', (2650, 2698), True, 'import aoareader as reader\n'), ((2954, 3064), 'aoareader.AoAReader', 'reader.AoAReader', (['vocab_dict'], {'dropout_rate': 'opt.dropout', 'embed_dim': 'opt.embed_size', 'hidden_dim': 'opt.gru_size'}), '(vocab_dict, dropout_rate=opt.dropout, embed_dim=opt.\n embed_size, hidden_dim=opt.gru_size)\n', (2970, 3064), True, 'import aoareader as reader\n'), ((826, 854), 'torch.load', 'torch.load', (["(testfile + '.pt')"], {}), "(testfile + '.pt')\n", (836, 854), False, 'import torch\n'), ((1173, 1208), 'torch.save', 'torch.save', (['testd', "(testfile + '.pt')"], {}), "(testd, testfile + '.pt')\n", (1183, 1208), False, 'import torch\n'), ((2585, 2615), 'torch.cuda.set_device', 'torch.cuda.set_device', (['opt.gpu'], {}), '(opt.gpu)\n', (2606, 2615), False, 'import torch\n'), ((987, 1031), 'preprocess.get_stories', 'get_stories', (['tlines'], {'with_answer': 'with_answer'}), '(tlines, with_answer=with_answer)\n', (998, 1031), False, 'from preprocess import get_stories, vectorize_stories\n'), ((1121, 1164), 'preprocess.vectorize_stories', 'vectorize_stories', (['test_stories', 'vocab_dict'], {}), '(test_stories, vocab_dict)\n', (1138, 1164), False, 'from preprocess import get_stories, vectorize_stories\n')] |
from django.contrib import admin
from .models import Report
@admin.register(Report)
class ReportAdmin(admin.ModelAdmin):
list_display = ['project_name','contractor_name', 'done_on']
search_fields = ['project_name','contractor_name'] | [
"django.contrib.admin.register"
] | [((62, 84), 'django.contrib.admin.register', 'admin.register', (['Report'], {}), '(Report)\n', (76, 84), False, 'from django.contrib import admin\n')] |
from abc import abstractmethod
from dataclasses import dataclass
from typing import Any
class Spec:
@abstractmethod
def passes(self, candidate: Any) -> bool:
raise NotImplementedError()
def __call__(self, candidate: Any) -> bool:
return self.passes(candidate)
def __and__(self, other: "Spec") -> "And":
return And(self, other)
def __or__(self, other: "Spec") -> "Or":
return Or(self, other)
def __neg__(self) -> "Not":
return Not(self)
@dataclass(frozen=True)
class And(Spec):
first: Spec
second: Spec
def passes(self, candidate: Any) -> bool:
return self.first.passes(candidate) and self.second.passes(candidate)
@dataclass(frozen=True)
class Or(Spec):
first: Spec
second: Spec
def passes(self, candidate: Any) -> bool:
return self.first.passes(candidate) or self.second.passes(candidate)
@dataclass(frozen=True)
class Not(Spec):
subject: Spec
def passes(self, candidate: Any) -> bool:
return not self.subject.passes(candidate)
| [
"dataclasses.dataclass"
] | [((509, 531), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (518, 531), False, 'from dataclasses import dataclass\n'), ((710, 732), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (719, 732), False, 'from dataclasses import dataclass\n'), ((909, 931), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (918, 931), False, 'from dataclasses import dataclass\n')] |
from os import getenv, \
path
from time import time
from datetime import timedelta
class Config(object):
AWS_ACCESS_KEY_ID = getenv('AWS_ACCESS_KEY_ID')
AWS_REGION = getenv('AWS_REGION')
AWS_S3_BUCKET = getenv('AWS_S3_BUCKET')
AWS_SECRET_ACCESS_KEY = getenv('AWS_SECRET_ACCESS_KEY')
CACHE_BUSTER = time()
DEBUG = getenv('DEBUG', False)
GALLERIES_PER_PAGE = getenv('GALLERIES_PER_PAGE', 5)
GOOGLE_ANALYTICS_ID = getenv('GOOGLE_ANALYTICS_ID', False)
LAMBDA_INSTRUCTIONS = getenv('LAMBDA_INSTRUCTIONS')
MAX_UPLOAD_SIZE = getenv('MAX_UPLOAD_SIZE')
PERMANENT_SESSION_LIFETIME = timedelta(minutes=30)
REMEMBER_COOKIE_DURATION = timedelta(days=30)
SECRET_KEY = getenv('SECRET_KEY')
SEND_FILE_MAX_AGE_DEFAULT = 365 * 86400
SITE_NAME = getenv('SITE_NAME', 'Ineffable')
SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL', 'sqlite:///' + path.dirname(__file__) + '/app/app.db').replace('mysql2:', 'mysql:')
SQLALCHEMY_ECHO = getenv('SQLALCHEMY_ECHO', False)
SQLALCHEMY_POOL_RECYCLE = 60
TESTING = False
| [
"os.path.dirname",
"datetime.timedelta",
"time.time",
"os.getenv"
] | [((145, 172), 'os.getenv', 'getenv', (['"""AWS_ACCESS_KEY_ID"""'], {}), "('AWS_ACCESS_KEY_ID')\n", (151, 172), False, 'from os import getenv, path\n'), ((190, 210), 'os.getenv', 'getenv', (['"""AWS_REGION"""'], {}), "('AWS_REGION')\n", (196, 210), False, 'from os import getenv, path\n'), ((231, 254), 'os.getenv', 'getenv', (['"""AWS_S3_BUCKET"""'], {}), "('AWS_S3_BUCKET')\n", (237, 254), False, 'from os import getenv, path\n'), ((283, 314), 'os.getenv', 'getenv', (['"""AWS_SECRET_ACCESS_KEY"""'], {}), "('AWS_SECRET_ACCESS_KEY')\n", (289, 314), False, 'from os import getenv, path\n'), ((334, 340), 'time.time', 'time', ([], {}), '()\n', (338, 340), False, 'from time import time\n'), ((353, 375), 'os.getenv', 'getenv', (['"""DEBUG"""', '(False)'], {}), "('DEBUG', False)\n", (359, 375), False, 'from os import getenv, path\n'), ((401, 432), 'os.getenv', 'getenv', (['"""GALLERIES_PER_PAGE"""', '(5)'], {}), "('GALLERIES_PER_PAGE', 5)\n", (407, 432), False, 'from os import getenv, path\n'), ((459, 495), 'os.getenv', 'getenv', (['"""GOOGLE_ANALYTICS_ID"""', '(False)'], {}), "('GOOGLE_ANALYTICS_ID', False)\n", (465, 495), False, 'from os import getenv, path\n'), ((522, 551), 'os.getenv', 'getenv', (['"""LAMBDA_INSTRUCTIONS"""'], {}), "('LAMBDA_INSTRUCTIONS')\n", (528, 551), False, 'from os import getenv, path\n'), ((574, 599), 'os.getenv', 'getenv', (['"""MAX_UPLOAD_SIZE"""'], {}), "('MAX_UPLOAD_SIZE')\n", (580, 599), False, 'from os import getenv, path\n'), ((633, 654), 'datetime.timedelta', 'timedelta', ([], {'minutes': '(30)'}), '(minutes=30)\n', (642, 654), False, 'from datetime import timedelta\n'), ((686, 704), 'datetime.timedelta', 'timedelta', ([], {'days': '(30)'}), '(days=30)\n', (695, 704), False, 'from datetime import timedelta\n'), ((722, 742), 'os.getenv', 'getenv', (['"""SECRET_KEY"""'], {}), "('SECRET_KEY')\n", (728, 742), False, 'from os import getenv, path\n'), ((803, 835), 'os.getenv', 'getenv', (['"""SITE_NAME"""', '"""Ineffable"""'], {}), "('SITE_NAME', 'Ineffable')\n", (809, 835), False, 'from os import getenv, path\n'), ((995, 1027), 'os.getenv', 'getenv', (['"""SQLALCHEMY_ECHO"""', '(False)'], {}), "('SQLALCHEMY_ECHO', False)\n", (1001, 1027), False, 'from os import getenv, path\n'), ((904, 926), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (916, 926), False, 'from os import getenv, path\n')] |
from ConnectFour import ConnectFour
import pytest
def test_empty_cell():
my = ConnectFour.Game()
assert not my.check_for_win(2, 2)
def test_diagonal_win():
# positive slope
my = ConnectFour.Game()
my.move(1) # X
my.move(2) # Y
my.move(2) # YX
my.move(3) # Y
my.move(3) # YX
my.move(4) # Y
my.move(3) # YXX
my.move(4) # YY
my.move(4) # YYX
my.move(6) # Y
my.move(4) # YYXX
assert my.check_for_win(3, 4)
assert my.winner == 'X'
winning_discs = [(3, 4), (2, 3), (1, 2), (0, 1)]
returned_winning_discs = my.get_winning_discs()
for disc in returned_winning_discs:
assert disc in winning_discs
for disc in winning_discs:
assert disc in returned_winning_discs
# game was already decided
assert my.move(4) == None
# negative slope
my = ConnectFour.Game()
my.move(6) # X
my.move(5) # Y
my.move(5) # YX
my.move(0) # Y
my.move(4) # X
my.move(4) # XY
my.move(4) # XYX
my.move(3) # Y
my.move(3) # YX
my.move(3) # YXY
my.move(3) # YXYX
assert my.check_for_win(3, 3)
assert my.winner == 'X'
returned_winning_discs = my.get_winning_discs()
winning_discs = [(3, 3), (2, 4), (1, 5), (0, 6)]
for disc in returned_winning_discs:
assert disc in winning_discs
for disc in winning_discs:
assert disc in returned_winning_discs
def test_horizontal_win():
my = ConnectFour.Game()
# fill the first row
for i in range(7):
my.move(i)
my.move(2)
my.move(2)
my.move(3)
my.move(3)
my.move(4)
my.move(4)
my.move(5)
assert my.check_for_win(1, 5)
assert my.winner == 'Y'
winning_discs = [(1, 2), (1, 3), (1, 4), (1, 5)]
returned_winning_discs = my.get_winning_discs()
for disc in returned_winning_discs:
assert disc in winning_discs
for disc in winning_discs:
assert disc in returned_winning_discs
# game was already decided
assert my.move(4) == None
def test_vertical_win():
my = ConnectFour.Game()
my.move(2)
my.move(2)
my.move(2)
my.move(5)
my.move(2)
my.move(5)
my.move(2)
my.move(5)
my.move(2)
assert my.check_for_win(5, 2)
assert my.winner == 'X'
winning_discs = [(2, 2), (3, 2), (4, 2), (5, 2)]
returned_winning_discs = my.get_winning_discs()
for disc in returned_winning_discs:
assert disc in winning_discs
for disc in winning_discs:
assert disc in returned_winning_discs
# game was already decided
assert my.move(4) == None
def test_draw():
my = ConnectFour.Game()
for col in range(3):
for _ in range(6):
my.move(col)
my.move(6)
for col in range(3, 7):
for _ in range(6):
my.move(col)
# now the board is full, but no winners
assert my.winner == 'D'
my.print_board()
test_draw() | [
"ConnectFour.ConnectFour.Game"
] | [((89, 107), 'ConnectFour.ConnectFour.Game', 'ConnectFour.Game', ([], {}), '()\n', (105, 107), False, 'from ConnectFour import ConnectFour\n'), ((207, 225), 'ConnectFour.ConnectFour.Game', 'ConnectFour.Game', ([], {}), '()\n', (223, 225), False, 'from ConnectFour import ConnectFour\n'), ((893, 911), 'ConnectFour.ConnectFour.Game', 'ConnectFour.Game', ([], {}), '()\n', (909, 911), False, 'from ConnectFour import ConnectFour\n'), ((1522, 1540), 'ConnectFour.ConnectFour.Game', 'ConnectFour.Game', ([], {}), '()\n', (1538, 1540), False, 'from ConnectFour import ConnectFour\n'), ((2155, 2173), 'ConnectFour.ConnectFour.Game', 'ConnectFour.Game', ([], {}), '()\n', (2171, 2173), False, 'from ConnectFour import ConnectFour\n'), ((2742, 2760), 'ConnectFour.ConnectFour.Game', 'ConnectFour.Game', ([], {}), '()\n', (2758, 2760), False, 'from ConnectFour import ConnectFour\n')] |
#coding:UTF-8
import os
import discord
from discord.ext import tasks
from datetime import datetime
token = os.environ['DISCORD_BOT_TOKEN'] #トークン
channel_id = os.environ['CHANNEL_ID'] #チャンネルID
# 接続に必要なオブジェクトを生成
client = discord.Client()
@tasks.loop(seconds=60)
async def loop():
print(datetime.now().strftime("%Y/%m/%d %H:%M:%S"), "start")
print(client.is_ready())
channel = client.get_channel(channel_id)
if channel != None :
print(channel)
await channel.send('てすと')
@client.event
async def on_ready():
#ループ処理実行
loop.start()
# Botの起動とDiscordサーバーへの接続
client.run(token)
| [
"discord.Client",
"datetime.datetime.now",
"discord.ext.tasks.loop"
] | [((221, 237), 'discord.Client', 'discord.Client', ([], {}), '()\n', (235, 237), False, 'import discord\n'), ((240, 262), 'discord.ext.tasks.loop', 'tasks.loop', ([], {'seconds': '(60)'}), '(seconds=60)\n', (250, 262), False, 'from discord.ext import tasks\n'), ((291, 305), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (303, 305), False, 'from datetime import datetime\n')] |
import os
import sys
# from lmdb.cffi import version as ver
sys.path.append(os.getcwd())
import torch
from iqra.models.crnn import *
from iqra.modules.feature import *
if __name__ == '__main__':
image_data = torch.rand(3,1,224,224)
text_data = torch.rand(3,512).long()
# text_data = torch.LongTensor(text_data)
# fe = FeatureExtraction(in_channels=1, version=50)
# hype = fe.feature.last_channels
# print(fe)
# print(fe(image_data))
# print()
# print(fe(image_data).shape)
# out = enc(test_data)
# # print(out)
num_class = 96
im_size = (32, 100)
model = OCRNet(num_class = num_class, im_size=im_size)
out = model(image_data, text_data)
print(out)
print(out.shape)
| [
"torch.rand",
"os.getcwd"
] | [((76, 87), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (85, 87), False, 'import os\n'), ((216, 242), 'torch.rand', 'torch.rand', (['(3)', '(1)', '(224)', '(224)'], {}), '(3, 1, 224, 224)\n', (226, 242), False, 'import torch\n'), ((256, 274), 'torch.rand', 'torch.rand', (['(3)', '(512)'], {}), '(3, 512)\n', (266, 274), False, 'import torch\n')] |
import numpy as np
import yt
from matplotlib import rc
fsize = 17
rc('text', usetex=False)
rc('font', size=fsize)#, ftype=42)
line_width = 3
point_size = 30
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from galaxy_analysis.particle_analysis import particle_types as pdef
def plot_dtd(ds):
data = ds.all_data()
snIa = pdef.snIa(ds, data)
WD = pdef.white_dwarfs(ds, data)
WD_death = data['dynamical_time'][WD] # + data['creation_time'][WD]
SNIa_death = data['dynamical_time'][snIa] # + data['creation_time'][snIa]
WD_death = list(WD_death.convert_to_units("Gyr").value)
SNIa_death = list(SNIa_death.convert_to_units("Gyr").value)
fig, ax = plt.subplots()
all = np.array( WD_death + SNIa_death)
hist, bins = np.histogram(all, bins = np.arange(0,14.25,0.5))
x = 0.5 * (bins[1:] + bins[:-1])
ax.plot(x, hist, lw = 3, color = 'black', ls = '-')
y = x**(-1.0* ds.parameters['IndividualStarDTDSlope'])
norm = hist[0] / y[0]
ax.plot(x, norm*y, lw = 3, color = 'black', ls='--')
ax.plot(x, hist[0]/((x[0])**(-1.01)) * x**(-1.01),lw =3, color = 'black',ls=':')
ax.set_xlabel(r'Time (Gyr)')
ax.set_ylabel(r'Binned SNIa (counts)')
ax.loglog()
fig.set_size_inches(8,8)
plt.tight_layout()
plt.minorticks_on()
fig.savefig('dtd.png')
plt.close()
return
if __name__ == "__main__":
ds = yt.load('DD0205/DD0205')
data = ds.all_data()
plot_dtd(ds)
| [
"matplotlib.use",
"galaxy_analysis.particle_analysis.particle_types.snIa",
"matplotlib.pyplot.minorticks_on",
"matplotlib.pyplot.close",
"numpy.array",
"galaxy_analysis.particle_analysis.particle_types.white_dwarfs",
"yt.load",
"matplotlib.rc",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.... | [((66, 90), 'matplotlib.rc', 'rc', (['"""text"""'], {'usetex': '(False)'}), "('text', usetex=False)\n", (68, 90), False, 'from matplotlib import rc\n'), ((91, 113), 'matplotlib.rc', 'rc', (['"""font"""'], {'size': 'fsize'}), "('font', size=fsize)\n", (93, 113), False, 'from matplotlib import rc\n'), ((182, 196), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (189, 196), True, 'import matplotlib as mpl\n'), ((355, 374), 'galaxy_analysis.particle_analysis.particle_types.snIa', 'pdef.snIa', (['ds', 'data'], {}), '(ds, data)\n', (364, 374), True, 'from galaxy_analysis.particle_analysis import particle_types as pdef\n'), ((386, 413), 'galaxy_analysis.particle_analysis.particle_types.white_dwarfs', 'pdef.white_dwarfs', (['ds', 'data'], {}), '(ds, data)\n', (403, 413), True, 'from galaxy_analysis.particle_analysis import particle_types as pdef\n'), ((710, 724), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (722, 724), True, 'import matplotlib.pyplot as plt\n'), ((735, 766), 'numpy.array', 'np.array', (['(WD_death + SNIa_death)'], {}), '(WD_death + SNIa_death)\n', (743, 766), True, 'import numpy as np\n'), ((1282, 1300), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1298, 1300), True, 'import matplotlib.pyplot as plt\n'), ((1305, 1324), 'matplotlib.pyplot.minorticks_on', 'plt.minorticks_on', ([], {}), '()\n', (1322, 1324), True, 'import matplotlib.pyplot as plt\n'), ((1356, 1367), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1365, 1367), True, 'import matplotlib.pyplot as plt\n'), ((1419, 1443), 'yt.load', 'yt.load', (['"""DD0205/DD0205"""'], {}), "('DD0205/DD0205')\n", (1426, 1443), False, 'import yt\n'), ((811, 835), 'numpy.arange', 'np.arange', (['(0)', '(14.25)', '(0.5)'], {}), '(0, 14.25, 0.5)\n', (820, 835), True, 'import numpy as np\n')] |
from flask_wtf import FlaskForm
from wtforms import IntegerField
from wtforms.validators import DataRequired
class ClusterSetupForm(FlaskForm):
clusters = IntegerField('Clusters', validators=[DataRequired()])
replicas = IntegerField('Replicas', validators=[DataRequired()])
| [
"wtforms.validators.DataRequired"
] | [((198, 212), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (210, 212), False, 'from wtforms.validators import DataRequired\n'), ((267, 281), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (279, 281), False, 'from wtforms.validators import DataRequired\n')] |
#!/usr/bin/env python3
# Tool that dumps all the (ids, titles, urls) of SimpleWiki articles into a pickle file. It reads this information from the output of the WikiExtraction parser [1]
# [1]: https://github.com/attardi/wikiextractor
import argparse
import os
import random
import pickle
from lxml import etree
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('inputDir', type=str, help="Directory, where the wikiExtraction output was written to")
parser.add_argument('--output', type=str, help="Name and directory of outputfile.", default='wikiextraction_id_dump.pickle')
args = parser.parse_args()
inputDir = args.inputDir
output = args.output
files = [os.path.join(root, name)
for root, dirs, files in os.walk(inputDir)
for name in files
if name.startswith(("wiki_"))]
articleList = []
parser = etree.XMLParser(recover=True)
for fn in files:
f = open(fn)
currArticle = ''
for line in f:
currArticle += line
if line.strip() == '</doc>':
xmlArticle = etree.fromstring(currArticle, parser=parser)
currArticle = ''
articleList.append(dict(xmlArticle.attrib))
random.shuffle(articleList)
pickle.dump(articleList, open(output, "wb"))
print('article list successfully dumped into ' + output)
| [
"random.shuffle",
"argparse.ArgumentParser",
"os.path.join",
"lxml.etree.XMLParser",
"lxml.etree.fromstring",
"os.walk"
] | [((351, 376), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (374, 376), False, 'import argparse\n'), ((866, 895), 'lxml.etree.XMLParser', 'etree.XMLParser', ([], {'recover': '(True)'}), '(recover=True)\n', (881, 895), False, 'from lxml import etree\n'), ((1167, 1194), 'random.shuffle', 'random.shuffle', (['articleList'], {}), '(articleList)\n', (1181, 1194), False, 'import random\n'), ((709, 733), 'os.path.join', 'os.path.join', (['root', 'name'], {}), '(root, name)\n', (721, 733), False, 'import os\n'), ((761, 778), 'os.walk', 'os.walk', (['inputDir'], {}), '(inputDir)\n', (768, 778), False, 'import os\n'), ((1046, 1090), 'lxml.etree.fromstring', 'etree.fromstring', (['currArticle'], {'parser': 'parser'}), '(currArticle, parser=parser)\n', (1062, 1090), False, 'from lxml import etree\n')] |
# UNUSED
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from six import text_type
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, appointment, timestamp):
return (text_type(appointment.volunteer)+text_type(appointment.pk)+text_type(timestamp))
# return (text_type(user.pk) + text_type(timestamp) + text_type(user.profile.email_confirmed))
appointment_confirmation_token = TokenGenerator() | [
"six.text_type"
] | [((285, 305), 'six.text_type', 'text_type', (['timestamp'], {}), '(timestamp)\n', (294, 305), False, 'from six import text_type\n'), ((226, 258), 'six.text_type', 'text_type', (['appointment.volunteer'], {}), '(appointment.volunteer)\n', (235, 258), False, 'from six import text_type\n'), ((259, 284), 'six.text_type', 'text_type', (['appointment.pk'], {}), '(appointment.pk)\n', (268, 284), False, 'from six import text_type\n')] |
"""Tests cac.models.classification.ClassificationModel"""
import os
from os.path import dirname, join, exists
from copy import deepcopy
import torch
import wandb
import unittest
from tqdm import tqdm
import numpy as np
from torch import optim
from cac.config import Config
from cac.utils.logger import set_logger, color
from cac.models.classification import ClassificationModel
class ClassificationModelTestCase(unittest.TestCase):
"""Class to check the creation of ClassificationModel"""
@classmethod
def setUpClass(cls):
version = 'default.yml'
cls.cfg = Config(version)
cls.cfg.data['dataset']['params']['val']['fraction'] = 0.1
cls.cfg.num_workers = 1 if torch.cuda.is_available() else 10
# def test_1_model_fitting(self):
# """Test model.fit()"""
# set_logger(join(self.cfg.log_dir, 'train.log'))
# tester_cfg = deepcopy(self.cfg)
# tester_cfg.model['epochs'] = 1
# classifier = ClassificationModel(tester_cfg)
# classifier.fit(debug=True, use_wandb=False)
def test_optimizer(self):
"""Test model.fit()"""
set_logger(join(self.cfg.log_dir, 'train.log'))
tester_cfg = deepcopy(self.cfg)
tester_cfg.model['epochs'] = 1
classifier = ClassificationModel(tester_cfg)
self.assertIsInstance(classifier.optimizer, optim.SGD)
self.assertIsInstance(
classifier.scheduler, optim.lr_scheduler.ReduceLROnPlateau)
def test_with_frames(self):
"""Test models/lassification.py with fixed frames"""
cfg = Config('defaults/with-frames.yml')
cfg.data['dataset']['params']['train']['fraction'] = 0.01
cfg.data['dataset']['params']['val']['fraction'] = 0.03
cfg.model['batch_size'] = 4 # to make it work on small CPU machines
cfg.num_workers = 1
set_logger(join(cfg.log_dir, 'train.log'))
tester_cfg = deepcopy(cfg)
tester_cfg.model['epochs'] = 1
classifier = ClassificationModel(tester_cfg)
classifier.fit(debug=True, use_wandb=False)
def test_with_label_smoothing(self):
"""Test model.fit() with label smoothing"""
tester_cfg = Config('defaults/label-smoothing-random.yml')
set_logger(join(tester_cfg.log_dir, 'train.log'))
tester_cfg.data['dataset']['params']['train']['fraction'] = 0.01
tester_cfg.data['dataset']['params']['val']['fraction'] = 0.03
tester_cfg.model['batch_size'] = 4 # to make it work on small CPU machines
tester_cfg.num_workers = 1
tester_cfg.model['epochs'] = 1
classifier = ClassificationModel(tester_cfg)
classifier.fit(use_wandb=False)
def test_get_unique_paths(self):
"""Tests getting unique paths with order preserved (Used in _aggregate_data())"""
# input paths
paths = ['b', 'b', 'a', 'a', 'c', 'c', 'c', 'c']
# expected unique outputs with preserved order
exp_output = np.array(['b', 'a', 'c'])
_, idx = np.unique(paths, return_index=True)
unique_paths = np.take(paths, np.sort(idx))
self.assertTrue((unique_paths == exp_output).all())
if __name__ == "__main__":
unittest.main()
| [
"numpy.unique",
"numpy.sort",
"os.path.join",
"numpy.array",
"torch.cuda.is_available",
"copy.deepcopy",
"unittest.main",
"cac.models.classification.ClassificationModel",
"cac.config.Config"
] | [((3251, 3266), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3264, 3266), False, 'import unittest\n'), ((587, 602), 'cac.config.Config', 'Config', (['version'], {}), '(version)\n', (593, 602), False, 'from cac.config import Config\n'), ((1202, 1220), 'copy.deepcopy', 'deepcopy', (['self.cfg'], {}), '(self.cfg)\n', (1210, 1220), False, 'from copy import deepcopy\n'), ((1281, 1312), 'cac.models.classification.ClassificationModel', 'ClassificationModel', (['tester_cfg'], {}), '(tester_cfg)\n', (1300, 1312), False, 'from cac.models.classification import ClassificationModel\n'), ((1587, 1621), 'cac.config.Config', 'Config', (['"""defaults/with-frames.yml"""'], {}), "('defaults/with-frames.yml')\n", (1593, 1621), False, 'from cac.config import Config\n'), ((1929, 1942), 'copy.deepcopy', 'deepcopy', (['cfg'], {}), '(cfg)\n', (1937, 1942), False, 'from copy import deepcopy\n'), ((2003, 2034), 'cac.models.classification.ClassificationModel', 'ClassificationModel', (['tester_cfg'], {}), '(tester_cfg)\n', (2022, 2034), False, 'from cac.models.classification import ClassificationModel\n'), ((2202, 2247), 'cac.config.Config', 'Config', (['"""defaults/label-smoothing-random.yml"""'], {}), "('defaults/label-smoothing-random.yml')\n", (2208, 2247), False, 'from cac.config import Config\n'), ((2628, 2659), 'cac.models.classification.ClassificationModel', 'ClassificationModel', (['tester_cfg'], {}), '(tester_cfg)\n', (2647, 2659), False, 'from cac.models.classification import ClassificationModel\n'), ((3010, 3035), 'numpy.array', 'np.array', (["['b', 'a', 'c']"], {}), "(['b', 'a', 'c'])\n", (3018, 3035), True, 'import numpy as np\n'), ((3062, 3097), 'numpy.unique', 'np.unique', (['paths'], {'return_index': '(True)'}), '(paths, return_index=True)\n', (3071, 3097), True, 'import numpy as np\n'), ((705, 730), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (728, 730), False, 'import torch\n'), ((1143, 1178), 'os.path.join', 'join', (['self.cfg.log_dir', '"""train.log"""'], {}), "(self.cfg.log_dir, 'train.log')\n", (1147, 1178), False, 'from os.path import dirname, join, exists\n'), ((1875, 1905), 'os.path.join', 'join', (['cfg.log_dir', '"""train.log"""'], {}), "(cfg.log_dir, 'train.log')\n", (1879, 1905), False, 'from os.path import dirname, join, exists\n'), ((2267, 2304), 'os.path.join', 'join', (['tester_cfg.log_dir', '"""train.log"""'], {}), "(tester_cfg.log_dir, 'train.log')\n", (2271, 2304), False, 'from os.path import dirname, join, exists\n'), ((3136, 3148), 'numpy.sort', 'np.sort', (['idx'], {}), '(idx)\n', (3143, 3148), True, 'import numpy as np\n')] |
import random
from time import sleep
from selenium import webdriver
# Instancio el driver de selenium que va a controlar el navegador
# A partir de este objeto voy a realizar el web scraping e interacciones
driver = webdriver.Chrome(r"C:\Users\rburi\AppData\Local\Programs\Python\Python39\Proyectos\Scraping_Project\chromedriver.exe")
# Voy a la pagina que requiero
driver.get('https://www.olx.com.co/atlantico_g2007003/carros_c378?sorting=desc-creation')
'''
# Busco el boton para cargar mas informacion
boton = driver.find_element_by_xpath('//button[@data-aut-id="btnLoadMore"]')
for i in range(1): # Voy a darle click en cargar mas 3 veces
try:
# le doy click
boton.click()
# espero que cargue la informacion dinamica
sleep(random.uniform(8.0, 10.0))
# busco el boton nuevamente para darle click en la siguiente iteracion
boton = driver.find_element_by_xpath('//button[@data-aut-id="btnLoadMore"]')
except:
# si hay algun error, rompo el lazo. No me complico.
break
# Encuentro cual es el XPATH de cada elemento donde esta la informacion que quiero extraer
# Esto es una LISTA. Por eso el metodo esta en plural
'''
'''
# Busco el boton de los carros para darle click
boton_auto = driver.find_element_by_xpath('//li[@data-aut-id="itemBox"]')
for i in range(1): # Voy a darle click en cargar mas 3 veces
try:
# le doy click
boton_auto.click()
# espero que cargue la informacion dinamica
sleep(random.uniform(8.0, 10.0))
# busco el boton nuevamente para darle click en la siguiente iteracion
boton_auto = driver.find_element_by_xpath('//li[@data-aut-id="itemBox"]')
except:
# si hay algun error, rompo el lazo. No me complico.
break
'''
#INICIO DE SESION OLX
boton_login = driver.find_element_by_xpath('//button[@data-aut-id="btnLogin"]')
boton_login.click()
sleep(random.uniform(8.0, 10.0))
boton_email = driver.find_element_by_xpath('//button[@data-aut-id="emailLogin"]')
boton_email.click()
sleep(random.uniform(6.0, 10.0))
e_mail = driver.find_element_by_xpath('//input[@id="email_input_field"]')
e_mail.send_keys("<EMAIL>")
sleep(random.uniform(6.0, 11.0))
boton_sgte_mail = driver.find_element_by_xpath('//button[@class="rui-3sH3b rui-2yJ_A rui-1zK8h _2_t7-"]')
boton_sgte_mail.click()
sleep(random.uniform(6.0, 11.0))
'''
#DESCOMENTAR PARA SEGUIR CON LA SECUENCIA
autos = driver.find_element_by_xpath('//li[@data-aut-id="itemBox"]')
# Recorro cada uno de los anuncios que he encontrado
for auto in autos:
# Por cada anuncio hallo el precio
autos.click()
sleep(random.uniform(8.0, 10.0))
precio = driver.find_element_by_xpath('.//span[@data-aut-id="itemPrice"]').text
nombre_vendedor = driver.find_element_by_xpath('.//div[@class="_3oOe9"]').text
descripcion = driver.find_element_by_xpath('.//span[@data-aut-id="itemTitle"]').text
print(nombre_vendedor)
print (precio)
print (descripcion)
sleep(random.uniform(8.0, 10.0))
driver.back()
# Por cada anuncio hallo la descripcion
'''
| [
"selenium.webdriver.Chrome",
"random.uniform"
] | [((217, 354), 'selenium.webdriver.Chrome', 'webdriver.Chrome', (['"""C:\\\\Users\\\\rburi\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python39\\\\Proyectos\\\\Scraping_Project\\\\chromedriver.exe"""'], {}), "(\n 'C:\\\\Users\\\\rburi\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python39\\\\Proyectos\\\\Scraping_Project\\\\chromedriver.exe'\n )\n", (233, 354), False, 'from selenium import webdriver\n'), ((1916, 1941), 'random.uniform', 'random.uniform', (['(8.0)', '(10.0)'], {}), '(8.0, 10.0)\n', (1930, 1941), False, 'import random\n'), ((2051, 2076), 'random.uniform', 'random.uniform', (['(6.0)', '(10.0)'], {}), '(6.0, 10.0)\n', (2065, 2076), False, 'import random\n'), ((2186, 2211), 'random.uniform', 'random.uniform', (['(6.0)', '(11.0)'], {}), '(6.0, 11.0)\n', (2200, 2211), False, 'import random\n'), ((2349, 2374), 'random.uniform', 'random.uniform', (['(6.0)', '(11.0)'], {}), '(6.0, 11.0)\n', (2363, 2374), False, 'import random\n')] |
"""
Scrape card info from pokemon-card.com
and save as csv file
author: type-null
date: July 2020
"""
import bs4
import sys
import requests
import pandas as pd
def getContent(cardId):
# anti-scraping
user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:68.0) Gecko/20100101 Firefox/68.0"
url = f'https://www.pokemon-card.com/card-search/details.php/card/{cardId}'
response = requests.get(url, headers={'User-Agent': user_agent})
if response.status_code == 200:
# print(response.content.decode('utf-8'))
return response.content.decode('utf-8')
else:
print(f"Fail to get the url [{response.status_code}]")
return [cardId, response.status_code]
def readEnergyMegaPrismstar(p):
# <span class="pcg pcg-megamark"></span>
# <span class="pcg pcg-prismstar">
# <span class="icon-psychic icon">
spans = p.find_all('span')
marks = []
if spans:
for span in spans:
if 'icon' in str(span):
marks.append(span['class'][0].split('-')[1])
elif 'mega' in str(span):
marks.append(span['class'][1].split('-')[1][:4])
elif 'prismstar' in str(span):
marks.append(span['class'][1].split('-')[1])
for i in range(len(marks)):
p = str(p).replace(str(spans[i]), marks[i])
p = bs4.BeautifulSoup(p)
p = p.get_text().replace('\n ', '')
return p
def readCard(content):
# start reading content
soup = bs4.BeautifulSoup(content, 'html.parser')
card = soup.section
# all type cards
name = readEnergyMegaPrismstar(card.h1)
img = card.find('img', class_='fit')['src']
# init
[reg, setNum, setCount, rarity, dexNum, dexClass,
height, weight, dexDesc, author, desc, stage,
hp, pType, ability, abilityDesc, waza1Cost, waza1Name,
waza1Damage, waza1Desc, waza2Cost, waza2Name, waza2Damage, waza2Desc,
GXCost, GXName, GXDamage, GXDesc,
weakType, weakValue, resistType, resistValue, escape, spRule] = [''] * 34
# decide card type
cardType = card.h2.get_text()
if cardType == '基本エネルギー':
return [cardType, name, img, reg, setNum, setCount, rarity, dexNum,
dexClass, height, weight, dexDesc, author, desc, stage, hp, pType,
ability, abilityDesc, waza1Cost, waza1Name, waza1Damage,
waza1Desc, waza2Cost, waza2Name, waza2Damage, waza2Desc,
GXCost, GXName, GXDamage, GXDesc,
weakType, weakValue, resistType, resistValue,
escape, spRule]
## left box
reg = card.find('img', class_='img-regulation')['alt'] # regulation
regImg = card.find('img', class_='img-regulation')['src']
setInfo = card.find('div', class_='subtext').get_text().strip()
if len(setInfo.split('/')) == 2:
setCount = setInfo.strip()[-3:]
if setCount.isdigit():
setCount = int(setCount)
setNum = int(setInfo.strip()[:3])
else:
setCount = setInfo
if card.find('img', width='24'):
rarityImg = card.find('img', width='24')['src']
rarity = rarityImg.split('.')[0].split('ic_')[1]
if cardType == '特殊エネルギー':
desc = readEnergyMegaPrismstar(card.find('p'))
return [cardType, name, img, reg, setNum, setCount, rarity, dexNum,
dexClass, height, weight, dexDesc, author, desc, stage, hp, pType,
ability, abilityDesc, waza1Cost, waza1Name, waza1Damage,
waza1Desc, waza2Cost, waza2Name, waza2Damage, waza2Desc,
GXCost, GXName, GXDamage, GXDesc,
weakType, weakValue, resistType, resistValue,
escape, spRule]
author = card.find('div', class_='author').get_text().strip()
if author:
author = card.find('div', class_='author').get_text().strip().split('\n')[1]
### national pokedex
pokedex = card.find('div', class_='card')
if pokedex: # has pokedex
if pokedex.h4:
dexline = pokedex.h4.get_text().strip().split('\u3000')
if len(dexline) == 2:
[dexNum, dexClass] = dexline
dexNum = int(dexNum.split('.')[1])
elif len(dexline) == 1:
if any(char.isdigit() for char in dexline[0]):
dexNum = dexline[0]
else:
dexClass = dexline[0]
if len(pokedex.find_all('p')) == 2:
htAndWt = pokedex.p.get_text().split(':')
height = float(htAndWt[1].split(' ')[0])
weight = float(htAndWt[2].split(' ')[0])
dexDesc = pokedex.find_all('p')[1].get_text()
elif len(pokedex.find_all('p')) == 1 and '重さ' in pokedex.find('p').get_text():
htAndWt = pokedex.p.get_text().split(':')
height = float(htAndWt[1].split(' ')[0])
weight = float(htAndWt[2].split(' ')[0])
elif len(pokedex.find_all('p')) == 1:
dexDesc = pokedex.find('p').get_text()
if cardType in ['サポート', 'グッズ', 'ポケモンのどうぐ', 'スタジアム']:
desc = card.find_all('p')
if cardType in ['サポート', 'グッズ', 'スタジアム']:
desc = readEnergyMegaPrismstar(desc[0])
if cardType == 'ポケモンのどうぐ':
desc = readEnergyMegaPrismstar(desc[1])
return [cardType, name, img, reg, setNum, setCount, rarity, dexNum,
dexClass, height, weight, dexDesc, author, desc, stage, hp, pType,
ability, abilityDesc, waza1Cost, waza1Name, waza1Damage,
waza1Desc, waza2Cost, waza2Name, waza2Damage, waza2Desc,
GXCost, GXName, GXDamage, GXDesc,
weakType, weakValue, resistType, resistValue,
escape, spRule]
cardType = 'pokemon'
## right box
stage = card.find('span', class_='type').get_text()
if '\xa0' in stage:
stage = stage.replace('\xa0', ' ')
hp = card.find('span', class_='hp-num').get_text()
hp = int(hp)
topSpans = card.find('div', class_='td-r').find_all('span')
topSpansClass = [span['class'] for span in topSpans]
pTypes = [s for s in topSpansClass if 'icon' in s]
pType = [l[0].split('-')[1] for l in pTypes]
### waza part
part = content.split('<span class="hp-type">タイプ</span>')[1].split('</table>')[0].strip()
soup = bs4.BeautifulSoup(part)
wazaPart = bs4.BeautifulSoup(soup.prettify(formatter="minimal"))
h2 = wazaPart.find_all('h2')
skills = wazaPart.find_all('h4')
if not skills[-1].get_text().strip():
# empty (wrong special rule as void)
del skills[-1]
p = wazaPart.find_all('p')
if not skills[0].get_text().strip():
# mega evolution rule (delete)
del skills[0]
del p[0]
for area in h2:
areaType = area.get_text().strip()
if areaType in ["特性", "古代能力"]:
# ability or ancient trait
# print('learning an ability')
ability = skills[0].get_text().strip()
abilityDesc = readEnergyMegaPrismstar(p[0]).strip()
del skills[0]
elif areaType == "特別なルール":
# special rule
# print('learning a special rule')
spRule = readEnergyMegaPrismstar(p[-1]).strip()
del p[-1]
elif areaType == "GXワザ":
# GX waza
[GXCost, GXName, GXDamage, GXDesc] = [''] * 4
# print('learning a GX attack')
GXCost = [span['class'][0].split('-')[1] for span in skills[-1].find_all('span', class_='icon')]
GX = skills[-1].get_text().strip().split(' ')
GXName = GX[0].strip()
GXDamage = GX[-1]
if not GXDamage[-2].isdigit():
GXDamage = ''
GXDesc = skills[-1].find_next_sibling('p')
GXDesc = readEnergyMegaPrismstar(GXDesc).strip()
del skills[-1], p[-2]
elif areaType == "ワザ":
# waza
waza1Cost = [span['class'][0].split('-')[1] for span in skills[0].find_all('span', class_='icon')]
waza1 = skills[0].get_text().strip().split(' ')
waza1Name = waza1[0].strip()
waza1Damage = waza1[-1]
if not waza1Damage[-2].isdigit():
waza1Damage = ''
waza1Desc = skills[0].find_next_sibling('p')
waza1Desc = readEnergyMegaPrismstar(waza1Desc).strip()
if len(skills) > 1:
waza2Cost = [span['class'][0].split('-')[1] for span in skills[1].find_all('span', class_='icon')]
waza2 = skills[1].get_text().strip().split(' ')
waza2Name = waza2[0].strip()
waza2Damage = waza2[-1]
if not waza2Damage[-2].isdigit():
waza2Damage = ''
waza2Desc = skills[1].find_next_sibling('p')
waza2Desc = readEnergyMegaPrismstar(waza2Desc).strip()
else:
print(f"{name} has an unseen areaType: {areaType}!!")
### table
td = wazaPart.find_all('td')
if td[0].find('span'):
weakType = td[0].find('span')['class'][0].split('-')[1]
weakValue = td[0].get_text().strip()
if td[1].find('span'):
resistType = td[1].find('span')['class'][0].split('-')[1]
resistValue = td[1].get_text().strip()
escape = len(td[2].find_all('span'))
return [cardType, name, img, reg, setNum, setCount, rarity, dexNum,
dexClass, height, weight, dexDesc, author, desc, stage, hp, pType,
ability, abilityDesc, waza1Cost, waza1Name, waza1Damage,
waza1Desc, waza2Cost, waza2Name, waza2Damage, waza2Desc,
GXCost, GXName, GXDamage, GXDesc,
weakType, weakValue, resistType, resistValue,
escape, spRule]
def scrapeCards(start, end):
columns = ['cardId', 'cardType', 'name', 'img', 'regulation', 'setNum', 'setCount', 'rarity', 'dexNum',
'dexClass', 'height', 'weight', 'dexDesc', 'author', 'desc', 'stage', 'hp', 'pType',
'ability', 'abilityDesc', 'waza1Cost', 'waza1Name', 'waza1Damage',
'waza1Desc', 'waza2Cost', 'waza2Name', 'waza2Damage', 'waza2Desc',
'GXCost', 'GXName', 'GXDamage', 'GXDesc',
'weakType', 'weakValue', 'resistType', 'resistValue', 'escape', 'spRule']
cardDF = pd.DataFrame(columns=columns)
errorDF = pd.DataFrame(columns=['errorCardId'])
n = end - start+1
for i in range(n):
cardId = start + i
content = getContent(cardId)
soup = bs4.BeautifulSoup(content, 'html.parser')
if soup.section:
cardDF.loc[i] = [cardId] + readCard(content)
else:
errorDF.loc[i] = [cardId]
# print(cardId)
j = (i + 1) / n
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write("[%-20s] %d%%" % ('='*int(20*j), 100*j))
sys.stdout.write(f"\t({i+1}/{n})")
sys.stdout.flush()
cardDF.reset_index().to_csv(f'output/cards_jp_{start}_{end}.csv')
if len(errorDF) > 0:
errorDF.reset_index().to_csv(f'output/error_id_{start}_{end}.csv') | [
"requests.get",
"bs4.BeautifulSoup",
"pandas.DataFrame",
"sys.stdout.flush",
"sys.stdout.write"
] | [((396, 449), 'requests.get', 'requests.get', (['url'], {'headers': "{'User-Agent': user_agent}"}), "(url, headers={'User-Agent': user_agent})\n", (408, 449), False, 'import requests\n'), ((1509, 1550), 'bs4.BeautifulSoup', 'bs4.BeautifulSoup', (['content', '"""html.parser"""'], {}), "(content, 'html.parser')\n", (1526, 1550), False, 'import bs4\n'), ((6370, 6393), 'bs4.BeautifulSoup', 'bs4.BeautifulSoup', (['part'], {}), '(part)\n', (6387, 6393), False, 'import bs4\n'), ((10435, 10464), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns'}), '(columns=columns)\n', (10447, 10464), True, 'import pandas as pd\n'), ((10479, 10516), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['errorCardId']"}), "(columns=['errorCardId'])\n", (10491, 10516), True, 'import pandas as pd\n'), ((1369, 1389), 'bs4.BeautifulSoup', 'bs4.BeautifulSoup', (['p'], {}), '(p)\n', (1386, 1389), False, 'import bs4\n'), ((10646, 10687), 'bs4.BeautifulSoup', 'bs4.BeautifulSoup', (['content', '"""html.parser"""'], {}), "(content, 'html.parser')\n", (10663, 10687), False, 'import bs4\n'), ((10878, 10900), 'sys.stdout.write', 'sys.stdout.write', (["'\\r'"], {}), "('\\r')\n", (10894, 10900), False, 'import sys\n'), ((11022, 11058), 'sys.stdout.write', 'sys.stdout.write', (['f"""\t({i + 1}/{n})"""'], {}), "(f'\\t({i + 1}/{n})')\n", (11038, 11058), False, 'import sys\n'), ((11065, 11083), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (11081, 11083), False, 'import sys\n')] |
# Create your views here.
import mimetypes
from django.http import HttpResponse
from django import shortcuts
from sample import models
def serve_mongo_download(request, mongo_id):
obj = shortcuts.get_object_or_404(models.SampleModel, content=mongo_id)
return get_mongo_response(obj.content)
def get_mongo_response(file_object, chunks=10000):
"""
Prepares a Django HttpResponse to deliver the stored file.
parameters:
- file_object: the file object from our model's MongoFileField.
(ie. model.content in the sample models included)
- chunks: how big of chunk size to read and deliver the file
"""
mimetype, encoding = mimetypes.guess_type(file_object.file_name)
mimetype = mimetype or 'application/octet-stream'
response = HttpResponse(file_object.chunks(chunks), mimetype=mimetype)
response['Content-Length'] = file_object.size
response['Content-Disposition'] = "inline; filename = %s; " % file_object.file_name
if encoding:
response['Content-Encoding'] = encoding
return response | [
"mimetypes.guess_type",
"django.shortcuts.get_object_or_404"
] | [((194, 259), 'django.shortcuts.get_object_or_404', 'shortcuts.get_object_or_404', (['models.SampleModel'], {'content': 'mongo_id'}), '(models.SampleModel, content=mongo_id)\n', (221, 259), False, 'from django import shortcuts\n'), ((681, 724), 'mimetypes.guess_type', 'mimetypes.guess_type', (['file_object.file_name'], {}), '(file_object.file_name)\n', (701, 724), False, 'import mimetypes\n')] |
# Copyright 2017 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Reads and parses lines from a serial device.
Typically from an Arduino. Lines are expected to follow the InfluxDB's line
protocol format (with the difference that the timestamp is allowed to be
missing).
"""
import logging
import time
import serial
class Sample(object):
"""Represents a single sample in the InfluxDB format."""
def __init__(self, line):
"""Parses a given line and stores in a new Sample.
If timestamp is missing, the current time is used.
Args:
line: String to be parsed.
Raises:
ValueError if the line can't be parsed.
"""
words = line.strip().split(" ")
if len(words) == 2:
(self.tags_line, self.values_line) = words
self.timestamp = time.time()
elif len(words) == 3:
(self.tags_line, self.values_line, timestamp) = words
self.timestamp = float(timestamp) / 1000000000.0
else:
raise ValueError("Unable to parse line {0!r}".format(line))
def AddTags(self, tag_line):
"""Adds tags from 'tag_line' into 'self.tags_line'."""
if tag_line:
self.tags_line += ","
self.tags_line += tag_line
return self
def FormatInfluxLine(self):
"""Formats the accumulated tags and values into an InfluxDB line."""
return "{0} {1} {2:d}".format(
self.tags_line, self.values_line, long(self.timestamp * 1000000000))
def __str__(self):
return '{0}(tags_line={1},values_line={2},timestamp={3})'.format(
self.__class__.__name__, self.tags_line, self.values_line,
self.timestamp)
def __repr__(self):
return "{0}({1!r})".format(self.__class__.__name__,
self.FormatInfluxLine())
def SkipUntilNewLine(handle):
"""Skips data until a new-line character is received.
This is needed so that the first sample is read from a complete line.
"""
logging.debug("Skipping until the end of a new line.")
while not handle.readline(4096).endswith('\n'):
pass
class LineOverflowError(IOError):
"""Thrown when a line longer than a given limit is received."""
def __init__(self, line):
super(LineOverflowError, self).__init__(
"Received incomplete line {0!r}".format(line))
def SerialLines(device_url, baud_rate, read_timeout, max_line_length):
"""A generator that yields lines from a configured serial line.
Will never exit normally, only with an exception when there is an error
in the serial communication.
"""
with serial.serial_for_url(device_url, baudrate=baud_rate,
timeout=read_timeout) as handle:
SkipUntilNewLine(handle)
while True:
line = handle.readline(max_line_length)
logging.debug("Received line %r", line)
if not line.endswith('\n'):
raise LineOverflowError(line)
try:
yield Sample(line.rstrip())
except ValueError:
logging.exception("Failed to parse Sample from '%s'", line)
| [
"logging.exception",
"serial.serial_for_url",
"logging.debug",
"time.time"
] | [((2559, 2613), 'logging.debug', 'logging.debug', (['"""Skipping until the end of a new line."""'], {}), "('Skipping until the end of a new line.')\n", (2572, 2613), False, 'import logging\n'), ((3187, 3262), 'serial.serial_for_url', 'serial.serial_for_url', (['device_url'], {'baudrate': 'baud_rate', 'timeout': 'read_timeout'}), '(device_url, baudrate=baud_rate, timeout=read_timeout)\n', (3208, 3262), False, 'import serial\n'), ((1345, 1356), 'time.time', 'time.time', ([], {}), '()\n', (1354, 1356), False, 'import time\n'), ((3422, 3461), 'logging.debug', 'logging.debug', (['"""Received line %r"""', 'line'], {}), "('Received line %r', line)\n", (3435, 3461), False, 'import logging\n'), ((3656, 3715), 'logging.exception', 'logging.exception', (['"""Failed to parse Sample from \'%s\'"""', 'line'], {}), '("Failed to parse Sample from \'%s\'", line)\n', (3673, 3715), False, 'import logging\n')] |
import importlib
import os
import runpy
import shutil
from configparser import ConfigParser
import pkg_resources
import sys
from clinodes.nodes import ArgNode, Switch
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relation, sessionmaker
from gofri.lib.http.app import Application
from gofri.lib.pip.pip_handler import PIPHandler
try:
from gofri.lib.global_config import Configuration
from gofri.lib.conf.local import init_local_conf_file, load_default_config
os.environ["GOFRI_HAS_ROOT"] = "True"
except KeyError:
print("No root package detected! Running in standalone mode")
os.environ["GOFRI_HAS_ROOT"] = "False"
def init_extension_config(filename):
fullpath = "{}/{}".format(Configuration.ROOT_PATH, filename)
conf = ConfigParser()
conf.read(fullpath)
return conf
EXTENSION_CONFIG = {}
APP = Application(static_conf={
"enable": True,
"dir": "/static",
"path": os.path.join(os.path.dirname(__file__), "static"),
})
Base = declarative_base()
def integrate_extensions(autoconf=False):
root_path = Configuration.ROOT_PATH
if Configuration.EXTENSIONS is not None:
init_local_conf_file(root_path)
exts = Configuration.EXTENSIONS
for cmod in Configuration.EXTENSIONS:
ext = exts["extension"]
name = ext["name"]
if "autorun" in ext:
if ext["autorun"] == "True":
runpy.run_module("{}.main".format(name), run_name="__main__", alter_sys=True)
if autoconf:
if "autoconf" in ext:
if ext["autoconf"] == "True":
load_default_config(root_path, name)
USE_RELOADER = False
def run():
conf = Configuration
if conf.HOST == None:
conf.HOST = "127.0.0.1"
APP.run(port=int(conf.PORT), host=conf.HOST, use_reloader=USE_RELOADER)
def start(root_path, modules, autoconf=False, auto_install=False,):
piphandler = PIPHandler()
piphandler.packages = Configuration.DEPENDENCIES
if auto_install:
piphandler.install()
print("All required dependencies are installed")
CUSTOM_CONFIG = init_extension_config("custom-conf.ini")
integrate_extensions(autoconf)
importlib.import_module("modules", modules)
run()
def main(root_path, modules):
Configuration.AUTO_INSTALL = False
do_autoconf = False
class ReloaderSwitch(Switch):
def run(self, *args):
global USE_RELOADER
USE_RELOADER = True
class InstallerSwitch(Switch):
def setup(self):
self.expects_more = False
def run(self, *args):
Configuration.AUTO_INSTALL = True
class UpdaterSwitch(Switch):
def setup(self):
self.expects_more = False
def run(self, *args):
do_autoconf = True
class RootNode(ArgNode):
def setup(self):
self.expects_more = False
self.switches = {
"--enable-default": UpdaterSwitch,
"-ed": UpdaterSwitch,
"--install": InstallerSwitch,
"--use-reloader": ReloaderSwitch
}
def run(self, *args_remained):
do_auto_install = Configuration.AUTO_INSTALL
start(root_path, modules, autoconf=do_autoconf, auto_install=do_auto_install)
RootNode() | [
"importlib.import_module",
"configparser.ConfigParser",
"gofri.lib.pip.pip_handler.PIPHandler",
"gofri.lib.conf.local.init_local_conf_file",
"os.path.dirname",
"gofri.lib.conf.local.load_default_config",
"sqlalchemy.ext.declarative.declarative_base"
] | [((1042, 1060), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {}), '()\n', (1058, 1060), False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((814, 828), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (826, 828), False, 'from configparser import ConfigParser\n'), ((2011, 2023), 'gofri.lib.pip.pip_handler.PIPHandler', 'PIPHandler', ([], {}), '()\n', (2021, 2023), False, 'from gofri.lib.pip.pip_handler import PIPHandler\n'), ((2284, 2327), 'importlib.import_module', 'importlib.import_module', (['"""modules"""', 'modules'], {}), "('modules', modules)\n", (2307, 2327), False, 'import importlib\n'), ((1197, 1228), 'gofri.lib.conf.local.init_local_conf_file', 'init_local_conf_file', (['root_path'], {}), '(root_path)\n', (1217, 1228), False, 'from gofri.lib.conf.local import init_local_conf_file, load_default_config\n'), ((993, 1018), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1008, 1018), False, 'import os\n'), ((1695, 1731), 'gofri.lib.conf.local.load_default_config', 'load_default_config', (['root_path', 'name'], {}), '(root_path, name)\n', (1714, 1731), False, 'from gofri.lib.conf.local import init_local_conf_file, load_default_config\n')] |
import requests, io, csv, datetime
import county_report, state_report
STATE_ABBR = 'OH'
STATE = 'Ohio'
URL = 'https://coronavirus.ohio.gov/static/COVIDSummaryData.csv'
def scraper():
# make an HTTP web request to get the CA CSV file
response = requests.get(URL)
if response.status_code == requests.codes.ok:
# Success - print to the console that the HTTP request succeeeded
print(' ', STATE_ABBR, ': Downloaded succeeded')
csvData = response.text
# read the in-memory string using the 'csv' module so we can iterate over each row
csvReader = csv.reader(csvData.splitlines(), delimiter=',', quotechar='"')
# create a list that will contain our county data
counties = []
# iterate over every row in the CSV
for row in csvReader:
county_name = row[0]
confirmedStr = row[6]
# skip the header row
if county_name == 'County' or len(county_name) == 0 or confirmedStr == 'Case Count' or county_name == 'Grand Total':
continue
confirmed = int(confirmedStr.replace(',', ''))
deathsStr = row[7]
deaths = int(deathsStr.replace(',', ''))
hospitalizationsStr = row[8]
hospitalizations = int(hospitalizationsStr.replace(',', ''))
county = findCounty(county_name, counties)
if county == None:
county = county_report.CountyReport(STATE, county_name, confirmed, deaths, hospitalizations, -1, datetime.datetime.now())
counties.append(county) # append the countyReport to our list of counties
else:
county.confirmed += confirmed
county.deaths += deaths
county.hospitalizations += hospitalizations
# print the number of counties we processed
print(' ', STATE_ABBR, ':', len(counties), ' counties processed OK')
# build the state-level report object that will include all of the counties
stateReport = state_report.StateReport(STATE, STATE_ABBR, counties, datetime.datetime.now())
# return the state-level report
return stateReport
else:
# Fail
print(' ', STATE_ABBR, ': ERROR : Download failed - HTTP status code ', response.status_code)
def findCounty(county_name, counties):
for county in counties:
if county.county == county_name:
return county | [
"datetime.datetime.now",
"requests.get"
] | [((254, 271), 'requests.get', 'requests.get', (['URL'], {}), '(URL)\n', (266, 271), False, 'import requests, io, csv, datetime\n'), ((2154, 2177), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2175, 2177), False, 'import requests, io, csv, datetime\n'), ((1568, 1591), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1589, 1591), False, 'import requests, io, csv, datetime\n')] |
from ossConfig import ossConfig
import Oss
access_key = '<KEY>'
secret_key = '<KEY>'
endpoint_url = 'http://XXXXXXXXXXXXXXXXX.com'
config = ossConfig(access_key, secret_key, endpoint_url)
bucket_name = 'test1'
object_name = 'mytestput'
URL = Oss.PresignedURLs(config, bucket_name, object_name)
print(URL)
| [
"Oss.PresignedURLs",
"ossConfig.ossConfig"
] | [((141, 188), 'ossConfig.ossConfig', 'ossConfig', (['access_key', 'secret_key', 'endpoint_url'], {}), '(access_key, secret_key, endpoint_url)\n', (150, 188), False, 'from ossConfig import ossConfig\n'), ((245, 296), 'Oss.PresignedURLs', 'Oss.PresignedURLs', (['config', 'bucket_name', 'object_name'], {}), '(config, bucket_name, object_name)\n', (262, 296), False, 'import Oss\n')] |
import models
import serializers
# Third Party
from rest_framework import viewsets
class RoastViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows roastss to be viewed or edited.
"""
filter_fields = ['coffee', ]
queryset = models.Roast.objects.all()
serializer_class = serializers.RoastSerializer | [
"models.Roast.objects.all"
] | [((254, 280), 'models.Roast.objects.all', 'models.Roast.objects.all', ([], {}), '()\n', (278, 280), False, 'import models\n')] |
import numpy as np
from numba import jit
from numba.core import types
from numba.tests.support import TestCase, tag
import unittest
# Array overlaps involving a displacement
def array_overlap1(src, dest, k=1):
assert src.shape == dest.shape
dest[k:] = src[:-k]
def array_overlap2(src, dest, k=1):
assert src.shape == dest.shape
dest[:-k] = src[k:]
def array_overlap3(src, dest, k=1):
assert src.shape == dest.shape
dest[:,:-k] = src[:,k:]
def array_overlap4(src, dest, k=1):
assert src.shape == dest.shape
dest[:,k:] = src[:,:-k]
def array_overlap5(src, dest, k=1):
assert src.shape == dest.shape
dest[...,:-k] = src[...,k:]
def array_overlap6(src, dest, k=1):
assert src.shape == dest.shape
dest[...,k:] = src[...,:-k]
# Array overlaps involving an in-place reversal
def array_overlap11(src, dest):
assert src.shape == dest.shape
dest[::-1] = src
def array_overlap12(src, dest):
assert src.shape == dest.shape
dest[:] = src[::-1]
def array_overlap13(src, dest):
assert src.shape == dest.shape
dest[:,::-1] = src
def array_overlap14(src, dest):
assert src.shape == dest.shape
dest[:] = src[:,::-1]
def array_overlap15(src, dest):
assert src.shape == dest.shape
dest[...,::-1] = src
def array_overlap16(src, dest):
assert src.shape == dest.shape
dest[:] = src[...,::-1]
class TestArrayOverlap(TestCase):
def check_overlap(self, pyfunc, min_ndim, have_k_argument=False):
N = 4
def vary_layouts(orig):
yield orig.copy(order='C')
yield orig.copy(order='F')
a = orig[::-1].copy()[::-1]
assert not a.flags.c_contiguous and not a.flags.f_contiguous
yield a
def check(pyfunc, cfunc, pydest, cdest, kwargs):
pyfunc(pydest, pydest, **kwargs)
cfunc(cdest, cdest, **kwargs)
self.assertPreciseEqual(pydest, cdest)
cfunc = jit(nopython=True)(pyfunc)
# Check for up to 3d arrays
for ndim in range(min_ndim, 4):
shape = (N,) * ndim
orig = np.arange(0, N**ndim).reshape(shape)
# Note we cannot copy a 'A' layout array exactly (bitwise),
# so instead we call vary_layouts() twice
for pydest, cdest in zip(vary_layouts(orig), vary_layouts(orig)):
if have_k_argument:
for k in range(1, N):
check(pyfunc, cfunc, pydest, cdest, dict(k=k))
else:
check(pyfunc, cfunc, pydest, cdest, {})
def check_overlap_with_k(self, pyfunc, min_ndim):
self.check_overlap(pyfunc, min_ndim=min_ndim, have_k_argument=True)
def test_overlap1(self):
self.check_overlap_with_k(array_overlap1, min_ndim=1)
def test_overlap2(self):
self.check_overlap_with_k(array_overlap2, min_ndim=1)
def test_overlap3(self):
self.check_overlap_with_k(array_overlap3, min_ndim=2)
def test_overlap4(self):
self.check_overlap_with_k(array_overlap4, min_ndim=2)
def test_overlap5(self):
self.check_overlap_with_k(array_overlap5, min_ndim=1)
def test_overlap6(self):
self.check_overlap_with_k(array_overlap6, min_ndim=1)
def test_overlap11(self):
self.check_overlap(array_overlap11, min_ndim=1)
def test_overlap12(self):
self.check_overlap(array_overlap12, min_ndim=1)
def test_overlap13(self):
self.check_overlap(array_overlap13, min_ndim=2)
def test_overlap14(self):
self.check_overlap(array_overlap14, min_ndim=2)
def test_overlap15(self):
self.check_overlap(array_overlap15, min_ndim=1)
def test_overlap16(self):
self.check_overlap(array_overlap16, min_ndim=1)
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"numba.jit",
"numpy.arange"
] | [((3823, 3838), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3836, 3838), False, 'import unittest\n'), ((1959, 1977), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (1962, 1977), False, 'from numba import jit\n'), ((2113, 2136), 'numpy.arange', 'np.arange', (['(0)', '(N ** ndim)'], {}), '(0, N ** ndim)\n', (2122, 2136), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import collections
import csv
import io
import math
import pathlib
import re
import pandas as pd
class Barcode:
"""A TCGA barcode.
TCGA barcodes can be truncated at almost any segment depending on what they represent, for example, a particiant, a
sample or an aliquot; therefore, it is valid for parts to be missing.
"""
# Regular expression to match TCGA barcodes.
# regex = re.compile(r'''(?P<project>\w+)-
# (?P<tss>\w+)-
# (?P<participant>\w+)-
# (?P<sample>\d+)
# (?P<vial>[A-Z])?-
# (?P<portion>\d+)
# (?P<analyte>[A-Z])?-
# (?P<plate>\w{4})-
# (?P<center>\w+)''',
# re.VERBOSE)
# The above regex won't work if a truncated barcode is used. Maybe it would be better to manually pull the barcode
# apart.
# It would be better to raise an exception if a missing value is accessed rather than returning None.
regex = re.compile(r'''(?P<project>\w+)-
(?P<tss>\w+)-
(?P<participant>\w+)-
(?P<sample>\d+)''',
re.VERBOSE)
def __init__(self, barcode):
self.barcode = barcode
self.match = Barcode.regex.search(barcode)
if self.match:
self.groupdict = self.match.groupdict()
else:
raise ValueError(barcode)
@property
def project(self):
return self.groupdict['project']
@property
def tss(self):
return self.groupdict['tss']
@property
def participant(self):
return self.groupdict['participant']
@property
def sample(self):
"""Return the sample code.
Tumour types range from 01-09, normal types from 10-29 and control samples from 20-29.
"""
return self.groupdict['sample']
@property
def vial(self):
"""Return the vial from the barcode.
Sample/vial is encoded as e.g., 01A where 01 is the sample code and A is the vial. Even if there is a sample
code the vial does not have to be present.
"""
return self.groupdict['vial']
@property
def portion(self):
"""Return the portion.
Always in the range 01-99.
"""
return self.groupdict['portion']
@property
def analyte(self):
return self.groupdict['analyte']
@property
def plate(self):
return self.groupdict['plate']
@property
def center(self):
return self.groupdict['center']
@property
def sample_type(self, short=False):
# 'Code','Definition','Short Letter Code'
sample_codes = {'01': ('Primary solid Tumor', 'TP'),
'02': ('Recurrent Solid Tumor', 'TR'),
'03': ('Primary Blood Derived Cancer - Peripheral Blood', 'TB'),
'04': ('Recurrent Blood Derived Cancer - Bone Marrow', 'TRBM'),
'05': ('Additional - New Primary', 'TAP'),
'06': ('Metastatic', 'TM'),
'07': ('Additional Metastatic', 'TAM'),
'08': ('Human Tumor Original Cells', 'THOC'),
'09': ('Primary Blood Derived Cancer - Bone Marrow', 'TBM'),
'10': ('Blood Derived Normal', 'NB'),
'11': ('Solid Tissue Normal', 'NT'),
'12': ('Buccal Cell Normal', 'NBC'),
'13': ('EBV Immortalized Normal', 'NEBV'),
'14': ('Bone Marrow Normal', 'NBM'),
'20': ('Control Analyte', 'CELLC'),
'40': ('Recurrent Blood Derived Cancer - Peripheral Blood', 'TRB'),
'50': ('Cell Lines', 'CELL'),
'60': ('Primary Xenograft Tissue', 'XP'),
'61': ('Cell Line Derived Xenograft Tissue', 'XCL')}
if short:
return sample_codes[self.sample][1]
else:
return sample_codes[self.sample][0]
@property
def is_tumour(self):
sm = int(self.sample)
return sm >= 1 and sm <= 9
@property
def is_normal(self):
sm = int(self.sample)
return sm >= 10 and sm <= 19
@property
def is_control(self):
sm = int(self.sample)
return sm >= 20 and sm <= 29
@property
def sample_barcode(self):
return '-'.join([self.project, self.tss, self.participant, self.sample])
class Centromere:
@staticmethod
def region(chrom):
centromere_regions = {
'1': (121236957, 123476957), '2': (91689898, 94689898),
'3': (90587544, 93487544), '4': (49354874, 52354874),
'5': (46441398, 49441398), '6': (58938125, 61938125),
'7': (58058273, 61058273), '8': (43958052, 46958052),
'9': (47107499, 50107499), '10': (39244941, 41624941),
'11': (51450781, 54450781), '12': (34747961, 36142961),
'13': (16000000, 17868000), '14': (15070000, 18070000),
'15': (15260000, 18260000), '16': (35143302, 36943302),
'17': (22187133, 22287133), '18': (15400898, 16764896),
'19': (26923622, 29923622), '20': (26267569, 28033230),
'21': (10260000, 13260000), '22': (11330000, 14330000)
}
return centromere_regions[chrom]
class Segment:
def __init__(self, sample, chrom, start, end, num_probes, mean):
# coordinates should be 0-based
self.sample = sample
self.chrom = chrom
self.start = int(float(start))
self.end = int(float(end))
self.num_probes = int(float(num_probes)) # some firehose files have 1e+05 which will cause int to fail
self.mean = float(mean)
def __len__(self):
# return self.end - (self.start - 1)
return self.end - self.start
class SegmentFile:
@staticmethod
def parse(file_name):
with open(file_name, 'rt') as in_handle:
reader = csv.DictReader(in_handle, delimiter='\t')
for row in reader:
segment = Segment(row['Sample'], row['Chromosome'], row['Start'], row['End'],
row['Num_Probes'], row['Segment_Mean'])
if segment.chrom not in ['X', 'Y', '23', '24']:
yield segment
Survival = collections.namedtuple('Survival', ['case_id', 'os_status', 'os_months', 'dfs_status', 'dfs_months'])
class SurvivalFile:
@staticmethod
def parse(file_name):
with open(file_name) as handle:
reader = csv.DictReader(handle, delimiter='\t')
for row in reader:
try:
os_months = float(row['OS_MONTHS'])
except ValueError:
os_months = math.nan
try:
dfs_months = float(row['DFS_MONTHS'])
except ValueError:
dfs_months = math.nan
yield Survival(row['CASE_ID'], row['OS_STATUS'], os_months, row['DFS_STATUS'], dfs_months)
class Chromosomes:
# in_order = [str(i) for i in range(1, 23)] + ['X', 'Y']
in_order = [str(i) for i in range(1, 23)]
def summarise_sample(segments):
seg_ns = {}
seg_lens = {}
seg_means = {}
arm_lengths = {}
# Initialise all data structures.
for chrom in Chromosomes.in_order:
for arm in ['p', 'q']:
arm_lengths[(chrom, arm)] = 0
for direction in ['amp', 'del']:
seg_ns[(chrom, arm, direction)] = 0
seg_lens[(chrom, arm, direction)] = 0
seg_means[(chrom, arm, direction)] = 0
for segment in segments:
if segment.chrom in ['X', 'Y']:
continue
centromere_start, centromere_end = Centromere.region(segment.chrom)
if segment.end < centromere_start:
arm = 'p'
arm_lengths[(segment.chrom, arm)] += len(segment)
elif segment.start > centromere_end:
arm = 'q'
arm_lengths[(segment.chrom, arm)] += len(segment)
else:
# Segment intersects centromere, skip
continue
if segment.mean > 0.2:
direction = 'amp'
elif segment.mean < -0.2:
direction = 'del'
else:
# This segment hasn't reached the required threshold, skip.
continue
key = (segment.chrom, arm, direction)
seg_ns[key] += 1
seg_lens[key] += len(segment)
seg_means[key] += segment.mean
return (seg_ns, seg_lens, seg_means, arm_lengths)
def header():
"""Return the header row for the output."""
yield 'Tumour'
yield 'Sample'
for chrom in Chromosomes.in_order:
for end in ['p amp', 'p del', 'q amp', 'q del']:
for middle in ['Num_Segments', 'Segments_Length', 'Frac_Length', 'Segments_Mean']:
yield '{} {} {}'.format(chrom, middle, end)
for column in ['OS_STATUS', 'OS_MONTHS', 'DFS_STATUS', 'DFS_MONTHS']:
yield column
def format_output(tumour, sample_id, seg_ns, seg_lens, seg_means, arm_lengths, survival_data):
row = [tumour, sample_id]
for chrom in Chromosomes.in_order:
for arm, direction in [('p', 'amp'), ('p', 'del'), ('q', 'amp'), ('q', 'del')]:
key = (chrom, arm, direction)
if seg_lens[key] == 0 and arm_lengths[(chrom, arm)] == 0:
frac = 0
elif arm_lengths[(chrom, arm)] > 0:
frac = seg_lens[key] / arm_lengths[(chrom, arm)]
else:
raise ValueError('have segment length without arm length, {}{} {}'.format(
chrom, arm, direction))
row.extend([seg_ns[key],
seg_lens[key],
frac,
seg_means[key]])
row.extend([survival_data.os_status,
survival_data.os_months,
survival_data.dfs_status,
survival_data.dfs_months])
return row
def process_single_tumour(tumour, seg_files, survival_file):
survival_dict = {}
for data in SurvivalFile.parse(survival_file):
survival_dict[data.case_id] = data
segments = {}
for seg_file in seg_files:
for segment in SegmentFile.parse(seg_file):
segments.setdefault(segment.sample, []).append(segment)
out_handle = io.StringIO()
writer = csv.writer(out_handle)
writer.writerow(list(header()))
for sample_id, sample_segments in segments.items():
barcode = Barcode(sample_id)
if not barcode.is_tumour:
# Skip normals
continue
try:
survival_data = survival_dict[barcode.sample_barcode]
except KeyError:
survival_data = Survival(barcode.sample_barcode, 'NA', 'NA', 'NA', 'NA')
(seg_ns, seg_lens, seg_means, arm_lengths) = summarise_sample(sample_segments)
writer.writerow(format_output(tumour, sample_id, seg_ns, seg_lens, seg_means, arm_lengths, survival_data))
out_handle.seek(0)
dat = pd.read_csv(out_handle)
return dat
def find_segment_files(tumour):
result = []
for path in pathlib.Path('cnv_data').glob('*.seg.txt'):
if path.name.startswith(tumour):
result.append(str(path))
if result == []:
raise ValueError("can not find segment file for {}".format(tumour))
else:
return result
def find_survival_file(tumour):
for path in pathlib.Path('survival_data').glob('*.txt'):
if path.name.startswith(tumour):
return str(path)
raise ValueError("can not find survival file for {}".format(tumour))
def process_tumours(output_file):
cohorts = ['BLCA', 'BRCA', 'CESC', 'ESCA', 'LIHC', 'LUAD', 'STAD', 'OV',
'PRAD', 'COADREAD', 'ACC', 'CHOL', 'HNSC', 'KIRC', 'KIRP', 'LUSC',
'PAAD', 'SARC', 'SKCM', 'TGCT', 'THYM', 'THCA', 'UCS', 'UCEC',
'UVM', 'LGG', 'GBM', 'MESO', 'PCPG', 'LAML', 'DLBC']
with pd.ExcelWriter(output_file) as writer:
for tumour in cohorts:
seg_files = find_segment_files(tumour)
survival_file = find_survival_file(tumour)
dat = process_single_tumour(tumour, seg_files, survival_file)
dat.to_excel(writer, sheet_name=tumour, index=False)
def main():
process_tumours('TCGA_CNV_Analysis.xlsx')
if __name__ == "__main__":
main()
| [
"collections.namedtuple",
"pandas.ExcelWriter",
"csv.DictReader",
"pandas.read_csv",
"re.compile",
"pathlib.Path",
"csv.writer",
"io.StringIO"
] | [((6621, 6726), 'collections.namedtuple', 'collections.namedtuple', (['"""Survival"""', "['case_id', 'os_status', 'os_months', 'dfs_status', 'dfs_months']"], {}), "('Survival', ['case_id', 'os_status', 'os_months',\n 'dfs_status', 'dfs_months'])\n", (6643, 6726), False, 'import collections\n'), ((1165, 1359), 're.compile', 're.compile', (['"""(?P<project>\\\\w+)-\n (?P<tss>\\\\w+)-\n (?P<participant>\\\\w+)-\n (?P<sample>\\\\d+)"""', 're.VERBOSE'], {}), '(\n """(?P<project>\\\\w+)-\n (?P<tss>\\\\w+)-\n (?P<participant>\\\\w+)-\n (?P<sample>\\\\d+)"""\n , re.VERBOSE)\n', (1175, 1359), False, 'import re\n'), ((10684, 10697), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (10695, 10697), False, 'import io\n'), ((10711, 10733), 'csv.writer', 'csv.writer', (['out_handle'], {}), '(out_handle)\n', (10721, 10733), False, 'import csv\n'), ((11373, 11396), 'pandas.read_csv', 'pd.read_csv', (['out_handle'], {}), '(out_handle)\n', (11384, 11396), True, 'import pandas as pd\n'), ((12318, 12345), 'pandas.ExcelWriter', 'pd.ExcelWriter', (['output_file'], {}), '(output_file)\n', (12332, 12345), True, 'import pandas as pd\n'), ((6269, 6310), 'csv.DictReader', 'csv.DictReader', (['in_handle'], {'delimiter': '"""\t"""'}), "(in_handle, delimiter='\\t')\n", (6283, 6310), False, 'import csv\n'), ((6851, 6889), 'csv.DictReader', 'csv.DictReader', (['handle'], {'delimiter': '"""\t"""'}), "(handle, delimiter='\\t')\n", (6865, 6889), False, 'import csv\n'), ((11478, 11502), 'pathlib.Path', 'pathlib.Path', (['"""cnv_data"""'], {}), "('cnv_data')\n", (11490, 11502), False, 'import pathlib\n'), ((11779, 11808), 'pathlib.Path', 'pathlib.Path', (['"""survival_data"""'], {}), "('survival_data')\n", (11791, 11808), False, 'import pathlib\n')] |
from datetime import timedelta, datetime
from typing import Optional
from fastapi import HTTPException, Depends
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from passlib.context import CryptContext
from pydantic import BaseModel
from db import database as adb
from usermanagement.models import users
from usermanagement.schema import UserCreate, User
from starlette import status
SECRET_KEY = "<KEY>"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: Optional[str] = None
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password, hashed_password) -> str:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password) -> str:
return pwd_context.hash(password)
async def get_user(username: Optional[str]) -> UserCreate:
query = users.select()
user_list = await adb.fetch_all(query)
for user in user_list:
if user["username"] == username:
return UserCreate(**user)
return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
"""authenticating user"""
async def authenticate_user(username: str, password: str):
user = await get_user(username)
if not user:
return False
if not verify_password(password, user.password):
return False
return user
"""code to create the access token"""
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
to_encode = data.copy()
if expires_delta:
expire = datetime.now() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
"""getting the current user details"""
async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
token_data = TokenData(username=username)
except JWTError:
raise credentials_exception
user = await get_user(username=token_data.username)
if not user:
raise credentials_exception
return user
"""Checking users if they are active or not"""
async def get_current_active_user(
current_user: User = Depends(get_current_user)
) -> User:
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
def testFunc():
return "Hello"
| [
"fastapi.HTTPException",
"fastapi.security.OAuth2PasswordBearer",
"datetime.datetime.utcnow",
"jose.jwt.decode",
"passlib.context.CryptContext",
"db.database.fetch_all",
"jose.jwt.encode",
"datetime.datetime.now",
"usermanagement.schema.UserCreate",
"datetime.timedelta",
"fastapi.Depends",
"us... | [((510, 548), 'fastapi.security.OAuth2PasswordBearer', 'OAuth2PasswordBearer', ([], {'tokenUrl': '"""token"""'}), "(tokenUrl='token')\n", (530, 548), False, 'from fastapi.security import OAuth2PasswordBearer\n'), ((698, 749), 'passlib.context.CryptContext', 'CryptContext', ([], {'schemes': "['bcrypt']", 'deprecated': '"""auto"""'}), "(schemes=['bcrypt'], deprecated='auto')\n", (710, 749), False, 'from passlib.context import CryptContext\n'), ((1029, 1043), 'usermanagement.models.users.select', 'users.select', ([], {}), '()\n', (1041, 1043), False, 'from usermanagement.models import users\n'), ((1204, 1281), 'fastapi.HTTPException', 'HTTPException', ([], {'status_code': 'status.HTTP_404_NOT_FOUND', 'detail': '"""User not found"""'}), "(status_code=status.HTTP_404_NOT_FOUND, detail='User not found')\n", (1217, 1281), False, 'from fastapi import HTTPException, Depends\n'), ((1887, 1941), 'jose.jwt.encode', 'jwt.encode', (['to_encode', 'SECRET_KEY'], {'algorithm': 'ALGORITHM'}), '(to_encode, SECRET_KEY, algorithm=ALGORITHM)\n', (1897, 1941), False, 'from jose import jwt, JWTError\n'), ((2048, 2070), 'fastapi.Depends', 'Depends', (['oauth2_scheme'], {}), '(oauth2_scheme)\n', (2055, 2070), False, 'from fastapi import HTTPException, Depends\n'), ((2109, 2250), 'fastapi.HTTPException', 'HTTPException', ([], {'status_code': 'status.HTTP_401_UNAUTHORIZED', 'detail': '"""Could not validate credentials"""', 'headers': "{'WWW-Authenticate': 'Bearer'}"}), "(status_code=status.HTTP_401_UNAUTHORIZED, detail=\n 'Could not validate credentials', headers={'WWW-Authenticate': 'Bearer'})\n", (2122, 2250), False, 'from fastapi import HTTPException, Depends\n'), ((2814, 2839), 'fastapi.Depends', 'Depends', (['get_current_user'], {}), '(get_current_user)\n', (2821, 2839), False, 'from fastapi import HTTPException, Depends\n'), ((1066, 1086), 'db.database.fetch_all', 'adb.fetch_all', (['query'], {}), '(query)\n', (1079, 1086), True, 'from db import database as adb\n'), ((2305, 2358), 'jose.jwt.decode', 'jwt.decode', (['token', 'SECRET_KEY'], {'algorithms': '[ALGORITHM]'}), '(token, SECRET_KEY, algorithms=[ALGORITHM])\n', (2315, 2358), False, 'from jose import jwt, JWTError\n'), ((2895, 2949), 'fastapi.HTTPException', 'HTTPException', ([], {'status_code': '(400)', 'detail': '"""Inactive user"""'}), "(status_code=400, detail='Inactive user')\n", (2908, 2949), False, 'from fastapi import HTTPException, Depends\n'), ((1174, 1192), 'usermanagement.schema.UserCreate', 'UserCreate', ([], {}), '(**user)\n', (1184, 1192), False, 'from usermanagement.schema import UserCreate, User\n'), ((1731, 1745), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1743, 1745), False, 'from datetime import timedelta, datetime\n'), ((1789, 1806), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (1804, 1806), False, 'from datetime import timedelta, datetime\n'), ((1809, 1830), 'datetime.timedelta', 'timedelta', ([], {'minutes': '(15)'}), '(minutes=15)\n', (1818, 1830), False, 'from datetime import timedelta, datetime\n')] |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django.test import TestCase
from ralph.discovery.tests.util import MockSSH
from ralph.scan.plugins.proxmox_2_3 import (
_get_node_sn,
_get_node_mac_address,
_get_device_info,
_get_vm_info,
)
from ralph.scan.tests.plugins.samples.proxmox_2_3 import (
NODE_SN,
NODE_MAC,
DEVICE_INFO_SAMPLE,
VM_INFO_SAMPLE,
)
class Proxmox23PluginTest(TestCase):
def test_get_node_sn(self):
ssh = MockSSH([("sudo /usr/sbin/dmidecode -t 1 | grep -i serial", NODE_SN)])
node_sn = _get_node_sn(ssh)
node_sn_expected = "XYZ1234567890"
self.assertEqual(node_sn, node_sn_expected)
def test_get_node_mac_address(self):
ssh = MockSSH([("/sbin/ifconfig eth0 | head -n 1", NODE_MAC)])
node_mac = _get_node_mac_address(ssh)
node_mac_expected = "202020202020"
self.assertEqual(node_mac, node_mac_expected)
def test_get_device_info(self):
ssh = MockSSH([
("sudo /usr/bin/pvesh get /nodes/node123/status", DEVICE_INFO_SAMPLE)
])
node_name, session, base_url = 'node123', None, None
device_info = _get_device_info(node_name, session, ssh, base_url)
device_info_expected = {
u'installed_software': [{
u'model_name': u'Proxmox',
u'path': u'proxmox',
}],
u'model_name': u'Proxmox',
u'processors': [{
u'cores': 16,
u'family': u'Intel(R) Xeon(R) CPU F7-666 0 @ 2.00GHz',
u'label': u'CPU 1',
u'speed': 2000
}, {
u'cores': 16,
u'family': u'Intel(R) Xeon(R) CPU F7-666 0 @ 2.00GHz',
u'label': u'CPU 2',
u'speed': 2000
}]
}
self.assertEqual(device_info, device_info_expected)
def test_vm_info(self):
ssh = MockSSH([
("sudo /usr/bin/pvesh get /nodes/node123/qemu/vm123/config", VM_INFO_SAMPLE)
])
node_name, vmid, session, base_url = 'node123', 'vm123', None, None
vm_info = _get_vm_info(node_name, vmid, session, ssh, base_url)
vm_info_expexted = {
u'disks': [{
u'family': u'Proxmox Virtual Disk',
u'label': u'vm-0123456-disk-1',
u'model_name': u'Proxmox Virtual Disk 8192MiB',
u'size': 8192
}],
u'hostname': u'test_node.local',
u'mac_addresses': [u'101010101010'],
u'memory': [{
u'index': 0,
u'label': u'Virtual DIMM 0',
u'size': 1024
}],
u'model_name': u'Proxmox qemu kvm',
u'processors': [{
u'cores': 1,
u'family': u'QEMU Virtual',
u'index': 1,
u'label': u'CPU 1',
u'model_name': u'QEMU Virtual CPU'
}],
u'type': u'virtual server'
}
self.assertEqual(vm_info, vm_info_expexted)
| [
"ralph.scan.plugins.proxmox_2_3._get_node_sn",
"ralph.scan.plugins.proxmox_2_3._get_vm_info",
"ralph.discovery.tests.util.MockSSH",
"ralph.scan.plugins.proxmox_2_3._get_node_mac_address",
"ralph.scan.plugins.proxmox_2_3._get_device_info"
] | [((606, 676), 'ralph.discovery.tests.util.MockSSH', 'MockSSH', (["[('sudo /usr/sbin/dmidecode -t 1 | grep -i serial', NODE_SN)]"], {}), "([('sudo /usr/sbin/dmidecode -t 1 | grep -i serial', NODE_SN)])\n", (613, 676), False, 'from ralph.discovery.tests.util import MockSSH\n'), ((695, 712), 'ralph.scan.plugins.proxmox_2_3._get_node_sn', '_get_node_sn', (['ssh'], {}), '(ssh)\n', (707, 712), False, 'from ralph.scan.plugins.proxmox_2_3 import _get_node_sn, _get_node_mac_address, _get_device_info, _get_vm_info\n'), ((864, 920), 'ralph.discovery.tests.util.MockSSH', 'MockSSH', (["[('/sbin/ifconfig eth0 | head -n 1', NODE_MAC)]"], {}), "([('/sbin/ifconfig eth0 | head -n 1', NODE_MAC)])\n", (871, 920), False, 'from ralph.discovery.tests.util import MockSSH\n'), ((940, 966), 'ralph.scan.plugins.proxmox_2_3._get_node_mac_address', '_get_node_mac_address', (['ssh'], {}), '(ssh)\n', (961, 966), False, 'from ralph.scan.plugins.proxmox_2_3 import _get_node_sn, _get_node_mac_address, _get_device_info, _get_vm_info\n'), ((1115, 1200), 'ralph.discovery.tests.util.MockSSH', 'MockSSH', (["[('sudo /usr/bin/pvesh get /nodes/node123/status', DEVICE_INFO_SAMPLE)]"], {}), "([('sudo /usr/bin/pvesh get /nodes/node123/status', DEVICE_INFO_SAMPLE)]\n )\n", (1122, 1200), False, 'from ralph.discovery.tests.util import MockSSH\n'), ((1301, 1352), 'ralph.scan.plugins.proxmox_2_3._get_device_info', '_get_device_info', (['node_name', 'session', 'ssh', 'base_url'], {}), '(node_name, session, ssh, base_url)\n', (1317, 1352), False, 'from ralph.scan.plugins.proxmox_2_3 import _get_node_sn, _get_node_mac_address, _get_device_info, _get_vm_info\n'), ((2070, 2161), 'ralph.discovery.tests.util.MockSSH', 'MockSSH', (["[('sudo /usr/bin/pvesh get /nodes/node123/qemu/vm123/config', VM_INFO_SAMPLE)]"], {}), "([('sudo /usr/bin/pvesh get /nodes/node123/qemu/vm123/config',\n VM_INFO_SAMPLE)])\n", (2077, 2161), False, 'from ralph.discovery.tests.util import MockSSH\n'), ((2274, 2327), 'ralph.scan.plugins.proxmox_2_3._get_vm_info', '_get_vm_info', (['node_name', 'vmid', 'session', 'ssh', 'base_url'], {}), '(node_name, vmid, session, ssh, base_url)\n', (2286, 2327), False, 'from ralph.scan.plugins.proxmox_2_3 import _get_node_sn, _get_node_mac_address, _get_device_info, _get_vm_info\n')] |
# pylint: disable=invalid-name
import sys
import pytest
from unittest.mock import MagicMock
sys.path.append('plugins/sdm')
sys.path.append('e2e')
from test_common import create_config, DummyResource, get_dummy_person, DummyRole, ErrBotExtraTestSettings
from lib import ShowResourcesHelper
pytest_plugins = ["errbot.backends.test"]
show_resources_command = 'show available resources'
show_resources_alias = 'sares'
access_to_resource_command = 'access to'
access_to_resource_alias = 'acres'
assign_role_command = 'access to role'
resource_id = 1
resource_name = "myresource"
role_name = "myrole"
account_id = 1
account_name = "<EMAIL>"
access_request_id = "12ab"
class Test_match_alias(ErrBotExtraTestSettings):
@pytest.fixture
def mocked_testbot(self, testbot):
config = create_config()
testbot.bot.plugin_manager.plugins['AccessBot'].get_admin_ids = MagicMock(
return_value = [get_dummy_person(account_name, is_deleted=False)]
)
return inject_config(testbot, config)
@pytest.fixture
def mocked_sdm_service(self, mocked_testbot):
accessbot = mocked_testbot.bot.plugin_manager.plugins['AccessBot']
return accessbot.get_sdm_service.return_value
def test_full_command_without_argument(self, mocked_testbot, mocked_sdm_service):
mocked_testbot.push_message(show_resources_command)
message = mocked_testbot.pop_message()
assert "Aaa (type: DummyResource)" in message
assert "Bbb (type: DummyResource)" in message
def test_command_alias_without_argument(self, mocked_testbot, mocked_sdm_service):
mocked_testbot.push_message(show_resources_alias)
message = mocked_testbot.pop_message()
assert "Aaa (type: DummyResource)" in message
assert "Bbb (type: DummyResource)" in message
def test_full_command_with_argument(self, mocked_testbot, mocked_sdm_service):
mocked_testbot.push_message(f'{access_to_resource_command} {resource_name}')
assert "valid request" in mocked_testbot.pop_message()
assert "access request" in mocked_testbot.pop_message()
def test_command_alias_with_argument(self, mocked_testbot, mocked_sdm_service):
mocked_testbot.push_message(f'{access_to_resource_alias} {resource_name}')
assert "valid request" in mocked_testbot.pop_message()
assert "access request" in mocked_testbot.pop_message()
def test_command_without_alias(self, mocked_testbot, mocked_sdm_service):
mocked_testbot.push_message(f'{assign_role_command} {role_name}')
assert "valid request" in mocked_testbot.pop_message()
assert "assign request" in mocked_testbot.pop_message()
# pylint: disable=dangerous-default-value
def inject_config(testbot, config):
accessbot = testbot.bot.plugin_manager.plugins['AccessBot']
accessbot.config = config
# The default implementation is not compatible with the backend identifier.
# Refer to: https://errbot.readthedocs.io/en/4.1/errbot.backends.test.html#errbot.backends.test.TestPerson
accessbot.bot_config.BOT_COMMANDS_ALIASES = {
'show_resources': show_resources_alias,
'access_resource': access_to_resource_alias,
'assign_role': None
}
accessbot.get_admins = MagicMock(return_value = ["gbin@localhost"])
accessbot.get_api_access_key = MagicMock(return_value = "api-access_key")
accessbot.get_api_secret_key = MagicMock(return_value = "<KEY>==") # valid base64 string
accessbot.get_sdm_service = MagicMock(return_value = create_sdm_service_mock())
accessbot.get_show_resources_helper = MagicMock(return_value = ShowResourcesHelper(accessbot))
return testbot
def create_sdm_service_mock():
mock = MagicMock()
mock.get_account_by_email = MagicMock(return_value = create_account_mock(account_tags={}))
mock.account_grant_exists = MagicMock(return_value = False)
mock.get_all_resources = MagicMock(return_value = [DummyResource("Aaa", {}), DummyResource("Bbb", {})])
mock.get_all_roles = MagicMock(return_value = [DummyRole(role_name, {})])
return mock
def create_resource_mock(tags):
mock = MagicMock()
mock.id = resource_id
mock.name = resource_name
mock.tags = tags
return mock
def create_account_mock(account_email = account_name, account_tags={}):
mock = MagicMock()
mock.id = account_id
mock.name = account_name
mock.email = account_email
mock.tags = account_tags
return mock
| [
"test_common.create_config",
"unittest.mock.MagicMock",
"test_common.DummyResource",
"test_common.DummyRole",
"lib.ShowResourcesHelper",
"test_common.get_dummy_person",
"sys.path.append"
] | [((93, 123), 'sys.path.append', 'sys.path.append', (['"""plugins/sdm"""'], {}), "('plugins/sdm')\n", (108, 123), False, 'import sys\n'), ((124, 146), 'sys.path.append', 'sys.path.append', (['"""e2e"""'], {}), "('e2e')\n", (139, 146), False, 'import sys\n'), ((3276, 3318), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': "['gbin@localhost']"}), "(return_value=['gbin@localhost'])\n", (3285, 3318), False, 'from unittest.mock import MagicMock\n'), ((3356, 3396), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': '"""api-access_key"""'}), "(return_value='api-access_key')\n", (3365, 3396), False, 'from unittest.mock import MagicMock\n'), ((3434, 3467), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': '"""<KEY>=="""'}), "(return_value='<KEY>==')\n", (3443, 3467), False, 'from unittest.mock import MagicMock\n'), ((3738, 3749), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (3747, 3749), False, 'from unittest.mock import MagicMock\n'), ((3877, 3906), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': '(False)'}), '(return_value=False)\n', (3886, 3906), False, 'from unittest.mock import MagicMock\n'), ((4155, 4166), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (4164, 4166), False, 'from unittest.mock import MagicMock\n'), ((4344, 4355), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (4353, 4355), False, 'from unittest.mock import MagicMock\n'), ((792, 807), 'test_common.create_config', 'create_config', ([], {}), '()\n', (805, 807), False, 'from test_common import create_config, DummyResource, get_dummy_person, DummyRole, ErrBotExtraTestSettings\n'), ((3644, 3674), 'lib.ShowResourcesHelper', 'ShowResourcesHelper', (['accessbot'], {}), '(accessbot)\n', (3663, 3674), False, 'from lib import ShowResourcesHelper\n'), ((3964, 3988), 'test_common.DummyResource', 'DummyResource', (['"""Aaa"""', '{}'], {}), "('Aaa', {})\n", (3977, 3988), False, 'from test_common import create_config, DummyResource, get_dummy_person, DummyRole, ErrBotExtraTestSettings\n'), ((3990, 4014), 'test_common.DummyResource', 'DummyResource', (['"""Bbb"""', '{}'], {}), "('Bbb', {})\n", (4003, 4014), False, 'from test_common import create_config, DummyResource, get_dummy_person, DummyRole, ErrBotExtraTestSettings\n'), ((4068, 4092), 'test_common.DummyRole', 'DummyRole', (['role_name', '{}'], {}), '(role_name, {})\n', (4077, 4092), False, 'from test_common import create_config, DummyResource, get_dummy_person, DummyRole, ErrBotExtraTestSettings\n'), ((919, 967), 'test_common.get_dummy_person', 'get_dummy_person', (['account_name'], {'is_deleted': '(False)'}), '(account_name, is_deleted=False)\n', (935, 967), False, 'from test_common import create_config, DummyResource, get_dummy_person, DummyRole, ErrBotExtraTestSettings\n')] |
import os
from conjureup import controllers, utils
from conjureup.app_config import app
from conjureup.download import EndpointType, download_local
from conjureup.models.addon import AddonModel
from conjureup.models.step import StepModel
from conjureup.ui.views.spellpicker import SpellPickerView
class SpellPickerController:
def finish(self, spellname):
if spellname != app.config.get('spell'):
utils.set_terminal_title("conjure-up {}".format(spellname))
utils.set_chosen_spell(spellname,
os.path.join(app.conjurefile['cache-dir'],
spellname))
download_local(os.path.join(app.config['spells-dir'],
spellname),
app.config['spell-dir'])
utils.set_spell_metadata()
StepModel.load_spell_steps()
AddonModel.load_spell_addons()
controllers.setup_metadata_controller()
return controllers.use('addons').render()
def render(self):
spells = []
if app.endpoint_type is None:
spells += utils.find_spells()
elif app.endpoint_type == EndpointType.LOCAL_SEARCH:
spells = utils.find_spells_matching(app.conjurefile['spell'])
else:
raise Exception("Unexpected endpoint type {}".format(
app.endpoint_type))
# add subdir of spells-dir to spell dict for bundle readme view:
for category, spell in spells:
spell['spell-dir'] = os.path.join(app.config['spells-dir'],
spell['key'])
def spellcatsorter(t):
cat = t[0]
name = t[1]['name']
if cat == '_unassigned_spells':
return ('z', name)
return (cat, name)
view = SpellPickerView(app,
sorted(spells,
key=spellcatsorter),
self.finish)
view.show()
_controller_class = SpellPickerController
| [
"conjureup.models.addon.AddonModel.load_spell_addons",
"conjureup.utils.find_spells_matching",
"os.path.join",
"conjureup.controllers.setup_metadata_controller",
"conjureup.utils.find_spells",
"conjureup.app_config.app.config.get",
"conjureup.utils.set_spell_metadata",
"conjureup.models.step.StepModel... | [((386, 409), 'conjureup.app_config.app.config.get', 'app.config.get', (['"""spell"""'], {}), "('spell')\n", (400, 409), False, 'from conjureup.app_config import app\n'), ((849, 875), 'conjureup.utils.set_spell_metadata', 'utils.set_spell_metadata', ([], {}), '()\n', (873, 875), False, 'from conjureup import controllers, utils\n'), ((888, 916), 'conjureup.models.step.StepModel.load_spell_steps', 'StepModel.load_spell_steps', ([], {}), '()\n', (914, 916), False, 'from conjureup.models.step import StepModel\n'), ((929, 959), 'conjureup.models.addon.AddonModel.load_spell_addons', 'AddonModel.load_spell_addons', ([], {}), '()\n', (957, 959), False, 'from conjureup.models.addon import AddonModel\n'), ((972, 1011), 'conjureup.controllers.setup_metadata_controller', 'controllers.setup_metadata_controller', ([], {}), '()\n', (1009, 1011), False, 'from conjureup import controllers, utils\n'), ((1165, 1184), 'conjureup.utils.find_spells', 'utils.find_spells', ([], {}), '()\n', (1182, 1184), False, 'from conjureup import controllers, utils\n'), ((1582, 1634), 'os.path.join', 'os.path.join', (["app.config['spells-dir']", "spell['key']"], {}), "(app.config['spells-dir'], spell['key'])\n", (1594, 1634), False, 'import os\n'), ((564, 617), 'os.path.join', 'os.path.join', (["app.conjurefile['cache-dir']", 'spellname'], {}), "(app.conjurefile['cache-dir'], spellname)\n", (576, 617), False, 'import os\n'), ((694, 743), 'os.path.join', 'os.path.join', (["app.config['spells-dir']", 'spellname'], {}), "(app.config['spells-dir'], spellname)\n", (706, 743), False, 'import os\n'), ((1027, 1052), 'conjureup.controllers.use', 'controllers.use', (['"""addons"""'], {}), "('addons')\n", (1042, 1052), False, 'from conjureup import controllers, utils\n'), ((1267, 1319), 'conjureup.utils.find_spells_matching', 'utils.find_spells_matching', (["app.conjurefile['spell']"], {}), "(app.conjurefile['spell'])\n", (1293, 1319), False, 'from conjureup import controllers, utils\n')] |
import pandas as pd
import numpy as np
from copy import deepcopy
import warnings
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import KFold, StratifiedKFold
from sklearn.externals.joblib import Parallel, delayed
from gravity_learn.utils import (force_array,
check_cv,
fit_model,
check_is_fitted)
__all__ = ['EnsemblerClassifier',
'QuickStackClassifier',
'FullStackClassifier']
class EnsemblerClassifier(BaseEstimator, TransformerMixin):
# TODO: require df? how to pass Yfactory in
"""
This is a class to ensemble a set of given base models. The assumption
is that those models are tuned (hyperparameters chosen). It works as
follows.
It accepts a dictionary of base models, the ensembler to combine them,
a number of folds (to be used in the cross validation strategy) and
a random state (to be used in the cross val strategy)
The fit method:
The ensemblers iterates through the base models, doing two things:
- determining out of sample predictions (so n_folds fit-predict
combinations). This is used for fitting the ensembler next.
- fit the base model to the full data, which is used for the
ensemblers predict method
Notice this implies we have n_folds + 1 fits for each base model.
With these out of sample predictions, it determines the parameters
of the ensemblers.
The predict method:
Determines the predictions of each of the base models and then
combines them with the fitted ensembler.
"""
def __init__(self, base_models, ensembler_est, n_folds, random_state=0):
"""
Parameters
----------
base_models : a dictionary of model name/model pairs
ensembler_est : an ensembler to combine the outputs of the base
model
n_folds : the number of folds to use when estimating the parameters
of the ensemblers. Note: Ideally, n_folds should be high, because
it makes the size of the base model fit for predictions and the
base model fit for ensembler calibration more similar.
random_state : the random state to use in the cross validaiton
strategy
"""
self.base_models = base_models
self.ensembler_est = ensembler_est
self.n_folds = n_folds
self.random_state = random_state
self.fitted_base_models = {}
self.model_order = []
warnings.warn('EnsemblerClassifier is deprecated, '
'please use FullStackClassifier instead',
DeprecationWarning)
def fit(self, X, y):
cv = StratifiedKFold(
n_splits=self.n_folds,
shuffle=True,
random_state=self.random_state
)
base_predictions = {}
for name, model in self.base_models.items():
# This is for determining the ensembler parameters
base_predictions[name] = cross_val_predict(
model, X, y, cv=cv, method='predict_proba'
)[:, 1]
# This for the ensembler.predict method
self.fitted_base_models[name] = model.fit(X, y)
self.model_order.append(name)
base_predictions = pd.DataFrame(
base_predictions,
index=X.index
)[self.model_order]
self.ensembler_est.fit(base_predictions, y)
return self
def predict_proba(self, X):
base_predictions = {}
for name, model in self.fitted_base_models.items():
base_predictions[name] = model.predict_proba(X)[:, 1]
base_predictions = pd.DataFrame(
base_predictions,
index=X.index
)[self.model_order]
return self.ensembler_est.predict_proba(base_predictions)
class QuickStackClassifier(BaseEstimator):
"""
This class has a similar stacking structure but also is scalable,
which means, it's objective to save computing run time on training
in-sample-fold and outputing out-of-fold predictions for fitting ensembler
Instead of doing K-fold training for each base model, it does only one-fold
To have a good performance, it requires ensembler to be a simple model with
only a few parameters to tune
Parameters
----------
base_models : list of (string, base_model) tuples. The first
half of each tuple is the group name of the pipeline.
ensembler : an ensembler to combine the outputs of the base models
proba : bool, if True, model will implement predict_proba when it
gets called
full_train : bool, if True, its base models are trained with 100% data
again and they are used for generating probas for new data
Default is True
cv : int, cross-validation generator or an iterable, optional
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross validation,
- integer, to specify the number of folds in a `(Stratified)KFold`,
- An object to be used as a cross-validation generator.
- An iterable yielding train, test splits.
n_jobs : integer, optional
The number of CPUs to use to do the computation. -1 means
'all CPUs'.
verbose : integer, optional
The verbosity level.
"""
def __init__(self, base_models, ensembler, proba=True,
full_train=True, cv=None, n_jobs=1, verbose=0):
self.base_models = list(base_models)
self.ensembler = ensembler
self.proba = proba
self.full_train = full_train
self.cv = cv
self.n_jobs = n_jobs
self.verbose = verbose
if self.cv is None:
self.cv = KFold(n_splits=3, shuffle=True)
warnings.warn('QuickStackClassifier is deprecated, '
'please use FullStackClassifier instead',
DeprecationWarning)
def get_params(self, deep=True):
return self.ensembler.get_params(deep=deep)
def set_params(self, **params):
return self.ensembler.set_params(**params)
def _fit(self, X, y, *args, **kwargs):
"""
private method to train n base models for last fold of cv
"""
# get list of folds of indices
self.last_fold = list(check_cv(self.cv).split(X, y))[-1]
self.in_fold = self.last_fold[0]
self.out_of_fold = self.last_fold[-1]
# Paralellization
parallel = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)
if isinstance(X, pd.DataFrame):
if not isinstance(y, (pd.Series, pd.DataFrame)):
y = pd.DataFrame(y)
self.fitted_models = parallel(delayed(fit_model)(
model=deepcopy(model),
X=X.iloc[self.in_fold],
y=y.iloc[self.in_fold],
*args,
**kwargs
) for (_, model) in self.base_models
)
else: # X is not a dataframe
self.fitted_models = parallel(delayed(fit_model)(
model=deepcopy(model),
X=X[self.in_fold],
y=force_array(y)[self.in_fold],
*args,
**kwargs
) for (_, model) in self.base_models
)
# train model with full 100% data
if self.full_train:
self.full_fitted_models = parallel(delayed(fit_model)(
model=deepcopy(model),
X=X,
y=y,
*args,
**kwargs
) for (_, model) in self.base_models
)
def fit(self, X, y, *args, **kwargs):
"""
fit method is the method for fitting the ensembler and the trainning
data is out-of-fold predictions from base_models
"""
# call _fit
self._fit(X, y, *args, **kwargs)
# generate out-of-sample predictions and reserve same order!!
proba_dfs = []
if isinstance(X, pd.DataFrame):
for i, model in enumerate(self.fitted_models):
df_proba = pd.DataFrame(
{'proba_{}'.format(i): model.predict_proba(X.iloc[self.out_of_fold])[:, 1]}, # noqa
index=self.out_of_fold
)
proba_dfs.append(df_proba)
else: # X is not a dataframe
for i, model in enumerate(self.fitted_models):
df_proba = pd.DataFrame(
{'proba_{}'.format(i): model.predict_proba(X[self.out_of_fold])[:, 1]}, # noqa
index=self.out_of_fold
)
proba_dfs.append(df_proba)
# horizontal concat dfs and revert to origin order
df_out_of_fold_pred = pd.concat(proba_dfs, axis=1)
# if need to convert to predict
if not self.proba:
df_out_of_fold_pred = df_out_of_fold_pred >= 0.5
# Now train ensembler
if not isinstance(y, (pd.Series, pd.DataFrame)):
y = pd.DataFrame(y)
self.ensembler.fit(
X=df_out_of_fold_pred,
y=y.iloc[self.out_of_fold],
*args, **kwargs
)
# signal done fitting
self.fitted = True
return self
def predict_proba(self, X, *args, **kwargs):
check_is_fitted(self, 'fitted')
# use full_trained model or not
if self.full_train:
base_models_list = self.full_fitted_models
else:
base_models_list = self.fitted_models
# get pred from all base models
proba_dfs = []
for i, model in enumerate(base_models_list):
df_proba = pd.DataFrame(
{'proba_{}'.format(i): model.predict_proba(X)[:, 1]}
)
proba_dfs.append(df_proba)
# horizontal concat P1 from all base models
df_base_pred = pd.concat(proba_dfs, axis=1)
if not self.proba:
df_base_pred = df_base_pred >= 0.5
# ensembler make predictions
return self.ensembler.predict_proba(df_base_pred, *args, **kwargs)
def predict(self, X, *args, **kwargs):
df_proba = self.predict_proba(X, *args, **kwargs)[:, 1]
df_pred = df_proba >= 0.5
return force_array(df_pred)
def _base_model_cross_val(model, X, y, cv=None, proba=True, *args, **kwargs):
"""
A private function that trains each base model for each fold
and outputs fitted base models, its out-of-fold predictions,
and array of y (in same order of out-of-fold predictions)
for fitting ensembler
Parameters
----------
model : object, base model
X : array-like, or dataframe
y : array-like, or dataframe
cv : int, cross-validation generator or an iterable, optional
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross validation,
- integer, to specify the number of folds in a `(Stratified)KFold`,
- An object to be used as a cross-validation generator.
- An iterable yielding train, test splits.
proba : bool, if True, model will implement predict_proba when it
gets called
Returns
-------
list of fitted model for each fold, Xt(out-of-fold pred),
y(matched with Xt)
"""
# get list of folds of indices
all_folds = list(check_cv(cv).split(X, y))
# check data type
if not isinstance(X, (pd.DataFrame, pd.Series)):
X = pd.DataFrame(force_array(X))
if not isinstance(y, (pd.DataFrame, pd.Series)):
y = pd.DataFrame(force_array(y))
# iterate each train-fold and fit base model
fitted_models = [
fit_model(
model=deepcopy(model),
X=X.iloc[train],
y=y.iloc[train],
*args,
**kwargs
) for train, test in all_folds
]
# generate out-of-sample predictions and reserve same order!!
proba_dfs = []
for i, (train, test) in enumerate(all_folds):
df_proba = pd.DataFrame(
{'proba': fitted_models[i].predict_proba(X.iloc[test])[:, 1]}, # noqa
index=test
)
proba_dfs.append(df_proba)
# concat dfs, sort index, and record index
df_out_of_sample = pd.concat(proba_dfs).sort_index()
idx = df_out_of_sample.index.values
# get pred_out_of_sample
pred_out_of_sample = \
force_array(df_out_of_sample).reshape((len(df_out_of_sample), 1))
# if need to convert to predict
if not proba:
pred_out_of_sample = pred_out_of_sample > 0.5
# get y matched with pred_out_of_sample
y_out_of_sample = y.iloc[idx]
return fitted_models, pred_out_of_sample, y_out_of_sample
class FullStackClassifier(BaseEstimator):
"""
This class is a full version of QuickStackClassifier, in other words,
QuickStackClassifier is a sub-instance of FullStackClassifier
Its objective is outputing out-of-fold predictions to fit ensembler
Instead of passing Xt, y (keep same shape) to ensembler, this class is
meant to allow Xt, y (modified shape due to specific CV strat) to ensembler
Parameters
----------
base_models : list of (string, base_model) tuples. The first
half of each tuple is the group name of the pipeline.
ensembler : an ensembler to combine the outputs of the base models
proba : bool, if True, model will implement predict_proba when it
gets called
full_train : bool, if True, its base models are trained with 100% data
again and they are used for generating probas for new data
Default is True
quick_stack : bool, if True, base models predict only on the last fold to
output out-of-sample predictions for ensembler to fit.
Default is False
cv : int, cross-validation generator or an iterable, optional
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross validation,
- integer, to specify the number of folds in a `(Stratified)KFold`,
- An object to be used as a cross-validation generator.
- An iterable yielding train, test splits.
n_jobs : integer, optional
The number of CPUs to use to do the computation. -1 means
'all CPUs'.
verbose : integer, optional
The verbosity level.
"""
def __init__(self, base_models, ensembler, proba=True,
full_train=True, quick_stack=False,
cv=None, n_jobs=1, verbose=0):
self.base_models = list(base_models)
self.ensembler = ensembler
self.proba = proba
self.full_train = full_train
self.quick_stack = quick_stack
self.cv = cv
self.n_jobs = n_jobs
self.verbose = verbose
def get_params(self, deep=True):
return self.ensembler.get_params(deep=deep)
def set_params(self, **params):
return self.ensembler.set_params(**params)
@property
def get_fitted_models_(self):
check_is_fitted(self, 'fitted')
if self.full_train:
fitted_models = self.full_fitted_models
else:
fitted_models = self.fitted_models
return fitted_models
@property
def get_fitted_ensembler_(self):
check_is_fitted(self, 'fitted')
return self.ensembler
def fit(self, X, y, *args, **kwargs):
"""
fit method is the method for fitting the ensembler and the trainning
data is out-of-fold predictions from base_models
"""
# cv has to be deterministic
cv = list(check_cv(self.cv).split(X, y))
# check quick_stack
if self.quick_stack:
cv = [cv[-1]]
# parallel iterating thru models to output out-of-fold pred
parallel = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)
result = parallel(delayed(_base_model_cross_val)(
model=deepcopy(model),
X=X,
y=y,
cv=cv,
proba=self.proba,
*args, **kwargs
) for (_, model) in self.base_models
)
# post process
fitted_models, pred_out_of_sample, y_out_of_sample = zip(*result)
self.fitted_models = \
[
(self.base_models[i][0], models)
for i, models in enumerate(fitted_models)
]
# assume all y_out_of_sample are the same, which they should be
y_out_of_sample = y_out_of_sample[0]
# prepare out_of_sample to fit ensembler
pred_out_of_sample = np.hstack(pred_out_of_sample)
# Now train ensembler
self.ensembler.fit(
X=pred_out_of_sample,
y=y_out_of_sample,
*args, **kwargs
)
# check full_train
if self.full_train:
self.full_fitted_models = parallel(delayed(fit_model)(
model=deepcopy(model),
X=X,
y=y,
*args,
**kwargs
) for (_, model) in self.base_models
)
# post process
self.full_fitted_models = \
[
(self.base_models[i][0], models)
for i, models in enumerate(self.full_fitted_models)
]
# signal done fitting
self.fitted = True
return self
def predict_proba(self, X, *args, **kwargs):
check_is_fitted(self, 'fitted')
# use full_trained model or not
proba_dfs = []
if self.full_train:
for name, model in self.full_fitted_models:
df_proba = pd.DataFrame(
{'proba_{}'.format(name): model.predict_proba(X)[:, 1]}
)
proba_dfs.append(df_proba)
else:
for name, models in self.fitted_models:
avg_proba = np.average(
np.hstack(
[
model.predict_proba(X)[:, 1].reshape((len(X), 1))
for model in models
]
),
axis=1
)
df_proba = pd.DataFrame({'proba_{}'.format(name): avg_proba})
proba_dfs.append(df_proba)
# horizontal concat P1 from all base models
df_base_pred = pd.concat(proba_dfs, axis=1)
if not self.proba:
df_base_pred = df_base_pred > 0.5
# ensembler make predictions
return self.ensembler.predict_proba(df_base_pred, *args, **kwargs)
def predict(self, X, *args, **kwargs):
df_proba = self.predict_proba(X, *args, **kwargs)[:, 1]
df_pred = df_proba > 0.5
return force_array(df_pred)
| [
"copy.deepcopy",
"sklearn.externals.joblib.delayed",
"pandas.DataFrame",
"numpy.hstack",
"gravity_learn.utils.force_array",
"sklearn.model_selection.StratifiedKFold",
"gravity_learn.utils.check_is_fitted",
"sklearn.externals.joblib.Parallel",
"sklearn.model_selection.cross_val_predict",
"gravity_l... | [((2660, 2780), 'warnings.warn', 'warnings.warn', (['"""EnsemblerClassifier is deprecated, please use FullStackClassifier instead"""', 'DeprecationWarning'], {}), "(\n 'EnsemblerClassifier is deprecated, please use FullStackClassifier instead'\n , DeprecationWarning)\n", (2673, 2780), False, 'import warnings\n'), ((2857, 2946), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'self.n_folds', 'shuffle': '(True)', 'random_state': 'self.random_state'}), '(n_splits=self.n_folds, shuffle=True, random_state=self.\n random_state)\n', (2872, 2946), False, 'from sklearn.model_selection import KFold, StratifiedKFold\n'), ((6009, 6130), 'warnings.warn', 'warnings.warn', (['"""QuickStackClassifier is deprecated, please use FullStackClassifier instead"""', 'DeprecationWarning'], {}), "(\n 'QuickStackClassifier is deprecated, please use FullStackClassifier instead'\n , DeprecationWarning)\n", (6022, 6130), False, 'import warnings\n'), ((6716, 6766), 'sklearn.externals.joblib.Parallel', 'Parallel', ([], {'n_jobs': 'self.n_jobs', 'verbose': 'self.verbose'}), '(n_jobs=self.n_jobs, verbose=self.verbose)\n', (6724, 6766), False, 'from sklearn.externals.joblib import Parallel, delayed\n'), ((9010, 9038), 'pandas.concat', 'pd.concat', (['proba_dfs'], {'axis': '(1)'}), '(proba_dfs, axis=1)\n', (9019, 9038), True, 'import pandas as pd\n'), ((9562, 9593), 'gravity_learn.utils.check_is_fitted', 'check_is_fitted', (['self', '"""fitted"""'], {}), "(self, 'fitted')\n", (9577, 9593), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n'), ((10131, 10159), 'pandas.concat', 'pd.concat', (['proba_dfs'], {'axis': '(1)'}), '(proba_dfs, axis=1)\n', (10140, 10159), True, 'import pandas as pd\n'), ((10503, 10523), 'gravity_learn.utils.force_array', 'force_array', (['df_pred'], {}), '(df_pred)\n', (10514, 10523), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n'), ((15338, 15369), 'gravity_learn.utils.check_is_fitted', 'check_is_fitted', (['self', '"""fitted"""'], {}), "(self, 'fitted')\n", (15353, 15369), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n'), ((15600, 15631), 'gravity_learn.utils.check_is_fitted', 'check_is_fitted', (['self', '"""fitted"""'], {}), "(self, 'fitted')\n", (15615, 15631), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n'), ((16119, 16169), 'sklearn.externals.joblib.Parallel', 'Parallel', ([], {'n_jobs': 'self.n_jobs', 'verbose': 'self.verbose'}), '(n_jobs=self.n_jobs, verbose=self.verbose)\n', (16127, 16169), False, 'from sklearn.externals.joblib import Parallel, delayed\n'), ((16891, 16920), 'numpy.hstack', 'np.hstack', (['pred_out_of_sample'], {}), '(pred_out_of_sample)\n', (16900, 16920), True, 'import numpy as np\n'), ((17763, 17794), 'gravity_learn.utils.check_is_fitted', 'check_is_fitted', (['self', '"""fitted"""'], {}), "(self, 'fitted')\n", (17778, 17794), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n'), ((18699, 18727), 'pandas.concat', 'pd.concat', (['proba_dfs'], {'axis': '(1)'}), '(proba_dfs, axis=1)\n', (18708, 18727), True, 'import pandas as pd\n'), ((19069, 19089), 'gravity_learn.utils.force_array', 'force_array', (['df_pred'], {}), '(df_pred)\n', (19080, 19089), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n'), ((3453, 3498), 'pandas.DataFrame', 'pd.DataFrame', (['base_predictions'], {'index': 'X.index'}), '(base_predictions, index=X.index)\n', (3465, 3498), True, 'import pandas as pd\n'), ((3843, 3888), 'pandas.DataFrame', 'pd.DataFrame', (['base_predictions'], {'index': 'X.index'}), '(base_predictions, index=X.index)\n', (3855, 3888), True, 'import pandas as pd\n'), ((5969, 6000), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(3)', 'shuffle': '(True)'}), '(n_splits=3, shuffle=True)\n', (5974, 6000), False, 'from sklearn.model_selection import KFold, StratifiedKFold\n'), ((9270, 9285), 'pandas.DataFrame', 'pd.DataFrame', (['y'], {}), '(y)\n', (9282, 9285), True, 'import pandas as pd\n'), ((11773, 11787), 'gravity_learn.utils.force_array', 'force_array', (['X'], {}), '(X)\n', (11784, 11787), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n'), ((11867, 11881), 'gravity_learn.utils.force_array', 'force_array', (['y'], {}), '(y)\n', (11878, 11881), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n'), ((12545, 12565), 'pandas.concat', 'pd.concat', (['proba_dfs'], {}), '(proba_dfs)\n', (12554, 12565), True, 'import pandas as pd\n'), ((12683, 12712), 'gravity_learn.utils.force_array', 'force_array', (['df_out_of_sample'], {}), '(df_out_of_sample)\n', (12694, 12712), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n'), ((3173, 3234), 'sklearn.model_selection.cross_val_predict', 'cross_val_predict', (['model', 'X', 'y'], {'cv': 'cv', 'method': '"""predict_proba"""'}), "(model, X, y, cv=cv, method='predict_proba')\n", (3190, 3234), False, 'from sklearn.model_selection import cross_val_predict\n'), ((6888, 6903), 'pandas.DataFrame', 'pd.DataFrame', (['y'], {}), '(y)\n', (6900, 6903), True, 'import pandas as pd\n'), ((11647, 11659), 'gravity_learn.utils.check_cv', 'check_cv', (['cv'], {}), '(cv)\n', (11655, 11659), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n'), ((11991, 12006), 'copy.deepcopy', 'deepcopy', (['model'], {}), '(model)\n', (11999, 12006), False, 'from copy import deepcopy\n'), ((15918, 15935), 'gravity_learn.utils.check_cv', 'check_cv', (['self.cv'], {}), '(self.cv)\n', (15926, 15935), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n'), ((16196, 16226), 'sklearn.externals.joblib.delayed', 'delayed', (['_base_model_cross_val'], {}), '(_base_model_cross_val)\n', (16203, 16226), False, 'from sklearn.externals.joblib import Parallel, delayed\n'), ((6549, 6566), 'gravity_learn.utils.check_cv', 'check_cv', (['self.cv'], {}), '(self.cv)\n', (6557, 6566), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n'), ((6946, 6964), 'sklearn.externals.joblib.delayed', 'delayed', (['fit_model'], {}), '(fit_model)\n', (6953, 6964), False, 'from sklearn.externals.joblib import Parallel, delayed\n'), ((7280, 7298), 'sklearn.externals.joblib.delayed', 'delayed', (['fit_model'], {}), '(fit_model)\n', (7287, 7298), False, 'from sklearn.externals.joblib import Parallel, delayed\n'), ((7654, 7672), 'sklearn.externals.joblib.delayed', 'delayed', (['fit_model'], {}), '(fit_model)\n', (7661, 7672), False, 'from sklearn.externals.joblib import Parallel, delayed\n'), ((16246, 16261), 'copy.deepcopy', 'deepcopy', (['model'], {}), '(model)\n', (16254, 16261), False, 'from copy import deepcopy\n'), ((17184, 17202), 'sklearn.externals.joblib.delayed', 'delayed', (['fit_model'], {}), '(fit_model)\n', (17191, 17202), False, 'from sklearn.externals.joblib import Parallel, delayed\n'), ((6988, 7003), 'copy.deepcopy', 'deepcopy', (['model'], {}), '(model)\n', (6996, 7003), False, 'from copy import deepcopy\n'), ((7322, 7337), 'copy.deepcopy', 'deepcopy', (['model'], {}), '(model)\n', (7330, 7337), False, 'from copy import deepcopy\n'), ((7696, 7711), 'copy.deepcopy', 'deepcopy', (['model'], {}), '(model)\n', (7704, 7711), False, 'from copy import deepcopy\n'), ((17226, 17241), 'copy.deepcopy', 'deepcopy', (['model'], {}), '(model)\n', (17234, 17241), False, 'from copy import deepcopy\n'), ((7392, 7406), 'gravity_learn.utils.force_array', 'force_array', (['y'], {}), '(y)\n', (7403, 7406), False, 'from gravity_learn.utils import force_array, check_cv, fit_model, check_is_fitted\n')] |
import sys
from data_reader.operations import load_dataset
from sklearn import metrics
import adlib.learners as learner
from data_reader.dataset import EmailDataset
import matplotlib.pyplot as plt
def main(argv):
"""
driver class that performs demo of the library
"""
# pre-process data and randomly partition
dataset = EmailDataset(path='../../data_reader/data/test/100_instance_debug.csv', raw=False)
training_, testing_ = dataset.split({'train': 60, 'test': 40})
training_data = load_dataset(training_)
testing_data = load_dataset(testing_)
# initialize and train RobustLearner
clf2 = learner.FeatureDeletion(training_data, {'hinge_loss_multiplier': 1,
'max_feature_deletion': 30})
clf2.train()
# produce simple metrics
y_predict = clf2.predict(testing_data[0])
y_true = testing_data[0].label
print(y_predict, y_true)
score = metrics.accuracy_score([y_true], [y_predict])
print("score = " + str(score))
wgt = clf2.decision_function()[0].tolist()[0]
print(wgt)
yaxis = [i for i in range(clf2.num_features)]
plt.plot(yaxis, wgt)
plt.show()
if __name__ == "__main__":
main(sys.argv[1:])
| [
"matplotlib.pyplot.plot",
"data_reader.operations.load_dataset",
"data_reader.dataset.EmailDataset",
"adlib.learners.FeatureDeletion",
"sklearn.metrics.accuracy_score",
"matplotlib.pyplot.show"
] | [((343, 430), 'data_reader.dataset.EmailDataset', 'EmailDataset', ([], {'path': '"""../../data_reader/data/test/100_instance_debug.csv"""', 'raw': '(False)'}), "(path='../../data_reader/data/test/100_instance_debug.csv', raw\n =False)\n", (355, 430), False, 'from data_reader.dataset import EmailDataset\n'), ((513, 536), 'data_reader.operations.load_dataset', 'load_dataset', (['training_'], {}), '(training_)\n', (525, 536), False, 'from data_reader.operations import load_dataset\n'), ((556, 578), 'data_reader.operations.load_dataset', 'load_dataset', (['testing_'], {}), '(testing_)\n', (568, 578), False, 'from data_reader.operations import load_dataset\n'), ((632, 732), 'adlib.learners.FeatureDeletion', 'learner.FeatureDeletion', (['training_data', "{'hinge_loss_multiplier': 1, 'max_feature_deletion': 30}"], {}), "(training_data, {'hinge_loss_multiplier': 1,\n 'max_feature_deletion': 30})\n", (655, 732), True, 'import adlib.learners as learner\n'), ((950, 995), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['[y_true]', '[y_predict]'], {}), '([y_true], [y_predict])\n', (972, 995), False, 'from sklearn import metrics\n'), ((1151, 1171), 'matplotlib.pyplot.plot', 'plt.plot', (['yaxis', 'wgt'], {}), '(yaxis, wgt)\n', (1159, 1171), True, 'import matplotlib.pyplot as plt\n'), ((1176, 1186), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1184, 1186), True, 'import matplotlib.pyplot as plt\n')] |
# -*- coding: utf-8 -*-
''' Widgets for displaying argparse arguments in a GUI '''
import argparse
from qtpy import QtCore, QtWidgets
from . import groupingTools, wrappedWidgets
class ArgDialog(QtWidgets.QDialog):
''' A simple settings dialog containing a single ArgparseWidget and stardard ok/cancel dialog buttons '''
valueAdjusted = QtCore.Signal()
def __init__(self, argParser, orphanGroupName='Main', parent=None):
super().__init__(parent)
self.argParser = argParser
self.argparseWidget = ArgparseListWidget(self.argParser, orphanGroupName)
self.argparseWidget.valueAdjusted.connect(self.valueAdjusted.emit)
self.setWindowTitle('Settings')
self.buttons = QtWidgets.QDialogButtonBox(self)
self.buttons.addButton(QtWidgets.QDialogButtonBox.Ok)
self.buttons.addButton(QtWidgets.QDialogButtonBox.Cancel)
self.setLayout(QtWidgets.QVBoxLayout())
self.layout().addWidget(self.argparseWidget)
self.layout().addWidget(self.buttons)
self.buttons.accepted.connect(self.accept)
self.buttons.rejected.connect(self.reject)
self.resize(800, 400)
def setValues(self, values):
return self.argparseWidget.setValues(values)
def getValues(self):
return self.argparseWidget.getValues()
class ArgparseListWidget(QtWidgets.QWidget):
''' A widget with a list of argparse groups in a listbox on the left, and stacked ArgGroupWidgets on the right.
This widget can be embedded into dialogs, windows, and other widgets
Clicking a group in the list on the left will display the settings for that group on the right
'''
valueAdjusted = QtCore.Signal()
def __init__(self, argParser, orphanGroupName, parent=None):
super().__init__(parent)
self.argParser = argParser
self.groupedParser = groupingTools.organizeIntoGroups(self.argParser)
self.setLayout(QtWidgets.QHBoxLayout())
self.groupList = QtWidgets.QListWidget(self)
self.widgetStack = QtWidgets.QStackedWidget(self)
self.groupList.setMaximumWidth(100)
self.layout().addWidget(self.groupList)
self.layout().addWidget(self.widgetStack, stretch=1)
self.orphanGroupname = orphanGroupName
for group,arguments in self.groupedParser.items():
if group.title in ['positional arguments', 'optional arguments']:
groupName = self.orphanGroupname
if self.widgetStack.count() > 0:
groupWidget = self.widgetStack.widget(0)
else:
groupWidget = self._addGroup(groupName, self.argParser.description)
else:
groupName = group.title
groupWidget = self._addGroup(groupName, group.description)
groupWidget.addArguments(arguments.values())
self.groupList.setCurrentRow(0)
self.groupList.currentRowChanged.connect(self.widgetStack.setCurrentIndex)
if self.groupList.count() == 1:
self.groupList.hide()
def _addGroup(self, name, description):
self.groupList.addItem(name)
groupWidget = ArgGroupWidget(name, description=description)
groupWidget.valueAdjusted.connect(self.valueAdjusted.emit)
self.widgetStack.addWidget(groupWidget)
return groupWidget
def setValues(self, values):
for i in range(self.widgetStack.count()):
groupName = self.groupList.item(i).text()
if groupName in values:
self.widgetStack.widget(i).setValues(values[groupName])
else:
self.widgetStack.widget(i).setValues(values)
def getValues(self):
settings = {}
for i in range(self.widgetStack.count()):
groupName = self.groupList.item(i).text()
if groupName == self.orphanGroupname:
settings = {**settings, **self.widgetStack.widget(i).getValues()}
else:
settings[groupName] = self.widgetStack.widget(i).getValues()
return settings
class ArgGroupWidget(QtWidgets.QWidget):
''' Container for a group of argument widgets
This widget can be embedded into other containers if you wanted, say, a tabbed-based view
'''
valueAdjusted = QtCore.Signal()
def __init__(self, name, arguments=[], description=None, parent=None):
super().__init__(parent)
self.name = name
self.setLayout(QtWidgets.QVBoxLayout())
self.layout().setAlignment(QtCore.Qt.AlignTop)
self.form = QtWidgets.QWidget()
self.form.setLayout(QtWidgets.QFormLayout())
self.form.layout().setHorizontalSpacing(32)
if description is None:
text = QtWidgets.QLabel(f'<h1>{name}</h1>')
else:
text = QtWidgets.QLabel(f'<h1>{name}</h1><h2>{description}</h2>')
text.setWordWrap(True)
self.layout().addWidget(text)
self.layout().addWidget(self.form)
self.addArguments(arguments)
def onValueChanged(self, _):
self.valueAdjusted.emit()
def addArguments(self, arguments):
for argument in arguments:
widget = wrappedWidgets.makeWidget(argument, self)
widget.valueChanged.connect(self.onValueChanged)
helpText = argument.help
widget.setToolTip(helpText)
widget.setWhatsThis(helpText)
self.form.layout().addRow(argument.dest, widget)
def setValues(self, values):
for row in range(self.form.layout().rowCount()):
itemName = self.form.layout().itemAt(row, QtWidgets.QFormLayout.LabelRole).widget().text()
if itemName in values:
widget = self.form.layout().itemAt(row, QtWidgets.QFormLayout.FieldRole).widget()
widget.setValue(values[itemName])
def getValues(self):
values = {}
for row in range(self.form.layout().rowCount()):
itemName = self.form.layout().itemAt(row, QtWidgets.QFormLayout.LabelRole).widget().text()
itemValue = self.form.layout().itemAt(row, QtWidgets.QFormLayout.FieldRole).widget().value()
values[itemName] = itemValue
return values
| [
"qtpy.QtWidgets.QVBoxLayout",
"qtpy.QtCore.Signal",
"qtpy.QtWidgets.QLabel",
"qtpy.QtWidgets.QListWidget",
"qtpy.QtWidgets.QStackedWidget",
"qtpy.QtWidgets.QDialogButtonBox",
"qtpy.QtWidgets.QFormLayout",
"qtpy.QtWidgets.QWidget",
"qtpy.QtWidgets.QHBoxLayout"
] | [((343, 358), 'qtpy.QtCore.Signal', 'QtCore.Signal', ([], {}), '()\n', (356, 358), False, 'from qtpy import QtCore, QtWidgets\n'), ((1572, 1587), 'qtpy.QtCore.Signal', 'QtCore.Signal', ([], {}), '()\n', (1585, 1587), False, 'from qtpy import QtCore, QtWidgets\n'), ((3808, 3823), 'qtpy.QtCore.Signal', 'QtCore.Signal', ([], {}), '()\n', (3821, 3823), False, 'from qtpy import QtCore, QtWidgets\n'), ((684, 716), 'qtpy.QtWidgets.QDialogButtonBox', 'QtWidgets.QDialogButtonBox', (['self'], {}), '(self)\n', (710, 716), False, 'from qtpy import QtCore, QtWidgets\n'), ((1842, 1869), 'qtpy.QtWidgets.QListWidget', 'QtWidgets.QListWidget', (['self'], {}), '(self)\n', (1863, 1869), False, 'from qtpy import QtCore, QtWidgets\n'), ((1891, 1921), 'qtpy.QtWidgets.QStackedWidget', 'QtWidgets.QStackedWidget', (['self'], {}), '(self)\n', (1915, 1921), False, 'from qtpy import QtCore, QtWidgets\n'), ((4049, 4068), 'qtpy.QtWidgets.QWidget', 'QtWidgets.QWidget', ([], {}), '()\n', (4066, 4068), False, 'from qtpy import QtCore, QtWidgets\n'), ((851, 874), 'qtpy.QtWidgets.QVBoxLayout', 'QtWidgets.QVBoxLayout', ([], {}), '()\n', (872, 874), False, 'from qtpy import QtCore, QtWidgets\n'), ((1797, 1820), 'qtpy.QtWidgets.QHBoxLayout', 'QtWidgets.QHBoxLayout', ([], {}), '()\n', (1818, 1820), False, 'from qtpy import QtCore, QtWidgets\n'), ((3961, 3984), 'qtpy.QtWidgets.QVBoxLayout', 'QtWidgets.QVBoxLayout', ([], {}), '()\n', (3982, 3984), False, 'from qtpy import QtCore, QtWidgets\n'), ((4091, 4114), 'qtpy.QtWidgets.QFormLayout', 'QtWidgets.QFormLayout', ([], {}), '()\n', (4112, 4114), False, 'from qtpy import QtCore, QtWidgets\n'), ((4199, 4235), 'qtpy.QtWidgets.QLabel', 'QtWidgets.QLabel', (['f"""<h1>{name}</h1>"""'], {}), "(f'<h1>{name}</h1>')\n", (4215, 4235), False, 'from qtpy import QtCore, QtWidgets\n'), ((4254, 4312), 'qtpy.QtWidgets.QLabel', 'QtWidgets.QLabel', (['f"""<h1>{name}</h1><h2>{description}</h2>"""'], {}), "(f'<h1>{name}</h1><h2>{description}</h2>')\n", (4270, 4312), False, 'from qtpy import QtCore, QtWidgets\n')] |
import smtplib
import argparse
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def main(args):
# Allow HTML-formatted emails (very simplistic atm, should be expanded if used)
msg = MIMEMultipart("alternative")
if args["body"].startswith("<html>", 0, 10):
msg.attach(MIMEText(args["body"],"html"))
else:
msg.attach(MIMEText(args["body"],"plain"))
msg["Subject"] = args["sub"]
msg["From"] = args["from"]
msg["To"] = args["to"]
s = smtplib.SMTP(args["smtp"])
# If authentication is required:
# s.starttls()
# s.login(user, pass)
s.sendmail(args["from"], [args["to"]], msg.as_string())
s.quit()
if __name__ == "__main__":
p = argparse.ArgumentParser(description="Send an email")
p.add_argument("--to", "-t", required=True, help="To address")
p.add_argument("--from", "-f", required=True, help="From address")
p.add_argument("--sub", "-s", required=True, help="Subject")
p.add_argument("--body", "-b", required=True, help="Message body")
p.add_argument("--smtp", default="localhost", help="SMTP server")
args = p.parse_args()
main(vars(args))
| [
"email.mime.text.MIMEText",
"email.mime.multipart.MIMEMultipart",
"argparse.ArgumentParser",
"smtplib.SMTP"
] | [((222, 250), 'email.mime.multipart.MIMEMultipart', 'MIMEMultipart', (['"""alternative"""'], {}), "('alternative')\n", (235, 250), False, 'from email.mime.multipart import MIMEMultipart\n'), ((482, 508), 'smtplib.SMTP', 'smtplib.SMTP', (["args['smtp']"], {}), "(args['smtp'])\n", (494, 508), False, 'import smtplib\n'), ((684, 736), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Send an email"""'}), "(description='Send an email')\n", (707, 736), False, 'import argparse\n'), ((310, 340), 'email.mime.text.MIMEText', 'MIMEText', (["args['body']", '"""html"""'], {}), "(args['body'], 'html')\n", (318, 340), False, 'from email.mime.text import MIMEText\n'), ((361, 392), 'email.mime.text.MIMEText', 'MIMEText', (["args['body']", '"""plain"""'], {}), "(args['body'], 'plain')\n", (369, 392), False, 'from email.mime.text import MIMEText\n')] |
from copy import deepcopy
from typing import List
from constants import BLACK, COLS, PIECES, RED, ROWS, SQUARE_SIZE, WHITE
from models.pieces import Piece
import pygame
class Board:
def __init__(self):
self.board = []
self.create_board()
self.white_left = self.red_left = PIECES
self.white_kings = self.red_kings = 0
def winner(self):
if self.red_left <= 0:
return WHITE
elif self.white_left <= 0:
return RED
return None
def get_piece(self, row, column):
return self.board[row][column]
def move(self, piece: Piece, row, column):
self.board[piece.row][piece.column], self.board[row][column] = (
self.board[row][column],
self.board[piece.row][piece.column],
)
piece.move(row, column)
if row == ROWS - 1 or row == 0:
piece.make_king()
if piece.color == WHITE:
self.white_kings += 1
if piece.color == RED:
self.red_kings += 1
def remove(self, pieces: List[Piece]):
for piece in pieces:
row, column = piece.row, piece.column
self.board[row][column] = None
if piece is not None:
if piece.color == RED:
self.red_left -= 1
else:
self.white_left -= 1
def _traverse_left(self, start, stop, step, color, left, skipped=None):
moves = {}
last = []
for r in range(start, stop, step):
if left < 0:
break
current = self.board[r][left]
if current is None:
if skipped and not last:
break
elif skipped:
moves[(r, left)] = last + skipped
else:
moves[(r, left)] = last
if last:
if step == -1:
row = max(r - 3, 0)
else:
row = min(r + 3, ROWS)
moves.update(
self._traverse_left(
r + step, row, step, color, left - 1, skipped=last
)
)
moves.update(
self._traverse_right(
r + step, row, step, color, left + 1, skipped=last
)
)
break
elif current.color == color:
break
else:
last = [current]
left -= 1
return moves
def _traverse_right(self, start, stop, step, color, right, skipped=None):
moves = {}
last = []
for r in range(start, stop, step):
if right >= COLS:
break
current = self.board[r][right]
if current is None:
if skipped and not last:
break
elif skipped:
moves[(r, right)] = last + skipped
else:
moves[(r, right)] = last
if last:
if step == -1:
row = max(r - 3, 0)
else:
row = min(r + 3, ROWS)
moves.update(
self._traverse_left(
r + step, row, step, color, right - 1, skipped=last
)
)
moves.update(
self._traverse_right(
r + step, row, step, color, right + 1, skipped=last
)
)
break
elif current.color == color:
break
else:
last = [current]
right += 1
return moves
def get_valid_moves(self, piece: Piece):
valid_moves = {}
left, right, row = piece.column - 1, piece.column + 1, piece.row
if piece.color == RED or piece.king:
valid_left_move = self._traverse_left(
row - 1, max(row - 3, -1), -1, piece.color, left
)
valid_right_move = self._traverse_right(
row - 1, max(row - 3, -1), -1, piece.color, right
)
valid_moves.update(valid_left_move)
valid_moves.update(valid_right_move)
if piece.color == WHITE or piece.king:
valid_left_move = self._traverse_left(
row + 1, min(row + 3, ROWS), 1, piece.color, left
)
valid_right_move = self._traverse_right(
row + 1, min(row + 3, ROWS), 1, piece.color, right
)
valid_moves.update(valid_left_move)
valid_moves.update(valid_right_move)
return valid_moves
def get_valid_boards(self, player):
boards = []
for piece in self.get_pieces(player):
for (move_row, move_column), skip in self.get_valid_moves(piece).items():
temporary_board = deepcopy(self)
temporary_piece = temporary_board.get_piece(piece.row, piece.column)
temporary_board.move(temporary_piece, move_row, move_column)
if skip:
temporary_board.remove(skip)
boards.append(temporary_board)
return boards
@staticmethod
def draw_squares(window):
window.fill(BLACK)
for row in range(ROWS):
for col in range(row % 2, COLS, 2):
pygame.draw.rect(
window,
RED,
(row * SQUARE_SIZE, col * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE),
)
def draw(self, window):
self.draw_squares(window)
for row in range(ROWS):
for column in range(COLS):
piece = self.board[row][column]
if piece is not None:
piece.draw(window)
def create_board(self):
for row in range(ROWS):
self.board.append([])
for column in range(COLS):
if column % 2 == (row + 1) % 2:
if row < 3:
piece = Piece(row, column, WHITE)
self.board[row].append(piece)
elif row > 4:
piece = Piece(row, column, RED)
self.board[row].append(piece)
else:
self.board[row].append(None)
else:
self.board[row].append(None)
def get_pieces(self, player):
pieces = []
for row in self.board:
for piece in row:
if piece and piece.color == player:
pieces.append(piece)
return pieces
def evaluate(self):
return (
self.white_left
- self.red_left
+ (self.white_kings * 0.5 - self.red_kings * 0.5)
)
| [
"pygame.draw.rect",
"models.pieces.Piece",
"copy.deepcopy"
] | [((5168, 5182), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (5176, 5182), False, 'from copy import deepcopy\n'), ((5662, 5761), 'pygame.draw.rect', 'pygame.draw.rect', (['window', 'RED', '(row * SQUARE_SIZE, col * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)'], {}), '(window, RED, (row * SQUARE_SIZE, col * SQUARE_SIZE,\n SQUARE_SIZE, SQUARE_SIZE))\n', (5678, 5761), False, 'import pygame\n'), ((6342, 6367), 'models.pieces.Piece', 'Piece', (['row', 'column', 'WHITE'], {}), '(row, column, WHITE)\n', (6347, 6367), False, 'from models.pieces import Piece\n'), ((6488, 6511), 'models.pieces.Piece', 'Piece', (['row', 'column', 'RED'], {}), '(row, column, RED)\n', (6493, 6511), False, 'from models.pieces import Piece\n')] |
#!/usr/bin/env python3
import os
import sys
import json
import configparser
import logging
import logging.config
import traceback
# install required package if in docker
if os.geteuid() == 0:
import pkgutil
import subprocess
required_pkgs = ["pytz"]
for pkg in required_pkgs:
if not pkgutil.find_loader(pkg):
p = subprocess.Popen(["pip3","install", pkg], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
import helper
import handler_basic
import handler_byline
import handler_lab
import handler_score
APP_VERSION = 4
if "WORKER_ID" in os.environ:
WORKER_ID = os.environ["WORKER_ID"]
else:
raise SystemExit("Environment variable 'WORKER_ID' is not found.")
if WORKER_ID == "dev":
logging.config.fileConfig('logging.conf')
helper.eventlog.enable_local_echo()
logger = logging.getLogger("basic")
helper.mongo.connect()
def update_self_then_restart():
helper.mongo.close()
if WORKER_ID == "dev":
raise SystemExit("NoUpdate if dev")
#script_path = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), "gitpull_then_restart.sh")
#subprocess.Popen([script_path])
#raise SystemExit("Exit for self-update")
# return code 99 will execute "git pull"
print("Exit for update and restart")
sys.exit(99)
def get_safe_param(jobj,pname):
if pname in jobj:
return jobj[pname]
else:
return None
def on_notice(raw_body):
#print("Got notice", raw_body)
try:
task_spec = json.loads(raw_body.decode("utf-8"))
cmd = task_spec["cmd"]
except:
logger.error("Invalid notice json: %r", raw_body)
return
if cmd == "exit":
logger.info("Got exit command from RabbitMQ channel")
helper.rabbit.stop()
elif cmd == "update":
update_self_then_restart()
elif cmd == "ping":
logger.info("Got ping command: " + get_safe_param(task_spec, "param"))
helper.eventlog.info("PONG " + get_safe_param(task_spec, "param"))
else:
logger.error("Unknown notice cmd: %s", cmd)
def on_task(raw_body):
#print("Got task", raw_body)
try:
task_spec = json.loads(raw_body.decode("utf-8"))
cmd = task_spec["cmd"]
ver = int(task_spec["ver"])
except:
logger.error("Invalid task json: %r", raw_body)
return
try:
if cmd == "basic":
handler_basic.process_basic_measurements(ver, task_spec)
elif cmd == "score":
handler_score.process_score_all(ver, task_spec)
elif cmd == "byline":
handler_byline.process_byline_extract(ver, task_spec) # 이제 안씀
elif cmd == "lab_split":
handler_lab.process_split(ver, task_spec)
elif cmd == "lab_postag":
handler_lab.process_postag(ver, task_spec)
elif cmd == "lab_sanitize":
handler_lab.process_sanitize(ver, task_spec)
elif cmd == "lab_metric":
handler_lab.process_metric(ver, task_spec)
elif cmd == "lab_trust":
handler_lab.process_trust(ver, task_spec)
elif cmd == "lab_integrate":
handler_lab.process_integrate(ver, task_spec)
else:
logger.error("Unknown task cmd: %s", cmd)
helper.eventlog.error("Unknown task cmd: %s" % cmd)
except Exception as ex:
newsId = task_spec["newsId"] if "newsId" in task_spec else "NoNews"
#ex_type, ex_value, ex_traceback = sys.exc_info()
#print("에러(%s,%s): %s,%s" % (cmd, newsId, ex_value.filename, ex_value.strerror))
helper.eventlog.fatal("에러(%s,%s): %s" % (cmd, newsId, str(ex)))
helper.eventlog.set_worker_id(WORKER_ID)
if WORKER_ID != "dev":
helper.eventlog.trace("Worker %s started (%d)" % (WORKER_ID, APP_VERSION))
logger.debug("Worker [%s] started (%d, %s)", WORKER_ID, APP_VERSION, os.environ["MQ_URL"])
# if __name__ == '__main__':
# handler_basic.process_basic_measurements(1, {"newsId":"02100101.20160630120514682"})
# handler_score.process_score_all(1, {"newsId":"02100101.20160630120514682"})
# on_task({"cmd":"basic", "ver":"1", "newsId":"01101001.20160601133622578"})
# 변경한 가중치 적용 -> 기사평가(asStats)
# coll_stat = helper.mongo.get_collection("asStats")
# docs = coll_stat.find({})
# for doc in docs:
# handler_score.process_score_all(1, {"newsId":doc["news_id"]})
# #print(doc["news_id"], doc["title"])
# 변경한 가중치 적용 -> 처리기사(news)
# coll_news = helper.mongo.get_collection("news")
# docs = coll_news.find({})
# for doc in docs:
# handler_basic.process_basic_measurements(1, {"newsId":doc["newsId"]})
# print(doc["newsId"], doc["title"])
try:
helper.rabbit.set_notice_handler(on_notice)
helper.rabbit.set_task_handler(on_task)
helper.rabbit.run(os.environ["MQ_URL"])
except KeyboardInterrupt:
helper.rabbit.stop()
logger.debug("Worker [%s] stopped.", WORKER_ID)
| [
"logging.getLogger",
"handler_basic.process_basic_measurements",
"helper.eventlog.enable_local_echo",
"handler_score.process_score_all",
"handler_byline.process_byline_extract",
"handler_lab.process_integrate",
"helper.eventlog.error",
"sys.exit",
"handler_lab.process_split",
"helper.mongo.connect... | [((846, 872), 'logging.getLogger', 'logging.getLogger', (['"""basic"""'], {}), "('basic')\n", (863, 872), False, 'import logging\n'), ((874, 896), 'helper.mongo.connect', 'helper.mongo.connect', ([], {}), '()\n', (894, 896), False, 'import helper\n'), ((3668, 3708), 'helper.eventlog.set_worker_id', 'helper.eventlog.set_worker_id', (['WORKER_ID'], {}), '(WORKER_ID)\n', (3697, 3708), False, 'import helper\n'), ((175, 187), 'os.geteuid', 'os.geteuid', ([], {}), '()\n', (185, 187), False, 'import os\n'), ((754, 795), 'logging.config.fileConfig', 'logging.config.fileConfig', (['"""logging.conf"""'], {}), "('logging.conf')\n", (779, 795), False, 'import logging\n'), ((800, 835), 'helper.eventlog.enable_local_echo', 'helper.eventlog.enable_local_echo', ([], {}), '()\n', (833, 835), False, 'import helper\n'), ((934, 954), 'helper.mongo.close', 'helper.mongo.close', ([], {}), '()\n', (952, 954), False, 'import helper\n'), ((1308, 1320), 'sys.exit', 'sys.exit', (['(99)'], {}), '(99)\n', (1316, 1320), False, 'import sys\n'), ((3736, 3810), 'helper.eventlog.trace', 'helper.eventlog.trace', (["('Worker %s started (%d)' % (WORKER_ID, APP_VERSION))"], {}), "('Worker %s started (%d)' % (WORKER_ID, APP_VERSION))\n", (3757, 3810), False, 'import helper\n'), ((4721, 4764), 'helper.rabbit.set_notice_handler', 'helper.rabbit.set_notice_handler', (['on_notice'], {}), '(on_notice)\n', (4753, 4764), False, 'import helper\n'), ((4769, 4808), 'helper.rabbit.set_task_handler', 'helper.rabbit.set_task_handler', (['on_task'], {}), '(on_task)\n', (4799, 4808), False, 'import helper\n'), ((4813, 4852), 'helper.rabbit.run', 'helper.rabbit.run', (["os.environ['MQ_URL']"], {}), "(os.environ['MQ_URL'])\n", (4830, 4852), False, 'import helper\n'), ((1771, 1791), 'helper.rabbit.stop', 'helper.rabbit.stop', ([], {}), '()\n', (1789, 1791), False, 'import helper\n'), ((4883, 4903), 'helper.rabbit.stop', 'helper.rabbit.stop', ([], {}), '()\n', (4901, 4903), False, 'import helper\n'), ((309, 333), 'pkgutil.find_loader', 'pkgutil.find_loader', (['pkg'], {}), '(pkg)\n', (328, 333), False, 'import pkgutil\n'), ((351, 446), 'subprocess.Popen', 'subprocess.Popen', (["['pip3', 'install', pkg]"], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), "(['pip3', 'install', pkg], stdout=subprocess.PIPE, stderr=\n subprocess.PIPE)\n", (367, 446), False, 'import subprocess\n'), ((2417, 2473), 'handler_basic.process_basic_measurements', 'handler_basic.process_basic_measurements', (['ver', 'task_spec'], {}), '(ver, task_spec)\n', (2457, 2473), False, 'import handler_basic\n'), ((2515, 2562), 'handler_score.process_score_all', 'handler_score.process_score_all', (['ver', 'task_spec'], {}), '(ver, task_spec)\n', (2546, 2562), False, 'import handler_score\n'), ((2605, 2658), 'handler_byline.process_byline_extract', 'handler_byline.process_byline_extract', (['ver', 'task_spec'], {}), '(ver, task_spec)\n', (2642, 2658), False, 'import handler_byline\n'), ((2714, 2755), 'handler_lab.process_split', 'handler_lab.process_split', (['ver', 'task_spec'], {}), '(ver, task_spec)\n', (2739, 2755), False, 'import handler_lab\n'), ((2802, 2844), 'handler_lab.process_postag', 'handler_lab.process_postag', (['ver', 'task_spec'], {}), '(ver, task_spec)\n', (2828, 2844), False, 'import handler_lab\n'), ((2893, 2937), 'handler_lab.process_sanitize', 'handler_lab.process_sanitize', (['ver', 'task_spec'], {}), '(ver, task_spec)\n', (2921, 2937), False, 'import handler_lab\n'), ((2984, 3026), 'handler_lab.process_metric', 'handler_lab.process_metric', (['ver', 'task_spec'], {}), '(ver, task_spec)\n', (3010, 3026), False, 'import handler_lab\n'), ((3072, 3113), 'handler_lab.process_trust', 'handler_lab.process_trust', (['ver', 'task_spec'], {}), '(ver, task_spec)\n', (3097, 3113), False, 'import handler_lab\n'), ((3163, 3208), 'handler_lab.process_integrate', 'handler_lab.process_integrate', (['ver', 'task_spec'], {}), '(ver, task_spec)\n', (3192, 3208), False, 'import handler_lab\n'), ((3289, 3340), 'helper.eventlog.error', 'helper.eventlog.error', (["('Unknown task cmd: %s' % cmd)"], {}), "('Unknown task cmd: %s' % cmd)\n", (3310, 3340), False, 'import helper\n')] |
"""
Indexes a dataset in Elasticsearch.
The dataset consists of a dataset.json file and optional supporting files
stored in the same directory. If a supporting file is found, it overrides
that section of the dataset.json.
Where possible dsloader attempts to enhance and complete information
available in dataset.json by adding dataset ids, etc.
"""
import os
import sys
import json
import requests
from argparse import ArgumentParser
from geojson import Polygon
from slugify import slugify, UniqueSlugify
from es_wrap import *
from noaa import *
import logging
log = logging.getLogger('dsloader')
def new_overlays(**kwargs):
"""Set default values with overrides for keyword args."""
new = dict(
title=unicode('', 'utf-8'),
name=unicode('', 'utf-8'),
shortname=unicode('', 'utf-8'),
description=unicode('', 'utf-8'),
url=unicode('', 'utf-8'),
type=unicode('wms', 'utf-8'),
styles=[unicode('default', 'utf-8')],
min=0,
max=0,
)
new.update(kwargs)
return new
def new_analytics(**kwargs):
"""Set default values with overrides for keyword args."""
new = dict(
title=unicode('', 'utf-8'),
name=unicode('', 'utf-8'),
shortname=unicode('', 'utf-8'),
description=unicode('', 'utf-8'),
url=unicode('', 'utf-8'),
)
new.update(kwargs)
return new
def new_downloads(**kwargs):
"""Set default values with overrides for keyword args."""
new = dict(
title=unicode('', 'utf-8'),
name=unicode('', 'utf-8'),
shortname=unicode('', 'utf-8'),
description=unicode('', 'utf-8'),
url=unicode('', 'utf-8'),
formats=unicode('', 'utf-8'),
size=0,
)
new.update(kwargs)
return new
def new_model(**kwargs):
new = dict(
name=unicode('', 'utf-8'),
description=unicode('', 'utf-8'),
url=unicode('', 'utf-8'),
type=unicode('', 'utf-8'),
)
new.update(kwargs)
return new
def new_metadata(markdown='', link='', description='', url=''):
new = dict(
markdown=unicode('', 'utf-8'),
link=unicode('', 'utf-8'),
description=unicode('', 'utf-8'),
url=unicode('', 'utf-8'),
)
new.update(kwargs)
return new
SERVICES = dict(overlays=new_overlays, model=new_model,
downloads=new_downloads, analytics=new_analytics)
def add_local_args(parser):
parser.add_argument('src',
help='name of the source dataset file (yaml or json)')
parser.add_argument('--preserve', default=False, action='store_true',
help='do no delete pre-existing ES dataset when re-indexing')
parser.add_argument('--force', default=False, action='store_true',
help='force dataset creation if final validation fails')
parser.add_argument('--novars', default=False, action='store_true',
help='append variable list to end of dataset description')
parser.add_argument('--debug',
default=logging.WARN, action='store_const', const=logging.DEBUG,
help='enable debugging output')
parser.add_argument('--verbose', '-v',
default=False, action='store_const', const=True,
help='print the document after successful load')
# standard file names used in loading dataset
parser.add_argument('--description-md', default='description.md',
metavar='FILE',
help="the markdown file will update the dataset's title and "
"description fields (default=description.md)")
parser.add_argument('--info-md', default='information.md', metavar='FILE',
help="the markdown file will update the dataset's information "
"field (default=information.md)")
parser.add_argument('--boundary', default='boundary.geojson',
metavar='FILE',
help='the boundary geojson file (default=boundary.geojson)')
parser.add_argument('--overlays', default='overlays.json',
metavar='FILE',
help='overlay parameter file (default=overlays.json)')
parser.add_argument('--overlays-md', default='overlays.md',
metavar='FILE',
help='markdown description of the overlay service '
'(default=overlays.md)')
parser.add_argument('--downloads', default='downloads.json',
metavar='FILE',
help='download parameter file (default=downloads.json)')
parser.add_argument('--downloads-md', default='downloads.md',
metavar='FILE',
help='markdown description of the download service '
'(default=downloads.md)')
parser.add_argument('--analytics', default='analytics.json',
metavar='FILE',
help='analytics parameter file (default=analytics.json)')
parser.add_argument('--analytics-md', default='analytics.md',
metavar='FILE',
help='markdown description of the analytic service '
'(default=analytics.md)')
parser.add_argument('--provenance-md', default='provenance.md',
metavar='FILE',
help='markdown description of the analytic service '
'(default=provenance.md)')
parser.add_argument('--model', default='model.json', metavar='FILE',
help='model parameter file (default=model.json)')
parser.add_argument('--model-md', default='model.md', metavar='FILE',
help='markdown description of the model service (default=model.md)')
parser.add_argument('--noaa', default=False, action='store_true',
help='the source dataset file is a NOAA metadata file')
def add_skope_args(parser):
"""SKOPE spectific variables used to complete strings with templates."""
parser.add_argument('--skope-deploy-host',
default=os.environ.get('SKOPE_DEPLOY_HOST', 'http://localhost'),
help='template variable automatically applied to json parameter files')
parser.add_argument('--skope-yyyy',
default=os.environ.get('SKOPE_YYYY', '{YYYY}'),
help='temporal variable used for years (completed by webapp)')
parser.add_argument('--skope-mm',
default=os.environ.get('SKOPE_MM', '{MM}'),
help='temporal variable used for months (completed by webapp)')
parser.add_argument('--skope-yyyy-mm',
default=os.environ.get('SKOPE_YYYY_MM', '{YYYY-MM}'),
help='temporal variable used for year-month (completed by webapp)')
def get_skope_args(args):
"""Extract SKOPE specific variables from argparse namespace."""
d = {k.replace('skope_','').upper(): v for (k, v) in vars(args).items() \
if k.startswith('skope_')}
d.update(dict(start='{start}', end='{end}',
boundaryGeometry='{boundaryGeometry}'))
log.debug('template variables = %s', str(d))
return d
def update_description(doc, path, fname):
filepath = os.path.join(path, fname)
if not os.path.isfile(filepath):
return
with open(filepath) as f:
md = f.readlines()
for idx, line in enumerate(md):
if line.startswith('# '):
doc['title'] = unicode(line[2:].strip(), 'utf-8')
del md[idx]
break
# skip empty lines after title
for idx, line in enumerate(md):
if not line.isspace():
break
doc['description'] = unicode(''.join(md[idx:]), 'utf-8')
def update_parameters(doc, service, path, fname, varstrings):
"""Read service parameter file and integrate into document.
Args:
doc (dict): dataset document
service (str): service being parsed
path (str): base path for parameter file
fname (str): filename of parameter file
varstrings (dict): variable substitution strings applied to parameters
"""
shortnames = { v['title']:v['shortname'] for v in doc['variables']}
filepath = os.path.join(path, fname)
if not os.path.isfile(filepath):
return
with open(filepath) as f:
#s = f.read().format(**kwargs)
#parameters = json.loads(s)[service]
parameters = json.load(f)[service]
for idx, p in enumerate(parameters):
# TODO name is deprecated, remove at some point
if not p.get('title', '') and p.get('name', ''):
log.warn("use of variable attribute 'name' in %s is deprecated",
fname)
p['title'] = p['name']
if not p.get('title', ''):
log.error('missing title in %s[%d]', service, idx)
sys.exit(1)
if p.get('title') not in shortnames.keys():
log.error('service %s variable %s not found in dataset variables',
service, p.get('title'))
sys.exit(1)
p['shortname'] = shortnames[p.get('title')]
if 'url' in p.keys():
p['url'] = p['url'].format(**varstrings)
if not p.get('description', ''):
p['description'] = 'dataset {} variable {}'.format(doc['title'],
p['title'].encode('utf-8'))
# update service specific values
doc[service] = [SERVICES[service](**p) for p in parameters]
def update_markdown(doc, service, path, fname):
log.debug('adding md file %s for service %s', fname, service)
doc.setdefault(service, {})
filepath = os.path.join(path, fname)
if os.path.isfile(filepath):
with open(filepath) as f:
doc[service]['markdown'] = unicode(f.read(), 'utf-8')
elif doc[service].get('markdown', ''):
log.debug('%s - file %s not found.', filepath)
doc.setdefault(service, {})['markdown'] = unicode('', 'utf-8')
def generate_boundary(extents):
"""Create boundary geometry based on extents."""
left, bottom, right, top = extents
return Polygon([[
(left, bottom),
(left, top),
(right, top),
(right, bottom),
(left, bottom)
]])
def read_boundary(filepath):
"""Read geojson boundary and return geometry."""
with open(filepath) as f:
geojson = f.read()
if geojson['type'] == 'FeatureCollection':
return geojson['features'][0]['geometry']
elif geojson['type'] == 'Feature':
return geojson['geometry']
else:
return {}
def update_boundary(doc, path, fname):
filepath = os.path.join(path, fname)
if os.path.isfile(filepath):
doc['region']['geometry'] = read_boundary(filepath)
elif doc['region'].get('extents', ''):
doc['region']['geometry'] = generate_boundary(doc['region']['extents'])
else:
log.warn('geometry not set - missing boundary file and extents')
# TODO 'name' is deprecated, remove in the future
def normalize_variables(doc):
"""Add unique shortname and handle deprecated 'name' attribute."""
for v in doc['variables']:
title = v.get('title', '')
if not title:
title = v.get('name', '')
if not title:
log.error('dataset variables missing title attribute')
sys.exit(1)
log.warn("use of variable attribute 'name' is deprecated")
v['title'] = title
v['shortname'] = slugify(title, to_lower=True)
#if not v.get('description', ''):
# v['description'] = '{} of dataset {}'.format(v['title'],
# doc['title'])
def get_variables(doc, title=False):
"""Return the list of variables from the document."""
field = 'shortname' if title==false else 'title'
return [v[field] for v in doc['variables']]
def append_variables(doc):
"""Append the list of variables to the dataset description."""
variables = ', '.join([ '%s (%s)' % (v['title'], v['class']) \
for v in doc['variables'] ])
markdown = '\n**Variables:** ' + variables
doc['description'] = doc.get('description', unicode('', 'utf-8')) \
+ markdown
#TODO
def validate_dataset(doc):
"""Check the document for errors and mistakes."""
return True
def update_dataset_id(es, results, path, preserve=False):
"""Delete existing document and update document id."""
filepath = os.path.join(path, 'ID')
if not preserve and os.path.exists(filepath):
with open(filepath) as f:
_id = f.read().strip()
es.delete(index=results['_index'], doc_type=results['_type'], id=_id)
with open(filepath, 'w') as f:
f.write(results['_id'])
def main():
parser = ArgumentParser()
add_local_args(parser)
add_elasticsearch_args(parser)
add_skope_args(parser)
args = parser.parse_args()
logging.basicConfig(level=args.debug)
template_vars = get_skope_args(args)
skopeid = UniqueSlugify(to_lower=True)
if args.noaa:
doc = dict(type='dataset')
noaa = NOAA(args.src)
importNOAAMetadata(doc, noaa)
else:
with open(args.src) as f:
doc = json.load(f)
# path is used to locating supporting metadata files
path, fname = os.path.split(args.src)
update_description(doc, path, args.description_md)
doc['skopeid'] = skopeid(doc['title'])
normalize_variables(doc)
if not args.novars:
append_variables(doc)
update_boundary(doc, path, args.boundary)
update_markdown(doc, 'information', path, args.info_md)
update_parameters(doc, 'overlays', path, args.overlays, template_vars)
update_markdown(doc, 'overlayService', path, args.overlays_md)
update_parameters(doc, 'downloads', path, args.downloads, template_vars)
update_markdown(doc, 'downloadService', path, args.downloads_md)
update_parameters(doc, 'analytics', path, args.analytics, template_vars)
update_markdown(doc, 'analyticService', path, args.analytics_md)
update_parameters(doc, 'model', path, args.model, template_vars)
update_markdown(doc, 'modelService', path, args.model_md)
update_markdown(doc, 'provenanceService', path, args.provenance_md)
if args.force or validate_dataset(doc):
es = config_elasticsearch(args.es_url)
res = es.index(index=args.es_index, doc_type='dataset', body=doc)
if res['_shards']['successful'] > 0:
update_dataset_id(es, res, path, preserve=args.preserve)
if args.verbose:
sys.stdout.write(json.dumps(doc)+'\n')
else:
sys.exit(1)
if __name__ == '__main__':
main()
| [
"logging.getLogger",
"logging.basicConfig",
"os.path.exists",
"argparse.ArgumentParser",
"json.dumps",
"os.path.join",
"os.environ.get",
"os.path.split",
"geojson.Polygon",
"os.path.isfile",
"json.load",
"sys.exit",
"slugify.UniqueSlugify",
"slugify.slugify"
] | [((573, 602), 'logging.getLogger', 'logging.getLogger', (['"""dsloader"""'], {}), "('dsloader')\n", (590, 602), False, 'import logging\n'), ((6857, 6882), 'os.path.join', 'os.path.join', (['path', 'fname'], {}), '(path, fname)\n', (6869, 6882), False, 'import os\n'), ((7835, 7860), 'os.path.join', 'os.path.join', (['path', 'fname'], {}), '(path, fname)\n', (7847, 7860), False, 'import os\n'), ((9278, 9303), 'os.path.join', 'os.path.join', (['path', 'fname'], {}), '(path, fname)\n', (9290, 9303), False, 'import os\n'), ((9312, 9336), 'os.path.isfile', 'os.path.isfile', (['filepath'], {}), '(filepath)\n', (9326, 9336), False, 'import os\n'), ((9746, 9837), 'geojson.Polygon', 'Polygon', (['[[(left, bottom), (left, top), (right, top), (right, bottom), (left, bottom)]]'], {}), '([[(left, bottom), (left, top), (right, top), (right, bottom), (left,\n bottom)]])\n', (9753, 9837), False, 'from geojson import Polygon\n'), ((10291, 10316), 'os.path.join', 'os.path.join', (['path', 'fname'], {}), '(path, fname)\n', (10303, 10316), False, 'import os\n'), ((10324, 10348), 'os.path.isfile', 'os.path.isfile', (['filepath'], {}), '(filepath)\n', (10338, 10348), False, 'import os\n'), ((12152, 12176), 'os.path.join', 'os.path.join', (['path', '"""ID"""'], {}), "(path, 'ID')\n", (12164, 12176), False, 'import os\n'), ((12471, 12487), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (12485, 12487), False, 'from argparse import ArgumentParser\n'), ((12613, 12650), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'args.debug'}), '(level=args.debug)\n', (12632, 12650), False, 'import logging\n'), ((12708, 12736), 'slugify.UniqueSlugify', 'UniqueSlugify', ([], {'to_lower': '(True)'}), '(to_lower=True)\n', (12721, 12736), False, 'from slugify import slugify, UniqueSlugify\n'), ((13011, 13034), 'os.path.split', 'os.path.split', (['args.src'], {}), '(args.src)\n', (13024, 13034), False, 'import os\n'), ((6894, 6918), 'os.path.isfile', 'os.path.isfile', (['filepath'], {}), '(filepath)\n', (6908, 6918), False, 'import os\n'), ((7872, 7896), 'os.path.isfile', 'os.path.isfile', (['filepath'], {}), '(filepath)\n', (7886, 7896), False, 'import os\n'), ((11146, 11175), 'slugify.slugify', 'slugify', (['title'], {'to_lower': '(True)'}), '(title, to_lower=True)\n', (11153, 11175), False, 'from slugify import slugify, UniqueSlugify\n'), ((12202, 12226), 'os.path.exists', 'os.path.exists', (['filepath'], {}), '(filepath)\n', (12216, 12226), False, 'import os\n'), ((14350, 14361), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (14358, 14361), False, 'import sys\n'), ((5746, 5801), 'os.environ.get', 'os.environ.get', (['"""SKOPE_DEPLOY_HOST"""', '"""http://localhost"""'], {}), "('SKOPE_DEPLOY_HOST', 'http://localhost')\n", (5760, 5801), False, 'import os\n'), ((5944, 5982), 'os.environ.get', 'os.environ.get', (['"""SKOPE_YYYY"""', '"""{YYYY}"""'], {}), "('SKOPE_YYYY', '{YYYY}')\n", (5958, 5982), False, 'import os\n'), ((6118, 6152), 'os.environ.get', 'os.environ.get', (['"""SKOPE_MM"""', '"""{MM}"""'], {}), "('SKOPE_MM', '{MM}')\n", (6132, 6152), False, 'import os\n'), ((6294, 6338), 'os.environ.get', 'os.environ.get', (['"""SKOPE_YYYY_MM"""', '"""{YYYY-MM}"""'], {}), "('SKOPE_YYYY_MM', '{YYYY-MM}')\n", (6308, 6338), False, 'import os\n'), ((8055, 8067), 'json.load', 'json.load', (['f'], {}), '(f)\n', (8064, 8067), False, 'import json\n'), ((8484, 8495), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (8492, 8495), False, 'import sys\n'), ((8688, 8699), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (8696, 8699), False, 'import sys\n'), ((12922, 12934), 'json.load', 'json.load', (['f'], {}), '(f)\n', (12931, 12934), False, 'import json\n'), ((11010, 11021), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (11018, 11021), False, 'import sys\n'), ((14309, 14324), 'json.dumps', 'json.dumps', (['doc'], {}), '(doc)\n', (14319, 14324), False, 'import json\n')] |
"""
This file is subject to the terms and conditions defined in the
LICENSE file, which is part of this source code package.
"""
from DigitalObject import DigitalObject
from lxml import etree
import Cfg
import Utils
import hashlib
import logging
import os
# namespaces
DOC_KEY = "doc"
DOC_NS = "urn:isbn:1-931666-33-4"
ESRC_KEY = "ns0"
ESRC_NS = "http://www.esrc.unimelb.edu.au"
XLINK_KEY = "xlink"
XLINK_NS = "http://www.w3.org/1999/xlink"
XSI_KEY = "xsi"
XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"
class EacCpf(object):
"""
EAC-CPF documents provide metadata and references to external entities
that are the subject of indexing. This class wraps the EAC-CPF document
and provides convenience methods for extracting required metadata. The
content of an EAC-CPF document is typically presented by a separate HTML
document, referred to here as the presentation.
"""
def __init__(self, Source, MetadataUrl=None, PresentationUrl=None):
"""
Source is a file system path or URL to the EAC-CPF document file. The
Source is used to load the content of the document. MetadataUrl is the
public URL to the EAC-CPF document. PresentationUrl is the public URL
to the HTML presentation.
"""
self.log = logging.getLogger()
self.metadata = MetadataUrl
self.ns = { DOC_KEY: DOC_NS, ESRC_KEY: ESRC_NS, XLINK_KEY: XLINK_NS }
self.presentation = PresentationUrl
self.source = Source
data = Utils.load_from_source(Source)
self.xml = etree.fromstring(data)
# some documents may be missing the fully specified eac-cpf document
# namespace attributes, which will result in failures during subsequent
# operations. we'll check for the missing attribute here so that we can
# make the problem and its resolution obvious in the log
root = self.xml.xpath('//doc:eac-cpf', namespaces=self.ns)
if len(root) == 0:
self.log.error("Missing EAC-CPF namespace declaration in {0}".format(Source))
raise Exception
def getAbstract(self):
"""
Get document abstract.
"""
try:
abstract = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:description/doc:biogHist/doc:abstract", namespaces=self.ns)
return abstract[0].text if abstract[0].text else None
except:
pass
def getBiogHist(self):
"""
Get the non-abstract portion of the biogHist entry.
"""
try:
val = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:description/doc:biogHist/doc:p", namespaces=self.ns)
if val:
ps = []
for p in val:
if p.text is not None:
ps.append(p.text)
return ' '.join(ps)
except:
pass
return None
def getCpfRelations(self):
"""
Get list of CPF relations.
"""
rels = []
try:
cpfr = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:relations/doc:cpfRelation", namespaces=self.ns)
rels.extend(cpfr)
except:
pass
return rels
def getCpfRelationLinks(self):
"""
"""
links = []
target = "{{{0}}}href".format(XLINK_NS)
try:
rels = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:relations/doc:cpfRelation", namespaces=self.ns)
for rel in rels:
for attr in rel.attrib:
if target in attr:
url = rel.attrib[attr]
relationEntry = rel.xpath("./doc:relationEntry[1]", namespaces=self.ns)
if relationEntry and len(relationEntry) > 0:
links.append((url, relationEntry[0].text))
except:
pass
return links
def getData(self):
"""
Get the raw XML data.
"""
return etree.tostring(self.xml, pretty_print=True)
def getDigitalObjects(self, Thumbnail=False):
"""
Get the list of digital objects referenced in the document. Transform
the metadata contained in the HTML page to an intermediate YML digital
object representation.
"""
dobjects = []
rels = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:relations/doc:resourceRelation", namespaces=self.ns)
for rel in rels:
try:
if rel.attrib['resourceRelationType'] == 'other':
relEntry = rel.xpath("./doc:relationEntry", namespaces=self.ns)
descNote = rel.xpath("./doc:descriptiveNote/doc:p", namespaces=self.ns)
if relEntry[0].attrib['localType'] == 'digitalObject':
# if the descriptiveNote does not contain the string "<p>Include in Gallery</p>",
# then it is not a thumbnail for this record
if Thumbnail and len(descNote) > 0 and not "Include in Gallery" in descNote[0].text:
continue
nz = {
"doc": "urn:isbn:1-931666-33-4",
"obj": "urn:isbn:1-931666-22-9",
}
# ISSUE #30 in some cases, the title string contains
# markup in it, which results in only a portion of the
# title string being returned. Here we concat the text
# content of all the child nodes together to create a
# single title string
title = ''
title_elements = rel.xpath("./doc:relationEntry", namespaces=self.ns)
if title_elements:
for e in title_elements.pop().itertext():
title += e
# ISSUE #30: abstract may contain markup. concat all
# the child elements on to the abstract value.
abstract = ''
abstract_elements = rel.xpath("./doc:objectXMLWrap/obj:archref/obj:abstract", namespaces=nz)
if abstract_elements:
for e in abstract_elements.pop().itertext():
abstract += e
alternate_title = self.getTitle()
localtype = self.getLocalType()
presentation = rel.attrib['{http://www.w3.org/1999/xlink}href']
unitdate = rel.xpath("./doc:objectXMLWrap/obj:archref/obj:unitdate", namespaces=nz)
# create the digital object
if unitdate and not hasattr(unitdate, 'lower'):
unitdate = unitdate[0].text
dobj = DigitalObject(self.source, self.metadata, presentation, title, abstract, localtype, UnitDate=unitdate, AlternateTitle=alternate_title)
else:
fromDate, toDate = self.getExistDates()
dobj = DigitalObject(self.source, self.metadata, presentation, title, abstract, localtype, FromDate=fromDate, ToDate=toDate, AlternateTitle=alternate_title)
dobjects.append(dobj)
except:
self.log.error("Could not retrieve digital object {0}".format(self.source), exc_info=Cfg.LOG_EXC_INFO)
return dobjects
def getEntityId(self):
"""
Get the record entity Id. If a value can not be found None is returned.
"""
try:
val = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:identity/doc:entityId", namespaces=self.ns)
return val[0].text if val[0].text else None
except:
pass
def getEntityType(self):
"""
Get the entity type.
"""
try:
val = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:identity/doc:entityType", namespaces=self.ns)
return val[0].text if val[0].text else None
except:
pass
def getExistDates(self):
"""
Get entity exist dates. Returns 'from date', 'to date' tuple.
"""
try:
val = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:description/doc:existDates", namespaces=self.ns)
if val:
fromDate = val[0].xpath("./doc:dateRange/doc:fromDate", namespaces=self.ns)
toDate = val[0].xpath("./doc:dateRange/doc:toDate", namespaces=self.ns)
if fromDate and len(fromDate) > 0 and 'standardDate' in fromDate[0].attrib:
fromDate = fromDate[0].attrib['standardDate']
else:
fromDate = None
if toDate and len(toDate) > 0 and 'standardDate' in toDate[0].attrib:
toDate = toDate[0].attrib['standardDate']
else:
toDate = None
# ensure dates are in ISO format
if fromDate and not 'T00:00:00Z' in fromDate:
fromDate += "T00:00:00Z"
if toDate and not 'T00:00:00Z' in toDate:
toDate += "T00:00:00Z"
return fromDate, toDate
except:
pass
return None, None
def getFileName(self):
"""
Get document file name.
"""
return Utils.getFileName(self.source)
def getFreeText(self):
"""
Get content from free text fields.
"""
freeText = ''
names = self.getNameEntries()
if names:
freeText = ' '.join(names)
abstract = self.getAbstract()
if abstract:
freeText += self.getAbstract() + ' '
biog = self.getBiogHist()
if biog:
freeText += biog + ' '
functions = self.getFunctions()
if functions:
freeText += ' '.join(functions)
return freeText
def getFunctions(self):
"""
Get the functions.
"""
functions = []
try:
val = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:description/doc:functions/doc:function/doc:term", namespaces=self.ns)
for func in val:
if func.text is not None:
functions.append(func.text)
return functions
except:
pass
return functions
def getHash(self):
"""
Get a secure hash for the content in hexadecimal format.
"""
h = hashlib.sha1()
data = etree.tostring(self.xml)
h.update(data)
return h.hexdigest()
def getLocalType(self):
"""
Get the local type.
"""
try:
val = self.xml.xpath("//doc:eac-cpf/doc:control/doc:localControl/doc:term", namespaces=self.ns)
return val[0].text if val[0].text else None
except:
pass
def getLocations(self):
"""
Get locations.
"""
locations = []
try:
places = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:description/doc:places/doc:place", namespaces=self.ns)
for place in places:
location = {}
placeEntry = place.xpath("./doc:placeEntry", namespaces=self.ns)
if placeEntry:
location['placeentry'] = placeEntry[0].text
if 'latitude' in placeEntry[0].attrib:
location['latitude'] = placeEntry[0].attrib['latitude']
if 'longitude' in placeEntry[0].attrib:
location['longitude'] = placeEntry[0].attrib['longitude']
locations.append(location)
except:
pass
return locations
def getChronLocations(self):
"""
Get locations.
"""
locations = []
try:
chronItems = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:description/doc:biogHist/doc:chronList/doc:chronItem", namespaces=self.ns)
for chronItem in chronItems:
location = {}
fromDate = chronItem.xpath("./doc:dateRange/doc:fromDate", namespaces=self.ns)
toDate = chronItem.xpath("./doc:dateRange/doc:toDate", namespaces=self.ns)
if fromDate and len(fromDate) > 0 and 'standardDate' in fromDate[0].attrib:
fromDate = fromDate[0].attrib['standardDate']
fromDate = Utils.fixIncorrectDateEncoding(fromDate)
location['fromDate'] = fromDate
if toDate and len(toDate) and 'standardDate' in toDate[0].attrib:
toDate = toDate[0].attrib['standardDate']
toDate = Utils.fixIncorrectDateEncoding(toDate)
location['toDate'] = toDate
placeEntry = chronItem.xpath("./doc:placeEntry", namespaces=self.ns)
if placeEntry:
location['placeentry'] = placeEntry[0].text
if 'latitude' in placeEntry[0].attrib:
location['latitude'] = placeEntry[0].attrib['latitude']
if 'longitude' in placeEntry[0].attrib:
location['longitude'] = placeEntry[0].attrib['longitude']
event = chronItem.xpath("./doc:event", namespaces=self.ns)
if event:
location['event'] = event[0].text
locations.append(location)
except:
pass
return locations
def getMetadataUrl(self):
"""
Get the URL to the EAC-CPF document.
"""
try:
if 'http://' in self.source or 'https://' in self.source:
return self.source
elif self.metadata:
return self.metadata
except:
pass
return None
def getNameEntries(self):
"""
Get name entry.
"""
names = []
try:
val = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:identity/doc:nameEntry/doc:part", namespaces=self.ns)
for part in val:
for t in part.itertext():
names.append(t)
return names
except:
pass
return names
def getPresentationUrl(self):
"""
Get the URL to the HTML presentation of the EAC-CPF document.
"""
if self.presentation:
return self.presentation
try:
val = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:identity/doc:entityId", namespaces=self.ns)
return val[0].text if val[0].text else None
except:
pass
def getRecordId(self):
"""
Get the record identifier.
"""
try:
val = self.xml.xpath("//doc:eac-cpf/doc:control/doc:recordId", namespaces=self.ns)
return val[0].text if val[0].text else None
except:
pass
def getResourceRelations(self):
"""
Get list of resource relations.
"""
rels = []
try:
val = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:relations/doc:resourceRelation", namespaces=self.ns)
rels.extend(val)
except:
pass
return rels
def getResourceRelationLinks(self):
"""
Get links from resource relation entries to external documents.
"""
links = []
target = "{{{0}}}href".format(XLINK_NS)
try:
rels = self.xml.xpath("//doc:eac-cpf/doc:cpfDescription/doc:relations/doc:resourceRelation", namespaces=self.ns)
for rel in rels:
for attr in rel.attrib:
if target in attr:
url = rel.attrib[attr]
relationEntry = rel.xpath("./doc:relationEntry[1]", namespaces=self.ns)
if relationEntry and len(relationEntry) > 0:
links.append((url, relationEntry[0].text))
except:
pass
return links
def getTitle(self):
"""
Get the record title.
"""
names = self.getNameEntries()
if names:
return ' '.join(names)
return None
def getThumbnail(self):
"""
Get the digital object that acts as a thumbnail image for this record.
"""
try:
obj = self.getDigitalObjects(Thumbnail=True)
return obj[0]
except:
return None
def hasDigitalObjects(self):
"""
Determine if the EAC-CPF record has digital object references.
"""
objects = self.getDigitalObjects()
if objects and len(objects) > 0:
return True
return False
def hasLocation(self):
"""
Determine if the record has a location.
"""
locations = self.getLocations()
if len(locations) > 0:
return True
return False
def hasMaintenanceRecord(self):
"""
Determine if the record has a maintenance history section.
"""
try:
val = self.xml.xpath("//doc:eac-cpf/doc:control/doc:maintenanceHistory/doc:maintenanceEvent", namespaces=self.ns)
if val and len(val) > 0:
return True
except:
pass
return False
def hasResourceRelations(self):
"""
Determine if the record has one or more resource relations.
"""
cr = self.getCpfRelations()
rr = self.getResourceRelations()
if cr and rr and len(cr) > 0 and len(rr) > 0:
return True
return False
def write(self, Path):
"""
Write the EAC-CPF data to the specified path. Add the metadata,
presentation source URLs as attributes to the eac-cpf node.
"""
# add the metadata and presentation source URLs to the eac-cpf node
root = self.xml.xpath('//doc:eac-cpf', namespaces=self.ns)
metadata = '{' + ESRC_NS + '}metadata'
presentation = '{' + ESRC_NS + '}presentation'
source = '{' + ESRC_NS + '}source'
root[0].set(metadata, self.metadata)
root[0].set(presentation, self.presentation)
root[0].set(source, self.source)
# write the data to the specified path
path = Path + os.sep + self.getFileName()
with open(path, 'w') as outfile:
data = etree.tostring(self.xml, pretty_print=True)
outfile.write(data)
self.log.info("Stored EAC-CPF document " + self.getFileName())
return path
| [
"logging.getLogger",
"Utils.load_from_source",
"DigitalObject.DigitalObject",
"lxml.etree.fromstring",
"Utils.getFileName",
"hashlib.sha1",
"lxml.etree.tostring",
"Utils.fixIncorrectDateEncoding"
] | [((1301, 1320), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1318, 1320), False, 'import logging\n'), ((1523, 1553), 'Utils.load_from_source', 'Utils.load_from_source', (['Source'], {}), '(Source)\n', (1545, 1553), False, 'import Utils\n'), ((1573, 1595), 'lxml.etree.fromstring', 'etree.fromstring', (['data'], {}), '(data)\n', (1589, 1595), False, 'from lxml import etree\n'), ((4063, 4106), 'lxml.etree.tostring', 'etree.tostring', (['self.xml'], {'pretty_print': '(True)'}), '(self.xml, pretty_print=True)\n', (4077, 4106), False, 'from lxml import etree\n'), ((9619, 9649), 'Utils.getFileName', 'Utils.getFileName', (['self.source'], {}), '(self.source)\n', (9636, 9649), False, 'import Utils\n'), ((10774, 10788), 'hashlib.sha1', 'hashlib.sha1', ([], {}), '()\n', (10786, 10788), False, 'import hashlib\n'), ((10804, 10828), 'lxml.etree.tostring', 'etree.tostring', (['self.xml'], {}), '(self.xml)\n', (10818, 10828), False, 'from lxml import etree\n'), ((18807, 18850), 'lxml.etree.tostring', 'etree.tostring', (['self.xml'], {'pretty_print': '(True)'}), '(self.xml, pretty_print=True)\n', (18821, 18850), False, 'from lxml import etree\n'), ((12750, 12790), 'Utils.fixIncorrectDateEncoding', 'Utils.fixIncorrectDateEncoding', (['fromDate'], {}), '(fromDate)\n', (12780, 12790), False, 'import Utils\n'), ((13016, 13054), 'Utils.fixIncorrectDateEncoding', 'Utils.fixIncorrectDateEncoding', (['toDate'], {}), '(toDate)\n', (13046, 13054), False, 'import Utils\n'), ((7009, 7147), 'DigitalObject.DigitalObject', 'DigitalObject', (['self.source', 'self.metadata', 'presentation', 'title', 'abstract', 'localtype'], {'UnitDate': 'unitdate', 'AlternateTitle': 'alternate_title'}), '(self.source, self.metadata, presentation, title, abstract,\n localtype, UnitDate=unitdate, AlternateTitle=alternate_title)\n', (7022, 7147), False, 'from DigitalObject import DigitalObject\n'), ((7277, 7435), 'DigitalObject.DigitalObject', 'DigitalObject', (['self.source', 'self.metadata', 'presentation', 'title', 'abstract', 'localtype'], {'FromDate': 'fromDate', 'ToDate': 'toDate', 'AlternateTitle': 'alternate_title'}), '(self.source, self.metadata, presentation, title, abstract,\n localtype, FromDate=fromDate, ToDate=toDate, AlternateTitle=alternate_title\n )\n', (7290, 7435), False, 'from DigitalObject import DigitalObject\n')] |
import numpy as np
from sklearn.exceptions import NotFittedError
from sklearn.linear_model import SGDClassifier
from sklearn.linear_model.base import LinearClassifierMixin
from sklearn.utils import check_array
import faiss
def _default_index(d):
index = faiss.index_factory(d, "IVF2048,Flat", faiss.METRIC_INNER_PRODUCT)
index.nprobe = 256
return index
class ApproximateClassifierMixin(LinearClassifierMixin):
def decision_function(self, X):
if not hasattr(self, 'coef_') or self.coef_ is None:
raise NotFittedError("This %(name)s instance is not fitted "
"yet" % {'name': type(self).__name__})
self._train_index()
X = check_array(X, accept_sparse=False)
n_features = self.coef_.shape[1]
if X.shape[1] != n_features:
raise ValueError("X has %d features per sample; expecting %d"
% (X.shape[1], n_features))
D, I = self.index_.search(X.astype(np.float32), 1)
return D, I
def _train_index(self):
if not hasattr(self, 'index_'):
self.index_ = _default_index(self.coef_.shape[1])
self.coef_ = np.ascontiguousarray(self.coef_, dtype=np.float32)
self.index_.train(self.coef_)
self.index_.add(self.coef_)
return self
def fast(cls):
assert LinearClassifierMixin in cls.mro(), "Can only speed up linear classifiers"
return type(cls.__name__, (ApproximateClassifierMixin,) + cls.__bases__, dict(cls.__dict__)) | [
"faiss.index_factory",
"sklearn.utils.check_array",
"numpy.ascontiguousarray"
] | [((261, 327), 'faiss.index_factory', 'faiss.index_factory', (['d', '"""IVF2048,Flat"""', 'faiss.METRIC_INNER_PRODUCT'], {}), "(d, 'IVF2048,Flat', faiss.METRIC_INNER_PRODUCT)\n", (280, 327), False, 'import faiss\n'), ((713, 748), 'sklearn.utils.check_array', 'check_array', (['X'], {'accept_sparse': '(False)'}), '(X, accept_sparse=False)\n', (724, 748), False, 'from sklearn.utils import check_array\n'), ((1196, 1246), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['self.coef_'], {'dtype': 'np.float32'}), '(self.coef_, dtype=np.float32)\n', (1216, 1246), True, 'import numpy as np\n')] |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from tests.system.data_sources.deploy_cloudsql.gcloud_context import GCloudContext
import json
import random
import string
DATABASE_TYPES = ("MYSQL_5_7", "POSTGRES_12", "SQLSERVER_2017_STANDARD")
class CloudSQLResourceManager:
def __init__(
self,
project_id,
database_type,
instance_id,
password,
database_id=None,
assign_public_ip=False,
authorized_networks=None,
cpu=None,
memory=None,
enable_bin_logs=True,
already_exists=False,
):
"""Initialize a CloudSQLResourceManager"""
if database_type not in DATABASE_TYPES:
raise ValueError(
f"Invalid database type. Must be of the form {str(DATABASE_TYPES)}"
)
self._project_id = project_id
self._database_type = database_type
self._instance_id = instance_id
self._password = password
self._database_id = database_id
self._assign_public_ip = assign_public_ip
self._authorized_networks = authorized_networks
self._cpu = cpu
self._memory = memory
self._enable_bin_logs = enable_bin_logs
self._already_exists = already_exists
self.db = {}
def describe(self):
"""Returns description of resource manager instance"""
print(
f"Creates a {self._database_type} instance in project {self._project_id} with "
f"database_id: {self._database_id}, instance_id: {self._instance_id}."
)
def setup(self):
"""Creates Cloud SQL instance and database"""
with GCloudContext(self._project_id) as gcloud:
if self._already_exists:
json_describe = gcloud.Run(
"sql", "instances", "describe", self._instance_id, "--format=json"
).decode("utf-8")
sql_describe = json.loads(json_describe)
return sql_describe["ipAddresses"][0].get("ipAddress")
else:
gcloud_create_params = [
"sql",
"instances",
"create",
self._instance_id,
"--region=us-central1",
f"--root-password={self._password}",
f"--database-version={self._database_type}",
]
if self._enable_bin_logs:
gcloud_create_params.append("--enable-bin-log")
if self._assign_public_ip:
gcloud_create_params.append("--assign-ip")
if self._authorized_networks:
gcloud_create_params.append(
f"--authorized-networks={self._authorized_networks}"
)
if self._cpu:
gcloud_create_params.append(f"--cpu={self._cpu}")
if self._memory:
gcloud_create_params.append(f"--memory={self._memory}")
db_info = gcloud.Run(*gcloud_create_params).decode("utf-8")
self.db = dict(
zip(
db_info.strip().split("\n")[0].split(),
db_info.strip().split("\n")[1].split(),
)
)
print("CLOUDSQL_DB Info")
print(self.db)
gcloud.Run(
"sql",
"databases",
"create",
self._database_id,
f"--instance={self._instance_id}",
)
return self.db["PRIMARY_ADDRESS"]
def add_data(self, gcs_data_path):
"""Adds data to Cloud SQL database"""
if self._already_exists:
return
with GCloudContext(self._project_id) as gcloud:
gcloud.Run(
"sql",
"import",
"sql",
self._instance_id,
gcs_data_path,
f"--database={self._database_id}",
"--quiet",
)
def teardown(self):
"""Deletes Cloud SQL instance"""
# If instance is deleted per integration test, instance_id will need a random
# suffix appended since Cloud SQL cannot re-use the same instance name until
# 1 week after deletion.
with GCloudContext(self._project_id) as gcloud:
gcloud.Run("--quiet", "sql", "instances", "delete", self._instance_id)
def _get_random_string(self, length=5):
"""Returns random string
Args:
length (int): Desired length of random string"""
return "".join(random.choice(string.ascii_lowercase) for i in range(length))
| [
"json.loads",
"random.choice",
"tests.system.data_sources.deploy_cloudsql.gcloud_context.GCloudContext"
] | [((2194, 2225), 'tests.system.data_sources.deploy_cloudsql.gcloud_context.GCloudContext', 'GCloudContext', (['self._project_id'], {}), '(self._project_id)\n', (2207, 2225), False, 'from tests.system.data_sources.deploy_cloudsql.gcloud_context import GCloudContext\n'), ((4366, 4397), 'tests.system.data_sources.deploy_cloudsql.gcloud_context.GCloudContext', 'GCloudContext', (['self._project_id'], {}), '(self._project_id)\n', (4379, 4397), False, 'from tests.system.data_sources.deploy_cloudsql.gcloud_context import GCloudContext\n'), ((4946, 4977), 'tests.system.data_sources.deploy_cloudsql.gcloud_context.GCloudContext', 'GCloudContext', (['self._project_id'], {}), '(self._project_id)\n', (4959, 4977), False, 'from tests.system.data_sources.deploy_cloudsql.gcloud_context import GCloudContext\n'), ((2470, 2495), 'json.loads', 'json.loads', (['json_describe'], {}), '(json_describe)\n', (2480, 2495), False, 'import json\n'), ((5248, 5285), 'random.choice', 'random.choice', (['string.ascii_lowercase'], {}), '(string.ascii_lowercase)\n', (5261, 5285), False, 'import random\n')] |
"""
Created on Thursday Mar 26 2020
<NAME>
based on
https://www.kaggle.com/bardor/covid-19-growing-rate
https://github.com/CSSEGISandData/COVID-19
https://github.com/imdevskp
https://www.kaggle.com/yamqwe/covid-19-status-israel
"""
import datetime
import numpy as np
import pandas as pd
import seaborn as sns
import plotly.express as px
import plotly.graph_objs as go
import matplotlib.pyplot as plt
from plotly.subplots import make_subplots
import folium
import plotly
import os
import time
import matplotlib.dates as mdates
plt.style.use('dark_background')
# Write Log file
class MyWriter:
def __init__(self, *writers):
self.writers = writers
def write(self, text):
for w in self.writers:
w.write(text)
def flush(self):
for w in self.writers:
w.flush()
# bar plot
def bar_country_plot(full_data, groupby='Date', inputs=['Confirmed', 'Active', 'Recovered', 'Deaths'],
fname='_cases_bars', log=False):
# Confirmed vs Recovered and Death
if isinstance(full_data.Date.max(), str):
day = datetime.datetime.strptime(full_data.Date.max(), '%m/%d/%y').strftime('%d%m%y')
else:
day = full_data.Date.max().strftime('%d%m%y')
title_string = full_data.State + ' Cases' + ' for' + day
with open(os.path.join(os.getcwd(), time.strftime("%d%m%Y"), day + '_' + full_data.State + '_' + fname + '.html'), 'a') as ff:
fig = px.bar(full_data, x=groupby, y=inputs, color=inputs, template='ggplot2', log_y=True,
title=title_string, hover_name=inputs)
fig.layout.template = 'plotly_dark'
# fig.show()
ff.write(fig.to_html(full_html=False, include_plotlyjs='cdn', default_width='100%'))
f = plt.figure(figsize=(9, 7))
colors = ['blue', 'green', 'cyan', 'magenta', 'cyan', 'red', 'black']
alphas = [1, 0.75, 0.75, 1]
title_string = str()
for cnt in range(len(inputs)):
k = inputs[cnt]
plt.bar(full_data[groupby], full_data[k], label=k, alpha=alphas[cnt], log=log, color=colors[cnt])
title_string = title_string + k + ' vs '
plt.xlabel('Date')
plt.ylabel("Count")
plt.legend(frameon=True, fontsize=12)
plt.title(title_string[:-4], fontsize=30)
f.autofmt_xdate()
plt.show()
plt.savefig(os.path.join(os.getcwd(), day + '_' + str(full_data['Country'].unique().values) + '.png'))
return f
##############################################################################################
# Normalise
def normalise_func(input_data, inputs=['Confirmed', 'Deaths', 'Recovered', 'Active'], name='NormPop',
normaliseTo='Population', factor=1e6, toRound=False):
for cnt in range(len(inputs)):
k = inputs[cnt]
new_name = name+k
input_data.loc[:, new_name] = 0
# Normalise to Population with factor of 1M
input_data.loc[:, new_name] = (input_data[k].values * factor / (input_data[normaliseTo].values + 1e-6)).clip(0)
if toRound:
input_data.loc[input_data.loc[:, new_name] > 1, new_name] = input_data.loc[input_data.loc[:, new_name] > 1, new_name].astype(int)
return input_data
############################################################################################################
# Events
def add_events(input_data, events):
input_data.loc[:, 'Event'] = ''
for cnt in range(events.shape[0]):
input_data.loc[input_data['Date'] == events.Date[cnt], 'Event'] = events.Event[cnt]
return input_data
######################################################################################################
# Growth
def growth_func(input_data, inputs, numDays=1, name='Growth', normalise=True, prediction_Range=1):
for cnt in range(len(inputs)):
k = inputs[cnt]
input_data.loc[:, name+k] = 0
if normalise:
input_data.loc[:, name+k] = ((input_data[k] / input_data[k].shift(numDays)) ** prediction_Range - 1) * 100.0 # .clip(0)
input_data.loc[input_data[k].shift(-numDays) == 0, name+k] = 0
else:
input_data[name+k] = (input_data[k] - input_data[k].shift(numDays)) # .clip(0)
return input_data
############################################################################################################
# add the population and age columns for the given data
def add_pop_age_data(input_data, world_population):
world_pop = None
input_data.loc[:, 'Population'] = np.nan
input_data.loc[:, 'Age'] = np.nan
for val in input_data.Country.unique():
curr = world_population[world_population['Country'] == val]
cntries = input_data.Country == val
try:
input_data.loc[cntries, 'Population'] = curr['Population'].values
input_data.loc[cntries, 'Age'] = curr['Age'].values
if world_pop is not None:
world_pop = pd.concat([world_pop, curr], axis=0, sort=False)
else:
world_pop = curr
except ValueError:
pass
return input_data, world_pop
#########################################################################################
# extract data according to group(Date and State) and if flag add_value is True add the country value to string of State
def group_extract_data(full_data, world_population, groupby=['Date', 'State', 'Country'], inputs=['Confirmed'],
threshould=5000, add_value=True):
sorted_data = full_data.sort_values(groupby)
group = sorted_data[groupby[1]].unique()
latest = sorted_data[sorted_data.Date == sorted_data.Date.max()]
remain_data = latest[latest[inputs] > threshould][groupby[1]].unique()
relevant = sorted_data.copy()
for val in group:
if (remain_data != val).all():
relevant = relevant[relevant[groupby[1]].str.endswith(val) != True]
elif not relevant[groupby[2]].str.endswith(val).any() and add_value:
relevant.loc[relevant[groupby[1]].str.endswith(val), groupby[1]] = \
relevant.loc[relevant[groupby[1]].str.endswith(val), groupby[2]].values[0] + \
'_' + val
relevant, world_pop = add_pop_age_data(relevant, world_population)
return relevant, world_pop
################################################################################################
# Create Sum Table
def create_table(indata, day, inputs=['Confirmed', 'Deaths', 'Recovered', 'Active'],
h_columns=['Current Day', 'Total', 'Max Value'], title_string='', height='100%',
fname='_World_Daily_Situation_Summarise_Table'):
head = indata[inputs].keys().values.tolist()
head.insert(0, h_columns[0])
body = [h_columns[1:]]
for cnt in range(len(inputs)):
body.append(indata[inputs[cnt]].values)
with open(os.path.join(os.getcwd(), time.strftime("%d%m%Y"), day.strftime('%d%m%y') + fname + '.html'), 'a') as f:
fig = go.Figure(data=[go.Table(header=dict(values=head, height=35, align=['left', 'center']),
cells=dict(values=body, height=28, align='left'))])
fig.layout.template = 'plotly_dark'
fig.layout.title = day.strftime('%d/%m/%y ') + title_string
# fig.show()
f.write(fig.to_html(full_html=False, include_plotlyjs='cdn', default_height=height))
########################################################################################################
# Create countries bar
def countries_bar(indata, day, groupby=['Country'], inputs=None, count=30, fname='_World_Daily_Situation'):
if inputs is None:
inputs = indata.keys()[1:].values
with open(os.path.join(os.getcwd(), time.strftime("%d%m%Y"), day.strftime('%d%m%y') + fname + '.html'), 'a') as f:
for cnt in range(len(inputs)-1, -1, -1):
k = inputs[cnt]
cur_data = indata.sort_values(k, ascending=0).reset_index()
cur_data = cur_data[:count]
if k == 'Population' or k == 'Age':
add_str = ''
else:
add_str = ' Cases'
if cnt in range(4):
f_str = 'Total '
else:
f_str = ''
title_string = f_str + k + add_str + ' for ' + day.strftime('%d/%m/%y') + ': ' + str(count) \
+ ' countries from ' + str(indata.shape[0])
fig = px.bar(cur_data, x=groupby[0], y=k, color=groupby[0], text=k, template='ggplot2', log_y=True,
title=title_string) # , hover_name=groupby[0])
fig.layout.template = 'plotly_dark'
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')
# fig.show()
f.write(fig.to_html(full_html=False, include_plotlyjs='cdn'))
# Create World Map
def create_map(data, world_pop, location=[31, 35]):
# Israel location start
# Affected place in world map including Confirm , Active, Deaths and Recovery
worldmap = folium.Map(location=location, zoom_start=4, tiles='Stamen Terrain')
for lat, long, country, state, conf, death, recover, active in zip(data['Lat'], data['Long'], data['Country'],
data['State'], data['Confirmed'], data['Deaths'],
data['Recovered'], data['Active']):
cur_pop = world_pop[world_pop['Country'] == country].reset_index()
if isinstance(state, str) and state != country or not cur_pop.sum().any():
popup_str = str(country) + '<br>' + 'State: ' + str(state) + '<br>' +\
'PositiveCases:' + str(conf) + '<br>' +\
'Active:' + str(int(active)) + '<br>' +\
'Recovered:' + str(int(recover)) + '<br>' +\
'Deaths:' + str(death) + '<br>'
elif np.isnan(cur_pop['Age'][0]):
popup_str = str(country) + ' Population:' + str(cur_pop['Population'][0]) + '<br>'\
'Positive:' + str(conf) + '<br>' + \
'Active:' + str(int(active)) + '<br>' + \
'Recovered:' + str(int(recover)) + '<br>' + \
'Deaths:' + str(death) + '<br>'
else:
popup_str = str(country) + ' Population:' + str(cur_pop['Population'][0]) + \
' Median Age:' + str(int(cur_pop['Age'][0])) + '<br>' + \
'Positive:' + str(conf) + '<br>' + \
'Active:' + str(int(active)) + '<br>' + \
'Recovered:' + str(int(recover)) + '<br>' + \
'Deaths:' + str(death) + '<br>'
folium.CircleMarker([lat, long], radius=5, color='red', popup=popup_str, fill_color='red',
fill_opacity=0.7).add_to(worldmap)
# in IPython Notebook, Jupyter
worldmap
day = data.Date.max().strftime('%d%m%y')
worldmap.save(os.path.join(os.getcwd(), time.strftime("%d%m%Y"), day + '_WorldMap.html'))
###################################################################################################
# bar plot according to cases
def case_groupby_bar(full_data, world_population, groupby=['Date', 'State', 'Country'],
inputs=['Confirmed', 'Recovered', 'Deaths', 'Active'], threshould=[10000, 1000, 100, 10000],
normalise=True, fname='_Cases_WorldData_Bars', factor=1e6):
daily = full_data.sort_values(groupby)
states = daily[groupby[1]].unique()
day = full_data.Date.max().strftime('%d/%m/%y')
array_relevant = []
for cnt in range(len(inputs)):
k = inputs[cnt]
with open(os.path.join(os.getcwd(), time.strftime("%d%m%Y"), full_data.Date.max().strftime('%d%m%y') + '_' + k + fname + '.html'), 'a') as f:
relevant, world_pop = group_extract_data(daily, world_population, groupby, k, threshould[cnt])
array_relevant.append(relevant)
srelevant = relevant.sort_values([groupby[0], groupby[1], k], ascending=[1, 1, 0])
srelevant.Date = [datetime.datetime.strftime(d, '%d/%m/%Y') for d in srelevant.Date]
num_contries = len(relevant[groupby[1]].unique())
title_string = k + ' Cases' + ' over ' + str(threshould[cnt]) + ' for ' + day + ': ' \
+ str(num_contries) + ' items from ' + str(len(states))
fig = px.bar(srelevant, y=groupby[1], x=k, color=groupby[1], template='ggplot2', orientation='h',
log_x=True, title=title_string, hover_name=groupby[1], animation_frame=groupby[0],
animation_group=groupby[1])
fig.layout.template = 'plotly_dark'
# soup = BeautifulSoup(ff)
height = str(np.max([100, num_contries/25 * 100])) + '%'
f.write(fig.to_html(full_html=False, include_plotlyjs='cdn', default_width='100%', default_height=height))
# in IPython Notebook, Jupyter, etc
# fig.show()
# Another way to save
# fig.write_html(os.path.join(os.getcwd(), full_data.Date.max().strftime('%d%m%y') + '_WorldData.html'))
del fig
if normalise:
# Normalise to Population with factor of 1M
norm_srelevant = srelevant.copy()
norm_srelevant.loc[:, k] = (norm_srelevant[k].values * factor /
norm_srelevant['Population'].values).clip(0)
norm_srelevant.loc[norm_srelevant.loc[:, k] > 1, k] = norm_srelevant.loc[norm_srelevant.loc[:, k] > 1, k].astype(int)
num_contries = len(relevant[groupby[1]].unique())
title_string = k + ' Cases' + ' over ' + str(threshould[cnt]) + ' Normalized to ' + str(int(factor/1e6)) \
+ 'M population' + ' for ' + day + ': ' + str(num_contries) + ' items from ' \
+ str(len(states))
fig = px.bar(norm_srelevant, y=groupby[1], x=k, color=groupby[1], template='ggplot2', log_x=True,
orientation='h', title=title_string, hover_name=groupby[1], animation_frame=groupby[0],
animation_group=groupby[1])
fig.layout.template = 'plotly_dark'
height = str(np.max([100, num_contries/25 * 100])) + '%'
f.write(fig.to_html(full_html=False, include_plotlyjs='cdn', default_width='100%', default_height=height))
del fig
# Normalised to inputs[0]: Confirmed
if cnt > 0:
# probability of dying/ recovered if infected by the virus (%)
norm_srelevant = srelevant.copy()
norm_srelevant.loc[:, k] = (norm_srelevant[k].values /
(norm_srelevant[inputs[0]].values + 1e-6)).clip(0)
norm_srelevant.loc[norm_srelevant[k] > 1, k] = 1
num_contries = len(relevant[groupby[1]].unique())
title_string = k + ' Cases' + ' over ' + str(threshould[cnt]) + ' Normalized to ' + inputs[0] \
+ ' for ' + day + ': ' + str(num_contries) + ' items from ' + str(len(states))\
+ '<br>"Probability" of ' + k + ' If Infected by the Virus'
fig = px.bar(norm_srelevant, y=groupby[1], x=k, color=groupby[1], template='ggplot2',
orientation='h', title=title_string, hover_name=groupby[1], animation_frame=groupby[0],
animation_group=groupby[1])
fig.layout.template = 'plotly_dark'
height = str(np.max([100, num_contries/25 * 100])) + '%'
f.write(fig.to_html(full_html=False, include_plotlyjs='cdn', default_width='100%', default_height=height))
del fig
#################################################################################################
# scatter plot
def scatter_country_plot(full_data, inputs=['Confirmed', 'Recovered', 'Deaths', 'Active'], base='Date', prefix='',
fname=' Total Cases ', add_growth_rates=False, num_days_for_rate=14, annotations=None,
add_events_text=False, factor=1.0, mat_plt=False, day=''):
if not day:
if isinstance(full_data.Date.max(), str):
day = datetime.datetime.strptime(full_data.Date.max(), '%m/%d/%y').strftime('%d%m%y')
else:
day = full_data.Date.max().strftime('%d/%m/%y')
try:
not_country = 0
country = full_data['Country'].unique()
state = full_data['State'].unique()
except:
not_country = 1
if not_country or country.shape[0] > 1:
title_string = day + fname + 'Various Cases'
save_string = full_data.Date.max().strftime('%d%m%y') + fname + '.png'
elif state != country:
title_string = country[0] + ' -- ' + state[0] + ' - ' + day + ' ' + fname
save_string = full_data.Date.max().strftime('%d%m%y') + '_' + country[0] + '_' + state[0] + '_' +\
fname.replace(' ', '_') +'.png'
else:
title_string = state[0] + ' - ' + day + ' - ' + fname
save_string = full_data.Date.max().strftime('%d%m%y') + '_' + state[0] + '_' + fname.replace(' ', '_') +'.png'
# colors = plotly.colors.DEFAULT_PLOTLY_COLORS
colors = plotly.colors.qualitative.Light24
if '#FED4C4' in colors:
colors.remove('#FED4C4')
fig = make_subplots(rows=1, cols=2, subplot_titles=("Linear Plot", "Log Plot"))
fig_cnt = -1
customdata = None
for cnt in range(len(inputs)):
case_k = inputs[cnt]
k = prefix + case_k
y = (full_data[k] * factor).fillna(0)
# y[np.isinf(y)] = 0
if base != 'Date':
customdata = full_data.Date
if add_events_text:
trace = go.Scatter(x=full_data[base], y=y, mode="markers+lines+text", name=case_k, customdata=customdata,
text=full_data.Event, marker=dict(size=8, color=colors[cnt]))
else:
trace = go.Scatter(x=full_data[base], y=y, mode="markers+lines", name=case_k, customdata=customdata,
marker=dict(size=8, color=colors[cnt]))
fig.add_trace(trace, row=1, col=1)
fig_cnt +=1
fig.add_trace(trace, row=1, col=2)
fig_cnt += 1
if fig_cnt % 2 == 1:
fig.data[fig_cnt-1].update(showlegend=False)
fig.update_traces(mode="markers+lines", hovertemplate=None)
if base != 'Date':
fig.update_traces(hovertemplate='%{y}<br>%{customdata| %_d %b %Y}')
if add_growth_rates:
len_rate = full_data[k].shape[0]
grows_rate = full_data['Growth' + base].fillna(0).values / 100.0
grows_rate[np.isinf(grows_rate)] = 0
vec = np.arange(0, round(len_rate*1/3))
one_third = grows_rate[vec].mean()
if one_third > 0:
grow_one_third = one_third * full_data[base] + full_data[k][vec[0]] * factor
add_trace1 = go.Scatter(x=full_data[base], y=grow_one_third, mode="lines",
name='Linear estimation: ' + str(full_data[k][vec[0]]) + ' + '
+ str(round(one_third, 3)) + '*' + base + '<br>' + str(round(one_third, 3))
+ ' - estim on first onethird of ' + base,
line=dict(dash="dash", width=3))
fig.add_trace(add_trace1, row=1, col=1)
fig.add_trace(add_trace1, row=1, col=2)
# estimation for two last weeks
vec = np.arange(np.max([1, len_rate-num_days_for_rate]), len_rate)
last_week = (full_data[k][vec[-1]] - full_data[k][vec[0]]) \
/ np.max([1e-6, (full_data[base][vec[-1]] - full_data[base][vec[0]])])
if not np.isinf(last_week) and last_week > 0:
bias = int(full_data[k][vec[-1]] - full_data[base][vec[-1]] * last_week)
grow_one_third = last_week * full_data[base] + bias * factor
add_trace2 = go.Scatter(x=full_data[base][round(len_rate*1/3):], y=grow_one_third[round(len_rate*1/3):],
mode="lines", name='Linear estimation: ' + str(bias) + ' + '
+ str(round(last_week, 3)) + '*' + base + '<br>'
+ str(round(last_week, 3)) + ' - estim on '
+ str(num_days_for_rate) + ' last days from ' + base,
line=dict(dash="dash", width=3))
fig.add_trace(add_trace2, row=1, col=1)
fig.add_trace(add_trace2, row=1, col=2)
fig.update_yaxes(range=[full_data[k][0], full_data[k][len_rate-1]], row=1, col=1)
if annotations is not None:
fig.update_annotations(annotations)
fig.update_layout(template='plotly_dark', hovermode="x", title=title_string,
yaxis=dict(title=fname), xaxis=dict(title=base), yaxis2=dict(title=fname, type='log'),
xaxis2=dict(title=base))
# fig.show()
if mat_plt:
fig_mat, ax = plt.subplots(figsize=(8, 6))
colors = ['blue', 'green', 'yellow', 'magenta', 'cyan', 'red', 'black']
max_values = []
for cnt in range(len(inputs)):
case_k = inputs[cnt]
k = prefix + case_k
full_data[k] = full_data[k].fillna(0)
ax = sns.scatterplot(x=base, y=k, data=full_data, color=colors[cnt])
plt.plot(full_data[base], full_data[k], zorder=1, color=colors[cnt], label=k)
if not np.isinf(max(full_data[k])):
max_values.append(max(full_data[k]))
ax.set_xlim([full_data['Date'].iloc[0], full_data['Date'].iloc[-1] + datetime.timedelta(days=1)])
if max(full_data[prefix + inputs[0]]) > 1:
max_value = max(max_values) + np.diff(full_data[k]).max()
min_value = -1
else:
max_value = max(max_values) + np.diff(full_data[k]).max()
min_value = 0
ax.set_ylim([min_value, max_value])
plt.legend(frameon=True, fontsize=12)
plt.grid()
plt.ylabel(fname)
plt.title(title_string, fontsize=16)
fig_mat.autofmt_xdate()
plt.savefig(os.path.join(os.getcwd(), save_string))
return fig
###################################################################################################################
# country analysis script
def country_analysis(clean_db, world_pop, country='China', state='Hubei', plt=False, fromFirstConfirm=False,
events=None, num_days_for_rate=14):
if isinstance(clean_db.Date.max(), str):
day = datetime.datetime.strptime(clean_db.Date.max(), '%m%d%y').strftime('%d%m%y')
else:
day = clean_db.Date.max().strftime('%d%m%y')
data = clean_db[clean_db['Country'] == country]
data = data.sort_values(by='Date', ascending=1)
today = data.Date.iloc[-1].strftime('%d.%m.%y')
if state:
data = data[data['State'] == state]
elif (data.State.unique() == country).any():
data = data[data['State'] == country]
else:
data = data.groupby(['Date', 'Country']).sum()
if fromFirstConfirm:
data = (data.loc[data.loc[:, 'Confirmed'] > 0, :]).reset_index()
else:
data = data.reset_index()
data['Active'] = (data['Confirmed'] - data['Recovered'] - data['Deaths']).astype(int) # .clip(0)
inputs = ['Confirmed', 'Recovered', 'Deaths', 'Active']
data = growth_func(data, inputs, numDays=1, name='New', normalise=False)
data = growth_func(data, inputs, numDays=1, name='Growth', normalise=True)
cur_pop_data = world_pop[world_pop['Country'] == country].reset_index()
data.loc[:, 'Population'] = cur_pop_data['Population'].values[0]
data.loc[:, 'Age'] = cur_pop_data['Age'].values[0]
data = normalise_func(data, name='NormPop', normaliseTo='Population', factor=1e6, toRound=True)
data = normalise_func(data, inputs=['Deaths', 'Recovered', 'Active'], name='NormConfirm', normaliseTo='Confirmed',
factor=1, toRound=True)
add_event = False
if events is not None:
data = add_events(data, events)
add_event = True
# Growth Rate
# last_days = data['Confirmed'].shift()[-3:]
# gr = data['Confirmed'][-3:] / last_days
# gr[last_days == 0] = 0
growth_rate = (data['Confirmed'][-3:] / data['Confirmed'].shift()[-3:]).fillna(0).mean()
growth_death = (data['Deaths'][-3:] / data['Deaths'].shift()[-3:]).fillna(0).mean()
growth_recovered = (data['Recovered'][-3:] / data['Recovered'].shift()[-3:]).fillna(0).mean()
prediction_cnfm = 0
prediction_dth = 0
prediction_rcv = 0
expected_cnfrm = 0
expected_dth = 0
expected_rcv = 0
if growth_rate != 0 and growth_rate != 1 and not np.isinf(growth_rate):
prediction_cnfm = (np.log(2)/np.log(growth_rate)).clip(0).astype(int)
expected_cnfrm = (data['Confirmed'].iloc[-1] * growth_rate).astype(int)
if growth_death != 0 and growth_death != 1 and not np.isinf(growth_death):
prediction_dth = (np.log(2)/np.log(growth_death)).clip(0).astype(int)
expected_dth = (data['Deaths'].iloc[-1] * growth_death).astype(int)
if growth_recovered != 0 and growth_recovered != 1 and not np.isinf(growth_recovered):
prediction_rcv = (np.log(2)/np.log(growth_recovered)).clip(0).astype(int)
expected_rcv = (data['Recovered'].iloc[-1] * growth_recovered).astype(int)
print('\n', country)
print('Mean Growth Rate for 3 last days : Confirmed %.2f%%, Deaths %.2f%%, Recovered %.2f%%'
% (round((growth_rate-1)*100.0, 2), round((growth_death-1)*100.0, 2), round((growth_recovered-1)*100.0, 2)))
print('Today\'s %s [confirmed, death, recovered] : %d, %d, %d ' % (today, data['Confirmed'].iloc[-1],
data['Deaths'].iloc[-1], data['Recovered'].iloc[-1]))
print('Expected Tomorrow [confirmed, death, recovered] : %d, %d, %d ' %
(expected_cnfrm, expected_dth, expected_rcv))
# logarithm of x to the given base, calculated as log(x)/log(base)
days = [prediction_cnfm, prediction_dth, prediction_rcv]
print('Twice the number of cases given the current growth rate in %s days' % days)
annot = dict(xref='paper', yref='paper', x=0.2, y=0.95, align='left', font=dict(size=12),
text='Mean Growth Rate for 3 last days: Confirmed ' + str(round((growth_rate-1)*100.0, 2))
+ '%, Deaths ' + str(round((growth_death-1)*100.0, 2)) + '%, Recovered '
+ str(round((growth_recovered-1)*100.0, 2))
+ '%<br>Today\'s ' + str(today) + ' [confirmed, death, recovered] : '
+ str(data['Confirmed'].iloc[-1]) + ' ' + str(data['Deaths'].iloc[-1]) + ' '
+ str(data['Recovered'].iloc[-1].astype(int))
+ '<br>Expected Tomorrow [confirmed, death, recovered] : '
+ str(expected_cnfrm) + ' ' + str(expected_dth) + ' ' + str(expected_rcv)
+ '<br>Twice the number of cases given the current growth rate in '
+ str(prediction_cnfm) + ' ' + str(prediction_dth) + ' ' + str(prediction_rcv) + ' days')
if plt:
if country[-1] == '*':
country = country[:-1]
with open(os.path.join(os.getcwd(), time.strftime("%d%m%Y"), day + '_' + country + '_Various_Cases.html'), 'a') as f:
fsc1 = scatter_country_plot(data, add_events_text=add_event)
fsc2 = scatter_country_plot(data, prefix='New', fname='Daily New Cases', add_events_text=add_event)
fsc3 = scatter_country_plot(data, prefix='NormPop', fname='Total Cases Normalised for 1M Population',
add_events_text=add_event)
fsc4 = scatter_country_plot(data, inputs=['Deaths', 'Recovered', 'Active'], prefix='NormConfirm',
factor=100.0, add_events_text=add_event,
fname='Normalised for Total Confirmed Cases - '
'Probability to Case If infected by the virus (%)')
fsc5 = scatter_country_plot(data, prefix='Growth', add_events_text=add_event,
fname='Growing rate in % a day', annotations=annot)
fsc6 = scatter_country_plot(data, inputs=['Deaths'], add_events_text=add_event, base='Recovered',
add_growth_rates=True, num_days_for_rate=num_days_for_rate,
fname='Cases Ratio: Deaths vs Recovered')
f.write(fsc1.to_html(full_html=False, include_plotlyjs='cdn'))
f.write(fsc2.to_html(full_html=False, include_plotlyjs='cdn'))
f.write(fsc3.to_html(full_html=False, include_plotlyjs='cdn'))
f.write(fsc4.to_html(full_html=False, include_plotlyjs='cdn'))
f.write(fsc5.to_html(full_html=False, include_plotlyjs='cdn'))
f.write(fsc6.to_html(full_html=False, include_plotlyjs='cdn'))
return data
###########################################################################################################
# plot with threshoulds on cases
def case_thresh_plot(full_data, threshDays=[10, 10], inputs=['Confirmed', 'Deaths'], prefix='', ref_cntry='Israel',
base='Date', factor=1.0, fname=' Corona virus situation since the ', annotations=[], log=False,
add_growth_rates=False, threshValues=[1, 1]):
if isinstance(full_data.Date.max(), str):
day = datetime.datetime.strptime(full_data.Date.max(), '%m/%d/%y').strftime('%d%m%y')
else:
day = full_data.Date.max().strftime('%d%m%y')
countries = full_data.Country.unique()
today = full_data.Date.iloc[-1].strftime('%d.%m.%y')
title_string = full_data.Date.max().strftime('%d/%m/%y') + ' - ' + str(len(countries)) + ' ' + fname
colors = plotly.colors.qualitative.Light24
if '#FED4C4' in colors:
colors.remove('#FED4C4')
ref_db = full_data[full_data.Country == ref_cntry]
ref_db = ref_db.sort_values([base])
fig = make_subplots(rows=1, cols=2, subplot_titles=(prefix + ' ' + inputs[0] + ' Cases',
prefix + ' ' + inputs[1] + ' Cases'))
showlegend = True
for cnt in range(len(inputs)):
case_k = inputs[cnt]
k = prefix + case_k
threshDay = threshDays[cnt]
threshValue = threshValues[cnt]
max_value = []
customdata = None
if cnt % 2:
showlegend = False
for cntry in range(len(countries)):
curr = full_data[full_data.Country == countries[cntry]]
thresh_data = curr.loc[curr.loc[:, k] * factor > threshValue, :]
thresh_data = thresh_data[threshDay:]
if thresh_data.values.any():
thresh_data = thresh_data.sort_values([base, k])
max_value.append(thresh_data[k].max())
customdata = thresh_data[base]
since_days = np.arange(0, thresh_data.shape[0])
trace = go.Scatter(x=since_days, y=thresh_data[k], mode="markers+lines", name=countries[cntry],
marker=dict(size=10, color=colors[cntry]), showlegend=showlegend, customdata=customdata)
fig.add_trace(trace, row=1, col=cnt+1)
fig.update_traces(hovertemplate=None)
fig.update_traces(hovertemplate='%{y}<br>%{customdata| %_d %b %Y}')
if add_growth_rates:
for cnt in range(len(inputs)):
case_k = inputs[cnt]
k = prefix + case_k
threshDay = threshDays[cnt]
threshValue = threshValues[cnt]
showlegend = True
if cnt % 2:
showlegend = False
threshed_ref_db = ref_db.loc[ref_db.loc[:, k] * factor > threshValue, :]
threshed_ref_db = threshed_ref_db[threshDay:]
if threshed_ref_db.values.any():
if 'Growth' + k not in threshed_ref_db.keys():
threshed_ref_db = growth_func(threshed_ref_db, [k])
grows_rate = threshed_ref_db['Growth' + k].fillna(0).values / 100.0 + 1
grows_rate[np.isinf(grows_rate)] = 0
growth_rate_mean = grows_rate[-3:].mean()
else:
threshed_ref_db = thresh_data.copy()
growth_rate_mean = (threshed_ref_db[k][-3:] / threshed_ref_db[k].shift()[-3:]).fillna(0).mean() # .clip(0)
if growth_rate_mean != 0 and growth_rate_mean != 1 and not np.isinf(growth_rate_mean) and not np.isnan(growth_rate_mean):
gr_days = (np.log(2) / np.log(growth_rate_mean)).astype(int)
prev_value = threshed_ref_db[k].iloc[-2].astype(int)
next_value = (threshed_ref_db[k].iloc[-1] * growth_rate_mean).astype(int)
else:
gr_days = 0
prev_value = 0
next_value = 0
growth_rate_mean = 0
if gr_days:
annot = dict(xref='paper', yref='paper', x=0.2 + cnt*0.55, y=0.87, align='left', font=dict(size=13),
text='Mean Growth Rate for 3 last days in ' + threshed_ref_db.Country.values[0] + ' : '
+ str(round((growth_rate_mean - 1) * 100.0, 2))
+ '%<br>Today\'s ' + str(today) + ' ' + inputs[cnt] + ': ' + str(prev_value)
+ '<br>Expected Tomorrow: ' + str(next_value)
+ '<br>Twice the number of cases given the current growth rate in ' + str(gr_days)
+ ' days')
fig.add_annotation(annot)
num_dates = threshed_ref_db[base].shape[0]
if num_dates:
since_days = np.arange(0, threshed_ref_db.shape[0])
max_value.append(threshed_ref_db[k].max())
thresh = threshed_ref_db[k].values[0]
grow15 = np.clip(thresh * (1.15 ** (np.linspace(1, num_dates, num_dates, endpoint=True))), 0, max(max_value)).astype(int)
fig.add_trace(go.Scatter(x=since_days, y=grow15, mode="lines", name='Grows 15% a day',
line=dict(dash="dash", width=3, color=colors[cntry+1]), showlegend=showlegend),
row=1, col=cnt+1) # threshed_ref_db[base]
grow08 = np.clip(thresh * (1.08 ** (np.linspace(1, num_dates, num_dates, endpoint=True))), 0, max(max_value)).astype(int)
fig.add_trace(go.Scatter(x=since_days, y=grow08, mode="lines", name='Grows 8% a day',
line=dict(dash="dashdot", width=3, color=colors[cntry+2]), showlegend=showlegend),
row=1, col=cnt+1)
if growth_rate_mean:
cur_value = threshed_ref_db[k].values[-3]
if cur_value > 0.8*max(max_value):
cur_value = min(max_value)
grow_cur = np.clip(cur_value * (growth_rate_mean ** (np.linspace(1, num_dates, num_dates, endpoint=True))), 0, max(max_value)).astype(int)
gr = int((growth_rate_mean - 1) * 100.0)
fig.add_trace(go.Scatter(x=since_days, y=grow_cur, mode="lines",
name='Grows ' + str(gr) + '% a day from last 3 days', showlegend=showlegend,
line=dict(dash="dot", width=3, color=colors[cntry+3])), row=1, col=cnt+1)
xaxis2 = 'Days since the ' + str(threshDays[1]) + 'th from the ' + str(threshValues[1]) + 'th case value'
xaxis1 = 'Days since the ' + str(threshDays[0]) + 'th from the ' + str(threshValues[0]) + 'th case value'
if log:
fig.update_layout(hovermode="x", title=title_string, template='plotly_dark',
xaxis=dict(title=xaxis1), xaxis2=dict(title=xaxis2),
yaxis=dict(title=prefix + ' ' + inputs[0] + ' Cases', type='log'),
yaxis2=dict(title=prefix + ' ' + inputs[1] + ' Cases', type='log'))
else:
fig.update_layout(hovermode="x", title=title_string, template='plotly_dark',
xaxis=dict(title=xaxis1), xaxis2=dict(title=xaxis2),
yaxis=dict(title=prefix + ' ' + inputs[0] + ' Cases'),
yaxis2=dict(title=prefix + ' ' + inputs[1] + ' Cases'))
return fig
###################################################################################################################
# line plot
def line_country_plot(full_data, inputs=['Confirmed', 'Recovered', 'Deaths', 'Active'], base='Date', prefixes=[''],
fname=' Total Cases ', add_growth_rates=False, annotations=None, add_events_text=False,
factor=1.0, mat_plt=False, day=''):
if not day:
if isinstance(full_data.Date.max(), str):
day = datetime.datetime.strptime(full_data.Date.max(), '%m/%d/%y').strftime('%d%m%y')
else:
day = full_data.Date.max().strftime('%d/%m/%y')
try:
not_country = 0
country = full_data['Country'].unique()
state = full_data['State'].unique()
except:
not_country = 1
if not_country or country.shape[0] > 1:
title_string = day + fname + 'Various Cases'
save_string = full_data.Date.max().strftime('%d%m%y') + fname + '.png'
elif state != country:
title_string = country[0] + ' -- ' + state[0] + ' - ' + day + ' ' + fname
save_string = full_data.Date.max().strftime('%d%m%y') + '_' + country[0] + '_' + state[0] + '_' +\
fname.replace(' ', '_') +'.png'
else:
title_string = state[0] + ' - ' + day + ' - ' + fname
save_string = full_data.Date.max().strftime('%d%m%y') + '_' + state[0] + '_' + fname.replace(' ', '_') +'.png'
fig = make_subplots(rows=1, cols=2, subplot_titles=("Linear Plot", "Log Plot"))
fig_cnt = -1
customdata = None
for pr_cnt in range(len(prefixes)):
prefix = prefixes[pr_cnt]
if prefix:
colors = ['blue', 'yellow', 'green', 'magenta', 'cyan', 'red', 'black']
else:
colors = plotly.colors.DEFAULT_PLOTLY_COLORS
for cnt in range(len(inputs)):
case_k = inputs[cnt]
k = prefix + case_k
if k in full_data.keys():
y = (full_data[k] * factor).fillna(0)
# y[np.isinf(y)] = 0
if base != 'Date':
customdata = full_data.Date
if add_events_text:
trace = go.Scatter(x=full_data[base], y=y, mode="markers+lines+text", name=k, customdata=customdata,
text=full_data.Event, marker=dict(size=4, color=colors[cnt]))
else:
trace = go.Scatter(x=full_data[base], y=y, mode="markers+lines", name=k, customdata=customdata,
marker=dict(size=4, color=colors[cnt]))
fig.add_trace(trace, row=1, col=1)
fig_cnt +=1
fig.add_trace(trace, row=1, col=2)
fig_cnt += 1
if fig_cnt % 2 == 1:
fig.data[fig_cnt-1].update(showlegend=False)
fig.update_traces(mode="markers+lines", hovertemplate=None)
if base != 'Date':
fig.update_traces(hovertemplate='%{y}<br>%{customdata| %_d %b %Y}')
if add_growth_rates:
grows_rate = full_data['Growth' + base].fillna(0).values / 100.0
grows_rate[np.isinf(grows_rate)] = 0
len_rate = len(grows_rate)
vec = np.arange(0, round(len_rate*1/3))
one_third = grows_rate[vec].mean()
if one_third > 0:
grow_one_third = one_third * full_data[base] + full_data[k][vec[0]] * factor
add_trace1 = go.Scatter(x=full_data[base], y=grow_one_third, mode="lines",
name='Linear estimation: ' + str(full_data[k][vec[0]]) + ' + '
+ str(round(one_third, 2)) + '*' + base + '<br>' + str(round(one_third, 2))
+ ' - estim on first onethird of ' + base,
line=dict(dash="dash", width=3))
fig.add_trace(add_trace1, row=1, col=1)
fig.add_trace(add_trace1, row=1, col=2)
grows_rate = full_data['GrowthConfirmed'].fillna(0).values / 100.0
grows_rate[np.isinf(grows_rate)] = 0
len_rate = len(grows_rate)
vec = np.arange(round(0.9*len_rate), len_rate)
one_third = grows_rate[vec].mean()
if one_third > 0:
grow_one_third = one_third * full_data[base] + full_data[k][vec[0]-round(0.1*len_rate)] * factor
add_trace2 = go.Scatter(x=full_data[base][round(len_rate*1/3):], y=grow_one_third[round(len_rate*1/3):],
mode="lines", name='Linear estimation: '
+ str(full_data[k][vec[0]-round(0.1*len_rate)]) + ' + '
+ str(round(one_third, 2)) + '*' + base + '<br>'
+ str(round(one_third, 2)) + ' - estim on 0.1 last from Confirmed',
line=dict(dash="dash", width=3))
fig.add_trace(add_trace2, row=1, col=1)
fig.add_trace(add_trace2, row=1, col=2)
fig.update_yaxes(range=[full_data[k][0], full_data[k][len_rate-1]], row=1, col=1)
if annotations is not None:
fig.update_annotations(annotations)
fig.update_layout(template='plotly_dark', hovermode="x", title=title_string,
yaxis=dict(title=fname), xaxis=dict(title=base), yaxis2=dict(title=fname, type='log'),
xaxis2=dict(title=base))
if mat_plt:
fig_mat, ax = plt.subplots(figsize=(8, 6))
colors = ['blue', 'green', 'yellow', 'magenta', 'cyan', 'red', 'black']
max_values = []
for cnt in range(len(inputs)):
case_k = inputs[cnt]
k = prefix + case_k
full_data[k] = full_data[k].fillna(0)
ax = sns.scatterplot(x=base, y=k, data=full_data, color=colors[cnt])
plt.plot(full_data[base], full_data[k], zorder=1, color=colors[cnt], label=k)
if not np.isinf(max(full_data[k])):
max_values.append(max(full_data[k]))
ax.set_xlim([full_data['Date'].iloc[0], full_data['Date'].iloc[-1] + datetime.timedelta(days=1)])
if max(full_data[prefix + inputs[0]]) > 1:
max_value = max(max_values) + np.diff(full_data[k]).max()
min_value = -1
else:
max_value = max(max_values) + np.diff(full_data[k]).max()
min_value = 0
ax.set_ylim([min_value, max_value])
plt.legend(frameon=True, fontsize=12)
plt.grid()
plt.ylabel(fname)
plt.title(title_string, fontsize=16)
fig_mat.autofmt_xdate()
plt.savefig(os.path.join(os.getcwd(), save_string))
return fig
###################################################################################################################
| [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"numpy.log",
"seaborn.scatterplot",
"datetime.timedelta",
"folium.CircleMarker",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.style.use",
"numpy.diff",
"folium.Map",
"numpy.max",
"numpy.linspa... | [((554, 586), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""dark_background"""'], {}), "('dark_background')\n", (567, 586), True, 'import matplotlib.pyplot as plt\n'), ((1813, 1839), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 7)'}), '(figsize=(9, 7))\n', (1823, 1839), True, 'import matplotlib.pyplot as plt\n'), ((2201, 2219), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Date"""'], {}), "('Date')\n", (2211, 2219), True, 'import matplotlib.pyplot as plt\n'), ((2225, 2244), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Count"""'], {}), "('Count')\n", (2235, 2244), True, 'import matplotlib.pyplot as plt\n'), ((2250, 2287), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'frameon': '(True)', 'fontsize': '(12)'}), '(frameon=True, fontsize=12)\n', (2260, 2287), True, 'import matplotlib.pyplot as plt\n'), ((2293, 2334), 'matplotlib.pyplot.title', 'plt.title', (['title_string[:-4]'], {'fontsize': '(30)'}), '(title_string[:-4], fontsize=30)\n', (2302, 2334), True, 'import matplotlib.pyplot as plt\n'), ((2363, 2373), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2371, 2373), True, 'import matplotlib.pyplot as plt\n'), ((9303, 9370), 'folium.Map', 'folium.Map', ([], {'location': 'location', 'zoom_start': '(4)', 'tiles': '"""Stamen Terrain"""'}), "(location=location, zoom_start=4, tiles='Stamen Terrain')\n", (9313, 9370), False, 'import folium\n'), ((18121, 18194), 'plotly.subplots.make_subplots', 'make_subplots', ([], {'rows': '(1)', 'cols': '(2)', 'subplot_titles': "('Linear Plot', 'Log Plot')"}), "(rows=1, cols=2, subplot_titles=('Linear Plot', 'Log Plot'))\n", (18134, 18194), False, 'from plotly.subplots import make_subplots\n'), ((31423, 31547), 'plotly.subplots.make_subplots', 'make_subplots', ([], {'rows': '(1)', 'cols': '(2)', 'subplot_titles': "(prefix + ' ' + inputs[0] + ' Cases', prefix + ' ' + inputs[1] + ' Cases')"}), "(rows=1, cols=2, subplot_titles=(prefix + ' ' + inputs[0] +\n ' Cases', prefix + ' ' + inputs[1] + ' Cases'))\n", (31436, 31547), False, 'from plotly.subplots import make_subplots\n'), ((39469, 39542), 'plotly.subplots.make_subplots', 'make_subplots', ([], {'rows': '(1)', 'cols': '(2)', 'subplot_titles': "('Linear Plot', 'Log Plot')"}), "(rows=1, cols=2, subplot_titles=('Linear Plot', 'Log Plot'))\n", (39482, 39542), False, 'from plotly.subplots import make_subplots\n'), ((1495, 1622), 'plotly.express.bar', 'px.bar', (['full_data'], {'x': 'groupby', 'y': 'inputs', 'color': 'inputs', 'template': '"""ggplot2"""', 'log_y': '(True)', 'title': 'title_string', 'hover_name': 'inputs'}), "(full_data, x=groupby, y=inputs, color=inputs, template='ggplot2',\n log_y=True, title=title_string, hover_name=inputs)\n", (1501, 1622), True, 'import plotly.express as px\n'), ((2046, 2148), 'matplotlib.pyplot.bar', 'plt.bar', (['full_data[groupby]', 'full_data[k]'], {'label': 'k', 'alpha': 'alphas[cnt]', 'log': 'log', 'color': 'colors[cnt]'}), '(full_data[groupby], full_data[k], label=k, alpha=alphas[cnt], log=\n log, color=colors[cnt])\n', (2053, 2148), True, 'import matplotlib.pyplot as plt\n'), ((22081, 22109), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (22093, 22109), True, 'import matplotlib.pyplot as plt\n'), ((23078, 23115), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'frameon': '(True)', 'fontsize': '(12)'}), '(frameon=True, fontsize=12)\n', (23088, 23115), True, 'import matplotlib.pyplot as plt\n'), ((23125, 23135), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (23133, 23135), True, 'import matplotlib.pyplot as plt\n'), ((23145, 23162), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['fname'], {}), '(fname)\n', (23155, 23162), True, 'import matplotlib.pyplot as plt\n'), ((23172, 23208), 'matplotlib.pyplot.title', 'plt.title', (['title_string'], {'fontsize': '(16)'}), '(title_string, fontsize=16)\n', (23181, 23208), True, 'import matplotlib.pyplot as plt\n'), ((43865, 43893), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (43877, 43893), True, 'import matplotlib.pyplot as plt\n'), ((44862, 44899), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'frameon': '(True)', 'fontsize': '(12)'}), '(frameon=True, fontsize=12)\n', (44872, 44899), True, 'import matplotlib.pyplot as plt\n'), ((44909, 44919), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (44917, 44919), True, 'import matplotlib.pyplot as plt\n'), ((44929, 44946), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['fname'], {}), '(fname)\n', (44939, 44946), True, 'import matplotlib.pyplot as plt\n'), ((44956, 44992), 'matplotlib.pyplot.title', 'plt.title', (['title_string'], {'fontsize': '(16)'}), '(title_string, fontsize=16)\n', (44965, 44992), True, 'import matplotlib.pyplot as plt\n'), ((2406, 2417), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2415, 2417), False, 'import os\n'), ((8615, 8733), 'plotly.express.bar', 'px.bar', (['cur_data'], {'x': 'groupby[0]', 'y': 'k', 'color': 'groupby[0]', 'text': 'k', 'template': '"""ggplot2"""', 'log_y': '(True)', 'title': 'title_string'}), "(cur_data, x=groupby[0], y=k, color=groupby[0], text=k, template=\n 'ggplot2', log_y=True, title=title_string)\n", (8621, 8733), True, 'import plotly.express as px\n'), ((10238, 10265), 'numpy.isnan', 'np.isnan', (["cur_pop['Age'][0]"], {}), "(cur_pop['Age'][0])\n", (10246, 10265), True, 'import numpy as np\n'), ((11359, 11370), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (11368, 11370), False, 'import os\n'), ((11372, 11395), 'time.strftime', 'time.strftime', (['"""%d%m%Y"""'], {}), "('%d%m%Y')\n", (11385, 11395), False, 'import time\n'), ((12838, 13048), 'plotly.express.bar', 'px.bar', (['srelevant'], {'y': 'groupby[1]', 'x': 'k', 'color': 'groupby[1]', 'template': '"""ggplot2"""', 'orientation': '"""h"""', 'log_x': '(True)', 'title': 'title_string', 'hover_name': 'groupby[1]', 'animation_frame': 'groupby[0]', 'animation_group': 'groupby[1]'}), "(srelevant, y=groupby[1], x=k, color=groupby[1], template='ggplot2',\n orientation='h', log_x=True, title=title_string, hover_name=groupby[1],\n animation_frame=groupby[0], animation_group=groupby[1])\n", (12844, 13048), True, 'import plotly.express as px\n'), ((22392, 22455), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': 'base', 'y': 'k', 'data': 'full_data', 'color': 'colors[cnt]'}), '(x=base, y=k, data=full_data, color=colors[cnt])\n', (22407, 22455), True, 'import seaborn as sns\n'), ((22469, 22546), 'matplotlib.pyplot.plot', 'plt.plot', (['full_data[base]', 'full_data[k]'], {'zorder': '(1)', 'color': 'colors[cnt]', 'label': 'k'}), '(full_data[base], full_data[k], zorder=1, color=colors[cnt], label=k)\n', (22477, 22546), True, 'import matplotlib.pyplot as plt\n'), ((25917, 25938), 'numpy.isinf', 'np.isinf', (['growth_rate'], {}), '(growth_rate)\n', (25925, 25938), True, 'import numpy as np\n'), ((26156, 26178), 'numpy.isinf', 'np.isinf', (['growth_death'], {}), '(growth_death)\n', (26164, 26178), True, 'import numpy as np\n'), ((26400, 26426), 'numpy.isinf', 'np.isinf', (['growth_recovered'], {}), '(growth_recovered)\n', (26408, 26426), True, 'import numpy as np\n'), ((44176, 44239), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': 'base', 'y': 'k', 'data': 'full_data', 'color': 'colors[cnt]'}), '(x=base, y=k, data=full_data, color=colors[cnt])\n', (44191, 44239), True, 'import seaborn as sns\n'), ((44253, 44330), 'matplotlib.pyplot.plot', 'plt.plot', (['full_data[base]', 'full_data[k]'], {'zorder': '(1)', 'color': 'colors[cnt]', 'label': 'k'}), '(full_data[base], full_data[k], zorder=1, color=colors[cnt], label=k)\n', (44261, 44330), True, 'import matplotlib.pyplot as plt\n'), ((1376, 1387), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1385, 1387), False, 'import os\n'), ((1389, 1412), 'time.strftime', 'time.strftime', (['"""%d%m%Y"""'], {}), "('%d%m%Y')\n", (1402, 1412), False, 'import time\n'), ((5038, 5086), 'pandas.concat', 'pd.concat', (['[world_pop, curr]'], {'axis': '(0)', 'sort': '(False)'}), '([world_pop, curr], axis=0, sort=False)\n', (5047, 5086), True, 'import pandas as pd\n'), ((7023, 7034), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (7032, 7034), False, 'import os\n'), ((7036, 7059), 'time.strftime', 'time.strftime', (['"""%d%m%Y"""'], {}), "('%d%m%Y')\n", (7049, 7059), False, 'import time\n'), ((7878, 7889), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (7887, 7889), False, 'import os\n'), ((7891, 7914), 'time.strftime', 'time.strftime', (['"""%d%m%Y"""'], {}), "('%d%m%Y')\n", (7904, 7914), False, 'import time\n'), ((11076, 11188), 'folium.CircleMarker', 'folium.CircleMarker', (['[lat, long]'], {'radius': '(5)', 'color': '"""red"""', 'popup': 'popup_str', 'fill_color': '"""red"""', 'fill_opacity': '(0.7)'}), "([lat, long], radius=5, color='red', popup=popup_str,\n fill_color='red', fill_opacity=0.7)\n", (11095, 11188), False, 'import folium\n'), ((12503, 12544), 'datetime.datetime.strftime', 'datetime.datetime.strftime', (['d', '"""%d/%m/%Y"""'], {}), "(d, '%d/%m/%Y')\n", (12529, 12544), False, 'import datetime\n'), ((14448, 14665), 'plotly.express.bar', 'px.bar', (['norm_srelevant'], {'y': 'groupby[1]', 'x': 'k', 'color': 'groupby[1]', 'template': '"""ggplot2"""', 'log_x': '(True)', 'orientation': '"""h"""', 'title': 'title_string', 'hover_name': 'groupby[1]', 'animation_frame': 'groupby[0]', 'animation_group': 'groupby[1]'}), "(norm_srelevant, y=groupby[1], x=k, color=groupby[1], template=\n 'ggplot2', log_x=True, orientation='h', title=title_string, hover_name=\n groupby[1], animation_frame=groupby[0], animation_group=groupby[1])\n", (14454, 14665), True, 'import plotly.express as px\n'), ((19501, 19521), 'numpy.isinf', 'np.isinf', (['grows_rate'], {}), '(grows_rate)\n', (19509, 19521), True, 'import numpy as np\n'), ((20419, 20460), 'numpy.max', 'np.max', (['[1, len_rate - num_days_for_rate]'], {}), '([1, len_rate - num_days_for_rate])\n', (20425, 20460), True, 'import numpy as np\n'), ((20571, 20638), 'numpy.max', 'np.max', (['[1e-06, full_data[base][vec[-1]] - full_data[base][vec[0]]]'], {}), '([1e-06, full_data[base][vec[-1]] - full_data[base][vec[0]]])\n', (20577, 20638), True, 'import numpy as np\n'), ((23276, 23287), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (23285, 23287), False, 'import os\n'), ((32394, 32428), 'numpy.arange', 'np.arange', (['(0)', 'thresh_data.shape[0]'], {}), '(0, thresh_data.shape[0])\n', (32403, 32428), True, 'import numpy as np\n'), ((35288, 35326), 'numpy.arange', 'np.arange', (['(0)', 'threshed_ref_db.shape[0]'], {}), '(0, threshed_ref_db.shape[0])\n', (35297, 35326), True, 'import numpy as np\n'), ((45060, 45071), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (45069, 45071), False, 'import os\n'), ((12104, 12115), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (12113, 12115), False, 'import os\n'), ((12117, 12140), 'time.strftime', 'time.strftime', (['"""%d%m%Y"""'], {}), "('%d%m%Y')\n", (12130, 12140), False, 'import time\n'), ((13208, 13246), 'numpy.max', 'np.max', (['[100, num_contries / 25 * 100]'], {}), '([100, num_contries / 25 * 100])\n', (13214, 13246), True, 'import numpy as np\n'), ((15893, 16097), 'plotly.express.bar', 'px.bar', (['norm_srelevant'], {'y': 'groupby[1]', 'x': 'k', 'color': 'groupby[1]', 'template': '"""ggplot2"""', 'orientation': '"""h"""', 'title': 'title_string', 'hover_name': 'groupby[1]', 'animation_frame': 'groupby[0]', 'animation_group': 'groupby[1]'}), "(norm_srelevant, y=groupby[1], x=k, color=groupby[1], template=\n 'ggplot2', orientation='h', title=title_string, hover_name=groupby[1],\n animation_frame=groupby[0], animation_group=groupby[1])\n", (15899, 16097), True, 'import plotly.express as px\n'), ((20660, 20679), 'numpy.isinf', 'np.isinf', (['last_week'], {}), '(last_week)\n', (20668, 20679), True, 'import numpy as np\n'), ((22729, 22755), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (22747, 22755), False, 'import datetime\n'), ((28534, 28545), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (28543, 28545), False, 'import os\n'), ((28547, 28570), 'time.strftime', 'time.strftime', (['"""%d%m%Y"""'], {}), "('%d%m%Y')\n", (28560, 28570), False, 'import time\n'), ((33972, 33998), 'numpy.isinf', 'np.isinf', (['growth_rate_mean'], {}), '(growth_rate_mean)\n', (33980, 33998), True, 'import numpy as np\n'), ((34007, 34033), 'numpy.isnan', 'np.isnan', (['growth_rate_mean'], {}), '(growth_rate_mean)\n', (34015, 34033), True, 'import numpy as np\n'), ((41250, 41270), 'numpy.isinf', 'np.isinf', (['grows_rate'], {}), '(grows_rate)\n', (41258, 41270), True, 'import numpy as np\n'), ((42294, 42314), 'numpy.isinf', 'np.isinf', (['grows_rate'], {}), '(grows_rate)\n', (42302, 42314), True, 'import numpy as np\n'), ((44513, 44539), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (44531, 44539), False, 'import datetime\n'), ((14799, 14837), 'numpy.max', 'np.max', (['[100, num_contries / 25 * 100]'], {}), '([100, num_contries / 25 * 100])\n', (14805, 14837), True, 'import numpy as np\n'), ((22855, 22876), 'numpy.diff', 'np.diff', (['full_data[k]'], {}), '(full_data[k])\n', (22862, 22876), True, 'import numpy as np\n'), ((22969, 22990), 'numpy.diff', 'np.diff', (['full_data[k]'], {}), '(full_data[k])\n', (22976, 22990), True, 'import numpy as np\n'), ((33611, 33631), 'numpy.isinf', 'np.isinf', (['grows_rate'], {}), '(grows_rate)\n', (33619, 33631), True, 'import numpy as np\n'), ((44639, 44660), 'numpy.diff', 'np.diff', (['full_data[k]'], {}), '(full_data[k])\n', (44646, 44660), True, 'import numpy as np\n'), ((44753, 44774), 'numpy.diff', 'np.diff', (['full_data[k]'], {}), '(full_data[k])\n', (44760, 44774), True, 'import numpy as np\n'), ((16248, 16286), 'numpy.max', 'np.max', (['[100, num_contries / 25 * 100]'], {}), '([100, num_contries / 25 * 100])\n', (16254, 16286), True, 'import numpy as np\n'), ((25968, 25977), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (25974, 25977), True, 'import numpy as np\n'), ((25978, 25997), 'numpy.log', 'np.log', (['growth_rate'], {}), '(growth_rate)\n', (25984, 25997), True, 'import numpy as np\n'), ((26207, 26216), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (26213, 26216), True, 'import numpy as np\n'), ((26217, 26237), 'numpy.log', 'np.log', (['growth_death'], {}), '(growth_death)\n', (26223, 26237), True, 'import numpy as np\n'), ((26455, 26464), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (26461, 26464), True, 'import numpy as np\n'), ((26465, 26489), 'numpy.log', 'np.log', (['growth_recovered'], {}), '(growth_recovered)\n', (26471, 26489), True, 'import numpy as np\n'), ((34063, 34072), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (34069, 34072), True, 'import numpy as np\n'), ((34075, 34099), 'numpy.log', 'np.log', (['growth_rate_mean'], {}), '(growth_rate_mean)\n', (34081, 34099), True, 'import numpy as np\n'), ((35495, 35546), 'numpy.linspace', 'np.linspace', (['(1)', 'num_dates', 'num_dates'], {'endpoint': '(True)'}), '(1, num_dates, num_dates, endpoint=True)\n', (35506, 35546), True, 'import numpy as np\n'), ((35936, 35987), 'numpy.linspace', 'np.linspace', (['(1)', 'num_dates', 'num_dates'], {'endpoint': '(True)'}), '(1, num_dates, num_dates, endpoint=True)\n', (35947, 35987), True, 'import numpy as np\n'), ((36564, 36615), 'numpy.linspace', 'np.linspace', (['(1)', 'num_dates', 'num_dates'], {'endpoint': '(True)'}), '(1, num_dates, num_dates, endpoint=True)\n', (36575, 36615), True, 'import numpy as np\n')] |
import os
from ..Task import Task
from .UpdateImageMetadataTask import UpdateImageMetadataTask
from ... import Crawler
class ConvertImageTask(Task):
"""
Convert the source image (from the crawler) to the target one using oiio.
"""
def __init__(self, *args, **kwargs):
"""
Create a ConvertImage task.
"""
super(ConvertImageTask, self).__init__(*args, **kwargs)
self.setMetadata('dispatch.split', True)
def _perform(self):
"""
Perform the task.
"""
import OpenImageIO as oiio
for crawler in self.crawlers():
targetFilePath = Crawler.Fs.Image.OiioCrawler.supportedString(
self.target(crawler)
)
# trying to create the directory automatically in case it does not exist
try:
os.makedirs(os.path.dirname(targetFilePath))
except OSError:
pass
# converting image using open image io
inputImageFilePath = Crawler.Fs.Image.OiioCrawler.supportedString(
crawler.var('filePath')
)
imageInput = oiio.ImageInput.open(inputImageFilePath)
inputSpec = imageInput.spec()
# updating kombi metadata
UpdateImageMetadataTask.updateDefaultMetadata(inputSpec, crawler)
outImage = oiio.ImageOutput.create(targetFilePath)
# in case we are using an older version of oiio we need to
# provide an additional argument to the open
outImageOpenArgs = [
targetFilePath,
inputSpec
]
if hasattr(oiio, 'ImageOutputOpenMode'):
outImageOpenArgs.append(oiio.ImageOutputOpenMode.Create)
outImage.open(
*outImageOpenArgs
)
outImage.copy_image(imageInput)
outImage.close()
# default result based on the target filePath
return super(ConvertImageTask, self)._perform()
# registering task
Task.register(
'convertImage',
ConvertImageTask
)
| [
"os.path.dirname",
"OpenImageIO.ImageInput.open",
"OpenImageIO.ImageOutput.create"
] | [((1160, 1200), 'OpenImageIO.ImageInput.open', 'oiio.ImageInput.open', (['inputImageFilePath'], {}), '(inputImageFilePath)\n', (1180, 1200), True, 'import OpenImageIO as oiio\n'), ((1384, 1423), 'OpenImageIO.ImageOutput.create', 'oiio.ImageOutput.create', (['targetFilePath'], {}), '(targetFilePath)\n', (1407, 1423), True, 'import OpenImageIO as oiio\n'), ((868, 899), 'os.path.dirname', 'os.path.dirname', (['targetFilePath'], {}), '(targetFilePath)\n', (883, 899), False, 'import os\n')] |
#!/usr/bin/env python
# coding: utf8
#
# Copyright (c) 2021 Centre National d'Etudes Spatiales (CNES).
#
# This file is part of PANDORA_MCCNN
#
# https://github.com/CNES/Pandora_MCCNN
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
This module contains all functions to generate the training and testing dataset on the Data Fusion Contest generated
with Beefrost
"""
import os
import glob
import argparse
import numpy as np
import h5py
import rasterio
from numba import njit
@njit()
def compute_mask(disp_map, mask_ref, mask_sec, patch_size):
"""
Masks invalid pixels : pixel outside epipolar image
:param disp_map: disparity map
:type disp_map: 2D numpy array
:param mask_ref: left epipolar image mask : with the convention 0 is valid pixel in epipolar image
:type mask_ref: 2D numpy array
:param mask_sec: right epipolar image mask : with the convention 0 is valid pixel in epipolar image
:type mask_sec: 2D numpy array
:param patch_size: patch size
:type patch_size: int
:return: the disparity map with invalid pixels = -9999
:rtype: 2D numpy array
"""
radius = int(patch_size / 2)
nb_row, nb_col = disp_map.shape
for row in range(radius, nb_row - radius):
for col in range(radius, nb_col - radius):
disp = disp_map[row, col]
# Matching in the right image
match = int(col + disp)
# Negative matching for training, with maximum negative displacement for creating negative example
neg_match = match - 6
# If negative example is inside right epipolar image
if radius < neg_match < (nb_col - radius) and radius < neg_match < (nb_row - radius):
patch_ref = mask_ref[(row - radius) : (row + radius + 1), (col - radius) : (col + radius + 1)]
patch_sec = mask_sec[(row - radius) : (row + radius + 1), (match - radius) : (match + radius + 1)]
# Invalid patch : outside left epipolar image
if np.sum(patch_ref != 0) != 0:
disp_map[row, col] = -9999
# Invalid patch : outside right epipolar image
if np.sum(patch_sec != 0) != 0:
disp_map[row, col] = -9999
neg_patch_sec = mask_sec[
(row - radius) : (row + radius + 1), (neg_match - radius) : (neg_match + radius + 1)
]
# Invalid patch : outside right epipolar image
if np.sum(neg_patch_sec != 0) != 0:
disp_map[row, col] = -9999
# Negative example cannot be created
else:
disp_map[row, col] = -9999
return disp_map
def save_dataset(img, sample, img_name, img_file, sample_file):
"""
Save the sample in hdf5 files :
- images are saved in the img_file file: creation of a dataset for each image pair
- sample are saved in the sample_file file : creation of dataset containing valid pixels
The dataset name is the ground truth file ( exemple : JAX_004_009_007_LEFT_DSP.tif )
:param img: images
:type img: np.array (2, 1024, 1024, 3) ( 2 = left image, right image)
:param sample: samples of the image
:type sample: np.array(number of valid pixels for all the images, 4).
The last dimension is : number of the image, row, col, disparity for the pixel p(row, col)
:param img_name: name of the current image pair ( name of the gt disparity )
:type img_name: string
:param img_file: image database file
:type img_file: hdf5 file
:param sample_file: training or testing database file
:type sample_file: hdf5 file
"""
sample_file.create_dataset(img_name, data=sample)
img_file.create_dataset(img_name, data=img)
def fusion_contest(input_dir, output):
"""
Preprocess and create data fusion contest hdf5 database
:param input_dir: path to the input directory
:type input_dir: string
:param output: output directory
:type output: string
"""
img_file = h5py.File(os.path.join(output, "images_training_dataset_fusion_contest.hdf5"), "w")
training_file = h5py.File(os.path.join(output, "training_dataset_fusion_contest.hdf5"), "w")
img_testing_file = h5py.File(os.path.join(output, "images_testing_dataset_fusion_contest.hdf5"), "w")
testing_file = h5py.File(os.path.join(output, "testing_dataset_fusion_contest.hdf5"), "w")
gt = glob.glob(input_dir + "/*/left_epipolar_disp.tif")
nb_img = len(gt)
# Shuffle the file list
indices = np.arange(nb_img)
np.random.seed(0)
np.random.shuffle(indices)
gt = [gt[i] for i in indices]
# 90 % Training, 10 % Testing
end_training = int(nb_img * 0.9)
for num_image in range(nb_img):
name_image = gt[num_image].split(input_dir)[1].split("/")[1]
path_image = gt[num_image].split("left_epipolar_disp.tif")[0]
# Read images
left = rasterio.open(os.path.join(path_image, "left_epipolar_image.tif")).read(1)
left_mask = rasterio.open(os.path.join(path_image, "left_epipolar_mask.tif")).read(1)
right = rasterio.open(os.path.join(path_image, "right_epipolar_image.tif")).read(1)
right_mask = rasterio.open(os.path.join(path_image, "right_epipolar_mask.tif")).read(1)
dsp = rasterio.open(gt[num_image]).read(1)
mask_dsp = rasterio.open(os.path.join(path_image, "left_epipolar_disp_mask.tif")).read(1)
cross_checking = rasterio.open(os.path.join(path_image, "valid_disp.tif")).read(1)
# Mask disparities
mask_disp = compute_mask(dsp, left_mask, right_mask, 11)
# Remove invalid pixels : invalidated by cross-checking mask and with invalid disparity
mask_disp[np.where(cross_checking == 255)] = -9999
mask_disp[np.where(mask_dsp == 255)] = -9999
# Change the disparity convention to ref(x,y) = sec(x-d,y)
mask_disp *= -1
# Remove invalid disparity
valid_row, valid_col = np.where(mask_disp != 9999)
# Red band selection
left = np.squeeze(left[0, :, :])
right = np.squeeze(right[0, :, :])
# Normalization
valid_left = np.where(left_mask == 0)
valid_right = np.where(right_mask == 0)
left[valid_left] = (left[valid_left] - left[valid_left].mean()) / left[valid_left].std()
right[valid_right] = (right[valid_right] - right[valid_right].mean()) / right[valid_right].std()
# data np.array of shape ( number of valid pixels the current image, 4 )
# 4 = number of the image, row, col, disparity for the pixel p(row, col)
valid_disp = np.column_stack(
(np.zeros_like(valid_row) + num_image, valid_row, valid_col, mask_disp[valid_row, valid_col])
).astype(np.float32)
# img of shape (2, 2048, 2048, 3)
img = np.stack((left, right), axis=0)
if num_image > end_training:
save_dataset(img, valid_disp, name_image, img_testing_file, testing_file)
else:
save_dataset(img, valid_disp, name_image, img_file, training_file)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Script for creating the training data fusion contest database. "
"it will create the following files: "
"- training_dataset_fusion_contest.hdf5, which contains training"
" coordinates of the valid pixels and their disparity."
"- testing_dataset_fusion_contest.hdf5, which contains testing "
"coordinates of the valid pixels and their disparity."
"- images_training_dataset_fusion_contest.hdf5, which contains the red"
" band normalized training images"
"- images_testing_dataset_fusion_contest.hdf5, which contains the red"
" band normalized testing images"
)
parser.add_argument("input_data", help="Path to the input directory containing the data")
parser.add_argument("output_dir", help="Path to the output directory ")
args = parser.parse_args()
fusion_contest(args.input_data, args.output_dir)
| [
"argparse.ArgumentParser",
"numpy.arange",
"numpy.where",
"rasterio.open",
"numba.njit",
"os.path.join",
"numpy.squeeze",
"numpy.stack",
"numpy.sum",
"numpy.random.seed",
"numpy.zeros_like",
"glob.glob",
"numpy.random.shuffle"
] | [((987, 993), 'numba.njit', 'njit', ([], {}), '()\n', (991, 993), False, 'from numba import njit\n'), ((4961, 5011), 'glob.glob', 'glob.glob', (["(input_dir + '/*/left_epipolar_disp.tif')"], {}), "(input_dir + '/*/left_epipolar_disp.tif')\n", (4970, 5011), False, 'import glob\n'), ((5076, 5093), 'numpy.arange', 'np.arange', (['nb_img'], {}), '(nb_img)\n', (5085, 5093), True, 'import numpy as np\n'), ((5098, 5115), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (5112, 5115), True, 'import numpy as np\n'), ((5120, 5146), 'numpy.random.shuffle', 'np.random.shuffle', (['indices'], {}), '(indices)\n', (5137, 5146), True, 'import numpy as np\n'), ((7669, 8247), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Script for creating the training data fusion contest database. it will create the following files: - training_dataset_fusion_contest.hdf5, which contains training coordinates of the valid pixels and their disparity.- testing_dataset_fusion_contest.hdf5, which contains testing coordinates of the valid pixels and their disparity.- images_training_dataset_fusion_contest.hdf5, which contains the red band normalized training images- images_testing_dataset_fusion_contest.hdf5, which contains the red band normalized testing images"""'}), "(description=\n 'Script for creating the training data fusion contest database. it will create the following files: - training_dataset_fusion_contest.hdf5, which contains training coordinates of the valid pixels and their disparity.- testing_dataset_fusion_contest.hdf5, which contains testing coordinates of the valid pixels and their disparity.- images_training_dataset_fusion_contest.hdf5, which contains the red band normalized training images- images_testing_dataset_fusion_contest.hdf5, which contains the red band normalized testing images'\n )\n", (7692, 8247), False, 'import argparse\n'), ((4579, 4646), 'os.path.join', 'os.path.join', (['output', '"""images_training_dataset_fusion_contest.hdf5"""'], {}), "(output, 'images_training_dataset_fusion_contest.hdf5')\n", (4591, 4646), False, 'import os\n'), ((4683, 4743), 'os.path.join', 'os.path.join', (['output', '"""training_dataset_fusion_contest.hdf5"""'], {}), "(output, 'training_dataset_fusion_contest.hdf5')\n", (4695, 4743), False, 'import os\n'), ((4783, 4849), 'os.path.join', 'os.path.join', (['output', '"""images_testing_dataset_fusion_contest.hdf5"""'], {}), "(output, 'images_testing_dataset_fusion_contest.hdf5')\n", (4795, 4849), False, 'import os\n'), ((4885, 4944), 'os.path.join', 'os.path.join', (['output', '"""testing_dataset_fusion_contest.hdf5"""'], {}), "(output, 'testing_dataset_fusion_contest.hdf5')\n", (4897, 4944), False, 'import os\n'), ((6523, 6550), 'numpy.where', 'np.where', (['(mask_disp != 9999)'], {}), '(mask_disp != 9999)\n', (6531, 6550), True, 'import numpy as np\n'), ((6596, 6621), 'numpy.squeeze', 'np.squeeze', (['left[0, :, :]'], {}), '(left[0, :, :])\n', (6606, 6621), True, 'import numpy as np\n'), ((6638, 6664), 'numpy.squeeze', 'np.squeeze', (['right[0, :, :]'], {}), '(right[0, :, :])\n', (6648, 6664), True, 'import numpy as np\n'), ((6711, 6735), 'numpy.where', 'np.where', (['(left_mask == 0)'], {}), '(left_mask == 0)\n', (6719, 6735), True, 'import numpy as np\n'), ((6758, 6783), 'numpy.where', 'np.where', (['(right_mask == 0)'], {}), '(right_mask == 0)\n', (6766, 6783), True, 'import numpy as np\n'), ((7379, 7410), 'numpy.stack', 'np.stack', (['(left, right)'], {'axis': '(0)'}), '((left, right), axis=0)\n', (7387, 7410), True, 'import numpy as np\n'), ((6271, 6302), 'numpy.where', 'np.where', (['(cross_checking == 255)'], {}), '(cross_checking == 255)\n', (6279, 6302), True, 'import numpy as np\n'), ((6330, 6355), 'numpy.where', 'np.where', (['(mask_dsp == 255)'], {}), '(mask_dsp == 255)\n', (6338, 6355), True, 'import numpy as np\n'), ((5838, 5866), 'rasterio.open', 'rasterio.open', (['gt[num_image]'], {}), '(gt[num_image])\n', (5851, 5866), False, 'import rasterio\n'), ((2522, 2544), 'numpy.sum', 'np.sum', (['(patch_ref != 0)'], {}), '(patch_ref != 0)\n', (2528, 2544), True, 'import numpy as np\n'), ((2681, 2703), 'numpy.sum', 'np.sum', (['(patch_sec != 0)'], {}), '(patch_sec != 0)\n', (2687, 2703), True, 'import numpy as np\n'), ((3006, 3032), 'numpy.sum', 'np.sum', (['(neg_patch_sec != 0)'], {}), '(neg_patch_sec != 0)\n', (3012, 3032), True, 'import numpy as np\n'), ((5481, 5532), 'os.path.join', 'os.path.join', (['path_image', '"""left_epipolar_image.tif"""'], {}), "(path_image, 'left_epipolar_image.tif')\n", (5493, 5532), False, 'import os\n'), ((5576, 5626), 'os.path.join', 'os.path.join', (['path_image', '"""left_epipolar_mask.tif"""'], {}), "(path_image, 'left_epipolar_mask.tif')\n", (5588, 5626), False, 'import os\n'), ((5666, 5718), 'os.path.join', 'os.path.join', (['path_image', '"""right_epipolar_image.tif"""'], {}), "(path_image, 'right_epipolar_image.tif')\n", (5678, 5718), False, 'import os\n'), ((5763, 5814), 'os.path.join', 'os.path.join', (['path_image', '"""right_epipolar_mask.tif"""'], {}), "(path_image, 'right_epipolar_mask.tif')\n", (5775, 5814), False, 'import os\n'), ((5908, 5963), 'os.path.join', 'os.path.join', (['path_image', '"""left_epipolar_disp_mask.tif"""'], {}), "(path_image, 'left_epipolar_disp_mask.tif')\n", (5920, 5963), False, 'import os\n'), ((6012, 6054), 'os.path.join', 'os.path.join', (['path_image', '"""valid_disp.tif"""'], {}), "(path_image, 'valid_disp.tif')\n", (6024, 6054), False, 'import os\n'), ((7200, 7224), 'numpy.zeros_like', 'np.zeros_like', (['valid_row'], {}), '(valid_row)\n', (7213, 7224), True, 'import numpy as np\n')] |
import numpy as np
# NOTE: these all assume a sample rate of 1000Hz and 0-centered(ish)
BUTTER2_45_55_NOTCH = [[0.95654323, -1.82035157, 0.95654323, 1., -1.84458768, 0.9536256 ],
[1. , -1.90305207, 1. , 1., -1.87701816, 0.95947072]]
BUTTER4_45_55_NOTCH = [[0.92117099, -1.75303637, 0.92117099, 1., -1.83993124, 0.94153282],
[1. , -1.90305207, 1. , 1., -1.85827897, 0.94562794],
[1. , -1.90305207, 1. , 1., -1.85916949, 0.9741553 ],
[1. , -1.90305207, 1. , 1., -1.89861232, 0.9783552 ]]
BUTTER8_45_55_NOTCH = [[0.85123494, -1.61994442, 0.85123494, 1., -1.84135423, 0.93909556],
[1. , -1.90305207, 1. , 1., -1.85081373, 0.94130689],
[1. , -1.90305207, 1. , 1., -1.84098214, 0.94640431],
[1. , -1.90305207, 1. , 1., -1.86712758, 0.95177517],
[1. , -1.90305207, 1. , 1., -1.85070766, 0.96298756],
[1. , -1.90305207, 1. , 1., -1.88761855, 0.96842656],
[1. , -1.90305207, 1. , 1., -1.86966575, 0.98667654],
[1. , -1.90305207, 1. , 1., -1.90969867, 0.98897339]]
BUTTER2_55_65_NOTCH = [[0.95654323, -1.77962093, 0.95654323, 1., -1.80093517, 0.95415195],
[1. , -1.860471 , 1. , 1., -1.83739919, 0.95894143]]
BUTTER4_55_65_NOTCH = [[0.92117099, -1.71381192, 0.92117099, 1., -1.79756457, 0.94190374],
[1. , -1.860471 , 1. , 1., -1.81789764, 0.94525555],
[1. , -1.860471 , 1. , 1., -1.81413419, 0.97453194],
[1. , -1.860471 , 1. , 1., -1.8595667 , 0.97797707]]
BUTTER8_55_65_NOTCH = [[0.85123494, -1.58369793, 0.85123494, 1., -1.799555 , 0.93929634],
[1. , -1.860471 , 1. , 1., -1.81000016, 0.94110568],
[1. , -1.860471 , 1. , 1., -1.79799514, 0.94688937],
[1. , -1.860471 , 1. , 1., -1.82714508, 0.95128761],
[1. , -1.860471 , 1. , 1., -1.80636275, 0.96347614],
[1. , -1.860471 , 1. , 1., -1.84831785, 0.96793547],
[1. , -1.860471 , 1. , 1., -1.82397995, 0.98688239],
[1. , -1.860471 , 1. , 1., -1.87082063, 0.9887671 ]]
class ButterworthFilter():
def __init__(self, coeffs):
self.order = len(coeffs)
self.coeffs = np.array(coeffs)
self.z = np.array([[0.0]*2]*self.order) # order x 2 array of zeros
def next_sample(self, xn):
for s in range(self.order):
xn_tmp = xn # make a temp copy
xn = self.coeffs[s, 0] * xn_tmp + self.z[s, 0]
self.z[s, 0] = (self.coeffs[s, 1] * xn_tmp - self.coeffs[s, 4] * xn + self.z[s, 1])
self.z[s, 1] = (self.coeffs[s, 2] * xn_tmp - self.coeffs[s, 5] * xn)
return xn | [
"numpy.array"
] | [((2752, 2768), 'numpy.array', 'np.array', (['coeffs'], {}), '(coeffs)\n', (2760, 2768), True, 'import numpy as np\n'), ((2786, 2820), 'numpy.array', 'np.array', (['([[0.0] * 2] * self.order)'], {}), '([[0.0] * 2] * self.order)\n', (2794, 2820), True, 'import numpy as np\n')] |
import datetime as dt
from stpmex.utils import strftime, strptime
def test_strftime():
assert strftime(dt.date(2020, 4, 20)) == '20200420'
def test_strptime():
assert strptime('20200420') == dt.date(2020, 4, 20)
| [
"stpmex.utils.strptime",
"datetime.date"
] | [((180, 200), 'stpmex.utils.strptime', 'strptime', (['"""20200420"""'], {}), "('20200420')\n", (188, 200), False, 'from stpmex.utils import strftime, strptime\n'), ((204, 224), 'datetime.date', 'dt.date', (['(2020)', '(4)', '(20)'], {}), '(2020, 4, 20)\n', (211, 224), True, 'import datetime as dt\n'), ((110, 130), 'datetime.date', 'dt.date', (['(2020)', '(4)', '(20)'], {}), '(2020, 4, 20)\n', (117, 130), True, 'import datetime as dt\n')] |
"""Describes Project class"""
import os
from collections import defaultdict
from fama.utils.const import ENDS
from fama.project.program_config import ProgramConfig
from fama.project.project_options import ProjectOptions
from fama.project.sample import Sample
from fama.reference_library.reference_data import ReferenceData
from fama.reference_library.taxonomy_data import TaxonomyData
from fama.output.report import generate_project_report
from fama.output.json_util import import_sample, import_annotated_reads
class Project(object):
"""Project is an umbrella object for all samples currently analyzed.
Attributes:
samples (:obj:'dict'[str,:obj:'Sample']): dictionary with sample
identifiers as keys and Sample objects as values
config (:obj:'ProgramConfig'): Fama configuration parameters
options (:obj:'ProjectOptions'): Fama project options
collection (str): collection identifier
collection (str): reference collection identifier
ref_data (:obj:'ReferenceData'): reference dataset for the
collection (list of functions, list of proteins etc.)
taxonomy_data (:obj:'TaxonomyData'): NCBI taxonomy dataset for
the collection
"""
def __init__(self, config_file, project_file):
"""
Args:
config_file (str): full path to program configuration ini file.
project_file (str): full path to project ini file.
"""
self.samples = {}
self.config = ProgramConfig(config_file)
self.options = ProjectOptions(project_file)
collection = self.options.get_collection()
if collection not in self.config.collections:
raise Exception(
'Collection ' + collection + ' not found. Available collections are: '
+ (',').join(self.config.collections)
)
self.collection = collection
self.ref_data = ReferenceData(self.config, self.collection)
self.taxonomy_data = TaxonomyData(self.config, self.collection)
if not os.path.exists(self.options.work_dir) and not os.path.isdir(self.options.work_dir):
os.makedirs(self.options.work_dir, exist_ok=True)
def list_samples(self):
"""Returns list of sample identifiers"""
return self.options.list_samples()
def save_project_options(self):
"""Saves project options as new version of project ini file"""
for sample_id in self.samples:
self.options.set_sample_data(self.samples[sample_id])
self.options.save_options()
def load_project(self):
"""Populates reads attribute with samples data"""
for sample_id in self.list_samples():
sample = Sample(sample_id=sample_id)
sample.load_sample(self.options)
self.samples[sample_id] = sample
def load_sample(self, sample):
"""Loads sample data from JSON file into memory
Args:
sample (:obj:'Sample'): Sample object
"""
self.samples[sample.sample_id] = \
import_sample(os.path.join(sample.work_directory,
sample.sample_id + '_' + self.options.reads_json_name))
def import_reads_json(self, sample_id, ends):
"""Loads annotated reads from one or two JSON files into memory
Args:
sample_id (str): sample identifier
ends (:obj:'list' of str): either ['pe1','pe2'] or ['pe1'] or ['pe2']
"""
for end_id in ends:
if end_id == 'pe2' and not self.samples[sample_id].is_paired_end:
continue
self.samples[sample_id].reads[end_id] = \
import_annotated_reads(os.path.join(self.options.get_project_dir(sample_id),
sample_id + '_' + end_id + '_'
+ self.options.reads_json_name))
def get_insert_size(self, sample):
"""Returns average insert size for paired-end sample. If calculation of
insert size is not possible, returns None.
"""
result = None
if not sample.is_paired_end or sample.insert_size is None:
pass
elif sample.insert_size == 0:
insert_size = sample.estimate_average_insert_size(
self.config.get_length_cutoff(self.options.get_collection(sample.sample_id)))
sample.insert_size = insert_size
result = insert_size
elif sample.insert_size > 0:
result = sample.insert_size
return result
def generate_report(self, metrics=None):
"""Writes project report in text format. Also, calls XLSX report
generation.
Args:
metrics (str, optional): metrics for report score calculation
"""
outfile = os.path.join(self.options.work_dir, 'project_report.txt')
with open(outfile, 'w') as outfile:
outfile.write(self.options.project_name + '\n\n')
for sample_id in self.list_samples():
outfile.write('\t'.join([sample_id + ':',
self.samples[sample_id].sample_name,
'pe1 reads: '
+ str(len(self.samples[sample_id].reads['pe1']))]))
if self.samples[sample_id].is_paired_end:
outfile.write('\tpe2 reads: '
+ str(len(self.samples[sample_id].reads['pe2'])))
outfile.write('\n')
generate_project_report(self, metrics)
def is_paired_end(self):
ret_val = None
for sample in self.options.list_samples():
paired_end_sample = True
if not os.path.exists(self.options.get_fastq_path(sample, ENDS[1])):
paired_end_sample = False
if ret_val is None:
ret_val = paired_end_sample
elif ret_val and not paired_end_sample:
raise RuntimeError('Project contains both single-end and' +
'paired-end input files. Process them separately.')
elif not ret_val and paired_end_sample:
raise RuntimeError('Project contains both single-end and' +
' paired-end input files. Process them separately.')
if ret_val is None:
raise RuntimeError('Project does not contain any samples.')
return ret_val
def check_project(self):
"""Checks if all files and directories of a project do exist.
Todo:
Ensure that it looks up the last version of file names
"""
problems = defaultdict(list)
print('Checking project', self.options.project_name)
for sample in self.list_samples():
print('Checking sample', sample)
for end in ENDS:
skip_output_check = False
if not os.path.exists(self.options.get_fastq_path(sample, end)):
problems[sample].append('Input FASTQ file not found for sample',
sample, ',end', end, ':',
self.options.get_fastq_path(sample, end))
outdir = self.options.get_project_dir(sample)
if not os.path.isdir(outdir):
problems[sample].append('Directory not found for sample', sample, ':',
outdir, 'CHECK INTERRUPTED')
continue
if not os.path.isdir(os.path.join(outdir, self.options.get_output_subdir(sample))):
problems[sample].append('Output directory not found for sample', sample, ':',
os.path.join(outdir,
self.options.get_output_subdir(sample)),
'OUTPUT FILES NOT CHECKED')
skip_output_check = True
if not os.path.exists(os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.ref_output_name)):
problems[sample].append('Reference DB search output not found for sample '
+ sample + ', end ' + end + ':' +
os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.ref_output_name))
if not os.path.exists(os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.background_output_name)):
problems[sample].append('Background DB search output not found \
for sample ' + sample + ', end ' + end + ':' +
os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.background_output_name))
if not os.path.exists(os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.reads_fastq_name + '.gz')):
problems[sample].append('Output FASTQ file with reads not found for sample '
+ sample + ', end ' + end + ':' +
os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.reads_fastq_name + '.gz'))
if not os.path.exists(os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.ref_hits_fastq_name)):
problems[sample].append('Reference hits FASTQ file not found for sample '
+ sample + ', end ' + end + ':' +
os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.ref_hits_fastq_name))
if not os.path.exists(os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.ref_hits_list_name)):
problems[sample].append('List of reference hits not found for sample '
+ sample + ', end ' + end + ':' +
os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.ref_hits_list_name))
if not os.path.exists(os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.pe_reads_fastq_name + '.gz')):
problems[sample].append('Output FASTQ file with paired-ends not found \
for sample ' + sample + ', end ' + end + ':' +
os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.pe_reads_fastq_name
+ '.gz'))
if not os.path.exists(os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.reads_json_name)):
problems[sample].append('Output JSON file with annotated reads not found \
for sample ' + sample + ', end ' + end + ':' +
os.path.join(outdir,
sample + '_' + end + '_'
+ self.options.reads_json_name))
if skip_output_check:
continue
if not os.path.exists(os.path.join(outdir,
self.options.get_output_subdir(sample),
sample + '_' + end + '_'
+ self.options.report_name)):
problems[sample].append('Text report file not found for sample ' + sample
+ ', end ' + end + ':' +
os.path.join(outdir,
self.options.get_output_subdir(sample),
sample + '_' + end + '_'
+ self.options.report_name))
if not os.path.exists(os.path.join(outdir,
self.options.get_output_subdir(sample),
sample + '_' + end + '_'
+ self.options.xml_name)):
problems[sample].append('Krona XML file for functional profile \
not found for sample ' + sample + ', end '
+ end + ':' +
os.path.join(outdir,
self.options.get_output_subdir(sample),
sample + '_' + end + '_'
+ self.options.xml_name))
if not os.path.exists(os.path.join(outdir,
self.options.get_output_subdir(sample),
sample + '_' + end + '_'
+ self.options.html_name)):
problems[sample].append('HTML file for functional profile not found for sample '
+ sample + ', end ' + end + ':' +
os.path.join(outdir,
self.options.get_output_subdir(sample),
sample + '_' + end + '_'
+ self.options.html_name))
if not problems:
print('No problems found in your project. Could be worse.')
else:
print('Problems found:')
for sample in problems:
print('********* ' + sample + ' *********')
print('\n'.join(problems[sample]))
print('*********************************\n\n')
| [
"os.path.exists",
"fama.project.program_config.ProgramConfig",
"fama.reference_library.taxonomy_data.TaxonomyData",
"os.makedirs",
"fama.project.sample.Sample",
"os.path.join",
"fama.project.project_options.ProjectOptions",
"fama.reference_library.reference_data.ReferenceData",
"os.path.isdir",
"c... | [((1515, 1541), 'fama.project.program_config.ProgramConfig', 'ProgramConfig', (['config_file'], {}), '(config_file)\n', (1528, 1541), False, 'from fama.project.program_config import ProgramConfig\n'), ((1565, 1593), 'fama.project.project_options.ProjectOptions', 'ProjectOptions', (['project_file'], {}), '(project_file)\n', (1579, 1593), False, 'from fama.project.project_options import ProjectOptions\n'), ((1948, 1991), 'fama.reference_library.reference_data.ReferenceData', 'ReferenceData', (['self.config', 'self.collection'], {}), '(self.config, self.collection)\n', (1961, 1991), False, 'from fama.reference_library.reference_data import ReferenceData\n'), ((2021, 2063), 'fama.reference_library.taxonomy_data.TaxonomyData', 'TaxonomyData', (['self.config', 'self.collection'], {}), '(self.config, self.collection)\n', (2033, 2063), False, 'from fama.reference_library.taxonomy_data import TaxonomyData\n'), ((4879, 4936), 'os.path.join', 'os.path.join', (['self.options.work_dir', '"""project_report.txt"""'], {}), "(self.options.work_dir, 'project_report.txt')\n", (4891, 4936), False, 'import os\n'), ((5613, 5651), 'fama.output.report.generate_project_report', 'generate_project_report', (['self', 'metrics'], {}), '(self, metrics)\n', (5636, 5651), False, 'from fama.output.report import generate_project_report\n'), ((6759, 6776), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (6770, 6776), False, 'from collections import defaultdict\n'), ((2175, 2224), 'os.makedirs', 'os.makedirs', (['self.options.work_dir'], {'exist_ok': '(True)'}), '(self.options.work_dir, exist_ok=True)\n', (2186, 2224), False, 'import os\n'), ((2749, 2776), 'fama.project.sample.Sample', 'Sample', ([], {'sample_id': 'sample_id'}), '(sample_id=sample_id)\n', (2755, 2776), False, 'from fama.project.sample import Sample\n'), ((3105, 3200), 'os.path.join', 'os.path.join', (['sample.work_directory', "(sample.sample_id + '_' + self.options.reads_json_name)"], {}), "(sample.work_directory, sample.sample_id + '_' + self.options.\n reads_json_name)\n", (3117, 3200), False, 'import os\n'), ((2079, 2116), 'os.path.exists', 'os.path.exists', (['self.options.work_dir'], {}), '(self.options.work_dir)\n', (2093, 2116), False, 'import os\n'), ((2125, 2161), 'os.path.isdir', 'os.path.isdir', (['self.options.work_dir'], {}), '(self.options.work_dir)\n', (2138, 2161), False, 'import os\n'), ((7404, 7425), 'os.path.isdir', 'os.path.isdir', (['outdir'], {}), '(outdir)\n', (7417, 7425), False, 'import os\n'), ((8136, 8213), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.ref_output_name)"], {}), "(outdir, sample + '_' + end + '_' + self.options.ref_output_name)\n", (8148, 8213), False, 'import os\n'), ((8766, 8855), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.background_output_name)"], {}), "(outdir, sample + '_' + end + '_' + self.options.\n background_output_name)\n", (8778, 8855), False, 'import os\n'), ((9413, 9504), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.reads_fastq_name + '.gz')"], {}), "(outdir, sample + '_' + end + '_' + self.options.\n reads_fastq_name + '.gz')\n", (9425, 9504), False, 'import os\n'), ((10063, 10149), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.ref_hits_fastq_name)"], {}), "(outdir, sample + '_' + end + '_' + self.options.\n ref_hits_fastq_name)\n", (10075, 10149), False, 'import os\n'), ((10700, 10785), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.ref_hits_list_name)"], {}), "(outdir, sample + '_' + end + '_' + self.options.ref_hits_list_name\n )\n", (10712, 10785), False, 'import os\n'), ((11332, 11426), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.pe_reads_fastq_name + '.gz')"], {}), "(outdir, sample + '_' + end + '_' + self.options.\n pe_reads_fastq_name + '.gz')\n", (11344, 11426), False, 'import os\n'), ((12053, 12130), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.reads_json_name)"], {}), "(outdir, sample + '_' + end + '_' + self.options.reads_json_name)\n", (12065, 12130), False, 'import os\n'), ((8535, 8612), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.ref_output_name)"], {}), "(outdir, sample + '_' + end + '_' + self.options.ref_output_name)\n", (8547, 8612), False, 'import os\n'), ((9175, 9264), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.background_output_name)"], {}), "(outdir, sample + '_' + end + '_' + self.options.\n background_output_name)\n", (9187, 9264), False, 'import os\n'), ((9823, 9914), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.reads_fastq_name + '.gz')"], {}), "(outdir, sample + '_' + end + '_' + self.options.\n reads_fastq_name + '.gz')\n", (9835, 9914), False, 'import os\n'), ((10465, 10551), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.ref_hits_fastq_name)"], {}), "(outdir, sample + '_' + end + '_' + self.options.\n ref_hits_fastq_name)\n", (10477, 10551), False, 'import os\n'), ((11098, 11183), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.ref_hits_list_name)"], {}), "(outdir, sample + '_' + end + '_' + self.options.ref_hits_list_name\n )\n", (11110, 11183), False, 'import os\n'), ((11753, 11847), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.pe_reads_fastq_name + '.gz')"], {}), "(outdir, sample + '_' + end + '_' + self.options.\n pe_reads_fastq_name + '.gz')\n", (11765, 11847), False, 'import os\n'), ((12445, 12522), 'os.path.join', 'os.path.join', (['outdir', "(sample + '_' + end + '_' + self.options.reads_json_name)"], {}), "(outdir, sample + '_' + end + '_' + self.options.reads_json_name)\n", (12457, 12522), False, 'import os\n')] |
from django.db import models
from django.contrib.auth.models import User
class Entry(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=128, unique=True)
slug = models.CharField(max_length=128)
created = models.DateTimeField()
# ImageField need Pillow
image = models.FileField(upload_to='tests/images', null=True, blank=True)
| [
"django.db.models.DateTimeField",
"django.db.models.FileField",
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((113, 173), 'django.db.models.ForeignKey', 'models.ForeignKey', (['User'], {'on_delete': 'models.CASCADE', 'null': '(True)'}), '(User, on_delete=models.CASCADE, null=True)\n', (130, 173), False, 'from django.db import models\n'), ((186, 231), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)', 'unique': '(True)'}), '(max_length=128, unique=True)\n', (202, 231), False, 'from django.db import models\n'), ((243, 275), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)'}), '(max_length=128)\n', (259, 275), False, 'from django.db import models\n'), ((290, 312), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {}), '()\n', (310, 312), False, 'from django.db import models\n'), ((354, 419), 'django.db.models.FileField', 'models.FileField', ([], {'upload_to': '"""tests/images"""', 'null': '(True)', 'blank': '(True)'}), "(upload_to='tests/images', null=True, blank=True)\n", (370, 419), False, 'from django.db import models\n')] |
import pygame
from settings import *
from random import uniform
class Ball(pygame.sprite.Sprite):
def __init__(self, groups, paddle, blocks):
super().__init__(groups)
# Setup
# image is mandatory attribute for pygame sprites.
self.image = pygame.image.load(BASE_DIR / 'assets' / 'imgs' / 'ball.png').convert_alpha()
self.image = pygame.transform.scale(self.image, (30, 30))
self.paddle = paddle
self.blocks = blocks
# Initial Position
self.rect = self.image.get_rect(midbottom=paddle.rect.midtop)
self.previous_rect = self.rect.copy()
self.direction = pygame.math.Vector2(uniform(-5, 5), -1)
self.speed = 10
# Active
self.active = False
def input(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
self.active = True
elif keys[pygame.K_DOWN]:
self.active = False
self.direction = pygame.math.Vector2(uniform(-5, 5), -1)
def screen_collision(self):
# Left part of the screen
if self.rect.left <= 0:
self.direction.x *= -1
# Right part of the screen
elif self.rect.right >= WINDOW_WIDTH:
self.direction.x *= -1
# Top part of the screen
elif self.rect.top <= 0:
self.direction.y *= -1
# Bottom part of screen.
elif self.rect.bottom > WINDOW_HEIGHT:
self.direction.y *= -1
self.active = False
def collision(self):
overlap_sprites = pygame.sprite.spritecollide(self, self.blocks, False)
if self.rect.colliderect(self.paddle.rect):
overlap_sprites.append(self.paddle)
if overlap_sprites:
for sprite in overlap_sprites:
# Horizontal Collision
# Right of the ball colliding into the left of another sprite
if self.rect.right >= sprite.rect.left and self.previous_rect.right <= sprite.previous_rect.left:
self.rect.right = sprite.rect.left - 1
self.direction.x *= -1
# Left of the ball collinding into the right of another sprite
if self.rect.left <= sprite.rect.right and self.previous_rect.left >= sprite.previous_rect.right:
self.rect.left = sprite.rect.right + 1
self.direction.x *= -1
# Vertical Collision
# Top of the ball collinding into the bottom of another sprite
if self.rect.top <= sprite.rect.bottom and self.previous_rect.top >= sprite.previous_rect.bottom:
self.rect.top = sprite.rect.bottom + 1
self.direction.y *= -1
# Bottom of the ball collinding into the top of another sprite
if self.rect.bottom >= sprite.rect.top and self.previous_rect.bottom <= sprite.previous_rect.top:
self.rect.bottom = sprite.rect.top - 1
self.direction.y *= -1
# Check if sprite is a block with attribute strenght. Getattr calls Hasattr.
if getattr(sprite, 'strength', None):
sprite.damage()
def update(self):
self.input()
if self.active:
# Normalize the direction if it is moving diagonally (almost always the case)
# Withot normalizing it, the ball would move way faster when in long diagonals
if self.direction.magnitude() != 0:
self.direction = self.direction.normalize()
# Save last frame's rect position
self.previous_rect = self.rect.copy()
# Update position and check for collisions
self.rect.topleft += self.direction * self.speed
self.screen_collision()
self.collision()
else:
self.rect.midbottom = self.paddle.rect.midtop
| [
"random.uniform",
"pygame.sprite.spritecollide",
"pygame.key.get_pressed",
"pygame.image.load",
"pygame.transform.scale"
] | [((375, 419), 'pygame.transform.scale', 'pygame.transform.scale', (['self.image', '(30, 30)'], {}), '(self.image, (30, 30))\n', (397, 419), False, 'import pygame\n'), ((794, 818), 'pygame.key.get_pressed', 'pygame.key.get_pressed', ([], {}), '()\n', (816, 818), False, 'import pygame\n'), ((1568, 1621), 'pygame.sprite.spritecollide', 'pygame.sprite.spritecollide', (['self', 'self.blocks', '(False)'], {}), '(self, self.blocks, False)\n', (1595, 1621), False, 'import pygame\n'), ((667, 681), 'random.uniform', 'uniform', (['(-5)', '(5)'], {}), '(-5, 5)\n', (674, 681), False, 'from random import uniform\n'), ((277, 337), 'pygame.image.load', 'pygame.image.load', (["(BASE_DIR / 'assets' / 'imgs' / 'ball.png')"], {}), "(BASE_DIR / 'assets' / 'imgs' / 'ball.png')\n", (294, 337), False, 'import pygame\n'), ((998, 1012), 'random.uniform', 'uniform', (['(-5)', '(5)'], {}), '(-5, 5)\n', (1005, 1012), False, 'from random import uniform\n')] |
# Downloads all Sentinel 1 images from PolarView which were used for the latest Antarctic coastline mapping, in .tif format.
# Reference coastline: https://data.bas.ac.uk/collections/e74543c0-4c4e-4b41-aa33-5bb2f67df389/
import time
import requests
import csv
startTime = time.time()
base_URI = 'https://www.polarview.aq/images/104_S1geotiff/'
filenames = []
# Open list of filenames of S1 data used in making the reference coastline
# Add path to csv file below
with open('') as csvfile:
reader = csv.reader(csvfile)
next(reader) # Skip first line of CSV file
for row in reader:
filenames.append(row) # Save filenames as array
for name in filenames:
save_name = name[0] + '.tar.gz'
request_URI = base_URI + save_name
dl_response = requests.get(request_URI, stream=True)
if dl_response.status_code != 404:
# Add destination folder path below
path = '' + save_name
with open(path, "wb") as f:
for chunk in dl_response.iter_content(chunk_size=16*1024):
f.write(chunk)
print(save_name, "downloaded.")
else:
print(save_name,"could not be downloaded.")
executionTime = (time.time() - startTime)
print("Execution time: " + str(executionTime))
| [
"requests.get",
"time.time",
"csv.reader"
] | [((273, 284), 'time.time', 'time.time', ([], {}), '()\n', (282, 284), False, 'import time\n'), ((507, 526), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (517, 526), False, 'import csv\n'), ((778, 816), 'requests.get', 'requests.get', (['request_URI'], {'stream': '(True)'}), '(request_URI, stream=True)\n', (790, 816), False, 'import requests\n'), ((1187, 1198), 'time.time', 'time.time', ([], {}), '()\n', (1196, 1198), False, 'import time\n')] |
import os
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm
from PyPDF2 import PdfFileWriter, PdfFileReader
def create_watermark(text, path=None):
if path:
f_pdf = os.path.join(path, 'mark.pdf')
else:
f_pdf = 'mark.pdf'
w_pdf = 20 * cm
h_pdf = 20 * cm
c = canvas.Canvas(f_pdf, pagesize=(w_pdf, h_pdf))
c.setFillAlpha(0.6) # 设置透明度
c.drawString(3.5 * cm, 7 * cm, text)
c.showPage()
c.save()
return f_pdf
def add_watermark(pdf_file_mark, pdf_file_in, pdf_file_out):
with open(pdf_file_in, 'rb') as fp:
pdf_input = PdfFileReader(fp)
# PDF文件被加密了
if pdf_input.getIsEncrypted():
print('该PDF文件被加密了.')
# 尝试用空密码解密
try:
pdf_input.decrypt('')
except Exception:
print('尝试用空密码解密失败.')
return False
else:
print('用空密码解密成功.')
# 获取PDF文件的页数
pageNum = pdf_input.getNumPages()
with open(pdf_file_mark, 'rb') as mfp:
pdf_output = PdfFileWriter()
# 读入水印pdf文件
pdf_watermark = PdfFileReader(mfp)
# 给每一页打水印
for i in range(pageNum):
page = pdf_input.getPage(i)
page.mergePage(pdf_watermark.getPage(0))
page.compressContentStreams() # 压缩内容
pdf_output.addPage(page)
with open(pdf_file_out, 'wb') as wfp:
pdf_output.write(wfp)
| [
"PyPDF2.PdfFileWriter",
"PyPDF2.PdfFileReader",
"os.path.join",
"reportlab.pdfgen.canvas.Canvas"
] | [((334, 379), 'reportlab.pdfgen.canvas.Canvas', 'canvas.Canvas', (['f_pdf'], {'pagesize': '(w_pdf, h_pdf)'}), '(f_pdf, pagesize=(w_pdf, h_pdf))\n', (347, 379), False, 'from reportlab.pdfgen import canvas\n'), ((209, 239), 'os.path.join', 'os.path.join', (['path', '"""mark.pdf"""'], {}), "(path, 'mark.pdf')\n", (221, 239), False, 'import os\n'), ((636, 653), 'PyPDF2.PdfFileReader', 'PdfFileReader', (['fp'], {}), '(fp)\n', (649, 653), False, 'from PyPDF2 import PdfFileWriter, PdfFileReader\n'), ((1129, 1144), 'PyPDF2.PdfFileWriter', 'PdfFileWriter', ([], {}), '()\n', (1142, 1144), False, 'from PyPDF2 import PdfFileWriter, PdfFileReader\n'), ((1199, 1217), 'PyPDF2.PdfFileReader', 'PdfFileReader', (['mfp'], {}), '(mfp)\n', (1212, 1217), False, 'from PyPDF2 import PdfFileWriter, PdfFileReader\n')] |
from os import path, remove
import subprocess
from glob import glob
from shutil import move
import MDAnalysis as mda
from miscell.file_util import check_dir_exist_and_make, check_file_exist, copy_verbose
from miscell.na_bp import d_n_bp, d_type_na
from pdb_util.pdb import PDBReader, PDBWriter
class PreliminaryAgent:
d_new_resname = {'RA5': 'A', 'RA3': 'A', 'RA': 'A',
'RU5': 'U', 'RU3': 'U', 'RU': 'U',
'RC5': 'C', 'RC3': 'C', 'RC': 'C',
'RG5': 'G', 'RG3': 'G', 'RG': 'G'}
def __init__(self, rootfolder, host):
self.rootfolder = rootfolder
self.host = host
self.n_bp = d_n_bp[host]
self.host_folder = path.join(rootfolder, host)
self.pdb_xtc_folder = path.join(self.host_folder, 'pdb_xtc')
self.single_pdb_folder = path.join(self.host_folder, 'single_pdb')
self.lis_folder = path.join(self.host_folder, 'lis')
self.haxis_smooth_folder = path.join(self.host_folder, 'haxis_smooth')
self.workspace_folder = path.join(self.host_folder, 'workspace')
self.input_pdb_backup = path.join(self.pdb_xtc_folder, f'input.backup.pdb')
self.input_pdb = path.join(self.pdb_xtc_folder, f'input.pdb')
self.input_xtc = path.join(self.pdb_xtc_folder, f'input.xtc')
self.input_pdb_exist = None
self.input_xtc_exist = None
def initialize_folders(self):
for folder in [self.host_folder, self.pdb_xtc_folder, self.single_pdb_folder, self.lis_folder,
self.haxis_smooth_folder, self.workspace_folder]:
check_dir_exist_and_make(folder)
def check_input_pdb_xtc(self):
self.input_pdb_exist = check_file_exist(self.input_pdb)
self.input_xtc_exist = check_file_exist(self.input_xtc)
def copy_input_pdb_xtc(self, old_pdb, old_xtc):
copy_verbose(old_pdb, self.input_pdb)
copy_verbose(old_xtc, self.input_xtc)
self.check_input_pdb_xtc()
def vmd_check_pdb_xtc(self):
cmd = f'vmd -pdb {self.input_pdb} {self.input_xtc}'
print(cmd)
def vim_check_pdb(self):
resid_i = self.n_bp + 1
resid_j = self.n_bp * 2
print(f'Please check the resid of second strand is from {resid_i} to {resid_j}')
print('If not, please add A and B at the end of the lines for the two strands by vim command')
print(":{line_begin},{line_end}s/$/A/g")
print(":{line_begin},{line_end}s/$/B/g")
print('Remember to trim the file becuase of PDBReader skip_header=1, skip_footer=1')
print(f'vim {self.input_pdb}')
def check_rna_with_modify_resname(self):
if self.is_rna():
copy_verbose(self.input_pdb, self.input_pdb_backup)
reader = PDBReader(self.input_pdb, segid_exist=False)
atgs = reader.get_atomgroup()
for atom in atgs:
self.modify_rna_resname(atom)
writer = PDBWriter(self.input_pdb, atgs)
writer.write_pdb()
def is_rna(self):
type_na = d_type_na[self.host]
return type_na == 'arna+arna'
def modify_rna_resname(self, atom):
new_resname = self.d_new_resname[atom.resname]
atom.set_resname(new_resname)
def change_input_pdb_resid(self, execute=False):
if execute:
copy_verbose(self.input_pdb, self.input_pdb_backup)
reader = PDBReader(self.input_pdb, segid_exist=True)
atgs = reader.get_atomgroup()
for atom in atgs:
if atom.segid == 'B':
atom.resid += self.n_bp
writer = PDBWriter(self.input_pdb, atgs)
writer.write_pdb()
class ExtractPDBAgent(PreliminaryAgent):
def __init__(self, rootfolder, host):
super().__init__(rootfolder, host)
self.u = mda.Universe(self.input_pdb, self.input_xtc)
def get_n_frames(self):
return len(self.u.trajectory)
def print_n_frames(self):
n_frame = self.get_n_frames()
print(f'n_frame: {n_frame}')
def extract_pdb_from_xtc(self, start_frame, stop_frame):
for ts in self.u.trajectory[start_frame:stop_frame]:
pdb_out = path.join(self.single_pdb_folder, f'{ts.frame}.pdb')
self.process_single_frame(pdb_out)
if ts.frame % 500 == 0:
print(f'Extract PDB for {self.host}, Frame-ID: {ts.frame}')
def process_single_frame(self, pdb_out):
with mda.Writer(pdb_out, bonds=None, n_atoms=self.u.atoms.n_atoms) as PDBOUT:
PDBOUT.write(self.u.atoms)
class ExecCurvesAgent(ExtractPDBAgent):
lis_name = 'r+bdna'
def execute_curve_plus(self, start_frame, stop_frame):
for frame_id in range(start_frame, stop_frame):
self.clean_files()
f_single_pdb = path.join(self.single_pdb_folder, f'{frame_id}.pdb')
# Start to execute curves
cmd = self.get_exectue_curve_plus_cmd(f_single_pdb)
errlog = open(path.join(self.workspace_folder, 'err.log'), 'w')
outlog = open(path.join(self.workspace_folder, 'out.log'), 'w')
subprocess.run(cmd, shell=True, stdout=outlog, stderr=errlog,check=False)
errlog.close()
outlog.close()
# Store .lis and _X.pdb files
workspace_lis = path.join(self.workspace_folder, f'{self.lis_name}.lis')
workspace_pdb = path.join(self.workspace_folder, f'{self.lis_name}_X.pdb')
f_lis = path.join(self.lis_folder, f'{frame_id}.lis')
f_x_pdb = path.join(self.haxis_smooth_folder, f'{frame_id}.pdb')
move(workspace_lis, f_lis)
move(workspace_pdb, f_x_pdb)
if frame_id % 500 == 0:
print(f'Curves+ for {self.host}, Frame-ID: {frame_id}')
def clean_files(self):
pathname = path.join(self.workspace_folder, f'{self.lis_name}*')
filelist = glob(pathname)
if len(filelist) != 0:
for fname in filelist:
remove(fname)
def get_exectue_curve_plus_cmd(self, f_single_pdb):
curve = '/home/yizaochen/opt/curves+/Cur+'
inp_end_txt = self.get_inp_end(f_single_pdb)
n1, n2, n3, n4 = self.get_four_numbers()
cmd1 = f'{curve} <<!\n'
cmd2 = f' &inp {inp_end_txt}&end\n'
cmd3 = '2 1 -1 0 0\n'
cmd4 = f'{n1}:{n2}\n'
cmd5 = f'{n3}:{n4}\n'
cmd6 = '!'
return cmd1 + cmd2 + cmd3 + cmd4 + cmd5 + cmd6
def get_inp_end(self, f_single_pdb):
curve_folder = '/home/yizaochen/opt/curves+/standard'
lis = path.join(self.workspace_folder, self.lis_name)
return f'file={f_single_pdb},\n lis={lis},\n lib={curve_folder},\n naxlim=3'
def get_four_numbers(self):
return 1, self.n_bp, 2*self.n_bp, self.n_bp+1
| [
"miscell.file_util.check_file_exist",
"miscell.file_util.check_dir_exist_and_make",
"shutil.move",
"subprocess.run",
"os.path.join",
"MDAnalysis.Writer",
"pdb_util.pdb.PDBReader",
"pdb_util.pdb.PDBWriter",
"MDAnalysis.Universe",
"miscell.file_util.copy_verbose",
"glob.glob",
"os.remove"
] | [((710, 737), 'os.path.join', 'path.join', (['rootfolder', 'host'], {}), '(rootfolder, host)\n', (719, 737), False, 'from os import path, remove\n'), ((768, 806), 'os.path.join', 'path.join', (['self.host_folder', '"""pdb_xtc"""'], {}), "(self.host_folder, 'pdb_xtc')\n", (777, 806), False, 'from os import path, remove\n'), ((840, 881), 'os.path.join', 'path.join', (['self.host_folder', '"""single_pdb"""'], {}), "(self.host_folder, 'single_pdb')\n", (849, 881), False, 'from os import path, remove\n'), ((908, 942), 'os.path.join', 'path.join', (['self.host_folder', '"""lis"""'], {}), "(self.host_folder, 'lis')\n", (917, 942), False, 'from os import path, remove\n'), ((978, 1021), 'os.path.join', 'path.join', (['self.host_folder', '"""haxis_smooth"""'], {}), "(self.host_folder, 'haxis_smooth')\n", (987, 1021), False, 'from os import path, remove\n'), ((1054, 1094), 'os.path.join', 'path.join', (['self.host_folder', '"""workspace"""'], {}), "(self.host_folder, 'workspace')\n", (1063, 1094), False, 'from os import path, remove\n'), ((1128, 1179), 'os.path.join', 'path.join', (['self.pdb_xtc_folder', 'f"""input.backup.pdb"""'], {}), "(self.pdb_xtc_folder, f'input.backup.pdb')\n", (1137, 1179), False, 'from os import path, remove\n'), ((1205, 1249), 'os.path.join', 'path.join', (['self.pdb_xtc_folder', 'f"""input.pdb"""'], {}), "(self.pdb_xtc_folder, f'input.pdb')\n", (1214, 1249), False, 'from os import path, remove\n'), ((1275, 1319), 'os.path.join', 'path.join', (['self.pdb_xtc_folder', 'f"""input.xtc"""'], {}), "(self.pdb_xtc_folder, f'input.xtc')\n", (1284, 1319), False, 'from os import path, remove\n'), ((1716, 1748), 'miscell.file_util.check_file_exist', 'check_file_exist', (['self.input_pdb'], {}), '(self.input_pdb)\n', (1732, 1748), False, 'from miscell.file_util import check_dir_exist_and_make, check_file_exist, copy_verbose\n'), ((1780, 1812), 'miscell.file_util.check_file_exist', 'check_file_exist', (['self.input_xtc'], {}), '(self.input_xtc)\n', (1796, 1812), False, 'from miscell.file_util import check_dir_exist_and_make, check_file_exist, copy_verbose\n'), ((1874, 1911), 'miscell.file_util.copy_verbose', 'copy_verbose', (['old_pdb', 'self.input_pdb'], {}), '(old_pdb, self.input_pdb)\n', (1886, 1911), False, 'from miscell.file_util import check_dir_exist_and_make, check_file_exist, copy_verbose\n'), ((1920, 1957), 'miscell.file_util.copy_verbose', 'copy_verbose', (['old_xtc', 'self.input_xtc'], {}), '(old_xtc, self.input_xtc)\n', (1932, 1957), False, 'from miscell.file_util import check_dir_exist_and_make, check_file_exist, copy_verbose\n'), ((3846, 3890), 'MDAnalysis.Universe', 'mda.Universe', (['self.input_pdb', 'self.input_xtc'], {}), '(self.input_pdb, self.input_xtc)\n', (3858, 3890), True, 'import MDAnalysis as mda\n'), ((5880, 5933), 'os.path.join', 'path.join', (['self.workspace_folder', 'f"""{self.lis_name}*"""'], {}), "(self.workspace_folder, f'{self.lis_name}*')\n", (5889, 5933), False, 'from os import path, remove\n'), ((5953, 5967), 'glob.glob', 'glob', (['pathname'], {}), '(pathname)\n', (5957, 5967), False, 'from glob import glob\n'), ((6633, 6680), 'os.path.join', 'path.join', (['self.workspace_folder', 'self.lis_name'], {}), '(self.workspace_folder, self.lis_name)\n', (6642, 6680), False, 'from os import path, remove\n'), ((1616, 1648), 'miscell.file_util.check_dir_exist_and_make', 'check_dir_exist_and_make', (['folder'], {}), '(folder)\n', (1640, 1648), False, 'from miscell.file_util import check_dir_exist_and_make, check_file_exist, copy_verbose\n'), ((2706, 2757), 'miscell.file_util.copy_verbose', 'copy_verbose', (['self.input_pdb', 'self.input_pdb_backup'], {}), '(self.input_pdb, self.input_pdb_backup)\n', (2718, 2757), False, 'from miscell.file_util import check_dir_exist_and_make, check_file_exist, copy_verbose\n'), ((2779, 2823), 'pdb_util.pdb.PDBReader', 'PDBReader', (['self.input_pdb'], {'segid_exist': '(False)'}), '(self.input_pdb, segid_exist=False)\n', (2788, 2823), False, 'from pdb_util.pdb import PDBReader, PDBWriter\n'), ((2963, 2994), 'pdb_util.pdb.PDBWriter', 'PDBWriter', (['self.input_pdb', 'atgs'], {}), '(self.input_pdb, atgs)\n', (2972, 2994), False, 'from pdb_util.pdb import PDBReader, PDBWriter\n'), ((3346, 3397), 'miscell.file_util.copy_verbose', 'copy_verbose', (['self.input_pdb', 'self.input_pdb_backup'], {}), '(self.input_pdb, self.input_pdb_backup)\n', (3358, 3397), False, 'from miscell.file_util import check_dir_exist_and_make, check_file_exist, copy_verbose\n'), ((3419, 3462), 'pdb_util.pdb.PDBReader', 'PDBReader', (['self.input_pdb'], {'segid_exist': '(True)'}), '(self.input_pdb, segid_exist=True)\n', (3428, 3462), False, 'from pdb_util.pdb import PDBReader, PDBWriter\n'), ((3639, 3670), 'pdb_util.pdb.PDBWriter', 'PDBWriter', (['self.input_pdb', 'atgs'], {}), '(self.input_pdb, atgs)\n', (3648, 3670), False, 'from pdb_util.pdb import PDBReader, PDBWriter\n'), ((4217, 4269), 'os.path.join', 'path.join', (['self.single_pdb_folder', 'f"""{ts.frame}.pdb"""'], {}), "(self.single_pdb_folder, f'{ts.frame}.pdb')\n", (4226, 4269), False, 'from os import path, remove\n'), ((4488, 4549), 'MDAnalysis.Writer', 'mda.Writer', (['pdb_out'], {'bonds': 'None', 'n_atoms': 'self.u.atoms.n_atoms'}), '(pdb_out, bonds=None, n_atoms=self.u.atoms.n_atoms)\n', (4498, 4549), True, 'import MDAnalysis as mda\n'), ((4839, 4891), 'os.path.join', 'path.join', (['self.single_pdb_folder', 'f"""{frame_id}.pdb"""'], {}), "(self.single_pdb_folder, f'{frame_id}.pdb')\n", (4848, 4891), False, 'from os import path, remove\n'), ((5160, 5234), 'subprocess.run', 'subprocess.run', (['cmd'], {'shell': '(True)', 'stdout': 'outlog', 'stderr': 'errlog', 'check': '(False)'}), '(cmd, shell=True, stdout=outlog, stderr=errlog, check=False)\n', (5174, 5234), False, 'import subprocess\n'), ((5358, 5414), 'os.path.join', 'path.join', (['self.workspace_folder', 'f"""{self.lis_name}.lis"""'], {}), "(self.workspace_folder, f'{self.lis_name}.lis')\n", (5367, 5414), False, 'from os import path, remove\n'), ((5443, 5501), 'os.path.join', 'path.join', (['self.workspace_folder', 'f"""{self.lis_name}_X.pdb"""'], {}), "(self.workspace_folder, f'{self.lis_name}_X.pdb')\n", (5452, 5501), False, 'from os import path, remove\n'), ((5522, 5567), 'os.path.join', 'path.join', (['self.lis_folder', 'f"""{frame_id}.lis"""'], {}), "(self.lis_folder, f'{frame_id}.lis')\n", (5531, 5567), False, 'from os import path, remove\n'), ((5590, 5644), 'os.path.join', 'path.join', (['self.haxis_smooth_folder', 'f"""{frame_id}.pdb"""'], {}), "(self.haxis_smooth_folder, f'{frame_id}.pdb')\n", (5599, 5644), False, 'from os import path, remove\n'), ((5657, 5683), 'shutil.move', 'move', (['workspace_lis', 'f_lis'], {}), '(workspace_lis, f_lis)\n', (5661, 5683), False, 'from shutil import move\n'), ((5696, 5724), 'shutil.move', 'move', (['workspace_pdb', 'f_x_pdb'], {}), '(workspace_pdb, f_x_pdb)\n', (5700, 5724), False, 'from shutil import move\n'), ((5022, 5065), 'os.path.join', 'path.join', (['self.workspace_folder', '"""err.log"""'], {}), "(self.workspace_folder, 'err.log')\n", (5031, 5065), False, 'from os import path, remove\n'), ((5098, 5141), 'os.path.join', 'path.join', (['self.workspace_folder', '"""out.log"""'], {}), "(self.workspace_folder, 'out.log')\n", (5107, 5141), False, 'from os import path, remove\n'), ((6050, 6063), 'os.remove', 'remove', (['fname'], {}), '(fname)\n', (6056, 6063), False, 'from os import path, remove\n')] |
import pandas as pd
import streamlit as st
def get_player_data(teams_data, player_name):
for team in teams_data:
for player in team['players']:
if player['name'] == player_name:
player['win'] = team['winner']
return player
return None
def get_player_team(teams_data, player_name):
for team in teams_data:
is_team = False
for player in team['players']:
player['win'] = 1 if team['winner'] else 0
if player['name'] == player_name:
is_team = True
if is_team:
return team['players']
return None
def get_player_matches(matches_df, player_name):
matches_df['player_data'] = matches_df['teams'].apply(
lambda match_teams: get_player_data(match_teams, player_name))
return matches_df[matches_df['player_data'].notnull()]
def get_player_matches_data(matches_df, player_name):
player_matches = get_player_matches(matches_df, player_name)
return pd.DataFrame(player_matches['player_data'].tolist())
def get_player_vs(matches_df, player_name):
player_matches = get_player_matches(matches_df, player_name)
player_matches['teammates'] = player_matches['teams'].apply(
lambda team: get_player_team(team, player_name))
teammates_list = [element for sublist in player_matches['teammates'].tolist()
for element in sublist]
teammates = pd.DataFrame(teammates_list)
teammates = teammates[teammates['name'] != player_name]
teammates['team'] = teammates['name'].apply(
lambda player_name: player_name.split()[0])
st.write("All teammates")
st.write(teammates)
# let's only return top 10 most played with for more readability
most_played_with_names = teammates['name'].value_counts().head(
10).index.tolist()
most_played_with = teammates[teammates['name'].isin(
most_played_with_names)]
return most_played_with
| [
"pandas.DataFrame",
"streamlit.write"
] | [((1443, 1471), 'pandas.DataFrame', 'pd.DataFrame', (['teammates_list'], {}), '(teammates_list)\n', (1455, 1471), True, 'import pandas as pd\n'), ((1638, 1663), 'streamlit.write', 'st.write', (['"""All teammates"""'], {}), "('All teammates')\n", (1646, 1663), True, 'import streamlit as st\n'), ((1668, 1687), 'streamlit.write', 'st.write', (['teammates'], {}), '(teammates)\n', (1676, 1687), True, 'import streamlit as st\n')] |
# Demonstrates the use of transformation matrices.
from miniipe import Document, Rotate, Translate, Scale, polyline
doc = Document()
doc.import_stylefile()
doc.add_layout( page=(640,640) )
doc.add_layer('alpha')
# Iteratively tweak a transformation matrix.
# (Matrix multiplication with the @ operator.)
ps = [(10,0),(20,0),(19,1),(19,-1),(20,0)]
M = Translate( (300,300) )
for _ in range(207):
doc.use( pos=(0,0), name='mark/cross(sx)', matrix=M )
doc.path( polyline(ps), matrix=M)
M @= Rotate(0.1) @ Translate( (3,1) ) @ Scale(1.01)
doc.write('matrix_fun.ipe') | [
"miniipe.Rotate",
"miniipe.Scale",
"miniipe.Document",
"miniipe.polyline",
"miniipe.Translate"
] | [((124, 134), 'miniipe.Document', 'Document', ([], {}), '()\n', (132, 134), False, 'from miniipe import Document, Rotate, Translate, Scale, polyline\n'), ((354, 375), 'miniipe.Translate', 'Translate', (['(300, 300)'], {}), '((300, 300))\n', (363, 375), False, 'from miniipe import Document, Rotate, Translate, Scale, polyline\n'), ((470, 482), 'miniipe.polyline', 'polyline', (['ps'], {}), '(ps)\n', (478, 482), False, 'from miniipe import Document, Rotate, Translate, Scale, polyline\n'), ((538, 549), 'miniipe.Scale', 'Scale', (['(1.01)'], {}), '(1.01)\n', (543, 549), False, 'from miniipe import Document, Rotate, Translate, Scale, polyline\n'), ((503, 514), 'miniipe.Rotate', 'Rotate', (['(0.1)'], {}), '(0.1)\n', (509, 514), False, 'from miniipe import Document, Rotate, Translate, Scale, polyline\n'), ((517, 534), 'miniipe.Translate', 'Translate', (['(3, 1)'], {}), '((3, 1))\n', (526, 534), False, 'from miniipe import Document, Rotate, Translate, Scale, polyline\n')] |
import random
import numpy as np
from pybullet_planning import multiply, interval_generator
from pybullet_planning import Pose, Point, Euler
def get_random_direction_generator(**kwargs):
lower = [-np.pi, -np.pi]
upper = [+np.pi, +np.pi]
for [roll, pitch] in interval_generator(lower, upper, **kwargs):
pose = Pose(euler=Euler(roll=roll, pitch=pitch))
yield pose
def get_enumeration_pose_generator(pose_list, shuffle=False):
if shuffle:
random.shuffle(pose_list)
for p in pose_list:
yield p
| [
"pybullet_planning.interval_generator",
"random.shuffle",
"pybullet_planning.Euler"
] | [((273, 315), 'pybullet_planning.interval_generator', 'interval_generator', (['lower', 'upper'], {}), '(lower, upper, **kwargs)\n', (291, 315), False, 'from pybullet_planning import multiply, interval_generator\n'), ((481, 506), 'random.shuffle', 'random.shuffle', (['pose_list'], {}), '(pose_list)\n', (495, 506), False, 'import random\n'), ((343, 372), 'pybullet_planning.Euler', 'Euler', ([], {'roll': 'roll', 'pitch': 'pitch'}), '(roll=roll, pitch=pitch)\n', (348, 372), False, 'from pybullet_planning import Pose, Point, Euler\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue May 12 08:23:58 2020
@author: sumanth
"""
import numpy as np
import cv2
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array
def pre_dect(frame,faceNet,model):
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300),(104.0, 177.0, 123.0))
faceNet.setInput(blob)
detections = faceNet.forward()
faces = []
locs = []
preds = []
for i in range(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence >= 0.168:
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
(startX, startY) = (max(0, startX), max(0, startY))
(endX, endY) = (min(w - 1, endX), min(h - 1, endY))
face = frame[startY:endY, startX:endX]
face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
face = cv2.resize(face, (224, 224))
face = img_to_array(face)
face = preprocess_input(face)
face = np.expand_dims(face, axis=0)
faces.append(face)
locs.append((startX, startY, endX, endY))
for k in faces:
preds.append(model.predict(k))
return (locs, preds)
| [
"cv2.dnn.blobFromImage",
"numpy.array",
"tensorflow.keras.applications.mobilenet_v2.preprocess_input",
"cv2.cvtColor",
"numpy.expand_dims",
"tensorflow.keras.preprocessing.image.img_to_array",
"cv2.resize"
] | [((341, 409), 'cv2.dnn.blobFromImage', 'cv2.dnn.blobFromImage', (['frame', '(1.0)', '(300, 300)', '(104.0, 177.0, 123.0)'], {}), '(frame, 1.0, (300, 300), (104.0, 177.0, 123.0))\n', (362, 409), False, 'import cv2\n'), ((976, 1013), 'cv2.cvtColor', 'cv2.cvtColor', (['face', 'cv2.COLOR_BGR2RGB'], {}), '(face, cv2.COLOR_BGR2RGB)\n', (988, 1013), False, 'import cv2\n'), ((1034, 1062), 'cv2.resize', 'cv2.resize', (['face', '(224, 224)'], {}), '(face, (224, 224))\n', (1044, 1062), False, 'import cv2\n'), ((1083, 1101), 'tensorflow.keras.preprocessing.image.img_to_array', 'img_to_array', (['face'], {}), '(face)\n', (1095, 1101), False, 'from tensorflow.keras.preprocessing.image import img_to_array\n'), ((1122, 1144), 'tensorflow.keras.applications.mobilenet_v2.preprocess_input', 'preprocess_input', (['face'], {}), '(face)\n', (1138, 1144), False, 'from tensorflow.keras.applications.mobilenet_v2 import preprocess_input\n'), ((1165, 1193), 'numpy.expand_dims', 'np.expand_dims', (['face'], {'axis': '(0)'}), '(face, axis=0)\n', (1179, 1193), True, 'import numpy as np\n'), ((689, 711), 'numpy.array', 'np.array', (['[w, h, w, h]'], {}), '([w, h, w, h])\n', (697, 711), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import os.path
import config
import experiment_lib
import lightgbm as lgb
class LightGBMExperimentEarlyStopping(experiment_lib.ExperimentEarlyStopping):
def __init__(self, **kwargs):
super(LightGBMExperimentEarlyStopping, self).__init__(**kwargs)
def get_estimator(self, cat_cols):
return lgb.LGBMRegressor(
n_jobs=16,
n_estimators=9999
)
def fit_estimator(self, estimator, X_train, y_train, X_test, y_test, cat_cols, early_stopping_rounds):
estimator.fit(
X_train,
y_train,
categorical_feature=cat_cols,
eval_set=[(X_test, y_test)],
eval_metric='rmse',
early_stopping_rounds=early_stopping_rounds
)
self.best_estimator = estimator
self.best_iteration = estimator.best_iteration_
self.best_params = estimator.get_params()
self.best_score = estimator.best_score_
if __name__ == "__main__":
dataset_path = config.preprocessed_dataset_path
LightGBMExperimentEarlyStopping(
train_path=os.path.join(config.preprocessed_dataset_path, 'train'),
test_path=os.path.join(config.preprocessed_dataset_path, 'test'),
cd_path=os.path.join(config.preprocessed_dataset_path, 'cd'),
output_folder_path=os.path.join(config.training_output_path, 'LightGBMExperimentEarlyStopping'),
header_in_data=False
).run()
| [
"lightgbm.LGBMRegressor"
] | [((342, 389), 'lightgbm.LGBMRegressor', 'lgb.LGBMRegressor', ([], {'n_jobs': '(16)', 'n_estimators': '(9999)'}), '(n_jobs=16, n_estimators=9999)\n', (359, 389), True, 'import lightgbm as lgb\n')] |
#
# Incremental Def Writer -- Brown University
#
# Copyright (C) 2019 Brown University
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# By: <NAME> 2019
# <EMAIL>
# --------------------- merge_defs ---------------------------------
# this function merges two def files where one is placed and the second is not
# it gives a modified def files which is similar to the unplaced one but modify the placements of the cells that exist in the first placed one
# Inputs:
# placed_components_map: map with components of the placed def
# placed_pins_map: map with pins of the placed def
# unplaced_components_map: map with the components of the unplaced def
# unplaced_nets_map: map with the nets of the unplaced def
# Output:
# merged_components_map: map with a merged def
# ------------------------------------------------------------------
#!/usr/bin/env python3
from utils import get_connected_components
def merge_defs(placed_components_map,placed_pins_map,unplaced_components_map,unplaced_nets_map,merged_components_map):
not_done = False
max_itter = 2
for component in unplaced_components_map:
if "x_location" in component:
continue
if component in placed_components_map.keys():
merged_components_map[component] = unplaced_components_map[component]
merged_components_map[component]["x_location"] = placed_components_map[component]["x_location"]
merged_components_map[component]["y_location"] = placed_components_map[component]["y_location"]
else:
merged_components_map[component] = unplaced_components_map[component]
gate_conn = []
get_connected_components(component,gate_conn,unplaced_nets_map)
x_coor_list = []
y_coor_list = []
for item in gate_conn:
if item in placed_components_map:
x_coor_list.append(int(placed_components_map[item]["x_location"]))
y_coor_list.append(int(placed_components_map[item]["y_location"]))
elif item in placed_pins_map:
x_coor_list.append(int(placed_pins_map[item]["x_location"]))
y_coor_list.append(int(placed_pins_map[item]["y_location"]))
if len(x_coor_list) == 0:
not_done = True
print("Skipped "),
print(component)
continue
min_x = min(x_coor_list)
min_y = min(y_coor_list)
max_x = max(x_coor_list)
max_y = max(y_coor_list)
merged_components_map[component]["x_location"] = int((max(x_coor_list)+min(x_coor_list))/2)
merged_components_map[component]["y_location"] = int((max(y_coor_list)+min(y_coor_list))/2)
| [
"utils.get_connected_components"
] | [((2362, 2427), 'utils.get_connected_components', 'get_connected_components', (['component', 'gate_conn', 'unplaced_nets_map'], {}), '(component, gate_conn, unplaced_nets_map)\n', (2386, 2427), False, 'from utils import get_connected_components\n')] |
#! /usr/bin/env python3
import argparse
from pathlib import Path
import sys
from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc
C0_OFF = "Task: C0, Corunner: OFF"
C0_ON = "Task: C0, Corunner: ON"
C0_ON_LOCAL = "Task: C0, Corunner: ON (Local)"
C1_OFF = "Task: C1, Corunner: OFF"
C1_ON = "Task: C1, Corunner: ON"
C1_ON_LOCAL = "Task: C1, Corunner: ON (Local)"
def getopts(argv):
parser = argparse.ArgumentParser()
parser.add_argument("--kdbv", type=Path, required=True)
parser.add_argument("--kcfg", type=Path, required=True)
parser.add_argument("--kapp", type=Path, required=True)
parser.add_argument("--c0-off", type=Path, required=True)
parser.add_argument("--c0-on", type=Path, required=True)
parser.add_argument("--c0-on-local", type=Path, required=True)
parser.add_argument("--c1-off", type=Path, required=True)
parser.add_argument("--c1-on", type=Path, required=True)
parser.add_argument("--c1-on-local", type=Path, required=True)
parser.add_argument("--output-dir", "-o", type=Path, required=True)
parser.add_argument("--task", choices=["FLASH"], required=True)
parser.add_argument("--stats", action='store_true')
return parser.parse_args(argv[1:])
def gen_r_script(data, out_dir):
script = f"""
library("rjson")
library("vioplot")
pdf(file="out.pdf", width=8, height=4)
par(mfrow=c(2,2), mar=c(3,3,1,1))
"""
for core in ["1", "2"]:
for ea in ["F1", "F2"]:
cval = int(core) - 1
script += f"""
# For EA {ea} (core {core}) #########################
result <- fromJSON(file = "{ea}.json")
data <- as.data.frame(result)
g <- data[ data$group == "Core {core}" , ]
# n: number of samples per plot
t <- paste0("{ea} (core={core}, n=", dim(g)/3, ")")
m1 <- g$values[ g$sample=="Task: C{cval}, Corunner: OFF" ]
m2 <- g$values[ g$sample=="Task: C{cval}, Corunner: ON (Local)" ]
m3 <- g$values[ g$sample=="Task: C{cval}, Corunner: ON" ]
# I'm sorry for doing this... but the hardware target is so deterministic
# that sometimes I get measures for one EA that are systematically the same,
# so I end up with a big data frame with the same value that gets repeated.
# This does not go well with violplot...
# So, if all my values are identical, I add 1e-11 to my very first measure,
# so it can be taken as-is by vioplot to displpay a horizontal bar.
# Sorry, I'm too unfamiliar with R and such things...
# I don't think this is significant, though, as my measures are precise at
# 1e-7. So adding 1e^-11 JUST FOR THE DISPLAY should not harm in any way.
if (length(unique(m1)) == 1) {{ m1[1] <- m1[1] + 1e-11 }}
if (length(unique(m2)) == 1) {{ m2[1] <- m2[1] + 1e-11 }}
if (length(unique(m3)) == 1) {{ m3[1] <- m3[1] + 1e-11 }}
vioplot(
m1,
m2,
m3,
col="grey75", line=2.1,
xlab=t, ylab="Time (ms)"
)
"""
script += "dev.off()\n"
out_dir.mkdir(parents=True, exist_ok=True)
with open(out_dir / "plot.R", "w") as stream:
stream.write(script)
def gen_stats(data):
table = [
dict(),
dict(),
]
for ea, info in data.items():
values = {
C0_OFF: 0.0,
C0_ON: 0.0,
C0_ON_LOCAL: 0.0,
C1_OFF: 0.0,
C1_ON: 0.0,
C1_ON_LOCAL: 0.0,
}
for value, sample in zip(info["values"], info["sample"]):
assert sample in values, f"Unknown sample {sample}"
values[sample] = max(values[sample], value)
r0a = calc(values[C0_OFF], values[C0_ON_LOCAL])
r0b = calc(values[C0_OFF], values[C0_ON])
r1a = calc(values[C1_OFF], values[C1_ON_LOCAL])
r1b = calc(values[C1_OFF], values[C1_ON])
table[0][ea] = [
values[C0_OFF],
values[C0_ON_LOCAL],
values[C0_ON],
r0a,
r0b,
]
table[1][ea] = [
values[C1_OFF],
values[C1_ON_LOCAL],
values[C1_ON],
r1a,
r1b,
]
text = r"""
\begin{tabular}{ |c|c|r|r|r|r|r| }\hline
& \textbf{EA} & \textbf{max(1)} \textit{(ms)} & \textbf{max(2)} \textit{(ms)} & \textbf{max(3)} \textit{(ms)} & %
$\bm{R(1, 2)}$ \textit{(\%)}& %
$\bm{R(1, 3)}$ \textit{(\%)} %
\\\hline
"""
for core, core_info in enumerate(table, 1):
line = 0
for ea, info in sorted(core_info.items()):
if ea == "F0":
continue
if line == 0:
text += r"\multirow{2}{*}{" + f"\\textbf{{Core {core}}}" + r'}'
line += 1
text += f' & {ea} & {info[0]:.3f} & {info[1]:.3f} & '
text += f'{info[2]:.3f} & {info[3]:.3f} & {info[4]:.3f}'
text += '\\\\'
if line == 2:
text += r'\hline'
text += '\n'
text += r"""\hline
\end{tabular}
"""
print(text)
def main(argv):
args = getopts(argv)
# Map indexed by EA:
# (src,dst) => name
ea_to_name, name_to_ea = get_nodes_to_ea(args)
data = {
C0_OFF: decode_file(args.c0_off),
C0_ON: decode_file(args.c0_on),
C0_ON_LOCAL: decode_file(args.c0_on_local),
C1_OFF: decode_file(args.c1_off),
C1_ON: decode_file(args.c1_on),
C1_ON_LOCAL: decode_file(args.c1_on_local),
}
groups = {
C0_OFF: ("Core 1", "OFF", False),
C0_ON: ("Core 1", "ON", False),
C0_ON_LOCAL: ("Core 1", "ON", True),
C1_OFF: ("Core 2", "OFF", False),
C1_ON: ("Core 2", "ON", False),
C1_ON_LOCAL: ("Core 2", "ON", True),
}
jdata = gen_json_data(data, ea_to_name, args.output_dir, groups)
gen_r_script(jdata, args.output_dir)
if args.stats:
gen_stats(jdata)
if __name__ == "__main__":
main(sys.argv)
| [
"argparse.ArgumentParser",
"scriptutil.gen_json_data",
"scriptutil.calc",
"scriptutil.get_nodes_to_ea",
"scriptutil.decode_file"
] | [((414, 439), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (437, 439), False, 'import argparse\n'), ((4996, 5017), 'scriptutil.get_nodes_to_ea', 'get_nodes_to_ea', (['args'], {}), '(args)\n', (5011, 5017), False, 'from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc\n'), ((5595, 5651), 'scriptutil.gen_json_data', 'gen_json_data', (['data', 'ea_to_name', 'args.output_dir', 'groups'], {}), '(data, ea_to_name, args.output_dir, groups)\n', (5608, 5651), False, 'from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc\n'), ((3499, 3540), 'scriptutil.calc', 'calc', (['values[C0_OFF]', 'values[C0_ON_LOCAL]'], {}), '(values[C0_OFF], values[C0_ON_LOCAL])\n', (3503, 3540), False, 'from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc\n'), ((3555, 3590), 'scriptutil.calc', 'calc', (['values[C0_OFF]', 'values[C0_ON]'], {}), '(values[C0_OFF], values[C0_ON])\n', (3559, 3590), False, 'from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc\n'), ((3605, 3646), 'scriptutil.calc', 'calc', (['values[C1_OFF]', 'values[C1_ON_LOCAL]'], {}), '(values[C1_OFF], values[C1_ON_LOCAL])\n', (3609, 3646), False, 'from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc\n'), ((3661, 3696), 'scriptutil.calc', 'calc', (['values[C1_OFF]', 'values[C1_ON]'], {}), '(values[C1_OFF], values[C1_ON])\n', (3665, 3696), False, 'from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc\n'), ((5048, 5072), 'scriptutil.decode_file', 'decode_file', (['args.c0_off'], {}), '(args.c0_off)\n', (5059, 5072), False, 'from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc\n'), ((5089, 5112), 'scriptutil.decode_file', 'decode_file', (['args.c0_on'], {}), '(args.c0_on)\n', (5100, 5112), False, 'from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc\n'), ((5135, 5164), 'scriptutil.decode_file', 'decode_file', (['args.c0_on_local'], {}), '(args.c0_on_local)\n', (5146, 5164), False, 'from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc\n'), ((5182, 5206), 'scriptutil.decode_file', 'decode_file', (['args.c1_off'], {}), '(args.c1_off)\n', (5193, 5206), False, 'from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc\n'), ((5223, 5246), 'scriptutil.decode_file', 'decode_file', (['args.c1_on'], {}), '(args.c1_on)\n', (5234, 5246), False, 'from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc\n'), ((5269, 5298), 'scriptutil.decode_file', 'decode_file', (['args.c1_on_local'], {}), '(args.c1_on_local)\n', (5280, 5298), False, 'from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc\n')] |
# -*- coding: utf-8 -*-
from csv import DictWriter
from os import path
from app_logger import app_logging
from execution_error import ExecutionError
class DeviceDataCsvWriter:
def __init__(self):
self.csv_writer = None
@staticmethod
def __get_merged_dict(log_date_time, dev_data, dev_names):
if len(dev_names) != len(dev_data):
raise ExecutionError('Device data and device names length mismatch')
header_to_zip = [f'{n}_{key}' for n, d in zip(dev_names, dev_data) for key in d.keys()]
data_to_zip = [v for d in dev_data for v in d.values()]
header_to_zip.insert(0, 'Date_Time')
data_to_zip.insert(0, log_date_time)
return dict(zip(header_to_zip, data_to_zip))
def __write_data_to_file(self, file_path, dev_data, write_header=False):
dev_names = dev_data.dev_names
dev_data_readouts = dev_data.dev_data_readouts
log_date_time = dev_data.log_date_time_csv
try:
with open(file_path, 'a') as csv_file:
data_merged = self.__get_merged_dict(log_date_time, dev_data_readouts, dev_names)
self.csv_writer = DictWriter(csv_file,
fieldnames=data_merged.keys(),
delimiter=',')
if write_header:
self.csv_writer.writeheader()
self.csv_writer.writerow(data_merged)
app_logging.debug('Written device data:\n%s to:\n%s',
data_merged, file_path)
except (IOError, OSError, PermissionError):
app_logging.error('Error while writing to: [%s]', file_path)
def write_data(self, file_path, dev_data):
self.__write_data_to_file(file_path,
dev_data,
write_header=not path.isfile(file_path))
| [
"os.path.isfile",
"execution_error.ExecutionError",
"app_logger.app_logging.debug",
"app_logger.app_logging.error"
] | [((378, 440), 'execution_error.ExecutionError', 'ExecutionError', (['"""Device data and device names length mismatch"""'], {}), "('Device data and device names length mismatch')\n", (392, 440), False, 'from execution_error import ExecutionError\n'), ((1478, 1557), 'app_logger.app_logging.debug', 'app_logging.debug', (['"""Written device data:\n%s to:\n%s"""', 'data_merged', 'file_path'], {}), '("""Written device data:\n%s to:\n%s""", data_merged, file_path)\n', (1495, 1557), False, 'from app_logger import app_logging\n'), ((1655, 1715), 'app_logger.app_logging.error', 'app_logging.error', (['"""Error while writing to: [%s]"""', 'file_path'], {}), "('Error while writing to: [%s]', file_path)\n", (1672, 1715), False, 'from app_logger import app_logging\n'), ((1904, 1926), 'os.path.isfile', 'path.isfile', (['file_path'], {}), '(file_path)\n', (1915, 1926), False, 'from os import path\n')] |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'CharakterInfo.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(974, 721)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setContentsMargins(20, 20, 20, 20)
self.gridLayout.setHorizontalSpacing(20)
self.gridLayout.setVerticalSpacing(10)
self.gridLayout.setObjectName("gridLayout")
self.verticalLayout_4 = QtWidgets.QVBoxLayout()
self.verticalLayout_4.setObjectName("verticalLayout_4")
self.labelEinstellungen = QtWidgets.QLabel(Form)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.labelEinstellungen.setFont(font)
self.labelEinstellungen.setObjectName("labelEinstellungen")
self.verticalLayout_4.addWidget(self.labelEinstellungen)
self.groupBox_3 = QtWidgets.QGroupBox(Form)
self.groupBox_3.setTitle("")
self.groupBox_3.setObjectName("groupBox_3")
self.gridLayout_5 = QtWidgets.QGridLayout(self.groupBox_3)
self.gridLayout_5.setContentsMargins(20, 20, 20, 20)
self.gridLayout_5.setObjectName("gridLayout_5")
self.checkReq = QtWidgets.QCheckBox(self.groupBox_3)
self.checkReq.setChecked(True)
self.checkReq.setObjectName("checkReq")
self.gridLayout_5.addWidget(self.checkReq, 1, 0, 1, 2)
self.comboHausregeln = QtWidgets.QComboBox(self.groupBox_3)
self.comboHausregeln.setObjectName("comboHausregeln")
self.gridLayout_5.addWidget(self.comboHausregeln, 4, 1, 1, 1)
self.label_5 = QtWidgets.QLabel(self.groupBox_3)
self.label_5.setObjectName("label_5")
self.gridLayout_5.addWidget(self.label_5, 4, 0, 1, 1)
self.label_7 = QtWidgets.QLabel(self.groupBox_3)
self.label_7.setObjectName("label_7")
self.gridLayout_5.addWidget(self.label_7, 9, 0, 1, 1)
self.checkUeberPDF = QtWidgets.QCheckBox(self.groupBox_3)
self.checkUeberPDF.setObjectName("checkUeberPDF")
self.gridLayout_5.addWidget(self.checkUeberPDF, 3, 0, 1, 2)
self.label_6 = QtWidgets.QLabel(self.groupBox_3)
self.label_6.setObjectName("label_6")
self.gridLayout_5.addWidget(self.label_6, 6, 0, 1, 1)
self.checkFinanzen = QtWidgets.QCheckBox(self.groupBox_3)
self.checkFinanzen.setChecked(True)
self.checkFinanzen.setObjectName("checkFinanzen")
self.gridLayout_5.addWidget(self.checkFinanzen, 2, 0, 1, 2)
self.comboCharsheet = QtWidgets.QComboBox(self.groupBox_3)
self.comboCharsheet.setObjectName("comboCharsheet")
self.gridLayout_5.addWidget(self.comboCharsheet, 6, 1, 1, 1)
self.labelReload = QtWidgets.QLabel(self.groupBox_3)
self.labelReload.setStyleSheet("background-color: rgb(255, 255, 0); color: black;")
self.labelReload.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.labelReload.setWordWrap(True)
self.labelReload.setObjectName("labelReload")
self.gridLayout_5.addWidget(self.labelReload, 11, 0, 1, 2)
self.comboRegelnGroesse = QtWidgets.QComboBox(self.groupBox_3)
self.comboRegelnGroesse.setObjectName("comboRegelnGroesse")
self.comboRegelnGroesse.addItem("")
self.comboRegelnGroesse.addItem("")
self.comboRegelnGroesse.addItem("")
self.gridLayout_5.addWidget(self.comboRegelnGroesse, 9, 1, 1, 1)
self.checkRegeln = QtWidgets.QCheckBox(self.groupBox_3)
self.checkRegeln.setChecked(True)
self.checkRegeln.setTristate(False)
self.checkRegeln.setObjectName("checkRegeln")
self.gridLayout_5.addWidget(self.checkRegeln, 8, 0, 1, 2)
self.label_10 = QtWidgets.QLabel(self.groupBox_3)
self.label_10.setObjectName("label_10")
self.gridLayout_5.addWidget(self.label_10, 10, 0, 1, 1)
self.listRegelKategorien = QtWidgets.QListView(self.groupBox_3)
self.listRegelKategorien.setMaximumSize(QtCore.QSize(280, 80))
self.listRegelKategorien.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.listRegelKategorien.setObjectName("listRegelKategorien")
self.gridLayout_5.addWidget(self.listRegelKategorien, 10, 1, 1, 1)
self.verticalLayout_4.addWidget(self.groupBox_3)
spacerItem = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_4.addItem(spacerItem)
self.labelEP = QtWidgets.QLabel(Form)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.labelEP.setFont(font)
self.labelEP.setObjectName("labelEP")
self.verticalLayout_4.addWidget(self.labelEP)
self.groupBox_2 = QtWidgets.QGroupBox(Form)
self.groupBox_2.setTitle("")
self.groupBox_2.setObjectName("groupBox_2")
self.gridLayout_4 = QtWidgets.QGridLayout(self.groupBox_2)
self.gridLayout_4.setContentsMargins(20, 20, 20, 20)
self.gridLayout_4.setObjectName("gridLayout_4")
self.gridLayout_2 = QtWidgets.QGridLayout()
self.gridLayout_2.setObjectName("gridLayout_2")
self.spinFertigkeitenSpent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinFertigkeitenSpent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinFertigkeitenSpent.setAlignment(QtCore.Qt.AlignCenter)
self.spinFertigkeitenSpent.setReadOnly(True)
self.spinFertigkeitenSpent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinFertigkeitenSpent.setMaximum(999999)
self.spinFertigkeitenSpent.setObjectName("spinFertigkeitenSpent")
self.gridLayout_2.addWidget(self.spinFertigkeitenSpent, 3, 1, 1, 1)
self.spinUebernatuerlichPercent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinUebernatuerlichPercent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinUebernatuerlichPercent.setAlignment(QtCore.Qt.AlignCenter)
self.spinUebernatuerlichPercent.setReadOnly(True)
self.spinUebernatuerlichPercent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinUebernatuerlichPercent.setMaximum(100)
self.spinUebernatuerlichPercent.setObjectName("spinUebernatuerlichPercent")
self.gridLayout_2.addWidget(self.spinUebernatuerlichPercent, 6, 2, 1, 1)
self.labelUeber3 = QtWidgets.QLabel(self.groupBox_2)
self.labelUeber3.setMinimumSize(QtCore.QSize(230, 0))
font = QtGui.QFont()
font.setItalic(False)
self.labelUeber3.setFont(font)
self.labelUeber3.setObjectName("labelUeber3")
self.gridLayout_2.addWidget(self.labelUeber3, 8, 0, 1, 1)
self.spinProfanPercent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinProfanPercent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinProfanPercent.setAlignment(QtCore.Qt.AlignCenter)
self.spinProfanPercent.setReadOnly(True)
self.spinProfanPercent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinProfanPercent.setMaximum(100)
self.spinProfanPercent.setObjectName("spinProfanPercent")
self.gridLayout_2.addWidget(self.spinProfanPercent, 2, 2, 1, 1)
self.spinVorteileSpent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinVorteileSpent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinVorteileSpent.setAlignment(QtCore.Qt.AlignCenter)
self.spinVorteileSpent.setReadOnly(True)
self.spinVorteileSpent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinVorteileSpent.setMaximum(99999999)
self.spinVorteileSpent.setObjectName("spinVorteileSpent")
self.gridLayout_2.addWidget(self.spinVorteileSpent, 1, 1, 1, 1)
self.spinAttributeSpent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinAttributeSpent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinAttributeSpent.setAlignment(QtCore.Qt.AlignCenter)
self.spinAttributeSpent.setReadOnly(True)
self.spinAttributeSpent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinAttributeSpent.setMaximum(99999999)
self.spinAttributeSpent.setObjectName("spinAttributeSpent")
self.gridLayout_2.addWidget(self.spinAttributeSpent, 0, 1, 1, 1)
self.spinUeberTalenteSpent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinUeberTalenteSpent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinUeberTalenteSpent.setAlignment(QtCore.Qt.AlignCenter)
self.spinUeberTalenteSpent.setReadOnly(True)
self.spinUeberTalenteSpent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinUeberTalenteSpent.setMaximum(999999)
self.spinUeberTalenteSpent.setObjectName("spinUeberTalenteSpent")
self.gridLayout_2.addWidget(self.spinUeberTalenteSpent, 8, 1, 1, 1)
self.spinFreieSpent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinFreieSpent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinFreieSpent.setAlignment(QtCore.Qt.AlignCenter)
self.spinFreieSpent.setReadOnly(True)
self.spinFreieSpent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinFreieSpent.setMaximum(999999)
self.spinFreieSpent.setObjectName("spinFreieSpent")
self.gridLayout_2.addWidget(self.spinFreieSpent, 5, 1, 1, 1)
self.spinUeberFertigkeitenPercent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinUeberFertigkeitenPercent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinUeberFertigkeitenPercent.setAlignment(QtCore.Qt.AlignCenter)
self.spinUeberFertigkeitenPercent.setReadOnly(True)
self.spinUeberFertigkeitenPercent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinUeberFertigkeitenPercent.setMaximum(100)
self.spinUeberFertigkeitenPercent.setObjectName("spinUeberFertigkeitenPercent")
self.gridLayout_2.addWidget(self.spinUeberFertigkeitenPercent, 7, 2, 1, 1)
self.label_2 = QtWidgets.QLabel(self.groupBox_2)
self.label_2.setMinimumSize(QtCore.QSize(230, 0))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.gridLayout_2.addWidget(self.label_2, 1, 0, 1, 1)
self.spinAttributePercent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinAttributePercent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinAttributePercent.setAlignment(QtCore.Qt.AlignCenter)
self.spinAttributePercent.setReadOnly(True)
self.spinAttributePercent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinAttributePercent.setMaximum(100)
self.spinAttributePercent.setObjectName("spinAttributePercent")
self.gridLayout_2.addWidget(self.spinAttributePercent, 0, 2, 1, 1)
self.spinUeberTalentePercent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinUeberTalentePercent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinUeberTalentePercent.setAlignment(QtCore.Qt.AlignCenter)
self.spinUeberTalentePercent.setReadOnly(True)
self.spinUeberTalentePercent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinUeberTalentePercent.setMaximum(100)
self.spinUeberTalentePercent.setObjectName("spinUeberTalentePercent")
self.gridLayout_2.addWidget(self.spinUeberTalentePercent, 8, 2, 1, 1)
self.labelUeber1 = QtWidgets.QLabel(self.groupBox_2)
self.labelUeber1.setMinimumSize(QtCore.QSize(230, 0))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.labelUeber1.setFont(font)
self.labelUeber1.setObjectName("labelUeber1")
self.gridLayout_2.addWidget(self.labelUeber1, 6, 0, 1, 1)
self.label_4 = QtWidgets.QLabel(self.groupBox_2)
self.label_4.setMinimumSize(QtCore.QSize(230, 0))
font = QtGui.QFont()
font.setItalic(False)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.gridLayout_2.addWidget(self.label_4, 5, 0, 1, 1)
self.spinUebernatuerlichSpent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinUebernatuerlichSpent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinUebernatuerlichSpent.setAlignment(QtCore.Qt.AlignCenter)
self.spinUebernatuerlichSpent.setReadOnly(True)
self.spinUebernatuerlichSpent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinUebernatuerlichSpent.setMaximum(999999)
self.spinUebernatuerlichSpent.setObjectName("spinUebernatuerlichSpent")
self.gridLayout_2.addWidget(self.spinUebernatuerlichSpent, 6, 1, 1, 1)
self.spinUeberFertigkeitenSpent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinUeberFertigkeitenSpent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinUeberFertigkeitenSpent.setAlignment(QtCore.Qt.AlignCenter)
self.spinUeberFertigkeitenSpent.setReadOnly(True)
self.spinUeberFertigkeitenSpent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinUeberFertigkeitenSpent.setMaximum(999999)
self.spinUeberFertigkeitenSpent.setObjectName("spinUeberFertigkeitenSpent")
self.gridLayout_2.addWidget(self.spinUeberFertigkeitenSpent, 7, 1, 1, 1)
self.spinFreiePercent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinFreiePercent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinFreiePercent.setAlignment(QtCore.Qt.AlignCenter)
self.spinFreiePercent.setReadOnly(True)
self.spinFreiePercent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinFreiePercent.setMaximum(100)
self.spinFreiePercent.setObjectName("spinFreiePercent")
self.gridLayout_2.addWidget(self.spinFreiePercent, 5, 2, 1, 1)
self.spinFertigkeitenPercent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinFertigkeitenPercent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinFertigkeitenPercent.setAlignment(QtCore.Qt.AlignCenter)
self.spinFertigkeitenPercent.setReadOnly(True)
self.spinFertigkeitenPercent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinFertigkeitenPercent.setMaximum(100)
self.spinFertigkeitenPercent.setObjectName("spinFertigkeitenPercent")
self.gridLayout_2.addWidget(self.spinFertigkeitenPercent, 3, 2, 1, 1)
self.spinTalentePercent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinTalentePercent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinTalentePercent.setAlignment(QtCore.Qt.AlignCenter)
self.spinTalentePercent.setReadOnly(True)
self.spinTalentePercent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinTalentePercent.setMaximum(100)
self.spinTalentePercent.setObjectName("spinTalentePercent")
self.gridLayout_2.addWidget(self.spinTalentePercent, 4, 2, 1, 1)
self.spinProfanSpent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinProfanSpent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinProfanSpent.setAlignment(QtCore.Qt.AlignCenter)
self.spinProfanSpent.setReadOnly(True)
self.spinProfanSpent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinProfanSpent.setMaximum(999999)
self.spinProfanSpent.setObjectName("spinProfanSpent")
self.gridLayout_2.addWidget(self.spinProfanSpent, 2, 1, 1, 1)
self.label = QtWidgets.QLabel(self.groupBox_2)
self.label.setMinimumSize(QtCore.QSize(230, 0))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.gridLayout_2.addWidget(self.label, 0, 0, 1, 1)
self.label_9 = QtWidgets.QLabel(self.groupBox_2)
self.label_9.setMinimumSize(QtCore.QSize(230, 0))
font = QtGui.QFont()
font.setItalic(False)
self.label_9.setFont(font)
self.label_9.setObjectName("label_9")
self.gridLayout_2.addWidget(self.label_9, 4, 0, 1, 1)
self.labelUeber2 = QtWidgets.QLabel(self.groupBox_2)
self.labelUeber2.setMinimumSize(QtCore.QSize(230, 0))
font = QtGui.QFont()
font.setItalic(False)
self.labelUeber2.setFont(font)
self.labelUeber2.setObjectName("labelUeber2")
self.gridLayout_2.addWidget(self.labelUeber2, 7, 0, 1, 1)
self.label_8 = QtWidgets.QLabel(self.groupBox_2)
self.label_8.setMinimumSize(QtCore.QSize(230, 0))
font = QtGui.QFont()
font.setItalic(False)
self.label_8.setFont(font)
self.label_8.setObjectName("label_8")
self.gridLayout_2.addWidget(self.label_8, 3, 0, 1, 1)
self.label_3 = QtWidgets.QLabel(self.groupBox_2)
self.label_3.setMinimumSize(QtCore.QSize(230, 0))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.gridLayout_2.addWidget(self.label_3, 2, 0, 1, 1)
self.spinTalenteSpent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinTalenteSpent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinTalenteSpent.setAlignment(QtCore.Qt.AlignCenter)
self.spinTalenteSpent.setReadOnly(True)
self.spinTalenteSpent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinTalenteSpent.setMaximum(999999)
self.spinTalenteSpent.setObjectName("spinTalenteSpent")
self.gridLayout_2.addWidget(self.spinTalenteSpent, 4, 1, 1, 1)
self.spinVorteilePercent = QtWidgets.QSpinBox(self.groupBox_2)
self.spinVorteilePercent.setFocusPolicy(QtCore.Qt.NoFocus)
self.spinVorteilePercent.setAlignment(QtCore.Qt.AlignCenter)
self.spinVorteilePercent.setReadOnly(True)
self.spinVorteilePercent.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.spinVorteilePercent.setMaximum(100)
self.spinVorteilePercent.setObjectName("spinVorteilePercent")
self.gridLayout_2.addWidget(self.spinVorteilePercent, 1, 2, 1, 1)
self.gridLayout_4.addLayout(self.gridLayout_2, 0, 0, 1, 1)
self.verticalLayout_4.addWidget(self.groupBox_2)
spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_4.addItem(spacerItem1)
self.gridLayout.addLayout(self.verticalLayout_4, 0, 1, 1, 1)
self.verticalLayout_3 = QtWidgets.QVBoxLayout()
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.labelNotiz = QtWidgets.QLabel(Form)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.labelNotiz.setFont(font)
self.labelNotiz.setObjectName("labelNotiz")
self.verticalLayout_3.addWidget(self.labelNotiz)
self.groupBox = QtWidgets.QGroupBox(Form)
self.groupBox.setTitle("")
self.groupBox.setObjectName("groupBox")
self.gridLayout_3 = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout_3.setContentsMargins(20, 20, 20, 20)
self.gridLayout_3.setObjectName("gridLayout_3")
self.teNotiz = QtWidgets.QPlainTextEdit(self.groupBox)
self.teNotiz.setPlainText("")
self.teNotiz.setObjectName("teNotiz")
self.gridLayout_3.addWidget(self.teNotiz, 0, 0, 1, 1)
self.verticalLayout_3.addWidget(self.groupBox)
self.gridLayout.addLayout(self.verticalLayout_3, 0, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
Form.setTabOrder(self.teNotiz, self.checkReq)
Form.setTabOrder(self.checkReq, self.checkFinanzen)
Form.setTabOrder(self.checkFinanzen, self.checkUeberPDF)
Form.setTabOrder(self.checkUeberPDF, self.comboHausregeln)
Form.setTabOrder(self.comboHausregeln, self.comboCharsheet)
Form.setTabOrder(self.comboCharsheet, self.checkRegeln)
Form.setTabOrder(self.checkRegeln, self.comboRegelnGroesse)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.labelEinstellungen.setText(_translate("Form", "Charakter-Einstellungen"))
self.checkReq.setToolTip(_translate("Form", "Falls abgewählt, werden sämtliche Voraussetzungsprüfungen für Vorteile, übernatürliche Fertigkeiten usw. deaktiviert."))
self.checkReq.setText(_translate("Form", "Voraussetzungen überprüfen"))
self.label_5.setText(_translate("Form", "Hausregeln:"))
self.label_7.setText(_translate("Form", "Regelschriftgröße:"))
self.checkUeberPDF.setToolTip(_translate("Form", "<html><head/><body><p>Sephrasto übernimmt automatisch alle übernatürlichen Fertigkeiten in den Charakterbogen, deren FW mindestens 1 beträgt und für welche du mindestens ein Talent aktiviert hast. Wenn du diese Option aktivierst, zeigt Sephrasto eine PDF-Spalte bei den übernatürlichen Fertigkeiten an. Mit dieser kannst du selbst entscheiden, welche Fertigkeiten in den Charakterbogen übernommen werden sollen.</p></body></html>"))
self.checkUeberPDF.setText(_translate("Form", "PDF-Ausgabe von übernatürlichen Fertigkeiten manuell auswählen"))
self.label_6.setText(_translate("Form", "Charakterbogen:"))
self.checkFinanzen.setToolTip(_translate("Form", "<html><head/><body><p>Die Finanzen spielen nur bei einem neuen Charakter eine Rolle und können nach dem ersten Abenteuer ausgeblendet werden. Auch die aktuellen Schicksalspunkte werden dann nicht mehr ausgegeben, da diese ab dem ersten Abenteuer händisch verwaltet werden.</p></body></html>"))
self.checkFinanzen.setText(_translate("Form", "Finanzen anzeigen und aktuelle Schicksalspunkte ausgeben"))
self.labelReload.setText(_translate("Form", "Der Charakter muss gespeichert und neu geladen werden, damit alle Änderungen übernommen werden können!"))
self.comboRegelnGroesse.setItemText(0, _translate("Form", "Klein"))
self.comboRegelnGroesse.setItemText(1, _translate("Form", "Mittel"))
self.comboRegelnGroesse.setItemText(2, _translate("Form", "Groß"))
self.checkRegeln.setText(_translate("Form", "Dem Charakterbogen relevante Ilaris Regeln anhängen"))
self.label_10.setText(_translate("Form", "Regelkategorien:"))
self.labelEP.setText(_translate("Form", "EP-Verteilung"))
self.spinFertigkeitenSpent.setSuffix(_translate("Form", " EP"))
self.spinUebernatuerlichPercent.setSuffix(_translate("Form", " %"))
self.labelUeber3.setText(_translate("Form", " Talente"))
self.spinProfanPercent.setSuffix(_translate("Form", " %"))
self.spinVorteileSpent.setSuffix(_translate("Form", " EP"))
self.spinAttributeSpent.setSuffix(_translate("Form", " EP"))
self.spinUeberTalenteSpent.setSuffix(_translate("Form", " EP"))
self.spinFreieSpent.setSuffix(_translate("Form", " EP"))
self.spinUeberFertigkeitenPercent.setSuffix(_translate("Form", " %)"))
self.spinUeberFertigkeitenPercent.setPrefix(_translate("Form", "("))
self.label_2.setText(_translate("Form", "Vorteile"))
self.spinAttributePercent.setSuffix(_translate("Form", " %"))
self.spinUeberTalentePercent.setSuffix(_translate("Form", " %)"))
self.spinUeberTalentePercent.setPrefix(_translate("Form", "("))
self.labelUeber1.setText(_translate("Form", "Übernatürliche Fertigkeiten und Talente"))
self.label_4.setText(_translate("Form", " Freie Fertigkeiten"))
self.spinUebernatuerlichSpent.setSuffix(_translate("Form", " EP"))
self.spinUeberFertigkeitenSpent.setSuffix(_translate("Form", " EP"))
self.spinFreiePercent.setSuffix(_translate("Form", " %)"))
self.spinFreiePercent.setPrefix(_translate("Form", "("))
self.spinFertigkeitenPercent.setSuffix(_translate("Form", " %)"))
self.spinFertigkeitenPercent.setPrefix(_translate("Form", "("))
self.spinTalentePercent.setSuffix(_translate("Form", " %)"))
self.spinTalentePercent.setPrefix(_translate("Form", "("))
self.spinProfanSpent.setSuffix(_translate("Form", " EP"))
self.label.setText(_translate("Form", "Attribute"))
self.label_9.setText(_translate("Form", " Talente"))
self.labelUeber2.setText(_translate("Form", " Fertigkeiten"))
self.label_8.setText(_translate("Form", " Fertigkeiten"))
self.label_3.setText(_translate("Form", "Profane Fertigkeiten und Talente"))
self.spinTalenteSpent.setSuffix(_translate("Form", " EP"))
self.spinVorteilePercent.setSuffix(_translate("Form", " %"))
self.labelNotiz.setText(_translate("Form", "Notiz"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
| [
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtWidgets.QListView",
"PyQt5.QtWidgets.QSpinBox",
"PyQt5.QtGui.QFont",
"PyQt5.QtWidgets.QComboBox",
"PyQt5.QtWidgets.QPlainTextEdit",
"PyQt5.QtWidgets.QSpacerItem",
"PyQt5.QtCore.QMetaObject.connectSlotsByName",
"PyQt5.QtWidgets.QGridLayout",
"PyQt5.QtWidgets.QLab... | [((25171, 25203), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (25193, 25203), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((25215, 25234), 'PyQt5.QtWidgets.QWidget', 'QtWidgets.QWidget', ([], {}), '()\n', (25232, 25234), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((484, 511), 'PyQt5.QtWidgets.QGridLayout', 'QtWidgets.QGridLayout', (['Form'], {}), '(Form)\n', (505, 511), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((751, 774), 'PyQt5.QtWidgets.QVBoxLayout', 'QtWidgets.QVBoxLayout', ([], {}), '()\n', (772, 774), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((873, 895), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['Form'], {}), '(Form)\n', (889, 895), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((911, 924), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (922, 924), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1184, 1209), 'PyQt5.QtWidgets.QGroupBox', 'QtWidgets.QGroupBox', (['Form'], {}), '(Form)\n', (1203, 1209), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1327, 1365), 'PyQt5.QtWidgets.QGridLayout', 'QtWidgets.QGridLayout', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (1348, 1365), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1507, 1543), 'PyQt5.QtWidgets.QCheckBox', 'QtWidgets.QCheckBox', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (1526, 1543), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1725, 1761), 'PyQt5.QtWidgets.QComboBox', 'QtWidgets.QComboBox', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (1744, 1761), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1917, 1950), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (1933, 1950), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((2082, 2115), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (2098, 2115), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((2253, 2289), 'PyQt5.QtWidgets.QCheckBox', 'QtWidgets.QCheckBox', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (2272, 2289), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((2439, 2472), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (2455, 2472), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((2610, 2646), 'PyQt5.QtWidgets.QCheckBox', 'QtWidgets.QCheckBox', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (2629, 2646), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((2847, 2883), 'PyQt5.QtWidgets.QComboBox', 'QtWidgets.QComboBox', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (2866, 2883), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((3040, 3073), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (3056, 3073), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((3469, 3505), 'PyQt5.QtWidgets.QComboBox', 'QtWidgets.QComboBox', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (3488, 3505), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((3806, 3842), 'PyQt5.QtWidgets.QCheckBox', 'QtWidgets.QCheckBox', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (3825, 3842), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((4073, 4106), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (4089, 4106), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((4254, 4290), 'PyQt5.QtWidgets.QListView', 'QtWidgets.QListView', (['self.groupBox_3'], {}), '(self.groupBox_3)\n', (4273, 4290), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((4677, 4771), 'PyQt5.QtWidgets.QSpacerItem', 'QtWidgets.QSpacerItem', (['(20)', '(20)', 'QtWidgets.QSizePolicy.Minimum', 'QtWidgets.QSizePolicy.Fixed'], {}), '(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.\n QSizePolicy.Fixed)\n', (4698, 4771), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((4840, 4862), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['Form'], {}), '(Form)\n', (4856, 4862), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((4878, 4891), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (4889, 4891), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((5107, 5132), 'PyQt5.QtWidgets.QGroupBox', 'QtWidgets.QGroupBox', (['Form'], {}), '(Form)\n', (5126, 5132), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((5250, 5288), 'PyQt5.QtWidgets.QGridLayout', 'QtWidgets.QGridLayout', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (5271, 5288), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((5434, 5457), 'PyQt5.QtWidgets.QGridLayout', 'QtWidgets.QGridLayout', ([], {}), '()\n', (5455, 5457), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((5551, 5586), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (5569, 5586), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((6116, 6151), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (6134, 6151), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((6703, 6736), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (6719, 6736), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((6814, 6827), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (6825, 6827), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((7050, 7085), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (7068, 7085), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((7571, 7606), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (7589, 7606), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((8098, 8133), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (8116, 8133), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((8636, 8671), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (8654, 8671), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((9189, 9224), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (9207, 9224), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((9700, 9735), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (9718, 9735), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((10299, 10332), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (10315, 10332), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((10406, 10419), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (10417, 10419), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((10653, 10688), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (10671, 10688), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((11204, 11239), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (11222, 11239), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((11767, 11800), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (11783, 11800), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((11878, 11891), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (11889, 11891), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((12128, 12161), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (12144, 12161), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((12235, 12248), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (12246, 12248), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((12462, 12497), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (12480, 12497), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((13051, 13086), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (13069, 13086), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((13646, 13681), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (13664, 13681), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((14165, 14200), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (14183, 14200), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((14735, 14770), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (14753, 14770), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((15262, 15297), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (15280, 15297), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((15758, 15791), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (15774, 15791), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((15863, 15876), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (15874, 15876), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((16089, 16122), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (16105, 16122), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((16196, 16209), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (16207, 16209), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((16410, 16443), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (16426, 16443), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((16521, 16534), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (16532, 16534), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((16747, 16780), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (16763, 16780), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((16854, 16867), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (16865, 16867), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((17064, 17097), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (17080, 17097), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((17171, 17184), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (17182, 17184), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((17414, 17449), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (17432, 17449), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((17932, 17967), 'PyQt5.QtWidgets.QSpinBox', 'QtWidgets.QSpinBox', (['self.groupBox_2'], {}), '(self.groupBox_2)\n', (17950, 17967), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((18582, 18680), 'PyQt5.QtWidgets.QSpacerItem', 'QtWidgets.QSpacerItem', (['(20)', '(40)', 'QtWidgets.QSizePolicy.Minimum', 'QtWidgets.QSizePolicy.Expanding'], {}), '(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.\n QSizePolicy.Expanding)\n', (18603, 18680), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((18828, 18851), 'PyQt5.QtWidgets.QVBoxLayout', 'QtWidgets.QVBoxLayout', ([], {}), '()\n', (18849, 18851), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((18942, 18964), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['Form'], {}), '(Form)\n', (18958, 18964), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((18980, 18993), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (18991, 18993), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((19219, 19244), 'PyQt5.QtWidgets.QGroupBox', 'QtWidgets.QGroupBox', (['Form'], {}), '(Form)\n', (19238, 19244), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((19356, 19392), 'PyQt5.QtWidgets.QGridLayout', 'QtWidgets.QGridLayout', (['self.groupBox'], {}), '(self.groupBox)\n', (19377, 19392), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((19533, 19572), 'PyQt5.QtWidgets.QPlainTextEdit', 'QtWidgets.QPlainTextEdit', (['self.groupBox'], {}), '(self.groupBox)\n', (19557, 19572), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((19885, 19928), 'PyQt5.QtCore.QMetaObject.connectSlotsByName', 'QtCore.QMetaObject.connectSlotsByName', (['Form'], {}), '(Form)\n', (19922, 19928), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((4339, 4360), 'PyQt5.QtCore.QSize', 'QtCore.QSize', (['(280)', '(80)'], {}), '(280, 80)\n', (4351, 4360), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((6777, 6797), 'PyQt5.QtCore.QSize', 'QtCore.QSize', (['(230)', '(0)'], {}), '(230, 0)\n', (6789, 6797), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((10369, 10389), 'PyQt5.QtCore.QSize', 'QtCore.QSize', (['(230)', '(0)'], {}), '(230, 0)\n', (10381, 10389), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((11841, 11861), 'PyQt5.QtCore.QSize', 'QtCore.QSize', (['(230)', '(0)'], {}), '(230, 0)\n', (11853, 11861), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((12198, 12218), 'PyQt5.QtCore.QSize', 'QtCore.QSize', (['(230)', '(0)'], {}), '(230, 0)\n', (12210, 12218), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((15826, 15846), 'PyQt5.QtCore.QSize', 'QtCore.QSize', (['(230)', '(0)'], {}), '(230, 0)\n', (15838, 15846), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((16159, 16179), 'PyQt5.QtCore.QSize', 'QtCore.QSize', (['(230)', '(0)'], {}), '(230, 0)\n', (16171, 16179), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((16484, 16504), 'PyQt5.QtCore.QSize', 'QtCore.QSize', (['(230)', '(0)'], {}), '(230, 0)\n', (16496, 16504), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((16817, 16837), 'PyQt5.QtCore.QSize', 'QtCore.QSize', (['(230)', '(0)'], {}), '(230, 0)\n', (16829, 16837), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((17134, 17154), 'PyQt5.QtCore.QSize', 'QtCore.QSize', (['(230)', '(0)'], {}), '(230, 0)\n', (17146, 17154), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n')] |
#!/usr/bin/env python
# encoding: utf-8
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import configs
db = SQLAlchemy()
def create_app(app_name, config_name):
app = Flask(app_name, template_folder="app/templates")
app = Flask(app_name)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
if config_name == 'production':
app.config['DEBUG'] = False
@app.route('/static/<path:path>')
def static_files():
return app.send_static_file(path)
# init environment
app.config.from_object(configs[config_name])
db.init_app(app)
# attack routes and cunstom err pages here
from demo import demo as demo_blueprint
app.register_blueprint(demo_blueprint, url_prefix='/')
return app
| [
"flask_sqlalchemy.SQLAlchemy",
"flask.Flask"
] | [((139, 151), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', ([], {}), '()\n', (149, 151), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((203, 251), 'flask.Flask', 'Flask', (['app_name'], {'template_folder': '"""app/templates"""'}), "(app_name, template_folder='app/templates')\n", (208, 251), False, 'from flask import Flask\n'), ((262, 277), 'flask.Flask', 'Flask', (['app_name'], {}), '(app_name)\n', (267, 277), False, 'from flask import Flask\n')] |
import uproot
from .BEvents import BEvents
class EventBuilder(object):
def __init__(self, config):
self.config = config
def __repr__(self):
return '{}({!r})'.format(
self.__class__.__name__,
self.config,
)
def __call__(self):
if len(self.config.inputPaths) != 1:
# TODO - support multiple inputPaths
raise AttributeError("Multiple inputPaths not yet supported")
# Try to open the tree - some machines have configured limitations
# which prevent memmaps from begin created. Use a fallback - the
# localsource option
try:
rootfile = uproot.open(self.config.inputPaths[0])
tree = rootfile[self.config.treeName]
except:
rootfile = uproot.open(self.config.inputPaths[0],
localsource = uproot.FileSource.defaults)
tree = rootfile [self.config.treeName]
events = BEvents(tree,
self.config.nevents_per_block,
self.config.start_block,
self.config.stop_block)
events.config = self.config
return events
| [
"uproot.open"
] | [((672, 710), 'uproot.open', 'uproot.open', (['self.config.inputPaths[0]'], {}), '(self.config.inputPaths[0])\n', (683, 710), False, 'import uproot\n'), ((800, 878), 'uproot.open', 'uproot.open', (['self.config.inputPaths[0]'], {'localsource': 'uproot.FileSource.defaults'}), '(self.config.inputPaths[0], localsource=uproot.FileSource.defaults)\n', (811, 878), False, 'import uproot\n')] |
# Generated by Django 2.2.6 on 2020-05-30 22:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0010_auto_20200530_1531'),
]
operations = [
migrations.AlterField(
model_name='follow',
name='created',
field=models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='beginning_following_date'),
),
]
| [
"django.db.models.DateTimeField"
] | [((335, 435), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'db_index': '(True)', 'verbose_name': '"""beginning_following_date"""'}), "(auto_now_add=True, db_index=True, verbose_name=\n 'beginning_following_date')\n", (355, 435), False, 'from django.db import migrations, models\n')] |
import os
AIRFLOW_HOME = os.environ.get('AIRFLOW_HOME')
with open(f'{AIRFLOW_HOME}/dags/data.txt') as f:
time_data = f.read()
time_list = time_data.split()
with open(f'{AIRFLOW_HOME}/dags/time.txt', 'w') as split_text:
split_text.write(str(time_list[3]))
| [
"os.environ.get"
] | [((27, 57), 'os.environ.get', 'os.environ.get', (['"""AIRFLOW_HOME"""'], {}), "('AIRFLOW_HOME')\n", (41, 57), False, 'import os\n')] |
from sqlalchemy import DateTime, String, ForeignKey, Integer, Column, Float
from sqlalchemy.orm import relationship
from . import Base
class AumHistory(Base):
"""
Map class for table AumHistory.
- **aum_id**: Integer, primary_key.
- **aum_datetime**: DateTime, not null.
- **aum**: Float(20, 8), not null.
- **ts_name**: String(150), not null, foreign_key(ts.ts_name).
Relationships:
- **ts**: TradingSystem instance. (Many-to-One)
"""
__tablename__ = "aum_history"
aum_id = Column(Integer, primary_key = True)
aum_datetime = Column(DateTime, nullable = False)
aum = Column(Float(precision = 20, scale = 8, asdecimal = True), nullable = False)
ts_name = Column(String(150), ForeignKey("ts.ts_name"), nullable = False)
ts = relationship("Ts")
def __repr__(self):
return "<AumHistory(datetime={}, aum={}, ts={})>".format(self.aum_datetime,
self.aum,
self.ts_name
)
| [
"sqlalchemy.orm.relationship",
"sqlalchemy.Float",
"sqlalchemy.ForeignKey",
"sqlalchemy.String",
"sqlalchemy.Column"
] | [((557, 590), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (563, 590), False, 'from sqlalchemy import DateTime, String, ForeignKey, Integer, Column, Float\n'), ((612, 644), 'sqlalchemy.Column', 'Column', (['DateTime'], {'nullable': '(False)'}), '(DateTime, nullable=False)\n', (618, 644), False, 'from sqlalchemy import DateTime, String, ForeignKey, Integer, Column, Float\n'), ((822, 840), 'sqlalchemy.orm.relationship', 'relationship', (['"""Ts"""'], {}), "('Ts')\n", (834, 840), False, 'from sqlalchemy.orm import relationship\n'), ((664, 708), 'sqlalchemy.Float', 'Float', ([], {'precision': '(20)', 'scale': '(8)', 'asdecimal': '(True)'}), '(precision=20, scale=8, asdecimal=True)\n', (669, 708), False, 'from sqlalchemy import DateTime, String, ForeignKey, Integer, Column, Float\n'), ((755, 766), 'sqlalchemy.String', 'String', (['(150)'], {}), '(150)\n', (761, 766), False, 'from sqlalchemy import DateTime, String, ForeignKey, Integer, Column, Float\n'), ((768, 792), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""ts.ts_name"""'], {}), "('ts.ts_name')\n", (778, 792), False, 'from sqlalchemy import DateTime, String, ForeignKey, Integer, Column, Float\n')] |
import pytest
import os
from corpustools.corpus.io.text_spelling import (load_discourse_spelling,
load_directory_spelling,
inspect_discourse_spelling,
export_discourse_spelling)
from corpustools.corpus.io.text_transcription import (load_discourse_transcription,
load_directory_transcription,
inspect_discourse_transcription,
export_discourse_transcription)
from corpustools.exceptions import DelimiterError
from corpustools.corpus.classes import (Word, Corpus, FeatureMatrix, Discourse)
from corpustools.utils import generate_discourse
def test_export_spelling(export_test_dir, unspecified_test_corpus):
d = generate_discourse(unspecified_test_corpus)
export_path = os.path.join(export_test_dir, 'test_export_spelling.txt')
export_discourse_spelling(d, export_path, single_line = False)
d2 = load_discourse_spelling('test', export_path)
for k in unspecified_test_corpus.keys():
assert(d2.lexicon[k].spelling == unspecified_test_corpus[k].spelling)
assert(d2.lexicon[k].frequency == unspecified_test_corpus[k].frequency)
def test_export_transcription(export_test_dir, unspecified_test_corpus):
d = generate_discourse(unspecified_test_corpus)
export_path = os.path.join(export_test_dir, 'test_export_transcription.txt')
export_discourse_transcription(d, export_path, single_line = False)
d2 = load_discourse_transcription('test', export_path)
words = sorted([x for x in unspecified_test_corpus], key = lambda x: x.transcription)
words2 = sorted([x for x in d2.lexicon], key = lambda x: x.transcription)
for i,w in enumerate(words):
w2 = words2[i]
assert(w.transcription == w2.transcription)
assert(w.frequency == w2.frequency)
def test_load_spelling_no_ignore(text_test_dir):
spelling_path = os.path.join(text_test_dir, 'test_text_spelling.txt')
c = load_discourse_spelling('test',spelling_path)
assert(c.lexicon['ab'].frequency == 2)
def test_load_spelling_ignore(text_test_dir):
spelling_path = os.path.join(text_test_dir, 'test_text_spelling.txt')
a = inspect_discourse_spelling(spelling_path)
a[0].ignored_characters = set(["'",'.'])
c = load_discourse_spelling('test',spelling_path, a)
assert(c.lexicon['ab'].frequency == 3)
assert(c.lexicon['cabd'].frequency == 1)
def text_test_dir(text_test_dir):
transcription_path = os.path.join(text_test_dir, 'test_text_transcription.txt')
with pytest.raises(DelimiterError):
load_discourse_transcription('test',
transcription_path," ",[],
trans_delimiter = ',')
c = load_discourse_transcription('test',transcription_path)
assert(sorted(c.lexicon.inventory) == sorted(['#','a','b','c','d']))
def test_load_transcription_morpheme(text_test_dir):
transcription_morphemes_path = os.path.join(text_test_dir, 'test_text_transcription_morpheme_boundaries.txt')
ats = inspect_discourse_transcription(transcription_morphemes_path)
ats[0].morph_delimiters = set('-=')
c = load_discourse_transcription('test',transcription_morphemes_path, ats)
assert(c.lexicon['cab'].frequency == 2)
assert(str(c.lexicon['cab'].transcription) == 'c.a-b')
| [
"corpustools.corpus.io.text_transcription.export_discourse_transcription",
"corpustools.corpus.io.text_transcription.load_discourse_transcription",
"corpustools.corpus.io.text_transcription.inspect_discourse_transcription",
"corpustools.utils.generate_discourse",
"os.path.join",
"corpustools.corpus.io.tex... | [((906, 949), 'corpustools.utils.generate_discourse', 'generate_discourse', (['unspecified_test_corpus'], {}), '(unspecified_test_corpus)\n', (924, 949), False, 'from corpustools.utils import generate_discourse\n'), ((968, 1025), 'os.path.join', 'os.path.join', (['export_test_dir', '"""test_export_spelling.txt"""'], {}), "(export_test_dir, 'test_export_spelling.txt')\n", (980, 1025), False, 'import os\n'), ((1030, 1090), 'corpustools.corpus.io.text_spelling.export_discourse_spelling', 'export_discourse_spelling', (['d', 'export_path'], {'single_line': '(False)'}), '(d, export_path, single_line=False)\n', (1055, 1090), False, 'from corpustools.corpus.io.text_spelling import load_discourse_spelling, load_directory_spelling, inspect_discourse_spelling, export_discourse_spelling\n'), ((1103, 1147), 'corpustools.corpus.io.text_spelling.load_discourse_spelling', 'load_discourse_spelling', (['"""test"""', 'export_path'], {}), "('test', export_path)\n", (1126, 1147), False, 'from corpustools.corpus.io.text_spelling import load_discourse_spelling, load_directory_spelling, inspect_discourse_spelling, export_discourse_spelling\n'), ((1433, 1476), 'corpustools.utils.generate_discourse', 'generate_discourse', (['unspecified_test_corpus'], {}), '(unspecified_test_corpus)\n', (1451, 1476), False, 'from corpustools.utils import generate_discourse\n'), ((1495, 1557), 'os.path.join', 'os.path.join', (['export_test_dir', '"""test_export_transcription.txt"""'], {}), "(export_test_dir, 'test_export_transcription.txt')\n", (1507, 1557), False, 'import os\n'), ((1562, 1627), 'corpustools.corpus.io.text_transcription.export_discourse_transcription', 'export_discourse_transcription', (['d', 'export_path'], {'single_line': '(False)'}), '(d, export_path, single_line=False)\n', (1592, 1627), False, 'from corpustools.corpus.io.text_transcription import load_discourse_transcription, load_directory_transcription, inspect_discourse_transcription, export_discourse_transcription\n'), ((1640, 1689), 'corpustools.corpus.io.text_transcription.load_discourse_transcription', 'load_discourse_transcription', (['"""test"""', 'export_path'], {}), "('test', export_path)\n", (1668, 1689), False, 'from corpustools.corpus.io.text_transcription import load_discourse_transcription, load_directory_transcription, inspect_discourse_transcription, export_discourse_transcription\n'), ((2080, 2133), 'os.path.join', 'os.path.join', (['text_test_dir', '"""test_text_spelling.txt"""'], {}), "(text_test_dir, 'test_text_spelling.txt')\n", (2092, 2133), False, 'import os\n'), ((2143, 2189), 'corpustools.corpus.io.text_spelling.load_discourse_spelling', 'load_discourse_spelling', (['"""test"""', 'spelling_path'], {}), "('test', spelling_path)\n", (2166, 2189), False, 'from corpustools.corpus.io.text_spelling import load_discourse_spelling, load_directory_spelling, inspect_discourse_spelling, export_discourse_spelling\n'), ((2301, 2354), 'os.path.join', 'os.path.join', (['text_test_dir', '"""test_text_spelling.txt"""'], {}), "(text_test_dir, 'test_text_spelling.txt')\n", (2313, 2354), False, 'import os\n'), ((2363, 2404), 'corpustools.corpus.io.text_spelling.inspect_discourse_spelling', 'inspect_discourse_spelling', (['spelling_path'], {}), '(spelling_path)\n', (2389, 2404), False, 'from corpustools.corpus.io.text_spelling import load_discourse_spelling, load_directory_spelling, inspect_discourse_spelling, export_discourse_spelling\n'), ((2458, 2507), 'corpustools.corpus.io.text_spelling.load_discourse_spelling', 'load_discourse_spelling', (['"""test"""', 'spelling_path', 'a'], {}), "('test', spelling_path, a)\n", (2481, 2507), False, 'from corpustools.corpus.io.text_spelling import load_discourse_spelling, load_directory_spelling, inspect_discourse_spelling, export_discourse_spelling\n'), ((2656, 2714), 'os.path.join', 'os.path.join', (['text_test_dir', '"""test_text_transcription.txt"""'], {}), "(text_test_dir, 'test_text_transcription.txt')\n", (2668, 2714), False, 'import os\n'), ((2915, 2971), 'corpustools.corpus.io.text_transcription.load_discourse_transcription', 'load_discourse_transcription', (['"""test"""', 'transcription_path'], {}), "('test', transcription_path)\n", (2943, 2971), False, 'from corpustools.corpus.io.text_transcription import load_discourse_transcription, load_directory_transcription, inspect_discourse_transcription, export_discourse_transcription\n'), ((3134, 3212), 'os.path.join', 'os.path.join', (['text_test_dir', '"""test_text_transcription_morpheme_boundaries.txt"""'], {}), "(text_test_dir, 'test_text_transcription_morpheme_boundaries.txt')\n", (3146, 3212), False, 'import os\n'), ((3223, 3284), 'corpustools.corpus.io.text_transcription.inspect_discourse_transcription', 'inspect_discourse_transcription', (['transcription_morphemes_path'], {}), '(transcription_morphemes_path)\n', (3254, 3284), False, 'from corpustools.corpus.io.text_transcription import load_discourse_transcription, load_directory_transcription, inspect_discourse_transcription, export_discourse_transcription\n'), ((3333, 3404), 'corpustools.corpus.io.text_transcription.load_discourse_transcription', 'load_discourse_transcription', (['"""test"""', 'transcription_morphemes_path', 'ats'], {}), "('test', transcription_morphemes_path, ats)\n", (3361, 3404), False, 'from corpustools.corpus.io.text_transcription import load_discourse_transcription, load_directory_transcription, inspect_discourse_transcription, export_discourse_transcription\n'), ((2724, 2753), 'pytest.raises', 'pytest.raises', (['DelimiterError'], {}), '(DelimiterError)\n', (2737, 2753), False, 'import pytest\n'), ((2763, 2853), 'corpustools.corpus.io.text_transcription.load_discourse_transcription', 'load_discourse_transcription', (['"""test"""', 'transcription_path', '""" """', '[]'], {'trans_delimiter': '""","""'}), "('test', transcription_path, ' ', [],\n trans_delimiter=',')\n", (2791, 2853), False, 'from corpustools.corpus.io.text_transcription import load_discourse_transcription, load_directory_transcription, inspect_discourse_transcription, export_discourse_transcription\n')] |
"""Test for XBee Pro S3B"""
from xbradio import XBRadio
from pyb import SPI, Pin, delay
def test_PacketBuffer():
import test_PacketBuffer
test_PacketBuffer.main()
def test_as(xb):
#xb.verbose = True
#g = xb.get_and_process_available_packets
#BUG, this doesn't work: print("values: %r" % xb.values)
#print("values: %s" % str(xb.values))
#print(':'.join('%x' % v for v in xb.address))
at = xb.do_AT_cmd_and_process_response
at('TP')
assert 1 < xb.values['TP'] < 60, "bad temperature %d" % xb.values['TP']
at('%V')
assert 3200 < xb.values['%V'] < 3400, "bad voltage %d" % xb.values['%V']
at('ER')
#print("values: %s" % str(xb.values))
assert xb.rx_available() == 0
xb.tx('bar', xb.address)
delay(5)
assert xb.rx_available() == 1
xb.tx('blort', xb.address)
delay(100)
assert xb.rx_available() == 2
a, d = xb.rx()
#print("From %s got %r" % (':'.join('%x' % v for v in xb.address), d))
assert a == xb.address
assert d == b'bar', "Expected 'bar', got %r" % d
assert xb.rx_available() == 1
a, d = xb.rx()
#print("From %s got %r" % (':'.join('%x' % v for v in xb.address), d))
assert a == xb.address
assert d == b'blort', "Expected b'blort, got %r" % d
assert xb.rx_available() == 0
xb.tx('foo', 'thisisanaddress!')
delay(3000)
assert xb.rx_available() == 0
def gse():
test_as(create_test_radio('gse'))
def flight():
test_as(create_test_radio('flight'))
def create_test_radio(r):
if r == 'gse':
return XBRadio(spi = SPI(1),
nRESET = Pin('Y11'),
DOUT = Pin('Y12'),
nSSEL = Pin('X5'),
nATTN = Pin('Y10'))
if r == 'flight' or r == 'flt':
return XBRadio(spi = SPI(2),
nRESET = Pin('X11'),
DOUT = Pin('X12'),
nSSEL = Pin('Y5'),
nATTN = Pin('Y4'))
def create_test_radio_by_dialog(r):
while True:
r = input('Is this GSE or Flight? ').lower()
v = create_test_radio(r)
if v:
return v
"""
def master():
nrf = NRF24L01(SPI(2), Pin('Y5'), Pin('Y4'), payload_size=8)
nrf.open_tx_pipe(pipes[0])
nrf.open_rx_pipe(1, pipes[1])
nrf.start_listening()
num_needed = 16
num_successes = 0
num_failures = 0
led_state = 0
print('NRF24L01 master mode, sending %d packets...' % num_needed)
while num_successes < num_needed and num_failures < num_needed:
# stop listening and send packet
nrf.stop_listening()
millis = pyb.millis()
led_state = max(1, (led_state << 1) & 0x0f)
print('sending:', millis, led_state)
try:
nrf.send(struct.pack('ii', millis, led_state))
except OSError:
pass
# start listening again
nrf.start_listening()
# wait for response, with 250ms timeout
start_time = pyb.millis()
timeout = False
while not nrf.any() and not timeout:
if pyb.elapsed_millis(start_time) > 250:
timeout = True
if timeout:
print('failed, respones timed out')
num_failures += 1
else:
# recv packet
got_millis, = struct.unpack('i', nrf.recv())
# print response and round-trip delay
print('got response:', got_millis, '(delay', pyb.millis() - got_millis, 'ms)')
num_successes += 1
# delay then loop
pyb.delay(250)
print('master finished sending; succeses=%d, failures=%d' % (num_successes, num_failures))
def slave():
nrf = NRF24L01(SPI(2), Pin('Y5'), Pin('Y4'), payload_size=8)
nrf.open_tx_pipe(pipes[1])
nrf.open_rx_pipe(1, pipes[0])
nrf.start_listening()
print('NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)')
while True:
pyb.wfi()
if nrf.any():
while nrf.any():
buf = nrf.recv()
millis, led_state = struct.unpack('ii', buf)
print('received:', millis, led_state)
for i in range(4):
if led_state & (1 << i):
pyb.LED(i + 1).on()
else:
pyb.LED(i + 1).off()
pyb.delay(15)
nrf.stop_listening()
try:
nrf.send(struct.pack('i', millis))
except OSError:
pass
print('sent response')
nrf.start_listening()
"""
print('XBee radio test module loaded')
print(
"""XBee pinout for: GSE Flight
--- ------
DOUT (pin 2) Y12 X12
SPI_MISO (pin 4) X7 Y7
nRESET (pin 5) Y11 X11
SPI_MOSI (pin 11) X8 Y8
SPI_nSSEL (pin 17) X5 Y5
SPI_CLK (pin 18) X6 Y6
SPI_nATTN (pin 19) Y10 Y4 (not X10)
run xbradio_test.gse() on GSE, then xbradio_test.flight() on Flight')
""")
| [
"pyb.Pin",
"test_PacketBuffer.main",
"pyb.SPI",
"pyb.delay"
] | [((148, 172), 'test_PacketBuffer.main', 'test_PacketBuffer.main', ([], {}), '()\n', (170, 172), False, 'import test_PacketBuffer\n'), ((758, 766), 'pyb.delay', 'delay', (['(5)'], {}), '(5)\n', (763, 766), False, 'from pyb import SPI, Pin, delay\n'), ((836, 846), 'pyb.delay', 'delay', (['(100)'], {}), '(100)\n', (841, 846), False, 'from pyb import SPI, Pin, delay\n'), ((1342, 1353), 'pyb.delay', 'delay', (['(3000)'], {}), '(3000)\n', (1347, 1353), False, 'from pyb import SPI, Pin, delay\n'), ((1575, 1581), 'pyb.SPI', 'SPI', (['(1)'], {}), '(1)\n', (1578, 1581), False, 'from pyb import SPI, Pin, delay\n'), ((1615, 1625), 'pyb.Pin', 'Pin', (['"""Y11"""'], {}), "('Y11')\n", (1618, 1625), False, 'from pyb import SPI, Pin, delay\n'), ((1657, 1667), 'pyb.Pin', 'Pin', (['"""Y12"""'], {}), "('Y12')\n", (1660, 1667), False, 'from pyb import SPI, Pin, delay\n'), ((1700, 1709), 'pyb.Pin', 'Pin', (['"""X5"""'], {}), "('X5')\n", (1703, 1709), False, 'from pyb import SPI, Pin, delay\n'), ((1742, 1752), 'pyb.Pin', 'Pin', (['"""Y10"""'], {}), "('Y10')\n", (1745, 1752), False, 'from pyb import SPI, Pin, delay\n'), ((1819, 1825), 'pyb.SPI', 'SPI', (['(2)'], {}), '(2)\n', (1822, 1825), False, 'from pyb import SPI, Pin, delay\n'), ((1859, 1869), 'pyb.Pin', 'Pin', (['"""X11"""'], {}), "('X11')\n", (1862, 1869), False, 'from pyb import SPI, Pin, delay\n'), ((1901, 1911), 'pyb.Pin', 'Pin', (['"""X12"""'], {}), "('X12')\n", (1904, 1911), False, 'from pyb import SPI, Pin, delay\n'), ((1944, 1953), 'pyb.Pin', 'Pin', (['"""Y5"""'], {}), "('Y5')\n", (1947, 1953), False, 'from pyb import SPI, Pin, delay\n'), ((1986, 1995), 'pyb.Pin', 'Pin', (['"""Y4"""'], {}), "('Y4')\n", (1989, 1995), False, 'from pyb import SPI, Pin, delay\n')] |
import torch
import torchaudio
import configparser
from torch import nn
from model import KWS
from prepare_big_wav import getBigWaveform
use_cuda = torch.cuda.is_available()
torch.manual_seed(7)
device = torch.device("cuda" if use_cuda else "cpu")
config = configparser.ConfigParser()
config.read('config.ini')
mel_transform = torchaudio.transforms.MelSpectrogram(
sample_rate=22050,
n_fft=1024,
win_length=1024,
hop_length=256,
f_min=0,
f_max=8000,
n_mels=40).to(device)
def apply(model, spectrogram, mode):
log_softmax = nn.LogSoftmax(dim=1)
model.eval()
window_length = 100
shift = 10
start_index = 0
with torch.no_grad():
end_index = start_index + window_length
if end_index >= spectrogram.shape[-1] or mode == "check":
output, hidden = model(spectrogram, single_input=True)
__, predicted = torch.max(output, dim=1)
print("Key word presence score:", output[0][1].item(), ".\tPredicted class:", predicted.item())
return output[0][1].item()
else:
outputs = []
output, hidden = model(spectrogram[:, :, start_index:end_index], single_input=True)
__, predicted = torch.max(output, dim=1)
print("Key word presence score:", output[0][1].item(), ".\tPredicted class:", predicted.item())
start_index += shift
end_index += shift
while end_index < spectrogram.shape[-1]:
output, hidden = model(spectrogram[:, :, start_index:end_index], encoder_hidden=hidden, single_input=True)
__, predicted = torch.max(output, dim=1)
print("Key word presence score:", output[0][1].item(), ".\tPredicted class:", predicted.item())
outputs.append(output[0][1].item())
start_index += shift
end_index += shift
return outputs
model = KWS().to(device)
state_dict = torch.load(config.get('paths', 'path_to_weights_dict'))
model.load_state_dict(state_dict)
model = model.to(device)
mode = config.get('common', 'mode')
if mode == 'example':
waveform = getBigWaveform()
elif mode == 'check':
waveform, sample_rate = torchaudio.load(config.get('paths', 'path_to_audio'))
spectrogram = mel_transform(waveform)
spectrogram = torch.log(spectrogram + 1e-9)
print("device:", device)
probabilities = apply(model, spectrogram, mode)
# print("-------------------------------------------------------\n\
# all scores:", probabilities)
| [
"torch.manual_seed",
"prepare_big_wav.getBigWaveform",
"torch.log",
"configparser.ConfigParser",
"torchaudio.transforms.MelSpectrogram",
"torch.max",
"torch.cuda.is_available",
"torch.nn.LogSoftmax",
"torch.no_grad",
"model.KWS",
"torch.device"
] | [((151, 176), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (174, 176), False, 'import torch\n'), ((177, 197), 'torch.manual_seed', 'torch.manual_seed', (['(7)'], {}), '(7)\n', (194, 197), False, 'import torch\n'), ((207, 250), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (219, 250), False, 'import torch\n'), ((261, 288), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (286, 288), False, 'import configparser\n'), ((2364, 2394), 'torch.log', 'torch.log', (['(spectrogram + 1e-09)'], {}), '(spectrogram + 1e-09)\n', (2373, 2394), False, 'import torch\n'), ((561, 581), 'torch.nn.LogSoftmax', 'nn.LogSoftmax', ([], {'dim': '(1)'}), '(dim=1)\n', (574, 581), False, 'from torch import nn\n'), ((2190, 2206), 'prepare_big_wav.getBigWaveform', 'getBigWaveform', ([], {}), '()\n', (2204, 2206), False, 'from prepare_big_wav import getBigWaveform\n'), ((332, 468), 'torchaudio.transforms.MelSpectrogram', 'torchaudio.transforms.MelSpectrogram', ([], {'sample_rate': '(22050)', 'n_fft': '(1024)', 'win_length': '(1024)', 'hop_length': '(256)', 'f_min': '(0)', 'f_max': '(8000)', 'n_mels': '(40)'}), '(sample_rate=22050, n_fft=1024,\n win_length=1024, hop_length=256, f_min=0, f_max=8000, n_mels=40)\n', (368, 468), False, 'import torchaudio\n'), ((668, 683), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (681, 683), False, 'import torch\n'), ((1970, 1975), 'model.KWS', 'KWS', ([], {}), '()\n', (1973, 1975), False, 'from model import KWS\n'), ((896, 920), 'torch.max', 'torch.max', (['output'], {'dim': '(1)'}), '(output, dim=1)\n', (905, 920), False, 'import torch\n'), ((1234, 1258), 'torch.max', 'torch.max', (['output'], {'dim': '(1)'}), '(output, dim=1)\n', (1243, 1258), False, 'import torch\n'), ((1653, 1677), 'torch.max', 'torch.max', (['output'], {'dim': '(1)'}), '(output, dim=1)\n', (1662, 1677), False, 'import torch\n')] |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2018] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import operator as op
import enum
import attr
from attr.validators import instance_of as is_a
class UnknownStrand(Exception):
"""
Raised when a strand integer has an invalid value.
"""
pass
class UnknownCoordinateStart(Exception):
pass
class UnknownCloseStatus(Exception):
pass
class UnknownCoordinateSystem(Exception):
pass
@enum.unique
class Strand(enum.Enum):
reverse = -1
unknown = 0
forward = 1
@classmethod
def build(cls, value):
if isinstance(value, float) and int(value) == value:
value = int(value)
if value in {1, "+", "1", Strand.forward}:
return cls.forward
if value in {-1, "-", "-1", Strand.reverse}:
return cls.reverse
if value in {0, ".", 0, Strand.unknown}:
return cls.unknown
raise UnknownStrand("No way to handle raw strand: " + str(value))
def display_string(self):
if self is Strand.reverse:
return "-"
if self is Strand.forward:
return "+"
if self is Strand.unknown:
return "."
raise ValueError("Strand %s has no representation" % self)
def display_int(self):
return self.value
# @enum.unique
class CoordinateStart(enum.Enum):
zero = 0
one = 1
@classmethod
def from_name(cls, name):
if name == "0-start":
return cls.zero
if name == "1-start":
return cls.one
raise UnknownCoordinateStart(name)
def __str__(self):
return "%i-start" % self.value
# @enum.unique
class CloseStatus(enum.Enum):
closed = 0
open = 1
@classmethod
def from_name(cls, name):
if name == "fully-closed":
return cls.closed
if name == "half-open":
return cls.open
raise UnknownCloseStatus(name)
def __str__(self):
if self is CloseStatus.closed:
return "fully-closed"
if self is CloseStatus.open:
return "half-open"
raise ValueError("No name for %s" % self)
@attr.s(frozen=True, hash=True, slots=True)
class CoordinateSystem(object):
"""
This is meant to represent how a database numbers a genome. Some databases
will start counting at zeros and others one, this is called the basis here.
If the stop endpoint is open or closed changes the value of the close_status
here. This is really only meant to cover the two main systems 0 based and
1 based. The logic of how to represent things and deal with the two systems
is taken from:
http://genome.ucsc.edu/blog/the-ucsc-genome-browser-coordinate-counting-systems/
"""
basis = attr.ib(validator=is_a(CoordinateStart))
close_status = attr.ib(validator=is_a(CloseStatus))
@classmethod
def build(cls, value):
if isinstance(value, str):
return cls.from_name(value)
if isinstance(value, dict):
return cls(**value)
if isinstance(value, cls):
return value
raise ValueError("Cannot build CoordinateSystem from %s" % str(value))
@classmethod
def from_name(cls, name):
"""
Create a CoordinateSystem from a given name. The name must be formatted
like 'basis, close_status'. Examples are:
- '0-start, half-open',
- '1-start, fully-closed'
"""
try:
basis_name, close_name = name.split(", ", 1)
except:
raise UnknownCoordinateSystem(name)
return cls(
basis=CoordinateStart.from_name(basis_name),
close_status=CloseStatus.from_name(close_name),
)
@classmethod
def zero_based(cls):
"""
Just a short cut for '0-start, half-open'.
"""
return cls.from_name("0-start, half-open")
@classmethod
def one_based(cls):
"""
Just a short cut for '1-start, fully-closed'.
"""
return cls.from_name("1-start, fully-closed")
def name(self):
return "%s, %s" % (self.basis, self.close_status)
def size(self, location):
size = None
if self.close_status == CloseStatus.closed:
size = location.stop - location.start + 1
elif self.close_status == CloseStatus.open:
size = location.stop - location.start
else:
raise ValueError("Could not find the size for %s" % location)
assert size >= 0, "Somehow computed negative exon size %s" % location
return size
def as_zero_based(self, location):
start = location.start
if self.basis is CoordinateStart.zero:
pass
elif self.basis is CoordinateStart.one:
start = start - 1
else:
raise ValueError("Unknown type of start: %s" % self.basis)
return attr.evolve(location, start=start)
def as_one_based(self, location):
start = location.start
if self.basis is CoordinateStart.zero:
start = start + 1
elif self.basis is CoordinateStart.one:
pass
else:
raise ValueError("Unknown type of start: %s" % self.basis)
return attr.evolve(location, start=start)
def normalize(self, location):
return self.as_one_based(location)
@attr.s(frozen=True, hash=True, slots=True)
class Exon(object):
start = attr.ib(validator=is_a(int))
stop = attr.ib(validator=is_a(int))
@classmethod
def from_dict(cls, raw):
return cls(start=raw["exon_start"], stop=raw["exon_stop"])
@stop.validator
def greater_than_start(self, attribute, value):
if value < self.start:
raise ValueError("stop (%i) must be >= start (%i)" % (value, self.start))
def as_sorted_exons(raw):
exons = []
for entry in raw:
if isinstance(entry, dict):
exons.append(Exon(**entry))
else:
exons.append(entry)
return tuple(sorted(exons, key=op.attrgetter("start")))
@attr.s(frozen=True, hash=True, slots=True)
class SequenceRegion:
assembly_id = attr.ib(validator=is_a(str), converter=str)
chromosome = attr.ib(validator=is_a(str), converter=str)
strand = attr.ib(validator=is_a(Strand), converter=Strand.build)
exons = attr.ib(validator=is_a(tuple), converter=as_sorted_exons)
coordinate_system = attr.ib(
validator=is_a(CoordinateSystem),
converter=CoordinateSystem.build,
)
@property
def start(self):
return self.exons[0].start
@property
def stop(self):
return self.exons[-1].stop
def name(self, upi=""):
exon_names = []
for exon in self.exons:
normalized = self.coordinate_system.normalize(exon)
exon_names.append(
"{start}-{stop}".format(
start=normalized.start,
stop=normalized.stop,
)
)
return "{upi}@{chromosome}/{exons}:{strand}".format(
upi=upi,
chromosome=self.chromosome,
exons=",".join(exon_names),
strand=self.strand.display_string(),
)
def sizes(self):
return [self.coordinate_system.size(e) for e in self.exons]
def as_one_based(self):
converter = self.coordinate_system.as_one_based
return attr.evolve(
self,
exons=[converter(e) for e in self.exons],
coordinate_system=CoordinateSystem.one_based(),
)
def as_zero_based(self):
converter = self.coordinate_system.as_zero_based
return attr.evolve(
self,
exons=[converter(e) for e in self.exons],
coordinate_system=CoordinateSystem.zero_based(),
)
def writeable(self, accession, is_upi=False, require_strand=True):
assert accession, "Must given an accession to write %s" % self
if require_strand and self.strand is Strand.unknown:
return
name = self.name()
if is_upi:
name = self.name(upi=accession)
for exon in self.exons:
normalized = self.coordinate_system.normalize(exon)
yield [
accession,
name,
self.chromosome,
self.strand.display_int(),
self.assembly_id,
len(self.exons),
normalized.start,
normalized.stop,
]
| [
"attr.evolve",
"attr.validators.instance_of",
"attr.s",
"operator.attrgetter"
] | [((2699, 2741), 'attr.s', 'attr.s', ([], {'frozen': '(True)', 'hash': '(True)', 'slots': '(True)'}), '(frozen=True, hash=True, slots=True)\n', (2705, 2741), False, 'import attr\n'), ((5929, 5971), 'attr.s', 'attr.s', ([], {'frozen': '(True)', 'hash': '(True)', 'slots': '(True)'}), '(frozen=True, hash=True, slots=True)\n', (5935, 5971), False, 'import attr\n'), ((6627, 6669), 'attr.s', 'attr.s', ([], {'frozen': '(True)', 'hash': '(True)', 'slots': '(True)'}), '(frozen=True, hash=True, slots=True)\n', (6633, 6669), False, 'import attr\n'), ((5464, 5498), 'attr.evolve', 'attr.evolve', (['location'], {'start': 'start'}), '(location, start=start)\n', (5475, 5498), False, 'import attr\n'), ((5812, 5846), 'attr.evolve', 'attr.evolve', (['location'], {'start': 'start'}), '(location, start=start)\n', (5823, 5846), False, 'import attr\n'), ((3324, 3345), 'attr.validators.instance_of', 'is_a', (['CoordinateStart'], {}), '(CoordinateStart)\n', (3328, 3345), True, 'from attr.validators import instance_of as is_a\n'), ((3384, 3401), 'attr.validators.instance_of', 'is_a', (['CloseStatus'], {}), '(CloseStatus)\n', (3388, 3401), True, 'from attr.validators import instance_of as is_a\n'), ((6022, 6031), 'attr.validators.instance_of', 'is_a', (['int'], {}), '(int)\n', (6026, 6031), True, 'from attr.validators import instance_of as is_a\n'), ((6062, 6071), 'attr.validators.instance_of', 'is_a', (['int'], {}), '(int)\n', (6066, 6071), True, 'from attr.validators import instance_of as is_a\n'), ((6728, 6737), 'attr.validators.instance_of', 'is_a', (['str'], {}), '(str)\n', (6732, 6737), True, 'from attr.validators import instance_of as is_a\n'), ((6789, 6798), 'attr.validators.instance_of', 'is_a', (['str'], {}), '(str)\n', (6793, 6798), True, 'from attr.validators import instance_of as is_a\n'), ((6846, 6858), 'attr.validators.instance_of', 'is_a', (['Strand'], {}), '(Strand)\n', (6850, 6858), True, 'from attr.validators import instance_of as is_a\n'), ((6914, 6925), 'attr.validators.instance_of', 'is_a', (['tuple'], {}), '(tuple)\n', (6918, 6925), True, 'from attr.validators import instance_of as is_a\n'), ((7005, 7027), 'attr.validators.instance_of', 'is_a', (['CoordinateSystem'], {}), '(CoordinateSystem)\n', (7009, 7027), True, 'from attr.validators import instance_of as is_a\n'), ((6599, 6621), 'operator.attrgetter', 'op.attrgetter', (['"""start"""'], {}), "('start')\n", (6612, 6621), True, 'import operator as op\n')] |
from loris.constants import FEATURE_ROTATION_ARBITRARY
from loris.constants import FEATURE_ROTATION_BY_90S
from loris.constants import FEATURE_ROTATION_MIRRORING
from loris.exceptions import FeatureNotEnabledException
from loris.exceptions import RequestException
from loris.exceptions import SyntaxException
from loris.parameters.api import AbstractParameter
from re import compile
REGEX = compile(r"^!?\d+(?:\.\d+)?$")
class RotationParameter(AbstractParameter):
def __init__(self, uri_slice, enabled_features):
super().__init__(uri_slice, enabled_features)
if not REGEX.match(uri_slice):
msg = f"Could not parse region request ({uri_slice})"
raise SyntaxException(msg)
self.mirror = self.uri_slice[0] == "!"
self._rotation = None
self._run_checks()
@property
def rotation(self):
# raises SyntaxException
if self._rotation is None:
s = self.uri_slice[1:] if self.mirror else self.uri_slice
self._rotation = float(s)
return self._rotation
@property
def canonical(self):
if self._canonical is None:
if self.mirror:
self._canonical = f"!{self.rotation:g}"
else:
self._canonical = f"{self.rotation:g}"
return self._canonical
def _run_checks(self):
self._check_range()
self._check_mirroring()
self._check_rotation()
def _check_range(self):
if not 0.0 <= self.rotation <= 360.0:
msg = f"Rotation must be between 0 and 360 ({self.rotation})"
raise RequestException(msg)
def _check_mirroring(self):
if self.mirror and FEATURE_ROTATION_MIRRORING not in self.enabled_features:
raise FeatureNotEnabledException(FEATURE_ROTATION_MIRRORING)
def _check_rotation(self):
if self.rotation == 0.0:
return
if self.rotation % 90 == 0.0 and FEATURE_ROTATION_BY_90S not in self.enabled_features:
raise FeatureNotEnabledException(FEATURE_ROTATION_BY_90S)
if self.rotation % 90 != 0.0 and FEATURE_ROTATION_ARBITRARY not in self.enabled_features:
raise FeatureNotEnabledException(FEATURE_ROTATION_ARBITRARY)
| [
"loris.exceptions.SyntaxException",
"loris.exceptions.RequestException",
"loris.exceptions.FeatureNotEnabledException",
"re.compile"
] | [((392, 423), 're.compile', 'compile', (['"""^!?\\\\d+(?:\\\\.\\\\d+)?$"""'], {}), "('^!?\\\\d+(?:\\\\.\\\\d+)?$')\n", (399, 423), False, 'from re import compile\n'), ((698, 718), 'loris.exceptions.SyntaxException', 'SyntaxException', (['msg'], {}), '(msg)\n', (713, 718), False, 'from loris.exceptions import SyntaxException\n'), ((1618, 1639), 'loris.exceptions.RequestException', 'RequestException', (['msg'], {}), '(msg)\n', (1634, 1639), False, 'from loris.exceptions import RequestException\n'), ((1775, 1829), 'loris.exceptions.FeatureNotEnabledException', 'FeatureNotEnabledException', (['FEATURE_ROTATION_MIRRORING'], {}), '(FEATURE_ROTATION_MIRRORING)\n', (1801, 1829), False, 'from loris.exceptions import FeatureNotEnabledException\n'), ((2027, 2078), 'loris.exceptions.FeatureNotEnabledException', 'FeatureNotEnabledException', (['FEATURE_ROTATION_BY_90S'], {}), '(FEATURE_ROTATION_BY_90S)\n', (2053, 2078), False, 'from loris.exceptions import FeatureNotEnabledException\n'), ((2195, 2249), 'loris.exceptions.FeatureNotEnabledException', 'FeatureNotEnabledException', (['FEATURE_ROTATION_ARBITRARY'], {}), '(FEATURE_ROTATION_ARBITRARY)\n', (2221, 2249), False, 'from loris.exceptions import FeatureNotEnabledException\n')] |
from bytewax import Dataflow, run
flow = Dataflow()
flow.map(lambda x: x * x)
flow.capture()
if __name__ == "__main__":
for epoch, y in sorted(run(flow, enumerate(range(10)))):
print(y)
| [
"bytewax.Dataflow"
] | [((42, 52), 'bytewax.Dataflow', 'Dataflow', ([], {}), '()\n', (50, 52), False, 'from bytewax import Dataflow, run\n')] |
import pytest
from pyspark.sql import SparkSession
from collections import defaultdict
from dsgrid.project import Project
from dsgrid.dataset.dataset import Dataset
from dsgrid.dimension.base_models import DimensionType
from dsgrid.exceptions import DSGValueNotRegistered, DSGInvalidDimensionMapping
from dsgrid.tests.common import TEST_REGISTRY
PROJECT_ID = "test_efs"
DATASET_ID = "test_efs_comstock"
def test_project_load():
project = Project.load(PROJECT_ID, offline_mode=True, registry_path=TEST_REGISTRY)
assert isinstance(project, Project)
project = Project.load(
PROJECT_ID, version="1.0.0", offline_mode=True, registry_path=TEST_REGISTRY
)
assert isinstance(project, Project)
config = project.config
dim = config.get_base_dimension(DimensionType.GEOGRAPHY)
assert dim.model.dimension_type == DimensionType.GEOGRAPHY
supp_dims = config.get_supplemental_dimensions(DimensionType.GEOGRAPHY)
assert len(supp_dims) == 3
assert config.has_base_to_supplemental_dimension_mapping_types(DimensionType.GEOGRAPHY)
mappings = config.get_base_to_supplemental_dimension_mappings_by_types(DimensionType.GEOGRAPHY)
assert len(mappings) == 3
assert config.has_base_to_supplemental_dimension_mapping_types(DimensionType.SECTOR)
assert config.has_base_to_supplemental_dimension_mapping_types(DimensionType.SUBSECTOR)
records = project.config.get_dimension_records(DimensionType.SUBSECTOR, "none").collect()
assert len(records) == 1
assert records[0].id == "all_subsectors"
table = project.config.make_dimension_association_table()
assert table.select("data_source").distinct().collect()[0].data_source == "comstock"
with pytest.raises(DSGValueNotRegistered):
project = Project.load(
PROJECT_ID, version="0.0.0", offline_mode=True, registry_path=TEST_REGISTRY
)
assert isinstance(project, Project)
def test_dataset_load():
project = Project.load(PROJECT_ID, offline_mode=True, registry_path=TEST_REGISTRY)
project.load_dataset(DATASET_ID)
dataset = project.get_dataset(DATASET_ID)
assert isinstance(dataset, Dataset)
spark = SparkSession.getActiveSession()
data = spark.sql(f"select * from {DATASET_ID}__load_data")
assert "timestamp" in data.columns
assert "com_fans" in data.columns
lookup = spark.sql(f"select * from {DATASET_ID}__load_data_lookup")
assert "subsector" in lookup.columns
assert "id" in lookup.columns
query_names = sorted(project.config.list_dimension_query_names(DimensionType.GEOGRAPHY))
assert query_names == ["census_division", "census_region", "county", "state"]
records = project.config.get_dimension_records(DimensionType.GEOGRAPHY, "state")
assert records.filter("id = 'CO'").count() > 0
project.unload_dataset(DATASET_ID)
assert spark.sql("show tables").rdd.isEmpty()
def test_dimension_map_and_reduce_in_dataset():
project = Project.load(PROJECT_ID, offline_mode=True, registry_path=TEST_REGISTRY)
project.load_dataset(DATASET_ID)
dataset = project.get_dataset(DATASET_ID)
mapped_load_data = dataset._handler._remap_dimension_columns(dataset.load_data)
mapped_load_data_lookup = dataset._handler._remap_dimension_columns(dataset.load_data_lookup)
# [1] check that mapped tables contain all to_id records from mappings
table_is_lookup = False
for ref in dataset._handler._mapping_references:
column = ref.from_dimension_type.value
mapping_config = dataset._handler._dimension_mapping_mgr.get_by_id(ref.mapping_id)
to_records = mapping_config.get_unique_to_ids() # set
if column == dataset._handler.get_pivot_dimension_type().value:
diff = to_records.difference(mapped_load_data.columns)
else:
if column in mapped_load_data_lookup.columns:
diff = set(
[
row[column]
for row in mapped_load_data_lookup.select(column).distinct().collect()
]
).symmetric_difference(to_records)
table_is_lookup = True
else:
diff = set(
[row[column] for row in mapped_load_data.select(column).distinct().collect()]
).symmetric_difference(to_records)
if diff:
table_type = "load_data_lookup" if table_is_lookup else "load_data"
raise DSGInvalidDimensionMapping(
"Mapped %s is incorrect, check %s mapping: %s or mapping logic in 'dataset_schema_handler_base._map_and_reduce_dimension()' \n%s"
% (table_type, column, ref.mapping_id, diff)
)
# [2] check that fraction is correctly applied and reduced
# [2A] load_data_lookup
assert "fraction" in mapped_load_data_lookup.columns
# * this check is specific to the actual from_fraction values specified in the mapping *
data_filters = "data_source=='comstock' and subsector=='Warehouse' and model_year=='2050'"
fraction = [
row.fraction
for row in mapped_load_data_lookup.filter(data_filters)
.select("fraction")
.distinct()
.collect()
]
assert len(fraction) == 1
assert fraction[0] == (0.9 * 1.3)
# [2B] load_data
for ref in dataset._handler._mapping_references:
column = ref.from_dimension_type.value
if column == dataset._handler.get_pivot_dimension_type().value:
assert "fraction" not in mapped_load_data.columns
mapping_config = dataset._handler._dimension_mapping_mgr.get_by_id(ref.mapping_id)
records = mapping_config.model.records
# apply mapping to load_data.sum(), then compare to mapped_load_data.sum()
# 2B.1 get total enduse loads from each table
sum_query = [
f"SUM({col}) AS {col}" for col in dataset._handler.get_pivot_dimension_columns()
]
load_data_sum = dataset.load_data.selectExpr(*sum_query)
sum_query = [f"SUM({col}) AS {col}" for col in mapping_config.get_unique_to_ids()]
mapped_load_data_sum = mapped_load_data.selectExpr(*sum_query).toPandas()
# 2B.2 apply mapping
# this part of the code is the same as 'dataset_schema_handler_base._map_and_reduce_dimension() for pivoted dim mapping'
records_dict = defaultdict(dict)
for row in records:
if row.to_id is not None:
records_dict[row.to_id][row.from_id] = row.from_fraction
to_ids = sorted(records_dict)
value_operations = []
for tid in to_ids:
operation = "+".join(
[f"{from_id}*{fraction}" for from_id, fraction in records_dict[tid].items()]
) # assumes reduce by summation
operation += f" AS {tid}"
value_operations.append(operation)
load_data_sum = load_data_sum.selectExpr(*value_operations).toPandas()
# 2B.3 check that the newly mapped load_data_sum = mapped_load_data_sum within tolerance
decimal_tolerance = 3
load_data_diff = (
(load_data_sum - mapped_load_data_sum).round(decimal_tolerance).iloc[0]
) # pd.series
assert len(load_data_diff[load_data_diff != 0]) == 0
else:
pass
# def test_aggregate_load_by_state():
# store = DimensionStore.load(PROJECT_CONFIG_FILE)
# dataset = Dataset.load(store)
# df = dataset.aggregate_sector_sums_by_dimension(County, State)
# assert "state" in df.columns
# assert "sum((sum(fans) * scale_factor))" in df.columns
# # For now just ensure this doesn't fail.
# df.count()
| [
"dsgrid.project.Project.load",
"pyspark.sql.SparkSession.getActiveSession",
"dsgrid.exceptions.DSGInvalidDimensionMapping",
"collections.defaultdict",
"pytest.raises"
] | [((447, 519), 'dsgrid.project.Project.load', 'Project.load', (['PROJECT_ID'], {'offline_mode': '(True)', 'registry_path': 'TEST_REGISTRY'}), '(PROJECT_ID, offline_mode=True, registry_path=TEST_REGISTRY)\n', (459, 519), False, 'from dsgrid.project import Project\n'), ((574, 668), 'dsgrid.project.Project.load', 'Project.load', (['PROJECT_ID'], {'version': '"""1.0.0"""', 'offline_mode': '(True)', 'registry_path': 'TEST_REGISTRY'}), "(PROJECT_ID, version='1.0.0', offline_mode=True, registry_path=\n TEST_REGISTRY)\n", (586, 668), False, 'from dsgrid.project import Project\n'), ((1965, 2037), 'dsgrid.project.Project.load', 'Project.load', (['PROJECT_ID'], {'offline_mode': '(True)', 'registry_path': 'TEST_REGISTRY'}), '(PROJECT_ID, offline_mode=True, registry_path=TEST_REGISTRY)\n', (1977, 2037), False, 'from dsgrid.project import Project\n'), ((2174, 2205), 'pyspark.sql.SparkSession.getActiveSession', 'SparkSession.getActiveSession', ([], {}), '()\n', (2203, 2205), False, 'from pyspark.sql import SparkSession\n'), ((2959, 3031), 'dsgrid.project.Project.load', 'Project.load', (['PROJECT_ID'], {'offline_mode': '(True)', 'registry_path': 'TEST_REGISTRY'}), '(PROJECT_ID, offline_mode=True, registry_path=TEST_REGISTRY)\n', (2971, 3031), False, 'from dsgrid.project import Project\n'), ((1712, 1748), 'pytest.raises', 'pytest.raises', (['DSGValueNotRegistered'], {}), '(DSGValueNotRegistered)\n', (1725, 1748), False, 'import pytest\n'), ((1768, 1862), 'dsgrid.project.Project.load', 'Project.load', (['PROJECT_ID'], {'version': '"""0.0.0"""', 'offline_mode': '(True)', 'registry_path': 'TEST_REGISTRY'}), "(PROJECT_ID, version='0.0.0', offline_mode=True, registry_path=\n TEST_REGISTRY)\n", (1780, 1862), False, 'from dsgrid.project import Project\n'), ((4471, 4686), 'dsgrid.exceptions.DSGInvalidDimensionMapping', 'DSGInvalidDimensionMapping', (['("""Mapped %s is incorrect, check %s mapping: %s or mapping logic in \'dataset_schema_handler_base._map_and_reduce_dimension()\' \n%s"""\n % (table_type, column, ref.mapping_id, diff))'], {}), '(\n """Mapped %s is incorrect, check %s mapping: %s or mapping logic in \'dataset_schema_handler_base._map_and_reduce_dimension()\' \n%s"""\n % (table_type, column, ref.mapping_id, diff))\n', (4497, 4686), False, 'from dsgrid.exceptions import DSGValueNotRegistered, DSGInvalidDimensionMapping\n'), ((6433, 6450), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (6444, 6450), False, 'from collections import defaultdict\n')] |
import discord
from discord.ext import commands
class Info(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(help='Shows info about Dolphin', aliases=['link', 'l'])
async def links(self, ctx):
'''
Download links
'''
await ctx.send(embed=discord.Embed(title='Links:', description=
"Dolphin site: <https://dolphin-emu.org/>\n"
"Downloads: <https://dolphin-emu.org/download/>\n"
"FAQ: <https://dolphin-emu.org/docs/faq/>\n"
"Wiki: <https://wiki.dolphin-emu.org>\n"
"Forums: <https://forums.dolphin-emu.org/>\n"
"Source code: <https://github.com/dolphin-emu/dolphin>\n"
"Bug tracker: <https://bugs.dolphin-emu.org/projects/emulator/issues>\n"
"Translation: <https://www.transifex.com/delroth/dolphin-emu/>\n"
"TODO list: <https://wiki.dolphin-emu.org/index.php?title=TODO_List>\n"
"Developer wiki: <https://github.com/dolphin-emu/dolphin/wiki>\n"
"Reddit: <https://www.reddit.com/r/DolphinEmulator>\n"
"Twitter: <https://twitter.com/Dolphin_Emu>"
))
def setup(bot):
bot.add_cog(Info(bot))
| [
"discord.Embed",
"discord.ext.commands.command"
] | [((127, 199), 'discord.ext.commands.command', 'commands.command', ([], {'help': '"""Shows info about Dolphin"""', 'aliases': "['link', 'l']"}), "(help='Shows info about Dolphin', aliases=['link', 'l'])\n", (143, 199), False, 'from discord.ext import commands\n'), ((290, 965), 'discord.Embed', 'discord.Embed', ([], {'title': '"""Links:"""', 'description': '"""Dolphin site: <https://dolphin-emu.org/>\nDownloads: <https://dolphin-emu.org/download/>\nFAQ: <https://dolphin-emu.org/docs/faq/>\nWiki: <https://wiki.dolphin-emu.org>\nForums: <https://forums.dolphin-emu.org/>\nSource code: <https://github.com/dolphin-emu/dolphin>\nBug tracker: <https://bugs.dolphin-emu.org/projects/emulator/issues>\nTranslation: <https://www.transifex.com/delroth/dolphin-emu/>\nTODO list: <https://wiki.dolphin-emu.org/index.php?title=TODO_List>\nDeveloper wiki: <https://github.com/dolphin-emu/dolphin/wiki>\nReddit: <https://www.reddit.com/r/DolphinEmulator>\nTwitter: <https://twitter.com/Dolphin_Emu>"""'}), '(title=\'Links:\', description=\n """Dolphin site: <https://dolphin-emu.org/>\nDownloads: <https://dolphin-emu.org/download/>\nFAQ: <https://dolphin-emu.org/docs/faq/>\nWiki: <https://wiki.dolphin-emu.org>\nForums: <https://forums.dolphin-emu.org/>\nSource code: <https://github.com/dolphin-emu/dolphin>\nBug tracker: <https://bugs.dolphin-emu.org/projects/emulator/issues>\nTranslation: <https://www.transifex.com/delroth/dolphin-emu/>\nTODO list: <https://wiki.dolphin-emu.org/index.php?title=TODO_List>\nDeveloper wiki: <https://github.com/dolphin-emu/dolphin/wiki>\nReddit: <https://www.reddit.com/r/DolphinEmulator>\nTwitter: <https://twitter.com/Dolphin_Emu>"""\n )\n', (303, 965), False, 'import discord\n')] |
from functools import wraps
from qtpy import QtWidgets
from .histogram import HistogramWidget, HistogramModel, HistogramController
from .pdsspect_image_set import PDSSpectImageSetViewBase
class BasicHistogramModel(HistogramModel):
"""Model for the hhistograms in the Basic Widgets
Attributes
---------
connected_models : :obj:`list`
Other :class:`BasicHistogramModel` for other histograms
"""
def __init__(self, *args, **kwargs):
super(BasicHistogramModel, self).__init__(*args, **kwargs)
self.connected_models = []
def check_model_type(func):
@wraps(func)
def wrapper(self, model):
if not isinstance(model, BasicHistogramModel):
raise ValueError("Model must be a BasicHistogramModel object")
return func(self, model)
return wrapper
@check_model_type
def connect_model(self, model):
"""Connect another model to this model
Attributes
----------
model : :class:`BasicHistogramModel`
Connect the model to current model
Raises
------
ValueError
When :attr:`model` is not :class:`BasicHistogramModel`
"""
if model not in self.connected_models:
self.connected_models.append(model)
model.cuts = self.cuts
@check_model_type
def disconnect_model(self, model):
"""Disconnect another model from this model
Attributes
----------
model : :class:`BasicHistogramModel`
Disconnect the model from current model
Raises
------
ValueError
When :attr:`model` is not :class:`BasicHistogramModel`
"""
if model in self.connected_models:
self.connected_models.remove(model)
def disconnect_from_all_models(self):
"""Disconnect all models from this model"""
self.connected_models = []
class BasicHistogramController(HistogramController):
"""Controller for histogram views
Parameters
----------
model : :class:`BasicHistogramModel`
histogram model
view : :class:`object`
View with :class:`BasicHistogramModel` as its model
Attributes
----------
model : :class:`BasicHistogramModel`
histogram model
view : :class:`object`
View with :class:`BasicHistogramModel` as its model
"""
def set_cut_low(self, cut_low):
"""Set the low cut level to a new value
Parameters
----------
cut_low : :obj:`float`
New low cut value
"""
super(BasicHistogramController, self).set_cut_low(cut_low)
for model in self.model.connected_models:
model.cut_low = cut_low
def set_cut_high(self, cut_high):
"""Set the high cut level to a new value
Parameters
----------
cut_high : :obj:`float`
New high cut value
"""
super(BasicHistogramController, self).set_cut_high(cut_high)
for model in self.model.connected_models:
model.cut_high = cut_high
def set_cuts(self, cut_low, cut_high):
"""Set both the low and high cut levels
Parameters
----------
cut_low : :obj:`float`
New low cut value
cut_high : :obj:`float`
New high cut value
"""
super(BasicHistogramController, self).set_cuts(cut_low, cut_high)
for model in self.model.connected_models:
model.cuts = cut_low, cut_high
def restore(self):
"""Restore the histogram"""
super(BasicHistogramController, self).restore()
for model in self.model.connected_models:
model.restore()
class BasicHistogramWidget(HistogramWidget):
""":class:`~.pdsspect.histogram.HistogramWidget` in a different layout"""
def __init__(self, *args, **kwargs):
super(BasicHistogramWidget, self).__init__(*args, **kwargs)
self.controller = BasicHistogramController(self.model, self)
self.histogram.controller = BasicHistogramController(
self.model, self.histogram
)
def _create_layout(self):
layout = QtWidgets.QGridLayout()
layout.addWidget(self._cut_low_label, 0, 1)
layout.addWidget(self._cut_low_box, 0, 2)
layout.addWidget(self._cut_high_label, 1, 1)
layout.addWidget(self._cut_high_box, 1, 2)
layout.addWidget(self._bins_label, 2, 1)
layout.addWidget(self._bins_box, 2, 2)
layout.addWidget(self.histogram, 0, 0, 3, 1)
return layout
class BasicController(object):
"""Controller for :class:`Basic` window
Parameters
----------
image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`
pdsspect model
view : :class:`Basic`
View to control
Attributes
----------
image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`
pdsspect model
view : :class:`Basic`
View to control
"""
def __init__(self, image_set, view):
self.image_set = image_set
self.view = view
def change_current_image_index(self, new_index):
"""Change the current image index to a new index
Parameters
----------
new_index : :obj:`int`
The new index for
:class:`~.pdsspect_image_set.PDSSpectImageSetViewBase.images` to
determine the current image
"""
self.image_set.current_image_index = new_index
class BasicWidget(QtWidgets.QWidget):
"""Widget to hold each basic window
Parameters
----------
image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`
pdsspect model
view_canvas : :class:`~.pds_image_view_canvas.PDSImageViewCanvas`
view canvas
Attributes
----------
image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`
pdsspect model
basics : :obj:`list` of :class:`Basic`
:class:`Basic` in the widget
"""
def __init__(self, image_set, view_canvas):
super(BasicWidget, self).__init__()
self.image_set = image_set
self.basics = []
self.main_layout = QtWidgets.QHBoxLayout()
self.setLayout(self.main_layout)
self.setWindowTitle('Basic')
self.add_basic(image_set, view_canvas)
def add_basic(self, image_set, view_canvas):
"""Add a :class:`Basic` to the widget
Parameters
----------
image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`
pdsspect model
view_canvas : :class:`~.pds_image_view_canvas.PDSImageViewCanvas`
view canvas
"""
basic = Basic(image_set, view_canvas, self)
self.basics.append(basic)
self.main_layout.addWidget(basic)
self.connect_model(basic)
def connect_model(self, basic):
"""Connect the models of other basic windows to the given window
The models are connected when they have the same current image
Parameters
----------
basic : :class:`Basic`
Basic window connect/disconnect its histogram model to others
"""
other_basics = list(self.basics)
other_basics.remove(basic)
for other_basic in other_basics:
image = other_basic.image_set.current_image
if image == basic.image_set.current_image:
other_basic.histogram.connect_model(basic.histogram)
basic.histogram.connect_model(other_basic.histogram)
else:
other_basic.histogram.disconnect_model(basic.histogram)
basic.histogram.disconnect_model(other_basic.histogram)
class Basic(QtWidgets.QWidget, PDSSpectImageSetViewBase):
"""Window to apply cut levels and choose the current image
Parameters
----------
image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`
pdsspect model
view_canvas : :class:`~.pds_image_view_canvas.PDSImageViewCanvas`
Canvas to view the image
Attributes
----------
image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`
pdsspect model
view_canvas : :class:`~.pds_image_view_canvas.PDSImageViewCanvas`
Canvas to view the image
controller : :class:`BasicController`
Controller for view
image_menu : :class:`QtWidgets.QComboBox <PySide.QtGui.QComboBox>`
Drop down menu to pick the current image
histogram : :class:`~.histogram.HistogramModel`
Model for the :attr:`histogram_widget`
histogram_widget : :class:`BasicHistogramWidget`
The histogram widget to adjust the cut levels
layout : :class:`QtWidgets.QVBoxLayout <PySide.QtGui.QVBoxLayout>`
The main layout
"""
def __init__(self, image_set, view_canvas, basic_widget):
super(Basic, self).__init__(basic_widget)
self.image_set = image_set
self.image_set.register(self)
self.basic_widget = basic_widget
self.controller = BasicController(image_set, self)
self.view_canvas = view_canvas
self.image_menu = QtWidgets.QComboBox()
for image in self.image_set.images:
self.image_menu.addItem(image.image_name)
self.image_menu.setCurrentIndex(image_set.current_image_index)
self.image_menu.currentIndexChanged.connect(self.change_image)
self.histogram = BasicHistogramModel(self.view_canvas, bins=100)
self.histogram_widget = BasicHistogramWidget(self.histogram, self)
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.image_menu)
self.layout.addWidget(self.histogram_widget)
self.setLayout(self.layout)
self.histogram.set_data()
def change_image(self, new_index):
"""Change the image when new image selected in :attr:`image_menu`
Parameters
----------
new_index : :obj:`int`
The new index to determine the current image
"""
self.image_set.current_image.cuts = self.histogram.cuts
self.controller.change_current_image_index(new_index)
self.basic_widget.connect_model(self)
def set_image(self):
"""When the image is set, adjust the histogram"""
self.histogram.set_data()
self.histogram.restore()
| [
"qtpy.QtWidgets.QComboBox",
"qtpy.QtWidgets.QVBoxLayout",
"qtpy.QtWidgets.QGridLayout",
"functools.wraps",
"qtpy.QtWidgets.QHBoxLayout"
] | [((612, 623), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (617, 623), False, 'from functools import wraps\n'), ((4224, 4247), 'qtpy.QtWidgets.QGridLayout', 'QtWidgets.QGridLayout', ([], {}), '()\n', (4245, 4247), False, 'from qtpy import QtWidgets\n'), ((6215, 6238), 'qtpy.QtWidgets.QHBoxLayout', 'QtWidgets.QHBoxLayout', ([], {}), '()\n', (6236, 6238), False, 'from qtpy import QtWidgets\n'), ((9148, 9169), 'qtpy.QtWidgets.QComboBox', 'QtWidgets.QComboBox', ([], {}), '()\n', (9167, 9169), False, 'from qtpy import QtWidgets\n'), ((9581, 9604), 'qtpy.QtWidgets.QVBoxLayout', 'QtWidgets.QVBoxLayout', ([], {}), '()\n', (9602, 9604), False, 'from qtpy import QtWidgets\n')] |
import asyncio
from squall import Router, WebSocket
import orjson
class FanOut:
def __init__(self):
self.clients = set()
def join(self, ws):
self.clients.add(ws)
def left(self, ws):
self.clients.discard(ws)
async def send(self, message):
await asyncio.gather(*[ws.send_text(message) for ws in self.clients])
fanout = FanOut()
router = Router(prefix="/v1", tags=["Gateway"])
@router.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
fanout.join(websocket)
# await asyncio.sleep(5) # Emulate uge latency
commands = []
with open("/app/config.example.json") as fh:
data = orjson.loads(fh.read())
for service in data.get('services', []):
commands.append({
"type": "service",
"command": "add",
"data": service
})
if authentication := data.get('authentication', {}):
commands.append({
"type": "authentication",
"command": "add",
"data": authentication
})
await websocket.send_text(
orjson.dumps({
"data": commands
}).decode('utf-8')
)
try:
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
except Exception:
fanout.left(websocket)
| [
"squall.Router",
"orjson.dumps"
] | [((390, 428), 'squall.Router', 'Router', ([], {'prefix': '"""/v1"""', 'tags': "['Gateway']"}), "(prefix='/v1', tags=['Gateway'])\n", (396, 428), False, 'from squall import Router, WebSocket\n'), ((1180, 1212), 'orjson.dumps', 'orjson.dumps', (["{'data': commands}"], {}), "({'data': commands})\n", (1192, 1212), False, 'import orjson\n')] |
class Parser:
def __init__(self, *args, **kwargs):
import argparse
self.parser = argparse.ArgumentParser(
description='Request Ray-Triangle computations to the PYNQ-Z1 renderer.')
client_info = 'client: runs on any machine that accesses the PYNQ-Z1 renderer'
server_info = 'server: runs the render server on the PYNQ-Z1 board'
self.parser.add_argument(
'--mode',
choices=['client', 'server'],
help=f'Defines the execution mode: (1) {client_info}. (2) {server_info}')
self.parser.add_argument(
'--res',
type=int,
nargs=2,
help='Resolution of the final image')
self.parser.add_argument(
'--psize',
type=float,
help='Pixel size of the image')
self.args = self.parser.parse_args()
| [
"argparse.ArgumentParser"
] | [((102, 204), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Request Ray-Triangle computations to the PYNQ-Z1 renderer."""'}), "(description=\n 'Request Ray-Triangle computations to the PYNQ-Z1 renderer.')\n", (125, 204), False, 'import argparse\n')] |
import PySimpleGUI as sg
import os.path
import pandas as pd
from call_index import get_data, process_index
# Set path from computer
BROWSE_PATH = os.getcwd()+"/Dataset"
selected_filename = None
query = None
full_data = None
selected_doc = None
mii_index = None
original_data = None
def main():
global BROWSE_PATH, selected_filename, query, full_data, selected_doc, mii_index, original_data
sg.theme("Reddit")
file_list_row = [
[
sg.Text("Directorio"),
sg.In(size=(75, 1), enable_events=True, key="-FOLDER-"),
sg.FolderBrowse(button_text=" Buscar ", initial_folder=BROWSE_PATH,
tooltip=" Seleccione su archivo a indexar. "),
],
[
sg.Listbox(
values=[], enable_events=True, size=(200, 15), key="-FILE LIST-", no_scrollbar=True,
highlight_background_color='Blue'
)
],
[sg.Text(size=(80, 2), key="-TOUT-"), sg.Button(" Indexar ", key="-INDEX-")]
]
table_viewer_row = [
[sg.Text("Sección de Búsqueda", size=(80, 1))],
[sg.Text("Consulta"), sg.In(size=(70, 1), enable_events=True, key="-QUERY-"),
sg.Button(" Consultar ", key="-SEARCH-")],
[sg.Text(size=(80, 1), key="-MSG-")],
[sg.Listbox(values=[], key="-RESULT-", size=(200, 16), enable_events=True, no_scrollbar=True, )],
[sg.Button(" Abrir ", key="-SHOW-", button_color='gray', mouseover_colors='dodger blue', disabled=True),
sg.VSeparator(pad=260),
sg.Button(" Salir ", button_color='gray', mouseover_colors='red')]
]
# ----- Full layout -----
layout = [
[file_list_row],
[sg.HorizontalSeparator()],
[table_viewer_row]
]
window = sg.Window("Motor de Búsqueda", layout, size=(720, 720), location=(1000, 150))
# Run the Event Loop
while True:
event, values = window.read()
if event == " Salir " or event == sg.WIN_CLOSED:
break
# Folder name was filled in, make a list of files in the folder
if event == "-FOLDER-":
folder = values["-FOLDER-"]
try:
# Get list of files in folder
file_list = os.listdir(folder)
except:
file_list = []
fnames = [
f
for f in file_list
if os.path.isfile(os.path.join(folder, f))
and f.lower().endswith((".csv"))
]
print(fnames)
window["-FILE LIST-"].update(fnames)
elif event == "-FILE LIST-": # A file was chosen from the listbox
try:
filename = os.path.join(
values["-FOLDER-"], values["-FILE LIST-"][0]
)
selected_filename = filename
except Exception as e:
print(e)
elif event == "-INDEX-":
try:
if selected_filename is None:
window["-TOUT-"].update("Seleccione un archivo para indexar.")
continue
mii_index, success = process_index(selected_filename)
if success:
original_data = pd.read_csv(selected_filename)
window["-TOUT-"].update("El archivo {} fue procesado exitósamente!".format(selected_filename))
else:
window["-TOUT-"].update("Error al indexar el archivo.")
window["-MSG-"].update(filename=selected_filename)
except Exception as e:
print(e)
elif event == "-QUERY-":
try:
query = values["-QUERY-"]
except:
pass
elif event == "-SEARCH-":
try:
if query is None or len(query) < 1:
window["-MSG-"].update("Consulta no válida.")
continue
data = get_data(query, mii_index, original_data)
full_data = data
window["-MSG-"].update("Su consulta retornó {} archivos.".format(len(data)))
lines = []
for d in data:
lines.append("{:<10}".format(d[0]) + "{:<70}".format(d[1][:60]) + "\t" + (
"Spam" if d[2] == 1 else "No spam"))
window["-RESULT-"].update(lines)
except:
pass
elif event == "-RESULT-": # A file was chosen from the listbox
window["-SHOW-"].update(disabled=False)
try:
# TODO: obtain selected full body result
selected_doc = window[event].GetIndexes()[0]
except:
pass
elif event == "-SHOW-": # A file was chosen from the listbox
try:
doc = "{} - {}".format(full_data[selected_doc][0],
"Spam" if full_data[selected_doc][2] == 1 else "No spam")
layout2 = [[sg.Multiline(enable_events=True, disabled=True, size=(200, 15),
key="-TEXT-", no_scrollbar=True, default_text=full_data[selected_doc][1])]]
window2 = sg.Window(doc, layout2, size=(400, 200), location=(1200, 300))
event2, values2 = window2.read()
except:
pass
window.close()
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
main()
| [
"pandas.read_csv",
"PySimpleGUI.FolderBrowse",
"PySimpleGUI.Listbox",
"call_index.get_data",
"PySimpleGUI.In",
"PySimpleGUI.Text",
"PySimpleGUI.VSeparator",
"PySimpleGUI.Button",
"PySimpleGUI.theme",
"PySimpleGUI.HorizontalSeparator",
"call_index.process_index",
"PySimpleGUI.Multiline",
"PyS... | [((402, 420), 'PySimpleGUI.theme', 'sg.theme', (['"""Reddit"""'], {}), "('Reddit')\n", (410, 420), True, 'import PySimpleGUI as sg\n'), ((1789, 1866), 'PySimpleGUI.Window', 'sg.Window', (['"""Motor de Búsqueda"""', 'layout'], {'size': '(720, 720)', 'location': '(1000, 150)'}), "('Motor de Búsqueda', layout, size=(720, 720), location=(1000, 150))\n", (1798, 1866), True, 'import PySimpleGUI as sg\n'), ((465, 486), 'PySimpleGUI.Text', 'sg.Text', (['"""Directorio"""'], {}), "('Directorio')\n", (472, 486), True, 'import PySimpleGUI as sg\n'), ((500, 555), 'PySimpleGUI.In', 'sg.In', ([], {'size': '(75, 1)', 'enable_events': '(True)', 'key': '"""-FOLDER-"""'}), "(size=(75, 1), enable_events=True, key='-FOLDER-')\n", (505, 555), True, 'import PySimpleGUI as sg\n'), ((569, 690), 'PySimpleGUI.FolderBrowse', 'sg.FolderBrowse', ([], {'button_text': '""" Buscar """', 'initial_folder': 'BROWSE_PATH', 'tooltip': '""" Seleccione su archivo a indexar. """'}), "(button_text=' Buscar ', initial_folder=BROWSE_PATH,\n tooltip=' Seleccione su archivo a indexar. ')\n", (584, 690), True, 'import PySimpleGUI as sg\n'), ((749, 883), 'PySimpleGUI.Listbox', 'sg.Listbox', ([], {'values': '[]', 'enable_events': '(True)', 'size': '(200, 15)', 'key': '"""-FILE LIST-"""', 'no_scrollbar': '(True)', 'highlight_background_color': '"""Blue"""'}), "(values=[], enable_events=True, size=(200, 15), key='-FILE LIST-',\n no_scrollbar=True, highlight_background_color='Blue')\n", (759, 883), True, 'import PySimpleGUI as sg\n'), ((946, 981), 'PySimpleGUI.Text', 'sg.Text', ([], {'size': '(80, 2)', 'key': '"""-TOUT-"""'}), "(size=(80, 2), key='-TOUT-')\n", (953, 981), True, 'import PySimpleGUI as sg\n'), ((983, 1022), 'PySimpleGUI.Button', 'sg.Button', (['""" Indexar """'], {'key': '"""-INDEX-"""'}), "(' Indexar ', key='-INDEX-')\n", (992, 1022), True, 'import PySimpleGUI as sg\n'), ((1065, 1109), 'PySimpleGUI.Text', 'sg.Text', (['"""Sección de Búsqueda"""'], {'size': '(80, 1)'}), "('Sección de Búsqueda', size=(80, 1))\n", (1072, 1109), True, 'import PySimpleGUI as sg\n'), ((1121, 1140), 'PySimpleGUI.Text', 'sg.Text', (['"""Consulta"""'], {}), "('Consulta')\n", (1128, 1140), True, 'import PySimpleGUI as sg\n'), ((1142, 1196), 'PySimpleGUI.In', 'sg.In', ([], {'size': '(70, 1)', 'enable_events': '(True)', 'key': '"""-QUERY-"""'}), "(size=(70, 1), enable_events=True, key='-QUERY-')\n", (1147, 1196), True, 'import PySimpleGUI as sg\n'), ((1207, 1249), 'PySimpleGUI.Button', 'sg.Button', (['""" Consultar """'], {'key': '"""-SEARCH-"""'}), "(' Consultar ', key='-SEARCH-')\n", (1216, 1249), True, 'import PySimpleGUI as sg\n'), ((1261, 1295), 'PySimpleGUI.Text', 'sg.Text', ([], {'size': '(80, 1)', 'key': '"""-MSG-"""'}), "(size=(80, 1), key='-MSG-')\n", (1268, 1295), True, 'import PySimpleGUI as sg\n'), ((1307, 1403), 'PySimpleGUI.Listbox', 'sg.Listbox', ([], {'values': '[]', 'key': '"""-RESULT-"""', 'size': '(200, 16)', 'enable_events': '(True)', 'no_scrollbar': '(True)'}), "(values=[], key='-RESULT-', size=(200, 16), enable_events=True,\n no_scrollbar=True)\n", (1317, 1403), True, 'import PySimpleGUI as sg\n'), ((1413, 1522), 'PySimpleGUI.Button', 'sg.Button', (['""" Abrir """'], {'key': '"""-SHOW-"""', 'button_color': '"""gray"""', 'mouseover_colors': '"""dodger blue"""', 'disabled': '(True)'}), "(' Abrir ', key='-SHOW-', button_color='gray', mouseover_colors=\n 'dodger blue', disabled=True)\n", (1422, 1522), True, 'import PySimpleGUI as sg\n'), ((1528, 1550), 'PySimpleGUI.VSeparator', 'sg.VSeparator', ([], {'pad': '(260)'}), '(pad=260)\n', (1541, 1550), True, 'import PySimpleGUI as sg\n'), ((1561, 1628), 'PySimpleGUI.Button', 'sg.Button', (['""" Salir """'], {'button_color': '"""gray"""', 'mouseover_colors': '"""red"""'}), "(' Salir ', button_color='gray', mouseover_colors='red')\n", (1570, 1628), True, 'import PySimpleGUI as sg\n'), ((1716, 1740), 'PySimpleGUI.HorizontalSeparator', 'sg.HorizontalSeparator', ([], {}), '()\n', (1738, 1740), True, 'import PySimpleGUI as sg\n'), ((3174, 3206), 'call_index.process_index', 'process_index', (['selected_filename'], {}), '(selected_filename)\n', (3187, 3206), False, 'from call_index import get_data, process_index\n'), ((3271, 3301), 'pandas.read_csv', 'pd.read_csv', (['selected_filename'], {}), '(selected_filename)\n', (3282, 3301), True, 'import pandas as pd\n'), ((4003, 4044), 'call_index.get_data', 'get_data', (['query', 'mii_index', 'original_data'], {}), '(query, mii_index, original_data)\n', (4011, 4044), False, 'from call_index import get_data, process_index\n'), ((5264, 5326), 'PySimpleGUI.Window', 'sg.Window', (['doc', 'layout2'], {'size': '(400, 200)', 'location': '(1200, 300)'}), '(doc, layout2, size=(400, 200), location=(1200, 300))\n', (5273, 5326), True, 'import PySimpleGUI as sg\n'), ((5057, 5199), 'PySimpleGUI.Multiline', 'sg.Multiline', ([], {'enable_events': '(True)', 'disabled': '(True)', 'size': '(200, 15)', 'key': '"""-TEXT-"""', 'no_scrollbar': '(True)', 'default_text': 'full_data[selected_doc][1]'}), "(enable_events=True, disabled=True, size=(200, 15), key=\n '-TEXT-', no_scrollbar=True, default_text=full_data[selected_doc][1])\n", (5069, 5199), True, 'import PySimpleGUI as sg\n')] |
import tempfile
import shutil
import os
def _get_active_spark_session():
try:
from pyspark.sql import SparkSession
except ImportError:
# Return None if user doesn't have PySpark installed
return None
try:
# getActiveSession() only exists in Spark 3.0 and above
return SparkSession.getActiveSession()
except Exception:
# Fall back to this internal field for Spark 2.x and below.
return SparkSession._instantiatedSession
class _SparkDirectoryDistributor:
"""Distribute spark directory from driver to executors."""
_extracted_dir_paths = {}
def __init__(self):
pass
@staticmethod
def add_dir(spark, dir_path):
"""Given a SparkSession and a model_path which refers to a pyfunc directory locally,
we will zip the directory up, enable it to be distributed to executors, and return
the "archive_path", which should be used as the path in get_or_load().
"""
_, archive_basepath = tempfile.mkstemp()
# NB: We must archive the directory as Spark.addFile does not support non-DFS
# directories when recursive=True.
archive_path = shutil.make_archive(archive_basepath, "zip", dir_path)
spark.sparkContext.addFile(archive_path)
return archive_path
@staticmethod
def get_or_extract(archive_path):
"""Given a path returned by add_local_model(), this method will return a tuple of
(loaded_model, local_model_path).
If this Python process ever loaded the model before, we will reuse that copy.
"""
from pyspark.files import SparkFiles
import zipfile
if archive_path in _SparkDirectoryDistributor._extracted_dir_paths:
return _SparkDirectoryDistributor._extracted_dir_paths[archive_path]
# BUG: Despite the documentation of SparkContext.addFile() and SparkFiles.get() in Scala
# and Python, it turns out that we actually need to use the basename as the input to
# SparkFiles.get(), as opposed to the (absolute) path.
archive_path_basename = os.path.basename(archive_path)
local_path = SparkFiles.get(archive_path_basename)
temp_dir = tempfile.mkdtemp()
zip_ref = zipfile.ZipFile(local_path, "r")
zip_ref.extractall(temp_dir)
zip_ref.close()
_SparkDirectoryDistributor._extracted_dir_paths[archive_path] = temp_dir
return _SparkDirectoryDistributor._extracted_dir_paths[archive_path]
| [
"shutil.make_archive",
"zipfile.ZipFile",
"pyspark.sql.SparkSession.getActiveSession",
"pyspark.files.SparkFiles.get",
"os.path.basename",
"tempfile.mkdtemp",
"tempfile.mkstemp"
] | [((322, 353), 'pyspark.sql.SparkSession.getActiveSession', 'SparkSession.getActiveSession', ([], {}), '()\n', (351, 353), False, 'from pyspark.sql import SparkSession\n'), ((1019, 1037), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {}), '()\n', (1035, 1037), False, 'import tempfile\n'), ((1190, 1244), 'shutil.make_archive', 'shutil.make_archive', (['archive_basepath', '"""zip"""', 'dir_path'], {}), "(archive_basepath, 'zip', dir_path)\n", (1209, 1244), False, 'import shutil\n'), ((2121, 2151), 'os.path.basename', 'os.path.basename', (['archive_path'], {}), '(archive_path)\n', (2137, 2151), False, 'import os\n'), ((2173, 2210), 'pyspark.files.SparkFiles.get', 'SparkFiles.get', (['archive_path_basename'], {}), '(archive_path_basename)\n', (2187, 2210), False, 'from pyspark.files import SparkFiles\n'), ((2230, 2248), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (2246, 2248), False, 'import tempfile\n'), ((2267, 2299), 'zipfile.ZipFile', 'zipfile.ZipFile', (['local_path', '"""r"""'], {}), "(local_path, 'r')\n", (2282, 2299), False, 'import zipfile\n')] |
# -*- coding: utf-8 -*-
# Example package with a console entry point
"""Reads and formats data from the SWMM 5 output file."""
from __future__ import absolute_import, print_function
import copy
import datetime
import os
import struct
import sys
import warnings
from builtins import object, range, str, zip
import mando
import numpy as np
import pandas as pd
from mando.rst_text_formatter import RSTHelpFormatter
from tstoolbox import tsutils
PROPCODE = {
0: {1: "Area"},
1: {0: "Type", 2: "Inv_elev", 3: "Max_depth"},
2: {0: "Type", 4: "Inv_offset", 3: "Max_depth", 5: "Length"},
}
# Names for the 'Node type' and 'Link type' codes above
TYPECODE = {
0: {1: "Area"},
1: {0: "Junction", 1: "Outfall", 2: "Storage", 3: "Divider"}, # nodes
2: {0: "Conduit", 1: "Pump", 2: "Orifice", 3: "Weir", 4: "Outlet"}, # links
}
VARCODE = {
0: {
0: "Rainfall",
1: "Snow_depth",
2: "Evaporation_loss",
3: "Infiltration_loss",
4: "Runoff_rate",
5: "Groundwater_outflow",
6: "Groundwater_elevation",
7: "Soil_moisture",
},
1: {
0: "Depth_above_invert",
1: "Hydraulic_head",
2: "Volume_stored_ponded",
3: "Lateral_inflow",
4: "Total_inflow",
5: "Flow_lost_flooding",
},
2: {
0: "Flow_rate",
1: "Flow_depth",
2: "Flow_velocity",
3: "Froude_number",
4: "Capacity",
},
4: {
0: "Air_temperature",
1: "Rainfall",
2: "Snow_depth",
3: "Evaporation_infiltration",
4: "Runoff",
5: "Dry_weather_inflow",
6: "Groundwater_inflow",
7: "RDII_inflow",
8: "User_direct_inflow",
9: "Total_lateral_inflow",
10: "Flow_lost_to_flooding",
11: "Flow_leaving_outfalls",
12: "Volume_stored_water",
13: "Evaporation_rate",
14: "Potential_PET",
},
}
# Prior to 5.10.10
VARCODE_OLD = {
0: {
0: "Rainfall",
1: "Snow_depth",
2: "Evaporation_loss",
3: "Runoff_rate",
4: "Groundwater_outflow",
5: "Groundwater_elevation",
},
1: {
0: "Depth_above_invert",
1: "Hydraulic_head",
2: "Volume_stored_ponded",
3: "Lateral_inflow",
4: "Total_inflow",
5: "Flow_lost_flooding",
},
2: {
0: "Flow_rate",
1: "Flow_depth",
2: "Flow_velocity",
3: "Froude_number",
4: "Capacity",
},
4: {
0: "Air_temperature",
1: "Rainfall",
2: "Snow_depth",
3: "Evaporation_infiltration",
4: "Runoff",
5: "Dry_weather_inflow",
6: "Groundwater_inflow",
7: "RDII_inflow",
8: "User_direct_inflow",
9: "Total_lateral_inflow",
10: "Flow_lost_to_flooding",
11: "Flow_leaving_outfalls",
12: "Volume_stored_water",
13: "Evaporation_rate",
},
}
# swmm_flowunits is here, but currently not used.
_SWMM_FLOWUNITS = {0: "CFS", 1: "GPM", 2: "MGD", 3: "CMS", 4: "LPS", 5: "LPD"}
_LOCAL_DOCSTRINGS = tsutils.docstrings
_LOCAL_DOCSTRINGS[
"filename"
] = """filename : str
Filename of SWMM output file. The SWMM model must complete
successfully for "swmmtoolbox" to correctly read it.
"""
_LOCAL_DOCSTRINGS[
"itemtype"
] = """itemtype : str
One of 'system', 'node', 'link', or 'pollutant' to identify the
type of data you want to extract.
"""
_LOCAL_DOCSTRINGS[
"labels"
] = """labels : str
The remaining arguments uniquely identify a time-series
in the binary file. The format is::
'TYPE,NAME,VAR'
For example: 'link,41a,Flow_rate node,C63,1 ...'
The VAR part of the label can be the name of the variable or the index.
The available variables and their indices can be found using::
'swmmtoolbox listvariables filename.out'
All of the available labels can be listed with::
'swmmtoolbox catalog filename.out'
There is a wild card feature for the labels, where leaving the part out
will return all labels that match all other parts. For example,
+-----------------+-------------------------------------+
| link,b52, | Return all variables for link "b52" |
+-----------------+-------------------------------------+
| link,,Flow_rate | Return "Flow_rate" for all links |
+-----------------+-------------------------------------+
Note that all labels require two commas and no spaces.
"""
def tupleSearch(findme, haystack):
"""Partial search of list of tuples.
The "findme" argument is a tuple and this will find matches in "haystack"
which is a list of tuples of the same size as "findme". An empty string as
an item in "findme" is used as a wildcard for that item when searching
"haystack".
"""
match = []
for words in haystack:
testmatch = []
for i, j in zip(findme, words):
if not i:
testmatch.append(True)
continue
if i == j:
testmatch.append(True)
continue
testmatch.append(False)
if all(testmatch):
match.append(words)
return match
class SwmmExtract(object):
"""The class that handles all extraction of data from the out file."""
def __init__(self, filename):
self.RECORDSIZE = 4
self.fp = open(filename, "rb")
self.fp.seek(-6 * self.RECORDSIZE, 2)
(
self.Namesstartpos,
self.offset0,
self.startpos,
self.swmm_nperiods,
errcode,
magic2,
) = struct.unpack("6i", self.fp.read(6 * self.RECORDSIZE))
self.fp.seek(0, 0)
magic1 = struct.unpack("i", self.fp.read(self.RECORDSIZE))[0]
if magic1 != 516114522:
raise ValueError(
"""
*
* Beginning magic number incorrect.
*
"""
)
if magic2 != 516114522:
raise ValueError(
"""
*
* Ending magic number incorrect.
*
"""
)
if errcode != 0:
raise ValueError(
"""
*
* Error code "{0}" in output file indicates a problem with the run.
*
""".format(
errcode
)
)
if self.swmm_nperiods == 0:
raise ValueError(
"""
*
* There are zero time periods in the output file.
*
"""
)
# --- otherwise read additional parameters from start of file
(
version,
self.swmm_flowunits,
self.swmm_nsubcatch,
self.swmm_nnodes,
self.swmm_nlinks,
self.swmm_npolluts,
) = struct.unpack("6i", self.fp.read(6 * self.RECORDSIZE))
if version < 5100:
varcode = VARCODE_OLD
else:
varcode = VARCODE
self.itemlist = ["subcatchment", "node", "link", "pollutant", "system"]
# Read in the names
self.fp.seek(self.Namesstartpos, 0)
self.names = {0: [], 1: [], 2: [], 3: [], 4: []}
number_list = [
self.swmm_nsubcatch,
self.swmm_nnodes,
self.swmm_nlinks,
self.swmm_npolluts,
]
for i, j in enumerate(number_list):
for _ in range(j):
stringsize = struct.unpack("i", self.fp.read(self.RECORDSIZE))[0]
self.names[i].append(
struct.unpack("{0}s".format(stringsize), self.fp.read(stringsize))[
0
]
)
# Stupid Python 3
for key in self.names:
collect_names = []
for name in self.names[key]:
# Why would SWMM allow spaces in names? Anyway...
try:
rname = str(name, "ascii", "replace")
except TypeError:
rname = name.decode("ascii", "replace")
try:
collect_names.append(rname.decode())
except AttributeError:
collect_names.append(rname)
self.names[key] = collect_names
# Update self.varcode to add pollutant names to subcatchment,
# nodes, and links.
self.varcode = copy.deepcopy(varcode)
for itemtype in ["subcatchment", "node", "link"]:
typenumber = self.type_check(itemtype)
start = len(varcode[typenumber])
end = start + len(self.names[3])
nlabels = list(range(start, end))
ndict = dict(list(zip(nlabels, self.names[3])))
self.varcode[typenumber].update(ndict)
# Read pollutant concentration codes
# = Number of pollutants * 4 byte integers
self.pollutant_codes = struct.unpack(
"{0}i".format(self.swmm_npolluts),
self.fp.read(self.swmm_npolluts * self.RECORDSIZE),
)
self.propcode = {}
# self.prop[0] contain property codes and values for
# subcatchments
# self.prop[1] contain property codes and values for nodes
# self.prop[2] contain property codes and values for links
self.prop = {0: [], 1: [], 2: []}
# subcatchments
nsubprop = struct.unpack("i", self.fp.read(self.RECORDSIZE))[0]
self.propcode[0] = struct.unpack(
"{0}i".format(nsubprop), self.fp.read(nsubprop * self.RECORDSIZE)
)
for i in range(self.swmm_nsubcatch):
rprops = struct.unpack(
"{0}f".format(nsubprop), self.fp.read(nsubprop * self.RECORDSIZE)
)
self.prop[0].append(list(zip(self.propcode[0], rprops)))
# nodes
nnodeprop = struct.unpack("i", self.fp.read(self.RECORDSIZE))[0]
self.propcode[1] = struct.unpack(
"{0}i".format(nnodeprop), self.fp.read(nnodeprop * self.RECORDSIZE)
)
for i in range(self.swmm_nnodes):
rprops = struct.unpack(
"{0}f".format(nnodeprop), self.fp.read(nnodeprop * self.RECORDSIZE)
)
self.prop[1].append(list(zip(self.propcode[1], rprops)))
# links
nlinkprop = struct.unpack("i", self.fp.read(self.RECORDSIZE))[0]
self.propcode[2] = struct.unpack(
"{0}i".format(nlinkprop), self.fp.read(nlinkprop * self.RECORDSIZE)
)
for i in range(self.swmm_nlinks):
rprops = struct.unpack(
"{0}f".format(nlinkprop), self.fp.read(nlinkprop * self.RECORDSIZE)
)
self.prop[2].append(list(zip(self.propcode[2], rprops)))
self.vars = {}
self.swmm_nsubcatchvars = struct.unpack("i", self.fp.read(self.RECORDSIZE))[0]
self.vars[0] = struct.unpack(
"{0}i".format(self.swmm_nsubcatchvars),
self.fp.read(self.swmm_nsubcatchvars * self.RECORDSIZE),
)
self.nnodevars = struct.unpack("i", self.fp.read(self.RECORDSIZE))[0]
self.vars[1] = struct.unpack(
"{0}i".format(self.nnodevars),
self.fp.read(self.nnodevars * self.RECORDSIZE),
)
self.nlinkvars = struct.unpack("i", self.fp.read(self.RECORDSIZE))[0]
self.vars[2] = struct.unpack(
"{0}i".format(self.nlinkvars),
self.fp.read(self.nlinkvars * self.RECORDSIZE),
)
self.vars[3] = [0]
self.nsystemvars = struct.unpack("i", self.fp.read(self.RECORDSIZE))[0]
self.vars[4] = struct.unpack(
"{0}i".format(self.nsystemvars),
self.fp.read(self.nsystemvars * self.RECORDSIZE),
)
# System vars do not have names per se, but made names = number labels
self.names[4] = [self.varcode[4][i] for i in self.vars[4]]
self.startdate = struct.unpack("d", self.fp.read(2 * self.RECORDSIZE))[0]
days = int(self.startdate)
seconds = (self.startdate - days) * 86400
self.startdate = datetime.datetime(1899, 12, 30) + datetime.timedelta(
days=days, seconds=seconds
)
self.reportinterval = struct.unpack("i", self.fp.read(self.RECORDSIZE))[0]
self.reportinterval = datetime.timedelta(seconds=self.reportinterval)
# Calculate the bytes for each time period when
# reading the computed results
self.bytesperperiod = self.RECORDSIZE * (
2
+ self.swmm_nsubcatch * self.swmm_nsubcatchvars
+ self.swmm_nnodes * self.nnodevars
+ self.swmm_nlinks * self.nlinkvars
+ self.nsystemvars
)
def type_check(self, itemtype):
if itemtype in [0, 1, 2, 3, 4]:
return itemtype
try:
typenumber = self.itemlist.index(itemtype)
except ValueError:
raise ValueError(
"""
*
* Type argument "{0}" is incorrect.
* Must be in "{1}".
*
""".format(
itemtype, list(range(5)) + self.itemlist
)
)
return typenumber
def name_check(self, itemtype, itemname):
self.itemtype = self.type_check(itemtype)
try:
itemindex = self.names[self.itemtype].index(str(itemname))
except (ValueError, KeyError):
raise ValueError(
"""
*
* {0} was not found in "{1}" list.
*
""".format(
itemname, itemtype
)
)
return (itemname, itemindex)
def get_swmm_results(self, itemtype, name, variableindex, period):
if itemtype not in [0, 1, 2, 4]:
raise ValueError(
"""
*
* Type must be one of subcatchment (0), node (1). link (2), or system (4).
* You gave "{0}".
*
""".format(
itemtype
)
)
_, itemindex = self.name_check(itemtype, name)
date_offset = self.startpos + period * self.bytesperperiod
# Rewind
self.fp.seek(date_offset, 0)
date = struct.unpack("d", self.fp.read(2 * self.RECORDSIZE))[0]
offset = date_offset + 2 * self.RECORDSIZE # skip the date
if itemtype == 0:
offset = offset + self.RECORDSIZE * (itemindex * self.swmm_nsubcatchvars)
elif itemtype == 1:
offset = offset + self.RECORDSIZE * (
self.swmm_nsubcatch * self.swmm_nsubcatchvars
+ itemindex * self.nnodevars
)
elif itemtype == 2:
offset = offset + self.RECORDSIZE * (
self.swmm_nsubcatch * self.swmm_nsubcatchvars
+ self.swmm_nnodes * self.nnodevars
+ itemindex * self.nlinkvars
)
elif itemtype == 4:
offset = offset + self.RECORDSIZE * (
self.swmm_nsubcatch * self.swmm_nsubcatchvars
+ self.swmm_nnodes * self.nnodevars
+ self.swmm_nlinks * self.nlinkvars
)
offset = offset + self.RECORDSIZE * variableindex
self.fp.seek(offset, 0)
value = struct.unpack("f", self.fp.read(self.RECORDSIZE))[0]
return (date, value)
def get_dates(self):
"""Return start and end date tuple."""
begindate = datetime.datetime(1899, 12, 30)
ntimes = list(range(self.swmm_nperiods))
periods = [ntimes[0], ntimes[-1]]
st_end = []
for period in periods:
date_offset = self.startpos + period * self.bytesperperiod
self.fp.seek(date_offset, 0)
day = struct.unpack("d", self.fp.read(2 * self.RECORDSIZE))[0]
st_end.append(begindate + datetime.timedelta(days=int(day)))
return st_end
@mando.command()
def about():
"""Display version number and system information."""
tsutils.about(__name__)
@mando.command("catalog", formatter_class=RSTHelpFormatter, doctype="numpy")
@tsutils.doc(_LOCAL_DOCSTRINGS)
def catalog_cli(filename, itemtype="", tablefmt="csv_nos", header="default"):
"""List the catalog of objects in output file.
This catalog list is all of the labels that can be used in the extract
routine.
Parameters
----------
{filename}
{itemtype}
{tablefmt}
{header}
"""
if header == "default":
header = ["TYPE", "NAME", "VARIABLE"]
tsutils._printiso(
catalog(filename, itemtype=itemtype), headers=header, tablefmt=tablefmt
)
def catalog(filename, itemtype=""):
"""List the catalog of objects in output file."""
obj = SwmmExtract(filename)
if itemtype:
typenumber = obj.type_check(itemtype)
plist = [typenumber]
else:
plist = list(range(len(obj.itemlist)))
collect = []
for i in plist:
typenumber = obj.type_check(obj.itemlist[i])
for oname in obj.names[i]:
if obj.itemlist[i] == "pollutant":
continue
if obj.itemlist[i] == "system":
collect.append(["system", oname, oname])
continue
for j in obj.vars[typenumber]:
collect.append([obj.itemlist[i], oname, obj.varcode[typenumber][j]])
return collect
@mando.command("listdetail", formatter_class=RSTHelpFormatter, doctype="numpy")
@tsutils.doc(_LOCAL_DOCSTRINGS)
def listdetail_cli(filename, itemtype, name="", tablefmt="simple", header="default"):
"""List nodes and metadata in output file.
Parameters
----------
{filename}
{itemtype}
name : str
[optional, default is '']
Specific name to print only that entry. This can be
looked up using 'listvariables'.
{tablefmt}
{header}
"""
tsutils._printiso(
listdetail(filename, itemtype, name=name, header=header), tablefmt=tablefmt
)
def listdetail(filename, itemtype, name="", header="default"):
"""List nodes and metadata in output file."""
obj = SwmmExtract(filename)
typenumber = obj.type_check(itemtype)
if name:
objectlist = [obj.name_check(itemtype, name)[0]]
else:
objectlist = obj.names[typenumber]
propnumbers = obj.propcode[typenumber]
if header == "default":
header = ["#Name"] + [PROPCODE[typenumber][i] for i in propnumbers]
collect = []
for i, oname in enumerate(objectlist):
printvar = [oname]
for j in obj.prop[typenumber][i]:
if j[0] == 0:
try:
printvar.append(TYPECODE[typenumber][j[1]])
except KeyError:
printvar.append(TYPECODE[typenumber][0])
else:
printvar.append(j[1])
collect.append(printvar)
df = pd.DataFrame(collect)
cheader = []
for head in header:
if head not in cheader:
cheader.append(head)
else:
cnt = cheader.count(head)
cheader.append("{0}.{1}".format(head, cnt))
df.columns = cheader
return df
@mando.command("listvariables", formatter_class=RSTHelpFormatter, doctype="numpy")
@tsutils.doc(_LOCAL_DOCSTRINGS)
def listvariables_cli(filename, tablefmt="csv_nos", header="default"):
"""List variables available for each type.
The type are "subcatchment", "node", "link", "pollutant", "system".
Parameters
----------
{filename}
{tablefmt}
{header}
"""
tsutils._printiso(listvariables(filename, header=header), tablefmt=tablefmt)
def listvariables(filename, header="default"):
"""List variables available for each type."""
obj = SwmmExtract(filename)
if header == "default":
header = ["TYPE", "DESCRIPTION", "VARINDEX"]
# 'pollutant' really isn't it's own itemtype
# but part of subcatchment, node, and link...
collect = []
for itemtype in ["subcatchment", "node", "link", "system"]:
typenumber = obj.type_check(itemtype)
for i in obj.vars[typenumber]:
try:
collect.append([itemtype, obj.varcode[typenumber][i].decode(), i])
except (TypeError, AttributeError):
collect.append([itemtype, str(obj.varcode[typenumber][i]), str(i)])
return collect
@mando.command("stdtoswmm5", formatter_class=RSTHelpFormatter, doctype="numpy")
@tsutils.doc(_LOCAL_DOCSTRINGS)
def stdtoswmm5_cli(start_date=None, end_date=None, input_ts="-"):
"""Take the toolbox standard format and return SWMM5 format.
Toolbox standard::
Datetime, Column_Name
2000-01-01 00:00:00 , 45.6
2000-01-01 01:00:00 , 45.2
...
SWMM5 format::
; comment line
01/01/2000 00:00, 45.6
01/01/2000 01:00, 45.2
...
Parameters
----------
{input_ts}
{start_date}
{end_date}
"""
tsutils._printiso(
stdtoswmm5(start_date=start_date, end_date=end_date, input_ts=input_ts)
)
def stdtoswmm5(start_date=None, end_date=None, input_ts="-"):
"""Take the toolbox standard format and return SWMM5 format."""
import csv
sys.tracebacklimit = 1000
tsd = tsutils.read_iso_ts(input_ts)[start_date:end_date]
try:
# Header
print(";Datetime,", ", ".join(str(i) for i in tsd.columns))
# Data
cols = tsd.columns.tolist()
tsd["date_tmp_tstoolbox"] = tsd.index.format(
formatter=lambda x: x.strftime("%m/%d/%Y")
)
tsd["time_tmp_tstoolbox"] = tsd.index.format(
formatter=lambda x: x.strftime("%H:%M:%S")
)
tsd.to_csv(
sys.stdout,
float_format="%g",
header=False,
index=False,
cols=["date_tmp_tstoolbox", "time_tmp_tstoolbox"] + cols,
sep=" ",
quoting=csv.QUOTE_NONE,
)
except IOError:
return
@mando.command(formatter_class=RSTHelpFormatter, doctype="numpy")
@tsutils.doc(_LOCAL_DOCSTRINGS)
def getdata(filename, *labels):
"""DEPRECATED: Use 'extract' instead."""
return extract(filename, *labels)
@mando.command("extract", formatter_class=RSTHelpFormatter, doctype="numpy")
@tsutils.doc(_LOCAL_DOCSTRINGS)
def extract_cli(filename, *labels):
"""Get the time series data for a particular object and variable.
Parameters
----------
{filename}
{labels}
"""
tsutils._printiso(extract(filename, *labels))
def extract(filename, *labels):
"""Get the time series data for a particular object and variable."""
obj = SwmmExtract(filename)
nlabels = []
if isinstance(labels, (list, tuple)) and len(labels) == 1:
labels = labels[0]
for label in labels:
words = tsutils.make_list(label, n=3)
if None not in words:
nlabels.append(words)
continue
try:
words[2] = int(words[2])
typenumber = obj.type_check(words[2])
words[2] = obj.varcode[typenumber][words[2]]
except (ValueError, TypeError):
pass
words = [str(i) if i is not None else None for i in words]
res = tupleSearch(words, catalog(filename))
nlabels = nlabels + res
jtsd = []
for itemtype, name, variablename in nlabels:
typenumber = obj.type_check(itemtype)
name = obj.name_check(itemtype, name)[0]
inv_varcode_map = dict(
zip(obj.varcode[typenumber].values(), obj.varcode[typenumber].keys())
)
try:
variableindex = inv_varcode_map[int(variablename)]
except ValueError:
variableindex = inv_varcode_map[variablename]
begindate = datetime.datetime(1899, 12, 30)
dates = []
values = []
for time in range(obj.swmm_nperiods):
date, value = obj.get_swmm_results(typenumber, name, variableindex, time)
days = int(date)
seconds = int((date - days) * 86400)
extra = seconds % 10
if extra != 0:
if extra == 9:
seconds = seconds + 1
if extra == 1:
seconds = seconds - 1
date = begindate + datetime.timedelta(days=days, seconds=seconds)
dates.append(date)
values.append(value)
if itemtype == "system":
name = ""
jtsd.append(
pd.DataFrame(
pd.Series(values, index=dates),
columns=[
"{0}_{1}_{2}".format(
itemtype, name, obj.varcode[typenumber][variableindex]
)
],
)
)
result = pd.concat(jtsd, axis=1).reindex(jtsd[0].index)
return result
@tsutils.doc(_LOCAL_DOCSTRINGS)
def extract_arr(filename, *labels):
"""DEPRECATED: Extract and return the raw numpy array.
DEPRECATED: Will be removed in future version. Instead use the following.
>>> from swmmtoolbox import swmmtoolbox
>>> na = swmmtoolbox.extract("filename.out", "link,41a,Flow_rate")[0].to_array()
The `extract_arr` function will return the numpy array for the last entry
in "*labels".
Parameters
----------
{filename}
{labels}
"""
warnings.warn(
tsutils.error_wrapper(
"""
DEPRECATED: Will be removed in future version. Instead use the following.
>>> from swmmtoolbox import swmmtoolbox
>>> na = swmmtoolbox.extract("filename.out", "link,41a,Flow_rate")[0].to_array()
"""
)
)
obj = SwmmExtract(filename)
for label in labels:
itemtype, name, variableindex = tsutils.make_list(label, n=3)
typenumber = obj.type_check(itemtype)
if itemtype != "system":
name = obj.name_check(itemtype, name)[0]
data = np.zeros(len(list(range(obj.swmm_nperiods))))
for time in range(obj.swmm_nperiods):
_, value = obj.get_swmm_results(typenumber, name, int(variableindex), time)
data[time] = value
return data
def main():
if not os.path.exists("debug_swmmtoolbox"):
sys.tracebacklimit = 0
mando.main()
if __name__ == "__main__":
main()
| [
"datetime.datetime",
"os.path.exists",
"pandas.Series",
"tstoolbox.tsutils.make_list",
"tstoolbox.tsutils.doc",
"tstoolbox.tsutils.about",
"builtins.str",
"tstoolbox.tsutils.error_wrapper",
"builtins.zip",
"builtins.range",
"mando.main",
"copy.deepcopy",
"pandas.DataFrame",
"datetime.timed... | [((15877, 15892), 'mando.command', 'mando.command', ([], {}), '()\n', (15890, 15892), False, 'import mando\n'), ((15994, 16069), 'mando.command', 'mando.command', (['"""catalog"""'], {'formatter_class': 'RSTHelpFormatter', 'doctype': '"""numpy"""'}), "('catalog', formatter_class=RSTHelpFormatter, doctype='numpy')\n", (16007, 16069), False, 'import mando\n'), ((16071, 16101), 'tstoolbox.tsutils.doc', 'tsutils.doc', (['_LOCAL_DOCSTRINGS'], {}), '(_LOCAL_DOCSTRINGS)\n', (16082, 16101), False, 'from tstoolbox import tsutils\n'), ((17346, 17424), 'mando.command', 'mando.command', (['"""listdetail"""'], {'formatter_class': 'RSTHelpFormatter', 'doctype': '"""numpy"""'}), "('listdetail', formatter_class=RSTHelpFormatter, doctype='numpy')\n", (17359, 17424), False, 'import mando\n'), ((17426, 17456), 'tstoolbox.tsutils.doc', 'tsutils.doc', (['_LOCAL_DOCSTRINGS'], {}), '(_LOCAL_DOCSTRINGS)\n', (17437, 17456), False, 'from tstoolbox import tsutils\n'), ((19123, 19209), 'mando.command', 'mando.command', (['"""listvariables"""'], {'formatter_class': 'RSTHelpFormatter', 'doctype': '"""numpy"""'}), "('listvariables', formatter_class=RSTHelpFormatter, doctype=\n 'numpy')\n", (19136, 19209), False, 'import mando\n'), ((19206, 19236), 'tstoolbox.tsutils.doc', 'tsutils.doc', (['_LOCAL_DOCSTRINGS'], {}), '(_LOCAL_DOCSTRINGS)\n', (19217, 19236), False, 'from tstoolbox import tsutils\n'), ((20324, 20402), 'mando.command', 'mando.command', (['"""stdtoswmm5"""'], {'formatter_class': 'RSTHelpFormatter', 'doctype': '"""numpy"""'}), "('stdtoswmm5', formatter_class=RSTHelpFormatter, doctype='numpy')\n", (20337, 20402), False, 'import mando\n'), ((20404, 20434), 'tstoolbox.tsutils.doc', 'tsutils.doc', (['_LOCAL_DOCSTRINGS'], {}), '(_LOCAL_DOCSTRINGS)\n', (20415, 20434), False, 'from tstoolbox import tsutils\n'), ((21934, 21998), 'mando.command', 'mando.command', ([], {'formatter_class': 'RSTHelpFormatter', 'doctype': '"""numpy"""'}), "(formatter_class=RSTHelpFormatter, doctype='numpy')\n", (21947, 21998), False, 'import mando\n'), ((22000, 22030), 'tstoolbox.tsutils.doc', 'tsutils.doc', (['_LOCAL_DOCSTRINGS'], {}), '(_LOCAL_DOCSTRINGS)\n', (22011, 22030), False, 'from tstoolbox import tsutils\n'), ((22149, 22224), 'mando.command', 'mando.command', (['"""extract"""'], {'formatter_class': 'RSTHelpFormatter', 'doctype': '"""numpy"""'}), "('extract', formatter_class=RSTHelpFormatter, doctype='numpy')\n", (22162, 22224), False, 'import mando\n'), ((22226, 22256), 'tstoolbox.tsutils.doc', 'tsutils.doc', (['_LOCAL_DOCSTRINGS'], {}), '(_LOCAL_DOCSTRINGS)\n', (22237, 22256), False, 'from tstoolbox import tsutils\n'), ((24790, 24820), 'tstoolbox.tsutils.doc', 'tsutils.doc', (['_LOCAL_DOCSTRINGS'], {}), '(_LOCAL_DOCSTRINGS)\n', (24801, 24820), False, 'from tstoolbox import tsutils\n'), ((15967, 15990), 'tstoolbox.tsutils.about', 'tsutils.about', (['__name__'], {}), '(__name__)\n', (15980, 15990), False, 'from tstoolbox import tsutils\n'), ((18845, 18866), 'pandas.DataFrame', 'pd.DataFrame', (['collect'], {}), '(collect)\n', (18857, 18866), True, 'import pandas as pd\n'), ((26174, 26186), 'mando.main', 'mando.main', ([], {}), '()\n', (26184, 26186), False, 'import mando\n'), ((5065, 5083), 'builtins.zip', 'zip', (['findme', 'words'], {}), '(findme, words)\n', (5068, 5083), False, 'from builtins import object, range, str, zip\n'), ((8475, 8497), 'copy.deepcopy', 'copy.deepcopy', (['varcode'], {}), '(varcode)\n', (8488, 8497), False, 'import copy\n'), ((9652, 9678), 'builtins.range', 'range', (['self.swmm_nsubcatch'], {}), '(self.swmm_nsubcatch)\n', (9657, 9678), False, 'from builtins import object, range, str, zip\n'), ((10120, 10143), 'builtins.range', 'range', (['self.swmm_nnodes'], {}), '(self.swmm_nnodes)\n', (10125, 10143), False, 'from builtins import object, range, str, zip\n'), ((10587, 10610), 'builtins.range', 'range', (['self.swmm_nlinks'], {}), '(self.swmm_nlinks)\n', (10592, 10610), False, 'from builtins import object, range, str, zip\n'), ((12376, 12423), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 'self.reportinterval'}), '(seconds=self.reportinterval)\n', (12394, 12423), False, 'import datetime\n'), ((15418, 15449), 'datetime.datetime', 'datetime.datetime', (['(1899)', '(12)', '(30)'], {}), '(1899, 12, 30)\n', (15435, 15449), False, 'import datetime\n'), ((21198, 21227), 'tstoolbox.tsutils.read_iso_ts', 'tsutils.read_iso_ts', (['input_ts'], {}), '(input_ts)\n', (21217, 21227), False, 'from tstoolbox import tsutils\n'), ((22770, 22799), 'tstoolbox.tsutils.make_list', 'tsutils.make_list', (['label'], {'n': '(3)'}), '(label, n=3)\n', (22787, 22799), False, 'from tstoolbox import tsutils\n'), ((23718, 23749), 'datetime.datetime', 'datetime.datetime', (['(1899)', '(12)', '(30)'], {}), '(1899, 12, 30)\n', (23735, 23749), False, 'import datetime\n'), ((23809, 23833), 'builtins.range', 'range', (['obj.swmm_nperiods'], {}), '(obj.swmm_nperiods)\n', (23814, 23833), False, 'from builtins import object, range, str, zip\n'), ((25317, 25554), 'tstoolbox.tsutils.error_wrapper', 'tsutils.error_wrapper', (['"""\nDEPRECATED: Will be removed in future version. Instead use the following.\n\n>>> from swmmtoolbox import swmmtoolbox\n\n>>> na = swmmtoolbox.extract("filename.out", "link,41a,Flow_rate")[0].to_array()\n"""'], {}), '(\n """\nDEPRECATED: Will be removed in future version. Instead use the following.\n\n>>> from swmmtoolbox import swmmtoolbox\n\n>>> na = swmmtoolbox.extract("filename.out", "link,41a,Flow_rate")[0].to_array()\n"""\n )\n', (25338, 25554), False, 'from tstoolbox import tsutils\n'), ((25670, 25699), 'tstoolbox.tsutils.make_list', 'tsutils.make_list', (['label'], {'n': '(3)'}), '(label, n=3)\n', (25687, 25699), False, 'from tstoolbox import tsutils\n'), ((25915, 25939), 'builtins.range', 'range', (['obj.swmm_nperiods'], {}), '(obj.swmm_nperiods)\n', (25920, 25939), False, 'from builtins import object, range, str, zip\n'), ((26102, 26137), 'os.path.exists', 'os.path.exists', (['"""debug_swmmtoolbox"""'], {}), "('debug_swmmtoolbox')\n", (26116, 26137), False, 'import os\n'), ((7490, 7498), 'builtins.range', 'range', (['j'], {}), '(j)\n', (7495, 7498), False, 'from builtins import object, range, str, zip\n'), ((12159, 12190), 'datetime.datetime', 'datetime.datetime', (['(1899)', '(12)', '(30)'], {}), '(1899, 12, 30)\n', (12176, 12190), False, 'import datetime\n'), ((12193, 12239), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'days', 'seconds': 'seconds'}), '(days=days, seconds=seconds)\n', (12211, 12239), False, 'import datetime\n'), ((15472, 15497), 'builtins.range', 'range', (['self.swmm_nperiods'], {}), '(self.swmm_nperiods)\n', (15477, 15497), False, 'from builtins import object, range, str, zip\n'), ((24722, 24745), 'pandas.concat', 'pd.concat', (['jtsd'], {'axis': '(1)'}), '(jtsd, axis=1)\n', (24731, 24745), True, 'import pandas as pd\n'), ((8724, 8741), 'builtins.range', 'range', (['start', 'end'], {}), '(start, end)\n', (8729, 8741), False, 'from builtins import object, range, str, zip\n'), ((13392, 13405), 'builtins.str', 'str', (['itemname'], {}), '(itemname)\n', (13395, 13405), False, 'from builtins import object, range, str, zip\n'), ((23116, 23122), 'builtins.str', 'str', (['i'], {}), '(i)\n', (23119, 23122), False, 'from builtins import object, range, str, zip\n'), ((24236, 24282), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'days', 'seconds': 'seconds'}), '(days=days, seconds=seconds)\n', (24254, 24282), False, 'import datetime\n'), ((24465, 24495), 'pandas.Series', 'pd.Series', (['values'], {'index': 'dates'}), '(values, index=dates)\n', (24474, 24495), True, 'import pandas as pd\n'), ((8020, 8049), 'builtins.str', 'str', (['name', '"""ascii"""', '"""replace"""'], {}), "(name, 'ascii', 'replace')\n", (8023, 8049), False, 'from builtins import object, range, str, zip\n'), ((8773, 8800), 'builtins.zip', 'zip', (['nlabels', 'self.names[3]'], {}), '(nlabels, self.names[3])\n', (8776, 8800), False, 'from builtins import object, range, str, zip\n'), ((9849, 9878), 'builtins.zip', 'zip', (['self.propcode[0]', 'rprops'], {}), '(self.propcode[0], rprops)\n', (9852, 9878), False, 'from builtins import object, range, str, zip\n'), ((10316, 10345), 'builtins.zip', 'zip', (['self.propcode[1]', 'rprops'], {}), '(self.propcode[1], rprops)\n', (10319, 10345), False, 'from builtins import object, range, str, zip\n'), ((10783, 10812), 'builtins.zip', 'zip', (['self.propcode[2]', 'rprops'], {}), '(self.propcode[2], rprops)\n', (10786, 10812), False, 'from builtins import object, range, str, zip\n'), ((21313, 21319), 'builtins.str', 'str', (['i'], {}), '(i)\n', (21316, 21319), False, 'from builtins import object, range, str, zip\n'), ((25866, 25890), 'builtins.range', 'range', (['obj.swmm_nperiods'], {}), '(obj.swmm_nperiods)\n', (25871, 25890), False, 'from builtins import object, range, str, zip\n'), ((20260, 20291), 'builtins.str', 'str', (['obj.varcode[typenumber][i]'], {}), '(obj.varcode[typenumber][i])\n', (20263, 20291), False, 'from builtins import object, range, str, zip\n'), ((20293, 20299), 'builtins.str', 'str', (['i'], {}), '(i)\n', (20296, 20299), False, 'from builtins import object, range, str, zip\n'), ((13142, 13150), 'builtins.range', 'range', (['(5)'], {}), '(5)\n', (13147, 13150), False, 'from builtins import object, range, str, zip\n')] |
from graphviz import Digraph
from Nodo import Nodo
dot = Digraph(comment='AST')
#dot.render('test-output/round-table.gv', view=True) # doctest: +SKIP
#'test-output/round-table.gv.jpg'
class AST:
def __init__(self):
self.count = 0
print("constructor")
def defineTreeNodes(self, root):
root.setId(str(self.count))
dot.node(str(self.count), root.getVal())
self.count += 1
for node in root.getLista():
self.defineTreeNodes(node)
def joinTreeNodes(self, root):
for node in root.getLista():
dot.edge(root.getId(), node.getId())
self.joinTreeNodes(node)
def drawGraph(self):
dot.render('test-output/round-table.gv', view=True) # doctest: +SKIP
'test-output/round-table.gv.jpg'
raiz = Nodo("raiz")
update = Nodo("update")
delete = Nodo("delete")
j = 0
while j < 3 :
select = Nodo("select")
raiz.addNode(select)
j += 1
i = 0
while i < 5:
id = Nodo("ID")
select.addNode(id)
i += 1
raiz.addNode(update)
raiz.addNode(delete)
ast = AST()
#raiz = Nodo("raiz")
#nod1 = Nodo("nodo1")
#nod2 = Nodo("nodo2")
#nod11 = Nodo("nodo11")
#nod12 = Nodo("nodo12")
#nod121 = Nodo("nodo121")
#raiz.addNode(nod1)
#raiz.addNode(nod2)
#nod1.addNode(nod11)
#nod1.addNode(nod12)
#nod12.addNode(nod121)
#print("lista---------------------------")
#raiz.showList()
#nod1.showList()
#print("--------------------------------")
ast.defineTreeNodes(raiz)
ast.joinTreeNodes(raiz)
ast.drawGraph() | [
"graphviz.Digraph",
"Nodo.Nodo"
] | [((58, 80), 'graphviz.Digraph', 'Digraph', ([], {'comment': '"""AST"""'}), "(comment='AST')\n", (65, 80), False, 'from graphviz import Digraph\n'), ((830, 842), 'Nodo.Nodo', 'Nodo', (['"""raiz"""'], {}), "('raiz')\n", (834, 842), False, 'from Nodo import Nodo\n'), ((852, 866), 'Nodo.Nodo', 'Nodo', (['"""update"""'], {}), "('update')\n", (856, 866), False, 'from Nodo import Nodo\n'), ((876, 890), 'Nodo.Nodo', 'Nodo', (['"""delete"""'], {}), "('delete')\n", (880, 890), False, 'from Nodo import Nodo\n'), ((925, 939), 'Nodo.Nodo', 'Nodo', (['"""select"""'], {}), "('select')\n", (929, 939), False, 'from Nodo import Nodo\n'), ((1016, 1026), 'Nodo.Nodo', 'Nodo', (['"""ID"""'], {}), "('ID')\n", (1020, 1026), False, 'from Nodo import Nodo\n')] |
# -*- coding: utf-8 -*-
import unittest
from source.tree import bst
""" demo tree
7
/ \
5 8
/ \ \
2 6 9
"""
demo_tree = bst.BSTree(keys=[7, 5, 2, 6, 8, 9])
class BSTTest(unittest.TestCase):
"""
二叉搜索树测试
"""
def test_insert_node(self):
"""
插入结点测试
:return:
"""
new_node = bst.Node(key=3)
demo_tree.insert_node(new_node)
bst.inorder_tree_walk_recursive(demo_tree.root)
def test_tree_walk(self):
"""
中序遍历测试
:return:
"""
bst.inorder_tree_walk_recursive(demo_tree.root)
print('----------------')
bst.inorder_tree_walk_stack(demo_tree.root)
print('----------------')
bst.inorder_tree_walk_pointer(demo_tree.root)
def test_tree_search(self):
"""
搜索测试
:return:
"""
key = 8
# result = tree_search(demo_tree.root, key)
result = bst.iterative_tree_search(demo_tree.root, key)
if result:
print('result key: %s' % result.key)
else:
print('result key: %s NOT FOUND' % key)
minimum = bst.tree_minimum(demo_tree.root)
if minimum:
print('minimum: %s' % minimum.key)
else:
print('Tree is None')
maximum = bst.tree_maximum(demo_tree.root)
if maximum:
print('maximum: %s' % maximum.key)
else:
print('Tree is None')
node = demo_tree.root.left
successor = bst.tree_successor(node)
if successor:
print('Node %s\'s successor is: %s' % (node.key, successor.key))
else:
print('Tree is None')
predecessor = bst.tree_predecessor(demo_tree.root.left)
if predecessor:
print('Node %s\'s predecessor is: %s' % (node.key, predecessor.key))
else:
print('Tree is None')
def test_transplant(self):
"""
结点替换测试
:return:
"""
new_tree = bst.transplant(demo_tree, demo_tree.root.left, bst.tree_successor(demo_tree.root.left))
bst.inorder_tree_walk_recursive(new_tree.root)
def test_delete_node(self):
"""
删除结点测试
:return:
"""
demo_tree.delete_node(demo_tree.root)
bst.inorder_tree_walk_recursive(demo_tree.root)
| [
"source.tree.bst.tree_successor",
"source.tree.bst.inorder_tree_walk_stack",
"source.tree.bst.inorder_tree_walk_recursive",
"source.tree.bst.tree_maximum",
"source.tree.bst.Node",
"source.tree.bst.tree_minimum",
"source.tree.bst.tree_predecessor",
"source.tree.bst.BSTree",
"source.tree.bst.inorder_t... | [((165, 200), 'source.tree.bst.BSTree', 'bst.BSTree', ([], {'keys': '[7, 5, 2, 6, 8, 9]'}), '(keys=[7, 5, 2, 6, 8, 9])\n', (175, 200), False, 'from source.tree import bst\n'), ((373, 388), 'source.tree.bst.Node', 'bst.Node', ([], {'key': '(3)'}), '(key=3)\n', (381, 388), False, 'from source.tree import bst\n'), ((437, 484), 'source.tree.bst.inorder_tree_walk_recursive', 'bst.inorder_tree_walk_recursive', (['demo_tree.root'], {}), '(demo_tree.root)\n', (468, 484), False, 'from source.tree import bst\n'), ((580, 627), 'source.tree.bst.inorder_tree_walk_recursive', 'bst.inorder_tree_walk_recursive', (['demo_tree.root'], {}), '(demo_tree.root)\n', (611, 627), False, 'from source.tree import bst\n'), ((670, 713), 'source.tree.bst.inorder_tree_walk_stack', 'bst.inorder_tree_walk_stack', (['demo_tree.root'], {}), '(demo_tree.root)\n', (697, 713), False, 'from source.tree import bst\n'), ((756, 801), 'source.tree.bst.inorder_tree_walk_pointer', 'bst.inorder_tree_walk_pointer', (['demo_tree.root'], {}), '(demo_tree.root)\n', (785, 801), False, 'from source.tree import bst\n'), ((974, 1020), 'source.tree.bst.iterative_tree_search', 'bst.iterative_tree_search', (['demo_tree.root', 'key'], {}), '(demo_tree.root, key)\n', (999, 1020), False, 'from source.tree import bst\n'), ((1174, 1206), 'source.tree.bst.tree_minimum', 'bst.tree_minimum', (['demo_tree.root'], {}), '(demo_tree.root)\n', (1190, 1206), False, 'from source.tree import bst\n'), ((1341, 1373), 'source.tree.bst.tree_maximum', 'bst.tree_maximum', (['demo_tree.root'], {}), '(demo_tree.root)\n', (1357, 1373), False, 'from source.tree import bst\n'), ((1545, 1569), 'source.tree.bst.tree_successor', 'bst.tree_successor', (['node'], {}), '(node)\n', (1563, 1569), False, 'from source.tree import bst\n'), ((1740, 1781), 'source.tree.bst.tree_predecessor', 'bst.tree_predecessor', (['demo_tree.root.left'], {}), '(demo_tree.root.left)\n', (1760, 1781), False, 'from source.tree import bst\n'), ((2138, 2184), 'source.tree.bst.inorder_tree_walk_recursive', 'bst.inorder_tree_walk_recursive', (['new_tree.root'], {}), '(new_tree.root)\n', (2169, 2184), False, 'from source.tree import bst\n'), ((2328, 2375), 'source.tree.bst.inorder_tree_walk_recursive', 'bst.inorder_tree_walk_recursive', (['demo_tree.root'], {}), '(demo_tree.root)\n', (2359, 2375), False, 'from source.tree import bst\n'), ((2089, 2128), 'source.tree.bst.tree_successor', 'bst.tree_successor', (['demo_tree.root.left'], {}), '(demo_tree.root.left)\n', (2107, 2128), False, 'from source.tree import bst\n')] |
from datasette import hookimpl
from datasette.utils.asgi import Response
ROBOTS_TXT = """
Sitemap: https://cryptics.eigenfoo.xyz/sitemap.xml
""".strip()
SITEMAP_XML = """
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>https://cryptics.eigenfoo.xyz/data/charades</loc></url>
<url><loc>https://cryptics.eigenfoo.xyz/data/clues</loc></url>
<url><loc>https://cryptics.eigenfoo.xyz/data/indicators</loc></url>
<url><loc>https://cryptics.eigenfoo.xyz/data/metadata</loc></url>
<url><loc>https://cryptics.eigenfoo.xyz/data</loc></url>
<url><loc>https://cryptics.eigenfoo.xyz/datasheet</loc></url>
<url><loc>https://cryptics.eigenfoo.xyz</loc></url>
</urlset>
""".strip()
@hookimpl
def register_routes():
return [
("^/robots.txt$", robots_txt),
("^/sitemap.xml$", sitemap_xml),
]
def robots_txt():
return Response.text(ROBOTS_TXT)
def sitemap_xml():
return Response(SITEMAP_XML, 200, content_type="application/xml")
| [
"datasette.utils.asgi.Response",
"datasette.utils.asgi.Response.text"
] | [((909, 934), 'datasette.utils.asgi.Response.text', 'Response.text', (['ROBOTS_TXT'], {}), '(ROBOTS_TXT)\n', (922, 934), False, 'from datasette.utils.asgi import Response\n'), ((967, 1025), 'datasette.utils.asgi.Response', 'Response', (['SITEMAP_XML', '(200)'], {'content_type': '"""application/xml"""'}), "(SITEMAP_XML, 200, content_type='application/xml')\n", (975, 1025), False, 'from datasette.utils.asgi import Response\n')] |
import unittest
class TestLogoMain(unittest.TestCase):
def test_imports(self):
try:
from dreamcoder.domains.logo.main import (
animateSolutions,
dreamFromGrammar,
list_options,
outputDreams,
enumerateDreams,
visualizePrimitives,
Flatten,
LogoFeatureCNN,
main
)
except Exception:
self.fail('Unable to import logo module')
if __name__ == '__main__':
unittest.main()
| [
"unittest.main"
] | [((557, 572), 'unittest.main', 'unittest.main', ([], {}), '()\n', (570, 572), False, 'import unittest\n')] |
# Created By: <NAME>
# Created On: 2010-02-06
# Copyright 2011 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
# Interfaces for proxies in cocoalib
import logging
import objc
from ..reg import InvalidCodeError
from .objcmin import NSObject
def signature(signature):
"""Returns an objc.signature with 'i' and 'f' letters changed to correct NSInteger and
CGFloat values.
"""
signature = bytes(signature, encoding='ascii')
signature = signature.replace(b'i', objc._C_NSInteger)
signature = signature.replace(b'I', objc._C_NSUInteger)
signature = signature.replace(b'f', objc._C_CGFloat)
return objc.typedSelector(signature)
class PyGUIObject(NSObject):
def initWithCocoa_pyParent_(self, cocoa, pyparent):
super(PyGUIObject, self).init()
self.cocoa = cocoa
self.py = self.py_class(self, pyparent.py)
return self
def connect(self):
if hasattr(self.py, 'connect'):
self.py.connect()
def disconnect(self):
if hasattr(self.py, 'disconnect'):
self.py.disconnect()
def free(self):
# call this method only when you don't need to use this proxy anymore. you need to call this
# if you want to release the cocoa side (self.cocoa is holding a refcount)
# We don't delete py, it might be called after the free. It will be garbage collected anyway.
# The if is because there is something happening giving a new ref to cocoa right after
# the free, and then the ref gets to 1 again, free is called again.
self.disconnect()
if hasattr(self, 'cocoa'):
del self.cocoa
#--- Python -> Cocoa
def refresh(self):
self.cocoa.refresh()
class PyOutline(PyGUIObject):
def cancelEdits(self):
self.py.cancel_edits()
@signature('c@:@@')
def canEditProperty_atPath_(self, propname, path):
node = self.py.get_node(path)
assert node is self.py.selected_node
return getattr(node, 'can_edit_' + propname, False)
def saveEdits(self):
self.py.save_edits()
def selectedPath(self):
return self.py.selected_path
def setSelectedPath_(self, path):
self.py.selected_path = path
def selectedPaths(self):
return self.py.selected_paths
def setSelectedPaths_(self, paths):
self.py.selected_paths = paths
def property_valueAtPath_(self, property, path):
try:
return getattr(self.py.get_node(path), property)
except IndexError:
logging.warning("%r doesn't have a node at path %r", self.py, path)
return ''
def setProperty_value_atPath_(self, property, value, path):
setattr(self.py.get_node(path), property, value)
#--- Python -> Cocoa
def start_editing(self):
self.cocoa.startEditing()
def stop_editing(self):
self.cocoa.stopEditing()
def update_selection(self):
self.cocoa.updateSelection()
class PyTable(PyGUIObject):
#--- Helpers
def _getrow(self, row):
try:
return self.py[row]
except IndexError:
msg = "Trying to get an out of bounds row ({} / {}) on table {}"
logging.warning(msg.format(row, len(self.py), self.py.__class__.__name__))
#--- Cocoa --> Python
def add(self):
self.py.add()
def cancelEdits(self):
self.py.cancel_edits()
@signature('c@:@i')
def canEditColumn_atRow_(self, column, row):
return self.py.can_edit_cell(column, row)
def deleteSelectedRows(self):
self.py.delete()
@signature('i@:')
def numberOfRows(self):
return len(self.py)
def saveEdits(self):
self.py.save_edits()
def selectRows_(self, rows):
self.py.select(list(rows))
def selectedRows(self):
return self.py.selected_indexes
def selectionAsCSV(self):
return self.py.selection_as_csv()
@signature('v@:@@i')
def setValue_forColumn_row_(self, value, column, row):
# this try except is important for the case while a row is in edition mode and the delete
# button is clicked.
try:
self._getrow(row).set_cell_value(column, value)
except AttributeError:
msg = "Trying to set an attribute that can't: {} with value {} at row {} on table {}"
logging.warning(msg.format(column, value, row, self.py.__class__.__name__))
raise
@signature('v@:@c')
def sortByColumn_desc_(self, column, desc):
self.py.sort_by(column, desc=desc)
@signature('@@:@i')
def valueForColumn_row_(self, column, row):
return self._getrow(row).get_cell_value(column)
#--- Python -> Cocoa
def show_selected_row(self):
self.cocoa.showSelectedRow()
def start_editing(self):
self.cocoa.startEditing()
def stop_editing(self):
self.cocoa.stopEditing()
def update_selection(self):
self.cocoa.updateSelection()
class PyFairware(NSObject):
def appName(self):
return ""
@signature('c@:')
def isRegistered(self):
return self.py.registered
@signature('c@:')
def isFirstRun(self):
return self.py.is_first_run
def isCodeValid_withEmail_(self, code, email):
try:
self.py.validate_code(code, email)
return None
except InvalidCodeError as e:
return str(e)
@signature('v@:@@c')
def setRegisteredCode_andEmail_registerOS_(self, code, email, registerOS):
self.py.set_registration(code, email, registerOS)
def unpaidHours(self):
return self.py.unpaid_hours
| [
"logging.warning",
"objc.typedSelector"
] | [((845, 874), 'objc.typedSelector', 'objc.typedSelector', (['signature'], {}), '(signature)\n', (863, 874), False, 'import objc\n'), ((2813, 2880), 'logging.warning', 'logging.warning', (['"""%r doesn\'t have a node at path %r"""', 'self.py', 'path'], {}), '("%r doesn\'t have a node at path %r", self.py, path)\n', (2828, 2880), False, 'import logging\n')] |
import shutil
import subprocess # nosec # have to use subprocess
import warnings
from collections import Counter
from copy import deepcopy
from os import listdir, makedirs
from os.path import abspath, basename, dirname, exists, isfile, join
from subprocess import PIPE # nosec # have to use subprocess
from tempfile import mkdtemp
import f90nml
import numpy as np
import pandas as pd
from dateutil.relativedelta import relativedelta
from openscm_units import unit_registry
from scmdata import run_append
from .config import _wine_installed, config
from .errors import InvalidTemporalResError, NoReaderWriterError
from .io import MAGICCData, read_cfg_file
from .io.utils import _get_openscm_var_from_filepath
from .scenarios import zero_emissions
from .utils import get_date_time_string
IS_WINDOWS = config["is_windows"]
class WineNotInstalledError(Exception):
"""Exception raised if wine is not installed but is required"""
def _copy_files(source, target, recursive=False):
"""
Copy all the files in source directory to target.
If ``recursive``, include subdirectories, otherwise ignores subdirectories.
"""
if recursive:
shutil.copytree(source, target)
return
source_files = listdir(source)
if not exists(target):
makedirs(target)
for filename in source_files:
full_filename = join(source, filename)
if isfile(full_filename):
shutil.copy(full_filename, target)
def _clean_value(v):
if isinstance(v, str):
return v.strip()
elif isinstance(v, list):
if isinstance(v[0], str):
return [i.replace("\0", "").strip().replace("\n", "") for i in v]
return v
class MAGICCBase(object):
"""
Provides access to the MAGICC binary and configuration.
To enable multiple MAGICC 'setups' to be configured independently,
the MAGICC directory containing the input files, configuration
and binary is copied to a new folder. The configuration in this
MAGICC copy can then be edited without impacting other instances or your
original MAGICC distribution.
A ``MAGICC`` instance first has to be setup by calling
``create_copy``. If many model runs are being performed this step only has
to be performed once. The ``run`` method can then be called many times
without re-copying the files each time. Between each call to ``run``, the
configuration files can be updated to perform runs with different
configurations.
Parameters
----------
root_dir : str
If ``root_dir`` is supplied, an existing MAGICC 'setup' is
used.
"""
version = None
_scen_file_name = "SCENARIO.SCEN7"
def __init__(self, root_dir=None, strict=True):
"""
Initialise
Parameters
----------
root_dir : str
Root directory of the MAGICC package. If ``None``, a temporary
copy of MAGICC is made based on the result of `
`self.get_exectuable()``.
strict: bool
If True, enforce the configuration checks, otherwise a warning
is raised if any invalid configuration is found and the run is
continued. Setting ``strict=False`` is only recommended for
experienced users of MAGICC.
"""
self.root_dir = root_dir
self.config = None
self.executable = self.get_executable()
self.strict = strict
if root_dir is not None:
self.is_temp = False
else:
# Create a temp directory
self.is_temp = True
def __enter__(self):
if self.is_temp and self.run_dir is None:
self.create_copy()
return self
def __exit__(self, *args, **kwargs):
self.remove_temp_copy()
def create_copy(self):
"""
Initialises a temporary directory structure and copy of MAGICC
configuration files and binary.
The root folder and ``bin`` folders are copied (not recursively). The
``run`` folder is copied recursively.
"""
if self.executable is None or not isfile(self.executable):
raise FileNotFoundError(
"Could not find MAGICC{} executable: {}".format(
self.version, self.executable
)
)
if self.is_temp:
if self.root_dir is not None:
raise AssertionError(
"A temp copy for this instance has already been created"
)
self.root_dir = mkdtemp(prefix="pymagicc-")
if exists(self.run_dir):
raise Exception("A copy of MAGICC has already been created.")
if not exists(self.root_dir):
makedirs(self.root_dir)
exec_dir = basename(self.original_dir)
# Copy a subset of folders from the MAGICC `original_dir`
# Also copy anything which is in the root of the MAGICC distribution
# Assumes that the MAGICC binary is in a folder one level below the root
# of the MAGICC distribution. i.e. /run/magicc.exe or /bin/magicc
dirs_to_copy = [".", "bin"]
dirs_to_copy_recursive = ["run"]
# Check that the executable is in a valid sub directory
if exec_dir not in dirs_to_copy + dirs_to_copy_recursive:
raise AssertionError("binary must be in bin/ or run/ directory")
for d in dirs_to_copy + dirs_to_copy_recursive:
source_dir = abspath(join(self.original_dir, "..", d))
if exists(source_dir):
_copy_files(
source_dir,
join(self.root_dir, d),
recursive=d in dirs_to_copy_recursive,
)
# Create an empty out dir
# MAGICC assumes that the 'out' directory already exists
makedirs(join(self.root_dir, "out"))
# Create basic configuration files so magicc can run
self.set_years()
self.set_config()
@property
def binary_name(self):
"""
Name of the MAGICC binary file
Returns
-------
str
Name of the binary file
"""
return basename(self.executable)
@property
def original_dir(self):
"""
Directory of the MAGICC package.
This is the directory which contains the ``run`` and ``out`` folders.
Returns
-------
str
Path of the MAGICC package
"""
return dirname(self.executable)
@property
def run_dir(self):
"""
Run directory of the MAGICC package.
This path always ends in ``run``.
Returns
-------
str
Path of the run directory
"""
if self.root_dir is None:
return None
return join(self.root_dir, "run")
@property
def out_dir(self):
"""
Output directory of the MAGICC package.
This path always ends in ``out``.
Returns
-------
str
Path of the output directory
"""
if self.root_dir is None:
return None
return join(self.root_dir, "out")
@property
def default_config(self):
"""
Default configuration for a run
Returns
-------
:obj:`f90nml.Namelist`
Namelist object containing the default configuration
"""
base = f90nml.read(join(self.run_dir, "MAGCFG_DEFAULTALL.CFG"))
user = f90nml.read(join(self.run_dir, "MAGCFG_USER.CFG"))
self._default_config = deepcopy(base)
def _deep_update(b, o):
for k, v in o.items():
if isinstance(v, dict):
_deep_update(b[k], v)
else:
b.update(o)
_deep_update(self._default_config, user)
return self._default_config
def run(self, scenario=None, only=None, debug=False, **kwargs):
"""
Run MAGICC and parse the output.
As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its
parameters into ``out/PARAMETERS.OUT`` and they will then be read into
``output.metadata["parameters"]`` where ``output`` is the returned object.
Any logged output from running magicc will be in``output.metadata["stderr"]``.
For MAGICC7 and above, The level of logging can be controlled with the
``debug`` argument.
Any subannual files output by MAGICC will be ignored by this function. These
files can be read in manually using :class:`pymagicc.io.MAGICCData` directly.
Parameters
----------
scenario : :obj:`pymagicc.io.MAGICCData`
Scenario to run. If None MAGICC will simply run with whatever config has
already been set.
only : list of str
If not None, only extract variables in this list.
debug: {True, False, "verbose"}
If true, MAGICC will run in debug mode with the maximum amount of logging.
If "verbose", MAGICC will be run in verbose mode.
kwargs
Other config values to pass to MAGICC for the run
Returns
-------
:obj:`pymagicc.io.MAGICCData`
MAGICCData object containing that data in its ``df`` attribute and
metadata and parameters (depending on the value of ``include_parameters``)
in its ``metadata`` attribute.
Raises
------
ValueError
If no output is found which matches the list specified in ``only``.
subprocess.CalledProcessError
If MAGICC fails to run. Check the 'stderr' key of the result's `metadata`
attribute to inspect the results output from MAGICC.
ValueError
The user attempts to use ``debug`` with MAGICC6
"""
if not exists(self.root_dir):
raise FileNotFoundError(self.root_dir)
if self.executable is None:
raise ValueError(
"MAGICC executable not found, try setting an environment variable `MAGICC_EXECUTABLE_{}=/path/to/binary`".format(
self.version
)
)
if scenario is not None:
kwargs = self.set_emission_scenario_setup(scenario, kwargs)
yr_config = {}
if "startyear" in kwargs:
yr_config["startyear"] = kwargs.pop("startyear")
if "endyear" in kwargs:
yr_config["endyear"] = kwargs.pop("endyear")
if yr_config:
self.set_years(**yr_config)
# should be able to do some other nice metadata stuff re how magicc was run
# etc. here
kwargs.setdefault("rundate", get_date_time_string())
self.update_config(**kwargs)
self.check_config()
exec_dir = basename(self.original_dir)
command = [join(self.root_dir, exec_dir, self.binary_name)]
if self.version >= 7:
if debug == "verbose":
command.append("--verbose")
elif debug:
command.append("--debug")
elif debug:
raise ValueError("MAGICC6 has no debug capability")
if not IS_WINDOWS and self.binary_name.endswith(".exe"): # pragma: no cover
if not _wine_installed:
raise WineNotInstalledError(
"Wine is not installed but is required to run `.exe` binaries"
)
command.insert(0, "wine")
try:
res = subprocess.run( # nosec # on Windows shell=True is required
command,
check=True,
# thank you https://stackoverflow.com/a/53209196 for Python 3.6 hack
stdout=PIPE,
stderr=PIPE,
cwd=self.run_dir,
shell=IS_WINDOWS,
)
except subprocess.CalledProcessError as exc:
print("stderr:\n{}".format(exc.stderr.decode()))
raise exc
outfiles = self._get_output_filenames()
read_cols = {"climate_model": ["MAGICC{}".format(self.version)]}
if scenario is not None:
read_cols["model"] = scenario["model"].unique().tolist()
read_cols["scenario"] = scenario["scenario"].unique().tolist()
else:
read_cols.setdefault("model", ["unspecified"])
read_cols.setdefault("scenario", ["unspecified"])
mdata = []
for filepath in outfiles:
if filepath.startswith("DAT_VOLCANIC_RF.") or "SUBANN" in filepath:
warnings.warn(
"Not reading file: {}. Monthly data are not read in automatically by `run`. "
"Use `MAGICCData` instead.".format(filepath)
)
continue
try:
openscm_var = _get_openscm_var_from_filepath(filepath)
if only is None or openscm_var in only:
tempdata = MAGICCData(
join(self.out_dir, filepath), columns=deepcopy(read_cols)
)
mdata.append(tempdata)
except (NoReaderWriterError, InvalidTemporalResError):
# TODO: something like warnings.warn("Could not read {}".format(filepath))
continue
if not mdata and only is not None:
raise ValueError("No output found for only={}".format(only))
if not mdata:
if self.strict:
raise ValueError("No output found. Check configuration")
else:
# No data was loaded return an empty MAGICCData object
mdata = MAGICCData(
data={},
columns={
"model": [],
"unit": [],
"variable": [],
"region": [],
"scenario": [],
},
)
else:
mdata = run_append(mdata)
try:
run_paras = self.read_parameters()
self.config = run_paras
mdata.metadata["parameters"] = run_paras
except FileNotFoundError:
pass
mdata.metadata["stderr"] = res.stderr.decode("ascii")
levels_to_warn = ["WARNING", "ERROR", "FATAL"]
for level in levels_to_warn:
if "<{}>".format(level) in mdata.metadata["stderr"]:
warnings.warn(
"magicc logged a {} message. Check the 'stderr' key of the "
"result's `metadata` attribute.".format(level)
)
return mdata
def _get_output_filenames(self):
outfiles = [f for f in listdir(self.out_dir) if f != "PARAMETERS.OUT"]
bin_out = [
f.split(".")[0]
for f in outfiles
if f.startswith("DAT_") and f.endswith(".BINOUT")
]
extras = []
for f in outfiles:
var_name, ext = f.split(".")
if ext != "BINOUT" and var_name not in bin_out:
extras.append(f)
return [f + ".BINOUT" for f in bin_out] + extras
def _check_failed(self, msg):
if self.strict:
raise ValueError(msg)
else:
warnings.warn(msg)
def check_config(self):
"""Check that our MAGICC ``.CFG`` files are set to safely work with PYMAGICC
For further detail about why this is required, please see :ref:`MAGICC flags`.
Raises
------
ValueError
If we are not certain that the config written by PYMAGICC will overwrite
all other config i.e. that there will be no unexpected behaviour. A
ValueError will also be raised if the user tries to use more than one
scenario file.
"""
cfg_error_msg = (
"PYMAGICC is not the only tuning model that will be used by "
"`MAGCFG_USER.CFG`: your run is likely to fail/do odd things"
)
emisscen_error_msg = (
"You have more than one `FILE_EMISSCEN_X` flag set. Using more than "
"one emissions scenario is hard to debug and unnecessary with "
"Pymagicc's Dataframe scenario input. Please combine all your "
"scenarios into one Dataframe with Pymagicc and Pandas, then feed "
"this single Dataframe into Pymagicc's run API."
)
nml_to_check = "nml_allcfgs"
usr_cfg = read_cfg_file(join(self.run_dir, "MAGCFG_USER.CFG"))
for k in usr_cfg[nml_to_check]:
if k.startswith("file_tuningmodel"):
first_tuningmodel = k in ["file_tuningmodel", "file_tuningmodel_1"]
if first_tuningmodel:
if usr_cfg[nml_to_check][k] != "PYMAGICC":
self._check_failed(cfg_error_msg)
elif usr_cfg[nml_to_check][k] not in ["USER", ""]:
self._check_failed(cfg_error_msg)
elif k.startswith("file_emisscen_"):
if usr_cfg[nml_to_check][k] not in ["NONE", ""]:
self._check_failed(emisscen_error_msg)
self._check_config()
def write(self, mdata, name):
"""Write an input file to disk
Parameters
----------
mdata : :obj:`pymagicc.io.MAGICCData`
A MAGICCData instance with the data to write
name : str
The name of the file to write. The file will be written to the MAGICC
instance's run directory i.e. ``self.run_dir``
"""
mdata.write(join(self.run_dir, name), self.version)
def read_parameters(self):
"""
Read a parameters.out file
Returns
-------
dict
A dictionary containing all the configuration used by MAGICC
"""
param_fname = join(self.out_dir, "PARAMETERS.OUT")
if not exists(param_fname):
raise FileNotFoundError("No PARAMETERS.OUT found")
with open(param_fname) as nml_file:
parameters = dict(f90nml.read(nml_file))
for group in ["nml_years", "nml_allcfgs", "nml_outputcfgs"]:
parameters[group] = dict(parameters[group])
for k, v in parameters[group].items():
parameters[group][k] = _clean_value(v)
parameters[group.replace("nml_", "")] = parameters.pop(group)
self.config = parameters
return parameters
def remove_temp_copy(self):
"""
Removes a temporary copy of the MAGICC version shipped with Pymagicc.
"""
if self.is_temp and self.root_dir is not None:
shutil.rmtree(self.root_dir)
self.root_dir = None
def set_config(
self,
filename="MAGTUNE_PYMAGICC.CFG",
top_level_key="<KEY>",
conflict="warn",
**kwargs,
):
"""
Create a configuration file for MAGICC.
Writes a fortran namelist in run_dir.
Parameters
----------
filename : str
Name of configuration file to write
top_level_key : str
Name of namelist to be written in the
configuration file
conflict : {'warn', 'ignore'}
If 'warn', when a flag needs to be replaced by a different name (because,
for example, the flag name changed between MAGICC versions), a warning is
raised. If 'ignore', no warning is raised when a replacement is required.
kwargs
Other parameters to pass to the configuration file. No
validation on the parameters is performed.
Returns
-------
dict
The contents of the namelist which was written to file
Warning
-------
If a key is renamed, a warning is raised
Raises
------
ValueError
An invalid value for ``conflict`` is supplied
"""
kwargs = self._check_and_format_config(kwargs)
fname = join(self.run_dir, filename)
conf = {top_level_key: kwargs}
conf = self._fix_legacy_keys(conf, conflict=conflict)
f90nml.write(conf, fname, force=True)
return conf
def update_config(
self,
filename="MAGTUNE_PYMAGICC.CFG",
top_level_key="<KEY>",
conflict="warn",
**kwargs,
):
"""Updates a configuration file for MAGICC
Updates the contents of a fortran namelist in the run directory,
creating a new namelist if none exists.
Parameters
----------
filename : str
Name of configuration file to write
top_level_key : str
Name of namelist to be written in the
configuration file
conflict : {'warn', 'ignore'}
If 'warn', when a flag needs to be replaced by a different name (because,
for example, the flag name changed between MAGICC versions), a warning is
raised. If 'ignore', no warning is raised when a replacement is required.
kwargs
Other parameters to pass to the configuration file. No
validation on the parameters is performed.
Returns
-------
dict
The contents of the namelist which was written to file
Warning
-------
If a key is renamed, a warning is raised
Raises
------
ValueError
An invalid value for ``conflict`` is supplied
"""
kwargs = self._check_and_format_config(kwargs)
fname = join(self.run_dir, filename)
if exists(fname):
conf = f90nml.read(fname)
else:
conf = {top_level_key: {}}
conf[top_level_key].update(kwargs)
conf = self._fix_legacy_keys(conf, conflict=conflict)
f90nml.write(conf, fname, force=True)
return conf
def _fix_legacy_keys(self, conf, conflict="warn"):
"""
Go through config and fix any keys which are misnamed.
For example, fix any keys which have been renamed between MAGICC versions to
match the new names.
Parameters
----------
conf :obj:`f90nml.Namelist`
Configuration to check
conflict : {'warn', 'ignore'}
If 'warn', when a conflict is found, a warning is raised. If 'ignore', no
warning is raised when a conflict is found.
Returns
-------
:obj:`f90nml.Namelist`
Configuration with updated keys
Warning
-------
If a key is renamed, a warning is raised
Raises
------
ValueError
An invalid value for ``conflict`` is supplied
"""
valid_conflicts = ["warn", "ignore"]
if conflict not in valid_conflicts:
raise ValueError("`conflict` must be one of: {}".format(valid_conflicts))
cfg_key = "<KEY>"
if cfg_key not in conf:
return conf
new_conf = deepcopy(conf)
for wrong_key, right_key in self._config_renamings.items():
if wrong_key in new_conf[cfg_key]:
new_conf[cfg_key][right_key] = new_conf[cfg_key].pop(wrong_key)
if conflict == "warn":
warnings.warn(
"Altering config flag {} to {}".format(wrong_key, right_key)
)
return new_conf
def set_zero_config(self):
"""Set config such that radiative forcing and temperature output will be zero
This method is intended as a convenience only, it does not handle everything in
an obvious way. Adjusting the parameter settings still requires great care and
may behave unepexctedly.
"""
# zero_emissions is imported from scenarios module
# TODO: setup MAGICC6 so it puts extra variables in right place and hence
# warning about ignoring some data disappears
zero_emissions.write(join(self.run_dir, self._scen_file_name), self.version)
time = zero_emissions.filter(variable="Emissions|CH4", region="World")[
"time"
].values
no_timesteps = len(time)
# value doesn't actually matter as calculations are done from difference but
# chose sensible value nonetheless
co2_conc_pi = 722
co2_conc = co2_conc_pi * np.ones(no_timesteps)
co2_conc_df = pd.DataFrame(
{
"time": time,
"scenario": "idealised",
"model": "unspecified",
"climate_model": "unspecified",
"variable": "Atmospheric Concentrations|CO2",
"unit": "ppm",
"todo": "SET",
"region": "World",
"value": co2_conc,
}
)
co2_conc_writer = MAGICCData(co2_conc_df)
co2_conc_filename = "HIST_CONSTANT_CO2_CONC.IN"
co2_conc_writer.metadata = {
"header": "Constant pre-industrial CO2 concentrations"
}
co2_conc_writer.write(join(self.run_dir, co2_conc_filename), self.version)
ch4_conc_pi = 722
ch4_conc = ch4_conc_pi * np.ones(no_timesteps)
ch4_conc_df = pd.DataFrame(
{
"time": time,
"scenario": "idealised",
"model": "unspecified",
"climate_model": "unspecified",
"variable": "Atmospheric Concentrations|CH4",
"unit": "ppb",
"todo": "SET",
"region": "World",
"value": ch4_conc,
}
)
ch4_conc_writer = MAGICCData(ch4_conc_df)
ch4_conc_filename = "HIST_CONSTANT_CH4_CONC.IN"
ch4_conc_writer.metadata = {
"header": "Constant pre-industrial CH4 concentrations"
}
ch4_conc_writer.write(join(self.run_dir, ch4_conc_filename), self.version)
fgas_conc_pi = 0
fgas_conc = fgas_conc_pi * np.ones(no_timesteps)
varname = "FGAS_CONC"
fgas_conc_df = pd.DataFrame(
{
"time": time,
"scenario": "idealised",
"model": "unspecified",
"climate_model": "unspecified",
"variable": varname,
"unit": "ppt",
"todo": "SET",
"region": "World",
"value": fgas_conc,
}
)
fgas_conc_writer = MAGICCData(fgas_conc_df)
fgas_conc_filename = "HIST_ZERO_{}.IN".format(varname)
fgas_conc_writer.metadata = {"header": "Zero concentrations"}
fgas_conc_writer.write(join(self.run_dir, fgas_conc_filename), self.version)
def_config = self.default_config
tmp_nml = f90nml.Namelist({"nml_allcfgs": {"fgas_files_conc": 1}})
fgas_files_conc_flag = list(
self._fix_legacy_keys(tmp_nml, conflict="ignore")["nml_allcfgs"].keys()
)[0]
fgas_conc_files = [fgas_conc_filename] * len(
def_config["nml_allcfgs"][fgas_files_conc_flag]
)
self.set_config(
conflict="ignore",
file_emisscen=self._scen_file_name,
rf_initialization_method="ZEROSTARTSHIFT",
rf_total_constantafteryr=10000,
file_co2i_emis="",
file_co2b_emis="",
file_co2_conc=co2_conc_filename,
co2_switchfromconc2emis_year=10000,
file_ch4i_emis="",
file_ch4b_emis="",
file_ch4n_emis="",
file_ch4_conc=ch4_conc_filename,
ch4_switchfromconc2emis_year=10000,
file_n2oi_emis="",
file_n2ob_emis="",
file_n2on_emis="",
file_n2o_conc="",
n2o_switchfromconc2emis_year=1750,
file_noxi_emis="",
file_noxb_emis="",
file_noxi_ot="",
file_noxb_ot="",
file_noxt_rf="",
file_soxnb_ot="",
file_soxi_ot="",
file_soxt_rf="",
file_soxi_emis="",
file_soxb_emis="",
file_soxn_emis="",
file_oci_emis="",
file_ocb_emis="",
file_oci_ot="",
file_ocb_ot="",
file_oci_rf="",
file_ocb_rf="",
file_bci_emis="",
file_bcb_emis="",
file_bci_ot="",
file_bcb_ot="",
file_bci_rf="",
file_bcb_rf="",
bcoc_switchfromrf2emis_year=1750,
file_nh3i_emis="",
file_nh3b_emis="",
file_nmvoci_emis="",
file_nmvocb_emis="",
file_coi_emis="",
file_cob_emis="",
file_mineraldust_rf="",
file_landuse_rf="",
file_bcsnow_rf="",
# rf_fgassum_scale=0, # this appears to do nothing, hence the next two lines
fgas_switchfromconc2emis_year=10000,
rf_mhalosum_scale=0,
stratoz_o3scale=0,
rf_volcanic_scale=0,
rf_solar_scale=0,
mhalo_switchfromconc2emis_year=1750,
fgas_files_conc=fgas_conc_files,
)
def _check_and_format_config(self, config_dict):
self._check_for_duplicate_keys(config_dict)
config_dict = self._convert_out_config_flags_to_integers(config_dict)
return config_dict
@staticmethod
def _check_for_duplicate_keys(config_dict):
keys_lower = [v.lower() for v in config_dict.keys()]
counts = Counter(keys_lower)
if any([v > 1 for v in counts.values()]):
duplicate_keys = [
[ck for ck in config_dict.keys() if ck.lower() == k.lower()]
for k, v in counts.items()
if v > 1
]
error_msg = (
"The following configuration keys clash because configs are "
"case insensitive: {}".format(
", ".join([str(v) for v in duplicate_keys])
)
)
raise ValueError(error_msg)
@staticmethod
def _convert_out_config_flags_to_integers(config_dict):
valid_out_flags = [
"out_emissions",
"out_gwpemissions",
"out_sum_gwpemissions",
"out_concentrations",
"out_carboncycle",
"out_forcing",
"out_forcing_subannual",
"out_temperature",
"out_temperature_subannual",
"out_sealevel",
"out_parameters",
"out_misc",
"out_lifetimes",
"out_timeseriesmix",
"out_rcpdata",
"out_summaryidx",
"out_tempoceanlayers",
"out_oceanarea",
"out_heatuptake",
"out_warnings",
"out_precipinput",
"out_aogcmtuning",
"out_ccycletuning",
"out_observationaltuning",
"out_keydata_1",
"out_keydata_2",
"out_inverseemis",
"out_surfaceforcing",
"out_permafrost",
"out_allowanydynamicvars",
]
for key in valid_out_flags:
if key in config_dict:
# MAGICC expects 1 and 0 instead of True/False
config_dict[key] = 1 if config_dict[key] else 0
return config_dict
def set_years(self, startyear=1765, endyear=2100):
"""
Set the start and end dates of the simulations.
Parameters
----------
startyear : int
Start year of the simulation
endyear : int
End year of the simulation
Returns
-------
dict
The contents of the namelist
"""
# TODO: test altering stepsperyear, I think 1, 2 and 24 should all work
return self.set_config(
"MAGCFG_NMLYEARS.CFG",
"nml_years",
endyear=endyear,
startyear=startyear,
stepsperyear=12,
)
def set_output_variables(self, write_ascii=True, write_binary=False, **kwargs):
"""Set the output configuration, minimising output as much as possible
There are a number of configuration parameters which control which variables
are written to file and in which format. Limiting the variables that are
written to file can greatly speed up the running of MAGICC. By default,
calling this function without specifying any variables will disable all output
by setting all of MAGICC's ``out_xx`` flags to ``0``.
This convenience function should not be confused with ``set_config`` or
``update_config`` which allow the user to set/update the configuration flags
directly, without the more convenient syntax and default behaviour provided by
this function.
Parameters
----------
write_ascii : bool
If true, MAGICC is configured to write output files as human readable ascii files.
write_binary : bool
If true, MAGICC is configured to write binary output files. These files are much faster
to process and write, but are not human readable.
**kwargs:
List of variables to write out. A list of possible options are as follows. This
may not be a complete list.
'emissions',
'gwpemissions',
'sum_gwpemissions',
'concentrations',
'carboncycle',
'forcing',
'surfaceforcing',
'permafrost',
'temperature',
'sealevel',
'parameters',
'misc',
'lifetimes',
'timeseriesmix',
'rcpdata',
'summaryidx',
'inverseemis',
'tempoceanlayers',
'oceanarea',
'heatuptake',
'warnings',
'precipinput',
'aogcmtuning',
'ccycletuning',
'observationaltuning',
'keydata_1',
'keydata_2'
"""
if not (write_ascii or write_binary):
raise AssertionError("write_binary and/or write_ascii must be configured")
if write_binary and write_ascii:
ascii_binary = "BOTH"
elif write_ascii:
ascii_binary = "ASCII"
else:
ascii_binary = "BINARY"
# defaults
outconfig = {
"out_emissions": 0,
"out_gwpemissions": 0,
"out_sum_gwpemissions": 0,
"out_concentrations": 0,
"out_carboncycle": 0,
"out_forcing": 0,
"out_surfaceforcing": 0,
"out_permafrost": 0,
"out_temperature": 0,
"out_sealevel": 0,
"out_parameters": 0,
"out_misc": 0,
"out_timeseriesmix": 0,
"out_rcpdata": 0,
"out_summaryidx": 0,
"out_inverseemis": 0,
"out_tempoceanlayers": 0,
"out_heatuptake": 0,
"out_ascii_binary": ascii_binary,
"out_warnings": 0,
"out_precipinput": 0,
"out_aogcmtuning": 0,
"out_ccycletuning": 0,
"out_observationaltuning": 0,
"out_keydata_1": 0,
"out_keydata_2": 0,
}
if self.version == 7:
outconfig["out_oceanarea"] = 0
outconfig["out_lifetimes"] = 0
for kw in kwargs:
val = 1 if kwargs[kw] else 0 # convert values to 0/1 instead of booleans
outconfig["out_" + kw.lower()] = val
self.update_config(**outconfig)
def get_executable(self):
"""
Get path to MAGICC executable being used
Returns
-------
str
Path to MAGICC executable being used
"""
return config["executable_{}".format(self.version)]
def diagnose_tcr_ecs_tcre(self, **kwargs):
"""
Diagnose TCR, ECS and TCRE
The transient climate response (TCR), is the global-mean temperature response
per unit cumulative |CO2| emissions at the time at which atmospheric |CO2|
concentrations double in an experiment where atmospheric |CO2| concentrations
are increased at 1% per year from pre-industrial levels (1pctCO2 experiment).
The equilibrium climate sensitivity (ECS), is the equilibrium global-mean
temperature response to an instantaneous doubling of atmospheric |CO2|
concentrations (abrupt-2xCO2 experiment).
The transient climate response to emissions (TCRE), is the global-mean
temperature response per unit cumulative |CO2| emissions at the time at which
atmospheric |CO2| concentrations double in the 1pctCO2 experiment.
Please note that sometimes the run length won't be long enough to allow
MAGICC's oceans to fully equilibrate and hence the ECS value might not be what
you expect (it should match the value of ``core_climatesensitivity``).
Parameters
----------
**kwargs
parameter values to use in the diagnosis e.g. ``core_climatesensitivity=4``
Returns
-------
dict
Dictionary with keys: "ecs" - the diagnosed ECS; "tcr" - the diagnosed
TCR; "tcre" - the diagnosed TCRE; "timeseries" - the relevant model input
and output timeseries used in the experiment i.e. atmospheric |CO2|
concentrations, inverse |CO2| emissions, total radiative forcing and
global-mean surface temperature
"""
ecs_res = self.diagnose_ecs(**kwargs)
tcr_tcre_res = self.diagnose_tcr_tcre(**kwargs)
out = {**ecs_res, **tcr_tcre_res}
out["timeseries"] = run_append(
[ecs_res["timeseries"], tcr_tcre_res["timeseries"]]
)
return out
def diagnose_ecs(self, **kwargs):
"""
Diagnose ECS
The equilibrium climate sensitivity (ECS), is the equilibrium global-mean
temperature response to an instantaneous doubling of atmospheric |CO2|
concentrations (abrupt-2xCO2 experiment).
Please note that sometimes the run length won't be long enough to allow
MAGICC's oceans to fully equilibrate and hence the ECS value might not be what
you expect (it should match the value of ``core_climatesensitivity``).
Parameters
----------
**kwargs
parameter values to use in the diagnosis e.g. ``core_climatesensitivity=4``
Returns
-------
dict
Dictionary with keys: "ecs" - the diagnosed ECS; "timeseries" - the
relevant model input and output timeseries used in the experiment i.e.
atmospheric |CO2| concentrations, inverse |CO2| emissions, total radiative
forcing and global-mean surface temperature
"""
self._diagnose_ecs_config_setup(**kwargs)
timeseries = self.run(
scenario=None,
only=[
"Atmospheric Concentrations|CO2",
"Radiative Forcing",
"Surface Temperature",
],
)
timeseries["scenario"] = "abrupt-2xCO2"
ecs = self.get_ecs_from_diagnosis_results(timeseries)
return {"ecs": ecs, "timeseries": timeseries}
def diagnose_tcr_tcre(self, **kwargs):
"""
Diagnose TCR and TCRE
The transient climate response (TCR), is the global-mean temperature response
per unit cumulative |CO2| emissions at the time at which atmospheric |CO2|
concentrations double in an experiment where atmospheric |CO2| concentrations
are increased at 1% per year from pre-industrial levels (1pctCO2 experiment).
The transient climate response to emissions (TCRE), is the global-mean
temperature response per unit cumulative |CO2| emissions at the time at which
atmospheric |CO2| concentrations double in the 1pctCO2 experiment.
Parameters
----------
**kwargs
parameter values to use in the diagnosis e.g. ``core_climatesensitivity=4``
Returns
-------
dict
Dictionary with keys: "tcr" - the diagnosed TCR; "tcre" - the diagnosed
TCRE; "timeseries" - the relevant model input and output timeseries used
in the experiment i.e. atmospheric |CO2| concentrations, inverse |CO2|
emissions, total radiative forcing and global-mean surface temperature
"""
self._diagnose_tcr_tcre_config_setup(**kwargs)
timeseries = self.run(
scenario=None,
only=[
"Atmospheric Concentrations|CO2",
"INVERSEEMIS",
"Radiative Forcing",
"Surface Temperature",
],
)
# drop all the irrelevant inverse emissions
timeseries = timeseries.filter(
variable="Inverse Emissions*", level=1, keep=False
)
# drop the final year as concs stay constant from some reason,
# MAGICC bug...
timeseries = timeseries.filter(time=timeseries["time"].max(), keep=False)
timeseries["scenario"] = "1pctCO2"
tcr, tcre = self.get_tcr_tcre_from_diagnosis_results(timeseries)
return {"tcr": tcr, "tcre": tcre, "timeseries": timeseries}
def _diagnose_ecs_config_setup(self, **kwargs):
self.set_years(
startyear=1750, endyear=4200
) # 4200 seems to be the max I can push too without an error
self.update_config(
FILE_CO2_CONC="ABRUPT2XCO2_CO2_CONC.IN",
CO2_SWITCHFROMCONC2EMIS_YEAR=30000,
RF_TOTAL_RUNMODUS="CO2",
RF_TOTAL_CONSTANTAFTERYR=2000,
**kwargs,
)
def _diagnose_tcr_tcre_config_setup(self, **kwargs):
self.set_years(startyear=1750, endyear=2020)
self.update_config(
FILE_CO2_CONC="1PCTCO2_CO2_CONC.IN",
CO2_SWITCHFROMCONC2EMIS_YEAR=30000,
RF_TOTAL_RUNMODUS="CO2",
RF_TOTAL_CONSTANTAFTERYR=3000,
OUT_INVERSEEMIS=1,
**kwargs,
)
def get_ecs_from_diagnosis_results(self, results_ecs_run):
"""
Diagnose ECS from the results of the abrupt-2xCO2 experiment
Parameters
----------
results_ecs_run : :obj:`ScmRun`
Results of the abrupt-2xCO2 experiment, must contain atmospheric |CO2|
concentrations, total radiative forcing and surface temperature.
Returns
-------
ecs : :obj:`pint.quantity.Quantity`
ECS diagnosed from ``results_ecs_run``
"""
global_co2_concs = results_ecs_run.filter(
variable="Atmospheric Concentrations|CO2", region="World"
)
ecs_time, ecs_start_time = self._get_ecs_ecs_start_yr_from_CO2_concs(
global_co2_concs
)
global_total_rf = results_ecs_run.filter(
variable="Radiative Forcing", region="World"
)
self._check_ecs_total_RF(global_total_rf, jump_time=ecs_start_time)
global_temp = results_ecs_run.filter(
variable="Surface Temperature", region="World"
)
self._check_ecs_temp(global_temp)
ecs = float(global_temp.filter(time=ecs_time).values.squeeze())
unit = global_temp.get_unique_meta("unit", no_duplicates=True)
ecs = ecs * unit_registry(unit)
return ecs
def get_tcr_tcre_from_diagnosis_results(self, results_tcr_tcre_run):
"""
Diagnose TCR and TCRE from the results of the 1pctCO2 experiment
Parameters
----------
results_tcr_tcre_run : :obj:`ScmRun`
Results of the 1pctCO2 experiment, must contain atmospheric |CO2|
concentrations, inverse |CO2| emissions, total radiative forcing and
surface temperature.
Returns
-------
tcr, tcre : :obj:`pint.quantity.Quantity`, :obj:`pint.quantity.Quantity`
TCR and TCRE diagnosed from ``results_tcr_tcre_run``
"""
global_co2_concs = results_tcr_tcre_run.filter(
variable="Atmospheric Concentrations|CO2", region="World"
)
(tcr_time, tcr_start_time,) = self._get_tcr_tcr_start_yr_from_CO2_concs(
global_co2_concs
)
if tcr_time.year != tcr_start_time.year + 70: # pragma: no cover # emergency
raise AssertionError("Has the definition of TCR and TCRE changed?")
global_inverse_co2_emms = results_tcr_tcre_run.filter(
variable="Inverse Emissions|CO2|MAGICC Fossil and Industrial",
region="World",
)
global_total_rf = results_tcr_tcre_run.filter(
variable="Radiative Forcing", region="World"
)
self._check_tcr_tcre_total_RF(global_total_rf, tcr_time=tcr_time)
global_temp = results_tcr_tcre_run.filter(
variable="Surface Temperature", region="World"
)
self._check_tcr_tcre_temp(global_temp)
tcr = float(global_temp.filter(time=tcr_time).values.squeeze())
tcr_unit = global_temp.get_unique_meta("unit", no_duplicates=True)
tcr = tcr * unit_registry(tcr_unit)
tcre_cumulative_emms = float(
global_inverse_co2_emms.filter(
year=range(tcr_start_time.year, tcr_time.year)
).values.sum()
)
emms_unit = global_inverse_co2_emms.get_unique_meta("unit", no_duplicates=True)
years = global_inverse_co2_emms["year"].values.squeeze()
if not np.all((years[1:] - years[:-1]) == 1): # pragma: no cover
raise AssertionError(
"TCR/TCRE diagnosis assumed to be on annual timestep. Please "
"raise an issue at "
"https://github.com/openscm/pymagicc/issues to discuss "
"your use case"
)
# can now safely assume that our simple sum has done the right thing
tcre_cumulative_emms_unit = unit_registry(emms_unit) * unit_registry("yr")
tcre_cumulative_emms = tcre_cumulative_emms * tcre_cumulative_emms_unit
tcre = tcr / tcre_cumulative_emms
return tcr, tcre
def _get_ecs_ecs_start_yr_from_CO2_concs(self, df_co2_concs):
co2_concs = df_co2_concs.timeseries()
co2_conc_0 = co2_concs.iloc[0, 0]
t_start = co2_concs.columns.min()
t_end = co2_concs.columns.max()
ecs_start_time = co2_concs.iloc[
:, co2_concs.values.squeeze() > co2_conc_0
].columns[0]
spin_up_co2_concs = (
_filter_time_range(df_co2_concs, lambda x: t_start <= x < ecs_start_time)
.timeseries()
.values.squeeze()
)
if not (spin_up_co2_concs == co2_conc_0).all():
raise ValueError(
"The ECS CO2 concs look wrong, they are not constant before they start rising"
)
co2_conc_final = 2 * co2_conc_0
eqm_co2_concs = (
_filter_time_range(df_co2_concs, lambda x: ecs_start_time <= x <= t_end)
.timeseries()
.values.squeeze()
)
if not np.isclose(eqm_co2_concs, co2_conc_final).all():
raise ValueError(
"The ECS CO2 concs look wrong, they are not constant after doubling"
)
ecs_time = df_co2_concs["time"].iloc[-1]
return ecs_time, ecs_start_time
def _get_tcr_tcr_start_yr_from_CO2_concs(self, df_co2_concs):
co2_concs = df_co2_concs.timeseries()
co2_conc_0 = co2_concs.iloc[0, 0]
t_start = co2_concs.columns.min()
t_end = co2_concs.columns.max()
tcr_start_time = co2_concs.iloc[
:, co2_concs.values.squeeze() > co2_conc_0
].columns[0] - relativedelta(years=1)
tcr_time = tcr_start_time + relativedelta(years=70)
spin_up_co2_concs = (
_filter_time_range(df_co2_concs, lambda x: t_start <= x <= tcr_start_time)
.timeseries()
.values.squeeze()
)
if not (spin_up_co2_concs == co2_conc_0).all():
raise ValueError(
"The TCR/TCRE CO2 concs look wrong, they are not constant before they start rising"
)
actual_rise_co2_concs = (
_filter_time_range(df_co2_concs, lambda x: tcr_start_time <= x <= t_end)
.timeseries()
.values.squeeze()
)
# this will blow up if we switch to diagnose tcr/ecs with a monthly run...
expected_rise_co2_concs = co2_conc_0 * 1.01 ** np.arange(
len(actual_rise_co2_concs)
)
rise_co2_concs_correct = np.isclose(
actual_rise_co2_concs, expected_rise_co2_concs
).all()
if not rise_co2_concs_correct:
raise ValueError("The TCR/TCRE CO2 concs look wrong during the rise period")
return tcr_time, tcr_start_time
def _check_ecs_total_RF(self, df_total_rf, jump_time):
total_rf = df_total_rf.timeseries()
total_rf_max = total_rf.values.squeeze().max()
t_start = total_rf.columns.min()
t_end = total_rf.columns.max()
spin_up_rf = (
_filter_time_range(df_total_rf, lambda x: t_start <= x < jump_time)
.timeseries()
.values.squeeze()
)
if not (spin_up_rf == 0).all():
raise ValueError(
"The ECS total radiative forcing looks wrong, it is not all zero before concentrations start rising"
)
eqm_rf = (
_filter_time_range(df_total_rf, lambda x: jump_time <= x <= t_end)
.timeseries()
.values.squeeze()
)
if not (eqm_rf == total_rf_max).all():
raise ValueError(
"The ECS total radiative forcing looks wrong, it is not constant after concentrations double"
)
def _check_tcr_tcre_total_RF(self, df_total_rf, tcr_time):
total_rf = df_total_rf.timeseries()
t_start = total_rf.columns.min()
tcr_start_time = tcr_time - relativedelta(years=70)
spin_up_rf = (
_filter_time_range(df_total_rf, lambda x: t_start <= x <= tcr_start_time)
.timeseries()
.values.squeeze()
)
if not (spin_up_rf == 0).all():
raise ValueError(
"The TCR/TCRE total radiative forcing looks wrong, it is not all zero before concentrations start rising"
)
rf_vls = total_rf.values.squeeze()
rf_minus_previous_yr = rf_vls[1:] - rf_vls[:-1]
if not np.all(rf_minus_previous_yr >= 0):
raise ValueError(
"The TCR/TCRE total radiative forcing looks wrong, it is not rising after concentrations start rising"
)
def _check_ecs_temp(self, df_temp):
self._check_tcr_ecs_tcre_temp(
df_temp, "The ECS surface temperature looks wrong, it decreases"
)
def _check_tcr_tcre_temp(self, df_temp):
self._check_tcr_ecs_tcre_temp(
df_temp, "The TCR/TCRE surface temperature looks wrong, it decreases"
)
def _check_tcr_ecs_tcre_temp(self, df_temp, message):
tmp_vls = df_temp.timeseries().values.squeeze()
tmp_minus_previous_yr = tmp_vls[1:] - tmp_vls[:-1]
if not np.all(tmp_minus_previous_yr >= 0):
raise ValueError(message)
def set_emission_scenario_setup(self, scenario, config_dict):
"""Set the emissions flags correctly.
Parameters
----------
scenario : :obj:`pymagicc.io.MAGICCData`
Scenario to run.
config_dict : dict
Dictionary with current input configurations which is to be validated and
updated where necessary.
Returns
-------
dict
Updated configuration
"""
self.write(scenario, self._scen_file_name)
emis_flag = list(
self._fix_legacy_keys(
f90nml.Namelist({"nml_allcfgs": {"file_emisscen": "junk"}}),
conflict="ignore",
)["nml_allcfgs"].keys()
)[0]
config_dict[emis_flag] = self._scen_file_name
return config_dict
def _check_config(self):
"""
Check config above and beyond those checked by ``self.check_config``
"""
pass
class MAGICC6(MAGICCBase):
version = 6
_scen_file_name = "SCENARIO.SCEN"
_config_renamings = {
"file_emisscen": "file_emissionscenario",
"fgas_files_conc": "file_fgas_conc",
"mhalo_switchfromconc2emis_year": "mhalo_switch_conc2emis_yr",
}
@property
def default_config(self):
"""
Default configuration to use in a run
"""
base = f90nml.read(join(self.run_dir, "MAGCFG_DEFAULTALL_69.CFG"))
user = f90nml.read(join(self.run_dir, "MAGCFG_USER.CFG"))
self._default_config = deepcopy(base)
self._default_config.update(user)
return self._default_config
def _check_tcr_ecs_tcre_total_RF(self, df_total_rf, tcr_time, ecs_time):
super()._check_tcr_ecs_tcre_total_RF(df_total_rf, tcr_time, ecs_time)
# can be more careful with checks MAGICC6 only has logarithmic CO2 forcing
# i.e. linear rise in forcing
total_rf = df_total_rf.timeseries()
total_rf_max = total_rf.values.squeeze().max()
tcre_start_time = tcr_time - relativedelta(years=70)
actual_rise_rf = (
_filter_time_range(df_total_rf, lambda x: tcre_start_time <= x <= tcr_time)
.timeseries()
.values.squeeze()
)
# this will blow up if we switch to diagnose tcr/ecs with a monthly run...
expected_rise_rf = total_rf_max / 70.0 * np.arange(71)
rise_rf_correct = np.isclose(actual_rise_rf, expected_rise_rf).all()
if not rise_rf_correct:
raise ValueError(
"The TCR/ECS/TCRE total radiative forcing looks wrong during the rise period"
)
def _check_config(self):
cfg = self.update_config()
if "file_emissionscenario" in cfg["nml_allcfgs"]:
if cfg["nml_allcfgs"]["file_emissionscenario"].endswith("SCEN7"):
self._check_failed("MAGICC6 cannot run SCEN7 files")
class MAGICC7(MAGICCBase):
version = 7
_config_renamings = {
"file_emissionscenario": "file_emisscen",
"file_fgas_conc": "fgas_files_conc",
"mhalo_switch_conc2emis_yr": "mhalo_switchfromconc2emis_year",
}
def create_copy(self):
"""
Initialises a temporary directory structure and copy of MAGICC
configuration files and binary.
This will also overwrite the value of all ``file_tuningmodel_x`` flags to
ensure that Pymagicc's configurations will be read. If ``self.strict``, this
will also overwrite the value of all ``file_emisscen_x`` flags to ensure that
only Pymagicc's scenario input is used. This overwrite behaviour can be
removed once the MAGICC7 binary is publicly released as we can then create a
Pymagicc specific MAGCFG_USER.CFG rather than relying on whatever is in the
user's current copy.
"""
super(MAGICC7, self).create_copy()
self.update_config(
"MAGCFG_USER.CFG",
**{
"file_tuningmodel_1": "PYMAGICC",
"file_tuningmodel_2": "USER",
"file_tuningmodel_3": "USER",
"file_tuningmodel_4": "USER",
"file_tuningmodel_5": "USER",
"file_tuningmodel_6": "USER",
"file_tuningmodel_7": "USER",
"file_tuningmodel_8": "USER",
"file_tuningmodel_9": "USER",
"file_tuningmodel_10": "USER",
},
)
if self.strict:
self.update_config(
"MAGCFG_USER.CFG",
**{
"file_emisscen_2": "NONE",
"file_emisscen_3": "NONE",
"file_emisscen_4": "NONE",
"file_emisscen_5": "NONE",
"file_emisscen_6": "NONE",
"file_emisscen_7": "NONE",
"file_emisscen_8": "NONE",
},
)
def _diagnose_tcr_ecs_tcre_config_setup(self, **kwargs):
super()._diagnose_tcr_ecs_tcre_config_setup(**kwargs)
# also need to lock CH4 and N2O in case OLBL forcing mode is being used
self.update_config(
FILE_CH4_CONC="TCRECS_CH4_CONC.IN",
CH4_SWITCHFROMCONC2EMIS_YEAR=30000,
FILE_N2O_CONC="TCRECS_N2O_CONC.IN",
N2O_SWITCHFROMCONC2EMIS_YEAR=30000,
)
def _check_config(self):
pass
def _filter_time_range(scmdf, filter_func):
# TODO: move into openscm
tdf = scmdf.timeseries()
tdf = tdf.iloc[:, tdf.columns.map(filter_func)]
return MAGICCData(tdf)
| [
"f90nml.write",
"dateutil.relativedelta.relativedelta",
"f90nml.Namelist",
"copy.deepcopy",
"numpy.arange",
"os.path.exists",
"os.listdir",
"subprocess.run",
"pandas.DataFrame",
"warnings.warn",
"numpy.ones",
"openscm_units.unit_registry",
"os.path.isfile",
"os.path.dirname",
"scmdata.ru... | [((1232, 1247), 'os.listdir', 'listdir', (['source'], {}), '(source)\n', (1239, 1247), False, 'from os import listdir, makedirs\n'), ((1164, 1195), 'shutil.copytree', 'shutil.copytree', (['source', 'target'], {}), '(source, target)\n', (1179, 1195), False, 'import shutil\n'), ((1260, 1274), 'os.path.exists', 'exists', (['target'], {}), '(target)\n', (1266, 1274), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((1284, 1300), 'os.makedirs', 'makedirs', (['target'], {}), '(target)\n', (1292, 1300), False, 'from os import listdir, makedirs\n'), ((1360, 1382), 'os.path.join', 'join', (['source', 'filename'], {}), '(source, filename)\n', (1364, 1382), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((1394, 1415), 'os.path.isfile', 'isfile', (['full_filename'], {}), '(full_filename)\n', (1400, 1415), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((4600, 4620), 'os.path.exists', 'exists', (['self.run_dir'], {}), '(self.run_dir)\n', (4606, 4620), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((4791, 4818), 'os.path.basename', 'basename', (['self.original_dir'], {}), '(self.original_dir)\n', (4799, 4818), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((6202, 6227), 'os.path.basename', 'basename', (['self.executable'], {}), '(self.executable)\n', (6210, 6227), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((6514, 6538), 'os.path.dirname', 'dirname', (['self.executable'], {}), '(self.executable)\n', (6521, 6538), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((6845, 6871), 'os.path.join', 'join', (['self.root_dir', '"""run"""'], {}), "(self.root_dir, 'run')\n", (6849, 6871), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((7184, 7210), 'os.path.join', 'join', (['self.root_dir', '"""out"""'], {}), "(self.root_dir, 'out')\n", (7188, 7210), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((7618, 7632), 'copy.deepcopy', 'deepcopy', (['base'], {}), '(base)\n', (7626, 7632), False, 'from copy import deepcopy\n'), ((10896, 10923), 'os.path.basename', 'basename', (['self.original_dir'], {}), '(self.original_dir)\n', (10904, 10923), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((17967, 18003), 'os.path.join', 'join', (['self.out_dir', '"""PARAMETERS.OUT"""'], {}), "(self.out_dir, 'PARAMETERS.OUT')\n", (17971, 18003), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((20164, 20192), 'os.path.join', 'join', (['self.run_dir', 'filename'], {}), '(self.run_dir, filename)\n', (20168, 20192), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((20302, 20339), 'f90nml.write', 'f90nml.write', (['conf', 'fname'], {'force': '(True)'}), '(conf, fname, force=True)\n', (20314, 20339), False, 'import f90nml\n'), ((21739, 21767), 'os.path.join', 'join', (['self.run_dir', 'filename'], {}), '(self.run_dir, filename)\n', (21743, 21767), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((21780, 21793), 'os.path.exists', 'exists', (['fname'], {}), '(fname)\n', (21786, 21793), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((22000, 22037), 'f90nml.write', 'f90nml.write', (['conf', 'fname'], {'force': '(True)'}), '(conf, fname, force=True)\n', (22012, 22037), False, 'import f90nml\n'), ((23188, 23202), 'copy.deepcopy', 'deepcopy', (['conf'], {}), '(conf)\n', (23196, 23202), False, 'from copy import deepcopy\n'), ((24604, 24839), 'pandas.DataFrame', 'pd.DataFrame', (["{'time': time, 'scenario': 'idealised', 'model': 'unspecified',\n 'climate_model': 'unspecified', 'variable':\n 'Atmospheric Concentrations|CO2', 'unit': 'ppm', 'todo': 'SET',\n 'region': 'World', 'value': co2_conc}"], {}), "({'time': time, 'scenario': 'idealised', 'model': 'unspecified',\n 'climate_model': 'unspecified', 'variable':\n 'Atmospheric Concentrations|CO2', 'unit': 'ppm', 'todo': 'SET',\n 'region': 'World', 'value': co2_conc})\n", (24616, 24839), True, 'import pandas as pd\n'), ((25416, 25651), 'pandas.DataFrame', 'pd.DataFrame', (["{'time': time, 'scenario': 'idealised', 'model': 'unspecified',\n 'climate_model': 'unspecified', 'variable':\n 'Atmospheric Concentrations|CH4', 'unit': 'ppb', 'todo': 'SET',\n 'region': 'World', 'value': ch4_conc}"], {}), "({'time': time, 'scenario': 'idealised', 'model': 'unspecified',\n 'climate_model': 'unspecified', 'variable':\n 'Atmospheric Concentrations|CH4', 'unit': 'ppb', 'todo': 'SET',\n 'region': 'World', 'value': ch4_conc})\n", (25428, 25651), True, 'import pandas as pd\n'), ((26261, 26468), 'pandas.DataFrame', 'pd.DataFrame', (["{'time': time, 'scenario': 'idealised', 'model': 'unspecified',\n 'climate_model': 'unspecified', 'variable': varname, 'unit': 'ppt',\n 'todo': 'SET', 'region': 'World', 'value': fgas_conc}"], {}), "({'time': time, 'scenario': 'idealised', 'model': 'unspecified',\n 'climate_model': 'unspecified', 'variable': varname, 'unit': 'ppt',\n 'todo': 'SET', 'region': 'World', 'value': fgas_conc})\n", (26273, 26468), True, 'import pandas as pd\n'), ((26972, 27028), 'f90nml.Namelist', 'f90nml.Namelist', (["{'nml_allcfgs': {'fgas_files_conc': 1}}"], {}), "({'nml_allcfgs': {'fgas_files_conc': 1}})\n", (26987, 27028), False, 'import f90nml\n'), ((29737, 29756), 'collections.Counter', 'Counter', (['keys_lower'], {}), '(keys_lower)\n', (29744, 29756), False, 'from collections import Counter\n'), ((38037, 38100), 'scmdata.run_append', 'run_append', (["[ecs_res['timeseries'], tcr_tcre_res['timeseries']]"], {}), "([ecs_res['timeseries'], tcr_tcre_res['timeseries']])\n", (38047, 38100), False, 'from scmdata import run_append\n'), ((53343, 53357), 'copy.deepcopy', 'deepcopy', (['base'], {}), '(base)\n', (53351, 53357), False, 'from copy import deepcopy\n'), ((1429, 1463), 'shutil.copy', 'shutil.copy', (['full_filename', 'target'], {}), '(full_filename, target)\n', (1440, 1463), False, 'import shutil\n'), ((4560, 4587), 'tempfile.mkdtemp', 'mkdtemp', ([], {'prefix': '"""pymagicc-"""'}), "(prefix='pymagicc-')\n", (4567, 4587), False, 'from tempfile import mkdtemp\n'), ((4712, 4733), 'os.path.exists', 'exists', (['self.root_dir'], {}), '(self.root_dir)\n', (4718, 4733), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((4747, 4770), 'os.makedirs', 'makedirs', (['self.root_dir'], {}), '(self.root_dir)\n', (4755, 4770), False, 'from os import listdir, makedirs\n'), ((5541, 5559), 'os.path.exists', 'exists', (['source_dir'], {}), '(source_dir)\n', (5547, 5559), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((5860, 5886), 'os.path.join', 'join', (['self.root_dir', '"""out"""'], {}), "(self.root_dir, 'out')\n", (5864, 5886), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((7476, 7519), 'os.path.join', 'join', (['self.run_dir', '"""MAGCFG_DEFAULTALL.CFG"""'], {}), "(self.run_dir, 'MAGCFG_DEFAULTALL.CFG')\n", (7480, 7519), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((7548, 7585), 'os.path.join', 'join', (['self.run_dir', '"""MAGCFG_USER.CFG"""'], {}), "(self.run_dir, 'MAGCFG_USER.CFG')\n", (7552, 7585), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((9931, 9952), 'os.path.exists', 'exists', (['self.root_dir'], {}), '(self.root_dir)\n', (9937, 9952), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((10943, 10990), 'os.path.join', 'join', (['self.root_dir', 'exec_dir', 'self.binary_name'], {}), '(self.root_dir, exec_dir, self.binary_name)\n', (10947, 10990), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((11589, 11691), 'subprocess.run', 'subprocess.run', (['command'], {'check': '(True)', 'stdout': 'PIPE', 'stderr': 'PIPE', 'cwd': 'self.run_dir', 'shell': 'IS_WINDOWS'}), '(command, check=True, stdout=PIPE, stderr=PIPE, cwd=self.\n run_dir, shell=IS_WINDOWS)\n', (11603, 11691), False, 'import subprocess\n'), ((14078, 14095), 'scmdata.run_append', 'run_append', (['mdata'], {}), '(mdata)\n', (14088, 14095), False, 'from scmdata import run_append\n'), ((15363, 15381), 'warnings.warn', 'warnings.warn', (['msg'], {}), '(msg)\n', (15376, 15381), False, 'import warnings\n'), ((16590, 16627), 'os.path.join', 'join', (['self.run_dir', '"""MAGCFG_USER.CFG"""'], {}), "(self.run_dir, 'MAGCFG_USER.CFG')\n", (16594, 16627), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((17695, 17719), 'os.path.join', 'join', (['self.run_dir', 'name'], {}), '(self.run_dir, name)\n', (17699, 17719), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((18020, 18039), 'os.path.exists', 'exists', (['param_fname'], {}), '(param_fname)\n', (18026, 18039), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((18792, 18820), 'shutil.rmtree', 'shutil.rmtree', (['self.root_dir'], {}), '(self.root_dir)\n', (18805, 18820), False, 'import shutil\n'), ((21814, 21832), 'f90nml.read', 'f90nml.read', (['fname'], {}), '(fname)\n', (21825, 21832), False, 'import f90nml\n'), ((24167, 24207), 'os.path.join', 'join', (['self.run_dir', 'self._scen_file_name'], {}), '(self.run_dir, self._scen_file_name)\n', (24171, 24207), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((24560, 24581), 'numpy.ones', 'np.ones', (['no_timesteps'], {}), '(no_timesteps)\n', (24567, 24581), True, 'import numpy as np\n'), ((25259, 25296), 'os.path.join', 'join', (['self.run_dir', 'co2_conc_filename'], {}), '(self.run_dir, co2_conc_filename)\n', (25263, 25296), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((25372, 25393), 'numpy.ones', 'np.ones', (['no_timesteps'], {}), '(no_timesteps)\n', (25379, 25393), True, 'import numpy as np\n'), ((26071, 26108), 'os.path.join', 'join', (['self.run_dir', 'ch4_conc_filename'], {}), '(self.run_dir, ch4_conc_filename)\n', (26075, 26108), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((26185, 26206), 'numpy.ones', 'np.ones', (['no_timesteps'], {}), '(no_timesteps)\n', (26192, 26206), True, 'import numpy as np\n'), ((26858, 26896), 'os.path.join', 'join', (['self.run_dir', 'fgas_conc_filename'], {}), '(self.run_dir, fgas_conc_filename)\n', (26862, 26896), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((43770, 43789), 'openscm_units.unit_registry', 'unit_registry', (['unit'], {}), '(unit)\n', (43783, 43789), False, 'from openscm_units import unit_registry\n'), ((45568, 45591), 'openscm_units.unit_registry', 'unit_registry', (['tcr_unit'], {}), '(tcr_unit)\n', (45581, 45591), False, 'from openscm_units import unit_registry\n'), ((45943, 45978), 'numpy.all', 'np.all', (['(years[1:] - years[:-1] == 1)'], {}), '(years[1:] - years[:-1] == 1)\n', (45949, 45978), True, 'import numpy as np\n'), ((46385, 46409), 'openscm_units.unit_registry', 'unit_registry', (['emms_unit'], {}), '(emms_unit)\n', (46398, 46409), False, 'from openscm_units import unit_registry\n'), ((46412, 46431), 'openscm_units.unit_registry', 'unit_registry', (['"""yr"""'], {}), "('yr')\n", (46425, 46431), False, 'from openscm_units import unit_registry\n'), ((48173, 48195), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'years': '(1)'}), '(years=1)\n', (48186, 48195), False, 'from dateutil.relativedelta import relativedelta\n'), ((48232, 48255), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'years': '(70)'}), '(years=70)\n', (48245, 48255), False, 'from dateutil.relativedelta import relativedelta\n'), ((50476, 50499), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'years': '(70)'}), '(years=70)\n', (50489, 50499), False, 'from dateutil.relativedelta import relativedelta\n'), ((50997, 51030), 'numpy.all', 'np.all', (['(rf_minus_previous_yr >= 0)'], {}), '(rf_minus_previous_yr >= 0)\n', (51003, 51030), True, 'import numpy as np\n'), ((51728, 51762), 'numpy.all', 'np.all', (['(tmp_minus_previous_yr >= 0)'], {}), '(tmp_minus_previous_yr >= 0)\n', (51734, 51762), True, 'import numpy as np\n'), ((53198, 53244), 'os.path.join', 'join', (['self.run_dir', '"""MAGCFG_DEFAULTALL_69.CFG"""'], {}), "(self.run_dir, 'MAGCFG_DEFAULTALL_69.CFG')\n", (53202, 53244), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((53273, 53310), 'os.path.join', 'join', (['self.run_dir', '"""MAGCFG_USER.CFG"""'], {}), "(self.run_dir, 'MAGCFG_USER.CFG')\n", (53277, 53310), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((53851, 53874), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'years': '(70)'}), '(years=70)\n', (53864, 53874), False, 'from dateutil.relativedelta import relativedelta\n'), ((54190, 54203), 'numpy.arange', 'np.arange', (['(71)'], {}), '(71)\n', (54199, 54203), True, 'import numpy as np\n'), ((4122, 4145), 'os.path.isfile', 'isfile', (['self.executable'], {}), '(self.executable)\n', (4128, 4145), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((5492, 5524), 'os.path.join', 'join', (['self.original_dir', '""".."""', 'd'], {}), "(self.original_dir, '..', d)\n", (5496, 5524), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((14805, 14826), 'os.listdir', 'listdir', (['self.out_dir'], {}), '(self.out_dir)\n', (14812, 14826), False, 'from os import listdir, makedirs\n'), ((18179, 18200), 'f90nml.read', 'f90nml.read', (['nml_file'], {}), '(nml_file)\n', (18190, 18200), False, 'import f90nml\n'), ((49057, 49115), 'numpy.isclose', 'np.isclose', (['actual_rise_co2_concs', 'expected_rise_co2_concs'], {}), '(actual_rise_co2_concs, expected_rise_co2_concs)\n', (49067, 49115), True, 'import numpy as np\n'), ((54230, 54274), 'numpy.isclose', 'np.isclose', (['actual_rise_rf', 'expected_rise_rf'], {}), '(actual_rise_rf, expected_rise_rf)\n', (54240, 54274), True, 'import numpy as np\n'), ((5642, 5664), 'os.path.join', 'join', (['self.root_dir', 'd'], {}), '(self.root_dir, d)\n', (5646, 5664), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((47547, 47588), 'numpy.isclose', 'np.isclose', (['eqm_co2_concs', 'co2_conc_final'], {}), '(eqm_co2_concs, co2_conc_final)\n', (47557, 47588), True, 'import numpy as np\n'), ((13080, 13108), 'os.path.join', 'join', (['self.out_dir', 'filepath'], {}), '(self.out_dir, filepath)\n', (13084, 13108), False, 'from os.path import abspath, basename, dirname, exists, isfile, join\n'), ((13118, 13137), 'copy.deepcopy', 'deepcopy', (['read_cols'], {}), '(read_cols)\n', (13126, 13137), False, 'from copy import deepcopy\n'), ((52403, 52462), 'f90nml.Namelist', 'f90nml.Namelist', (["{'nml_allcfgs': {'file_emisscen': 'junk'}}"], {}), "({'nml_allcfgs': {'file_emisscen': 'junk'}})\n", (52418, 52462), False, 'import f90nml\n')] |
import json
import json
import boto3
import re
import json
import collections
import os
import pandas as pd
import csv
from csv import writer
# boto3 S3 initialization
s3_client = boto3.client("s3")
import numpy as np
def lambda_handler(event, context):
# TODO implement
bucketname = 'sourcedatab00870639'
# event contains all information about uploaded object
print("Event :", event)
# Bucket Name where file was uploaded
sourcebucket = event['Records'][0]['s3']['bucket']['name']
# Filename of object (with path)
file_key_name = event['Records'][0]['s3']['object']['key']
input_file = os.path.join(sourcebucket, file_key_name)
# Start the function that processes the incoming data.
bucket = bucketname
key = file_key_name
response = s3_client.get_object(Bucket=sourcebucket, Key=file_key_name)
content = response['Body'].read().decode('utf-8')
x = content.split()
stopwords = ['ourselves', 'hers', 'between', 'yourself', 'but', 'again', 'there', 'about', 'once', 'during', 'out',
'very', 'having', 'with', 'they', 'own', 'an', 'be', 'some', 'for', 'do', 'its', 'yours', 'such',
'into', 'of', 'most', 'itself', 'other', 'off', 'is', 's', 'am', 'or', 'who', 'as', 'from', 'him',
'each', 'the', 'themselves', 'until', 'below', 'are', 'we', 'these', 'your', 'his', 'through', 'don',
'nor', 'me', 'were', 'her', 'more', 'himself', 'this', 'down', 'should', 'our', 'their', 'while',
'above', 'both', 'up', 'to', 'ours', 'had', 'she', 'all', 'no', 'when', 'at', 'any', 'before', 'them',
'same', 'and', 'been', 'have', 'in', 'will', 'on', 'does', 'yourselves', 'then', 'that', 'because',
'what', 'over', 'why', 'so', 'can', 'did', 'not', 'now', 'under', 'he', 'you', 'herself', 'has',
'just', 'where', 'too', 'only', 'myself', 'which', 'those', 'i', 'after', 'few', 'whom', 't', 'being',
'if', 'theirs', 'my', 'against', 'a', 'by', 'doing', 'it', 'how', 'further', 'was', 'here', 'than']
stop_words = set(stopwords)
tokens_without_sw = [w for w in x if w not in stop_words]
current_word = []
next_word = []
data_list = [['Current_Word', 'Next_Word', 'Levenshtein_distance']]
def levenshteindistance(var1, var2):
size_x = len(var1) + 1
size_y = len(var2) + 1
matrix = np.zeros((size_x, size_y))
for x in range(size_x):
matrix[x, 0] = x
for y in range(size_y):
matrix[0, y] = y
for x in range(1, size_x):
for y in range(1, size_y):
if seq1[x - 1] == seq2[y - 1]:
matrix[x, y] = min(matrix[x - 1, y] + 1, matrix[x - 1, y - 1], matrix[x, y - 1] + 1)
else:
matrix[x, y] = min(matrix[x - 1, y] + 1, matrix[x - 1, y - 1] + 1, matrix[x, y - 1] + 1)
return (matrix[size_x - 1, size_y - 1])
for i in range(len(tokens_without_sw) - 1):
data_list.append([tokens_without_sw[i], tokens_without_sw[i + 1],
levenshteindistance(tokens_without_sw[i], tokens_without_sw[i + 1])])
print(tokens_without_sw)
df = pd.DataFrame(data_list)
bytes_to_write = df.to_csv(None, header=None, index=False).encode()
file_name = "testVector.csv"
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucketname)
key = file_name
ans = []
current_data = s3_client.get_object(Bucket=bucketname, Key=file_name)
lines = csv.reader(current_data)
for row in lines:
ans.append(row)
for d in data_list:
ans.append(d)
file_name = "trainVector.csv"
resfile = s3.get_object(Bucket="sourcedatab00870639", Key=file_name)
restext = resfile["Body"].read().decode('utf-8')
updated_data = restext + "\n" + "\n".join(str(item).strip('[]') for item in words_list)
s3.put_object(Body=updated_data, Bucket="sourcedatab00870639 ", Key=file_name)
print(updated_data)
| [
"boto3.client",
"os.path.join",
"numpy.zeros",
"boto3.resource",
"pandas.DataFrame",
"csv.reader"
] | [((181, 199), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (193, 199), False, 'import boto3\n'), ((625, 666), 'os.path.join', 'os.path.join', (['sourcebucket', 'file_key_name'], {}), '(sourcebucket, file_key_name)\n', (637, 666), False, 'import os\n'), ((2414, 2440), 'numpy.zeros', 'np.zeros', (['(size_x, size_y)'], {}), '((size_x, size_y))\n', (2422, 2440), True, 'import numpy as np\n'), ((3336, 3356), 'boto3.resource', 'boto3.resource', (['"""s3"""'], {}), "('s3')\n", (3350, 3356), False, 'import boto3\n'), ((3512, 3536), 'csv.reader', 'csv.reader', (['current_data'], {}), '(current_data)\n', (3522, 3536), False, 'import csv\n'), ((3189, 3212), 'pandas.DataFrame', 'pd.DataFrame', (['data_list'], {}), '(data_list)\n', (3201, 3212), True, 'import pandas as pd\n')] |
from lib.plugins import Driver
import os
from paramiko import SSHClient, RSAKey, AutoAddPolicy
from io import StringIO
class Ssh(Driver):
DEFAULT_KEY_PATH = "~/.ssh/id_rsa"
def __init__(self, host, username='root', password = None, key = None, port = 22, path = "/proc"):
Driver.__init__(self)
self._host = host
self._username = username
self._password = password
self._port = port
self._path = path
self._client = None
self._ftp = None
if not password or key:
self._key = RSAKey.from_private_key_file(os.path.expanduser(key or Ssh.DEFAULT_KEY_PATH))
else:
self._key = None
def readProc(self, path):
sftp = self._connectFtp()
o = StringIO()
for line in sftp.open(os.path.join(self._path, path)):
o.write(line)
return o.getvalue()
def sh(self, cmd):
client = self._connect()
stdin, stdout, stderr = client.exec_command(cmd)
return {
"stdout": stdout.read().decode('utf-8'),
"stderr": stderr.read().decode('utf-8'),
"status": stdout.channel.recv_exit_status()
}
def _connect(self):
if not self._client:
client = SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())
client.connect(hostname = self._host, username=self._username, password=self._password, pkey=self._key, port=self._port, look_for_keys=False)
self._client = client
return self._client
def _connectFtp(self):
if not self._ftp:
client = self._connect()
self._ftp = client.open_sftp()
return self._ftp
def getHost(self):
return self._host
def create(args):
return Ssh(**args) | [
"paramiko.AutoAddPolicy",
"os.path.join",
"lib.plugins.Driver.__init__",
"io.StringIO",
"paramiko.SSHClient",
"os.path.expanduser"
] | [((278, 299), 'lib.plugins.Driver.__init__', 'Driver.__init__', (['self'], {}), '(self)\n', (293, 299), False, 'from lib.plugins import Driver\n'), ((669, 679), 'io.StringIO', 'StringIO', ([], {}), '()\n', (677, 679), False, 'from io import StringIO\n'), ((704, 734), 'os.path.join', 'os.path.join', (['self._path', 'path'], {}), '(self._path, path)\n', (716, 734), False, 'import os\n'), ((1083, 1094), 'paramiko.SSHClient', 'SSHClient', ([], {}), '()\n', (1092, 1094), False, 'from paramiko import SSHClient, RSAKey, AutoAddPolicy\n'), ((529, 576), 'os.path.expanduser', 'os.path.expanduser', (['(key or Ssh.DEFAULT_KEY_PATH)'], {}), '(key or Ssh.DEFAULT_KEY_PATH)\n', (547, 576), False, 'import os\n'), ((1133, 1148), 'paramiko.AutoAddPolicy', 'AutoAddPolicy', ([], {}), '()\n', (1146, 1148), False, 'from paramiko import SSHClient, RSAKey, AutoAddPolicy\n')] |
"""
Friends-of-Friends (FOF) for N-body simulations
<NAME> - Oct 2016
"""
from __future__ import absolute_import, print_function
from lizard.periodic import pad_unitcube
from scipy.spatial import Delaunay
from scipy.sparse import csr_matrix, csgraph
from numpy import square, flatnonzero, ones, zeros_like, cumsum, concatenate, \
arange, searchsorted, bincount, sort, diff, int8, argsort, array
from lizard.log import MarkUp, null_log
def fof_groups(pos, b, log=null_log):
"""
Friends-of-Friends on the period unit cube
pos - (n,ndim) positions in [0,1]^ndim
b - linking length
returns labels - (n,) array of integers for each connected component.
This FoF algorithm computes the fixed radius connectivity by computing the
Delaunay tesselation (DT) for each link and then breaking those links that are
too long.
The reason this works is that the Relative Neighbourhood Graph (RNG) is a
subgraph of the DT, and so any pair of points separated by a distance R will be
connected by links of <R, and so it is enough to use the DT to establish
connectivity.
"""
print('Padding the unit cube', file=log)
pad_idx, pad_pos = pad_unitcube(pos, b)
all_pos = concatenate((pos, pad_pos), axis=0) + b
all_pos *= 1.0/(1+2*b)
b_scaled = b/(1+2*b)
print('Added {:,} points, performing'.format(len(pad_idx)),
MarkUp.OKBLUE+'Delaunay tesselation'+MarkUp.ENDC,
'of {:,} points'.format(len(all_pos)), file=log)
dlny = Delaunay(all_pos)
# construct list of links
indptr, indices = dlny.vertex_neighbor_vertices
idx1 = zeros_like(indices)
idx1[indptr[1:-1]] = 1
idx1 = cumsum(idx1)
idx2 = indices
print('{:,} links, disconnecting those with r>%.5f'.format(len(indices))%b, file=log)
# find all links < b using square distance
dist2 = square(all_pos[idx1] - all_pos[idx2]).sum(1)
del dlny
keep = flatnonzero(dist2<float(b_scaled*b_scaled))
idx1, idx2 = idx1[keep], idx2[keep]
print('{:,} links left, removing periodic images'.format(len(idx1)), file=log)
# Make the map back to the original IDs
old_id = arange(len(all_pos))
old_id[len(pos):] = pad_idx
idx1, idx2 = old_id[idx1], old_id[idx2]
# remove repeats
idx_sort = argsort(idx1*len(pos)+idx2)
idx1,idx2 = idx1[idx_sort], idx2[idx_sort]
if len(idx1)>0:
keep = array([0] + list(flatnonzero(diff(idx1) | diff(idx2))+1), dtype=idx2.dtype)
idx1, idx2 = idx1[keep], idx2[keep]
# make a sparse matrix of connectivity
print('{:,} links, building sparse matrix'.format(len(idx1)), file=log)
indices = idx2
indptr = searchsorted(idx1, arange(len(pos)+1))
mat = csr_matrix((ones(len(indices), dtype=int8), indices, indptr),
shape=(len(pos), len(pos)))
print('Finding connected components',file=log)
n_comps, labels = csgraph.connected_components(mat, directed=False)
print('From {:,} links between {:,} points found {:,} connected components'.format(len(idx1), len(pos), n_comps), file=log)
show_largest = min(n_comps, 3)
npts = sort(bincount(labels))[-show_largest:]
print('{:,} largest'.format(show_largest), MarkUp.OKBLUE+'FoF groups'+MarkUp.ENDC,
'have', MarkUp.OKBLUE+' '.join('{:,}'.format(i) for i in npts),
'points'+MarkUp.ENDC, file=log)
return labels
def test_labels():
""" Test with some 64^3 data """
from lizard.log import VerboseTimingLog
log = VerboseTimingLog()
import numpy as np
parts = np.load('/mainvol/peter.creasey/bigdata/runs/test_const_pmkick/out/lizard_snap_134.npz')
pos = parts['pos']
boxsize = 5600
nbox = len(pos)**(1.0/3.0)
print(pos.max(axis=0), boxsize, nbox, file=log)
labels = fof_groups(pos*(1.0/boxsize), b=0.2/nbox, log=log)
print('labels in', labels.min(), labels.max(), file=log)
bins = np.bincount(labels)
part_lim = 20 # ignore anything with < part_lim particles
NO_FOF = labels.max()+1
newlab = np.where(bins[labels]<part_lim, NO_FOF, np.arange(len(bins))[labels])
bins = bincount(newlab)
halo_counts = sort(bins[:NO_FOF-1])
print('halo counts', halo_counts[-10:][::-1], file=log)
# Top 10
idx = []
lab_sort = np.argsort(bins[:NO_FOF-1])
import pylab as pl
for i in range(50):
lab = lab_sort[-i-1]
idx_i = np.flatnonzero(labels==lab)
pl.plot(pos[idx_i][:,2], pos[idx_i][:,1], marker=',', ls='none')
pl.xlim(0,5600)
pl.ylim(0,5600)
pl.show()
def test_random_dist(n=64):
""" Random n^3 point placement """
from lizard.log import VerboseTimingLog
log = VerboseTimingLog()
from numpy.random import RandomState
rs = RandomState(seed=123)
pos = rs.rand(3*(n**3)).reshape((n**3,3))
fof_labels = fof_groups(pos, b=0.2/n, log=log)
if __name__=='__main__':
# test_labels()
test_random_dist(n=100)
| [
"numpy.argsort",
"numpy.random.RandomState",
"pylab.ylim",
"lizard.periodic.pad_unitcube",
"pylab.plot",
"numpy.sort",
"numpy.flatnonzero",
"numpy.diff",
"lizard.log.VerboseTimingLog",
"pylab.xlim",
"numpy.concatenate",
"numpy.square",
"numpy.bincount",
"pylab.show",
"scipy.sparse.csgrap... | [((1200, 1220), 'lizard.periodic.pad_unitcube', 'pad_unitcube', (['pos', 'b'], {}), '(pos, b)\n', (1212, 1220), False, 'from lizard.periodic import pad_unitcube\n'), ((1523, 1540), 'scipy.spatial.Delaunay', 'Delaunay', (['all_pos'], {}), '(all_pos)\n', (1531, 1540), False, 'from scipy.spatial import Delaunay\n'), ((1635, 1654), 'numpy.zeros_like', 'zeros_like', (['indices'], {}), '(indices)\n', (1645, 1654), False, 'from numpy import square, flatnonzero, ones, zeros_like, cumsum, concatenate, arange, searchsorted, bincount, sort, diff, int8, argsort, array\n'), ((1693, 1705), 'numpy.cumsum', 'cumsum', (['idx1'], {}), '(idx1)\n', (1699, 1705), False, 'from numpy import square, flatnonzero, ones, zeros_like, cumsum, concatenate, arange, searchsorted, bincount, sort, diff, int8, argsort, array\n'), ((2927, 2976), 'scipy.sparse.csgraph.connected_components', 'csgraph.connected_components', (['mat'], {'directed': '(False)'}), '(mat, directed=False)\n', (2955, 2976), False, 'from scipy.sparse import csr_matrix, csgraph\n'), ((3534, 3552), 'lizard.log.VerboseTimingLog', 'VerboseTimingLog', ([], {}), '()\n', (3550, 3552), False, 'from lizard.log import VerboseTimingLog\n'), ((3588, 3686), 'numpy.load', 'np.load', (['"""/mainvol/peter.creasey/bigdata/runs/test_const_pmkick/out/lizard_snap_134.npz"""'], {}), "(\n '/mainvol/peter.creasey/bigdata/runs/test_const_pmkick/out/lizard_snap_134.npz'\n )\n", (3595, 3686), True, 'import numpy as np\n'), ((3941, 3960), 'numpy.bincount', 'np.bincount', (['labels'], {}), '(labels)\n', (3952, 3960), True, 'import numpy as np\n'), ((4150, 4166), 'numpy.bincount', 'bincount', (['newlab'], {}), '(newlab)\n', (4158, 4166), False, 'from numpy import square, flatnonzero, ones, zeros_like, cumsum, concatenate, arange, searchsorted, bincount, sort, diff, int8, argsort, array\n'), ((4185, 4208), 'numpy.sort', 'sort', (['bins[:NO_FOF - 1]'], {}), '(bins[:NO_FOF - 1])\n', (4189, 4208), False, 'from numpy import square, flatnonzero, ones, zeros_like, cumsum, concatenate, arange, searchsorted, bincount, sort, diff, int8, argsort, array\n'), ((4309, 4338), 'numpy.argsort', 'np.argsort', (['bins[:NO_FOF - 1]'], {}), '(bins[:NO_FOF - 1])\n', (4319, 4338), True, 'import numpy as np\n'), ((4543, 4559), 'pylab.xlim', 'pl.xlim', (['(0)', '(5600)'], {}), '(0, 5600)\n', (4550, 4559), True, 'import pylab as pl\n'), ((4563, 4579), 'pylab.ylim', 'pl.ylim', (['(0)', '(5600)'], {}), '(0, 5600)\n', (4570, 4579), True, 'import pylab as pl\n'), ((4583, 4592), 'pylab.show', 'pl.show', ([], {}), '()\n', (4590, 4592), True, 'import pylab as pl\n'), ((4715, 4733), 'lizard.log.VerboseTimingLog', 'VerboseTimingLog', ([], {}), '()\n', (4731, 4733), False, 'from lizard.log import VerboseTimingLog\n'), ((4785, 4806), 'numpy.random.RandomState', 'RandomState', ([], {'seed': '(123)'}), '(seed=123)\n', (4796, 4806), False, 'from numpy.random import RandomState\n'), ((1235, 1270), 'numpy.concatenate', 'concatenate', (['(pos, pad_pos)'], {'axis': '(0)'}), '((pos, pad_pos), axis=0)\n', (1246, 1270), False, 'from numpy import square, flatnonzero, ones, zeros_like, cumsum, concatenate, arange, searchsorted, bincount, sort, diff, int8, argsort, array\n'), ((4429, 4458), 'numpy.flatnonzero', 'np.flatnonzero', (['(labels == lab)'], {}), '(labels == lab)\n', (4443, 4458), True, 'import numpy as np\n'), ((4474, 4540), 'pylab.plot', 'pl.plot', (['pos[idx_i][:, 2]', 'pos[idx_i][:, 1]'], {'marker': '""","""', 'ls': '"""none"""'}), "(pos[idx_i][:, 2], pos[idx_i][:, 1], marker=',', ls='none')\n", (4481, 4540), True, 'import pylab as pl\n'), ((1876, 1913), 'numpy.square', 'square', (['(all_pos[idx1] - all_pos[idx2])'], {}), '(all_pos[idx1] - all_pos[idx2])\n', (1882, 1913), False, 'from numpy import square, flatnonzero, ones, zeros_like, cumsum, concatenate, arange, searchsorted, bincount, sort, diff, int8, argsort, array\n'), ((3158, 3174), 'numpy.bincount', 'bincount', (['labels'], {}), '(labels)\n', (3166, 3174), False, 'from numpy import square, flatnonzero, ones, zeros_like, cumsum, concatenate, arange, searchsorted, bincount, sort, diff, int8, argsort, array\n'), ((2446, 2456), 'numpy.diff', 'diff', (['idx1'], {}), '(idx1)\n', (2450, 2456), False, 'from numpy import square, flatnonzero, ones, zeros_like, cumsum, concatenate, arange, searchsorted, bincount, sort, diff, int8, argsort, array\n'), ((2459, 2469), 'numpy.diff', 'diff', (['idx2'], {}), '(idx2)\n', (2463, 2469), False, 'from numpy import square, flatnonzero, ones, zeros_like, cumsum, concatenate, arange, searchsorted, bincount, sort, diff, int8, argsort, array\n')] |
from logger import logger
from ...file_utils import file_exists, dir_exists
from ...path_utils import get_newest_filepath
from ...prompt_utils import weights_scratch_prompt, weights_newest_prompt
class ResumeWeightsChecker:
def __init__(self, resume: bool, resume_path: str=None, weights_save_dir: str=None, weights_extension: str='pth'):
self.resume = resume
self.resume_path = resume_path
self.weights_save_dir = weights_save_dir
self.weights_extension = weights_extension
def _scratch_prompt(self):
start_from_scratch = weights_scratch_prompt()
if start_from_scratch:
self.resume = False
self.resume_path = None
else:
raise Exception
def prompt_if_invalid(self):
if self.resume:
if self.resume_path is None:
if self.weights_save_dir is not None:
if dir_exists(self.weights_save_dir):
self.resume_path = get_newest_filepath(dir_path=self.weights_save_dir, extension=self.weights_extension)
if self.resume_path is None:
logger.warning(f"Couldn't find a .{self.weights_extension} weights file in:\n{self.weights_save_dir}")
self._scratch_prompt()
else:
logger.warning(f"Couldn't find weights dir:\n{self.weights_save_dir}")
self._scratch_prompt()
else:
logger.warning(f"weights_save_dir hasn't been provided for detecting the newest weights path.")
self._scratch_prompt()
else:
if not file_exists(self.resume_path):
logger.warning(f"Couldn't find resume_path:\n{self.resume_path}")
if dir_exists(self.weights_save_dir):
newest_weights_path = get_newest_filepath(dir_path=self.weights_save_dir, extension=self.weights_extension)
if newest_weights_path is not None:
use_newest_weights = weights_newest_prompt(newest_weights_path)
if use_newest_weights:
self.resume_path = newest_weights_path
else:
self._scratch_prompt()
else:
logger.warning(f"Couldn't find newest weights.")
self._scratch_prompt()
else:
self._scratch_prompt()
else:
self.resume_path = None
def get_updated(self) -> (bool, str):
return self.resume, self.resume_path | [
"logger.logger.warning"
] | [((1524, 1629), 'logger.logger.warning', 'logger.warning', (['f"""weights_save_dir hasn\'t been provided for detecting the newest weights path."""'], {}), '(\n f"weights_save_dir hasn\'t been provided for detecting the newest weights path."\n )\n', (1538, 1629), False, 'from logger import logger\n'), ((1755, 1823), 'logger.logger.warning', 'logger.warning', (['f"""Couldn\'t find resume_path:\n{self.resume_path}"""'], {}), '(f"""Couldn\'t find resume_path:\n{self.resume_path}""")\n', (1769, 1823), False, 'from logger import logger\n'), ((1364, 1437), 'logger.logger.warning', 'logger.warning', (['f"""Couldn\'t find weights dir:\n{self.weights_save_dir}"""'], {}), '(f"""Couldn\'t find weights dir:\n{self.weights_save_dir}""")\n', (1378, 1437), False, 'from logger import logger\n'), ((1160, 1275), 'logger.logger.warning', 'logger.warning', (['f"""Couldn\'t find a .{self.weights_extension} weights file in:\n{self.weights_save_dir}"""'], {}), '(\n f"""Couldn\'t find a .{self.weights_extension} weights file in:\n{self.weights_save_dir}"""\n )\n', (1174, 1275), False, 'from logger import logger\n'), ((2432, 2480), 'logger.logger.warning', 'logger.warning', (['f"""Couldn\'t find newest weights."""'], {}), '(f"Couldn\'t find newest weights.")\n', (2446, 2480), False, 'from logger import logger\n')] |
from __future__ import print_function
import os
import sys
from pyspark import SparkContext, SQLContext
import pyspark.sql.functions as sql
import pyspark.sql.types as types
import unicodecsv
from dateutil.parser import parse
sc = SparkContext(appName="BHLParquet")
sqlContext = SQLContext(sc)
def as_int(s):
return None if (s is None) or (len(s.strip()) is 0) else int(s)
def as_date(s):
return None if (s is None) or (len(s.strip()) is 0) else parse(s)
def type_data_item(l):
try:
return (
as_int(l["ItemID"]),
as_int(l["TitleID"]),
as_int(l["ThumbnailPageID"]),
l["BarCode"],
l["MARCItemID"],
l["CallNumber"],
l["VolumeInfo"],
l["ItemURL"],
l["LocalID"],
l["Year"],
l["InstitutionName"],
l["ZQuery"],
as_date(l["CreationDate"])
)
except Exception as e:
print(e)
#raise
return False
def schema_item():
return types.StructType([
types.StructField("itemid", types.IntegerType(), True),
types.StructField("titleid", types.IntegerType(), True),
types.StructField("thumbnailpageid", types.IntegerType(), True),
types.StructField("barcode", types.StringType(), True),
types.StructField("marcitemid", types.StringType(), True),
types.StructField("callnumber", types.StringType(), True),
types.StructField("volumeinfo", types.StringType(), True),
types.StructField("itemurl", types.StringType(), True),
types.StructField("localid", types.StringType(), True),
types.StructField("year", types.StringType(), True),
types.StructField("institutionname", types.StringType(), True),
types.StructField("zquery", types.StringType(), True),
types.StructField("creationdate", types.DateType(), True)
])
def type_data_subject(l):
try:
return (
int(l["TitleID"]),
l["Subject"],
parse(l["CreationDate"])
)
except:
return False
def schema_subject():
return types.StructType([
types.StructField("titleid", types.IntegerType(), True),
types.StructField("subject", types.StringType(), True),
types.StructField("creationdate", types.DateType(), True)
])
# Read a file with python's csv reader into a df - single threaded and
# inefficient but csv reading is not garanteed to be line-paralizable
# and Python's parsing code is more known/hackable than Spark's
def t_gen(fn, parse_method):
i = 1 # start row number at 1 due to header
errors = 0
with open(fn) as f:
# encoding specified as 'utf-8-sig' since dumps have byte order mark
# debugging #2, replacing this line didn't help
#f_tsv = unicodecsv.DictReader(f, dialect="excel-tab")
f_tsv = unicodecsv.DictReader(f, encoding='utf-8-sig', dialect="excel-tab")
for l in f_tsv:
i += 1
row = parse_method(l)
if row is not False:
yield row
else:
errors += 1
print("Error with {0} on line {1}".format(l, i))
if errors > 50:
print("Too many errors, stopping.")
break
def mk_ocr_fn(dir_name, barcode):
return os.path.join(mirror_dir, barcode) + "_djvu.txt"
def get_ocr(barcode):
try:
with open(mk_ocr_fn(mirror_dir, barcode), 'r') as f:
ocr_text = f.read()
except Exception as e:
#print(e)
ocr_text = None
return ocr_text
dataset_date = sys.argv[1]
mirror_dir = "data/mirror"
data_dir = "data/data-{0}".format(dataset_date)
out_dir = "data/bhl-{0}.parquet".format(dataset_date)
if os.path.isdir(out_dir):
print("Output dir {0} exists".format(out_dir))
exit
get_ocr_udf = sql.udf(get_ocr, types.StringType())
fn = os.path.join(data_dir, "item.txt")
# Optional limit for testing, add this to the chain as second step
# .sample(withReplacement=False, fraction=0.001) \
sqlContext.createDataFrame(t_gen(fn, type_data_item), schema_item()) \
.withColumn("ocrtext", get_ocr_udf(sql.col("barcode"))) \
.write.parquet(out_dir)
# Example run on Elk (16 thread single machine)
#real 84m21.818s
#user 198m57.612s
#sys 15m19.662s
# Example run on okapi (128 thread single machine)
#real 41m13.984s
#user 482m34.084s
#sys 278m12.404s
| [
"dateutil.parser.parse",
"pyspark.sql.types.DateType",
"os.path.join",
"pyspark.sql.types.IntegerType",
"pyspark.sql.functions.col",
"os.path.isdir",
"unicodecsv.DictReader",
"pyspark.SQLContext",
"pyspark.sql.types.StringType",
"pyspark.SparkContext"
] | [((233, 267), 'pyspark.SparkContext', 'SparkContext', ([], {'appName': '"""BHLParquet"""'}), "(appName='BHLParquet')\n", (245, 267), False, 'from pyspark import SparkContext, SQLContext\n'), ((281, 295), 'pyspark.SQLContext', 'SQLContext', (['sc'], {}), '(sc)\n', (291, 295), False, 'from pyspark import SparkContext, SQLContext\n'), ((3817, 3839), 'os.path.isdir', 'os.path.isdir', (['out_dir'], {}), '(out_dir)\n', (3830, 3839), False, 'import os\n'), ((3960, 3994), 'os.path.join', 'os.path.join', (['data_dir', '"""item.txt"""'], {}), "(data_dir, 'item.txt')\n", (3972, 3994), False, 'import os\n'), ((3935, 3953), 'pyspark.sql.types.StringType', 'types.StringType', ([], {}), '()\n', (3951, 3953), True, 'import pyspark.sql.types as types\n'), ((458, 466), 'dateutil.parser.parse', 'parse', (['s'], {}), '(s)\n', (463, 466), False, 'from dateutil.parser import parse\n'), ((2905, 2972), 'unicodecsv.DictReader', 'unicodecsv.DictReader', (['f'], {'encoding': '"""utf-8-sig"""', 'dialect': '"""excel-tab"""'}), "(f, encoding='utf-8-sig', dialect='excel-tab')\n", (2926, 2972), False, 'import unicodecsv\n'), ((3381, 3414), 'os.path.join', 'os.path.join', (['mirror_dir', 'barcode'], {}), '(mirror_dir, barcode)\n', (3393, 3414), False, 'import os\n'), ((2042, 2066), 'dateutil.parser.parse', 'parse', (["l['CreationDate']"], {}), "(l['CreationDate'])\n", (2047, 2066), False, 'from dateutil.parser import parse\n'), ((1088, 1107), 'pyspark.sql.types.IntegerType', 'types.IntegerType', ([], {}), '()\n', (1105, 1107), True, 'import pyspark.sql.types as types\n'), ((1153, 1172), 'pyspark.sql.types.IntegerType', 'types.IntegerType', ([], {}), '()\n', (1170, 1172), True, 'import pyspark.sql.types as types\n'), ((1226, 1245), 'pyspark.sql.types.IntegerType', 'types.IntegerType', ([], {}), '()\n', (1243, 1245), True, 'import pyspark.sql.types as types\n'), ((1291, 1309), 'pyspark.sql.types.StringType', 'types.StringType', ([], {}), '()\n', (1307, 1309), True, 'import pyspark.sql.types as types\n'), ((1358, 1376), 'pyspark.sql.types.StringType', 'types.StringType', ([], {}), '()\n', (1374, 1376), True, 'import pyspark.sql.types as types\n'), ((1425, 1443), 'pyspark.sql.types.StringType', 'types.StringType', ([], {}), '()\n', (1441, 1443), True, 'import pyspark.sql.types as types\n'), ((1492, 1510), 'pyspark.sql.types.StringType', 'types.StringType', ([], {}), '()\n', (1508, 1510), True, 'import pyspark.sql.types as types\n'), ((1556, 1574), 'pyspark.sql.types.StringType', 'types.StringType', ([], {}), '()\n', (1572, 1574), True, 'import pyspark.sql.types as types\n'), ((1620, 1638), 'pyspark.sql.types.StringType', 'types.StringType', ([], {}), '()\n', (1636, 1638), True, 'import pyspark.sql.types as types\n'), ((1681, 1699), 'pyspark.sql.types.StringType', 'types.StringType', ([], {}), '()\n', (1697, 1699), True, 'import pyspark.sql.types as types\n'), ((1753, 1771), 'pyspark.sql.types.StringType', 'types.StringType', ([], {}), '()\n', (1769, 1771), True, 'import pyspark.sql.types as types\n'), ((1816, 1834), 'pyspark.sql.types.StringType', 'types.StringType', ([], {}), '()\n', (1832, 1834), True, 'import pyspark.sql.types as types\n'), ((1885, 1901), 'pyspark.sql.types.DateType', 'types.DateType', ([], {}), '()\n', (1899, 1901), True, 'import pyspark.sql.types as types\n'), ((2200, 2219), 'pyspark.sql.types.IntegerType', 'types.IntegerType', ([], {}), '()\n', (2217, 2219), True, 'import pyspark.sql.types as types\n'), ((2265, 2283), 'pyspark.sql.types.StringType', 'types.StringType', ([], {}), '()\n', (2281, 2283), True, 'import pyspark.sql.types as types\n'), ((2334, 2350), 'pyspark.sql.types.DateType', 'types.DateType', ([], {}), '()\n', (2348, 2350), True, 'import pyspark.sql.types as types\n'), ((4224, 4242), 'pyspark.sql.functions.col', 'sql.col', (['"""barcode"""'], {}), "('barcode')\n", (4231, 4242), True, 'import pyspark.sql.functions as sql\n')] |
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from __future__ import print_function
from crhelper import CfnResource
import logging
import boto3
import os
from requests_aws4auth import AWS4Auth
from elasticsearch import Elasticsearch, RequestsHttpConnection, RequestError
logger = logging.getLogger(__name__)
# Initialise the helper, all inputs are optional, this example shows the defaults
helper = CfnResource(json_logging=False, log_level='DEBUG', boto_level='CRITICAL')
service = 'es'
INDEXES = ["person_index", "vehicle_registration_index"]
es = None
try:
host = os.environ['ES_HOST']
session = boto3.Session()
credentials = session.get_credentials()
region = session.region_name
awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)
es = Elasticsearch(
hosts=[{'host': host, 'port': 443}],
http_auth=awsauth,
use_ssl=True,
verify_certs=True,
connection_class=RequestsHttpConnection,
retry_on_timeout=True,
max_retries=3
)
except Exception as e:
helper.init_failure(e)
@helper.create
def create(event, context):
logger.info("Initiating index creation")
helper.Data.update({"Status": "Initiated"})
for index in INDEXES:
try:
es.indices.create(index=index, body={'settings': {'index': {'gc_deletes': '1d'}}})
except RequestError as e:
if e.error == "resource_already_exists_exception":
es.indices.put_settings(index=index, body={'gc_deletes': '1d'})
else:
raise e
@helper.update
def update(event, context):
# no op
pass
@helper.delete
def delete(event, context):
# no op
pass
def lambda_handler(event, context):
helper(event, context)
| [
"logging.getLogger",
"requests_aws4auth.AWS4Auth",
"elasticsearch.Elasticsearch",
"boto3.Session",
"crhelper.CfnResource"
] | [((1226, 1253), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1243, 1253), False, 'import logging\n'), ((1345, 1418), 'crhelper.CfnResource', 'CfnResource', ([], {'json_logging': '(False)', 'log_level': '"""DEBUG"""', 'boto_level': '"""CRITICAL"""'}), "(json_logging=False, log_level='DEBUG', boto_level='CRITICAL')\n", (1356, 1418), False, 'from crhelper import CfnResource\n'), ((1555, 1570), 'boto3.Session', 'boto3.Session', ([], {}), '()\n', (1568, 1570), False, 'import boto3\n'), ((1662, 1772), 'requests_aws4auth.AWS4Auth', 'AWS4Auth', (['credentials.access_key', 'credentials.secret_key', 'region', 'service'], {'session_token': 'credentials.token'}), '(credentials.access_key, credentials.secret_key, region, service,\n session_token=credentials.token)\n', (1670, 1772), False, 'from requests_aws4auth import AWS4Auth\n'), ((1778, 1968), 'elasticsearch.Elasticsearch', 'Elasticsearch', ([], {'hosts': "[{'host': host, 'port': 443}]", 'http_auth': 'awsauth', 'use_ssl': '(True)', 'verify_certs': '(True)', 'connection_class': 'RequestsHttpConnection', 'retry_on_timeout': '(True)', 'max_retries': '(3)'}), "(hosts=[{'host': host, 'port': 443}], http_auth=awsauth,\n use_ssl=True, verify_certs=True, connection_class=\n RequestsHttpConnection, retry_on_timeout=True, max_retries=3)\n", (1791, 1968), False, 'from elasticsearch import Elasticsearch, RequestsHttpConnection, RequestError\n')] |
import numpy as np
from numpy.core.fromnumeric import size
class BrownionPathGen:
def __init__(self, NumPaths, Maturity):
self.NumPaths = NumPaths
self.Maturity = Maturity # this is in days
# this is not optimal lets make a matrix of the std normal and then perform the operation to
# change its mean and std but for now lets leave it as it is
def GenerateCrossSection(self, Last_Mean, DiffTime):
Normals = np.random.standard_normal(size=[self.NumPaths, 1])
# have to adjust for leap year
# between two crosssection the time spend it difftime so var is also proportional to diff time
Var = DiffTime/365
Std = Var**0.5
# so basically the next cross-section will be data which was produced by last cross secion +
# std*RN . this can be proved to produce normal dist with mean given by last cross section and std .
Adjusted_Normals = Std*Normals+Last_Mean
return Adjusted_Normals
def GeneratePaths(self):
Path = np.zeros([self.NumPaths, 1])
Paths = [Path]
# lets find out a matrix operation to do this . will be much faster
# Maturity is a number for now but should be a date which should be compared to the global date
for i in range(0, self.Maturity - 1):
# this difftime is for now 1 but we may change it in future to make it more advance
Paths.append(self.GenerateCrossSection(
Last_Mean=Paths[i], DiffTime=1))
return Paths
| [
"numpy.random.standard_normal",
"numpy.zeros"
] | [((453, 503), 'numpy.random.standard_normal', 'np.random.standard_normal', ([], {'size': '[self.NumPaths, 1]'}), '(size=[self.NumPaths, 1])\n', (478, 503), True, 'import numpy as np\n'), ((1037, 1065), 'numpy.zeros', 'np.zeros', (['[self.NumPaths, 1]'], {}), '([self.NumPaths, 1])\n', (1045, 1065), True, 'import numpy as np\n')] |
"""
Module defining transfer functions
"""
from typing import List, Optional, Dict, Any, Union
from pydantic import validator, constr
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from resistics.common import Metadata
class Component(Metadata):
"""
Data class for a single component in a Transfer function
Example
-------
>>> from resistics.transfunc import Component
>>> component = Component(real=[1, 2, 3, 4, 5], imag=[-5, -4, -3, -2 , -1])
>>> component.get_value(0)
(1-5j)
>>> component.to_numpy()
array([1.-5.j, 2.-4.j, 3.-3.j, 4.-2.j, 5.-1.j])
"""
real: List[float]
"""The real part of the component"""
imag: List[float]
"""The complex part of the component"""
def get_value(self, eval_idx: int) -> complex:
"""Get the value for an evaluation frequency"""
return self.real[eval_idx] + 1j * self.imag[eval_idx]
def to_numpy(self) -> np.ndarray:
"""Get the component as a numpy complex array"""
return np.array(self.real) + 1j * np.array(self.imag)
def get_component_key(out_chan: str, in_chan: str) -> str:
"""
Get key for out channel and in channel combination in the solution
Parameters
----------
out_chan : str
The output channel
in_chan : str
The input channel
Returns
-------
str
The component key
Examples
--------
>>> from resistics.regression import get_component_key
>>> get_component_key("Ex", "Hy")
'ExHy'
"""
return f"{out_chan}{in_chan}"
class TransferFunction(Metadata):
"""
Define a generic transfer function
This class is a describes generic transfer function, including:
- The output channels for the transfer function
- The input channels for the transfer function
- The cross channels for the transfer function
The cross channels are the channels that will be used to calculate out the
cross powers for the regression.
This generic parent class has no implemented plotting function. However,
child classes may have a plotting function as different transfer functions
may need different types of plots.
.. note::
Users interested in writing a custom transfer function should inherit
from this generic Transfer function
See Also
--------
ImpandanceTensor : Transfer function for the MT impedance tensor
Tipper : Transfer function for the MT tipper
Examples
--------
A generic example
>>> tf = TransferFunction(variation="example", out_chans=["bye", "see you", "ciao"], in_chans=["hello", "hi_there"])
>>> print(tf.to_string())
| bye | | bye_hello bye_hi_there | | hello |
| see you | = | see you_hello see you_hi_there | | hi_there |
| ciao | | ciao_hello ciao_hi_there |
Combining the impedance tensor and the tipper into one TransferFunction
>>> tf = TransferFunction(variation="combined", out_chans=["Ex", "Ey"], in_chans=["Hx", "Hy", "Hz"])
>>> print(tf.to_string())
| Ex | | Ex_Hx Ex_Hy Ex_Hz | | Hx |
| Ey | = | Ey_Hx Ey_Hy Ey_Hz | | Hy |
| Hz |
"""
_types: Dict[str, type] = {}
"""Store types which will help automatic instantiation"""
name: Optional[str] = None
"""The name of the transfer function, this will be set automatically"""
variation: constr(max_length=16) = "generic"
"""A short additional bit of information about this variation"""
out_chans: List[str]
"""The output channels"""
in_chans: List[str]
"""The input channels"""
cross_chans: Optional[List[str]] = None
"""The channels to use for calculating the cross spectra"""
n_out: Optional[int] = None
"""The number of output channels"""
n_in: Optional[int] = None
"""The number of input channels"""
n_cross: Optional[int] = None
"""The number of cross power channels"""
def __init_subclass__(cls) -> None:
"""
Used to automatically register child transfer functions in `_types`
When a TransferFunction child class is imported, it is added to the base
TransferFunction _types variable. Later, this dictionary of class types
can be used to initialise a specific child transfer function from a
dictonary as long as that specific child transfer fuction has already
been imported and it is called from a pydantic class that will validate
the inputs.
The intention of this method is to support initialising transfer
functions from JSON files. This is a similar approach to
ResisticsProcess.
"""
cls._types[cls.__name__] = cls
@classmethod
def __get_validators__(cls):
"""Get the validators that will be used by pydantic"""
yield cls.validate
@classmethod
def validate(
cls, value: Union["TransferFunction", Dict[str, Any]]
) -> "TransferFunction":
"""
Validate a TransferFunction
Parameters
----------
value : Union[TransferFunction, Dict[str, Any]]
A TransferFunction child class or a dictionary
Returns
-------
TransferFunction
A TransferFunction or TransferFunction child class
Raises
------
ValueError
If the value is neither a TransferFunction or a dictionary
KeyError
If name is not in the dictionary
ValueError
If initialising from dictionary fails
Examples
--------
The following example will show how a child TransferFunction class
can be instantiated using a dictionary and the parent TransferFunction
(but only as long as that child class has been imported).
>>> from resistics.transfunc import TransferFunction
Show known TransferFunction types in built into resistics
>>> for entry in TransferFunction._types.items():
... print(entry)
('ImpedanceTensor', <class 'resistics.transfunc.ImpedanceTensor'>)
('Tipper', <class 'resistics.transfunc.Tipper'>)
Now let's initialise an ImpedanceTensor from the base TransferFunction
and a dictionary.
>>> mytf = {"name": "ImpedanceTensor", "variation": "ecross", "cross_chans": ["Ex", "Ey"]}
>>> test = TransferFunction(**mytf)
Traceback (most recent call last):
...
KeyError: 'out_chans'
This is not quite what we were expecting. The generic TransferFunction
requires out_chans to be defined, but they are not in the dictionary as
the ImpedanceTensor child class defaults these. To get this to work,
instead use the validate class method. This is the class method used by
pydantic when instantiating.
>>> mytf = {"name": "ImpedanceTensor", "variation": "ecross", "cross_chans": ["Ex", "Ey"]}
>>> test = TransferFunction.validate(mytf)
>>> test.summary()
{
'name': 'ImpedanceTensor',
'variation': 'ecross',
'out_chans': ['Ex', 'Ey'],
'in_chans': ['Hx', 'Hy'],
'cross_chans': ['Ex', 'Ey'],
'n_out': 2,
'n_in': 2,
'n_cross': 2
}
That's more like it. This will raise errors if an unknown type of
TransferFunction is received.
>>> mytf = {"name": "NewTF", "cross_chans": ["Ex", "Ey"]}
>>> test = TransferFunction.validate(mytf)
Traceback (most recent call last):
...
ValueError: Unable to initialise NewTF from dictionary
Or if the dictionary does not have a name key
>>> mytf = {"cross_chans": ["Ex", "Ey"]}
>>> test = TransferFunction.validate(mytf)
Traceback (most recent call last):
...
KeyError: 'No name provided for initialisation of TransferFunction'
Unexpected inputs will also raise an error
>>> test = TransferFunction.validate(5)
Traceback (most recent call last):
...
ValueError: TransferFunction unable to initialise from <class 'int'>
"""
if isinstance(value, TransferFunction):
return value
if not isinstance(value, dict):
raise ValueError(
f"TransferFunction unable to initialise from {type(value)}"
)
if "name" not in value:
raise KeyError("No name provided for initialisation of TransferFunction")
# check if it is a TransferFunction
name = value.pop("name")
if name == "TransferFunction":
return cls(**value)
# check other known Transfer Functions
try:
return cls._types[name](**value)
except Exception:
raise ValueError(f"Unable to initialise {name} from dictionary")
@validator("name", always=True)
def validate_name(cls, value: Union[str, None]) -> str:
"""Inialise the name attribute of the transfer function"""
if value is None:
return cls.__name__
return value
@validator("cross_chans", always=True)
def validate_cross_chans(
cls, value: Union[None, List[str]], values: Dict[str, Any]
) -> List[str]:
"""Validate cross spectra channels"""
if value is None:
return values["in_chans"]
return value
@validator("n_out", always=True)
def validate_n_out(cls, value: Union[None, int], values: Dict[str, Any]) -> int:
"""Validate number of output channels"""
if value is None:
return len(values["out_chans"])
return value
@validator("n_in", always=True)
def validate_n_in(cls, value: Union[None, int], values: Dict[str, Any]) -> int:
"""Validate number of input channels"""
if value is None:
return len(values["in_chans"])
return value
@validator("n_cross", always=True)
def validate_n_cross(cls, value: Union[None, int], values: Dict[str, Any]) -> int:
"""Validate number of cross channels"""
if value is None:
return len(values["cross_chans"])
return value
def n_eqns_per_output(self) -> int:
"""Get the number of equations per output"""
return len(self.cross_chans)
def n_regressors(self) -> int:
"""Get the number of regressors"""
return self.n_in
def to_string(self):
"""Get the transfer function as as string"""
n_lines = max(len(self.in_chans), len(self.out_chans))
lens = [len(x) for x in self.in_chans] + [len(x) for x in self.out_chans]
max_len = max(lens)
line_equals = (n_lines - 1) // 2
outstr = ""
for il in range(n_lines):
out_chan = self._out_chan_string(il, max_len)
in_chan = self._in_chan_string(il, max_len)
tensor = self._tensor_string(il, max_len)
eq = "=" if il == line_equals else " "
outstr += f"{out_chan} {eq} {tensor} {in_chan}\n"
return outstr.rstrip("\n")
def _out_chan_string(self, il: int, max_len: int) -> str:
"""Get the out channels string"""
if il >= self.n_out:
empty_len = max_len + 4
return f"{'':{empty_len}s}"
return f"| { self.out_chans[il]:{max_len}s} |"
def _in_chan_string(self, il: int, max_len: int) -> str:
"""Get the in channel string"""
if il >= self.n_in:
return ""
return f"| { self.in_chans[il]:{max_len}s} |"
def _tensor_string(self, il: int, max_len: int) -> str:
"""Get the tensor string"""
if il >= self.n_out:
element_len = ((max_len * 2 + 1) + 1) * self.n_in + 3
return f"{'':{element_len}s}"
elements = "| "
for chan in self.in_chans:
component = f"{self.out_chans[il]}_{chan}"
elements += f"{component:{2*max_len + 1}s} "
elements += "|"
return elements
class ImpedanceTensor(TransferFunction):
"""
Standard magnetotelluric impedance tensor
Notes
-----
Information about data units
- Magnetic permeability in nT . m / A
- Electric (E) data is in mV/m
- Magnetic (H) data is in nT
- Z = E/H is in mV / m . nT
- Units of resistance = Ohm = V / A
Examples
--------
>>> from resistics.transfunc import ImpedanceTensor
>>> tf = ImpedanceTensor()
>>> print(tf.to_string())
| Ex | = | Ex_Hx Ex_Hy | | Hx |
| Ey | | Ey_Hx Ey_Hy | | Hy |
"""
variation: constr(max_length=16) = "default"
out_chans: List[str] = ["Ex", "Ey"]
in_chans: List[str] = ["Hx", "Hy"]
@staticmethod
def get_resistivity(periods: np.ndarray, component: Component) -> np.ndarray:
"""
Get apparent resistivity for a component
Parameters
----------
periods : np.ndarray
The periods of the component
component : Component
The component values
Returns
-------
np.ndarray
Apparent resistivity
"""
squared = np.power(np.absolute(component.to_numpy()), 2)
return 0.2 * periods * squared
@staticmethod
def get_phase(key: str, component: Component) -> np.ndarray:
"""
Get the phase for the component
.. note::
Components ExHx and ExHy are wrapped around in [0,90]
Parameters
----------
key : str
The component name
component : Component
The component values
Returns
-------
np.ndarray
The phase values
"""
phase = np.angle(component.to_numpy())
# unwrap into specific quadrant and convert to degrees
phase = np.unwrap(phase) * 180 / np.pi
if key == "ExHx" or key == "ExHy":
phase = np.mod(phase, 360) - 180
return phase
@staticmethod
def get_fig(
x_lim: Optional[List[float]] = None,
res_lim: Optional[List[float]] = None,
phs_lim: Optional[List[float]] = None,
) -> go.Figure:
"""
Get a figure for plotting the ImpedanceTensor
Parameters
----------
x_lim : Optional[List[float]], optional
The x limits, to be provided as powers of 10, by default None. For
example, for 0.001, use -3
res_lim : Optional[List[float]], optional
The y limits for resistivity, to be provided as powers of 10, by
default None. For example, for 1000, use 3
phs_lim : Optional[List[float]], optional
The phase limits, by default None
Returns
-------
go.Figure
Plotly figure
"""
from resistics.plot import PLOTLY_MARGIN, PLOTLY_TEMPLATE
fig = make_subplots(
rows=2,
cols=1,
shared_xaxes=True,
vertical_spacing=0.08,
subplot_titles=["Apparent resistivity", "Phase"],
)
# apparent resistivity axes
fig.update_xaxes(type="log", showticklabels=True, row=1, col=1)
fig.update_yaxes(title_text="App. resistivity (Ohm m)", row=1, col=1)
fig.update_yaxes(type="log", row=1, col=1)
if x_lim is not None:
fig.update_xaxes(range=x_lim, row=1, col=1)
if res_lim is not None:
fig.update_yaxes(range=res_lim, row=1, col=1)
# phase axes
fig.update_xaxes(title_text="Period (s)", type="log", row=2, col=1)
fig.update_xaxes(showticklabels=True, row=2, col=1)
# fig.update_yaxes(scaleanchor="x", scaleratio=1, row=1, col=1)
fig.update_yaxes(title_text="Phase (degrees)", row=2, col=1)
if phs_lim is not None:
fig.update_yaxes(range=phs_lim, row=2, col=1)
# update the layout
fig.update_layout(template=PLOTLY_TEMPLATE, margin=dict(PLOTLY_MARGIN))
return fig
@staticmethod
def plot(
freqs: List[float],
components: Dict[str, Component],
fig: Optional[go.Figure] = None,
to_plot: Optional[List[str]] = None,
legend: str = "Impedance tensor",
x_lim: Optional[List[float]] = None,
res_lim: Optional[List[float]] = None,
phs_lim: Optional[List[float]] = None,
symbol: Optional[str] = "circle",
) -> go.Figure:
"""
Plot the Impedance tensor
Parameters
----------
freqs : List[float]
The frequencies where the impedance tensor components have been
calculated
components : Dict[str, Component]
The component data
fig : Optional[go.Figure], optional
Figure to add to, by default None
to_plot : Optional[List[str]], optional
The components to plot, by default all of the components of the
impedance tensor
legend : str, optional
Legend prefix for the components, by default "Impedance tensor"
x_lim : Optional[List[float]], optional
The x limits, to be provided as powers of 10, by default None. For
example, for 0.001, use -3. Only used when a figure is not provided.
res_lim : Optional[List[float]], optional
The y limits for resistivity, to be provided as powers of 10, by
default None. For example, for 1000, use 3. Only used when a figure
is not provided.
phs_lim : Optional[List[float]], optional
The phase limits, by default None. Only used when a figure is not
provided.
symbol : Optional[str], optional
The marker symbol to use, by default "circle"
Returns
-------
go.Figure
[description]
"""
if fig is None:
fig = ImpedanceTensor.get_fig(x_lim=x_lim, res_lim=res_lim, phs_lim=phs_lim)
if to_plot is None:
to_plot = ["ExHy", "EyHx", "ExHx", "EyHy"]
periods = np.reciprocal(freqs)
colors = {"ExHx": "orange", "EyHy": "green", "ExHy": "red", "EyHx": "blue"}
for comp in to_plot:
res = ImpedanceTensor.get_resistivity(periods, components[comp])
phs = ImpedanceTensor.get_phase(comp, components[comp])
comp_legend = f"{legend} - {comp}"
scatter = go.Scatter(
x=periods,
y=res,
mode="lines+markers",
marker=dict(color=colors[comp], symbol=symbol),
line=dict(color=colors[comp]),
name=comp_legend,
legendgroup=comp_legend,
)
fig.add_trace(scatter, row=1, col=1)
scatter = go.Scatter(
x=periods,
y=phs,
mode="lines+markers",
marker=dict(color=colors[comp], symbol=symbol),
line=dict(color=colors[comp]),
name=comp_legend,
legendgroup=comp_legend,
showlegend=False,
)
fig.add_trace(scatter, row=2, col=1)
return fig
class Tipper(TransferFunction):
"""
Magnetotelluric tipper
The tipper components are Tx = HzHx and Ty = HzHy
The tipper length is sqrt(Re(Tx)^2 + Re(Ty)^2)
The tipper angle is arctan (Re(Ty)/Re(Tx))
Notes
-----
Information about units
- Tipper T = H/H is dimensionless
Examples
--------
>>> from resistics.transfunc import Tipper
>>> tf = Tipper()
>>> print(tf.to_string())
| Hz | = | Hz_Hx Hz_Hy | | Hx |
| Hy |
"""
variation: constr(max_length=16) = "default"
out_chans: List[str] = ["Hz"]
in_chans: List[str] = ["Hx", "Hy"]
def get_length(self, components: Dict[str, Component]) -> np.ndarray:
"""Get the tipper length"""
txRe = components["HzHx"].real
tyRe = components["HzHy"].real
return np.sqrt(np.power(txRe, 2) + np.power(tyRe, 2))
def get_real_angle(self, components: Dict[str, Component]) -> np.ndarray:
"""Get the real angle"""
txRe = np.array(components["HzHx"].real)
tyRe = np.array(components["HzHy"].real)
return np.arctan(tyRe / txRe) * 180 / np.pi
def get_imag_angle(self, components: Dict[str, Component]) -> np.ndarray:
"""Get the imaginary angle"""
txIm = np.array(components["HzHx"].imag)
tyIm = np.array(components["HzHy"].imag)
return np.arctan(tyIm / txIm) * 180 / np.pi
def plot(
self,
freqs: List[float],
components: Dict[str, Component],
x_lim: Optional[List[float]] = None,
len_lim: Optional[List[float]] = None,
ang_lim: Optional[List[float]] = None,
) -> go.Figure:
"""
Plot the impedance tensor
.. warning::
This probably needs further checking and verification
Parameters
----------
freqs : List[float]
The x axis frequencies
components : Dict[str, Component]
The component data
x_lim : Optional[List[float]], optional
The x limits, to be provided as powers of 10, by default None. For
example, for 0.001, use -3
len_lim : Optional[List[float]], optional
The y limits for tipper length, to be provided as powers of 10, by
default None. For example, for 1000, use 3
ang_lim : Optional[List[float]], optional
The angle limits, by default None
Returns
-------
go.Figure
Plotly figure
"""
import warnings
from plotly.subplots import make_subplots
warnings.warn("Plotting of tippers needs further verification")
periods = np.reciprocal(freqs)
if x_lim is None:
x_lim = [-3, 5]
if len_lim is None:
len_lim = [-2, 6]
if ang_lim is None:
ang_lim = [-10, 100]
fig = make_subplots(
rows=2,
cols=1,
shared_xaxes=True,
vertical_spacing=0.08,
subplot_titles=["Length", "Angles"],
)
fig.update_layout(width=1000, autosize=True)
# x axes
fig.update_xaxes(title_text="Period (s)", type="log", range=x_lim, row=1, col=1)
fig.update_xaxes(showticklabels=True, row=1, col=1)
fig.update_xaxes(title_text="Period (s)", type="log", range=x_lim, row=2, col=1)
fig.update_xaxes(showticklabels=True, row=2, col=1)
# y axes
fig.update_yaxes(title_text="Tipper length", row=1, col=1)
# fig.update_yaxes(type="log", row=1, col=1)
# fig.update_yaxes(scaleanchor="x", scaleratio=1, row=1, col=1)
fig.update_yaxes(title_text="Angle (degrees)", row=2, col=1)
# plot the tipper length
scatter = go.Scatter(
x=periods,
y=self.get_length(components),
mode="lines+markers",
marker=dict(color="red"),
line=dict(color="red"),
name="Tipper length",
)
fig.add_trace(scatter, row=1, col=1)
# plot the real angle
scatter = go.Scatter(
x=periods,
y=self.get_real_angle(components),
mode="lines+markers",
marker=dict(color="green"),
line=dict(color="green"),
name="Real angle",
)
fig.add_trace(scatter, row=2, col=1)
# plot the imag angle
scatter = go.Scatter(
x=periods,
y=self.get_imag_angle(components),
mode="lines+markers",
marker=dict(color="blue"),
line=dict(color="blue"),
name="Imag angle",
)
fig.add_trace(scatter, row=2, col=1)
return fig
| [
"plotly.subplots.make_subplots",
"pydantic.validator",
"numpy.reciprocal",
"numpy.power",
"pydantic.constr",
"numpy.unwrap",
"numpy.array",
"warnings.warn",
"numpy.mod",
"numpy.arctan"
] | [((3479, 3500), 'pydantic.constr', 'constr', ([], {'max_length': '(16)'}), '(max_length=16)\n', (3485, 3500), False, 'from pydantic import validator, constr\n'), ((8972, 9002), 'pydantic.validator', 'validator', (['"""name"""'], {'always': '(True)'}), "('name', always=True)\n", (8981, 9002), False, 'from pydantic import validator, constr\n'), ((9215, 9252), 'pydantic.validator', 'validator', (['"""cross_chans"""'], {'always': '(True)'}), "('cross_chans', always=True)\n", (9224, 9252), False, 'from pydantic import validator, constr\n'), ((9507, 9538), 'pydantic.validator', 'validator', (['"""n_out"""'], {'always': '(True)'}), "('n_out', always=True)\n", (9516, 9538), False, 'from pydantic import validator, constr\n'), ((9770, 9800), 'pydantic.validator', 'validator', (['"""n_in"""'], {'always': '(True)'}), "('n_in', always=True)\n", (9779, 9800), False, 'from pydantic import validator, constr\n'), ((10029, 10062), 'pydantic.validator', 'validator', (['"""n_cross"""'], {'always': '(True)'}), "('n_cross', always=True)\n", (10038, 10062), False, 'from pydantic import validator, constr\n'), ((12687, 12708), 'pydantic.constr', 'constr', ([], {'max_length': '(16)'}), '(max_length=16)\n', (12693, 12708), False, 'from pydantic import validator, constr\n'), ((19821, 19842), 'pydantic.constr', 'constr', ([], {'max_length': '(16)'}), '(max_length=16)\n', (19827, 19842), False, 'from pydantic import validator, constr\n'), ((14981, 15106), 'plotly.subplots.make_subplots', 'make_subplots', ([], {'rows': '(2)', 'cols': '(1)', 'shared_xaxes': '(True)', 'vertical_spacing': '(0.08)', 'subplot_titles': "['Apparent resistivity', 'Phase']"}), "(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.08,\n subplot_titles=['Apparent resistivity', 'Phase'])\n", (14994, 15106), False, 'from plotly.subplots import make_subplots\n'), ((18166, 18186), 'numpy.reciprocal', 'np.reciprocal', (['freqs'], {}), '(freqs)\n', (18179, 18186), True, 'import numpy as np\n'), ((20306, 20339), 'numpy.array', 'np.array', (["components['HzHx'].real"], {}), "(components['HzHx'].real)\n", (20314, 20339), True, 'import numpy as np\n'), ((20355, 20388), 'numpy.array', 'np.array', (["components['HzHy'].real"], {}), "(components['HzHy'].real)\n", (20363, 20388), True, 'import numpy as np\n'), ((20573, 20606), 'numpy.array', 'np.array', (["components['HzHx'].imag"], {}), "(components['HzHx'].imag)\n", (20581, 20606), True, 'import numpy as np\n'), ((20622, 20655), 'numpy.array', 'np.array', (["components['HzHy'].imag"], {}), "(components['HzHy'].imag)\n", (20630, 20655), True, 'import numpy as np\n'), ((21894, 21957), 'warnings.warn', 'warnings.warn', (['"""Plotting of tippers needs further verification"""'], {}), "('Plotting of tippers needs further verification')\n", (21907, 21957), False, 'import warnings\n'), ((21977, 21997), 'numpy.reciprocal', 'np.reciprocal', (['freqs'], {}), '(freqs)\n', (21990, 21997), True, 'import numpy as np\n'), ((22186, 22298), 'plotly.subplots.make_subplots', 'make_subplots', ([], {'rows': '(2)', 'cols': '(1)', 'shared_xaxes': '(True)', 'vertical_spacing': '(0.08)', 'subplot_titles': "['Length', 'Angles']"}), "(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.08,\n subplot_titles=['Length', 'Angles'])\n", (22199, 22298), False, 'from plotly.subplots import make_subplots\n'), ((1063, 1082), 'numpy.array', 'np.array', (['self.real'], {}), '(self.real)\n', (1071, 1082), True, 'import numpy as np\n'), ((1090, 1109), 'numpy.array', 'np.array', (['self.imag'], {}), '(self.imag)\n', (1098, 1109), True, 'import numpy as np\n'), ((13927, 13943), 'numpy.unwrap', 'np.unwrap', (['phase'], {}), '(phase)\n', (13936, 13943), True, 'import numpy as np\n'), ((14021, 14039), 'numpy.mod', 'np.mod', (['phase', '(360)'], {}), '(phase, 360)\n', (14027, 14039), True, 'import numpy as np\n'), ((20140, 20157), 'numpy.power', 'np.power', (['txRe', '(2)'], {}), '(txRe, 2)\n', (20148, 20157), True, 'import numpy as np\n'), ((20160, 20177), 'numpy.power', 'np.power', (['tyRe', '(2)'], {}), '(tyRe, 2)\n', (20168, 20177), True, 'import numpy as np\n'), ((20404, 20426), 'numpy.arctan', 'np.arctan', (['(tyRe / txRe)'], {}), '(tyRe / txRe)\n', (20413, 20426), True, 'import numpy as np\n'), ((20671, 20693), 'numpy.arctan', 'np.arctan', (['(tyIm / txIm)'], {}), '(tyIm / txIm)\n', (20680, 20693), True, 'import numpy as np\n')] |
import codecs
from setuptools import setup
from setuptools import find_packages
with codecs.open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
with codecs.open('Changelog.rst', 'r', 'utf-8') as f:
changes = f.read()
long_description = '\n\n' + readme + '\n\n' + changes
setup(
name='pytaxize',
version='0.5.9251',
description='Taxonomic toolbelt for Python',
long_description = long_description,
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/sckott/pytaxize',
license = 'MIT',
packages = find_packages(exclude=['test-*']),
install_requires=['pandas','requests>=2.7.0','lxml'],
extras_require={
'test': ['vcrpy', 'vcrpy-unittest'],
},
data_files=[('pytaxize/data', ['data/apg_orders.csv', 'data/apg_families.csv',
'data/plantGenusNames.csv', 'data/plantNames.csv', 'data/rank_ref.csv'] )],
classifiers = (
'Development Status :: 3 - Alpha',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3'
)
)
| [
"codecs.open",
"setuptools.find_packages"
] | [((86, 125), 'codecs.open', 'codecs.open', (['"""README.rst"""', '"""r"""', '"""utf-8"""'], {}), "('README.rst', 'r', 'utf-8')\n", (97, 125), False, 'import codecs\n'), ((160, 202), 'codecs.open', 'codecs.open', (['"""Changelog.rst"""', '"""r"""', '"""utf-8"""'], {}), "('Changelog.rst', 'r', 'utf-8')\n", (171, 202), False, 'import codecs\n'), ((558, 591), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['test-*']"}), "(exclude=['test-*'])\n", (571, 591), False, 'from setuptools import find_packages\n')] |
from typing import Optional
from django.contrib.auth.models import User
from django.db import models
from django.db.models.aggregates import Count
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q
from django.urls import reverse
from django_extensions.db.models import TimeStampedModel
from .doi import Doi
from .image import Image
class Collection(TimeStampedModel):
creator = models.ForeignKey(User, on_delete=models.PROTECT)
images = models.ManyToManyField(Image, related_name='collections')
# TODO: probably make it unique per user, or unique for official collections
name = models.CharField(max_length=200, unique=True)
description = models.TextField(blank=True)
public = models.BooleanField(default=False)
official = models.BooleanField(default=False)
doi = models.OneToOneField(Doi, on_delete=models.PROTECT, null=True, blank=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('core/collection-detail', args=[self.pk])
def _get_datacite_creators(self) -> list[str]:
"""
Return a list of datacite creators for this collection.
Creators are ordered by number of images contributed (to this collection), ties are broken
alphabetically, except for Anonymous contributions which are always last.
"""
creators = (
self.images.alias(num_images=Count('accession__image'))
.values_list('accession__cohort__attribution', flat=True)
.order_by('-num_images', 'accession__cohort__attribution')
.distinct()
)
# Push an Anonymous attribution to the end
creators = sorted(creators, key=lambda x: 1 if x == 'Anonymous' else 0)
return creators
def as_datacite_doi(self, contributor: User, doi_id: str) -> dict:
return {
'data': {
'type': 'dois',
'attributes': {
'identifiers': [{'identifierType': 'DOI', 'identifier': doi_id}],
'event': 'publish',
'doi': doi_id,
'creators': [{'name': creator} for creator in self._get_datacite_creators()],
'contributor': f'{self.creator.first_name} {self.creator.last_name}',
'titles': [{'title': self.name}],
'publisher': 'ISIC Archive',
'publicationYear': self.images.order_by('created').latest().created.year,
# resourceType?
'types': {'resourceTypeGeneral': 'Dataset'},
# TODO: api.?
'url': f'https://api.isic-archive.com/collections/{self.pk}/',
'schemaVersion': 'http://datacite.org/schema/kernel-4',
'description': self.description,
'descriptionType': 'Other',
},
}
}
class CollectionPermissions:
model = Collection
perms = ['view_collection', 'create_doi']
filters = {'view_collection': 'view_collection_list', 'create_doi': 'create_doi_list'}
@staticmethod
def view_collection_list(
user_obj: User, qs: Optional[QuerySet[Collection]] = None
) -> QuerySet[Collection]:
qs = qs if qs is not None else Collection._default_manager.all()
if user_obj.is_active and user_obj.is_staff:
return qs
elif user_obj.is_authenticated:
return qs.filter(Q(public=True) | Q(creator=user_obj))
else:
return qs.filter(public=True)
@staticmethod
def view_collection(user_obj, obj):
# TODO: use .contains in django 4
return CollectionPermissions.view_collection_list(user_obj).filter(pk=obj.pk).exists()
@staticmethod
def create_doi_list(
user_obj: User, qs: Optional[QuerySet[Collection]] = None
) -> QuerySet[Collection]:
qs = qs if qs is not None else Collection._default_manager.all()
if user_obj.is_active and user_obj.is_staff:
return qs
else:
return qs.none()
@staticmethod
def create_doi(user_obj: User, obj: Collection) -> bool:
return CollectionPermissions.create_doi_list(user_obj).filter(pk=obj.pk).exists()
Collection.perms_class = CollectionPermissions
| [
"django.db.models.OneToOneField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.aggregates.Count",
"django.db.models.BooleanField",
"django.db.models.query_utils.Q",
"django.urls.reverse",
"django.db.models.CharField"
] | [((423, 472), 'django.db.models.ForeignKey', 'models.ForeignKey', (['User'], {'on_delete': 'models.PROTECT'}), '(User, on_delete=models.PROTECT)\n', (440, 472), False, 'from django.db import models\n'), ((487, 544), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Image'], {'related_name': '"""collections"""'}), "(Image, related_name='collections')\n", (509, 544), False, 'from django.db import models\n'), ((638, 683), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)', 'unique': '(True)'}), '(max_length=200, unique=True)\n', (654, 683), False, 'from django.db import models\n'), ((702, 730), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)'}), '(blank=True)\n', (718, 730), False, 'from django.db import models\n'), ((745, 779), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (764, 779), False, 'from django.db import models\n'), ((796, 830), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (815, 830), False, 'from django.db import models\n'), ((842, 916), 'django.db.models.OneToOneField', 'models.OneToOneField', (['Doi'], {'on_delete': 'models.PROTECT', 'null': '(True)', 'blank': '(True)'}), '(Doi, on_delete=models.PROTECT, null=True, blank=True)\n', (862, 916), False, 'from django.db import models\n'), ((1014, 1063), 'django.urls.reverse', 'reverse', (['"""core/collection-detail"""'], {'args': '[self.pk]'}), "('core/collection-detail', args=[self.pk])\n", (1021, 1063), False, 'from django.urls import reverse\n'), ((3521, 3535), 'django.db.models.query_utils.Q', 'Q', ([], {'public': '(True)'}), '(public=True)\n', (3522, 3535), False, 'from django.db.models.query_utils import Q\n'), ((3538, 3557), 'django.db.models.query_utils.Q', 'Q', ([], {'creator': 'user_obj'}), '(creator=user_obj)\n', (3539, 3557), False, 'from django.db.models.query_utils import Q\n'), ((1448, 1473), 'django.db.models.aggregates.Count', 'Count', (['"""accession__image"""'], {}), "('accession__image')\n", (1453, 1473), False, 'from django.db.models.aggregates import Count\n')] |
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, LSTM, Embedding
from tensorflow.keras.optimizers import RMSprop
from datagen import *
# Defining the layers to be used in the model
transfer_values_input = Input(shape=(2048,), name='transfer_values_input')
decoder_transfer_map = Dense(256, activation='tanh')
decoder_input = Input(shape=(None, ), name='decoder_input')
decoder_embedding = Embedding(input_dim=5000, output_dim=128, name='decoder_embedding')
decoderlstm = LSTM(256, return_sequences=True)
decoder_dense = Dense(5000, activation='softmax', name='decoder_output')
# Function to get the output of the decoder, given output of encoder
def connect_decoder(transfer_values):
state = decoder_transfer_map(transfer_values)
initial_state = [state, state]
# Start the decoder-network with its input-layer.
net = decoder_input
net = decoder_embedding(net)
net = decoderlstm(net, initial_state=initial_state)
decoder_output1 = decoder_dense(net)
return decoder_output1
decoder_output = connect_decoder(transfer_values=transfer_values_input)
# Defining, compiling, training, saving the model
decoder_model = Model(inputs=[transfer_values_input, decoder_input], outputs=[decoder_output])
decoder_model.compile(optimizer=RMSprop(lr=1e-3), loss='sparse_categorical_crossentropy')
decoder_model.fit(generator, steps_per_epoch=1700, epochs=25)
# Enter the path of output directory where model_weights can be saved
output_dir = './'
decoder_model.save_weights(output_dir)
| [
"tensorflow.keras.layers.Input",
"tensorflow.keras.layers.Embedding",
"tensorflow.keras.layers.LSTM",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.models.Model",
"tensorflow.keras.optimizers.RMSprop"
] | [((249, 299), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(2048,)', 'name': '"""transfer_values_input"""'}), "(shape=(2048,), name='transfer_values_input')\n", (254, 299), False, 'from tensorflow.keras.layers import Input, Dense, LSTM, Embedding\n'), ((323, 352), 'tensorflow.keras.layers.Dense', 'Dense', (['(256)'], {'activation': '"""tanh"""'}), "(256, activation='tanh')\n", (328, 352), False, 'from tensorflow.keras.layers import Input, Dense, LSTM, Embedding\n'), ((369, 411), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(None,)', 'name': '"""decoder_input"""'}), "(shape=(None,), name='decoder_input')\n", (374, 411), False, 'from tensorflow.keras.layers import Input, Dense, LSTM, Embedding\n'), ((433, 500), 'tensorflow.keras.layers.Embedding', 'Embedding', ([], {'input_dim': '(5000)', 'output_dim': '(128)', 'name': '"""decoder_embedding"""'}), "(input_dim=5000, output_dim=128, name='decoder_embedding')\n", (442, 500), False, 'from tensorflow.keras.layers import Input, Dense, LSTM, Embedding\n'), ((515, 547), 'tensorflow.keras.layers.LSTM', 'LSTM', (['(256)'], {'return_sequences': '(True)'}), '(256, return_sequences=True)\n', (519, 547), False, 'from tensorflow.keras.layers import Input, Dense, LSTM, Embedding\n'), ((564, 620), 'tensorflow.keras.layers.Dense', 'Dense', (['(5000)'], {'activation': '"""softmax"""', 'name': '"""decoder_output"""'}), "(5000, activation='softmax', name='decoder_output')\n", (569, 620), False, 'from tensorflow.keras.layers import Input, Dense, LSTM, Embedding\n'), ((1195, 1273), 'tensorflow.keras.models.Model', 'Model', ([], {'inputs': '[transfer_values_input, decoder_input]', 'outputs': '[decoder_output]'}), '(inputs=[transfer_values_input, decoder_input], outputs=[decoder_output])\n', (1200, 1273), False, 'from tensorflow.keras.models import Model\n'), ((1307, 1324), 'tensorflow.keras.optimizers.RMSprop', 'RMSprop', ([], {'lr': '(0.001)'}), '(lr=0.001)\n', (1314, 1324), False, 'from tensorflow.keras.optimizers import RMSprop\n')] |
import os
appen_lexicon_file = '/data/USE_ASR001/USE_ASR001/TABLE/LEXICON.TBL'
vocab_file='../data/local/lm/vocab.txt'
if not os.path.exists('../data/local/lm'):
os.mkdir('../data/local/lm')
fid = open(appen_lexicon_file)
all_lines = fid.readlines()
fid.close()
fid = open(vocab_file,'w')
for ln in all_lines:
fid.write(ln.split('\t')[0]+'\n')
fid.close()
| [
"os.path.exists",
"os.mkdir"
] | [((127, 161), 'os.path.exists', 'os.path.exists', (['"""../data/local/lm"""'], {}), "('../data/local/lm')\n", (141, 161), False, 'import os\n'), ((167, 195), 'os.mkdir', 'os.mkdir', (['"""../data/local/lm"""'], {}), "('../data/local/lm')\n", (175, 195), False, 'import os\n')] |
__author__ = '<NAME>'
__website__ = 'https://www.iabdullahmughal.com'
__twitter__ = '@iabdullahmughal'
import os
class FileSize:
def __init__(self, file_path):
self.__file_path__ = file_path
# https://stackoverflow.com/questions/2104080/how-to-check-file-size-in-python
@staticmethod
def __convert_bytes(number_value):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if number_value < 1024.0:
return "%3.1f %s" % (number_value, x)
number_value /= 1024.0
def __file_size(self):
"""
this function will return the file size
"""
file_size = {'file_size': None, 'file_size_readable': None, 'error': []}
try:
file_info = os.stat(self.__file_path__)
file_size['file_size'] = file_info.st_size
file_size['file_size_readable'] = self.__convert_bytes(file_info.st_size)
return True, file_size
except FileNotFoundError:
file_size['error'].append('No file path was given.')
return False, file_size
def do_size_calculation(self, file_path=None):
file_size = {'file_size': None, 'file_size_readable': None, 'error': []}
if file_path:
self.__file_path__ = file_path
if not self.__file_path__:
file_size['error'].append('No file path was given.')
return file_size
was_successful, file_size = self.__file_size()
return was_successful, file_size
| [
"os.stat"
] | [((829, 856), 'os.stat', 'os.stat', (['self.__file_path__'], {}), '(self.__file_path__)\n', (836, 856), False, 'import os\n')] |